@12-apps/chat 0.0.0-stage → 1.1.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 +194 -2
- package/package.json +95 -4
- package/prisma/chat.prisma +61 -0
- package/prisma/migrations/20261002120000_add_chat/migration.sql +41 -0
- package/prisma/migrations/20261003120000_add_chat_thread_activity_index/migration.sql +2 -0
- package/scripts/sync-chat-schema.mjs +64 -0
- package/src/client/api.ts +146 -0
- package/src/client/assert.ts +7 -0
- package/src/client/copy.ts +43 -0
- package/src/client/en-US.ts +17 -0
- package/src/client/index.ts +18 -0
- package/src/client/locales.ts +12 -0
- package/src/client/pt-BR.ts +17 -0
- package/src/client/use-chat-thread.ts +302 -0
- package/src/core/contact-views.ts +231 -0
- package/src/core/contact.ts +333 -0
- package/src/core/errors.ts +9 -0
- package/src/core/types.ts +82 -0
- package/src/index.ts +26 -0
- package/src/manifest/index.ts +20 -0
- package/src/manifest/native.ts +13 -0
- package/src/manifest/server.ts +14 -0
- package/src/manifest/web.ts +14 -0
- package/src/native/composer.tsx +52 -0
- package/src/native/index.ts +21 -0
- package/src/native/layout.tsx +96 -0
- package/src/react/composer.tsx +58 -0
- package/src/react/index.ts +20 -0
- package/src/react/layout.tsx +103 -0
- package/src/server/context.ts +228 -0
- package/src/server/copy.ts +73 -0
- package/src/server/db.ts +87 -0
- package/src/server/en-US.ts +14 -0
- package/src/server/handler.ts +110 -0
- package/src/server/index.ts +34 -0
- package/src/server/locales.ts +12 -0
- package/src/server/pt-BR.ts +14 -0
- package/src/server/rate.ts +34 -0
- package/src/server/reads.ts +52 -0
- package/src/server/routes.ts +119 -0
- package/src/server/send.ts +203 -0
- package/src/ui/bubble-tint.ts +19 -0
- package/src/ui/surface.tsx +87 -0
- package/src/ui/thread-view.tsx +225 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ChatUiCopy } from "./copy";
|
|
2
|
+
|
|
3
|
+
/** The thread screen in US English — pass by hand, never a default. */
|
|
4
|
+
export const EN_US_CHAT_UI_COPY: ChatUiCopy = {
|
|
5
|
+
placeholder: "Write a message",
|
|
6
|
+
send: "Send",
|
|
7
|
+
sending: "Sending…",
|
|
8
|
+
emptyTitle: "No messages yet",
|
|
9
|
+
emptyDescription: "Send the first message here.",
|
|
10
|
+
closed: "This conversation is closed. The messages stay here for reference.",
|
|
11
|
+
loadError: "We could not load the conversation.",
|
|
12
|
+
retry: "Try again",
|
|
13
|
+
quickReplies: "Quick replies",
|
|
14
|
+
sendFailed: "We could not send it. Check your connection and try again.",
|
|
15
|
+
loading: "Loading the conversation…",
|
|
16
|
+
messagesLabel: "Conversation messages",
|
|
17
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/chat/client` — platform-free: the HTTP client, the thread state
|
|
3
|
+
* hook, and the screen's copy packs. Both surfaces are built on it; a host
|
|
4
|
+
* drawing its own thread UI can use it directly.
|
|
5
|
+
*/
|
|
6
|
+
export { ChatClientError, createChatClient, type ChatClient, type ChatFetch, type ChatSendInput } from "./api";
|
|
7
|
+
export {
|
|
8
|
+
useChatThread,
|
|
9
|
+
type ChatAutoMarkRead,
|
|
10
|
+
type ChatSendFailure,
|
|
11
|
+
type ChatThreadControls,
|
|
12
|
+
type ChatThreadPhase,
|
|
13
|
+
type ChatThreadState,
|
|
14
|
+
} from "./use-chat-thread";
|
|
15
|
+
export type { ChatUiCopy } from "./copy";
|
|
16
|
+
export { PT_BR_CHAT_UI_COPY } from "./pt-BR";
|
|
17
|
+
export { EN_US_CHAT_UI_COPY } from "./en-US";
|
|
18
|
+
export { CHAT_UI_COPY } from "./locales";
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { ChatUiCopy } from "./copy";
|
|
2
|
+
import { EN_US_CHAT_UI_COPY } from "./en-US";
|
|
3
|
+
import { PT_BR_CHAT_UI_COPY } from "./pt-BR";
|
|
4
|
+
|
|
5
|
+
/** Mirrored rather than imported, so the package stays liftable into any repo. */
|
|
6
|
+
type LocalePack<T> = { readonly "pt-BR": T; readonly "en-US": T };
|
|
7
|
+
|
|
8
|
+
/** Both languages, keyed by tag. */
|
|
9
|
+
export const CHAT_UI_COPY = {
|
|
10
|
+
"pt-BR": PT_BR_CHAT_UI_COPY,
|
|
11
|
+
"en-US": EN_US_CHAT_UI_COPY,
|
|
12
|
+
} as const satisfies LocalePack<ChatUiCopy>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ChatUiCopy } from "./copy";
|
|
2
|
+
|
|
3
|
+
/** The thread screen in Brazilian Portuguese — pass by hand, never a default. */
|
|
4
|
+
export const PT_BR_CHAT_UI_COPY: ChatUiCopy = {
|
|
5
|
+
placeholder: "Escreva uma mensagem",
|
|
6
|
+
send: "Enviar",
|
|
7
|
+
sending: "Enviando…",
|
|
8
|
+
emptyTitle: "Nenhuma mensagem ainda",
|
|
9
|
+
emptyDescription: "Mande a primeira mensagem por aqui.",
|
|
10
|
+
closed: "Esta conversa foi encerrada. As mensagens continuam aqui para consulta.",
|
|
11
|
+
loadError: "Não foi possível carregar a conversa.",
|
|
12
|
+
retry: "Tentar de novo",
|
|
13
|
+
quickReplies: "Respostas rápidas",
|
|
14
|
+
sendFailed: "Não foi possível enviar. Confira sua conexão e tente de novo.",
|
|
15
|
+
loading: "Carregando a conversa…",
|
|
16
|
+
messagesLabel: "Mensagens da conversa",
|
|
17
|
+
};
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The thread's state, platform-free: one hook both surfaces render.
|
|
3
|
+
*
|
|
4
|
+
* Loads on mount and again whenever `refreshSignal` changes — the host bumps it
|
|
5
|
+
* when its live channel says the thread moved, so the package needs no socket
|
|
6
|
+
* of its own. A reload keeps the messages on screen (no spinner after the
|
|
7
|
+
* first). Unless `autoMarkRead` is off, the thread is marked read up to the
|
|
8
|
+
* newest message a load SHOWED whenever that load found unread messages. With
|
|
9
|
+
* `autoMarkRead: "visible"` a load's unread wait until the list reports itself
|
|
10
|
+
* on screen (`controls.onVisibleChange(true)`): a thread mounted below the fold
|
|
11
|
+
* is marked read when it is scrolled to, not when it is mounted.
|
|
12
|
+
*
|
|
13
|
+
* Three races are closed here rather than left to the host:
|
|
14
|
+
* - a load that resolves after a send never drops the sent message: what is
|
|
15
|
+
* on screen and what a load returns are merged by id, never replaced;
|
|
16
|
+
* - a load overtaken by a newer one (or by a new `client`) is ignored;
|
|
17
|
+
* - a new `client` (another thread) shows nothing of the previous one, from
|
|
18
|
+
* the very render that receives it.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
22
|
+
|
|
23
|
+
import type { ChatThreadPayload, ChatWireMessage } from "../core/types";
|
|
24
|
+
import { ChatClientError, type ChatClient, type ChatSendInput } from "./api";
|
|
25
|
+
|
|
26
|
+
export type ChatThreadPhase = "loading" | "ready" | "error";
|
|
27
|
+
|
|
28
|
+
/** Why the last send failed: the server's own sentence, or a network failure (`message: null`). */
|
|
29
|
+
export interface ChatSendFailure {
|
|
30
|
+
readonly code: string | null;
|
|
31
|
+
readonly message: string | null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface ChatThreadState {
|
|
35
|
+
readonly phase: ChatThreadPhase;
|
|
36
|
+
readonly payload: ChatThreadPayload | null;
|
|
37
|
+
/** The server's own sentence for a refused load (a gone thread, an expired session), when it sent one. */
|
|
38
|
+
readonly loadFailure: string | null;
|
|
39
|
+
readonly sending: boolean;
|
|
40
|
+
readonly sendFailure: ChatSendFailure | null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface ChatThreadControls extends ChatThreadState {
|
|
44
|
+
send(text: string): Promise<boolean>;
|
|
45
|
+
sendQuickReply(key: string): Promise<boolean>;
|
|
46
|
+
reload(): void;
|
|
47
|
+
/**
|
|
48
|
+
* Set only with `autoMarkRead: "visible"`. The message list calls it with
|
|
49
|
+
* whether it is on screen now, and with `false` when it unmounts; nothing is
|
|
50
|
+
* marked read until it has said `true`.
|
|
51
|
+
*/
|
|
52
|
+
readonly onVisibleChange?: (visible: boolean) => void;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* When the thread marks itself read: after each load that found unread
|
|
57
|
+
* (`true`, the default), never (`false`, a hidden badge-only mount), or once
|
|
58
|
+
* the message list is on screen (`"visible"`).
|
|
59
|
+
*/
|
|
60
|
+
export type ChatAutoMarkRead = boolean | "visible";
|
|
61
|
+
|
|
62
|
+
/** The state, tagged with the client (thread) it belongs to. */
|
|
63
|
+
interface OwnedState extends ChatThreadState {
|
|
64
|
+
readonly owner: ChatClient;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const fresh = (owner: ChatClient): OwnedState => ({
|
|
68
|
+
owner,
|
|
69
|
+
phase: "loading",
|
|
70
|
+
payload: null,
|
|
71
|
+
loadFailure: null,
|
|
72
|
+
sending: false,
|
|
73
|
+
sendFailure: null,
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
/** The server's own order: oldest first, `id` breaking a tie. */
|
|
77
|
+
function byTime(a: ChatWireMessage, b: ChatWireMessage): number {
|
|
78
|
+
if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? -1 : 1;
|
|
79
|
+
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Messages never leave a thread, so what is shown and what arrived are a union; the newer copy wins. */
|
|
83
|
+
function mergeMessages(shown: readonly ChatWireMessage[], arrived: readonly ChatWireMessage[]): ChatWireMessage[] {
|
|
84
|
+
const byId = new Map(shown.map((message) => [message.id, message]));
|
|
85
|
+
for (const message of arrived) byId.set(message.id, message);
|
|
86
|
+
return [...byId.values()].sort(byTime);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function afterLoad(state: OwnedState, loaded: ChatThreadPayload): OwnedState {
|
|
90
|
+
const payload = state.payload ? { ...loaded, messages: mergeMessages(state.payload.messages, loaded.messages) } : loaded;
|
|
91
|
+
return { ...state, phase: "ready", loadFailure: null, payload };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Refusals that mean the thread is no longer readable by this caller. */
|
|
95
|
+
const UNREADABLE = new Set([401, 403, 404]);
|
|
96
|
+
|
|
97
|
+
function afterLoadFailure(state: OwnedState, error: unknown): OwnedState {
|
|
98
|
+
const refusal = error instanceof ChatClientError ? error : null;
|
|
99
|
+
// A reload lost to the network keeps what is on screen; a refused one does not.
|
|
100
|
+
if (state.payload && !(refusal && UNREADABLE.has(refusal.status))) return state;
|
|
101
|
+
return { ...state, phase: "error", payload: null, loadFailure: refusal?.serverMessage ?? null };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function afterSendFailure(state: OwnedState, error: unknown): OwnedState {
|
|
105
|
+
const refusal = error instanceof ChatClientError ? error : null;
|
|
106
|
+
const sendFailure = { code: refusal?.code ?? null, message: refusal?.serverMessage ?? null };
|
|
107
|
+
const shown = state.payload;
|
|
108
|
+
// A thread that closed mid-session turns read-only now; the reload that follows confirms it.
|
|
109
|
+
const payload = shown && refusal?.code === "closed" ? { ...shown, thread: { ...shown.thread, canWrite: false } } : shown;
|
|
110
|
+
return { ...state, sending: false, sendFailure, payload };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** A send refused because the thread closed or vanished: what is on screen is out of date. */
|
|
114
|
+
const outdates = (error: unknown): boolean =>
|
|
115
|
+
error instanceof ChatClientError && (error.code === "closed" || error.status === 404);
|
|
116
|
+
|
|
117
|
+
const visibleOf = (state: OwnedState): ChatThreadState => ({
|
|
118
|
+
phase: state.phase,
|
|
119
|
+
payload: state.payload,
|
|
120
|
+
loadFailure: state.loadFailure,
|
|
121
|
+
sending: state.sending,
|
|
122
|
+
sendFailure: state.sendFailure,
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
type Update = (owner: ChatClient, step: (previous: OwnedState) => OwnedState) => void;
|
|
126
|
+
|
|
127
|
+
interface UseChatThreadOptions {
|
|
128
|
+
client: ChatClient;
|
|
129
|
+
refreshSignal?: unknown;
|
|
130
|
+
/** Told the unread count each load found (before marking read), then what is left once marked read. */
|
|
131
|
+
onUnreadChange?: (unread: number) => void;
|
|
132
|
+
/** Mark the thread read after a load shows unread messages. Default true; see {@link ChatAutoMarkRead}. */
|
|
133
|
+
autoMarkRead?: ChatAutoMarkRead;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** What a load showed, and whether that load is still the latest. */
|
|
137
|
+
interface Shown {
|
|
138
|
+
readonly payload: ChatThreadPayload;
|
|
139
|
+
readonly isCurrent: () => boolean;
|
|
140
|
+
/** The thread the payload came from: a mark goes to it, never to whichever thread is open now. */
|
|
141
|
+
readonly client: ChatClient;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
interface Loader {
|
|
145
|
+
readonly load: () => Promise<void>;
|
|
146
|
+
readonly onVisibleChange: (visible: boolean) => void;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The latest value, readable from callbacks without re-creating them. */
|
|
150
|
+
function useLatest<T>(value: T): { readonly current: T } {
|
|
151
|
+
const ref = useRef(value);
|
|
152
|
+
useEffect(() => {
|
|
153
|
+
ref.current = value;
|
|
154
|
+
}, [value]);
|
|
155
|
+
return ref;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Tell the host the unread count; its callback throwing must not reject a load nobody awaits. */
|
|
159
|
+
function report(onUnread: { readonly current?: (unread: number) => void }, unread: number): void {
|
|
160
|
+
try {
|
|
161
|
+
onUnread.current?.(unread);
|
|
162
|
+
} catch {
|
|
163
|
+
// The host's badge failed to update; the thread itself is fine.
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** The state, owned by the client it was loaded through; `update` ignores a client the hook has left. */
|
|
168
|
+
function useOwnedState(client: ChatClient): { state: OwnedState; update: Update; latest: { readonly current: ChatClient } } {
|
|
169
|
+
const [state, setState] = useState<OwnedState>(() => fresh(client));
|
|
170
|
+
const latest = useLatest(client);
|
|
171
|
+
const update = useCallback<Update>(
|
|
172
|
+
(owner, step) => {
|
|
173
|
+
setState((previous) => {
|
|
174
|
+
if (owner !== latest.current) return previous;
|
|
175
|
+
return step(previous.owner === owner ? previous : fresh(owner));
|
|
176
|
+
});
|
|
177
|
+
},
|
|
178
|
+
[latest],
|
|
179
|
+
);
|
|
180
|
+
return { state, update, latest };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Mark read what a load showed — at once, or (`"visible"`) once the list is on
|
|
185
|
+
* screen. Only the latest load's unread wait; a newer load replaces them.
|
|
186
|
+
*/
|
|
187
|
+
function useMarkRead(options: UseChatThreadOptions, onUnread: { readonly current?: (unread: number) => void }) {
|
|
188
|
+
const client = useLatest(options.client);
|
|
189
|
+
const mode = useLatest(options.autoMarkRead ?? true);
|
|
190
|
+
const visible = useRef(false);
|
|
191
|
+
const pending = useRef<Shown | null>(null);
|
|
192
|
+
|
|
193
|
+
const markRead = useCallback(
|
|
194
|
+
async ({ payload, isCurrent, client: from }: Shown) => {
|
|
195
|
+
const upTo = payload.messages.at(-1)?.createdAt;
|
|
196
|
+
if (payload.unread === 0 || upTo === undefined) return;
|
|
197
|
+
const left = await from.markRead(upTo).catch(() => null);
|
|
198
|
+
if (left !== null && isCurrent()) report(onUnread, left);
|
|
199
|
+
},
|
|
200
|
+
[onUnread],
|
|
201
|
+
);
|
|
202
|
+
|
|
203
|
+
const markShown = useCallback(
|
|
204
|
+
async (shown: Shown) => {
|
|
205
|
+
pending.current = null;
|
|
206
|
+
if (mode.current === false || shown.payload.unread === 0) return;
|
|
207
|
+
if (mode.current === "visible" && !visible.current) {
|
|
208
|
+
pending.current = shown;
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
await markRead(shown);
|
|
212
|
+
},
|
|
213
|
+
[mode, markRead],
|
|
214
|
+
);
|
|
215
|
+
|
|
216
|
+
const onVisibleChange = useCallback(
|
|
217
|
+
(now: boolean) => {
|
|
218
|
+
visible.current = now;
|
|
219
|
+
const waiting = pending.current;
|
|
220
|
+
if (!now || waiting === null || mode.current !== "visible") return;
|
|
221
|
+
pending.current = null;
|
|
222
|
+
// A load overtaken by a refresh of the SAME thread still showed these
|
|
223
|
+
// messages (they stay on screen until the newer load lands, and after it
|
|
224
|
+
// fails), so they are marked; a load from another thread is not.
|
|
225
|
+
if (waiting.client === client.current) void markRead(waiting);
|
|
226
|
+
},
|
|
227
|
+
[mode, markRead, client],
|
|
228
|
+
);
|
|
229
|
+
|
|
230
|
+
return { markShown, onVisibleChange };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Load on mount and on every signal; ignore a load something newer overtook; mark read what a load showed. */
|
|
234
|
+
function useLoader(options: UseChatThreadOptions, update: Update): Loader {
|
|
235
|
+
const { client, refreshSignal } = options;
|
|
236
|
+
const generation = useRef(0);
|
|
237
|
+
const onUnread = useLatest(options.onUnreadChange);
|
|
238
|
+
const { markShown, onVisibleChange } = useMarkRead(options, onUnread);
|
|
239
|
+
|
|
240
|
+
const load = useCallback(async () => {
|
|
241
|
+
const mine = ++generation.current;
|
|
242
|
+
const isCurrent = () => mine === generation.current;
|
|
243
|
+
let payload: ChatThreadPayload;
|
|
244
|
+
try {
|
|
245
|
+
payload = await client.load();
|
|
246
|
+
} catch (error) {
|
|
247
|
+
if (isCurrent()) update(client, (previous) => afterLoadFailure(previous, error));
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if (!isCurrent()) return;
|
|
251
|
+
update(client, (previous) => afterLoad(previous, payload));
|
|
252
|
+
report(onUnread, payload.unread);
|
|
253
|
+
await markShown({ payload, isCurrent, client });
|
|
254
|
+
}, [client, update, markShown, onUnread]);
|
|
255
|
+
|
|
256
|
+
useEffect(() => {
|
|
257
|
+
void load();
|
|
258
|
+
// Whatever is still in flight belongs to a thread or a signal that has moved on.
|
|
259
|
+
return () => {
|
|
260
|
+
generation.current += 1;
|
|
261
|
+
};
|
|
262
|
+
}, [load, refreshSignal]);
|
|
263
|
+
|
|
264
|
+
return { load, onVisibleChange };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export function useChatThread(options: UseChatThreadOptions): ChatThreadControls {
|
|
268
|
+
const { client } = options;
|
|
269
|
+
const { state, update, latest } = useOwnedState(client);
|
|
270
|
+
const { load, onVisibleChange } = useLoader(options, update);
|
|
271
|
+
|
|
272
|
+
const deliver = useCallback(
|
|
273
|
+
async (input: ChatSendInput): Promise<boolean> => {
|
|
274
|
+
update(client, (previous) => ({ ...previous, sending: true, sendFailure: null }));
|
|
275
|
+
try {
|
|
276
|
+
const message = await client.send(input);
|
|
277
|
+
update(client, (previous) => ({
|
|
278
|
+
...previous,
|
|
279
|
+
sending: false,
|
|
280
|
+
payload: previous.payload ? { ...previous.payload, messages: mergeMessages(previous.payload.messages, [message]) } : null,
|
|
281
|
+
}));
|
|
282
|
+
return true;
|
|
283
|
+
} catch (error) {
|
|
284
|
+
update(client, (previous) => afterSendFailure(previous, error));
|
|
285
|
+
if (outdates(error) && latest.current === client) void load();
|
|
286
|
+
return false;
|
|
287
|
+
}
|
|
288
|
+
},
|
|
289
|
+
[client, update, load, latest],
|
|
290
|
+
);
|
|
291
|
+
|
|
292
|
+
const send = useCallback((text: string) => deliver({ body: text }), [deliver]);
|
|
293
|
+
const sendQuickReply = useCallback((key: string) => deliver({ quickReply: key }), [deliver]);
|
|
294
|
+
const reload = useCallback(() => {
|
|
295
|
+
update(client, (previous) => (previous.payload ? previous : { ...previous, phase: "loading", loadFailure: null }));
|
|
296
|
+
void load();
|
|
297
|
+
}, [client, update, load]);
|
|
298
|
+
|
|
299
|
+
const visible = state.owner === client ? state : fresh(client);
|
|
300
|
+
const seen = options.autoMarkRead === "visible" ? { onVisibleChange } : {};
|
|
301
|
+
return { ...visibleOf(visible), send, sendQuickReply, reload, ...seen };
|
|
302
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The readings of a message the contact-info scanners look at: the text
|
|
3
|
+
* normalised once, then widened with the host's vocabulary. Lives apart from
|
|
4
|
+
* the scanners (`contact.ts`) so each file stays one idea.
|
|
5
|
+
*
|
|
6
|
+
* {@link fold} is the normalisation: NFKC (full-width and mathematical forms
|
|
7
|
+
* become ASCII), format and private-use characters dropped (zero-width
|
|
8
|
+
* joiners, soft hyphens, BOMs, bidi controls), lowercased, combining marks
|
|
9
|
+
* dropped (accents, the keycap enclosure U+20E3, emoji variation selectors),
|
|
10
|
+
* every decimal digit of any script mapped to ASCII, the common Cyrillic and
|
|
11
|
+
* Greek look-alikes of Latin letters mapped to the Latin letter, and the full
|
|
12
|
+
* stops of other scripts mapped to `.`.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** Host vocabulary that widens the generic patterns. All optional. */
|
|
16
|
+
export interface ContactVocabulary {
|
|
17
|
+
/**
|
|
18
|
+
* Spelled digits, word → digit (`{ nine: "9" }`), folded before the scans.
|
|
19
|
+
* A word is folded when it stands alone OR when a whole run of letters is
|
|
20
|
+
* nothing but such words glued together (`nineeightseven`) — never inside
|
|
21
|
+
* an ordinary word, so `ninety` stays a word.
|
|
22
|
+
*/
|
|
23
|
+
readonly numberWords?: Readonly<Record<string, string>>;
|
|
24
|
+
/** Words standing in for `@` in an address (`["at"]`). Count only toward an e-mail, never a handle. */
|
|
25
|
+
readonly atWords?: readonly string[];
|
|
26
|
+
/** Words standing in for `.` in an address or a domain (`["dot"]`). Count only before a known top-level domain. */
|
|
27
|
+
readonly dotWords?: readonly string[];
|
|
28
|
+
/**
|
|
29
|
+
* Anything else that means "reach me elsewhere" — app names, slang. The
|
|
30
|
+
* host's flags are kept (`u` included) and `i` added; `g`/`y` are dropped so
|
|
31
|
+
* a call never depends on the previous one. Each runs against the raw text,
|
|
32
|
+
* the normalised text, and a copy where runs of single letters are joined
|
|
33
|
+
* (`w h a t s` → `whats`), so an accented pattern and a plain one both work.
|
|
34
|
+
*/
|
|
35
|
+
readonly extraPatterns?: readonly RegExp[];
|
|
36
|
+
/**
|
|
37
|
+
* Spans that legitimately carry numbers — an address unit (`apt 1204`), a
|
|
38
|
+
* lot, a room — blanked before the phone scan, so a street number and a unit
|
|
39
|
+
* number do not add up to eight digits. Matched against the normalised text
|
|
40
|
+
* (lowercase, no accents). A match counts as ONE digit, and only when it
|
|
41
|
+
* holds at most five digits, is not followed straight away by a digit and
|
|
42
|
+
* not preceded straight away by a run of five or more — so a host pattern
|
|
43
|
+
* can never swallow a phone number's tail.
|
|
44
|
+
*/
|
|
45
|
+
readonly neutralPatterns?: readonly RegExp[];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Private-use stand-ins for the host's at/dot words: user input is stripped of private-use characters first, so these cannot be typed. */
|
|
49
|
+
export const AT_MARK = "\uE001";
|
|
50
|
+
export const DOT_MARK = "\uE000";
|
|
51
|
+
|
|
52
|
+
const INVISIBLE = /[\p{Cf}\p{Co}]/gu;
|
|
53
|
+
const MARKS = /\p{M}+/gu;
|
|
54
|
+
const DECIMAL_DIGIT = /\p{Nd}/u;
|
|
55
|
+
const NON_ASCII_DIGIT = /[^\P{Nd}0-9]/gu;
|
|
56
|
+
const LETTER_RUN = /\p{L}+/gu;
|
|
57
|
+
/** Longer letter runs are left alone, so a pathological host vocabulary cannot make the token match slow. */
|
|
58
|
+
const MAX_NUMBER_TOKEN = 80;
|
|
59
|
+
|
|
60
|
+
/** Cyrillic then Greek look-alikes, and the Latin letter each passes for. */
|
|
61
|
+
const CONFUSABLE_FROM = [
|
|
62
|
+
..."\u0430\u0435\u043E\u0440\u0441\u0443\u0445\u0456\u0458\u0455\u0501\u0261\u043A\u043C\u043D\u0442\u0432",
|
|
63
|
+
..."\u03BF\u03B1\u03B5\u03B9\u03BA\u03BD\u03C1\u03C4\u03C5\u03C7",
|
|
64
|
+
];
|
|
65
|
+
const CONFUSABLE_TO = [..."aeopcyxijsdgkmhtb", ..."oaeikvptux"];
|
|
66
|
+
const CONFUSABLES = new Map(CONFUSABLE_FROM.map((from, index) => [from, CONFUSABLE_TO[index] ?? from]));
|
|
67
|
+
const CONFUSABLE = new RegExp(`[${CONFUSABLE_FROM.join("")}]`, "gu");
|
|
68
|
+
/** Full stops of other scripts and dot-like punctuation (ideographic, half-width, middle dot, bullets, Lisu, Armenian, Arabic), read as `.`. */
|
|
69
|
+
const DOT_LOOKALIKE = /[\u3002\uFF61\u00B7\u2027\u2219\u2022\uA4F8\u0589\u06D4]/g;
|
|
70
|
+
|
|
71
|
+
/** An override or isolate opening (LRO, RLO, LRI, RLI, FSI), and the run it governs up to PDF, PDI or the end of the line. */
|
|
72
|
+
const BIDI_OPENING = /[\u202D\u202E\u2066-\u2068]/;
|
|
73
|
+
const BIDI_RUN = /[\u202D\u202E\u2066-\u2068]([^\u202C\u2069\n]*)/g;
|
|
74
|
+
|
|
75
|
+
/** `(at)`, `[dot]`, `{@}`, `( <at-word> )` — a bracketed stand-in is deliberate, so it becomes the symbol itself. */
|
|
76
|
+
const BRACKETED = new RegExp(`(?<!\\s)\\s*[([{<]\\s*(at|dot|@|\\.|${AT_MARK}|${DOT_MARK})\\s*[)\\]}>]\\s*`, "g");
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Three or more single letters in a row, one to three separators apart, line
|
|
80
|
+
* breaks included: `w h a t s`, `z-a-p`, `z` / `a` / `p` on three lines.
|
|
81
|
+
* `e a casa` is two, so ordinary text is left alone.
|
|
82
|
+
*/
|
|
83
|
+
const SINGLE_LETTER_RUN = /(?<![\p{L}\p{N}])\p{L}(?![\p{L}\p{N}])(?:[^\p{L}\p{N}]{1,3}\p{L}(?![\p{L}\p{N}])){2,}/gu;
|
|
84
|
+
const NON_LETTER = /[^\p{L}]+/gu;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The value of a decimal digit in any script. Unicode lays every `Nd` script
|
|
88
|
+
* out as a contiguous 0–9 run, so the value is the distance from the start of
|
|
89
|
+
* the run (modulo ten, for scripts whose runs sit back to back).
|
|
90
|
+
*/
|
|
91
|
+
function asciiDigit(char: string): string {
|
|
92
|
+
const code = char.codePointAt(0) ?? 0;
|
|
93
|
+
let zero = code;
|
|
94
|
+
while (DECIMAL_DIGIT.test(String.fromCodePoint(zero - 1))) zero -= 1;
|
|
95
|
+
return String((code - zero) % 10);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The text as every scanner reads it, before any host word is applied. */
|
|
99
|
+
function fold(text: string): string {
|
|
100
|
+
return text
|
|
101
|
+
.normalize("NFKC")
|
|
102
|
+
.replace(INVISIBLE, "")
|
|
103
|
+
.toLowerCase()
|
|
104
|
+
.normalize("NFD")
|
|
105
|
+
.replace(MARKS, "")
|
|
106
|
+
.replace(NON_ASCII_DIGIT, asciiDigit)
|
|
107
|
+
.replace(CONFUSABLE, (char) => CONFUSABLES.get(char) ?? char)
|
|
108
|
+
.replace(DOT_LOOKALIKE, ".");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function escapeRegExp(text: string): string {
|
|
112
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** An alternation of the folded words, longest first so `uma` wins over `um`. */
|
|
116
|
+
function alternation(words: readonly string[]): string {
|
|
117
|
+
return [...new Set(words.map(fold))]
|
|
118
|
+
.filter((word) => word.length > 0)
|
|
119
|
+
.sort((a, b) => b.length - a.length)
|
|
120
|
+
.map(escapeRegExp)
|
|
121
|
+
.join("|");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function wordPattern(words: readonly string[] | undefined): RegExp | null {
|
|
125
|
+
const alternatives = alternation(words ?? []);
|
|
126
|
+
return alternatives ? new RegExp(`\\b(?:${alternatives})\\b`, "g") : null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
interface NumberFolder {
|
|
130
|
+
readonly whole: RegExp;
|
|
131
|
+
readonly part: RegExp;
|
|
132
|
+
readonly digits: ReadonlyMap<string, string>;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function numberFolder(numberWords: Readonly<Record<string, string>> | undefined): NumberFolder | null {
|
|
136
|
+
const entries = Object.entries(numberWords ?? {});
|
|
137
|
+
const alternatives = alternation(entries.map(([word]) => word));
|
|
138
|
+
if (!alternatives) return null;
|
|
139
|
+
return {
|
|
140
|
+
whole: new RegExp(`^(?:${alternatives})+$`),
|
|
141
|
+
part: new RegExp(alternatives, "g"),
|
|
142
|
+
digits: new Map(entries.map(([word, digit]) => [fold(word), digit])),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The host's pattern with its own flags, `i` added, and `g`/`y` replaced by `extra` (`""` to test, `"g"` to scan). */
|
|
147
|
+
function hostPattern(pattern: RegExp, extra: "" | "g"): RegExp {
|
|
148
|
+
const flags = pattern.flags.replace(/[giy]/g, "");
|
|
149
|
+
return new RegExp(pattern.source, `${flags}i${extra}`);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** A vocabulary turned into regexes once, not once per message. */
|
|
153
|
+
export interface CompiledVocabulary {
|
|
154
|
+
readonly numbers: NumberFolder | null;
|
|
155
|
+
readonly atWords: RegExp | null;
|
|
156
|
+
readonly dotWords: RegExp | null;
|
|
157
|
+
readonly extra: readonly RegExp[];
|
|
158
|
+
/** Global, for scanning with `matchAll`. */
|
|
159
|
+
readonly neutral: readonly RegExp[];
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const compiledCache = new WeakMap<ContactVocabulary, CompiledVocabulary>();
|
|
163
|
+
|
|
164
|
+
export function compile(vocabulary: ContactVocabulary): CompiledVocabulary {
|
|
165
|
+
const cached = compiledCache.get(vocabulary);
|
|
166
|
+
if (cached) return cached;
|
|
167
|
+
const compiled: CompiledVocabulary = {
|
|
168
|
+
numbers: numberFolder(vocabulary.numberWords),
|
|
169
|
+
atWords: wordPattern(vocabulary.atWords),
|
|
170
|
+
dotWords: wordPattern(vocabulary.dotWords),
|
|
171
|
+
extra: (vocabulary.extraPatterns ?? []).map((pattern) => hostPattern(pattern, "")),
|
|
172
|
+
neutral: (vocabulary.neutralPatterns ?? []).map((pattern) => hostPattern(pattern, "g")),
|
|
173
|
+
};
|
|
174
|
+
compiledCache.set(vocabulary, compiled);
|
|
175
|
+
return compiled;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Turn a letter run into digits only when it is nothing BUT number words — `noveoito` yes, `novembro` no. */
|
|
179
|
+
function foldNumberWords(text: string, numbers: NumberFolder | null): string {
|
|
180
|
+
if (!numbers) return text;
|
|
181
|
+
return text.replace(LETTER_RUN, (token) =>
|
|
182
|
+
token.length <= MAX_NUMBER_TOKEN && numbers.whole.test(token)
|
|
183
|
+
? token.replace(numbers.part, (word) => numbers.digits.get(word) ?? word)
|
|
184
|
+
: token,
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function replaceWith(text: string, pattern: RegExp | null, by: string): string {
|
|
189
|
+
return pattern ? text.replace(pattern, by) : text;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function unbracket(_match: string, symbol: string): string {
|
|
193
|
+
return symbol === "at" || symbol === "@" || symbol === AT_MARK ? "@" : ".";
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** One reading of a message. */
|
|
197
|
+
export interface View {
|
|
198
|
+
readonly raw: string;
|
|
199
|
+
readonly folded: string;
|
|
200
|
+
/** `folded` with number words as digits and the host's at/dot words as private marks. */
|
|
201
|
+
readonly scan: string;
|
|
202
|
+
/** `scan` with runs of single letters joined — read by the host's extra patterns only. */
|
|
203
|
+
readonly collapsed: string;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function view(raw: string, compiled: CompiledVocabulary): View {
|
|
207
|
+
const folded = fold(raw);
|
|
208
|
+
let scan = foldNumberWords(folded, compiled.numbers);
|
|
209
|
+
scan = replaceWith(scan, compiled.atWords, AT_MARK);
|
|
210
|
+
scan = replaceWith(scan, compiled.dotWords, DOT_MARK);
|
|
211
|
+
scan = scan.replace(BRACKETED, unbracket);
|
|
212
|
+
const collapsed = scan.replace(SINGLE_LETTER_RUN, (run) => run.replace(NON_LETTER, ""));
|
|
213
|
+
return { raw, folded, scan, collapsed };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* The text roughly as DISPLAYED when it carries a bidi override or isolate:
|
|
218
|
+
* each run after an opening control reversed, up to its closing control or
|
|
219
|
+
* the end of the line. `null` when there is none. Reversing an LTR override
|
|
220
|
+
* too is deliberate — an extra reading can only add a refusal, never hide one.
|
|
221
|
+
*/
|
|
222
|
+
function visualOrder(text: string): string | null {
|
|
223
|
+
if (!BIDI_OPENING.test(text)) return null;
|
|
224
|
+
return text.replace(BIDI_RUN, (_match, run: string) => [...run].reverse().join(""));
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Every reading of a message: as stored, and as displayed when bidi controls reorder it. */
|
|
228
|
+
export function views(raw: string, compiled: CompiledVocabulary): readonly View[] {
|
|
229
|
+
const visual = visualOrder(raw);
|
|
230
|
+
return visual === null ? [view(raw, compiled)] : [view(raw, compiled), view(visual, compiled)];
|
|
231
|
+
}
|