@skyphusion/create-prism 0.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/LICENSE +235 -0
- package/NOTICE +3 -0
- package/README.md +114 -0
- package/index.js +195 -0
- package/package.json +44 -0
- package/template/CONTRIBUTING.md +80 -0
- package/template/LICENSE +235 -0
- package/template/MIGRATIONS.md +197 -0
- package/template/NOTICE +3 -0
- package/template/README.md +875 -0
- package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +98 -0
- package/template/docs/legal/INSTANCE-PRIVACY.md +112 -0
- package/template/docs/legal/README.md +11 -0
- package/template/docs/screenshot-desktop.jpg +0 -0
- package/template/docs/screenshot-mobile.jpg +0 -0
- package/template/gitignore +23 -0
- package/template/migrate-v0.164.0.sql +6 -0
- package/template/migrate-v0.167.0.sql +44 -0
- package/template/migrate-v0.20.0.sql +40 -0
- package/template/migrate-v0.20.2.sql +19 -0
- package/template/migrate-v0.20.3.sql +36 -0
- package/template/migrations/0001_init.sql +134 -0
- package/template/package.json +32 -0
- package/template/public/app.js +2778 -0
- package/template/public/apple-touch-icon.png +0 -0
- package/template/public/favicon-16.png +0 -0
- package/template/public/favicon-32.png +0 -0
- package/template/public/favicon.svg +5 -0
- package/template/public/icon-192.png +0 -0
- package/template/public/icon-512.png +0 -0
- package/template/public/index.html +329 -0
- package/template/public/manifest.webmanifest +14 -0
- package/template/public/streaming-client.js +207 -0
- package/template/public/stt.html +68 -0
- package/template/public/stt.js +16 -0
- package/template/public/styles.css +2068 -0
- package/template/public/voice-widget.js +195 -0
- package/template/schema.sql +283 -0
- package/template/src/ai-binding.ts +33 -0
- package/template/src/auth-kdf.ts +106 -0
- package/template/src/auth.ts +315 -0
- package/template/src/chunking.ts +161 -0
- package/template/src/discord.ts +353 -0
- package/template/src/env.ts +55 -0
- package/template/src/gateway-credentials.ts +97 -0
- package/template/src/health-schema.ts +25 -0
- package/template/src/index.ts +4180 -0
- package/template/src/longrun-params.ts +135 -0
- package/template/src/models.ts +214 -0
- package/template/src/output-extract.ts +128 -0
- package/template/src/parsers/anthropic-sse.ts +56 -0
- package/template/src/parsers/gemini-sse.ts +62 -0
- package/template/src/parsers/openai-sse.ts +60 -0
- package/template/src/parsers/sse-framer.ts +39 -0
- package/template/src/parsers/types.ts +16 -0
- package/template/src/parsers/workers-ai-sse.ts +43 -0
- package/template/src/parsers/xai-sse.ts +40 -0
- package/template/src/providers/anthropic.ts +208 -0
- package/template/src/providers/google.ts +150 -0
- package/template/src/providers/openai.ts +69 -0
- package/template/src/providers/workers-ai.ts +83 -0
- package/template/src/providers/xai.ts +159 -0
- package/template/src/proxied-image-params.ts +43 -0
- package/template/src/rate-limit.ts +77 -0
- package/template/src/searxng.ts +75 -0
- package/template/src/session.ts +114 -0
- package/template/src/stt-session.ts +206 -0
- package/template/src/stt-util.ts +19 -0
- package/template/src/types.ts +56 -0
- package/template/src/user-prefs.ts +63 -0
- package/template/src/utils.ts +73 -0
- package/template/src/zip.ts +137 -0
- package/template/tests/anthropic-sse.test.ts +149 -0
- package/template/tests/auth-kdf.test.ts +59 -0
- package/template/tests/auth-unit.test.ts +97 -0
- package/template/tests/chunking.test.ts +217 -0
- package/template/tests/discord.test.ts +184 -0
- package/template/tests/gateway-credentials.test.ts +65 -0
- package/template/tests/gemini-sse.test.ts +75 -0
- package/template/tests/google-gemini.test.ts +65 -0
- package/template/tests/health-schema.test.ts +35 -0
- package/template/tests/longrun-params.test.ts +128 -0
- package/template/tests/openai-sse.test.ts +71 -0
- package/template/tests/output-extract.test.ts +171 -0
- package/template/tests/proxied-image-params.test.ts +51 -0
- package/template/tests/rate-limit.test.ts +45 -0
- package/template/tests/searxng.test.ts +51 -0
- package/template/tests/sse-framer.test.ts +113 -0
- package/template/tests/stt-session.test.ts +35 -0
- package/template/tests/utils.test.ts +39 -0
- package/template/tests/workers-ai-sse.test.ts +67 -0
- package/template/tests/xai-sse.test.ts +60 -0
- package/template/tests/zip.test.ts +145 -0
- package/template/tests-integration/auth.test.ts +371 -0
- package/template/tests-integration/worker.test.ts +322 -0
- package/template/tsconfig.json +18 -0
- package/template/vitest.config.ts +18 -0
- package/template/vitest.node.config.ts +19 -0
- package/template/vitest.workers.config.ts +47 -0
- package/template/wrangler.example.toml +151 -0
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// Conversational STT session Durable Object (v0.108.0).
|
|
2
|
+
//
|
|
3
|
+
// Wraps a @cf/deepgram/flux WebSocket session so the final transcript can be
|
|
4
|
+
// persisted to /history on close, which a plain Worker cannot do reliably (no
|
|
5
|
+
// clean hook after the 101 to write D1). The DO:
|
|
6
|
+
// - accepts the browser socket via the Hibernation API (ctx.acceptWebSocket),
|
|
7
|
+
// - opens the upstream flux socket (env.AI.run({websocket:true})) and bridges
|
|
8
|
+
// audio up / Deepgram events down,
|
|
9
|
+
// - accumulates each committed turn into DO SQLite (hibernation-safe; the
|
|
10
|
+
// in-memory upstream socket is NOT — outbound sockets do not hibernate, so
|
|
11
|
+
// we lean on the fact that an active STT session streams audio continuously
|
|
12
|
+
// and never goes idle long enough to hibernate, with a guard if it does),
|
|
13
|
+
// - on close, concatenates the turns and writes one chats row (model_type
|
|
14
|
+
// "voice") so the session shows up in history.
|
|
15
|
+
|
|
16
|
+
import { DurableObject } from "cloudflare:workers";
|
|
17
|
+
import type { Env } from "./env";
|
|
18
|
+
import { buildTranscript, sanitizeCloseCode } from "./stt-util";
|
|
19
|
+
import { resolveIdentity } from "./auth";
|
|
20
|
+
|
|
21
|
+
export const FLUX_STT_MODEL = "@cf/deepgram/flux";
|
|
22
|
+
|
|
23
|
+
interface FluxRunResult {
|
|
24
|
+
webSocket?: WebSocket | null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class SttSession extends DurableObject<Env> {
|
|
28
|
+
private upstream: WebSocket | null = null;
|
|
29
|
+
private finalized = false;
|
|
30
|
+
|
|
31
|
+
constructor(ctx: DurableObjectState, env: Env) {
|
|
32
|
+
super(ctx, env);
|
|
33
|
+
ctx.blockConcurrencyWhile(async () => {
|
|
34
|
+
ctx.storage.sql.exec(
|
|
35
|
+
`CREATE TABLE IF NOT EXISTS turns (seq INTEGER PRIMARY KEY AUTOINCREMENT, text TEXT NOT NULL, confidence REAL)`,
|
|
36
|
+
);
|
|
37
|
+
ctx.storage.sql.exec(
|
|
38
|
+
`CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT NOT NULL)`,
|
|
39
|
+
);
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async fetch(request: Request): Promise<Response> {
|
|
44
|
+
// Identity read site #2 (WebSocket), in lockstep with getUserEmail in
|
|
45
|
+
// src/index.ts. The session cookie rides the same-origin WS upgrade, so
|
|
46
|
+
// resolveIdentity derives the owner the same way as every HTTP route.
|
|
47
|
+
const userEmail = (await resolveIdentity(request, this.env)) ?? "anonymous";
|
|
48
|
+
this.ctx.storage.sql.exec(
|
|
49
|
+
`INSERT OR REPLACE INTO meta (k, v) VALUES ('user', ?), ('model', ?), ('started_at', ?)`,
|
|
50
|
+
userEmail,
|
|
51
|
+
FLUX_STT_MODEL,
|
|
52
|
+
new Date().toISOString(),
|
|
53
|
+
);
|
|
54
|
+
|
|
55
|
+
let upstream: WebSocket | null;
|
|
56
|
+
try {
|
|
57
|
+
const resp = (await (this.env.AI as unknown as {
|
|
58
|
+
run: (m: string, p: unknown, o: { websocket: boolean }) => Promise<FluxRunResult>;
|
|
59
|
+
}).run(FLUX_STT_MODEL, { encoding: "linear16", sample_rate: "16000" }, { websocket: true }));
|
|
60
|
+
upstream = resp?.webSocket ?? null;
|
|
61
|
+
} catch (err) {
|
|
62
|
+
return Response.json(
|
|
63
|
+
{ error: `flux upstream open failed: ${err instanceof Error ? err.message : String(err)}` },
|
|
64
|
+
{ status: 502 },
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
if (!upstream) {
|
|
68
|
+
return Response.json({ error: "flux did not return a WebSocket" }, { status: 502 });
|
|
69
|
+
}
|
|
70
|
+
upstream.accept();
|
|
71
|
+
this.upstream = upstream;
|
|
72
|
+
|
|
73
|
+
const [client, server] = Object.values(new WebSocketPair()) as [WebSocket, WebSocket];
|
|
74
|
+
// Hibernation API for the browser-facing socket: webSocketMessage / -Close
|
|
75
|
+
// fire even after an idle eviction, and DO SQLite holds the transcript.
|
|
76
|
+
this.ctx.acceptWebSocket(server);
|
|
77
|
+
|
|
78
|
+
// Upstream -> browser. Outbound socket, so regular listeners (these run only
|
|
79
|
+
// while the DO is in memory, which an active session keeps it).
|
|
80
|
+
upstream.addEventListener("message", (e: MessageEvent) => this.onUpstreamMessage(e));
|
|
81
|
+
upstream.addEventListener("close", (e: CloseEvent) => {
|
|
82
|
+
for (const ws of this.ctx.getWebSockets()) {
|
|
83
|
+
try {
|
|
84
|
+
ws.close(sanitizeCloseCode(e.code), e.reason);
|
|
85
|
+
} catch {
|
|
86
|
+
/* peer gone */
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
upstream.addEventListener("error", () => {
|
|
91
|
+
for (const ws of this.ctx.getWebSockets()) {
|
|
92
|
+
try {
|
|
93
|
+
ws.close(1011, "upstream error");
|
|
94
|
+
} catch {
|
|
95
|
+
/* peer gone */
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
return new Response(null, { status: 101, webSocket: client });
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
private onUpstreamMessage(e: MessageEvent): void {
|
|
104
|
+
// Relay the raw frame to the browser first, then parse (text = JSON events,
|
|
105
|
+
// binary would never be parsed). Never let a parse error drop the relay.
|
|
106
|
+
for (const ws of this.ctx.getWebSockets()) {
|
|
107
|
+
try {
|
|
108
|
+
ws.send(e.data);
|
|
109
|
+
} catch {
|
|
110
|
+
/* peer gone */
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (typeof e.data !== "string") return;
|
|
114
|
+
let ev: Record<string, unknown>;
|
|
115
|
+
try {
|
|
116
|
+
ev = JSON.parse(e.data);
|
|
117
|
+
} catch {
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
// Flux nests turn events: {type:"TurnInfo", event:"EndOfTurn", ...}. (It used
|
|
121
|
+
// to be flat {type:"EndOfTurn"}; the API changed.) Handle both shapes.
|
|
122
|
+
const type = ev.type === "TurnInfo" ? (ev.event as string) : ((ev.type as string) || (ev.event as string) || "");
|
|
123
|
+
if (type === "EndOfTurn") {
|
|
124
|
+
const text = typeof ev.transcript === "string" ? ev.transcript.trim() : "";
|
|
125
|
+
if (text) {
|
|
126
|
+
const conf = typeof ev.end_of_turn_confidence === "number" ? ev.end_of_turn_confidence : null;
|
|
127
|
+
this.ctx.storage.sql.exec(`INSERT INTO turns (text, confidence) VALUES (?, ?)`, text, conf);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Browser -> upstream (binary linear16 PCM frames, or a client text control).
|
|
133
|
+
async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {
|
|
134
|
+
if (this.upstream) {
|
|
135
|
+
try {
|
|
136
|
+
this.upstream.send(message);
|
|
137
|
+
} catch {
|
|
138
|
+
/* upstream gone */
|
|
139
|
+
}
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
// The DO was evicted mid-session and lost the (non-hibernatable) upstream
|
|
143
|
+
// socket; a flux session can't be resumed, so close cleanly and persist
|
|
144
|
+
// whatever turns we captured.
|
|
145
|
+
try {
|
|
146
|
+
ws.close(1011, "session expired");
|
|
147
|
+
} catch {
|
|
148
|
+
/* */
|
|
149
|
+
}
|
|
150
|
+
await this.finalize();
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async webSocketClose(ws: WebSocket, code: number, reason: string): Promise<void> {
|
|
154
|
+
try {
|
|
155
|
+
this.upstream?.close(sanitizeCloseCode(code), reason);
|
|
156
|
+
} catch {
|
|
157
|
+
/* */
|
|
158
|
+
}
|
|
159
|
+
this.upstream = null;
|
|
160
|
+
await this.finalize();
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async webSocketError(ws: WebSocket): Promise<void> {
|
|
164
|
+
try {
|
|
165
|
+
this.upstream?.close(1011);
|
|
166
|
+
} catch {
|
|
167
|
+
/* */
|
|
168
|
+
}
|
|
169
|
+
this.upstream = null;
|
|
170
|
+
await this.finalize();
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Write the accumulated transcript to /history as one chats row. Idempotent:
|
|
174
|
+
// close + error can both fire, but only the first persists.
|
|
175
|
+
private async finalize(): Promise<void> {
|
|
176
|
+
if (this.finalized) return;
|
|
177
|
+
this.finalized = true;
|
|
178
|
+
const turns = this.ctx.storage.sql
|
|
179
|
+
.exec<{ text: string }>(`SELECT text FROM turns ORDER BY seq`)
|
|
180
|
+
.toArray();
|
|
181
|
+
const transcript = buildTranscript(turns);
|
|
182
|
+
if (!transcript) return; // nothing said; don't litter history with empties
|
|
183
|
+
|
|
184
|
+
const meta = Object.fromEntries(
|
|
185
|
+
this.ctx.storage.sql.exec<{ k: string; v: string }>(`SELECT k, v FROM meta`).toArray().map((r) => [r.k, r.v]),
|
|
186
|
+
);
|
|
187
|
+
try {
|
|
188
|
+
// Minimal voice row; chats column defaults cover the rest. conversation_id
|
|
189
|
+
// mirrors persistChat's synthetic single-<id> so the history sidebar groups
|
|
190
|
+
// it as a standalone conversation.
|
|
191
|
+
const inserted = await this.env.DB.prepare(
|
|
192
|
+
`INSERT INTO chats (user_email, model, model_type, system_prompt, user_input, output, status, turn_index)
|
|
193
|
+
VALUES (?, ?, 'voice', NULL, '(live voice session)', ?, 'done', 0) RETURNING id`,
|
|
194
|
+
)
|
|
195
|
+
.bind(meta.user ?? "anonymous", meta.model ?? FLUX_STT_MODEL, transcript)
|
|
196
|
+
.first<{ id: number }>();
|
|
197
|
+
if (inserted?.id != null) {
|
|
198
|
+
await this.env.DB.prepare(`UPDATE chats SET conversation_id = ? WHERE id = ?`)
|
|
199
|
+
.bind(`single-${inserted.id}`, inserted.id)
|
|
200
|
+
.run();
|
|
201
|
+
}
|
|
202
|
+
} catch (err) {
|
|
203
|
+
console.warn("stt-session persist failed:", err instanceof Error ? err.message : String(err));
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Pure helpers for the conversational-STT session (v0.108.0). Kept free of the
|
|
2
|
+
// `cloudflare:workers` import (which the DO needs) so they're unit-testable in
|
|
3
|
+
// the plain node test pool.
|
|
4
|
+
|
|
5
|
+
// WebSocket.close() only accepts 1000 or 3000-4999; codes like 1006/1011/1005
|
|
6
|
+
// arrive on close events but cannot be re-sent. Map anything illegal to 1011 so
|
|
7
|
+
// forwarding a peer's close code never throws and leaks the other socket.
|
|
8
|
+
export function sanitizeCloseCode(code: number): number {
|
|
9
|
+
return code === 1000 || (code >= 3000 && code <= 4999) ? code : 1011;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// Join committed turns into a single transcript.
|
|
13
|
+
export function buildTranscript(turns: Array<{ text: string }>): string {
|
|
14
|
+
return turns
|
|
15
|
+
.map((t) => (t.text || "").trim())
|
|
16
|
+
.filter((t) => t.length > 0)
|
|
17
|
+
.join(" ")
|
|
18
|
+
.trim();
|
|
19
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Shared request types (v0.19.2).
|
|
2
|
+
//
|
|
3
|
+
// Extracted from src/index.ts so provider modules can typecheck attachment
|
|
4
|
+
// handling. The `InputAttachment` discriminated union (v0.17.1) is the shape
|
|
5
|
+
// the worker accepts on the request boundary; providers that consume
|
|
6
|
+
// attachments directly import the narrow variant types via `find` with a
|
|
7
|
+
// type predicate, and TypeScript narrows correctly thanks to the
|
|
8
|
+
// discriminator.
|
|
9
|
+
//
|
|
10
|
+
// PersistedAttachment family (the D1 storage shape after R2 upload) is not
|
|
11
|
+
// included here for now; only the worker entry deals with persistence,
|
|
12
|
+
// providers only see the in-flight Input shape.
|
|
13
|
+
|
|
14
|
+
export interface InputImageAttachment {
|
|
15
|
+
type: "image";
|
|
16
|
+
data?: string; // data URL (inline upload). Optional if `key` is set.
|
|
17
|
+
key?: string; // v0.21.7: R2 key of an artifact already produced in this
|
|
18
|
+
// conversation; resolved to `data` at the request boundary.
|
|
19
|
+
mime?: string;
|
|
20
|
+
filename?: string;
|
|
21
|
+
}
|
|
22
|
+
export interface InputAudioAttachment {
|
|
23
|
+
type: "audio";
|
|
24
|
+
data: string; // data URL
|
|
25
|
+
mime?: string;
|
|
26
|
+
filename?: string;
|
|
27
|
+
}
|
|
28
|
+
export interface InputVideoFramesAttachment {
|
|
29
|
+
type: "video_frames";
|
|
30
|
+
frames: string[]; // array of data URLs (one per keyframe)
|
|
31
|
+
duration?: number;
|
|
32
|
+
filename?: string;
|
|
33
|
+
}
|
|
34
|
+
export interface InputVideoFullAttachment {
|
|
35
|
+
type: "video_full";
|
|
36
|
+
data?: string; // data URL (inline upload). Optional if `key` is set.
|
|
37
|
+
key?: string; // v0.21.7: R2 key of a video artifact already in this conversation.
|
|
38
|
+
mime?: string;
|
|
39
|
+
filename?: string;
|
|
40
|
+
}
|
|
41
|
+
// v0.24.0: a text-based file attached to a chat turn for inline analysis
|
|
42
|
+
// (yaml, json, csv, source code, logs, etc.). The frontend decodes the file
|
|
43
|
+
// to UTF-8 text and sends it here; the worker inlines it into the prompt.
|
|
44
|
+
// Binary files are rejected at the worker boundary (looksBinary).
|
|
45
|
+
export interface InputDocumentAttachment {
|
|
46
|
+
type: "document";
|
|
47
|
+
text: string; // UTF-8 file contents, decoded client-side
|
|
48
|
+
mime?: string;
|
|
49
|
+
filename?: string;
|
|
50
|
+
}
|
|
51
|
+
export type InputAttachment =
|
|
52
|
+
| InputImageAttachment
|
|
53
|
+
| InputAudioAttachment
|
|
54
|
+
| InputVideoFramesAttachment
|
|
55
|
+
| InputVideoFullAttachment
|
|
56
|
+
| InputDocumentAttachment;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Per-user preferences stored in D1 (v0.164.0).
|
|
2
|
+
//
|
|
3
|
+
// JSON blob keyed by Cloudflare Access email. Gateway fields are the first
|
|
4
|
+
// use case for a public demo deployment where each visitor brings their own
|
|
5
|
+
// AI Gateway slug and CF_AIG_TOKEN.
|
|
6
|
+
|
|
7
|
+
export interface UserPrefsJson {
|
|
8
|
+
gateway_id?: string;
|
|
9
|
+
cf_aig_token?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function parsePrefsJson(raw: string | null | undefined): UserPrefsJson {
|
|
13
|
+
if (!raw?.trim()) return {};
|
|
14
|
+
try {
|
|
15
|
+
const parsed = JSON.parse(raw) as UserPrefsJson;
|
|
16
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
|
|
17
|
+
return parsed;
|
|
18
|
+
} catch {
|
|
19
|
+
return {};
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function loadUserPrefs(db: D1Database, userEmail: string): Promise<UserPrefsJson | null> {
|
|
24
|
+
const row = await db.prepare(
|
|
25
|
+
`SELECT prefs_json FROM user_prefs WHERE user_email = ?`,
|
|
26
|
+
)
|
|
27
|
+
.bind(userEmail)
|
|
28
|
+
.first<{ prefs_json: string }>();
|
|
29
|
+
if (!row) return null;
|
|
30
|
+
return parsePrefsJson(row.prefs_json);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function saveUserPrefs(
|
|
34
|
+
db: D1Database,
|
|
35
|
+
userEmail: string,
|
|
36
|
+
patch: UserPrefsJson,
|
|
37
|
+
): Promise<UserPrefsJson> {
|
|
38
|
+
const existing = (await loadUserPrefs(db, userEmail)) ?? {};
|
|
39
|
+
const merged: UserPrefsJson = { ...existing };
|
|
40
|
+
|
|
41
|
+
if (patch.gateway_id !== undefined) {
|
|
42
|
+
const trimmed = patch.gateway_id.trim();
|
|
43
|
+
if (trimmed) merged.gateway_id = trimmed;
|
|
44
|
+
else delete merged.gateway_id;
|
|
45
|
+
}
|
|
46
|
+
if (patch.cf_aig_token !== undefined) {
|
|
47
|
+
const trimmed = patch.cf_aig_token.trim();
|
|
48
|
+
if (trimmed) merged.cf_aig_token = trimmed;
|
|
49
|
+
else delete merged.cf_aig_token;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
await db.prepare(
|
|
53
|
+
`INSERT INTO user_prefs (user_email, prefs_json, updated_at)
|
|
54
|
+
VALUES (?, ?, datetime('now'))
|
|
55
|
+
ON CONFLICT(user_email) DO UPDATE SET
|
|
56
|
+
prefs_json = excluded.prefs_json,
|
|
57
|
+
updated_at = excluded.updated_at`,
|
|
58
|
+
)
|
|
59
|
+
.bind(userEmail, JSON.stringify(merged))
|
|
60
|
+
.run();
|
|
61
|
+
|
|
62
|
+
return merged;
|
|
63
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Cross-cutting helpers (v0.19.0).
|
|
2
|
+
//
|
|
3
|
+
// Pulled from src/index.ts so provider modules and future feature modules
|
|
4
|
+
// can import them without round-tripping through the worker entry. All
|
|
5
|
+
// pure functions with no I/O or env dependencies.
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Parse a `data:` URL into mime + base64 payload. Returns null for any URL
|
|
9
|
+
* that isn't a base64-encoded data URL (URL-encoded data URLs not supported;
|
|
10
|
+
* none of our upload paths produce them).
|
|
11
|
+
*/
|
|
12
|
+
export function parseDataUrl(dataUrl: string): { mime: string; base64: string } | null {
|
|
13
|
+
const match = dataUrl.match(/^data:([^;]+);base64,(.+)$/);
|
|
14
|
+
if (!match) return null;
|
|
15
|
+
return { mime: match[1], base64: match[2] };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Decode a base64 string to a fresh owned Uint8Array. Return type is
|
|
20
|
+
* Uint8Array<ArrayBuffer> (not the looser default Uint8Array<ArrayBufferLike>)
|
|
21
|
+
* so callers like `new Blob([...])` typecheck without explicit casts under
|
|
22
|
+
* TypeScript 5.7+.
|
|
23
|
+
*/
|
|
24
|
+
export function base64ToBytes(b64: string): Uint8Array<ArrayBuffer> {
|
|
25
|
+
const bin = atob(b64);
|
|
26
|
+
const out = new Uint8Array(bin.length);
|
|
27
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Encode bytes to a base64 string. Chunked because the naive
|
|
33
|
+
* `btoa(String.fromCharCode(...bytes))` spreads every byte as an argument and
|
|
34
|
+
* overflows the call stack on multi-MB inputs (e.g. an uploaded source image).
|
|
35
|
+
* 0x8000 chars/chunk is the standard safe window. Round-trips with
|
|
36
|
+
* base64ToBytes. (v0.21.6: used to inline an R2 source image as a data: URI
|
|
37
|
+
* for image-to-video, since the upstream accepts data URIs.)
|
|
38
|
+
*/
|
|
39
|
+
export function bytesToBase64(bytes: Uint8Array): string {
|
|
40
|
+
let bin = "";
|
|
41
|
+
const chunk = 0x8000;
|
|
42
|
+
for (let i = 0; i < bytes.length; i += chunk) {
|
|
43
|
+
bin += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
|
44
|
+
}
|
|
45
|
+
return btoa(bin);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Pick a file extension for a MIME type. Used for R2 object key construction
|
|
50
|
+
* and for the Content-Disposition filename header on artifact downloads.
|
|
51
|
+
* Falls through to "bin" for unknown types (covered by v0.10.3's fix: the
|
|
52
|
+
* video-gen path hardcodes mime to video/mp4 before this is called so we
|
|
53
|
+
* always get the right extension even when upstream CDNs lie about types).
|
|
54
|
+
*/
|
|
55
|
+
export function extFromMime(mime: string): string {
|
|
56
|
+
const m = mime.toLowerCase();
|
|
57
|
+
if (m.includes("png")) return "png";
|
|
58
|
+
if (m.includes("jpeg")) return "jpg";
|
|
59
|
+
if (m.includes("jpg")) return "jpg";
|
|
60
|
+
if (m.includes("webp")) return "webp";
|
|
61
|
+
if (m.includes("gif")) return "gif";
|
|
62
|
+
if (m.includes("mp4")) return "mp4";
|
|
63
|
+
if (m.includes("quicktime")) return "mov";
|
|
64
|
+
if (m.includes("mov")) return "mov";
|
|
65
|
+
if (m.includes("matroska") || m.includes("mkv")) return "mkv";
|
|
66
|
+
if (m.includes("mp3")) return "mp3";
|
|
67
|
+
if (m.includes("mpeg")) return "mp3";
|
|
68
|
+
if (m.includes("wav")) return "wav";
|
|
69
|
+
if (m.includes("ogg")) return "ogg";
|
|
70
|
+
if (m.includes("webm")) return "webm";
|
|
71
|
+
if (m.includes("m4a")) return "m4a";
|
|
72
|
+
return "bin";
|
|
73
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// v0.25.0: minimal, zero-dependency ZIP reader for the Workers runtime.
|
|
2
|
+
//
|
|
3
|
+
// Parsing is driven off the central directory (not the local headers), which
|
|
4
|
+
// is what makes this robust: the central directory always carries the real
|
|
5
|
+
// compressed/uncompressed sizes even when an entry was written with a
|
|
6
|
+
// streaming data descriptor (general-purpose bit 3), so we never have to chase
|
|
7
|
+
// the descriptor that trails the file data. For each entry we read its sizes,
|
|
8
|
+
// name, and local-header offset from the central directory, then seek to the
|
|
9
|
+
// local header only to skip past its (possibly different) name/extra fields
|
|
10
|
+
// and slice out the compressed bytes.
|
|
11
|
+
//
|
|
12
|
+
// Decompression uses the Workers-native DecompressionStream("deflate-raw"),
|
|
13
|
+
// which is also available in Node 18+ (so this module is unit-testable without
|
|
14
|
+
// the Workers pool). Stored (method 0) entries are copied as-is; deflate
|
|
15
|
+
// (method 8) entries are inflated. Any other method, encrypted entries, and
|
|
16
|
+
// zip64 archives are skipped/rejected. The 10MB document upload cap keeps real
|
|
17
|
+
// archives well under the zip64 threshold, so rejecting zip64 is safe here.
|
|
18
|
+
|
|
19
|
+
export interface ZipEntry {
|
|
20
|
+
name: string;
|
|
21
|
+
bytes: Uint8Array;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface UnzipLimits {
|
|
25
|
+
maxEntries: number; // refuse archives declaring more entries than this
|
|
26
|
+
maxTotalBytes: number; // cap on cumulative uncompressed output (zip-bomb guard)
|
|
27
|
+
maxFileBytes: number; // cap on a single entry's uncompressed size
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface UnzipResult {
|
|
31
|
+
entries: ZipEntry[];
|
|
32
|
+
skipped: Array<{ name: string; reason: string }>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const SIG_EOCD = 0x06054b50; // end of central directory
|
|
36
|
+
const SIG_CD = 0x02014b50; // central directory file header
|
|
37
|
+
const SIG_LOCAL = 0x04034b50; // local file header
|
|
38
|
+
|
|
39
|
+
// Magic-byte check: a ZIP starts with a local file header, or with the EOCD
|
|
40
|
+
// signature in the empty-archive case. Detection is independent of extension.
|
|
41
|
+
export function isZip(bytes: Uint8Array): boolean {
|
|
42
|
+
return bytes.length >= 4 &&
|
|
43
|
+
bytes[0] === 0x50 && bytes[1] === 0x4b &&
|
|
44
|
+
((bytes[2] === 0x03 && bytes[3] === 0x04) || // local file header "PK\x03\x04"
|
|
45
|
+
(bytes[2] === 0x05 && bytes[3] === 0x06)); // empty archive EOCD "PK\x05\x06"
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function inflateRaw(data: Uint8Array): Promise<Uint8Array> {
|
|
49
|
+
const ds = new DecompressionStream("deflate-raw");
|
|
50
|
+
const stream = new Response(data).body!.pipeThrough(ds);
|
|
51
|
+
return new Uint8Array(await new Response(stream).arrayBuffer());
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function unzip(bytes: Uint8Array, limits: UnzipLimits): Promise<UnzipResult> {
|
|
55
|
+
const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
56
|
+
const u16 = (o: number) => dv.getUint16(o, true);
|
|
57
|
+
const u32 = (o: number) => dv.getUint32(o, true);
|
|
58
|
+
|
|
59
|
+
// The EOCD lives at the tail. Its trailing comment can be up to 65535 bytes,
|
|
60
|
+
// so scan backwards through that window for the signature.
|
|
61
|
+
const MIN_EOCD = 22;
|
|
62
|
+
let eocd = -1;
|
|
63
|
+
const floor = Math.max(0, bytes.length - (MIN_EOCD + 0xffff));
|
|
64
|
+
for (let i = bytes.length - MIN_EOCD; i >= floor; i--) {
|
|
65
|
+
if (u32(i) === SIG_EOCD) { eocd = i; break; }
|
|
66
|
+
}
|
|
67
|
+
if (eocd < 0) throw new Error("not a valid zip (no end-of-central-directory record)");
|
|
68
|
+
|
|
69
|
+
const cdCount = u16(eocd + 10);
|
|
70
|
+
const cdSize = u32(eocd + 12);
|
|
71
|
+
const cdOffset = u32(eocd + 16);
|
|
72
|
+
if (cdCount === 0xffff || cdSize === 0xffffffff || cdOffset === 0xffffffff) {
|
|
73
|
+
throw new Error("zip64 archives are not supported");
|
|
74
|
+
}
|
|
75
|
+
if (cdCount > limits.maxEntries) {
|
|
76
|
+
throw new Error(`zip declares ${cdCount} entries, over the limit of ${limits.maxEntries}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const entries: ZipEntry[] = [];
|
|
80
|
+
const skipped: Array<{ name: string; reason: string }> = [];
|
|
81
|
+
const decoder = new TextDecoder("utf-8");
|
|
82
|
+
let total = 0;
|
|
83
|
+
let p = cdOffset;
|
|
84
|
+
|
|
85
|
+
for (let n = 0; n < cdCount; n++) {
|
|
86
|
+
if (u32(p) !== SIG_CD) throw new Error("corrupt zip (bad central directory header)");
|
|
87
|
+
const flag = u16(p + 8);
|
|
88
|
+
const method = u16(p + 10);
|
|
89
|
+
const compSize = u32(p + 20);
|
|
90
|
+
const uncompSize = u32(p + 24);
|
|
91
|
+
const nameLen = u16(p + 28);
|
|
92
|
+
const extraLen = u16(p + 30);
|
|
93
|
+
const commentLen = u16(p + 32);
|
|
94
|
+
const localOffset = u32(p + 42);
|
|
95
|
+
const name = decoder.decode(bytes.subarray(p + 46, p + 46 + nameLen));
|
|
96
|
+
p = p + 46 + nameLen + extraLen + commentLen;
|
|
97
|
+
|
|
98
|
+
if (name.endsWith("/")) continue; // directory entry, no data
|
|
99
|
+
if (flag & 0x0001) { skipped.push({ name, reason: "encrypted" }); continue; }
|
|
100
|
+
if (compSize === 0xffffffff || uncompSize === 0xffffffff || localOffset === 0xffffffff) {
|
|
101
|
+
skipped.push({ name, reason: "zip64 entry not supported" }); continue;
|
|
102
|
+
}
|
|
103
|
+
if (uncompSize > limits.maxFileBytes) {
|
|
104
|
+
skipped.push({ name, reason: `uncompressed size ${uncompSize} over per-file limit` }); continue;
|
|
105
|
+
}
|
|
106
|
+
if (total + uncompSize > limits.maxTotalBytes) {
|
|
107
|
+
skipped.push({ name, reason: "cumulative uncompressed size limit reached" }); continue;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Seek the local header to find where the data actually starts. The local
|
|
111
|
+
// header's name/extra lengths can differ from the central directory's, so
|
|
112
|
+
// re-read them here rather than reusing nameLen/extraLen.
|
|
113
|
+
if (u32(localOffset) !== SIG_LOCAL) { skipped.push({ name, reason: "bad local header" }); continue; }
|
|
114
|
+
const dataStart = localOffset + 30 + u16(localOffset + 26) + u16(localOffset + 28);
|
|
115
|
+
const comp = bytes.subarray(dataStart, dataStart + compSize);
|
|
116
|
+
|
|
117
|
+
let out: Uint8Array;
|
|
118
|
+
if (method === 0) {
|
|
119
|
+
out = comp.slice();
|
|
120
|
+
} else if (method === 8) {
|
|
121
|
+
try {
|
|
122
|
+
out = await inflateRaw(comp);
|
|
123
|
+
} catch {
|
|
124
|
+
skipped.push({ name, reason: "inflate failed" });
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
} else {
|
|
128
|
+
skipped.push({ name, reason: `unsupported compression method ${method}` });
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
total += out.length;
|
|
133
|
+
entries.push({ name, bytes: out });
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return { entries, skipped };
|
|
137
|
+
}
|