silosdk 0.0.6 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/store.mjs ADDED
@@ -0,0 +1,429 @@
1
+ import { randomUUID } from "expo-crypto";
2
+ import { openDatabaseSync } from "expo-sqlite";
3
+
4
+ //#region src/store/index.ts
5
+ const sourceNames = /* @__PURE__ */ new Set();
6
+ const sourceNamePattern = /^[A-Za-z][A-Za-z0-9_-]*$/;
7
+ const reservedDocumentFields = new Set([
8
+ "id",
9
+ "data",
10
+ "set"
11
+ ]);
12
+ const deletedDocs = /* @__PURE__ */ new WeakSet();
13
+ function createID() {
14
+ return randomUUID();
15
+ }
16
+ function createStore(defaults) {
17
+ const names = Object.keys(defaults);
18
+ const nameSet = new Set(names);
19
+ for (const name of names) {
20
+ assertSourceName(name);
21
+ assertFlatDefaults(name, defaults[name]);
22
+ }
23
+ if (new Set(names).size !== names.length) throw new Error("Store collection names must be unique.");
24
+ return {
25
+ names,
26
+ collectionOptions(name, options = {}) {
27
+ assertStoreCollectionName(nameSet, name);
28
+ return createSourceCollectionOptions(name, defaults[name], options);
29
+ },
30
+ linkCollectionOptions(options = {}) {
31
+ return createLinkCollectionOptions(names, nameSet, options);
32
+ }
33
+ };
34
+ }
35
+ function source(name, defaults) {
36
+ assertSourceName(name);
37
+ assertFlatDefaults(name, defaults);
38
+ if (sourceNames.has(name)) throw new Error(`Source "${name}" is already registered. Define each source once and import the existing source instead.`);
39
+ sourceNames.add(name);
40
+ return {
41
+ name,
42
+ defaults,
43
+ schema: createSourceSchema(name, defaults),
44
+ collectionOptions(options = {}) {
45
+ return createSourceCollectionOptions(name, defaults, options);
46
+ }
47
+ };
48
+ }
49
+ function createSourceCollectionOptions(name, defaults, options = {}) {
50
+ return {
51
+ id: name,
52
+ getKey: (item) => item.id,
53
+ schema: createSourceSchema(name, defaults),
54
+ startSync: options.startSync,
55
+ sync: { sync({ begin, write, commit, markReady, truncate }) {
56
+ const rows = loadRows(name);
57
+ begin();
58
+ truncate();
59
+ for (const row of rows) write({
60
+ type: "insert",
61
+ value: row
62
+ });
63
+ commit();
64
+ markReady();
65
+ } },
66
+ onInsert: async ({ transaction }) => {
67
+ await insertRows(name, transaction.mutations.map((mutation) => mutation.modified));
68
+ },
69
+ onUpdate: async ({ transaction }) => {
70
+ await updateRows(name, transaction.mutations);
71
+ },
72
+ onDelete: async ({ transaction }) => {
73
+ await deleteRows(name, transaction.mutations);
74
+ }
75
+ };
76
+ }
77
+ function createLinkCollectionOptions(names, nameSet, options = {}) {
78
+ const schema = createLinkSchema();
79
+ let syncBegin;
80
+ let syncWrite;
81
+ let syncCommit;
82
+ const writeSyncedLink = (type, row) => {
83
+ if (!syncBegin || !syncWrite || !syncCommit) return;
84
+ syncBegin();
85
+ syncWrite({
86
+ type,
87
+ value: row
88
+ });
89
+ syncCommit();
90
+ };
91
+ return {
92
+ id: "silo-links",
93
+ getKey: (item) => item.id,
94
+ schema,
95
+ startSync: options.startSync,
96
+ sync: { sync({ begin, write, commit, markReady, truncate }) {
97
+ syncBegin = begin;
98
+ syncWrite = write;
99
+ syncCommit = commit;
100
+ const rows = loadLinkRows().map((row) => createLinkRow(names, row));
101
+ begin();
102
+ truncate();
103
+ for (const row of rows) write({
104
+ type: "insert",
105
+ value: row
106
+ });
107
+ commit();
108
+ markReady();
109
+ } },
110
+ onInsert: async ({ transaction }) => {
111
+ for (const mutation of transaction.mutations) insertLinkRow(extractStoredLinkRow(mutation.modified));
112
+ },
113
+ onDelete: async ({ transaction }) => {
114
+ for (const mutation of transaction.mutations) deleteLinkRow(String(mutation.key));
115
+ },
116
+ utils: {
117
+ async link(collectionA, idA, collectionB, idB) {
118
+ const row = createStoredLinkRow(nameSet, collectionA, idA, collectionB, idB);
119
+ const exists = hasLinkRow(row.id);
120
+ insertLinkRow(row);
121
+ if (!exists) writeSyncedLink("insert", createLinkRow(names, row));
122
+ },
123
+ async unlink(collectionA, idA, collectionB, idB) {
124
+ const row = createStoredLinkRow(nameSet, collectionA, idA, collectionB, idB);
125
+ const exists = hasLinkRow(row.id);
126
+ deleteLinkRow(row.id);
127
+ if (exists) writeSyncedLink("delete", createLinkRow(names, row));
128
+ },
129
+ has(collectionA, idA, collectionB, idB) {
130
+ return hasLinkRow(createStoredLinkRow(nameSet, collectionA, idA, collectionB, idB).id);
131
+ }
132
+ }
133
+ };
134
+ }
135
+ function assertSourceName(name) {
136
+ if (!sourceNamePattern.test(name)) throw new Error(`Source names must start with a letter and contain only letters, numbers, underscores, or hyphens. Received "${name}".`);
137
+ }
138
+ function assertStoreCollectionName(nameSet, name) {
139
+ if (!nameSet.has(name)) throw new Error(`Store collection "${name}" is not registered.`);
140
+ }
141
+ function assertLinkCollectionName(nameSet, name) {
142
+ if (!nameSet.has(name)) throw new Error(`Cannot link unknown collection "${name}".`);
143
+ }
144
+ function createStoredLinkRow(nameSet, collectionA, idA, collectionB, idB) {
145
+ assertLinkCollectionName(nameSet, collectionA);
146
+ assertLinkCollectionName(nameSet, collectionB);
147
+ if (collectionA === collectionB) throw new Error(`Links between the same collection are not supported. Received "${collectionA}".`);
148
+ const [firstCollection, firstId, secondCollection, secondId] = collectionA < collectionB ? [
149
+ collectionA,
150
+ idA,
151
+ collectionB,
152
+ idB
153
+ ] : [
154
+ collectionB,
155
+ idB,
156
+ collectionA,
157
+ idA
158
+ ];
159
+ const collections = encodePair(firstCollection, secondCollection);
160
+ const ids = encodePair(firstId, secondId);
161
+ return {
162
+ id: encodePair(collections, ids),
163
+ collections,
164
+ ids,
165
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
166
+ };
167
+ }
168
+ function createLinkRow(names, row) {
169
+ const [firstCollection, secondCollection] = decodePair(row.collections);
170
+ const [firstId, secondId] = decodePair(row.ids);
171
+ const result = {
172
+ id: row.id,
173
+ collections: row.collections,
174
+ ids: row.ids,
175
+ createdAt: row.createdAt
176
+ };
177
+ for (const other of names) {
178
+ const byCurrent = {};
179
+ for (const current of names) {
180
+ let id = null;
181
+ if (other !== current) {
182
+ if (current === firstCollection && other === secondCollection) id = firstId;
183
+ else if (current === secondCollection && other === firstCollection) id = secondId;
184
+ }
185
+ byCurrent[current] = { id };
186
+ }
187
+ result[other] = byCurrent;
188
+ }
189
+ return result;
190
+ }
191
+ function extractStoredLinkRow(row) {
192
+ if (!isRecord(row)) throw new Error("Expected a link row object.");
193
+ if (typeof row.id !== "string" || typeof row.collections !== "string" || typeof row.ids !== "string" || typeof row.createdAt !== "string") throw new Error("Link rows must include string id, collections, ids, and createdAt fields.");
194
+ return {
195
+ id: row.id,
196
+ collections: row.collections,
197
+ ids: row.ids,
198
+ createdAt: row.createdAt
199
+ };
200
+ }
201
+ function encodePair(first, second) {
202
+ return `${encodePart(first)}:${encodePart(second)}`;
203
+ }
204
+ function decodePair(value) {
205
+ const parts = value.split(":");
206
+ if (parts.length !== 2) throw new Error(`Invalid encoded link pair "${value}".`);
207
+ return [decodePart(parts[0]), decodePart(parts[1])];
208
+ }
209
+ function encodePart(value) {
210
+ return encodeURIComponent(value);
211
+ }
212
+ function decodePart(value) {
213
+ return decodeURIComponent(value);
214
+ }
215
+ function assertFlatDefaults(sourceName, defaults) {
216
+ for (const [field, defaultValue] of Object.entries(defaults)) {
217
+ if (reservedDocumentFields.has(field)) throw new Error(`Source "${sourceName}" field "${field}" is reserved by Silo documents.`);
218
+ if (!isFieldValue(resolveDefault(defaultValue))) throw new Error(`Source "${sourceName}" field "${field}" must default to a string, number, boolean, null, or a function returning one of those values.`);
219
+ }
220
+ }
221
+ function createSourceSchema(sourceName, defaults) {
222
+ return { "~standard": {
223
+ version: 1,
224
+ vendor: "silo",
225
+ validate(value) {
226
+ if (!isRecord(value)) return failure("Expected a flat source row object.");
227
+ if (typeof value.id !== "string") return failure("Expected source document field \"id\" to be a string.", ["id"]);
228
+ const inputData = isRecord(value.data) ? value.data : extractDocumentData(value);
229
+ const data = {};
230
+ for (const [field, fieldValue] of Object.entries(inputData)) {
231
+ if (reservedDocumentFields.has(field)) return failure(`Source "${sourceName}" field "${field}" is reserved by Silo documents.`, ["data", field]);
232
+ if (!isFieldValue(fieldValue)) return failure(`Source "${sourceName}" field "${field}" must be a string, number, boolean, or null.`, ["data", field]);
233
+ data[field] = fieldValue;
234
+ }
235
+ for (const [field, defaultValue] of Object.entries(defaults)) {
236
+ if (field in data) continue;
237
+ data[field] = resolveDefault(defaultValue);
238
+ }
239
+ return { value: createDoc(value.id, data) };
240
+ }
241
+ } };
242
+ }
243
+ function createLinkSchema() {
244
+ return { "~standard": {
245
+ version: 1,
246
+ vendor: "silo",
247
+ validate(value) {
248
+ try {
249
+ extractStoredLinkRow(value);
250
+ return { value };
251
+ } catch (error) {
252
+ return failure(error instanceof Error ? error.message : "Expected a link row.");
253
+ }
254
+ }
255
+ } };
256
+ }
257
+ function createDoc(id, data) {
258
+ const doc = {};
259
+ Object.defineProperty(doc, "id", {
260
+ value: id,
261
+ enumerable: true,
262
+ writable: false,
263
+ configurable: false
264
+ });
265
+ for (const [field, value] of Object.entries(data)) Object.defineProperty(doc, field, {
266
+ value,
267
+ enumerable: true,
268
+ writable: true,
269
+ configurable: true
270
+ });
271
+ Object.defineProperty(doc, "data", {
272
+ value() {
273
+ return deletedDocs.has(this) ? null : extractDocumentData(this);
274
+ },
275
+ enumerable: true,
276
+ writable: false,
277
+ configurable: false
278
+ });
279
+ Object.defineProperty(doc, "set", {
280
+ get() {
281
+ return function setDocumentData(patch) {
282
+ Object.assign(this, patch);
283
+ };
284
+ },
285
+ enumerable: true,
286
+ configurable: false
287
+ });
288
+ return doc;
289
+ }
290
+ function extractDocumentData(value) {
291
+ if (!isRecord(value)) return {};
292
+ const data = {};
293
+ for (const [field, fieldValue] of Object.entries(value)) {
294
+ if (reservedDocumentFields.has(field) || field.startsWith("$") || typeof fieldValue === "function") continue;
295
+ if (isFieldValue(fieldValue)) data[field] = fieldValue;
296
+ }
297
+ return data;
298
+ }
299
+ function resolveDefault(value) {
300
+ const resolved = typeof value === "function" ? value() : value;
301
+ if (!isFieldValue(resolved)) throw new Error("Source defaults must resolve to a string, number, boolean, or null.");
302
+ return resolved;
303
+ }
304
+ function isRecord(value) {
305
+ return typeof value === "object" && value !== null && !Array.isArray(value);
306
+ }
307
+ function isFieldValue(value) {
308
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null;
309
+ }
310
+ function failure(message, path) {
311
+ return { issues: [{
312
+ message,
313
+ path
314
+ }] };
315
+ }
316
+ let database;
317
+ function getDatabase() {
318
+ if (!database) {
319
+ database = openDatabaseSync("silo.db");
320
+ database.execSync(`
321
+ PRAGMA journal_mode = WAL;
322
+
323
+ CREATE TABLE IF NOT EXISTS sources (
324
+ source TEXT NOT NULL,
325
+ id TEXT NOT NULL,
326
+ data TEXT NOT NULL,
327
+ createdAt TEXT NOT NULL,
328
+ updatedAt TEXT NOT NULL,
329
+ version INTEGER NOT NULL DEFAULT 1,
330
+ PRIMARY KEY (source, id)
331
+ );
332
+
333
+ CREATE TABLE IF NOT EXISTS links (
334
+ id TEXT PRIMARY KEY,
335
+ collections TEXT NOT NULL,
336
+ ids TEXT NOT NULL,
337
+ createdAt TEXT NOT NULL
338
+ );
339
+
340
+ CREATE UNIQUE INDEX IF NOT EXISTS links_collections_ids_idx
341
+ ON links(collections, ids);
342
+
343
+ CREATE INDEX IF NOT EXISTS links_collections_idx
344
+ ON links(collections);
345
+ `);
346
+ }
347
+ return database;
348
+ }
349
+ function loadRows(sourceName) {
350
+ return getDatabase().getAllSync(`SELECT id, data FROM sources WHERE source = ?`, [sourceName]).map((row) => createDoc(row.id, JSON.parse(row.data)));
351
+ }
352
+ function insertRows(sourceName, rows) {
353
+ const db = getDatabase();
354
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
355
+ db.withTransactionSync(() => {
356
+ for (const row of rows) {
357
+ const data = extractDocumentData(row);
358
+ db.runSync(`INSERT INTO sources (source, id, data, createdAt, updatedAt, version)
359
+ VALUES (?, ?, ?, ?, ?, 1)`, [
360
+ sourceName,
361
+ row.id,
362
+ JSON.stringify(data),
363
+ timestamp,
364
+ timestamp
365
+ ]);
366
+ }
367
+ });
368
+ return Promise.resolve();
369
+ }
370
+ function updateRows(sourceName, mutations) {
371
+ const db = getDatabase();
372
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
373
+ db.withTransactionSync(() => {
374
+ for (const mutation of mutations) {
375
+ const data = extractDocumentData(mutation.modified);
376
+ mutation.modified = createDoc(String(mutation.key), data);
377
+ db.runSync(`UPDATE sources
378
+ SET data = ?, updatedAt = ?, version = version + 1
379
+ WHERE source = ? AND id = ?`, [
380
+ JSON.stringify(data),
381
+ timestamp,
382
+ sourceName,
383
+ String(mutation.key)
384
+ ]);
385
+ }
386
+ });
387
+ return Promise.resolve();
388
+ }
389
+ function deleteRows(sourceName, mutations) {
390
+ const db = getDatabase();
391
+ db.withTransactionSync(() => {
392
+ for (const mutation of mutations) {
393
+ if (mutation.original) deletedDocs.add(mutation.original);
394
+ deletedDocs.add(mutation.modified);
395
+ db.runSync(`DELETE FROM sources WHERE source = ? AND id = ?`, [sourceName, String(mutation.key)]);
396
+ deleteLinksForSourceRow(sourceName, String(mutation.key));
397
+ }
398
+ });
399
+ return Promise.resolve();
400
+ }
401
+ function loadLinkRows() {
402
+ return getDatabase().getAllSync(`SELECT id, collections, ids, createdAt FROM links`);
403
+ }
404
+ function insertLinkRow(row) {
405
+ getDatabase().runSync(`INSERT OR IGNORE INTO links (id, collections, ids, createdAt)
406
+ VALUES (?, ?, ?, ?)`, [
407
+ row.id,
408
+ row.collections,
409
+ row.ids,
410
+ row.createdAt
411
+ ]);
412
+ }
413
+ function deleteLinkRow(id) {
414
+ getDatabase().runSync(`DELETE FROM links WHERE id = ?`, [id]);
415
+ }
416
+ function hasLinkRow(id) {
417
+ return !!getDatabase().getFirstSync(`SELECT id FROM links WHERE id = ?`, [id]);
418
+ }
419
+ function deleteLinksForSourceRow(sourceName, id) {
420
+ const rows = loadLinkRows();
421
+ for (const row of rows) {
422
+ const [firstCollection, secondCollection] = decodePair(row.collections);
423
+ const [firstId, secondId] = decodePair(row.ids);
424
+ if (firstCollection === sourceName && firstId === id || secondCollection === sourceName && secondId === id) deleteLinkRow(row.id);
425
+ }
426
+ }
427
+
428
+ //#endregion
429
+ export { createID, createStore, source };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "silosdk",
3
- "version": "0.0.6",
3
+ "version": "0.0.8",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "build": "tsdown",
@@ -45,14 +45,14 @@
45
45
  "printWidth": 80,
46
46
  "tabWidth": 2
47
47
  },
48
- "main": "./dist/source.cjs",
49
- "module": "./dist/source.mjs",
50
- "types": "./dist/source.d.cts",
48
+ "main": "./dist/store.cjs",
49
+ "module": "./dist/store.mjs",
50
+ "types": "./dist/store.d.cts",
51
51
  "exports": {
52
- "./source": {
53
- "types": "./dist/source.d.mts",
54
- "import": "./dist/source.mjs",
55
- "require": "./dist/source.cjs"
52
+ "./store": {
53
+ "types": "./dist/store.d.mts",
54
+ "import": "./dist/store.mjs",
55
+ "require": "./dist/store.cjs"
56
56
  },
57
57
  "./settings": {
58
58
  "types": "./dist/settings.d.mts",
package/dist/source.cjs DELETED
@@ -1,221 +0,0 @@
1
- const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
- let expo_crypto = require("expo-crypto");
3
- let expo_sqlite = require("expo-sqlite");
4
-
5
- //#region src/source/index.ts
6
- const sourceNames = /* @__PURE__ */ new Set();
7
- const sourceNamePattern = /^[A-Za-z][A-Za-z0-9_-]*$/;
8
- const reservedDocumentFields = new Set([
9
- "id",
10
- "data",
11
- "set"
12
- ]);
13
- const deletedDocs = /* @__PURE__ */ new WeakSet();
14
- function createID() {
15
- return (0, expo_crypto.randomUUID)();
16
- }
17
- function source(name, defaults) {
18
- assertSourceName(name);
19
- assertFlatDefaults(name, defaults);
20
- if (sourceNames.has(name)) throw new Error(`Source "${name}" is already registered. Define each source once and import the existing source instead.`);
21
- sourceNames.add(name);
22
- const schema = createSourceSchema(name, defaults);
23
- return {
24
- name,
25
- defaults,
26
- schema,
27
- collectionOptions(options = {}) {
28
- return {
29
- id: name,
30
- getKey: (item) => item.id,
31
- schema,
32
- startSync: options.startSync,
33
- sync: { sync({ begin, write, commit, markReady, truncate }) {
34
- const rows = loadRows(name);
35
- begin();
36
- truncate();
37
- for (const row of rows) write({
38
- type: "insert",
39
- value: row
40
- });
41
- commit();
42
- markReady();
43
- } },
44
- onInsert: async ({ transaction }) => {
45
- await insertRows(name, transaction.mutations.map((mutation) => mutation.modified));
46
- },
47
- onUpdate: async ({ transaction }) => {
48
- await updateRows(name, transaction.mutations);
49
- },
50
- onDelete: async ({ transaction }) => {
51
- await deleteRows(name, transaction.mutations);
52
- }
53
- };
54
- }
55
- };
56
- }
57
- function assertSourceName(name) {
58
- if (!sourceNamePattern.test(name)) throw new Error(`Source names must start with a letter and contain only letters, numbers, underscores, or hyphens. Received "${name}".`);
59
- }
60
- function assertFlatDefaults(sourceName, defaults) {
61
- for (const [field, defaultValue] of Object.entries(defaults)) {
62
- if (reservedDocumentFields.has(field)) throw new Error(`Source "${sourceName}" field "${field}" is reserved by Silo documents.`);
63
- if (!isFieldValue(resolveDefault(defaultValue))) throw new Error(`Source "${sourceName}" field "${field}" must default to a string, number, boolean, null, or a function returning one of those values.`);
64
- }
65
- }
66
- function createSourceSchema(sourceName, defaults) {
67
- return { "~standard": {
68
- version: 1,
69
- vendor: "silo",
70
- validate(value) {
71
- if (!isRecord(value)) return failure("Expected a flat source row object.");
72
- if (typeof value.id !== "string") return failure("Expected source document field \"id\" to be a string.", ["id"]);
73
- const inputData = isRecord(value.data) ? value.data : extractDocumentData(value);
74
- const data = {};
75
- for (const [field, fieldValue] of Object.entries(inputData)) {
76
- if (reservedDocumentFields.has(field)) return failure(`Source "${sourceName}" field "${field}" is reserved by Silo documents.`, ["data", field]);
77
- if (!isFieldValue(fieldValue)) return failure(`Source "${sourceName}" field "${field}" must be a string, number, boolean, or null.`, ["data", field]);
78
- data[field] = fieldValue;
79
- }
80
- for (const [field, defaultValue] of Object.entries(defaults)) {
81
- if (field in data) continue;
82
- data[field] = resolveDefault(defaultValue);
83
- }
84
- return { value: createDoc(value.id, data) };
85
- }
86
- } };
87
- }
88
- function createDoc(id, data) {
89
- const doc = {};
90
- Object.defineProperty(doc, "id", {
91
- value: id,
92
- enumerable: true,
93
- writable: false,
94
- configurable: false
95
- });
96
- for (const [field, value] of Object.entries(data)) Object.defineProperty(doc, field, {
97
- value,
98
- enumerable: true,
99
- writable: true,
100
- configurable: true
101
- });
102
- Object.defineProperty(doc, "data", {
103
- value() {
104
- return deletedDocs.has(this) ? null : extractDocumentData(this);
105
- },
106
- enumerable: true,
107
- writable: false,
108
- configurable: false
109
- });
110
- Object.defineProperty(doc, "set", {
111
- get() {
112
- return function setDocumentData(patch) {
113
- Object.assign(this, patch);
114
- };
115
- },
116
- enumerable: true,
117
- configurable: false
118
- });
119
- return doc;
120
- }
121
- function extractDocumentData(value) {
122
- if (!isRecord(value)) return {};
123
- const data = {};
124
- for (const [field, fieldValue] of Object.entries(value)) {
125
- if (reservedDocumentFields.has(field) || field.startsWith("$") || typeof fieldValue === "function") continue;
126
- if (isFieldValue(fieldValue)) data[field] = fieldValue;
127
- }
128
- return data;
129
- }
130
- function resolveDefault(value) {
131
- const resolved = typeof value === "function" ? value() : value;
132
- if (!isFieldValue(resolved)) throw new Error("Source defaults must resolve to a string, number, boolean, or null.");
133
- return resolved;
134
- }
135
- function isRecord(value) {
136
- return typeof value === "object" && value !== null && !Array.isArray(value);
137
- }
138
- function isFieldValue(value) {
139
- return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null;
140
- }
141
- function failure(message, path) {
142
- return { issues: [{
143
- message,
144
- path
145
- }] };
146
- }
147
- let database;
148
- function getDatabase() {
149
- if (!database) {
150
- database = (0, expo_sqlite.openDatabaseSync)("silo.db");
151
- database.execSync(`
152
- PRAGMA journal_mode = WAL;
153
-
154
- CREATE TABLE IF NOT EXISTS sources (
155
- source TEXT NOT NULL,
156
- id TEXT NOT NULL,
157
- data TEXT NOT NULL,
158
- createdAt TEXT NOT NULL,
159
- updatedAt TEXT NOT NULL,
160
- version INTEGER NOT NULL DEFAULT 1,
161
- PRIMARY KEY (source, id)
162
- );
163
- `);
164
- }
165
- return database;
166
- }
167
- function loadRows(sourceName) {
168
- return getDatabase().getAllSync(`SELECT id, data FROM sources WHERE source = ?`, [sourceName]).map((row) => createDoc(row.id, JSON.parse(row.data)));
169
- }
170
- function insertRows(sourceName, rows) {
171
- const db = getDatabase();
172
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
173
- db.withTransactionSync(() => {
174
- for (const row of rows) {
175
- const data = extractDocumentData(row);
176
- db.runSync(`INSERT INTO sources (source, id, data, createdAt, updatedAt, version)
177
- VALUES (?, ?, ?, ?, ?, 1)`, [
178
- sourceName,
179
- row.id,
180
- JSON.stringify(data),
181
- timestamp,
182
- timestamp
183
- ]);
184
- }
185
- });
186
- return Promise.resolve();
187
- }
188
- function updateRows(sourceName, mutations) {
189
- const db = getDatabase();
190
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
191
- db.withTransactionSync(() => {
192
- for (const mutation of mutations) {
193
- const data = extractDocumentData(mutation.modified);
194
- mutation.modified = createDoc(String(mutation.key), data);
195
- db.runSync(`UPDATE sources
196
- SET data = ?, updatedAt = ?, version = version + 1
197
- WHERE source = ? AND id = ?`, [
198
- JSON.stringify(data),
199
- timestamp,
200
- sourceName,
201
- String(mutation.key)
202
- ]);
203
- }
204
- });
205
- return Promise.resolve();
206
- }
207
- function deleteRows(sourceName, mutations) {
208
- const db = getDatabase();
209
- db.withTransactionSync(() => {
210
- for (const mutation of mutations) {
211
- if (mutation.original) deletedDocs.add(mutation.original);
212
- deletedDocs.add(mutation.modified);
213
- db.runSync(`DELETE FROM sources WHERE source = ? AND id = ?`, [sourceName, String(mutation.key)]);
214
- }
215
- });
216
- return Promise.resolve();
217
- }
218
-
219
- //#endregion
220
- exports.createID = createID;
221
- exports.source = source;