@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.
Files changed (44) hide show
  1. package/README.md +194 -2
  2. package/package.json +95 -4
  3. package/prisma/chat.prisma +61 -0
  4. package/prisma/migrations/20261002120000_add_chat/migration.sql +41 -0
  5. package/prisma/migrations/20261003120000_add_chat_thread_activity_index/migration.sql +2 -0
  6. package/scripts/sync-chat-schema.mjs +64 -0
  7. package/src/client/api.ts +146 -0
  8. package/src/client/assert.ts +7 -0
  9. package/src/client/copy.ts +43 -0
  10. package/src/client/en-US.ts +17 -0
  11. package/src/client/index.ts +18 -0
  12. package/src/client/locales.ts +12 -0
  13. package/src/client/pt-BR.ts +17 -0
  14. package/src/client/use-chat-thread.ts +302 -0
  15. package/src/core/contact-views.ts +231 -0
  16. package/src/core/contact.ts +333 -0
  17. package/src/core/errors.ts +9 -0
  18. package/src/core/types.ts +82 -0
  19. package/src/index.ts +26 -0
  20. package/src/manifest/index.ts +20 -0
  21. package/src/manifest/native.ts +13 -0
  22. package/src/manifest/server.ts +14 -0
  23. package/src/manifest/web.ts +14 -0
  24. package/src/native/composer.tsx +52 -0
  25. package/src/native/index.ts +21 -0
  26. package/src/native/layout.tsx +96 -0
  27. package/src/react/composer.tsx +58 -0
  28. package/src/react/index.ts +20 -0
  29. package/src/react/layout.tsx +103 -0
  30. package/src/server/context.ts +228 -0
  31. package/src/server/copy.ts +73 -0
  32. package/src/server/db.ts +87 -0
  33. package/src/server/en-US.ts +14 -0
  34. package/src/server/handler.ts +110 -0
  35. package/src/server/index.ts +34 -0
  36. package/src/server/locales.ts +12 -0
  37. package/src/server/pt-BR.ts +14 -0
  38. package/src/server/rate.ts +34 -0
  39. package/src/server/reads.ts +52 -0
  40. package/src/server/routes.ts +119 -0
  41. package/src/server/send.ts +203 -0
  42. package/src/ui/bubble-tint.ts +19 -0
  43. package/src/ui/surface.tsx +87 -0
  44. package/src/ui/thread-view.tsx +225 -0
package/README.md CHANGED
@@ -1,3 +1,195 @@
1
- # Temporary Holding Version
1
+ # @12-apps/chat
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Conversation threads between the parties to one piece of work, where each
4
+ party is known to the others **only by its role's label**. No person id, name
5
+ or contact detail crosses the wire. Mount the routes once per audience, and the
6
+ same thread screen renders in a web SPA and in a React Native app.
7
+
8
+ ## What is in the box
9
+
10
+ | subpath | what |
11
+ |---|---|
12
+ | `./server` | `createApiChat(config) → { routes }`: framework-neutral `GET /`, `POST /messages`, `POST /read`. `createChatReads` gives unread badges for the host's own lists. |
13
+ | `./client` | `createChatClient` and `useChatThread`, both platform-free: for a host drawing its own UI. |
14
+ | `./react` | `createWebChat(config) → { ChatThread }`: the web surface. |
15
+ | `./native` | `createNativeChat(config) → { ChatThread }`: the React Native surface. |
16
+ | `./manifest*` | wiring manifests for the server, web and native runtimes. |
17
+ | `prisma/` | `chat.prisma` (`ChatThread`, `ChatMessage`, `ChatReadMarker`) plus its migrations. `pnpm --filter @12-apps/chat prisma:sync` copies the partial into a host schema folder. |
18
+
19
+ ## The host decides who is in a thread
20
+
21
+ ```ts
22
+ const { routes } = createApiChat({
23
+ db: () => getPrismaClient(),
24
+ authorize: async (request) => {
25
+ // Is this caller a party to the thread the URL names? Under which role?
26
+ // May that role still write? Answer null for "no such thread for you" (404).
27
+ return { tenantId, threadKey: `job:${request.params.id}`, role: "client",
28
+ authorId: user.id, readerId: user.id, canWrite: true };
29
+ },
30
+ roles: {
31
+ client: { label: "Client", shared: false, maxLength: 500, freeText: true,
32
+ blockContact: [], quickReplies: [], rateLimit: { max: 20, windowMs: 60_000 } },
33
+ agent: { label: "Agent", shared: false, maxLength: 160, freeText: true,
34
+ blockContact: ["phone", "email", "url", "handle"],
35
+ quickReplies: [{ key: "arrived", text: "I have arrived." }],
36
+ rateLimit: { max: 6, windowMs: 60_000 } },
37
+ team: { label: "Team", shared: true, maxLength: 1000, freeText: true,
38
+ blockContact: [], quickReplies: [], rateLimit: { max: 30, windowMs: 60_000 } },
39
+ },
40
+ copy: EN_US_CHAT_SERVER_COPY, // or a per-request resolver
41
+ contactVocabulary: { numberWords: { nine: "9" }, atWords: ["at"] },
42
+ onMessage: async (event) => { /* notify, publish a live hint */ },
43
+ onRefused: async (event) => { /* who keeps trying to pass contact info */ },
44
+ onError: (error, { hook }) => logger.error(`chat ${hook} failed`, error),
45
+ });
46
+ ```
47
+
48
+ `db` may return the client or a promise of it. `onMessage` and `onRefused`
49
+ run in the background: the send answers without waiting for a push
50
+ provider, and a hook that throws or rejects is reported to `onError`, never
51
+ to the sender.
52
+
53
+ All of this belongs to the host: the write window, which role a caller holds,
54
+ the labels, and the quick replies' words. The package owns the rest:
55
+ - the role's content rules;
56
+ - the contact-info filter, which also reads the host's dodge-words;
57
+ - the per-author rate limit;
58
+ - what a message looks like on the wire.
59
+
60
+ ### The wire
61
+
62
+ Every 2xx answers `{ data }`: `GET /` gives `{ thread, messages, unread }`,
63
+ `POST /messages` gives `{ message }` (201), and `POST /read` gives
64
+ `{ unread }`. A refusal answers `{ error, message }`, where `error` is the
65
+ package's code (`contact_info`, `closed`, `rate_limited`, …) and `message` is
66
+ the host's sentence. No person id ever crosses it: authors show only as their
67
+ role's label.
68
+
69
+ `POST /read` takes `{ upTo }`, the `createdAt` of the newest message the
70
+ reader was actually shown. The marker never moves backwards and never past
71
+ now, so a message that arrived after the screen loaded stays unread. Reading
72
+ never creates a thread row; the first message does.
73
+
74
+ ### The contact filter
75
+
76
+ It reads the text after Unicode normalisation: full-width and other-script
77
+ digits, invisible characters, look-alike Cyrillic and Greek letters, a
78
+ bidi-reversed run, and spelled-out digits from the host's
79
+ `contactVocabulary`. A phone number is 8 digits within any 16 characters,
80
+ whatever separates them. Clock times, amounts after a currency symbol, and
81
+ spans matching the host's `neutralPatterns` (address units like
82
+ `apto 1204`, at most 4 digits each) are set aside first, so an address with
83
+ an apartment number passes; a set-aside span still counts as at least one
84
+ digit. An amount is set aside only when it is a price as a courier writes
85
+ one, at most four integer digits (`85,90`, `1.250,00`), so `$54321`,
86
+ `$98765,43` and `$8.765.432` are not. A CEP, a full date, or a
87
+ five-digit street number before a unit is refused; that is the documented
88
+ price.
89
+
90
+ Across messages it reads only a contiguous chain: the same author's recent
91
+ free text (`contactLookback`, default the last 12 messages within 10
92
+ minutes) joins the draft while each message ends where the next begins with
93
+ a digit, a dot or an at-sign. A number trickled one digit per message is
94
+ one number; `Apto 1204` followed by `Chego 19:30` is two lines. One author's
95
+ sends to a thread are checked one at a time in each process, so parallel
96
+ requests cannot pass the rule against each other's absence (several
97
+ replicas can still interleave). Bidi controls are removed before a message
98
+ is stored, so the screen shows what the filter read.
99
+
100
+ Every attempt spends a rate-limit slot, including a refused one, so probing
101
+ the filter runs out of attempts. It is a deterrent, not a guarantee: a
102
+ person determined to pass a number can always find an encoding no filter
103
+ reads, and `onRefused` is how the host sees who keeps trying. Known misses,
104
+ each the price of letting an ordinary line through: a word between the
105
+ pieces of a number (`98765 e 4321`), a number of nine or ten digits split
106
+ by one address unit or one price (`98 765 ap 4321`, `9876 $5.432` — a
107
+ space inside the first group is exactly how a street number is written),
108
+ both pieces behind a unit or a price (`apto 98765 apto 4321`), a chain broken
109
+ by a message of something else, and a picture. A mobile with its area code
110
+ (eleven digits) cannot hide behind one span. A host that wants `arroba` to count
111
+ toward a social handle adds it to `extraPatterns`.
112
+
113
+ ### Retention
114
+
115
+ Messages keep `author_id` for moderation, and the package ships no delete
116
+ or anonymise API: retention (LGPD, GDPR) is the host's. The
117
+ `chat_messages (tenant_id, created_at)` index is there for the host's sweep.
118
+ `created_at` comes from the app process's clock, and messages in the same
119
+ millisecond are ordered by id.
120
+
121
+ ### Indexes for the host's own queries
122
+
123
+ `chat_threads (tenant_id, last_message_at)` (1.1.0, migration
124
+ `20261003120000_add_chat_thread_activity_index`) serves a host badge that
125
+ counts the threads with activity since a moment (`tenant_id = ? AND
126
+ last_message_at >= ?`). A host that copies the package's migrations picks it
127
+ up with its next sync; it is additive, so it needs no release choreography.
128
+
129
+ ## The screen
130
+
131
+ ```tsx
132
+ const { ChatThread } = createWebChat({ fetch: credentialedFetch, copy: EN_US_CHAT_UI_COPY, formatTime });
133
+ <ChatThread endpoint={`/api/jobs/${id}/chat`} refreshSignal={liveTick} onUnreadChange={setBadge} />
134
+ ```
135
+
136
+ The thread marks itself read up to the newest message it showed, and
137
+ `onUnreadChange` then gets the server's remaining count (normally 0). Pass
138
+ `autoMarkRead={false}` to mount it hidden only for its unread count.
139
+
140
+ `autoMarkRead="visible"` is for a thread that may be mounted out of sight (the
141
+ lower half of a drawer): a load's unread messages wait until the message list
142
+ is on screen, and are marked read then; a load that finds unread while the
143
+ list is already on screen marks at once. On the web the list is watched with
144
+ an `IntersectionObserver` (on screen from its first pixel); a browser without
145
+ one marks at once, as `true` does. On native a mounted list counts as on
146
+ screen. A host testing in jsdom stubs `IntersectionObserver` to drive it.
147
+ A host drawing its own list with `useChatThread({ autoMarkRead: "visible" })`
148
+ reports it through `controls.onVisibleChange(visible)`.
149
+
150
+ A read-only thread (`canWrite: false`) with no messages shows only the closed
151
+ notice: no empty-thread invitation to write the first message, and no list.
152
+
153
+ Own messages and the others' are told apart by their surface: the reader's
154
+ own bubbles are a tint of the theme's `palette.primary.main` (8% in light
155
+ mode, 16% in dark), the others' sit on the paper surface. The label is body
156
+ text on the own tint and secondary text on paper; the primary colour itself
157
+ reads under 4.5:1 on its own tint, so it is not used for text there. A bubble is at most 80% of the thread wide (and 60
158
+ characters, on the web).
159
+
160
+ Accessibility: the list is a polite live region (`aria-live` on the web,
161
+ `accessibilityLiveRegion` on native), so an arriving message is announced.
162
+ On the web a click on the send button hands focus back to the field, and the
163
+ role's `maxLength` sits on the `<input>` itself.
164
+
165
+ Layout:
166
+ - **Web:** the messages sit in ui's `ScrollArea` (up to 60% of the viewport
167
+ tall), which keeps the newest in view. `ScrollArea` needs `ResizeObserver`,
168
+ so a host testing in jsdom stubs it.
169
+ - **Native:** the thread is a ui `Screen` with keyboard avoidance and its own
170
+ `ScrollView`. Mount it in a parent with a bounded height (a flex-1 view, or
171
+ `Screen scroll={false}`), never inside another ScrollView. Pass
172
+ `keyboardOffset` (dp) when a header sits above it.
173
+
174
+ `createNativeChat` takes the same config. Both surfaces draw the thread from
175
+ `@12-apps/ui` primitives using only their cross-platform props, so a React
176
+ Native bundle resolves each primitive to its native twin through ui's
177
+ `react-native` export condition. What differs per platform is a slot of the
178
+ internal `ChatPlatform`, the one place platform styling lives:
179
+
180
+ | slot | receives | web | native |
181
+ |---|---|---|---|
182
+ | `Frame` | the list and the writing area | a `Stack` | a keyboard-avoiding `Screen` |
183
+ | `MessageList` | the bubbles, `label`, `scrollKey`, `onVisibleChange?` | `ScrollArea` + `IntersectionObserver` | `ScrollView`, visible on mount |
184
+ | `Bubble` | `{ mine, children }` | ui `Box` with `sx` (tint, `min(80%, 60ch)`) | ui `Box` with `style` (tint, `80%`) |
185
+ | `Composer` | the controlled field and its send action | `Input` + Enter | `Input` + the keyboard's send key |
186
+
187
+ The package opens no socket. Bump `refreshSignal` when your live channel says
188
+ the thread moved.
189
+
190
+ ## Copy
191
+
192
+ Every sentence is required config, with no defaults. `PT_BR_*` and `EN_US_*`
193
+ packs ship for the routes (`CHAT_SERVER_COPY`) and the screen
194
+ (`CHAT_UI_COPY`); pass one by hand. Role labels are part of the role config,
195
+ so every surface shows the same name for a role.
package/package.json CHANGED
@@ -1,6 +1,97 @@
1
1
  {
2
2
  "name": "@12-apps/chat",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "type": "module",
5
+ "sideEffects": false,
6
+ "description": "Conversation threads between the parties to one piece of work, each shown only by a host-chosen role label: framework-neutral HTTP routes with per-role write windows, a contact-info filter and quick replies, plus one thread screen built from @12-apps/ui primitives for web hosts and React Native hosts alike.",
7
+ "exports": {
8
+ ".": "./src/index.ts",
9
+ "./server": "./src/server/index.ts",
10
+ "./client": "./src/client/index.ts",
11
+ "./react": "./src/react/index.ts",
12
+ "./native": "./src/native/index.ts",
13
+ "./manifest": "./src/manifest/index.ts",
14
+ "./manifest/server": "./src/manifest/server.ts",
15
+ "./manifest/web": "./src/manifest/web.ts",
16
+ "./manifest/native": "./src/manifest/native.ts",
17
+ "./package.json": "./package.json"
18
+ },
19
+ "scripts": {
20
+ "clean": "rm -rf node_modules coverage coverage-native dist",
21
+ "test": "node ../../scripts/vitest-with-teardown.mjs run && vitest run --config vitest.native.config.ts",
22
+ "test:watch": "vitest watch",
23
+ "lint": "eslint src --max-warnings 0",
24
+ "check-types": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json",
25
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json",
26
+ "prisma:sync": "node scripts/sync-chat-schema.mjs",
27
+ "prisma:sync:check": "node scripts/sync-chat-schema.mjs --check"
28
+ },
29
+ "peerDependencies": {
30
+ "@12-apps/ui": ">=6.59.0",
31
+ "@12-apps/wiring": ">=1.17.0",
32
+ "react": "^18.0.0 || ^19.0.0",
33
+ "react-native": ">=0.79.0"
34
+ },
35
+ "peerDependenciesMeta": {
36
+ "@12-apps/ui": {
37
+ "optional": true
38
+ },
39
+ "@12-apps/wiring": {
40
+ "optional": true
41
+ },
42
+ "react": {
43
+ "optional": true
44
+ },
45
+ "react-native": {
46
+ "optional": true
47
+ }
48
+ },
49
+ "devDependencies": {
50
+ "@12-apps/eslint-config": "^1.22.0",
51
+ "@12-apps/typescript-config": "^1.21.0",
52
+ "@12-apps/ui": "^6.62.0",
53
+ "@12-apps/wiring": "^1.17.0",
54
+ "@testing-library/react": "^16.3.1",
55
+ "@types/node": "^22.10.6",
56
+ "@types/react": "19.2.2",
57
+ "@types/react-dom": "^19.2.0",
58
+ "@vitejs/plugin-react": "^4.5.2",
59
+ "eslint": "^9.39.1",
60
+ "eslint-plugin-test-flakiness": "^1.4.0",
61
+ "jsdom": "^26.1.0",
62
+ "react": "19.2.0",
63
+ "react-dom": "19.2.0",
64
+ "react-native": "0.83.1",
65
+ "react-native-web": "0.20.0",
66
+ "typescript": "^5.9.2",
67
+ "vitest": "^3.2.4"
68
+ },
69
+ "wiring": {
70
+ "db": {
71
+ "partial": "prisma/chat.prisma",
72
+ "migrations": "prisma/migrations"
73
+ }
74
+ },
75
+ "engines": {
76
+ "node": ">=22.0.0"
77
+ },
78
+ "license": "MIT",
79
+ "publishConfig": {
80
+ "registry": "https://registry.npmjs.org",
81
+ "access": "public"
82
+ },
83
+ "repository": {
84
+ "type": "git",
85
+ "url": "git+https://github.com/12-apps/shared-packages.git",
86
+ "directory": "packages/chat"
87
+ },
88
+ "files": [
89
+ "src",
90
+ "prisma",
91
+ "scripts",
92
+ "*.md",
93
+ "!eslint.config.js",
94
+ "!**/__tests__/**",
95
+ "!**/*.test.*"
96
+ ]
97
+ }
@@ -0,0 +1,61 @@
1
+ // ─────────────────────────────────────────────────────────────────────────────
2
+ // OWNED BY @12-apps/chat — the host's multi-file schema folder holds only a
3
+ // COPY of this file (created/verified by `pnpm --filter @12-apps/chat
4
+ // prisma:sync`): conversation threads live here, in the package, never in the
5
+ // application.
6
+ //
7
+ // Self-contained on purpose: `tenant_id`, `thread_key` and `author_id` are
8
+ // by-value String columns with NO foreign key into any host table, so the
9
+ // models work in every repo without schema coupling. What a thread is ABOUT is
10
+ // the host's business, carried in `thread_key` (a string the host composes);
11
+ // who may read or write it is decided by the host for every request.
12
+ // ─────────────────────────────────────────────────────────────────────────────
13
+
14
+ // One conversation. Created lazily, the first time a participant opens it.
15
+ model ChatThread {
16
+ id String @id @default(uuid())
17
+ tenantId String @map("tenant_id")
18
+ threadKey String @map("thread_key")
19
+ createdAt DateTime @default(now()) @map("created_at")
20
+ lastMessageAt DateTime? @map("last_message_at")
21
+ messages ChatMessage[]
22
+ readMarkers ChatReadMarker[]
23
+
24
+ @@unique([tenantId, threadKey])
25
+ // A host's "threads with activity since" badge query: tenant, then recency.
26
+ @@index([tenantId, lastMessageAt])
27
+ @@map("chat_threads")
28
+ }
29
+
30
+ // One message. `author_role` is the host's role key (what the thread SHOWS as
31
+ // the author's name, via the host's label); `author_id` is the person behind
32
+ // it, kept for moderation and never sent to the other participants.
33
+ model ChatMessage {
34
+ id String @id @default(uuid())
35
+ threadId String @map("thread_id")
36
+ tenantId String @map("tenant_id")
37
+ authorRole String @map("author_role")
38
+ authorId String @map("author_id")
39
+ body String
40
+ quickKey String? @map("quick_key")
41
+ createdAt DateTime @default(now()) @map("created_at")
42
+ thread ChatThread @relation(fields: [threadId], references: [id], onDelete: Cascade)
43
+
44
+ @@index([threadId, createdAt])
45
+ @@index([tenantId, createdAt])
46
+ @@map("chat_messages")
47
+ }
48
+
49
+ // How far one reader has read a thread. `reader_id` is the host's choice: a
50
+ // person, or one shared id for a role whose members read as one (a team).
51
+ model ChatReadMarker {
52
+ id String @id @default(uuid())
53
+ threadId String @map("thread_id")
54
+ role String
55
+ readerId String @map("reader_id")
56
+ lastReadAt DateTime @map("last_read_at")
57
+ thread ChatThread @relation(fields: [threadId], references: [id], onDelete: Cascade)
58
+
59
+ @@unique([threadId, role, readerId])
60
+ @@map("chat_read_markers")
61
+ }
@@ -0,0 +1,41 @@
1
+ -- @12-apps/chat: conversation threads, their messages, and read markers.
2
+ CREATE TABLE "chat_threads" (
3
+ "id" TEXT NOT NULL,
4
+ "tenant_id" TEXT NOT NULL,
5
+ "thread_key" TEXT NOT NULL,
6
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
7
+ "last_message_at" TIMESTAMP(3),
8
+
9
+ CONSTRAINT "chat_threads_pkey" PRIMARY KEY ("id")
10
+ );
11
+
12
+ CREATE TABLE "chat_messages" (
13
+ "id" TEXT NOT NULL,
14
+ "thread_id" TEXT NOT NULL,
15
+ "tenant_id" TEXT NOT NULL,
16
+ "author_role" TEXT NOT NULL,
17
+ "author_id" TEXT NOT NULL,
18
+ "body" TEXT NOT NULL,
19
+ "quick_key" TEXT,
20
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
21
+
22
+ CONSTRAINT "chat_messages_pkey" PRIMARY KEY ("id")
23
+ );
24
+
25
+ CREATE TABLE "chat_read_markers" (
26
+ "id" TEXT NOT NULL,
27
+ "thread_id" TEXT NOT NULL,
28
+ "role" TEXT NOT NULL,
29
+ "reader_id" TEXT NOT NULL,
30
+ "last_read_at" TIMESTAMP(3) NOT NULL,
31
+
32
+ CONSTRAINT "chat_read_markers_pkey" PRIMARY KEY ("id")
33
+ );
34
+
35
+ CREATE UNIQUE INDEX "chat_threads_tenant_id_thread_key_key" ON "chat_threads"("tenant_id", "thread_key");
36
+ CREATE INDEX "chat_messages_thread_id_created_at_idx" ON "chat_messages"("thread_id", "created_at");
37
+ CREATE INDEX "chat_messages_tenant_id_created_at_idx" ON "chat_messages"("tenant_id", "created_at");
38
+ CREATE UNIQUE INDEX "chat_read_markers_thread_id_role_reader_id_key" ON "chat_read_markers"("thread_id", "role", "reader_id");
39
+
40
+ ALTER TABLE "chat_messages" ADD CONSTRAINT "chat_messages_thread_id_fkey" FOREIGN KEY ("thread_id") REFERENCES "chat_threads"("id") ON DELETE CASCADE ON UPDATE CASCADE;
41
+ ALTER TABLE "chat_read_markers" ADD CONSTRAINT "chat_read_markers_thread_id_fkey" FOREIGN KEY ("thread_id") REFERENCES "chat_threads"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,2 @@
1
+ -- @12-apps/chat: the index behind a host's "threads with activity since" query.
2
+ CREATE INDEX "chat_threads_tenant_id_last_message_at_idx" ON "chat_threads"("tenant_id", "last_message_at");
@@ -0,0 +1,64 @@
1
+ #!/usr/bin/env node
2
+ /* global console, process */
3
+ /**
4
+ * Copy this package's Prisma model PARTIAL into the host's schema folder.
5
+ *
6
+ * node scripts/sync-chat-schema.mjs [--check] [<host-schema-dir>]
7
+ *
8
+ * The partial is COPIED, never symlinked (the entity-lifecycle doctrine):
9
+ * `turbo prune` copies only what the dependency graph reaches, so a committed
10
+ * symlink dangles the moment the owning package is not a declared workspace
11
+ * dependency; `npm pack` SILENTLY DROPS symlinked entries from the tarball;
12
+ * and a SYMLINKED MIGRATION is silently skipped by Prisma.
13
+ *
14
+ * Only the schema partial. MIGRATIONS ARE NOT HANDLED HERE — the host
15
+ * discovers and copies them structurally, by looking for a `prisma/migrations`
16
+ * directory inside every installed `@12-apps/*` package (see
17
+ * packages/prisma/scripts/sync-prisma-plugins.mjs).
18
+ *
19
+ * Default host path follows the origin host layout
20
+ * (`packages/prisma/prisma/schema/`); another repo passes its own schema
21
+ * folder as the positional argument, or sets CHAT_HOST_SCHEMA_DIR.
22
+ */
23
+ import { copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
24
+ import { dirname, join } from 'node:path';
25
+ import { fileURLToPath } from 'node:url';
26
+
27
+ const LABEL = '[chat-schema]';
28
+ const RESYNC = 'pnpm --filter @12-apps/chat prisma:sync';
29
+
30
+ const HERE = dirname(fileURLToPath(import.meta.url));
31
+ const SOURCE = join(HERE, '../prisma/chat.prisma');
32
+
33
+ const args = process.argv.slice(2).filter((arg) => arg !== '--check');
34
+ const check = process.argv.includes('--check');
35
+ const hostSchemaDir =
36
+ args[0] ??
37
+ process.env.CHAT_HOST_SCHEMA_DIR ??
38
+ join(HERE, '../../prisma/prisma/schema');
39
+ const TARGET = join(hostSchemaDir, 'chat.prisma');
40
+
41
+ const source = readFileSync(SOURCE, 'utf8');
42
+ // `lstat` first: a symlink must be REPLACED, not read through. Reading
43
+ // through it would report "in sync" for a link whose bytes match — and a link
44
+ // is exactly what `npm pack` drops.
45
+ const stat = existsSync(TARGET) ? lstatSync(TARGET) : null;
46
+ const isPlainCopy = stat !== null && stat.isFile() && !stat.isSymbolicLink();
47
+ const target = isPlainCopy ? readFileSync(TARGET, 'utf8') : null;
48
+
49
+ if (source === target) {
50
+ console.log(`${LABEL} in sync.`);
51
+ } else if (check) {
52
+ console.error(
53
+ `${LABEL} DRIFT: ${TARGET} is not a byte-identical COPY of the ` +
54
+ `@12-apps/chat partial. Run "${RESYNC}" and commit the result.`,
55
+ );
56
+ process.exit(1);
57
+ } else {
58
+ mkdirSync(hostSchemaDir, { recursive: true });
59
+ // Unconditional: a DANGLING symlink reports existsSync=false, and copying
60
+ // through a live one would land the bytes at the link's target instead.
61
+ rmSync(TARGET, { force: true });
62
+ copyFileSync(SOURCE, TARGET);
63
+ console.log(`${LABEL} copied ${SOURCE} -> ${TARGET}.`);
64
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * The thread's HTTP client — platform-free, so the web and the native surface
3
+ * share it. The host supplies `fetch`: its credentials (a session cookie, a
4
+ * Bearer link) are the host's, and so is the base URL of the mounted routes.
5
+ *
6
+ * The wire is strict: every 2xx body is `{ data: X }`, every refusal
7
+ * `{ error, message }` with a 4xx status. A body that is not that shape is
8
+ * refused HERE, as a {@link ChatClientError} with `code: null` — so a broken
9
+ * adapter surfaces as a load or send failure, never as a crash while drawing.
10
+ */
11
+
12
+ import { CHAT_ERROR_CODES, type ChatErrorCode, type ChatThreadPayload, type ChatWireMessage } from "../core/types";
13
+
14
+ /** The subset of `fetch` this client uses — the platform's own, or a host wrapper. */
15
+ export type ChatFetch = (
16
+ url: string,
17
+ init: { method: "GET" | "POST"; headers: Record<string, string>; body?: string },
18
+ ) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>;
19
+
20
+ /**
21
+ * A refused or failed call. `status` 0 means the request never reached the
22
+ * server; a 2xx `status` with `code: null` means the body was not the wire shape.
23
+ */
24
+ export class ChatClientError extends Error {
25
+ readonly status: number;
26
+ readonly code: ChatErrorCode | null;
27
+ /** The server's own sentence for the refusal (host copy), when it sent one. */
28
+ readonly serverMessage: string | null;
29
+
30
+ constructor(status: number, code: ChatErrorCode | null, serverMessage: string | null) {
31
+ super(`chat request failed (${status}${code ? ` ${code}` : ""})`);
32
+ this.name = "ChatClientError";
33
+ this.status = status;
34
+ this.code = code;
35
+ this.serverMessage = serverMessage;
36
+ }
37
+ }
38
+
39
+ export type ChatSendInput = { readonly body: string } | { readonly quickReply: string };
40
+
41
+ export interface ChatClient {
42
+ load(): Promise<ChatThreadPayload>;
43
+ send(input: ChatSendInput): Promise<ChatWireMessage>;
44
+ /**
45
+ * Mark the thread read up to `upTo` — the `createdAt` of the newest message
46
+ * the viewer was SHOWN. Resolves to the unread count the server has left.
47
+ */
48
+ markRead(upTo: string): Promise<number>;
49
+ }
50
+
51
+ type Shape = Record<string, unknown>;
52
+
53
+ const isRecord = (value: unknown): value is Shape => typeof value === "object" && value !== null && !Array.isArray(value);
54
+
55
+ /**
56
+ * The refusal, when it is the package's own: a known code carries the
57
+ * host's sentence, which the screen may show. Anything else — a proxy's 502
58
+ * page, a framework's 500 with an internal `message` — is a bare failure.
59
+ */
60
+ function errorOf(status: number, body: unknown): ChatClientError {
61
+ const shaped = isRecord(body) ? body : {};
62
+ const code = CHAT_ERROR_CODES.find((known) => known === shaped.error) ?? null;
63
+ return new ChatClientError(status, code, code !== null && typeof shaped.message === "string" ? shaped.message : null);
64
+ }
65
+
66
+ const malformed = (status: number): ChatClientError => new ChatClientError(status, null, null);
67
+
68
+ function isMessage(value: unknown): value is ChatWireMessage {
69
+ if (!isRecord(value)) return false;
70
+ const strings = [value.id, value.role, value.label, value.body, value.createdAt].every((field) => typeof field === "string");
71
+ return strings && typeof value.mine === "boolean";
72
+ }
73
+
74
+ function isQuickReply(value: unknown): boolean {
75
+ return isRecord(value) && typeof value.key === "string" && typeof value.text === "string";
76
+ }
77
+
78
+ function isThread(value: unknown): boolean {
79
+ if (!isRecord(value) || !isRecord(value.me)) return false;
80
+ const flags = typeof value.canWrite === "boolean" && typeof value.freeText === "boolean";
81
+ return flags && typeof value.maxLength === "number" && Array.isArray(value.quickReplies) && value.quickReplies.every(isQuickReply);
82
+ }
83
+
84
+ function isPayload(value: unknown): value is ChatThreadPayload {
85
+ if (!isRecord(value) || !isThread(value.thread) || typeof value.unread !== "number") return false;
86
+ return Array.isArray(value.messages) && value.messages.every(isMessage);
87
+ }
88
+
89
+ /** The `X` of a `{ data: X }` body that passes `accept`, or a refusal carrying the response's status. */
90
+ function dataOf<T>(status: number, body: unknown, accept: (data: unknown) => data is T): T {
91
+ if (!isRecord(body) || !accept(body.data)) throw malformed(status);
92
+ return body.data;
93
+ }
94
+
95
+ const isSent = (data: unknown): data is { message: ChatWireMessage } => isRecord(data) && isMessage(data.message);
96
+ const isRead = (data: unknown): data is { unread: number } => isRecord(data) && typeof data.unread === "number";
97
+
98
+ /** Drop trailing `/`s with one backward scan — no regex to backtrack on. */
99
+ function trimTrailingSlashes(path: string): string {
100
+ let end = path.length;
101
+ while (end > 0 && path[end - 1] === "/") end -= 1;
102
+ return path.slice(0, end);
103
+ }
104
+
105
+ interface ChatResponse {
106
+ readonly status: number;
107
+ readonly body: unknown;
108
+ }
109
+
110
+ /**
111
+ * `endpoint` is the mount of the three routes for ONE thread
112
+ * (`…/threads/abc/chat`): `GET endpoint`, `POST endpoint/messages`,
113
+ * `POST endpoint/read`.
114
+ */
115
+ export function createChatClient(options: { fetch: ChatFetch; endpoint: string }): ChatClient {
116
+ const base = trimTrailingSlashes(options.endpoint);
117
+ const call = async (path: string, method: "GET" | "POST", payload?: unknown): Promise<ChatResponse> => {
118
+ let response: Awaited<ReturnType<ChatFetch>>;
119
+ try {
120
+ response = await options.fetch(`${base}${path}`, {
121
+ method,
122
+ headers: payload === undefined ? { Accept: "application/json" } : { Accept: "application/json", "Content-Type": "application/json" },
123
+ ...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
124
+ });
125
+ } catch {
126
+ throw new ChatClientError(0, null, null);
127
+ }
128
+ const body = await response.json().catch(() => null);
129
+ if (!response.ok) throw errorOf(response.status, body);
130
+ return { status: response.status, body };
131
+ };
132
+ return {
133
+ load: async () => {
134
+ const response = await call("", "GET");
135
+ return dataOf(response.status, response.body, isPayload);
136
+ },
137
+ send: async (input) => {
138
+ const response = await call("/messages", "POST", input);
139
+ return dataOf(response.status, response.body, isSent).message;
140
+ },
141
+ markRead: async (upTo) => {
142
+ const response = await call("/read", "POST", { upTo });
143
+ return dataOf(response.status, response.body, isRead).unread;
144
+ },
145
+ };
146
+ }
@@ -0,0 +1,7 @@
1
+ import { UI_COPY_KEYS, type ChatUiCopy } from "./copy";
2
+
3
+ /** Screen copy keys absent or blank — checked when a surface is built. */
4
+ export function missingUiCopy(copy: ChatUiCopy | undefined): string[] {
5
+ if (copy === undefined || copy === null) return [...UI_COPY_KEYS];
6
+ return UI_COPY_KEYS.filter((key) => typeof copy[key] !== "string" || copy[key].trim() === "");
7
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Every string the thread SCREEN renders — required host config, no defaults.
3
+ * Role labels are not here: they come from the server, which got them from the
4
+ * host's role config, so every surface shows the same name for a role.
5
+ */
6
+ export interface ChatUiCopy {
7
+ /** The composer's placeholder. */
8
+ readonly placeholder: string;
9
+ readonly send: string;
10
+ /** Shown on the send button while a message is in flight. */
11
+ readonly sending: string;
12
+ /** No message yet. */
13
+ readonly emptyTitle: string;
14
+ readonly emptyDescription: string;
15
+ /** Read-only notice when the caller may no longer write. */
16
+ readonly closed: string;
17
+ /** First load failed. */
18
+ readonly loadError: string;
19
+ readonly retry: string;
20
+ /** Heading over the quick replies. */
21
+ readonly quickReplies: string;
22
+ /** A send failed with no sentence from the server (no connection). */
23
+ readonly sendFailed: string;
24
+ /** Shown while the first load is in flight. */
25
+ readonly loading: string;
26
+ /** The accessible name of the scrolling message list. */
27
+ readonly messagesLabel: string;
28
+ }
29
+
30
+ export const UI_COPY_KEYS: readonly (keyof ChatUiCopy)[] = [
31
+ "placeholder",
32
+ "send",
33
+ "sending",
34
+ "emptyTitle",
35
+ "emptyDescription",
36
+ "closed",
37
+ "loadError",
38
+ "retry",
39
+ "quickReplies",
40
+ "sendFailed",
41
+ "loading",
42
+ "messagesLabel",
43
+ ];