durable-db 0.8.0 → 0.9.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/README.md +124 -0
- package/dist/cli/index.d.ts +2 -2
- package/dist/db/index.d.ts +3 -3
- package/dist/db/index.js +215 -8
- package/dist/defineDatabase-BvFOZVkv.d.ts +377 -0
- package/dist/defineDatabase-CaqKQagA.js +767 -0
- package/dist/describeAction-CEKfxTQ4.js +24 -0
- package/dist/{index-rlnVnzJJ.d.ts → index-DoxI1p4-.d.ts} +1 -1
- package/dist/index.d.ts +19 -3
- package/dist/index.js +3 -2
- package/dist/kysely-D8JQ4v8n.js +278 -0
- package/dist/registry.d.ts +15 -0
- package/dist/registry.js +30 -2
- package/dist/schema.d.ts +15 -2
- package/dist/testing/index.js +2 -2
- package/dist/vite/durableDb.d.ts +1 -1
- package/dist/vite/durableDb.js +35 -1
- package/package.json +1 -1
- package/virtual.d.ts +12 -0
- package/dist/defineDatabase-595bNB6M.js +0 -110
- package/dist/defineDatabase-By401iHp.d.ts +0 -200
- package/dist/kysely-DvAoap5h.js +0 -631
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
//#region src/db/describeAction.ts
|
|
2
|
+
/** On a compiled call site: what `registerAction()` was told. */
|
|
3
|
+
const ACTION_INFO = Symbol.for("durable-db.actionInfo");
|
|
4
|
+
/** On an untransformed action (see ./defineDatabase). */
|
|
5
|
+
const ACTION_TEST_META = Symbol.for("durable-db.actionTestMeta");
|
|
6
|
+
/** The description of an action, or undefined for anything that is not one. */
|
|
7
|
+
function describeAction(action) {
|
|
8
|
+
if (typeof action !== "function") return void 0;
|
|
9
|
+
const tagged = action;
|
|
10
|
+
const info = tagged[ACTION_INFO];
|
|
11
|
+
if (info) return {
|
|
12
|
+
database: info.database,
|
|
13
|
+
name: info.name,
|
|
14
|
+
args: info.args
|
|
15
|
+
};
|
|
16
|
+
const meta = tagged[ACTION_TEST_META];
|
|
17
|
+
if (meta) return {
|
|
18
|
+
database: null,
|
|
19
|
+
name: null,
|
|
20
|
+
args: meta.validator
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
//#endregion
|
|
24
|
+
export { describeAction as n, ACTION_INFO as t };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "./defineDatabase-
|
|
1
|
+
import "./defineDatabase-BvFOZVkv.js";
|
|
2
2
|
import { i as OutboxSink, t as Outbox } from "./outbox-D3Q9n7Rt.js";
|
|
3
3
|
import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
|
|
4
4
|
import { CamelCasePlugin, CamelCasePlugin as CamelCasePlugin$1, CompiledQuery, Kysely, Kysely as Kysely$1, KyselyPlugin, KyselyPlugin as KyselyPlugin$1, PluginTransformQueryArgs, PluginTransformResultArgs, QueryResult, QueryResult as QueryResult$1, RootOperationNode, UnknownRow } from "kysely";
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,23 @@
|
|
|
1
|
-
import { l as type } from "./index-bUUlOWfP.js";
|
|
2
|
-
import { c as DatabaseDefinition, d as InferArgs, i as ActionContext, n as Action, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely } from "./defineDatabase-
|
|
1
|
+
import { i as Type, l as type } from "./index-bUUlOWfP.js";
|
|
2
|
+
import { _ as RelationMap, b as relationOf, c as DatabaseDefinition, d as InferArgs, g as Relation, h as RelatedOptions, i as ActionContext, m as RelatedExpression, n as Action, p as Related, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelationType, x as relationsOf, y as Relations } from "./defineDatabase-BvFOZVkv.js";
|
|
3
3
|
import { a as OutboxSinkContext, i as OutboxSink, n as OutboxEnvelope, o as OutboxSinkModule, r as OutboxMessage, t as Outbox } from "./outbox-D3Q9n7Rt.js";
|
|
4
4
|
import { getTenantId, hasTenantId, setTenantIdResolver } from "./context/index.js";
|
|
5
5
|
import { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
|
|
6
6
|
import { Kysely } from "kysely";
|
|
7
|
-
|
|
7
|
+
//#region src/db/describeAction.d.ts
|
|
8
|
+
interface ActionDescription {
|
|
9
|
+
/** The database it belongs to, as discovered (`main`); null untransformed. */
|
|
10
|
+
database: string | null;
|
|
11
|
+
/** Its export name; null untransformed. */
|
|
12
|
+
name: string | null;
|
|
13
|
+
/**
|
|
14
|
+
* Its compiled args schema: the `type()` of its `args` — `.toJsonSchema()`,
|
|
15
|
+
* `.expression`, or call it to validate. Undefined only for a call site
|
|
16
|
+
* registered by hand without one.
|
|
17
|
+
*/
|
|
18
|
+
args: Type | undefined;
|
|
19
|
+
}
|
|
20
|
+
/** The description of an action, or undefined for anything that is not one. */
|
|
21
|
+
export declare function describeAction(action: unknown): ActionDescription | undefined;
|
|
22
|
+
//#endregion
|
|
23
|
+
export { type Action, type ActionConfig, type ActionContext, type ActionDescription, type AnySQLiteColumn, type DatabaseConfig, type DatabaseDefinition, type DrizzleToKysely, type InferArgs, type Kysely, type Outbox, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, type Related, RelatedExpression, type RelatedOptions, type Relation, type RelationMap, type RelationType, type Relations, blob, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, relationOf, relationsOf, setTenantIdResolver, table, text, type, uniqueIndex };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import { d as relationOf, f as relationsOf, i as RelatedExpression, n as defineDatabase } from "./defineDatabase-CaqKQagA.js";
|
|
1
2
|
import { r as type } from "./type-CUgZsZp3.js";
|
|
2
3
|
import "./actionArgs-DP2tQrlf.js";
|
|
3
|
-
import { n as defineDatabase } from "./defineDatabase-595bNB6M.js";
|
|
4
4
|
import { blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
|
|
5
|
+
import { n as describeAction } from "./describeAction-CEKfxTQ4.js";
|
|
5
6
|
import { getTenantId, hasTenantId, setTenantIdResolver } from "./context/index.js";
|
|
6
|
-
export { blob, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, setTenantIdResolver, table, text, type, uniqueIndex };
|
|
7
|
+
export { RelatedExpression, blob, defineDatabase, describeAction, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, relationOf, relationsOf, setTenantIdResolver, table, text, type, uniqueIndex };
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { a as createRelatedPlugins, l as createDrizzlePlugins, o as DateSerializePlugin } from "./defineDatabase-CaqKQagA.js";
|
|
2
|
+
import { CamelCasePlugin, Kysely, SqliteDialect, SqliteQueryCompiler } from "kysely";
|
|
3
|
+
//#region src/db/outbox.ts
|
|
4
|
+
/** A sink module's default export as a sink: a deliver function, or an object with one. */
|
|
5
|
+
function outboxSink(module) {
|
|
6
|
+
if (typeof module === "function") return { deliver: module };
|
|
7
|
+
if (module && typeof module.deliver === "function") return module;
|
|
8
|
+
throw new TypeError("[db] An outbox module must default-export a deliver function, or an object with one");
|
|
9
|
+
}
|
|
10
|
+
/** Cloudflare Queues takes at most 100 messages per sendBatch. */
|
|
11
|
+
const QUEUE_BATCH = 100;
|
|
12
|
+
/** Each message to the Queue binding `binding`, as it was pushed. */
|
|
13
|
+
function queueOutboxSink(binding) {
|
|
14
|
+
return { async deliver(envelopes, { env }) {
|
|
15
|
+
const queue = env[binding];
|
|
16
|
+
if (!queue?.sendBatch) throw new Error(`[db] The outbox sends to the Queue binding ${binding}, which this worker does not have`);
|
|
17
|
+
for (let i = 0; i < envelopes.length; i += QUEUE_BATCH) await queue.sendBatch(envelopes.slice(i, i + QUEUE_BATCH).map((envelope) => ({ body: envelope.message })));
|
|
18
|
+
} };
|
|
19
|
+
}
|
|
20
|
+
const OUTBOX_TABLE = "__outbox";
|
|
21
|
+
const OUTBOX_DDL = `CREATE TABLE IF NOT EXISTS ${OUTBOX_TABLE} (
|
|
22
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
23
|
+
instance_key TEXT NOT NULL,
|
|
24
|
+
message TEXT NOT NULL,
|
|
25
|
+
recorded_at INTEGER NOT NULL,
|
|
26
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
27
|
+
last_error TEXT
|
|
28
|
+
)`;
|
|
29
|
+
/** The wait before retrying a failed delivery: 5 s, doubling, at most 5 minutes. */
|
|
30
|
+
function outboxRetryDelay(attempts) {
|
|
31
|
+
return Math.min(5e3 * 2 ** Math.max(0, attempts - 1), 3e5);
|
|
32
|
+
}
|
|
33
|
+
/** The tenant an instance key belongs to (its dev epoch suffix dropped); null for a global database. */
|
|
34
|
+
function tenantOfInstanceKey(instanceKey) {
|
|
35
|
+
const suffixAt = instanceKey.lastIndexOf("__dev_");
|
|
36
|
+
const tenant = suffixAt === -1 ? instanceKey : instanceKey.slice(0, suffixAt);
|
|
37
|
+
return tenant === "global" ? null : tenant;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The outbox of one action run: `push()` collects, and once the handler has
|
|
41
|
+
* resolved `take()` hands the messages over to be written. A message must be
|
|
42
|
+
* a JSON value; it is checked (serialized) when pushed, so a bad one fails
|
|
43
|
+
* the action that pushed it rather than a delivery later.
|
|
44
|
+
*/
|
|
45
|
+
function createActionOutbox(sinkConfigured) {
|
|
46
|
+
let messages = [];
|
|
47
|
+
return {
|
|
48
|
+
push(message) {
|
|
49
|
+
if (!sinkConfigured) throw new Error("[db] ctx.outbox.push(): no outbox sink is configured — durableDb({ outbox: { queue: \"<QUEUE_BINDING>\" } }) or durableDb({ outbox: { module: \"./src/outbox.ts\" } })");
|
|
50
|
+
const json = JSON.stringify(message);
|
|
51
|
+
if (json === void 0) throw new TypeError("[db] ctx.outbox.push(): a message must be a JSON value");
|
|
52
|
+
messages.push(json);
|
|
53
|
+
},
|
|
54
|
+
take() {
|
|
55
|
+
const taken = messages;
|
|
56
|
+
messages = [];
|
|
57
|
+
return taken;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
//#endregion
|
|
62
|
+
//#region src/db/kysely.ts
|
|
63
|
+
const MAX_BOUND_PARAMETERS = 100;
|
|
64
|
+
/**
|
|
65
|
+
* Kysely's SQLite compiler with identifiers quoted in backticks instead of
|
|
66
|
+
* double quotes. SQLite (workerd's build included) reads a double-quoted
|
|
67
|
+
* identifier that names no column as a string literal, so a column missing
|
|
68
|
+
* from the database — a schema change not yet migrated — silently selects its
|
|
69
|
+
* own name (`"weight_grams"` → 'weight_grams') and a WHERE on it compares two
|
|
70
|
+
* constants. A backtick-quoted identifier is never a literal: the query fails
|
|
71
|
+
* with "no such column". The migrations already quote with backticks.
|
|
72
|
+
*/
|
|
73
|
+
var BacktickSqliteQueryCompiler = class extends SqliteQueryCompiler {
|
|
74
|
+
getLeftIdentifierWrapper() {
|
|
75
|
+
return "`";
|
|
76
|
+
}
|
|
77
|
+
getRightIdentifierWrapper() {
|
|
78
|
+
return "`";
|
|
79
|
+
}
|
|
80
|
+
sanitizeIdentifier(identifier) {
|
|
81
|
+
return identifier.replaceAll("`", "``");
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* workerd has no boolean binding type and silently stringifies JS booleans
|
|
86
|
+
* (storing TEXT 'true' in an INTEGER column); node:sqlite rejects them
|
|
87
|
+
* outright. Normalize to SQLite's 1/0 convention before the value reaches
|
|
88
|
+
* either. `undefined` → NULL for the same reason.
|
|
89
|
+
*/
|
|
90
|
+
function normalizeParameter(value) {
|
|
91
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
92
|
+
if (value === void 0) return null;
|
|
93
|
+
return value;
|
|
94
|
+
}
|
|
95
|
+
function escapeLiteral(value) {
|
|
96
|
+
if (value === null || value === void 0) return "NULL";
|
|
97
|
+
if (typeof value === "boolean") return value ? "1" : "0";
|
|
98
|
+
if (typeof value === "number") {
|
|
99
|
+
if (!Number.isFinite(value)) throw new Error(`[db] Cannot inline non-finite number parameter (${value})`);
|
|
100
|
+
return String(value);
|
|
101
|
+
}
|
|
102
|
+
if (typeof value === "bigint") return value.toString();
|
|
103
|
+
if (typeof value === "string") {
|
|
104
|
+
if (value.includes("\0")) throw new Error("[db] Cannot inline a string parameter containing a NUL byte");
|
|
105
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
106
|
+
}
|
|
107
|
+
if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
|
|
108
|
+
const bytes = value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
109
|
+
let hex = "";
|
|
110
|
+
for (const b of bytes) hex += b.toString(16).padStart(2, "0");
|
|
111
|
+
return `X'${hex}'`;
|
|
112
|
+
}
|
|
113
|
+
throw new Error(`[db] Cannot inline SQL parameter of type ${typeof value}`);
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Replace each `?` placeholder in `sql` with the escaped literal of its
|
|
117
|
+
* parameter. A real scanner, not a regex: '…' string literals ('' escapes),
|
|
118
|
+
* "…" and `…` quoted identifiers, `--` line comments and C-style block
|
|
119
|
+
* comments are skipped, so a `?` inside any of them is never touched.
|
|
120
|
+
*
|
|
121
|
+
* Exported for tests.
|
|
122
|
+
*/
|
|
123
|
+
function inlineParameters(sql, parameters) {
|
|
124
|
+
let out = "";
|
|
125
|
+
let p = 0;
|
|
126
|
+
for (let i = 0; i < sql.length; i++) {
|
|
127
|
+
const ch = sql[i];
|
|
128
|
+
if (ch === "'" || ch === "\"" || ch === "`") {
|
|
129
|
+
let j = i + 1;
|
|
130
|
+
while (j < sql.length) {
|
|
131
|
+
if (sql[j] === ch) {
|
|
132
|
+
if (sql[j + 1] === ch) {
|
|
133
|
+
j += 2;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
j++;
|
|
139
|
+
}
|
|
140
|
+
out += sql.slice(i, j + 1);
|
|
141
|
+
i = j;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (ch === "-" && sql[i + 1] === "-") {
|
|
145
|
+
let j = sql.indexOf("\n", i);
|
|
146
|
+
if (j === -1) j = sql.length;
|
|
147
|
+
out += sql.slice(i, j);
|
|
148
|
+
i = j - 1;
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
if (ch === "/" && sql[i + 1] === "*") {
|
|
152
|
+
let j = sql.indexOf("*/", i + 2);
|
|
153
|
+
j = j === -1 ? sql.length : j + 2;
|
|
154
|
+
out += sql.slice(i, j);
|
|
155
|
+
i = j - 1;
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
if (ch === "?") {
|
|
159
|
+
if (p >= parameters.length) throw new Error("[db] Query has more `?` placeholders than parameters while inlining");
|
|
160
|
+
out += escapeLiteral(parameters[p++]);
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
out += ch;
|
|
164
|
+
}
|
|
165
|
+
if (p !== parameters.length) throw new Error(`[db] Inlined ${p} parameter(s) but the query provided ${parameters.length} — placeholder/parameter mismatch`);
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* A Kysely driver that uses Cloudflare DO SQLite storage
|
|
170
|
+
*/
|
|
171
|
+
var CloudflareSqliteDriver = class {
|
|
172
|
+
sql;
|
|
173
|
+
constructor(sql) {
|
|
174
|
+
this.sql = sql;
|
|
175
|
+
}
|
|
176
|
+
async init() {}
|
|
177
|
+
async acquireConnection() {
|
|
178
|
+
return new CloudflareSqliteConnection(this.sql);
|
|
179
|
+
}
|
|
180
|
+
async beginTransaction(connection, settings) {
|
|
181
|
+
if (settings.isolationLevel) throw new Error("SQLite does not support isolation levels");
|
|
182
|
+
await connection.executeQuery(createCompiledQuery("BEGIN"));
|
|
183
|
+
}
|
|
184
|
+
async commitTransaction(connection) {
|
|
185
|
+
await connection.executeQuery(createCompiledQuery("COMMIT"));
|
|
186
|
+
}
|
|
187
|
+
async rollbackTransaction(connection) {
|
|
188
|
+
await connection.executeQuery(createCompiledQuery("ROLLBACK"));
|
|
189
|
+
}
|
|
190
|
+
async releaseConnection() {}
|
|
191
|
+
async destroy() {}
|
|
192
|
+
};
|
|
193
|
+
/**
|
|
194
|
+
* Helper to create a CompiledQuery object
|
|
195
|
+
*/
|
|
196
|
+
function createCompiledQuery(sql, parameters = []) {
|
|
197
|
+
return {
|
|
198
|
+
sql,
|
|
199
|
+
parameters,
|
|
200
|
+
query: {
|
|
201
|
+
kind: "RawNode",
|
|
202
|
+
sqlFragments: [sql],
|
|
203
|
+
parameters: []
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* A Kysely connection that wraps Cloudflare's SqlStorage
|
|
209
|
+
*/
|
|
210
|
+
var CloudflareSqliteConnection = class {
|
|
211
|
+
sql;
|
|
212
|
+
constructor(sql) {
|
|
213
|
+
this.sql = sql;
|
|
214
|
+
}
|
|
215
|
+
async executeQuery(compiledQuery) {
|
|
216
|
+
let queryStr = compiledQuery.sql;
|
|
217
|
+
let parameters = compiledQuery.parameters.map(normalizeParameter);
|
|
218
|
+
if (parameters.length > MAX_BOUND_PARAMETERS) {
|
|
219
|
+
queryStr = inlineParameters(queryStr, parameters);
|
|
220
|
+
parameters = [];
|
|
221
|
+
}
|
|
222
|
+
const isSelect = /^\s*(SELECT|RETURNING)/i.test(queryStr) || /\s+RETURNING\s+/i.test(queryStr);
|
|
223
|
+
try {
|
|
224
|
+
if (isSelect) return {
|
|
225
|
+
rows: this.sql.exec(queryStr, ...parameters).toArray(),
|
|
226
|
+
numAffectedRows: void 0,
|
|
227
|
+
insertId: void 0
|
|
228
|
+
};
|
|
229
|
+
else {
|
|
230
|
+
this.sql.exec(queryStr, ...parameters);
|
|
231
|
+
const [result] = this.sql.exec("SELECT changes() AS changes, last_insert_rowid() AS id").toArray();
|
|
232
|
+
const changes = result?.changes ?? 0;
|
|
233
|
+
const lastId = result?.id;
|
|
234
|
+
return {
|
|
235
|
+
rows: [],
|
|
236
|
+
numAffectedRows: BigInt(changes),
|
|
237
|
+
insertId: typeof lastId === "number" || typeof lastId === "bigint" ? BigInt(lastId) : void 0
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
} catch (error) {
|
|
241
|
+
throw error;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
streamQuery() {
|
|
245
|
+
throw new Error("Streaming is not supported in Cloudflare SQLite");
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
/**
|
|
249
|
+
* Create a Kysely instance from Cloudflare SqlStorage
|
|
250
|
+
*
|
|
251
|
+
* @param sqlStorage - The Cloudflare SqlStorage instance
|
|
252
|
+
* @param options - Configuration options including schema for plugins
|
|
253
|
+
*/
|
|
254
|
+
function createKyselyFromSql(sqlStorage, options = {}) {
|
|
255
|
+
const { schema, plugins = [], camelCase = true } = options;
|
|
256
|
+
const sqliteDialect = new SqliteDialect({ database: null });
|
|
257
|
+
const allPlugins = [];
|
|
258
|
+
const related = schema ? createRelatedPlugins(schema) : void 0;
|
|
259
|
+
if (related) allPlugins.push(related.capture);
|
|
260
|
+
if (schema) allPlugins.push(...createDrizzlePlugins(schema, camelCase));
|
|
261
|
+
else if (camelCase) {
|
|
262
|
+
allPlugins.push(new CamelCasePlugin());
|
|
263
|
+
allPlugins.push(new DateSerializePlugin());
|
|
264
|
+
} else allPlugins.push(new DateSerializePlugin());
|
|
265
|
+
allPlugins.push(...plugins);
|
|
266
|
+
if (related) allPlugins.push(related.results);
|
|
267
|
+
return new Kysely({
|
|
268
|
+
dialect: {
|
|
269
|
+
createAdapter: () => sqliteDialect.createAdapter(),
|
|
270
|
+
createDriver: () => new CloudflareSqliteDriver(sqlStorage),
|
|
271
|
+
createIntrospector: (db) => sqliteDialect.createIntrospector(db),
|
|
272
|
+
createQueryCompiler: () => new BacktickSqliteQueryCompiler()
|
|
273
|
+
},
|
|
274
|
+
plugins: allPlugins
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
//#endregion
|
|
278
|
+
export { outboxRetryDelay as a, tenantOfInstanceKey as c, createActionOutbox as i, OUTBOX_DDL as n, outboxSink as o, OUTBOX_TABLE as r, queueOutboxSink as s, createKyselyFromSql as t };
|
package/dist/registry.d.ts
CHANGED
|
@@ -30,6 +30,10 @@ 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()`. */
|
|
34
|
+
args?: unknown;
|
|
35
|
+
/** The call site the build compiled this action to: `describeAction()` reads the description from it. */
|
|
36
|
+
stub?: object;
|
|
33
37
|
}
|
|
34
38
|
export interface DoContext {
|
|
35
39
|
db: unknown;
|
|
@@ -48,6 +52,17 @@ export interface RpcContext {
|
|
|
48
52
|
}
|
|
49
53
|
export declare function registerAction(dbName: string, actionName: string, def: ActionDefinition): void;
|
|
50
54
|
export declare function getAction(dbName: string, actionName: string): ActionDefinition | undefined;
|
|
55
|
+
/**
|
|
56
|
+
* Registers an action every database has: `stub.rpc(actionName, args)` runs it
|
|
57
|
+
* in whichever Durable Object is called, with that database's `db` and the
|
|
58
|
+
* action context — for a library that works on any schema (a query executor,
|
|
59
|
+
* an exporter). A database's own action of the same name wins; give a shared
|
|
60
|
+
* action a name no export can have (`"graph:run"`).
|
|
61
|
+
*
|
|
62
|
+
* Opt-in: nothing is registered unless a module calls this, and the module
|
|
63
|
+
* has to be loaded in the Durable Object's isolate (the worker's entry is).
|
|
64
|
+
*/
|
|
65
|
+
export declare function registerSharedAction(actionName: string, def: ActionDefinition): void;
|
|
51
66
|
export declare function getDoContext(): DoContext | undefined;
|
|
52
67
|
export declare function runWithDoContext<T>(store: DoContext, fn: () => T): T;
|
|
53
68
|
/**
|
package/dist/registry.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { r as type } from "./type-CUgZsZp3.js";
|
|
2
2
|
import { t as actionArgsType } from "./actionArgs-DP2tQrlf.js";
|
|
3
|
+
import { t as ACTION_INFO } from "./describeAction-CEKfxTQ4.js";
|
|
3
4
|
import { WebSocketTransport } from "./transport/websocket.js";
|
|
4
5
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
5
6
|
//#region src/registry.ts
|
|
@@ -23,9 +24,36 @@ function registerAction(dbName, actionName, def) {
|
|
|
23
24
|
actionsByDb.set(dbName, dbMap);
|
|
24
25
|
}
|
|
25
26
|
dbMap.set(actionName, def);
|
|
27
|
+
if (def.stub) Object.defineProperty(def.stub, ACTION_INFO, {
|
|
28
|
+
value: {
|
|
29
|
+
database: dbName,
|
|
30
|
+
name: actionName,
|
|
31
|
+
args: def.args
|
|
32
|
+
},
|
|
33
|
+
enumerable: false,
|
|
34
|
+
configurable: true
|
|
35
|
+
});
|
|
26
36
|
}
|
|
27
37
|
function getAction(dbName, actionName) {
|
|
28
|
-
return actionsByDb.get(dbName)?.get(actionName);
|
|
38
|
+
return actionsByDb.get(dbName)?.get(actionName) ?? sharedActions().get(actionName);
|
|
39
|
+
}
|
|
40
|
+
const SHARED_ACTIONS = Symbol.for("durable-db.sharedActions");
|
|
41
|
+
function sharedActions() {
|
|
42
|
+
const store = globalThis;
|
|
43
|
+
return store[SHARED_ACTIONS] ??= /* @__PURE__ */ new Map();
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Registers an action every database has: `stub.rpc(actionName, args)` runs it
|
|
47
|
+
* in whichever Durable Object is called, with that database's `db` and the
|
|
48
|
+
* action context — for a library that works on any schema (a query executor,
|
|
49
|
+
* an exporter). A database's own action of the same name wins; give a shared
|
|
50
|
+
* action a name no export can have (`"graph:run"`).
|
|
51
|
+
*
|
|
52
|
+
* Opt-in: nothing is registered unless a module calls this, and the module
|
|
53
|
+
* has to be loaded in the Durable Object's isolate (the worker's entry is).
|
|
54
|
+
*/
|
|
55
|
+
function registerSharedAction(actionName, def) {
|
|
56
|
+
sharedActions().set(actionName, def);
|
|
29
57
|
}
|
|
30
58
|
function getOrThrow(dbName, actionName) {
|
|
31
59
|
const entry = getAction(dbName, actionName);
|
|
@@ -140,4 +168,4 @@ function flushCalls(namespace, instanceKey, byKey) {
|
|
|
140
168
|
});
|
|
141
169
|
}
|
|
142
170
|
//#endregion
|
|
143
|
-
export { batchedRpc, cachedArgsSchema, callAction, getAction, getDoContext, registerAction, runWithDoContext, actionArgsType as type };
|
|
171
|
+
export { batchedRpc, cachedArgsSchema, callAction, getAction, getDoContext, registerAction, registerSharedAction, runWithDoContext, actionArgsType as type };
|
package/dist/schema.d.ts
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
|
-
import { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
1
|
+
import { AnySQLiteColumn as AnySQLiteColumn$1, UpdateDeleteAction, blob, foreignKey, index, integer, numeric, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
2
|
+
import { ColumnBuilderBaseConfig, ColumnBuilderExtraConfig, ColumnDataType } from "drizzle-orm";
|
|
2
3
|
//#region src/schema.d.ts
|
|
4
|
+
declare module 'drizzle-orm/sqlite-core/columns/common' {
|
|
5
|
+
interface SQLiteColumnBuilder<T extends ColumnBuilderBaseConfig<ColumnDataType, string> = ColumnBuilderBaseConfig<ColumnDataType, string>, TRuntimeConfig extends object = object, TTypeConfig extends object = object, TExtraConfig extends ColumnBuilderExtraConfig = object> {
|
|
6
|
+
references<C extends AnySQLiteColumn>(ref: () => C, actions?: {
|
|
7
|
+
onUpdate?: UpdateDeleteAction;
|
|
8
|
+
onDelete?: UpdateDeleteAction;
|
|
9
|
+
}): this & {
|
|
10
|
+
_: {
|
|
11
|
+
references: C;
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
}
|
|
3
16
|
export declare const table: typeof sqliteTable;
|
|
4
17
|
//#endregion
|
|
5
|
-
export { type AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, text, uniqueIndex };
|
|
18
|
+
export { type AnySQLiteColumn$1 as AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, text, uniqueIndex };
|
package/dist/testing/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
+
import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-CaqKQagA.js";
|
|
1
2
|
import { r as type } from "../type-CUgZsZp3.js";
|
|
2
3
|
import "../actionArgs-DP2tQrlf.js";
|
|
3
|
-
import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-595bNB6M.js";
|
|
4
4
|
import { setTenantIdResolver } from "../context/index.js";
|
|
5
|
-
import {
|
|
5
|
+
import { c as tenantOfInstanceKey, i as createActionOutbox, t as createKyselyFromSql } from "../kysely-D8JQ4v8n.js";
|
|
6
6
|
import { i as generateSnapshotFromSchema, n as createEmptySnapshot, r as generateMigrationStatements } from "../snapshot-D_z95s6E.js";
|
|
7
7
|
import { createRequire } from "node:module";
|
|
8
8
|
//#region src/testing/index.ts
|
package/dist/vite/durableDb.d.ts
CHANGED
package/dist/vite/durableDb.js
CHANGED
|
@@ -822,6 +822,26 @@ function generateDurableObjectsModule(databases, registryImport, isDev = false,
|
|
|
822
822
|
return generateCode(t.file(program));
|
|
823
823
|
}
|
|
824
824
|
/**
|
|
825
|
+
* `virtual:durable-db/__databases`: what the plugin discovered, for a library
|
|
826
|
+
* that needs to know which database a table belongs to —
|
|
827
|
+
*
|
|
828
|
+
* export const databases = [{ name, bindingName, className, instance, schema: { <table>: <the table> } }];
|
|
829
|
+
*
|
|
830
|
+
* The tables are imported from the schema module, as the Durable Object
|
|
831
|
+
* classes import them: the same objects the app's own code holds.
|
|
832
|
+
*/
|
|
833
|
+
function generateDatabasesModule(databases) {
|
|
834
|
+
const entries = databases.map((db) => t.objectExpression([
|
|
835
|
+
t.objectProperty(t.identifier("name"), t.stringLiteral(db.name)),
|
|
836
|
+
t.objectProperty(t.identifier("bindingName"), t.stringLiteral(db.bindingName)),
|
|
837
|
+
t.objectProperty(t.identifier("className"), t.stringLiteral(db.className)),
|
|
838
|
+
t.objectProperty(t.identifier("instance"), t.stringLiteral(db.instance)),
|
|
839
|
+
t.objectProperty(t.identifier("schema"), hasSchema(db) ? buildSchemaProperty(db).value : t.objectExpression([]))
|
|
840
|
+
]));
|
|
841
|
+
const program = t.program([...databases.filter(hasSchema).map(buildSchemaImport), t.exportNamedDeclaration(t.variableDeclaration("const", [t.variableDeclarator(t.identifier("databases"), t.arrayExpression(entries))]))]);
|
|
842
|
+
return generateCode(t.file(program));
|
|
843
|
+
}
|
|
844
|
+
/**
|
|
825
845
|
* `export class <Old>DatabaseDO extends RemovedDatabaseDurableObject { … }`:
|
|
826
846
|
* the class of a removed database, kept so the worker still exports every
|
|
827
847
|
* class its migrations declare — its storage untouched, every call refused.
|
|
@@ -1142,7 +1162,12 @@ function applyActionTransforms(body, ctx) {
|
|
|
1142
1162
|
replaced.push(t.expressionStatement(t.callExpression(t.identifier("registerAction"), [
|
|
1143
1163
|
t.stringLiteral(dbName),
|
|
1144
1164
|
t.stringLiteral(exportName),
|
|
1145
|
-
t.objectExpression([
|
|
1165
|
+
t.objectExpression([
|
|
1166
|
+
t.objectProperty(t.identifier("validator"), t.arrowFunctionExpression([t.identifier("args")], t.callExpression(validatorId, [t.identifier("args")]))),
|
|
1167
|
+
t.objectProperty(t.identifier("handler"), handlerId),
|
|
1168
|
+
t.objectProperty(t.identifier("args"), validatorId),
|
|
1169
|
+
t.objectProperty(t.identifier("stub"), t.identifier(exportName))
|
|
1170
|
+
])
|
|
1146
1171
|
])));
|
|
1147
1172
|
const funcDecl = t.functionDeclaration(t.identifier(exportName), [t.identifier("args")], t.blockStatement(buildStubBodyStatements({
|
|
1148
1173
|
action,
|
|
@@ -1329,6 +1354,9 @@ const DURABLE_OBJECTS_ID = "durable-db/__durableObjects";
|
|
|
1329
1354
|
const VIRTUAL_DO_MODULE_ID = "\0virtual:durable-db/__durableObjects.js";
|
|
1330
1355
|
const DEV_EPOCH_ID = "durable-db/__devEpoch";
|
|
1331
1356
|
const VIRTUAL_DEV_EPOCH_MODULE_ID = "\0virtual:durable-db/__devEpoch.js";
|
|
1357
|
+
/** The discovered databases, for whoever imports it (nothing of durable-db's does). */
|
|
1358
|
+
const DATABASES_ID = "durable-db/__databases";
|
|
1359
|
+
const VIRTUAL_DATABASES_MODULE_ID = "\0virtual:durable-db/__databases.js";
|
|
1332
1360
|
/** Old org-prefixed spelling, still resolved for compatibility. */
|
|
1333
1361
|
const LEGACY_ID_PREFIX = "eagerpatch/";
|
|
1334
1362
|
/** Match a virtual id in all accepted spellings (`virtual:` optional, legacy prefix). */
|
|
@@ -1512,6 +1540,7 @@ var PluginState = class {
|
|
|
1512
1540
|
}
|
|
1513
1541
|
invalidateDOModule() {
|
|
1514
1542
|
this.invalidateVirtualModule(VIRTUAL_DO_MODULE_ID);
|
|
1543
|
+
this.invalidateVirtualModule(VIRTUAL_DATABASES_MODULE_ID);
|
|
1515
1544
|
}
|
|
1516
1545
|
invalidateDevEpochModule() {
|
|
1517
1546
|
this.invalidateVirtualModule(VIRTUAL_DEV_EPOCH_MODULE_ID);
|
|
@@ -1640,6 +1669,7 @@ function durableDb(options = {}) {
|
|
|
1640
1669
|
resolveId(id) {
|
|
1641
1670
|
if (matchesVirtualId(id, DURABLE_OBJECTS_ID)) return VIRTUAL_DO_MODULE_ID;
|
|
1642
1671
|
if (matchesVirtualId(id, DEV_EPOCH_ID)) return VIRTUAL_DEV_EPOCH_MODULE_ID;
|
|
1672
|
+
if (matchesVirtualId(id, DATABASES_ID)) return VIRTUAL_DATABASES_MODULE_ID;
|
|
1643
1673
|
return null;
|
|
1644
1674
|
},
|
|
1645
1675
|
async load(id) {
|
|
@@ -1658,6 +1688,10 @@ function durableDb(options = {}) {
|
|
|
1658
1688
|
}
|
|
1659
1689
|
return { code: generateDevEpochModule(epoch, databaseEpochs) };
|
|
1660
1690
|
}
|
|
1691
|
+
if (id === VIRTUAL_DATABASES_MODULE_ID) {
|
|
1692
|
+
await state.initialize();
|
|
1693
|
+
return { code: generateDatabasesModule(Array.from(state.databases.values())) };
|
|
1694
|
+
}
|
|
1661
1695
|
if (id !== VIRTUAL_DO_MODULE_ID) return null;
|
|
1662
1696
|
await state.initialize();
|
|
1663
1697
|
const isDev = state.config.command === "serve";
|
package/package.json
CHANGED
package/virtual.d.ts
CHANGED
|
@@ -13,5 +13,17 @@ declare module "virtual:durable-db/__devEpoch" {
|
|
|
13
13
|
export function applyDevEpoch(key: string, dbName?: string): string;
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
+
// The databases the plugin discovered, each with its tables (the schema
|
|
17
|
+
// module's own objects) — for a library that maps a table to its database.
|
|
18
|
+
declare module "virtual:durable-db/__databases" {
|
|
19
|
+
export const databases: ReadonlyArray<{
|
|
20
|
+
name: string;
|
|
21
|
+
bindingName: string;
|
|
22
|
+
className: string;
|
|
23
|
+
instance: 'per-tenant' | 'global';
|
|
24
|
+
schema: Record<string, unknown>;
|
|
25
|
+
}>;
|
|
26
|
+
}
|
|
27
|
+
|
|
16
28
|
/** @deprecated Use "virtual:durable-db/__durableObjects" instead. */
|
|
17
29
|
declare module "virtual:eagerpatch/durable-db/__durableObjects";
|