@teable/app 0.0.0-stage → 5.0.1

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.
@@ -0,0 +1,1126 @@
1
+ import {
2
+ describeTables
3
+ } from "./LV3ZHKKL.js";
4
+ import {
5
+ CAPABILITIES,
6
+ PROTOCOL_VERSION,
7
+ admit
8
+ } from "./JQWQD45Z.js";
9
+
10
+ // src/server/errors.ts
11
+ import { z } from "zod";
12
+ var AppError = class extends Error {
13
+ code;
14
+ issues;
15
+ constructor(code, message, issues) {
16
+ super(message);
17
+ this.name = "AppError";
18
+ this.code = code;
19
+ this.issues = issues;
20
+ }
21
+ };
22
+ var FAIL_CODES = [
23
+ "BAD_INPUT",
24
+ "FORBIDDEN",
25
+ "NOT_FOUND",
26
+ "CONFLICT"
27
+ ];
28
+ function fail(code, message) {
29
+ if (!FAIL_CODES.includes(code)) {
30
+ throw new Error(`fail() takes ${FAIL_CODES.join(", ")}; "${code}" is the platform's`);
31
+ }
32
+ throw new AppError(code, message);
33
+ }
34
+ function toErrorShape(error) {
35
+ if (error instanceof AppError) {
36
+ return error.issues ? { code: error.code, message: error.message, issues: error.issues } : { code: error.code, message: error.message };
37
+ }
38
+ if (error instanceof z.ZodError) {
39
+ return {
40
+ code: "BAD_INPUT",
41
+ message: "Input does not match the method's schema",
42
+ issues: issuesOf(error)
43
+ };
44
+ }
45
+ const message = error instanceof Error ? error.message : String(error);
46
+ if (message.includes("SQLITE_CONSTRAINT")) {
47
+ return { code: "CONSTRAINT", message: describeConstraint(message) };
48
+ }
49
+ return { code: "INTERNAL", message };
50
+ }
51
+ function issuesOf(error) {
52
+ return error.issues.map((issue) => ({
53
+ path: issue.path.map((p) => typeof p === "symbol" ? String(p) : p),
54
+ message: issue.message
55
+ }));
56
+ }
57
+ function describeConstraint(message) {
58
+ const end = message.indexOf(": SQLITE_CONSTRAINT");
59
+ return end === -1 ? message : message.slice(0, end);
60
+ }
61
+
62
+ // src/server/app.ts
63
+ import { DurableObject } from "cloudflare:workers";
64
+ import { drizzle } from "drizzle-orm/durable-sqlite";
65
+ import { z as z2 } from "zod";
66
+
67
+ // src/server/changefeed.ts
68
+ var RESERVED_PREFIX = "_teable_";
69
+ var OUTSIDE_WRITE = "teable: rows change only inside write methods";
70
+ var OPS = ["insert", "update", "delete"];
71
+ var TRIGGER_PREFIX = `${RESERVED_PREFIX}cf_`;
72
+ function ident(name) {
73
+ return `"${name.replaceAll('"', '""')}"`;
74
+ }
75
+ function literal(value) {
76
+ return `'${value.replaceAll("'", "''")}'`;
77
+ }
78
+ function appTableNames(sql) {
79
+ return sql.exec(
80
+ "SELECT name FROM pragma_table_list WHERE schema = 'main' AND type = 'table' ORDER BY name"
81
+ ).toArray().map((row) => row.name).filter(
82
+ (name) => !name.startsWith(RESERVED_PREFIX) && !name.startsWith("sqlite_") && !name.startsWith("_cf_") && name !== "__drizzle_migrations"
83
+ );
84
+ }
85
+ var PAIRS_PER_CALL = 60;
86
+ function rowJson(prefix, columns) {
87
+ const values = columns.map((c) => {
88
+ if (c.name.includes('"')) throw new Error(`Column names cannot contain '"': ${c.name}`);
89
+ const ref = `${prefix}.${ident(c.name)}`;
90
+ return {
91
+ name: c.name,
92
+ value: `CASE WHEN typeof(${ref}) = 'blob' THEN hex(${ref}) ELSE ${ref} END`
93
+ };
94
+ });
95
+ const first = values.slice(0, PAIRS_PER_CALL);
96
+ let json = `json_object(${first.map((v) => `${literal(v.name)}, ${v.value}`).join(", ")})`;
97
+ for (let i = PAIRS_PER_CALL; i < values.length; i += PAIRS_PER_CALL) {
98
+ const chunk = values.slice(i, i + PAIRS_PER_CALL);
99
+ json = `json_set(${json}, ${chunk.map((v) => `${literal(`$."${v.name}"`)}, ${v.value}`).join(", ")})`;
100
+ }
101
+ return json;
102
+ }
103
+ function pkExpression(prefix, columns) {
104
+ const keys = columns.filter((c) => c.pk > 0).sort((a, b) => a.pk - b.pk);
105
+ const [first] = keys;
106
+ if (first === void 0) return `${prefix}.rowid`;
107
+ if (keys.length === 1) return `${prefix}.${ident(first.name)}`;
108
+ return `json_array(${keys.map((c) => `${prefix}.${ident(c.name)}`).join(", ")})`;
109
+ }
110
+ function triggerSql(table, op, columns) {
111
+ const rowRef = op === "delete" ? "OLD" : "NEW";
112
+ const oldJson = op === "insert" ? "NULL" : rowJson("OLD", columns);
113
+ const newJson = op === "delete" ? "NULL" : rowJson("NEW", columns);
114
+ return [
115
+ `CREATE TRIGGER ${ident(`${TRIGGER_PREFIX}${table}_${op}`)} AFTER ${op.toUpperCase()} ON ${ident(table)} BEGIN`,
116
+ `SELECT RAISE(ABORT, ${literal(OUTSIDE_WRITE)}) FROM _teable_context WHERE id = 1 AND invocation IS NULL;`,
117
+ "INSERT INTO _teable_changes (invocation, tbl, op, pk, old, new) VALUES (",
118
+ `(SELECT invocation FROM _teable_context WHERE id = 1), ${literal(table)}, ${literal(op)},`,
119
+ `${pkExpression(rowRef, columns)}, ${oldJson}, ${newJson}); END`
120
+ ].join(" ");
121
+ }
122
+ function existingTriggers(sql) {
123
+ return sql.exec(
124
+ "SELECT name, sql FROM sqlite_schema WHERE type = 'trigger' AND name LIKE '\\_teable\\_cf\\_%' ESCAPE '\\'"
125
+ ).toArray();
126
+ }
127
+ function dropTriggers(sql) {
128
+ for (const trigger of existingTriggers(sql)) {
129
+ sql.exec(`DROP TRIGGER IF EXISTS ${ident(trigger.name)}`);
130
+ }
131
+ }
132
+ function syncTriggers(sql) {
133
+ const wanted = /* @__PURE__ */ new Map();
134
+ for (const table of appTableNames(sql)) {
135
+ const columns = sql.exec(`SELECT name, pk FROM pragma_table_xinfo(?)`, table).toArray();
136
+ for (const op of OPS)
137
+ wanted.set(`${TRIGGER_PREFIX}${table}_${op}`, triggerSql(table, op, columns));
138
+ }
139
+ for (const trigger of existingTriggers(sql)) {
140
+ if (wanted.get(trigger.name) !== trigger.sql) {
141
+ sql.exec(`DROP TRIGGER IF EXISTS ${ident(trigger.name)}`);
142
+ } else {
143
+ wanted.delete(trigger.name);
144
+ }
145
+ }
146
+ for (const statement of wanted.values()) sql.exec(statement);
147
+ }
148
+ function beginInvocation(sql, method, caller, at) {
149
+ const { id } = sql.exec(
150
+ "INSERT INTO _teable_invocations (method, caller, at) VALUES (?, ?, ?) RETURNING id",
151
+ method,
152
+ JSON.stringify(caller),
153
+ at
154
+ ).one();
155
+ sql.exec("UPDATE _teable_context SET invocation = ? WHERE id = 1", id);
156
+ return id;
157
+ }
158
+ function endInvocation(sql) {
159
+ sql.exec("UPDATE _teable_context SET invocation = NULL WHERE id = 1");
160
+ }
161
+ function currentCursor(sql) {
162
+ return sql.exec("SELECT seq FROM sqlite_sequence WHERE name = '_teable_changes'").toArray()[0]?.seq ?? 0;
163
+ }
164
+ function changedTablesSince(sql, before) {
165
+ return sql.exec(
166
+ "SELECT DISTINCT tbl FROM _teable_changes WHERE seq > ? ORDER BY tbl",
167
+ before
168
+ ).toArray().map((row) => row.tbl);
169
+ }
170
+ function expiredThrough(sql) {
171
+ const oldest = sql.exec("SELECT min(seq) AS seq FROM _teable_changes").one().seq;
172
+ return oldest === null ? currentCursor(sql) : oldest - 1;
173
+ }
174
+ function readChanges(sql, since, limit) {
175
+ if (since < expiredThrough(sql)) return null;
176
+ return sql.exec(
177
+ "SELECT seq, invocation, tbl, op, pk, old, new FROM _teable_changes WHERE seq > ? ORDER BY seq LIMIT ?",
178
+ since,
179
+ limit
180
+ ).toArray().map((row) => ({
181
+ seq: row.seq,
182
+ table: row.tbl,
183
+ op: row.op,
184
+ pk: row.pk,
185
+ old: row.old === null ? null : JSON.parse(row.old),
186
+ new: row.new === null ? null : JSON.parse(row.new),
187
+ invocation: row.invocation
188
+ }));
189
+ }
190
+ var HISTORY_MS = 30 * 24 * 60 * 6e4;
191
+ var PRUNE_BATCH = 1e3;
192
+ function pruneHistory(sql, now, invocation) {
193
+ const before = now - HISTORY_MS;
194
+ const oldest = sql.exec("SELECT at FROM _teable_invocations ORDER BY id LIMIT 1").toArray()[0];
195
+ if (oldest === void 0 || oldest.at >= before) return;
196
+ const made = sql.exec(
197
+ "SELECT count(*) AS n FROM _teable_changes WHERE invocation = ?",
198
+ invocation
199
+ ).one().n;
200
+ const limit = PRUNE_BATCH + made;
201
+ let last = 0;
202
+ for (const row of sql.exec(
203
+ "SELECT id, at FROM _teable_invocations ORDER BY id LIMIT ?",
204
+ limit
205
+ )) {
206
+ if (row.at >= before) break;
207
+ last = row.id;
208
+ }
209
+ const kept = sql.exec(
210
+ "SELECT seq FROM _teable_changes WHERE invocation > ? ORDER BY invocation, seq LIMIT 1",
211
+ last
212
+ ).toArray()[0];
213
+ sql.exec(
214
+ "DELETE FROM _teable_changes WHERE seq IN (SELECT seq FROM _teable_changes WHERE seq < ? ORDER BY seq LIMIT ?)",
215
+ kept?.seq ?? Number.POSITIVE_INFINITY,
216
+ limit
217
+ );
218
+ sql.exec(
219
+ `DELETE FROM _teable_invocations WHERE id <= ?
220
+ AND NOT EXISTS (SELECT 1 FROM _teable_changes AS c WHERE c.invocation = _teable_invocations.id)`,
221
+ last
222
+ );
223
+ }
224
+
225
+ // src/server/cron.ts
226
+ function field(text, min, max, name) {
227
+ const values = /* @__PURE__ */ new Set();
228
+ for (const part of text.split(",")) {
229
+ const match = part.match(/^(\*|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/);
230
+ if (!match) throw new Error(`Bad cron ${name}: "${part}"`);
231
+ const [, all, from, to, step] = match;
232
+ const start = all === "*" ? min : Number(from);
233
+ const end = all === "*" ? max : to !== void 0 ? Number(to) : step ? max : start;
234
+ const by = step ? Number(step) : 1;
235
+ if (start < min || end > max || start > end || by < 1) {
236
+ throw new Error(`Bad cron ${name}: "${part}" (allowed ${min}-${max})`);
237
+ }
238
+ for (let v = start; v <= end; v += by) values.add(v);
239
+ }
240
+ return [...values].sort((a, b) => a - b);
241
+ }
242
+ function parseCron(expression) {
243
+ const parts = expression.trim().split(/\s+/);
244
+ if (parts.length !== 5) throw new Error(`Cron needs 5 fields: "${expression}"`);
245
+ const [minute, hour, day, month, weekday] = parts;
246
+ return {
247
+ minutes: field(minute, 0, 59, "minute"),
248
+ hours: field(hour, 0, 23, "hour"),
249
+ days: new Set(field(day, 1, 31, "day of month")),
250
+ months: new Set(field(month, 1, 12, "month")),
251
+ weekdays: new Set(field(weekday, 0, 7, "day of week").map((d) => d % 7)),
252
+ daysRestricted: day !== "*",
253
+ weekdaysRestricted: weekday !== "*"
254
+ };
255
+ }
256
+ var formatters = /* @__PURE__ */ new Map();
257
+ function wall(instant, timeZone) {
258
+ let format = formatters.get(timeZone);
259
+ if (!format) {
260
+ format = new Intl.DateTimeFormat("en-US", {
261
+ timeZone,
262
+ hourCycle: "h23",
263
+ year: "numeric",
264
+ month: "numeric",
265
+ day: "numeric",
266
+ hour: "numeric",
267
+ minute: "numeric"
268
+ });
269
+ formatters.set(timeZone, format);
270
+ }
271
+ const parts = Object.fromEntries(format.formatToParts(instant).map((p) => [p.type, p.value]));
272
+ return {
273
+ year: Number(parts.year),
274
+ month: Number(parts.month),
275
+ day: Number(parts.day),
276
+ hour: Number(parts.hour),
277
+ minute: Number(parts.minute)
278
+ };
279
+ }
280
+ var MINUTE = 6e4;
281
+ var HOUR = 60 * MINUTE;
282
+ var DAY = 24 * HOUR;
283
+ function offsetAt(instant, timeZone) {
284
+ const at = Math.floor(instant / MINUTE) * MINUTE;
285
+ const w = wall(at, timeZone);
286
+ return Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute) - at;
287
+ }
288
+ function changeAt(low, high, before, timeZone) {
289
+ while (high - low > MINUTE) {
290
+ const middle = low + Math.floor((high - low) / (2 * MINUTE)) * MINUTE;
291
+ if (offsetAt(middle, timeZone) === before) low = middle;
292
+ else high = middle;
293
+ }
294
+ return high;
295
+ }
296
+ function onDay(cron, date) {
297
+ if (!cron.months.has(date.getUTCMonth() + 1)) return false;
298
+ const day = cron.days.has(date.getUTCDate());
299
+ const weekday = cron.weekdays.has(date.getUTCDay());
300
+ return cron.daysRestricted && cron.weekdaysRestricted ? day || weekday : day && weekday;
301
+ }
302
+ function firingsOn(cron, midnight, timeZone) {
303
+ const before = offsetAt(midnight - DAY, timeZone);
304
+ const after = offsetAt(midnight + 2 * DAY, timeZone);
305
+ const change = before === after ? Number.POSITIVE_INFINITY : changeAt(midnight - DAY, midnight + 2 * DAY, before, timeZone);
306
+ const everyHour = cron.hours.length === 24;
307
+ const firings = [];
308
+ for (const hour of cron.hours) {
309
+ for (const minute of cron.minutes) {
310
+ const local = midnight + hour * HOUR + minute * MINUTE;
311
+ const early = local - before;
312
+ const late = local - after;
313
+ if (everyHour) {
314
+ if (early < change) firings.push(early);
315
+ if (late >= change) firings.push(late);
316
+ } else {
317
+ const skipped = early >= change && late < change;
318
+ firings.push(early < change || skipped ? early : late);
319
+ }
320
+ }
321
+ }
322
+ return firings;
323
+ }
324
+ function nextFire(expression, timeZone, after) {
325
+ const cron = parseCron(expression);
326
+ const start = wall(after, timeZone);
327
+ let next = Number.POSITIVE_INFINITY;
328
+ for (let offset = -1; offset < 1500; offset++) {
329
+ const midnight = Date.UTC(start.year, start.month - 1, start.day + offset);
330
+ if (next <= midnight - DAY) break;
331
+ if (!onDay(cron, new Date(midnight))) continue;
332
+ for (const at of firingsOn(cron, midnight, timeZone)) {
333
+ if (at > after && at < next) next = at;
334
+ }
335
+ }
336
+ if (next === Number.POSITIVE_INFINITY) throw new Error(`Cron "${expression}" never fires`);
337
+ return next;
338
+ }
339
+
340
+ // src/server/tasks.ts
341
+ var DEFAULT_MAX_ATTEMPTS = 8;
342
+ var LEASE_MS = 5 * 6e4;
343
+ var TASKS_PER_WAKE = 25;
344
+ var DEAD_TASKS_PER_PRUNE = 4 * TASKS_PER_WAKE;
345
+ function retryDelay(attempt) {
346
+ return Math.min(1e3 * 2 ** (attempt - 1), 60 * 6e4);
347
+ }
348
+ function enqueueTask(sql, task, now) {
349
+ sql.exec(
350
+ "INSERT INTO _teable_tasks (method, input, run_at, invocation, created_at) VALUES (?, ?, ?, ?, ?)",
351
+ task.method,
352
+ task.input,
353
+ task.runAt,
354
+ task.invocation,
355
+ now
356
+ );
357
+ }
358
+ function claimNextTask(sql, now) {
359
+ return sql.exec(
360
+ `UPDATE _teable_tasks SET lease_until = ?, attempts = attempts + 1
361
+ WHERE id = (
362
+ SELECT id FROM _teable_tasks
363
+ WHERE status = 'pending' AND run_at <= ? AND (lease_until IS NULL OR lease_until <= ?)
364
+ ORDER BY run_at, id LIMIT 1
365
+ )
366
+ RETURNING id, method, input, attempts`,
367
+ now + LEASE_MS,
368
+ now,
369
+ now
370
+ ).toArray()[0] ?? null;
371
+ }
372
+ function bury(sql, id, error, now) {
373
+ sql.exec(
374
+ "UPDATE _teable_tasks SET status = 'dead', last_error = ?, run_at = ?, lease_until = NULL WHERE id = ?",
375
+ error,
376
+ now,
377
+ id
378
+ );
379
+ }
380
+ async function runDueTasks(storage, now, handlerFor) {
381
+ const sql = storage.sql;
382
+ const failed = [];
383
+ for (let claimed = 0; claimed < TASKS_PER_WAKE; claimed++) {
384
+ const task = claimNextTask(sql, now);
385
+ if (task === null) break;
386
+ const handler = handlerFor(task.method);
387
+ const maxAttempts = handler?.maxAttempts ?? 1;
388
+ const report = (error, dead) => failed.push({ method: task.method, attempt: task.attempts, error, dead });
389
+ if (task.attempts > maxAttempts) {
390
+ const message = `Gave up after ${maxAttempts} attempts; the last one never finished (the app crashed or ran out of time)`;
391
+ bury(sql, task.id, message, now);
392
+ report({ code: "INTERNAL", message }, true);
393
+ continue;
394
+ }
395
+ sql.exec("UPDATE _teable_attempts SET unreported = unreported + 1");
396
+ await storage.sync();
397
+ try {
398
+ if (handler === void 0) {
399
+ throw new Error(`Task "${task.method}" is not defined in this version of the app`);
400
+ }
401
+ await handler.run(JSON.parse(task.input), task.attempts);
402
+ sql.exec("DELETE FROM _teable_tasks WHERE id = ?", task.id);
403
+ } catch (thrown) {
404
+ const error = toErrorShape(thrown);
405
+ const dead = task.attempts >= maxAttempts;
406
+ if (dead) {
407
+ bury(sql, task.id, error.message, now);
408
+ } else {
409
+ sql.exec(
410
+ "UPDATE _teable_tasks SET last_error = ?, run_at = ?, lease_until = NULL WHERE id = ?",
411
+ error.message,
412
+ Math.max(now, Date.now()) + retryDelay(task.attempts),
413
+ task.id
414
+ );
415
+ }
416
+ report(error, dead);
417
+ }
418
+ }
419
+ pruneDeadTasks(sql, now);
420
+ return failed;
421
+ }
422
+ function takeAttempts(sql) {
423
+ const { unreported } = sql.exec("SELECT unreported FROM _teable_attempts").one();
424
+ if (unreported > 0) sql.exec("UPDATE _teable_attempts SET unreported = 0");
425
+ return unreported;
426
+ }
427
+ function nextTaskAt(sql) {
428
+ return sql.exec(
429
+ "SELECT min(max(run_at, coalesce(lease_until, 0))) AS at FROM _teable_tasks WHERE status = 'pending'"
430
+ ).one().at;
431
+ }
432
+ function pruneDeadTasks(sql, now) {
433
+ sql.exec(
434
+ `DELETE FROM _teable_tasks WHERE id IN (
435
+ SELECT id FROM _teable_tasks WHERE status = 'dead' AND run_at < ? ORDER BY run_at LIMIT ?
436
+ )`,
437
+ now - HISTORY_MS,
438
+ DEAD_TASKS_PER_PRUNE
439
+ );
440
+ }
441
+
442
+ // src/server/schedules.ts
443
+ function syncSchedules(sql, methods, now) {
444
+ const schedules = methods.flatMap((m) => m.schedule ? [{ task: m.name, ...m.schedule }] : []);
445
+ const stored = new Map(
446
+ sql.exec(
447
+ "SELECT task, cron, timezone FROM _teable_schedules"
448
+ ).toArray().map((row) => [row.task, row])
449
+ );
450
+ for (const schedule of schedules) {
451
+ const current = stored.get(schedule.task);
452
+ stored.delete(schedule.task);
453
+ if (current?.cron === schedule.cron && current.timezone === schedule.timezone) continue;
454
+ sql.exec(
455
+ "INSERT OR REPLACE INTO _teable_schedules (task, cron, timezone, next_at) VALUES (?, ?, ?, ?)",
456
+ schedule.task,
457
+ schedule.cron,
458
+ schedule.timezone,
459
+ nextFire(schedule.cron, schedule.timezone, now)
460
+ );
461
+ }
462
+ for (const task of stored.keys()) sql.exec("DELETE FROM _teable_schedules WHERE task = ?", task);
463
+ }
464
+ function fireDueSchedules(sql, now) {
465
+ const due = sql.exec(
466
+ "SELECT task, cron, timezone, next_at FROM _teable_schedules WHERE next_at <= ?",
467
+ now
468
+ ).toArray();
469
+ for (const schedule of due) {
470
+ enqueueTask(
471
+ sql,
472
+ { method: schedule.task, input: "{}", runAt: schedule.next_at, invocation: null },
473
+ now
474
+ );
475
+ sql.exec(
476
+ "UPDATE _teable_schedules SET next_at = ? WHERE task = ?",
477
+ nextFire(schedule.cron, schedule.timezone, now),
478
+ schedule.task
479
+ );
480
+ }
481
+ }
482
+ function nextScheduleAt(sql) {
483
+ return sql.exec("SELECT min(next_at) AS at FROM _teable_schedules").one().at;
484
+ }
485
+
486
+ // src/server/migrations.ts
487
+ var PLATFORM_MIGRATIONS = [
488
+ // 1: the first versioned layout. Every statement also brings a database
489
+ // created before versions existed to it, so no version needs a special case.
490
+ [
491
+ `CREATE TABLE IF NOT EXISTS _teable_invocations (
492
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
493
+ method TEXT NOT NULL,
494
+ caller TEXT NOT NULL,
495
+ at INTEGER NOT NULL
496
+ )`,
497
+ // Retention walks invocations in id order and no longer needs it.
498
+ "DROP INDEX IF EXISTS _teable_invocations_at",
499
+ // The invocation the running write records changes for; triggers read it.
500
+ // It holds nothing between calls, so it is recreated, which also drops the
501
+ // guard column of databases created before versions existed.
502
+ "DROP TABLE IF EXISTS _teable_context",
503
+ `CREATE TABLE _teable_context (
504
+ id INTEGER PRIMARY KEY CHECK (id = 1),
505
+ invocation INTEGER
506
+ )`,
507
+ "INSERT INTO _teable_context (id, invocation) VALUES (1, NULL)",
508
+ // `invocation` is never NULL: the triggers refuse a change made outside a write.
509
+ `CREATE TABLE IF NOT EXISTS _teable_changes (
510
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
511
+ invocation INTEGER,
512
+ tbl TEXT NOT NULL,
513
+ op TEXT NOT NULL,
514
+ pk,
515
+ old TEXT,
516
+ new TEXT
517
+ )`,
518
+ "CREATE INDEX IF NOT EXISTS _teable_changes_invocation ON _teable_changes (invocation)",
519
+ // Changes made by migrations, recorded before migrations ran with the
520
+ // triggers dropped; the feed does not carry them (ADR 0004).
521
+ "DELETE FROM _teable_changes WHERE invocation IS NULL",
522
+ `CREATE TABLE IF NOT EXISTS _teable_tasks (
523
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
524
+ method TEXT NOT NULL,
525
+ input TEXT NOT NULL,
526
+ run_at INTEGER NOT NULL,
527
+ lease_until INTEGER,
528
+ attempts INTEGER NOT NULL DEFAULT 0,
529
+ last_error TEXT,
530
+ status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'dead')),
531
+ invocation INTEGER,
532
+ created_at INTEGER NOT NULL
533
+ )`,
534
+ "CREATE INDEX IF NOT EXISTS _teable_tasks_due ON _teable_tasks (status, run_at)",
535
+ `CREATE TABLE IF NOT EXISTS _teable_migrations (
536
+ tag TEXT PRIMARY KEY,
537
+ hash TEXT NOT NULL,
538
+ created_at INTEGER NOT NULL
539
+ )`,
540
+ `CREATE TABLE IF NOT EXISTS _teable_schedules (
541
+ task TEXT PRIMARY KEY,
542
+ cron TEXT NOT NULL,
543
+ timezone TEXT NOT NULL,
544
+ next_at INTEGER NOT NULL
545
+ )`
546
+ ],
547
+ // 2: task attempts started and not yet reported to the host, which meters
548
+ // them (ADR 0006). They outlive a wake that crashes, so the next one reports them.
549
+ [
550
+ `CREATE TABLE _teable_attempts (
551
+ id INTEGER PRIMARY KEY CHECK (id = 1),
552
+ unreported INTEGER NOT NULL CHECK (unreported >= 0)
553
+ )`,
554
+ "INSERT INTO _teable_attempts (id, unreported) VALUES (1, 0)"
555
+ ]
556
+ ];
557
+ var PLATFORM_VERSION = PLATFORM_MIGRATIONS.length;
558
+ function migratePlatform(sql) {
559
+ sql.exec(
560
+ "CREATE TABLE IF NOT EXISTS _teable_meta (id INTEGER PRIMARY KEY CHECK (id = 1), version INTEGER NOT NULL)"
561
+ );
562
+ sql.exec("INSERT OR IGNORE INTO _teable_meta (id, version) VALUES (1, 0)");
563
+ const { version } = sql.exec("SELECT version FROM _teable_meta").one();
564
+ if (version > PLATFORM_VERSION) {
565
+ throw new Error(
566
+ `The database's platform tables are at version ${version}, newer than this @teable/app (version ${PLATFORM_VERSION}); deploy with a newer @teable/app`
567
+ );
568
+ }
569
+ for (const statements of PLATFORM_MIGRATIONS.slice(version)) {
570
+ for (const statement of statements) sql.exec(statement);
571
+ }
572
+ sql.exec("UPDATE _teable_meta SET version = ?", PLATFORM_VERSION);
573
+ }
574
+ async function prepareDatabase(storage, migrations, app) {
575
+ const sql = storage.sql;
576
+ const hashes = await hashMigrations(migrations);
577
+ storage.transactionSync(() => {
578
+ migratePlatform(sql);
579
+ const pending = pendingMigrations(sql, migrations, hashes);
580
+ if (pending.length > 0) runMigrations(sql, migrations, pending, hashes);
581
+ checkSchema(sql, app.tables);
582
+ syncTriggers(sql);
583
+ syncSchedules(sql, app.methods, Date.now());
584
+ });
585
+ }
586
+ function runMigrations(sql, migrations, pending, hashes) {
587
+ dropTriggers(sql);
588
+ sql.exec("PRAGMA defer_foreign_keys = ON");
589
+ for (const entry of pending) {
590
+ const text = migrations.migrations[migrationKey(entry.idx)] ?? "";
591
+ const triggers = appTriggers(sql);
592
+ for (const statement of text.split("--> statement-breakpoint")) {
593
+ if (statement.trim() === "") continue;
594
+ refuseLosingRows(sql, statement, entry.tag);
595
+ try {
596
+ sql.exec(statement);
597
+ } catch (error) {
598
+ throw new Error(`Migration ${entry.tag} failed: ${explainFailure(error)}`);
599
+ }
600
+ }
601
+ checkTriggersKept(sql, triggers, entry.tag, text);
602
+ sql.exec(
603
+ "INSERT INTO _teable_migrations (tag, hash, created_at) VALUES (?, ?, ?)",
604
+ entry.tag,
605
+ hashes.get(entry.tag),
606
+ entry.when
607
+ );
608
+ }
609
+ const orphans = sql.exec('SELECT "table", parent FROM pragma_foreign_key_check').toArray();
610
+ if (orphans.length > 0) {
611
+ const [first] = orphans;
612
+ throw new Error(
613
+ `Migrations would leave ${orphans.length} row(s) in ${first?.table} pointing at missing rows in ${first?.parent}`
614
+ );
615
+ }
616
+ sql.exec("PRAGMA defer_foreign_keys = OFF");
617
+ }
618
+ var NAME = String.raw`(?:"(?:[^"]|"")+"|\x60(?:[^\x60]|\x60\x60)+\x60|\[[^\]]+\]|[^\s;.,()"\x60\[\]]+)`;
619
+ var DROP_TABLE = new RegExp(
620
+ String.raw`\bDROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:${NAME}\s*\.\s*)?(${NAME})`,
621
+ "gi"
622
+ );
623
+ function droppedTables(statement) {
624
+ return [...statement.matchAll(DROP_TABLE)].map(([, name = ""]) => {
625
+ const quote = name[0];
626
+ if (quote === "[") return name.slice(1, -1);
627
+ if (quote === '"' || quote === "`") return name.slice(1, -1).replaceAll(quote + quote, quote);
628
+ return name;
629
+ });
630
+ }
631
+ function refuseLosingRows(sql, statement, tag) {
632
+ for (const table of droppedTables(statement)) {
633
+ const references = sql.exec(
634
+ `SELECT t.name AS child, json_group_array(f."from") AS columns, f.on_delete AS action
635
+ FROM pragma_table_list AS t, pragma_foreign_key_list(t.name) AS f
636
+ WHERE t.schema = 'main' AND t.type = 'table' AND t.name <> ? COLLATE NOCASE
637
+ AND f."table" = ? COLLATE NOCASE AND f.on_delete IN ('CASCADE', 'SET NULL', 'SET DEFAULT')
638
+ GROUP BY t.name, f.id
639
+ ORDER BY t.name, f.id`,
640
+ table,
641
+ table
642
+ ).toArray();
643
+ for (const reference of references) {
644
+ const { child, action } = reference;
645
+ const columns = JSON.parse(reference.columns);
646
+ const rows = sql.exec(
647
+ `SELECT count(*) AS n FROM ${ident(child)} WHERE ${columns.map((c) => `${ident(c)} IS NOT NULL`).join(" AND ")}`
648
+ ).one().n;
649
+ if (rows === 0) continue;
650
+ const key = columns.length === 1 ? `${child}.${columns[0]}` : `${child} (${columns.join(", ")})`;
651
+ const loss = action === "CASCADE" ? `${rows} row(s) of ${child} would be deleted` : `${key} would be set to ${action === "SET NULL" ? "NULL" : "its default"} in ${rows} row(s)`;
652
+ throw new Error(
653
+ `Migration ${tag} drops table ${table}, and dropping a table deletes its rows first: ${key} references ${table} ON DELETE ${action}, so ${loss}. (drizzle-kit changes a table by copying it, dropping it and renaming the copy.) First change ${key} to ON DELETE NO ACTION or RESTRICT in a migration of its own, which rebuilds only ${child}, or move ${child}'s rows aside before the drop and back after it, in this migration.`
654
+ );
655
+ }
656
+ }
657
+ }
658
+ function explainFailure(error) {
659
+ const message = error instanceof Error ? error.message : String(error);
660
+ const match = /error in trigger ([^:]+): no such table: (?:main\.)?([^\s:]+)/.exec(message);
661
+ if (!match) return message;
662
+ const [, trigger, table] = match;
663
+ return `${message}. Trigger "${trigger}" uses ${table}, which this migration rebuilds: drop the trigger before the rebuild and create it again after it, in the same migration.`;
664
+ }
665
+ function appTriggers(sql) {
666
+ return sql.exec(
667
+ `SELECT name, tbl_name AS "table" FROM sqlite_schema WHERE type = 'trigger'`
668
+ ).toArray().filter((trigger) => !trigger.name.startsWith(RESERVED_PREFIX));
669
+ }
670
+ function checkTriggersKept(sql, before, tag, text) {
671
+ const exists = (name, ...types) => sql.exec(
672
+ `SELECT 1 FROM sqlite_schema WHERE name = ? COLLATE NOCASE AND type IN (${types.map(() => "?").join(", ")})`,
673
+ name,
674
+ ...types
675
+ ).toArray().length > 0;
676
+ const lost = before.filter(
677
+ (trigger) => !exists(trigger.name, "trigger") && exists(trigger.table, "table", "view") && !dropsTrigger(text, trigger.name)
678
+ );
679
+ if (lost.length > 0) {
680
+ const names = lost.map((trigger) => `"${trigger.name}" on ${trigger.table}`).join(", ");
681
+ throw new Error(
682
+ `Migration ${tag} removed trigger ${names}: rebuilding a table drops its triggers. Re-create the trigger in that same migration, after the rebuild (or drop it there with DROP TRIGGER if the rule should go).`
683
+ );
684
+ }
685
+ }
686
+ function dropsTrigger(text, name) {
687
+ const escaped = name.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
688
+ return new RegExp(
689
+ `\\bDROP\\s+TRIGGER\\s+(IF\\s+EXISTS\\s+)?["\`[]?${escaped}["\`\\]]?(?![\\w$])`,
690
+ "i"
691
+ ).test(text);
692
+ }
693
+ function checkSchema(sql, tables) {
694
+ const problems = [];
695
+ const nullability = (notNull) => notNull ? "NOT NULL" : "nullable";
696
+ const keyness = (key) => key ? "in the primary key" : "not in the primary key";
697
+ for (const table of tables) {
698
+ const columns = sql.exec(
699
+ `SELECT name, type, "notnull", pk FROM pragma_table_xinfo(?)`,
700
+ table.name
701
+ ).toArray();
702
+ if (columns.length === 0) {
703
+ problems.push(`table ${table.name} does not exist`);
704
+ continue;
705
+ }
706
+ const keys = columns.filter((c) => c.pk > 0);
707
+ const rowid = keys.length === 1 && keys[0]?.type.toUpperCase() === "INTEGER" ? keys[0] : null;
708
+ for (const column of table.columns) {
709
+ const where = `${table.name}.${column.name}`;
710
+ const found = columns.find((c) => c.name === column.name);
711
+ if (found === void 0) {
712
+ problems.push(`column ${where} does not exist`);
713
+ continue;
714
+ }
715
+ const notNull = found.notnull === 1;
716
+ if (found !== rowid && notNull !== column.notNull) {
717
+ problems.push(
718
+ `${where} is ${nullability(notNull)} in the database but ${nullability(column.notNull)} in schema.ts`
719
+ );
720
+ }
721
+ if (found.pk > 0 !== column.primaryKey) {
722
+ problems.push(
723
+ `${where} is ${keyness(found.pk > 0)} in the database but ${keyness(column.primaryKey)} in schema.ts`
724
+ );
725
+ }
726
+ }
727
+ }
728
+ if (problems.length > 0) {
729
+ throw new Error(
730
+ `The database does not match schema.ts: ${problems.join("; ")}. Generate a migration for the change with \`db:generate\` (drizzle-kit generate).`
731
+ );
732
+ }
733
+ }
734
+ function migrationKey(idx) {
735
+ return `m${String(idx).padStart(4, "0")}`;
736
+ }
737
+ async function hashMigrations(migrations) {
738
+ const hashes = /* @__PURE__ */ new Map();
739
+ for (const entry of migrations.journal.entries) {
740
+ const text = migrations.migrations[migrationKey(entry.idx)];
741
+ if (text === void 0) throw new Error(`Migration ${entry.tag} is in the journal but missing`);
742
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
743
+ hashes.set(
744
+ entry.tag,
745
+ [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("")
746
+ );
747
+ }
748
+ return hashes;
749
+ }
750
+ function pendingMigrations(sql, migrations, hashes) {
751
+ const applied = new Map(
752
+ sql.exec(
753
+ "SELECT tag, hash, created_at FROM _teable_migrations"
754
+ ).toArray().map((row) => [row.tag, row])
755
+ );
756
+ const journal = [...migrations.journal.entries].sort((a, b) => a.idx - b.idx);
757
+ const tags = new Set(journal.map((e) => e.tag));
758
+ for (const tag of applied.keys()) {
759
+ if (!tags.has(tag)) {
760
+ throw new Error(`Migration ${tag} was applied but is missing from this version`);
761
+ }
762
+ }
763
+ const lastApplied = Math.max(0, ...[...applied.values()].map((row) => row.created_at));
764
+ const pending = [];
765
+ for (const entry of journal) {
766
+ const row = applied.get(entry.tag);
767
+ if (row && row.hash !== hashes.get(entry.tag)) {
768
+ throw new Error(
769
+ `Migration ${entry.tag} changed after it was applied; add a new migration instead`
770
+ );
771
+ }
772
+ if (!row && entry.when <= lastApplied) {
773
+ throw new Error(
774
+ `Migration ${entry.tag} is older than the latest applied migration; regenerate it`
775
+ );
776
+ }
777
+ if (!row) pending.push(entry);
778
+ }
779
+ return pending;
780
+ }
781
+
782
+ // src/server/app.ts
783
+ var NAME2 = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
784
+ function isThenable(value) {
785
+ return typeof value === "object" && value !== null && typeof value.then === "function";
786
+ }
787
+ var emptyInput = z2.object({});
788
+ function createApp(options) {
789
+ return {
790
+ /** Read data. Synchronous and read-only: a read that writes is rolled back and fails. */
791
+ read(def) {
792
+ return {
793
+ kind: "read",
794
+ input: def.input ?? emptyInput,
795
+ output: def.output,
796
+ access: def.access ?? "viewer",
797
+ description: def.description,
798
+ handler: def.handler
799
+ };
800
+ },
801
+ /** Change data. Synchronous and atomic: if it throws, nothing it wrote is kept. */
802
+ write(def) {
803
+ return {
804
+ kind: "write",
805
+ input: def.input ?? emptyInput,
806
+ output: def.output,
807
+ access: def.access ?? "editor",
808
+ description: def.description,
809
+ handler: def.handler
810
+ };
811
+ },
812
+ /** Async work outside transactions: external services, multi-step flows. Retried on failure. */
813
+ task(def) {
814
+ const schedule = def.schedule && {
815
+ cron: def.schedule.cron,
816
+ timezone: def.schedule.timezone ?? "UTC"
817
+ };
818
+ if (schedule) {
819
+ parseCron(schedule.cron);
820
+ new Intl.DateTimeFormat("en-US", { timeZone: schedule.timezone });
821
+ }
822
+ return {
823
+ kind: "task",
824
+ input: def.input ?? emptyInput,
825
+ access: "internal",
826
+ description: def.description,
827
+ maxAttempts: def.maxAttempts ?? DEFAULT_MAX_ATTEMPTS,
828
+ schedule,
829
+ handler: def.handler
830
+ };
831
+ },
832
+ /**
833
+ * Register the methods under their names and return the app's Durable
834
+ * Object class. It keeps the method map's type, which pages read.
835
+ */
836
+ define(methods) {
837
+ return defineApp(options.schema, options.migrations, methods, options.capabilities ?? []);
838
+ }
839
+ };
840
+ }
841
+ var registry = /* @__PURE__ */ new WeakMap();
842
+ function methodName(method) {
843
+ const name = registry.get(method);
844
+ if (name === void 0) throw new Error("This method is not registered in define()");
845
+ return name;
846
+ }
847
+ function defineApp(schema, migrations, methods, capabilities) {
848
+ for (const capability of capabilities) {
849
+ if (!CAPABILITIES.includes(capability)) {
850
+ throw new Error(`Unknown capability "${capability}" (known: ${CAPABILITIES.join(", ")})`);
851
+ }
852
+ }
853
+ for (const [name, method] of Object.entries(methods)) {
854
+ if (!NAME2.test(name)) throw new Error(`Method name "${name}" must match ${NAME2}`);
855
+ const existing = registry.get(method);
856
+ if (existing !== void 0) {
857
+ throw new Error(`Method "${name}" is already registered as "${existing}"`);
858
+ }
859
+ registry.set(method, name);
860
+ }
861
+ const tables = describeTables(schema);
862
+ for (const table of tables) {
863
+ if (table.name.startsWith(RESERVED_PREFIX)) {
864
+ throw new Error(`Table "${table.name}" uses the reserved prefix ${RESERVED_PREFIX}`);
865
+ }
866
+ }
867
+ const manifest = {
868
+ protocol: PROTOCOL_VERSION,
869
+ methods: Object.entries(methods).map(([name, m]) => describeMethod(name, m)),
870
+ tables,
871
+ capabilities: [...new Set(capabilities)]
872
+ };
873
+ const byName = new Map(Object.entries(methods));
874
+ return class App extends DurableObject {
875
+ static manifest = manifest;
876
+ /** The methods by the names `define()` gave them; pages take their types from here. */
877
+ static methods = methods;
878
+ #db;
879
+ #sql;
880
+ constructor(ctx, env) {
881
+ super(ctx, env);
882
+ this.#sql = ctx.storage.sql;
883
+ this.#db = drizzle(ctx.storage, { schema });
884
+ ctx.blockConcurrencyWhile(() => prepareDatabase(ctx.storage, migrations, manifest));
885
+ }
886
+ async manifest() {
887
+ return manifest;
888
+ }
889
+ async invoke(request) {
890
+ const before = currentCursor(this.#sql);
891
+ try {
892
+ const admitted = admit(manifest, request.method, request.caller);
893
+ if (!admitted.ok) throw new AppError(admitted.error.code, admitted.error.message);
894
+ const method = byName.get(request.method);
895
+ const value = this.#run(method, request.method, request.input, request.caller);
896
+ return { ok: true, value, effects: effectsSince(this.#sql, before) };
897
+ } catch (error) {
898
+ return { ok: false, error: toErrorShape(error), effects: effectsSince(this.#sql, before) };
899
+ }
900
+ }
901
+ /** Run due tasks. The host calls this from its alarm; `now` lets tests move time forward. */
902
+ async wake(now) {
903
+ const before = currentCursor(this.#sql);
904
+ const storage = this.ctx.storage;
905
+ storage.transactionSync(() => fireDueSchedules(this.#sql, now));
906
+ const failed = await runDueTasks(storage, now, (name) => {
907
+ const method = byName.get(name);
908
+ if (method?.kind !== "task") return void 0;
909
+ return {
910
+ maxAttempts: method.maxAttempts,
911
+ run: (input, attempt) => method.handler({
912
+ input: method.input.parse(input),
913
+ attempt,
914
+ ...capabilitiesFrom(this.env),
915
+ call: async (target, callInput) => this.#run(target, methodName(target), callInput, {
916
+ kind: "system",
917
+ via: "task",
918
+ task: name
919
+ })
920
+ })
921
+ };
922
+ });
923
+ const attempts = storage.transactionSync(() => takeAttempts(this.#sql));
924
+ return { attempts, failed, effects: effectsSince(this.#sql, before) };
925
+ }
926
+ async changes(since, limit = 500) {
927
+ return readChanges(this.#sql, since, Math.min(limit, 5e3));
928
+ }
929
+ #run(method, name, rawInput, caller) {
930
+ const input = method.input.parse(rawInput ?? {});
931
+ const storage = this.ctx.storage;
932
+ if (method.kind === "read") {
933
+ return storage.transactionSync(() => {
934
+ const before = totalChanges(this.#sql);
935
+ const schema2 = schemaFingerprint(this.#sql);
936
+ let value;
937
+ try {
938
+ value = method.handler({ db: this.#db, input, caller });
939
+ } catch (error) {
940
+ if (String(error?.message).includes(OUTSIDE_WRITE)) {
941
+ throw new AppError(
942
+ "INTERNAL",
943
+ `Read method "${name}" wrote data; use a write method`
944
+ );
945
+ }
946
+ throw error;
947
+ }
948
+ const result = resultOf(method, name, value);
949
+ if (totalChanges(this.#sql) !== before) {
950
+ throw new AppError("INTERNAL", `Read method "${name}" wrote data; use a write method`);
951
+ }
952
+ assertSchemaUnchanged(this.#sql, schema2, name);
953
+ return result;
954
+ });
955
+ }
956
+ if (method.kind === "write") {
957
+ return storage.transactionSync(() => {
958
+ const now = Date.now();
959
+ const schema2 = schemaFingerprint(this.#sql);
960
+ const invocation = beginInvocation(this.#sql, name, caller, now);
961
+ const value = method.handler({
962
+ db: this.#db,
963
+ input,
964
+ caller,
965
+ enqueue: (task, taskInput, options) => {
966
+ const taskName = methodName(task);
967
+ const json = JSON.stringify(taskInput ?? {});
968
+ const stored = task.input.safeParse(JSON.parse(json));
969
+ if (!stored.success) {
970
+ throw new AppError(
971
+ "INTERNAL",
972
+ `Task "${taskName}" cannot take this input: tasks receive their input as JSON, and once stored as JSON it no longer matches the task's schema`,
973
+ issuesOf(stored.error)
974
+ );
975
+ }
976
+ enqueueTask(
977
+ this.#sql,
978
+ {
979
+ method: taskName,
980
+ input: json,
981
+ runAt: now + (options?.delayMs ?? 0),
982
+ invocation
983
+ },
984
+ now
985
+ );
986
+ }
987
+ });
988
+ const result = resultOf(method, name, value);
989
+ assertSchemaUnchanged(this.#sql, schema2, name);
990
+ endInvocation(this.#sql);
991
+ pruneHistory(this.#sql, now, invocation);
992
+ pruneDeadTasks(this.#sql, now);
993
+ return result;
994
+ });
995
+ }
996
+ throw new AppError("FORBIDDEN", `Task "${name}" cannot be called; enqueue it from a write`);
997
+ }
998
+ };
999
+ }
1000
+ function capabilitiesFrom(env) {
1001
+ const each = (name) => env[name] ?? new Proxy(
1002
+ {},
1003
+ {
1004
+ get: () => () => Promise.reject(
1005
+ new Error(`Declare capabilities: ["${name}"] in createApp to use ${name}`)
1006
+ )
1007
+ }
1008
+ );
1009
+ return Object.fromEntries(
1010
+ CAPABILITIES.map((name) => [name, each(name)])
1011
+ );
1012
+ }
1013
+ function describeMethod(name, method) {
1014
+ const input = z2.toJSONSchema(method.input, {
1015
+ io: "input",
1016
+ unrepresentable: "any"
1017
+ });
1018
+ if (input.type !== "object") {
1019
+ throw new Error(`Method "${name}" input must be a z.object(...)`);
1020
+ }
1021
+ const info = { name, kind: method.kind, access: method.access, input };
1022
+ if (method.description !== void 0) info.description = method.description;
1023
+ if (method.kind !== "task" && method.output !== void 0) {
1024
+ info.output = outputSchema(method.output);
1025
+ }
1026
+ if (method.kind === "task" && method.schedule) {
1027
+ if (!method.input.safeParse({}).success) {
1028
+ throw new Error(`Scheduled task "${name}" must accept an empty input`);
1029
+ }
1030
+ info.schedule = method.schedule;
1031
+ }
1032
+ return info;
1033
+ }
1034
+ function outputSchema(output) {
1035
+ return z2.toJSONSchema(output, {
1036
+ io: "output",
1037
+ unrepresentable: "any",
1038
+ override: ({ zodSchema, jsonSchema }) => {
1039
+ if (zodSchema._zod.def.type === "date") {
1040
+ Object.assign(jsonSchema, { type: "string", format: "date-time" });
1041
+ }
1042
+ }
1043
+ });
1044
+ }
1045
+ function resultOf(method, name, value) {
1046
+ assertSync(value, name);
1047
+ if (method.output === void 0) return value;
1048
+ const checked = method.output.safeParse(value);
1049
+ if (checked.success) return checked.data;
1050
+ const issues = issuesOf(checked.error);
1051
+ const [first] = issues;
1052
+ const where = (first?.path ?? []).reduce(
1053
+ (path, key) => typeof key === "number" ? `${path}[${key}]` : `${path}.${key}`,
1054
+ "result"
1055
+ );
1056
+ const more = issues.length > 1 ? ` (and ${issues.length - 1} more)` : "";
1057
+ throw new AppError(
1058
+ "INTERNAL",
1059
+ `Method "${name}" returned what its output schema refuses, at ${where}: ${first?.message}${more}`,
1060
+ issues
1061
+ );
1062
+ }
1063
+ function assertSync(value, name) {
1064
+ if (isThenable(value)) {
1065
+ value.then(
1066
+ void 0,
1067
+ (error) => console.warn(`Method "${name}" kept running after it returned:`, error)
1068
+ );
1069
+ throw new AppError(
1070
+ "INTERNAL",
1071
+ `Method "${name}" returned a Promise; read and write handlers must be synchronous. Move async work into a task.`
1072
+ );
1073
+ }
1074
+ assertPlain(value, name, "result", 0);
1075
+ }
1076
+ function assertPlain(value, name, path, depth) {
1077
+ if (value === null || value === void 0 || value instanceof Date) return;
1078
+ const type = typeof value;
1079
+ if (type === "string" || type === "number" || type === "boolean") return;
1080
+ const problem = (what) => new AppError(
1081
+ "INTERNAL",
1082
+ `Method "${name}" returned ${what} at ${path}; return plain data (rows, objects, arrays). Did you forget .get() or .all()?`
1083
+ );
1084
+ if (type !== "object") throw problem(`a ${type}`);
1085
+ if (depth > 32) throw problem("data nested too deeply (or a cycle)");
1086
+ if (Array.isArray(value)) {
1087
+ for (const [i, item] of value.entries()) assertPlain(item, name, `${path}[${i}]`, depth + 1);
1088
+ return;
1089
+ }
1090
+ const prototype = Object.getPrototypeOf(value);
1091
+ if (prototype !== Object.prototype && prototype !== null) {
1092
+ throw problem(`a ${prototype?.constructor?.name ?? "class instance"}`);
1093
+ }
1094
+ for (const [key, item] of Object.entries(value)) {
1095
+ assertPlain(item, name, `${path}.${key}`, depth + 1);
1096
+ }
1097
+ }
1098
+ function assertSchemaUnchanged(sql, before, name) {
1099
+ if (schemaFingerprint(sql) !== before) {
1100
+ throw new AppError(
1101
+ "INTERNAL",
1102
+ `Method "${name}" changed the database schema; schema changes belong in migrations`
1103
+ );
1104
+ }
1105
+ }
1106
+ function schemaFingerprint(sql) {
1107
+ return sql.exec("SELECT count(*) || ':' || total(length(sql)) AS f FROM sqlite_schema").one().f;
1108
+ }
1109
+ function totalChanges(sql) {
1110
+ return sql.exec("SELECT total_changes() AS n").one().n;
1111
+ }
1112
+ function effectsSince(sql, before) {
1113
+ const cursor = currentCursor(sql);
1114
+ const next = [nextTaskAt(sql), nextScheduleAt(sql)].filter((at) => at !== null);
1115
+ return {
1116
+ cursor,
1117
+ changedTables: cursor > before ? changedTablesSince(sql, before) : [],
1118
+ wakeAt: next.length > 0 ? Math.min(...next) : null
1119
+ };
1120
+ }
1121
+
1122
+ export {
1123
+ fail,
1124
+ createApp,
1125
+ methodName
1126
+ };