on-zero 0.6.13 → 0.6.15

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 (93) hide show
  1. package/dist/cjs/createSchemaFromDrizzle.cjs +4 -4
  2. package/dist/cjs/createSchemaFromDrizzle.native.js +4 -4
  3. package/dist/cjs/createSchemaFromDrizzle.native.js.map +1 -1
  4. package/dist/cjs/createZeroDirectServer.cjs +279 -0
  5. package/dist/cjs/createZeroDirectServer.native.js +292 -0
  6. package/dist/cjs/createZeroDirectServer.native.js.map +1 -0
  7. package/dist/cjs/createZeroSQLiteServer.cjs +8 -277
  8. package/dist/cjs/createZeroSQLiteServer.native.js +8 -390
  9. package/dist/cjs/createZeroSQLiteServer.native.js.map +1 -1
  10. package/dist/cjs/createZeroSQLiteServer.test.cjs +30 -3
  11. package/dist/cjs/createZeroSQLiteServer.test.native.js +31 -3
  12. package/dist/cjs/createZeroSQLiteServer.test.native.js.map +1 -1
  13. package/dist/cjs/createZeroServerCore.cjs +20 -205
  14. package/dist/cjs/createZeroServerCore.native.js +19 -213
  15. package/dist/cjs/createZeroServerCore.native.js.map +1 -1
  16. package/dist/cjs/generate.cjs +10 -3
  17. package/dist/cjs/generate.native.js +10 -3
  18. package/dist/cjs/generate.native.js.map +1 -1
  19. package/dist/cjs/generate.test.cjs +39 -0
  20. package/dist/cjs/generate.test.native.js +39 -0
  21. package/dist/cjs/generate.test.native.js.map +1 -1
  22. package/dist/cjs/sqliteRuntime.cjs +318 -0
  23. package/dist/cjs/sqliteRuntime.native.js +438 -0
  24. package/dist/cjs/sqliteRuntime.native.js.map +1 -0
  25. package/dist/cjs/syncHost.cjs +16 -9
  26. package/dist/cjs/syncHost.native.js +21 -12
  27. package/dist/cjs/syncHost.native.js.map +1 -1
  28. package/dist/cjs/syncHost.test.cjs +13 -2
  29. package/dist/cjs/syncHost.test.native.js +14 -2
  30. package/dist/cjs/syncHost.test.native.js.map +1 -1
  31. package/dist/esm/createSchemaFromDrizzle.mjs +2 -2
  32. package/dist/esm/createSchemaFromDrizzle.native.js +2 -2
  33. package/dist/esm/createZeroDirectServer.mjs +251 -0
  34. package/dist/esm/createZeroDirectServer.mjs.map +1 -0
  35. package/dist/esm/createZeroDirectServer.native.js +261 -0
  36. package/dist/esm/createZeroDirectServer.native.js.map +1 -0
  37. package/dist/esm/createZeroSQLiteServer.mjs +3 -272
  38. package/dist/esm/createZeroSQLiteServer.mjs.map +1 -1
  39. package/dist/esm/createZeroSQLiteServer.native.js +3 -385
  40. package/dist/esm/createZeroSQLiteServer.native.js.map +1 -1
  41. package/dist/esm/createZeroSQLiteServer.test.mjs +30 -3
  42. package/dist/esm/createZeroSQLiteServer.test.mjs.map +1 -1
  43. package/dist/esm/createZeroSQLiteServer.test.native.js +31 -3
  44. package/dist/esm/createZeroSQLiteServer.test.native.js.map +1 -1
  45. package/dist/esm/createZeroServerCore.mjs +18 -202
  46. package/dist/esm/createZeroServerCore.mjs.map +1 -1
  47. package/dist/esm/createZeroServerCore.native.js +18 -211
  48. package/dist/esm/createZeroServerCore.native.js.map +1 -1
  49. package/dist/esm/generate.mjs +10 -3
  50. package/dist/esm/generate.mjs.map +1 -1
  51. package/dist/esm/generate.native.js +10 -3
  52. package/dist/esm/generate.native.js.map +1 -1
  53. package/dist/esm/generate.test.mjs +39 -1
  54. package/dist/esm/generate.test.mjs.map +1 -1
  55. package/dist/esm/generate.test.native.js +39 -1
  56. package/dist/esm/generate.test.native.js.map +1 -1
  57. package/dist/esm/sqliteRuntime.mjs +289 -0
  58. package/dist/esm/sqliteRuntime.mjs.map +1 -0
  59. package/dist/esm/sqliteRuntime.native.js +406 -0
  60. package/dist/esm/sqliteRuntime.native.js.map +1 -0
  61. package/dist/esm/syncHost.mjs +14 -7
  62. package/dist/esm/syncHost.mjs.map +1 -1
  63. package/dist/esm/syncHost.native.js +19 -10
  64. package/dist/esm/syncHost.native.js.map +1 -1
  65. package/dist/esm/syncHost.test.mjs +13 -2
  66. package/dist/esm/syncHost.test.mjs.map +1 -1
  67. package/dist/esm/syncHost.test.native.js +14 -2
  68. package/dist/esm/syncHost.test.native.js.map +1 -1
  69. package/package.json +5 -6
  70. package/src/createSchemaFromDrizzle.ts +2 -2
  71. package/src/createZeroDirectServer.ts +427 -0
  72. package/src/createZeroSQLiteServer.test.ts +20 -5
  73. package/src/createZeroSQLiteServer.ts +14 -481
  74. package/src/createZeroServerCore.ts +32 -337
  75. package/src/generate.test.ts +57 -1
  76. package/src/generate.ts +23 -3
  77. package/src/sqliteRuntime.ts +512 -0
  78. package/src/syncHost.test.ts +10 -3
  79. package/src/syncHost.ts +49 -12
  80. package/test-fixtures/server-return-types.ts +8 -1
  81. package/types/createSchemaFromDrizzle.d.ts +2 -2
  82. package/types/createSchemaFromDrizzle.d.ts.map +1 -1
  83. package/types/createZeroDirectServer.d.ts +80 -0
  84. package/types/createZeroDirectServer.d.ts.map +1 -0
  85. package/types/createZeroSQLiteServer.d.ts +5 -30
  86. package/types/createZeroSQLiteServer.d.ts.map +1 -1
  87. package/types/createZeroServerCore.d.ts +30 -87
  88. package/types/createZeroServerCore.d.ts.map +1 -1
  89. package/types/generate.d.ts.map +1 -1
  90. package/types/sqliteRuntime.d.ts +71 -0
  91. package/types/sqliteRuntime.d.ts.map +1 -0
  92. package/types/syncHost.d.ts +10 -19
  93. package/types/syncHost.d.ts.map +1 -1
@@ -0,0 +1,318 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all) __defProp(target, name, {
7
+ get: all[name],
8
+ enumerable: true
9
+ });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
14
+ get: () => from[key],
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ return to;
19
+ };
20
+ var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
21
+ value: true
22
+ }), mod);
23
+ var sqliteRuntime_exports = {};
24
+ __export(sqliteRuntime_exports, {
25
+ createSQLiteDatabase: () => createSQLiteDatabase,
26
+ createZeroSQLiteTransaction: () => createZeroSQLiteTransaction,
27
+ defaultLedgerTables: () => defaultLedgerTables,
28
+ encodeSQLiteValue: () => encodeSQLiteValue,
29
+ persistAlreadyProcessedMutationResults: () => persistAlreadyProcessedMutationResults
30
+ });
31
+ module.exports = __toCommonJS(sqliteRuntime_exports);
32
+ var import_zero = require("@rocicorp/zero");
33
+ var import_bindings = require("@rocicorp/zero/bindings");
34
+ function createSQLiteDatabase(options) {
35
+ return {
36
+ async transaction(callback, input) {
37
+ let committedLedgers = /* @__PURE__ */new Set();
38
+ const value = await options.transactionProvider(async executor => {
39
+ const attemptLedgers = /* @__PURE__ */new Set();
40
+ const ensureLedger = async upstreamSchema => {
41
+ const tables = options.ledgerTables(upstreamSchema);
42
+ const key = ledgerKey(tables);
43
+ if (options.initializedLedgers.has(key) || attemptLedgers.has(key)) {
44
+ return;
45
+ }
46
+ await createLedgerTables(executor, tables);
47
+ attemptLedgers.add(key);
48
+ };
49
+ const transaction = createZeroSQLiteTransaction(options, executor, input);
50
+ const result = await callback(transaction, createLedgerHooks(options, executor, ensureLedger, input));
51
+ committedLedgers = attemptLedgers;
52
+ return result;
53
+ });
54
+ for (const key of committedLedgers) options.initializedLedgers.add(key);
55
+ return value;
56
+ }
57
+ };
58
+ }
59
+ function createZeroSQLiteTransaction(options, executor, input) {
60
+ const transactionOptions = {
61
+ encodeValue: options.encodeValue ?? encodeSQLiteValue,
62
+ schema: options.schema
63
+ };
64
+ const clientID = input?.clientID ?? "";
65
+ const mutationID = input?.mutationID ?? 0;
66
+ const mutate = new Proxy({}, {
67
+ get(_target, tableKey) {
68
+ const tableName = String(tableKey);
69
+ if (!options.schema.tables[tableName]) {
70
+ throw new Error(`unknown SQLite mutation table ${tableName}`);
71
+ }
72
+ return new Proxy({}, {
73
+ get(_innerTarget, kindKey) {
74
+ const kind = String(kindKey);
75
+ if (!isCrudKind(kind)) return;
76
+ return value => executeCrud(transactionOptions, executor, tableName, kind, value);
77
+ }
78
+ });
79
+ }
80
+ });
81
+ const runQuery = (ast, format, queryName) => Promise.resolve(executor.queryAst(ast, format, queryName));
82
+ const dbTransaction = {
83
+ wrappedTransaction: executor,
84
+ query: (sql, args) => executor.query(sql, args),
85
+ runQuery
86
+ };
87
+ return {
88
+ clientID,
89
+ dbTransaction,
90
+ location: "server",
91
+ mutate,
92
+ mutationID,
93
+ query: transactionOptions.schema.enableLegacyQueries ? createLegacyQueryBuilder(transactionOptions.schema, query => {
94
+ const internals = (0, import_bindings.asQueryInternals)(query);
95
+ return runQuery(internals.ast, internals.format, internals.customQueryID?.name);
96
+ }) : void 0,
97
+ reason: "authoritative",
98
+ async run(query) {
99
+ const internals = (0, import_bindings.asQueryInternals)(query);
100
+ return runQuery(internals.ast, internals.format, internals.customQueryID?.name);
101
+ }
102
+ };
103
+ }
104
+ function isCrudKind(value) {
105
+ return value === "delete" || value === "insert" || value === "update" || value === "upsert";
106
+ }
107
+ async function executeCrud(options, executor, tableName, kind, raw) {
108
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
109
+ throw new Error(`${tableName}.${kind} expects an object`);
110
+ }
111
+ const table = options.schema.tables[tableName];
112
+ const values = Object.fromEntries(Object.entries(raw).filter(([, value]) => value !== void 0));
113
+ for (const columnName of Object.keys(values)) {
114
+ if (!table.columns[columnName]) {
115
+ throw new Error(`unknown SQLite column ${tableName}.${columnName}`);
116
+ }
117
+ }
118
+ const primaryValues = table.primaryKey.map(columnName => {
119
+ if (!(columnName in values)) {
120
+ throw new Error(`${tableName}.${kind} is missing primary key ${columnName}`);
121
+ }
122
+ return encodeColumn(options, tableName, columnName, values[columnName]);
123
+ });
124
+ const primaryWhere = table.primaryKey.map(columnName => `${quoteSQLiteIdentifier(serverColumn(table, columnName))} = ?`).join(" AND ");
125
+ const serverTableName = quoteSQLiteIdentifier(table.serverName ?? table.name);
126
+ if (kind === "delete") {
127
+ await executor.exec(`DELETE FROM ${serverTableName} WHERE ${primaryWhere}`, primaryValues, {
128
+ table: table.serverName ?? table.name,
129
+ publicTable: tableName,
130
+ kind
131
+ });
132
+ return;
133
+ }
134
+ const columnNames = Object.keys(values);
135
+ if (columnNames.length === 0) {
136
+ throw new Error(`${tableName}.${kind} has no values`);
137
+ }
138
+ const serverColumns = columnNames.map(columnName => quoteSQLiteIdentifier(serverColumn(table, columnName)));
139
+ const params = columnNames.map(columnName => encodeColumn(options, tableName, columnName, values[columnName]));
140
+ const insert = `INSERT INTO ${serverTableName} (${serverColumns.join(", ")}) VALUES (${columnNames.map(() => "?").join(", ")})`;
141
+ if (kind === "insert") {
142
+ await executor.exec(insert, params, {
143
+ table: table.serverName ?? table.name,
144
+ publicTable: tableName,
145
+ kind
146
+ });
147
+ return;
148
+ }
149
+ if (kind === "upsert") {
150
+ const mutableColumns2 = columnNames.filter(columnName => !table.primaryKey.includes(columnName));
151
+ const conflictColumns = table.primaryKey.map(columnName => quoteSQLiteIdentifier(serverColumn(table, columnName))).join(", ");
152
+ const conflictAction = mutableColumns2.length === 0 ? "DO NOTHING" : `DO UPDATE SET ${mutableColumns2.map(columnName => {
153
+ const column = quoteSQLiteIdentifier(serverColumn(table, columnName));
154
+ return `${column} = excluded.${column}`;
155
+ }).join(", ")}`;
156
+ await executor.exec(`${insert} ON CONFLICT (${conflictColumns}) ${conflictAction}`, params, {
157
+ table: table.serverName ?? table.name,
158
+ publicTable: tableName,
159
+ kind
160
+ });
161
+ return;
162
+ }
163
+ const mutableColumns = columnNames.filter(columnName => !table.primaryKey.includes(columnName));
164
+ if (mutableColumns.length === 0) return;
165
+ await executor.exec(`UPDATE ${serverTableName} SET ${mutableColumns.map(columnName => `${quoteSQLiteIdentifier(serverColumn(table, columnName))} = ?`).join(", ")} WHERE ${primaryWhere}`, [...mutableColumns.map(columnName => encodeColumn(options, tableName, columnName, values[columnName])), ...primaryValues], {
166
+ table: table.serverName ?? table.name,
167
+ publicTable: tableName,
168
+ kind
169
+ });
170
+ }
171
+ function serverColumn(table, columnName) {
172
+ const column = table.columns[columnName];
173
+ if (!column) throw new Error(`unknown SQLite column ${table.name}.${columnName}`);
174
+ return column.serverName ?? columnName;
175
+ }
176
+ function encodeColumn(options, tableName, columnName, value) {
177
+ return options.encodeValue(value, {
178
+ column: options.schema.tables[tableName].columns[columnName],
179
+ columnName,
180
+ tableName
181
+ });
182
+ }
183
+ function createLegacyQueryBuilder(schema, run) {
184
+ const builder = (0, import_zero.createBuilder)(schema);
185
+ return new Proxy(builder, {
186
+ get(target, property) {
187
+ return makeRunnableQuery(Reflect.get(target, property, target), run);
188
+ }
189
+ });
190
+ }
191
+ function makeRunnableQuery(query, run) {
192
+ if (!isQueryBuilder(query)) return query;
193
+ return new Proxy(query, {
194
+ get(target, property) {
195
+ if (property === "run") return () => run(target);
196
+ if (property === "materialize" || property === "preload") {
197
+ return () => {
198
+ throw new Error(`${String(property)}() is not supported in server transactions`);
199
+ };
200
+ }
201
+ const value = Reflect.get(target, property, target);
202
+ if (typeof value !== "function") return value;
203
+ return (...args) => makeRunnableQuery(Reflect.apply(value, target, args), run);
204
+ }
205
+ });
206
+ }
207
+ function isQueryBuilder(value) {
208
+ if (!value || typeof value !== "object") return false;
209
+ try {
210
+ (0, import_bindings.asQueryInternals)(value);
211
+ return true;
212
+ } catch {
213
+ return false;
214
+ }
215
+ }
216
+ function createLedgerHooks(options, executor, ensureLedger, input) {
217
+ const upstreamSchema = input?.upstreamSchema ?? "";
218
+ const clientGroupID = input?.clientGroupID ?? "";
219
+ const clientID = input?.clientID ?? "";
220
+ const tables = options.ledgerTables(upstreamSchema);
221
+ const clientsTable = quoteSQLiteIdentifier(tables.clients);
222
+ const mutationsTable = quoteSQLiteIdentifier(tables.mutations);
223
+ return {
224
+ async updateClientMutationID() {
225
+ await ensureLedger(upstreamSchema);
226
+ const rows = await executor.query(`INSERT INTO ${clientsTable}
227
+ (clientGroupID, clientID, lastMutationID)
228
+ VALUES (?, ?, 1)
229
+ ON CONFLICT (clientGroupID, clientID)
230
+ DO UPDATE SET lastMutationID = lastMutationID + 1
231
+ RETURNING lastMutationID`, [clientGroupID, clientID]);
232
+ const lastMutationID = rows[0]?.lastMutationID;
233
+ if (typeof lastMutationID !== "number" && typeof lastMutationID !== "bigint") {
234
+ throw new Error("SQLite mutation ledger returned no lastMutationID");
235
+ }
236
+ return {
237
+ lastMutationID
238
+ };
239
+ },
240
+ async writeMutationResult(result) {
241
+ await ensureLedger(upstreamSchema);
242
+ await executor.exec(`INSERT INTO ${mutationsTable}
243
+ (clientGroupID, clientID, mutationID, result)
244
+ VALUES (?, ?, ?, ?)`, [clientGroupID, result.id.clientID, result.id.id, JSON.stringify(result.result)]);
245
+ },
246
+ async deleteMutationResults(args) {
247
+ await ensureLedger(upstreamSchema);
248
+ if ("type" in args && args.type === "bulk") {
249
+ if (args.clientIDs.length === 0) return;
250
+ await executor.exec(`DELETE FROM ${mutationsTable}
251
+ WHERE clientGroupID = ?
252
+ AND clientID IN (${args.clientIDs.map(() => "?").join(", ")})`, [args.clientGroupID, ...args.clientIDs]);
253
+ return;
254
+ }
255
+ await executor.exec(`DELETE FROM ${mutationsTable}
256
+ WHERE clientGroupID = ?
257
+ AND clientID = ?
258
+ AND mutationID <= ?`, [args.clientGroupID, args.clientID, args.upToMutationID]);
259
+ }
260
+ };
261
+ }
262
+ async function persistAlreadyProcessedMutationResults(options, {
263
+ clientGroupID,
264
+ mutations,
265
+ upstreamSchema
266
+ }) {
267
+ const tables = options.ledgerTables(upstreamSchema);
268
+ const table = quoteSQLiteIdentifier(tables.mutations);
269
+ const key = ledgerKey(tables);
270
+ await options.transactionProvider(async executor => {
271
+ if (!options.initializedLedgers.has(key)) {
272
+ await createLedgerTables(executor, tables);
273
+ }
274
+ for (const mutation of mutations) {
275
+ await executor.exec(`INSERT INTO ${table}
276
+ (clientGroupID, clientID, mutationID, result)
277
+ VALUES (?, ?, ?, ?)
278
+ ON CONFLICT (clientGroupID, clientID, mutationID) DO NOTHING`, [clientGroupID, mutation.id.clientID, mutation.id.id, JSON.stringify(mutation.result)]);
279
+ }
280
+ });
281
+ options.initializedLedgers.add(key);
282
+ }
283
+ async function createLedgerTables(executor, tables) {
284
+ await executor.exec(`CREATE TABLE IF NOT EXISTS ${quoteSQLiteIdentifier(tables.clients)} (
285
+ clientGroupID TEXT NOT NULL,
286
+ clientID TEXT NOT NULL,
287
+ lastMutationID INTEGER NOT NULL,
288
+ PRIMARY KEY (clientGroupID, clientID)
289
+ )`);
290
+ await executor.exec(`CREATE TABLE IF NOT EXISTS ${quoteSQLiteIdentifier(tables.mutations)} (
291
+ clientGroupID TEXT NOT NULL,
292
+ clientID TEXT NOT NULL,
293
+ mutationID INTEGER NOT NULL,
294
+ result TEXT NOT NULL,
295
+ PRIMARY KEY (clientGroupID, clientID, mutationID)
296
+ )`);
297
+ }
298
+ function ledgerKey(tables) {
299
+ return `${tables.clients}\0${tables.mutations}`;
300
+ }
301
+ function defaultLedgerTables(upstreamSchema) {
302
+ const prefix = upstreamSchema ? `${upstreamSchema}_` : "";
303
+ return {
304
+ clients: `${prefix}clients`,
305
+ mutations: `${prefix}mutations`
306
+ };
307
+ }
308
+ function encodeSQLiteValue(value, {
309
+ column
310
+ }) {
311
+ if (value === null) return null;
312
+ if (column.type === "boolean") return value ? 1 : 0;
313
+ if (column.type === "json") return JSON.stringify(value);
314
+ return value;
315
+ }
316
+ function quoteSQLiteIdentifier(value) {
317
+ return `"${value.replaceAll('"', '""')}"`;
318
+ }