@yaks/phone 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +251 -2
  3. package/_dist/call.d.ts +37 -0
  4. package/_dist/call.d.ts.map +1 -0
  5. package/_dist/effects.d.ts +5 -0
  6. package/_dist/effects.d.ts.map +1 -0
  7. package/_dist/mobile.d.ts +41 -0
  8. package/_dist/mobile.d.ts.map +1 -0
  9. package/_dist/mod.d.ts +27 -0
  10. package/_dist/mod.d.ts.map +1 -0
  11. package/_dist/numbers.d.ts +150 -0
  12. package/_dist/numbers.d.ts.map +1 -0
  13. package/_dist/options.d.ts +21 -0
  14. package/_dist/options.d.ts.map +1 -0
  15. package/_dist/plugin.d.ts +54 -0
  16. package/_dist/plugin.d.ts.map +1 -0
  17. package/_dist/provider.d.ts +72 -0
  18. package/_dist/provider.d.ts.map +1 -0
  19. package/_dist/received.d.ts +24 -0
  20. package/_dist/received.d.ts.map +1 -0
  21. package/_dist/replies.d.ts +18 -0
  22. package/_dist/replies.d.ts.map +1 -0
  23. package/_dist/send.d.ts +16 -0
  24. package/_dist/send.d.ts.map +1 -0
  25. package/_dist/stash.d.ts +19 -0
  26. package/_dist/stash.d.ts.map +1 -0
  27. package/_dist/text.d.ts +102 -0
  28. package/_dist/text.d.ts.map +1 -0
  29. package/_dist/tools.d.ts +3 -0
  30. package/_dist/tools.d.ts.map +1 -0
  31. package/_dist/vocab.d.ts +8 -0
  32. package/_dist/vocab.d.ts.map +1 -0
  33. package/call.js +5 -0
  34. package/call.js.map +1 -0
  35. package/call.ts +53 -0
  36. package/deno.json +1 -0
  37. package/effects.js +30 -0
  38. package/effects.js.map +1 -0
  39. package/effects.ts +35 -0
  40. package/mobile.js +75 -0
  41. package/mobile.js.map +1 -0
  42. package/mobile.ts +72 -0
  43. package/mod.js +28 -0
  44. package/mod.js.map +1 -0
  45. package/mod.ts +78 -0
  46. package/numbers.js +72 -0
  47. package/numbers.js.map +1 -0
  48. package/numbers.ts +259 -0
  49. package/options.js +3 -0
  50. package/options.js.map +1 -0
  51. package/options.ts +23 -0
  52. package/package.json +44 -4
  53. package/plugin.js +155 -0
  54. package/plugin.js.map +1 -0
  55. package/plugin.ts +226 -0
  56. package/provider.js +48 -0
  57. package/provider.js.map +1 -0
  58. package/provider.ts +119 -0
  59. package/received.js +72 -0
  60. package/received.js.map +1 -0
  61. package/received.ts +76 -0
  62. package/recipients.js +58 -0
  63. package/replies.js +23 -0
  64. package/replies.js.map +1 -0
  65. package/replies.ts +38 -0
  66. package/send.js +136 -0
  67. package/send.js.map +1 -0
  68. package/send.ts +131 -0
  69. package/stash.js +26 -0
  70. package/stash.js.map +1 -0
  71. package/stash.ts +41 -0
  72. package/text.js +127 -0
  73. package/text.js.map +1 -0
  74. package/text.ts +192 -0
  75. package/tools.js +62 -0
  76. package/tools.js.map +1 -0
  77. package/tools.ts +55 -0
  78. package/vocab.js +18 -0
  79. package/vocab.js.map +1 -0
  80. package/vocab.json +245 -0
  81. package/vocab.ts +19 -0
package/received.js ADDED
@@ -0,0 +1,72 @@
1
+ // What a box keeps of what its provider posts: a text that arrived becomes a
2
+ // `text` entity, STOP takes back the sender's consent, and a later failure
3
+ // of a text that left bounces it. Pure: it answers bundles from what a read
4
+ // found, and the caller applies them.
5
+ import { derivedEid } from "@yaks/graph/identity";
6
+ import { consentEid, consentRemoved, keyword } from "./text.js";
7
+ /** The eid of a text that arrived, derived from the provider's id for it and
8
+ * the transport it came by, so a webhook posted twice keeps one. */ export let arrivalEid = (id, via)=>derivedEid(via ? `text|${via}|${id}` : `text|${id}`);
9
+ /**
10
+ * The bundles that keep a text that arrived from the people at `people`
11
+ * (everyone here with its number, often one, none when nobody has it): the
12
+ * text itself, which stays as the record of what they said; the removal of
13
+ * their consent when it says STOP; and their consent, in the words they sent,
14
+ * when it says JOIN or START (or YES, from someone who is `stopped`).
15
+ *
16
+ * ```ts
17
+ * import { equal } from '@yaks/testing'
18
+ * import { consentEid, kept } from '@yaks/phone'
19
+ * let stop = { id: 'm1', from: '+12695550142', to: '+12695550100',
20
+ * text: 'STOP', at: '2026-11-04T00:00:00Z', rcs: false, media: [] }
21
+ * equal(kept(stop, ['ana'])[1], { entity: { eid: consentEid('ana') }, sms_consent: null })
22
+ * equal(kept({ ...stop, text: 'Join' }, ['ana'])[1].sms_consent,
23
+ * { person: 'ana', consent: 'Join', at: '2026-11-04T00:00:00Z' })
24
+ * ```
25
+ */ export let kept = (arrival, people, stopped = true)=>{
26
+ let word = keyword(arrival.text, stopped);
27
+ return [
28
+ {
29
+ entity: {
30
+ eid: arrivalEid(arrival.id, arrival.via)
31
+ },
32
+ doc: {
33
+ body: arrival.text
34
+ },
35
+ text: {
36
+ from: arrival.from,
37
+ to: arrival.to,
38
+ at: arrival.at,
39
+ message_id: arrival.id,
40
+ ...arrival.via ? {
41
+ via: arrival.via
42
+ } : {},
43
+ rcs: arrival.rcs
44
+ }
45
+ },
46
+ ...people.flatMap((person)=>word == 'stop' ? consentRemoved(person) : word == 'start' ? [
47
+ {
48
+ entity: {
49
+ eid: consentEid(person)
50
+ },
51
+ sms_consent: {
52
+ person,
53
+ consent: arrival.text.trim(),
54
+ at: arrival.at
55
+ }
56
+ }
57
+ ] : [])
58
+ ];
59
+ };
60
+ /** What a later failure of the text `sent` (the entity with that
61
+ * `text.message_id`) writes onto it: a bounce, or nothing when it arrived. */ export let settled = (outcome, sent)=>outcome.failed ? [
62
+ {
63
+ entity: {
64
+ eid: sent
65
+ },
66
+ bounced: {
67
+ at: new Date().toISOString(),
68
+ reason: outcome.failed.reason
69
+ }
70
+ }
71
+ ] : [];
72
+ //# sourceMappingURL=received.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"received.js","sources":["./received.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,2EAA2E;AAC3E,4EAA4E;AAC5E,sCAAsC;AAGtC,SAAS,UAAU,oCAAy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` entity, STOP takes back the sender's consent, and a later failure
3
+ // of a text that left bounces it. Pure: it answers bundles from what a read
4
+ // found, and the caller applies them.
5
+
6
+ import type { Bundle } from 'jsr:@yaks/graph@0.2.36'
7
+ import { derivedEid } from '@yaks/graph/identity'
8
+ import {
9
+ type Arrival,
10
+ consentEid,
11
+ consentRemoved,
12
+ keyword,
13
+ type Outcome,
14
+ } from './text.js'
15
+
16
+ /** The eid of a text that arrived, derived from the provider's id for it and
17
+ * the transport it came by, so a webhook posted twice keeps one. */
18
+ export let arrivalEid = (id: string, via?: string): string =>
19
+ derivedEid(via ? `text|${via}|${id}` : `text|${id}`)
20
+
21
+ /**
22
+ * The bundles that keep a text that arrived from the people at `people`
23
+ * (everyone here with its number, often one, none when nobody has it): the
24
+ * text itself, which stays as the record of what they said; the removal of
25
+ * their consent when it says STOP; and their consent, in the words they sent,
26
+ * when it says JOIN or START (or YES, from someone who is `stopped`).
27
+ *
28
+ * ```ts
29
+ * import { equal } from '@yaks/testing'
30
+ * import { consentEid, kept } from '@yaks/phone'
31
+ * let stop = { id: 'm1', from: '+12695550142', to: '+12695550100',
32
+ * text: 'STOP', at: '2026-11-04T00:00:00Z', rcs: false, media: [] }
33
+ * equal(kept(stop, ['ana'])[1], { entity: { eid: consentEid('ana') }, sms_consent: null })
34
+ * equal(kept({ ...stop, text: 'Join' }, ['ana'])[1].sms_consent,
35
+ * { person: 'ana', consent: 'Join', at: '2026-11-04T00:00:00Z' })
36
+ * ```
37
+ */
38
+ export let kept = (
39
+ arrival: Arrival,
40
+ people: string[],
41
+ stopped = true,
42
+ ): Bundle[] => {
43
+ let word = keyword(arrival.text, stopped)
44
+ return [
45
+ {
46
+ entity: { eid: arrivalEid(arrival.id, arrival.via) },
47
+ doc: { body: arrival.text },
48
+ text: {
49
+ from: arrival.from,
50
+ to: arrival.to,
51
+ at: arrival.at,
52
+ message_id: arrival.id,
53
+ ...(arrival.via ? { via: arrival.via } : {}),
54
+ rcs: arrival.rcs,
55
+ },
56
+ },
57
+ ...people.flatMap((person): Bundle[] =>
58
+ word == 'stop' ? consentRemoved(person) : word == 'start'
59
+ ? [{
60
+ entity: { eid: consentEid(person) },
61
+ sms_consent: { person, consent: arrival.text.trim(), at: arrival.at },
62
+ }]
63
+ : []
64
+ ),
65
+ ]
66
+ }
67
+
68
+ /** What a later failure of the text `sent` (the entity with that
69
+ * `text.message_id`) writes onto it: a bounce, or nothing when it arrived. */
70
+ export let settled = (outcome: Outcome, sent: string): Bundle[] =>
71
+ outcome.failed
72
+ ? [{
73
+ entity: { eid: sent },
74
+ bounced: { at: new Date().toISOString(), reason: outcome.failed.reason },
75
+ }]
76
+ : []
package/recipients.js ADDED
@@ -0,0 +1,58 @@
1
+ // US numbers as they are commonly pasted, including spaces inside a number.
2
+ // Commas and line breaks always start another entry.
3
+ let gap = '[ \\t\\u00a0.\\-–‑]*'
4
+ let local = `(?:\\([2-9]\\d{2}\\)|[2-9]\\d{2})${gap}[2-9]\\d{2}${gap}\\d{4}`
5
+ let phone = new RegExp(
6
+ `(?:\\+?1${gap})?${local}(?:[ \\t]*(?:x|ext\\.?|extension|#)[ \\t]*\\d+)?(?=$|\\s)`,
7
+ 'iy',
8
+ )
9
+ // A foreign calling code can precede ten digits that look like a US number.
10
+ let foreign = new RegExp(`^\\+(?!1\\s)\\d{1,3}\\s+${local}(?=$|\\s)`)
11
+
12
+ export let OPTED_OUT = 'opted out (texted STOP)'
13
+
14
+ /** Unique E.164 numbers and the entries that could not be parsed. */
15
+ export let parseNumbers = (text) => {
16
+ let numbers = new Set(), invalid = []
17
+ for (let line of text.split(/[,\r\n]+/)) {
18
+ for (let at = 0; at < line.length;) {
19
+ if (/\s/.test(line[at])) {
20
+ at++
21
+ continue
22
+ }
23
+ phone.lastIndex = at
24
+ let match = phone.exec(line)
25
+ if (match) {
26
+ let digits = match[0].split(/[a-z#]/i)[0].replace(/\D/g, '')
27
+ numbers.add(`+1${digits.slice(-10)}`)
28
+ at = phone.lastIndex
29
+ } else {
30
+ let rest = line.slice(at)
31
+ let entry = (foreign.exec(rest) ?? /^\S+/.exec(rest))[0]
32
+ invalid.push(entry)
33
+ at += entry.length
34
+ }
35
+ }
36
+ }
37
+ return { numbers: [...numbers], invalid }
38
+ }
39
+
40
+ /** Match each number to someone with consent at that number. Directory
41
+ * contact details can label a number but cannot authorize a text to it. */
42
+ export let resolveNumbers = (
43
+ { holders, consent, stopped, people, byNumber },
44
+ numbers,
45
+ ) =>
46
+ numbers.map((number) => {
47
+ let person = byNumber.get(number) ?? null
48
+ let to = (holders.get(number) ?? []).find((eid) => {
49
+ let p = people.get(eid)
50
+ return consent.has(eid) && (!p || !p.deceased && p.mobile == number)
51
+ })
52
+ let why = stopped.has(number)
53
+ ? OPTED_OUT
54
+ : !to
55
+ ? 'has not agreed to texts at this number'
56
+ : null
57
+ return { number, person, to: why ? null : to, why }
58
+ })
package/replies.js ADDED
@@ -0,0 +1,23 @@
1
+ // The words a number answers carrier keywords with: its campaign's own,
2
+ // kept as `keyword_replies{start, stop, help}` beside the number, and
3
+ // defaults naming whoever texts from it for any it does not give.
4
+ /**
5
+ * The words a number answers each keyword in: its own (`own`), and for any
6
+ * it lacks, defaults naming `name`, whoever texts from it, with HELP giving
7
+ * `office` to call where there is one. Each names the sender and says how to
8
+ * opt out, as carriers require of these three answers.
9
+ *
10
+ * ```ts
11
+ * import { equal } from '@yaks/testing'
12
+ * import { replies } from '@yaks/phone'
13
+ * let said = replies('Oak Hall', { stop: 'Oak Hall: Unsubscribed.' })
14
+ * equal(said.stop, 'Oak Hall: Unsubscribed.')
15
+ * equal(said.start.startsWith("Oak Hall: You're signed up for texts."), true)
16
+ * equal(replies('Oak Hall', {}, '(269) 555-0100').help.includes('call (269) 555-0100'), true)
17
+ * ```
18
+ */ export let replies = (name, own = {}, office = '')=>({
19
+ start: own.start || `${name}: You're signed up for texts. Msg frequency varies. Msg & data rates may apply. Reply HELP for help, STOP to opt out.`,
20
+ stop: own.stop || `${name}: You are unsubscribed and will get no more texts. Reply START to subscribe again.`,
21
+ help: own.help || `${name}: Reply here to reach us${office ? ` or call ${office}` : ''}. Msg & data rates may apply. Reply STOP to opt out.`
22
+ });
23
+ //# sourceMappingURL=replies.js.map
package/replies.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replies.js","sources":["./replies.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,sEAAsE;AACtE,kEAAkE;AAOlE;;;;;;;;;;;;;;CAcC,GACD,OAAO,IAAI,UAAU,CACnB,MACA,MAAe,CAAC,CAAC,EACjB,SAAS,EAAE,GACiB,CAAC;IAC7B,OAAO,IAAI,KAAK,IACd,GAAG,KAAK,qHAAqH,CAAC;IAChI,MAAM,IAAI,IAAI,IACZ,GAAG,KAAK,kFAAkF,CAAC;IAC7F,MAAM,IAAI,IAAI,IACZ,GAAG,KAAK,wBAAwB,EAC9B,SAAS,CAAC,SAAS,EAAE,QAAQ,GAAG,GACjC,oDAAoD,CAAC;EAC1D,CAAC,EAAC"}
package/replies.ts ADDED
@@ -0,0 +1,38 @@
1
+ // The words a number answers carrier keywords with: its campaign's own,
2
+ // kept as `keyword_replies{start, stop, help}` beside the number, and
3
+ // defaults naming whoever texts from it for any it does not give.
4
+
5
+ import type { Keyword } from './text.ts'
6
+
7
+ /** A number's own words for each keyword, as `keyword_replies` keeps them. */
8
+ export type Replies = Partial<Record<Keyword, string>>
9
+
10
+ /**
11
+ * The words a number answers each keyword in: its own (`own`), and for any
12
+ * it lacks, defaults naming `name`, whoever texts from it, with HELP giving
13
+ * `office` to call where there is one. Each names the sender and says how to
14
+ * opt out, as carriers require of these three answers.
15
+ *
16
+ * ```ts
17
+ * import { equal } from '@yaks/testing'
18
+ * import { replies } from '@yaks/phone'
19
+ * let said = replies('Oak Hall', { stop: 'Oak Hall: Unsubscribed.' })
20
+ * equal(said.stop, 'Oak Hall: Unsubscribed.')
21
+ * equal(said.start.startsWith("Oak Hall: You're signed up for texts."), true)
22
+ * equal(replies('Oak Hall', {}, '(269) 555-0100').help.includes('call (269) 555-0100'), true)
23
+ * ```
24
+ */
25
+ export let replies = (
26
+ name: string,
27
+ own: Replies = {},
28
+ office = '',
29
+ ): Record<Keyword, string> => ({
30
+ start: own.start ||
31
+ `${name}: You're signed up for texts. Msg frequency varies. Msg & data rates may apply. Reply HELP for help, STOP to opt out.`,
32
+ stop: own.stop ||
33
+ `${name}: You are unsubscribed and will get no more texts. Reply START to subscribe again.`,
34
+ help: own.help ||
35
+ `${name}: Reply here to reach us${
36
+ office ? ` or call ${office}` : ''
37
+ }. Msg & data rates may apply. Reply STOP to opt out.`,
38
+ })
package/send.js ADDED
@@ -0,0 +1,136 @@
1
+ // Sending a text kept in the graph: an entity wearing `text` and @yaks/mail's
2
+ // `deliver{to}` asks to be sent to the `phone{number}` of `deliver.to`. The
3
+ // effect runs after the write commits and writes the outcome back as
4
+ // `delivered` or `bounced`, the words a letter's outcome uses.
5
+ //
6
+ // Sending is at most once, as a letter's is: `deliver.tried` is claimed
7
+ // before the text reaches the sender, so a crash between the two leaves a
8
+ // text that is never handed over again. A sender's `Unsent` knows the text
9
+ // never left: the claim is given back and the run fails to be tried again.
10
+ import { Stale } from "@yaks/graph/errors";
11
+ import { token } from "@yaks/graph/sha256";
12
+ import { line } from "@yaks/query";
13
+ import { Unsent } from "@yaks/host/senders";
14
+ import { OPTED_OUT } from './recipients.js';
15
+ import { Blocked, consented, Denied, stoppedBy } from "./text.js";
16
+ let comp = (b, name)=>b?.[name];
17
+ let get = async (tx, eid)=>(await tx.get([
18
+ eid
19
+ ]))[0];
20
+ let stopped = async (tx, number)=>{
21
+ let replies = await tx.read(line`.text.from=${number}&.order=text.at&?doc`);
22
+ return stoppedBy(replies.map((r)=>String(comp(r, 'doc')?.body ?? '')));
23
+ };
24
+ /** Whether a text is still owed a send: it asks to go, was never handed to
25
+ * a sender, and has no outcome. */ export let owed = (text)=>!!comp(text, 'text') && !!comp(text, 'deliver') && comp(text, 'deliver')?.tried == null && !comp(text, 'delivered') && !comp(text, 'bounced');
26
+ /**
27
+ * The `text_post` handler: hand an outbound text to the sender and write
28
+ * back what became of it. A {@link Blocked} text is bounced with the
29
+ * carrier's reason and reports nothing; any other refusal is bounced and
30
+ * thrown, so the host's reporter hears it.
31
+ */ export let sending = ({ sender, now = ()=>new Date().toISOString() })=>async (event, tx, write)=>{
32
+ let entity = event.entity;
33
+ let text = await get(tx, entity.eid);
34
+ if (!owed(text)) return;
35
+ let deliver = comp(text, 'deliver');
36
+ let said = comp(text, 'text');
37
+ let settle = (out)=>write([
38
+ {
39
+ entity,
40
+ ...out
41
+ }
42
+ ]);
43
+ let bounce = (reason)=>settle({
44
+ bounced: {
45
+ at: now(),
46
+ reason: reason.slice(0, 500)
47
+ }
48
+ });
49
+ let to = String(comp(await get(tx, String(deliver.to ?? '')), 'phone')?.number ?? '');
50
+ if (said.to && said.to != to) {
51
+ return await bounce('The recipient no longer has this number on file.');
52
+ }
53
+ if (!to) {
54
+ await bounce(`no phone number on file for ${deliver.to}`);
55
+ throw new Error(`text ${entity.eid}: no number for ${deliver.to}`);
56
+ }
57
+ // Nobody is texted before they agree; a text to someone who has not, or
58
+ // who replied STOP, comes to rest as a bounce, which is expected.
59
+ if (said.to && await stopped(tx, to)) return await bounce(OPTED_OUT);
60
+ if (!await consented(tx, String(deliver.to))) {
61
+ return await bounce(said.to ? 'This number has not agreed to texts.' : `${deliver.to} has not agreed to texts: no sms_consent is kept for them`);
62
+ }
63
+ let stamp = now();
64
+ try {
65
+ await write([
66
+ {
67
+ entity,
68
+ deliver: {
69
+ tried: stamp,
70
+ waiting: null
71
+ },
72
+ $was: {
73
+ deliver: {
74
+ tried: token(deliver.tried)
75
+ }
76
+ }
77
+ }
78
+ ]);
79
+ } catch (error) {
80
+ // Another run claimed it first.
81
+ if (error instanceof Stale && error.eid == entity.eid) return;
82
+ throw error;
83
+ }
84
+ let receipt;
85
+ try {
86
+ receipt = await sender.send({
87
+ to,
88
+ text: String(comp(text, 'doc')?.body ?? ''),
89
+ ...said.from ? {
90
+ from: String(said.from)
91
+ } : {}
92
+ });
93
+ } catch (error) {
94
+ if (error instanceof Unsent) {
95
+ await write([
96
+ {
97
+ entity,
98
+ deliver: {
99
+ tried: null,
100
+ waiting: error.message.slice(0, 240)
101
+ },
102
+ $was: {
103
+ deliver: {
104
+ tried: token(stamp)
105
+ }
106
+ }
107
+ }
108
+ ]);
109
+ throw error;
110
+ }
111
+ let why = error instanceof Error ? error.message : String(error);
112
+ // Only a carrier's no and a refused key are said as they are; any other
113
+ // failure is ours, reported below, and said so.
114
+ await bounce(error instanceof Blocked || error instanceof Denied ? why : `This text could not be sent because of a fault on our side, which has been reported. (${why})`);
115
+ if (error instanceof Blocked) return;
116
+ throw error;
117
+ }
118
+ await settle({
119
+ text: {
120
+ to,
121
+ ...receipt.via ? {
122
+ via: receipt.via
123
+ } : {},
124
+ ...receipt.from ? {
125
+ from: receipt.from
126
+ } : {},
127
+ ...receipt.id ? {
128
+ message_id: receipt.id
129
+ } : {}
130
+ },
131
+ delivered: {
132
+ at: now()
133
+ }
134
+ });
135
+ };
136
+ //# sourceMappingURL=send.js.map
package/send.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"send.js","sources":["./send.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,4EAA4E;AAC5E,qEAAqE;AACrE,+DAA+D;AAC/D,EAAE;AACF,wEAAwE;AACxE,0EAA0E;AAC1E,2EAA2E;AAC3E,2EAA2E;AAG3E,SAAS,KAAK,kCAAuC;AACrD,SAAS,KAAK,kCAAuC;AACrD,SAAS,IAAI,2BAAgC;AAE7C,SAAS,MAAM,kCAAuC;AACtD,SAAS,SAAS,QAAQ,kBAAiB;AAC3C,SAAS,OAAO,EAAE,SAAS,EAAE,MAAM,EAAe,SAAS,oBAAmB;AAU9E,IAAI,OAAO,CAAC,GAAuB,OACjC,GAAG,CAAC,KAAK;AAEX,IAAI,MAAM,OAAO,IAAY,MAAgB,CAAC,MAAM,GAAG,GAAG,CA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,iBAAiB,SAAS;MAC9B,MAAM;IACR;IACA,MAAM,OAAO;MACX,MAAM;QACJ;QACA,GAAI,QAAQ,GAAG,GAAG;UAAE,KAAK,QAAQ,GAAG;QAAC,IAAI,CAAC,CAAC;QAC3C,GAAI,QAAQ,IAAI,GAAG;UAAE,MAAM,QAAQ,IAAI;QAAC,IAAI,CAAC,CAAC;QAC9C,GAAI,QAAQ,EAAE,GAAG;UAAE,YAAY,QAAQ,EAAE;QAAC,IAAI,CAAC,CAAC;MAClD;MACA,WAAW;QAAE,IAAI;MAAM;IACzB;EACF,EAAC"}
package/send.ts ADDED
@@ -0,0 +1,131 @@
1
+ // Sending a text kept in the graph: an entity wearing `text` and @yaks/mail's
2
+ // `deliver{to}` asks to be sent to the `phone{number}` of `deliver.to`. The
3
+ // effect runs after the write commits and writes the outcome back as
4
+ // `delivered` or `bounced`, the words a letter's outcome uses.
5
+ //
6
+ // Sending is at most once, as a letter's is: `deliver.tried` is claimed
7
+ // before the text reaches the sender, so a crash between the two leaves a
8
+ // text that is never handed over again. A sender's `Unsent` knows the text
9
+ // never left: the claim is given back and the run fails to be tried again.
10
+
11
+ import type { Bundle, Comp, Entity, ReadTx } from 'jsr:@yaks/graph@0.2.36'
12
+ import { Stale } from '@yaks/graph/errors'
13
+ import { token } from '@yaks/graph/sha256'
14
+ import { line } from '@yaks/query'
15
+ import type { Handler } from 'jsr:@yaks/effects@0.2.36'
16
+ import { Unsent } from '@yaks/host/senders'
17
+ import { OPTED_OUT } from './recipients.js'
18
+ import { Blocked, consented, Denied, type Sender, stoppedBy } from './text.js'
19
+
20
+ /** How the effect is built. */
21
+ export type Texting = {
22
+ /** what hands a text over */
23
+ sender: Sender
24
+ /** the clock, for a test to hold still */
25
+ now?: () => string
26
+ }
27
+
28
+ let comp = (b: Bundle | undefined, name: string) =>
29
+ b?.[name] as Comp | undefined
30
+
31
+ let get = async (tx: ReadTx, eid: string) => (await tx.get([eid]))[0]
32
+
33
+ let stopped = async (tx: ReadTx, number: string) => {
34
+ let replies = await tx.read(line`.text.from=${number}&.order=text.at&?doc`)
35
+ return stoppedBy(replies.map((r) => String(comp(r, 'doc')?.body ?? '')))
36
+ }
37
+
38
+ /** Whether a text is still owed a send: it asks to go, was never handed to
39
+ * a sender, and has no outcome. */
40
+ export let owed = (text: Bundle | undefined): boolean =>
41
+ !!comp(text, 'text') && !!comp(text, 'deliver') &&
42
+ comp(text, 'deliver')?.tried == null && !comp(text, 'delivered') &&
43
+ !comp(text, 'bounced')
44
+
45
+ /**
46
+ * The `text_post` handler: hand an outbound text to the sender and write
47
+ * back what became of it. A {@link Blocked} text is bounced with the
48
+ * carrier's reason and reports nothing; any other refusal is bounced and
49
+ * thrown, so the host's reporter hears it.
50
+ */
51
+ export let sending =
52
+ ({ sender, now = () => new Date().toISOString() }: Texting): Handler =>
53
+ async (event, tx, write) => {
54
+ let entity: Entity = event.entity
55
+ let text = await get(tx, entity.eid)
56
+ if (!owed(text)) return
57
+ let deliver = comp(text, 'deliver')!
58
+ let said = comp(text, 'text')!
59
+ let settle = (out: Record<string, Comp>) => write([{ entity, ...out }])
60
+ let bounce = (reason: string) =>
61
+ settle({ bounced: { at: now(), reason: reason.slice(0, 500) } })
62
+ let to = String(
63
+ comp(await get(tx, String(deliver.to ?? '')), 'phone')
64
+ ?.number ?? '',
65
+ )
66
+ if (said.to && said.to != to) {
67
+ return await bounce('The recipient no longer has this number on file.')
68
+ }
69
+ if (!to) {
70
+ await bounce(`no phone number on file for ${deliver.to}`)
71
+ throw new Error(`text ${entity.eid}: no number for ${deliver.to}`)
72
+ }
73
+ // Nobody is texted before they agree; a text to someone who has not, or
74
+ // who replied STOP, comes to rest as a bounce, which is expected.
75
+ if (said.to && await stopped(tx, to)) return await bounce(OPTED_OUT)
76
+ if (!await consented(tx, String(deliver.to))) {
77
+ return await bounce(
78
+ said.to
79
+ ? 'This number has not agreed to texts.'
80
+ : `${deliver.to} has not agreed to texts: no sms_consent is kept for them`,
81
+ )
82
+ }
83
+ let stamp = now()
84
+ try {
85
+ await write([{
86
+ entity,
87
+ deliver: { tried: stamp, waiting: null },
88
+ $was: { deliver: { tried: token(deliver.tried) } },
89
+ }])
90
+ } catch (error) {
91
+ // Another run claimed it first.
92
+ if (error instanceof Stale && error.eid == entity.eid) return
93
+ throw error
94
+ }
95
+ let receipt
96
+ try {
97
+ receipt = await sender.send({
98
+ to,
99
+ text: String(comp(text, 'doc')?.body ?? ''),
100
+ ...(said.from ? { from: String(said.from) } : {}),
101
+ })
102
+ } catch (error) {
103
+ if (error instanceof Unsent) {
104
+ await write([{
105
+ entity,
106
+ deliver: { tried: null, waiting: error.message.slice(0, 240) },
107
+ $was: { deliver: { tried: token(stamp) } },
108
+ }])
109
+ throw error
110
+ }
111
+ let why = error instanceof Error ? error.message : String(error)
112
+ // Only a carrier's no and a refused key are said as they are; any other
113
+ // failure is ours, reported below, and said so.
114
+ await bounce(
115
+ error instanceof Blocked || error instanceof Denied
116
+ ? why
117
+ : `This text could not be sent because of a fault on our side, which has been reported. (${why})`,
118
+ )
119
+ if (error instanceof Blocked) return
120
+ throw error
121
+ }
122
+ await settle({
123
+ text: {
124
+ to,
125
+ ...(receipt.via ? { via: receipt.via } : {}),
126
+ ...(receipt.from ? { from: receipt.from } : {}),
127
+ ...(receipt.id ? { message_id: receipt.id } : {}),
128
+ },
129
+ delivered: { at: now() },
130
+ })
131
+ }
package/stash.js ADDED
@@ -0,0 +1,26 @@
1
+ // The sender that sends nothing: it keeps the texts in an array, for tests
2
+ // and for a box with no provider.
3
+ import { Blocked } from "./text.js";
4
+ /**
5
+ * A sender that keeps texts in memory. Receipts are `stash-1`, `stash-2`, ….
6
+ * `refuse` rejects every text with that reason, and `block` rejects it as
7
+ * {@link Blocked}, the way a carrier refuses an unregistered number.
8
+ *
9
+ * ```ts
10
+ * import { equal } from '@yaks/testing'
11
+ * import { stash } from '@yaks/phone'
12
+ * let texts = stash()
13
+ * equal(await texts.send({ to: '+12695550142', text: 'Hi' }), { id: 'stash-1' })
14
+ * equal(texts.last()?.text, 'Hi')
15
+ * ```
16
+ */ export let stash = ({ refuse, block } = {})=>{
17
+ let sent = [];
18
+ return {
19
+ sent,
20
+ last: ()=>sent.at(-1),
21
+ send: (text)=>block ? Promise.reject(new Blocked(block)) : refuse ? Promise.reject(new Error(refuse)) : Promise.resolve({
22
+ id: `stash-${sent.push(text)}`
23
+ })
24
+ };
25
+ };
26
+ //# sourceMappingURL=stash.js.map
package/stash.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stash.js","sources":["./stash.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,kCAAkC;AAElC,SAAS,OAAO,oBAAyD;AAUzE;;;;;;;;;;;;CAYC,GACD,OAAO,IAAI,QAAQ,CACjB,EAAE,MAAM,EAAE,KAAK,EAAuC,GAAG,CAAC,CAAC;EAE3D,IAAI,OAAe,EAAE;EACrB,OAAO;IACL;IACA,MAAM,IAAM,KAAK,EAAE,CAAC,CAAC;IACrB,MAAM,CAAC,OACL,QACI,QAAQ,MAAM,CAAC,IAAI,QAAQ,UAC3B,SACA,QAAQ,MAAM,CAAC,IAAI,MAAM,WACzB,QAAQ,OAAO,CAAC;QAAE,IAAI,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,OAAO;MAAC;EACzD;AACF,EAAC"}
package/stash.ts ADDED
@@ -0,0 +1,41 @@
1
+ // The sender that sends nothing: it keeps the texts in an array, for tests
2
+ // and for a box with no provider.
3
+
4
+ import { Blocked, type Receipt, type Sender, type Text } from './text.js'
5
+
6
+ /** A {@link Sender} that keeps what it was given. */
7
+ export type Stash = Sender & {
8
+ /** every text handed over, in order */
9
+ sent: Text[]
10
+ /** the last one */
11
+ last: () => Text | undefined
12
+ }
13
+
14
+ /**
15
+ * A sender that keeps texts in memory. Receipts are `stash-1`, `stash-2`, ….
16
+ * `refuse` rejects every text with that reason, and `block` rejects it as
17
+ * {@link Blocked}, the way a carrier refuses an unregistered number.
18
+ *
19
+ * ```ts
20
+ * import { equal } from '@yaks/testing'
21
+ * import { stash } from '@yaks/phone'
22
+ * let texts = stash()
23
+ * equal(await texts.send({ to: '+12695550142', text: 'Hi' }), { id: 'stash-1' })
24
+ * equal(texts.last()?.text, 'Hi')
25
+ * ```
26
+ */
27
+ export let stash = (
28
+ { refuse, block }: { refuse?: string; block?: string } = {},
29
+ ): Stash => {
30
+ let sent: Text[] = []
31
+ return {
32
+ sent,
33
+ last: () => sent.at(-1),
34
+ send: (text: Text): Promise<Receipt> =>
35
+ block
36
+ ? Promise.reject(new Blocked(block))
37
+ : refuse
38
+ ? Promise.reject(new Error(refuse))
39
+ : Promise.resolve({ id: `stash-${sent.push(text)}` }),
40
+ }
41
+ }