@marktiderman/genesis-chat 0.5.0 → 0.6.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/dist/native.d.ts +40 -1
- package/dist/native.js +20 -6
- package/dist/native.js.map +1 -1
- package/dist/react.d.ts +8 -8
- package/package.json +35 -11
- package/src/native/__tests__/tus.test.ts +51 -0
- package/src/native/index.ts +1 -1
- package/src/native/tus.ts +72 -10
package/dist/react.d.ts
CHANGED
|
@@ -142,10 +142,10 @@ declare function useInbox(opts?: {
|
|
|
142
142
|
archived?: boolean;
|
|
143
143
|
limit?: number;
|
|
144
144
|
}): {
|
|
145
|
-
items:
|
|
145
|
+
items: ChatInboxItem[];
|
|
146
146
|
isLoading: boolean;
|
|
147
147
|
error: Error | null;
|
|
148
|
-
refetch: (options?: _tanstack_query_core.RefetchOptions) => Promise<_tanstack_query_core.QueryObserverResult<
|
|
148
|
+
refetch: (options?: _tanstack_query_core.RefetchOptions) => Promise<_tanstack_query_core.QueryObserverResult<ChatInboxItem[], Error>>;
|
|
149
149
|
};
|
|
150
150
|
/** How many messages wait for you everywhere (for a badge), live. */
|
|
151
151
|
declare function useUnreadTotal(opts?: {
|
|
@@ -162,8 +162,8 @@ interface UseConversationOptions {
|
|
|
162
162
|
}
|
|
163
163
|
/** One conversation: its messages (with what you are still sending), members, your role, and who is typing. */
|
|
164
164
|
declare function useConversation(conversationId: string | null | undefined, opts?: UseConversationOptions): {
|
|
165
|
-
conversation:
|
|
166
|
-
members:
|
|
165
|
+
conversation: ChatConversation | null;
|
|
166
|
+
members: ChatMember[];
|
|
167
167
|
role: ChatRole | null;
|
|
168
168
|
canPost: boolean;
|
|
169
169
|
/** Your role and posting rights are still loading: show the composer as waiting, not refused. */
|
|
@@ -177,7 +177,7 @@ declare function useConversation(conversationId: string | null | undefined, opts
|
|
|
177
177
|
/** Same as refetchAccess: every per-conversation lookup again, for a Retry after being offline. */
|
|
178
178
|
refetchConversation: () => Promise<undefined>;
|
|
179
179
|
/** The kind's rules (max members, threads, who posts). */
|
|
180
|
-
kind:
|
|
180
|
+
kind: ChatKindRules | null;
|
|
181
181
|
/** May you pin here: owners and admins, or anyone in a two-person conversation. */
|
|
182
182
|
canPin: boolean;
|
|
183
183
|
/** Gives a message whose files were lost on a relaunch its files again. */
|
|
@@ -239,7 +239,7 @@ declare function useTopics(conversationId: string | null | undefined): {
|
|
|
239
239
|
isLoading: boolean;
|
|
240
240
|
error: Error | null;
|
|
241
241
|
setTopic: (topic: string, input?: TopicInput) => Promise<void>;
|
|
242
|
-
refetch: (options?: _tanstack_query_core.RefetchOptions) => Promise<_tanstack_query_core.QueryObserverResult<
|
|
242
|
+
refetch: (options?: _tanstack_query_core.RefetchOptions) => Promise<_tanstack_query_core.QueryObserverResult<ChatTopic[], Error>>;
|
|
243
243
|
};
|
|
244
244
|
/**
|
|
245
245
|
* Your scheduled messages (in one conversation, or all), soonest first, with `schedule` and
|
|
@@ -257,14 +257,14 @@ declare function useScheduled(conversationId?: string | null, opts?: {
|
|
|
257
257
|
clientId?: string;
|
|
258
258
|
}, files?: LocalFile[]) => Promise<string>;
|
|
259
259
|
cancel: (id: string) => Promise<void>;
|
|
260
|
-
refetch: (options?: _tanstack_query_core.RefetchOptions) => Promise<_tanstack_query_core.QueryObserverResult<
|
|
260
|
+
refetch: (options?: _tanstack_query_core.RefetchOptions) => Promise<_tanstack_query_core.QueryObserverResult<ScheduledMessage[], Error>>;
|
|
261
261
|
};
|
|
262
262
|
/**
|
|
263
263
|
* Availability: yours (`mine`, `setMine`) and, given a conversation, its members' (`members`,
|
|
264
264
|
* `forUser`). Pair with `awayLine` and `isWithinWorkingHours` from the core.
|
|
265
265
|
*/
|
|
266
266
|
declare function useAvailability(conversationId?: string | null): {
|
|
267
|
-
mine:
|
|
267
|
+
mine: ChatAvailability | null;
|
|
268
268
|
mineLoading: boolean;
|
|
269
269
|
setMine: (input: AvailabilityInput) => Promise<void>;
|
|
270
270
|
members: ChatAvailability[];
|
package/package.json
CHANGED
|
@@ -1,10 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@marktiderman/genesis-chat",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"description": "Chat for Genesis apps, in the app's own Supabase: conversations of kinds the app defines (direct, group, cohort, support ticket) with members, observers and internal notes; messages with replies, threads, topics, mentions, reactions, edits and deletes; photos, files, voice notes and videos; read state, live updates and typing over private Realtime topics; an outbox for push, transcripts and storage cleanup. A headless core, React hooks, web and native renderers on Genesis UI, and a server runner. Part of the Genesis framework.",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"genesis",
|
|
10
|
+
"genesis-framework",
|
|
11
|
+
"chat",
|
|
12
|
+
"messaging",
|
|
13
|
+
"supabase",
|
|
14
|
+
"realtime",
|
|
15
|
+
"react",
|
|
16
|
+
"react-native",
|
|
17
|
+
"messages",
|
|
18
|
+
"dm",
|
|
19
|
+
"group-chat",
|
|
20
|
+
"voice-notes",
|
|
21
|
+
"video-messages",
|
|
22
|
+
"inbox",
|
|
23
|
+
"support-tickets"
|
|
24
|
+
],
|
|
25
|
+
"homepage": "https://github.com/marktiderman/genesis/tree/main/packages/chat#readme",
|
|
26
|
+
"bugs": {
|
|
27
|
+
"url": "https://github.com/marktiderman/genesis/issues"
|
|
28
|
+
},
|
|
8
29
|
"repository": {
|
|
9
30
|
"type": "git",
|
|
10
31
|
"url": "git+https://github.com/marktiderman/genesis.git",
|
|
@@ -65,7 +86,7 @@
|
|
|
65
86
|
"README.md"
|
|
66
87
|
],
|
|
67
88
|
"dependencies": {
|
|
68
|
-
"@marktiderman/genesis-features": "^0.
|
|
89
|
+
"@marktiderman/genesis-features": "^0.8.0",
|
|
69
90
|
"frimousse": "0.4.0"
|
|
70
91
|
},
|
|
71
92
|
"peerDependencies": {
|
|
@@ -153,29 +174,32 @@
|
|
|
153
174
|
},
|
|
154
175
|
"devDependencies": {
|
|
155
176
|
"@ai-sdk/anthropic": "4.0.85",
|
|
156
|
-
"@marktiderman/genesis-ai": "^0.
|
|
157
|
-
"@marktiderman/genesis-core": "^2.
|
|
158
|
-
"@marktiderman/genesis-notifications": "^0.
|
|
159
|
-
"@marktiderman/genesis-ui": "^2.
|
|
160
|
-
"@marktiderman/genesis-ui-native": "^3.
|
|
177
|
+
"@marktiderman/genesis-ai": "^0.2.0",
|
|
178
|
+
"@marktiderman/genesis-core": "^2.4.0",
|
|
179
|
+
"@marktiderman/genesis-notifications": "^0.4.0",
|
|
180
|
+
"@marktiderman/genesis-ui": "^2.25.1",
|
|
181
|
+
"@marktiderman/genesis-ui-native": "^3.2.2",
|
|
161
182
|
"@supabase/supabase-js": "^2.118.0",
|
|
162
|
-
"@tanstack/react-query": "^5.
|
|
183
|
+
"@tanstack/react-query": "^5.104.5",
|
|
163
184
|
"@testing-library/react": "^16.3.2",
|
|
164
185
|
"@types/node": "^22",
|
|
165
186
|
"@types/react": "^19.2.14",
|
|
166
187
|
"@types/react-dom": "^19.2.3",
|
|
167
188
|
"ai": "7.0.148",
|
|
168
|
-
"happy-dom": "^
|
|
189
|
+
"happy-dom": "^21.0.4",
|
|
169
190
|
"hls.js": "1.7.3",
|
|
170
191
|
"lucide-react": "^1.28.0",
|
|
171
192
|
"react": "^19.2.5",
|
|
172
193
|
"react-dom": "^19.2.5",
|
|
173
194
|
"tsup": "^8.3.0",
|
|
174
195
|
"typescript": "~6.0.3",
|
|
175
|
-
"vitest": "^
|
|
176
|
-
"zod": "^4.
|
|
196
|
+
"vitest": "^5.0.5",
|
|
197
|
+
"zod": "^4.6.6"
|
|
177
198
|
},
|
|
178
199
|
"genesis": {
|
|
200
|
+
"layer": "primitive",
|
|
201
|
+
"group": "collaboration",
|
|
202
|
+
"owner": "@marktiderman",
|
|
179
203
|
"blocks": {
|
|
180
204
|
"chat": {
|
|
181
205
|
"feature": {
|
|
@@ -152,3 +152,54 @@ describe("base64Utf8", () => {
|
|
|
152
152
|
expect(base64Utf8("é/ü")).toBe(Buffer.from("é/ü").toString("base64"));
|
|
153
153
|
});
|
|
154
154
|
});
|
|
155
|
+
|
|
156
|
+
describe("createTusUpload's transport port", () => {
|
|
157
|
+
it("sends through the transport it's given, with chat's path, bucket, type and the person's headers", async () => {
|
|
158
|
+
const seen: { path: string; bucket: string; contentType: string; headers: Record<string, string>; bytes: number }[] = [];
|
|
159
|
+
const upload = createTusUpload({
|
|
160
|
+
supabaseUrl: URL_,
|
|
161
|
+
userId: USER,
|
|
162
|
+
getAccessToken: async () => "jwt",
|
|
163
|
+
apikey: "pk",
|
|
164
|
+
newId: () => "id9",
|
|
165
|
+
transport: {
|
|
166
|
+
async send(record, source, info) {
|
|
167
|
+
const bytes = await source.read(0, source.size);
|
|
168
|
+
seen.push({ path: record.path, bucket: info.bucket, contentType: info.contentType, headers: await info.headers(), bytes: bytes.byteLength });
|
|
169
|
+
record.done = true;
|
|
170
|
+
return record.path;
|
|
171
|
+
},
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
const f = file(10);
|
|
175
|
+
const path = await upload(CONV, f);
|
|
176
|
+
expect(path).toBe(`${CONV}/${USER}/id9.jpg`);
|
|
177
|
+
expect(seen).toEqual([{ path, bucket: "genesis-chat", contentType: "image/jpeg", headers: { authorization: "Bearer jwt", apikey: "pk" }, bytes: 10 }]);
|
|
178
|
+
// Done once: the same file again is the same path, without another send.
|
|
179
|
+
expect(await upload(CONV, f)).toBe(path);
|
|
180
|
+
expect(seen).toHaveLength(1);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it("keeps chat's file checks before the transport, and a rename the transport asks for", async () => {
|
|
184
|
+
const send = vi.fn(async (_record: { path: string }, _source: unknown, _info: unknown, renamePath: () => string) => renamePath());
|
|
185
|
+
let n = 0;
|
|
186
|
+
const upload = createTusUpload({ supabaseUrl: URL_, userId: USER, getAccessToken: async () => "jwt", newId: () => `id${++n}`, transport: { send } });
|
|
187
|
+
await expect(upload(CONV, { data: new Uint8Array(1).buffer, name: "run.exe", contentType: "application/x-msdownload" })).rejects.toMatchObject({ code: "22023" });
|
|
188
|
+
expect(send).not.toHaveBeenCalled();
|
|
189
|
+
expect(await upload(CONV, file(3))).toBe(`${CONV}/${USER}/id2.jpg`);
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
it("turns a transport's failures into chat's errors: refusals keep their kind, the rest are transient", async () => {
|
|
193
|
+
const failing = (error: unknown) =>
|
|
194
|
+
createTusUpload({ supabaseUrl: URL_, userId: USER, getAccessToken: async () => "jwt", transport: { send: async () => Promise.reject(error) } });
|
|
195
|
+
const forbidden = await failing(Object.assign(new Error("no"), { failure: "forbidden" }))(CONV, file(3)).catch((e: unknown) => e);
|
|
196
|
+
expect(forbidden).toBeInstanceOf(ChatError);
|
|
197
|
+
expect((forbidden as ChatError).forbidden).toBe(true);
|
|
198
|
+
const invalid = await failing(Object.assign(new Error("bad"), { failure: "invalid" }))(CONV, file(3)).catch((e: unknown) => e);
|
|
199
|
+
expect((invalid as ChatError).code).toBe("22023");
|
|
200
|
+
const network = await failing(new TypeError("Network request failed"))(CONV, file(3)).catch((e: unknown) => e);
|
|
201
|
+
expect((network as ChatError).transient).toBe(true);
|
|
202
|
+
const own = new ChatError("Sign in to send files", "42501", "upload");
|
|
203
|
+
expect(await failing(own)(CONV, file(3)).catch((e: unknown) => e)).toBe(own);
|
|
204
|
+
});
|
|
205
|
+
});
|
package/src/native/index.ts
CHANGED
|
@@ -135,7 +135,7 @@ export {
|
|
|
135
135
|
export { useVoiceRecorder, voiceNoteFile, type UseVoiceRecorderOptions } from "./use-voice-recorder";
|
|
136
136
|
export { invertedRows, buildThreadRows, rowKey, type ThreadRow, type BuildRowsOptions } from "./rows";
|
|
137
137
|
export { messageActionsFor, canReactTo, QUICK_REACTIONS, type MessageActionId, type MessageActionContext } from "./actions";
|
|
138
|
-
export { createTusUpload, base64Utf8, TUS_CHUNK_BYTES, type TusUploadOptions } from "./tus";
|
|
138
|
+
export { createTusUpload, base64Utf8, TUS_CHUNK_BYTES, type TusUploadOptions, type TusTransport, type TusUploadRecord, type TusUploadSource, type TusSendInfo } from "./tus";
|
|
139
139
|
export {
|
|
140
140
|
CHAT_PUSH_CATEGORY,
|
|
141
141
|
CHAT_REPLY_ACTION,
|
package/src/native/tus.ts
CHANGED
|
@@ -15,6 +15,10 @@
|
|
|
15
15
|
*
|
|
16
16
|
* The path is `<conversation>/<uploader>/<uuid>.<ext>`, as `send_message`
|
|
17
17
|
* expects; the upload finishes before the send (the outbox orders that).
|
|
18
|
+
*
|
|
19
|
+
* What moves the bytes is a port (`transport`): this file's own TUS client by
|
|
20
|
+
* default, or any `TusTransport` an app passes. chat's paths, file checks and
|
|
21
|
+
* errors stay here either way.
|
|
18
22
|
*/
|
|
19
23
|
import { CHAT_BUCKET, ChatError } from "../core/client";
|
|
20
24
|
import { fileExtension, isAllowedExtension, randomId } from "../core/media";
|
|
@@ -46,6 +50,49 @@ export interface TusUploadOptions {
|
|
|
46
50
|
/** A uuid for each file's name. Default core's `randomId` (crypto.randomUUID where there is one, else getRandomValues). */
|
|
47
51
|
newId?: () => string;
|
|
48
52
|
bucket?: string;
|
|
53
|
+
/**
|
|
54
|
+
* What sends the bytes. Default: Supabase Storage's TUS endpoint, built in (with `fetch`,
|
|
55
|
+
* `chunkBytes` and `retries` above). An app opts into another by passing it here.
|
|
56
|
+
*/
|
|
57
|
+
transport?: TusTransport;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Where one file's upload stands: its path and, once the TUS upload is made,
|
|
62
|
+
* where it lives. A transport keeps it current, so a retry of the same file
|
|
63
|
+
* resumes rather than starting again.
|
|
64
|
+
*/
|
|
65
|
+
export interface TusUploadRecord {
|
|
66
|
+
path: string;
|
|
67
|
+
location?: string | undefined;
|
|
68
|
+
done?: boolean | undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** What a transport reads a file's bytes from: exactly `from` to `to`. */
|
|
72
|
+
export interface TusUploadSource {
|
|
73
|
+
size: number;
|
|
74
|
+
read(from: number, to: number): Promise<ArrayBuffer>;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** What a transport is told about the file it sends. */
|
|
78
|
+
export interface TusSendInfo {
|
|
79
|
+
bucket: string;
|
|
80
|
+
contentType: string;
|
|
81
|
+
cacheControl: string;
|
|
82
|
+
/** The person's headers (`authorization`, and `apikey` when given). Rejects when they're signed out. */
|
|
83
|
+
headers: () => Promise<Record<string, string>>;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The upload port: what moves a file's bytes to `record.path` in `info.bucket`.
|
|
88
|
+
* It resolves to the path the object ended at; `renamePath()` gives a fresh
|
|
89
|
+
* one (ask it at most once) when the path is taken by a send that never
|
|
90
|
+
* finished. A rejection whose `failure` is `"forbidden"` or `"invalid"`, or a
|
|
91
|
+
* `ChatError` that isn't transient, is a refusal; anything else is worth
|
|
92
|
+
* trying again.
|
|
93
|
+
*/
|
|
94
|
+
export interface TusTransport {
|
|
95
|
+
send(record: TusUploadRecord, source: TusUploadSource, info: TusSendInfo, renamePath: () => string): Promise<string>;
|
|
49
96
|
}
|
|
50
97
|
|
|
51
98
|
/** An open file, read a chunk at a time. */
|
|
@@ -69,11 +116,7 @@ const exact = (bytes: ArrayBuffer | Uint8Array): ArrayBuffer =>
|
|
|
69
116
|
|
|
70
117
|
const inMemory = (buffer: ArrayBuffer): Source => ({ size: buffer.byteLength, read: async (from, to) => buffer.slice(from, to), close: () => undefined });
|
|
71
118
|
|
|
72
|
-
|
|
73
|
-
path: string;
|
|
74
|
-
location?: string;
|
|
75
|
-
done?: boolean;
|
|
76
|
-
}
|
|
119
|
+
type UploadRecord = TusUploadRecord;
|
|
77
120
|
|
|
78
121
|
/** Base64 of a UTF-8 string, for TUS's Upload-Metadata (no `btoa`, which isn't on every Hermes build). */
|
|
79
122
|
export function base64Utf8(text: string): string {
|
|
@@ -101,17 +144,36 @@ export function createTusUpload(options: TusUploadOptions): (conversationId: str
|
|
|
101
144
|
// share an object, so deleting one never breaks the other.
|
|
102
145
|
const byFile = new WeakMap<LocalFile, UploadRecord>();
|
|
103
146
|
|
|
104
|
-
async function
|
|
147
|
+
async function auth(): Promise<Record<string, string>> {
|
|
105
148
|
const token = await options.getAccessToken();
|
|
106
149
|
if (!token) throw new ChatError("Sign in to send files", "42501", "upload");
|
|
107
150
|
return {
|
|
108
151
|
authorization: `Bearer ${token}`,
|
|
109
152
|
...(options.apikey ? { apikey: options.apikey } : {}),
|
|
110
|
-
"tus-resumable": "1.0.0",
|
|
111
|
-
...extra,
|
|
112
153
|
};
|
|
113
154
|
}
|
|
114
155
|
|
|
156
|
+
async function headers(extra: Record<string, string> = {}) {
|
|
157
|
+
return { ...(await auth()), "tus-resumable": "1.0.0", ...extra };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const renamePath = (rec: UploadRecord) => `${rec.path.slice(0, rec.path.lastIndexOf("/") + 1)}${newId()}.${rec.path.slice(rec.path.lastIndexOf(".") + 1)}`;
|
|
161
|
+
|
|
162
|
+
/** Sends through the app's own transport, with chat's errors whatever it throws. */
|
|
163
|
+
async function sendThrough(transport: TusTransport, file: LocalFile, rec: UploadRecord, source: Source): Promise<string> {
|
|
164
|
+
try {
|
|
165
|
+
const path = await transport.send(rec, source, { bucket, contentType: file.contentType, cacheControl: "3600", headers: auth }, () => renamePath(rec));
|
|
166
|
+
rec.path = path;
|
|
167
|
+
rec.done = true;
|
|
168
|
+
return path;
|
|
169
|
+
} catch (e) {
|
|
170
|
+
if (e instanceof ChatError) throw e;
|
|
171
|
+
const failure = typeof e === "object" && e !== null ? (e as { failure?: unknown }).failure : undefined;
|
|
172
|
+
// A refusal keeps its kind; anything else (the network) is transient, so the outbox retries it.
|
|
173
|
+
throw new ChatError(e instanceof Error ? e.message : String(e), failure === "forbidden" ? "42501" : failure === "invalid" ? "22023" : undefined, "upload");
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
115
177
|
async function sourceOf(file: LocalFile): Promise<Source> {
|
|
116
178
|
const data = file.data;
|
|
117
179
|
if (typeof data === "string") {
|
|
@@ -195,7 +257,7 @@ export function createTusUpload(options: TusUploadOptions): (conversationId: str
|
|
|
195
257
|
|
|
196
258
|
const source = await sourceOf(file);
|
|
197
259
|
try {
|
|
198
|
-
return await send(file, record, source);
|
|
260
|
+
return await (options.transport ? sendThrough(options.transport, file, record, source) : send(file, record, source));
|
|
199
261
|
} finally {
|
|
200
262
|
source.close();
|
|
201
263
|
}
|
|
@@ -246,7 +308,7 @@ export function createTusUpload(options: TusUploadOptions): (conversationId: str
|
|
|
246
308
|
if (created === "conflict") {
|
|
247
309
|
if (fresh) throw new ChatError("The upload is out of step", undefined, "upload");
|
|
248
310
|
fresh = true;
|
|
249
|
-
rec.path =
|
|
311
|
+
rec.path = renamePath(rec);
|
|
250
312
|
continue;
|
|
251
313
|
}
|
|
252
314
|
rec.location = created;
|