@12-apps/chat 0.0.0-stage → 1.0.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.
Files changed (42) hide show
  1. package/README.md +153 -2
  2. package/package.json +95 -4
  3. package/prisma/chat.prisma +59 -0
  4. package/prisma/migrations/20261002120000_add_chat/migration.sql +41 -0
  5. package/scripts/sync-chat-schema.mjs +64 -0
  6. package/src/client/api.ts +146 -0
  7. package/src/client/assert.ts +7 -0
  8. package/src/client/copy.ts +43 -0
  9. package/src/client/en-US.ts +17 -0
  10. package/src/client/index.ts +17 -0
  11. package/src/client/locales.ts +12 -0
  12. package/src/client/pt-BR.ts +17 -0
  13. package/src/client/use-chat-thread.ts +232 -0
  14. package/src/core/contact-views.ts +231 -0
  15. package/src/core/contact.ts +333 -0
  16. package/src/core/errors.ts +9 -0
  17. package/src/core/types.ts +82 -0
  18. package/src/index.ts +26 -0
  19. package/src/manifest/index.ts +20 -0
  20. package/src/manifest/native.ts +13 -0
  21. package/src/manifest/server.ts +14 -0
  22. package/src/manifest/web.ts +14 -0
  23. package/src/native/composer.tsx +52 -0
  24. package/src/native/index.ts +16 -0
  25. package/src/native/layout.tsx +60 -0
  26. package/src/react/composer.tsx +48 -0
  27. package/src/react/index.ts +15 -0
  28. package/src/react/layout.tsx +36 -0
  29. package/src/server/context.ts +228 -0
  30. package/src/server/copy.ts +73 -0
  31. package/src/server/db.ts +87 -0
  32. package/src/server/en-US.ts +14 -0
  33. package/src/server/handler.ts +110 -0
  34. package/src/server/index.ts +34 -0
  35. package/src/server/locales.ts +12 -0
  36. package/src/server/pt-BR.ts +14 -0
  37. package/src/server/rate.ts +34 -0
  38. package/src/server/reads.ts +52 -0
  39. package/src/server/routes.ts +119 -0
  40. package/src/server/send.ts +203 -0
  41. package/src/ui/surface.tsx +83 -0
  42. package/src/ui/thread-view.tsx +198 -0
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The web composer: the design system's field and button, wired with the
3
+ * DOM's change event. Enter sends; Shift+Enter is left to the field, and so is
4
+ * the Enter that confirms an IME composition.
5
+ *
6
+ * The field stays enabled while a message is in flight: disabling it would
7
+ * drop focus after every Enter. Only the send action is gated (here, and again
8
+ * in the thread's submit).
9
+ */
10
+
11
+ import { Button } from "@12-apps/ui/form/Button";
12
+ import { Input } from "@12-apps/ui/form/Input";
13
+ import { Box } from "@12-apps/ui/layout/Box";
14
+ import type { JSX, KeyboardEvent } from "react";
15
+
16
+ import type { ChatComposerProps } from "../ui/thread-view";
17
+
18
+ export function WebComposer(props: ChatComposerProps): JSX.Element {
19
+ const onKeyDown = (event: KeyboardEvent<HTMLInputElement>): void => {
20
+ if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return;
21
+ event.preventDefault();
22
+ props.onSubmit();
23
+ };
24
+ return (
25
+ <Box direction="row" gap={1} align="center">
26
+ <Box flex={1}>
27
+ <Input
28
+ fullWidth
29
+ value={props.value}
30
+ placeholder={props.copy.placeholder}
31
+ aria-label={props.copy.placeholder}
32
+ maxLength={props.maxLength}
33
+ onChange={(event) => props.onChange(event.target.value)}
34
+ onKeyDown={onKeyDown}
35
+ testID="chat-input"
36
+ />
37
+ </Box>
38
+ <Button
39
+ variant="solid"
40
+ onClick={props.onSubmit}
41
+ disabled={props.sending || props.value.trim() === ""}
42
+ testID="chat-send"
43
+ >
44
+ {props.sending ? props.copy.sending : props.copy.send}
45
+ </Button>
46
+ </Box>
47
+ );
48
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `@12-apps/chat/react` — the web host's surface: `createWebChat(config) →
3
+ * { ChatThread }`. One component per thread; the host decides where it sits.
4
+ * Members are component TYPES — build once per config (the wiring binder does).
5
+ */
6
+
7
+ import { buildChatSurface, type ChatSurface, type ChatSurfaceConfig } from "../ui/surface";
8
+ import { WebComposer } from "./composer";
9
+ import { WebFrame, WebMessageList } from "./layout";
10
+
11
+ export function createWebChat(config: ChatSurfaceConfig): ChatSurface {
12
+ return buildChatSurface(config, { Frame: WebFrame, MessageList: WebMessageList, Composer: WebComposer });
13
+ }
14
+
15
+ export type { ChatSurface, ChatSurfaceConfig, ChatThreadProps } from "../ui/surface";
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The web thread's frame and message list. The list is the design system's
3
+ * scroll region, bounded to a share of the viewport so a long thread scrolls
4
+ * inside it while the composer stays in view, and it follows the newest
5
+ * message whenever one is added (a send, a reload that brought one in).
6
+ */
7
+
8
+ import { ScrollArea } from "@12-apps/ui/layout/ScrollArea";
9
+ import { Stack } from "@12-apps/ui/layout/Stack";
10
+ import { useEffect, useRef, type JSX } from "react";
11
+
12
+ import type { ChatFrameProps, ChatMessageListProps } from "../ui/thread-view";
13
+
14
+ /** The list's ceiling: relative to the viewport, so it holds at every width and zoom. */
15
+ const LIST_MAX_HEIGHT = "60vh";
16
+
17
+ export function WebFrame(props: ChatFrameProps): JSX.Element {
18
+ return (
19
+ <Stack gap={2} testID={props.testID}>
20
+ {props.children}
21
+ </Stack>
22
+ );
23
+ }
24
+
25
+ export function WebMessageList(props: ChatMessageListProps): JSX.Element {
26
+ const viewport = useRef<HTMLDivElement | null>(null);
27
+ useEffect(() => {
28
+ const element = viewport.current;
29
+ if (element) element.scrollTop = element.scrollHeight;
30
+ }, [props.scrollKey]);
31
+ return (
32
+ <ScrollArea regionLabel={props.label} scrollRef={viewport} height="auto" maxHeight={LIST_MAX_HEIGHT} testId={props.testID}>
33
+ <Stack gap={1}>{props.children}</Stack>
34
+ </ScrollArea>
35
+ );
36
+ }
@@ -0,0 +1,228 @@
1
+ /**
2
+ * The server surface's vocabulary: the host seams, the per-role rules, and the
3
+ * wire-route twins.
4
+ *
5
+ * The request/response/route shapes are RESTATED rather than imported from
6
+ * `@12-apps/wiring` (the structural-twin move), so the contract package stays
7
+ * a type-only devDependency. The manifest suite pins that they still fit.
8
+ */
9
+
10
+ import { CONTACT_KINDS, type ContactKind, type ContactVocabulary } from "../core/contact";
11
+ import { ChatConfigError } from "../core/errors";
12
+ import type { ChatQuickReply } from "../core/types";
13
+ import { missingCopy, resolveCopy, SERVER_COPY_KEYS, type ChatCopySource, type ChatServerCopy } from "./copy";
14
+ import type { ChatDb } from "./db";
15
+
16
+ /**
17
+ * Who the caller is IN THIS THREAD, decided by the host for every request.
18
+ * The host's whole policy lives behind it: whether this person is a party to
19
+ * the thread at all (no ⇒ `null` ⇒ 404), under which role, and whether that
20
+ * role may still write. The package never learns why.
21
+ */
22
+ export interface ChatAccess {
23
+ /** Partition key — threads never cross it. */
24
+ readonly tenantId: string;
25
+ /** What the thread is about, in a string the host composes (`job:123`). */
26
+ readonly threadKey: string;
27
+ /** The caller's role key; must be a key of the config's `roles`. */
28
+ readonly role: string;
29
+ /** The person, kept on their messages for moderation; never sent to the others. */
30
+ readonly authorId: string;
31
+ /**
32
+ * Whose read marker this caller moves. A person's own id, or — for a role
33
+ * whose members read as one (a team) — one shared id for the whole role.
34
+ */
35
+ readonly readerId: string;
36
+ /** False ⇒ read-only: the window closed, the role lost the thread, … */
37
+ readonly canWrite: boolean;
38
+ }
39
+
40
+ /** How one role behaves in every thread. All REQUIRED: these are host decisions. */
41
+ export interface ChatRoleConfig {
42
+ /** The only name the thread shows for this role's messages. */
43
+ readonly label: string;
44
+ /**
45
+ * True when every member of the role speaks as one (a team): their messages
46
+ * all read as `mine` to each of them, and `readerId` is expected to be shared.
47
+ */
48
+ readonly shared: boolean;
49
+ /** Longest message, in characters. */
50
+ readonly maxLength: number;
51
+ /** False ⇒ quick replies only. */
52
+ readonly freeText: boolean;
53
+ /** Contact information this role may not send; `[]` for none. */
54
+ readonly blockContact: readonly ContactKind[];
55
+ /** Canned lines this role may send with one tap; `[]` for none. */
56
+ readonly quickReplies: readonly ChatQuickReply[];
57
+ /** At most `max` messages per `windowMs`, per role and author, per thread. */
58
+ readonly rateLimit: { readonly max: number; readonly windowMs: number };
59
+ }
60
+
61
+ /** What a committed message tells the host — notifications and live hints are the host's. */
62
+ export interface ChatMessageEvent {
63
+ readonly tenantId: string;
64
+ readonly threadKey: string;
65
+ readonly message: {
66
+ readonly id: string;
67
+ readonly role: string;
68
+ readonly label: string;
69
+ readonly authorId: string;
70
+ readonly body: string;
71
+ /** The quick reply's key when one was sent, else `null` (free text). */
72
+ readonly quickKey: string | null;
73
+ readonly createdAt: string;
74
+ };
75
+ }
76
+
77
+ /** A send the content rules refused — so the host can see who keeps trying. */
78
+ export interface ChatRefusalEvent {
79
+ readonly tenantId: string;
80
+ readonly threadKey: string;
81
+ readonly role: string;
82
+ readonly authorId: string;
83
+ readonly code: "contact_info";
84
+ /** What the filter found. Never the text: the host decides what it keeps. */
85
+ readonly kinds: readonly ContactKind[];
86
+ }
87
+
88
+ export interface ChatServerConfig<TActor = unknown> {
89
+ /** The host's Prisma client (or a structural twin), lazily. */
90
+ db: () => ChatDb | Promise<ChatDb>;
91
+ /** Resolve the caller's place in the thread the request names, or `null`. */
92
+ authorize: (request: ChatRequest<TActor>) => Promise<ChatAccess | null>;
93
+ /** Every role a thread may hold, keyed by the host's role key. */
94
+ roles: Readonly<Record<string, ChatRoleConfig>>;
95
+ /** Every sentence the routes answer with — host vocabulary, or a per-request resolver. */
96
+ copy: ChatCopySource<ChatServerCopy>;
97
+ /** Host words that widen the contact-info filter (spelled digits, app names, …). */
98
+ contactVocabulary?: ContactVocabulary;
99
+ /**
100
+ * After a message commits — the host's notifications and live hints. Run in
101
+ * the background: the send answers without waiting for it, and a throw or
102
+ * rejection goes to `onError`, never to the sender.
103
+ */
104
+ onMessage?: (event: ChatMessageEvent) => void | Promise<void>;
105
+ /** After the content rules refuse a send. Background, like `onMessage`. */
106
+ onRefused?: (event: ChatRefusalEvent) => void | Promise<void>;
107
+ /** Where a failing background hook is reported (`hook` names which). Silent when absent. */
108
+ onError?: (error: unknown, context: { readonly hook: string }) => void;
109
+ /**
110
+ * How much of the author's own recent free text the contact rules read
111
+ * with a draft, so a number split over several messages is still caught.
112
+ * Defaults to the last 12 messages within 10 minutes.
113
+ */
114
+ contactLookback?: { readonly messages: number; readonly windowMs: number };
115
+ /** How many messages a thread answers with, newest kept. Defaults to 200. */
116
+ historyLimit?: number;
117
+ /** Test seam. */
118
+ clock?: () => Date;
119
+ }
120
+
121
+ // ─── WireRoute twins ─────────────────────────────────────────────────────────
122
+
123
+ export interface ChatRequest<TActor = unknown> {
124
+ actor: TActor;
125
+ params: Record<string, string | undefined>;
126
+ query: Record<string, string | undefined>;
127
+ body?: unknown;
128
+ /** BCP-47, set by the host's adapter; absent means "answer in the configured words". */
129
+ locale?: string;
130
+ }
131
+
132
+ export interface ChatResponse {
133
+ status: number;
134
+ body: unknown;
135
+ }
136
+
137
+ export interface ChatRoute<TActor = unknown> {
138
+ method: "GET" | "POST";
139
+ /** Mount-relative. */
140
+ path: string;
141
+ handle(request: ChatRequest<TActor>): Promise<ChatResponse>;
142
+ }
143
+
144
+ // ─── Assembly checks ─────────────────────────────────────────────────────────
145
+
146
+ const isPositiveInt = (value: unknown): boolean => Number.isInteger(value) && (value as number) > 0;
147
+
148
+ /** Each rule a role must satisfy, with the message naming the field it broke. */
149
+ const ROLE_RULES: readonly [(role: ChatRoleConfig) => boolean, string][] = [
150
+ [(role) => typeof role?.label === "string" && role.label.trim() !== "", "label is required."],
151
+ [(role) => typeof role.shared === "boolean", "shared must be a boolean."],
152
+ [(role) => isPositiveInt(role.maxLength), "maxLength must be a positive integer."],
153
+ [(role) => typeof role.freeText === "boolean", "freeText must be a boolean."],
154
+ [
155
+ (role) => Array.isArray(role.blockContact) && role.blockContact.every((kind) => CONTACT_KINDS.includes(kind)),
156
+ `blockContact must list only ${CONTACT_KINDS.join(", ")}.`,
157
+ ],
158
+ [(role) => isPositiveInt(role.rateLimit?.max) && isPositiveInt(role.rateLimit?.windowMs), "rateLimit needs a positive max and windowMs."],
159
+ ];
160
+
161
+ /**
162
+ * The longest message a role that blocks contact info may send. The filter
163
+ * reads the draft with the author's recent text on every send, so its cost
164
+ * grows with the length; a few thousand characters is no chat message.
165
+ */
166
+ const MAX_FILTERED_LENGTH = 2000;
167
+
168
+ function assertRole(key: string, role: ChatRoleConfig): void {
169
+ for (const [holds, message] of ROLE_RULES) {
170
+ if (!holds(role)) throw new ChatConfigError(`roles.${key}.${message}`);
171
+ }
172
+ if (role.blockContact.length > 0 && role.maxLength > MAX_FILTERED_LENGTH) {
173
+ throw new ChatConfigError(`roles.${key}.maxLength may be at most ${MAX_FILTERED_LENGTH} while blockContact is set.`);
174
+ }
175
+ assertQuickReplies(`roles.${key}`, role);
176
+ }
177
+
178
+ function assertQuickReply(at: string, reply: ChatQuickReply, seen: Set<string>): void {
179
+ if (typeof reply?.key !== "string" || reply.key.trim() === "") throw new ChatConfigError(`${at}.quickReplies needs a key on every entry.`);
180
+ if (typeof reply.text !== "string" || reply.text.trim() === "") throw new ChatConfigError(`${at}.quickReplies.${reply.key} needs text.`);
181
+ if (seen.has(reply.key)) throw new ChatConfigError(`${at}.quickReplies repeats "${reply.key}".`);
182
+ seen.add(reply.key);
183
+ }
184
+
185
+ function assertQuickReplies(at: string, role: ChatRoleConfig): void {
186
+ if (!Array.isArray(role.quickReplies)) throw new ChatConfigError(`${at}.quickReplies must be a list.`);
187
+ const seen = new Set<string>();
188
+ role.quickReplies.forEach((reply) => assertQuickReply(at, reply, seen));
189
+ if (!role.freeText && role.quickReplies.length === 0) {
190
+ throw new ChatConfigError(`${at} allows no free text and offers no quick replies — it could never write.`);
191
+ }
192
+ }
193
+
194
+ const HOOKS = ["onMessage", "onRefused", "onError"] as const;
195
+
196
+ function assertOptionalSettings(config: ChatServerConfig): void {
197
+ for (const hook of HOOKS) {
198
+ // A hook that is not a function would throw inside the background run, where nobody sees it.
199
+ if (config[hook] !== undefined && typeof config[hook] !== "function") throw new ChatConfigError(`${hook} must be a function.`);
200
+ }
201
+ if (config.historyLimit !== undefined && !isPositiveInt(config.historyLimit)) {
202
+ throw new ChatConfigError("historyLimit must be a positive integer.");
203
+ }
204
+ assertLookback(config.contactLookback);
205
+ }
206
+
207
+ function assertLookback(lookback: ChatServerConfig["contactLookback"]): void {
208
+ if (lookback === undefined) return;
209
+ if (!(isPositiveInt(lookback?.messages) && isPositiveInt(lookback?.windowMs))) {
210
+ throw new ChatConfigError("contactLookback needs a positive messages and windowMs.");
211
+ }
212
+ }
213
+
214
+ /** Throws {@link ChatConfigError} at assembly, where the call site is. */
215
+ export function assertChatServerConfig(config: ChatServerConfig): void {
216
+ if (typeof config?.db !== "function") throw new ChatConfigError("db must be a function returning the client.");
217
+ if (typeof config.authorize !== "function") throw new ChatConfigError("authorize is required — who may see which thread is the host's.");
218
+ const keys = Object.keys(config.roles ?? {});
219
+ if (keys.length === 0) throw new ChatConfigError("roles must declare at least one role.");
220
+ keys.forEach((key) => assertRole(key, config.roles[key] as ChatRoleConfig));
221
+ assertOptionalSettings(config);
222
+ const missing = missingCopy(resolveCopy(config.copy, undefined), SERVER_COPY_KEYS);
223
+ if (missing.length > 0) {
224
+ throw new ChatConfigError(
225
+ `copy is required, with every key non-blank — missing: ${missing.join(", ")}. A host passes a named pack by hand.`,
226
+ );
227
+ }
228
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Every sentence the routes answer a HUMAN with — required host config, no
3
+ * defaults (the copy-portability doctrine). The machine half of a refusal —
4
+ * status and `error` code — stays the package's; only the words are the host's.
5
+ *
6
+ * A host imports a named pack (`./pt-BR`, `./en-US`) and passes it by hand,
7
+ * or passes a RESOLVER to answer each request in its reader's language.
8
+ */
9
+ export interface ChatServerCopy {
10
+ /** 404 — no thread the caller may see (not a participant, or no such subject). */
11
+ readonly notFound: string;
12
+ /** 403 — the caller may read but no longer write. */
13
+ readonly closed: string;
14
+ /** 422 — the body is not the JSON object the route reads. */
15
+ readonly invalidBody: string;
16
+ /** 422 — nothing to send. */
17
+ readonly empty: string;
18
+ /** 422 — longer than the role allows; `{max}` is replaced by the limit. */
19
+ readonly tooLong: string;
20
+ /** 422 — the role may only send quick replies. */
21
+ readonly freeTextDisabled: string;
22
+ /** 422 — the quick reply key is not one the role offers. */
23
+ readonly unknownQuickReply: string;
24
+ /** 422 — the text carries a phone number, address, link or handle. */
25
+ readonly contactInfo: string;
26
+ /** 429 — too many messages in a short time. */
27
+ readonly rateLimited: string;
28
+ }
29
+
30
+ export const SERVER_COPY_KEYS: readonly (keyof ChatServerCopy)[] = [
31
+ "notFound",
32
+ "closed",
33
+ "invalidBody",
34
+ "empty",
35
+ "tooLong",
36
+ "freeTextDisabled",
37
+ "unknownQuickReply",
38
+ "contactInfo",
39
+ "rateLimited",
40
+ ];
41
+
42
+ /** Declared structurally (no `@12-apps/i18n` dependency): a raw tag in, words out. */
43
+ export type ChatCopyResolver<T> = (context: { readonly locale?: string | null }) => T;
44
+
45
+ /** The words, or a resolver choosing them per request. */
46
+ export type ChatCopySource<T> = T | ChatCopyResolver<T>;
47
+
48
+ export function resolveCopy<T>(source: ChatCopySource<T>, locale: string | undefined): T {
49
+ return typeof source === "function" ? (source as ChatCopyResolver<T>)({ locale }) : source;
50
+ }
51
+
52
+ /**
53
+ * The words for one request. A resolver that has no complete pack for the
54
+ * reader's locale (it answers `undefined`, or a pack with a blank key) falls
55
+ * back to the configured words — the ones assembly checked, with no locale —
56
+ * rather than failing the request it was only meant to phrase.
57
+ */
58
+ export function resolveCompleteCopy(source: ChatCopySource<ChatServerCopy>, locale: string | undefined): ChatServerCopy {
59
+ const words = resolveCopy(source, locale);
60
+ if (locale === undefined || missingCopy(words, SERVER_COPY_KEYS).length === 0) return words;
61
+ return resolveCopy(source, undefined);
62
+ }
63
+
64
+ /** Keys absent or blank — checked at assembly. */
65
+ export function missingCopy<T extends object>(copy: T | undefined, keys: readonly (keyof T)[]): string[] {
66
+ if (copy === undefined || copy === null) return keys.map(String);
67
+ return keys
68
+ .filter((key) => {
69
+ const value = copy[key];
70
+ return typeof value !== "string" || value.trim() === "";
71
+ })
72
+ .map(String);
73
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * The database seam: exactly the delegate calls this package makes, shaped so
3
+ * a generated Prisma client carrying the `prisma/chat.prisma` models satisfies
4
+ * it structurally — and so a test fake implementing the interface behaves the
5
+ * same. Nothing here may rely on a client-specific error code.
6
+ */
7
+
8
+ export interface ChatThreadRow {
9
+ readonly id: string;
10
+ readonly tenantId: string;
11
+ readonly threadKey: string;
12
+ readonly createdAt: Date;
13
+ readonly lastMessageAt: Date | null;
14
+ }
15
+
16
+ export interface ChatMessageRow {
17
+ readonly id: string;
18
+ readonly threadId: string;
19
+ readonly tenantId: string;
20
+ readonly authorRole: string;
21
+ readonly authorId: string;
22
+ readonly body: string;
23
+ readonly quickKey: string | null;
24
+ readonly createdAt: Date;
25
+ }
26
+
27
+ export interface ChatReadMarkerRow {
28
+ readonly id: string;
29
+ readonly threadId: string;
30
+ readonly role: string;
31
+ readonly readerId: string;
32
+ readonly lastReadAt: Date;
33
+ }
34
+
35
+ type ThreadKeyWhere = { tenantId_threadKey: { tenantId: string; threadKey: string } };
36
+ type MarkerKeyWhere = { threadId_role_readerId: { threadId: string; role: string; readerId: string } };
37
+
38
+ export interface ChatDb {
39
+ chatThread: {
40
+ findUnique(args: { where: ThreadKeyWhere }): Promise<ChatThreadRow | null>;
41
+ upsert(args: {
42
+ where: ThreadKeyWhere;
43
+ create: { tenantId: string; threadKey: string };
44
+ update: Record<string, never>;
45
+ }): Promise<ChatThreadRow>;
46
+ findMany(args: { where: { tenantId: string; threadKey: { in: string[] } } }): Promise<ChatThreadRow[]>;
47
+ update(args: { where: { id: string }; data: { lastMessageAt: Date } }): Promise<unknown>;
48
+ };
49
+ chatMessage: {
50
+ findMany(args: {
51
+ where: {
52
+ threadId: string;
53
+ authorRole?: string;
54
+ authorId?: string;
55
+ quickKey?: null;
56
+ createdAt?: { gt: Date };
57
+ };
58
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }];
59
+ take: number;
60
+ }): Promise<ChatMessageRow[]>;
61
+ create(args: {
62
+ data: {
63
+ threadId: string;
64
+ tenantId: string;
65
+ authorRole: string;
66
+ authorId: string;
67
+ body: string;
68
+ quickKey: string | null;
69
+ createdAt: Date;
70
+ };
71
+ }): Promise<ChatMessageRow>;
72
+ count(args: {
73
+ where: { threadId: string; authorRole: { not: string }; createdAt?: { gt: Date } };
74
+ }): Promise<number>;
75
+ };
76
+ chatReadMarker: {
77
+ findUnique(args: { where: MarkerKeyWhere }): Promise<ChatReadMarkerRow | null>;
78
+ findMany(args: {
79
+ where: { threadId: { in: string[] }; role: string; readerId: string };
80
+ }): Promise<ChatReadMarkerRow[]>;
81
+ upsert(args: {
82
+ where: MarkerKeyWhere;
83
+ create: { threadId: string; role: string; readerId: string; lastReadAt: Date };
84
+ update: { lastReadAt: Date };
85
+ }): Promise<ChatReadMarkerRow>;
86
+ };
87
+ }
@@ -0,0 +1,14 @@
1
+ import type { ChatServerCopy } from "./copy";
2
+
3
+ /** The routes' sentences in US English — pass by hand, never a default. */
4
+ export const EN_US_CHAT_SERVER_COPY: ChatServerCopy = {
5
+ notFound: "Conversation not found.",
6
+ closed: "This conversation is closed. You can still read the messages.",
7
+ invalidBody: "We could not read that message.",
8
+ empty: "Write a message before sending.",
9
+ tooLong: "A message can be up to {max} characters.",
10
+ freeTextDisabled: "Use one of the quick replies.",
11
+ unknownQuickReply: "That quick reply is not available.",
12
+ contactInfo: "For safety, phone numbers, e-mail addresses, links and social profiles cannot be sent.",
13
+ rateLimited: "Too many messages in a row. Wait a moment and try again.",
14
+ };
@@ -0,0 +1,110 @@
1
+ /**
2
+ * What every route shares: the response shapes, resolving the caller's place
3
+ * in the thread, finding the thread row, and the wire form of a message.
4
+ *
5
+ * Every 2xx answers `{ data }` — the house envelope the other server packages
6
+ * answer with — and every refusal answers `{ error, message }`: the machine
7
+ * code is the package's, the sentence is the host's.
8
+ */
9
+
10
+ import type { ChatWireMessage } from "../core/types";
11
+ import type { ChatAccess, ChatRequest, ChatResponse, ChatRoleConfig, ChatServerConfig } from "./context";
12
+ import { resolveCompleteCopy, type ChatServerCopy } from "./copy";
13
+ import type { ChatDb, ChatMessageRow, ChatThreadRow } from "./db";
14
+
15
+ export function success(status: number, data: unknown): ChatResponse {
16
+ return { status, body: { data } };
17
+ }
18
+
19
+ export function failure(status: number, error: string, message: string): ChatResponse {
20
+ return { status, body: { error, message } };
21
+ }
22
+
23
+ export interface Resolved {
24
+ readonly access: ChatAccess;
25
+ readonly role: ChatRoleConfig;
26
+ readonly copy: ChatServerCopy;
27
+ }
28
+
29
+ /** The caller's place in the thread, or the refusal to answer with. */
30
+ export async function resolve<TActor>(
31
+ config: ChatServerConfig<TActor>,
32
+ request: ChatRequest<TActor>,
33
+ ): Promise<Resolved | ChatResponse> {
34
+ const copy = resolveCompleteCopy(config.copy, request.locale);
35
+ const access = await config.authorize(request);
36
+ if (!access) return failure(404, "not_found", copy.notFound);
37
+ const role = config.roles[access.role];
38
+ if (!role) throw new Error(`@12-apps/chat: authorize answered role "${access.role}", which roles does not declare.`);
39
+ return { access, role, copy };
40
+ }
41
+
42
+ export function isResponse(value: object): value is ChatResponse {
43
+ return "status" in value;
44
+ }
45
+
46
+ function threadKeyOf(access: ChatAccess): { tenantId_threadKey: { tenantId: string; threadKey: string } } {
47
+ return { tenantId_threadKey: { tenantId: access.tenantId, threadKey: access.threadKey } };
48
+ }
49
+
50
+ /** The thread, if anyone ever wrote in it. Reading never creates one. */
51
+ export function findThread(db: ChatDb, access: ChatAccess): Promise<ChatThreadRow | null> {
52
+ return db.chatThread.findUnique({ where: threadKeyOf(access) });
53
+ }
54
+
55
+ /**
56
+ * The thread, created on the first message. Two first messages at the same
57
+ * instant race on the unique key, and the loser's client throws — whatever
58
+ * its error code (the seam relies on none): the winner's row is then there,
59
+ * so read it back, and rethrow only when it is not.
60
+ */
61
+ export async function openThread(db: ChatDb, access: ChatAccess): Promise<ChatThreadRow> {
62
+ try {
63
+ return await db.chatThread.upsert({
64
+ where: threadKeyOf(access),
65
+ create: { tenantId: access.tenantId, threadKey: access.threadKey },
66
+ update: {},
67
+ });
68
+ } catch (error) {
69
+ const winner = await findThread(db, access);
70
+ if (winner) return winner;
71
+ throw error;
72
+ }
73
+ }
74
+
75
+ function isMine(row: ChatMessageRow, access: ChatAccess, role: ChatRoleConfig): boolean {
76
+ if (row.authorRole !== access.role) return false;
77
+ return role.shared || row.authorId === access.authorId;
78
+ }
79
+
80
+ export function wireMessage<TActor>(config: ChatServerConfig<TActor>, row: ChatMessageRow, resolved: Resolved): ChatWireMessage {
81
+ return {
82
+ id: row.id,
83
+ role: row.authorRole,
84
+ // A role the host has since removed still shows as its key, never a blank.
85
+ label: config.roles[row.authorRole]?.label ?? row.authorRole,
86
+ mine: isMine(row, resolved.access, resolved.role),
87
+ body: row.body,
88
+ createdAt: row.createdAt.toISOString(),
89
+ };
90
+ }
91
+
92
+ /**
93
+ * Run a host hook without making the caller wait for it or fail by it: the
94
+ * message is committed, and a push provider's latency or outage is the
95
+ * host's. A throw (or a rejected promise) goes to `onError`, when given.
96
+ */
97
+ export function inBackground<TActor>(config: ChatServerConfig<TActor>, hook: string, run: () => unknown): void {
98
+ const report = (error: unknown): void => {
99
+ try {
100
+ config.onError?.(error, { hook });
101
+ } catch {
102
+ // A failing error reporter has nowhere left to report to.
103
+ }
104
+ };
105
+ try {
106
+ void Promise.resolve(run()).catch(report);
107
+ } catch (error) {
108
+ report(error);
109
+ }
110
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The one thing this package exposes to a BACKEND host: `createApiChat(config)
3
+ * → { routes }`, plus `createChatReads` for the host's own lists.
4
+ *
5
+ * Routes are framework-neutral descriptors (the wiring `WireRoute` twin). A
6
+ * host mounts one set per audience — each with its own `authorize`, which is
7
+ * where every rule about who is in which thread lives — under a path that
8
+ * names the subject. The package never learns what a thread is about.
9
+ */
10
+
11
+ import { assertChatServerConfig, type ChatRoute, type ChatServerConfig } from "./context";
12
+ import { chatRoutes } from "./routes";
13
+
14
+ export function createApiChat<TActor = unknown>(config: ChatServerConfig<TActor>): { routes: ChatRoute<TActor>[] } {
15
+ assertChatServerConfig(config as ChatServerConfig);
16
+ return { routes: chatRoutes(config) };
17
+ }
18
+
19
+ export { createChatReads, type ChatReads, type UnreadCountsQuery } from "./reads";
20
+ export type {
21
+ ChatAccess,
22
+ ChatMessageEvent,
23
+ ChatRefusalEvent,
24
+ ChatRequest,
25
+ ChatResponse,
26
+ ChatRoleConfig,
27
+ ChatRoute,
28
+ ChatServerConfig,
29
+ } from "./context";
30
+ export type { ChatDb, ChatMessageRow, ChatReadMarkerRow, ChatThreadRow } from "./db";
31
+ export type { ChatCopyResolver, ChatCopySource, ChatServerCopy } from "./copy";
32
+ export { PT_BR_CHAT_SERVER_COPY } from "./pt-BR";
33
+ export { EN_US_CHAT_SERVER_COPY } from "./en-US";
34
+ export { CHAT_SERVER_COPY } from "./locales";
@@ -0,0 +1,12 @@
1
+ import type { ChatServerCopy } from "./copy";
2
+ import { EN_US_CHAT_SERVER_COPY } from "./en-US";
3
+ import { PT_BR_CHAT_SERVER_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 — what a host hands its i18n resolver. */
9
+ export const CHAT_SERVER_COPY = {
10
+ "pt-BR": PT_BR_CHAT_SERVER_COPY,
11
+ "en-US": EN_US_CHAT_SERVER_COPY,
12
+ } as const satisfies LocalePack<ChatServerCopy>;