durable-db 0.11.0 → 0.13.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/registry.js CHANGED
@@ -107,38 +107,61 @@ function cachedArgsSchema(key, make) {
107
107
  if (!schema) argsSchemas.set(key, schema = make());
108
108
  return schema;
109
109
  }
110
- const pending = /* @__PURE__ */ new WeakMap();
110
+ const BATCH_SCOPES = Symbol.for("durable-db.batchScopes");
111
+ const batchScopes = globalThis[BATCH_SCOPES] ??= new AsyncLocalStorage();
111
112
  /**
112
- * Call an action on the Durable Object `instanceKey` of `namespace`. Calls to
113
- * the same object started before the code waits on I/O — `Promise.all([a(),
114
- * b()])` however deep in middleware, sibling server components awaiting at
115
- * once — travel in ONE RPC
116
- * (`rpcBatch`) and run there one after another, in the order they were made,
117
- * each result or error to its own caller; a lone call is a plain `rpc`, as
118
- * before. Results are plain values: the RPC's top-level `Symbol.dispose` is
119
- * dropped (React Server Components refuse symbol-keyed props).
113
+ * Runs `fn` as one invocation: the action calls it starts on the same Durable
114
+ * Object before it waits on I/O travel in ONE RPC. Wrap what the platform
115
+ * invokes — a worker's `fetch`, `queue` and `scheduled` handlers:
116
+ *
117
+ * export default { fetch: (request, env, ctx) => batchScope(() => app.fetch(request, env, ctx)) }
118
+ *
119
+ * Outside a scope every call is its own RPC: batching is only safe among the
120
+ * calls of one invocation, and nothing else tells them apart.
121
+ */
122
+ function batchScope(fn) {
123
+ return batchScopes.run({ pending: /* @__PURE__ */ new WeakMap() }, fn);
124
+ }
125
+ /**
126
+ * Call an action on the Durable Object `instanceKey` of `namespace`. Inside a
127
+ * `batchScope()`, calls to the same object started before the code waits on
128
+ * I/O — `Promise.all([a(), b()])` however deep in middleware, sibling server
129
+ * components awaiting at once — travel in ONE RPC (`rpcBatch`) and run there
130
+ * one after another, in the order they were made, each result or error to its
131
+ * own caller; a lone call, and every call outside a scope, is a plain `rpc`.
132
+ * Results are plain values: the RPC's top-level `Symbol.dispose` is dropped
133
+ * (React Server Components refuse symbol-keyed props).
120
134
  */
121
135
  function batchedRpc(namespace, instanceKey, action, args) {
136
+ const scope = batchScopes.getStore();
122
137
  return new Promise((resolve, reject) => {
123
- let byKey = pending.get(namespace);
124
- if (!byKey) pending.set(namespace, byKey = /* @__PURE__ */ new Map());
138
+ const call = {
139
+ action,
140
+ args,
141
+ resolve,
142
+ reject
143
+ };
144
+ if (!scope) {
145
+ sendCalls(namespace, instanceKey, [call]);
146
+ return;
147
+ }
148
+ let byKey = scope.pending.get(namespace);
149
+ if (!byKey) scope.pending.set(namespace, byKey = /* @__PURE__ */ new Map());
125
150
  let calls = byKey.get(instanceKey);
126
151
  if (!calls) {
127
152
  byKey.set(instanceKey, calls = []);
128
153
  const queued = byKey;
129
154
  setTimeout(() => flushCalls(namespace, instanceKey, queued), 0);
130
155
  }
131
- calls.push({
132
- action,
133
- args,
134
- resolve,
135
- reject
136
- });
156
+ calls.push(call);
137
157
  });
138
158
  }
139
159
  function flushCalls(namespace, instanceKey, byKey) {
140
160
  const calls = byKey.get(instanceKey) ?? [];
141
161
  byKey.delete(instanceKey);
162
+ sendCalls(namespace, instanceKey, calls);
163
+ }
164
+ function sendCalls(namespace, instanceKey, calls) {
142
165
  if (calls.length === 0) return;
143
166
  let stub;
144
167
  try {
@@ -168,4 +191,4 @@ function flushCalls(namespace, instanceKey, byKey) {
168
191
  });
169
192
  }
170
193
  //#endregion
171
- export { batchedRpc, cachedArgsSchema, callAction, getAction, getDoContext, registerAction, registerSharedAction, runWithDoContext, actionArgsType as type };
194
+ export { batchScope, batchedRpc, cachedArgsSchema, callAction, getAction, getDoContext, registerAction, registerSharedAction, runWithDoContext, actionArgsType as type };
@@ -85,6 +85,50 @@ function findAmbiguities(prevSnapshot, curSnapshot) {
85
85
  });
86
86
  return ambiguities;
87
87
  }
88
+ /**
89
+ * The questions that have one answer: a table that lost exactly one column
90
+ * and gained exactly one that is declared the same way — its type, whether it
91
+ * may be null, its default, everything but the name — and a schema that lost
92
+ * exactly one table and gained exactly one with the same columns. That is a
93
+ * rename: the name changed and nothing else did. Taking it for a drop and a
94
+ * create would lose the data for a change nobody made; so it is answered
95
+ * without asking, and said (`renamesFromStatements()` of what was generated).
96
+ * Two candidates, or one that changed in more than its name, stay a question.
97
+ */
98
+ function obviousRenames(prevSnapshot, curSnapshot, ambiguities = findAmbiguities(prevSnapshot, curSnapshot)) {
99
+ const prev = shape(prevSnapshot);
100
+ const cur = shape(curSnapshot);
101
+ const but = (column) => JSON.stringify({
102
+ ...column,
103
+ name: ""
104
+ });
105
+ const answers = [];
106
+ for (const ambiguity of ambiguities) {
107
+ if (ambiguity.created.length !== 1 || ambiguity.deleted.length !== 1) continue;
108
+ const from = ambiguity.deleted[0];
109
+ const to = ambiguity.created[0];
110
+ if (ambiguity.kind === "column") {
111
+ const was = prev.tables[ambiguity.table]?.columns[from];
112
+ const now = cur.tables[ambiguity.table]?.columns[to];
113
+ if (was && now && but(was) === but(now)) answers.push({
114
+ kind: "column",
115
+ table: ambiguity.table,
116
+ from,
117
+ to
118
+ });
119
+ } else if (ambiguity.kind === "table") {
120
+ const was = Object.values(prev.tables[from]?.columns ?? {}).map(but).sort();
121
+ const now = Object.values(cur.tables[to]?.columns ?? {}).map(but).sort();
122
+ const names = (columns) => Object.keys(columns ?? {}).sort().join(",");
123
+ if (was.length > 0 && JSON.stringify(was) === JSON.stringify(now) && names(prev.tables[from]?.columns) === names(cur.tables[to]?.columns)) answers.push({
124
+ kind: "table",
125
+ from,
126
+ to
127
+ });
128
+ }
129
+ }
130
+ return answers;
131
+ }
88
132
  /** One line per ambiguity: `products: summary added, description removed`. */
89
133
  function describeAmbiguity(ambiguity) {
90
134
  return `${ambiguity.kind === "column" ? `${ambiguity.table}: ` : `${ambiguity.kind}s: `}${ambiguity.created.join(", ")} added, ${ambiguity.deleted.join(", ")} removed`;
@@ -294,6 +338,8 @@ function renamesFromStatements(statements) {
294
338
  }
295
339
  //#endregion
296
340
  //#region src/migrations/risks.ts
341
+ /** What a foreign key references, as one string: the same key before and after is no change. */
342
+ const referenceOf = (key) => `${key.columnsFrom.join(",")}->${key.tableTo}(${key.columnsTo.join(",")})`;
297
343
  /** The remedy `db generate` prints when it refuses a NOT NULL column without a default. */
298
344
  const NOT_NULL_WITHOUT_DEFAULT_HINT = "fails on every table that has rows: add .default(...) or add it nullable and backfill";
299
345
  /**
@@ -343,6 +389,18 @@ function analyzeMigrationRisks(prevSnapshot, curSnapshot, renames = []) {
343
389
  message: `${name}.${column} becomes NOT NULL — the migration fails on a database where a row holds NULL there: backfill it first`
344
390
  });
345
391
  }
392
+ const had = new Set(Object.values(table.foreignKeys ?? {}).map(referenceOf));
393
+ for (const key of Object.values(after.foreignKeys ?? {})) {
394
+ if (had.has(referenceOf(key))) continue;
395
+ const from = key.columnsFrom.join(", ");
396
+ risks.push({
397
+ kind: "add-foreign-key",
398
+ severity: "warning",
399
+ table: name,
400
+ ...key.columnsFrom.length === 1 ? { column: key.columnsFrom[0] } : {},
401
+ message: `${name}.${from} now references ${key.tableTo}.${key.columnsTo.join(", ")} — the migration fails on a database where a row of ${name} references a row of ${key.tableTo} that is not there, and that database answers nothing until it passes: remove or repair those rows in a migration before this one`
402
+ });
403
+ }
346
404
  }
347
405
  return risks;
348
406
  }
@@ -407,11 +465,22 @@ async function generateSnapshotFromSchema(schema) {
407
465
  */
408
466
  async function generateMigrationStatements(from, to, resolution = {}) {
409
467
  const answers = (resolution.renames ?? []).map((r) => typeof r === "string" ? parseRenameSpec(r) : r);
410
- const renamed = answers.length > 0 ? applyRenames(from, to, answers) : {
468
+ let renamed = answers.length > 0 ? applyRenames(from, to, answers) : {
411
469
  snapshot: from,
412
470
  statements: []
413
471
  };
414
- const ambiguities = findAmbiguities(renamed.snapshot, to);
472
+ let ambiguities = findAmbiguities(renamed.snapshot, to);
473
+ if (ambiguities.length > 0 && !resolution.noRenames) {
474
+ const obvious = obviousRenames(renamed.snapshot, to, ambiguities);
475
+ if (obvious.length > 0) {
476
+ const taken = applyRenames(renamed.snapshot, to, obvious);
477
+ renamed = {
478
+ snapshot: taken.snapshot,
479
+ statements: [...renamed.statements, ...taken.statements]
480
+ };
481
+ ambiguities = findAmbiguities(renamed.snapshot, to);
482
+ }
483
+ }
415
484
  if (ambiguities.length === 0) return [...renamed.statements, ...await generateSQLiteMigration(renamed.snapshot, to)];
416
485
  if (resolution.noRenames) {
417
486
  const dropped = withoutRemoved(renamed.snapshot, to);
@@ -456,4 +525,4 @@ function hashSnapshot(snapshot) {
456
525
  return Math.abs(hash).toString(36);
457
526
  }
458
527
  //#endregion
459
- export { renamesFromStatements as _, generateSnapshotId as a, NOT_NULL_WITHOUT_DEFAULT_HINT as c, applyRenames as d, describeAmbiguity as f, parseRenameSpec as g, formatRename as h, generateSnapshotFromSchema as i, analyzeMigrationRisks as l, findAmbiguities as m, createEmptySnapshot as n, hashSnapshot as o, exampleRenames as p, generateMigrationStatements as r, snapshotsEqual as s, canPrompt as t, SchemaRenameRequiredError as u, unusedRenames as v };
528
+ export { parseRenameSpec as _, generateSnapshotId as a, NOT_NULL_WITHOUT_DEFAULT_HINT as c, applyRenames as d, describeAmbiguity as f, obviousRenames as g, formatRename as h, generateSnapshotFromSchema as i, analyzeMigrationRisks as l, findAmbiguities as m, createEmptySnapshot as n, hashSnapshot as o, exampleRenames as p, generateMigrationStatements as r, snapshotsEqual as s, canPrompt as t, SchemaRenameRequiredError as u, renamesFromStatements as v, unusedRenames as y };
@@ -35,6 +35,17 @@ interface SchemaAmbiguity {
35
35
  }
36
36
  /** Every question drizzle-kit would ask to diff `prev` → `cur`. */
37
37
  declare function findAmbiguities(prevSnapshot: Snapshot$2, curSnapshot: Snapshot$2): SchemaAmbiguity[];
38
+ /**
39
+ * The questions that have one answer: a table that lost exactly one column
40
+ * and gained exactly one that is declared the same way — its type, whether it
41
+ * may be null, its default, everything but the name — and a schema that lost
42
+ * exactly one table and gained exactly one with the same columns. That is a
43
+ * rename: the name changed and nothing else did. Taking it for a drop and a
44
+ * create would lose the data for a change nobody made; so it is answered
45
+ * without asking, and said (`renamesFromStatements()` of what was generated).
46
+ * Two candidates, or one that changed in more than its name, stay a question.
47
+ */
48
+ declare function obviousRenames(prevSnapshot: Snapshot$2, curSnapshot: Snapshot$2, ambiguities?: SchemaAmbiguity[]): RenameAnswer[];
38
49
  /** One line per ambiguity: `products: summary added, description removed`. */
39
50
  declare function describeAmbiguity(ambiguity: SchemaAmbiguity): string;
40
51
  /** Example `--rename` answers for an ambiguity (each new name from the first vanished one). */
@@ -88,7 +99,7 @@ declare function renamesFromStatements(statements: string[]): RenameAnswer[];
88
99
  //#endregion
89
100
  //#region src/migrations/risks.d.ts
90
101
  type Snapshot$1 = DrizzleSQLiteSnapshotJSON;
91
- type MigrationRiskKind = 'add-not-null-without-default' | 'set-not-null' | 'drop-column' | 'drop-table';
102
+ type MigrationRiskKind = 'add-not-null-without-default' | 'set-not-null' | 'add-foreign-key' | 'drop-column' | 'drop-table';
92
103
  interface MigrationRisk {
93
104
  kind: MigrationRiskKind;
94
105
  /** `error`: fails on every table that has rows. `warning`: loses data, or may fail. */
@@ -177,4 +188,4 @@ declare function snapshotsEqual(a: Snapshot, b: Snapshot): boolean;
177
188
  */
178
189
  declare function hashSnapshot(snapshot: Snapshot): string;
179
190
  //#endregion
180
- export { renamesFromStatements as C, parseRenameSpec as S, applyRenames as _, generateMigrationStatements as a, findAmbiguities as b, hashSnapshot as c, MigrationRiskKind as d, NOT_NULL_WITHOUT_DEFAULT_HINT as f, SchemaRenameRequiredError as g, SchemaAmbiguity as h, createEmptySnapshot as i, snapshotsEqual as l, RenameAnswer as m, Snapshot as n, generateSnapshotFromSchema as o, analyzeMigrationRisks as p, canPrompt as r, generateSnapshotId as s, MigrationResolution as t, MigrationRisk as u, describeAmbiguity as v, unusedRenames as w, formatRename as x, exampleRenames as y };
191
+ export { parseRenameSpec as C, obviousRenames as S, unusedRenames as T, applyRenames as _, generateMigrationStatements as a, findAmbiguities as b, hashSnapshot as c, MigrationRiskKind as d, NOT_NULL_WITHOUT_DEFAULT_HINT as f, SchemaRenameRequiredError as g, SchemaAmbiguity as h, createEmptySnapshot as i, snapshotsEqual as l, RenameAnswer as m, Snapshot as n, generateSnapshotFromSchema as o, analyzeMigrationRisks as p, canPrompt as r, generateSnapshotId as s, MigrationResolution as t, MigrationRisk as u, describeAmbiguity as v, renamesFromStatements as w, formatRename as x, exampleRenames as y };
@@ -5,6 +5,7 @@ import * as crypto from "node:crypto";
5
5
  //#region src/cli/state.ts
6
6
  var state_exports = /* @__PURE__ */ __exportAll({
7
7
  DEV_SERVER_LOCK_FILE: () => DEV_SERVER_LOCK_FILE,
8
+ SCHEMA_TEMP_PREFIX: () => SCHEMA_TEMP_PREFIX,
8
9
  clearDatabaseDevState: () => clearDatabaseDevState,
9
10
  clearDevMigrations: () => clearDevMigrations,
10
11
  createEmptyDevState: () => createEmptyDevState,
@@ -284,15 +285,16 @@ function parseSqlMigration(content) {
284
285
  return chunk.split("\n").filter((line) => !line.trim().startsWith("--")).join("\n").split(/;(?:\s*\n|\s*$)/).map((s) => s.trim()).filter((s) => s.length > 0);
285
286
  }).filter((chunk) => chunk.length > 0);
286
287
  }
287
- var CACHE_DIR_NAME, STATE_FILE_NAME, DEV_SERVER_LOCK_FILE, DEV_MIGRATIONS_DIR, DEV_SNAPSHOT_FILE, BREAKPOINT_MARKER;
288
+ var CACHE_DIR_NAME, STATE_FILE_NAME, DEV_SERVER_LOCK_FILE, SCHEMA_TEMP_PREFIX, DEV_MIGRATIONS_DIR, DEV_SNAPSHOT_FILE, BREAKPOINT_MARKER;
288
289
  var init_state = __esmMin((() => {
289
290
  init_debug();
290
291
  CACHE_DIR_NAME = ".cache/durable-db";
291
292
  STATE_FILE_NAME = "state.json";
292
293
  DEV_SERVER_LOCK_FILE = "dev-server.json";
294
+ SCHEMA_TEMP_PREFIX = "_schema_temp_";
293
295
  DEV_MIGRATIONS_DIR = "migrations";
294
296
  DEV_SNAPSHOT_FILE = "_snapshot.json";
295
297
  BREAKPOINT_MARKER = /^-->\s*breakpoint\s*$/im;
296
298
  }));
297
299
  //#endregion
298
- export { saveDevState as _, generateEpoch as a, getDevEpoch as c, init_state as d, loadDevMigrations as f, saveDevMigration as g, runningDevServer as h, forgetDatabaseDevState as i, getDevPaths as l, removeDevServerLock as m, clearDatabaseDevState as n, getDatabaseEpoch as o, loadDevState as p, clearDevMigrations as r, getDatabaseEpochs as s, DEV_SERVER_LOCK_FILE as t, getInstanceKey as u, state_exports as v, writeDevServerLock as y };
300
+ export { saveDevMigration as _, forgetDatabaseDevState as a, writeDevServerLock as b, getDatabaseEpochs as c, getInstanceKey as d, init_state as f, runningDevServer as g, removeDevServerLock as h, clearDevMigrations as i, getDevEpoch as l, loadDevState as m, SCHEMA_TEMP_PREFIX as n, generateEpoch as o, loadDevMigrations as p, clearDatabaseDevState as r, getDatabaseEpoch as s, DEV_SERVER_LOCK_FILE as t, getDevPaths as u, saveDevState as v, state_exports as y };
@@ -1,9 +1,9 @@
1
- import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-Cb5sMNg0.js";
1
+ import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-DypFFfjn.js";
2
2
  import { r as type } from "../type-CUgZsZp3.js";
3
3
  import "../actionArgs-DP2tQrlf.js";
4
4
  import { setTenantIdResolver } from "../context/index.js";
5
- import { c as tenantOfInstanceKey, i as createActionOutbox, t as createKyselyFromSql } from "../kysely-q97dtmaQ.js";
6
- import { i as generateSnapshotFromSchema, n as createEmptySnapshot, r as generateMigrationStatements } from "../snapshot-D_z95s6E.js";
5
+ import { c as tenantOfInstanceKey, i as createActionOutbox, t as createKyselyFromSql } from "../kysely-DGc-CG_v.js";
6
+ import { i as generateSnapshotFromSchema, n as createEmptySnapshot, r as generateMigrationStatements } from "../snapshot-CY4FLqAo.js";
7
7
  import { createRequire } from "node:module";
8
8
  //#region src/testing/index.ts
9
9
  const loadSqlite = () => createRequire(import.meta.url)("node:sqlite");
@@ -1,5 +1,5 @@
1
1
  import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
2
- import "../index-CUkSkt7G.js";
2
+ import "../index-B5W4m0Dq.js";
3
3
  import { Plugin } from "vite";
4
4
  import "@babel/types";
5
5
  //#region src/vite/modules/wrangler.d.ts
@@ -1,5 +1,5 @@
1
1
  import { i as init_debug, r as debugVite } from "../debug-Cz8KzMft.js";
2
- import { _ as saveDevState, d as init_state, l as getDevPaths, m as removeDevServerLock, p as loadDevState, s as getDatabaseEpochs, y as writeDevServerLock } from "../state-DGYycIoJ.js";
2
+ import { b as writeDevServerLock, c as getDatabaseEpochs, f as init_state, h as removeDevServerLock, m as loadDevState, u as getDevPaths, v as saveDevState } from "../state-UT6GH0JD.js";
3
3
  import { loadMigrationFiles } from "../migrations/generator.js";
4
4
  import { a as databaseSources, c as readFile, i as toPascalCase, n as declaresSchema, o as discoverActionFiles, r as parseDatabaseFile, s as discoverDatabaseFiles, t as BABEL_PARSER_PLUGINS } from "../parser-mUnAtllk.js";
5
5
  import * as fs from "node:fs";
@@ -1548,7 +1548,7 @@ var PluginState = class {
1548
1548
  const isDev = this.config.command === "serve";
1549
1549
  db.migrations = loadMigrationFiles(migrationsDir);
1550
1550
  if (isDev) try {
1551
- const { loadDevMigrations } = await import("../state-DGYycIoJ.js").then((n) => (n.d(), n.v));
1551
+ const { loadDevMigrations } = await import("../state-UT6GH0JD.js").then((n) => (n.f(), n.y));
1552
1552
  const devMigrations = loadDevMigrations(this.projectRoot, db.name);
1553
1553
  for (const [name, chunks] of devMigrations) db.migrations.set(`_dev_${name}`, chunks);
1554
1554
  if (devMigrations.size > 0) debugVite("Loaded %d dev migration(s) for %s", devMigrations.size, db.name);
@@ -1658,6 +1658,7 @@ function durableDb(options = {}) {
1658
1658
  const cacheDirName = path$1.basename(devPaths.cacheDir);
1659
1659
  const onDevStateChange = (_event, filename) => {
1660
1660
  if (typeof filename === "string" && (path$1.basename(filename) === "dev-server.json" || filename === cacheDirName)) return;
1661
+ if (typeof filename === "string" && path$1.basename(filename).startsWith("_schema_temp_")) return;
1661
1662
  if (state.isWithinSelfDevStateWriteWindow()) {
1662
1663
  debugVite("Ignoring dev cache event caused by the plugin itself");
1663
1664
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "durable-db",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/eagerpatch/durable-db.git"