durable-db 0.14.1 → 0.15.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.
@@ -30,7 +30,7 @@ declare const actionArgsType: TypeParser;
30
30
  export interface ActionDefinition {
31
31
  validator: (args: unknown) => unknown;
32
32
  handler: (db: unknown, args: unknown, ctx: unknown) => Promise<unknown>;
33
- /** The compiled args schema (a `type()`), for `describeAction()`. */
33
+ /** The compiled args schema (a `type()`), for `describeAction()`; a getter, read only when asked. */
34
34
  args?: unknown;
35
35
  /** The call site the build compiled this action to: `describeAction()` reads the description from it. */
36
36
  stub?: object;
@@ -50,6 +50,18 @@ export interface DoContext {
50
50
  * as its key, `'global'` as no tenant, when no resolver is set.
51
51
  */
52
52
  tenantId?: string | null;
53
+ /**
54
+ * The objects waiting on this call, outermost first: each is inside an
55
+ * action that called the next one. An action holds its object until it
56
+ * resolves (a transaction), so a call into one of them would wait for
57
+ * itself — `batchedRpc` refuses it (`ActionCycleError`).
58
+ */
59
+ via?: ActionCaller[];
60
+ }
61
+ /** An object waiting on a call it made: its database and instance key. */
62
+ export interface ActionCaller {
63
+ database: string;
64
+ instanceKey: string;
53
65
  }
54
66
  export interface RpcContext {
55
67
  env: Record<string, unknown>;
@@ -57,8 +69,23 @@ export interface RpcContext {
57
69
  dbBindingNames: Record<string, string>;
58
70
  dbTransports?: Record<string, 'rpc' | 'websocket'>;
59
71
  instanceKey: string;
60
- /** The action run's outbox (`runWithOutbox`); an action called from another of the same database shares it. */
72
+ /** The action run's outbox (`runAction`); an action called from another of the same database shares it. */
61
73
  outbox?: Outbox;
74
+ /**
75
+ * Runs `fn` as a part of the action that may fail on its own: its writes
76
+ * and the messages it pushed are rolled back when it throws, and the rest
77
+ * of the action goes on (`runAction`). An action called from another of
78
+ * the same database runs in one.
79
+ */
80
+ transaction?: <T>(fn: () => Promise<T>) => Promise<T>;
81
+ }
82
+ /**
83
+ * A call into an object that is waiting on it: an action holds its object
84
+ * until it resolves, so the call would wait for itself (for 30 s, after
85
+ * which the runtime resets the object).
86
+ */
87
+ export declare class ActionCycleError extends Error {
88
+ constructor(via: readonly ActionCaller[], target: ActionCaller, action?: string);
62
89
  }
63
90
  export declare function registerAction(dbName: string, actionName: string, def: ActionDefinition): void;
64
91
  export declare function getAction(dbName: string, actionName: string): ActionDefinition | undefined;
@@ -90,24 +117,26 @@ export type BatchedResult = {
90
117
  message: string;
91
118
  };
92
119
  };
120
+ /** What a call tells the object it reaches: its instance key, and the objects waiting on it. */
121
+ export interface RpcOptions {
122
+ instanceKey: string;
123
+ via?: ActionCaller[];
124
+ }
93
125
  interface ActionStub {
94
- rpc(action: string, args: unknown, options: {
95
- instanceKey: string;
96
- }): Promise<unknown>;
126
+ rpc(action: string, args: unknown, options: RpcOptions): Promise<unknown>;
97
127
  rpcBatch(calls: Array<{
98
128
  action: string;
99
129
  args: unknown;
100
- }>, options: {
101
- instanceKey: string;
102
- }): Promise<BatchedResult[]>;
130
+ }>, options: RpcOptions): Promise<BatchedResult[]>;
103
131
  }
104
132
  interface ActionNamespace {
105
133
  idFromName(name: string): unknown;
106
134
  get(id: unknown): ActionStub;
107
135
  }
108
136
  /**
109
- * The args schema of an action, compiled on its first call in this isolate
110
- * and kept — the compiled call site used to build it on every call.
137
+ * What `make()` answers for `key`, made at the first call in this isolate and
138
+ * kept. (The action transform no longer calls it: each action file keeps its
139
+ * one compiled args schema itself, so an edit in dev compiles the new one.)
111
140
  */
112
141
  export declare function cachedArgsSchema<T>(key: string, make: () => T): T;
113
142
  /**
@@ -130,7 +159,12 @@ export declare function batchScope<T>(fn: () => T): T;
130
159
  * own caller; a lone call, and every call outside a scope, is a plain `rpc`.
131
160
  * Results are plain values: the RPC's top-level `Symbol.dispose` is dropped
132
161
  * (React Server Components refuse symbol-keyed props).
162
+ *
163
+ * Made from an action (inside a Durable Object), the call names the objects
164
+ * waiting on it (`via`), and one into any of them is refused at once
165
+ * (`ActionCycleError`): `database` is the target's name, which the build
166
+ * passes.
133
167
  */
134
- export declare function batchedRpc(namespace: ActionNamespace, instanceKey: string, action: string, args: unknown): Promise<unknown>;
168
+ export declare function batchedRpc(namespace: ActionNamespace, instanceKey: string, action: string, args: unknown, database?: string): Promise<unknown>;
135
169
  //#endregion
136
170
  export { actionArgsType as type };
package/dist/registry.js CHANGED
@@ -1,9 +1,21 @@
1
- import { r as type } from "./type-pAQ37iEL.js";
2
- import { t as actionArgsType } from "./actionArgs-oUWwX6Xn.js";
1
+ import { r as type } from "./type-C7apBBQw.js";
2
+ import { t as actionArgsType } from "./actionArgs-BAmU_AIB.js";
3
3
  import { t as ACTION_INFO } from "./describeAction-CEKfxTQ4.js";
4
4
  import { WebSocketTransport } from "./transport/websocket.js";
5
5
  import { AsyncLocalStorage } from "node:async_hooks";
6
6
  //#region src/registry.ts
7
+ /**
8
+ * A call into an object that is waiting on it: an action holds its object
9
+ * until it resolves, so the call would wait for itself (for 30 s, after
10
+ * which the runtime resets the object).
11
+ */
12
+ var ActionCycleError = class extends Error {
13
+ constructor(via, target, action) {
14
+ const name = ({ database, instanceKey }) => `${database} (${instanceKey})`;
15
+ super(`[db] ${action ? `${action}: a call` : "A call"} into ${name(target)}, which is waiting on this call: ${[...via, target].map(name).join(" → ")}. An action holds its object until it resolves, so the call would wait for itself. Make the calls from the worker, one after the other, or have the first action push the work to its outbox.`);
16
+ this.name = "ActionCycleError";
17
+ }
18
+ };
7
19
  const actionsByDb = /* @__PURE__ */ new Map();
8
20
  const als = new AsyncLocalStorage();
9
21
  const wsTransportCache = /* @__PURE__ */ new Map();
@@ -24,15 +36,20 @@ function registerAction(dbName, actionName, def) {
24
36
  actionsByDb.set(dbName, dbMap);
25
37
  }
26
38
  dbMap.set(actionName, def);
27
- if (def.stub) Object.defineProperty(def.stub, ACTION_INFO, {
28
- value: {
39
+ if (def.stub) {
40
+ const info = {
29
41
  database: dbName,
30
42
  name: actionName,
31
- args: def.args
32
- },
33
- enumerable: false,
34
- configurable: true
35
- });
43
+ get args() {
44
+ return def.args;
45
+ }
46
+ };
47
+ Object.defineProperty(def.stub, ACTION_INFO, {
48
+ value: info,
49
+ enumerable: false,
50
+ configurable: true
51
+ });
52
+ }
36
53
  }
37
54
  function getAction(dbName, actionName) {
38
55
  return actionsByDb.get(dbName)?.get(actionName) ?? sharedActions().get(actionName);
@@ -83,7 +100,7 @@ async function callAction(db, targetDb, actionName, args, ctx) {
83
100
  const entry = getOrThrow(targetDb, actionName);
84
101
  const validated = entry.validator(args);
85
102
  if (validated instanceof type.errors) throw new Error(`[db] Invalid args for ${targetDb}/${actionName}: ${validated.summary}`);
86
- if (ctx.dbName === targetDb) return entry.handler(db, validated, ctx);
103
+ if (ctx.dbName === targetDb) return ctx.transaction ? ctx.transaction(() => entry.handler(db, validated, ctx)) : entry.handler(db, validated, ctx);
87
104
  const bindingName = ctx.dbBindingNames[targetDb];
88
105
  if (!bindingName) {
89
106
  const known = Object.keys(ctx.dbBindingNames);
@@ -99,8 +116,9 @@ async function callAction(db, targetDb, actionName, args, ctx) {
99
116
  }
100
117
  const argsSchemas = /* @__PURE__ */ new Map();
101
118
  /**
102
- * The args schema of an action, compiled on its first call in this isolate
103
- * and kept — the compiled call site used to build it on every call.
119
+ * What `make()` answers for `key`, made at the first call in this isolate and
120
+ * kept. (The action transform no longer calls it: each action file keeps its
121
+ * one compiled args schema itself, so an edit in dev compiles the new one.)
104
122
  */
105
123
  function cachedArgsSchema(key, make) {
106
124
  let schema = argsSchemas.get(key);
@@ -131,8 +149,22 @@ function batchScope(fn) {
131
149
  * own caller; a lone call, and every call outside a scope, is a plain `rpc`.
132
150
  * Results are plain values: the RPC's top-level `Symbol.dispose` is dropped
133
151
  * (React Server Components refuse symbol-keyed props).
152
+ *
153
+ * Made from an action (inside a Durable Object), the call names the objects
154
+ * waiting on it (`via`), and one into any of them is refused at once
155
+ * (`ActionCycleError`): `database` is the target's name, which the build
156
+ * passes.
134
157
  */
135
- function batchedRpc(namespace, instanceKey, action, args) {
158
+ function batchedRpc(namespace, instanceKey, action, args, database) {
159
+ const caller = als.getStore();
160
+ const via = caller ? [...caller.via ?? [], {
161
+ database: caller.dbName,
162
+ instanceKey: caller.instanceKey
163
+ }] : void 0;
164
+ if (via && database !== void 0 && via.some((waiting) => waiting.database === database && waiting.instanceKey === instanceKey)) return Promise.reject(new ActionCycleError(via, {
165
+ database,
166
+ instanceKey
167
+ }, action));
136
168
  const scope = batchScopes.getStore();
137
169
  return new Promise((resolve, reject) => {
138
170
  const call = {
@@ -141,8 +173,11 @@ function batchedRpc(namespace, instanceKey, action, args) {
141
173
  resolve,
142
174
  reject
143
175
  };
144
- if (!scope) {
145
- sendCalls(namespace, instanceKey, [call]);
176
+ if (!scope || via) {
177
+ sendCalls(namespace, via ? {
178
+ instanceKey,
179
+ via
180
+ } : { instanceKey }, [call]);
146
181
  return;
147
182
  }
148
183
  let byKey = scope.pending.get(namespace);
@@ -159,18 +194,17 @@ function batchedRpc(namespace, instanceKey, action, args) {
159
194
  function flushCalls(namespace, instanceKey, byKey) {
160
195
  const calls = byKey.get(instanceKey) ?? [];
161
196
  byKey.delete(instanceKey);
162
- sendCalls(namespace, instanceKey, calls);
197
+ sendCalls(namespace, { instanceKey }, calls);
163
198
  }
164
- function sendCalls(namespace, instanceKey, calls) {
199
+ function sendCalls(namespace, options, calls) {
165
200
  if (calls.length === 0) return;
166
201
  let stub;
167
202
  try {
168
- stub = namespace.get(namespace.idFromName(instanceKey));
203
+ stub = namespace.get(namespace.idFromName(options.instanceKey));
169
204
  } catch (error) {
170
205
  for (const call of calls) call.reject(error);
171
206
  return;
172
207
  }
173
- const options = { instanceKey };
174
208
  if (calls.length === 1) {
175
209
  const [call] = calls;
176
210
  stub.rpc(call.action, call.args, options).then((value) => call.resolve(structuredClone(value)), call.reject);
@@ -191,4 +225,4 @@ function sendCalls(namespace, instanceKey, calls) {
191
225
  });
192
226
  }
193
227
  //#endregion
194
- export { batchScope, batchedRpc, cachedArgsSchema, callAction, getAction, getDoContext, registerAction, registerSharedAction, runWithDoContext, actionArgsType as type };
228
+ export { ActionCycleError, batchScope, batchedRpc, cachedArgsSchema, callAction, getAction, getDoContext, registerAction, registerSharedAction, runWithDoContext, actionArgsType as type };
package/dist/schema.d.ts CHANGED
@@ -1,5 +1,14 @@
1
- import { AnySQLiteColumn as AnySQLiteColumn$1, UpdateDeleteAction, blob, foreignKey, index, integer, numeric, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
1
+ import { AnySQLiteColumn as AnySQLiteColumn$1, UpdateDeleteAction } from "drizzle-orm/sqlite-core";
2
2
  import { ColumnBuilderBaseConfig, ColumnBuilderExtraConfig, ColumnDataType } from "drizzle-orm";
3
+ import { sqliteTable } from "drizzle-orm/sqlite-core/table";
4
+ import { text } from "drizzle-orm/sqlite-core/columns/text";
5
+ import { integer } from "drizzle-orm/sqlite-core/columns/integer";
6
+ import { real } from "drizzle-orm/sqlite-core/columns/real";
7
+ import { blob } from "drizzle-orm/sqlite-core/columns/blob";
8
+ import { numeric } from "drizzle-orm/sqlite-core/columns/numeric";
9
+ import { index, uniqueIndex } from "drizzle-orm/sqlite-core/indexes";
10
+ import { foreignKey } from "drizzle-orm/sqlite-core/foreign-keys";
11
+ import { primaryKey } from "drizzle-orm/sqlite-core/primary-keys";
3
12
  //#region src/schema.d.ts
4
13
  declare module 'drizzle-orm/sqlite-core/columns/common' {
5
14
  interface SQLiteColumnBuilder<T extends ColumnBuilderBaseConfig<ColumnDataType, string> = ColumnBuilderBaseConfig<ColumnDataType, string>, TRuntimeConfig extends object = object, TTypeConfig extends object = object, TExtraConfig extends ColumnBuilderExtraConfig = object> {
package/dist/schema.js CHANGED
@@ -1,5 +1,13 @@
1
- import { blob, foreignKey, index, integer, numeric, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
2
1
  import { toSnakeCase } from "drizzle-orm/casing";
2
+ import { sqliteTable } from "drizzle-orm/sqlite-core/table";
3
+ import { text } from "drizzle-orm/sqlite-core/columns/text";
4
+ import { integer } from "drizzle-orm/sqlite-core/columns/integer";
5
+ import { real } from "drizzle-orm/sqlite-core/columns/real";
6
+ import { blob } from "drizzle-orm/sqlite-core/columns/blob";
7
+ import { numeric } from "drizzle-orm/sqlite-core/columns/numeric";
8
+ import { index, uniqueIndex } from "drizzle-orm/sqlite-core/indexes";
9
+ import { foreignKey } from "drizzle-orm/sqlite-core/foreign-keys";
10
+ import { primaryKey } from "drizzle-orm/sqlite-core/primary-keys";
3
11
  //#region src/schema.ts
4
12
  const table = ((name, columns, extraConfig) => sqliteTable(toSnakeCase(name), columns, extraConfig));
5
13
  //#endregion
@@ -1,4 +1,4 @@
1
- import { a as __esmMin, i as init_debug, o as __exportAll, t as debugCli } from "./debug-BFOTDUja.js";
1
+ import { i as init_debug, o as __esmMin, s as __exportAll, t as debugCli } from "./debug-Di50ua4a.js";
2
2
  import * as fs from "node:fs";
3
3
  import * as path$1 from "node:path";
4
4
  import * as crypto from "node:crypto";
@@ -58,6 +58,12 @@ export interface TestDatabase<TSchema = any> {
58
58
  * every table of the action's database.
59
59
  */
60
60
  run<TArgs, TResult>(action: (args: TArgs) => Promise<TResult>, args: TArgs): Promise<TResult>;
61
+ /**
62
+ * Run an action's handler with `args` already validated, as {@link run}
63
+ * does once it has validated them: for a library that finds an action's
64
+ * handler itself (a database driver of its own).
65
+ */
66
+ runHandler<TResult>(handler: (db: any, args: any, ctx: any) => Promise<TResult>, args: unknown): Promise<TResult>;
61
67
  /** The raw `node:sqlite` handle, for escape-hatch SQL. */
62
68
  sqlite: DatabaseSync;
63
69
  /** Every message the actions run here pushed to `ctx.outbox` (successful ones only), oldest first. */
@@ -1,10 +1,12 @@
1
- import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-_AusJf3r.js";
2
- import { r as type } from "../type-pAQ37iEL.js";
3
- import "../actionArgs-oUWwX6Xn.js";
1
+ import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-xd-9vnhm.js";
2
+ import { r as type } from "../type-C7apBBQw.js";
3
+ import "../actionArgs-BAmU_AIB.js";
4
4
  import { setTenantIdResolver } from "../context/index.js";
5
- import { h as tenantOfInstanceKey, l as createActionOutbox, t as createKyselyFromSql } from "../kysely-C675L1b9.js";
5
+ import { h as tenantOfInstanceKey, l as createActionOutbox, t as createKyselyFromSql } from "../kysely-BUmrdN9f.js";
6
6
  import { i as generateSnapshotFromSchema, n as createEmptySnapshot, r as generateMigrationStatements } from "../snapshot-4RsNw1yr.js";
7
+ import { ActionCycleError } from "../registry.js";
7
8
  import { createRequire } from "node:module";
9
+ import { AsyncLocalStorage } from "node:async_hooks";
8
10
  //#region src/testing/index.ts
9
11
  let sqlite;
10
12
  /** `node:sqlite`, loaded without Node 22's experimental notice: for a test that opens a database of its own. */
@@ -49,6 +51,53 @@ function sqlStorageShim(sqlite) {
49
51
  return { toArray: () => rows };
50
52
  } };
51
53
  }
54
+ const FRAMES = Symbol.for("durable-db.testTransactions");
55
+ const frames = globalThis[FRAMES] ??= new AsyncLocalStorage();
56
+ /**
57
+ * Runs `fn` in a transaction of `transactions` — BEGIN, or a SAVEPOINT inside
58
+ * the one the calling code is in — once it is this one's turn, committing it
59
+ * when `fn` resolves and rolling it back when it throws.
60
+ */
61
+ async function inTransaction(sqlite, transactions, ctx, fn) {
62
+ const stack = frames.getStore() ?? [];
63
+ let inside;
64
+ for (const frame of stack) if (frame.transactions === transactions) inside = frame.level;
65
+ const parent = inside !== void 0 && transactions.open.includes(inside) ? inside : void 0;
66
+ while (transactions.open.at(-1) !== parent) await new Promise((resolve) => transactions.waiting.push(resolve));
67
+ const level = Symbol("transaction");
68
+ transactions.open.push(level);
69
+ const depth = transactions.open.length;
70
+ const savepoint = `durable_db_test_${depth}`;
71
+ sqlite.exec(depth === 1 ? "BEGIN" : `SAVEPOINT ${savepoint}`);
72
+ try {
73
+ const result = await frames.run([...stack, {
74
+ transactions,
75
+ level,
76
+ ctx
77
+ }], fn);
78
+ sqlite.exec(depth === 1 ? "COMMIT" : `RELEASE ${savepoint}`);
79
+ return result;
80
+ } catch (error) {
81
+ sqlite.exec(depth === 1 ? "ROLLBACK" : `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}`);
82
+ throw error;
83
+ } finally {
84
+ transactions.open.pop();
85
+ const waiting = transactions.waiting.splice(0);
86
+ if (waiting.length > 0) setImmediate(() => waiting.forEach((wake) => wake()));
87
+ }
88
+ }
89
+ /** A part of the action of `ctx`: a savepoint, and what it pushed goes with it when it throws. */
90
+ function partOf(sqlite, transactions, ctx) {
91
+ return (fn) => inTransaction(sqlite, transactions, ctx, async () => {
92
+ const mark = ctx.outbox.mark();
93
+ try {
94
+ return await fn();
95
+ } catch (error) {
96
+ ctx.outbox.rewind(mark);
97
+ throw error;
98
+ }
99
+ });
100
+ }
52
101
  async function deriveStatements(schema) {
53
102
  const snapshot = await generateSnapshotFromSchema(schema);
54
103
  return generateMigrationStatements(createEmptySnapshot(), snapshot);
@@ -78,25 +127,47 @@ async function createTestDatabase(options) {
78
127
  const ddl = statements ?? await deriveStatements(schema);
79
128
  for (const stmt of ddl) sqlite.exec(stmt);
80
129
  setTenantIdResolver(() => tenantId);
81
- async function run(action, args) {
82
- const meta = action[ACTION_TEST_META];
83
- if (!meta) throw new Error("createTestDatabase().run() was given a function that is not a durable-db action (no test metadata). Pass an export created by `action({ … })`.");
84
- const validated = meta.validator(args);
85
- if (validated instanceof type.errors) throw new Error(`Invalid args for action: ${validated.summary}`);
86
- const instance = options.instance ?? meta.instance ?? "per-tenant";
87
- const instanceKey = instance === "global" ? "global" : tenantId;
88
- const outbox = createActionOutbox(true);
89
- const result = await meta.handler(db, validated, {
130
+ const instance = (meta) => options.instance ?? meta?.instance ?? "per-tenant";
131
+ const transactions = {
132
+ name: database,
133
+ open: [],
134
+ waiting: []
135
+ };
136
+ async function execute(handler, validated, kind) {
137
+ const instanceKey = kind === "global" ? "global" : tenantId;
138
+ const stack = frames.getStore() ?? [];
139
+ const innermost = stack.at(-1);
140
+ if (innermost?.transactions === transactions) return innermost.ctx.transaction(() => handler(db, validated, innermost.ctx));
141
+ if (stack.some((frame) => frame.transactions === transactions)) {
142
+ const via = stack.map((frame) => ({
143
+ database: frame.transactions.name,
144
+ instanceKey: frame.ctx.instanceKey
145
+ }));
146
+ throw new ActionCycleError(via, {
147
+ database,
148
+ instanceKey
149
+ });
150
+ }
151
+ const ctx = {
90
152
  env,
153
+ dbName: database,
91
154
  instanceKey,
92
- outbox
155
+ outbox: createActionOutbox(true),
156
+ transaction: (fn) => part(fn)
157
+ };
158
+ const part = partOf(sqlite, transactions, ctx);
159
+ let recordedAt = 0;
160
+ const result = await inTransaction(sqlite, transactions, ctx, async () => {
161
+ const value = await handler(db, validated, ctx);
162
+ recordedAt = Date.now();
163
+ return value;
93
164
  });
94
- const envelopes = outbox.take().map((message) => ({
165
+ const envelopes = ctx.outbox.take().map((message) => ({
95
166
  message: JSON.parse(message),
96
167
  database,
97
168
  instanceKey,
98
- tenantId: tenantOfInstanceKey(instanceKey, { instance }),
99
- recordedAt: Date.now(),
169
+ tenantId: tenantOfInstanceKey(instanceKey, { instance: kind }),
170
+ recordedAt,
100
171
  attempts: 0
101
172
  }));
102
173
  if (envelopes.length > 0) {
@@ -105,6 +176,14 @@ async function createTestDatabase(options) {
105
176
  }
106
177
  return result;
107
178
  }
179
+ async function run(action, args) {
180
+ const meta = action[ACTION_TEST_META];
181
+ if (!meta) throw new Error("createTestDatabase().run() was given a function that is not a durable-db action (no test metadata). Pass an export created by `action({ … })`.");
182
+ const validated = meta.validator(args);
183
+ if (validated instanceof type.errors) throw new Error(`Invalid args for action: ${validated.summary}`);
184
+ return execute(meta.handler, validated, instance(meta));
185
+ }
186
+ const runHandler = (handler, args) => execute(handler, args, instance());
108
187
  const live = {
109
188
  tables: new Set(Object.values(schema)),
110
189
  run: (action, args) => run(action, args),
@@ -123,6 +202,7 @@ async function createTestDatabase(options) {
123
202
  return {
124
203
  db,
125
204
  run,
205
+ runHandler,
126
206
  sqlite,
127
207
  outbox: recorded,
128
208
  destroy() {
@@ -1 +1 @@
1
- export { o as ArkError, s as ArkErrors, i as ParseError, a as ToJsonSchemaError, c as TraversalError, t as createTypeParser, n as isType, r as type } from "../type-pAQ37iEL.js";
1
+ export { o as ArkError, s as ArkErrors, i as ParseError, a as ToJsonSchemaError, c as TraversalError, t as createTypeParser, n as isType, r as type } from "../type-C7apBBQw.js";
@@ -1342,7 +1342,8 @@ const iso8601 = /^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|
1342
1342
  const ipv4Segment = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";
1343
1343
  const ipv4Address = `(${ipv4Segment}[.]){3}${ipv4Segment}`;
1344
1344
  const ipv6Segment = "(?:[0-9a-fA-F]{1,4})";
1345
- const ipv6 = new RegExp(`^((?:${ipv6Segment}:){7}(?:${ipv6Segment}|:)|(?:${ipv6Segment}:){6}(?:${ipv4Address}|:${ipv6Segment}|:)|(?:${ipv6Segment}:){5}(?::${ipv4Address}|(:${ipv6Segment}){1,2}|:)|(?:${ipv6Segment}:){4}(?:(:${ipv6Segment}){0,1}:${ipv4Address}|(:${ipv6Segment}){1,3}|:)|(?:${ipv6Segment}:){3}(?:(:${ipv6Segment}){0,2}:${ipv4Address}|(:${ipv6Segment}){1,4}|:)|(?:${ipv6Segment}:){2}(?:(:${ipv6Segment}){0,3}:${ipv4Address}|(:${ipv6Segment}){1,5}|:)|(?:${ipv6Segment}:){1}(?:(:${ipv6Segment}){0,4}:${ipv4Address}|(:${ipv6Segment}){1,6}|:)|(?::((?::${ipv6Segment}){0,5}:${ipv4Address}|(?::${ipv6Segment}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?\$`);
1345
+ let ipv6Pattern;
1346
+ const ipv6 = () => ipv6Pattern ??= new RegExp(`^((?:${ipv6Segment}:){7}(?:${ipv6Segment}|:)|(?:${ipv6Segment}:){6}(?:${ipv4Address}|:${ipv6Segment}|:)|(?:${ipv6Segment}:){5}(?::${ipv4Address}|(:${ipv6Segment}){1,2}|:)|(?:${ipv6Segment}:){4}(?:(:${ipv6Segment}){0,1}:${ipv4Address}|(:${ipv6Segment}){1,3}|:)|(?:${ipv6Segment}:){3}(?:(:${ipv6Segment}){0,2}:${ipv4Address}|(:${ipv6Segment}){1,4}|:)|(?:${ipv6Segment}:){2}(?:(:${ipv6Segment}){0,3}:${ipv4Address}|(:${ipv6Segment}){1,5}|:)|(?:${ipv6Segment}:){1}(?:(:${ipv6Segment}){0,4}:${ipv4Address}|(:${ipv6Segment}){1,6}|:)|(?::((?::${ipv6Segment}){0,5}:${ipv4Address}|(?::${ipv6Segment}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?\$`);
1346
1347
  const uuidVersioned = /^[\dA-Fa-f]{8}-[\dA-Fa-f]{4}-[1-8][\dA-Fa-f]{3}-[89ABab][\dA-Fa-f]{3}-[\dA-Fa-f]{12}$/;
1347
1348
  const uuidVersion = (v) => new RegExp(`^[\\dA-Fa-f]{8}-[\\dA-Fa-f]{4}-${v}[\\dA-Fa-f]{3}-[89ABab][\\dA-Fa-f]{3}-[\\dA-Fa-f]{12}$`);
1348
1349
  const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/;
@@ -1481,12 +1482,12 @@ const KEYWORDS = {
1481
1482
  "string.semver": () => regexString(semver, "a semantic version (see https://semver.org/)"),
1482
1483
  "string.creditCard": () => new RefinedNode(string(), [patternRefinement(creditCardMatcher, "a credit card number"), predicateRefinement(isLuhnValid, "a credit card number")], "a credit card number"),
1483
1484
  "string.ip": () => {
1484
- const node = described(new UnionNode([regexString(new RegExp(`^${ipv4Address}$`), "an IPv4 address", "ipv4"), regexString(ipv6, "an IPv6 address", "ipv6")]), "an IP address");
1485
+ const node = described(new UnionNode([regexString(new RegExp(`^${ipv4Address}$`), "an IPv4 address", "ipv4"), regexString(ipv6(), "an IPv6 address", "ipv6")]), "an IP address");
1485
1486
  node.meta = { description: "an IP address" };
1486
1487
  return node;
1487
1488
  },
1488
1489
  "string.ip.v4": () => regexString(new RegExp(`^${ipv4Address}$`), "an IPv4 address", "ipv4"),
1489
- "string.ip.v6": () => regexString(ipv6, "an IPv6 address", "ipv6"),
1490
+ "string.ip.v6": () => regexString(ipv6(), "an IPv6 address", "ipv6"),
1490
1491
  "string.uuid": () => described(new UnionNode([
1491
1492
  regexString(uuidVersioned, "a UUID"),
1492
1493
  new UnitNode("00000000-0000-0000-0000-000000000000"),
@@ -2290,6 +2291,73 @@ function makeType(node, config) {
2290
2291
  validate[CONFIG] = config;
2291
2292
  return validate;
2292
2293
  }
2294
+ /**
2295
+ * A Type whose node is made at its first use — a call, any property or
2296
+ * method, its use inside another Type — then kept, so a definition is parsed
2297
+ * once, and never if its Type is never used. `type()` runs at module scope
2298
+ * (an action's args, an API's inputs, a job's), and every isolate — a
2299
+ * worker's and each Durable Object's — evaluates all of them as it starts,
2300
+ * though a request validates one or two. A definition that cannot be parsed
2301
+ * throws its ParseError at that first use, each time it is used. `parse`
2302
+ * reads the definition as `type()` copied it (`snapshot()`).
2303
+ */
2304
+ function lazyType(parse, config) {
2305
+ let node;
2306
+ const nodeOf = () => node ??= parse();
2307
+ const validate = ((data) => run(nodeOf(), config, data));
2308
+ Object.setPrototypeOf(validate, prototype);
2309
+ Object.defineProperty(validate, NODE, {
2310
+ configurable: true,
2311
+ enumerable: true,
2312
+ get() {
2313
+ const parsed = nodeOf();
2314
+ Object.defineProperty(validate, NODE, {
2315
+ value: parsed,
2316
+ writable: true,
2317
+ enumerable: true,
2318
+ configurable: true
2319
+ });
2320
+ return parsed;
2321
+ }
2322
+ });
2323
+ validate[CONFIG] = config;
2324
+ return validate;
2325
+ }
2326
+ /**
2327
+ * The definition as it is at `type()`, for a parse that comes later: its plain
2328
+ * objects and arrays copied, at any depth, so one changed after `type()` does
2329
+ * not change what the Type checks — as when `type()` parsed it. What a
2330
+ * definition holds as a value is kept as it is: the values of `['===', …]`
2331
+ * (compared by identity) and a default (`[def, '=', value]`, handed out as
2332
+ * it is), and a Type, a function, a RegExp, a Standard Schema or an instance
2333
+ * of a class anywhere (one of those is read when it is parsed).
2334
+ */
2335
+ function snapshot(def) {
2336
+ if (typeof def !== "object" || def === null || def instanceof RegExp || "~standard" in def) return def;
2337
+ if (Array.isArray(def)) {
2338
+ if (def[0] === "===") return def.slice();
2339
+ if (def.length === 3 && def[1] === "=") return [
2340
+ snapshot(def[0]),
2341
+ "=",
2342
+ def[2]
2343
+ ];
2344
+ return def.map(snapshot);
2345
+ }
2346
+ const proto = Object.getPrototypeOf(def);
2347
+ if (proto !== Object.prototype && proto !== null) return def;
2348
+ const copy = {};
2349
+ for (const key of Object.keys(def)) {
2350
+ const value = snapshot(def[key]);
2351
+ if (key === "__proto__") Object.defineProperty(copy, key, {
2352
+ value,
2353
+ enumerable: true,
2354
+ writable: true,
2355
+ configurable: true
2356
+ });
2357
+ else copy[key] = value;
2358
+ }
2359
+ return copy;
2360
+ }
2293
2361
  /** A `type()` whose Types follow `config` (durable-db's action args admit `undefined` for an optional key). */
2294
2362
  function createTypeParser(config = {}) {
2295
2363
  const resolved = {
@@ -2297,15 +2365,24 @@ function createTypeParser(config = {}) {
2297
2365
  ...config
2298
2366
  };
2299
2367
  const context = contextFor(resolved);
2300
- const parse = (def) => makeType(parseDefinition(def, context), resolved);
2368
+ const parse = (def) => {
2369
+ const written = snapshot(def);
2370
+ return lazyType(() => parseDefinition(written, context), resolved);
2371
+ };
2301
2372
  const parser = ((...args) => parse(args.length === 1 ? args[0] : args));
2302
2373
  Object.assign(parser, {
2303
2374
  errors: ArkErrors,
2304
2375
  raw: parse,
2305
2376
  unit: (value) => makeType(new UnitNode(value), resolved),
2306
2377
  enumerated: (...values) => makeType(union(values.map((v) => new UnitNode(v))), resolved),
2307
- or: (...defs) => makeType(union(defs.map((d) => parseDefinition(d, context))), resolved),
2308
- and: (...defs) => makeType(defs.map((d) => parseDefinition(d, context)).reduce(intersect), resolved)
2378
+ or: (...defs) => {
2379
+ const written = defs.map(snapshot);
2380
+ return lazyType(() => union(written.map((d) => parseDefinition(d, context))), resolved);
2381
+ },
2382
+ and: (...defs) => {
2383
+ const written = defs.map(snapshot);
2384
+ return lazyType(() => written.map((d) => parseDefinition(d, context)).reduce(intersect), resolved);
2385
+ }
2309
2386
  });
2310
2387
  return parser;
2311
2388
  }
@@ -1,5 +1,5 @@
1
1
  import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
2
- import "../index-B1J4Kjum.js";
2
+ import "../index-oTr2B0ap.js";
3
3
  import { Plugin } from "vite";
4
4
  import "@babel/types";
5
5
  //#region src/vite/modules/wrangler.d.ts