@oddington/sdk 0.1.56 → 0.1.57
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
CHANGED
|
@@ -375,8 +375,8 @@ session subscription. Workspace existence and member access are checked by the
|
|
|
375
375
|
OS service. App modules use capability namespaces; routines and handlers receive
|
|
376
376
|
runtime context without calling `os.init`.
|
|
377
377
|
|
|
378
|
-
Hosted browser apps can initialize an existing named Data snapshot for local
|
|
379
|
-
|
|
378
|
+
Hosted browser apps can initialize an existing named Data snapshot for local
|
|
379
|
+
queries and shared Record Changes after host startup has installed that context:
|
|
380
380
|
|
|
381
381
|
```ts
|
|
382
382
|
const accounting = await data.init({ repository: 'general', snapshot: 'buchhaltung' });
|
|
@@ -385,22 +385,47 @@ const month = await accounting.records.query({
|
|
|
385
385
|
});
|
|
386
386
|
const transaction = await accounting.records.read('transactions/example');
|
|
387
387
|
const changes = await accounting.changes.list();
|
|
388
|
+
const proposed = await accounting.transact(tx => {
|
|
389
|
+
tx.transactions[transactionId].update({ payment: 'paid' }).link({ invoice: invoiceRef });
|
|
390
|
+
});
|
|
391
|
+
await accounting.changes.publish(proposed, { summary: 'Invoice paid' });
|
|
392
|
+
// Or discard an exact current owned selection before publication:
|
|
393
|
+
// await accounting.changes.discard(proposed);
|
|
388
394
|
```
|
|
389
395
|
|
|
390
396
|
Initialization confirms current access and the available artifact, reuses an
|
|
391
397
|
exact complete artifact-and-Changes installation or installs the validated
|
|
392
398
|
download and relevant Changes together. Published Changes are materialized before
|
|
393
399
|
querying or exact reads. Stored Changes without publication information remain
|
|
394
|
-
in
|
|
400
|
+
in `changes.list()` and never alter Records.
|
|
395
401
|
`records.query`, `records.pages` and `records.all(query, { maxRecords })` use the existing query language and generated-schema inference.
|
|
396
402
|
They read locally and expose the initialized version in `$meta.version`. The
|
|
397
|
-
handle
|
|
398
|
-
later
|
|
403
|
+
handle incorporates its own successful mutations; explicitly call `data.init`
|
|
404
|
+
again to observe another client's later Changes or an operator-built snapshot. Single-ref `records.read(ref)`
|
|
399
405
|
returns the complete structured Record or `null` from that same pinned state.
|
|
400
406
|
Initialization never refreshes the hosted artifact. Sign-out, context replacement and expiry invalidate local reads.
|
|
401
407
|
Snapshot initialization requires a hosted browser app; Node, routines and local
|
|
402
408
|
app contexts receive `DataOperationError` with `context_unavailable`.
|
|
403
409
|
|
|
410
|
+
`transact` captures a synchronous callback describing create, update, link,
|
|
411
|
+
unlink and delete operations across selected collections. Record methods chain;
|
|
412
|
+
create followed by edits folds into creation on the host. Generated schema
|
|
413
|
+
declarations refine fields and values, while the normalized runtime schemas and
|
|
414
|
+
host remain authoritative. Each call makes one authenticated hosted request;
|
|
415
|
+
transact changes only shared unpublished work. Publish and discard require exact
|
|
416
|
+
current owned Change IDs and versions. Publication uses the canonical writer and
|
|
417
|
+
applies its confirmed effects to local Records and the same Changes before
|
|
418
|
+
resolving, without waiting for hosted projection settlement. No operation
|
|
419
|
+
refreshes the artifact or adds a client subscription or unpublished query overlay.
|
|
420
|
+
|
|
421
|
+
After a lost transact/discard response, `DataOperationError.effect` is
|
|
422
|
+
`uncertain`, `retryable` is false, and that handle is invalid. Explicitly
|
|
423
|
+
initialize again to inspect authoritative work; do not replay the transaction.
|
|
424
|
+
A lost publication response may be retried on the same handle with the same
|
|
425
|
+
selection and summary; the SDK retains its canonical operation identity. If the
|
|
426
|
+
host accepted work but local persistence fails, the error reports `applied` and
|
|
427
|
+
invalidates the handle. Initialize again to recover coherent local state.
|
|
428
|
+
|
|
404
429
|
First-party Auth uses the handle without initializing workspace context. Its
|
|
405
430
|
bounded `browserAuth.authorization.get(id)`, `approve(id)` and `deny(id)` actions
|
|
406
431
|
support only the OS CLI request and fixed callback. Inspection/restoration never
|
package/dist/browser.js
CHANGED
|
@@ -2256,7 +2256,7 @@ function cursorPosition(value, binding, limit) {
|
|
|
2256
2256
|
return Object.keys(payload).length !== 4 || payload.format !== 1 || payload.binding !== binding || typeof position != "number" || !Number.isSafeInteger(position) || position <= 0 || position % limit !== 0 || typeof ref != "string" || !validRecordRef(ref) ? fail3("incompatible cursor") : { position, ref };
|
|
2257
2257
|
}
|
|
2258
2258
|
|
|
2259
|
-
var invalid7 = () => {
|
|
2259
|
+
var snapshotCollection = (catalogue, ref) => catalogue.filter((c) => ref.startsWith(`${c.name}/`)).sort((a, b) => b.name.length - a.name.length)[0], invalid7 = () => {
|
|
2260
2260
|
throw new DataOperationError("unavailable", !0);
|
|
2261
2261
|
}, object4 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid7() : value;
|
|
2262
2262
|
function stable(value) {
|
|
@@ -2293,7 +2293,7 @@ function validateSnapshotEnvelope(input, repository, name2) {
|
|
|
2293
2293
|
let previous = "";
|
|
2294
2294
|
for (let record4 of records) {
|
|
2295
2295
|
let value = object4(record4);
|
|
2296
|
-
if (!validRecordRef(value.$ref) ||
|
|
2296
|
+
if (!validRecordRef(value.$ref) || snapshotCollection(catalogue, value.$ref)?.name !== collection.name || value.$ref <= previous || types.has(value.$ref) || typeof value.$version != "string" || !/^record-v1:[0-9a-f]{64}$/.test(value.$version)) return invalid7();
|
|
2297
2297
|
types.set(value.$ref, collection.schema.type), previous = value.$ref;
|
|
2298
2298
|
}
|
|
2299
2299
|
}
|
|
@@ -2406,6 +2406,125 @@ function* evaluateRecordsQuery(query, catalogue, context, maxRecords) {
|
|
|
2406
2406
|
|
|
2407
2407
|
var snapshotAcquisitionType = "application/vnd.os.data-snapshot.v2+json", snapshotAcquisitionFormat = "data-snapshot-acquisition.v2", snapshotPairHeader = "Snapshot-Pair", validSnapshotPairToken = (value) => typeof value == "string" && /^snapshot-pair-v1:[0-9a-f]{64}$/.test(value);
|
|
2408
2408
|
|
|
2409
|
+
var invalid8 = () => {
|
|
2410
|
+
throw new DataOperationError("unavailable", !0);
|
|
2411
|
+
}, object5 = (v) => v && typeof v == "object" && !Array.isArray(v) ? v : invalid8(), uuid = (v) => typeof v == "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v), time = (v) => typeof v == "string" && Number.isFinite(Date.parse(v)), recordVersion = (v) => typeof v == "string" && /^record-v1:[0-9a-f]{64}$/.test(v), keys3 = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
|
|
2412
|
+
function validateAcquisition(input, repository, name2) {
|
|
2413
|
+
let row = object5(input), snapshot = object5(row.snapshot);
|
|
2414
|
+
return Object.keys(row).sort().join(",") !== "changes,format,snapshot" || row.format !== snapshotAcquisitionFormat || Object.keys(snapshot).sort().join(",") !== "collections,id,name,refreshedAt,repository,version" || !uuid(snapshot.id) || snapshot.repository !== repository || snapshot.name !== name2 || !dataVersion(snapshot.version) || !time(snapshot.refreshedAt) || !Array.isArray(snapshot.collections) || !snapshot.collections.length || !snapshot.collections.every((c) => typeof c == "string" && validRecordRef(`${c}/example`)) || snapshot.collections.join("\0") !== [...new Set(snapshot.collections)].sort().join("\0") || !Array.isArray(row.changes) ? invalid8() : {
|
|
2415
|
+
snapshot,
|
|
2416
|
+
changes: validateSnapshotChanges(row.changes, snapshot.collections)
|
|
2417
|
+
};
|
|
2418
|
+
}
|
|
2419
|
+
function validateSnapshotChanges(input, collections) {
|
|
2420
|
+
if (!Array.isArray(input)) return invalid8();
|
|
2421
|
+
let ids = /* @__PURE__ */ new Set(), unpublished = !1;
|
|
2422
|
+
for (let value of input) {
|
|
2423
|
+
let c = object5(value), effect = object5(c.effect);
|
|
2424
|
+
if (!keys3(c, ["id", "version", "ref", "recordVersion", "effect", "updatedAt", "person", "source", "publication"]) || !uuid(c.id) || ids.has(c.id) || !dataVersion(c.version) || !validRecordRef(c.ref) || !collections.some((name2) => c.ref.startsWith(`${name2}/`)) || !recordVersion(c.recordVersion) || !time(c.updatedAt)) return invalid8();
|
|
2425
|
+
if (ids.add(c.id), c.person !== void 0) {
|
|
2426
|
+
let person = object5(c.person);
|
|
2427
|
+
if (!keys3(person, ["id", "name", "email"]) || !uuid(person.id) || person.name !== void 0 && !dataText(person.name) || person.email !== void 0 && !dataText(person.email)) return invalid8();
|
|
2428
|
+
}
|
|
2429
|
+
if (c.source !== void 0) {
|
|
2430
|
+
let source2 = object5(c.source);
|
|
2431
|
+
if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine" || !dataText(source2.id)) return invalid8();
|
|
2432
|
+
}
|
|
2433
|
+
if (c.publication !== void 0) {
|
|
2434
|
+
let publication = object5(c.publication);
|
|
2435
|
+
if (unpublished || Object.keys(publication).sort().join(",") !== "commit,time" || typeof publication.commit != "string" || !/^[0-9a-f]{40}$/.test(publication.commit) || !time(publication.time)) return invalid8();
|
|
2436
|
+
} else unpublished = !0;
|
|
2437
|
+
if (effect.kind === "set") {
|
|
2438
|
+
if (Object.keys(effect).sort().join(",") !== "field,kind,value" || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field)) return invalid8();
|
|
2439
|
+
} else if (effect.kind === "link" || effect.kind === "unlink") {
|
|
2440
|
+
if (!keys3(effect, ["kind", "field", "refs", ...effect.kind === "link" ? ["remove"] : []]) || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field) || !Array.isArray(effect.refs) || !effect.refs.length || effect.refs.length > 1e5 || effect.refs.some((ref) => !validRecordRef(ref)) || new Set(effect.refs).size !== effect.refs.length || effect.remove !== void 0 && (!Array.isArray(effect.remove) || !effect.remove.length || effect.remove.length > 1e5 || effect.remove.some((ref) => !validRecordRef(ref)) || new Set(effect.remove).size !== effect.remove.length)) return invalid8();
|
|
2441
|
+
} else if (effect.kind === "create" || effect.kind === "delete") {
|
|
2442
|
+
if (Object.keys(effect).sort().join(",") !== "fields,kind") return invalid8();
|
|
2443
|
+
object5(effect.fields);
|
|
2444
|
+
} else return invalid8();
|
|
2445
|
+
}
|
|
2446
|
+
return input;
|
|
2447
|
+
}
|
|
2448
|
+
function materializeSnapshot(envelope, changes, version) {
|
|
2449
|
+
try {
|
|
2450
|
+
if (!changes.length) return envelope;
|
|
2451
|
+
let rows = new Map(Object.values(envelope.collections).flat().map((r) => [r.$ref, structuredClone(r)]));
|
|
2452
|
+
for (let c of changes) {
|
|
2453
|
+
let schema2 = snapshotCollection(envelope.catalogue, c.ref);
|
|
2454
|
+
if (!schema2) return invalid8();
|
|
2455
|
+
let effect = c.effect, definitions2 = "field" in effect ? schema2.schema.fields.filter((f) => f.name === effect.field) : schema2.schema.fields;
|
|
2456
|
+
if ("field" in effect && !definitions2.length) return invalid8();
|
|
2457
|
+
let values;
|
|
2458
|
+
if (effect.kind === "link" || effect.kind === "unlink") {
|
|
2459
|
+
let field = definitions2[0];
|
|
2460
|
+
if (field.kind !== "link" || !field.many && effect.kind === "link" && effect.refs.length !== 1) return invalid8();
|
|
2461
|
+
let targets = [...effect.refs, ...effect.kind === "link" ? effect.remove ?? [] : []];
|
|
2462
|
+
for (let ref of targets) validateRecordFields({ [effect.field]: field.many ? [ref] : ref }, definitions2, (_ref, allowed) => allowed[0], !0);
|
|
2463
|
+
values = { [effect.field]: field.many ? effect.refs : effect.refs[0] };
|
|
2464
|
+
} else values = effect.kind === "set" ? { [effect.field]: effect.value } : "fields" in effect ? effect.fields : invalid8();
|
|
2465
|
+
if (validateRecordFields(
|
|
2466
|
+
values,
|
|
2467
|
+
definitions2,
|
|
2468
|
+
(_ref, targets) => targets[0],
|
|
2469
|
+
!0
|
|
2470
|
+
), !c.publication) continue;
|
|
2471
|
+
let prior = rows.get(c.ref);
|
|
2472
|
+
if (effect.kind === "set") {
|
|
2473
|
+
if (!prior) return invalid8();
|
|
2474
|
+
rows.set(c.ref, { ...prior, [effect.field]: effect.value, $version: c.recordVersion });
|
|
2475
|
+
} else if (effect.kind === "link" || effect.kind === "unlink") {
|
|
2476
|
+
if (!prior) return invalid8();
|
|
2477
|
+
let field = definitions2[0], current2 = prior[effect.field], value = field.many ? effect.kind === "link" ? [.../* @__PURE__ */ new Set([...Array.isArray(current2) ? current2 : [], ...effect.refs])].filter((ref) => !effect.remove?.includes(String(ref))) : (Array.isArray(current2) ? current2 : []).filter((ref) => !effect.refs.includes(String(ref))) : effect.kind === "link" ? effect.remove?.includes(effect.refs[0]) ? null : effect.refs[0] : effect.refs.includes(String(current2)) ? null : current2;
|
|
2478
|
+
rows.set(c.ref, { ...prior, [effect.field]: value, $version: c.recordVersion });
|
|
2479
|
+
} else if (effect.kind === "create") {
|
|
2480
|
+
if (prior) return invalid8();
|
|
2481
|
+
rows.set(c.ref, { ...effect.fields, $ref: c.ref, $version: c.recordVersion });
|
|
2482
|
+
} else {
|
|
2483
|
+
if (!prior) return invalid8();
|
|
2484
|
+
rows.delete(c.ref);
|
|
2485
|
+
}
|
|
2486
|
+
}
|
|
2487
|
+
return validateSnapshotEnvelope({
|
|
2488
|
+
format: envelope.format,
|
|
2489
|
+
repository: envelope.repository,
|
|
2490
|
+
name: envelope.name,
|
|
2491
|
+
version,
|
|
2492
|
+
schemas: Object.fromEntries(envelope.catalogue.map((c) => [c.name, {
|
|
2493
|
+
name: c.name,
|
|
2494
|
+
type: c.schema.type,
|
|
2495
|
+
...c.schema.description === void 0 ? {} : { description: c.schema.description },
|
|
2496
|
+
fields: c.schema.fields.map(publicField)
|
|
2497
|
+
}])),
|
|
2498
|
+
collections: Object.fromEntries(envelope.catalogue.map((c) => [c.name, [...rows.values()].filter((r) => snapshotCollection(envelope.catalogue, r.$ref)?.name === c.name).sort((a, b) => a.$ref < b.$ref ? -1 : 1)]))
|
|
2499
|
+
}, envelope.repository, envelope.name);
|
|
2500
|
+
} catch {
|
|
2501
|
+
return invalid8();
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
2504
|
+
|
|
2505
|
+
function applySnapshotMutation(envelope, prior, mutation, installation) {
|
|
2506
|
+
let rejected = () => {
|
|
2507
|
+
throw new DataOperationError("unavailable");
|
|
2508
|
+
}, changes = prior;
|
|
2509
|
+
if (mutation.kind === "discard")
|
|
2510
|
+
changes = prior.filter((c) => !mutation.selected.some((s) => s.id === c.id && s.version === c.version));
|
|
2511
|
+
else {
|
|
2512
|
+
let accepted = validateSnapshotChanges(mutation.changes, installation.catalogue.map((c) => c.name)), ids = new Set(accepted.map((c) => c.id));
|
|
2513
|
+
if (changes = [...prior.filter((c) => !ids.has(c.id)), ...accepted], changes = [...changes.filter((c) => c.publication), ...changes.filter((c) => !c.publication)], mutation.kind === "publish") {
|
|
2514
|
+
if (!accepted.length || accepted.some((c) => !c.publication) || !Array.isArray(mutation.effects) || !mutation.effects.length) return rejected();
|
|
2515
|
+
let effects = mutation.effects.map((e) => {
|
|
2516
|
+
let source2 = accepted.find((c) => c.ref === e.ref);
|
|
2517
|
+
return !source2 || snapshotCollection(envelope.catalogue, e.ref)?.name !== e.collection || !["set", "create", "delete"].includes(e.effect.kind) ? rejected() : { ...source2, id: crypto.randomUUID(), recordVersion: e.version, effect: e.effect };
|
|
2518
|
+
});
|
|
2519
|
+
validateSnapshotChanges(effects, installation.catalogue.map((c) => c.name)), envelope = materializeSnapshot(envelope, effects, `snapshot-${crypto.randomUUID()}`);
|
|
2520
|
+
} else {
|
|
2521
|
+
if (!accepted.length || accepted.some((c) => c.publication)) return rejected();
|
|
2522
|
+
materializeSnapshot(envelope, accepted, envelope.version);
|
|
2523
|
+
}
|
|
2524
|
+
}
|
|
2525
|
+
return { envelope, changes };
|
|
2526
|
+
}
|
|
2527
|
+
|
|
2409
2528
|
var unavailable2 = () => {
|
|
2410
2529
|
throw new DataOperationError("unavailable", !0);
|
|
2411
2530
|
};
|
|
@@ -2440,7 +2559,7 @@ async function openSnapshotStore() {
|
|
|
2440
2559
|
await done;
|
|
2441
2560
|
return;
|
|
2442
2561
|
}
|
|
2443
|
-
if (value.partition !== partition || !value.id || !validSnapshotPairToken(value.pairToken) || !value.version || !Array.isArray(value.catalogue) || !value.counts || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
|
|
2562
|
+
if (value.partition !== partition || !value.id || !value.snapshotId || !validSnapshotPairToken(value.pairToken) || !value.version || !Array.isArray(value.catalogue) || !value.counts || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
|
|
2444
2563
|
await done;
|
|
2445
2564
|
return;
|
|
2446
2565
|
}
|
|
@@ -2449,12 +2568,15 @@ async function openSnapshotStore() {
|
|
|
2449
2568
|
await request(transaction.objectStore("records").index("collection").count([value.id, collection.name])) !== value.counts[collection.name] && (complete = !1);
|
|
2450
2569
|
return await done, complete ? value : void 0;
|
|
2451
2570
|
},
|
|
2452
|
-
async install(partition, pairToken, envelope, changes, assertCurrent) {
|
|
2571
|
+
async install(partition, pairToken, envelope, changes, assertCurrent, snapshotId) {
|
|
2453
2572
|
let installation = {
|
|
2454
2573
|
id: crypto.randomUUID(),
|
|
2455
2574
|
partition,
|
|
2456
2575
|
pairToken,
|
|
2457
2576
|
version: envelope.version,
|
|
2577
|
+
snapshotId,
|
|
2578
|
+
repository: envelope.repository,
|
|
2579
|
+
name: envelope.name,
|
|
2458
2580
|
catalogue: envelope.catalogue,
|
|
2459
2581
|
changeCount: changes.length,
|
|
2460
2582
|
cursorKey: crypto.getRandomValues(new Uint8Array(32)),
|
|
@@ -2475,8 +2597,51 @@ async function openSnapshotStore() {
|
|
|
2475
2597
|
}), error;
|
|
2476
2598
|
}
|
|
2477
2599
|
},
|
|
2600
|
+
async invalidate(installation) {
|
|
2601
|
+
let transaction = database.transaction(["current", "changes"], "readwrite"), done = completed(transaction);
|
|
2602
|
+
transaction.objectStore("changes").delete(installation.id), (await request(transaction.objectStore("current").get(installation.partition)))?.id === installation.id && transaction.objectStore("current").delete(installation.partition), await done;
|
|
2603
|
+
},
|
|
2604
|
+
async mutate(installation, mutation, assertCurrent) {
|
|
2605
|
+
let transaction = database.transaction(["current", "records", "changes"], "readwrite"), done = completed(transaction);
|
|
2606
|
+
try {
|
|
2607
|
+
assertCurrent();
|
|
2608
|
+
let records = transaction.objectStore("records"), collections = {}, prior = await request(transaction.objectStore("changes").get(installation.id));
|
|
2609
|
+
if (!prior || prior.length !== installation.changeCount) return unavailable2();
|
|
2610
|
+
for (let c of installation.catalogue) {
|
|
2611
|
+
let rows = await request(records.index("collection").getAll([installation.id, c.name]));
|
|
2612
|
+
if (rows.length !== installation.counts[c.name]) return unavailable2();
|
|
2613
|
+
collections[c.name] = rows.map((r) => r.record);
|
|
2614
|
+
}
|
|
2615
|
+
let { envelope, changes } = applySnapshotMutation({
|
|
2616
|
+
format: "data-snapshot.v1",
|
|
2617
|
+
repository: installation.repository,
|
|
2618
|
+
name: installation.name,
|
|
2619
|
+
version: installation.version,
|
|
2620
|
+
catalogue: installation.catalogue,
|
|
2621
|
+
collections
|
|
2622
|
+
}, prior, mutation, installation), id3 = crypto.randomUUID(), next = {
|
|
2623
|
+
...installation,
|
|
2624
|
+
id: id3,
|
|
2625
|
+
pairToken: "",
|
|
2626
|
+
version: envelope.version,
|
|
2627
|
+
queryIdentity: mutation.kind === "publish" ? id3 : installation.queryIdentity ?? installation.id,
|
|
2628
|
+
changeCount: changes.length,
|
|
2629
|
+
counts: Object.fromEntries(Object.entries(envelope.collections).map(([name2, rows]) => [name2, rows.length]))
|
|
2630
|
+
};
|
|
2631
|
+
for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
|
|
2632
|
+
records.put({ installation: id3, collection, ref: record4.$ref, record: record4 });
|
|
2633
|
+
return transaction.objectStore("changes").put(changes, id3), (await request(transaction.objectStore("current").get(installation.partition)))?.id === installation.id && transaction.objectStore("current").put(next, installation.partition), assertCurrent(), await done, assertCurrent(), next;
|
|
2634
|
+
} catch (error) {
|
|
2635
|
+
try {
|
|
2636
|
+
transaction.abort();
|
|
2637
|
+
} catch {
|
|
2638
|
+
}
|
|
2639
|
+
throw await done.catch(() => {
|
|
2640
|
+
}), error;
|
|
2641
|
+
}
|
|
2642
|
+
},
|
|
2478
2643
|
async read(installation, ref) {
|
|
2479
|
-
let transaction = database.transaction("records", "readonly"), done = completed(transaction), row = await request(transaction.objectStore("records").get([installation.id, ref])), collection = ref.
|
|
2644
|
+
let transaction = database.transaction("records", "readonly"), done = completed(transaction), row = await request(transaction.objectStore("records").get([installation.id, ref])), collection = snapshotCollection(installation.catalogue, ref).name, count = await request(transaction.objectStore("records").index("collection").count([installation.id, collection]));
|
|
2480
2645
|
return await done, count !== installation.counts[collection] ? unavailable2() : row?.record ?? null;
|
|
2481
2646
|
},
|
|
2482
2647
|
async changes(installation) {
|
|
@@ -2489,7 +2654,7 @@ async function openSnapshotStore() {
|
|
|
2489
2654
|
}, evaluation = evaluateRecordsQuery(query, installation.catalogue, {
|
|
2490
2655
|
workspaceId: installation.partition,
|
|
2491
2656
|
repository: installation.partition,
|
|
2492
|
-
identity: installation.id,
|
|
2657
|
+
identity: installation.queryIdentity ?? installation.id,
|
|
2493
2658
|
version: installation.version
|
|
2494
2659
|
}, maxRecords);
|
|
2495
2660
|
try {
|
|
@@ -2532,78 +2697,58 @@ async function openSnapshotStore() {
|
|
|
2532
2697
|
};
|
|
2533
2698
|
}
|
|
2534
2699
|
|
|
2535
|
-
var
|
|
2536
|
-
throw new DataOperationError("
|
|
2537
|
-
},
|
|
2538
|
-
function
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
if (
|
|
2545
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2700
|
+
var invalidChange2 = () => {
|
|
2701
|
+
throw new DataOperationError("invalid_change", !1, "unapplied");
|
|
2702
|
+
}, unsafe = (key) => key.startsWith("$") || ["__proto__", "constructor", "prototype"].includes(key);
|
|
2703
|
+
function capture5(value, depth = 0) {
|
|
2704
|
+
return depth > 32 ? invalidChange2() : Array.isArray(value) ? dataArray(value).map((v) => capture5(v, depth + 1)) : value && typeof value == "object" ? Object.fromEntries(Object.entries(dataProperties(value)).map(([key, d]) => unsafe(key) ? invalidChange2() : [key, capture5(d.value, depth + 1)])) : value === null || typeof value == "string" || typeof value == "boolean" || typeof value == "number" && Number.isFinite(value) ? value : invalidChange2();
|
|
2705
|
+
}
|
|
2706
|
+
function captureTransaction(callback, installation) {
|
|
2707
|
+
let active2 = !0, operations2 = [];
|
|
2708
|
+
try {
|
|
2709
|
+
if (typeof callback != "function") return invalidChange2();
|
|
2710
|
+
let tx = new Proxy(/* @__PURE__ */ Object.create(null), { get(_target, name2) {
|
|
2711
|
+
return typeof name2 != "string" || unsafe(name2) || !installation.catalogue.some((c) => c.name === name2) ? invalidChange2() : new Proxy(/* @__PURE__ */ Object.create(null), { get(_target2, id3) {
|
|
2712
|
+
let ref = `${name2}/${String(id3)}`;
|
|
2713
|
+
if (typeof id3 != "string" || !validRecordRef(ref) || snapshotCollection(installation.catalogue, ref)?.name !== name2) return invalidChange2();
|
|
2714
|
+
let schema2 = installation.catalogue.find((c) => c.name === name2).schema, builder = Object.fromEntries(["create", "update", "link", "unlink", "delete"].map((kind) => [kind, (...args) => {
|
|
2715
|
+
if (!active2 || args.length !== (kind === "delete" ? 0 : 1) || operations2.length >= 1e4) return invalidChange2();
|
|
2716
|
+
let fields4;
|
|
2717
|
+
if (kind !== "delete") {
|
|
2718
|
+
if (dataProperties(args[0]), fields4 = capture5(args[0]), !Object.keys(fields4).length || Object.keys(fields4).some((key) => unsafe(key) || kind !== "create" && ["id", "type"].includes(key))) return invalidChange2();
|
|
2719
|
+
let definitions2 = kind === "create" ? schema2.fields : schema2.fields.filter((f) => Object.hasOwn(fields4, f.name));
|
|
2720
|
+
if (kind === "link" || kind === "unlink")
|
|
2721
|
+
for (let [key, value] of Object.entries(fields4)) {
|
|
2722
|
+
let field = definitions2.find((f) => f.name === key), refs = typeof value == "string" ? [value] : value;
|
|
2723
|
+
if (field?.kind !== "link" || !Array.isArray(refs) || !refs.length || !field.many && refs.length !== 1 || refs.some((ref2) => !validRecordRef(ref2)) || new Set(refs).size !== refs.length) return invalidChange2();
|
|
2724
|
+
fields4[key] = field.many ? refs : refs[0];
|
|
2725
|
+
}
|
|
2726
|
+
validateRecordFields(fields4, definitions2, (ref2) => snapshotCollection(installation.catalogue, ref2)?.schema.type, !0), fields4 = captureDataCreate({ ...fields4, $ref: ref }).fields;
|
|
2727
|
+
}
|
|
2728
|
+
let prior = operations2.filter((op) => op.ref === ref);
|
|
2729
|
+
return kind === "delete" && prior.length || prior.some((op) => op.kind === "delete") || kind === "create" && prior.length ? invalidChange2() : (operations2.push({ kind, ref, ...fields4 ? { fields: fields4 } : {} }), builder);
|
|
2730
|
+
}]));
|
|
2731
|
+
return builder;
|
|
2732
|
+
} });
|
|
2733
|
+
} }), result2 = callback(tx);
|
|
2734
|
+
return result2 && typeof result2.then == "function" ? (Promise.resolve(result2).catch(() => {
|
|
2735
|
+
}), invalidChange2()) : operations2.length ? operations2 : invalidChange2();
|
|
2736
|
+
} catch (error) {
|
|
2737
|
+
if (error instanceof DataOperationError && error.code === "invalid_change") throw error;
|
|
2738
|
+
return invalidChange2();
|
|
2739
|
+
} finally {
|
|
2740
|
+
active2 = !1;
|
|
2559
2741
|
}
|
|
2560
|
-
return {
|
|
2561
|
-
snapshot,
|
|
2562
|
-
changes: row.changes
|
|
2563
|
-
};
|
|
2564
2742
|
}
|
|
2565
|
-
function
|
|
2743
|
+
function captureSelection(input) {
|
|
2566
2744
|
try {
|
|
2567
|
-
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
let effect = c.effect, definitions2 = effect.kind === "set" ? schema2.schema.fields.filter((f) => f.name === effect.field) : schema2.schema.fields;
|
|
2573
|
-
if (effect.kind === "set" && !definitions2.length) return invalid8();
|
|
2574
|
-
if (validateRecordFields(
|
|
2575
|
-
effect.kind === "set" ? { [effect.field]: effect.value } : effect.fields,
|
|
2576
|
-
definitions2,
|
|
2577
|
-
(_ref, targets) => targets[0],
|
|
2578
|
-
!0
|
|
2579
|
-
), !c.publication) continue;
|
|
2580
|
-
let prior = rows.get(c.ref);
|
|
2581
|
-
if (effect.kind === "set") {
|
|
2582
|
-
if (!prior) return invalid8();
|
|
2583
|
-
rows.set(c.ref, { ...prior, [effect.field]: effect.value, $version: c.recordVersion });
|
|
2584
|
-
} else if (effect.kind === "create") {
|
|
2585
|
-
if (prior) return invalid8();
|
|
2586
|
-
rows.set(c.ref, { ...effect.fields, $ref: c.ref, $version: c.recordVersion });
|
|
2587
|
-
} else {
|
|
2588
|
-
if (!prior) return invalid8();
|
|
2589
|
-
rows.delete(c.ref);
|
|
2590
|
-
}
|
|
2591
|
-
}
|
|
2592
|
-
return validateSnapshotEnvelope({
|
|
2593
|
-
format: envelope.format,
|
|
2594
|
-
repository: envelope.repository,
|
|
2595
|
-
name: envelope.name,
|
|
2596
|
-
version,
|
|
2597
|
-
schemas: Object.fromEntries(envelope.catalogue.map((c) => [c.name, {
|
|
2598
|
-
name: c.name,
|
|
2599
|
-
type: c.schema.type,
|
|
2600
|
-
...c.schema.description === void 0 ? {} : { description: c.schema.description },
|
|
2601
|
-
fields: c.schema.fields.map(publicField)
|
|
2602
|
-
}])),
|
|
2603
|
-
collections: Object.fromEntries(envelope.catalogue.map((c) => [c.name, [...rows.values()].filter((r) => r.$ref.startsWith(`${c.name}/`)).sort((a, b) => a.$ref < b.$ref ? -1 : 1)]))
|
|
2604
|
-
}, envelope.repository, envelope.name);
|
|
2745
|
+
let selected = dataArray(input).map((value) => {
|
|
2746
|
+
let row = dataProperties(value), id3 = row.id?.value, version = row.version?.value;
|
|
2747
|
+
return typeof id3 != "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(id3) || !dataVersion(version) ? invalidChange2() : { id: id3, version };
|
|
2748
|
+
});
|
|
2749
|
+
return !selected.length || selected.length > 1e4 || new Set(selected.map((c) => c.id)).size !== selected.length ? invalidChange2() : selected;
|
|
2605
2750
|
} catch {
|
|
2606
|
-
return
|
|
2751
|
+
return invalidChange2();
|
|
2607
2752
|
}
|
|
2608
2753
|
}
|
|
2609
2754
|
|
|
@@ -2678,7 +2823,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
|
|
|
2678
2823
|
version = `snapshot-${Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
2679
2824
|
}
|
|
2680
2825
|
let materialized = materializeSnapshot(envelope, acquired.changes, version);
|
|
2681
|
-
return assertCurrent(), await store.install(partition, pairToken, materialized, acquired.changes, assertCurrent);
|
|
2826
|
+
return assertCurrent(), await store.install(partition, pairToken, materialized, acquired.changes, assertCurrent, acquired.snapshot.id);
|
|
2682
2827
|
}
|
|
2683
2828
|
throw new DataOperationError("unavailable", !0);
|
|
2684
2829
|
} finally {
|
|
@@ -2694,7 +2839,50 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
|
|
|
2694
2839
|
} catch (error) {
|
|
2695
2840
|
throw assertCurrent(), error instanceof DataOperationError ? error : new DataOperationError("unavailable", !0);
|
|
2696
2841
|
}
|
|
2697
|
-
let
|
|
2842
|
+
let tail = Promise.resolve(), serial = (work2) => {
|
|
2843
|
+
let result2 = tail.then(work2);
|
|
2844
|
+
return tail = result2.catch(() => {
|
|
2845
|
+
}), result2;
|
|
2846
|
+
}, publications = /* @__PURE__ */ new Map(), mutate = async (kind, payload, selected, publication) => {
|
|
2847
|
+
if (assertCurrent(), publication?.complete) return [];
|
|
2848
|
+
let body = { snapshotId: installation.snapshotId, ...payload };
|
|
2849
|
+
checkDataRequestSize(body, 2 * 1024 * 1024);
|
|
2850
|
+
let dispatched = !1, applied = !1, store;
|
|
2851
|
+
try {
|
|
2852
|
+
store = await open(), assertCurrent(), dispatched = !0;
|
|
2853
|
+
let response2 = await fetch(`${authority2.endpoint}/api/data/snapshots/${repository}/${snapshot}/changes/${kind}`, {
|
|
2854
|
+
method: "POST",
|
|
2855
|
+
redirect: "error",
|
|
2856
|
+
cache: "no-store",
|
|
2857
|
+
headers: { ...authority2.headers, "content-type": "application/json" },
|
|
2858
|
+
body: JSON.stringify(body)
|
|
2859
|
+
});
|
|
2860
|
+
if (!response2.ok) throw dataTransportError(response2.status, await response2.json());
|
|
2861
|
+
applied = !0;
|
|
2862
|
+
let value = await response2.json(), mutation;
|
|
2863
|
+
if (kind === "discard") {
|
|
2864
|
+
if (!value || typeof value != "object" || Array.isArray(value) || Object.keys(value).length) throw new Error();
|
|
2865
|
+
mutation = { kind, selected };
|
|
2866
|
+
} else if (kind === "transact") mutation = { kind, changes: value };
|
|
2867
|
+
else {
|
|
2868
|
+
if (!value || Object.keys(value).sort().join(",") !== "changes,effects" || !Array.isArray(value.changes) || value.changes.length !== selected.length || value.changes.some((c) => !selected.some((s) => s.id === c.id && s.version === c.version))) throw new Error();
|
|
2869
|
+
mutation = { kind, changes: value.changes, effects: value.effects };
|
|
2870
|
+
}
|
|
2871
|
+
return installation = await store.mutate(installation, mutation, assertCurrent), assertCurrent(), publication && (publication.complete = !0), structuredClone(mutation.changes ?? []);
|
|
2872
|
+
} catch (error) {
|
|
2873
|
+
let failure = error instanceof DataOperationError ? error : new DataOperationError("unavailable"), effect = applied ? "applied" : dispatched ? failure.effect ?? "uncertain" : "unapplied";
|
|
2874
|
+
throw effect !== "unapplied" && (kind !== "publish" || effect === "applied") && (invalidated = !0, await store?.invalidate(installation).catch(() => {
|
|
2875
|
+
})), new DataOperationError(
|
|
2876
|
+
failure.code,
|
|
2877
|
+
effect === "uncertain" ? kind === "publish" : effect === "applied" ? !1 : failure.retryable,
|
|
2878
|
+
effect,
|
|
2879
|
+
failure.component,
|
|
2880
|
+
failure.detail
|
|
2881
|
+
);
|
|
2882
|
+
} finally {
|
|
2883
|
+
store?.close();
|
|
2884
|
+
}
|
|
2885
|
+
}, query = async (query2, maxRecords) => {
|
|
2698
2886
|
assertCurrent();
|
|
2699
2887
|
let captured = captureRecordsQuery(query2);
|
|
2700
2888
|
checkDataRequestSize({
|
|
@@ -2725,18 +2913,41 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
|
|
|
2725
2913
|
} finally {
|
|
2726
2914
|
store?.close();
|
|
2727
2915
|
}
|
|
2728
|
-
}, queryRecords =
|
|
2729
|
-
|
|
2916
|
+
}, queryRecords = (async (input2) => {
|
|
2917
|
+
let captured = captureRecordsQuery(input2);
|
|
2918
|
+
return serial(() => query(captured));
|
|
2919
|
+
});
|
|
2920
|
+
return { transact: (callback) => {
|
|
2921
|
+
try {
|
|
2922
|
+
assertCurrent();
|
|
2923
|
+
let operations2 = captureTransaction(callback, installation);
|
|
2924
|
+
return serial(() => mutate("transact", { operations: operations2 }));
|
|
2925
|
+
} catch (error) {
|
|
2926
|
+
return Promise.reject(error);
|
|
2927
|
+
}
|
|
2928
|
+
}, changes: {
|
|
2929
|
+
list: () => serial(() => localRead((store) => store.changes(installation))),
|
|
2930
|
+
discard: async (input2) => {
|
|
2931
|
+
let selected = captureSelection(input2);
|
|
2932
|
+
await serial(() => mutate("discard", { selected }, selected));
|
|
2933
|
+
},
|
|
2934
|
+
publish: async (input2, options) => {
|
|
2935
|
+
let selected = captureSelection(input2), metadata = captureDataChangeOptions(options);
|
|
2936
|
+
if (metadata.source) return invalidChange2();
|
|
2937
|
+
let key = JSON.stringify([selected.slice().sort((a, b) => a.id.localeCompare(b.id)), metadata]), publication = publications.get(key);
|
|
2938
|
+
publication || (publication = { id: crypto.randomUUID() }, publications.set(key, publication)), await serial(() => mutate("publish", { selected, ...metadata, publicationId: publication.id }, selected, publication));
|
|
2939
|
+
}
|
|
2940
|
+
}, records: {
|
|
2730
2941
|
read: async (ref, ...extra) => {
|
|
2731
2942
|
if (typeof ref != "string" || extra.length) return Promise.reject(new DataOperationError("invalid_query"));
|
|
2732
2943
|
let [captured] = captureRecordsReadRefs([ref]);
|
|
2733
|
-
return installation.catalogue.some((c) => captured.startsWith(`${c.name}/`)) ? localRead((store) => store.read(installation, captured)) : Promise.reject(new DataOperationError("invalid_query"));
|
|
2944
|
+
return installation.catalogue.some((c) => captured.startsWith(`${c.name}/`)) ? serial(() => localRead((store) => store.read(installation, captured))) : Promise.reject(new DataOperationError("invalid_query"));
|
|
2734
2945
|
},
|
|
2735
2946
|
query: queryRecords,
|
|
2736
2947
|
...recordPagination(queryRecords),
|
|
2737
2948
|
all: (input2, options) => {
|
|
2738
2949
|
let captured = captureRecordsAll(input2, options);
|
|
2739
|
-
return query(captured.query, captured.maxRecords);
|
|
2950
|
+
return serial(() => query(captured.query, captured.maxRecords));
|
|
2740
2951
|
}
|
|
2741
2952
|
} };
|
|
2742
2953
|
};
|