durable-db 0.2.0 → 0.2.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.
Files changed (52) hide show
  1. package/dist/arktypeConfig-DdIO8VV1.d.ts +6130 -0
  2. package/dist/{arktypeConfig-CTCJm4vA.js → arktypeConfig-DxP0OcV_.js} +1014 -1033
  3. package/dist/cli/bin.d.ts +1 -1
  4. package/dist/cli/bin.js +2 -10
  5. package/dist/cli/index.d.ts +27 -29
  6. package/dist/cli/index.js +4 -9
  7. package/dist/{cli-DnsOTcrH.js → cli-BUSZTS2D.js} +196 -19
  8. package/dist/context/index.d.ts +50 -2
  9. package/dist/context/index.js +119 -5
  10. package/dist/db/index.d.ts +4 -4
  11. package/dist/db/index.js +10 -12
  12. package/dist/{debug-DmBrUmwe.js → debug-Cz8KzMft.js} +23 -27
  13. package/dist/{defineDatabase-DtkM6k1S.d.ts → defineDatabase-CHmTgZTx.d.ts} +4 -5
  14. package/dist/{defineDatabase-BD3k1L7d.js → defineDatabase-CHmzpzFf.js} +2 -4
  15. package/dist/{discovery-DfimBbS_.d.ts → discovery-gHeLq8jk.d.ts} +1 -1
  16. package/dist/{index-BHLOQ7uV.d.ts → index-M4Jp_PFM.d.ts} +2 -1
  17. package/dist/index.d.ts +4 -4
  18. package/dist/index.js +5 -8
  19. package/dist/{kysely-BH7QZBZw.js → kysely-Be6KwFZC.js} +45 -31
  20. package/dist/migrations/generator.d.ts +14 -17
  21. package/dist/migrations/generator.js +202 -5
  22. package/dist/migrations/snapshot.d.ts +1 -1
  23. package/dist/migrations/snapshot.js +91 -3
  24. package/dist/{parser-BdV7Zqcv.js → parser-DR57GOjv.js} +21 -19
  25. package/dist/registry.d.ts +10 -11
  26. package/dist/registry.js +3 -5
  27. package/dist/schema.d.ts +5 -2
  28. package/dist/schema.js +6 -3
  29. package/dist/snapshot-CaG5xnE2.d.ts +48 -0
  30. package/dist/{state-DtZ70cBR.js → state-OVuoHRC9.js} +3 -5
  31. package/dist/testing/index.d.ts +4 -5
  32. package/dist/testing/index.js +6 -10
  33. package/dist/transport/protocol.d.ts +7 -8
  34. package/dist/transport/protocol.js +34 -3
  35. package/dist/transport/websocket.d.ts +4 -5
  36. package/dist/transport/websocket.js +103 -3
  37. package/dist/vite/durableDb.d.ts +6 -7
  38. package/dist/vite/durableDb.js +23 -28
  39. package/package.json +12 -12
  40. package/dist/arktypeConfig-zgI5p6zF.d.ts +0 -6
  41. package/dist/context-kIVZbhye.js +0 -121
  42. package/dist/generator-KHBZaOI1.js +0 -202
  43. package/dist/index-zzQS_psa.d.ts +0 -51
  44. package/dist/protocol-DEubbBbR.js +0 -35
  45. package/dist/push-BhrMZaQx.js +0 -190
  46. package/dist/push-cUJBpv5y.js +0 -8
  47. package/dist/schema-C2yy5KCT.d.ts +0 -6
  48. package/dist/schema-IFq7ovQq.js +0 -8
  49. package/dist/snapshot-DMW6j2Ix.js +0 -93
  50. package/dist/snapshot-DsSRYFe-.d.ts +0 -125
  51. package/dist/state-vav3VCId.js +0 -5
  52. package/dist/websocket-eao2rnHL.js +0 -104
@@ -1,3 +1,34 @@
1
- import { i as encodeResponse, n as decodeResponse, r as encodeRequest, t as decodeRequest } from "../protocol-DEubbBbR.js";
2
-
3
- export { decodeRequest, decodeResponse, encodeRequest, encodeResponse };
1
+ //#region src/transport/protocol.ts
2
+ function encodeRequest(req) {
3
+ return JSON.stringify(req);
4
+ }
5
+ function decodeRequest(data) {
6
+ const parsed = JSON.parse(data);
7
+ if (typeof parsed !== "object" || parsed === null) throw new Error(`Invalid WsActionRequest: expected object, got ${parsed === null ? "null" : typeof parsed}`);
8
+ const obj = parsed;
9
+ for (const field of [
10
+ "id",
11
+ "action",
12
+ "instanceKey"
13
+ ]) if (typeof obj[field] !== "string") throw new Error(`Invalid WsActionRequest: '${field}' must be a string, got ${describeType(obj[field])}`);
14
+ return obj;
15
+ }
16
+ function encodeResponse(res) {
17
+ return JSON.stringify(res);
18
+ }
19
+ function decodeResponse(data) {
20
+ const parsed = JSON.parse(data);
21
+ if (typeof parsed !== "object" || parsed === null) throw new Error(`Invalid WsActionResponse: expected object, got ${parsed === null ? "null" : typeof parsed}`);
22
+ const obj = parsed;
23
+ if (typeof obj.id !== "string") throw new Error(`Invalid WsActionResponse: 'id' must be a string, got ${describeType(obj.id)}`);
24
+ if (typeof obj.ok !== "boolean") throw new Error(`Invalid WsActionResponse: 'ok' must be a boolean, got ${describeType(obj.ok)}`);
25
+ if (!obj.ok && typeof obj.error !== "string") throw new Error(`Invalid WsActionResponse: 'error' must be a string when ok=false, got ${describeType(obj.error)}`);
26
+ return obj;
27
+ }
28
+ function describeType(value) {
29
+ if (value === null) return "null";
30
+ if (Array.isArray(value)) return "array";
31
+ return typeof value;
32
+ }
33
+ //#endregion
34
+ export { decodeRequest, decodeResponse, encodeRequest, encodeResponse };
@@ -1,7 +1,7 @@
1
1
  //#region src/transport/websocket.d.ts
2
2
  /** Default timeout (ms) after which a pending WebSocket request rejects. */
3
- declare const DEFAULT_WS_REQUEST_TIMEOUT_MS = 30000;
4
- interface WebSocketTransportOptions {
3
+ export declare const DEFAULT_WS_REQUEST_TIMEOUT_MS = 30000;
4
+ export interface WebSocketTransportOptions {
5
5
  /** Per-request timeout in ms. Set to 0 or Infinity to disable. */
6
6
  requestTimeoutMs?: number;
7
7
  }
@@ -11,7 +11,7 @@ interface WebSocketTransportOptions {
11
11
  * Manages a single WebSocket connection to a Durable Object stub,
12
12
  * with request-response correlation via message IDs.
13
13
  */
14
- declare class WebSocketTransport {
14
+ export declare class WebSocketTransport {
15
15
  private stub;
16
16
  private ws;
17
17
  private pending;
@@ -27,5 +27,4 @@ declare class WebSocketTransport {
27
27
  private onClose;
28
28
  close(): void;
29
29
  }
30
- //#endregion
31
- export { DEFAULT_WS_REQUEST_TIMEOUT_MS, WebSocketTransport, WebSocketTransportOptions };
30
+ //#endregion
@@ -1,3 +1,103 @@
1
- import { n as WebSocketTransport, t as DEFAULT_WS_REQUEST_TIMEOUT_MS } from "../websocket-eao2rnHL.js";
2
-
3
- export { DEFAULT_WS_REQUEST_TIMEOUT_MS, WebSocketTransport };
1
+ import { decodeResponse, encodeRequest } from "./protocol.js";
2
+ //#region src/transport/websocket.ts
3
+ /** Default timeout (ms) after which a pending WebSocket request rejects. */
4
+ const DEFAULT_WS_REQUEST_TIMEOUT_MS = 3e4;
5
+ /**
6
+ * Client-side WebSocket transport for calling DO actions over WebSocket.
7
+ *
8
+ * Manages a single WebSocket connection to a Durable Object stub,
9
+ * with request-response correlation via message IDs.
10
+ */
11
+ var WebSocketTransport = class {
12
+ stub;
13
+ ws = null;
14
+ pending = /* @__PURE__ */ new Map();
15
+ connectPromise = null;
16
+ requestTimeoutMs;
17
+ constructor(stub, options = {}) {
18
+ this.stub = stub;
19
+ this.requestTimeoutMs = options.requestTimeoutMs ?? 3e4;
20
+ }
21
+ async call(action, args, instanceKey) {
22
+ await this.ensureConnected();
23
+ const id = crypto.randomUUID();
24
+ const message = encodeRequest({
25
+ id,
26
+ action,
27
+ args,
28
+ instanceKey
29
+ });
30
+ return new Promise((resolve, reject) => {
31
+ const timer = this.requestTimeoutMs > 0 && Number.isFinite(this.requestTimeoutMs) ? setTimeout(() => {
32
+ const entry = this.pending.get(id);
33
+ if (!entry) return;
34
+ this.pending.delete(id);
35
+ entry.reject(/* @__PURE__ */ new Error(`[db] WebSocket request '${action}' timed out after ${this.requestTimeoutMs}ms`));
36
+ }, this.requestTimeoutMs) : null;
37
+ this.pending.set(id, {
38
+ resolve,
39
+ reject,
40
+ timer
41
+ });
42
+ this.ws.send(message);
43
+ });
44
+ }
45
+ async ensureConnected() {
46
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) return;
47
+ if (this.connectPromise) return this.connectPromise;
48
+ this.connectPromise = this.connect();
49
+ try {
50
+ await this.connectPromise;
51
+ } finally {
52
+ this.connectPromise = null;
53
+ }
54
+ }
55
+ async connect() {
56
+ const ws = (await this.stub.fetch(new Request("https://do/ws", { headers: { Upgrade: "websocket" } }))).webSocket;
57
+ if (!ws) throw new Error("WebSocket upgrade failed: no webSocket on response");
58
+ ws.accept();
59
+ this.ws = ws;
60
+ ws.addEventListener("message", (event) => {
61
+ this.onMessage(event);
62
+ });
63
+ ws.addEventListener("close", () => {
64
+ this.onClose();
65
+ });
66
+ ws.addEventListener("error", () => {
67
+ this.onClose();
68
+ });
69
+ }
70
+ onMessage(event) {
71
+ const raw = typeof event.data === "string" ? event.data : String(event.data);
72
+ let response;
73
+ try {
74
+ response = decodeResponse(raw);
75
+ } catch (e) {
76
+ const message = e instanceof Error ? e.message : String(e);
77
+ console.warn(`[db] WebSocket received malformed message (ignored): ${message}. First 120 chars: ${raw.slice(0, 120)}`);
78
+ return;
79
+ }
80
+ const pending = this.pending.get(response.id);
81
+ if (!pending) return;
82
+ this.pending.delete(response.id);
83
+ if (pending.timer) clearTimeout(pending.timer);
84
+ if (response.ok) pending.resolve(response.result);
85
+ else pending.reject(new Error(response.error));
86
+ }
87
+ onClose() {
88
+ this.ws = null;
89
+ for (const [, entry] of this.pending) {
90
+ if (entry.timer) clearTimeout(entry.timer);
91
+ entry.reject(/* @__PURE__ */ new Error("WebSocket connection closed"));
92
+ }
93
+ this.pending.clear();
94
+ }
95
+ close() {
96
+ if (this.ws) {
97
+ this.ws.close(1e3, "Client closing");
98
+ this.ws = null;
99
+ }
100
+ }
101
+ };
102
+ //#endregion
103
+ export { DEFAULT_WS_REQUEST_TIMEOUT_MS, WebSocketTransport };
@@ -1,8 +1,7 @@
1
- import { t as DatabaseSource } from "../discovery-DfimBbS_.js";
1
+ import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
2
2
  import { Plugin } from "vite";
3
-
4
3
  //#region src/vite/durableDb.d.ts
5
- interface DurableDbOptions {
4
+ export interface DurableDbOptions {
6
5
  /** Import path for the context module. Default: 'durable-db/context' */
7
6
  contextImport?: string;
8
7
  /** Import path for the registry module. Default: 'durable-db/registry' */
@@ -19,10 +18,10 @@ interface DurableDbOptions {
19
18
  */
20
19
  patchWranglerConfig?: boolean;
21
20
  }
22
- declare function durableDb(options?: DurableDbOptions): Plugin;
21
+ export declare function durableDb(options?: DurableDbOptions): Plugin;
23
22
  /** @deprecated Renamed to {@link durableDb}. */
24
- declare const databasePlugin: typeof durableDb;
23
+ export declare const databasePlugin: typeof durableDb;
25
24
  /** @deprecated Renamed to {@link DurableDbOptions}. */
26
- type DatabasePluginOptions = DurableDbOptions;
25
+ export type DatabasePluginOptions = DurableDbOptions;
27
26
  //#endregion
28
- export { DatabasePluginOptions, type DatabaseSource, DurableDbOptions, databasePlugin, durableDb as default, durableDb };
27
+ export { type DatabaseSource, durableDb as default };
@@ -1,15 +1,12 @@
1
- import { i as init_debug, r as debugVite } from "../debug-DmBrUmwe.js";
2
- import { _ as saveDevState, c as getDevPaths, d as init_state, m as loadDevState } from "../state-DtZ70cBR.js";
3
- import "../snapshot-DMW6j2Ix.js";
4
- import { a as loadMigrationFiles } from "../generator-KHBZaOI1.js";
5
- import { a as discoverDatabaseFiles, i as discoverActionFiles, n as parseDatabaseFile, o as readFile, r as databaseSources, t as BABEL_PARSER_PLUGINS } from "../parser-BdV7Zqcv.js";
1
+ import { i as init_debug, r as debugVite } from "../debug-Cz8KzMft.js";
2
+ import { a as getDevPaths, d as saveDevState, l as loadDevState, s as init_state } from "../state-OVuoHRC9.js";
3
+ import { loadMigrationFiles } from "../migrations/generator.js";
4
+ import { a as discoverDatabaseFiles, i as discoverActionFiles, n as parseDatabaseFile, o as readFile, r as databaseSources, t as BABEL_PARSER_PLUGINS } from "../parser-DR57GOjv.js";
6
5
  import * as fs from "node:fs";
7
- import * as path$1 from "node:path";
8
- import path from "node:path";
6
+ import path, * as path$1 from "node:path";
9
7
  import { parse } from "@babel/parser";
10
8
  import _generate from "@babel/generator";
11
9
  import * as t from "@babel/types";
12
-
13
10
  //#region src/vite/modules/wrangler.ts
14
11
  init_debug();
15
12
  /**
@@ -262,7 +259,6 @@ function generateRequiredConfig(databases) {
262
259
  }]
263
260
  };
264
261
  }
265
-
266
262
  //#endregion
267
263
  //#region src/vite/modules/generator.ts
268
264
  const generate = typeof _generate === "function" ? _generate : _generate.default;
@@ -281,7 +277,8 @@ function parseProgram(code) {
281
277
  });
282
278
  }
283
279
  function parseExpression(code) {
284
- const stmt = parse(`(${code.trim().replace(/;\s*$/, "")})`, {
280
+ const wrapped = `(${code.trim().replace(/;\s*$/, "")})`;
281
+ const stmt = parse(wrapped, {
285
282
  sourceType: "module",
286
283
  plugins: BABEL_PARSER_PLUGINS
287
284
  }).program.body[0];
@@ -420,8 +417,8 @@ function buildDurableObjectStatements(db, bindingNamesExpr, dbTransportsExpr, is
420
417
  const classMethods = [rpcMethod, buildSysMethod()];
421
418
  if (db.transport === "websocket") classMethods.push(buildWebSocketMessageMethod(db, bindingNamesExpr, dbTransportsExpr));
422
419
  if (!isBrowsable) {
423
- const classDecl$1 = t.classDeclaration(t.identifier(db.className), t.identifier("SqliteDurableObject"), t.classBody([...dataProperties, ...classMethods]));
424
- return [t.exportNamedDeclaration(classDecl$1)];
420
+ const classDecl = t.classDeclaration(t.identifier(db.className), t.identifier("SqliteDurableObject"), t.classBody([...dataProperties, ...classMethods]));
421
+ return [t.exportNamedDeclaration(classDecl)];
425
422
  }
426
423
  const baseName = `_${db.className}_Base`;
427
424
  const innerClass = t.classExpression(null, t.identifier("SqliteDurableObject"), t.classBody([...dataProperties]));
@@ -767,7 +764,6 @@ function applyDestroyDatabaseTransform(body, database, contextImport) {
767
764
  function isDefineDatabaseCallNode(node) {
768
765
  return t.isCallExpression(node) && t.isIdentifier(node.callee) && node.callee.name === "defineDatabase";
769
766
  }
770
-
771
767
  //#endregion
772
768
  //#region src/vite/durableDb.ts
773
769
  init_debug();
@@ -798,6 +794,7 @@ function generateDevEpochModule(epoch) {
798
794
  ].join("\n");
799
795
  }
800
796
  var PluginState = class {
797
+ options;
801
798
  databases = /* @__PURE__ */ new Map();
802
799
  actions = /* @__PURE__ */ new Map();
803
800
  databaseFilePaths = /* @__PURE__ */ new Map();
@@ -901,7 +898,7 @@ var PluginState = class {
901
898
  const isDev = this.config.command === "serve";
902
899
  db.migrations = loadMigrationFiles(migrationsDir);
903
900
  if (isDev) try {
904
- const { loadDevMigrations } = await import("../state-vav3VCId.js");
901
+ const { loadDevMigrations } = await import("../state-OVuoHRC9.js").then((n) => (n.s(), n.f));
905
902
  const devMigrations = loadDevMigrations(this.projectRoot, db.name);
906
903
  for (const [name, chunks] of devMigrations) db.migrations.set(`_dev_${name}`, chunks);
907
904
  if (devMigrations.size > 0) debugVite("Loaded %d dev migration(s) for %s", devMigrations.size, db.name);
@@ -1018,9 +1015,9 @@ function durableDb(options = {}) {
1018
1015
  },
1019
1016
  async load(id) {
1020
1017
  if (id === VIRTUAL_DEV_EPOCH_MODULE_ID) {
1021
- const isDev$1 = state.config.command === "serve";
1018
+ const isDev = state.config.command === "serve";
1022
1019
  let epoch = null;
1023
- if (isDev$1) {
1020
+ if (isDev) {
1024
1021
  const devState = loadDevState(state.projectRoot);
1025
1022
  if (!fs.existsSync(getDevPaths(state.projectRoot).stateFile)) {
1026
1023
  state.markSelfDevStateWrite();
@@ -1051,20 +1048,20 @@ function durableDb(options = {}) {
1051
1048
  const cleanId = path$1.normalize(id.split("?", 1)[0]);
1052
1049
  const dbNameForPath = state.getDatabaseNameForPath(cleanId);
1053
1050
  if (dbNameForPath) {
1054
- const database$1 = state.databases.get(dbNameForPath);
1055
- if (!database$1) return null;
1056
- const parsed$1 = parseDatabaseFile(cleanId, code, { aliases: state.aliases });
1057
- for (const action of parsed$1.actions) state.registerAction(action, dbNameForPath, cleanId);
1058
- const result$1 = transformDatabaseFile({
1051
+ const database = state.databases.get(dbNameForPath);
1052
+ if (!database) return null;
1053
+ const parsed = parseDatabaseFile(cleanId, code, { aliases: state.aliases });
1054
+ for (const action of parsed.actions) state.registerAction(action, dbNameForPath, cleanId);
1055
+ const result = transformDatabaseFile({
1059
1056
  code,
1060
1057
  sourceFileName: cleanId,
1061
- database: database$1,
1062
- actionsInFile: parsed$1.actions,
1058
+ database,
1059
+ actionsInFile: parsed.actions,
1063
1060
  contextImport: state.options.contextImport,
1064
1061
  registryImport: state.options.registryImport
1065
1062
  });
1066
- if (result$1 && parsed$1.actions.length > 0 && state.config.command === "serve") state.invalidateDOModule();
1067
- return result$1;
1063
+ if (result && parsed.actions.length > 0 && state.config.command === "serve") state.invalidateDOModule();
1064
+ return result;
1068
1065
  }
1069
1066
  const parsed = parseDatabaseFile(cleanId, code, { aliases: state.aliases });
1070
1067
  if (parsed.actions.length === 0) return null;
@@ -1092,7 +1089,5 @@ function durableDb(options = {}) {
1092
1089
  }
1093
1090
  /** @deprecated Renamed to {@link durableDb}. */
1094
1091
  const databasePlugin = durableDb;
1095
- var durableDb_default = durableDb;
1096
-
1097
1092
  //#endregion
1098
- export { databasePlugin, durableDb_default as default, durableDb };
1093
+ export { databasePlugin, durableDb as default, durableDb };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "durable-db",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/eagerpatch/durable-db.git"
@@ -83,12 +83,12 @@
83
83
  "@babel/traverse": "^7.0.0",
84
84
  "@babel/types": "^7.0.0",
85
85
  "@outerbase/browsable-durable-object": "^0.1.0",
86
- "arktype": "^2.1.28",
86
+ "arktype": "^2.2.8",
87
87
  "commander": "^15.0.0",
88
- "drizzle-kit": "^0.30.0",
88
+ "drizzle-kit": "^0.31.11",
89
89
  "drizzle-orm": "^0.38.0",
90
90
  "esbuild": "^0.27.1",
91
- "kysely": "^0.27.0",
91
+ "kysely": "^0.29.6",
92
92
  "libsql": "^0.5.0",
93
93
  "magic-string": "^0.30.21"
94
94
  },
@@ -100,17 +100,17 @@
100
100
  "@babel/parser": "^7.26.0",
101
101
  "@babel/traverse": "^7.26.0",
102
102
  "@babel/types": "^7.26.0",
103
- "@changesets/cli": "^2.29.8",
104
- "@cloudflare/vitest-pool-workers": "^0.8.71",
105
- "@cloudflare/workers-types": "^4.20241127.0",
103
+ "@changesets/cli": "^3.0.3",
104
+ "@cloudflare/vitest-pool-workers": "^0.23.0",
105
+ "@cloudflare/workers-types": "^5.20261016.1",
106
106
  "@types/babel__generator": "^7.6.8",
107
107
  "@types/babel__traverse": "^7.20.6",
108
- "@types/node": "^24.0.0",
108
+ "@types/node": "^26.6.5",
109
109
  "drizzle-kit": "^0.30.0",
110
110
  "esbuild": "^0.27.1",
111
- "tsdown": "^0.17.2",
112
- "typescript": "^5.7.0",
113
- "vite": "^7.0.0",
114
- "vitest": "^2.1.0"
111
+ "tsdown": "^0.23.1",
112
+ "typescript": "^7.0.2",
113
+ "vite": "^8.3.4",
114
+ "vitest": "^5.0.5"
115
115
  }
116
116
  }
@@ -1,6 +0,0 @@
1
- import { type } from "arktype";
2
-
3
- //#region src/arktypeConfig.d.ts
4
- declare const type$1: typeof type;
5
- //#endregion
6
- export { type$1 as t };
@@ -1,121 +0,0 @@
1
- import { s as __toCommonJS } from "./debug-DmBrUmwe.js";
2
- import { d as init_state, v as state_exports } from "./state-DtZ70cBR.js";
3
-
4
- //#region src/context/index.ts
5
- /**
6
- * Tenant ID resolver for framework integration.
7
- */
8
- let tenantIdResolver = null;
9
- /**
10
- * Configure a tenant ID resolver.
11
- *
12
- * The resolver is called at the moment a database operation needs the tenant ID —
13
- * by which point request middleware (auth, session, etc.) has already completed.
14
- *
15
- * @example
16
- * ```ts
17
- * import { setTenantIdResolver } from 'durable-db/context';
18
- * import { getRequestInfo } from 'rwsdk/worker';
19
- *
20
- * setTenantIdResolver(() => getRequestInfo().ctx.session!.shop);
21
- * ```
22
- */
23
- function setTenantIdResolver(resolver) {
24
- tenantIdResolver = resolver;
25
- }
26
- /**
27
- * Get the current tenant ID from the configured resolver.
28
- *
29
- * @throws Error if no resolver is configured
30
- *
31
- * @example
32
- * ```ts
33
- * import { getTenantId } from 'durable-db/context';
34
- *
35
- * async function myHandler() {
36
- * const tenantId = getTenantId();
37
- * // ...
38
- * }
39
- * ```
40
- */
41
- /**
42
- * Inside a Durable Object the instance key IS the tenant (per-tenant DBs key
43
- * their instances by tenant id, plus an optional `__dev_<epoch>` suffix in
44
- * dev). The registry publishes its DoContext store getter on globalThis — see
45
- * the note there for why this is not a module import — so getTenantId() works
46
- * in action handlers without the worker-side resolver, which the DO execution
47
- * context never registers.
48
- */
49
- function tenantIdFromDoContext() {
50
- const getStore = globalThis[Symbol.for("durable-db.doContext")];
51
- const key = getStore?.()?.instanceKey;
52
- if (!key || key === "global") return null;
53
- const suffixAt = key.lastIndexOf("__dev_");
54
- return suffixAt === -1 ? key : key.slice(0, suffixAt);
55
- }
56
- function getTenantId() {
57
- if (tenantIdResolver) return tenantIdResolver();
58
- const doTenant = tenantIdFromDoContext();
59
- if (doTenant) return doTenant;
60
- throw new Error("getTenantId() called without a resolver. Call setTenantIdResolver() first.");
61
- }
62
- /**
63
- * Check if a tenant ID resolver is configured (or a Durable Object context
64
- * can supply the tenant).
65
- */
66
- function hasTenantId() {
67
- return tenantIdResolver !== null || tenantIdFromDoContext() !== null;
68
- }
69
- /**
70
- * One-time warning guard: we only log an unexpected dev-epoch load failure
71
- * once per process so Vite HMR / repeated lookups don't spam stderr.
72
- */
73
- let loggedDevEpochFailure = false;
74
- /**
75
- * Get the dev epoch for instance key suffixing
76
- * Only used in development to allow database resets
77
- *
78
- * Returns null in production or if no dev state exists
79
- *
80
- * @deprecated The epoch is now baked into generated stubs at build time via
81
- * the `virtual:durable-db/__devEpoch` module — this function
82
- * cannot read the dev state inside workerd (no filesystem) and returns null
83
- * there. Import `devEpoch` / `applyDevEpoch` from the virtual module instead.
84
- */
85
- function getDevInstanceKeySuffix() {
86
- if (process.env.NODE_ENV === "production") return null;
87
- try {
88
- const { getDevEpoch } = (init_state(), __toCommonJS(state_exports));
89
- return getDevEpoch(process.cwd());
90
- } catch (e) {
91
- const code = e?.code;
92
- if (code !== "MODULE_NOT_FOUND" && code !== "ERR_MODULE_NOT_FOUND" && !loggedDevEpochFailure) {
93
- loggedDevEpochFailure = true;
94
- const message = e instanceof Error ? e.message : String(e);
95
- console.warn(`[durable-db] Could not load dev epoch state (continuing without it): ${message}`);
96
- }
97
- return null;
98
- }
99
- }
100
- /**
101
- * Get a database instance key, optionally suffixed with dev epoch
102
- *
103
- * In development, this appends an epoch suffix to enable database resets.
104
- * In production, this returns the base key unchanged.
105
- *
106
- * @deprecated Generated stubs apply the epoch automatically via
107
- * `applyDevEpoch` from `virtual:durable-db/__devEpoch`. This
108
- * function only works in Node (it reads the dev state from disk) and is the
109
- * identity inside workerd — combining it with the generated stubs would
110
- * also double-suffix keys. Import from the virtual module instead.
111
- *
112
- * @param baseKey - The base instance key (e.g., tenant ID or 'global')
113
- */
114
- function getInstanceKey(baseKey) {
115
- const suffix = getDevInstanceKeySuffix();
116
- if (!suffix) return baseKey;
117
- return `${baseKey}__dev_${suffix}`;
118
- }
119
-
120
- //#endregion
121
- export { setTenantIdResolver as a, hasTenantId as i, getInstanceKey as n, getTenantId as r, getDevInstanceKeySuffix as t };