From fcd124d5b7f37cdb07f0321de04b47b859c040e3 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 21 Oct 2026 18:35:38 -0700 Subject: [PATCH 01/11] feat: a direct send finds or imports the person given by their fields The five direct sends took only --contact-id, so a send to someone Reply did not hold yet needed an add command first. They now take the contact flags the add commands take. A person given by their fields is looked up by the address the send reaches them at (the email for send-email, the LinkedIn URL for the four LinkedIn sends) and imported, as the add commands import one, only when Reply holds nobody under it. The answer names the contact the send went to and says whether the command created it. When --contact - and --message - both read stdin, it holds one object, {"contact": {...}, "message": {...}}, so neither the person nor the text ever sits in the argument list. A lost answer to the import says nothing was sent. --- src/__tests__/operations/commands.test.ts | 49 +++- src/__tests__/operations/direct-send.test.ts | 231 ++++++++++++++++++- src/operations/commands.ts | 65 ++++-- src/operations/contact-input.ts | 8 +- src/operations/contact.ts | 22 +- src/operations/contacts.ts | 31 ++- src/operations/direct-send.ts | 63 +++-- src/operations/stdin-input.ts | 43 +++- 8 files changed, 428 insertions(+), 84 deletions(-) diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index 97bb68f..4f305d6 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -42,17 +42,21 @@ describe('operations/commands', ()=>{ expect(text, text).not.toContain('outcome.unknown'); }); + // The sends and contact update find or import the person as the add commands do. + const SENDS_AND_UPDATE = ['send-email', 'linkedin-connect', 'linkedin-message', 'linkedin-inmail', 'linkedin-voice']; + const CONTACT_FLAGS = ['--contact-id', '--email', '--first-name', '--last-name', '--company', '--title', '--contact']; + it('the commands about a person take the contact flags', ()=>{ for (const c of [sub(sequence_command, 'add-contact'), sub(sequence_command, 'remove-contact'), - sub(contact_list_command, 'add-contact'), sub(contact_command, 'opt-out')]) + sub(contact_list_command, 'add-contact'), sub(contact_command, 'opt-out'), ...SENDS_AND_UPDATE.map(n=>sub(contact_command, n))]) { - expect(flags(c)).toEqual(expect.arrayContaining(['--contact-id', '--email', '--contact'])); + expect(flags(c), c.name()).toEqual(expect.arrayContaining(CONTACT_FLAGS)); } }); it('the commands about a person say their JSON takes linkedin_url, and a lookup is never left incomplete', ()=>{ for (const c of [sub(sequence_command, 'add-contact'), sub(sequence_command, 'remove-contact'), - sub(contact_list_command, 'add-contact'), sub(contact_command, 'opt-out')]) + sub(contact_list_command, 'add-contact'), sub(contact_command, 'opt-out'), ...SENDS_AND_UPDATE.map(n=>sub(contact_command, n))]) { const text = help_of(c); expect(text, text).toContain('linkedin_url'); @@ -61,10 +65,35 @@ describe('operations/commands', ()=>{ // Each of them looks a contact up by address, and two contacts under one address is refused. expect(text, text).toContain(' contact.not_unique\n'); } - for (const c of [sub(sequence_command, 'add-contact'), sub(contact_list_command, 'add-contact'), sub(contact_command, 'opt-out')]) + for (const c of [sub(sequence_command, 'add-contact'), sub(contact_list_command, 'add-contact'), sub(contact_command, 'opt-out'), + ...SENDS_AND_UPDATE.map(n=>sub(contact_command, n))]) { const text = help_of(c); - expect(text, text).toContain('contact.invalid_linkedin_url'); + for (const code of ['contact.invalid_email', 'contact.invalid_linkedin_url', 'account.contact_limit_reached']) + { + expect(text, `${c.name()} ${code}`).toContain(` ${code}\n`); + } + } + }); + + it('the sends and contact update say a contact is imported only when Reply holds nobody, and how stdin holds both inputs', ()=>{ + for (const name of SENDS_AND_UPDATE) + { + const text = help_of(sub(contact_command, name)); + const flat = text.replace(/\s+/g, ' '); + const input = name === 'update' ? 'fields' : 'message'; + expect(flat, text).toContain('imported only when Reply holds nobody under'); + expect(flat, text).toContain('only then does Reply need a first name'); + expect(flat, text).toContain('contact_created says whether this command created'); + expect(flat, text).toContain(`With --contact - and --${input} - both, stdin holds one object: {"contact": {…}, "${input}": {…}}`); + expect(text, text).toContain(`--contact - `); + } + const email = help_of(sub(contact_command, 'send-email')).replace(/\s+/g, ' '); + expect(email, email).toContain('looked up by its email'); + for (const name of ['linkedin-connect', 'linkedin-message', 'linkedin-inmail', 'linkedin-voice']) + { + const text = help_of(sub(contact_command, name)).replace(/\s+/g, ' '); + expect(text, text).toContain('looked up by its LinkedIn URL'); } }); @@ -119,11 +148,12 @@ describe('operations/commands', ()=>{ // Each direct send: the flag naming the account it goes from, the codes its endpoint publishes, and what its help // says sent_at is. - const LINKEDIN = ['contact.not_found', 'contact.no_linkedin_profile', 'linkedin.account_not_found', 'linkedin.feature_disabled', + const IMPORT = ['contact.not_unique', 'contact.invalid_email', 'contact.invalid_linkedin_url', 'account.contact_limit_reached']; + const LINKEDIN = ['contact.not_found', ...IMPORT, 'contact.no_linkedin_profile', 'linkedin.account_not_found', 'linkedin.feature_disabled', 'linkedin.account_inactive', 'linkedin.invalid_cookie']; const SENT_AT_AS_GIVEN = 'sentAtUtc as Reply gives them, each null when it gives none; the CLI adds no time of its own'; const DIRECT_SENDS: [string, string, string[], string][] = [ - ['send-email', '--email-account-id', ['contact.not_found', 'email_account.not_found', 'contact.blacklisted'], + ['send-email', '--email-account-id', ['contact.not_found', ...IMPORT, 'email_account.not_found', 'contact.blacklisted'], 'sent_at is always null; the CLI adds none of its own'], ['linkedin-connect', '--linkedin-account-id', [...LINKEDIN, 'linkedin.not_connected', 'linkedin.limit_reached', 'linkedin.message_too_long', 'linkedin.missing_variables'], SENT_AT_AS_GIVEN], @@ -143,11 +173,12 @@ describe('operations/commands', ()=>{ expect(text, text).not.toContain('connected or not'); }); - it('each direct send takes ids by flag and its text only through --message -, and says a repeat may send it twice', ()=>{ + it('each direct send takes the contact flags, the account by flag and its text only through --message -, and says a ' + + 'repeat may send it twice', ()=>{ for (const [name, account_flag, codes, sent_at] of DIRECT_SENDS) { const c = sub(contact_command, name); - expect(flags(c), name).toEqual(['--contact-id', account_flag, '--message']); + expect(flags(c), name).toEqual([...CONTACT_FLAGS, account_flag, '--message']); const text = help_of(c); const flat = text.replace(/\s+/g, ' '); expect(text, text).toContain('--message -'); diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index 9a31b33..137345d 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -1,3 +1,6 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; import {describe, it, expect, beforeEach} from 'vitest'; import {mock_fetch, json, ctx, sent, answer, capture} from './helpers'; import {handle_direct_send, type Direct_send_name, type Direct_send_opts} from '../../operations/direct-send'; @@ -34,7 +37,7 @@ describe('contact send-email', ()=>{ it('sends one email from the mailbox named, with the subject and body from stdin, and adds no time of its own', async()=>{ answer(json({status: 'sent', messageId: ''})); expect(await run('send-email', {subject: SUBJECT, body: BODY}, EMAIL_OPTS)).toStrictEqual({ - status: 'sent', contact_id: 456, message_id: '', sent_at: null, reply_status: 'sent', + status: 'sent', contact_id: 456, contact_created: false, message_id: '', sent_at: null, reply_status: 'sent', }); expect(sent()).toEqual([{ method: 'POST', url: 'https://api/v3/contacts/456/send-direct-email', body: {emailAccountId: 12, subject: SUBJECT, body: BODY}, @@ -44,12 +47,12 @@ describe('contact send-email', ()=>{ it('keeps Reply\'s own word as reply_status, gives a null messageId as null, and never takes a time from the answer', async()=>{ answer(json({status: 'new', messageId: null, sentAtUtc: '2026-10-19T10:00:00Z', date: '2026-10-19T10:00:00Z'})); expect(await run('send-email', {subject: SUBJECT, body: BODY}, EMAIL_OPTS)).toStrictEqual({ - status: 'sent', contact_id: 456, message_id: null, sent_at: null, reply_status: 'new', + status: 'sent', contact_id: 456, contact_created: false, message_id: null, sent_at: null, reply_status: 'new', }); mock_fetch.mockReset(); answer(json({})); expect(await run('send-email', {subject: SUBJECT, body: BODY}, EMAIL_OPTS)).toStrictEqual({ - status: 'sent', contact_id: 456, message_id: null, sent_at: null, reply_status: null, + status: 'sent', contact_id: 456, contact_created: false, message_id: null, sent_at: null, reply_status: null, }); }); @@ -99,7 +102,7 @@ describe('the LinkedIn sends', ()=>{ mock_fetch.mockReset(); answer(activity(action)); expect(await run(name, message, LINKEDIN_OPTS), name).toStrictEqual({ - status: 'sent', contact_id: 456, activity_id: 1042, sent_at: '2026-10-19T10:30:00Z', + status: 'sent', contact_id: 456, contact_created: false, activity_id: 1042, sent_at: '2026-10-19T10:30:00Z', }); const requests = sent(); expect(requests.map(r=>[r.method, r.url]), name).toEqual([['POST', `https://api/v3/contacts/456/${path}`]]); @@ -113,7 +116,7 @@ describe('the LinkedIn sends', ()=>{ mock_fetch.mockReset(); answer(json({actionType: 'message', linkedInActivityId: '1042'})); expect(await run('linkedin-message', {body: TEXT}, LINKEDIN_OPTS)).toStrictEqual({ - status: 'sent', contact_id: 456, activity_id: null, sent_at: null, + status: 'sent', contact_id: 456, contact_created: false, activity_id: null, sent_at: null, }); }); @@ -127,7 +130,7 @@ describe('the LinkedIn sends', ()=>{ it('an invitation to someone already connected is already_connected, exit 0, sent once; on a message it is a refusal', async()=>{ answer(json({title: 'Conflict', status: 409, code: 'directLinkedIn.alreadyConnected'}, 409)); expect(await run('linkedin-connect', {note: NOTE}, LINKEDIN_OPTS)).toStrictEqual({ - status: 'already_connected', contact_id: 456, activity_id: null, sent_at: null, + status: 'already_connected', contact_id: 456, contact_created: false, activity_id: null, sent_at: null, }); expect(mock_fetch).toHaveBeenCalledTimes(1); mock_fetch.mockReset(); @@ -328,16 +331,226 @@ describe('every direct send', ()=>{ expect(mock_fetch).not.toHaveBeenCalled(); }); - it('refuses a missing or malformed contact or account id before any call', async()=>{ + it('refuses a missing contact, or a malformed contact or account id, before any call', async()=>{ for (const [name, message, opts] of SENDS) { const account_flag = Object.keys(opts).find(k=>k.endsWith('AccountId')) as keyof Direct_send_opts; - for (const bad of [{contactId: undefined}, {contactId: 'abc'}, {contactId: '0'}, {[account_flag]: undefined}, {[account_flag]: '-3'}]) + const cases: [Direct_send_opts, string][] = [ + [{contactId: undefined}, 'usage.contact'], [{contactId: 'abc'}, 'usage.id'], [{contactId: '0'}, 'usage.id'], + [{[account_flag]: undefined}, 'usage.id'], [{[account_flag]: '-3'}, 'usage.id'], + ]; + for (const [bad, code] of cases) { const e = await failure(name, message, {...opts, ...bad}); - expect(e, `${name} ${JSON.stringify(bad)}`).toMatchObject({code: 'usage.id', exit_code: 2}); + expect(e, `${name} ${JSON.stringify(bad)}`).toMatchObject({code, exit_code: 2}); } } expect(mock_fetch).not.toHaveBeenCalled(); }); }); + +describe('a direct send to a person given by their fields', ()=>{ + const MARTA = {email: 'marta@example.com', first_name: 'Marta', last_name: 'Example'}; + const PROFILE = 'https://www.linkedin.com/in/marta-example'; + const EMAIL_LOOKUP = 'GET https://api/v3/contacts?email=marta%40example.com&top=100&skip=0'; + const PROFILE_LOOKUP = `GET https://api/v3/contacts?linkedIn=${encodeURIComponent(PROFILE)}&top=100&skip=0`; + const IMPORT = 'POST https://api/v3/contacts/import'; + const nobody = ()=>json({items: [], hasMore: false}); + const held = (entry: Record)=>json({items: [entry], hasMore: false}); + const imported = (id: number, status = 'created')=>json({items: [{id, status}]}); + const by_fields = (opts: Direct_send_opts): Direct_send_opts=>({...opts, contactId: undefined, contact: '-'}); + const lines = ()=>sent().map(r=>`${r.method} ${r.url}`); + + // The person and the text both come on stdin, so the argument list carries neither: it is checked on every run. + const PERSONAL = /marta|example\.com|tuesday|meetup/i; + const send_by_fields = (name: Direct_send_name, input: unknown, opts: Direct_send_opts)=>{ + expect(JSON.stringify(opts), JSON.stringify(opts)).not.toMatch(PERSONAL); + return send(name, input, opts); + }; + const run_by_fields = async(name: Direct_send_name, input: unknown, opts: Direct_send_opts)=> + JSON.parse((await capture(()=>send_by_fields(name, input, opts))).out); + const fail_by_fields = (name: Direct_send_name, input: unknown, opts: Direct_send_opts)=> + send_by_fields(name, input, opts).catch((x: unknown)=>x); + + const LINKEDIN_SENDS: [Direct_send_name, unknown, string, string][] = [ + ['linkedin-connect', {note: NOTE}, 'send-direct-linkedin-connect', 'connect'], + ['linkedin-message', {body: TEXT}, 'send-direct-linkedin-message', 'message'], + ['linkedin-inmail', {subject: SUBJECT, body: TEXT}, 'send-direct-linkedin-inmail', 'inMail'], + ['linkedin-voice', {script: SCRIPT}, 'send-direct-linkedin-ai-voice', 'aiVoice'], + ]; + + it('send-email: Reply holds nobody under the email, so it is looked up, imported with the person\'s names, then sent, ' + + 'and the answer names the contact it went to', async()=>{ + answer(nobody(), imported(457), json({status: 'sent', messageId: ''})); + const message = {subject: SUBJECT, body: BODY}; + expect(await run_by_fields('send-email', {contact: MARTA, message}, by_fields(EMAIL_OPTS))).toStrictEqual({ + status: 'sent', contact_id: 457, contact_created: true, message_id: '', sent_at: null, reply_status: 'sent', + }); + expect(lines()).toEqual([EMAIL_LOOKUP, IMPORT, 'POST https://api/v3/contacts/457/send-direct-email']); + expect(sent()[1].body).toStrictEqual({items: [{email: 'marta@example.com', firstName: 'Marta', lastName: 'Example'}]}); + expect(sent()[2].body).toStrictEqual({emailAccountId: 12, subject: SUBJECT, body: BODY}); + }); + + it('each LinkedIn send: Reply holds nobody under the profile, so it is looked up by it, the person imported keyed by it ' + + 'with no email, then sent', async()=>{ + for (const [name, message, path, action] of LINKEDIN_SENDS) + { + mock_fetch.mockReset(); + answer(nobody(), imported(458), activity(action)); + const person = {linkedin_url: PROFILE, first_name: 'Marta'}; + expect(await run_by_fields(name, {contact: person, message}, by_fields(LINKEDIN_OPTS)), name).toStrictEqual({ + status: 'sent', contact_id: 458, contact_created: true, activity_id: 1042, sent_at: '2026-10-19T10:30:00Z', + }); + expect(lines(), name).toEqual([PROFILE_LOOKUP, IMPORT, `POST https://api/v3/contacts/458/${path}`]); + expect(sent()[1].body, name).toStrictEqual({items: [{linkedInUrl: PROFILE, firstName: 'Marta'}], options: {keys: {linkedInUrl: true}}}); + } + }); + + it('a person Reply holds is sent to with no import, and needs no first name', async()=>{ + answer(held({id: 456, email: 'Marta@Example.com'}), json({status: 'sent', messageId: null})); + expect(await run_by_fields('send-email', {contact: {email: 'marta@example.com'}, message: {subject: SUBJECT, body: BODY}}, + by_fields(EMAIL_OPTS))).toMatchObject({status: 'sent', contact_id: 456, contact_created: false}); + expect(lines()).toEqual([EMAIL_LOOKUP, 'POST https://api/v3/contacts/456/send-direct-email']); + for (const [name, message, path, action] of LINKEDIN_SENDS) + { + mock_fetch.mockReset(); + answer(held({id: 456, linkedInUrl: `${PROFILE}/`}), activity(action)); + expect(await run_by_fields(name, {contact: {linkedin_url: PROFILE}, message}, by_fields(LINKEDIN_OPTS)), name) + .toMatchObject({status: 'sent', contact_id: 456, contact_created: false}); + expect(lines(), name).toEqual([PROFILE_LOOKUP, `POST https://api/v3/contacts/456/${path}`]); + } + }); + + it('a send looks the person up by the address it reaches them at, whatever else is given, and the import matches by ' + + 'the email as an add\'s does', async()=>{ + const both = {...MARTA, linkedin_url: PROFILE}; + answer(nobody(), imported(456, 'updated'), activity('message')); + expect(await run_by_fields('linkedin-message', {contact: both, message: {body: TEXT}}, by_fields(LINKEDIN_OPTS))) + .toMatchObject({contact_id: 456, contact_created: false}); + expect(lines()).toEqual([PROFILE_LOOKUP, IMPORT, 'POST https://api/v3/contacts/456/send-direct-linkedin-message']); + expect(sent()[1].body).toStrictEqual({items: [{email: 'marta@example.com', linkedInUrl: PROFILE, firstName: 'Marta', lastName: 'Example'}]}); + mock_fetch.mockReset(); + answer(held({id: 456, email: 'marta@example.com'}), json({status: 'sent'})); + await run_by_fields('send-email', {contact: both, message: {subject: SUBJECT, body: BODY}}, by_fields(EMAIL_OPTS)); + expect(lines()).toEqual([EMAIL_LOOKUP, 'POST https://api/v3/contacts/456/send-direct-email']); + }); + + it('a person without the address the send reaches them at is refused before any call, the address not repeated', async()=>{ + const cases: [Direct_send_name, unknown, Direct_send_opts][] = [ + ['send-email', {contact: {linkedin_url: PROFILE, first_name: 'Marta'}, message: {subject: SUBJECT, body: BODY}}, by_fields(EMAIL_OPTS)], + ...LINKEDIN_SENDS.map(([name, message]): [Direct_send_name, unknown, Direct_send_opts]=> + [name, {contact: MARTA, message}, by_fields(LINKEDIN_OPTS)]), + ]; + for (const [name, input, opts] of cases) + { + const e = await fail_by_fields(name, input, opts); + expect(e, name).toMatchObject({code: 'usage.contact', exit_code: 2}); + expect(shown(e), shown(e)).not.toMatch(PERSONAL); + } + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('refuses as the add commands do: two contacts held, an address or a profile Reply will not import, the plan\'s limit, ' + + 'an item the import failed; and nothing is sent', async()=>{ + const two = json({items: [{id: 1, email: 'marta@example.com'}, {id: 2, email: 'marta@example.com'}], hasMore: false}); + const cases: [Response[], string, number][] = [ + [[two], 'contact.not_unique', 1], + [[nobody(), json({status: 400, errors: [{pointer: '/items/0/email', detail: '\'marta@example\' is not valid'}]}, 400)], + 'contact.invalid_email', 1], + [[nobody(), json({status: 400, errors: [{pointer: '/items/0/linkedInUrl', detail: 'not valid'}]}, 400)], + 'contact.invalid_linkedin_url', 1], + [[nobody(), json({code: 'contact.limitExceeded', detail: 'Contact limit reached.'}, 400)], 'account.contact_limit_reached', 1], + [[nobody(), json({items: [{id: null, status: 'failed', error: 'Invalid data'}]})], 'reply.refused', 1], + ]; + for (const [answers, code, exit_code] of cases) + { + mock_fetch.mockReset(); + answer(...answers); + const e = await fail_by_fields('send-email', {contact: {...MARTA, linkedin_url: PROFILE}, message: {subject: SUBJECT, body: BODY}}, + by_fields(EMAIL_OPTS)); + expect(e, code).toMatchObject({code, exit_code, ids: {email_account_id: 12}}); + expect((e as {ids?: Record}).ids, code).not.toHaveProperty('contact_id'); + expect(shown(e), shown(e)).not.toMatch(PERSONAL); + expect(lines().filter(l=>l.includes('send-direct')), code).toEqual([]); + } + }); + + it('a lost answer to the import is outcome.unknown (exit 3) that says nothing was sent; one to the send says it may go ' + + 'twice, and names the contact', async()=>{ + mock_fetch.mockResolvedValueOnce(nobody()).mockRejectedValueOnce(lost_connection()); + const input = {contact: MARTA, message: {subject: SUBJECT, body: BODY}}; + const before = await fail_by_fields('send-email', input, by_fields(EMAIL_OPTS)) as {hint?: string; ids?: object}; + expect(before).toMatchObject({code: 'outcome.unknown', exit_code: 3}); + expect(before.hint, before.hint).toContain('Nothing was sent'); + expect(before.hint, before.hint).not.toContain('may send it twice'); + expect(before.ids, JSON.stringify(before.ids)).not.toHaveProperty('contact_id'); + expect(lines()).toEqual([EMAIL_LOOKUP, IMPORT]); + mock_fetch.mockReset(); + mock_fetch.mockResolvedValueOnce(nobody()).mockResolvedValueOnce(imported(457)).mockRejectedValueOnce(lost_connection()); + const after = await fail_by_fields('send-email', input, by_fields(EMAIL_OPTS)) as {hint?: string}; + expect(after).toMatchObject({code: 'outcome.unknown', exit_code: 3, ids: {contact_id: 457, email_account_id: 12}}); + expect(after.hint, after.hint).toContain('may send it twice'); + expect(shown(after), shown(after)).not.toMatch(PERSONAL); + }); + + it('a refusal of the send after an import carries the contact it created, and an invitation to someone already connected ' + + 'names them too', async()=>{ + answer(nobody(), imported(457), json({code: 'contact.contactInBlackList'}, 400)); + const e = await fail_by_fields('send-email', {contact: MARTA, message: {subject: SUBJECT, body: BODY}}, by_fields(EMAIL_OPTS)); + expect(e).toMatchObject({code: 'contact.blacklisted', exit_code: 1, ids: {contact_id: 457, email_account_id: 12}}); + mock_fetch.mockReset(); + answer(nobody(), imported(458), json({code: 'directLinkedIn.alreadyConnected'}, 409)); + expect(await run_by_fields('linkedin-connect', {contact: {linkedin_url: PROFILE, first_name: 'Marta'}, message: {note: NOTE}}, + by_fields(LINKEDIN_OPTS))).toStrictEqual({ + status: 'already_connected', contact_id: 458, contact_created: true, activity_id: null, sent_at: null, + }); + }); + + it('an invitation without a note reads the person alone from stdin', async()=>{ + answer(nobody(), imported(458), activity('connect')); + const opts = {...by_fields(LINKEDIN_OPTS), message: undefined}; + await run_by_fields('linkedin-connect', {linkedin_url: PROFILE, first_name: 'Marta'}, opts); + expect(sent()[2].body).toStrictEqual({linkedInAccountId: 34}); + }); + + it('with --contact - and --message - both, stdin is one object holding each, read once', async()=>{ + answer(nobody(), imported(457), json({status: 'sent'})); + let reads = 0; + const input = JSON.stringify({contact: MARTA, message: {subject: SUBJECT, body: BODY}}); + await capture(()=>handle_direct_send('send-email', by_fields(EMAIL_OPTS), ctx(), {json: true}, ()=>{ reads++; return input; })); + expect(reads).toBe(1); + expect(sent()[2].body).toMatchObject({subject: SUBJECT, body: BODY}); + }); + + it('refuses stdin that is not that object, without repeating any of it and before any call', async()=>{ + const message = {subject: SUBJECT, body: BODY}; + const cases: [unknown, string][] = [ + ['not json, Marta', 'usage.stdin'], [[MARTA, message], 'usage.stdin'], [{contact: MARTA}, 'usage.stdin'], + [{message}, 'usage.stdin'], [{contact: MARTA, message, cc: 'marta@example.com'}, 'usage.stdin'], + [{...MARTA, ...message}, 'usage.stdin'], + [{contact: 'marta@example.com', message}, 'usage.contact'], [{contact: {...MARTA, phone: '1'}, message}, 'usage.contact'], + [{contact: MARTA, message: {subject: SUBJECT}}, 'usage.message'], [{contact: MARTA, message: 'Hi Marta'}, 'usage.message'], + ]; + for (const [input, code] of cases) + { + const e = await fail_by_fields('send-email', input, by_fields(EMAIL_OPTS)); + expect(e, JSON.stringify(input)).toMatchObject({code, exit_code: 2}); + expect(shown(e), shown(e)).not.toMatch(PERSONAL); + } + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('a person from a file leaves stdin to the text alone', async()=>{ + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'reply-send-')); + const file = path.join(dir, 'person.json'); + fs.writeFileSync(file, JSON.stringify(MARTA)); + try { + answer(held({id: 456, email: 'marta@example.com'}), json({status: 'sent'})); + await run_by_fields('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, contactId: undefined, contact: `@${file}`}); + expect(lines()).toEqual([EMAIL_LOOKUP, 'POST https://api/v3/contacts/456/send-direct-email']); + expect(sent()[1].body).toMatchObject({subject: SUBJECT, body: BODY}); + } finally { + fs.rmSync(dir, {recursive: true, force: true}); + } + }); +}); diff --git a/src/operations/commands.ts b/src/operations/commands.ts index ab38a78..e1b5b48 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -2,7 +2,7 @@ import {Command} from 'commander'; import {PROGRAM_NAME} from '../config'; import {build_context} from '../context'; import {read_op_globals} from './options'; -import {add_contact_options, CONTACT_HELP} from './contact-input'; +import {add_contact_options, CONTACT_FORMS, CONTACT_HELP} from './contact-input'; import {handle_sequence_get, handle_sequence_contacts, handle_sequence_stats} from './sequence-read'; import {handle_sequence_list, handle_sequence_create} from './sequence-by-name'; import {handle_sequence_add_contact, handle_sequence_remove_contact} from './sequence-membership'; @@ -255,19 +255,41 @@ add_contact_options(contact_command.command('opt-out')) const SEND_TWICE = (what: string): string=>`the ${what} may have been sent; running the command again may send it twice`; -contact_command.command('send-email') - .option('--contact-id ', 'The contact by its Reply id') +// The codes a command that finds or imports a contact shares with the add commands. +const IMPORT_CODES = ['contact.not_unique', 'contact.invalid_email', 'contact.invalid_linkedin_url', 'account.contact_limit_reached']; + +// Both inputs on stdin, the person and the one the command acts with. +const STDIN_PAIR = (input: string): string=> + `With --contact - and --${input} - both, stdin holds one object: {"contact": {…}, "${input}": {…}}.\n`; + +// How a send names its contact: looked up by the address it reaches them at, else imported as an add imports one. +const SENT_TO = (by: 'email' | 'linkedin', what: string): string=>CONTACT_FORMS + + `A contact given by its fields is looked up by ${by === 'email' ? 'its email' : 'its LinkedIn URL'}, where the ${what} goes, and imported only\n` + + 'when Reply holds nobody under it, as the add commands import one (matched by its email when it has one); only\n' + + 'then does Reply need a first name. A LinkedIn URL is matched by its lowercased slug, and the CLI stores it by\n' + + `that slug when it imports the contact. contact_id is the contact the ${what} went to, and contact_created says\n` + + 'whether this command created them.\n' + STDIN_PAIR('message'); + +// One send's example with the person and the text both on stdin. +const piped_send = (command: string, contact: string, message: string, flags: string): string=> + `echo '{"contact":${contact},"message":${message}}' | ${P} contact ${command} --contact - ${flags} --message -`; +const ANN_EMAIL = '{"email":"ann@example.com","first_name":"Ann"}'; +const ANN_PROFILE = '{"linkedin_url":"https://www.linkedin.com/in/ann-example","first_name":"Ann"}'; + +add_contact_options(contact_command.command('send-email')) .option('--email-account-id ', 'The mailbox to send from (see `account list`)') .option('--message ', 'Only -: the email {subject, body} as JSON on stdin') .description('Send one email to a contact now, outside any sequence, from the mailbox you name') .addHelpText('after', help( - [`echo '{"subject":"Quick question","body":"

Hi Ann, does Tuesday work?

"}' | ${P} contact send-email --contact-id 456 --email-account-id 12 --message -`], - ['contact.not_found', 'email_account.not_found', 'contact.blacklisted'], true, - 'Result: {"status":"sent","contact_id","message_id","sent_at","reply_status"}: sent means Reply accepted the email, and\n' - + 'reply_status is Reply\'s own word for it (new or sent). message_id is Reply\'s messageId, null when it gives none.\n' - + 'Reply\'s answer carries no time, so sent_at is always null; the CLI adds none of its own.\n' + [`echo '{"subject":"Quick question","body":"

Hi Ann, does Tuesday work?

"}' | ${P} contact send-email --contact-id 456 --email-account-id 12 --message -`, + piped_send('send-email', ANN_EMAIL, '{"subject":"Quick question","body":"

Hi Ann

"}', '--email-account-id 12')], + ['contact.not_found', ...IMPORT_CODES, 'email_account.not_found', 'contact.blacklisted'], true, + 'Result: {"status":"sent","contact_id","contact_created","message_id","sent_at","reply_status"}: sent means Reply\n' + + 'accepted the email, and reply_status is Reply\'s own word for it (new or sent). message_id is Reply\'s messageId,\n' + + 'null when it gives none. Reply\'s answer carries no time, so sent_at is always null; the CLI adds none of its own.\n' + 'The email is read from stdin only, so its text never sits in the argument list. The body is HTML. Reply sends a\n' - + 'direct email at once, outside the mailbox\'s daily limit and sending delay.\n', + + 'direct email at once, outside the mailbox\'s daily limit and sending delay.\n' + + SENT_TO('email', 'email'), SEND_TWICE('email'))) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); @@ -276,10 +298,10 @@ contact_command.command('send-email') // The four LinkedIn sends share their flags, their first codes and the shape of their result. const LINKEDIN_SEND_CODES = [ - 'contact.not_found', 'contact.no_linkedin_profile', 'linkedin.account_not_found', 'linkedin.feature_disabled', + 'contact.not_found', ...IMPORT_CODES, 'contact.no_linkedin_profile', 'linkedin.account_not_found', 'linkedin.feature_disabled', 'linkedin.account_inactive', 'linkedin.invalid_cookie', ]; -const LINKEDIN_SENT = '"contact_id","activity_id","sent_at"}:\n' +const LINKEDIN_SENT = '"contact_id","contact_created","activity_id","sent_at"}:\n' + 'activity_id and sent_at are Reply\'s linkedInActivityId and sentAtUtc as Reply gives them, each null when it gives\n' + 'none; the CLI adds no time of its own.\n'; const VARIABLES = (where: string): string=> @@ -290,12 +312,11 @@ const linkedin_send = ( name: Exclude, description: string, message: string, examples: string[], codes: string[], extra: string, what: string, ): void=>{ - contact_command.command(name) - .option('--contact-id ', 'The contact by its Reply id') + add_contact_options(contact_command.command(name)) .option('--linkedin-account-id ', 'The LinkedIn account to send from (see `account list`)') .option('--message ', `Only -: the ${message} as JSON on stdin`) .description(description) - .addHelpText('after', help(examples, [...LINKEDIN_SEND_CODES, ...codes], true, extra, SEND_TWICE(what))) + .addHelpText('after', help(examples, [...LINKEDIN_SEND_CODES, ...codes], true, extra + SENT_TO('linkedin', what), SEND_TWICE(what))) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); await handle_direct_send(name, cmd.opts(), ctx, g); @@ -304,17 +325,21 @@ const linkedin_send = ( linkedin_send('linkedin-connect', 'Invite a contact to connect on LinkedIn, with or without a note', 'note {note}', [`echo '{"note":"Hi Ann, we met at the meetup."}' | ${P} contact linkedin-connect ${LINKEDIN_EXAMPLE} --message -`, - ex(`contact linkedin-connect ${LINKEDIN_EXAMPLE}`)], + ex(`contact linkedin-connect ${LINKEDIN_EXAMPLE}`), + piped_send('linkedin-connect', ANN_PROFILE, '{"note":"Hi Ann, we met at the meetup."}', '--linkedin-account-id 34'), + `echo '${ANN_PROFILE}' | ${P} contact linkedin-connect --contact - --linkedin-account-id 34`], ['linkedin.not_connected', 'linkedin.limit_reached', 'linkedin.message_too_long', 'linkedin.missing_variables'], 'Result: {"status":"sent"|"already_connected",' + LINKEDIN_SENT + 'already_connected means the contact is already a connection: nothing is sent, and activity_id and sent_at are null.\n' + 'The note is read from stdin only, so its text never sits in the argument list; without --message the invitation\n' - + 'carries no note. Reply publishes no limit for a note, and one it finds too long is linkedin.message_too_long.\n' + + 'carries no note, and stdin holds the contact alone. Reply publishes no limit for a note, and one it finds too long\n' + + 'is linkedin.message_too_long.\n' + VARIABLES('note'), 'invitation'); linkedin_send('linkedin-message', 'Send a LinkedIn message to a contact the account is connected with', 'message {body}', - [`echo '{"body":"Thanks for connecting, Ann."}' | ${P} contact linkedin-message ${LINKEDIN_EXAMPLE} --message -`], + [`echo '{"body":"Thanks for connecting, Ann."}' | ${P} contact linkedin-message ${LINKEDIN_EXAMPLE} --message -`, + piped_send('linkedin-message', ANN_PROFILE, '{"body":"Thanks for connecting, Ann."}', '--linkedin-account-id 34')], ['linkedin.not_connected', 'linkedin.limit_reached', 'linkedin.message_too_long', 'linkedin.missing_variables'], 'Result: {"status":"sent",' + LINKEDIN_SENT + 'The message is read from stdin only, so its text never sits in the argument list. Reply takes a body of at most\n' @@ -323,7 +348,8 @@ linkedin_send('linkedin-message', 'Send a LinkedIn message to a contact the acco linkedin_send('linkedin-inmail', 'Send a LinkedIn InMail, which reaches a contact the account is not connected with (needs Sales Navigator and InMail credits)', 'InMail {subject, body}', - [`echo '{"subject":"Quick question","body":"Hi Ann, does Tuesday work?"}' | ${P} contact linkedin-inmail ${LINKEDIN_EXAMPLE} --message -`], + [`echo '{"subject":"Quick question","body":"Hi Ann, does Tuesday work?"}' | ${P} contact linkedin-inmail ${LINKEDIN_EXAMPLE} --message -`, + piped_send('linkedin-inmail', ANN_PROFILE, '{"subject":"Quick question","body":"Hi Ann, does Tuesday work?"}', '--linkedin-account-id 34')], ['linkedin.limit_reached', 'linkedin.message_too_long', 'linkedin.missing_variables', 'linkedin.sales_navigator_required', 'linkedin.sales_navigator_disconnected', 'linkedin.no_inmail_credits'], 'Result: {"status":"sent",' + LINKEDIN_SENT @@ -332,7 +358,8 @@ linkedin_send('linkedin-inmail', 'Send a LinkedIn InMail, which reaches a contac 'InMail'); linkedin_send('linkedin-voice', 'Send a LinkedIn voice message that Reply speaks from a script in the account\'s voice', 'script {script}', - [`echo '{"script":"Hi Ann, a quick hello about Tuesday."}' | ${P} contact linkedin-voice ${LINKEDIN_EXAMPLE} --message -`], + [`echo '{"script":"Hi Ann, a quick hello about Tuesday."}' | ${P} contact linkedin-voice ${LINKEDIN_EXAMPLE} --message -`, + piped_send('linkedin-voice', ANN_PROFILE, '{"script":"Hi Ann, a quick hello about Tuesday."}', '--linkedin-account-id 34')], ['linkedin.not_connected', 'linkedin.limit_reached', 'linkedin.missing_variables', 'linkedin.voice_profile_missing', 'linkedin.voice_too_long'], 'Result: {"status":"sent",' + LINKEDIN_SENT diff --git a/src/operations/contact-input.ts b/src/operations/contact-input.ts index c56ec44..643dec1 100644 --- a/src/operations/contact-input.ts +++ b/src/operations/contact-input.ts @@ -29,14 +29,16 @@ const add_contact_options = (cmd: Command): Command=>cmd .option('--title ', 'Job title (with --email)') .option('--contact <json>', 'The contact as JSON {email, linkedin_url, first_name, last_name, company, title}: inline, @file, or - for stdin'); -const CONTACT_HELP = ` +const CONTACT_FORMS = ` A contact is given exactly one way: --contact <json>|@file|- {email, linkedin_url, first_name, last_name, company, title}, with an email, a LinkedIn URL or both; '-' reads stdin, which keeps personal data out of the argument list --email <address> [--first-name <name>] [--last-name <name>] [--company <name>] [--title <title>] --contact-id <id> a contact Reply already holds -Reply is asked about a contact by its email; one with only a LinkedIn URL, by that. A LinkedIn URL is +`; + +const CONTACT_HELP = `${CONTACT_FORMS}Reply is asked about a contact by its email; one with only a LinkedIn URL, by that. A LinkedIn URL is matched by its lowercased slug, and the CLI stores it by that slug when it imports the contact. `; @@ -150,5 +152,5 @@ const read_contact_input = (f: Contact_flags, read_stdin?: () => string): Contac })}; }; -export {read_contact_input, add_contact_options, person_of, CONTACT_HELP, linkedin_key, is_email}; +export {read_contact_input, add_contact_options, person_of, CONTACT_FORMS, CONTACT_HELP, linkedin_key, is_email}; export type {Person, Contact_ref, Contact_flags}; diff --git a/src/operations/contact.ts b/src/operations/contact.ts index 41a52c5..0698b2b 100644 --- a/src/operations/contact.ts +++ b/src/operations/contact.ts @@ -2,7 +2,7 @@ import {Operation_error, type Ids} from '../utils/errors'; import {call_reply, expect_object, item_failure, refusal, open_session, type Op_session} from './call'; import type {Op_globals} from './options'; import {read_contact_input, type Contact_flags} from './contact-input'; -import {find_contact_by_address, import_contact} from './contacts'; +import {find_or_import} from './contacts'; import {print_result, with_ids} from './result'; import type {Cli_context} from '../context'; @@ -36,22 +36,10 @@ const handle_contact_opt_out = async(opts: Opt_out_opts, ctx: Cli_context, g: Op try { // The person Reply already holds, so the opt-out lands on them. A contact is created only // when Reply holds nobody under the address, by an import that asks nothing again. - let contact_id: number; - let created = false; - if (contact.kind === 'id') - { - contact_id = contact.id; - } - else - { - const found = await find_contact_by_address(s, contact.person); - const ensured = found === null ? await import_contact(s, contact.person) : {id: found, created: false}; - contact_id = ensured.id; - created = ensured.created; - } - ids.contact_id = contact_id; - await set_opted_out(s, contact_id); - print_result({status: 'opted_out', contact_id, contact_created: created}, g); + const ensured = await find_or_import(s, contact); + ids.contact_id = ensured.id; + await set_opted_out(s, ensured.id); + print_result({status: 'opted_out', contact_id: ensured.id, contact_created: ensured.created}, g); } catch (e) { throw with_ids(e, ids); } diff --git a/src/operations/contacts.ts b/src/operations/contacts.ts index a5a50c7..06947b5 100644 --- a/src/operations/contacts.ts +++ b/src/operations/contacts.ts @@ -99,17 +99,18 @@ const import_contact = async(s: Op_session, person: Person): Promise<Ensured>=>{ }; type Lookup = {param: 'email' | 'linkedIn'; values: string[]; holds: (entry: Record<string, unknown>) => boolean}; +type Channel = 'email' | 'linkedin'; -// What a person is looked up by: the email when there is one, else the LinkedIn URL. An entry -// counts only when it carries the same address: an email equal ignoring case, a LinkedIn URL equal -// under linkedin_key. +// What a person is looked up by: the channel named, which the person carries, or else the email when +// there is one, else the LinkedIn URL. An entry counts only when it carries the same address: an email +// equal ignoring case, a LinkedIn URL equal under linkedin_key. // INTERIM (API gap): the document does not say whether the exact lookup by LinkedIn URL ignores case. // Needed: a lookup that matches a LinkedIn URL by its slug whatever its case, or a word that it does. // Workaround: ask with the URL in the form it is written in (its lowercased slug) first, then as // given, and count the matches of both together, so one slug held under two spellings is refused // rather than half seen. -const lookup_of = (p: Person): Lookup=>{ - if (p.email !== undefined) +const lookup_of = (p: Person, by?: Channel): Lookup=>{ + if (p.email !== undefined && by !== 'linkedin') { const wanted = p.email.toLowerCase(); return {param: 'email', values: [p.email], holds: entry=>typeof entry.email === 'string' && entry.email.toLowerCase() === wanted}; @@ -162,8 +163,8 @@ const read_lookup = async(s: Op_session, lookup: Lookup, value: string, found_be throw new Operation_error('reply.unavailable', 'Reply answered the exact lookup with more pages than one address can fill.', {status: 200}); }; -const find_contact_by_address = async(s: Op_session, person: Person): Promise<number | null>=>{ - const lookup = lookup_of(person); +const find_contact_by_address = async(s: Op_session, person: Person, by?: Channel): Promise<number | null>=>{ + const lookup = lookup_of(person, by); let found: number | null = null; for (const value of lookup.values) { @@ -195,6 +196,18 @@ const ensure_contact = async(s: Op_session, ref: Contact_ref): Promise<Ensured>= return import_contact(s, ref.person); }; +// The contact a command acts on: the id given; else the one Reply holds under the address the command +// reaches the person by (by default the one a lookup uses); else the person imported as an add imports +// them. Looking first means that a person Reply already holds needs no first name. +const find_or_import = async(s: Op_session, ref: Contact_ref, by?: Channel): Promise<Ensured>=>{ + if (ref.kind === 'id') + { + return {id: ref.id, created: false}; + } + const found = await find_contact_by_address(s, ref.person, by); + return found === null ? import_contact(s, ref.person) : {id: found, created: false}; +}; + const find_contact = async(s: Op_session, ref: Contact_ref): Promise<number | null>=> ref.kind === 'id' ? ref.id : find_contact_by_address(s, ref.person); @@ -219,5 +232,5 @@ const read_opted_out = async(s: Op_session, contact_id: number): Promise<boolean return body.isOptedOut; }; -export {ensure_contact, import_contact, find_contact, find_contact_by_address, read_opted_out, contact_not_found}; -export type {Ensured}; +export {ensure_contact, find_or_import, import_contact, find_contact, find_contact_by_address, read_opted_out, contact_not_found}; +export type {Ensured, Channel}; diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index 996356c..184378b 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -3,13 +3,14 @@ import {Operation_error, Unknown_outcome_error, UsageError, type Ids} from '../u import {parse_retry_after} from '../utils/client'; import {call_reply, expect_object, refusal, reply_code_of, detail_of, open_session, type Answer} from './call'; import {parse_id, LARGEST_SAFE_ID, type Op_globals} from './options'; -import {contact_not_found} from './contacts'; -import {read_stdin_object} from './stdin-input'; +import {read_contact_input, type Contact_flags, type Contact_ref} from './contact-input'; +import {contact_not_found, find_or_import, type Channel, type Ensured} from './contacts'; +import {read_stdin_object, stdin_inputs} from './stdin-input'; import {print_result, with_ids} from './result'; import type {Cli_context} from '../context'; type Direct_send_name = 'send-email' | 'linkedin-connect' | 'linkedin-message' | 'linkedin-inmail' | 'linkedin-voice'; -type Direct_send_opts = {contactId?: string; emailAccountId?: string; linkedinAccountId?: string; message?: string}; +type Direct_send_opts = Contact_flags & {emailAccountId?: string; linkedinAccountId?: string; message?: string}; type Text = Record<string, string>; type Direct_send = { @@ -165,53 +166,81 @@ const send_refusal = (a: Answer, contact_id: number): Operation_error=>{ const positive_integer = (v: unknown): number | null=> typeof v === 'number' && Number.isSafeInteger(v) && v > 0 ? v : null; -// What the CLI answers for a send Reply took. Neither adds a time of its own: Reply's answer to a -// direct email carries none, and a LinkedIn send's sentAtUtc is given as Reply gives it. -const result_of = (name: Direct_send_name, contact_id: number, sent: Record<string, unknown>): Record<string, unknown>=> +// What the CLI answers for a send Reply took: the contact it went to, as the add commands name it, so +// a caller can keep its id. Neither adds a time of its own: Reply's answer to a direct email carries +// none, and a LinkedIn send's sentAtUtc is given as Reply gives it. +const result_of = (name: Direct_send_name, contact: Ensured, sent: Record<string, unknown>): Record<string, unknown>=> name === 'send-email' ? { - status: 'sent', contact_id, + status: 'sent', contact_id: contact.id, contact_created: contact.created, message_id: typeof sent.messageId === 'string' ? sent.messageId : null, sent_at: null, reply_status: typeof sent.status === 'string' ? sent.status : null, } : { - status: 'sent', contact_id, + status: 'sent', contact_id: contact.id, contact_created: contact.created, activity_id: positive_integer(sent.linkedInActivityId), sent_at: typeof sent.sentAtUtc === 'string' ? sent.sentAtUtc : null, }; +// A person given by their fields is looked up by the address the send reaches them at, so one who +// lacks it is refused before anything is asked. The address is never repeated. +const require_address = (name: Direct_send_name, contact: Contact_ref, by: Channel): void=>{ + if (contact.kind === 'person' && (by === 'email' ? contact.person.email : contact.person.linkedin_url) === undefined) + { + throw new UsageError(by === 'email' + ? `contact ${name} needs the contact's email: the email goes to it.` + : `contact ${name} needs the contact's linkedin_url: the send goes to that profile.`, { + code: 'usage.contact', hint: 'Give it in --contact, or name a contact Reply holds with --contact-id.', + }); + } +}; + const handle_direct_send = async( name: Direct_send_name, opts: Direct_send_opts, ctx: Cli_context, g: Op_globals, read_stdin?: () => string, ): Promise<void>=>{ const send = DIRECT_SENDS[name]; - const contact_id = required_id(opts.contactId, '--contact-id'); + const stdin = stdin_inputs({contact: opts.contact, message: opts.message}, { + code: 'usage.stdin', hint: `Pipe both in one object: echo '{"contact":{…},"message":{…}}' | ${PROGRAM_NAME} contact ${name} --contact - … --message -`, + }, read_stdin); + const contact = read_contact_input(opts, stdin.contact); // A send always names the account it goes from: Reply would send an email from the default mailbox. const by_email = name === 'send-email'; + const by: Channel = by_email ? 'email' : 'linkedin'; + require_address(name, contact, by); const account_id = by_email ? required_id(opts.emailAccountId, '--email-account-id', LARGEST_SAFE_ID) : required_id(opts.linkedinAccountId, '--linkedin-account-id'); - const ids: Ids = by_email ? {contact_id, email_account_id: account_id} : {contact_id, linkedin_account_id: account_id}; - const text = read_text(name, send, opts.message, read_stdin); + const ids: Ids = by_email ? {email_account_id: account_id} : {linkedin_account_id: account_id}; + const text = read_text(name, send, opts.message, stdin.message); const s = await open_session(ctx, g); + let sending = false; try { - const a = await call_reply(s, 'POST', `/v3/contacts/${contact_id}/${send.path}`, 'write', send.body(account_id, text)); + // The contact first, found or imported as an add would; the send goes to the one this names. + const ensured = await find_or_import(s, contact, by); + ids.contact_id = ensured.id; + sending = true; + const a = await call_reply(s, 'POST', `/v3/contacts/${ensured.id}/${send.path}`, 'write', send.body(account_id, text)); if (name === 'linkedin-connect' && a.status === 409 && reply_code_of(a) === 'directLinkedIn.alreadyConnected') { // Nothing was sent, and nothing needs to be: the contact is already a connection. - print_result({status: 'already_connected', contact_id, activity_id: null, sent_at: null}, g); + print_result({status: 'already_connected', contact_id: ensured.id, contact_created: ensured.created, activity_id: null, sent_at: null}, g); return; } if (a.status !== 200) { - throw send_refusal(a, contact_id); + throw send_refusal(a, ensured.id); } - print_result(result_of(name, contact_id, expect_object(a, 'write')), g); + print_result(result_of(name, ensured, expect_object(a, 'write')), g); } catch (e) { - // Unlike most work commands, a send is not safe to repeat: the same text would go twice. + // Unlike most work commands, a send is not safe to repeat: the same text would go twice. Before + // the send was made, only the contact's import can have been lost, and that is safe to repeat. if (e instanceof Unknown_outcome_error) { - e.hint = `The ${send.what} may have been sent; running the command again may send it twice.`; + e.hint = sending + ? `The ${send.what} may have been sent; running the command again may send it twice.` + : `Nothing was sent: no answer came back to the contact's import, so the ${send.what} was never made. ` + + 'Running the command again is safe.'; } throw with_ids(e, ids); } diff --git a/src/operations/stdin-input.ts b/src/operations/stdin-input.ts index ae89635..55a6fba 100644 --- a/src/operations/stdin-input.ts +++ b/src/operations/stdin-input.ts @@ -39,5 +39,46 @@ const read_stdin_object = (source: string | undefined, o: Stdin_object_opts, rea return value; }; -export {read_stdin_object}; +// The person and their text, each read from stdin by its own flag. When both flags take '-', stdin +// holds one object with each input under its flag's name, {"contact": {…}, "message": {…}}; it is +// read once, and each flag is handed its member as the text it would have read alone. When at most +// one does, that one reads stdin as ever. No message here repeats any of it: an unknown member is +// named, never its value. +const stdin_inputs = <K extends string>( + sources: Record<K, string | undefined>, o: {code: string; hint: string}, read_stdin?: () => string, +): Record<K, () => string>=>{ + const read = read_stdin ?? read_all_stdin; + const names = Object.keys(sources) as K[]; + const piped = names.filter(n=>sources[n] === '-'); + if (piped.length < 2) + { + return Object.fromEntries(names.map(n=>[n, read])) as Record<K, () => string>; + } + const flags = piped.map(n=>`--${n} -`).join(' and '); + const shape = `{${piped.map(n=>`"${n}": {…}`).join(', ')}}`; + let value: unknown; + try { + value = JSON.parse(read()); + } catch { + throw new UsageError(`With ${flags} both, stdin must be JSON: ${shape}.`, {code: o.code, hint: o.hint}); + } + if (!is_object(value)) + { + throw new UsageError(`With ${flags} both, stdin must be one JSON object: ${shape}.`, {code: o.code, hint: o.hint}); + } + const input = value; + const unknown_field = Object.keys(input).find(k=>!(piped as string[]).includes(k)); + if (unknown_field !== undefined) + { + throw new UsageError(`Stdin has an unknown field '${unknown_field}'.`, {code: o.code, hint: `Fields: ${piped.join(', ')}.`}); + } + const missing = piped.find(n=>input[n] === undefined); + if (missing !== undefined) + { + throw new UsageError(`Stdin has no ${missing}: with ${flags} both, it holds ${shape}.`, {code: o.code, hint: o.hint}); + } + return Object.fromEntries(names.map(n=>[n, sources[n] === '-' ? ()=>JSON.stringify(input[n]) : read])) as Record<K, () => string>; +}; + +export {read_stdin_object, stdin_inputs}; export type {Stdin_object_opts}; From 05c392d910acc2fd196618ece59f1dec2fdef908 Mon Sep 17 00:00:00 2001 From: Artem Kosolap <art@reply.io> Date: Wed, 21 Oct 2026 18:38:26 -0700 Subject: [PATCH 02/11] feat: contact update finds or imports the person given by their fields contact update took only a contact id, so changing the fields of someone Reply did not hold yet needed an add command first. It now also takes the contact flags the add commands take. A person given by their fields is looked up as the add commands look one up and imported only when Reply holds nobody under the address; the id argument keeps working and counts as one of the ways. The fields that name the person only find or import them: on a contact Reply holds, the PATCH carries exactly what --fields names, never the address the contact was found by. Custom fields are read before the person is found or imported, so an unknown name still changes nothing. With --contact - and --fields - both, stdin holds one object, {"contact": {...}, "fields": {...}}. --- src/__tests__/operations/commands.test.ts | 8 +- .../operations/contact-record.test.ts | 127 +++++++++++++++++- src/operations/commands.ts | 34 +++-- src/operations/contact-record.ts | 55 ++++++-- 4 files changed, 194 insertions(+), 30 deletions(-) diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index 4f305d6..5dd388e 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -43,7 +43,7 @@ describe('operations/commands', ()=>{ }); // The sends and contact update find or import the person as the add commands do. - const SENDS_AND_UPDATE = ['send-email', 'linkedin-connect', 'linkedin-message', 'linkedin-inmail', 'linkedin-voice']; + const SENDS_AND_UPDATE = ['update', 'send-email', 'linkedin-connect', 'linkedin-message', 'linkedin-inmail', 'linkedin-voice']; const CONTACT_FLAGS = ['--contact-id', '--email', '--first-name', '--last-name', '--company', '--title', '--contact']; it('the commands about a person take the contact flags', ()=>{ @@ -95,6 +95,10 @@ describe('operations/commands', ()=>{ const text = help_of(sub(contact_command, name)).replace(/\s+/g, ' '); expect(text, text).toContain('looked up by its LinkedIn URL'); } + const update = help_of(sub(contact_command, 'update')).replace(/\s+/g, ' '); + expect(update, update).toContain('looked up as the add commands look one up'); + expect(update, update).toContain('only what --fields names is changed'); + expect(update, update).toContain('contact update 456 is contact update --contact-id 456'); }); it('carries each command\'s own flags', ()=>{ @@ -127,7 +131,7 @@ describe('operations/commands', ()=>{ it('contact update takes its values only through --fields -, and contact delete says what a re-run answers', ()=>{ const update = sub(contact_command, 'update'); - expect(flags(update)).toEqual(['--fields']); + expect(flags(update)).toEqual([...CONTACT_FLAGS, '--fields']); const text = help_of(update); expect(text, text).toContain('--fields -'); expect(text, text).toContain('contact.field_not_found'); diff --git a/src/__tests__/operations/contact-record.test.ts b/src/__tests__/operations/contact-record.test.ts index 6ef510b..c6298bd 100644 --- a/src/__tests__/operations/contact-record.test.ts +++ b/src/__tests__/operations/contact-record.test.ts @@ -129,7 +129,7 @@ describe('contact update', ()=>{ answer(json([{id: 1, title: 'leadSource', fieldType: 'text'}, {id: 2, title: 'budget', fieldType: 'text'}]), json({id: 456})); const {out} = await update('-', {first_name: ' Marta ', title: null, linkedin_url: URL_, custom_fields: [{name: 'leadSource', value: 'Event'}, {name: 'Budget', value: null}]}); - expect(JSON.parse(out)).toEqual({status: 'updated', contact_id: 456}); + expect(JSON.parse(out)).toEqual({status: 'updated', contact_id: 456, contact_created: false}); expect(sent()).toEqual([ {method: 'GET', url: FIELDS_URL, body: undefined}, {method: 'PATCH', url: 'https://api/v3/contacts/456', body: {firstName: 'Marta', title: null, linkedInUrl: URL_, @@ -146,7 +146,7 @@ describe('contact update', ()=>{ it('without custom fields there is no read before the PATCH', async()=>{ answer(json({id: 456})); const {out} = await update('-', {company: 'Acme', last_name: null}); - expect(JSON.parse(out)).toEqual({status: 'updated', contact_id: 456}); + expect(JSON.parse(out)).toEqual({status: 'updated', contact_id: 456, contact_created: false}); expect(sent()).toEqual([{method: 'PATCH', url: 'https://api/v3/contacts/456', body: {company: 'Acme', lastName: null}}]); }); @@ -223,6 +223,129 @@ describe('contact update', ()=>{ }); }); +describe('contact update of a person given by their fields', ()=>{ + const OTHER_PROFILE = 'https://www.linkedin.com/in/marta-other'; + const EMAIL_LOOKUP = 'GET https://api/v3/contacts?email=marta%40example.com&top=100&skip=0'; + const PROFILE_LOOKUP = `GET https://api/v3/contacts?linkedIn=${encodeURIComponent(URL_)}&top=100&skip=0`; + const IMPORT = 'POST https://api/v3/contacts/import'; + const nobody = ()=>json({items: [], hasMore: false}); + const held = (entry: Record<string, unknown>)=>json({items: [entry], hasMore: false}); + const lines = ()=>sent().map(r=>`${r.method} ${r.url}`); + type Update_opts = Parameters<typeof handle_contact_update>[1]; + + // The person and the fields both come on stdin, so the argument list carries neither: it is checked on every run. + const PERSONAL = /marta|example\.com|cto|acme|secret/i; + const update_by_fields = (input: unknown, opts: Update_opts = {contact: '-', fields: '-'}, id?: string)=>{ + expect(JSON.stringify([id, opts]), JSON.stringify(opts)).not.toMatch(PERSONAL); + return capture(()=>handle_contact_update(id, opts, ctx(), {json: true}, stdin(input))); + }; + const fail_by_fields = (input: unknown, opts?: Update_opts, id?: string)=>update_by_fields(input, opts, id).catch((x: unknown)=>x); + + it('a person Reply holds is found as the add commands find one and changed only by --fields: never their email or ' + + 'LinkedIn URL from the fields that found them', async()=>{ + answer(held({id: 456, email: 'marta@example.com'}), json({id: 456})); + const contact = {email: EMAIL, linkedin_url: OTHER_PROFILE, first_name: 'Marta', last_name: 'Example', company: 'Old Co', title: 'Old'}; + const {out} = await update_by_fields({contact, fields: {title: 'CTO'}}); + expect(JSON.parse(out)).toStrictEqual({status: 'updated', contact_id: 456, contact_created: false}); + expect(lines()).toEqual([EMAIL_LOOKUP, 'PATCH https://api/v3/contacts/456']); + expect(sent()[1].body).toStrictEqual({title: 'CTO'}); + }); + + it('a person given only by LinkedIn URL is found by it, and only a linkedin_url in --fields changes it', async()=>{ + answer(held({id: 456, linkedInUrl: URL_}), json({id: 456})); + await update_by_fields({contact: {linkedin_url: URL_}, fields: {company: 'Acme'}}); + expect(lines()).toEqual([PROFILE_LOOKUP, 'PATCH https://api/v3/contacts/456']); + expect(sent()[1].body).toStrictEqual({company: 'Acme'}); + mock_fetch.mockReset(); + answer(held({id: 456, linkedInUrl: URL_}), json({id: 456})); + await update_by_fields({contact: {linkedin_url: URL_}, fields: {linkedin_url: OTHER_PROFILE}}); + expect(sent()[1].body).toStrictEqual({linkedInUrl: OTHER_PROFILE}); + }); + + it('a person Reply holds nobody under is imported with their names as an add imports them, then changed', async()=>{ + answer(nobody(), json({items: [{id: 457, status: 'created'}]}), json({id: 457})); + const {out} = await update_by_fields({contact: {email: EMAIL, first_name: 'Marta'}, fields: {title: 'CTO'}}); + expect(JSON.parse(out)).toStrictEqual({status: 'updated', contact_id: 457, contact_created: true}); + expect(lines()).toEqual([EMAIL_LOOKUP, IMPORT, 'PATCH https://api/v3/contacts/457']); + expect(sent()[1].body).toStrictEqual({items: [{email: EMAIL, firstName: 'Marta'}]}); + expect(sent()[2].body).toStrictEqual({title: 'CTO'}); + mock_fetch.mockReset(); + answer(nobody(), json({items: [{id: 458, status: 'created'}]}), json({id: 458})); + await update_by_fields({contact: {linkedin_url: URL_, first_name: 'Marta'}, fields: {title: 'CTO'}}); + expect(lines()).toEqual([PROFILE_LOOKUP, IMPORT, 'PATCH https://api/v3/contacts/458']); + expect(sent()[1].body).toStrictEqual({items: [{linkedInUrl: URL_, firstName: 'Marta'}], options: {keys: {linkedInUrl: true}}}); + }); + + it('custom fields are read before the person is found or imported, so a name the account lacks imports nobody', async()=>{ + answer(json([{id: 1, title: 'leadSource', fieldType: 'text'}])); + const e = await fail_by_fields({contact: {email: EMAIL, first_name: 'Marta'}, fields: {custom_fields: [{name: 'Tier', value: SECRET}]}}); + expect(e).toMatchObject({code: 'contact.field_not_found', exit_code: 1}); + expect(lines()).toEqual([`GET ${FIELDS_URL}`]); + }); + + it('refuses as the add commands do, and changes nothing: two contacts held, the plan\'s limit, an item the import failed', async()=>{ + const two = json({items: [{id: 1, email: EMAIL}, {id: 2, email: EMAIL}], hasMore: false}); + const cases: [Response[], string][] = [ + [[two], 'contact.not_unique'], + [[nobody(), json({code: 'contact.limitExceeded', detail: 'Contact limit reached.'}, 400)], 'account.contact_limit_reached'], + [[nobody(), json({items: [{id: null, status: 'failed', error: 'Invalid data'}]})], 'reply.refused'], + ]; + for (const [answers, code] of cases) + { + mock_fetch.mockReset(); + answer(...answers); + const e = await fail_by_fields({contact: {email: EMAIL}, fields: {title: 'CTO'}}); + expect(e, code).toMatchObject({code, exit_code: 1}); + expect(shown(e), shown(e)).not.toMatch(PERSONAL); + expect(lines().filter(l=>l.startsWith('PATCH')), code).toEqual([]); + } + }); + + it('a lost answer to the import is outcome.unknown (exit 3), and nothing is changed; a lost PATCH names the contact', async()=>{ + const lost = Object.assign(new TypeError('fetch failed'), {cause: Object.assign(new Error('ECONNRESET'), {code: 'ECONNRESET'})}); + mock_fetch.mockResolvedValueOnce(nobody()).mockRejectedValueOnce(lost); + const before = await fail_by_fields({contact: {email: EMAIL, first_name: 'Marta'}, fields: {title: 'CTO'}}); + expect(before).toMatchObject({code: 'outcome.unknown', exit_code: 3}); + expect(lines()).toEqual([EMAIL_LOOKUP, IMPORT]); + mock_fetch.mockReset(); + answer(nobody(), json({items: [{id: 457, status: 'created'}]}), json('', 503)); + const after = await fail_by_fields({contact: {email: EMAIL, first_name: 'Marta'}, fields: {title: 'CTO'}}); + expect(after).toMatchObject({code: 'outcome.unknown', exit_code: 3, ids: {contact_id: 457}}); + }); + + it('the contact is given one way only: the id argument with a contact flag, or none at all, is refused before any call', async()=>{ + const cases: [Update_opts, string | undefined][] = [ + [{contactId: '457', fields: '-'}, '456'], [{contact: '-', fields: '-'}, '456'], [{fields: '-'}, undefined], + ]; + for (const [opts, id] of cases) + { + const e = await fail_by_fields({contact: {email: EMAIL}, fields: {title: 'CTO'}}, opts, id); + expect(e, JSON.stringify([id, opts])).toMatchObject({code: 'usage.contact', exit_code: 2}); + } + expect(mock_fetch).not.toHaveBeenCalled(); + answer(json({id: 457})); + const {out} = await update_by_fields({title: 'CTO'}, {contactId: '457', fields: '-'}); + expect(JSON.parse(out)).toStrictEqual({status: 'updated', contact_id: 457, contact_created: false}); + expect(lines()).toEqual(['PATCH https://api/v3/contacts/457']); + }); + + it('with --contact - and --fields - both, stdin must be one object holding each; nothing is repeated or called otherwise', async()=>{ + const cases: [unknown, string][] = [ + ['not json, Marta', 'usage.stdin'], [{contact: {email: EMAIL}}, 'usage.stdin'], [{fields: {title: 'CTO'}}, 'usage.stdin'], + [{contact: {email: EMAIL}, fields: {title: 'CTO'}, message: {body: SECRET}}, 'usage.stdin'], + [{contact: {email: EMAIL}, fields: {email: 'marta@example.org'}}, 'usage.fields'], + [{contact: {first_name: 'Marta'}, fields: {title: 'CTO'}}, 'usage.contact'], + ]; + for (const [input, code] of cases) + { + const e = await fail_by_fields(input); + expect(e, JSON.stringify(input)).toMatchObject({code, exit_code: 2}); + expect(shown(e), shown(e)).not.toMatch(PERSONAL); + } + expect(mock_fetch).not.toHaveBeenCalled(); + }); +}); + describe('contact delete', ()=>{ it('deletes the contact with one DELETE', async()=>{ answer(json(undefined, 204)); diff --git a/src/operations/commands.ts b/src/operations/commands.ts index e1b5b48..ceae14b 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -42,6 +42,13 @@ const piped = (command: string, contact = '{"email":"ann@example.com","first_nam const ALWAYS_IMPORTED = 'A contact given by email is always imported, so Reply needs a first name, even for one it already holds.\n' + 'One given only by LinkedIn URL is looked up first and imported only when Reply holds nobody under it.\n'; +// The codes a command that finds or imports a contact shares with the add commands. +const IMPORT_CODES = ['contact.not_unique', 'contact.invalid_email', 'contact.invalid_linkedin_url', 'account.contact_limit_reached']; + +// Both inputs on stdin, the person and the one the command acts with. +const STDIN_PAIR = (input: string): string=> + `With --contact - and --${input} - both, stdin holds one object: {"contact": {…}, "${input}": {…}}.\n`; + const run = (fn: (cmd: Command) => Promise<void>)=>async function(this: Command): Promise<void> { await fn(this); @@ -212,19 +219,27 @@ contact_command.command('get') await handle_contact_get(cmd.args[0], ctx, g); })); -contact_command.command('update') - .argument('<contact-id>', 'Contact id') +add_contact_options(contact_command.command('update') + .argument('[contact-id]', 'Contact id (or give the contact by the flags below)')) .option('--fields <stdin>', 'Only -: the fields to change as JSON on stdin') .description('Change some of a contact\'s fields and custom fields; the rest stay as they are') .addHelpText('after', help( [`echo '{"title":"CTO","company":"Acme"}' | ${P} contact update 456 --fields -`, - `echo '{"last_name":null,"custom_fields":[{"name":"leadSource","value":"Event"}]}' | ${P} contact update 456 --fields -`], - ['contact.not_found', 'contact.field_not_found'], true, - 'Result: {"status":"updated","contact_id"}\n' + `echo '{"last_name":null,"custom_fields":[{"name":"leadSource","value":"Event"}]}' | ${P} contact update 456 --fields -`, + `echo '{"contact":{"email":"ann@example.com","first_name":"Ann"},"fields":{"title":"CTO"}}' | ${P} contact update --contact - --fields -`], + ['contact.not_found', ...IMPORT_CODES, 'contact.field_not_found'], true, + 'Result: {"status":"updated","contact_id","contact_created"}\n' + 'Fields: {first_name, last_name, company, title, linkedin_url, custom_fields: [{name, value}]}; a field left out stays as\n' + 'it is, and null clears one. They are read from stdin only, so no value ever sits in the argument list. The CLI stores\n' + 'a LinkedIn URL by its lowercased slug, the form contacts are looked up by. A custom field is named as the account\n' - + 'names it (ignoring case); a name the account has none of is contact.field_not_found, and then nothing is changed.\n')) + + 'names it (ignoring case); a name the account has none of is contact.field_not_found, and then nothing is changed.\n' + + CONTACT_FORMS + + 'contact update 456 is contact update --contact-id 456. A contact given by its fields is looked up as the add commands\n' + + 'look one up, by its email, or one with only a LinkedIn URL by that, and imported only when Reply holds nobody under\n' + + 'it, as they import one; only then does Reply need a first name. A LinkedIn URL is matched by its lowercased slug,\n' + + 'and the CLI stores it by that slug when it imports the contact. Those fields only find or import the contact: on\n' + + 'one Reply holds, only what --fields names is changed. contact_created says whether this command created it.\n' + + STDIN_PAIR('fields'))) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); await handle_contact_update(cmd.args[0], cmd.opts(), ctx, g); @@ -255,13 +270,6 @@ add_contact_options(contact_command.command('opt-out')) const SEND_TWICE = (what: string): string=>`the ${what} may have been sent; running the command again may send it twice`; -// The codes a command that finds or imports a contact shares with the add commands. -const IMPORT_CODES = ['contact.not_unique', 'contact.invalid_email', 'contact.invalid_linkedin_url', 'account.contact_limit_reached']; - -// Both inputs on stdin, the person and the one the command acts with. -const STDIN_PAIR = (input: string): string=> - `With --contact - and --${input} - both, stdin holds one object: {"contact": {…}, "${input}": {…}}.\n`; - // How a send names its contact: looked up by the address it reaches them at, else imported as an add imports one. const SENT_TO = (by: 'email' | 'linkedin', what: string): string=>CONTACT_FORMS + `A contact given by its fields is looked up by ${by === 'email' ? 'its email' : 'its LinkedIn URL'}, where the ${what} goes, and imported only\n` diff --git a/src/operations/contact-record.ts b/src/operations/contact-record.ts index f2bc612..dd4ad77 100644 --- a/src/operations/contact-record.ts +++ b/src/operations/contact-record.ts @@ -1,10 +1,10 @@ import {PROGRAM_NAME} from '../config'; -import {Operation_error, Unknown_outcome_error, UsageError} from '../utils/errors'; +import {Operation_error, Unknown_outcome_error, UsageError, type Ids} from '../utils/errors'; import {call_reply, expect_object, is_object, refusal, unreadable, open_session, type Op_session} from './call'; import {parse_id, type Op_globals} from './options'; -import {person_of, linkedin_key} from './contact-input'; -import {find_contact_by_address, contact_not_found} from './contacts'; -import {read_stdin_object} from './stdin-input'; +import {person_of, linkedin_key, read_contact_input, type Contact_flags, type Contact_ref} from './contact-input'; +import {find_contact_by_address, find_or_import, contact_not_found} from './contacts'; +import {read_stdin_object, stdin_inputs} from './stdin-input'; import {print_result, with_ids} from './result'; import type {Cli_context} from '../context'; @@ -161,27 +161,55 @@ const resolve_custom_fields = async(s: Op_session, custom: Custom_value[]): Prom return custom.map(c=>({name: title_of(c.name) as string, value: c.value})); }; +type Update_opts = Contact_flags & {fields?: string}; + +// The contact id as the argument, as it always was, or the contact flags; never both. +const contact_to_update = (id_arg: string | undefined, opts: Update_opts, read_stdin: () => string): Contact_ref=>{ + if (id_arg === undefined) + { + return read_contact_input(opts, read_stdin); + } + if ([opts.contactId, opts.email, opts.firstName, opts.lastName, opts.company, opts.title, opts.contact].some(v=>v !== undefined)) + { + throw new UsageError('The contact was given more than one way.', { + code: 'usage.contact', hint: 'Give the contact id as the argument, or the contact by its flags, not both.', + }); + } + return {kind: 'id', id: parse_id(id_arg, 'Contact id')}; +}; + const handle_contact_update = async( - id_arg: string, opts: {fields?: string}, ctx: Cli_context, g: Op_globals, read_stdin?: () => string, + id_arg: string | undefined, opts: Update_opts, ctx: Cli_context, g: Op_globals, read_stdin?: () => string, ): Promise<void>=>{ - const id = parse_id(id_arg, 'Contact id'); - const {patch, custom} = read_contact_update(opts.fields, read_stdin); + const stdin = stdin_inputs({contact: opts.contact, fields: opts.fields}, { + code: 'usage.stdin', hint: `Pipe both in one object: echo '{"contact":{…},"fields":{…}}' | ${PROGRAM_NAME} contact update --contact - --fields -`, + }, read_stdin); + const contact = contact_to_update(id_arg, opts, stdin.contact); + const {patch, custom} = read_contact_update(opts.fields, stdin.fields); const s = await open_session(ctx, g); + const ids: Ids = contact.kind === 'id' ? {contact_id: contact.id} : {}; try { - // Absent fields stay as they are; a null clears one. Custom fields go by name. - const body = custom === undefined ? patch : {...patch, customFields: await resolve_custom_fields(s, custom)}; - const a = await call_reply(s, 'PATCH', `/v3/contacts/${id}`, 'write', body); + // Custom fields go by name, read before the contact is found or imported, so a name the account + // lacks changes nothing at all. + const custom_fields = custom === undefined ? undefined : await resolve_custom_fields(s, custom); + // The contact's fields only find the contact, or import it as an add would; the change is the + // --fields alone, so a contact Reply holds keeps the address it was found by. + const ensured = await find_or_import(s, contact); + ids.contact_id = ensured.id; + // Absent fields stay as they are; a null clears one. + const body = custom_fields === undefined ? patch : {...patch, customFields: custom_fields}; + const a = await call_reply(s, 'PATCH', `/v3/contacts/${ensured.id}`, 'write', body); if (a.status === 404) { - throw contact_not_found(id, a); + throw contact_not_found(ensured.id, a); } if (a.status !== 200 && a.status !== 204) { throw refusal(a, 'write'); } - print_result({status: 'updated', contact_id: id}, g); + print_result({status: 'updated', contact_id: ensured.id, contact_created: ensured.created}, g); } catch (e) { - throw with_ids(e, {contact_id: id}); + throw with_ids(e, ids); } }; @@ -210,3 +238,4 @@ const handle_contact_delete = async(id_arg: string, ctx: Cli_context, g: Op_glob }; export {handle_contact_find, handle_contact_get, handle_contact_update, handle_contact_delete}; +export type {Update_opts}; From dbd5a81b9c904eb3fb8052182e886d2cf3873640 Mon Sep 17 00:00:00 2001 From: Artem Kosolap <art@reply.io> Date: Wed, 21 Oct 2026 18:39:12 -0700 Subject: [PATCH 03/11] test: the whole program takes the person and the text from stdin, never from the argument list A send to a person Reply does not hold and an update of one it holds, run as reply runs them: the argument list carries no personal data, the requests carry the person and the text, and the update's PATCH carries only its fields. --- src/__tests__/operations/program.test.ts | 43 ++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/__tests__/operations/program.test.ts b/src/__tests__/operations/program.test.ts index 2bd0626..03f88fa 100644 --- a/src/__tests__/operations/program.test.ts +++ b/src/__tests__/operations/program.test.ts @@ -109,6 +109,49 @@ describe('the program', ()=>{ } }); + // Stdin as the program reads it: descriptor 0 answers the text piped in, every other read goes to the disk. + const pipe_stdin = (text: string): void=>{ + const real = fs.readFileSync; + vi.spyOn(fs, 'readFileSync').mockImplementation(((file: fs.PathOrFileDescriptor, ...rest: unknown[])=> + (file === 0 ? text : (real as (...a: unknown[]) => unknown)(file, ...rest))) as typeof fs.readFileSync); + }; + const requests = ()=>(mock_fetch.mock.calls as [string, RequestInit][]).map(([url, init])=> + ({method: String(init.method), url, body: typeof init.body === 'string' ? JSON.parse(init.body) : undefined})); + const PERSONAL = /marta|example\.com|tuesday|cto/i; + + it('a send to a person Reply does not hold takes the person and the text from stdin: the argument list carries ' + + 'neither, and Reply gets both', async()=>{ + pipe_stdin(JSON.stringify({contact: {email: 'marta@example.com', first_name: 'Marta'}, + message: {subject: 'Hi Marta', body: 'Tuesday works'}})); + answer(json({items: [], hasMore: false}), json({items: [{id: 457, status: 'created'}]}), + json({code: 'contact.contactInBlackList'}, 400)); + const args = ['--json', '-k', 'key-1', 'contact', 'send-email', '--contact', '-', '--email-account-id', '12', '--message', '-']; + const {code, err} = await run_program(args); + expect(args.join(' '), args.join(' ')).not.toMatch(PERSONAL); + expect(code).toBe(1); + expect(JSON.parse(err)).toMatchObject({error: {code: 'contact.blacklisted', ids: {contact_id: 457, email_account_id: 12}}}); + expect(err, err).not.toMatch(PERSONAL); + expect(requests()).toEqual([ + {method: 'GET', url: 'https://api.reply.io/v3/contacts?email=marta%40example.com&top=100&skip=0', body: undefined}, + {method: 'POST', url: 'https://api.reply.io/v3/contacts/import', body: {items: [{email: 'marta@example.com', firstName: 'Marta'}]}}, + {method: 'POST', url: 'https://api.reply.io/v3/contacts/457/send-direct-email', + body: {emailAccountId: 12, subject: 'Hi Marta', body: 'Tuesday works'}}, + ]); + }); + + it('contact update of a person Reply holds takes the person and the fields from stdin, and changes only the fields', async()=>{ + pipe_stdin(JSON.stringify({contact: {email: 'marta@example.com', linkedin_url: 'https://www.linkedin.com/in/marta-other'}, + fields: {title: 'CTO'}})); + answer(json({items: [{id: 456, email: 'marta@example.com'}], hasMore: false}), json('', 503)); + const args = ['--json', '-k', 'key-1', 'contact', 'update', '--contact', '-', '--fields', '-']; + const {code, err} = await run_program(args); + expect(args.join(' '), args.join(' ')).not.toMatch(PERSONAL); + expect(code).toBe(3); + expect(JSON.parse(err)).toMatchObject({error: {code: 'outcome.unknown', ids: {contact_id: 456}}}); + expect(requests().map(r=>[r.method, r.body])).toEqual([['GET', undefined], ['PATCH', {title: 'CTO'}]]); + expect(requests()[1].url).toBe('https://api.reply.io/v3/contacts/456'); + }); + it('account list is a work command of its own: a channel it does not know exits 2 before any request', async()=>{ const {code, err} = await run_program(['--json', '-k', 'key-1', 'account', 'list', '--channel', 'sms']); expect(code).toBe(2); From 2bb812c00c490b675dfffadfd124acdf3368afaf Mon Sep 17 00:00:00 2001 From: Artem Kosolap <art@reply.io> Date: Wed, 21 Oct 2026 18:40:10 -0700 Subject: [PATCH 04/11] docs: the README says the sends and contact update find or import the person The table names the sends and contact update by <contact>, the paragraph on imports says which commands look first, by which address a send looks, and that each answers the contact id it acted on; a new paragraph shows stdin holding the person and the text together. --- README.md | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 81c32de..d11730c 100644 --- a/README.md +++ b/README.md @@ -195,11 +195,11 @@ prints JSON (indented; compact with `--json`) and says what happened in a stable | `reply contact-list add-contact <list-id> <contact> [--refuse-opted-out]` | → `added` | | `reply contact find --contact -` | the id of the contact under an email or a LinkedIn URL, or null; never creates one | | `reply contact get <id>` | the contact as Reply holds it | -| `reply contact update <id> --fields -` | change some fields and custom fields; null clears one → `updated` | +| `reply contact update (<id> \| <contact>) --fields -` | change some fields and custom fields; null clears one → `updated` | | `reply contact delete <id>` | → `deleted` | | `reply contact opt-out <contact>` | → `opted_out` | -| `reply contact send-email --contact-id N --email-account-id N --message -` | one email now, outside any sequence → `sent` | -| `reply contact linkedin-connect --contact-id N --linkedin-account-id N [--message -]` | a LinkedIn invitation, with or without a note → `sent` / `already_connected` | +| `reply contact send-email <contact> --email-account-id N --message -` | one email now, outside any sequence → `sent` | +| `reply contact linkedin-connect <contact> --linkedin-account-id N [--message -]` | a LinkedIn invitation, with or without a note → `sent` / `already_connected` | | `reply contact linkedin-message …` · `linkedin-inmail …` · `linkedin-voice …` | a LinkedIn message, an InMail, or an AI voice message spoken from a script → `sent` | | `reply inbox list (--contact-id \| --sequence-id) [--source] [--channel] [--category-id] [--since]` | one page of threads | | `reply inbox get <thread-id>` | a thread with its subject, and one page of its messages | @@ -221,9 +221,13 @@ echo '{"linkedin_url":"https://www.linkedin.com/in/ann-example","first_name":"An The two `add-contact` commands always import a contact given by email, and Reply refuses an import without a first name, even for a contact it already holds; a contact given only by LinkedIn URL is -looked up first and imported only when Reply holds nobody under it. `contact opt-out` imports only -someone Reply doesn't hold yet; `sequence remove-contact` never imports. A contact is looked up, and -an import matched, by its email; one with only a LinkedIn URL, by that. The lookup is Reply's exact +looked up first and imported only when Reply holds nobody under it. `contact opt-out`, `contact +update` and the direct sends look first and import only someone Reply doesn't hold yet, so only then +is a first name needed; `sequence remove-contact` never imports. Each of them answers the +`contact_id` it acted on and `contact_created`, so a caller can keep the id. A send looks the person +up by the address it reaches them at: the email for `contact send-email`, the LinkedIn URL for the +LinkedIn sends. Otherwise a contact is looked up by its email, and one with only a LinkedIn URL by +that; an import is matched by the email when there is one. The lookup is Reply's exact one: an email matches ignoring case, and a LinkedIn URL is matched by its lowercased slug — on linkedin.com the path's case does not count, nor the scheme's or host's, a default port, one trailing slash or a fragment, while `www` and the query do. Reply is asked for a LinkedIn URL in that form @@ -242,7 +246,18 @@ echo '{"name":"Q4 outreach"}' | reply sequence list --name - ``` `contact update` refuses a custom field the account has none of, `contact.field_not_found`, before -it changes anything. +it changes or imports anything. Given the contact by its flags rather than its id, it changes only +what `--fields` names: the contact's own fields find the contact, or import it, and never change one +Reply already holds. + +When `--contact -` and the command's own input (`--message -` or `--fields -`) both read stdin, it +holds one object with each under its flag's name, so neither the person nor the text ever sits in +the argument list: + +```sh +echo '{"contact":{"email":"ann@example.com","first_name":"Ann"},"fields":{"title":"CTO"}}' | reply contact update --contact - --fields - +echo '{"contact":{"linkedin_url":"https://www.linkedin.com/in/ann-example","first_name":"Ann"},"message":{"body":"Thanks for connecting, Ann."}}' | reply contact linkedin-message --contact - --linkedin-account-id 34 --message - +``` `inbox reply` takes its message, `{body, reply_to_message_id}`, from stdin only, and refuses it on the argument list. The reply goes to the thread's contact from the account that owns the thread; @@ -276,7 +291,8 @@ variables, and refuses one it cannot fill with `linkedin.missing_variables`. `inbox reply`, `sequence create` and the five direct sends are the work commands that are not safe to re-run. On exit 3 (outcome unknown) a reply or a send may already have gone, and running it again may -send it twice; for `inbox reply`, read the thread with `reply inbox get` before trying again. For +send it twice; a send whose contact's import lost its answer was never made, and its hint says so. +For `inbox reply`, read the thread with `reply inbox get` before trying again. For `sequence create`, Reply allows two sequences of one name, so after exit 3 look the name up with `sequence list --name -` first. Every other work command can simply be run again; a `contact delete` repeated after its first one took effect answers `contact.not_found`. From 9439ee560b6d32320a17eb106c5a7558b4ce93d8 Mon Sep 17 00:00:00 2001 From: Artem Kosolap <art@reply.io> Date: Wed, 21 Oct 2026 19:00:04 -0700 Subject: [PATCH 05/11] fix: a LinkedIn send never reaches a profile other than the one it was given When the person is given by fields and nobody is found by the LinkedIn URL, the import is matched by the email and may return a contact Reply already holds. That contact is now read before the send: a different LinkedIn profile refuses the send with contact.channel_conflict (exit 1, nothing sent or changed, the contact in ids); an empty one is given the profile, and only that field, before the send; the same profile (compared ignoring the scheme and www) goes ahead. A contact found by the URL or created by the import is not read. The hint after a lost answer to any step before the send says the send was never made. --- src/__tests__/operations/direct-send.test.ts | 93 +++++++++++++++++++- src/operations/contacts.ts | 60 ++++++++++++- src/operations/direct-send.ts | 9 +- 3 files changed, 154 insertions(+), 8 deletions(-) diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index 137345d..fd6ab0a 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -355,6 +355,8 @@ describe('a direct send to a person given by their fields', ()=>{ const EMAIL_LOOKUP = 'GET https://api/v3/contacts?email=marta%40example.com&top=100&skip=0'; const PROFILE_LOOKUP = `GET https://api/v3/contacts?linkedIn=${encodeURIComponent(PROFILE)}&top=100&skip=0`; const IMPORT = 'POST https://api/v3/contacts/import'; + const GET_456 = 'GET https://api/v3/contacts/456'; + const PATCH_456 = 'PATCH https://api/v3/contacts/456'; const nobody = ()=>json({items: [], hasMore: false}); const held = (entry: Record<string, unknown>)=>json({items: [entry], hasMore: false}); const imported = (id: number, status = 'created')=>json({items: [{id, status}]}); @@ -424,10 +426,10 @@ describe('a direct send to a person given by their fields', ()=>{ it('a send looks the person up by the address it reaches them at, whatever else is given, and the import matches by ' + 'the email as an add\'s does', async()=>{ const both = {...MARTA, linkedin_url: PROFILE}; - answer(nobody(), imported(456, 'updated'), activity('message')); + answer(nobody(), imported(456, 'updated'), json({id: 456, linkedInUrl: PROFILE}), activity('message')); expect(await run_by_fields('linkedin-message', {contact: both, message: {body: TEXT}}, by_fields(LINKEDIN_OPTS))) .toMatchObject({contact_id: 456, contact_created: false}); - expect(lines()).toEqual([PROFILE_LOOKUP, IMPORT, 'POST https://api/v3/contacts/456/send-direct-linkedin-message']); + expect(lines()).toEqual([PROFILE_LOOKUP, IMPORT, GET_456, 'POST https://api/v3/contacts/456/send-direct-linkedin-message']); expect(sent()[1].body).toStrictEqual({items: [{email: 'marta@example.com', linkedInUrl: PROFILE, firstName: 'Marta', lastName: 'Example'}]}); mock_fetch.mockReset(); answer(held({id: 456, email: 'marta@example.com'}), json({status: 'sent'})); @@ -435,6 +437,93 @@ describe('a direct send to a person given by their fields', ()=>{ expect(lines()).toEqual([EMAIL_LOOKUP, 'POST https://api/v3/contacts/456/send-direct-email']); }); + // A person given by fields whom the import matched (not created, not found by the profile) may hold another profile: + // the contact is read before the act, and the act goes only to the profile that was asked about. + describe('a LinkedIn send to a contact the import matched', ()=>{ + const BOTH = {...MARTA, linkedin_url: PROFILE}; + const OTHER = 'https://www.linkedin.com/in/someone-else'; + const matched = (...rest: Response[])=>answer(nobody(), imported(456, 'updated'), ...rest); + const changes = ()=>lines().filter(l=>l.includes('send-direct') || l.startsWith('PATCH')); + + it('refuses a contact that holds another profile, before anything is sent or changed, naming the contact and neither URL', async()=>{ + for (const [name, message] of LINKEDIN_SENDS) + { + mock_fetch.mockReset(); + matched(json({id: 456, email: 'marta@example.com', linkedInUrl: OTHER})); + const e = await fail_by_fields(name, {contact: BOTH, message}, by_fields(LINKEDIN_OPTS)); + expect(e, name).toMatchObject({code: 'contact.channel_conflict', exit_code: 1, ids: {contact_id: 456, linkedin_account_id: 34}}); + expect(shown(e), shown(e)).not.toMatch(/marta|example|linkedin\.com/i); + expect(shown(e), shown(e)).toContain('nothing was sent'); + expect(lines(), name).toEqual([PROFILE_LOOKUP, IMPORT, GET_456]); + } + }); + + it('acts when the contact holds the same profile, whatever its scheme, www, case or trailing slash', async()=>{ + for (const held_url of [PROFILE, 'http://linkedin.com/in/Marta-Example/', 'https://linkedin.com/in/marta-example']) + { + mock_fetch.mockReset(); + matched(json({id: 456, linkedInUrl: held_url}), activity('message')); + expect(await run_by_fields('linkedin-message', {contact: BOTH, message: {body: TEXT}}, by_fields(LINKEDIN_OPTS)), held_url) + .toMatchObject({status: 'sent', contact_id: 456, contact_created: false}); + expect(lines(), held_url).toEqual([PROFILE_LOOKUP, IMPORT, GET_456, 'POST https://api/v3/contacts/456/send-direct-linkedin-message']); + } + }); + + it('gives a contact that holds no profile the given one, alone, before the act: no other field and never an email', async()=>{ + for (const empty of [{}, {linkedInUrl: null}, {linkedInUrl: ''}, {linkedInUrl: ' '}]) + { + mock_fetch.mockReset(); + matched(json({id: 456, email: 'other@example.org', firstName: 'Marta', ...empty}), json({}), activity('connect')); + await run_by_fields('linkedin-connect', {contact: BOTH, message: {note: NOTE}}, by_fields(LINKEDIN_OPTS)); + expect(lines(), JSON.stringify(empty)).toEqual([PROFILE_LOOKUP, IMPORT, GET_456, PATCH_456, + 'POST https://api/v3/contacts/456/send-direct-linkedin-connect']); + expect(sent()[3].body, JSON.stringify(empty)).toStrictEqual({linkedInUrl: PROFILE}); + } + }); + + it('refuses, with nothing sent, a contact that cannot be read or given the profile, and a lost answer to either', async()=>{ + const input = {contact: BOTH, message: {body: TEXT}}; + matched(json({code: 'contact.notFound'}, 404)); + expect(await fail_by_fields('linkedin-message', input, by_fields(LINKEDIN_OPTS))) + .toMatchObject({code: 'contact.not_found', exit_code: 1, ids: {contact_id: 456}}); + expect(changes()).toEqual([]); + mock_fetch.mockReset(); + matched(json({id: 456, linkedInUrl: null}), json({code: 'contact.notFound'}, 404)); + expect(await fail_by_fields('linkedin-message', input, by_fields(LINKEDIN_OPTS))) + .toMatchObject({code: 'contact.not_found', exit_code: 1, ids: {contact_id: 456}}); + expect(changes()).toEqual([PATCH_456]); + mock_fetch.mockReset(); + mock_fetch.mockResolvedValueOnce(nobody()).mockResolvedValueOnce(imported(456, 'updated')).mockRejectedValueOnce(lost_connection()); + const read = await fail_by_fields('linkedin-message', input, by_fields(LINKEDIN_OPTS)); + expect(read, shown(read)).toMatchObject({exit_code: 1, ids: {contact_id: 456}}); + expect(changes()).toEqual([]); + mock_fetch.mockReset(); + mock_fetch.mockResolvedValueOnce(nobody()).mockResolvedValueOnce(imported(456, 'updated')) + .mockResolvedValueOnce(json({id: 456})).mockRejectedValueOnce(lost_connection()); + const set = await fail_by_fields('linkedin-message', input, by_fields(LINKEDIN_OPTS)) as {hint?: string}; + expect(set).toMatchObject({code: 'outcome.unknown', exit_code: 3, ids: {contact_id: 456}}); + expect(set.hint, set.hint).toContain('Nothing was sent'); + expect(set.hint, set.hint).not.toContain('may send it twice'); + expect(changes()).toEqual([PATCH_456]); + }); + + it('reads nothing of a contact found by the profile, or created by the import', async()=>{ + answer(held({id: 456, linkedInUrl: PROFILE}), activity('message')); + await run_by_fields('linkedin-message', {contact: BOTH, message: {body: TEXT}}, by_fields(LINKEDIN_OPTS)); + expect(lines()).toEqual([PROFILE_LOOKUP, 'POST https://api/v3/contacts/456/send-direct-linkedin-message']); + mock_fetch.mockReset(); + answer(nobody(), imported(457), activity('message')); + await run_by_fields('linkedin-message', {contact: BOTH, message: {body: TEXT}}, by_fields(LINKEDIN_OPTS)); + expect(lines()).toEqual([PROFILE_LOOKUP, IMPORT, 'POST https://api/v3/contacts/457/send-direct-linkedin-message']); + }); + + it('send-email reads nothing: the contact is found by the address it is sent to', async()=>{ + answer(nobody(), imported(456, 'updated'), json({status: 'sent'})); + await run_by_fields('send-email', {contact: BOTH, message: {subject: SUBJECT, body: BODY}}, by_fields(EMAIL_OPTS)); + expect(lines()).toEqual([EMAIL_LOOKUP, IMPORT, 'POST https://api/v3/contacts/456/send-direct-email']); + }); + }); + it('a person without the address the send reaches them at is refused before any call, the address not repeated', async()=>{ const cases: [Direct_send_name, unknown, Direct_send_opts][] = [ ['send-email', {contact: {linkedin_url: PROFILE, first_name: 'Marta'}, message: {subject: SUBJECT, body: BODY}}, by_fields(EMAIL_OPTS)], diff --git a/src/operations/contacts.ts b/src/operations/contacts.ts index 06947b5..01618d5 100644 --- a/src/operations/contacts.ts +++ b/src/operations/contacts.ts @@ -199,13 +199,65 @@ const ensure_contact = async(s: Op_session, ref: Contact_ref): Promise<Ensured>= // The contact a command acts on: the id given; else the one Reply holds under the address the command // reaches the person by (by default the one a lookup uses); else the person imported as an add imports // them. Looking first means that a person Reply already holds needs no first name. -const find_or_import = async(s: Op_session, ref: Contact_ref, by?: Channel): Promise<Ensured>=>{ +const find_or_import = async(s: Op_session, ref: Contact_ref, by?: Channel): Promise<Ensured & {imported: boolean}>=>{ if (ref.kind === 'id') { - return {id: ref.id, created: false}; + return {id: ref.id, created: false, imported: false}; } const found = await find_contact_by_address(s, ref.person, by); - return found === null ? import_contact(s, ref.person) : {id: found, created: false}; + return found === null ? {...await import_contact(s, ref.person), imported: true} : {id: found, created: false, imported: false}; +}; + +// A profile compared as the lookup compares it, except that the scheme and a leading www do not count here: +// a contact stored as linkedin.com/in/x is the profile www.linkedin.com/in/x names. +const profile_of = (text: string): string | null=>{ + const key = linkedin_key(text) ?? linkedin_key(`https://${text.trim()}`); + return key === null ? null : key.replace(/^https?:\/\/(www\.)?/i, ''); +}; + +// An import that matched a contact fills only its empty fields, so the contact it returns may hold another +// LinkedIn profile than the one asked for, or none. A send to it must not reach a profile other than the one +// the caller named, an address is never changed, and a profile is given only where there is none: so the +// contact is read, a different profile refuses the send, and an empty one is given the profile, and only that +// field, before the send. A contact that can't be read is refused too. +const hold_profile = async(s: Op_session, contact_id: number, linkedin_url: string): Promise<void>=>{ + const a = await call_reply(s, 'GET', `/v3/contacts/${contact_id}`, 'read'); + if (a.status === 404) + { + throw contact_not_found(contact_id, a); + } + if (a.status !== 200) + { + throw refusal(a, 'read'); + } + const held = expect_object(a, 'read').linkedInUrl; + if (held !== undefined && held !== null && typeof held !== 'string') + { + throw unreadable(a, 'read'); + } + if (typeof held === 'string' && held.trim() !== '') + { + const wanted = profile_of(linkedin_url); + if (wanted !== null && profile_of(held) === wanted) + { + return; + } + throw new Operation_error('contact.channel_conflict', + 'The contact Reply holds under this email has another LinkedIn profile than the one given, so nothing was sent.', { + status: 200, + hint: 'Send to that contact with --contact-id if it is the same person, or change its linkedin_url with contact update ' + + 'first; or give the LinkedIn URL alone.', + }); + } + const set = await call_reply(s, 'PATCH', `/v3/contacts/${contact_id}`, 'write', {linkedInUrl: linkedin_key(linkedin_url) ?? linkedin_url}); + if (set.status === 404) + { + throw contact_not_found(contact_id, set); + } + if (set.status !== 200 && set.status !== 204) + { + throw refusal(set, 'write'); + } }; const find_contact = async(s: Op_session, ref: Contact_ref): Promise<number | null>=> @@ -232,5 +284,5 @@ const read_opted_out = async(s: Op_session, contact_id: number): Promise<boolean return body.isOptedOut; }; -export {ensure_contact, find_or_import, import_contact, find_contact, find_contact_by_address, read_opted_out, contact_not_found}; +export {ensure_contact, find_or_import, hold_profile, import_contact, find_contact, find_contact_by_address, read_opted_out, contact_not_found}; export type {Ensured, Channel}; diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index 184378b..20376bf 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -4,7 +4,7 @@ import {parse_retry_after} from '../utils/client'; import {call_reply, expect_object, refusal, reply_code_of, detail_of, open_session, type Answer} from './call'; import {parse_id, LARGEST_SAFE_ID, type Op_globals} from './options'; import {read_contact_input, type Contact_flags, type Contact_ref} from './contact-input'; -import {contact_not_found, find_or_import, type Channel, type Ensured} from './contacts'; +import {contact_not_found, find_or_import, hold_profile, type Channel, type Ensured} from './contacts'; import {read_stdin_object, stdin_inputs} from './stdin-input'; import {print_result, with_ids} from './result'; import type {Cli_context} from '../context'; @@ -219,6 +219,11 @@ const handle_direct_send = async( // The contact first, found or imported as an add would; the send goes to the one this names. const ensured = await find_or_import(s, contact, by); ids.contact_id = ensured.id; + // A contact the import matched may hold another profile, or none: it carries the one asked for before a LinkedIn send. + if (!by_email && contact.kind === 'person' && ensured.imported && !ensured.created && contact.person.linkedin_url !== undefined) + { + await hold_profile(s, ensured.id, contact.person.linkedin_url); + } sending = true; const a = await call_reply(s, 'POST', `/v3/contacts/${ensured.id}/${send.path}`, 'write', send.body(account_id, text)); if (name === 'linkedin-connect' && a.status === 409 && reply_code_of(a) === 'directLinkedIn.alreadyConnected') @@ -239,7 +244,7 @@ const handle_direct_send = async( { e.hint = sending ? `The ${send.what} may have been sent; running the command again may send it twice.` - : `Nothing was sent: no answer came back to the contact's import, so the ${send.what} was never made. ` + : `Nothing was sent: the outcome of a step before the ${send.what} is unknown, so the ${send.what} was never made. ` + 'Running the command again is safe.'; } throw with_ids(e, ids); From b9c4bca156d3353179fad692938b7b0db3f51890 Mon Sep 17 00:00:00 2001 From: Artem Kosolap <art@reply.io> Date: Wed, 21 Oct 2026 19:00:07 -0700 Subject: [PATCH 06/11] docs: the LinkedIn sends and the README say what happens to a contact the import matched --help of the four LinkedIn sends and the README state the contact.channel_conflict refusal, the profile set on a contact that holds none, and that --email alone is refused; the exit 3 line says "unless the hint says nothing was sent"; the name flags of the commands that look a contact up first say they are used only if it is imported; the README no longer implies sequence remove-contact answers contact_created. --- README.md | 19 +++++++++++---- src/__tests__/operations/commands.test.ts | 29 +++++++++++++++++++++-- src/operations/commands.ts | 24 +++++++++++++------ src/operations/contact-input.ts | 12 ++++++---- 4 files changed, 66 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index d11730c..4de495e 100644 --- a/README.md +++ b/README.md @@ -223,11 +223,21 @@ The two `add-contact` commands always import a contact given by email, and Reply without a first name, even for a contact it already holds; a contact given only by LinkedIn URL is looked up first and imported only when Reply holds nobody under it. `contact opt-out`, `contact update` and the direct sends look first and import only someone Reply doesn't hold yet, so only then -is a first name needed; `sequence remove-contact` never imports. Each of them answers the -`contact_id` it acted on and `contact_created`, so a caller can keep the id. A send looks the person +is a first name needed; `sequence remove-contact` never imports. Each of these except `sequence remove-contact` +answers the `contact_id` it acted on and `contact_created`, so a caller can keep the id. A send looks the person up by the address it reaches them at: the email for `contact send-email`, the LinkedIn URL for the LinkedIn sends. Otherwise a contact is looked up by its email, and one with only a LinkedIn URL by -that; an import is matched by the email when there is one. The lookup is Reply's exact +that; an import is matched by the email when there is one. + +A LinkedIn send never reaches a profile other than the one it was given. A contact found by the LinkedIn URL is +sent to as it is. When the person is given with an email and nobody is found by the LinkedIn URL, the import is +matched by the email and may return a contact Reply already holds, so that contact is read before the send: +if it holds another LinkedIn profile, nothing is sent or changed and the answer is `contact.channel_conflict` +(exit 1, the contact in `ids.contact_id`; send to it with `--contact-id` if it is the same person, or change its +`linkedin_url` with `contact update` first); if it holds none, only the given profile is set on it before the +send, never an email or any other field; if it holds the same profile (compared ignoring the scheme and `www`), +the send goes ahead. A contact the import created is not read. A LinkedIn send needs a `linkedin_url` in +`--contact` (or `--contact-id`): `--email` alone is refused. The lookup is Reply's exact one: an email matches ignoring case, and a LinkedIn URL is matched by its lowercased slug — on linkedin.com the path's case does not count, nor the scheme's or host's, a default port, one trailing slash or a fragment, while `www` and the query do. Reply is asked for a LinkedIn URL in that form @@ -291,7 +301,8 @@ variables, and refuses one it cannot fill with `linkedin.missing_variables`. `inbox reply`, `sequence create` and the five direct sends are the work commands that are not safe to re-run. On exit 3 (outcome unknown) a reply or a send may already have gone, and running it again may -send it twice; a send whose contact's import lost its answer was never made, and its hint says so. +send it twice, unless the hint says nothing was sent: a send whose contact's import, read or profile update lost its +answer was never made, and its hint says so. For `inbox reply`, read the thread with `reply inbox get` before trying again. For `sequence create`, Reply allows two sequences of one name, so after exit 3 look the name up with `sequence list --name -` first. Every other work command can simply be run again; a `contact delete` diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index 5dd388e..c85dba8 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -150,10 +150,26 @@ describe('operations/commands', ()=>{ expect(text.replace(/\s+/g, ' '), text).toContain('matched by its lowercased slug'); }); + it('the commands that look a contact up first say the name flags are used only if it is imported; the add commands do not', ()=>{ + const described = (c: Command, flag: string)=>c.options.find(o=>o.long === flag)?.description as string; + const lookups = ['update', 'opt-out', 'send-email', 'linkedin-connect', 'linkedin-message', 'linkedin-inmail', 'linkedin-voice']; + for (const name of lookups) + { + for (const flag of ['--last-name', '--company', '--title']) + { + expect(described(sub(contact_command, name), flag), `${name} ${flag}`).toContain('used only if the contact is imported'); + } + } + for (const flag of ['--last-name', '--company', '--title']) + { + expect(described(sub(sequence_command, 'add-contact'), flag), flag).not.toContain('used only if'); + } + }); + // Each direct send: the flag naming the account it goes from, the codes its endpoint publishes, and what its help // says sent_at is. const IMPORT = ['contact.not_unique', 'contact.invalid_email', 'contact.invalid_linkedin_url', 'account.contact_limit_reached']; - const LINKEDIN = ['contact.not_found', ...IMPORT, 'contact.no_linkedin_profile', 'linkedin.account_not_found', 'linkedin.feature_disabled', + const LINKEDIN = ['contact.not_found', ...IMPORT, 'contact.channel_conflict', 'contact.no_linkedin_profile', 'linkedin.account_not_found', 'linkedin.feature_disabled', 'linkedin.account_inactive', 'linkedin.invalid_cookie']; const SENT_AT_AS_GIVEN = 'sentAtUtc as Reply gives them, each null when it gives none; the CLI adds no time of its own'; const DIRECT_SENDS: [string, string, string[], string][] = [ @@ -186,8 +202,17 @@ describe('operations/commands', ()=>{ const text = help_of(c); const flat = text.replace(/\s+/g, ' '); expect(text, text).toContain('--message -'); - expect(flat, text).toContain('may send it twice'); + expect(flat, text).toContain('may send it twice, unless the hint says nothing was sent'); expect(text, text).not.toContain('re-running is safe'); + // A LinkedIn send says what happens to a contact the import matched; an email send has no such step. + const says_conflict = flat.includes('another LinkedIn profile than the one given, nothing is sent or changed'); + expect(says_conflict, text).toBe(name !== 'send-email'); + if (name !== 'send-email') + { + expect(flat, text).toContain('contact.channel_conflict (exit 1, with ids.contact_id)'); + expect(flat, text).toContain('only the given profile is set on it before the send, never an email or any other field'); + expect(flat, text).toContain('--email alone is refused (usage.contact)'); + } expect(flat, text).toContain(sent_at); expect(flat, text).toContain('read from stdin only'); // Exactly the codes its endpoint publishes, then the shared ones, as the help lists them. diff --git a/src/operations/commands.ts b/src/operations/commands.ts index ceae14b..2d47a48 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -220,7 +220,7 @@ contact_command.command('get') })); add_contact_options(contact_command.command('update') - .argument('[contact-id]', 'Contact id (or give the contact by the flags below)')) + .argument('[contact-id]', 'Contact id (or give the contact by the flags below)'), true) .option('--fields <stdin>', 'Only -: the fields to change as JSON on stdin') .description('Change some of a contact\'s fields and custom fields; the rest stay as they are') .addHelpText('after', help( @@ -256,7 +256,7 @@ contact_command.command('delete') await handle_contact_delete(cmd.args[0], ctx, g); })); -add_contact_options(contact_command.command('opt-out')) +add_contact_options(contact_command.command('opt-out'), true) .description('Mark the contact as opted out at Reply, creating them only if Reply has nobody under the address') .addHelpText('after', help([piped('contact opt-out'), ex('contact opt-out --contact-id 456')], ['contact.not_found', 'contact.not_unique', 'contact.invalid_email', 'contact.invalid_linkedin_url', 'account.contact_limit_reached'], true, @@ -268,7 +268,16 @@ add_contact_options(contact_command.command('opt-out')) await handle_contact_opt_out(cmd.opts(), ctx, g); })); -const SEND_TWICE = (what: string): string=>`the ${what} may have been sent; running the command again may send it twice`; +const SEND_TWICE = (what: string): string=> + `the ${what} may have been sent; running the command again may send it twice, unless the hint says nothing was sent`; + +// What a LinkedIn send does with a contact the import matched: the send goes only to the profile that was named. +const LINKEDIN_PROFILE = 'A LinkedIn send needs the contact\'s linkedin_url in --contact (or --contact-id); --email alone is refused (usage.contact).\n' + + 'When the import matches a contact Reply already holds, for instance by the email also given, that contact is read\n' + + 'before the send. If it holds another LinkedIn profile than the one given, nothing is sent or changed and the\n' + + 'answer is contact.channel_conflict (exit 1, with ids.contact_id); if it holds none, only the given profile is set\n' + + 'on it before the send, never an email or any other field; if it holds the same profile, the send goes ahead. A\n' + + 'contact found by its LinkedIn URL, or created by the import, is not read.\n'; // How a send names its contact: looked up by the address it reaches them at, else imported as an add imports one. const SENT_TO = (by: 'email' | 'linkedin', what: string): string=>CONTACT_FORMS @@ -276,7 +285,8 @@ const SENT_TO = (by: 'email' | 'linkedin', what: string): string=>CONTACT_FORMS + 'when Reply holds nobody under it, as the add commands import one (matched by its email when it has one); only\n' + 'then does Reply need a first name. A LinkedIn URL is matched by its lowercased slug, and the CLI stores it by\n' + `that slug when it imports the contact. contact_id is the contact the ${what} went to, and contact_created says\n` - + 'whether this command created them.\n' + STDIN_PAIR('message'); + + 'whether this command created them.\n' + + (by === 'email' ? '' : LINKEDIN_PROFILE) + STDIN_PAIR('message'); // One send's example with the person and the text both on stdin. const piped_send = (command: string, contact: string, message: string, flags: string): string=> @@ -284,7 +294,7 @@ const piped_send = (command: string, contact: string, message: string, flags: st const ANN_EMAIL = '{"email":"ann@example.com","first_name":"Ann"}'; const ANN_PROFILE = '{"linkedin_url":"https://www.linkedin.com/in/ann-example","first_name":"Ann"}'; -add_contact_options(contact_command.command('send-email')) +add_contact_options(contact_command.command('send-email'), true) .option('--email-account-id <id>', 'The mailbox to send from (see `account list`)') .option('--message <stdin>', 'Only -: the email {subject, body} as JSON on stdin') .description('Send one email to a contact now, outside any sequence, from the mailbox you name') @@ -306,7 +316,7 @@ add_contact_options(contact_command.command('send-email')) // The four LinkedIn sends share their flags, their first codes and the shape of their result. const LINKEDIN_SEND_CODES = [ - 'contact.not_found', ...IMPORT_CODES, 'contact.no_linkedin_profile', 'linkedin.account_not_found', 'linkedin.feature_disabled', + 'contact.not_found', ...IMPORT_CODES, 'contact.channel_conflict', 'contact.no_linkedin_profile', 'linkedin.account_not_found', 'linkedin.feature_disabled', 'linkedin.account_inactive', 'linkedin.invalid_cookie', ]; const LINKEDIN_SENT = '"contact_id","contact_created","activity_id","sent_at"}:\n' @@ -320,7 +330,7 @@ const linkedin_send = ( name: Exclude<Direct_send_name, 'send-email'>, description: string, message: string, examples: string[], codes: string[], extra: string, what: string, ): void=>{ - add_contact_options(contact_command.command(name)) + add_contact_options(contact_command.command(name), true) .option('--linkedin-account-id <id>', 'The LinkedIn account to send from (see `account list`)') .option('--message <stdin>', `Only -: the ${message} as JSON on stdin`) .description(description) diff --git a/src/operations/contact-input.ts b/src/operations/contact-input.ts index 643dec1..a231b9f 100644 --- a/src/operations/contact-input.ts +++ b/src/operations/contact-input.ts @@ -20,13 +20,15 @@ const PERSON_FIELDS = ['email', 'linkedin_url', 'first_name', 'last_name', 'comp const CODE = 'usage.contact'; const ONE_WAY_HINT = 'Use exactly one of --contact-id, --email (with its name flags), or --contact (which also takes linkedin_url).'; -const add_contact_options = (cmd: Command): Command=>cmd +// `found_first`: the command looks the contact up before it imports one, so the names only matter for a contact +// Reply doesn't hold yet and are otherwise unused. +const add_contact_options = (cmd: Command, found_first = false): Command=>cmd .option('--contact-id <id>', 'The contact by its Reply id') .option('--email <address>', 'The contact by email; with --first-name, --last-name, --company, --title') - .option('--first-name <name>', 'First name (with --email; Reply refuses to import a contact without one)') - .option('--last-name <name>', 'Last name (with --email)') - .option('--company <name>', 'Company (with --email)') - .option('--title <title>', 'Job title (with --email)') + .option('--first-name <name>', `First name (with --email; Reply refuses to import a contact without one)`) + .option('--last-name <name>', `Last name (with --email${found_first ? '; used only if the contact is imported' : ''})`) + .option('--company <name>', `Company (with --email${found_first ? '; used only if the contact is imported' : ''})`) + .option('--title <title>', `Job title (with --email${found_first ? '; used only if the contact is imported' : ''})`) .option('--contact <json>', 'The contact as JSON {email, linkedin_url, first_name, last_name, company, title}: inline, @file, or - for stdin'); const CONTACT_FORMS = ` From ca8a23789592ce0bb85e29252f3a79a0e7d556d6 Mon Sep 17 00:00:00 2001 From: Artem Kosolap <art@reply.io> Date: Wed, 21 Oct 2026 19:07:05 -0700 Subject: [PATCH 07/11] docs: say precisely what a channel_conflict refusal leaves untouched The import runs before the read, so it may already have filled the held contact's empty fields. The refusal now says nothing is sent and the contact's LinkedIn profile is not changed, names the contact as one Reply already holds, and adds "if it is a different person" to the hint. --- README.md | 2 +- src/__tests__/operations/commands.test.ts | 2 +- src/operations/commands.ts | 2 +- src/operations/contacts.ts | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 4de495e..76464dd 100644 --- a/README.md +++ b/README.md @@ -232,7 +232,7 @@ that; an import is matched by the email when there is one. A LinkedIn send never reaches a profile other than the one it was given. A contact found by the LinkedIn URL is sent to as it is. When the person is given with an email and nobody is found by the LinkedIn URL, the import is matched by the email and may return a contact Reply already holds, so that contact is read before the send: -if it holds another LinkedIn profile, nothing is sent or changed and the answer is `contact.channel_conflict` +if it holds another LinkedIn profile, nothing is sent and its LinkedIn profile is not changed, and the answer is `contact.channel_conflict` (exit 1, the contact in `ids.contact_id`; send to it with `--contact-id` if it is the same person, or change its `linkedin_url` with `contact update` first); if it holds none, only the given profile is set on it before the send, never an email or any other field; if it holds the same profile (compared ignoring the scheme and `www`), diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index c85dba8..f65a14a 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -205,7 +205,7 @@ describe('operations/commands', ()=>{ expect(flat, text).toContain('may send it twice, unless the hint says nothing was sent'); expect(text, text).not.toContain('re-running is safe'); // A LinkedIn send says what happens to a contact the import matched; an email send has no such step. - const says_conflict = flat.includes('another LinkedIn profile than the one given, nothing is sent or changed'); + const says_conflict = flat.includes('another LinkedIn profile than the one given, nothing is sent and its LinkedIn profile is not changed, and the answer'); expect(says_conflict, text).toBe(name !== 'send-email'); if (name !== 'send-email') { diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 2d47a48..718ffe7 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -274,7 +274,7 @@ const SEND_TWICE = (what: string): string=> // What a LinkedIn send does with a contact the import matched: the send goes only to the profile that was named. const LINKEDIN_PROFILE = 'A LinkedIn send needs the contact\'s linkedin_url in --contact (or --contact-id); --email alone is refused (usage.contact).\n' + 'When the import matches a contact Reply already holds, for instance by the email also given, that contact is read\n' - + 'before the send. If it holds another LinkedIn profile than the one given, nothing is sent or changed and the\n' + + 'before the send. If it holds another LinkedIn profile than the one given, nothing is sent and its LinkedIn profile is not changed, and the\n' + 'answer is contact.channel_conflict (exit 1, with ids.contact_id); if it holds none, only the given profile is set\n' + 'on it before the send, never an email or any other field; if it holds the same profile, the send goes ahead. A\n' + 'contact found by its LinkedIn URL, or created by the import, is not read.\n'; diff --git a/src/operations/contacts.ts b/src/operations/contacts.ts index 01618d5..f892f9b 100644 --- a/src/operations/contacts.ts +++ b/src/operations/contacts.ts @@ -243,10 +243,10 @@ const hold_profile = async(s: Op_session, contact_id: number, linkedin_url: stri return; } throw new Operation_error('contact.channel_conflict', - 'The contact Reply holds under this email has another LinkedIn profile than the one given, so nothing was sent.', { + 'A contact Reply already holds carries another LinkedIn profile than the one given, so nothing was sent and its LinkedIn profile was not changed.', { status: 200, hint: 'Send to that contact with --contact-id if it is the same person, or change its linkedin_url with contact update ' - + 'first; or give the LinkedIn URL alone.', + + 'first; or, if it is a different person, give the LinkedIn URL alone.', }); } const set = await call_reply(s, 'PATCH', `/v3/contacts/${contact_id}`, 'write', {linkedInUrl: linkedin_key(linkedin_url) ?? linkedin_url}); From 053bf3c27b88fb94925d9e273f54f8a5d7489286 Mon Sep 17 00:00:00 2001 From: Artem Kosolap <art@reply.io> Date: Wed, 21 Oct 2026 20:44:33 -0700 Subject: [PATCH 08/11] fix: a send given a person's fields sends only to a contact it created Reply does not refuse a direct send to a contact it holds as opted out, so the only guard on that opt-out is a caller that reads the contact before it sends. Given a person's fields, the five sends now act only on a contact the command created: when the lookup finds a contact, or the import matches one Reply already holds, nothing is sent and the answer is the new contact.already_held (exit 1), with the contact in ids.contact_id and a hint to read it and send with --contact-id. contact update and --contact-id are unchanged. A matched contact is now refused before anything else, so the read of an import-matched contact before a LinkedIn send (contact.channel_conflict, and the PATCH of an empty LinkedIn URL) could no longer be reached; it is removed with its tests. The hint after a lost import answer says a re-run answers contact.already_held if that import did create the contact. --- src/__tests__/operations/commands.test.ts | 24 ++- src/__tests__/operations/direct-send.test.ts | 147 +++++++------------ src/__tests__/operations/program.test.ts | 13 ++ src/operations/commands.ts | 35 +++-- src/operations/contacts.ts | 60 +------- src/operations/direct-send.ts | 27 +++- 6 files changed, 116 insertions(+), 190 deletions(-) diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index f65a14a..df60954 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -83,7 +83,6 @@ describe('operations/commands', ()=>{ const flat = text.replace(/\s+/g, ' '); const input = name === 'update' ? 'fields' : 'message'; expect(flat, text).toContain('imported only when Reply holds nobody under'); - expect(flat, text).toContain('only then does Reply need a first name'); expect(flat, text).toContain('contact_created says whether this command created'); expect(flat, text).toContain(`With --contact - and --${input} - both, stdin holds one object: {"contact": {…}, "${input}": {…}}`); expect(text, text).toContain(`--contact - `); @@ -97,6 +96,8 @@ describe('operations/commands', ()=>{ } const update = help_of(sub(contact_command, 'update')).replace(/\s+/g, ' '); expect(update, update).toContain('looked up as the add commands look one up'); + // An update acts on a contact it finds, so only an import needs a first name. + expect(update, update).toContain('only then does Reply need a first name'); expect(update, update).toContain('only what --fields names is changed'); expect(update, update).toContain('contact update 456 is contact update --contact-id 456'); }); @@ -169,11 +170,11 @@ describe('operations/commands', ()=>{ // Each direct send: the flag naming the account it goes from, the codes its endpoint publishes, and what its help // says sent_at is. const IMPORT = ['contact.not_unique', 'contact.invalid_email', 'contact.invalid_linkedin_url', 'account.contact_limit_reached']; - const LINKEDIN = ['contact.not_found', ...IMPORT, 'contact.channel_conflict', 'contact.no_linkedin_profile', 'linkedin.account_not_found', 'linkedin.feature_disabled', - 'linkedin.account_inactive', 'linkedin.invalid_cookie']; + const LINKEDIN = ['contact.not_found', ...IMPORT, 'contact.already_held', 'contact.no_linkedin_profile', 'linkedin.account_not_found', + 'linkedin.feature_disabled', 'linkedin.account_inactive', 'linkedin.invalid_cookie']; const SENT_AT_AS_GIVEN = 'sentAtUtc as Reply gives them, each null when it gives none; the CLI adds no time of its own'; const DIRECT_SENDS: [string, string, string[], string][] = [ - ['send-email', '--email-account-id', ['contact.not_found', ...IMPORT, 'email_account.not_found', 'contact.blacklisted'], + ['send-email', '--email-account-id', ['contact.not_found', ...IMPORT, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted'], 'sent_at is always null; the CLI adds none of its own'], ['linkedin-connect', '--linkedin-account-id', [...LINKEDIN, 'linkedin.not_connected', 'linkedin.limit_reached', 'linkedin.message_too_long', 'linkedin.missing_variables'], SENT_AT_AS_GIVEN], @@ -204,15 +205,12 @@ describe('operations/commands', ()=>{ expect(text, text).toContain('--message -'); expect(flat, text).toContain('may send it twice, unless the hint says nothing was sent'); expect(text, text).not.toContain('re-running is safe'); - // A LinkedIn send says what happens to a contact the import matched; an email send has no such step. - const says_conflict = flat.includes('another LinkedIn profile than the one given, nothing is sent and its LinkedIn profile is not changed, and the answer'); - expect(says_conflict, text).toBe(name !== 'send-email'); - if (name !== 'send-email') - { - expect(flat, text).toContain('contact.channel_conflict (exit 1, with ids.contact_id)'); - expect(flat, text).toContain('only the given profile is set on it before the send, never an email or any other field'); - expect(flat, text).toContain('--email alone is refused (usage.contact)'); - } + // A send given a person's fields sends only to a contact it creates, and names one Reply already holds. + expect(flat, text).toContain('A send given a person\'s fields sends only to a contact it creates'); + expect(flat, text).toContain('the lookup finds a contact, or the import matches one Reply already holds, nothing is sent'); + expect(flat, text).toContain('the answer is contact.already_held (exit 1) with that contact\'s id in ids.contact_id'); + expect(flat, text).toContain('send to it with --contact-id'); + expect(flat.includes('--email alone is refused (usage.contact)'), text).toBe(name !== 'send-email'); expect(flat, text).toContain(sent_at); expect(flat, text).toContain('read from stdin only'); // Exactly the codes its endpoint publishes, then the shared ones, as the help lists them. diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index fd6ab0a..23b9a9e 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -355,8 +355,6 @@ describe('a direct send to a person given by their fields', ()=>{ const EMAIL_LOOKUP = 'GET https://api/v3/contacts?email=marta%40example.com&top=100&skip=0'; const PROFILE_LOOKUP = `GET https://api/v3/contacts?linkedIn=${encodeURIComponent(PROFILE)}&top=100&skip=0`; const IMPORT = 'POST https://api/v3/contacts/import'; - const GET_456 = 'GET https://api/v3/contacts/456'; - const PATCH_456 = 'PATCH https://api/v3/contacts/456'; const nobody = ()=>json({items: [], hasMore: false}); const held = (entry: Record<string, unknown>)=>json({items: [entry], hasMore: false}); const imported = (id: number, status = 'created')=>json({items: [{id, status}]}); @@ -408,120 +406,76 @@ describe('a direct send to a person given by their fields', ()=>{ } }); - it('a person Reply holds is sent to with no import, and needs no first name', async()=>{ - answer(held({id: 456, email: 'Marta@Example.com'}), json({status: 'sent', messageId: null})); - expect(await run_by_fields('send-email', {contact: {email: 'marta@example.com'}, message: {subject: SUBJECT, body: BODY}}, - by_fields(EMAIL_OPTS))).toMatchObject({status: 'sent', contact_id: 456, contact_created: false}); - expect(lines()).toEqual([EMAIL_LOOKUP, 'POST https://api/v3/contacts/456/send-direct-email']); - for (const [name, message, path, action] of LINKEDIN_SENDS) - { - mock_fetch.mockReset(); - answer(held({id: 456, linkedInUrl: `${PROFILE}/`}), activity(action)); - expect(await run_by_fields(name, {contact: {linkedin_url: PROFILE}, message}, by_fields(LINKEDIN_OPTS)), name) - .toMatchObject({status: 'sent', contact_id: 456, contact_created: false}); - expect(lines(), name).toEqual([PROFILE_LOOKUP, `POST https://api/v3/contacts/456/${path}`]); - } - }); - it('a send looks the person up by the address it reaches them at, whatever else is given, and the import matches by ' + 'the email as an add\'s does', async()=>{ const both = {...MARTA, linkedin_url: PROFILE}; - answer(nobody(), imported(456, 'updated'), json({id: 456, linkedInUrl: PROFILE}), activity('message')); + answer(nobody(), imported(457), activity('message')); expect(await run_by_fields('linkedin-message', {contact: both, message: {body: TEXT}}, by_fields(LINKEDIN_OPTS))) - .toMatchObject({contact_id: 456, contact_created: false}); - expect(lines()).toEqual([PROFILE_LOOKUP, IMPORT, GET_456, 'POST https://api/v3/contacts/456/send-direct-linkedin-message']); + .toMatchObject({contact_id: 457, contact_created: true}); + expect(lines()).toEqual([PROFILE_LOOKUP, IMPORT, 'POST https://api/v3/contacts/457/send-direct-linkedin-message']); expect(sent()[1].body).toStrictEqual({items: [{email: 'marta@example.com', linkedInUrl: PROFILE, firstName: 'Marta', lastName: 'Example'}]}); mock_fetch.mockReset(); - answer(held({id: 456, email: 'marta@example.com'}), json({status: 'sent'})); + answer(nobody(), imported(457), json({status: 'sent'})); await run_by_fields('send-email', {contact: both, message: {subject: SUBJECT, body: BODY}}, by_fields(EMAIL_OPTS)); - expect(lines()).toEqual([EMAIL_LOOKUP, 'POST https://api/v3/contacts/456/send-direct-email']); + expect(lines()).toEqual([EMAIL_LOOKUP, IMPORT, 'POST https://api/v3/contacts/457/send-direct-email']); }); - // A person given by fields whom the import matched (not created, not found by the profile) may hold another profile: - // the contact is read before the act, and the act goes only to the profile that was asked about. - describe('a LinkedIn send to a contact the import matched', ()=>{ - const BOTH = {...MARTA, linkedin_url: PROFILE}; - const OTHER = 'https://www.linkedin.com/in/someone-else'; - const matched = (...rest: Response[])=>answer(nobody(), imported(456, 'updated'), ...rest); - const changes = ()=>lines().filter(l=>l.includes('send-direct') || l.startsWith('PATCH')); + // Reply does not refuse a direct send to a contact it holds as opted out, so a send given a person's fields acts only + // on a contact it created: one Reply already holds, found by the lookup or matched by the import, is refused before + // anything is sent and named, for the caller to read before sending to it by its id. + describe('a send given a person\'s fields acts only on a contact it created', ()=>{ + type Case = {name: Direct_send_name; message: unknown; opts: Direct_send_opts; lookup: string; path: string; holder: object; done: () => Response}; + const FIVE: Case[] = [ + {name: 'send-email', message: {subject: SUBJECT, body: BODY}, opts: EMAIL_OPTS, lookup: EMAIL_LOOKUP, path: 'send-direct-email', + holder: {email: 'Marta@Example.com'}, done: ()=>json({status: 'sent'})}, + ...LINKEDIN_SENDS.map(([name, message, path, action]): Case=>({name, message, opts: LINKEDIN_OPTS, lookup: PROFILE_LOOKUP, path, + holder: {linkedInUrl: `${PROFILE}/`}, done: ()=>activity(action)})), + ]; + const PERSON = {...MARTA, linkedin_url: PROFILE}; + const refused = (e: unknown, label: string)=>{ + expect(e, label).toMatchObject({code: 'contact.already_held', exit_code: 1, ids: {contact_id: 456}}); + const hint = (e as {hint?: string}).hint ?? ''; + expect(hint, `${label}: ${hint}`).toContain('contact get 456'); + expect(hint, `${label}: ${hint}`).toContain('--contact-id 456'); + expect(shown(e), shown(e)).toContain('nothing was sent'); + expect(shown(e), shown(e)).not.toMatch(PERSONAL); + expect(lines().filter(l=>l.includes('send-direct')), label).toEqual([]); + }; - it('refuses a contact that holds another profile, before anything is sent or changed, naming the contact and neither URL', async()=>{ - for (const [name, message] of LINKEDIN_SENDS) + it('refuses a person the lookup finds: nothing is imported or sent, and the contact is named', async()=>{ + for (const c of FIVE) { mock_fetch.mockReset(); - matched(json({id: 456, email: 'marta@example.com', linkedInUrl: OTHER})); - const e = await fail_by_fields(name, {contact: BOTH, message}, by_fields(LINKEDIN_OPTS)); - expect(e, name).toMatchObject({code: 'contact.channel_conflict', exit_code: 1, ids: {contact_id: 456, linkedin_account_id: 34}}); - expect(shown(e), shown(e)).not.toMatch(/marta|example|linkedin\.com/i); - expect(shown(e), shown(e)).toContain('nothing was sent'); - expect(lines(), name).toEqual([PROFILE_LOOKUP, IMPORT, GET_456]); + answer(held({id: 456, ...c.holder}), c.done()); + refused(await fail_by_fields(c.name, {contact: PERSON, message: c.message}, by_fields(c.opts)), c.name); + expect(lines(), c.name).toEqual([c.lookup]); } }); - it('acts when the contact holds the same profile, whatever its scheme, www, case or trailing slash', async()=>{ - for (const held_url of [PROFILE, 'http://linkedin.com/in/Marta-Example/', 'https://linkedin.com/in/marta-example']) + it('refuses a person the import matches to a contact Reply already holds, a teammate\'s too: nothing is sent, and the ' + + 'contact is named', async()=>{ + for (const c of FIVE) { - mock_fetch.mockReset(); - matched(json({id: 456, linkedInUrl: held_url}), activity('message')); - expect(await run_by_fields('linkedin-message', {contact: BOTH, message: {body: TEXT}}, by_fields(LINKEDIN_OPTS)), held_url) - .toMatchObject({status: 'sent', contact_id: 456, contact_created: false}); - expect(lines(), held_url).toEqual([PROFILE_LOOKUP, IMPORT, GET_456, 'POST https://api/v3/contacts/456/send-direct-linkedin-message']); + for (const status of ['updated', 'skipped']) + { + mock_fetch.mockReset(); + answer(nobody(), imported(456, status), c.done()); + refused(await fail_by_fields(c.name, {contact: PERSON, message: c.message}, by_fields(c.opts)), `${c.name} ${status}`); + expect(lines(), `${c.name} ${status}`).toEqual([c.lookup, IMPORT]); + } } }); - it('gives a contact that holds no profile the given one, alone, before the act: no other field and never an email', async()=>{ - for (const empty of [{}, {linkedInUrl: null}, {linkedInUrl: ''}, {linkedInUrl: ' '}]) + it('sends to a person the import creates', async()=>{ + for (const c of FIVE) { mock_fetch.mockReset(); - matched(json({id: 456, email: 'other@example.org', firstName: 'Marta', ...empty}), json({}), activity('connect')); - await run_by_fields('linkedin-connect', {contact: BOTH, message: {note: NOTE}}, by_fields(LINKEDIN_OPTS)); - expect(lines(), JSON.stringify(empty)).toEqual([PROFILE_LOOKUP, IMPORT, GET_456, PATCH_456, - 'POST https://api/v3/contacts/456/send-direct-linkedin-connect']); - expect(sent()[3].body, JSON.stringify(empty)).toStrictEqual({linkedInUrl: PROFILE}); + answer(nobody(), imported(457), c.done()); + expect(await run_by_fields(c.name, {contact: PERSON, message: c.message}, by_fields(c.opts)), c.name) + .toMatchObject({status: 'sent', contact_id: 457, contact_created: true}); + expect(lines(), c.name).toEqual([c.lookup, IMPORT, `POST https://api/v3/contacts/457/${c.path}`]); } }); - - it('refuses, with nothing sent, a contact that cannot be read or given the profile, and a lost answer to either', async()=>{ - const input = {contact: BOTH, message: {body: TEXT}}; - matched(json({code: 'contact.notFound'}, 404)); - expect(await fail_by_fields('linkedin-message', input, by_fields(LINKEDIN_OPTS))) - .toMatchObject({code: 'contact.not_found', exit_code: 1, ids: {contact_id: 456}}); - expect(changes()).toEqual([]); - mock_fetch.mockReset(); - matched(json({id: 456, linkedInUrl: null}), json({code: 'contact.notFound'}, 404)); - expect(await fail_by_fields('linkedin-message', input, by_fields(LINKEDIN_OPTS))) - .toMatchObject({code: 'contact.not_found', exit_code: 1, ids: {contact_id: 456}}); - expect(changes()).toEqual([PATCH_456]); - mock_fetch.mockReset(); - mock_fetch.mockResolvedValueOnce(nobody()).mockResolvedValueOnce(imported(456, 'updated')).mockRejectedValueOnce(lost_connection()); - const read = await fail_by_fields('linkedin-message', input, by_fields(LINKEDIN_OPTS)); - expect(read, shown(read)).toMatchObject({exit_code: 1, ids: {contact_id: 456}}); - expect(changes()).toEqual([]); - mock_fetch.mockReset(); - mock_fetch.mockResolvedValueOnce(nobody()).mockResolvedValueOnce(imported(456, 'updated')) - .mockResolvedValueOnce(json({id: 456})).mockRejectedValueOnce(lost_connection()); - const set = await fail_by_fields('linkedin-message', input, by_fields(LINKEDIN_OPTS)) as {hint?: string}; - expect(set).toMatchObject({code: 'outcome.unknown', exit_code: 3, ids: {contact_id: 456}}); - expect(set.hint, set.hint).toContain('Nothing was sent'); - expect(set.hint, set.hint).not.toContain('may send it twice'); - expect(changes()).toEqual([PATCH_456]); - }); - - it('reads nothing of a contact found by the profile, or created by the import', async()=>{ - answer(held({id: 456, linkedInUrl: PROFILE}), activity('message')); - await run_by_fields('linkedin-message', {contact: BOTH, message: {body: TEXT}}, by_fields(LINKEDIN_OPTS)); - expect(lines()).toEqual([PROFILE_LOOKUP, 'POST https://api/v3/contacts/456/send-direct-linkedin-message']); - mock_fetch.mockReset(); - answer(nobody(), imported(457), activity('message')); - await run_by_fields('linkedin-message', {contact: BOTH, message: {body: TEXT}}, by_fields(LINKEDIN_OPTS)); - expect(lines()).toEqual([PROFILE_LOOKUP, IMPORT, 'POST https://api/v3/contacts/457/send-direct-linkedin-message']); - }); - - it('send-email reads nothing: the contact is found by the address it is sent to', async()=>{ - answer(nobody(), imported(456, 'updated'), json({status: 'sent'})); - await run_by_fields('send-email', {contact: BOTH, message: {subject: SUBJECT, body: BODY}}, by_fields(EMAIL_OPTS)); - expect(lines()).toEqual([EMAIL_LOOKUP, IMPORT, 'POST https://api/v3/contacts/456/send-direct-email']); - }); }); it('a person without the address the send reaches them at is refused before any call, the address not repeated', async()=>{ @@ -571,6 +525,7 @@ describe('a direct send to a person given by their fields', ()=>{ const before = await fail_by_fields('send-email', input, by_fields(EMAIL_OPTS)) as {hint?: string; ids?: object}; expect(before).toMatchObject({code: 'outcome.unknown', exit_code: 3}); expect(before.hint, before.hint).toContain('Nothing was sent'); + expect(before.hint, before.hint).toContain('contact.already_held'); expect(before.hint, before.hint).not.toContain('may send it twice'); expect(before.ids, JSON.stringify(before.ids)).not.toHaveProperty('contact_id'); expect(lines()).toEqual([EMAIL_LOOKUP, IMPORT]); @@ -634,10 +589,10 @@ describe('a direct send to a person given by their fields', ()=>{ const file = path.join(dir, 'person.json'); fs.writeFileSync(file, JSON.stringify(MARTA)); try { - answer(held({id: 456, email: 'marta@example.com'}), json({status: 'sent'})); + answer(nobody(), imported(457), json({status: 'sent'})); await run_by_fields('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, contactId: undefined, contact: `@${file}`}); - expect(lines()).toEqual([EMAIL_LOOKUP, 'POST https://api/v3/contacts/456/send-direct-email']); - expect(sent()[1].body).toMatchObject({subject: SUBJECT, body: BODY}); + expect(lines()).toEqual([EMAIL_LOOKUP, IMPORT, 'POST https://api/v3/contacts/457/send-direct-email']); + expect(sent()[2].body).toMatchObject({subject: SUBJECT, body: BODY}); } finally { fs.rmSync(dir, {recursive: true, force: true}); } diff --git a/src/__tests__/operations/program.test.ts b/src/__tests__/operations/program.test.ts index 03f88fa..a5c9833 100644 --- a/src/__tests__/operations/program.test.ts +++ b/src/__tests__/operations/program.test.ts @@ -139,6 +139,19 @@ describe('the program', ()=>{ ]); }); + it('a send to a person Reply already holds exits 1, sends nothing, and names the contact', async()=>{ + pipe_stdin(JSON.stringify({contact: {email: 'marta@example.com', first_name: 'Marta'}, + message: {subject: 'Hi Marta', body: 'Tuesday works'}})); + // Were the send made, this refusal would answer it: a send Reply took ends without the exit this run waits for. + answer(json({items: [{id: 456, email: 'marta@example.com'}], hasMore: false}), json({code: 'contact.contactInBlackList'}, 400)); + const {code, err} = await run_program(['--json', '-k', 'key-1', 'contact', 'send-email', '--contact', '-', '--email-account-id', '12', + '--message', '-']); + expect(code).toBe(1); + expect(JSON.parse(err)).toMatchObject({error: {code: 'contact.already_held', ids: {contact_id: 456, email_account_id: 12}}}); + expect(err, err).not.toMatch(PERSONAL); + expect(requests().map(r=>r.method)).toEqual(['GET']); + }); + it('contact update of a person Reply holds takes the person and the fields from stdin, and changes only the fields', async()=>{ pipe_stdin(JSON.stringify({contact: {email: 'marta@example.com', linkedin_url: 'https://www.linkedin.com/in/marta-other'}, fields: {title: 'CTO'}})); diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 718ffe7..2e13a00 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -271,22 +271,21 @@ add_contact_options(contact_command.command('opt-out'), true) const SEND_TWICE = (what: string): string=> `the ${what} may have been sent; running the command again may send it twice, unless the hint says nothing was sent`; -// What a LinkedIn send does with a contact the import matched: the send goes only to the profile that was named. -const LINKEDIN_PROFILE = 'A LinkedIn send needs the contact\'s linkedin_url in --contact (or --contact-id); --email alone is refused (usage.contact).\n' - + 'When the import matches a contact Reply already holds, for instance by the email also given, that contact is read\n' - + 'before the send. If it holds another LinkedIn profile than the one given, nothing is sent and its LinkedIn profile is not changed, and the\n' - + 'answer is contact.channel_conflict (exit 1, with ids.contact_id); if it holds none, only the given profile is set\n' - + 'on it before the send, never an email or any other field; if it holds the same profile, the send goes ahead. A\n' - + 'contact found by its LinkedIn URL, or created by the import, is not read.\n'; - -// How a send names its contact: looked up by the address it reaches them at, else imported as an add imports one. +const LINKEDIN_URL_NEEDED = 'A LinkedIn send needs the contact\'s linkedin_url in --contact (or --contact-id); --email alone is refused ' + + '(usage.contact).\n'; + +// How a send names its contact: looked up by the address it reaches them at, else imported as an add imports one; and +// it sends only to a contact it created, naming one Reply already holds instead. const SENT_TO = (by: 'email' | 'linkedin', what: string): string=>CONTACT_FORMS - + `A contact given by its fields is looked up by ${by === 'email' ? 'its email' : 'its LinkedIn URL'}, where the ${what} goes, and imported only\n` - + 'when Reply holds nobody under it, as the add commands import one (matched by its email when it has one); only\n' - + 'then does Reply need a first name. A LinkedIn URL is matched by its lowercased slug, and the CLI stores it by\n' - + `that slug when it imports the contact. contact_id is the contact the ${what} went to, and contact_created says\n` - + 'whether this command created them.\n' - + (by === 'email' ? '' : LINKEDIN_PROFILE) + STDIN_PAIR('message'); + + 'A send given a person\'s fields sends only to a contact it creates. The contact is looked up by\n' + + `${by === 'email' ? 'its email' : 'its LinkedIn URL'}, where the ${what} goes, and imported only when Reply holds nobody under it, as the add\n` + + 'commands import one (matched by its email when it has one), so Reply needs a first name. When the lookup finds a\n' + + 'contact, or the import matches one Reply already holds, nothing is sent: the answer is contact.already_held (exit 1)\n' + + 'with that contact\'s id in ids.contact_id. Read that contact first (contact get shows it, its opt-out included),\n' + + 'and send to it with --contact-id if it is the one to reach. A LinkedIn URL is matched by its lowercased slug, and\n' + + `the CLI stores it by that slug when it imports the contact. contact_id is the contact the ${what} went to, and\n` + + 'contact_created says whether this command created them.\n' + + (by === 'email' ? '' : LINKEDIN_URL_NEEDED) + STDIN_PAIR('message'); // One send's example with the person and the text both on stdin. const piped_send = (command: string, contact: string, message: string, flags: string): string=> @@ -301,7 +300,7 @@ add_contact_options(contact_command.command('send-email'), true) .addHelpText('after', help( [`echo '{"subject":"Quick question","body":"<p>Hi Ann, does Tuesday work?</p>"}' | ${P} contact send-email --contact-id 456 --email-account-id 12 --message -`, piped_send('send-email', ANN_EMAIL, '{"subject":"Quick question","body":"<p>Hi Ann</p>"}', '--email-account-id 12')], - ['contact.not_found', ...IMPORT_CODES, 'email_account.not_found', 'contact.blacklisted'], true, + ['contact.not_found', ...IMPORT_CODES, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted'], true, 'Result: {"status":"sent","contact_id","contact_created","message_id","sent_at","reply_status"}: sent means Reply\n' + 'accepted the email, and reply_status is Reply\'s own word for it (new or sent). message_id is Reply\'s messageId,\n' + 'null when it gives none. Reply\'s answer carries no time, so sent_at is always null; the CLI adds none of its own.\n' @@ -316,8 +315,8 @@ add_contact_options(contact_command.command('send-email'), true) // The four LinkedIn sends share their flags, their first codes and the shape of their result. const LINKEDIN_SEND_CODES = [ - 'contact.not_found', ...IMPORT_CODES, 'contact.channel_conflict', 'contact.no_linkedin_profile', 'linkedin.account_not_found', 'linkedin.feature_disabled', - 'linkedin.account_inactive', 'linkedin.invalid_cookie', + 'contact.not_found', ...IMPORT_CODES, 'contact.already_held', 'contact.no_linkedin_profile', 'linkedin.account_not_found', + 'linkedin.feature_disabled', 'linkedin.account_inactive', 'linkedin.invalid_cookie', ]; const LINKEDIN_SENT = '"contact_id","contact_created","activity_id","sent_at"}:\n' + 'activity_id and sent_at are Reply\'s linkedInActivityId and sentAtUtc as Reply gives them, each null when it gives\n' diff --git a/src/operations/contacts.ts b/src/operations/contacts.ts index f892f9b..06947b5 100644 --- a/src/operations/contacts.ts +++ b/src/operations/contacts.ts @@ -199,65 +199,13 @@ const ensure_contact = async(s: Op_session, ref: Contact_ref): Promise<Ensured>= // The contact a command acts on: the id given; else the one Reply holds under the address the command // reaches the person by (by default the one a lookup uses); else the person imported as an add imports // them. Looking first means that a person Reply already holds needs no first name. -const find_or_import = async(s: Op_session, ref: Contact_ref, by?: Channel): Promise<Ensured & {imported: boolean}>=>{ +const find_or_import = async(s: Op_session, ref: Contact_ref, by?: Channel): Promise<Ensured>=>{ if (ref.kind === 'id') { - return {id: ref.id, created: false, imported: false}; + return {id: ref.id, created: false}; } const found = await find_contact_by_address(s, ref.person, by); - return found === null ? {...await import_contact(s, ref.person), imported: true} : {id: found, created: false, imported: false}; -}; - -// A profile compared as the lookup compares it, except that the scheme and a leading www do not count here: -// a contact stored as linkedin.com/in/x is the profile www.linkedin.com/in/x names. -const profile_of = (text: string): string | null=>{ - const key = linkedin_key(text) ?? linkedin_key(`https://${text.trim()}`); - return key === null ? null : key.replace(/^https?:\/\/(www\.)?/i, ''); -}; - -// An import that matched a contact fills only its empty fields, so the contact it returns may hold another -// LinkedIn profile than the one asked for, or none. A send to it must not reach a profile other than the one -// the caller named, an address is never changed, and a profile is given only where there is none: so the -// contact is read, a different profile refuses the send, and an empty one is given the profile, and only that -// field, before the send. A contact that can't be read is refused too. -const hold_profile = async(s: Op_session, contact_id: number, linkedin_url: string): Promise<void>=>{ - const a = await call_reply(s, 'GET', `/v3/contacts/${contact_id}`, 'read'); - if (a.status === 404) - { - throw contact_not_found(contact_id, a); - } - if (a.status !== 200) - { - throw refusal(a, 'read'); - } - const held = expect_object(a, 'read').linkedInUrl; - if (held !== undefined && held !== null && typeof held !== 'string') - { - throw unreadable(a, 'read'); - } - if (typeof held === 'string' && held.trim() !== '') - { - const wanted = profile_of(linkedin_url); - if (wanted !== null && profile_of(held) === wanted) - { - return; - } - throw new Operation_error('contact.channel_conflict', - 'A contact Reply already holds carries another LinkedIn profile than the one given, so nothing was sent and its LinkedIn profile was not changed.', { - status: 200, - hint: 'Send to that contact with --contact-id if it is the same person, or change its linkedin_url with contact update ' - + 'first; or, if it is a different person, give the LinkedIn URL alone.', - }); - } - const set = await call_reply(s, 'PATCH', `/v3/contacts/${contact_id}`, 'write', {linkedInUrl: linkedin_key(linkedin_url) ?? linkedin_url}); - if (set.status === 404) - { - throw contact_not_found(contact_id, set); - } - if (set.status !== 200 && set.status !== 204) - { - throw refusal(set, 'write'); - } + return found === null ? import_contact(s, ref.person) : {id: found, created: false}; }; const find_contact = async(s: Op_session, ref: Contact_ref): Promise<number | null>=> @@ -284,5 +232,5 @@ const read_opted_out = async(s: Op_session, contact_id: number): Promise<boolean return body.isOptedOut; }; -export {ensure_contact, find_or_import, hold_profile, import_contact, find_contact, find_contact_by_address, read_opted_out, contact_not_found}; +export {ensure_contact, find_or_import, import_contact, find_contact, find_contact_by_address, read_opted_out, contact_not_found}; export type {Ensured, Channel}; diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index 20376bf..64337bb 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -4,7 +4,7 @@ import {parse_retry_after} from '../utils/client'; import {call_reply, expect_object, refusal, reply_code_of, detail_of, open_session, type Answer} from './call'; import {parse_id, LARGEST_SAFE_ID, type Op_globals} from './options'; import {read_contact_input, type Contact_flags, type Contact_ref} from './contact-input'; -import {contact_not_found, find_or_import, hold_profile, type Channel, type Ensured} from './contacts'; +import {contact_not_found, find_or_import, type Channel, type Ensured} from './contacts'; import {read_stdin_object, stdin_inputs} from './stdin-input'; import {print_result, with_ids} from './result'; import type {Cli_context} from '../context'; @@ -196,6 +196,19 @@ const require_address = (name: Direct_send_name, contact: Contact_ref, by: Chann } }; +// INTERIM (API gap): Reply does not refuse a direct send to a contact it holds as opted out, so the only guard on that +// opt-out is a caller that reads the contact before it sends. +// Needed: a direct send that refuses a contact Reply holds as opted out. +// Workaround: a send given a person's fields acts only on a contact it created. One Reply already holds, found by the +// lookup or matched by the import, is refused before anything is sent, and named, for the caller to read and then send +// to by its id. +const already_held = (contact_id: number): Operation_error=> + new Operation_error('contact.already_held', + `Reply already holds contact ${contact_id} under what was given, so nothing was sent: a send given a person's fields goes only to a contact it creates.`, { + status: 200, + hint: `Read it first with ${PROGRAM_NAME} contact get ${contact_id}; if it is the one to reach, send to it with --contact-id ${contact_id}.`, + }); + const handle_direct_send = async( name: Direct_send_name, opts: Direct_send_opts, ctx: Cli_context, g: Op_globals, read_stdin?: () => string, ): Promise<void>=>{ @@ -216,13 +229,13 @@ const handle_direct_send = async( const s = await open_session(ctx, g); let sending = false; try { - // The contact first, found or imported as an add would; the send goes to the one this names. + // The contact first, found or imported as an add would; a person given by their fields is sent to only when + // this import created them. const ensured = await find_or_import(s, contact, by); ids.contact_id = ensured.id; - // A contact the import matched may hold another profile, or none: it carries the one asked for before a LinkedIn send. - if (!by_email && contact.kind === 'person' && ensured.imported && !ensured.created && contact.person.linkedin_url !== undefined) + if (contact.kind === 'person' && !ensured.created) { - await hold_profile(s, ensured.id, contact.person.linkedin_url); + throw already_held(ensured.id); } sending = true; const a = await call_reply(s, 'POST', `/v3/contacts/${ensured.id}/${send.path}`, 'write', send.body(account_id, text)); @@ -244,8 +257,8 @@ const handle_direct_send = async( { e.hint = sending ? `The ${send.what} may have been sent; running the command again may send it twice.` - : `Nothing was sent: the outcome of a step before the ${send.what} is unknown, so the ${send.what} was never made. ` - + 'Running the command again is safe.'; + : `Nothing was sent: the outcome of the contact's import is unknown, so the ${send.what} was never made. ` + + 'Running the command again is safe: if the import did create the contact, it answers contact.already_held with its id.'; } throw with_ids(e, ids); } From d5a2b82a83118dab3c0bcb591e6e294349fbcc70 Mon Sep 17 00:00:00 2001 From: Artem Kosolap <art@reply.io> Date: Wed, 21 Oct 2026 20:44:35 -0700 Subject: [PATCH 09/11] docs: the README says a send given a person's fields sends only to a contact it creates The paragraph on the LinkedIn profile check gives way to the rule: a direct send given a person's fields refuses a contact Reply already holds with contact.already_held, naming it, so the caller reads it and sends with --contact-id. The note on exit 3 names the import as the only step before a send whose answer can be lost. --- README.md | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 76464dd..c938b29 100644 --- a/README.md +++ b/README.md @@ -223,21 +223,22 @@ The two `add-contact` commands always import a contact given by email, and Reply without a first name, even for a contact it already holds; a contact given only by LinkedIn URL is looked up first and imported only when Reply holds nobody under it. `contact opt-out`, `contact update` and the direct sends look first and import only someone Reply doesn't hold yet, so only then -is a first name needed; `sequence remove-contact` never imports. Each of these except `sequence remove-contact` -answers the `contact_id` it acted on and `contact_created`, so a caller can keep the id. A send looks the person +is a first name needed, and a direct send sends only to a contact it created (below); `sequence +remove-contact` never imports. Each of these except `sequence remove-contact` answers the +`contact_id` it acted on and `contact_created`, so a caller can keep the id. A send looks the person up by the address it reaches them at: the email for `contact send-email`, the LinkedIn URL for the LinkedIn sends. Otherwise a contact is looked up by its email, and one with only a LinkedIn URL by that; an import is matched by the email when there is one. -A LinkedIn send never reaches a profile other than the one it was given. A contact found by the LinkedIn URL is -sent to as it is. When the person is given with an email and nobody is found by the LinkedIn URL, the import is -matched by the email and may return a contact Reply already holds, so that contact is read before the send: -if it holds another LinkedIn profile, nothing is sent and its LinkedIn profile is not changed, and the answer is `contact.channel_conflict` -(exit 1, the contact in `ids.contact_id`; send to it with `--contact-id` if it is the same person, or change its -`linkedin_url` with `contact update` first); if it holds none, only the given profile is set on it before the -send, never an email or any other field; if it holds the same profile (compared ignoring the scheme and `www`), -the send goes ahead. A contact the import created is not read. A LinkedIn send needs a `linkedin_url` in -`--contact` (or `--contact-id`): `--email` alone is refused. The lookup is Reply's exact +A direct send given a person's fields sends only to a contact it creates. When its lookup finds a +contact, or its import matches one Reply already holds (by the email, say, or a teammate's), nothing +is sent: the answer is `contact.already_held` (exit 1) with that contact's id in `ids.contact_id`. +Read that contact first with `reply contact get`, its opt-out included, and send to it with +`--contact-id` if it is the one to reach. Reply does not refuse a direct send to a contact it holds +as opted out, so a send never reaches a contact Reply already held without that read. A LinkedIn +send needs a `linkedin_url` in `--contact` (or `--contact-id`): `--email` alone is refused. + +The lookup is Reply's exact one: an email matches ignoring case, and a LinkedIn URL is matched by its lowercased slug — on linkedin.com the path's case does not count, nor the scheme's or host's, a default port, one trailing slash or a fragment, while `www` and the query do. Reply is asked for a LinkedIn URL in that form @@ -301,8 +302,9 @@ variables, and refuses one it cannot fill with `linkedin.missing_variables`. `inbox reply`, `sequence create` and the five direct sends are the work commands that are not safe to re-run. On exit 3 (outcome unknown) a reply or a send may already have gone, and running it again may -send it twice, unless the hint says nothing was sent: a send whose contact's import, read or profile update lost its -answer was never made, and its hint says so. +send it twice, unless the hint says nothing was sent: a send whose contact's import lost its answer +was never made, and its hint says so; run again, it answers `contact.already_held` if that import did +create the contact. For `inbox reply`, read the thread with `reply inbox get` before trying again. For `sequence create`, Reply allows two sequences of one name, so after exit 3 look the name up with `sequence list --name -` first. Every other work command can simply be run again; a `contact delete` From 544314fa086fe49779f4499fe15d3089867fd51b Mon Sep 17 00:00:00 2001 From: Artem Kosolap <art@reply.io> Date: Wed, 21 Oct 2026 20:56:03 -0700 Subject: [PATCH 10/11] fix: a send given a person's fields looks the person up by every address it was given A send looked the person up only by the address it reaches them at, so a contact Reply held under the other address (the LinkedIn URL for an email send, the email for a LinkedIn send) was neither read nor refused, and a second contact was created beside it. The lookups now run in a fixed order, the address the send reaches them at first and the other when it was given. A hit under either is refused with contact.already_held naming the first contact found, and nothing is imported or sent. The help of the five sends and the README say so, and say that contact_created is kept on a send for consistency with the add commands and is always true when something was sent. --- README.md | 11 ++-- src/__tests__/operations/commands.test.ts | 7 ++- src/__tests__/operations/direct-send.test.ts | 60 +++++++++++++------- src/operations/commands.ts | 9 +-- src/operations/direct-send.ts | 35 ++++++++++-- 5 files changed, 87 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index c938b29..8209e2e 100644 --- a/README.md +++ b/README.md @@ -226,17 +226,18 @@ update` and the direct sends look first and import only someone Reply doesn't ho is a first name needed, and a direct send sends only to a contact it created (below); `sequence remove-contact` never imports. Each of these except `sequence remove-contact` answers the `contact_id` it acted on and `contact_created`, so a caller can keep the id. A send looks the person -up by the address it reaches them at: the email for `contact send-email`, the LinkedIn URL for the -LinkedIn sends. Otherwise a contact is looked up by its email, and one with only a LinkedIn URL by +up by every address it was given, the one it reaches them at first (the email for `contact send-email`, +the LinkedIn URL for the LinkedIn sends), then the other when there is one. Otherwise a contact is looked up by its email, and one with only a LinkedIn URL by that; an import is matched by the email when there is one. -A direct send given a person's fields sends only to a contact it creates. When its lookup finds a -contact, or its import matches one Reply already holds (by the email, say, or a teammate's), nothing +A direct send given a person's fields sends only to a contact it creates. When a lookup by any address +it was given finds a contact, or its import matches one Reply already holds (by the email, say, or a teammate's), nothing is sent: the answer is `contact.already_held` (exit 1) with that contact's id in `ids.contact_id`. Read that contact first with `reply contact get`, its opt-out included, and send to it with `--contact-id` if it is the one to reach. Reply does not refuse a direct send to a contact it holds as opted out, so a send never reaches a contact Reply already held without that read. A LinkedIn -send needs a `linkedin_url` in `--contact` (or `--contact-id`): `--email` alone is refused. +send needs a `linkedin_url` in `--contact` (or `--contact-id`): `--email` alone is refused. On a send, +`contact_created` is kept for consistency with the add commands and is always `true` when something was sent. The lookup is Reply's exact one: an email matches ignoring case, and a LinkedIn URL is matched by its lowercased slug — on diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index df60954..c6f5426 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -83,7 +83,8 @@ describe('operations/commands', ()=>{ const flat = text.replace(/\s+/g, ' '); const input = name === 'update' ? 'fields' : 'message'; expect(flat, text).toContain('imported only when Reply holds nobody under'); - expect(flat, text).toContain('contact_created says whether this command created'); + expect(flat, text).toContain(name === 'update' ? 'contact_created says whether this command created' + : 'contact_created is kept for consistency with the add commands: on a send it is always true when something was sent'); expect(flat, text).toContain(`With --contact - and --${input} - both, stdin holds one object: {"contact": {…}, "${input}": {…}}`); expect(text, text).toContain(`--contact - `); } @@ -207,7 +208,9 @@ describe('operations/commands', ()=>{ expect(text, text).not.toContain('re-running is safe'); // A send given a person's fields sends only to a contact it creates, and names one Reply already holds. expect(flat, text).toContain('A send given a person\'s fields sends only to a contact it creates'); - expect(flat, text).toContain('the lookup finds a contact, or the import matches one Reply already holds, nothing is sent'); + expect(flat, text).toContain('a lookup finds a contact, or the import matches one Reply already holds, nothing is sent'); + expect(flat, text).toContain(`then by its ${name === 'send-email' ? 'LinkedIn URL' : 'email'} when it was given one`); + expect(flat, text).toContain('imported only when Reply holds nobody under any address given'); expect(flat, text).toContain('the answer is contact.already_held (exit 1) with that contact\'s id in ids.contact_id'); expect(flat, text).toContain('send to it with --contact-id'); expect(flat.includes('--email alone is refused (usage.contact)'), text).toBe(name !== 'send-email'); diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index 23b9a9e..9f6272a 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -406,30 +406,30 @@ describe('a direct send to a person given by their fields', ()=>{ } }); - it('a send looks the person up by the address it reaches them at, whatever else is given, and the import matches by ' + it('a send looks the person up by every address it was given, the one it reaches them at first, and the import matches by ' + 'the email as an add\'s does', async()=>{ const both = {...MARTA, linkedin_url: PROFILE}; - answer(nobody(), imported(457), activity('message')); + answer(nobody(), nobody(), imported(457), activity('message')); expect(await run_by_fields('linkedin-message', {contact: both, message: {body: TEXT}}, by_fields(LINKEDIN_OPTS))) .toMatchObject({contact_id: 457, contact_created: true}); - expect(lines()).toEqual([PROFILE_LOOKUP, IMPORT, 'POST https://api/v3/contacts/457/send-direct-linkedin-message']); - expect(sent()[1].body).toStrictEqual({items: [{email: 'marta@example.com', linkedInUrl: PROFILE, firstName: 'Marta', lastName: 'Example'}]}); + expect(lines()).toEqual([PROFILE_LOOKUP, EMAIL_LOOKUP, IMPORT, 'POST https://api/v3/contacts/457/send-direct-linkedin-message']); + expect(sent()[2].body).toStrictEqual({items: [{email: 'marta@example.com', linkedInUrl: PROFILE, firstName: 'Marta', lastName: 'Example'}]}); mock_fetch.mockReset(); - answer(nobody(), imported(457), json({status: 'sent'})); + answer(nobody(), nobody(), imported(457), json({status: 'sent'})); await run_by_fields('send-email', {contact: both, message: {subject: SUBJECT, body: BODY}}, by_fields(EMAIL_OPTS)); - expect(lines()).toEqual([EMAIL_LOOKUP, IMPORT, 'POST https://api/v3/contacts/457/send-direct-email']); + expect(lines()).toEqual([EMAIL_LOOKUP, PROFILE_LOOKUP, IMPORT, 'POST https://api/v3/contacts/457/send-direct-email']); }); // Reply does not refuse a direct send to a contact it holds as opted out, so a send given a person's fields acts only // on a contact it created: one Reply already holds, found by the lookup or matched by the import, is refused before // anything is sent and named, for the caller to read before sending to it by its id. describe('a send given a person\'s fields acts only on a contact it created', ()=>{ - type Case = {name: Direct_send_name; message: unknown; opts: Direct_send_opts; lookup: string; path: string; holder: object; done: () => Response}; + type Case = {name: Direct_send_name; message: unknown; opts: Direct_send_opts; lookup: string; other: string; path: string; holder: object; other_holder: object; done: () => Response}; const FIVE: Case[] = [ - {name: 'send-email', message: {subject: SUBJECT, body: BODY}, opts: EMAIL_OPTS, lookup: EMAIL_LOOKUP, path: 'send-direct-email', - holder: {email: 'Marta@Example.com'}, done: ()=>json({status: 'sent'})}, - ...LINKEDIN_SENDS.map(([name, message, path, action]): Case=>({name, message, opts: LINKEDIN_OPTS, lookup: PROFILE_LOOKUP, path, - holder: {linkedInUrl: `${PROFILE}/`}, done: ()=>activity(action)})), + {name: 'send-email', message: {subject: SUBJECT, body: BODY}, opts: EMAIL_OPTS, lookup: EMAIL_LOOKUP, other: PROFILE_LOOKUP, + path: 'send-direct-email', holder: {email: 'Marta@Example.com'}, other_holder: {linkedInUrl: `${PROFILE}/`}, done: ()=>json({status: 'sent'})}, + ...LINKEDIN_SENDS.map(([name, message, path, action]): Case=>({name, message, opts: LINKEDIN_OPTS, lookup: PROFILE_LOOKUP, other: EMAIL_LOOKUP, + path, holder: {linkedInUrl: `${PROFILE}/`}, other_holder: {email: 'Marta@Example.com'}, done: ()=>activity(action)})), ]; const PERSON = {...MARTA, linkedin_url: PROFILE}; const refused = (e: unknown, label: string)=>{ @@ -459,9 +459,9 @@ describe('a direct send to a person given by their fields', ()=>{ for (const status of ['updated', 'skipped']) { mock_fetch.mockReset(); - answer(nobody(), imported(456, status), c.done()); + answer(nobody(), nobody(), imported(456, status), c.done()); refused(await fail_by_fields(c.name, {contact: PERSON, message: c.message}, by_fields(c.opts)), `${c.name} ${status}`); - expect(lines(), `${c.name} ${status}`).toEqual([c.lookup, IMPORT]); + expect(lines(), `${c.name} ${status}`).toEqual([c.lookup, c.other, IMPORT]); } } }); @@ -470,10 +470,32 @@ describe('a direct send to a person given by their fields', ()=>{ for (const c of FIVE) { mock_fetch.mockReset(); - answer(nobody(), imported(457), c.done()); + answer(nobody(), nobody(), imported(457), c.done()); expect(await run_by_fields(c.name, {contact: PERSON, message: c.message}, by_fields(c.opts)), c.name) .toMatchObject({status: 'sent', contact_id: 457, contact_created: true}); - expect(lines(), c.name).toEqual([c.lookup, IMPORT, `POST https://api/v3/contacts/457/${c.path}`]); + expect(lines(), c.name).toEqual([c.lookup, c.other, IMPORT, `POST https://api/v3/contacts/457/${c.path}`]); + } + }); + + it('refuses a person held only under the other address it was given: the lookup by the address it reaches them at ' + + 'finds nobody, the one by the other finds the contact, and nothing is imported or sent', async()=>{ + for (const c of FIVE) + { + mock_fetch.mockReset(); + answer(nobody(), held({id: 456, ...c.other_holder}), c.done()); + refused(await fail_by_fields(c.name, {contact: PERSON, message: c.message}, by_fields(c.opts)), c.name); + expect(lines(), c.name).toEqual([c.lookup, c.other]); + } + }); + + it('names the first contact found when two are held, one under each address: the address it reaches them at is asked ' + + 'first, and the second is never asked', async()=>{ + for (const c of FIVE) + { + mock_fetch.mockReset(); + answer(held({id: 456, ...c.holder}), held({id: 789, ...c.other_holder}), c.done()); + refused(await fail_by_fields(c.name, {contact: PERSON, message: c.message}, by_fields(c.opts)), c.name); + expect(lines(), c.name).toEqual([c.lookup]); } }); }); @@ -498,12 +520,12 @@ describe('a direct send to a person given by their fields', ()=>{ const two = json({items: [{id: 1, email: 'marta@example.com'}, {id: 2, email: 'marta@example.com'}], hasMore: false}); const cases: [Response[], string, number][] = [ [[two], 'contact.not_unique', 1], - [[nobody(), json({status: 400, errors: [{pointer: '/items/0/email', detail: '\'marta@example\' is not valid'}]}, 400)], + [[nobody(), nobody(), json({status: 400, errors: [{pointer: '/items/0/email', detail: '\'marta@example\' is not valid'}]}, 400)], 'contact.invalid_email', 1], - [[nobody(), json({status: 400, errors: [{pointer: '/items/0/linkedInUrl', detail: 'not valid'}]}, 400)], + [[nobody(), nobody(), json({status: 400, errors: [{pointer: '/items/0/linkedInUrl', detail: 'not valid'}]}, 400)], 'contact.invalid_linkedin_url', 1], - [[nobody(), json({code: 'contact.limitExceeded', detail: 'Contact limit reached.'}, 400)], 'account.contact_limit_reached', 1], - [[nobody(), json({items: [{id: null, status: 'failed', error: 'Invalid data'}]})], 'reply.refused', 1], + [[nobody(), nobody(), json({code: 'contact.limitExceeded', detail: 'Contact limit reached.'}, 400)], 'account.contact_limit_reached', 1], + [[nobody(), nobody(), json({items: [{id: null, status: 'failed', error: 'Invalid data'}]})], 'reply.refused', 1], ]; for (const [answers, code, exit_code] of cases) { diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 2e13a00..58ec3f7 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -274,17 +274,18 @@ const SEND_TWICE = (what: string): string=> const LINKEDIN_URL_NEEDED = 'A LinkedIn send needs the contact\'s linkedin_url in --contact (or --contact-id); --email alone is refused ' + '(usage.contact).\n'; -// How a send names its contact: looked up by the address it reaches them at, else imported as an add imports one; and +// How a send names its contact: looked up by every address it was given, else imported as an add imports one; and // it sends only to a contact it created, naming one Reply already holds instead. const SENT_TO = (by: 'email' | 'linkedin', what: string): string=>CONTACT_FORMS + 'A send given a person\'s fields sends only to a contact it creates. The contact is looked up by\n' - + `${by === 'email' ? 'its email' : 'its LinkedIn URL'}, where the ${what} goes, and imported only when Reply holds nobody under it, as the add\n` - + 'commands import one (matched by its email when it has one), so Reply needs a first name. When the lookup finds a\n' + + `${by === 'email' ? 'its email' : 'its LinkedIn URL'}, where the ${what} goes, then by its ${by === 'email' ? 'LinkedIn URL' : 'email'} when it was given one, and imported only when\n` + + 'Reply holds nobody under any address given, as the add commands import one (matched by its email when it has\n' + + 'one), so Reply needs a first name. When a lookup finds a\n' + 'contact, or the import matches one Reply already holds, nothing is sent: the answer is contact.already_held (exit 1)\n' + 'with that contact\'s id in ids.contact_id. Read that contact first (contact get shows it, its opt-out included),\n' + 'and send to it with --contact-id if it is the one to reach. A LinkedIn URL is matched by its lowercased slug, and\n' + `the CLI stores it by that slug when it imports the contact. contact_id is the contact the ${what} went to, and\n` - + 'contact_created says whether this command created them.\n' + + 'contact_created is kept for consistency with the add commands: on a send it is always true when something was sent.\n' + (by === 'email' ? '' : LINKEDIN_URL_NEEDED) + STDIN_PAIR('message'); // One send's example with the person and the text both on stdin. diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index 64337bb..34f4de8 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -4,7 +4,7 @@ import {parse_retry_after} from '../utils/client'; import {call_reply, expect_object, refusal, reply_code_of, detail_of, open_session, type Answer} from './call'; import {parse_id, LARGEST_SAFE_ID, type Op_globals} from './options'; import {read_contact_input, type Contact_flags, type Contact_ref} from './contact-input'; -import {contact_not_found, find_or_import, type Channel, type Ensured} from './contacts'; +import {contact_not_found, find_contact_by_address, find_or_import, import_contact, type Channel, type Ensured} from './contacts'; import {read_stdin_object, stdin_inputs} from './stdin-input'; import {print_result, with_ids} from './result'; import type {Cli_context} from '../context'; @@ -231,11 +231,36 @@ const handle_direct_send = async( try { // The contact first, found or imported as an add would; a person given by their fields is sent to only when // this import created them. - const ensured = await find_or_import(s, contact, by); - ids.contact_id = ensured.id; - if (contact.kind === 'person' && !ensured.created) + let ensured: Ensured; + if (contact.kind === 'person') { - throw already_held(ensured.id); + // A person is looked up by every address given, the one the send reaches them at first: a hit under any of + // them is a contact Reply holds, and the first one found is the one named. + const other: Channel = by === 'email' ? 'linkedin' : 'email'; + for (const channel of [by, other]) + { + if ((channel === 'email' ? contact.person.email : contact.person.linkedin_url) === undefined) + { + continue; + } + const held = await find_contact_by_address(s, contact.person, channel); + if (held !== null) + { + ids.contact_id = held; + throw already_held(held); + } + } + ensured = await import_contact(s, contact.person); + ids.contact_id = ensured.id; + if (!ensured.created) + { + throw already_held(ensured.id); + } + } + else + { + ensured = await find_or_import(s, contact, by); + ids.contact_id = ensured.id; } sending = true; const a = await call_reply(s, 'POST', `/v3/contacts/${ensured.id}/${send.path}`, 'write', send.body(account_id, text)); From cabd40a99d8ba2dea96d1f5405e98cf87fd0e3e3 Mon Sep 17 00:00:00 2001 From: Artem Kosolap <art@reply.io> Date: Wed, 21 Oct 2026 21:01:36 -0700 Subject: [PATCH 11/11] fix: say what contact_created means on a send, and drop find_or_import's unused channel contact_created is always true when a send was given a person's fields and always false with --contact-id; in both cases a successful answer says the send was made. The help, the README and the test that pins the sentence now say so. find_or_import no longer takes a channel, since the sends look a person up themselves. --- README.md | 8 +++++--- src/__tests__/operations/commands.test.ts | 2 +- src/operations/commands.ts | 7 ++++--- src/operations/contacts.ts | 10 +++++----- src/operations/direct-send.ts | 4 ++-- 5 files changed, 17 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 8209e2e..d97f196 100644 --- a/README.md +++ b/README.md @@ -227,8 +227,9 @@ is a first name needed, and a direct send sends only to a contact it created (be remove-contact` never imports. Each of these except `sequence remove-contact` answers the `contact_id` it acted on and `contact_created`, so a caller can keep the id. A send looks the person up by every address it was given, the one it reaches them at first (the email for `contact send-email`, -the LinkedIn URL for the LinkedIn sends), then the other when there is one. Otherwise a contact is looked up by its email, and one with only a LinkedIn URL by -that; an import is matched by the email when there is one. +the LinkedIn URL for the LinkedIn sends), then the other when there is one. Otherwise a contact is +looked up by its email, and one with only a LinkedIn URL by that; an import is matched by the email +when there is one. A direct send given a person's fields sends only to a contact it creates. When a lookup by any address it was given finds a contact, or its import matches one Reply already holds (by the email, say, or a teammate's), nothing @@ -237,7 +238,8 @@ Read that contact first with `reply contact get`, its opt-out included, and send `--contact-id` if it is the one to reach. Reply does not refuse a direct send to a contact it holds as opted out, so a send never reaches a contact Reply already held without that read. A LinkedIn send needs a `linkedin_url` in `--contact` (or `--contact-id`): `--email` alone is refused. On a send, -`contact_created` is kept for consistency with the add commands and is always `true` when something was sent. +`contact_created` is kept for consistency with the add commands: given a person's fields it is always `true`, +and with `--contact-id` it is always `false`; in both cases a successful answer says the send was made. The lookup is Reply's exact one: an email matches ignoring case, and a LinkedIn URL is matched by its lowercased slug — on diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index c6f5426..79610be 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -84,7 +84,7 @@ describe('operations/commands', ()=>{ const input = name === 'update' ? 'fields' : 'message'; expect(flat, text).toContain('imported only when Reply holds nobody under'); expect(flat, text).toContain(name === 'update' ? 'contact_created says whether this command created' - : 'contact_created is kept for consistency with the add commands: on a send it is always true when something was sent'); + : 'contact_created is kept for consistency with the add commands: given a person\'s fields it is always true, and with --contact-id it is always false; in both cases a successful answer says the send was made'); expect(flat, text).toContain(`With --contact - and --${input} - both, stdin holds one object: {"contact": {…}, "${input}": {…}}`); expect(text, text).toContain(`--contact - `); } diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 58ec3f7..665d30e 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -280,12 +280,13 @@ const SENT_TO = (by: 'email' | 'linkedin', what: string): string=>CONTACT_FORMS + 'A send given a person\'s fields sends only to a contact it creates. The contact is looked up by\n' + `${by === 'email' ? 'its email' : 'its LinkedIn URL'}, where the ${what} goes, then by its ${by === 'email' ? 'LinkedIn URL' : 'email'} when it was given one, and imported only when\n` + 'Reply holds nobody under any address given, as the add commands import one (matched by its email when it has\n' - + 'one), so Reply needs a first name. When a lookup finds a\n' - + 'contact, or the import matches one Reply already holds, nothing is sent: the answer is contact.already_held (exit 1)\n' + + 'one), so Reply needs a first name. When a lookup finds a contact,\n' + + 'or the import matches one Reply already holds, nothing is sent: the answer is contact.already_held (exit 1)\n' + 'with that contact\'s id in ids.contact_id. Read that contact first (contact get shows it, its opt-out included),\n' + 'and send to it with --contact-id if it is the one to reach. A LinkedIn URL is matched by its lowercased slug, and\n' + `the CLI stores it by that slug when it imports the contact. contact_id is the contact the ${what} went to, and\n` - + 'contact_created is kept for consistency with the add commands: on a send it is always true when something was sent.\n' + + 'contact_created is kept for consistency with the add commands: given a person\'s fields it is always true, and with\n' + + '--contact-id it is always false; in both cases a successful answer says the send was made.\n' + (by === 'email' ? '' : LINKEDIN_URL_NEEDED) + STDIN_PAIR('message'); // One send's example with the person and the text both on stdin. diff --git a/src/operations/contacts.ts b/src/operations/contacts.ts index 06947b5..181d4cd 100644 --- a/src/operations/contacts.ts +++ b/src/operations/contacts.ts @@ -196,15 +196,15 @@ const ensure_contact = async(s: Op_session, ref: Contact_ref): Promise<Ensured>= return import_contact(s, ref.person); }; -// The contact a command acts on: the id given; else the one Reply holds under the address the command -// reaches the person by (by default the one a lookup uses); else the person imported as an add imports -// them. Looking first means that a person Reply already holds needs no first name. -const find_or_import = async(s: Op_session, ref: Contact_ref, by?: Channel): Promise<Ensured>=>{ +// The contact a command acts on: the id given; else the one Reply holds under the address a lookup uses; +// else the person imported as an add imports them. Looking first means that a person Reply already holds needs +// no first name. +const find_or_import = async(s: Op_session, ref: Contact_ref): Promise<Ensured>=>{ if (ref.kind === 'id') { return {id: ref.id, created: false}; } - const found = await find_contact_by_address(s, ref.person, by); + const found = await find_contact_by_address(s, ref.person); return found === null ? import_contact(s, ref.person) : {id: found, created: false}; }; diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index 34f4de8..19fe209 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -4,7 +4,7 @@ import {parse_retry_after} from '../utils/client'; import {call_reply, expect_object, refusal, reply_code_of, detail_of, open_session, type Answer} from './call'; import {parse_id, LARGEST_SAFE_ID, type Op_globals} from './options'; import {read_contact_input, type Contact_flags, type Contact_ref} from './contact-input'; -import {contact_not_found, find_contact_by_address, find_or_import, import_contact, type Channel, type Ensured} from './contacts'; +import {contact_not_found, find_contact_by_address, import_contact, type Channel, type Ensured} from './contacts'; import {read_stdin_object, stdin_inputs} from './stdin-input'; import {print_result, with_ids} from './result'; import type {Cli_context} from '../context'; @@ -259,7 +259,7 @@ const handle_direct_send = async( } else { - ensured = await find_or_import(s, contact, by); + ensured = {id: contact.id, created: false}; ids.contact_id = ensured.id; } sending = true;