@connextar/house 0.25.4 → 0.27.0
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.
- package/README.md +112 -0
- package/dist/inbox/inbox.d.ts +104 -0
- package/dist/inbox/inbox.d.ts.map +1 -0
- package/dist/inbox/inbox.js +178 -0
- package/dist/inbox/inbox.js.map +1 -0
- package/dist/inbox/index.d.ts +11 -0
- package/dist/inbox/index.d.ts.map +1 -0
- package/dist/inbox/index.js +11 -0
- package/dist/inbox/index.js.map +1 -0
- package/dist/inbox/use-selection.d.ts +23 -0
- package/dist/inbox/use-selection.d.ts.map +1 -0
- package/dist/inbox/use-selection.js +51 -0
- package/dist/inbox/use-selection.js.map +1 -0
- package/dist/voice/handoff.d.ts +20 -0
- package/dist/voice/handoff.d.ts.map +1 -0
- package/dist/voice/handoff.js +18 -0
- package/dist/voice/handoff.js.map +1 -0
- package/dist/voice/index.d.ts +16 -0
- package/dist/voice/index.d.ts.map +1 -0
- package/dist/voice/index.js +16 -0
- package/dist/voice/index.js.map +1 -0
- package/dist/voice/opening-hours.d.ts +23 -0
- package/dist/voice/opening-hours.d.ts.map +1 -0
- package/dist/voice/opening-hours.js +117 -0
- package/dist/voice/opening-hours.js.map +1 -0
- package/dist/voice/out-of-hours.d.ts +29 -0
- package/dist/voice/out-of-hours.d.ts.map +1 -0
- package/dist/voice/out-of-hours.js +20 -0
- package/dist/voice/out-of-hours.js.map +1 -0
- package/dist/voice/phone.d.ts +33 -0
- package/dist/voice/phone.d.ts.map +1 -0
- package/dist/voice/phone.js +62 -0
- package/dist/voice/phone.js.map +1 -0
- package/dist/voice/relay/agent-client.d.ts +24 -0
- package/dist/voice/relay/agent-client.d.ts.map +1 -0
- package/dist/voice/relay/agent-client.js +45 -0
- package/dist/voice/relay/agent-client.js.map +1 -0
- package/dist/voice/relay/model.d.ts +124 -0
- package/dist/voice/relay/model.d.ts.map +1 -0
- package/dist/voice/relay/model.js +304 -0
- package/dist/voice/relay/model.js.map +1 -0
- package/dist/voice/relay/protocol.d.ts +44 -0
- package/dist/voice/relay/protocol.d.ts.map +1 -0
- package/dist/voice/relay/protocol.js +16 -0
- package/dist/voice/relay/protocol.js.map +1 -0
- package/dist/voice/relay/sentence-gate.d.ts +24 -0
- package/dist/voice/relay/sentence-gate.d.ts.map +1 -0
- package/dist/voice/relay/sentence-gate.js +65 -0
- package/dist/voice/relay/sentence-gate.js.map +1 -0
- package/dist/voice/relay/server.d.ts +71 -0
- package/dist/voice/relay/server.d.ts.map +1 -0
- package/dist/voice/relay/server.js +192 -0
- package/dist/voice/relay/server.js.map +1 -0
- package/dist/voice/relay/transfer-line.d.ts +33 -0
- package/dist/voice/relay/transfer-line.d.ts.map +1 -0
- package/dist/voice/relay/transfer-line.js +116 -0
- package/dist/voice/relay/transfer-line.js.map +1 -0
- package/dist/voice/relay-index.d.ts +13 -0
- package/dist/voice/relay-index.d.ts.map +1 -0
- package/dist/voice/relay-index.js +13 -0
- package/dist/voice/relay-index.js.map +1 -0
- package/dist/voice/session-token.d.ts +58 -0
- package/dist/voice/session-token.d.ts.map +1 -0
- package/dist/voice/session-token.js +152 -0
- package/dist/voice/session-token.js.map +1 -0
- package/dist/voice/transfer.d.ts +123 -0
- package/dist/voice/transfer.d.ts.map +1 -0
- package/dist/voice/transfer.js +95 -0
- package/dist/voice/transfer.js.map +1 -0
- package/dist/voice/twilio-request.d.ts +30 -0
- package/dist/voice/twilio-request.d.ts.map +1 -0
- package/dist/voice/twilio-request.js +46 -0
- package/dist/voice/twilio-request.js.map +1 -0
- package/dist/voice/twilio-signature.d.ts +8 -0
- package/dist/voice/twilio-signature.d.ts.map +1 -0
- package/dist/voice/twilio-signature.js +22 -0
- package/dist/voice/twilio-signature.js.map +1 -0
- package/dist/voice/twiml.d.ts +93 -0
- package/dist/voice/twiml.d.ts.map +1 -0
- package/dist/voice/twiml.js +107 -0
- package/dist/voice/twiml.js.map +1 -0
- package/package.json +19 -1
- package/src/inbox/inbox.ts +200 -0
- package/src/inbox/index.ts +33 -0
- package/src/inbox/use-selection.ts +60 -0
- package/src/voice/handoff.ts +34 -0
- package/src/voice/index.ts +78 -0
- package/src/voice/opening-hours.ts +125 -0
- package/src/voice/out-of-hours.ts +48 -0
- package/src/voice/phone.ts +68 -0
- package/src/voice/relay/agent-client.ts +64 -0
- package/src/voice/relay/model.ts +412 -0
- package/src/voice/relay/protocol.ts +52 -0
- package/src/voice/relay/sentence-gate.ts +64 -0
- package/src/voice/relay/server.ts +242 -0
- package/src/voice/relay/transfer-line.ts +114 -0
- package/src/voice/relay-index.ts +46 -0
- package/src/voice/session-token.ts +205 -0
- package/src/voice/transfer.ts +171 -0
- package/src/voice/twilio-request.ts +60 -0
- package/src/voice/twilio-signature.ts +27 -0
- package/src/voice/twiml.ts +184 -0
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The rules of a notifications inbox, with no markup and no database in them.
|
|
5
|
+
*
|
|
6
|
+
* Which list is showing (`filter`), which page of it (`page`), what can be done
|
|
7
|
+
* to the rows that are ticked (`actionsFor`), what a bulk request may carry
|
|
8
|
+
* (`inboxActionSchema`) and which page numbers a pager shows (`pageWindow`).
|
|
9
|
+
* The app owns the rows, the storage and the look; this owns the arithmetic
|
|
10
|
+
* that every inbox gets slightly wrong on its own.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** The lists an inbox shows: everything not archived, only the unread ones, or the archive. */
|
|
14
|
+
export const INBOX_FILTERS = ["inbox", "unread", "archived"] as const;
|
|
15
|
+
export type InboxFilter = (typeof INBOX_FILTERS)[number];
|
|
16
|
+
|
|
17
|
+
/** What can be done to ticked rows. `delete` is permanent; `archive` is the way to put something away. */
|
|
18
|
+
export const INBOX_ACTIONS = ["read", "unread", "archive", "unarchive", "delete"] as const;
|
|
19
|
+
export type InboxAction = (typeof INBOX_ACTIONS)[number];
|
|
20
|
+
|
|
21
|
+
/** Rows a page, unless the app says otherwise. */
|
|
22
|
+
export const INBOX_PAGE_SIZE = 20;
|
|
23
|
+
|
|
24
|
+
/** The most rows one bulk request may name — a page and then some, never "everything" by accident. */
|
|
25
|
+
export const INBOX_MAX_BULK = 100;
|
|
26
|
+
|
|
27
|
+
/** The longest id accepted. A cuid is 25 characters, a UUID 36. */
|
|
28
|
+
const MAX_ID_LENGTH = 64;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The body of a bulk request: which rows, and what to do to them. The ids are the reader's own only after the
|
|
32
|
+
* app's query scopes them to the reader — this checks shape, never ownership.
|
|
33
|
+
*/
|
|
34
|
+
export const inboxActionSchema = z.object({
|
|
35
|
+
ids: z.array(z.string().min(1).max(MAX_ID_LENGTH)).min(1).max(INBOX_MAX_BULK),
|
|
36
|
+
action: z.enum(INBOX_ACTIONS),
|
|
37
|
+
});
|
|
38
|
+
export type InboxActionRequest = z.infer<typeof inboxActionSchema>;
|
|
39
|
+
|
|
40
|
+
type QueryInput = URLSearchParams | Record<string, string | string[] | undefined>;
|
|
41
|
+
|
|
42
|
+
function first(input: QueryInput, key: string): string | undefined {
|
|
43
|
+
if (input instanceof URLSearchParams) return input.get(key) ?? undefined;
|
|
44
|
+
const value = input[key];
|
|
45
|
+
return Array.isArray(value) ? value[0] : value;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* `?filter=` and `?page=` from a request or a page's `searchParams`. Anything unrecognised reads as the inbox's
|
|
50
|
+
* first page rather than an error: an address someone edited, or one from before a filter was renamed, still opens.
|
|
51
|
+
*/
|
|
52
|
+
export function parseInboxQuery(input: QueryInput): { filter: InboxFilter; page: number } {
|
|
53
|
+
const rawFilter = first(input, "filter");
|
|
54
|
+
const filter = INBOX_FILTERS.includes(rawFilter as InboxFilter) ? (rawFilter as InboxFilter) : "inbox";
|
|
55
|
+
const rawPage = first(input, "page");
|
|
56
|
+
const parsed = rawPage && /^\d{1,6}$/.test(rawPage) ? Number(rawPage) : 1;
|
|
57
|
+
return { filter, page: Math.max(1, parsed) };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The address of one page of one list, keeping the defaults out of it so the plain inbox is the plain path. */
|
|
61
|
+
export function inboxHref(path: string, filter: InboxFilter, page: number): string {
|
|
62
|
+
const params = new URLSearchParams();
|
|
63
|
+
if (filter !== "inbox") params.set("filter", filter);
|
|
64
|
+
if (page > 1) params.set("page", String(page));
|
|
65
|
+
const query = params.toString();
|
|
66
|
+
return query ? `${path}?${query}` : path;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** How many pages `total` rows fill; an empty list is one empty page, so "page 1 of 1" is always true. */
|
|
70
|
+
export function pageCount(total: number, pageSize: number = INBOX_PAGE_SIZE): number {
|
|
71
|
+
return Math.max(1, Math.ceil(Math.max(0, total) / Math.max(1, pageSize)));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A requested page brought within the list — after a delete empties the last page, the one before it. */
|
|
75
|
+
export function clampPage(page: number, pages: number): number {
|
|
76
|
+
return Math.min(Math.max(1, Math.floor(page) || 1), Math.max(1, pages));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The first and last row numbers on a page, 1-based, for "21–40 of 57"; both 0 for an empty list. */
|
|
80
|
+
export function pageRange(
|
|
81
|
+
page: number,
|
|
82
|
+
total: number,
|
|
83
|
+
pageSize: number = INBOX_PAGE_SIZE,
|
|
84
|
+
): { from: number; to: number } {
|
|
85
|
+
if (total <= 0) return { from: 0, to: 0 };
|
|
86
|
+
const from = (page - 1) * pageSize + 1;
|
|
87
|
+
return { from, to: Math.min(page * pageSize, total) };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The page numbers a pager shows: always the first and last, the current one with `around` either side, and a
|
|
92
|
+
* `"gap"` where numbers are left out. A gap never stands for a single page — that page is shown instead, since a
|
|
93
|
+
* "…" hiding one number is longer than the number.
|
|
94
|
+
*/
|
|
95
|
+
export function pageWindow(page: number, pages: number, around = 1): Array<number | "gap"> {
|
|
96
|
+
const last = Math.max(1, pages);
|
|
97
|
+
const current = clampPage(page, last);
|
|
98
|
+
const wanted = new Set<number>([1, last]);
|
|
99
|
+
for (let p = current - around; p <= current + around; p++) if (p >= 1 && p <= last) wanted.add(p);
|
|
100
|
+
const sorted = [...wanted].sort((a, b) => a - b);
|
|
101
|
+
const out: Array<number | "gap"> = [];
|
|
102
|
+
let previous = 0;
|
|
103
|
+
for (const p of sorted) {
|
|
104
|
+
if (p - previous === 2) out.push(previous + 1);
|
|
105
|
+
else if (p - previous > 2) out.push("gap");
|
|
106
|
+
out.push(p);
|
|
107
|
+
previous = p;
|
|
108
|
+
}
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** What an inbox needs to know about a row to offer actions on it. */
|
|
113
|
+
export interface InboxRowState {
|
|
114
|
+
read: boolean;
|
|
115
|
+
archived: boolean;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The actions worth offering for the ticked rows, in the order a toolbar shows them. Only what would change at
|
|
120
|
+
* least one of them: "Mark read" is offered while any is unread, "Unarchive" only in the archive. Delete is always
|
|
121
|
+
* offered for a selection, and never for an empty one.
|
|
122
|
+
*/
|
|
123
|
+
export function actionsFor(rows: readonly InboxRowState[]): InboxAction[] {
|
|
124
|
+
if (rows.length === 0) return [];
|
|
125
|
+
const actions: InboxAction[] = [];
|
|
126
|
+
if (rows.some((row) => !row.read)) actions.push("read");
|
|
127
|
+
if (rows.some((row) => row.read)) actions.push("unread");
|
|
128
|
+
if (rows.some((row) => !row.archived)) actions.push("archive");
|
|
129
|
+
if (rows.some((row) => row.archived)) actions.push("unarchive");
|
|
130
|
+
actions.push("delete");
|
|
131
|
+
return actions;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* The field an action sets on every named row. `delete` changes no field: the row goes.
|
|
136
|
+
*
|
|
137
|
+
* Archiving reads a row too — put away is dealt with, so the archive never holds the unread count — but only a row
|
|
138
|
+
* that is still unread: overwriting an earlier `readAt` would restart whatever the app keeps read rows for. That
|
|
139
|
+
* second, narrower update is `readsUnread`.
|
|
140
|
+
*/
|
|
141
|
+
export function actionChanges(action: Exclude<InboxAction, "delete">, now: Date = new Date()) {
|
|
142
|
+
switch (action) {
|
|
143
|
+
case "read":
|
|
144
|
+
return { readAt: now } as const;
|
|
145
|
+
case "unread":
|
|
146
|
+
return { readAt: null } as const;
|
|
147
|
+
case "archive":
|
|
148
|
+
return { archivedAt: now } as const;
|
|
149
|
+
case "unarchive":
|
|
150
|
+
return { archivedAt: null } as const;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Whether an action also sets `readAt` on the named rows that are unread (archiving does). */
|
|
155
|
+
export function readsUnread(action: InboxAction): boolean {
|
|
156
|
+
return action === "archive";
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Whether a row still belongs in a list after an action — so a toolbar knows to take it out of view. */
|
|
160
|
+
export function stillListed(filter: InboxFilter, row: InboxRowState): boolean {
|
|
161
|
+
if (filter === "archived") return row.archived;
|
|
162
|
+
if (filter === "unread") return !row.archived && !row.read;
|
|
163
|
+
return !row.archived;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** A row's state after an action, without asking the server — for an optimistic update. */
|
|
167
|
+
export function afterAction(action: Exclude<InboxAction, "delete">, row: InboxRowState): InboxRowState {
|
|
168
|
+
switch (action) {
|
|
169
|
+
case "read":
|
|
170
|
+
return { ...row, read: true };
|
|
171
|
+
case "unread":
|
|
172
|
+
return { ...row, read: false };
|
|
173
|
+
case "archive":
|
|
174
|
+
return { read: true, archived: true };
|
|
175
|
+
case "unarchive":
|
|
176
|
+
return { ...row, archived: false };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const VERBS: Record<InboxAction, { label: string; done: (n: number) => string }> = {
|
|
181
|
+
read: { label: "Mark read", done: (n) => `Marked ${count(n)} read.` },
|
|
182
|
+
unread: { label: "Mark unread", done: (n) => `Marked ${count(n)} unread.` },
|
|
183
|
+
archive: { label: "Archive", done: (n) => `Archived ${count(n)}.` },
|
|
184
|
+
unarchive: { label: "Move to inbox", done: (n) => `Moved ${count(n)} to the inbox.` },
|
|
185
|
+
delete: { label: "Delete", done: (n) => `Deleted ${count(n)}.` },
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
function count(n: number): string {
|
|
189
|
+
return n === 1 ? "1 notification" : `${n} notifications`;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** The button's words for an action. */
|
|
193
|
+
export function actionLabel(action: InboxAction): string {
|
|
194
|
+
return VERBS[action].label;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** What to say once an action has been applied to `n` rows. */
|
|
198
|
+
export function actionDone(action: InboxAction, n: number): string {
|
|
199
|
+
return VERBS[action].done(n);
|
|
200
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@connextar/house/inbox` — the rules of a notifications inbox.
|
|
3
|
+
*
|
|
4
|
+
* Filters (inbox, unread, archived), numbered pages, ticked rows and the bulk
|
|
5
|
+
* actions on them — read, unread, archive, move back, delete — with no markup
|
|
6
|
+
* and no database in it: React and Zod, and nothing else. The app owns its rows,
|
|
7
|
+
* its storage and its look, the same bargain `grid` offers.
|
|
8
|
+
*/
|
|
9
|
+
export {
|
|
10
|
+
INBOX_ACTIONS,
|
|
11
|
+
INBOX_FILTERS,
|
|
12
|
+
INBOX_MAX_BULK,
|
|
13
|
+
INBOX_PAGE_SIZE,
|
|
14
|
+
actionChanges,
|
|
15
|
+
actionDone,
|
|
16
|
+
actionLabel,
|
|
17
|
+
actionsFor,
|
|
18
|
+
afterAction,
|
|
19
|
+
clampPage,
|
|
20
|
+
inboxActionSchema,
|
|
21
|
+
inboxHref,
|
|
22
|
+
pageCount,
|
|
23
|
+
pageRange,
|
|
24
|
+
pageWindow,
|
|
25
|
+
parseInboxQuery,
|
|
26
|
+
readsUnread,
|
|
27
|
+
stillListed,
|
|
28
|
+
type InboxAction,
|
|
29
|
+
type InboxActionRequest,
|
|
30
|
+
type InboxFilter,
|
|
31
|
+
type InboxRowState,
|
|
32
|
+
} from "./inbox.js";
|
|
33
|
+
export { useSelection, type Selection } from "./use-selection.js";
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
import * as React from "react";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Ticked rows on a list that changes under them.
|
|
7
|
+
*
|
|
8
|
+
* Only the rows on show can be ticked: what is selected is always the ticked keys that are still in `visible`, so
|
|
9
|
+
* turning a page, changing the filter or a row leaving after an action can never leave something ticked that the
|
|
10
|
+
* reader can't see — and then act on it. Derived on every render rather than pruned by an effect, so there is no
|
|
11
|
+
* render in which a hidden row is still counted.
|
|
12
|
+
*/
|
|
13
|
+
export function useSelection(visible: readonly string[]) {
|
|
14
|
+
const [ticked, setTicked] = React.useState<ReadonlySet<string>>(() => new Set());
|
|
15
|
+
|
|
16
|
+
const visibleSet = React.useMemo(() => new Set(visible), [visible]);
|
|
17
|
+
const keys = React.useMemo(() => visible.filter((key) => ticked.has(key)), [visible, ticked]);
|
|
18
|
+
const count = keys.length;
|
|
19
|
+
const all = visible.length > 0 && count === visible.length;
|
|
20
|
+
|
|
21
|
+
const toggle = React.useCallback((key: string, on?: boolean) => {
|
|
22
|
+
setTicked((previous) => {
|
|
23
|
+
const next = new Set(previous);
|
|
24
|
+
const tick = on ?? !next.has(key);
|
|
25
|
+
if (tick) next.add(key);
|
|
26
|
+
else next.delete(key);
|
|
27
|
+
return next;
|
|
28
|
+
});
|
|
29
|
+
}, []);
|
|
30
|
+
|
|
31
|
+
const toggleAll = React.useCallback(
|
|
32
|
+
(on?: boolean) => {
|
|
33
|
+
setTicked((previous) => {
|
|
34
|
+
const tickedVisible = [...visibleSet].filter((key) => previous.has(key)).length;
|
|
35
|
+
const tick = on ?? !(visibleSet.size > 0 && tickedVisible === visibleSet.size);
|
|
36
|
+
return tick ? new Set(visibleSet) : new Set();
|
|
37
|
+
});
|
|
38
|
+
},
|
|
39
|
+
[visibleSet],
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
const clear = React.useCallback(() => setTicked(new Set()), []);
|
|
43
|
+
const isSelected = React.useCallback((key: string) => visibleSet.has(key) && ticked.has(key), [visibleSet, ticked]);
|
|
44
|
+
|
|
45
|
+
return {
|
|
46
|
+
/** The ticked keys on show, in list order. */
|
|
47
|
+
keys,
|
|
48
|
+
count,
|
|
49
|
+
/** Every row on show is ticked (and there is at least one). */
|
|
50
|
+
all,
|
|
51
|
+
/** Some, but not all, are ticked — a header checkbox's "indeterminate". */
|
|
52
|
+
some: count > 0 && !all,
|
|
53
|
+
isSelected,
|
|
54
|
+
toggle,
|
|
55
|
+
toggleAll,
|
|
56
|
+
clear,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export type Selection = ReturnType<typeof useSelection>;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The relay ends an AI session with `{ "type": "end", "handoffData": "<json>" }`;
|
|
3
|
+
* Twilio passes that string to the `<Connect action>` webhook as `HandoffData`.
|
|
4
|
+
* Never put personal data in it: the webhook looks anything else up by CallSid.
|
|
5
|
+
*/
|
|
6
|
+
export interface HandoffData {
|
|
7
|
+
reasonCode: "transfer" | "completed";
|
|
8
|
+
reason?: string;
|
|
9
|
+
/** The caller described an emergency and was told to call 999: say it again if nobody answers. */
|
|
10
|
+
emergency?: boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface ParsedHandoff {
|
|
14
|
+
/** `unknown` for anything unexpected, including a session that failed: treat it as a transfer. */
|
|
15
|
+
reasonCode: HandoffData["reasonCode"] | "unknown";
|
|
16
|
+
reason?: string;
|
|
17
|
+
emergency: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Read `HandoffData` defensively: anything unexpected is "unknown", which transfers to a person. */
|
|
21
|
+
export function parseHandoff(raw: string | undefined): ParsedHandoff {
|
|
22
|
+
if (!raw) return { reasonCode: "unknown", emergency: false };
|
|
23
|
+
try {
|
|
24
|
+
const data = JSON.parse(raw) as { reasonCode?: unknown; reason?: unknown; emergency?: unknown };
|
|
25
|
+
const reasonCode = data.reasonCode === "transfer" || data.reasonCode === "completed" ? data.reasonCode : "unknown";
|
|
26
|
+
return {
|
|
27
|
+
reasonCode,
|
|
28
|
+
reason: typeof data.reason === "string" ? data.reason.slice(0, 200) : undefined,
|
|
29
|
+
emergency: data.emergency === true,
|
|
30
|
+
};
|
|
31
|
+
} catch {
|
|
32
|
+
return { reasonCode: "unknown", emergency: false };
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@connextar/house/voice`: the app side of a Twilio voice line. TwiML builders,
|
|
3
|
+
* webhook signatures, per-call session tokens, UK phone rules, opening hours and
|
|
4
|
+
* the transfer policy. Imports only `node:crypto`, so a Next route handler takes
|
|
5
|
+
* it without the relay's WebSocket server or any model SDK.
|
|
6
|
+
*/
|
|
7
|
+
export {
|
|
8
|
+
connectConversationRelay,
|
|
9
|
+
DEFAULT_SAY_VOICE,
|
|
10
|
+
dial,
|
|
11
|
+
escapeXml,
|
|
12
|
+
gather,
|
|
13
|
+
hangup,
|
|
14
|
+
play,
|
|
15
|
+
reject,
|
|
16
|
+
response,
|
|
17
|
+
say,
|
|
18
|
+
sayAndHangup,
|
|
19
|
+
thenHangup,
|
|
20
|
+
type DialOptions,
|
|
21
|
+
type GatherOptions,
|
|
22
|
+
type RelayTwimlOptions,
|
|
23
|
+
type SayVoice,
|
|
24
|
+
} from "./twiml.js";
|
|
25
|
+
export { computeTwilioSignature, isValidTwilioSignature } from "./twilio-signature.js";
|
|
26
|
+
export {
|
|
27
|
+
createTwilioWebhooks,
|
|
28
|
+
twiml,
|
|
29
|
+
type TwilioParams,
|
|
30
|
+
type TwilioReadResult,
|
|
31
|
+
type TwilioWebhookConfig,
|
|
32
|
+
} from "./twilio-request.js";
|
|
33
|
+
export {
|
|
34
|
+
generateVoiceSessionKeys,
|
|
35
|
+
isUsablePublicKey,
|
|
36
|
+
isVoiceSessionToken,
|
|
37
|
+
publicKeyFor,
|
|
38
|
+
signVoiceSession,
|
|
39
|
+
verifyVoiceSession,
|
|
40
|
+
VOICE_SESSION_TTL_SECONDS,
|
|
41
|
+
type VoiceSession,
|
|
42
|
+
type VoiceSigner,
|
|
43
|
+
type VoiceVerifier,
|
|
44
|
+
} from "./session-token.js";
|
|
45
|
+
export {
|
|
46
|
+
divertsToAiLine,
|
|
47
|
+
isAllowedTransferNumber,
|
|
48
|
+
presentedNumber,
|
|
49
|
+
toE164,
|
|
50
|
+
TRANSFER_NUMBER_RULE,
|
|
51
|
+
type CallForwardingMode,
|
|
52
|
+
} from "./phone.js";
|
|
53
|
+
export {
|
|
54
|
+
DAY_KEYS,
|
|
55
|
+
describeOpeningHours,
|
|
56
|
+
hasOpeningHours,
|
|
57
|
+
isOpenAt,
|
|
58
|
+
nextOpening,
|
|
59
|
+
parseOpeningHours,
|
|
60
|
+
spokenTime,
|
|
61
|
+
type DayKey,
|
|
62
|
+
type OpeningHours,
|
|
63
|
+
} from "./opening-hours.js";
|
|
64
|
+
export { lineStatus, teamReachable, transferTarget, type LineHours, type LineStatus } from "./out-of-hours.js";
|
|
65
|
+
export { parseHandoff, type HandoffData, type ParsedHandoff } from "./handoff.js";
|
|
66
|
+
export {
|
|
67
|
+
dialTarget,
|
|
68
|
+
isTransferComingBack,
|
|
69
|
+
LOOP_WINDOW_MS,
|
|
70
|
+
plannedTransfer,
|
|
71
|
+
type ComingBackStore,
|
|
72
|
+
type DialRefusal,
|
|
73
|
+
type TransferLine,
|
|
74
|
+
type TransferRefusal,
|
|
75
|
+
type TransferRule,
|
|
76
|
+
type TransferRules,
|
|
77
|
+
type TransferStore,
|
|
78
|
+
} from "./transfer.js";
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Opening hours as an app stores them (JSON on its line or business row):
|
|
3
|
+
* `{ mon: [["09:00","18:00"]], …, sun: [] }` — a list of open intervals per day.
|
|
4
|
+
*/
|
|
5
|
+
export type OpeningHours = Partial<Record<DayKey, [string, string][]>>;
|
|
6
|
+
|
|
7
|
+
export const DAY_KEYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] as const;
|
|
8
|
+
export type DayKey = (typeof DAY_KEYS)[number];
|
|
9
|
+
|
|
10
|
+
const DAY_NAMES: Record<DayKey, string> = {
|
|
11
|
+
mon: "Monday",
|
|
12
|
+
tue: "Tuesday",
|
|
13
|
+
wed: "Wednesday",
|
|
14
|
+
thu: "Thursday",
|
|
15
|
+
fri: "Friday",
|
|
16
|
+
sat: "Saturday",
|
|
17
|
+
sun: "Sunday",
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export function parseOpeningHours(value: unknown): OpeningHours | null {
|
|
21
|
+
if (!value || typeof value !== "object") return null;
|
|
22
|
+
const hours: OpeningHours = {};
|
|
23
|
+
for (const day of DAY_KEYS) {
|
|
24
|
+
const intervals = (value as Record<string, unknown>)[day];
|
|
25
|
+
if (!Array.isArray(intervals)) continue;
|
|
26
|
+
hours[day] = intervals.filter(
|
|
27
|
+
(i): i is [string, string] =>
|
|
28
|
+
Array.isArray(i) && i.length === 2 && i.every((t) => typeof t === "string" && /^\d{2}:\d{2}$/.test(t)),
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
return hours;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** "09:00" → "9am", "17:30" → "5:30pm", "12:00" → "12pm" — how people say times. */
|
|
35
|
+
export function spokenTime(hhmm: string): string {
|
|
36
|
+
const [h, m] = hhmm.split(":").map(Number) as [number, number];
|
|
37
|
+
const suffix = h >= 12 ? "pm" : "am";
|
|
38
|
+
const hour12 = h % 12 === 0 ? 12 : h % 12;
|
|
39
|
+
return m === 0 ? `${hour12}${suffix}` : `${hour12}:${String(m).padStart(2, "0")}${suffix}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function daySentence(intervals: [string, string][] | undefined): string {
|
|
43
|
+
if (!intervals || intervals.length === 0) return "closed";
|
|
44
|
+
return intervals.map(([open, close]) => `${spokenTime(open)} to ${spokenTime(close)}`).join(" and ");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** "Monday to Friday 9am to 6pm, Saturday 9am to 1pm, and closed on Sunday." */
|
|
48
|
+
export function describeOpeningHours(hours: OpeningHours | null): string {
|
|
49
|
+
if (!hours) return "Opening hours haven't been set up yet.";
|
|
50
|
+
const groups: { from: DayKey; to: DayKey; text: string }[] = [];
|
|
51
|
+
for (const day of DAY_KEYS) {
|
|
52
|
+
const text = daySentence(hours[day]);
|
|
53
|
+
const last = groups[groups.length - 1];
|
|
54
|
+
if (last && last.text === text) last.to = day;
|
|
55
|
+
else groups.push({ from: day, to: day, text });
|
|
56
|
+
}
|
|
57
|
+
const parts = groups.map((g) => {
|
|
58
|
+
const days = g.from === g.to ? DAY_NAMES[g.from] : `${DAY_NAMES[g.from]} to ${DAY_NAMES[g.to]}`;
|
|
59
|
+
return g.text === "closed" ? `closed on ${days}` : `${days} ${g.text}`;
|
|
60
|
+
});
|
|
61
|
+
const sentence = parts.length > 1 ? `${parts.slice(0, -1).join(", ")}, and ${parts[parts.length - 1]}` : parts[0]!;
|
|
62
|
+
return `${sentence.charAt(0).toUpperCase()}${sentence.slice(1)}.`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Whether the line is open at `at` in its own timezone. */
|
|
66
|
+
export function isOpenAt(hours: OpeningHours | null, at: Date, timeZone = "Europe/London"): boolean {
|
|
67
|
+
if (!hours) return false;
|
|
68
|
+
const parts = new Intl.DateTimeFormat("en-GB", {
|
|
69
|
+
timeZone,
|
|
70
|
+
weekday: "short",
|
|
71
|
+
hour: "2-digit",
|
|
72
|
+
minute: "2-digit",
|
|
73
|
+
hourCycle: "h23",
|
|
74
|
+
}).formatToParts(at);
|
|
75
|
+
const weekday = parts
|
|
76
|
+
.find((p) => p.type === "weekday")
|
|
77
|
+
?.value.toLowerCase()
|
|
78
|
+
.slice(0, 3) as DayKey | undefined;
|
|
79
|
+
const time = `${parts.find((p) => p.type === "hour")?.value}:${parts.find((p) => p.type === "minute")?.value}`;
|
|
80
|
+
if (!weekday) return false;
|
|
81
|
+
return (hours[weekday] ?? []).some(([open, close]) => time >= open && time < close);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Whether any opening hours are set. With none, the line is never treated as closed. */
|
|
85
|
+
export function hasOpeningHours(hours: OpeningHours | null): hours is OpeningHours {
|
|
86
|
+
return Boolean(hours && DAY_KEYS.some((d) => (hours[d] ?? []).length > 0));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The weekday and "HH:MM" at `at` in a timezone. */
|
|
90
|
+
function localDayAndTime(at: Date, timeZone: string): { day: number; time: string } {
|
|
91
|
+
const parts = new Intl.DateTimeFormat("en-GB", {
|
|
92
|
+
timeZone,
|
|
93
|
+
weekday: "short",
|
|
94
|
+
hour: "2-digit",
|
|
95
|
+
minute: "2-digit",
|
|
96
|
+
hourCycle: "h23",
|
|
97
|
+
}).formatToParts(at);
|
|
98
|
+
const weekday = parts
|
|
99
|
+
.find((p) => p.type === "weekday")
|
|
100
|
+
?.value.toLowerCase()
|
|
101
|
+
.slice(0, 3) as DayKey;
|
|
102
|
+
const time = `${parts.find((p) => p.type === "hour")?.value}:${parts.find((p) => p.type === "minute")?.value}`;
|
|
103
|
+
return { day: DAY_KEYS.indexOf(weekday), time };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* When the line next opens after `at`, as a caller would be told it: "at 9am today",
|
|
108
|
+
* "at 9am tomorrow", "at 9am on Monday". Null when no opening hours are set. Bank holidays aren't
|
|
109
|
+
* known here, so a bank holiday is treated as the weekday it falls on.
|
|
110
|
+
*/
|
|
111
|
+
export function nextOpening(hours: OpeningHours | null, at: Date, timeZone = "Europe/London"): string | null {
|
|
112
|
+
if (!hasOpeningHours(hours)) return null;
|
|
113
|
+
const { day, time } = localDayAndTime(at, timeZone);
|
|
114
|
+
for (let ahead = 0; ahead <= 7; ahead++) {
|
|
115
|
+
const key = DAY_KEYS[(day + ahead) % 7]!;
|
|
116
|
+
const opens = (hours[key] ?? [])
|
|
117
|
+
.map(([open]) => open)
|
|
118
|
+
.filter((open) => ahead > 0 || open > time)
|
|
119
|
+
.sort()[0];
|
|
120
|
+
if (!opens) continue;
|
|
121
|
+
const when = ahead === 0 ? "today" : ahead === 1 ? "tomorrow" : `on ${DAY_NAMES[key]}`;
|
|
122
|
+
return `at ${spokenTime(opens)} ${when}`;
|
|
123
|
+
}
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { hasOpeningHours, isOpenAt, nextOpening, parseOpeningHours } from "./opening-hours.js";
|
|
2
|
+
import { toE164 } from "./phone.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Whether a line is open now, and where a transfer goes when it isn't.
|
|
6
|
+
*
|
|
7
|
+
* Decided here, from the opening hours, rather than by the model: whether a
|
|
8
|
+
* caller is put through to a person can't depend on how a reply was worded. A
|
|
9
|
+
* line with no opening hours set is never treated as closed.
|
|
10
|
+
*
|
|
11
|
+
* What a caller hears when a line is closed is the app's own wording, so none is
|
|
12
|
+
* here (PharmaLine's names NHS 111; a switchboard says when it will call back).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export interface LineHours {
|
|
16
|
+
openingHours: unknown;
|
|
17
|
+
timezone: string;
|
|
18
|
+
/** Where transfers go while closed, or null for no transfer. */
|
|
19
|
+
outOfHoursTransferNumber: string | null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface LineStatus {
|
|
23
|
+
open: boolean;
|
|
24
|
+
/** "at 9am tomorrow": null while open or when no hours are set. */
|
|
25
|
+
opensAgain: string | null;
|
|
26
|
+
/** Where transfers go while closed (E.164), or null for no transfer. */
|
|
27
|
+
outOfHoursNumber: string | null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function lineStatus(line: LineHours, now: Date = new Date()): LineStatus {
|
|
31
|
+
const hours = parseOpeningHours(line.openingHours);
|
|
32
|
+
const open = !hasOpeningHours(hours) || isOpenAt(hours, now, line.timezone);
|
|
33
|
+
return {
|
|
34
|
+
open,
|
|
35
|
+
opensAgain: open ? null : nextOpening(hours, now, line.timezone),
|
|
36
|
+
outOfHoursNumber: toE164(line.outOfHoursTransferNumber),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Whether a transfer reaches a person right now: open, or closed with an out-of-hours number. */
|
|
41
|
+
export function teamReachable(status: LineStatus): boolean {
|
|
42
|
+
return status.open || Boolean(status.outOfHoursNumber);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The number a transfer rings now, or null when the caller should hear the closed line instead. */
|
|
46
|
+
export function transferTarget(status: LineStatus, transferNumber: string | null): string | null {
|
|
47
|
+
return status.open ? toE164(transferNumber) : status.outOfHoursNumber;
|
|
48
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Normalise a UK-style or international phone number to E.164 (`+441614960000`) so numbers typed
|
|
3
|
+
* into Settings ("0161 496 0000") match what the carrier sends. Returns null when it can't be a
|
|
4
|
+
* phone number.
|
|
5
|
+
*/
|
|
6
|
+
export function toE164(value: string | null | undefined, defaultCountryCode = "44"): string | null {
|
|
7
|
+
if (!value) return null;
|
|
8
|
+
const trimmed = value.trim();
|
|
9
|
+
const digits = trimmed.replace(/\D/g, "");
|
|
10
|
+
if (!digits) return null;
|
|
11
|
+
|
|
12
|
+
let e164: string;
|
|
13
|
+
if (trimmed.startsWith("+")) e164 = `+${digits}`;
|
|
14
|
+
else if (digits.startsWith("00")) e164 = `+${digits.slice(2)}`;
|
|
15
|
+
else if (digits.startsWith("0")) e164 = `+${defaultCountryCode}${digits.slice(1)}`;
|
|
16
|
+
else e164 = `+${digits}`;
|
|
17
|
+
|
|
18
|
+
// E.164 allows up to 15 digits; anything shorter than 8 isn't a dialable line.
|
|
19
|
+
const length = e164.length - 1;
|
|
20
|
+
return length >= 8 && length <= 15 ? e164 : null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Whether the platform may dial this number to put a caller through to staff.
|
|
25
|
+
*
|
|
26
|
+
* Every transfer is dialled from the app's own Twilio account, and an owner sets the transfer
|
|
27
|
+
* and out-of-hours numbers themselves — so a number that earns money when called (premium 09,
|
|
28
|
+
* revenue-sharing 084/087, personal 070) or costs a lot to reach (international) would let anyone
|
|
29
|
+
* who can make the line transfer run up the platform's bill (security round 3, finding 7). A
|
|
30
|
+
* team answers on a UK landline (01, 02), a non-geographic 03, a mobile (07, but not 070
|
|
31
|
+
* personal numbers or 076 pagers), or freephone (0800, 0808). Takes an E.164 number.
|
|
32
|
+
*/
|
|
33
|
+
export function isAllowedTransferNumber(e164: string | null | undefined): boolean {
|
|
34
|
+
return Boolean(e164 && /^\+44(?:1\d{8,9}|2\d{9}|3\d{9}|7[1-57-9]\d{8}|80[08]\d{6,7})$/.test(e164));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Carrier stand-ins for a number that isn't presented — withheld, restricted, unavailable — which
|
|
39
|
+
* Twilio sends in place of a caller ID. Thousands of callers share each, so none is a caller.
|
|
40
|
+
*/
|
|
41
|
+
const NOT_A_CALLER = new Set(["+266696687", "+86282452253", "+7378742833", "+2562533", "+8656696"]);
|
|
42
|
+
|
|
43
|
+
/** A caller's own number as presented, or null when it is withheld or not a number. */
|
|
44
|
+
export function presentedNumber(value: string | null | undefined): string | null {
|
|
45
|
+
const digits = value?.replace(/[^\d+]/g, "");
|
|
46
|
+
if (!digits || !/^\+\d{8,15}$/.test(digits) || NOT_A_CALLER.has(digits)) return null;
|
|
47
|
+
return digits;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** What an owner is told when a number is refused. */
|
|
51
|
+
export const TRANSFER_NUMBER_RULE =
|
|
52
|
+
"Use a UK landline, mobile or freephone number (01, 02, 03, 07 or 0800/0808) — premium, personal and international numbers can't be used";
|
|
53
|
+
|
|
54
|
+
/** How a line's own number reaches the AI line (PharmaLine's `Organization.callForwarding`). */
|
|
55
|
+
export type CallForwardingMode = "EVERY_CALL" | "EVERY_CALL_EXCEPT_AI_LINE" | "BUSY_OR_UNANSWERED";
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Whether ringing `number` reaches the AI line again rather than a person: it is the line's own
|
|
59
|
+
* number, and every call to that is diverted to the AI line. `dialTarget` never dials it, and an
|
|
60
|
+
* app's settings should warn when a transfer number is one.
|
|
61
|
+
*/
|
|
62
|
+
export function divertsToAiLine(
|
|
63
|
+
line: { phone: string | null; callForwarding: CallForwardingMode | null },
|
|
64
|
+
number: string | null,
|
|
65
|
+
): boolean {
|
|
66
|
+
const own = toE164(line.phone);
|
|
67
|
+
return line.callForwarding === "EVERY_CALL" && Boolean(own) && toE164(number) === own;
|
|
68
|
+
}
|