js-bao 0.12.0-alpha.12 → 0.12.0-alpha.14
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/browser.cjs +1526 -280
- package/dist/browser.d.cts +658 -28
- package/dist/browser.d.ts +658 -28
- package/dist/browser.js +1526 -280
- package/dist/client.cjs +9 -0
- package/dist/client.d.cts +253 -7
- package/dist/client.d.ts +253 -7
- package/dist/client.js +9 -0
- package/dist/cloudflare-do.cjs +104 -23
- package/dist/cloudflare-do.d.cts +313 -11
- package/dist/cloudflare-do.d.ts +313 -11
- package/dist/cloudflare-do.js +104 -23
- package/dist/cloudflare.cjs +13 -0
- package/dist/cloudflare.d.cts +253 -7
- package/dist/cloudflare.d.ts +253 -7
- package/dist/cloudflare.js +13 -0
- package/dist/codegen-v2.cjs +496 -297
- package/dist/codegen.cjs +6 -5
- package/dist/format2-worker.js +1133 -582
- package/dist/index.cjs +14656 -13385
- package/dist/index.d.cts +770 -42
- package/dist/index.d.ts +770 -42
- package/dist/index.js +14256 -12995
- package/dist/node.cjs +1572 -283
- package/dist/node.d.cts +658 -28
- package/dist/node.d.ts +658 -28
- package/dist/node.js +1567 -283
- package/dist/record-log.cjs +100 -25
- package/dist/record-log.d.cts +121 -17
- package/dist/record-log.d.ts +121 -17
- package/dist/record-log.js +100 -25
- package/package.json +7 -6
package/dist/browser.cjs
CHANGED
|
@@ -2000,14 +2000,14 @@ function servableOperator(condition) {
|
|
|
2000
2000
|
}
|
|
2001
2001
|
return null;
|
|
2002
2002
|
}
|
|
2003
|
-
function analyze(model, node, indexes,
|
|
2003
|
+
function analyze(model, node, indexes, isSetField2) {
|
|
2004
2004
|
const out = { served: false, servable: false, first: null };
|
|
2005
2005
|
if (!isPlainObject(node)) return out;
|
|
2006
2006
|
if ("id" in node && servableOperator(node.id) !== null) return { served: true, servable: false, first: null };
|
|
2007
2007
|
for (const [key, value] of Object.entries(node)) {
|
|
2008
2008
|
if (key === "$and" || key === "$or") {
|
|
2009
2009
|
if (!Array.isArray(value) || value.length === 0) continue;
|
|
2010
|
-
const branches = value.map((branch) => analyze(model, branch, indexes,
|
|
2010
|
+
const branches = value.map((branch) => analyze(model, branch, indexes, isSetField2));
|
|
2011
2011
|
out.served ||= key === "$and" ? branches.some((b) => b.served) : branches.every((b) => b.served);
|
|
2012
2012
|
out.servable ||= branches.some((b) => b.servable);
|
|
2013
2013
|
out.first ??= branches.find((b) => b.first)?.first ?? null;
|
|
@@ -2015,7 +2015,7 @@ function analyze(model, node, indexes, isSetField) {
|
|
|
2015
2015
|
}
|
|
2016
2016
|
if (key.startsWith("$") || key === "id" || key === "type") continue;
|
|
2017
2017
|
const operator = servableOperator(value);
|
|
2018
|
-
if (operator === null ||
|
|
2018
|
+
if (operator === null || isSetField2(model, key)) continue;
|
|
2019
2019
|
out.servable = true;
|
|
2020
2020
|
if (out.served) continue;
|
|
2021
2021
|
if (indexes.leads(model, key)) out.served = true;
|
|
@@ -2024,14 +2024,14 @@ function analyze(model, node, indexes, isSetField) {
|
|
|
2024
2024
|
if (out.served) out.first = null;
|
|
2025
2025
|
return out;
|
|
2026
2026
|
}
|
|
2027
|
-
function sortSignal(model, sort, indexes,
|
|
2027
|
+
function sortSignal(model, sort, indexes, isSetField2) {
|
|
2028
2028
|
if (!isPlainObject(sort)) return null;
|
|
2029
2029
|
const entries = Object.entries(sort);
|
|
2030
2030
|
while (entries.length > 0 && entries[entries.length - 1][0] === "id") entries.pop();
|
|
2031
2031
|
if (entries.length === 0) return null;
|
|
2032
2032
|
const fields = entries.map(([field2]) => field2);
|
|
2033
2033
|
const directions = entries.map(([, direction]) => Number(direction) < 0 || direction === "desc" ? -1 : 1);
|
|
2034
|
-
const named = (field2) => field2 !== "id" && field2 !== "type" && !
|
|
2034
|
+
const named = (field2) => field2 !== "id" && field2 !== "type" && !isSetField2(model, field2);
|
|
2035
2035
|
if (!named(fields[0])) return null;
|
|
2036
2036
|
const tuples = indexes.of(model);
|
|
2037
2037
|
let covered = 0;
|
|
@@ -2046,13 +2046,13 @@ function sortSignal(model, sort, indexes, isSetField) {
|
|
|
2046
2046
|
if (!named(field)) return null;
|
|
2047
2047
|
return { model, field, reason: "sort", fields: fields.slice(0, covered + 1) };
|
|
2048
2048
|
}
|
|
2049
|
-
function signalFor(model, filter, sort, indexes,
|
|
2050
|
-
const analysis = analyze(model, filter, indexes,
|
|
2049
|
+
function signalFor(model, filter, sort, indexes, isSetField2) {
|
|
2050
|
+
const analysis = analyze(model, filter, indexes, isSetField2);
|
|
2051
2051
|
if (analysis.served) return null;
|
|
2052
2052
|
if (analysis.servable) {
|
|
2053
2053
|
return analysis.first ? { model, field: analysis.first.field, reason: "filter", operator: analysis.first.operator } : null;
|
|
2054
2054
|
}
|
|
2055
|
-
return sortSignal(model, sort, indexes,
|
|
2055
|
+
return sortSignal(model, sort, indexes, isSetField2);
|
|
2056
2056
|
}
|
|
2057
2057
|
function scanSignalsFor(model, filter, options, context) {
|
|
2058
2058
|
const indexes = new Indexes(context);
|
|
@@ -3466,6 +3466,10 @@ var init_JsonQueryTranslator = __esm({
|
|
|
3466
3466
|
get membershipFromData() {
|
|
3467
3467
|
return this.options.stringSets === "json_each";
|
|
3468
3468
|
}
|
|
3469
|
+
/** The whole row's `_data` as a select column: JSON text, whichever encoding the row is stored in. */
|
|
3470
|
+
get wholeData() {
|
|
3471
|
+
return this.options.jsonbData === true ? "json(_data) AS _data" : "_data";
|
|
3472
|
+
}
|
|
3469
3473
|
/** Whether `$all`, `$size` and the substring operators read a set's array in `_data`. */
|
|
3470
3474
|
get setArraysFromData() {
|
|
3471
3475
|
return this.membershipFromData || this.options.setArraysInData === true;
|
|
@@ -3632,7 +3636,7 @@ var init_JsonQueryTranslator = __esm({
|
|
|
3632
3636
|
`${foreignKeySql} IN (${parentValues.map(() => "?").join(", ")})`
|
|
3633
3637
|
];
|
|
3634
3638
|
const sql = `
|
|
3635
|
-
SELECT "_id", "_type",
|
|
3639
|
+
SELECT "_id", "_type", ${this.wholeData} FROM (
|
|
3636
3640
|
SELECT "_id", "_type", _data,
|
|
3637
3641
|
ROW_NUMBER() OVER (
|
|
3638
3642
|
PARTITION BY ${foreignKeySql}
|
|
@@ -3668,7 +3672,7 @@ var init_JsonQueryTranslator = __esm({
|
|
|
3668
3672
|
*/
|
|
3669
3673
|
aggregateSource(options = {}) {
|
|
3670
3674
|
const table = this.table;
|
|
3671
|
-
const
|
|
3675
|
+
const isSetField2 = options.isSetField ?? (() => false);
|
|
3672
3676
|
const baseConditions = this.options.baseConditions ?? [];
|
|
3673
3677
|
const setAlias = (field, index) => {
|
|
3674
3678
|
assertValidIdentifier(field, "aggregation groupBy field");
|
|
@@ -3680,7 +3684,8 @@ var init_JsonQueryTranslator = __esm({
|
|
|
3680
3684
|
table,
|
|
3681
3685
|
facetOperations: "all",
|
|
3682
3686
|
facetSortsByMember: true,
|
|
3683
|
-
|
|
3687
|
+
facetTiesByMember: this.options.facetTiesByMember === true,
|
|
3688
|
+
isSetField: isSetField2,
|
|
3684
3689
|
fieldSql: (field) => qualified.getFieldSql(field),
|
|
3685
3690
|
operationSql: (operation) => operation.type === "count" ? `COUNT(*) AS ${quoteIdentifier("count")}` : `${operation.type.toUpperCase()}(${qualified.getFieldSql(operation.field)}) AS ${quoteIdentifier(
|
|
3686
3691
|
aggregationOperationKey(operation)
|
|
@@ -3696,11 +3701,29 @@ var init_JsonQueryTranslator = __esm({
|
|
|
3696
3701
|
filterSql: (filter, reservedParams) => qualified.translateFilterWithinBound(filter ?? {}, reservedParams),
|
|
3697
3702
|
membership: (level, index) => {
|
|
3698
3703
|
const alias = setAlias(level.field, index);
|
|
3699
|
-
|
|
3704
|
+
const memberIndex = this.memberIndexOf(level.field);
|
|
3705
|
+
if (memberIndex !== null) {
|
|
3700
3706
|
return {
|
|
3701
3707
|
alias,
|
|
3702
|
-
select: `CASE WHEN ${this.
|
|
3708
|
+
select: `CASE WHEN ${this.memberIndexSql(memberIndex)} THEN 'true' ELSE 'false' END`,
|
|
3703
3709
|
selectParams: [level.contains],
|
|
3710
|
+
// The level is judged against the bound as its `_data` statement
|
|
3711
|
+
// binds it, its field and its member, though the probe binds the
|
|
3712
|
+
// member alone (#5150, #5146).
|
|
3713
|
+
reservedParams: 1,
|
|
3714
|
+
group: quoteIdentifier(alias),
|
|
3715
|
+
join: "",
|
|
3716
|
+
joinParams: []
|
|
3717
|
+
};
|
|
3718
|
+
}
|
|
3719
|
+
if (this.membershipFromData) {
|
|
3720
|
+
return {
|
|
3721
|
+
alias,
|
|
3722
|
+
select: `CASE WHEN ${this.setMemberSql(level.field, "_set.value = ?", true)} THEN 'true' ELSE 'false' END`,
|
|
3723
|
+
// The level binds its field and its member, as the member table's
|
|
3724
|
+
// join does, so a filter is refused past the bound where it is on
|
|
3725
|
+
// every source (#5146).
|
|
3726
|
+
selectParams: [this.dataPath(level.field), level.contains],
|
|
3704
3727
|
// The presence binds its member, so the level groups by its alias
|
|
3705
3728
|
// rather than repeating the expression and its bind.
|
|
3706
3729
|
group: quoteIdentifier(alias),
|
|
@@ -3718,14 +3741,26 @@ var init_JsonQueryTranslator = __esm({
|
|
|
3718
3741
|
joinParams: [level.field, level.contains]
|
|
3719
3742
|
};
|
|
3720
3743
|
},
|
|
3721
|
-
facet: (field) => {
|
|
3744
|
+
facet: (field, facetOptions) => {
|
|
3745
|
+
const memberIndex = this.memberIndexOf(field);
|
|
3746
|
+
if (memberIndex !== null && !facetOptions?.filtered) {
|
|
3747
|
+
return {
|
|
3748
|
+
from: facetOptions?.readsRecords ? `${quoteIdentifier(memberIndex)} AS _facet JOIN ${table} ON ${table}.rowid = _facet.rid` : `${quoteIdentifier(memberIndex)} AS _facet`,
|
|
3749
|
+
value: "_facet.value",
|
|
3750
|
+
conditions: [],
|
|
3751
|
+
params: []
|
|
3752
|
+
};
|
|
3753
|
+
}
|
|
3722
3754
|
if (this.membershipFromData) {
|
|
3723
|
-
const path = this.dataPathSql(field);
|
|
3724
3755
|
return {
|
|
3725
|
-
from: `${table}, json_each(${
|
|
3756
|
+
from: `${table}, json_each(${table}._data, ?) AS _facet`,
|
|
3726
3757
|
value: "_facet.value",
|
|
3727
|
-
conditions: [
|
|
3728
|
-
|
|
3758
|
+
conditions: [
|
|
3759
|
+
`${table}.${quoteIdentifier("_type")} = ?`,
|
|
3760
|
+
`json_type(${this.dataPathSql(field)}) = 'array'`,
|
|
3761
|
+
...baseConditions
|
|
3762
|
+
],
|
|
3763
|
+
params: [this.dataPath(field), this.modelName]
|
|
3729
3764
|
};
|
|
3730
3765
|
}
|
|
3731
3766
|
return {
|
|
@@ -4008,16 +4043,35 @@ var init_JsonQueryTranslator = __esm({
|
|
|
4008
4043
|
* A membership condition over the array a record holds in `fieldName`
|
|
4009
4044
|
* (`stringSets: "json_each"`): true only where the stored value is an
|
|
4010
4045
|
* array, and then when `members` (a condition over the `json_each` rows of
|
|
4011
|
-
* its members, aliased `_set`) holds for one of them.
|
|
4046
|
+
* its members, aliased `_set`) holds for one of them. With `bindPath`, the
|
|
4047
|
+
* `json_each` takes the field's path as its first parameter, before any
|
|
4048
|
+
* `members` binds.
|
|
4012
4049
|
*/
|
|
4013
|
-
setMemberSql(fieldName, members) {
|
|
4050
|
+
setMemberSql(fieldName, members, bindPath = false) {
|
|
4014
4051
|
const path = this.dataPathSql(fieldName);
|
|
4015
|
-
|
|
4052
|
+
const each = bindPath ? `${this.table}._data, ?` : path;
|
|
4053
|
+
return `(json_type(${path}) = 'array' AND EXISTS (SELECT 1 FROM json_each(${each}) AS _set WHERE ${members}))`;
|
|
4054
|
+
}
|
|
4055
|
+
/** The member index `fieldName`'s members are read from, or `null` (#5150). */
|
|
4056
|
+
memberIndexOf(fieldName) {
|
|
4057
|
+
if (SYSTEM_FIELDS2.has(fieldName)) return null;
|
|
4058
|
+
return this.options.memberIndexTable?.(fieldName) ?? null;
|
|
4059
|
+
}
|
|
4060
|
+
/**
|
|
4061
|
+
* A record holds `?` in the set `table` indexes: a rowid probe of the
|
|
4062
|
+
* member index (#5150), driven by the member, never a correlated `EXISTS`.
|
|
4063
|
+
*/
|
|
4064
|
+
memberIndexSql(table) {
|
|
4065
|
+
return `${this.table}.rowid IN (SELECT rid FROM ${quoteIdentifier(table)} WHERE value = ?)`;
|
|
4016
4066
|
}
|
|
4017
4067
|
/** `<table>._data, '$.<field>'`: the arguments that address a field's stored JSON. */
|
|
4018
4068
|
dataPathSql(fieldName) {
|
|
4069
|
+
return `${this.table}._data, '${this.dataPath(fieldName)}'`;
|
|
4070
|
+
}
|
|
4071
|
+
/** `$.<field>`: the JSON path of a field in `_data`. */
|
|
4072
|
+
dataPath(fieldName) {
|
|
4019
4073
|
assertValidIdentifier(fieldName, "query field");
|
|
4020
|
-
return
|
|
4074
|
+
return `$.${fieldName}`;
|
|
4021
4075
|
}
|
|
4022
4076
|
/**
|
|
4023
4077
|
* Translate field condition to SQL
|
|
@@ -4113,7 +4167,7 @@ var init_JsonQueryTranslator = __esm({
|
|
|
4113
4167
|
} catch {
|
|
4114
4168
|
}
|
|
4115
4169
|
}
|
|
4116
|
-
if (this.setArraysFromData) {
|
|
4170
|
+
if (this.setArraysFromData && !SYSTEM_FIELDS2.has(fieldName)) {
|
|
4117
4171
|
const like = `LIKE ? ESCAPE '\\' COLLATE NOCASE`;
|
|
4118
4172
|
conditions.push(
|
|
4119
4173
|
`((json_type(${this.dataPathSql(fieldName)}) <> 'array' AND ${fieldSql} ${like}) OR ${this.setMemberSql(fieldName, `_set.value ${like}`)})`
|
|
@@ -4298,6 +4352,10 @@ var init_JsonQueryTranslator = __esm({
|
|
|
4298
4352
|
fieldType
|
|
4299
4353
|
);
|
|
4300
4354
|
}
|
|
4355
|
+
{
|
|
4356
|
+
const table = this.memberIndexOf(fieldName);
|
|
4357
|
+
if (table !== null) return { sql: this.memberIndexSql(table), params: [value] };
|
|
4358
|
+
}
|
|
4301
4359
|
if (this.membershipFromData) {
|
|
4302
4360
|
return { sql: this.setMemberSql(fieldName, "_set.value = ?"), params: [value] };
|
|
4303
4361
|
}
|
|
@@ -4380,7 +4438,7 @@ var init_JsonQueryTranslator = __esm({
|
|
|
4380
4438
|
*/
|
|
4381
4439
|
buildSelectClause(projection, aliasedSortFields) {
|
|
4382
4440
|
if (!projection || Object.keys(projection).length === 0) {
|
|
4383
|
-
return
|
|
4441
|
+
return `_id, _type, ${this.wholeData}`;
|
|
4384
4442
|
}
|
|
4385
4443
|
const includeFields = [];
|
|
4386
4444
|
const excludeFields = [];
|
|
@@ -4421,9 +4479,9 @@ var init_JsonQueryTranslator = __esm({
|
|
|
4421
4479
|
}
|
|
4422
4480
|
return selectParts.join(", ");
|
|
4423
4481
|
} else if (hasExcludes) {
|
|
4424
|
-
return
|
|
4482
|
+
return `_id, _type, ${this.wholeData}`;
|
|
4425
4483
|
}
|
|
4426
|
-
return
|
|
4484
|
+
return `_id, _type, ${this.wholeData}`;
|
|
4427
4485
|
}
|
|
4428
4486
|
/**
|
|
4429
4487
|
* Build LIMIT clause
|
|
@@ -5204,6 +5262,74 @@ var init_write = __esm({
|
|
|
5204
5262
|
}
|
|
5205
5263
|
});
|
|
5206
5264
|
|
|
5265
|
+
// src/record-log-client/declared-types.ts
|
|
5266
|
+
function isRepresentableDate(value) {
|
|
5267
|
+
if (typeof value === "number") return Number.isFinite(value) && !Number.isNaN(new Date(value).getTime());
|
|
5268
|
+
const shape = ISO_DATE_STRING.exec(value);
|
|
5269
|
+
if (!shape) return false;
|
|
5270
|
+
if (Number.isNaN(Date.parse(value.replace(" ", "T")))) return false;
|
|
5271
|
+
const [, year, month, day] = shape;
|
|
5272
|
+
const roundTrip = /* @__PURE__ */ new Date(`${year}-${month}-${day}T00:00:00Z`);
|
|
5273
|
+
return roundTrip.getUTCFullYear() === Number(year) && roundTrip.getUTCMonth() + 1 === Number(month) && roundTrip.getUTCDate() === Number(day);
|
|
5274
|
+
}
|
|
5275
|
+
function receivedKind(value) {
|
|
5276
|
+
if (Array.isArray(value)) return "an array";
|
|
5277
|
+
return typeof value;
|
|
5278
|
+
}
|
|
5279
|
+
function declaredTypeProblem(mutations, type) {
|
|
5280
|
+
const declaredModels = Object.keys(type.models).sort();
|
|
5281
|
+
for (const [at, m] of mutations.entries()) {
|
|
5282
|
+
const where2 = at === 0 ? "m" : `also[${at - 1}]`;
|
|
5283
|
+
if (declaredModels.length && !Object.prototype.hasOwnProperty.call(type.models, m.model)) {
|
|
5284
|
+
return {
|
|
5285
|
+
code: "DB3_MODEL_NOT_DECLARED",
|
|
5286
|
+
message: `${where2}: ${m.model} is not a model of the db3's type ${type.name}; it declares ${declaredModels.join(", ")}`
|
|
5287
|
+
};
|
|
5288
|
+
}
|
|
5289
|
+
if (m.kind === "delete") continue;
|
|
5290
|
+
const kinds = type.models[m.model];
|
|
5291
|
+
if (!kinds || !Object.keys(kinds).length) continue;
|
|
5292
|
+
const declaredOf = (field) => Object.prototype.hasOwnProperty.call(kinds, field) ? kinds[field] : void 0;
|
|
5293
|
+
const refuse = (field, declared, received) => ({
|
|
5294
|
+
code: "DOCUMENT_ENTRY_INVALID",
|
|
5295
|
+
message: `${where2}: ${m.model} id=${m.id}: field "${field}" is declared ${declared}; the entry wrote ${received}`
|
|
5296
|
+
});
|
|
5297
|
+
for (const [field, value] of Object.entries(m.fields ?? {})) {
|
|
5298
|
+
if (field === "id" || value === null) continue;
|
|
5299
|
+
const declared = declaredOf(field);
|
|
5300
|
+
if (declared === void 0) continue;
|
|
5301
|
+
const kind = m.kind === "increment" ? "number" : receivedKind(value);
|
|
5302
|
+
if (declared === "stringset") return refuse(field, declared, `a scalar (${kind})`);
|
|
5303
|
+
if (!SCALAR_KINDS.has(declared)) continue;
|
|
5304
|
+
const matches = declared === "date" ? (kind === "string" || kind === "number") && (m.kind === "increment" || isRepresentableDate(value)) : declared === "id" ? kind === "string" : kind === declared;
|
|
5305
|
+
if (!matches) return refuse(field, declared, kind === "string" && declared === "date" ? "a string that is not an ISO date" : kind);
|
|
5306
|
+
}
|
|
5307
|
+
for (const field of Object.keys(m.stringSetDeltas ?? {})) {
|
|
5308
|
+
const declared = declaredOf(field);
|
|
5309
|
+
if (declared !== void 0 && declared !== "stringset") return refuse(field, declared, "a string-set change");
|
|
5310
|
+
}
|
|
5311
|
+
}
|
|
5312
|
+
return null;
|
|
5313
|
+
}
|
|
5314
|
+
function assertRecordLogDeclaredTypes(documentId, mutations, type, report) {
|
|
5315
|
+
if (!type || !mutations.length) return;
|
|
5316
|
+
const problem = declaredTypeProblem(mutations, type);
|
|
5317
|
+
if (!problem) return;
|
|
5318
|
+
const error = new RecordLogWriteRefusedError(problem.code, documentId, problem.message, { scope: "local" });
|
|
5319
|
+
const [first, ...rest] = mutations;
|
|
5320
|
+
report?.({ documentId, model: first.model, recordId: first.id, error, writes: refusedWritesOf({ seq: 0, m: first, also: rest }) });
|
|
5321
|
+
throw error;
|
|
5322
|
+
}
|
|
5323
|
+
var SCALAR_KINDS, ISO_DATE_STRING;
|
|
5324
|
+
var init_declared_types = __esm({
|
|
5325
|
+
"src/record-log-client/declared-types.ts"() {
|
|
5326
|
+
"use strict";
|
|
5327
|
+
init_types();
|
|
5328
|
+
SCALAR_KINDS = /* @__PURE__ */ new Set(["string", "number", "boolean", "date", "id"]);
|
|
5329
|
+
ISO_DATE_STRING = /^(\d{4})-(\d{2})-(\d{2})(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/;
|
|
5330
|
+
}
|
|
5331
|
+
});
|
|
5332
|
+
|
|
5207
5333
|
// src/record-log/types.ts
|
|
5208
5334
|
function recordKeyString(key) {
|
|
5209
5335
|
return `${key.model}${KEY_SEPARATOR}${key.id}`;
|
|
@@ -5280,6 +5406,24 @@ var init_resolve = __esm({
|
|
|
5280
5406
|
});
|
|
5281
5407
|
|
|
5282
5408
|
// src/record-log/results.ts
|
|
5409
|
+
function sameValue(a, b) {
|
|
5410
|
+
if (a === b) return true;
|
|
5411
|
+
if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
|
|
5412
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
5413
|
+
}
|
|
5414
|
+
function changeBetween(key, before, after) {
|
|
5415
|
+
const { model, id } = key;
|
|
5416
|
+
if (!after) return before ? { model, id, gone: true } : null;
|
|
5417
|
+
if (!before) return { model, id, row: after };
|
|
5418
|
+
const set = {};
|
|
5419
|
+
for (const [field, v] of Object.entries(after)) {
|
|
5420
|
+
if (field !== "id" && (!(field in before) || !sameValue(before[field], v))) set[field] = v;
|
|
5421
|
+
}
|
|
5422
|
+
const unset = Object.keys(before).filter((field) => !(field in after));
|
|
5423
|
+
const hasSet = Object.keys(set).length > 0;
|
|
5424
|
+
if (!hasSet && !unset.length) return null;
|
|
5425
|
+
return { model, id, ...hasSet ? { set } : {}, ...unset.length ? { unset } : {} };
|
|
5426
|
+
}
|
|
5283
5427
|
function plainRowAfter(row, m) {
|
|
5284
5428
|
if (m.kind === "delete") return null;
|
|
5285
5429
|
const prior = m.kind === "create" ? { id: m.id } : row;
|
|
@@ -5513,11 +5657,12 @@ function checkOptions(options) {
|
|
|
5513
5657
|
throw new AggregateOptionsError("options.limit must be a positive integer");
|
|
5514
5658
|
}
|
|
5515
5659
|
}
|
|
5516
|
-
function orderAndLimit(options, sortSql) {
|
|
5660
|
+
function orderAndLimit(options, sortSql, tieBreak = null) {
|
|
5517
5661
|
let sql = "";
|
|
5518
5662
|
if (options.sort) {
|
|
5519
5663
|
const direction = options.sort.direction === 1 ? "ASC" : "DESC";
|
|
5520
5664
|
sql += ` ORDER BY ${sortSql(options.sort.field)} ${direction}`;
|
|
5665
|
+
if (tieBreak !== null) sql += `, ${tieBreak} ASC`;
|
|
5521
5666
|
}
|
|
5522
5667
|
if (options.limit) {
|
|
5523
5668
|
sql += ` LIMIT ${Number(options.limit)}`;
|
|
@@ -5566,9 +5711,10 @@ function buildAggregate(source, options) {
|
|
|
5566
5711
|
const joinParams = joined.flatMap((entry) => entry.joinParams);
|
|
5567
5712
|
const base = source.baseConditions();
|
|
5568
5713
|
const scope = source.documentConditions(options.documents);
|
|
5714
|
+
const reserved = joined.reduce((n, entry) => n + (entry.reservedParams ?? 0), 0);
|
|
5569
5715
|
const translated = source.filterSql(
|
|
5570
5716
|
filter,
|
|
5571
|
-
selectParams.length + joinParams.length + base.params.length + scope.params.length
|
|
5717
|
+
selectParams.length + joinParams.length + reserved + base.params.length + scope.params.length
|
|
5572
5718
|
);
|
|
5573
5719
|
const conditions = [...base.sql, ...translated.sql ? [translated.sql] : [], ...scope.sql];
|
|
5574
5720
|
const group = [...plainSql, ...periodSql, ...joined.map((entry) => entry.group)];
|
|
@@ -5601,7 +5747,10 @@ function buildAggregate(source, options) {
|
|
|
5601
5747
|
}
|
|
5602
5748
|
function facetPlan(source, options, field, filter) {
|
|
5603
5749
|
const { groupBy, operations } = options;
|
|
5604
|
-
const facet = source.facet(field
|
|
5750
|
+
const facet = source.facet(field, {
|
|
5751
|
+
filtered: Object.keys(filter).length > 0,
|
|
5752
|
+
readsRecords: source.facetOperations === "all" && operations.some((operation) => operation.type !== "count")
|
|
5753
|
+
});
|
|
5605
5754
|
const selected = source.facetOperations === "all" ? operations.map((operation) => source.operationSql(operation, true)) : [source.operationSql({ type: "count" }, true)];
|
|
5606
5755
|
const scope = source.documentConditions(options.documents);
|
|
5607
5756
|
const translated = source.filterSql(filter, facet.params.length + scope.params.length);
|
|
@@ -5609,6 +5758,8 @@ function facetPlan(source, options, field, filter) {
|
|
|
5609
5758
|
let sql = `SELECT ${facet.value} AS ${quoteIdentifier("group_key")}, ${selected.join(", ")} FROM ${facet.from}`;
|
|
5610
5759
|
sql += where(conditions);
|
|
5611
5760
|
sql += ` GROUP BY ${facet.value}`;
|
|
5761
|
+
const sortsByMember = options.sort?.field === field && source.facetSortsByMember;
|
|
5762
|
+
const tieBreak = source.facetTiesByMember && !sortsByMember ? facet.value : null;
|
|
5612
5763
|
sql += orderAndLimit(options, (sortField) => {
|
|
5613
5764
|
if (sortField === "count") return "COUNT(*)";
|
|
5614
5765
|
if (operations.some((operation) => aggregationOperationKey(operation) === sortField)) {
|
|
@@ -5616,7 +5767,7 @@ function facetPlan(source, options, field, filter) {
|
|
|
5616
5767
|
}
|
|
5617
5768
|
if (sortField === field && source.facetSortsByMember) return facet.value;
|
|
5618
5769
|
return quoteIdentifier(sortField);
|
|
5619
|
-
});
|
|
5770
|
+
}, tieBreak);
|
|
5620
5771
|
const layout = { facetField: field, plainFields: [], periodLevels: [], memberships: [] };
|
|
5621
5772
|
return {
|
|
5622
5773
|
sql,
|
|
@@ -6951,6 +7102,18 @@ function stagedForRead(ormContext, store, model, id) {
|
|
|
6951
7102
|
const group = activeRecordLogTransactions.get(ormContext) ?? (unbound && unbound.owner === ormContext ? unbound : null);
|
|
6952
7103
|
return group?.staged(store, model, id);
|
|
6953
7104
|
}
|
|
7105
|
+
function refusalRecords(error) {
|
|
7106
|
+
const { conflicting, current } = error.details ?? {};
|
|
7107
|
+
return {
|
|
7108
|
+
...conflicting ? { conflictingRecord: { model: conflicting.model, id: conflicting.id } } : {},
|
|
7109
|
+
...current ? { current } : {}
|
|
7110
|
+
};
|
|
7111
|
+
}
|
|
7112
|
+
function declaredTypeOf(store) {
|
|
7113
|
+
const models = store.declaredTypes();
|
|
7114
|
+
const name = store.marks().db3Type?.name;
|
|
7115
|
+
return models && name ? { name, models } : null;
|
|
7116
|
+
}
|
|
6954
7117
|
function recordLogTransactionOf(ormContext) {
|
|
6955
7118
|
const bound = activeRecordLogTransactions.get(ormContext);
|
|
6956
7119
|
if (bound) return bound;
|
|
@@ -6988,6 +7151,7 @@ var init_BaseModel = __esm({
|
|
|
6988
7151
|
init_fieldCoercion();
|
|
6989
7152
|
init_OrmContext();
|
|
6990
7153
|
init_write();
|
|
7154
|
+
init_declared_types();
|
|
6991
7155
|
init_types();
|
|
6992
7156
|
init_guess();
|
|
6993
7157
|
init_types2();
|
|
@@ -7083,6 +7247,7 @@ var init_BaseModel = __esm({
|
|
|
7083
7247
|
try {
|
|
7084
7248
|
for (const entry of entries) {
|
|
7085
7249
|
assertRecordLogEntry(store.docId, entry.mutations, report, entry.upsertOn ? { upsertOn: entry.upsertOn } : {});
|
|
7250
|
+
assertRecordLogDeclaredTypes(store.docId, entry.mutations, declaredTypeOf(store), report);
|
|
7086
7251
|
}
|
|
7087
7252
|
seqs = await store.trackLocalWrite(
|
|
7088
7253
|
() => store.run("transaction", async (ops) => {
|
|
@@ -7096,6 +7261,7 @@ var init_BaseModel = __esm({
|
|
|
7096
7261
|
model: mutations[0].model,
|
|
7097
7262
|
recordId: mutations[0].id,
|
|
7098
7263
|
error,
|
|
7264
|
+
...refusalRecords(error),
|
|
7099
7265
|
writes: mutations.map((m) => ({
|
|
7100
7266
|
model: m.model,
|
|
7101
7267
|
recordId: m.id,
|
|
@@ -9807,7 +9973,8 @@ var init_BaseModel = __esm({
|
|
|
9807
9973
|
for (const [field, value] of Object.entries(dataToSave)) {
|
|
9808
9974
|
if (value !== void 0) postMutation[field] = value;
|
|
9809
9975
|
}
|
|
9810
|
-
|
|
9976
|
+
const selfJudged = store.marks().localOnly === true;
|
|
9977
|
+
for (const constraint of selfJudged ? [] : schema.resolvedUniqueConstraints) {
|
|
9811
9978
|
if (!store.constraintInForce(constraint.name)) continue;
|
|
9812
9979
|
const values = constraint.fields.map((field) => postMutation[field]);
|
|
9813
9980
|
if (values.some((value) => value === void 0 || value === null)) continue;
|
|
@@ -9845,6 +10012,7 @@ var init_BaseModel = __esm({
|
|
|
9845
10012
|
};
|
|
9846
10013
|
const entryUpsertOn = upsertOn ?? (upsertOnField !== null && guards.ifNotExists ? upsertOnField : void 0);
|
|
9847
10014
|
assertRecordLogEntry(docId, [mutation], report, entryUpsertOn !== void 0 ? { upsertOn: entryUpsertOn } : {});
|
|
10015
|
+
if (!transaction) assertRecordLogDeclaredTypes(docId, [mutation], declaredTypeOf(store), report);
|
|
9848
10016
|
this._format2Row = store.entryFor(modelName, this.id);
|
|
9849
10017
|
if (transaction) {
|
|
9850
10018
|
stagedEntry = transaction.add(store, { mutation, upsertOn, instance: this, existing });
|
|
@@ -9861,6 +10029,7 @@ var init_BaseModel = __esm({
|
|
|
9861
10029
|
model: modelName,
|
|
9862
10030
|
recordId: this.id,
|
|
9863
10031
|
error,
|
|
10032
|
+
...refusalRecords(error),
|
|
9864
10033
|
writes: [
|
|
9865
10034
|
{
|
|
9866
10035
|
model: modelName,
|
|
@@ -9918,6 +10087,7 @@ var init_BaseModel = __esm({
|
|
|
9918
10087
|
model: modelName,
|
|
9919
10088
|
recordId: this.id,
|
|
9920
10089
|
error,
|
|
10090
|
+
...refusalRecords(error),
|
|
9921
10091
|
writes: [{ model: modelName, recordId: this.id, kind: "delete", seq: 0 }]
|
|
9922
10092
|
});
|
|
9923
10093
|
}
|
|
@@ -9984,6 +10154,7 @@ var init_BaseModel = __esm({
|
|
|
9984
10154
|
await store.trackLocalWrite(
|
|
9985
10155
|
() => store.run("increment", async (ops) => {
|
|
9986
10156
|
assertRecordLogEntry(docId, [mutation], report);
|
|
10157
|
+
if (!transaction) assertRecordLogDeclaredTypes(docId, [mutation], declaredTypeOf(store), report);
|
|
9987
10158
|
const viewRow = await ops.read(modelName, id);
|
|
9988
10159
|
const staged = transaction?.staged(store, modelName, id);
|
|
9989
10160
|
const existing = staged === void 0 ? viewRow : staged;
|
|
@@ -10009,7 +10180,7 @@ var init_BaseModel = __esm({
|
|
|
10009
10180
|
if (result && "entry" in result) seq = result.entry.seq;
|
|
10010
10181
|
} catch (error) {
|
|
10011
10182
|
if (error instanceof RecordLogWriteRefusedError) {
|
|
10012
|
-
report({ documentId: docId, model: modelName, recordId: id, error, writes: [write] });
|
|
10183
|
+
report({ documentId: docId, model: modelName, recordId: id, error, ...refusalRecords(error), writes: [write] });
|
|
10013
10184
|
}
|
|
10014
10185
|
throw error;
|
|
10015
10186
|
}
|
|
@@ -11441,7 +11612,10 @@ var init_BaseModel = __esm({
|
|
|
11441
11612
|
/**
|
|
11442
11613
|
* Execute a callback with automatic transaction handling for all modified
|
|
11443
11614
|
* models. On a db3 the saves made inside land as one entry per db3, or one
|
|
11444
|
-
* per record with `options.atomic` set to `false`.
|
|
11615
|
+
* per record with `options.atomic` set to `false`. "Atomic" describes that
|
|
11616
|
+
* entry: the room applies it whole or refuses it whole. It does not undo
|
|
11617
|
+
* the callback itself — if the callback throws, the saves it already made
|
|
11618
|
+
* still land, and the error is rethrown after.
|
|
11445
11619
|
*/
|
|
11446
11620
|
static async withTransaction(callback, options) {
|
|
11447
11621
|
const modifiedModels = /* @__PURE__ */ new Set();
|
|
@@ -11814,6 +11988,7 @@ __export(browser_exports, {
|
|
|
11814
11988
|
RecordLogClient: () => RecordLogClient,
|
|
11815
11989
|
RecordLogDocumentBinding: () => RecordLogDocumentBinding,
|
|
11816
11990
|
RecordLogDocumentSession: () => RecordLogDocumentSession,
|
|
11991
|
+
RecordLogLocalIndexError: () => RecordLogLocalIndexError,
|
|
11817
11992
|
RecordLogRecords: () => RecordLogRecords,
|
|
11818
11993
|
RecordLogSender: () => RecordLogSender,
|
|
11819
11994
|
RecordLogSessions: () => RecordLogSessions,
|
|
@@ -11837,6 +12012,7 @@ __export(browser_exports, {
|
|
|
11837
12012
|
aggregateViewRows: () => aggregateViewRows,
|
|
11838
12013
|
applyChange: () => applyChange,
|
|
11839
12014
|
applyGuess: () => applyGuess,
|
|
12015
|
+
assertRecordLogDeclaredTypes: () => assertRecordLogDeclaredTypes,
|
|
11840
12016
|
assertRecordLogEntry: () => assertRecordLogEntry,
|
|
11841
12017
|
assertRecordLogRecordInput: () => assertRecordLogRecordInput,
|
|
11842
12018
|
assertRecordLogWriteAllowed: () => assertRecordLogWriteAllowed,
|
|
@@ -11853,6 +12029,7 @@ __export(browser_exports, {
|
|
|
11853
12029
|
conditionProblem: () => conditionProblem,
|
|
11854
12030
|
countViewRows: () => countViewRows,
|
|
11855
12031
|
db3ViewTranslator: () => db3ViewTranslator,
|
|
12032
|
+
declaredTypeProblem: () => declaredTypeProblem,
|
|
11856
12033
|
decodeRecordLogChunk: () => decodeRecordLogChunk,
|
|
11857
12034
|
decodeRecordLogError: () => decodeRecordLogError,
|
|
11858
12035
|
defineModelSchema: () => defineModelSchema,
|
|
@@ -11881,6 +12058,8 @@ __export(browser_exports, {
|
|
|
11881
12058
|
isRecordLogStoreResponse: () => isRecordLogStoreResponse,
|
|
11882
12059
|
lineBytes: () => lineBytes,
|
|
11883
12060
|
loadSchemaFromTomlString: () => loadSchemaFromTomlString,
|
|
12061
|
+
localConstraints: () => localConstraints,
|
|
12062
|
+
localIndexList: () => localIndexList,
|
|
11884
12063
|
omitStringsetConstraints: () => omitStringsetConstraints,
|
|
11885
12064
|
parseSnapshotChunkPath: () => parseSnapshotChunkPath,
|
|
11886
12065
|
planRecordLogDelete: () => planRecordLogDelete,
|
|
@@ -12502,7 +12681,8 @@ async function guardedLoadSqlJs(locateFile) {
|
|
|
12502
12681
|
});
|
|
12503
12682
|
try {
|
|
12504
12683
|
const initPromise = (0, import_sql10.default)({
|
|
12505
|
-
|
|
12684
|
+
// Whatever the build calls its wasm, it is the `sql-wasm.wasm` resolved above.
|
|
12685
|
+
locateFile: (file) => file.endsWith(".wasm") ? wasmPath : locateFile(file),
|
|
12506
12686
|
// Layer 1: emscripten onAbort.
|
|
12507
12687
|
onAbort: (reason) => abortReject?.(
|
|
12508
12688
|
isLinkError(reason) ? recordMismatch(reason) : toError(reason)
|
|
@@ -13548,6 +13728,9 @@ function dispatchRecordLogStoreCommand(store, command) {
|
|
|
13548
13728
|
case "findIdByFields":
|
|
13549
13729
|
value = store.findIdByFields(c.model, c.fields, c.values);
|
|
13550
13730
|
break;
|
|
13731
|
+
case "duplicateKeys":
|
|
13732
|
+
value = store.duplicateKeys(c.model, c.fields, c.limit);
|
|
13733
|
+
break;
|
|
13551
13734
|
case "queryView":
|
|
13552
13735
|
value = store.queryView(c.model, c.filter, c.options);
|
|
13553
13736
|
break;
|
|
@@ -13605,6 +13788,9 @@ function dispatchRecordLogStoreCommand(store, command) {
|
|
|
13605
13788
|
case "setState":
|
|
13606
13789
|
value = store.setState(c);
|
|
13607
13790
|
break;
|
|
13791
|
+
case "changeLocalIndexes":
|
|
13792
|
+
value = store.changeLocalIndexes(c);
|
|
13793
|
+
break;
|
|
13608
13794
|
default: {
|
|
13609
13795
|
const unknown = c;
|
|
13610
13796
|
throw new Error(`Unknown record-log store command ${JSON.stringify(unknown?.kind)}`);
|
|
@@ -13634,15 +13820,54 @@ function changedModelsOf(reply) {
|
|
|
13634
13820
|
|
|
13635
13821
|
// src/record-log-client/store.ts
|
|
13636
13822
|
var import_ulid3 = require("ulid");
|
|
13637
|
-
|
|
13823
|
+
|
|
13824
|
+
// src/record-log/constraints.ts
|
|
13825
|
+
function constraintKey(row, fields) {
|
|
13826
|
+
const values = fields.map((field) => row[field]);
|
|
13827
|
+
return values.some((v) => v === void 0 || v === null) ? null : values;
|
|
13828
|
+
}
|
|
13829
|
+
function checkConstraints(trial, touched, constraints) {
|
|
13830
|
+
const rows = touched.map((key) => ({ key, row: trial.row(key) }));
|
|
13831
|
+
for (const constraint of constraints) {
|
|
13832
|
+
const mine = rows.filter(
|
|
13833
|
+
(x) => x.row !== null && x.key.model === constraint.model
|
|
13834
|
+
);
|
|
13835
|
+
if (!mine.length) continue;
|
|
13836
|
+
const ids = rows.filter((x) => x.key.model === constraint.model).map((x) => x.key.id);
|
|
13837
|
+
const held = /* @__PURE__ */ new Map();
|
|
13838
|
+
for (const { key, row } of mine) {
|
|
13839
|
+
const values = constraintKey(row, constraint.fields);
|
|
13840
|
+
if (values === null) continue;
|
|
13841
|
+
const text = JSON.stringify(values);
|
|
13842
|
+
const other = held.get(text);
|
|
13843
|
+
if (other) return { constraint, key: values, record: key, conflicting: other };
|
|
13844
|
+
held.set(text, key);
|
|
13845
|
+
const holder = trial.holder(constraint.model, constraint.fields, values, ids);
|
|
13846
|
+
if (holder !== null) {
|
|
13847
|
+
return {
|
|
13848
|
+
constraint,
|
|
13849
|
+
key: values,
|
|
13850
|
+
record: key,
|
|
13851
|
+
conflicting: { model: constraint.model, id: holder }
|
|
13852
|
+
};
|
|
13853
|
+
}
|
|
13854
|
+
}
|
|
13855
|
+
}
|
|
13856
|
+
return null;
|
|
13857
|
+
}
|
|
13858
|
+
|
|
13859
|
+
// src/record-log-client/store.ts
|
|
13860
|
+
init_resolve();
|
|
13861
|
+
init_results();
|
|
13638
13862
|
|
|
13639
13863
|
// src/utils/fieldLookupSql.ts
|
|
13640
13864
|
init_sql();
|
|
13865
|
+
var ID_PREDICATE = "_id IS ?";
|
|
13641
13866
|
function fieldLookupPredicates(modelName, fields) {
|
|
13642
13867
|
const literal2 = isValidIdentifier(modelName) && fields.every((f) => isValidIdentifier(f));
|
|
13643
13868
|
if (literal2) {
|
|
13644
13869
|
const predicates2 = fields.map(
|
|
13645
|
-
(field) => `json_extract(_data, '$.${field}') IS ?`
|
|
13870
|
+
(field) => field === "id" ? ID_PREDICATE : `json_extract(_data, '$.${field}') IS ?`
|
|
13646
13871
|
);
|
|
13647
13872
|
return {
|
|
13648
13873
|
where: [`_type = ${quoteStringLiteral(modelName)}`, ...predicates2].join(
|
|
@@ -13652,7 +13877,9 @@ function fieldLookupPredicates(modelName, fields) {
|
|
|
13652
13877
|
bindPaths: false
|
|
13653
13878
|
};
|
|
13654
13879
|
}
|
|
13655
|
-
const predicates = fields.map(
|
|
13880
|
+
const predicates = fields.map(
|
|
13881
|
+
(field) => field === "id" ? ID_PREDICATE : `json_extract(_data, '$.' || ?) IS ?`
|
|
13882
|
+
);
|
|
13656
13883
|
return {
|
|
13657
13884
|
where: ["_type = ?", ...predicates].join(" AND "),
|
|
13658
13885
|
bindType: true,
|
|
@@ -13662,12 +13889,60 @@ function fieldLookupPredicates(modelName, fields) {
|
|
|
13662
13889
|
function fieldLookupBindings(predicates, modelName, fields, values) {
|
|
13663
13890
|
const bindings = predicates.bindType ? [modelName] : [];
|
|
13664
13891
|
for (let i = 0; i < fields.length; i++) {
|
|
13665
|
-
if (predicates.bindPaths) bindings.push(fields[i]);
|
|
13892
|
+
if (predicates.bindPaths && fields[i] !== "id") bindings.push(fields[i]);
|
|
13666
13893
|
bindings.push(values[i]);
|
|
13667
13894
|
}
|
|
13668
13895
|
return bindings;
|
|
13669
13896
|
}
|
|
13670
13897
|
|
|
13898
|
+
// src/record-log/sql.ts
|
|
13899
|
+
init_resolve();
|
|
13900
|
+
init_results();
|
|
13901
|
+
|
|
13902
|
+
// src/record-log/state.ts
|
|
13903
|
+
init_stringSetOrder();
|
|
13904
|
+
init_types2();
|
|
13905
|
+
|
|
13906
|
+
// src/schema/JsonSchemaDDL.ts
|
|
13907
|
+
init_sql();
|
|
13908
|
+
init_sql();
|
|
13909
|
+
var DURABLE_OBJECT_SCHEMA_OPTIONS = Object.freeze({ includeDocIdColumn: false, memberShape: "keyed" });
|
|
13910
|
+
|
|
13911
|
+
// src/record-log/schema.ts
|
|
13912
|
+
var META_KEYS = Object.freeze({
|
|
13913
|
+
/** The log number the next accepted entry gets. */
|
|
13914
|
+
nextLsn: "next_lsn",
|
|
13915
|
+
/** The current epoch. */
|
|
13916
|
+
currentEpoch: "epoch_current",
|
|
13917
|
+
/** The epoch open ahead of the current one. */
|
|
13918
|
+
nextEpoch: "epoch_next",
|
|
13919
|
+
/** Epochs at or below this are frozen. */
|
|
13920
|
+
epochFloor: "epoch_floor",
|
|
13921
|
+
/** Entries whose writer had not applied the log up to this are refused. */
|
|
13922
|
+
cursorFloor: "cursor_floor",
|
|
13923
|
+
/** The bulk load in progress, as JSON, when there is one. */
|
|
13924
|
+
loadInProgress: "load_in_progress"
|
|
13925
|
+
});
|
|
13926
|
+
|
|
13927
|
+
// src/record-log/stamps.ts
|
|
13928
|
+
init_types2();
|
|
13929
|
+
init_stringSetOrder();
|
|
13930
|
+
|
|
13931
|
+
// src/record-log/sql.ts
|
|
13932
|
+
init_types2();
|
|
13933
|
+
function jsonData(column = "_data") {
|
|
13934
|
+
return `json(${column}) AS _data`;
|
|
13935
|
+
}
|
|
13936
|
+
function rowWithId(id, row) {
|
|
13937
|
+
if (Object.prototype.hasOwnProperty.call(row, "id")) return row;
|
|
13938
|
+
return { id, ...row };
|
|
13939
|
+
}
|
|
13940
|
+
var SELECT_ROW = `SELECT ${jsonData()}, _stamps, _dead, _lsn FROM records WHERE _type = ? AND _id = ?`;
|
|
13941
|
+
|
|
13942
|
+
// src/record-log-client/store.ts
|
|
13943
|
+
init_types2();
|
|
13944
|
+
init_condition();
|
|
13945
|
+
|
|
13671
13946
|
// src/record-log-client/viewReader.ts
|
|
13672
13947
|
init_aggregateBuilder();
|
|
13673
13948
|
init_CursorManager();
|
|
@@ -14035,6 +14310,7 @@ function db3ViewTranslator(model, options = {}) {
|
|
|
14035
14310
|
table: "record_log_view",
|
|
14036
14311
|
documentColumn: DOCUMENT_COLUMN,
|
|
14037
14312
|
stringSets: "json_each",
|
|
14313
|
+
jsonbData: true,
|
|
14038
14314
|
...options.document !== void 0 ? { baseConditions: [`${DOCUMENT_COLUMN} = ${sqlText2(options.document)}`] } : {},
|
|
14039
14315
|
...options.tieBreak ? { tieBreakFields: [DOCUMENT_COLUMN] } : {}
|
|
14040
14316
|
});
|
|
@@ -14112,7 +14388,7 @@ function readViewPage(sql, model, filter, options, limits = {}) {
|
|
|
14112
14388
|
row = stripCursorSortValues(parsed, aliased);
|
|
14113
14389
|
if (excluding) row = applyIncludeProjection(row, selected);
|
|
14114
14390
|
} else {
|
|
14115
|
-
row = JSON.parse(String(columns._data));
|
|
14391
|
+
row = rowWithId(String(columns._id), JSON.parse(String(columns._data)));
|
|
14116
14392
|
mint = row;
|
|
14117
14393
|
}
|
|
14118
14394
|
row = canonicalSets(row, setFields);
|
|
@@ -14275,6 +14551,7 @@ function syncRecordLogIndexes(sql, docId, indexes) {
|
|
|
14275
14551
|
if (indexes) {
|
|
14276
14552
|
sql.exec(`DELETE FROM record_log_indexes WHERE doc_id = ?`, docId);
|
|
14277
14553
|
for (const entry of indexes) {
|
|
14554
|
+
if (entry.members === true) continue;
|
|
14278
14555
|
const refusal = usable(entry);
|
|
14279
14556
|
if (refusal) {
|
|
14280
14557
|
Logger.warn(`[record-log] ${docId}: index '${entry.name}' skipped: ${refusal}; queries on it scan.`);
|
|
@@ -15183,103 +15460,6 @@ init_guess();
|
|
|
15183
15460
|
|
|
15184
15461
|
// src/record-log-client/maintenance.ts
|
|
15185
15462
|
init_logger();
|
|
15186
|
-
function storedDocuments(sql) {
|
|
15187
|
-
const documents = /* @__PURE__ */ new Set();
|
|
15188
|
-
try {
|
|
15189
|
-
for (const row of sql.exec(
|
|
15190
|
-
`SELECT doc_id FROM record_log_state UNION SELECT doc_id FROM record_log_pending`
|
|
15191
|
-
)) {
|
|
15192
|
-
documents.add(String(row.doc_id));
|
|
15193
|
-
}
|
|
15194
|
-
} catch {
|
|
15195
|
-
}
|
|
15196
|
-
return Array.from(documents);
|
|
15197
|
-
}
|
|
15198
|
-
function purgeDocumentQueryRows(sql, docId) {
|
|
15199
|
-
const tables = Array.from(
|
|
15200
|
-
sql.exec("SELECT name FROM sqlite_master WHERE type = 'table'")
|
|
15201
|
-
).map((row) => String(row.name));
|
|
15202
|
-
const columnsOf = /* @__PURE__ */ new Map();
|
|
15203
|
-
for (const table of tables) {
|
|
15204
|
-
let columns = [];
|
|
15205
|
-
try {
|
|
15206
|
-
columns = Array.from(sql.exec(`PRAGMA table_info(${quote(table)})`)).map((row) => String(row.name));
|
|
15207
|
-
} catch {
|
|
15208
|
-
}
|
|
15209
|
-
columnsOf.set(table, columns);
|
|
15210
|
-
}
|
|
15211
|
-
const derived = tables.filter((table) => columnsOf.get(table).includes("_meta_doc_id"));
|
|
15212
|
-
for (const parent of derived) {
|
|
15213
|
-
for (const junction of legacyJunctionsOf(parent, tables, columnsOf)) {
|
|
15214
|
-
sql.exec(
|
|
15215
|
-
`DELETE FROM ${quote(junction.table)} WHERE ${quote(junction.foreignKey)} IN (SELECT "id" FROM ${quote(parent)} WHERE "_meta_doc_id" = ?)`,
|
|
15216
|
-
docId
|
|
15217
|
-
);
|
|
15218
|
-
sql.exec(
|
|
15219
|
-
`DELETE FROM ${quote(junction.table)} WHERE ${quote(junction.foreignKey)} NOT IN (SELECT "id" FROM ${quote(parent)})`
|
|
15220
|
-
);
|
|
15221
|
-
}
|
|
15222
|
-
}
|
|
15223
|
-
for (const parent of derived) {
|
|
15224
|
-
sql.exec(`DELETE FROM ${quote(parent)} WHERE "_meta_doc_id" = ?`, docId);
|
|
15225
|
-
}
|
|
15226
|
-
}
|
|
15227
|
-
var RECORD_LOG_STORAGE_VERSION = 2;
|
|
15228
|
-
function migrateRecordLogStore(sql, options) {
|
|
15229
|
-
let current = 1;
|
|
15230
|
-
try {
|
|
15231
|
-
const [row] = Array.from(sql.exec(`SELECT value FROM record_log_meta WHERE key = 'storage_version'`));
|
|
15232
|
-
if (row) current = Number(row.value);
|
|
15233
|
-
} catch {
|
|
15234
|
-
}
|
|
15235
|
-
if (current >= RECORD_LOG_STORAGE_VERSION) return { migrated: false };
|
|
15236
|
-
sql.transaction(() => {
|
|
15237
|
-
for (const docId of storedDocuments(sql)) purgeDocumentQueryRows(sql, docId);
|
|
15238
|
-
if (options.db3Only) dropDocumentQueryTables(sql);
|
|
15239
|
-
sql.exec(`DROP TABLE IF EXISTS record_log_projection`);
|
|
15240
|
-
for (const row of Array.from(
|
|
15241
|
-
sql.exec(
|
|
15242
|
-
`SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'record_log_view' AND (name LIKE 'idx\\_record\\_log\\_view\\_f%' ESCAPE '\\' OR name LIKE 'idx\\_record\\_log\\_view\\_u%' ESCAPE '\\')`
|
|
15243
|
-
)
|
|
15244
|
-
)) {
|
|
15245
|
-
sql.exec(`DROP INDEX IF EXISTS ${quote(String(row.name))}`);
|
|
15246
|
-
}
|
|
15247
|
-
sql.exec(`CREATE TABLE IF NOT EXISTS record_log_meta (key TEXT PRIMARY KEY, value TEXT)`);
|
|
15248
|
-
sql.exec(
|
|
15249
|
-
`INSERT INTO record_log_meta (key, value) VALUES ('storage_version', ?)
|
|
15250
|
-
ON CONFLICT (key) DO UPDATE SET value = excluded.value`,
|
|
15251
|
-
String(RECORD_LOG_STORAGE_VERSION)
|
|
15252
|
-
);
|
|
15253
|
-
});
|
|
15254
|
-
Logger.info(`[record-log] the local store was migrated to storage version ${RECORD_LOG_STORAGE_VERSION} (db3 query tables ${options.db3Only ? "dropped" : "emptied of db3 rows"}).`);
|
|
15255
|
-
return { migrated: true };
|
|
15256
|
-
}
|
|
15257
|
-
function dropDocumentQueryTables(sql) {
|
|
15258
|
-
const tables = Array.from(sql.exec("SELECT name FROM sqlite_master WHERE type = 'table'")).map((row) => String(row.name));
|
|
15259
|
-
const columnsOf = /* @__PURE__ */ new Map();
|
|
15260
|
-
for (const table of tables) {
|
|
15261
|
-
let columns = [];
|
|
15262
|
-
try {
|
|
15263
|
-
columns = Array.from(sql.exec(`PRAGMA table_info(${quote(table)})`)).map((row) => String(row.name));
|
|
15264
|
-
} catch {
|
|
15265
|
-
}
|
|
15266
|
-
columnsOf.set(table, columns);
|
|
15267
|
-
}
|
|
15268
|
-
const derived = tables.filter((table) => columnsOf.get(table).includes("_meta_doc_id"));
|
|
15269
|
-
const junctions = derived.flatMap((parent) => legacyJunctionsOf(parent, tables, columnsOf).map((j) => j.table));
|
|
15270
|
-
for (const table of /* @__PURE__ */ new Set([...junctions, ...derived])) sql.exec(`DROP TABLE IF EXISTS ${quote(table)}`);
|
|
15271
|
-
}
|
|
15272
|
-
function legacyJunctionsOf(parent, tables, columnsOf) {
|
|
15273
|
-
const model = parent.startsWith("model_") ? parent.slice("model_".length) : parent;
|
|
15274
|
-
const foreignKey = `${model}_id`;
|
|
15275
|
-
return tables.filter((table) => table.startsWith(`${parent}_`)).filter((table) => {
|
|
15276
|
-
const columns = columnsOf.get(table) ?? [];
|
|
15277
|
-
return columns.includes("value") && !columns.includes("_meta_doc_id") && columns.includes(foreignKey);
|
|
15278
|
-
}).map((table) => ({ table, foreignKey }));
|
|
15279
|
-
}
|
|
15280
|
-
function quote(identifier) {
|
|
15281
|
-
return `"${identifier.replace(/"/g, '""')}"`;
|
|
15282
|
-
}
|
|
15283
15463
|
|
|
15284
15464
|
// src/record-log-client/schema.ts
|
|
15285
15465
|
var RECORD_LOG_CLIENT_TABLES = Object.freeze([
|
|
@@ -15326,7 +15506,11 @@ function recordLogClientDDL() {
|
|
|
15326
15506
|
replacing INTEGER,
|
|
15327
15507
|
receipt TEXT,
|
|
15328
15508
|
segment TEXT,
|
|
15329
|
-
staged INTEGER
|
|
15509
|
+
staged INTEGER,
|
|
15510
|
+
typed TEXT,
|
|
15511
|
+
db3_type TEXT,
|
|
15512
|
+
local_only INTEGER NOT NULL DEFAULT 0,
|
|
15513
|
+
local_indexes TEXT
|
|
15330
15514
|
)`,
|
|
15331
15515
|
`CREATE TABLE IF NOT EXISTS record_log_writers (
|
|
15332
15516
|
doc_id TEXT NOT NULL,
|
|
@@ -15417,69 +15601,247 @@ function recordLogClientDDL() {
|
|
|
15417
15601
|
)`
|
|
15418
15602
|
];
|
|
15419
15603
|
}
|
|
15604
|
+
var RECORD_LOG_LOCAL_ONLY_COLUMNS = Object.freeze([
|
|
15605
|
+
{
|
|
15606
|
+
table: "record_log_state",
|
|
15607
|
+
column: "local_only",
|
|
15608
|
+
add: `ALTER TABLE record_log_state ADD COLUMN local_only INTEGER NOT NULL DEFAULT 0`
|
|
15609
|
+
},
|
|
15610
|
+
{ table: "record_log_state", column: "local_indexes", add: `ALTER TABLE record_log_state ADD COLUMN local_indexes TEXT` }
|
|
15611
|
+
]);
|
|
15420
15612
|
var RECORD_LOG_CLIENT_ADDED_COLUMNS = Object.freeze([
|
|
15421
15613
|
{ table: "record_log_state", column: "receipt", add: `ALTER TABLE record_log_state ADD COLUMN receipt TEXT` },
|
|
15422
15614
|
{ table: "record_log_state", column: "segment", add: `ALTER TABLE record_log_state ADD COLUMN segment TEXT` },
|
|
15423
|
-
{ table: "record_log_state", column: "staged", add: `ALTER TABLE record_log_state ADD COLUMN staged INTEGER` }
|
|
15615
|
+
{ table: "record_log_state", column: "staged", add: `ALTER TABLE record_log_state ADD COLUMN staged INTEGER` },
|
|
15616
|
+
{ table: "record_log_state", column: "typed", add: `ALTER TABLE record_log_state ADD COLUMN typed TEXT` },
|
|
15617
|
+
{ table: "record_log_state", column: "db3_type", add: `ALTER TABLE record_log_state ADD COLUMN db3_type TEXT` },
|
|
15618
|
+
...RECORD_LOG_LOCAL_ONLY_COLUMNS
|
|
15424
15619
|
]);
|
|
15425
15620
|
function recordLogFieldIndexName(kind, model, name, table = "view") {
|
|
15426
15621
|
const tag = kind === "field" ? "f" : "u";
|
|
15427
15622
|
return `idx_record_log_${table}_${tag}${model.length}_${model.toLowerCase()}_${name.toLowerCase()}`;
|
|
15428
15623
|
}
|
|
15429
15624
|
|
|
15430
|
-
// src/record-log-client/
|
|
15431
|
-
|
|
15432
|
-
|
|
15433
|
-
|
|
15434
|
-
|
|
15435
|
-
|
|
15436
|
-
|
|
15437
|
-
|
|
15438
|
-
|
|
15439
|
-
|
|
15440
|
-
h2 = Math.imul(h2 ^ c, 1597334677);
|
|
15625
|
+
// src/record-log-client/maintenance.ts
|
|
15626
|
+
function storedDocuments(sql) {
|
|
15627
|
+
const documents = /* @__PURE__ */ new Set();
|
|
15628
|
+
try {
|
|
15629
|
+
for (const row of sql.exec(
|
|
15630
|
+
`SELECT doc_id FROM record_log_state UNION SELECT doc_id FROM record_log_pending`
|
|
15631
|
+
)) {
|
|
15632
|
+
documents.add(String(row.doc_id));
|
|
15633
|
+
}
|
|
15634
|
+
} catch {
|
|
15441
15635
|
}
|
|
15442
|
-
|
|
15443
|
-
h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
|
|
15444
|
-
return `${text.length}:${(4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36)}`;
|
|
15445
|
-
}
|
|
15446
|
-
var keyText2 = (key) => recordKeyString(key);
|
|
15447
|
-
function latestReceipt(state) {
|
|
15448
|
-
const last = state?.attempts[state.attempts.length - 1];
|
|
15449
|
-
return last ? { kind: last.kind, id: last.id } : null;
|
|
15450
|
-
}
|
|
15451
|
-
var RECORD_LOG_HELD_WARN = 1e4;
|
|
15452
|
-
var GUESS_HELD = 2 ** 50;
|
|
15453
|
-
var GUESS_CREATED = 2 ** 51;
|
|
15454
|
-
var parseKey = (text) => {
|
|
15455
|
-
const at = text.indexOf("\0");
|
|
15456
|
-
return { model: text.slice(0, at), id: text.slice(at + 1) };
|
|
15457
|
-
};
|
|
15458
|
-
function lookupBinding(value) {
|
|
15459
|
-
if (value === void 0 || value === null) return null;
|
|
15460
|
-
if (typeof value === "boolean") return value ? 1 : 0;
|
|
15461
|
-
if (typeof value === "number") return value;
|
|
15462
|
-
return String(value);
|
|
15463
|
-
}
|
|
15464
|
-
function writtenValue(value) {
|
|
15465
|
-
if (typeof value === "boolean") return value ? 1 : 0;
|
|
15466
|
-
if (typeof value === "number" || typeof value === "string") return value;
|
|
15467
|
-
return JSON.stringify(value);
|
|
15468
|
-
}
|
|
15469
|
-
function rowsOf2(sql, query, ...bindings) {
|
|
15470
|
-
return Array.from(sql.exec(query, ...bindings));
|
|
15471
|
-
}
|
|
15472
|
-
function pendingRow(row) {
|
|
15473
|
-
const entry = JSON.parse(String(row.entry));
|
|
15474
|
-
if (row.acked !== null && row.acked !== void 0) entry.acked = Number(row.acked);
|
|
15475
|
-
return entry;
|
|
15636
|
+
return Array.from(documents);
|
|
15476
15637
|
}
|
|
15477
|
-
|
|
15478
|
-
|
|
15479
|
-
|
|
15480
|
-
|
|
15638
|
+
function purgeDocumentQueryRows(sql, docId) {
|
|
15639
|
+
const tables = Array.from(
|
|
15640
|
+
sql.exec("SELECT name FROM sqlite_master WHERE type = 'table'")
|
|
15641
|
+
).map((row) => String(row.name));
|
|
15642
|
+
const columnsOf = /* @__PURE__ */ new Map();
|
|
15643
|
+
for (const table of tables) {
|
|
15644
|
+
let columns = [];
|
|
15645
|
+
try {
|
|
15646
|
+
columns = Array.from(sql.exec(`PRAGMA table_info(${quote(table)})`)).map((row) => String(row.name));
|
|
15647
|
+
} catch {
|
|
15648
|
+
}
|
|
15649
|
+
columnsOf.set(table, columns);
|
|
15481
15650
|
}
|
|
15482
|
-
|
|
15651
|
+
const derived = tables.filter((table) => columnsOf.get(table).includes("_meta_doc_id"));
|
|
15652
|
+
for (const parent of derived) {
|
|
15653
|
+
for (const junction of legacyJunctionsOf(parent, tables, columnsOf)) {
|
|
15654
|
+
sql.exec(
|
|
15655
|
+
`DELETE FROM ${quote(junction.table)} WHERE ${quote(junction.foreignKey)} IN (SELECT "id" FROM ${quote(parent)} WHERE "_meta_doc_id" = ?)`,
|
|
15656
|
+
docId
|
|
15657
|
+
);
|
|
15658
|
+
sql.exec(
|
|
15659
|
+
`DELETE FROM ${quote(junction.table)} WHERE ${quote(junction.foreignKey)} NOT IN (SELECT "id" FROM ${quote(parent)})`
|
|
15660
|
+
);
|
|
15661
|
+
}
|
|
15662
|
+
}
|
|
15663
|
+
for (const parent of derived) {
|
|
15664
|
+
sql.exec(`DELETE FROM ${quote(parent)} WHERE "_meta_doc_id" = ?`, docId);
|
|
15665
|
+
}
|
|
15666
|
+
}
|
|
15667
|
+
var RECORD_LOG_STORAGE_VERSION = 4;
|
|
15668
|
+
var DATA_TABLES = ["record_log_rows", "record_log_view", "record_log_staged_base"];
|
|
15669
|
+
function migrateRecordLogStore(sql, options) {
|
|
15670
|
+
let current = 1;
|
|
15671
|
+
try {
|
|
15672
|
+
const [row] = Array.from(sql.exec(`SELECT value FROM record_log_meta WHERE key = 'storage_version'`));
|
|
15673
|
+
if (row) current = Number(row.value);
|
|
15674
|
+
} catch {
|
|
15675
|
+
}
|
|
15676
|
+
if (current >= RECORD_LOG_STORAGE_VERSION) return { migrated: false };
|
|
15677
|
+
if (current < 2) dropDb3QueryRows(sql, options);
|
|
15678
|
+
const converted = current < 3 ? convertToJsonb(sql) : null;
|
|
15679
|
+
sql.transaction(() => {
|
|
15680
|
+
addLocalOnlyColumns(sql);
|
|
15681
|
+
writeStorageVersion(sql, RECORD_LOG_STORAGE_VERSION);
|
|
15682
|
+
});
|
|
15683
|
+
converted?.report();
|
|
15684
|
+
return { migrated: true };
|
|
15685
|
+
}
|
|
15686
|
+
function addLocalOnlyColumns(sql) {
|
|
15687
|
+
const present = Array.from(sql.exec(`SELECT name FROM pragma_table_info('record_log_state')`)).map((row) => String(row.name));
|
|
15688
|
+
if (present.length === 0) return;
|
|
15689
|
+
for (const { column, add } of RECORD_LOG_LOCAL_ONLY_COLUMNS) {
|
|
15690
|
+
if (!present.includes(column)) sql.exec(add);
|
|
15691
|
+
}
|
|
15692
|
+
}
|
|
15693
|
+
function dropDb3QueryRows(sql, options) {
|
|
15694
|
+
sql.transaction(() => {
|
|
15695
|
+
for (const docId of storedDocuments(sql)) purgeDocumentQueryRows(sql, docId);
|
|
15696
|
+
if (options.db3Only) dropDocumentQueryTables(sql);
|
|
15697
|
+
sql.exec(`DROP TABLE IF EXISTS record_log_projection`);
|
|
15698
|
+
for (const row of Array.from(
|
|
15699
|
+
sql.exec(
|
|
15700
|
+
`SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'record_log_view' AND (name LIKE 'idx\\_record\\_log\\_view\\_f%' ESCAPE '\\' OR name LIKE 'idx\\_record\\_log\\_view\\_u%' ESCAPE '\\')`
|
|
15701
|
+
)
|
|
15702
|
+
)) {
|
|
15703
|
+
sql.exec(`DROP INDEX IF EXISTS ${quote(String(row.name))}`);
|
|
15704
|
+
}
|
|
15705
|
+
writeStorageVersion(sql, 2);
|
|
15706
|
+
});
|
|
15707
|
+
Logger.info(`[record-log] the local store was migrated to storage version 2 (db3 query tables ${options.db3Only ? "dropped" : "emptied of db3 rows"}).`);
|
|
15708
|
+
}
|
|
15709
|
+
function convertToJsonb(sql) {
|
|
15710
|
+
const present = new Set(
|
|
15711
|
+
Array.from(sql.exec(`SELECT name FROM sqlite_master WHERE type = 'table'`)).map((row) => String(row.name))
|
|
15712
|
+
);
|
|
15713
|
+
const tables = DATA_TABLES.filter((table) => present.has(table));
|
|
15714
|
+
const documents = (where2) => tables.length === 0 ? [] : Array.from(
|
|
15715
|
+
sql.exec(`${tables.map((table) => `SELECT doc_id FROM ${table}${where2}`).join(" UNION ")} ORDER BY doc_id`)
|
|
15716
|
+
).map((row) => String(row.doc_id));
|
|
15717
|
+
const remaining = documents(` WHERE typeof(_data) = 'text'`);
|
|
15718
|
+
const total = documents("").length;
|
|
15719
|
+
const resumed = tables.some(
|
|
15720
|
+
(table) => Array.from(sql.exec(`SELECT 1 FROM ${table} WHERE typeof(_data) = 'blob' LIMIT 1`)).length > 0
|
|
15721
|
+
);
|
|
15722
|
+
let rewritten = 0;
|
|
15723
|
+
for (const docId of remaining) {
|
|
15724
|
+
sql.transaction(() => {
|
|
15725
|
+
for (const table of tables) {
|
|
15726
|
+
sql.exec(
|
|
15727
|
+
`UPDATE ${table} SET _data = jsonb(json_remove(_data, '$.id')) WHERE doc_id = ? AND typeof(_data) = 'text'`,
|
|
15728
|
+
docId
|
|
15729
|
+
);
|
|
15730
|
+
const [changed] = Array.from(sql.exec(`SELECT changes() AS n`));
|
|
15731
|
+
rewritten += Number(changed?.n ?? 0);
|
|
15732
|
+
}
|
|
15733
|
+
});
|
|
15734
|
+
}
|
|
15735
|
+
return {
|
|
15736
|
+
report: () => {
|
|
15737
|
+
if (total === 0) return;
|
|
15738
|
+
Logger.info(
|
|
15739
|
+
`[record-log] the local store was converted to storage version 3` + (resumed ? ` (resumed: ${remaining.length} of ${total} document(s) remained)` : "") + `: ${remaining.length} document(s), ${rewritten} row(s) rewritten as JSONB without id.`
|
|
15740
|
+
);
|
|
15741
|
+
}
|
|
15742
|
+
};
|
|
15743
|
+
}
|
|
15744
|
+
function writeStorageVersion(sql, version) {
|
|
15745
|
+
sql.exec(`CREATE TABLE IF NOT EXISTS record_log_meta (key TEXT PRIMARY KEY, value TEXT)`);
|
|
15746
|
+
sql.exec(
|
|
15747
|
+
`INSERT INTO record_log_meta (key, value) VALUES ('storage_version', ?)
|
|
15748
|
+
ON CONFLICT (key) DO UPDATE SET value = excluded.value`,
|
|
15749
|
+
String(version)
|
|
15750
|
+
);
|
|
15751
|
+
}
|
|
15752
|
+
function dropDocumentQueryTables(sql) {
|
|
15753
|
+
const tables = Array.from(sql.exec("SELECT name FROM sqlite_master WHERE type = 'table'")).map((row) => String(row.name));
|
|
15754
|
+
const columnsOf = /* @__PURE__ */ new Map();
|
|
15755
|
+
for (const table of tables) {
|
|
15756
|
+
let columns = [];
|
|
15757
|
+
try {
|
|
15758
|
+
columns = Array.from(sql.exec(`PRAGMA table_info(${quote(table)})`)).map((row) => String(row.name));
|
|
15759
|
+
} catch {
|
|
15760
|
+
}
|
|
15761
|
+
columnsOf.set(table, columns);
|
|
15762
|
+
}
|
|
15763
|
+
const derived = tables.filter((table) => columnsOf.get(table).includes("_meta_doc_id"));
|
|
15764
|
+
const junctions = derived.flatMap((parent) => legacyJunctionsOf(parent, tables, columnsOf).map((j) => j.table));
|
|
15765
|
+
for (const table of /* @__PURE__ */ new Set([...junctions, ...derived])) sql.exec(`DROP TABLE IF EXISTS ${quote(table)}`);
|
|
15766
|
+
}
|
|
15767
|
+
function legacyJunctionsOf(parent, tables, columnsOf) {
|
|
15768
|
+
const model = parent.startsWith("model_") ? parent.slice("model_".length) : parent;
|
|
15769
|
+
const foreignKey = `${model}_id`;
|
|
15770
|
+
return tables.filter((table) => table.startsWith(`${parent}_`)).filter((table) => {
|
|
15771
|
+
const columns = columnsOf.get(table) ?? [];
|
|
15772
|
+
return columns.includes("value") && !columns.includes("_meta_doc_id") && columns.includes(foreignKey);
|
|
15773
|
+
}).map((table) => ({ table, foreignKey }));
|
|
15774
|
+
}
|
|
15775
|
+
function quote(identifier) {
|
|
15776
|
+
return `"${identifier.replace(/"/g, '""')}"`;
|
|
15777
|
+
}
|
|
15778
|
+
|
|
15779
|
+
// src/record-log-client/store.ts
|
|
15780
|
+
init_types();
|
|
15781
|
+
function localIndexesText(indexes) {
|
|
15782
|
+
return JSON.stringify(
|
|
15783
|
+
[...indexes].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).map(({ name, model, fields, unique, named }) => [name, model, fields, unique, named ?? null])
|
|
15784
|
+
);
|
|
15785
|
+
}
|
|
15786
|
+
function recordLogRowRevision(row) {
|
|
15787
|
+
if (row === null) return null;
|
|
15788
|
+
const text = JSON.stringify(row);
|
|
15789
|
+
let h1 = 3735928559;
|
|
15790
|
+
let h2 = 1103547991;
|
|
15791
|
+
for (let i = 0; i < text.length; i++) {
|
|
15792
|
+
const c = text.charCodeAt(i);
|
|
15793
|
+
h1 = Math.imul(h1 ^ c, 2654435761);
|
|
15794
|
+
h2 = Math.imul(h2 ^ c, 1597334677);
|
|
15795
|
+
}
|
|
15796
|
+
h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
|
|
15797
|
+
h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
|
|
15798
|
+
return `${text.length}:${(4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36)}`;
|
|
15799
|
+
}
|
|
15800
|
+
var keyText2 = (key) => recordKeyString(key);
|
|
15801
|
+
function latestReceipt(state) {
|
|
15802
|
+
const last = state?.attempts[state.attempts.length - 1];
|
|
15803
|
+
return last ? { kind: last.kind, id: last.id } : null;
|
|
15804
|
+
}
|
|
15805
|
+
var RECORD_LOG_HELD_WARN = 1e4;
|
|
15806
|
+
var GUESS_HELD = 2 ** 50;
|
|
15807
|
+
var GUESS_CREATED = 2 ** 51;
|
|
15808
|
+
var parseKey = (text) => {
|
|
15809
|
+
const at = text.indexOf("\0");
|
|
15810
|
+
return { model: text.slice(0, at), id: text.slice(at + 1) };
|
|
15811
|
+
};
|
|
15812
|
+
function lookupBinding(value) {
|
|
15813
|
+
if (value === void 0 || value === null) return null;
|
|
15814
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
15815
|
+
if (typeof value === "number") return value;
|
|
15816
|
+
return String(value);
|
|
15817
|
+
}
|
|
15818
|
+
function writtenValue(value) {
|
|
15819
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
15820
|
+
if (typeof value === "number" || typeof value === "string") return value;
|
|
15821
|
+
return JSON.stringify(value);
|
|
15822
|
+
}
|
|
15823
|
+
function storedData(row) {
|
|
15824
|
+
const { id: _id, ...fields } = row;
|
|
15825
|
+
void _id;
|
|
15826
|
+
return JSON.stringify(fields);
|
|
15827
|
+
}
|
|
15828
|
+
function storedRow(id, data) {
|
|
15829
|
+
return rowWithId(String(id), JSON.parse(String(data)));
|
|
15830
|
+
}
|
|
15831
|
+
function rowsOf2(sql, query, ...bindings) {
|
|
15832
|
+
return Array.from(sql.exec(query, ...bindings));
|
|
15833
|
+
}
|
|
15834
|
+
function pendingRow(row) {
|
|
15835
|
+
const entry = JSON.parse(String(row.entry));
|
|
15836
|
+
if (row.acked !== null && row.acked !== void 0) entry.acked = Number(row.acked);
|
|
15837
|
+
return entry;
|
|
15838
|
+
}
|
|
15839
|
+
var SqlRecordLogTables = class {
|
|
15840
|
+
constructor(sql, docId) {
|
|
15841
|
+
this.sql = sql;
|
|
15842
|
+
this.docId = docId;
|
|
15843
|
+
}
|
|
15844
|
+
/** Results ahead of the cursor; held in memory, refetched by catch-up if lost. */
|
|
15483
15845
|
held = /* @__PURE__ */ new Map();
|
|
15484
15846
|
/** Whether the held results passed {@link RECORD_LOG_HELD_WARN} since they last fell below it. */
|
|
15485
15847
|
heldWarned = false;
|
|
@@ -15533,10 +15895,64 @@ var SqlRecordLogTables = class {
|
|
|
15533
15895
|
this.ensureState();
|
|
15534
15896
|
this.sql.exec(`UPDATE record_log_state SET permission = ? WHERE doc_id = ?`, permission, this.docId);
|
|
15535
15897
|
}
|
|
15898
|
+
/** The typed mark, the type and its held declarations. */
|
|
15899
|
+
typeState() {
|
|
15900
|
+
const state = this.state();
|
|
15901
|
+
const typed = state?.typed === "yes" ? "yes" : state?.typed === "no" ? "no" : "unknown";
|
|
15902
|
+
if (typed !== "yes" || !state?.db3_type) return { typed, db3Type: null, declarations: null };
|
|
15903
|
+
try {
|
|
15904
|
+
const held = JSON.parse(String(state.db3_type));
|
|
15905
|
+
return { typed, db3Type: { name: held.name, hash: held.hash ?? null }, declarations: held.models ?? null };
|
|
15906
|
+
} catch {
|
|
15907
|
+
return { typed, db3Type: null, declarations: null };
|
|
15908
|
+
}
|
|
15909
|
+
}
|
|
15910
|
+
/**
|
|
15911
|
+
* Record what the room said of the type: untyped clears the type; typed
|
|
15912
|
+
* keeps the held declarations when the hash is theirs and none were sent.
|
|
15913
|
+
*/
|
|
15914
|
+
setType(update) {
|
|
15915
|
+
this.ensureState();
|
|
15916
|
+
if (update.typed === "no") {
|
|
15917
|
+
this.sql.exec(`UPDATE record_log_state SET typed = 'no', db3_type = NULL WHERE doc_id = ?`, this.docId);
|
|
15918
|
+
return;
|
|
15919
|
+
}
|
|
15920
|
+
const held = this.typeState();
|
|
15921
|
+
const { name, hash, models } = update.db3Type;
|
|
15922
|
+
const kept = models ?? (hash !== null && held.db3Type?.hash === hash ? held.declarations : null);
|
|
15923
|
+
this.sql.exec(
|
|
15924
|
+
`UPDATE record_log_state SET typed = 'yes', db3_type = ? WHERE doc_id = ?`,
|
|
15925
|
+
JSON.stringify({ name, hash: kept ? hash : null, models: kept }),
|
|
15926
|
+
this.docId
|
|
15927
|
+
);
|
|
15928
|
+
}
|
|
15536
15929
|
setLastCatchUpAt(at) {
|
|
15537
15930
|
this.ensureState();
|
|
15538
15931
|
this.sql.exec(`UPDATE record_log_state SET last_catch_up_at = ? WHERE doc_id = ?`, at, this.docId);
|
|
15539
15932
|
}
|
|
15933
|
+
/** Whether the db3 lives only on this device (#5155). */
|
|
15934
|
+
localOnly() {
|
|
15935
|
+
return Number(this.state()?.local_only ?? 0) === 1;
|
|
15936
|
+
}
|
|
15937
|
+
setLocalOnly(localOnly) {
|
|
15938
|
+
this.ensureState();
|
|
15939
|
+
this.sql.exec(`UPDATE record_log_state SET local_only = ? WHERE doc_id = ?`, localOnly ? 1 : 0, this.docId);
|
|
15940
|
+
}
|
|
15941
|
+
/** A local-only db3's index registrations, by name. */
|
|
15942
|
+
localIndexes() {
|
|
15943
|
+
const text = this.state()?.local_indexes;
|
|
15944
|
+
if (!text) return [];
|
|
15945
|
+
try {
|
|
15946
|
+
return JSON.parse(String(text));
|
|
15947
|
+
} catch {
|
|
15948
|
+
return [];
|
|
15949
|
+
}
|
|
15950
|
+
}
|
|
15951
|
+
setLocalIndexes(indexes) {
|
|
15952
|
+
this.ensureState();
|
|
15953
|
+
const sorted = [...indexes].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
15954
|
+
this.sql.exec(`UPDATE record_log_state SET local_indexes = ? WHERE doc_id = ?`, JSON.stringify(sorted), this.docId);
|
|
15955
|
+
}
|
|
15540
15956
|
generation() {
|
|
15541
15957
|
const state = this.state();
|
|
15542
15958
|
if (state?.replacing !== null && state?.replacing !== void 0) return Number(state.replacing);
|
|
@@ -15624,8 +16040,14 @@ var SqlRecordLogTables = class {
|
|
|
15624
16040
|
const write = () => writing ??= { replacing: this.isReplacing(), generation: this.generation() };
|
|
15625
16041
|
return {
|
|
15626
16042
|
row: (key) => {
|
|
15627
|
-
const [row] = rowsOf2(
|
|
15628
|
-
|
|
16043
|
+
const [row] = rowsOf2(
|
|
16044
|
+
sql,
|
|
16045
|
+
`SELECT ${jsonData()} FROM record_log_rows WHERE doc_id = ? AND _type = ? AND _id = ?`,
|
|
16046
|
+
docId,
|
|
16047
|
+
key.model,
|
|
16048
|
+
key.id
|
|
16049
|
+
);
|
|
16050
|
+
return row ? storedRow(key.id, row._data) : null;
|
|
15629
16051
|
},
|
|
15630
16052
|
set: (key, row) => {
|
|
15631
16053
|
const { replacing, generation } = write();
|
|
@@ -15633,12 +16055,12 @@ var SqlRecordLogTables = class {
|
|
|
15633
16055
|
sql.exec(`DELETE FROM record_log_rows WHERE doc_id = ? AND _type = ? AND _id = ?`, docId, key.model, key.id);
|
|
15634
16056
|
}
|
|
15635
16057
|
sql.exec(
|
|
15636
|
-
`INSERT INTO record_log_rows (doc_id, _type, _id, _data, _gen) VALUES (?, ?, ?,
|
|
16058
|
+
`INSERT INTO record_log_rows (doc_id, _type, _id, _data, _gen) VALUES (?, ?, ?, jsonb(?), ?)
|
|
15637
16059
|
ON CONFLICT (doc_id, _type, _id) DO UPDATE SET _data = excluded._data, _gen = excluded._gen`,
|
|
15638
16060
|
docId,
|
|
15639
16061
|
key.model,
|
|
15640
16062
|
key.id,
|
|
15641
|
-
|
|
16063
|
+
storedData(row),
|
|
15642
16064
|
generation
|
|
15643
16065
|
);
|
|
15644
16066
|
},
|
|
@@ -15692,13 +16114,13 @@ var SqlRecordLogTables = class {
|
|
|
15692
16114
|
return (key) => {
|
|
15693
16115
|
const [kept] = rowsOf2(
|
|
15694
16116
|
this.sql,
|
|
15695
|
-
`SELECT
|
|
16117
|
+
`SELECT ${jsonData()} FROM record_log_staged_base WHERE doc_id = ? AND _type = ? AND _id = ?`,
|
|
15696
16118
|
this.docId,
|
|
15697
16119
|
key.model,
|
|
15698
16120
|
key.id
|
|
15699
16121
|
);
|
|
15700
16122
|
if (!kept) return confirmed.row(key);
|
|
15701
|
-
return kept._data === null || kept._data === void 0 ? null :
|
|
16123
|
+
return kept._data === null || kept._data === void 0 ? null : storedRow(key.id, kept._data);
|
|
15702
16124
|
};
|
|
15703
16125
|
}
|
|
15704
16126
|
clearStagedBase() {
|
|
@@ -16056,14 +16478,15 @@ var RecordLogStore = class {
|
|
|
16056
16478
|
lowestPending: Number(row.lowest),
|
|
16057
16479
|
pending: Number(row.pending)
|
|
16058
16480
|
}));
|
|
16059
|
-
const [state] = rowsOf2(this.sql, `SELECT
|
|
16481
|
+
const [state] = rowsOf2(this.sql, `SELECT * FROM record_log_state WHERE doc_id = ?`, this.docId);
|
|
16060
16482
|
return {
|
|
16061
16483
|
cursor: this.tables.cursor(),
|
|
16062
16484
|
rows: Number(count?.n ?? 0),
|
|
16063
16485
|
writers,
|
|
16064
16486
|
replacing: this.tables.isReplacing(),
|
|
16065
16487
|
staged: this.tables.staged(),
|
|
16066
|
-
lastCatchUpAt: state?.last_catch_up_at === null || state?.last_catch_up_at === void 0 ? null : Number(state.last_catch_up_at)
|
|
16488
|
+
lastCatchUpAt: state?.last_catch_up_at === null || state?.last_catch_up_at === void 0 ? null : Number(state.last_catch_up_at),
|
|
16489
|
+
...state ? { localOnly: Number(state.local_only ?? 0) === 1 } : {}
|
|
16067
16490
|
};
|
|
16068
16491
|
}
|
|
16069
16492
|
/** This client's writer, or `null` before one is minted. */
|
|
@@ -16180,6 +16603,11 @@ var RecordLogStore = class {
|
|
|
16180
16603
|
};
|
|
16181
16604
|
});
|
|
16182
16605
|
}
|
|
16606
|
+
/** The permission mark alone. */
|
|
16607
|
+
permissionMark() {
|
|
16608
|
+
const [state] = rowsOf2(this.sql, `SELECT permission FROM record_log_state WHERE doc_id = ?`, this.docId);
|
|
16609
|
+
return state?.permission ?? null;
|
|
16610
|
+
}
|
|
16183
16611
|
/** Everything a facade mirrors, in one read. */
|
|
16184
16612
|
marks() {
|
|
16185
16613
|
const epochs = this.tables.epochs();
|
|
@@ -16208,9 +16636,38 @@ var RecordLogStore = class {
|
|
|
16208
16636
|
pending: Number(pending?.n ?? 0),
|
|
16209
16637
|
unacked: writer ? this.unackedOf(writer) : [],
|
|
16210
16638
|
receipt: latestReceipt(this.tables.receipts()),
|
|
16211
|
-
segment: this.tables.heldSegment()
|
|
16639
|
+
segment: this.tables.heldSegment(),
|
|
16640
|
+
...this.tables.typeState(),
|
|
16641
|
+
models: this.modelsHeld(),
|
|
16642
|
+
localOnly: Number(state?.local_only ?? 0) === 1,
|
|
16643
|
+
localIndexes: this.tables.localIndexes()
|
|
16212
16644
|
};
|
|
16213
16645
|
}
|
|
16646
|
+
/**
|
|
16647
|
+
* The models this copy holds, sorted and distinct: those with a view or
|
|
16648
|
+
* confirmed row, and those an unjudged entry of any writer touches.
|
|
16649
|
+
*/
|
|
16650
|
+
modelsHeld() {
|
|
16651
|
+
const docId = this.docId;
|
|
16652
|
+
const skipScan = (table) => `WITH RECURSIVE t(m) AS (
|
|
16653
|
+
SELECT MIN(_type) FROM ${table} WHERE doc_id = ?
|
|
16654
|
+
UNION ALL SELECT (SELECT MIN(_type) FROM ${table} WHERE doc_id = ? AND _type > t.m) FROM t WHERE t.m IS NOT NULL)
|
|
16655
|
+
SELECT m AS _type FROM t WHERE m IS NOT NULL`;
|
|
16656
|
+
const held = /* @__PURE__ */ new Set();
|
|
16657
|
+
for (const table of ["record_log_view", "record_log_rows"]) {
|
|
16658
|
+
for (const row of rowsOf2(this.sql, skipScan(table), docId, docId)) held.add(String(row._type));
|
|
16659
|
+
}
|
|
16660
|
+
for (const row of rowsOf2(
|
|
16661
|
+
this.sql,
|
|
16662
|
+
`SELECT DISTINCT k._type AS _type FROM record_log_pending p JOIN record_log_pending_keys k
|
|
16663
|
+
ON k.doc_id = p.doc_id AND k.writer = p.writer AND k.seq = p.seq
|
|
16664
|
+
WHERE p.doc_id = ? AND p.void = 0 AND p.acked IS NULL`,
|
|
16665
|
+
docId
|
|
16666
|
+
)) {
|
|
16667
|
+
held.add(String(row._type));
|
|
16668
|
+
}
|
|
16669
|
+
return [...held].sort();
|
|
16670
|
+
}
|
|
16214
16671
|
/** A writer's unacknowledged, unwithdrawn entries and the records each touches. */
|
|
16215
16672
|
unackedOf(writer) {
|
|
16216
16673
|
const bySeq = /* @__PURE__ */ new Map();
|
|
@@ -16239,12 +16696,12 @@ var RecordLogStore = class {
|
|
|
16239
16696
|
read(model, id) {
|
|
16240
16697
|
const [row] = rowsOf2(
|
|
16241
16698
|
this.sql,
|
|
16242
|
-
`SELECT
|
|
16699
|
+
`SELECT ${jsonData()} FROM record_log_view WHERE doc_id = ? AND _type = ? AND _id = ?`,
|
|
16243
16700
|
this.docId,
|
|
16244
16701
|
model,
|
|
16245
16702
|
id
|
|
16246
16703
|
);
|
|
16247
|
-
return row ?
|
|
16704
|
+
return row ? storedRow(id, row._data) : null;
|
|
16248
16705
|
}
|
|
16249
16706
|
/** Several records' view rows, in the order asked for; a missing one is `null`. */
|
|
16250
16707
|
readMany(model, ids) {
|
|
@@ -16254,12 +16711,12 @@ var RecordLogStore = class {
|
|
|
16254
16711
|
for (let at = 0; at < unique.length; at += 500) {
|
|
16255
16712
|
const slice = unique.slice(at, at + 500);
|
|
16256
16713
|
for (const row of this.sql.exec(
|
|
16257
|
-
`SELECT _id,
|
|
16714
|
+
`SELECT _id, ${jsonData()} FROM record_log_view WHERE doc_id = ? AND _type = ? AND _id IN (${slice.map(() => "?").join(", ")})`,
|
|
16258
16715
|
this.docId,
|
|
16259
16716
|
model,
|
|
16260
16717
|
...slice
|
|
16261
16718
|
)) {
|
|
16262
|
-
found.set(String(row._id),
|
|
16719
|
+
found.set(String(row._id), storedRow(row._id, row._data));
|
|
16263
16720
|
}
|
|
16264
16721
|
}
|
|
16265
16722
|
return ids.map((id) => found.get(id) ?? null);
|
|
@@ -16268,9 +16725,9 @@ var RecordLogStore = class {
|
|
|
16268
16725
|
readRowsAfter(model, after, limit) {
|
|
16269
16726
|
return rowsOf2(
|
|
16270
16727
|
this.sql,
|
|
16271
|
-
after === null ? `SELECT
|
|
16728
|
+
after === null ? `SELECT _id, ${jsonData()} FROM record_log_view WHERE doc_id = ? AND _type = ? ORDER BY _id LIMIT ?` : `SELECT _id, ${jsonData()} FROM record_log_view WHERE doc_id = ? AND _type = ? AND _id > ? ORDER BY _id LIMIT ?`,
|
|
16272
16729
|
...after === null ? [this.docId, model, limit] : [this.docId, model, after, limit]
|
|
16273
|
-
).map((row) =>
|
|
16730
|
+
).map((row) => storedRow(row._id, row._data));
|
|
16274
16731
|
}
|
|
16275
16732
|
/** One page of a model's record ids in id order, after `after`. */
|
|
16276
16733
|
recordIdsAfter(model, after, limit) {
|
|
@@ -16284,6 +16741,22 @@ var RecordLogStore = class {
|
|
|
16284
16741
|
findIdByFields(model, fields, values) {
|
|
16285
16742
|
return findHolder(this.sql, "record_log_view", this.docId, model, fields, values, []);
|
|
16286
16743
|
}
|
|
16744
|
+
/**
|
|
16745
|
+
* Up to `limit` keys over `fields` that records of `model` in the view
|
|
16746
|
+
* share, null-free keys only, in key order: what a unique registration on
|
|
16747
|
+
* a local-only db3 is refused for (#5155), as the room reads its records.
|
|
16748
|
+
*/
|
|
16749
|
+
duplicateKeys(model, fields, limit = 10) {
|
|
16750
|
+
const columns = fields.map((field) => `json_extract(_data, '$.${field}')`);
|
|
16751
|
+
return rowsOf2(
|
|
16752
|
+
this.sql,
|
|
16753
|
+
`SELECT ${columns.map((c, i) => `${c} AS k${i}`).join(", ")}, COUNT(*) AS n FROM record_log_view
|
|
16754
|
+
WHERE doc_id = ? AND _type = ? AND ${columns.map((c) => `${c} IS NOT NULL`).join(" AND ")}
|
|
16755
|
+
GROUP BY ${columns.join(", ")} HAVING COUNT(*) > 1 ORDER BY ${columns.join(", ")} LIMIT ${Math.max(1, Math.floor(limit))}`,
|
|
16756
|
+
this.docId,
|
|
16757
|
+
model
|
|
16758
|
+
).map((row) => ({ values: fields.map((_, i) => row[`k${i}`]), count: Number(row.n) }));
|
|
16759
|
+
}
|
|
16287
16760
|
/**
|
|
16288
16761
|
* The records of `model` in the view matching `filter`, one page of them:
|
|
16289
16762
|
* the model API's filter grammar on any field, declared or not, answered by
|
|
@@ -16550,12 +17023,12 @@ var RecordLogStore = class {
|
|
|
16550
17023
|
this.sql.exec(`DELETE FROM record_log_view WHERE doc_id = ? AND _type = ? AND _id = ?`, docId, key.model, key.id);
|
|
16551
17024
|
} else {
|
|
16552
17025
|
this.sql.exec(
|
|
16553
|
-
`INSERT INTO record_log_view (doc_id, _type, _id, _data) VALUES (?, ?, ?, ?)
|
|
17026
|
+
`INSERT INTO record_log_view (doc_id, _type, _id, _data) VALUES (?, ?, ?, jsonb(?))
|
|
16554
17027
|
ON CONFLICT (doc_id, _type, _id) DO UPDATE SET _data = excluded._data`,
|
|
16555
17028
|
docId,
|
|
16556
17029
|
key.model,
|
|
16557
17030
|
key.id,
|
|
16558
|
-
|
|
17031
|
+
storedData(row)
|
|
16559
17032
|
);
|
|
16560
17033
|
}
|
|
16561
17034
|
changed.push(key);
|
|
@@ -16578,12 +17051,14 @@ var RecordLogStore = class {
|
|
|
16578
17051
|
/**
|
|
16579
17052
|
* Commit local writes, one entry each, in one transaction: the budget
|
|
16580
17053
|
* check, the pending entry and the guess on the view. A write whose
|
|
16581
|
-
* `expect` no longer holds lands nothing and answers `stale`.
|
|
17054
|
+
* `expect` no longer holds lands nothing and answers `stale`. A db3 that
|
|
17055
|
+
* lives only on this device commits through {@link commitLocally}.
|
|
16582
17056
|
*
|
|
16583
17057
|
* @throws RecordLogWriteRefusedError `DOCUMENT_EPOCH_BUDGET` when both
|
|
16584
17058
|
* epochs this client may write into are full; nothing of the command lands.
|
|
16585
17059
|
*/
|
|
16586
17060
|
commitEntries(command) {
|
|
17061
|
+
if (this.tables.localOnly()) return this.sql.transaction(() => this.commitLocally(command));
|
|
16587
17062
|
return this.sql.transaction(
|
|
16588
17063
|
() => this.tables.countingEpochs(() => {
|
|
16589
17064
|
const client = this.client(command.writer);
|
|
@@ -16619,6 +17094,153 @@ var RecordLogStore = class {
|
|
|
16619
17094
|
})
|
|
16620
17095
|
);
|
|
16621
17096
|
}
|
|
17097
|
+
/**
|
|
17098
|
+
* Commit the writes of a db3 that lives only on this device (#5155). No
|
|
17099
|
+
* room will judge them, so the store does, as the room would: each write
|
|
17100
|
+
* is resolved against the confirmed rows (an upsert lands on the live
|
|
17101
|
+
* record holding its value), its guards are judged (`ifNotExists` fails on
|
|
17102
|
+
* a live record, `condition` on no live record or one that does not match,
|
|
17103
|
+
* an increment on a record neither live nor created by the entry), and the
|
|
17104
|
+
* rows it would leave are checked against the store's unique constraints.
|
|
17105
|
+
* An accepted write is written and confirmed at once by a result of the
|
|
17106
|
+
* store's own making (the next log number, the open epoch, its changes),
|
|
17107
|
+
* so it leaves the pending log as it lands and the cursor advances by one.
|
|
17108
|
+
* The reply carries what such a `receive` answers. No write budget
|
|
17109
|
+
* applies: nothing else writes to the db3.
|
|
17110
|
+
*
|
|
17111
|
+
* @throws RecordLogWriteRefusedError `DOCUMENT_CONSTRAINT_VIOLATED`,
|
|
17112
|
+
* `DB3_CONDITION_NOT_MET`, `DB3_RECORD_NOT_FOUND` or
|
|
17113
|
+
* `DOCUMENT_ENTRY_INVALID` (`details.scope: "local"`, with the room's
|
|
17114
|
+
* `conflicting`, `constraint` and `current`); nothing of the command lands.
|
|
17115
|
+
*/
|
|
17116
|
+
commitLocally(command) {
|
|
17117
|
+
const client = this.client(command.writer);
|
|
17118
|
+
const results = [];
|
|
17119
|
+
const touched = [];
|
|
17120
|
+
const acknowledged = [];
|
|
17121
|
+
const settled = [];
|
|
17122
|
+
const settlements = [];
|
|
17123
|
+
for (const write of command.writes) {
|
|
17124
|
+
const stale = (write.expect ?? []).some(
|
|
17125
|
+
({ model, id, revision }) => recordLogRowRevision(this.read(model, id)) !== revision
|
|
17126
|
+
);
|
|
17127
|
+
if (stale) {
|
|
17128
|
+
results.push({ stale: true });
|
|
17129
|
+
continue;
|
|
17130
|
+
}
|
|
17131
|
+
const judged = this.judgeLocally(write);
|
|
17132
|
+
const [m, ...also] = write.mutations;
|
|
17133
|
+
const entry = client.write(m, {
|
|
17134
|
+
also,
|
|
17135
|
+
...write.upsertOn !== void 0 ? { upsertOn: write.upsertOn } : {},
|
|
17136
|
+
ts: command.ts ?? Date.now()
|
|
17137
|
+
});
|
|
17138
|
+
const out = client.receive({
|
|
17139
|
+
l: this.tables.cursor() + 1,
|
|
17140
|
+
e: this.tables.epochs().open,
|
|
17141
|
+
w: command.writer,
|
|
17142
|
+
seq: entry.seq,
|
|
17143
|
+
changes: judged.changes,
|
|
17144
|
+
...judged.alias ? { alias: judged.alias } : {}
|
|
17145
|
+
});
|
|
17146
|
+
touched.push(...out.touched);
|
|
17147
|
+
acknowledged.push(...out.acknowledged);
|
|
17148
|
+
settled.push(...out.settled);
|
|
17149
|
+
settlements.push(...out.settlements ?? []);
|
|
17150
|
+
results.push(judged.resolved ? { entry, resolved: judged.resolved } : { entry });
|
|
17151
|
+
}
|
|
17152
|
+
const changed = this.settleView(touched);
|
|
17153
|
+
return { results, changed, cursor: this.tables.cursor(), acknowledged, settled, settlements };
|
|
17154
|
+
}
|
|
17155
|
+
/**
|
|
17156
|
+
* Judge one write of a local-only db3 against the confirmed rows, as the
|
|
17157
|
+
* room judges an entry: answers its changes, and for an upsert the record
|
|
17158
|
+
* it landed on and its alias when that is another record.
|
|
17159
|
+
*
|
|
17160
|
+
* @throws RecordLogWriteRefusedError when the room would refuse it.
|
|
17161
|
+
*/
|
|
17162
|
+
judgeLocally(write) {
|
|
17163
|
+
const docId = this.docId;
|
|
17164
|
+
const confirmed = this.tables.confirmed();
|
|
17165
|
+
const constraints = this.tables.constraints();
|
|
17166
|
+
const [m, ...also] = write.mutations;
|
|
17167
|
+
const entry = { m, ...also.length ? { also } : {}, ...write.upsertOn !== void 0 ? { upsertOn: write.upsertOn } : {} };
|
|
17168
|
+
const refuse = (code, message, details = {}) => {
|
|
17169
|
+
throw new RecordLogWriteRefusedError(code, docId, message, { scope: "local", ...details });
|
|
17170
|
+
};
|
|
17171
|
+
if (write.upsertOn !== void 0 && !constraints.some((c) => c.model === m.model && c.fields.length === 1 && c.fields[0] === write.upsertOn)) {
|
|
17172
|
+
refuse(
|
|
17173
|
+
"DOCUMENT_ENTRY_INVALID",
|
|
17174
|
+
`upsertOn names ${write.upsertOn}, which no single-field unique constraint of ${m.model} covers`
|
|
17175
|
+
);
|
|
17176
|
+
}
|
|
17177
|
+
const resolved = resolveEntry(confirmed, entry, constraints);
|
|
17178
|
+
const created = /* @__PURE__ */ new Set();
|
|
17179
|
+
mutationsOf(entry).forEach((sent, at) => {
|
|
17180
|
+
const target = resolved.mutations[at];
|
|
17181
|
+
const key = { model: target.model, id: target.id };
|
|
17182
|
+
if (target.kind === "create") created.add(keyText2(key));
|
|
17183
|
+
if (sent.kind !== "increment" && sent.condition === void 0 && sent.ifNotExists === void 0) return;
|
|
17184
|
+
const where2 = at === 0 ? "" : `write ${at + 1} of the transaction: `;
|
|
17185
|
+
const record = `${target.model} id=${target.id}`;
|
|
17186
|
+
const row = confirmed.row(key);
|
|
17187
|
+
const current = { model: target.model, id: target.id, row };
|
|
17188
|
+
if (sent.kind === "increment" && !created.has(keyText2(key)) && row === null) {
|
|
17189
|
+
refuse("DB3_RECORD_NOT_FOUND", `${where2}${record} has no live record to increment`, { current });
|
|
17190
|
+
}
|
|
17191
|
+
if (sent.ifNotExists && row !== null) {
|
|
17192
|
+
refuse("DB3_CONDITION_NOT_MET", `${where2}ifNotExists failed: ${record} already exists`, { current });
|
|
17193
|
+
}
|
|
17194
|
+
if (sent.condition !== void 0 && (row === null || !conditionHolds(this.sql, target.model, target.id, row, sent.condition))) {
|
|
17195
|
+
refuse(
|
|
17196
|
+
"DB3_CONDITION_NOT_MET",
|
|
17197
|
+
`${where2}the condition on ${record} is not met${row === null ? " (a record with no live row meets none)" : ""}`,
|
|
17198
|
+
{ current }
|
|
17199
|
+
);
|
|
17200
|
+
}
|
|
17201
|
+
});
|
|
17202
|
+
const before = /* @__PURE__ */ new Map();
|
|
17203
|
+
const after = /* @__PURE__ */ new Map();
|
|
17204
|
+
const keys = [];
|
|
17205
|
+
resolved.mutations.forEach((mutation, at) => {
|
|
17206
|
+
const { condition: _condition, ifNotExists: _ifNotExists, ...applied } = mutation;
|
|
17207
|
+
void _condition;
|
|
17208
|
+
void _ifNotExists;
|
|
17209
|
+
const key = { model: applied.model, id: applied.id };
|
|
17210
|
+
const text = keyText2(key);
|
|
17211
|
+
if (!before.has(text)) {
|
|
17212
|
+
const row2 = confirmed.row(key);
|
|
17213
|
+
before.set(text, row2);
|
|
17214
|
+
after.set(text, row2);
|
|
17215
|
+
keys.push(key);
|
|
17216
|
+
}
|
|
17217
|
+
const row = plainRowAfter(after.get(text) ?? null, applied);
|
|
17218
|
+
if (applied.kind === "increment" && row) {
|
|
17219
|
+
const field = Object.keys(applied.fields ?? {}).find((f) => !Number.isFinite(row[f]));
|
|
17220
|
+
if (field !== void 0) {
|
|
17221
|
+
refuse("DOCUMENT_ENTRY_INVALID", `${at === 0 ? "" : `write ${at + 1} of the transaction: `}increment of \`${field}\` overflows`, {
|
|
17222
|
+
current: { model: key.model, id: key.id, row: after.get(text) ?? null }
|
|
17223
|
+
});
|
|
17224
|
+
}
|
|
17225
|
+
}
|
|
17226
|
+
after.set(text, row);
|
|
17227
|
+
});
|
|
17228
|
+
const trial = {
|
|
17229
|
+
row: (key) => after.has(keyText2(key)) ? after.get(keyText2(key)) ?? null : confirmed.row(key),
|
|
17230
|
+
holder: (model, fields, values, excluding = []) => confirmed.holder(model, fields, values, excluding)
|
|
17231
|
+
};
|
|
17232
|
+
const violation = checkConstraints(trial, keys, constraints);
|
|
17233
|
+
if (violation) {
|
|
17234
|
+
refuse(
|
|
17235
|
+
"DOCUMENT_CONSTRAINT_VIOLATED",
|
|
17236
|
+
`unique constraint "${violation.constraint.name}" of ${violation.constraint.model}: ${violation.conflicting.id} already holds the key`,
|
|
17237
|
+
{ constraint: violation.constraint.name, conflicting: { model: violation.conflicting.model, id: violation.conflicting.id } }
|
|
17238
|
+
);
|
|
17239
|
+
}
|
|
17240
|
+
const changes = keys.map((key) => changeBetween(key, before.get(keyText2(key)) ?? null, after.get(keyText2(key)) ?? null)).filter((change) => change !== null);
|
|
17241
|
+
const landed = write.upsertOn !== void 0 ? { model: m.model, id: resolved.alias?.to ?? m.id } : void 0;
|
|
17242
|
+
return { changes, ...landed ? { resolved: landed } : {}, ...resolved.alias ? { alias: resolved.alias } : {} };
|
|
17243
|
+
}
|
|
16622
17244
|
/** Apply what the room relayed, item by item. */
|
|
16623
17245
|
receive(command) {
|
|
16624
17246
|
return this.sql.transaction(() => {
|
|
@@ -16978,16 +17600,44 @@ var RecordLogStore = class {
|
|
|
16978
17600
|
}
|
|
16979
17601
|
return { changed: this.settleBulk([...keys.values()]), models };
|
|
16980
17602
|
}
|
|
16981
|
-
/** Record what the room said about epochs and
|
|
17603
|
+
/** Record what the room said about epochs, constraints and the db3's type, and the permission the client holds. */
|
|
16982
17604
|
setState(command) {
|
|
16983
17605
|
return this.sql.transaction(() => {
|
|
16984
17606
|
const client = this.client(command.writer);
|
|
16985
17607
|
if (command.notice) client.notice(command.notice.current, command.notice.next, command.notice.entries);
|
|
16986
17608
|
if (command.constraints) this.tables.setConstraints(command.constraints);
|
|
16987
|
-
if (command.permission !== void 0
|
|
17609
|
+
if (command.permission !== void 0 && (command.permissionFrom === void 0 || this.permissionMark() === command.permissionFrom)) {
|
|
17610
|
+
this.tables.setPermission(command.permission);
|
|
17611
|
+
}
|
|
17612
|
+
if (command.type) this.tables.setType(command.type);
|
|
17613
|
+
if (command.localOnly !== void 0) this.tables.setLocalOnly(command.localOnly);
|
|
17614
|
+
if (command.localIndexes) this.tables.setLocalIndexes(command.localIndexes);
|
|
16988
17615
|
return this.marks();
|
|
16989
17616
|
});
|
|
16990
17617
|
}
|
|
17618
|
+
/**
|
|
17619
|
+
* Replace a local-only db3's index registrations and the constraints it
|
|
17620
|
+
* enforces, in one transaction (#5155), only while its registrations are
|
|
17621
|
+
* still `from` and, when `unique` names a key, no two records of the view
|
|
17622
|
+
* share it: a registration is judged against the registrations and rows it
|
|
17623
|
+
* changes, and no write lands between the check and the constraint.
|
|
17624
|
+
* Answers `moved` (nothing written) when another change came first, and
|
|
17625
|
+
* `duplicates` (nothing written) naming up to `unique.limit` shared keys.
|
|
17626
|
+
*/
|
|
17627
|
+
changeLocalIndexes(command) {
|
|
17628
|
+
return this.sql.transaction(() => {
|
|
17629
|
+
if (localIndexesText(this.tables.localIndexes()) !== localIndexesText(command.from)) {
|
|
17630
|
+
return { outcome: "moved", marks: this.marks() };
|
|
17631
|
+
}
|
|
17632
|
+
if (command.unique) {
|
|
17633
|
+
const duplicates = this.duplicateKeys(command.unique.model, command.unique.fields, command.unique.limit);
|
|
17634
|
+
if (duplicates.length > 0) return { outcome: "duplicates", duplicates, marks: this.marks() };
|
|
17635
|
+
}
|
|
17636
|
+
this.tables.setLocalIndexes(command.to);
|
|
17637
|
+
this.tables.setConstraints(command.constraints);
|
|
17638
|
+
return { outcome: "changed", marks: this.marks() };
|
|
17639
|
+
});
|
|
17640
|
+
}
|
|
16991
17641
|
/**
|
|
16992
17642
|
* The client's copy of its open epoch is full: it moves to the next epoch
|
|
16993
17643
|
* the room has opened, the move a write's budget check makes on its own.
|
|
@@ -20059,9 +20709,11 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
|
|
|
20059
20709
|
let pending = this.mirror.pending;
|
|
20060
20710
|
let lowest = this.mirror.lowestPending;
|
|
20061
20711
|
const committed = [];
|
|
20712
|
+
const confirmed = reply.acknowledged !== void 0;
|
|
20062
20713
|
for (const result of reply.results) {
|
|
20063
20714
|
if (!("entry" in result)) continue;
|
|
20064
20715
|
nextSeq = Math.max(nextSeq, result.entry.seq + 1);
|
|
20716
|
+
if (confirmed) continue;
|
|
20065
20717
|
pending++;
|
|
20066
20718
|
lowest = lowest === null ? result.entry.seq : Math.min(lowest, result.entry.seq);
|
|
20067
20719
|
this.unacked.set(result.entry.seq, keysOf(result.entry));
|
|
@@ -20069,6 +20721,11 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
|
|
|
20069
20721
|
committed.push(result.entry);
|
|
20070
20722
|
}
|
|
20071
20723
|
this.mirror = { ...this.mirror, nextSeq, pending, lowestPending: lowest };
|
|
20724
|
+
if (confirmed) {
|
|
20725
|
+
const own = this.mirror.writer;
|
|
20726
|
+
this.acknowledged((reply.acknowledged ?? []).filter((a) => a.writer === own).map((a) => a.seq));
|
|
20727
|
+
this.noteSettled(reply);
|
|
20728
|
+
}
|
|
20072
20729
|
if (committed.length) {
|
|
20073
20730
|
for (const listener of [...this.commitListeners]) {
|
|
20074
20731
|
try {
|
|
@@ -20375,6 +21032,10 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
|
|
|
20375
21032
|
syncIndexes(indexes) {
|
|
20376
21033
|
return this.host.dispatch({ kind: "syncIndexes", ...indexes ? { indexes: indexes.map((i) => ({ ...i, fields: [...i.fields] })) } : {} });
|
|
20377
21034
|
}
|
|
21035
|
+
/** Up to `limit` keys over `fields` that records of `model` in the view share (the store's `duplicateKeys`). */
|
|
21036
|
+
duplicateKeys(model, fields, limit) {
|
|
21037
|
+
return this.host.dispatch({ kind: "duplicateKeys", model, fields: [...fields], ...limit !== void 0 ? { limit } : {} });
|
|
21038
|
+
}
|
|
20378
21039
|
/** The store's view indexes as the room lists its own, `(model, fields, unique)`. */
|
|
20379
21040
|
indexTuples() {
|
|
20380
21041
|
return this.host.dispatch({ kind: "indexTuples" });
|
|
@@ -20617,13 +21278,42 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
|
|
|
20617
21278
|
return reply;
|
|
20618
21279
|
});
|
|
20619
21280
|
}
|
|
20620
|
-
/** Record epochs, constraints and
|
|
21281
|
+
/** Record epochs, constraints, permission and what the room said of the db3's type; refresh the mirror. */
|
|
20621
21282
|
setState(state) {
|
|
20622
21283
|
return this.run("setState", async () => {
|
|
20623
21284
|
this.mirror = await this.host.dispatch({ kind: "setState", writer: this.writer(), ...state });
|
|
20624
21285
|
return this.mirror;
|
|
20625
21286
|
});
|
|
20626
21287
|
}
|
|
21288
|
+
/**
|
|
21289
|
+
* Replace a local-only db3's index registrations and constraints in one
|
|
21290
|
+
* store transaction (the store's `changeLocalIndexes`, #5155): written only
|
|
21291
|
+
* while the stored registrations are `from` and no two records share the
|
|
21292
|
+
* `unique` key; once written, the view indexes become `indexes`. Nothing
|
|
21293
|
+
* else scheduled here interleaves with it.
|
|
21294
|
+
*/
|
|
21295
|
+
changeLocalIndexes(change) {
|
|
21296
|
+
return this.run("changeLocalIndexes", async () => {
|
|
21297
|
+
const reply = await this.host.dispatch({
|
|
21298
|
+
kind: "changeLocalIndexes",
|
|
21299
|
+
from: change.from.map((r) => ({ ...r, fields: [...r.fields] })),
|
|
21300
|
+
to: change.to.map((r) => ({ ...r, fields: [...r.fields] })),
|
|
21301
|
+
constraints: change.constraints.map((c) => ({ ...c, fields: [...c.fields] })),
|
|
21302
|
+
...change.unique ? { unique: { ...change.unique, fields: [...change.unique.fields] } } : {}
|
|
21303
|
+
});
|
|
21304
|
+
this.mirror = reply.marks;
|
|
21305
|
+
if (reply.outcome === "changed") await this.syncIndexes(change.indexes);
|
|
21306
|
+
return reply;
|
|
21307
|
+
});
|
|
21308
|
+
}
|
|
21309
|
+
/**
|
|
21310
|
+
* The declarations of the db3's type the room sent this device (#5020),
|
|
21311
|
+
* per model each declared field's kind; `null` while the db3 is not known
|
|
21312
|
+
* to be typed or none were received yet.
|
|
21313
|
+
*/
|
|
21314
|
+
declaredTypes() {
|
|
21315
|
+
return this.mirror.typed === "yes" ? this.mirror.declarations ?? null : null;
|
|
21316
|
+
}
|
|
20627
21317
|
/**
|
|
20628
21318
|
* Whether the local pre-check should hold a save to a unique constraint:
|
|
20629
21319
|
* every constraint is checked unless the room has said it keeps it out of
|
|
@@ -21146,7 +21836,28 @@ var RecordLogSender = class {
|
|
|
21146
21836
|
// src/record-log-client/session.ts
|
|
21147
21837
|
init_types();
|
|
21148
21838
|
var ACCESS_REFUSED_MESSAGE = "Access denied to document";
|
|
21149
|
-
var ACCESS_REFUSED_CODES = /* @__PURE__ */ new Set(["ACCESS_DENIED", "DOC_ACCESS_DENIED", "DB3_SYNC_OFF"]);
|
|
21839
|
+
var ACCESS_REFUSED_CODES = /* @__PURE__ */ new Set(["ACCESS_DENIED", "DOC_ACCESS_DENIED", "DB3_SYNC_OFF", "DOCUMENT_DELETED"]);
|
|
21840
|
+
function typeOfOpened(frame, docId) {
|
|
21841
|
+
if (!("db3Type" in frame) || frame.db3Type === void 0) return { type: { typed: "no" } };
|
|
21842
|
+
const type = frame.db3Type;
|
|
21843
|
+
const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
21844
|
+
const models = isObject(type) ? type.models : void 0;
|
|
21845
|
+
const wellFormed = isObject(type) && typeof type.name === "string" && type.name !== "" && typeof type.hash === "string" && type.hash !== "" && (models === void 0 || isObject(models) && Object.values(models).every((fields) => isObject(fields) && Object.values(fields).every((kind) => typeof kind === "string")));
|
|
21846
|
+
if (!wellFormed) {
|
|
21847
|
+
Logger.warn(`[record-log] ${docId}: record.opened carried a db3Type this client cannot read; the type it holds is kept`);
|
|
21848
|
+
return {};
|
|
21849
|
+
}
|
|
21850
|
+
return {
|
|
21851
|
+
type: {
|
|
21852
|
+
typed: "yes",
|
|
21853
|
+
db3Type: {
|
|
21854
|
+
name: type.name,
|
|
21855
|
+
hash: type.hash,
|
|
21856
|
+
...models !== void 0 ? { models } : {}
|
|
21857
|
+
}
|
|
21858
|
+
}
|
|
21859
|
+
};
|
|
21860
|
+
}
|
|
21150
21861
|
function isAccessRefusal(frame) {
|
|
21151
21862
|
const type = frame.messageType;
|
|
21152
21863
|
if (type !== void 0 && !(typeof type === "string" && type.startsWith("record."))) return false;
|
|
@@ -21231,6 +21942,10 @@ function wireEntryOf(entry) {
|
|
|
21231
21942
|
...entry.upsertOn !== void 0 ? { upsertOn: entry.upsertOn } : {}
|
|
21232
21943
|
};
|
|
21233
21944
|
}
|
|
21945
|
+
function modelsOf2(entry) {
|
|
21946
|
+
if (entry.void || !entry.m) return [];
|
|
21947
|
+
return [...new Set([entry.m, ...entry.also ?? []].map((mutation) => mutation.model))];
|
|
21948
|
+
}
|
|
21234
21949
|
var RecordLogDocumentSession = class {
|
|
21235
21950
|
/**
|
|
21236
21951
|
* @param docId - The document.
|
|
@@ -21253,7 +21968,10 @@ var RecordLogDocumentSession = class {
|
|
|
21253
21968
|
);
|
|
21254
21969
|
this.stopCommits = store.onCommitted((entries) => {
|
|
21255
21970
|
if (this.phase !== "open") return;
|
|
21256
|
-
for (const entry of entries)
|
|
21971
|
+
for (const entry of entries) {
|
|
21972
|
+
this.declareFirstWrites(entry);
|
|
21973
|
+
this.sender.enqueue(wireEntryOf(entry));
|
|
21974
|
+
}
|
|
21257
21975
|
});
|
|
21258
21976
|
}
|
|
21259
21977
|
phase = "idle";
|
|
@@ -21272,6 +21990,11 @@ var RecordLogDocumentSession = class {
|
|
|
21272
21990
|
held = [];
|
|
21273
21991
|
/** The open in progress sent its declaration and entries ahead of `record.opened`, or `null`. */
|
|
21274
21992
|
ahead = null;
|
|
21993
|
+
/**
|
|
21994
|
+
* The models this open's declarations named (#5115): a model first written
|
|
21995
|
+
* while open that is not among them is declared before its entry.
|
|
21996
|
+
*/
|
|
21997
|
+
declaredThisOpen = /* @__PURE__ */ new Set();
|
|
21275
21998
|
/** `record.open` frames sent on this connection; only its first may send frames ahead. */
|
|
21276
21999
|
openedOnConnection = 0;
|
|
21277
22000
|
/** Set while the frames sent ahead are flushed: the sender may send before the open completes. */
|
|
@@ -21412,6 +22135,10 @@ var RecordLogDocumentSession = class {
|
|
|
21412
22135
|
*/
|
|
21413
22136
|
start() {
|
|
21414
22137
|
return this.serially(async () => {
|
|
22138
|
+
if (this.store.marks().localOnly) {
|
|
22139
|
+
Logger.debug(`[record-log] ${this.docId}: lives only on this device; not opened on the socket`);
|
|
22140
|
+
return;
|
|
22141
|
+
}
|
|
21415
22142
|
if (this.phase === "open") {
|
|
21416
22143
|
this.host.synced(this.docId);
|
|
21417
22144
|
return;
|
|
@@ -21432,6 +22159,7 @@ var RecordLogDocumentSession = class {
|
|
|
21432
22159
|
this.host.syncFailed(this.docId, "not connected");
|
|
21433
22160
|
return;
|
|
21434
22161
|
}
|
|
22162
|
+
this.store.resumeAcknowledgements?.();
|
|
21435
22163
|
this.phase = "opening";
|
|
21436
22164
|
const generation = this.generation;
|
|
21437
22165
|
const own = this.store.writer();
|
|
@@ -21465,7 +22193,8 @@ var RecordLogDocumentSession = class {
|
|
|
21465
22193
|
const nextSeq = unacked.length ? unacked[0].seq : current.orphan ? Math.max(1, ...pending.map((p) => p.seq + 1)) : marks.nextSeq;
|
|
21466
22194
|
this.phase = "opening";
|
|
21467
22195
|
this.loadInProgress = null;
|
|
21468
|
-
const
|
|
22196
|
+
const typed = marks.typed ?? "unknown";
|
|
22197
|
+
const sendAhead = !current.orphan && this.openedOnConnection === 0 && [...this.history.opened].every((writer) => writer === current.writer) && nextSeq > marks.resumedAt && (typed !== "unknown" || !this.host.awaitTypeBeforeDeclaring);
|
|
21469
22198
|
this.openedOnConnection++;
|
|
21470
22199
|
this.history.opened.add(current.writer);
|
|
21471
22200
|
const fetches = typeof this.host.connection()?.fetchArtifact === "function";
|
|
@@ -21476,6 +22205,7 @@ var RecordLogDocumentSession = class {
|
|
|
21476
22205
|
);
|
|
21477
22206
|
}
|
|
21478
22207
|
const accepts = RECORD_LOG_ACCEPTS.filter((token) => token !== "building" || !waited);
|
|
22208
|
+
this.declaredThisOpen = /* @__PURE__ */ new Set();
|
|
21479
22209
|
this.sendFrame({
|
|
21480
22210
|
type: "record.open",
|
|
21481
22211
|
writer: current.writer,
|
|
@@ -21489,13 +22219,19 @@ var RecordLogDocumentSession = class {
|
|
|
21489
22219
|
acks: "compact",
|
|
21490
22220
|
// A room past this client's wire version refuses the open (DB3_CLIENT_OUTDATED).
|
|
21491
22221
|
wireVersion: RECORD_LOG_WIRE_VERSION,
|
|
21492
|
-
...fetches ? { accepts: this.failedReceipts >= RECORD_LOG_RECEIPT_FAILURES_BEFORE_ROWS ? [] : accepts } : {}
|
|
22222
|
+
...fetches ? { accepts: this.failedReceipts >= RECORD_LOG_RECEIPT_FAILURES_BEFORE_ROWS ? [] : accepts } : {},
|
|
22223
|
+
// The type revision whose declarations this device holds: the room
|
|
22224
|
+
// sends them again only for another one (#5020).
|
|
22225
|
+
...typed === "yes" && marks.db3Type?.hash ? { db3TypeHash: marks.db3Type.hash } : {}
|
|
21493
22226
|
});
|
|
21494
22227
|
if (!sendAhead) return;
|
|
21495
|
-
const
|
|
21496
|
-
const ahead = { declarations: JSON.stringify(models), refused: false, seqs: [] };
|
|
22228
|
+
const ahead = { declarations: null, refused: false, seqs: [] };
|
|
21497
22229
|
this.ahead = ahead;
|
|
21498
|
-
|
|
22230
|
+
if (typed !== "yes") {
|
|
22231
|
+
const models = this.declarationsFor(pending);
|
|
22232
|
+
ahead.declarations = JSON.stringify(models);
|
|
22233
|
+
this.sender.enqueueControl({ type: "record.declare", models });
|
|
22234
|
+
}
|
|
21499
22235
|
for (const entry of unacked) this.sender.enqueue(wireEntryOf(entry));
|
|
21500
22236
|
this.sendingAhead = true;
|
|
21501
22237
|
try {
|
|
@@ -21505,6 +22241,36 @@ var RecordLogDocumentSession = class {
|
|
|
21505
22241
|
}
|
|
21506
22242
|
ahead.seqs = this.sender.inFlightSeqs();
|
|
21507
22243
|
}
|
|
22244
|
+
/**
|
|
22245
|
+
* The declarations this open carries (#5115): the host's answer for the
|
|
22246
|
+
* models the copy holds, as the marks last read name them, united with the
|
|
22247
|
+
* models of `pending`, the entries in hand (marks read before a commit
|
|
22248
|
+
* made since do not name its models). The models it names are this open's.
|
|
22249
|
+
*/
|
|
22250
|
+
declarationsFor(pending) {
|
|
22251
|
+
const held = new Set(this.store.marks().models ?? []);
|
|
22252
|
+
for (const entry of pending) for (const model of modelsOf2(entry)) held.add(model);
|
|
22253
|
+
const models = this.host.declarations(this.docId, [...held].sort());
|
|
22254
|
+
this.declaredThisOpen = new Set(Object.keys(models));
|
|
22255
|
+
return models;
|
|
22256
|
+
}
|
|
22257
|
+
/**
|
|
22258
|
+
* A committed entry's models this open has not declared go in a
|
|
22259
|
+
* `record.declare` queued before it (#5115), so the room holds their
|
|
22260
|
+
* indexes and constraints before it applies the entry. A typed db3 takes
|
|
22261
|
+
* none (#5020), nor does a model the host has no declaration of.
|
|
22262
|
+
*/
|
|
22263
|
+
declareFirstWrites(entry) {
|
|
22264
|
+
if (this.store.marks().typed === "yes") return;
|
|
22265
|
+
const fresh = modelsOf2(entry).filter((model) => !this.declaredThisOpen.has(model));
|
|
22266
|
+
if (!fresh.length) return;
|
|
22267
|
+
const answer = this.host.declarations(this.docId, fresh);
|
|
22268
|
+
const models = {};
|
|
22269
|
+
for (const model of fresh) if (answer[model] !== void 0) models[model] = answer[model];
|
|
22270
|
+
if (!Object.keys(models).length) return;
|
|
22271
|
+
for (const model of Object.keys(models)) this.declaredThisOpen.add(model);
|
|
22272
|
+
this.sender.enqueueControl({ type: "record.declare", models });
|
|
22273
|
+
}
|
|
21508
22274
|
/**
|
|
21509
22275
|
* The numbers sent ahead under the writer being opened that the room has
|
|
21510
22276
|
* not answered: none once it refused them, and none an answer held so far
|
|
@@ -21744,7 +22510,9 @@ var RecordLogDocumentSession = class {
|
|
|
21744
22510
|
...Array.isArray(frame.constraints) ? { constraints: frame.constraints } : {},
|
|
21745
22511
|
// The room opened the document for this client's writer: an access
|
|
21746
22512
|
// refusal it answered before is over.
|
|
21747
|
-
...!this.current.orphan && this.store.marks().permission === "refused" ? { permission: null } : {}
|
|
22513
|
+
...!this.current.orphan && this.store.marks().permission === "refused" ? { permission: null } : {},
|
|
22514
|
+
// The room says whether the db3 is typed, and by what (#5020).
|
|
22515
|
+
...typeOfOpened(frame, this.docId)
|
|
21748
22516
|
});
|
|
21749
22517
|
if (generation !== this.generation) return;
|
|
21750
22518
|
this.lastSeq = Number(frame.lastSeq ?? 0);
|
|
@@ -22408,8 +23176,12 @@ var RecordLogDocumentSession = class {
|
|
|
22408
23176
|
if (ahead && !ahead.refused) {
|
|
22409
23177
|
if (!unsent.length) await this.store.refreshMarks();
|
|
22410
23178
|
if (generation !== this.generation) return;
|
|
22411
|
-
|
|
22412
|
-
|
|
23179
|
+
if (this.store.marks().typed === "yes") {
|
|
23180
|
+
if (ahead.declarations === null) this.host.declared?.(this.docId);
|
|
23181
|
+
} else {
|
|
23182
|
+
const models = this.declarationsFor(pending);
|
|
23183
|
+
if (JSON.stringify(models) !== ahead.declarations) this.sender.enqueueControl({ type: "record.declare", models });
|
|
23184
|
+
}
|
|
22413
23185
|
for (const entry of unsent) this.sender.enqueue(wireEntryOf(entry));
|
|
22414
23186
|
return this.synced();
|
|
22415
23187
|
}
|
|
@@ -22424,7 +23196,8 @@ var RecordLogDocumentSession = class {
|
|
|
22424
23196
|
return;
|
|
22425
23197
|
}
|
|
22426
23198
|
this.sender.requeueInFlight(unsent.map(wireEntryOf));
|
|
22427
|
-
this.
|
|
23199
|
+
if (this.store.marks().typed === "yes") this.host.declared?.(this.docId);
|
|
23200
|
+
else this.sender.enqueueControl({ type: "record.declare", models: this.declarationsFor(pending) });
|
|
22428
23201
|
for (const entry of unsent) this.sender.enqueue(wireEntryOf(entry));
|
|
22429
23202
|
return this.synced();
|
|
22430
23203
|
}
|
|
@@ -22447,6 +23220,8 @@ var RecordLogDocumentSession = class {
|
|
|
22447
23220
|
connected: () => this.phase === "draining" && this.current?.writer === writer && this.connected()
|
|
22448
23221
|
});
|
|
22449
23222
|
this.orphanSender = sender;
|
|
23223
|
+
const models = this.orphanDeclarations(unsent);
|
|
23224
|
+
if (models) sender.enqueueControl({ type: "record.declare", models });
|
|
22450
23225
|
for (const entry of unsent) sender.enqueue(wireEntryOf(entry));
|
|
22451
23226
|
sender.kick();
|
|
22452
23227
|
if (this.outstanding.size) {
|
|
@@ -22472,6 +23247,24 @@ var RecordLogDocumentSession = class {
|
|
|
22472
23247
|
this.orphanSender = null;
|
|
22473
23248
|
await this.openNext();
|
|
22474
23249
|
}
|
|
23250
|
+
/**
|
|
23251
|
+
* The declarations an earlier writer's entries go behind (#5115): those of
|
|
23252
|
+
* every model they write that the host declares into this db3. An earlier
|
|
23253
|
+
* session may have written them offline after its open declared what the
|
|
23254
|
+
* copy held and had bound then, and a binding made since says nothing of
|
|
23255
|
+
* what went, so none is left out. A host that does not scope declared
|
|
23256
|
+
* every model at the earlier open, as before #5115, and the drain keeps
|
|
23257
|
+
* today's frames. A typed db3 takes none (#5020).
|
|
23258
|
+
*/
|
|
23259
|
+
orphanDeclarations(unsent) {
|
|
23260
|
+
if (!this.host.scopesDeclarations || this.store.marks().typed === "yes") return null;
|
|
23261
|
+
const written = [...new Set(unsent.flatMap(modelsOf2))].sort();
|
|
23262
|
+
if (!written.length) return null;
|
|
23263
|
+
const answer = this.host.declarations(this.docId, written);
|
|
23264
|
+
const models = {};
|
|
23265
|
+
for (const model of written) if (answer[model] !== void 0) models[model] = answer[model];
|
|
23266
|
+
return Object.keys(models).length ? models : null;
|
|
23267
|
+
}
|
|
22475
23268
|
/** Answers for an orphan writer's entries arrived. */
|
|
22476
23269
|
answered(seqs) {
|
|
22477
23270
|
if (!this.current?.orphan) return;
|
|
@@ -22617,9 +23410,11 @@ var RecordLogDocumentSession = class {
|
|
|
22617
23410
|
if (!this.current || !Number.isInteger(expected)) return;
|
|
22618
23411
|
Logger.info(`[record-log] ${this.docId}: the room is missing entries from ${expected}; resending`);
|
|
22619
23412
|
const pending = await this.store.pendingOf(this.current.writer);
|
|
22620
|
-
this.senderOf(this.current.writer)
|
|
23413
|
+
const sender = this.senderOf(this.current.writer);
|
|
23414
|
+
const sent = new Set(sender?.inFlightSeqs() ?? []);
|
|
23415
|
+
sender?.resendFrom(
|
|
22621
23416
|
expected,
|
|
22622
|
-
pending.filter((p) => p.acked === void 0).map(wireEntryOf)
|
|
23417
|
+
pending.filter((p) => p.acked === void 0 && sent.has(p.seq)).map(wireEntryOf)
|
|
22623
23418
|
);
|
|
22624
23419
|
}
|
|
22625
23420
|
/**
|
|
@@ -22670,18 +23465,20 @@ var RecordLogDocumentSession = class {
|
|
|
22670
23465
|
* is marked `permission: "refused"` (local writes are refused from now),
|
|
22671
23466
|
* its unjudged entries stay for the room to judge once access returns,
|
|
22672
23467
|
* nothing more is sent, and the open is reported failed with
|
|
22673
|
-
* `ACCESS_DENIED`,
|
|
22674
|
-
* (#4799)
|
|
23468
|
+
* `ACCESS_DENIED`, `DB3_SYNC_OFF` when the db3's sync was turned off
|
|
23469
|
+
* (#4799), or `DOCUMENT_DELETED` when the db3 was deleted (#5049). The own
|
|
23470
|
+
* writer's next `record.opened` lifts the mark.
|
|
22675
23471
|
*/
|
|
22676
23472
|
async accessRefused(frame) {
|
|
22677
23473
|
if (this.phase === "closed") return;
|
|
22678
|
-
const
|
|
23474
|
+
const reason = frame.code === "DB3_SYNC_OFF" || frame.code === "DOCUMENT_DELETED" ? frame.code : "ACCESS_DENIED";
|
|
23475
|
+
const why = reason === "DB3_SYNC_OFF" ? "because its sync is off" : reason === "DOCUMENT_DELETED" ? "because it was deleted" : "for access";
|
|
22679
23476
|
Logger.warn(
|
|
22680
|
-
`[record-log] ${this.docId}: the room refused ${frame.messageType ?? "a record frame"} ${
|
|
23477
|
+
`[record-log] ${this.docId}: the room refused ${frame.messageType ?? "a record frame"} ${why}; the document stays readable here, its unsent writes are kept, and nothing more is sent`
|
|
22681
23478
|
);
|
|
22682
23479
|
this.disconnected();
|
|
22683
23480
|
await this.store.setState({ permission: "refused" });
|
|
22684
|
-
this.host.syncFailed(this.docId,
|
|
23481
|
+
this.host.syncFailed(this.docId, reason);
|
|
22685
23482
|
}
|
|
22686
23483
|
/**
|
|
22687
23484
|
* The room refused this writer's writes for the whole document (it is
|
|
@@ -22706,9 +23503,15 @@ var RecordLogDocumentSession = class {
|
|
|
22706
23503
|
const code = String(frame.code ?? "");
|
|
22707
23504
|
const current = this.current;
|
|
22708
23505
|
if (code === "DB3_DECLARATION_REFUSED_TYPED" && frame.messageType === "record.declare") {
|
|
22709
|
-
Logger.
|
|
23506
|
+
Logger.debug(
|
|
22710
23507
|
`[record-log] ${this.docId}: the db3 is typed by ${frame.db3Type ?? "its type"}; the room keeps the type's declarations, and this client's models are judged against them.`
|
|
22711
23508
|
);
|
|
23509
|
+
if (typeof frame.db3Type === "string" && frame.db3Type) {
|
|
23510
|
+
const held = this.store.marks().db3Type;
|
|
23511
|
+
await this.store.setState({
|
|
23512
|
+
type: { typed: "yes", db3Type: { name: frame.db3Type, hash: held?.name === frame.db3Type ? held.hash : null } }
|
|
23513
|
+
});
|
|
23514
|
+
}
|
|
22712
23515
|
this.host.declared?.(this.docId);
|
|
22713
23516
|
return;
|
|
22714
23517
|
}
|
|
@@ -22907,7 +23710,9 @@ var RecordLogSessions = class {
|
|
|
22907
23710
|
store,
|
|
22908
23711
|
{
|
|
22909
23712
|
connection: () => this.connection,
|
|
22910
|
-
|
|
23713
|
+
awaitTypeBeforeDeclaring: this.host.awaitTypeBeforeDeclaring === true,
|
|
23714
|
+
scopesDeclarations: this.host.scopesDeclarations === true,
|
|
23715
|
+
declarations: (id, held) => this.host.declarations(id, held),
|
|
22911
23716
|
notify: (records) => this.host.notify(records),
|
|
22912
23717
|
reportRefused: (event) => this.host.reportRefused(event),
|
|
22913
23718
|
synced: (id) => {
|
|
@@ -22980,12 +23785,239 @@ var RecordLogSessions = class {
|
|
|
22980
23785
|
|
|
22981
23786
|
// src/record-log-client/binding.ts
|
|
22982
23787
|
init_types();
|
|
23788
|
+
|
|
23789
|
+
// src/record-log-client/local-only.ts
|
|
23790
|
+
init_reservedFields();
|
|
23791
|
+
var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
23792
|
+
var fieldsKey = (fields) => JSON.stringify(fields);
|
|
23793
|
+
var sameFieldSet = (a, b) => a.length === b.length && [...a].sort().join("\0") === [...b].sort().join("\0");
|
|
23794
|
+
function entriesOf(fields) {
|
|
23795
|
+
return fields instanceof Map ? [...fields.entries()] : Object.entries(fields);
|
|
23796
|
+
}
|
|
23797
|
+
function isSetField(declaration, field) {
|
|
23798
|
+
return entriesOf(declaration.fields).some(([name, options]) => name === field && options?.type === "stringset");
|
|
23799
|
+
}
|
|
23800
|
+
function fieldIndexName(model, field) {
|
|
23801
|
+
return `idx_records_${model.toLowerCase()}_${field.toLowerCase()}`;
|
|
23802
|
+
}
|
|
23803
|
+
function namedIndexName(model, name) {
|
|
23804
|
+
return `idx_named_${model.toLowerCase()}_${name.toLowerCase()}`;
|
|
23805
|
+
}
|
|
23806
|
+
function constraintIndexName(model, constraint) {
|
|
23807
|
+
const name = constraint.replace(/[^A-Za-z0-9_]/g, "_");
|
|
23808
|
+
const safe = IDENTIFIER.test(name) ? name : `c_${name}`;
|
|
23809
|
+
return `idx_uc_${model.toLowerCase()}_${safe.toLowerCase()}`;
|
|
23810
|
+
}
|
|
23811
|
+
function declaredConstraints(declarations) {
|
|
23812
|
+
const out = [];
|
|
23813
|
+
for (const declaration of declarations) {
|
|
23814
|
+
for (const constraint of declaration.uniqueConstraints) {
|
|
23815
|
+
if (constraint.fields.length === 0 || constraint.fields.some((field) => isSetField(declaration, field))) continue;
|
|
23816
|
+
out.push({ model: declaration.model, name: constraint.name, fields: [...constraint.fields] });
|
|
23817
|
+
}
|
|
23818
|
+
}
|
|
23819
|
+
return out;
|
|
23820
|
+
}
|
|
23821
|
+
function declarationIndexes(declarations) {
|
|
23822
|
+
const out = [];
|
|
23823
|
+
for (const declaration of declarations) {
|
|
23824
|
+
const { model } = declaration;
|
|
23825
|
+
if (!IDENTIFIER.test(model)) continue;
|
|
23826
|
+
const wants = /* @__PURE__ */ new Map();
|
|
23827
|
+
for (const [field, options] of entriesOf(declaration.fields)) {
|
|
23828
|
+
if (field === "id" || options?.type === "stringset" || !IDENTIFIER.test(field)) continue;
|
|
23829
|
+
if (options?.indexed !== true && options?.unique !== true) continue;
|
|
23830
|
+
wants.set(fieldsKey([field]), {
|
|
23831
|
+
name: fieldIndexName(model, field),
|
|
23832
|
+
model,
|
|
23833
|
+
fields: [field],
|
|
23834
|
+
unique: false,
|
|
23835
|
+
origins: [{ kind: "declaration", unique: false }]
|
|
23836
|
+
});
|
|
23837
|
+
}
|
|
23838
|
+
for (const constraint of declaredConstraints([declaration])) {
|
|
23839
|
+
const fields = constraint.fields;
|
|
23840
|
+
if (fields.length === 1 && fields[0] === "id" || !fields.every((f) => IDENTIFIER.test(f))) continue;
|
|
23841
|
+
const wanted2 = wants.get(fieldsKey(fields));
|
|
23842
|
+
if (wanted2) {
|
|
23843
|
+
wanted2.unique = true;
|
|
23844
|
+
wanted2.origins = [{ kind: "declaration", unique: true }];
|
|
23845
|
+
continue;
|
|
23846
|
+
}
|
|
23847
|
+
wants.set(fieldsKey(fields), {
|
|
23848
|
+
name: constraintIndexName(model, constraint.name),
|
|
23849
|
+
model,
|
|
23850
|
+
fields: [...fields],
|
|
23851
|
+
unique: true,
|
|
23852
|
+
origins: [{ kind: "declaration", unique: true }]
|
|
23853
|
+
});
|
|
23854
|
+
}
|
|
23855
|
+
out.push(...wants.values());
|
|
23856
|
+
}
|
|
23857
|
+
return out;
|
|
23858
|
+
}
|
|
23859
|
+
function localIndexList(declarations, registrations) {
|
|
23860
|
+
const byDefinition = /* @__PURE__ */ new Map();
|
|
23861
|
+
for (const index of declarationIndexes(declarations)) byDefinition.set(fieldsKey([index.model, ...index.fields]), index);
|
|
23862
|
+
for (const registration of registrations) {
|
|
23863
|
+
const key = fieldsKey([registration.model, ...registration.fields]);
|
|
23864
|
+
const held = byDefinition.get(key);
|
|
23865
|
+
const origin = { kind: "named", unique: registration.unique };
|
|
23866
|
+
if (held) {
|
|
23867
|
+
held.origins = [...held.origins.filter((o) => o.kind !== "named"), origin];
|
|
23868
|
+
held.unique = held.origins.some((o) => o.unique);
|
|
23869
|
+
continue;
|
|
23870
|
+
}
|
|
23871
|
+
byDefinition.set(key, {
|
|
23872
|
+
name: registration.name,
|
|
23873
|
+
model: registration.model,
|
|
23874
|
+
fields: [...registration.fields],
|
|
23875
|
+
unique: registration.unique,
|
|
23876
|
+
origins: [origin]
|
|
23877
|
+
});
|
|
23878
|
+
}
|
|
23879
|
+
return [...byDefinition.values()].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
23880
|
+
}
|
|
23881
|
+
function localConstraints(declarations, registrations) {
|
|
23882
|
+
const declared = declaredConstraints(declarations);
|
|
23883
|
+
const out = [...declared];
|
|
23884
|
+
for (const index of localIndexList(declarations, registrations)) {
|
|
23885
|
+
if (!index.unique || !index.origins.some((o) => o.kind === "named" && o.unique)) continue;
|
|
23886
|
+
if (declared.some((c) => c.model === index.model && sameFieldSet(c.fields, index.fields))) continue;
|
|
23887
|
+
const declaration = declarations.find((d) => d.model === index.model);
|
|
23888
|
+
if (declaration && index.fields.some((field) => isSetField(declaration, field))) continue;
|
|
23889
|
+
out.push({ model: index.model, name: index.name, fields: [...index.fields] });
|
|
23890
|
+
}
|
|
23891
|
+
return out;
|
|
23892
|
+
}
|
|
23893
|
+
var LOCAL_INDEX_MAX_DUPLICATES = 10;
|
|
23894
|
+
var RecordLogLocalIndexError = class _RecordLogLocalIndexError extends Error {
|
|
23895
|
+
/**
|
|
23896
|
+
* @param code - The room's code (`DB3_INDEX_INVALID`, `DB3_INDEX_NOT_UNIQUE`, ...).
|
|
23897
|
+
* @param message - What is wrong, as the room says it.
|
|
23898
|
+
* @param details - What the refusal names (`duplicates`, `origins`, `index`, `field`).
|
|
23899
|
+
*/
|
|
23900
|
+
constructor(code, message, details = {}) {
|
|
23901
|
+
super(message);
|
|
23902
|
+
this.code = code;
|
|
23903
|
+
this.details = details;
|
|
23904
|
+
this.name = "RecordLogLocalIndexError";
|
|
23905
|
+
Object.setPrototypeOf(this, _RecordLogLocalIndexError.prototype);
|
|
23906
|
+
}
|
|
23907
|
+
};
|
|
23908
|
+
var invalid = (message) => new RecordLogLocalIndexError("DB3_INDEX_INVALID", message);
|
|
23909
|
+
function parseLocalRegistration(body) {
|
|
23910
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
23911
|
+
throw invalid("An index registration is an object: { model, field | fields, unique?, name? }");
|
|
23912
|
+
}
|
|
23913
|
+
const raw = body;
|
|
23914
|
+
const identifier = (value) => typeof value === "string" && IDENTIFIER.test(value);
|
|
23915
|
+
if (!identifier(raw.model)) throw invalid("model must be an identifier (letters, digits and _, not starting with a digit)");
|
|
23916
|
+
if (raw.field === void 0 === (raw.fields === void 0)) throw invalid("Give exactly one of field and fields");
|
|
23917
|
+
const fields = raw.field !== void 0 ? [raw.field] : raw.fields;
|
|
23918
|
+
if (!Array.isArray(fields) || fields.length === 0) throw invalid("fields must be a non-empty array of field names");
|
|
23919
|
+
for (const field of fields) {
|
|
23920
|
+
if (!identifier(field)) throw invalid(`Field ${JSON.stringify(field)} must be an identifier`);
|
|
23921
|
+
if (field === "id") throw invalid("id needs no index: the primary key serves it");
|
|
23922
|
+
const reserved = checkReservedFieldName(field);
|
|
23923
|
+
if (reserved) throw invalid(reserved);
|
|
23924
|
+
}
|
|
23925
|
+
if (new Set(fields).size !== fields.length) throw invalid("fields must not repeat a field");
|
|
23926
|
+
if (raw.unique !== void 0 && typeof raw.unique !== "boolean") throw invalid("unique must be true or false");
|
|
23927
|
+
if (raw.name !== void 0 && !identifier(raw.name)) throw invalid("name must be an identifier");
|
|
23928
|
+
const unique = raw.unique === true;
|
|
23929
|
+
if (fields.length > 1 && (raw.name === void 0 || !unique)) {
|
|
23930
|
+
throw invalid("An index over several fields is a unique constraint: give it a name and unique: true");
|
|
23931
|
+
}
|
|
23932
|
+
return { model: raw.model, fields, unique, ...raw.name !== void 0 ? { name: raw.name } : {} };
|
|
23933
|
+
}
|
|
23934
|
+
function localIndexNotUnique(model, fields, duplicates) {
|
|
23935
|
+
return new RecordLogLocalIndexError(
|
|
23936
|
+
"DB3_INDEX_NOT_UNIQUE",
|
|
23937
|
+
`Live ${model} records share ${fields.join(", ")}: resolve the duplicates before registering a unique index`,
|
|
23938
|
+
{ duplicates }
|
|
23939
|
+
);
|
|
23940
|
+
}
|
|
23941
|
+
function registerLocalIndex(declarations, registrations, body, duplicates) {
|
|
23942
|
+
const { model, fields, unique, name } = parseLocalRegistration(body);
|
|
23943
|
+
const declaration = declarations.find((d) => d.model === model);
|
|
23944
|
+
for (const field of fields) {
|
|
23945
|
+
if (declaration && isSetField(declaration, field)) {
|
|
23946
|
+
throw new RecordLogLocalIndexError(
|
|
23947
|
+
"DB3_INDEX_SET_FIELD",
|
|
23948
|
+
`${model}.${field} is a string set, and a set field takes no index: $contains and facets read its members from the record itself`,
|
|
23949
|
+
{ field }
|
|
23950
|
+
);
|
|
23951
|
+
}
|
|
23952
|
+
}
|
|
23953
|
+
const list = localIndexList(declarations, registrations);
|
|
23954
|
+
const existing = list.find((index2) => index2.model === model && fieldsKey(index2.fields) === fieldsKey(fields));
|
|
23955
|
+
const existingNamed = existing ? registrations.find((r) => r.name === existing.name)?.named ?? null : null;
|
|
23956
|
+
if (name !== void 0) {
|
|
23957
|
+
const holder = registrations.find((r) => r.model === model && r.named === name && fieldsKey(r.fields) !== fieldsKey(fields));
|
|
23958
|
+
if (holder) {
|
|
23959
|
+
throw new RecordLogLocalIndexError("DB3_INDEX_NAME_TAKEN", `${model} already has an index named ${name} (${holder.name}) over other fields`, {
|
|
23960
|
+
index: holder.name
|
|
23961
|
+
});
|
|
23962
|
+
}
|
|
23963
|
+
if (existing && existingNamed !== name) {
|
|
23964
|
+
throw new RecordLogLocalIndexError(
|
|
23965
|
+
"DB3_INDEX_EXISTS",
|
|
23966
|
+
`${existing.name} already indexes ${model} on ${fields.join(", ")}: register it without a name, or drop it first`,
|
|
23967
|
+
{ index: existing.name }
|
|
23968
|
+
);
|
|
23969
|
+
}
|
|
23970
|
+
}
|
|
23971
|
+
if (unique) {
|
|
23972
|
+
const shared = duplicates(model, fields);
|
|
23973
|
+
if (shared.length > 0) throw localIndexNotUnique(model, fields, shared);
|
|
23974
|
+
}
|
|
23975
|
+
const indexName = existing?.name ?? (name !== void 0 ? namedIndexName(model, name) : fieldIndexName(model, fields[0]));
|
|
23976
|
+
const registration = {
|
|
23977
|
+
name: indexName,
|
|
23978
|
+
model,
|
|
23979
|
+
fields: [...fields],
|
|
23980
|
+
unique,
|
|
23981
|
+
...name ?? existingNamed ? { named: name ?? existingNamed } : {}
|
|
23982
|
+
};
|
|
23983
|
+
const next = [...registrations.filter((r) => !(r.model === model && fieldsKey(r.fields) === fieldsKey(fields))), registration];
|
|
23984
|
+
const index = localIndexList(declarations, next).find((i) => i.name === indexName);
|
|
23985
|
+
return { registrations: next, index };
|
|
23986
|
+
}
|
|
23987
|
+
function dropLocalIndex(declarations, registrations, name) {
|
|
23988
|
+
const index = localIndexList(declarations, registrations).find((i) => i.name === name);
|
|
23989
|
+
if (!index) throw new RecordLogLocalIndexError("DB3_INDEX_NOT_FOUND", `No registered index is named ${name}`, { index: name });
|
|
23990
|
+
const remaining = index.origins.filter((o) => o.kind !== "named");
|
|
23991
|
+
if (remaining.length > 0) {
|
|
23992
|
+
throw new RecordLogLocalIndexError(
|
|
23993
|
+
"DB3_INDEX_IN_USE",
|
|
23994
|
+
`${name} is kept by ${remaining.map((o) => o.kind).join(" and ")}: change the declaration to drop it`,
|
|
23995
|
+
{ index: name, origins: remaining }
|
|
23996
|
+
);
|
|
23997
|
+
}
|
|
23998
|
+
return registrations.filter((r) => r.name !== name);
|
|
23999
|
+
}
|
|
24000
|
+
|
|
24001
|
+
// src/record-log-client/binding.ts
|
|
22983
24002
|
var RECORD_LOG_TEARDOWN_DRAIN_BOUND_MS = 2e3;
|
|
22984
24003
|
function isRecordLogResident(state, createdLocally = false) {
|
|
22985
|
-
if (createdLocally) return true;
|
|
24004
|
+
if (createdLocally || state.localOnly === true) return true;
|
|
22986
24005
|
if (state.lastCatchUpAt === null || state.lastCatchUpAt === void 0) return false;
|
|
22987
24006
|
return !state.replacing || state.staged === true;
|
|
22988
24007
|
}
|
|
24008
|
+
function declarationOf(schema) {
|
|
24009
|
+
const fields = {};
|
|
24010
|
+
for (const [field, options] of schema.fields) {
|
|
24011
|
+
const kept = {};
|
|
24012
|
+
for (const [key, value] of Object.entries(options ?? {})) {
|
|
24013
|
+
if (typeof value === "function" || value === void 0) continue;
|
|
24014
|
+
kept[key] = value;
|
|
24015
|
+
}
|
|
24016
|
+
fields[field] = kept;
|
|
24017
|
+
}
|
|
24018
|
+
const uniqueConstraints = schema.options?.uniqueConstraints;
|
|
24019
|
+
return { fields, ...uniqueConstraints?.length ? { uniqueConstraints } : {} };
|
|
24020
|
+
}
|
|
22989
24021
|
var RecordLogDocumentBinding = class {
|
|
22990
24022
|
/**
|
|
22991
24023
|
* @param dbEngine - The instance's engine.
|
|
@@ -22999,7 +24031,12 @@ var RecordLogDocumentBinding = class {
|
|
|
22999
24031
|
this.ormContext = ormContext;
|
|
23000
24032
|
this.storeScope = storeScope;
|
|
23001
24033
|
this.sessions = new RecordLogSessions({
|
|
23002
|
-
|
|
24034
|
+
// A db3 this device has not heard about may be typed: its first open
|
|
24035
|
+
// declares only once the room says it is not (#5020).
|
|
24036
|
+
awaitTypeBeforeDeclaring: true,
|
|
24037
|
+
// Each db3 is declared the models it uses (#5115).
|
|
24038
|
+
scopesDeclarations: true,
|
|
24039
|
+
declarations: (docId, held) => this.declarations(docId, held),
|
|
23003
24040
|
notify: (records) => this.notify(records),
|
|
23004
24041
|
reportRefused: (event) => this.ormContext.reportRecordLogWriteRefused(event)
|
|
23005
24042
|
});
|
|
@@ -23010,6 +24047,10 @@ var RecordLogDocumentBinding = class {
|
|
|
23010
24047
|
createdLocally = /* @__PURE__ */ new Set();
|
|
23011
24048
|
/** Bound db3s withdrawn from reads and writes while their release runs. */
|
|
23012
24049
|
hidden = /* @__PURE__ */ new Set();
|
|
24050
|
+
/** Opens in flight, by document: a concurrent open of the same document joins it. */
|
|
24051
|
+
opening = /* @__PURE__ */ new Map();
|
|
24052
|
+
/** Bound db3s whose models' query tables are loaded (`connect` completed). */
|
|
24053
|
+
connected = /* @__PURE__ */ new Set();
|
|
23013
24054
|
/** Told that a bound db3's unacknowledged entries changed. */
|
|
23014
24055
|
pendingListeners = /* @__PURE__ */ new Set();
|
|
23015
24056
|
/** Told every bound db3's view-row changes. */
|
|
@@ -23026,10 +24067,25 @@ var RecordLogDocumentBinding = class {
|
|
|
23026
24067
|
const persistent = platform.persistent && !(volatile && platform.probed);
|
|
23027
24068
|
if (!persistent) throw new Db3StorageCapabilityError("not-persistent", 0, platform.quotaBytes, []);
|
|
23028
24069
|
}
|
|
23029
|
-
/**
|
|
23030
|
-
|
|
24070
|
+
/**
|
|
24071
|
+
* Open `docId`'s store, once, and register it on the instance. A second
|
|
24072
|
+
* open while the first is under way gets the first's store, so the engine
|
|
24073
|
+
* hosts the document once (#5049).
|
|
24074
|
+
*/
|
|
24075
|
+
open(docId) {
|
|
23031
24076
|
const mine = this.opened.get(docId);
|
|
23032
|
-
if (mine && this.ormContext.recordLogDocuments.get(docId) === mine) return mine;
|
|
24077
|
+
if (mine && this.ormContext.recordLogDocuments.get(docId) === mine) return Promise.resolve(mine);
|
|
24078
|
+
const running = this.opening.get(docId);
|
|
24079
|
+
if (running) return running;
|
|
24080
|
+
const opening = this.openOnce(docId);
|
|
24081
|
+
this.opening.set(docId, opening);
|
|
24082
|
+
const settled = () => {
|
|
24083
|
+
if (this.opening.get(docId) === opening) this.opening.delete(docId);
|
|
24084
|
+
};
|
|
24085
|
+
opening.then(settled, settled);
|
|
24086
|
+
return opening;
|
|
24087
|
+
}
|
|
24088
|
+
async openOnce(docId) {
|
|
23033
24089
|
const host = await this.createHost(docId);
|
|
23034
24090
|
const store = await RecordLogStoreAsync.open(host, docId, { storeKey: this.storeKey() });
|
|
23035
24091
|
this.opened.set(docId, store);
|
|
@@ -23072,6 +24128,37 @@ var RecordLogDocumentBinding = class {
|
|
|
23072
24128
|
Logger.info(`[record-log] ${docId}: connected with write access again; saves are allowed`);
|
|
23073
24129
|
await store.setState({ permission: null });
|
|
23074
24130
|
}
|
|
24131
|
+
/**
|
|
24132
|
+
* Take the type the client knows `docId` was created with (#5020): a
|
|
24133
|
+
* store the room has not yet told whether the db3 is typed is marked typed
|
|
24134
|
+
* by `type`, so its first open declares nothing. A mark the room set is
|
|
24135
|
+
* kept.
|
|
24136
|
+
*/
|
|
24137
|
+
async seedType(docId, type) {
|
|
24138
|
+
const store = this.opened.get(docId);
|
|
24139
|
+
if (!store || (await store.refreshMarks()).typed !== "unknown") return;
|
|
24140
|
+
await store.setState({ type: { typed: "yes", db3Type: { name: type, hash: null } } });
|
|
24141
|
+
}
|
|
24142
|
+
/**
|
|
24143
|
+
* Take a permission the client heard for a bound db3 while it stays
|
|
24144
|
+
* connected (#5020): the connected document's hint becomes `permission`,
|
|
24145
|
+
* and the store's mark follows it, `read` on a read-only grant and lifted
|
|
24146
|
+
* on a write-capable one, as the room's `WRITE_ACCESS_DENIED` and a
|
|
24147
|
+
* connect with write access set and lift it. A `refused` mark is the
|
|
24148
|
+
* room's to lift. Nothing happens for a document not bound here.
|
|
24149
|
+
*/
|
|
24150
|
+
async permissionChanged(docId, permission) {
|
|
24151
|
+
const store = this.opened.get(docId);
|
|
24152
|
+
if (!store) return;
|
|
24153
|
+
const connected = this.ormContext.connectedDocuments.get(docId);
|
|
24154
|
+
if (connected) connected.permissionHint = permission;
|
|
24155
|
+
const before = store.marks().permission;
|
|
24156
|
+
const marks = permission === "read" ? await store.setState({ permission: "read", permissionFrom: null }) : await store.setState({ permission: null, permissionFrom: "read" });
|
|
24157
|
+
if (marks.permission === before) return;
|
|
24158
|
+
Logger.info(
|
|
24159
|
+
permission === "read" ? `[record-log] ${docId}: the client may only read now; saves are refused here` : `[record-log] ${docId}: the client may write again; saves are allowed`
|
|
24160
|
+
);
|
|
24161
|
+
}
|
|
23075
24162
|
/**
|
|
23076
24163
|
* The database a document opened now is stored in: an engine hosting its
|
|
23077
24164
|
* own stores keeps one per scope; otherwise every document shares the
|
|
@@ -23087,10 +24174,14 @@ var RecordLogDocumentBinding = class {
|
|
|
23087
24174
|
if (createdLocally) this.createdLocally.add(docId);
|
|
23088
24175
|
else this.createdLocally.delete(docId);
|
|
23089
24176
|
}
|
|
23090
|
-
/**
|
|
24177
|
+
/**
|
|
24178
|
+
* Whether bound `docId` is resident ({@link isRecordLogResident}) and
|
|
24179
|
+
* connected (its models' query tables loaded, #5049); `false` when it is
|
|
24180
|
+
* not bound here.
|
|
24181
|
+
*/
|
|
23091
24182
|
isResident(docId) {
|
|
23092
24183
|
const store = this.opened.get(docId);
|
|
23093
|
-
if (!store || this.hidden.has(docId)) return false;
|
|
24184
|
+
if (!store || this.hidden.has(docId) || !this.connected.has(docId)) return false;
|
|
23094
24185
|
return isRecordLogResident(store.marks(), this.createdLocally.has(docId));
|
|
23095
24186
|
}
|
|
23096
24187
|
/**
|
|
@@ -23159,6 +24250,7 @@ var RecordLogDocumentBinding = class {
|
|
|
23159
24250
|
const store = this.opened.get(docId);
|
|
23160
24251
|
if (!store) return;
|
|
23161
24252
|
this.hidden.add(docId);
|
|
24253
|
+
this.connected.delete(docId);
|
|
23162
24254
|
store.refuseLocalWrites();
|
|
23163
24255
|
if (this.ormContext.recordLogDocuments.get(docId) === store) this.ormContext.recordLogDocuments.delete(docId);
|
|
23164
24256
|
this.ormContext.connectedDocuments.delete(docId);
|
|
@@ -23219,38 +24311,155 @@ var RecordLogDocumentBinding = class {
|
|
|
23219
24311
|
});
|
|
23220
24312
|
}
|
|
23221
24313
|
/**
|
|
23222
|
-
*
|
|
23223
|
-
*
|
|
24314
|
+
* The declarations `record.declare` carries into `docId` (#5115): of the
|
|
24315
|
+
* `held` models (those its copy holds or this client writes there) with
|
|
24316
|
+
* an active class, of the models whose default db3 is `docId`, and, when
|
|
24317
|
+
* `docId` is the global default db3, of every active model without a
|
|
24318
|
+
* default db3 of its own elsewhere, since a save naming no db3 lands
|
|
24319
|
+
* there. Each is its fields with their JSON options and its compound
|
|
24320
|
+
* unique constraints. With no `docId`, every active model's.
|
|
23224
24321
|
*/
|
|
23225
|
-
declarations() {
|
|
24322
|
+
declarations(docId, held = []) {
|
|
23226
24323
|
const out = {};
|
|
24324
|
+
const wanted2 = new Set(held);
|
|
24325
|
+
const globalDefault = docId !== void 0 && this.ormContext.getGlobalDefaultDocumentId() === docId;
|
|
23227
24326
|
for (const [, modelClass] of this.modelRegistry.getActiveModels()) {
|
|
23228
24327
|
const schema = modelClass.getSchema?.();
|
|
23229
24328
|
const name = schema?.options?.name;
|
|
23230
24329
|
if (!name) continue;
|
|
23231
|
-
|
|
23232
|
-
|
|
23233
|
-
|
|
23234
|
-
for (const [key, value] of Object.entries(options ?? {})) {
|
|
23235
|
-
if (typeof value === "function" || value === void 0) continue;
|
|
23236
|
-
kept[key] = value;
|
|
23237
|
-
}
|
|
23238
|
-
fields[field] = kept;
|
|
24330
|
+
if (docId !== void 0 && !wanted2.has(name)) {
|
|
24331
|
+
const bound = this.ormContext.getDocumentIdForModel(name);
|
|
24332
|
+
if (bound !== docId && !(globalDefault && bound === void 0)) continue;
|
|
23239
24333
|
}
|
|
23240
|
-
|
|
23241
|
-
out[name] = { fields, ...uniqueConstraints?.length ? { uniqueConstraints } : {} };
|
|
24334
|
+
out[name] = declarationOf(schema);
|
|
23242
24335
|
}
|
|
23243
24336
|
return out;
|
|
23244
24337
|
}
|
|
23245
24338
|
/**
|
|
23246
24339
|
* Bind `docId` once its models are initialized: its store, opened once,
|
|
23247
24340
|
* its lookup indexes reconciled from the store's cached index lists (the
|
|
23248
|
-
* room's list arrives later through {@link syncIndexes}).
|
|
24341
|
+
* room's list arrives later through {@link syncIndexes}). From here it is
|
|
24342
|
+
* resident, when its store holds a readable copy; a second connect (a
|
|
24343
|
+
* re-bind) keeps it so.
|
|
23249
24344
|
*/
|
|
23250
24345
|
async connect(docId) {
|
|
23251
24346
|
const store = await this.open(docId);
|
|
23252
24347
|
store.resumeAcknowledgements();
|
|
23253
|
-
|
|
24348
|
+
if (store.marks().localOnly) await this.applyLocalDeclarations(docId);
|
|
24349
|
+
else await store.syncIndexes();
|
|
24350
|
+
if (this.opened.get(docId) === store) this.connected.add(docId);
|
|
24351
|
+
}
|
|
24352
|
+
/**
|
|
24353
|
+
* Mark bound `docId` as a db3 that lives only on this device (#5155): from
|
|
24354
|
+
* now its store judges and confirms its own writes, its session sends
|
|
24355
|
+
* nothing, and it is resident once connected. The mark is the store's, so
|
|
24356
|
+
* every later bind finds it.
|
|
24357
|
+
*/
|
|
24358
|
+
async markLocalOnly(docId) {
|
|
24359
|
+
const store = this.opened.get(docId);
|
|
24360
|
+
if (!store || store.marks().localOnly) return;
|
|
24361
|
+
await store.setState({ localOnly: true });
|
|
24362
|
+
}
|
|
24363
|
+
/**
|
|
24364
|
+
* Make a bound local-only db3's constraints and view indexes what this
|
|
24365
|
+
* instance's models declare and what was registered on it here
|
|
24366
|
+
* (`localConstraints`, `localIndexList`): at every bind, when a model
|
|
24367
|
+
* registers later, and after a registration or a drop. Nothing happens for
|
|
24368
|
+
* a db3 that syncs.
|
|
24369
|
+
*/
|
|
24370
|
+
async applyLocalDeclarations(docId) {
|
|
24371
|
+
const store = this.opened.get(docId);
|
|
24372
|
+
if (!store || !store.marks().localOnly) return;
|
|
24373
|
+
await this.changeLocalIndexes(store, (current) => ({ registrations: current }));
|
|
24374
|
+
}
|
|
24375
|
+
/**
|
|
24376
|
+
* Change a bound local-only db3's registrations to what `plan` makes of
|
|
24377
|
+
* the ones its store holds, with the constraints and view indexes that
|
|
24378
|
+
* follow, in one store transaction (#5155): the change is written only
|
|
24379
|
+
* while the store still holds the registrations it was planned from and,
|
|
24380
|
+
* for a unique key, no two records share it; planned again from the
|
|
24381
|
+
* store's registrations when another change came first (a concurrent
|
|
24382
|
+
* registration, another client of the store). Answers the registrations
|
|
24383
|
+
* written.
|
|
24384
|
+
*
|
|
24385
|
+
* @throws RecordLogLocalIndexError when `plan` refuses, or `DB3_INDEX_NOT_UNIQUE` when records share the key.
|
|
24386
|
+
*/
|
|
24387
|
+
async changeLocalIndexes(store, plan) {
|
|
24388
|
+
let current = (await store.refreshMarks()).localIndexes ?? [];
|
|
24389
|
+
for (; ; ) {
|
|
24390
|
+
const { registrations, unique } = plan(current);
|
|
24391
|
+
const declarations = this.modelDeclarations();
|
|
24392
|
+
const reply = await store.changeLocalIndexes({
|
|
24393
|
+
from: current,
|
|
24394
|
+
to: registrations,
|
|
24395
|
+
constraints: localConstraints(declarations, registrations),
|
|
24396
|
+
...unique ? { unique: { ...unique, limit: LOCAL_INDEX_MAX_DUPLICATES } } : {},
|
|
24397
|
+
indexes: localIndexList(declarations, registrations).map(({ name, model, fields, unique: unique2 }) => ({ name, model, fields: [...fields], unique: unique2 }))
|
|
24398
|
+
});
|
|
24399
|
+
if (reply.outcome === "changed") return registrations;
|
|
24400
|
+
if (reply.outcome === "duplicates") throw localIndexNotUnique(unique.model, unique.fields, reply.duplicates);
|
|
24401
|
+
current = reply.marks.localIndexes ?? [];
|
|
24402
|
+
}
|
|
24403
|
+
}
|
|
24404
|
+
/**
|
|
24405
|
+
* A bound local-only db3's index list (`localIndexList`), as the room
|
|
24406
|
+
* lists its registry; `null` when `docId` is not a local-only db3 bound
|
|
24407
|
+
* here.
|
|
24408
|
+
*/
|
|
24409
|
+
localIndexes(docId) {
|
|
24410
|
+
const store = this.opened.get(docId);
|
|
24411
|
+
if (!store || !store.marks().localOnly) return null;
|
|
24412
|
+
return localIndexList(this.modelDeclarations(), store.marks().localIndexes ?? []);
|
|
24413
|
+
}
|
|
24414
|
+
/**
|
|
24415
|
+
* Register an index on a bound local-only db3 by the room's rules
|
|
24416
|
+
* (`registerLocalIndex`): kept in its store, and its constraints and view
|
|
24417
|
+
* indexes made to match before this resolves, judged against the
|
|
24418
|
+
* registrations and records the store holds as it writes. Answers the
|
|
24419
|
+
* index as the list now shows it; `null` when `docId` is not a local-only
|
|
24420
|
+
* db3 bound here.
|
|
24421
|
+
*
|
|
24422
|
+
* @throws RecordLogLocalIndexError when the room would refuse it.
|
|
24423
|
+
*/
|
|
24424
|
+
async registerLocalIndex(docId, registration) {
|
|
24425
|
+
const store = this.opened.get(docId);
|
|
24426
|
+
if (!store || !store.marks().localOnly) return null;
|
|
24427
|
+
const { model, fields, unique } = parseLocalRegistration(registration);
|
|
24428
|
+
let index = null;
|
|
24429
|
+
await this.changeLocalIndexes(store, (current) => {
|
|
24430
|
+
const planned = registerLocalIndex(this.modelDeclarations(), current, registration, () => []);
|
|
24431
|
+
index = planned.index;
|
|
24432
|
+
return { registrations: planned.registrations, ...unique ? { unique: { model, fields } } : {} };
|
|
24433
|
+
});
|
|
24434
|
+
return index;
|
|
24435
|
+
}
|
|
24436
|
+
/**
|
|
24437
|
+
* Drop a registration's index on a bound local-only db3 by the room's
|
|
24438
|
+
* rules (`dropLocalIndex`); its constraints and view indexes follow before
|
|
24439
|
+
* this resolves. `false` when `docId` is not a local-only db3 bound here.
|
|
24440
|
+
*
|
|
24441
|
+
* @throws RecordLogLocalIndexError when the room would refuse it.
|
|
24442
|
+
*/
|
|
24443
|
+
async dropLocalIndex(docId, name) {
|
|
24444
|
+
const store = this.opened.get(docId);
|
|
24445
|
+
if (!store || !store.marks().localOnly) return false;
|
|
24446
|
+
await this.changeLocalIndexes(store, (current) => ({ registrations: dropLocalIndex(this.modelDeclarations(), current, name) }));
|
|
24447
|
+
return true;
|
|
24448
|
+
}
|
|
24449
|
+
/** Every active model's fields and resolved unique constraints, as a local-only db3's schema is derived from. */
|
|
24450
|
+
modelDeclarations() {
|
|
24451
|
+
const out = [];
|
|
24452
|
+
for (const [, modelClass] of this.modelRegistry.getActiveModels()) {
|
|
24453
|
+
const schema = modelClass.getSchema?.();
|
|
24454
|
+
const name = schema?.options?.name;
|
|
24455
|
+
if (!name) continue;
|
|
24456
|
+
out.push({
|
|
24457
|
+
model: name,
|
|
24458
|
+
fields: schema.fields,
|
|
24459
|
+
uniqueConstraints: schema.resolvedUniqueConstraints ?? []
|
|
24460
|
+
});
|
|
24461
|
+
}
|
|
24462
|
+
return out;
|
|
23254
24463
|
}
|
|
23255
24464
|
/**
|
|
23256
24465
|
* Cache the room's index list for `docId` and reconcile the store's
|
|
@@ -23290,6 +24499,7 @@ var RecordLogDocumentBinding = class {
|
|
|
23290
24499
|
}
|
|
23291
24500
|
store.refuseLocalWrites();
|
|
23292
24501
|
this.createdLocally.delete(docId);
|
|
24502
|
+
this.connected.delete(docId);
|
|
23293
24503
|
this.hidden.delete(docId);
|
|
23294
24504
|
this.unsubscribers.get(docId)?.();
|
|
23295
24505
|
this.unsubscribers.delete(docId);
|
|
@@ -23437,6 +24647,8 @@ var DocumentManagerImpl = class {
|
|
|
23437
24647
|
bindingEpoch = 0;
|
|
23438
24648
|
/** db3 connects not yet settled; an unbind of every db3 waits for them. */
|
|
23439
24649
|
recordLogConnects = /* @__PURE__ */ new Set();
|
|
24650
|
+
/** db3 connects under way, by document: a failed one releases its store only when it is the last (#5049). */
|
|
24651
|
+
recordLogConnecting = /* @__PURE__ */ new Map();
|
|
23440
24652
|
/**
|
|
23441
24653
|
* The `(model, document)` pairs whose initialization for this instance
|
|
23442
24654
|
* COMPLETED (#3615).
|
|
@@ -23510,19 +24722,22 @@ var DocumentManagerImpl = class {
|
|
|
23510
24722
|
*/
|
|
23511
24723
|
async withdrawIfOvertaken(docId, epoch, opened) {
|
|
23512
24724
|
if (this.bindingEpoch === epoch) return;
|
|
23513
|
-
|
|
23514
|
-
try {
|
|
23515
|
-
await this.modelRegistry.removeDocumentData(docId, this.dbEngine, { skipQueryTableWipe: true });
|
|
23516
|
-
this.ormContext.disposeObserversForDocument(docId);
|
|
23517
|
-
await this.recordLog.disconnect(docId);
|
|
23518
|
-
} catch (error) {
|
|
23519
|
-
Logger.error(`[DocumentManager] ${docId}: releasing a withdrawn binding failed:`, error);
|
|
23520
|
-
}
|
|
23521
|
-
}
|
|
24725
|
+
await this.releaseUnpublished(docId, opened);
|
|
23522
24726
|
throw new Error(
|
|
23523
24727
|
`[DocumentManager] Document ${docId} was not bound: every db3 was unbound (the storage identity changed) while it connected.`
|
|
23524
24728
|
);
|
|
23525
24729
|
}
|
|
24730
|
+
/** Release the store a db3 connect opened and did not publish, if it is still the bound one. */
|
|
24731
|
+
async releaseUnpublished(docId, opened) {
|
|
24732
|
+
if (!opened || this.recordLog.storeOf(docId) !== opened || this.connectedDocuments.has(docId)) return;
|
|
24733
|
+
try {
|
|
24734
|
+
await this.modelRegistry.removeDocumentData(docId, this.dbEngine, { skipQueryTableWipe: true });
|
|
24735
|
+
this.ormContext.disposeObserversForDocument(docId);
|
|
24736
|
+
await this.recordLog.disconnect(docId);
|
|
24737
|
+
} catch (error) {
|
|
24738
|
+
Logger.error(`[DocumentManager] ${docId}: releasing an unpublished binding failed:`, error);
|
|
24739
|
+
}
|
|
24740
|
+
}
|
|
23526
24741
|
async connectDocumentInner(docId, yDoc, permissionHint, options, epoch) {
|
|
23527
24742
|
const documentFormat = options?.documentFormat ?? 1;
|
|
23528
24743
|
const existing = this.connectedDocuments.get(docId);
|
|
@@ -23549,26 +24764,40 @@ var DocumentManagerImpl = class {
|
|
|
23549
24764
|
`[DocumentManager] Connecting document ${docId} with permission: ${permissionHint}`
|
|
23550
24765
|
);
|
|
23551
24766
|
let opened = null;
|
|
23552
|
-
if (documentFormat === 3)
|
|
23553
|
-
|
|
23554
|
-
|
|
23555
|
-
|
|
23556
|
-
|
|
23557
|
-
|
|
23558
|
-
|
|
23559
|
-
|
|
23560
|
-
|
|
23561
|
-
|
|
23562
|
-
|
|
23563
|
-
|
|
23564
|
-
|
|
23565
|
-
|
|
23566
|
-
|
|
23567
|
-
|
|
23568
|
-
|
|
23569
|
-
|
|
23570
|
-
|
|
23571
|
-
|
|
24767
|
+
if (documentFormat === 3) this.recordLogConnecting.set(docId, (this.recordLogConnecting.get(docId) ?? 0) + 1);
|
|
24768
|
+
try {
|
|
24769
|
+
if (documentFormat === 3) {
|
|
24770
|
+
await this.recordLog.assertCanHost(docId);
|
|
24771
|
+
await this.withdrawIfOvertaken(docId, epoch, null);
|
|
24772
|
+
opened = await this.recordLog.open(docId);
|
|
24773
|
+
await this.withdrawIfOvertaken(docId, epoch, opened);
|
|
24774
|
+
this.recordLog.setCreatedLocally(docId, options?.createdLocally !== false);
|
|
24775
|
+
if (options?.localOnly) await this.recordLog.markLocalOnly(docId);
|
|
24776
|
+
if (options?.type) await this.recordLog.seedType(docId, options.type);
|
|
24777
|
+
await this.recordLog.adoptPermission(docId, permissionHint);
|
|
24778
|
+
await this.withdrawIfOvertaken(docId, epoch, opened);
|
|
24779
|
+
}
|
|
24780
|
+
await this.modelRegistry.initializeAllForDocument(
|
|
24781
|
+
yDoc,
|
|
24782
|
+
this.dbEngine,
|
|
24783
|
+
docId,
|
|
24784
|
+
permissionHint,
|
|
24785
|
+
documentFormat
|
|
24786
|
+
);
|
|
24787
|
+
if (documentFormat === 3) {
|
|
24788
|
+
await this.withdrawIfOvertaken(docId, epoch, opened);
|
|
24789
|
+
await this.recordLog.connect(docId);
|
|
24790
|
+
await this.withdrawIfOvertaken(docId, epoch, opened);
|
|
24791
|
+
}
|
|
24792
|
+
} catch (error) {
|
|
24793
|
+
if (opened && this.recordLogConnecting.get(docId) === 1) await this.releaseUnpublished(docId, opened);
|
|
24794
|
+
throw error;
|
|
24795
|
+
} finally {
|
|
24796
|
+
if (documentFormat === 3) {
|
|
24797
|
+
const left = (this.recordLogConnecting.get(docId) ?? 1) - 1;
|
|
24798
|
+
if (left > 0) this.recordLogConnecting.set(docId, left);
|
|
24799
|
+
else this.recordLogConnecting.delete(docId);
|
|
24800
|
+
}
|
|
23572
24801
|
}
|
|
23573
24802
|
this.connectedDocuments.set(docId, connectedDoc);
|
|
23574
24803
|
for (const modelName of this.modelRegistry.getActiveModels().keys()) {
|
|
@@ -23589,6 +24818,8 @@ var DocumentManagerImpl = class {
|
|
|
23589
24818
|
async rebindRecordLogDocument(docId, yDoc, permissionHint, options, epoch) {
|
|
23590
24819
|
Logger.info(`[DocumentManager] Rebinding format-3 document ${docId} in place (permission: ${permissionHint})`);
|
|
23591
24820
|
if (options?.createdLocally !== void 0) this.recordLog.setCreatedLocally(docId, options.createdLocally);
|
|
24821
|
+
if (options?.localOnly) await this.recordLog.markLocalOnly(docId);
|
|
24822
|
+
if (options?.type) await this.recordLog.seedType(docId, options.type);
|
|
23592
24823
|
await this.recordLog.adoptPermission(docId, permissionHint);
|
|
23593
24824
|
await this.modelRegistry.initializeAllForDocument(yDoc, this.dbEngine, docId, permissionHint, 3);
|
|
23594
24825
|
await this.recordLog.connect(docId);
|
|
@@ -23633,7 +24864,16 @@ var DocumentManagerImpl = class {
|
|
|
23633
24864
|
onSyncProgress: (listener) => binding.sessions.onSyncProgress(listener),
|
|
23634
24865
|
onWriteRefused: (listener) => this.ormContext.onRecordLogWriteRefused(listener),
|
|
23635
24866
|
onDeclared: (listener) => binding.onDeclared(listener),
|
|
24867
|
+
permissionChanged: async (docId, permission) => {
|
|
24868
|
+
if (!binding.storeOf(docId)) return;
|
|
24869
|
+
const connected = this.connectedDocuments.get(docId);
|
|
24870
|
+
if (connected) connected.permissionHint = permission;
|
|
24871
|
+
await binding.permissionChanged(docId, permission);
|
|
24872
|
+
},
|
|
23636
24873
|
syncIndexes: (docId, indexes) => binding.syncIndexes(docId, indexes),
|
|
24874
|
+
localIndexes: (docId) => binding.localIndexes(docId),
|
|
24875
|
+
registerLocalIndex: (docId, registration) => binding.registerLocalIndex(docId, registration),
|
|
24876
|
+
dropLocalIndex: (docId, name) => binding.dropLocalIndex(docId, name),
|
|
23637
24877
|
storedState: (docId) => binding.probe(docId),
|
|
23638
24878
|
syncMarks: (docId) => binding.storeOf(docId)?.marks() ?? null,
|
|
23639
24879
|
pending: async (docId) => {
|
|
@@ -23788,6 +25028,7 @@ var DocumentManagerImpl = class {
|
|
|
23788
25028
|
3
|
|
23789
25029
|
);
|
|
23790
25030
|
await this.recordLog.hydrateModel(docId, modelName);
|
|
25031
|
+
await this.recordLog.applyLocalDeclarations(docId);
|
|
23791
25032
|
return;
|
|
23792
25033
|
}
|
|
23793
25034
|
const touched = /* @__PURE__ */ new Set();
|
|
@@ -24461,6 +25702,7 @@ function loadSchemaFromTomlString(tomlString, options = {}) {
|
|
|
24461
25702
|
if (!models || typeof models !== "object") {
|
|
24462
25703
|
throw new Error("TOML schema must have a [models] section");
|
|
24463
25704
|
}
|
|
25705
|
+
const isTypeFile = parsed.type !== null && typeof parsed.type === "object" && !Array.isArray(parsed.type);
|
|
24464
25706
|
const schemas = [];
|
|
24465
25707
|
for (const [modelName, modelDef] of Object.entries(models)) {
|
|
24466
25708
|
checkUnknownKeys(
|
|
@@ -24471,6 +25713,9 @@ function loadSchemaFromTomlString(tomlString, options = {}) {
|
|
|
24471
25713
|
);
|
|
24472
25714
|
const fields = {};
|
|
24473
25715
|
const declaredFields = /* @__PURE__ */ new Map();
|
|
25716
|
+
if (isTypeFile && !(modelDef.fields && Object.prototype.hasOwnProperty.call(modelDef.fields, "id"))) {
|
|
25717
|
+
fields.id = { type: "id", autoAssign: true };
|
|
25718
|
+
}
|
|
24474
25719
|
if (modelDef.fields) {
|
|
24475
25720
|
for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
|
|
24476
25721
|
const context = `[models.${modelName}.fields.${fieldName}]`;
|
|
@@ -24768,6 +26013,7 @@ init_types();
|
|
|
24768
26013
|
init_guess();
|
|
24769
26014
|
init_condition();
|
|
24770
26015
|
init_write();
|
|
26016
|
+
init_declared_types();
|
|
24771
26017
|
|
|
24772
26018
|
// src/cli/v2/toml-writer.ts
|
|
24773
26019
|
function commentLines(comments) {
|