js-bao 0.12.0-alpha.16 → 0.12.0-alpha.18

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 CHANGED
@@ -892,7 +892,7 @@ var init_patterns = __esm({
892
892
 
893
893
  // src/engines/queryTableKey.ts
894
894
  function queryTableUpsert(quotedTable, columns, values) {
895
- const quoted3 = columns.map(quoteIdentifier);
895
+ const quoted4 = columns.map(quoteIdentifier);
896
896
  const placeholders = columns.map(() => "?").join(", ");
897
897
  const docAt = columns.indexOf(DOC);
898
898
  const idAt = columns.indexOf(ID);
@@ -902,7 +902,7 @@ function queryTableUpsert(quotedTable, columns, values) {
902
902
  const onConflict = updates.length > 0 ? `ON CONFLICT DO UPDATE SET ${updates.join(", ")}` : "ON CONFLICT DO NOTHING";
903
903
  return [
904
904
  {
905
- sql: `INSERT INTO ${quotedTable} (${quoted3.join(
905
+ sql: `INSERT INTO ${quotedTable} (${quoted4.join(
906
906
  ", "
907
907
  )}) VALUES (${placeholders}) ${onConflict};`,
908
908
  params: [...values]
@@ -919,7 +919,7 @@ function queryTableUpsert(quotedTable, columns, values) {
919
919
  });
920
920
  }
921
921
  statements.push({
922
- sql: `INSERT INTO ${quotedTable} (${quoted3.join(
922
+ sql: `INSERT INTO ${quotedTable} (${quoted4.join(
923
923
  ", "
924
924
  )}) SELECT ${placeholders} WHERE NOT EXISTS (SELECT 1 FROM ${quotedTable} WHERE ${quoteIdentifier(
925
925
  ID
@@ -971,11 +971,11 @@ function junctionInsert(quotedJunction, quotedForeignKey, quotedParent, recordId
971
971
  }
972
972
  const quotedId = quoteIdentifier(ID);
973
973
  const quotedDoc = quoteIdentifier(DOC);
974
- const held = `SELECT 1 FROM ${quotedJunction} WHERE ${quotedForeignKey} = ? AND ${quoteIdentifier(
974
+ const held2 = `SELECT 1 FROM ${quotedJunction} WHERE ${quotedForeignKey} = ? AND ${quoteIdentifier(
975
975
  "value"
976
976
  )} = ?`;
977
977
  return {
978
- sql: `INSERT INTO ${quotedJunction} ${columns} SELECT ?, ?, ?, p.${quotedDoc} FROM ${quotedParent} AS p WHERE p.${quotedId} = ? AND NOT EXISTS (${held} AND ${quotedDoc} IS p.${quotedDoc}) UNION ALL SELECT ?, ?, ?, NULL WHERE NOT EXISTS (SELECT 1 FROM ${quotedParent} WHERE ${quotedId} = ?) AND NOT EXISTS (${held});`,
978
+ sql: `INSERT INTO ${quotedJunction} ${columns} SELECT ?, ?, ?, p.${quotedDoc} FROM ${quotedParent} AS p WHERE p.${quotedId} = ? AND NOT EXISTS (${held2} AND ${quotedDoc} IS p.${quotedDoc}) UNION ALL SELECT ?, ?, ?, NULL WHERE NOT EXISTS (SELECT 1 FROM ${quotedParent} WHERE ${quotedId} = ?) AND NOT EXISTS (${held2});`,
979
979
  params: [
980
980
  id,
981
981
  recordId,
@@ -1841,32 +1841,32 @@ var init_DocumentQueryTranslator = __esm({
1841
1841
  if (!includeFields.includes("id")) {
1842
1842
  includeFields.unshift("id");
1843
1843
  }
1844
- const quoted3 = includeFields.map((field) => this.getQuotedField(field));
1844
+ const quoted4 = includeFields.map((field) => this.getQuotedField(field));
1845
1845
  if (selectDocument) {
1846
- quoted3.push(quoteIdentifier(DOCUMENT_TIEBREAKER));
1846
+ quoted4.push(quoteIdentifier(DOCUMENT_TIEBREAKER));
1847
1847
  }
1848
1848
  for (const field of aliasedSortFields ?? []) {
1849
- quoted3.push(
1849
+ quoted4.push(
1850
1850
  `${this.quotedSortField(field)} AS ${quoteIdentifier(
1851
1851
  cursorSortAlias(field)
1852
1852
  )}`
1853
1853
  );
1854
1854
  }
1855
- return quoted3.join(", ");
1855
+ return quoted4.join(", ");
1856
1856
  } else if (hasExcludes) {
1857
1857
  const allFields = Array.from(this.schema.keys());
1858
1858
  const selectedFields = allFields.filter(
1859
1859
  (field) => !excludeFields.includes(field)
1860
1860
  );
1861
- const quoted3 = selectedFields.map((field) => this.getQuotedField(field));
1861
+ const quoted4 = selectedFields.map((field) => this.getQuotedField(field));
1862
1862
  for (const field of aliasedSortFields ?? []) {
1863
- quoted3.push(
1863
+ quoted4.push(
1864
1864
  `${this.quotedSortField(field)} AS ${quoteIdentifier(
1865
1865
  cursorSortAlias(field)
1866
1866
  )}`
1867
1867
  );
1868
1868
  }
1869
- return quoted3.join(", ");
1869
+ return quoted4.join(", ");
1870
1870
  }
1871
1871
  return "*";
1872
1872
  }
@@ -2297,7 +2297,7 @@ function scanSignalsFor(model, filter, options, context) {
2297
2297
  const out = [];
2298
2298
  const root = signalFor(model, filter ?? {}, options?.sort, indexes, context.isSetField);
2299
2299
  if (root) out.push(root);
2300
- const walk = (specs, prefix) => {
2300
+ const walk2 = (specs, prefix) => {
2301
2301
  if (!Array.isArray(specs)) return;
2302
2302
  for (const spec of specs) {
2303
2303
  if (!isPlainObject(spec) || typeof spec.model !== "string") continue;
@@ -2311,10 +2311,10 @@ function scanSignalsFor(model, filter, options, context) {
2311
2311
  leg = signalFor(spec.model, { id: { $in: [LEG_KEY] }, ...extra }, void 0, indexes, context.isSetField);
2312
2312
  }
2313
2313
  if (leg) out.push({ ...leg, path });
2314
- walk(spec.include, path);
2314
+ walk2(spec.include, path);
2315
2315
  }
2316
2316
  };
2317
- walk(options?.include, "");
2317
+ walk2(options?.include, "");
2318
2318
  return out;
2319
2319
  }
2320
2320
  var RANGES, LEG_KEY, isPlainObject, isPlainObjectOrArray, Indexes;
@@ -3240,15 +3240,343 @@ var init_vectorFields = __esm({
3240
3240
  }
3241
3241
  });
3242
3242
 
3243
+ // src/models/jsonFields.ts
3244
+ function quoted(text, path) {
3245
+ for (let i = 0; i < text.length; i++) {
3246
+ const unit = text.charCodeAt(i);
3247
+ if (unit >= 55296 && unit <= 56319) {
3248
+ const next = text.charCodeAt(i + 1);
3249
+ if (next >= 56320 && next <= 57343) {
3250
+ i++;
3251
+ continue;
3252
+ }
3253
+ }
3254
+ if (unit >= 55296 && unit <= 57343) throw new Refusal("surrogate", path, `${path} holds a lone surrogate, which JSON text cannot carry`);
3255
+ }
3256
+ return JSON.stringify(text);
3257
+ }
3258
+ function kindOf(value) {
3259
+ if (value === void 0) return "undefined";
3260
+ if (typeof value !== "object") return typeof value;
3261
+ return Object.prototype.toString.call(value).slice(8, -1);
3262
+ }
3263
+ function canonical(value, path) {
3264
+ if (value === null) return "null";
3265
+ if (value === true) return "true";
3266
+ if (value === false) return "false";
3267
+ if (typeof value === "number") {
3268
+ if (!Number.isFinite(value)) throw new Refusal("number", path, `${path} is ${String(value)}; JSON holds finite numbers only`);
3269
+ if (Math.abs(value) > MAX_EXACT) {
3270
+ throw new Refusal("number", path, `${path} is ${String(value)}; a db3 JSON value holds numbers up to 2^53 in magnitude (store a larger one as a string)`);
3271
+ }
3272
+ return Object.is(value, -0) ? "0" : String(value);
3273
+ }
3274
+ if (typeof value === "string") return quoted(value, path);
3275
+ if (Array.isArray(value)) {
3276
+ const items = [];
3277
+ for (let i = 0; i < value.length; i++) items.push(canonical(value[i], `${path}[${i}]`));
3278
+ return `[${items.join(",")}]`;
3279
+ }
3280
+ if (typeof value === "object" && Object.prototype.toString.call(value) === "[object Object]") {
3281
+ const record = value;
3282
+ const keys = Object.keys(record).filter((key) => record[key] !== void 0).sort();
3283
+ return `{${keys.map((key) => `${quoted(key, path)}:${canonical(record[key], `${path}.${key}`)}`).join(",")}}`;
3284
+ }
3285
+ throw new Refusal("type", path, `${path} is ${kindOf(value)}; a db3 JSON value holds only objects, arrays, strings, numbers, booleans and null`);
3286
+ }
3287
+ function canonicalDb3Json(value) {
3288
+ if (value === null || typeof value !== "object" || Array.isArray(value) || Object.prototype.toString.call(value) !== "[object Object]") {
3289
+ const what = Array.isArray(value) ? "an array" : value === null ? "null" : kindOf(value);
3290
+ return { ok: false, kind: "root", path: "value", reason: `the value is ${what}; a db3 JSON field holds an object` };
3291
+ }
3292
+ try {
3293
+ return { ok: true, text: canonical(value, "value") };
3294
+ } catch (error) {
3295
+ if (error instanceof Refusal) return { ok: false, kind: error.kind, path: error.path, reason: error.reason };
3296
+ throw error;
3297
+ }
3298
+ }
3299
+ function isType(value, type) {
3300
+ if (type === "array") return Array.isArray(value);
3301
+ if (type === "object") return isNode(value);
3302
+ if (type === "string") return typeof value === "string";
3303
+ if (type === "number") return typeof value === "number" && !Number.isNaN(value);
3304
+ if (type === "integer") return Number.isInteger(value);
3305
+ if (type === "boolean") return typeof value === "boolean";
3306
+ if (type === "null") return value === null;
3307
+ return true;
3308
+ }
3309
+ function enumTaggedOneOf(schema) {
3310
+ const members = schema.oneOf;
3311
+ if (!Array.isArray(members) || members.length < 2) return null;
3312
+ if (!members.every((m) => isNode(m) && m.type === "object")) return null;
3313
+ if (ONE_OF_SIBLINGS.some((key) => hasOwn(schema, key))) return null;
3314
+ const literals = members.map((m) => {
3315
+ const found = /* @__PURE__ */ new Map();
3316
+ if (!isNode(m.properties)) return found;
3317
+ for (const [name, sub] of Object.entries(m.properties)) {
3318
+ if (isNode(sub) && Array.isArray(sub.enum) && sub.enum.length === 1 && isScalarTag(sub.enum[0])) found.set(name, sub.enum[0]);
3319
+ }
3320
+ return found;
3321
+ });
3322
+ const candidates = [...literals[0].keys()].filter((name) => {
3323
+ if (!literals.every((map) => map.has(name))) return false;
3324
+ return new Set(literals.map((map) => JSON.stringify(map.get(name)))).size === literals.length;
3325
+ });
3326
+ if (candidates.length !== 1) return null;
3327
+ return { discriminant: candidates[0], members: members.map((m, i) => ({ tag: literals[i].get(candidates[0]), schema: m })) };
3328
+ }
3329
+ function requiredTagOneOf(members) {
3330
+ const objects = members.filter((m) => isNode(m) && m.type === "object");
3331
+ if (objects.length < 2 || objects.length !== members.length) return null;
3332
+ const tags = objects.map((m) => {
3333
+ const found = /* @__PURE__ */ new Map();
3334
+ if (!isNode(m.properties)) return found;
3335
+ for (const [name, sub] of Object.entries(m.properties)) {
3336
+ if (!isNode(sub)) continue;
3337
+ if (Array.isArray(sub.enum) && sub.enum.length === 1 && isScalarTag(sub.enum[0])) found.set(name, sub.enum[0]);
3338
+ else if (hasOwn(sub, "const") && isScalarTag(sub.const)) found.set(name, sub.const);
3339
+ }
3340
+ return found;
3341
+ });
3342
+ const candidates = [...tags[0].keys()].filter((name) => {
3343
+ if (!tags.every((map) => map.has(name))) return false;
3344
+ if (!objects.every((m) => Array.isArray(m.required) && m.required.includes(name))) return false;
3345
+ return new Set(tags.map((map) => JSON.stringify(map.get(name)))).size === tags.length;
3346
+ });
3347
+ if (candidates.length !== 1) return null;
3348
+ return { discriminant: candidates[0], members: objects.map((schema, i) => ({ tag: tags[i].get(candidates[0]), schema })) };
3349
+ }
3350
+ function bounds(value, schema, path, issues) {
3351
+ const fail2 = (message) => issues.push({ path, message });
3352
+ if (typeof value === "number") {
3353
+ if (typeof schema.minimum === "number" && value < schema.minimum) fail2(`${path} must be >= ${schema.minimum}`);
3354
+ if (typeof schema.maximum === "number" && value > schema.maximum) fail2(`${path} must be <= ${schema.maximum}`);
3355
+ }
3356
+ if (typeof value === "string") {
3357
+ const length = [...value].length;
3358
+ const tooShort = typeof schema.minLength === "number" && length < schema.minLength;
3359
+ const tooLong = typeof schema.maxLength === "number" && length > schema.maxLength;
3360
+ if (tooShort) fail2(`${path} must be at least ${schema.minLength} characters`);
3361
+ if (tooLong) fail2(`${path} must be at most ${schema.maxLength} characters`);
3362
+ if (typeof schema.pattern === "string" && !tooShort && !tooLong) {
3363
+ let pattern = null;
3364
+ try {
3365
+ pattern = new RegExp(schema.pattern, "u");
3366
+ } catch {
3367
+ fail2(`${path} cannot be checked: the schema's pattern ${JSON.stringify(schema.pattern)} is not a valid regular expression`);
3368
+ }
3369
+ if (pattern && !pattern.test(value)) fail2(`${path} must match the pattern ${schema.pattern}`);
3370
+ }
3371
+ }
3372
+ if (Array.isArray(value)) {
3373
+ if (typeof schema.minItems === "number" && value.length < schema.minItems) fail2(`${path} must have at least ${schema.minItems} items`);
3374
+ if (typeof schema.maxItems === "number" && value.length > schema.maxItems) {
3375
+ fail2(`${path} must have at most ${schema.maxItems} items`);
3376
+ return true;
3377
+ }
3378
+ }
3379
+ return false;
3380
+ }
3381
+ function walk(value, schema, path, issues) {
3382
+ if (!isNode(schema)) return;
3383
+ const fail2 = (at, message) => issues.push({ path: at, message });
3384
+ const union = enumTaggedOneOf(schema);
3385
+ if (union) {
3386
+ if (!isNode(value)) return void fail2(path, `${path} must be object`);
3387
+ bounds(value, schema, path, issues);
3388
+ const tag = value[union.discriminant];
3389
+ const matched = union.members.find((m) => m.tag === tag);
3390
+ if (!matched) {
3391
+ const expected = union.members.map((m) => JSON.stringify(m.tag)).join(", ");
3392
+ return void fail2(`${path}.${union.discriminant}`, `${path}.${union.discriminant} ${JSON.stringify(tag)} matches no case (expected one of ${expected})`);
3393
+ }
3394
+ return walk(value, matched.schema, path, issues);
3395
+ }
3396
+ const types = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : [];
3397
+ if (types.length > 0 && !types.some((type) => isType(value, type))) return void fail2(path, `${path} must be ${types.join(" or ")}`);
3398
+ if (Array.isArray(schema.enum) && !schema.enum.includes(value)) return void fail2(path, `${path} must be one of ${schema.enum.join(", ")}`);
3399
+ if (bounds(value, schema, path, issues)) return;
3400
+ if (isNode(value)) {
3401
+ const properties = isNode(schema.properties) ? schema.properties : {};
3402
+ const required = Array.isArray(schema.required) ? schema.required : [];
3403
+ for (const key of required) {
3404
+ if (!hasOwn(value, String(key))) fail2(`${path}.${key}`, `${path}.${key} is required`);
3405
+ }
3406
+ for (const [key, child] of Object.entries(properties)) {
3407
+ if (hasOwn(value, key)) walk(value[key], child, `${path}.${key}`, issues);
3408
+ }
3409
+ if (schema.additionalProperties === false) {
3410
+ for (const key of Object.keys(value)) {
3411
+ if (!hasOwn(properties, key)) fail2(`${path}.${key}`, `${path}.${key} is not allowed`);
3412
+ }
3413
+ }
3414
+ }
3415
+ if (Array.isArray(value) && isNode(schema.items)) {
3416
+ value.forEach((item, i) => walk(item, schema.items, `${path}[${i}]`, issues));
3417
+ }
3418
+ const oneOf = schema.oneOf;
3419
+ if (Array.isArray(oneOf) && oneOf.length > 0) {
3420
+ const tagged = requiredTagOneOf(oneOf);
3421
+ if (tagged) {
3422
+ if (!isNode(value)) return void fail2(path, `${path} must be object`);
3423
+ const tag = hasOwn(value, tagged.discriminant) ? value[tagged.discriminant] : void 0;
3424
+ const matched = tagged.members.find((m) => m.tag === tag);
3425
+ if (!matched) {
3426
+ const expected = tagged.members.map((m) => JSON.stringify(m.tag)).join(", ");
3427
+ return void fail2(`${path}.${tagged.discriminant}`, `${path}.${tagged.discriminant} ${JSON.stringify(tag)} matches no case (expected one of ${expected})`);
3428
+ }
3429
+ return walk(value, matched.schema, path, issues);
3430
+ }
3431
+ const matching = oneOf.filter((member) => {
3432
+ const trial = [];
3433
+ walk(value, member, path, trial);
3434
+ return trial.length === 0;
3435
+ }).length;
3436
+ if (matching === 0) fail2(path, `${path} matches no member of oneOf`);
3437
+ if (matching > 1) fail2(path, `${path} matches more than one member of oneOf`);
3438
+ }
3439
+ }
3440
+ function validateDb3Json(schema, value) {
3441
+ const issues = [];
3442
+ walk(value, schema, "value", issues);
3443
+ return issues;
3444
+ }
3445
+ function bindDb3JsonFields(modelClass, fields) {
3446
+ const schema = modelClass.getSchema?.();
3447
+ const modelName = schema?.options?.name ?? modelClass.name ?? "model";
3448
+ const bound = bindings.get(modelClass) ?? /* @__PURE__ */ new Map();
3449
+ for (const [field, def] of Object.entries(fields)) {
3450
+ if (!def || typeof def.id !== "string" || !isNode(def.schema)) {
3451
+ throw new Error(`bindDb3JsonFields: ${modelName}.${field} needs a def's id and its compiled schema; regenerate schema-defs.generated.ts with \`primitive functions codegen\`.`);
3452
+ }
3453
+ const declared = schema?.fields?.get?.(field);
3454
+ if (schema?.fields && declared?.type !== "string") {
3455
+ throw new Error(
3456
+ `bindDb3JsonFields: ${modelName}.${field} is ${declared ? `a ${declared.type} field` : "not declared"}; a JSON field is stored in a string field. Regenerate the models with js-bao-codegen-v2.`
3457
+ );
3458
+ }
3459
+ bound.set(field, { id: def.id, schema: def.schema });
3460
+ }
3461
+ bindings.set(modelClass, bound);
3462
+ }
3463
+ function db3JsonDefOf(modelClass, field) {
3464
+ for (let at = modelClass; at && at !== Function.prototype; at = Object.getPrototypeOf(at)) {
3465
+ const def = bindings.get(at)?.get(field);
3466
+ if (def) return def;
3467
+ }
3468
+ return void 0;
3469
+ }
3470
+ function db3JsonText(record, field) {
3471
+ const model = record;
3472
+ if (!db3JsonDefOf(model.constructor, field)) {
3473
+ const name = model.constructor?.getSchema?.()?.options?.name ?? model.constructor?.name ?? "model";
3474
+ throw new Error(`${name}.${field} is not a JSON field: db3JsonText reads a field bound to a schemas/ object def.`);
3475
+ }
3476
+ const stored = model.hasFieldChanged(field) ? model._localChanges?.[field] : model.getOriginalValue(field);
3477
+ return stored === null || stored === void 0 ? stored : String(stored);
3478
+ }
3479
+ function storeDb3JsonFields(record, data, fields) {
3480
+ for (const [field, options] of fields) {
3481
+ if (options?.type !== "string" || !db3JsonDefOf(record.constructor, field)) continue;
3482
+ const stored = db3JsonText(record, field);
3483
+ if (stored === void 0) delete data[field];
3484
+ else data[field] = stored;
3485
+ }
3486
+ }
3487
+ function encodeDb3JsonField(model, field, def, value) {
3488
+ if (value === null || value === void 0) return value;
3489
+ const encoded = canonicalDb3Json(value);
3490
+ if (!encoded.ok) throw new Db3JsonValueError({ model, field, def: def.id, path: encoded.path, reason: encoded.reason, kind: encoded.kind });
3491
+ const issues = validateDb3Json(def.schema, JSON.parse(encoded.text));
3492
+ if (issues.length > 0) {
3493
+ throw new Db3JsonValueError({ model, field, def: def.id, path: issues[0].path, reason: issues.map((issue) => issue.message).join("; "), kind: "schema" });
3494
+ }
3495
+ return encoded.text;
3496
+ }
3497
+ function deepFreeze(value) {
3498
+ if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
3499
+ for (const child of Object.values(value)) deepFreeze(child);
3500
+ Object.freeze(value);
3501
+ }
3502
+ return value;
3503
+ }
3504
+ function readDb3JsonField(model, field, stored) {
3505
+ if (stored === null || stored === void 0) return stored;
3506
+ if (typeof stored === "string") {
3507
+ if (decoded.has(stored)) return decoded.get(stored);
3508
+ let value;
3509
+ try {
3510
+ value = JSON.parse(stored);
3511
+ } catch {
3512
+ value = void 0;
3513
+ }
3514
+ if (isNode(value)) {
3515
+ deepFreeze(value);
3516
+ if (decoded.size >= DECODED_CACHE) decoded.delete(decoded.keys().next().value);
3517
+ decoded.set(stored, value);
3518
+ return value;
3519
+ }
3520
+ }
3521
+ const key = `${model}\0${field}`;
3522
+ if (!misreadFields.has(key)) {
3523
+ misreadFields.add(key);
3524
+ console.warn(`[js-bao] ${model}.${field}: a stored value is not JSON text of an object; it reads as undefined (its text stays readable through db3JsonText(record, "${field}"))`);
3525
+ }
3526
+ return void 0;
3527
+ }
3528
+ var Db3JsonValueError, Refusal, MAX_EXACT, isNode, hasOwn, isScalarTag, ONE_OF_SIBLINGS, bindings, misreadFields, decoded, DECODED_CACHE;
3529
+ var init_jsonFields = __esm({
3530
+ "src/models/jsonFields.ts"() {
3531
+ "use strict";
3532
+ Db3JsonValueError = class _Db3JsonValueError extends Error {
3533
+ code = "DB3_JSON_INVALID";
3534
+ model;
3535
+ field;
3536
+ def;
3537
+ path;
3538
+ reason;
3539
+ kind;
3540
+ constructor(details) {
3541
+ super(`${details.model}.${details.field} is typed by ${details.def}: ${details.reason}`);
3542
+ this.name = "Db3JsonValueError";
3543
+ this.model = details.model;
3544
+ this.field = details.field;
3545
+ this.def = details.def;
3546
+ this.path = details.path;
3547
+ this.reason = details.reason;
3548
+ this.kind = details.kind;
3549
+ Object.setPrototypeOf(this, _Db3JsonValueError.prototype);
3550
+ }
3551
+ };
3552
+ Refusal = class {
3553
+ constructor(kind, path, reason) {
3554
+ this.kind = kind;
3555
+ this.path = path;
3556
+ this.reason = reason;
3557
+ }
3558
+ };
3559
+ MAX_EXACT = 2 ** 53;
3560
+ isNode = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3561
+ hasOwn = (value, key) => value !== null && value !== void 0 && Object.prototype.hasOwnProperty.call(value, key);
3562
+ isScalarTag = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean";
3563
+ ONE_OF_SIBLINGS = ["type", "properties", "required", "additionalProperties", "items", "enum"];
3564
+ bindings = /* @__PURE__ */ new WeakMap();
3565
+ misreadFields = /* @__PURE__ */ new Set();
3566
+ decoded = /* @__PURE__ */ new Map();
3567
+ DECODED_CACHE = 256;
3568
+ }
3569
+ });
3570
+
3243
3571
  // src/query/indexPlacement.ts
3244
3572
  function findNearOperator(filter) {
3245
3573
  const seen = /* @__PURE__ */ new Set();
3246
- const walk = (value) => {
3574
+ const walk2 = (value) => {
3247
3575
  if (value === null || typeof value !== "object" || seen.has(value)) return null;
3248
3576
  seen.add(value);
3249
3577
  if (Array.isArray(value)) {
3250
3578
  for (const member of value) {
3251
- const found = walk(member);
3579
+ const found = walk2(member);
3252
3580
  if (found) return found;
3253
3581
  }
3254
3582
  return null;
@@ -3258,12 +3586,12 @@ function findNearOperator(filter) {
3258
3586
  const field = member?.field;
3259
3587
  return { field: typeof field === "string" ? field : null };
3260
3588
  }
3261
- const found = walk(member);
3589
+ const found = walk2(member);
3262
3590
  if (found) return found;
3263
3591
  }
3264
3592
  return null;
3265
3593
  };
3266
- return walk(filter);
3594
+ return walk2(filter);
3267
3595
  }
3268
3596
  function findNearInRead(model, filter, include) {
3269
3597
  const near = findNearOperator(filter);
@@ -4595,7 +4923,7 @@ function textTokenize(tokenizer) {
4595
4923
  function textTableDDL(table, fields, options) {
4596
4924
  const columns = fields.map((_, i) => textColumnAlias(i));
4597
4925
  const prefix = options.prefix.length > 0 ? `, prefix='${options.prefix.join(" ")}'` : "";
4598
- return `CREATE VIRTUAL TABLE ${quoted(table)} USING fts5(${columns.join(", ")}, content='', tokenize='${textTokenize(options.tokenizer)}'${prefix})`;
4926
+ return `CREATE VIRTUAL TABLE ${quoted2(table)} USING fts5(${columns.join(", ")}, content='', tokenize='${textTokenize(options.tokenizer)}'${prefix})`;
4599
4927
  }
4600
4928
  function textValueSql(row, fields) {
4601
4929
  return fields.map((field) => {
@@ -4604,12 +4932,12 @@ function textValueSql(row, fields) {
4604
4932
  });
4605
4933
  }
4606
4934
  function textInsertSql(table, fields) {
4607
- return `INSERT INTO ${quoted(table)} (${["rowid", ...fields.map((_, i) => textColumnAlias(i))].join(", ")})`;
4935
+ return `INSERT INTO ${quoted2(table)} (${["rowid", ...fields.map((_, i) => textColumnAlias(i))].join(", ")})`;
4608
4936
  }
4609
4937
  function textDeleteSql(table, fields) {
4610
- return `INSERT INTO ${quoted(table)} (${[quoted(table), "rowid", ...fields.map((_, i) => textColumnAlias(i))].join(", ")})`;
4938
+ return `INSERT INTO ${quoted2(table)} (${[quoted2(table), "rowid", ...fields.map((_, i) => textColumnAlias(i))].join(", ")})`;
4611
4939
  }
4612
- var TEXT_INDEX_TOKENIZERS, TEXT_INDEX_MAX_PREFIXES, TEXT_INDEX_MAX_PREFIX_LENGTH, OPTION_KEYS, TextIndexOptionsError, isPlainObject3, quoted, literal2;
4940
+ var TEXT_INDEX_TOKENIZERS, TEXT_INDEX_MAX_PREFIXES, TEXT_INDEX_MAX_PREFIX_LENGTH, OPTION_KEYS, TextIndexOptionsError, isPlainObject3, quoted2, literal2;
4613
4941
  var init_textIndex = __esm({
4614
4942
  "src/record-log/textIndex.ts"() {
4615
4943
  "use strict";
@@ -4625,7 +4953,7 @@ var init_textIndex = __esm({
4625
4953
  }
4626
4954
  };
4627
4955
  isPlainObject3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4628
- quoted = (name) => `"${name.replace(/"/g, '""')}"`;
4956
+ quoted2 = (name) => `"${name.replace(/"/g, '""')}"`;
4629
4957
  literal2 = (text) => `'${text.replace(/'/g, "''")}'`;
4630
4958
  }
4631
4959
  });
@@ -4681,7 +5009,7 @@ function textColumnsOf(fields) {
4681
5009
  return fields.map((field, i) => ({ field, alias: textColumnAlias(i) }));
4682
5010
  }
4683
5011
  function matchExpression(search, indexFields) {
4684
- const terms = search.terms.map((term) => quoted2(term.text) + (search.prefix ? "*" : ""));
5012
+ const terms = search.terms.map((term) => quoted3(term.text) + (search.prefix ? "*" : ""));
4685
5013
  const joined = terms.join(search.mode === "any" ? " OR " : " AND ");
4686
5014
  if (search.fields === null) return joined;
4687
5015
  const columns = textColumnsOf(indexFields);
@@ -4690,11 +5018,11 @@ function matchExpression(search, indexFields) {
4690
5018
  if (!column) {
4691
5019
  throw new DocumentQueryError(`$search.fields names ${field}, which the text index does not cover: ${indexFields.join(", ")}`);
4692
5020
  }
4693
- return quoted2(column.alias);
5021
+ return quoted3(column.alias);
4694
5022
  });
4695
5023
  return `{${selected.join(" ")}} : (${joined})`;
4696
5024
  }
4697
- var SEARCH_KEYS, TOKEN_CHARACTER, quoted2;
5025
+ var SEARCH_KEYS, TOKEN_CHARACTER, quoted3;
4698
5026
  var init_textSearch = __esm({
4699
5027
  "src/query/textSearch.ts"() {
4700
5028
  "use strict";
@@ -4702,7 +5030,7 @@ var init_textSearch = __esm({
4702
5030
  init_textIndex();
4703
5031
  SEARCH_KEYS = ["query", "mode", "prefix", "fields"];
4704
5032
  TOKEN_CHARACTER = /[\p{L}\p{N}\p{Co}]/u;
4705
- quoted2 = (text) => `"${text.replace(/"/g, '""')}"`;
5033
+ quoted3 = (text) => `"${text.replace(/"/g, '""')}"`;
4706
5034
  }
4707
5035
  });
4708
5036
 
@@ -4723,19 +5051,19 @@ function parseRecordRow(row) {
4723
5051
  return { id: _id, type: _type, ...parsed, ...decodeProjectedColumns(rest) };
4724
5052
  }
4725
5053
  function decodeProjectedColumns(columns) {
4726
- const decoded = {};
5054
+ const decoded2 = {};
4727
5055
  for (const [column, value] of Object.entries(columns)) {
4728
5056
  if (column.startsWith(CURSOR_SORT_ALIAS_PREFIX)) {
4729
- decoded[column] = parseJsonColumn(value);
5057
+ decoded2[column] = parseJsonColumn(value);
4730
5058
  continue;
4731
5059
  }
4732
5060
  if (!column.startsWith(PROJECTED_JSON_ALIAS_PREFIX)) {
4733
- decoded[column] = value;
5061
+ decoded2[column] = value;
4734
5062
  continue;
4735
5063
  }
4736
- decoded[column.slice(PROJECTED_JSON_ALIAS_PREFIX.length)] = parseJsonColumn(value);
5064
+ decoded2[column.slice(PROJECTED_JSON_ALIAS_PREFIX.length)] = parseJsonColumn(value);
4737
5065
  }
4738
- return decoded;
5066
+ return decoded2;
4739
5067
  }
4740
5068
  function parseJsonColumn(value) {
4741
5069
  if (typeof value !== "string") return value;
@@ -4755,7 +5083,7 @@ var init_recordRow = __esm({
4755
5083
  });
4756
5084
 
4757
5085
  // src/query/JsonQueryTranslator.ts
4758
- var SYSTEM_FIELDS2, QUERY_IN_LIST_MAX_VALUES, QUERY_STATEMENT_MAX_BOUND_PARAMS, SEARCH_ALIAS, SCORE_KEY, NEAR_ALIAS, JsonQueryTranslator;
5086
+ var SYSTEM_FIELDS2, QUERY_IN_LIST_MAX_VALUES, QUERY_STATEMENT_MAX_BOUND_PARAMS, UNSET_PATH, SEARCH_ALIAS, SCORE_KEY, NEAR_ALIAS, JsonQueryTranslator;
4759
5087
  var init_JsonQueryTranslator = __esm({
4760
5088
  "src/query/JsonQueryTranslator.ts"() {
4761
5089
  "use strict";
@@ -4771,6 +5099,7 @@ var init_JsonQueryTranslator = __esm({
4771
5099
  SYSTEM_FIELDS2 = /* @__PURE__ */ new Set(["id", "type"]);
4772
5100
  QUERY_IN_LIST_MAX_VALUES = 1e3;
4773
5101
  QUERY_STATEMENT_MAX_BOUND_PARAMS = 100;
5102
+ UNSET_PATH = "$._unset";
4774
5103
  SEARCH_ALIAS = "_search";
4775
5104
  SCORE_KEY = "_score";
4776
5105
  NEAR_ALIAS = "_near";
@@ -4868,7 +5197,7 @@ var init_JsonQueryTranslator = __esm({
4868
5197
  assertValidIdentifier(fieldName, "query field");
4869
5198
  this.fieldSqlCache.set(
4870
5199
  fieldName,
4871
- `json_extract(_data, '$.${fieldName}')`
5200
+ `json_extract(_data, ${this.dataPathLiteral(fieldName)})`
4872
5201
  );
4873
5202
  }
4874
5203
  }
@@ -5532,8 +5861,7 @@ var init_JsonQueryTranslator = __esm({
5532
5861
  if (SYSTEM_FIELDS2.has(fieldName)) {
5533
5862
  return `${this.table}.${quoteIdentifier(`_${fieldName}`)}`;
5534
5863
  }
5535
- assertValidIdentifier(fieldName, "query field");
5536
- return `json_extract(${this.table}._data, '$.${fieldName}')`;
5864
+ return `json_extract(${this.table}._data, ${this.dataPathLiteral(fieldName)})`;
5537
5865
  }
5538
5866
  /**
5539
5867
  * A membership condition over the array a record holds in `fieldName`
@@ -5550,7 +5878,7 @@ var init_JsonQueryTranslator = __esm({
5550
5878
  }
5551
5879
  /** The member index `fieldName`'s members are read from, or `null` (#5150). */
5552
5880
  memberIndexOf(fieldName) {
5553
- if (SYSTEM_FIELDS2.has(fieldName)) return null;
5881
+ if (SYSTEM_FIELDS2.has(fieldName) || this.options.unsetFields?.has(fieldName)) return null;
5554
5882
  return this.options.memberIndexTable?.(fieldName) ?? null;
5555
5883
  }
5556
5884
  /**
@@ -5562,12 +5890,32 @@ var init_JsonQueryTranslator = __esm({
5562
5890
  }
5563
5891
  /** `<table>._data, '$.<field>'`: the arguments that address a field's stored JSON. */
5564
5892
  dataPathSql(fieldName) {
5565
- return `${this.table}._data, '${this.dataPath(fieldName)}'`;
5893
+ return `${this.table}._data, ${this.dataPathLiteral(fieldName)}`;
5566
5894
  }
5567
- /** `$.<field>`: the JSON path of a field in `_data`. */
5895
+ /**
5896
+ * `$.<field>`: the JSON path of a field in `_data`, as a bound value. A
5897
+ * field unset only in some documents is bound at its stored path: each such
5898
+ * site sits behind a {@link dataPathLiteral} guard that reads it as unset
5899
+ * in those documents.
5900
+ */
5568
5901
  dataPath(fieldName) {
5569
5902
  assertValidIdentifier(fieldName, "query field");
5570
- return `$.${fieldName}`;
5903
+ if (!this.options.unsetFields?.has(fieldName)) return `$.${fieldName}`;
5904
+ return this.options.unsetFieldDocuments?.has(fieldName) ? `$.${fieldName}` : UNSET_PATH;
5905
+ }
5906
+ /**
5907
+ * The JSON path of a field in `_data` as SQL: the quoted path, or, for a
5908
+ * field unset in some documents only, a `CASE` on the row's document that
5909
+ * picks the unset path in those. Any other field's SQL is unchanged.
5910
+ */
5911
+ dataPathLiteral(fieldName) {
5912
+ assertValidIdentifier(fieldName, "query field");
5913
+ const documents = this.options.unsetFields?.has(fieldName) ? this.options.unsetFieldDocuments?.get(fieldName) : void 0;
5914
+ if (!documents) return `'${this.dataPath(fieldName)}'`;
5915
+ if (!documents.length) return `'$.${fieldName}'`;
5916
+ const column = `${this.table}.${quoteIdentifier(this.documentColumn)}`;
5917
+ const ids = documents.map((id) => `'${String(id).replace(/'/g, "''")}'`).join(", ");
5918
+ return `(CASE WHEN ${column} IN (${ids}) THEN '${UNSET_PATH}' ELSE '$.${fieldName}' END)`;
5571
5919
  }
5572
5920
  /**
5573
5921
  * Translate field condition to SQL
@@ -5824,10 +6172,10 @@ var init_JsonQueryTranslator = __esm({
5824
6172
  return value ? { sql: `${fieldSql} IS NOT NULL`, params: [] } : { sql: `${fieldSql} IS NULL`, params: [] };
5825
6173
  } else {
5826
6174
  return value ? {
5827
- sql: `json_type(_data, '$.${fieldName}') IS NOT NULL`,
6175
+ sql: `json_type(_data, ${this.dataPathLiteral(fieldName)}) IS NOT NULL`,
5828
6176
  params: []
5829
6177
  } : {
5830
- sql: `json_type(_data, '$.${fieldName}') IS NULL`,
6178
+ sql: `json_type(_data, ${this.dataPathLiteral(fieldName)}) IS NULL`,
5831
6179
  params: []
5832
6180
  };
5833
6181
  }
@@ -5964,13 +6312,12 @@ var init_JsonQueryTranslator = __esm({
5964
6312
  for (const field of includeFields) {
5965
6313
  if (field === "id" || field === "type") continue;
5966
6314
  selectParts.push(
5967
- `_data -> '$.${field}' AS ${quoteIdentifier(projectedJsonAlias(field))}`
6315
+ `_data -> ${this.dataPathLiteral(field)} AS ${quoteIdentifier(projectedJsonAlias(field))}`
5968
6316
  );
5969
6317
  }
5970
6318
  for (const field of aliasedSortFields ?? []) {
5971
- assertValidIdentifier(field, "query field");
5972
6319
  selectParts.push(
5973
- `_data -> '$.${field}' AS ${quoteIdentifier(cursorSortAlias(field))}`
6320
+ `_data -> ${this.dataPathLiteral(field)} AS ${quoteIdentifier(cursorSortAlias(field))}`
5974
6321
  );
5975
6322
  }
5976
6323
  return selectParts.join(", ");
@@ -6234,12 +6581,13 @@ var init_JsonQueryTranslator = __esm({
6234
6581
  });
6235
6582
 
6236
6583
  // src/record-log-client/condition.ts
6237
- function conditionTranslator(model) {
6584
+ function conditionTranslator(model, unsetFields) {
6238
6585
  return new JsonQueryTranslator(model, void 0, {
6239
6586
  includeDocId: false,
6240
6587
  table: CONDITION_TABLE,
6241
6588
  stringSets: "json_each",
6242
- setArraysInData: true
6589
+ setArraysInData: true,
6590
+ ...unsetFields?.size ? { unsetFields } : {}
6243
6591
  });
6244
6592
  }
6245
6593
  function sqlText(value) {
@@ -6256,14 +6604,14 @@ function conditionProblem(condition) {
6256
6604
  return `condition: ${error instanceof Error ? error.message : String(error)}`;
6257
6605
  }
6258
6606
  }
6259
- function conditionHolds(sql, model, id, row, condition) {
6260
- const { sql: where2, params } = conditionTranslator(model).translateFilter(condition);
6607
+ function conditionHolds(sql, model, id, row, condition, unsetFields) {
6608
+ const { sql: where2, params } = conditionTranslator(model, unsetFields).translateFilter(condition);
6261
6609
  const query = `WITH ${CONDITION_TABLE}(_id, _type, _data) AS (SELECT ${sqlText(id)}, ${sqlText(model)}, ?) SELECT 1 AS hit FROM ${CONDITION_TABLE}${where2 ? ` WHERE ${where2}` : ""}`;
6262
6610
  const [hit] = [...sql.exec(query, JSON.stringify(row), ...params)];
6263
6611
  return hit !== void 0;
6264
6612
  }
6265
- function storedConditionHolds(sql, model, id, condition) {
6266
- const { sql: where2, params } = conditionTranslator(model).translateFilter(condition);
6613
+ function storedConditionHolds(sql, model, id, condition, unsetFields) {
6614
+ const { sql: where2, params } = conditionTranslator(model, unsetFields).translateFilter(condition);
6267
6615
  const query = `WITH ${CONDITION_TABLE}(_id, _type, _data) AS (SELECT _id, _type, _data FROM records WHERE _type = ${sqlText(model)} AND _id = ${sqlText(id)} AND _dead = 0) SELECT 1 AS hit FROM ${CONDITION_TABLE}${where2 ? ` WHERE ${where2}` : ""}`;
6268
6616
  const [hit] = [...sql.exec(query, ...params)];
6269
6617
  return hit !== void 0;
@@ -6304,7 +6652,7 @@ var init_types = __esm({
6304
6652
  RECORD_LOG_UP_BATCH_MAX = 200;
6305
6653
  RECORD_LOG_FRAME_ENTRIES_MAX = 64;
6306
6654
  RECORD_LOG_FIRST_EPOCH = 1;
6307
- RECORD_LOG_WIRE_VERSION = 4;
6655
+ RECORD_LOG_WIRE_VERSION = 5;
6308
6656
  RecordLogStaleReceiptError = class _RecordLogStaleReceiptError extends Error {
6309
6657
  /**
6310
6658
  * @param attempt - The attempt the command carried.
@@ -6473,12 +6821,12 @@ function mergeRecordLogMutations(earlier, later) {
6473
6821
  const fields = { ...earlier.fields ?? {}, ...later.fields ?? {} };
6474
6822
  const stringSetDeltas = {};
6475
6823
  for (const [field, delta] of Object.entries(earlier.stringSetDeltas ?? {})) {
6476
- if (later.fields && hasOwn(later.fields, field)) continue;
6824
+ if (later.fields && hasOwn2(later.fields, field)) continue;
6477
6825
  stringSetDeltas[field] = Object.assign(memberMap(), delta);
6478
6826
  }
6479
6827
  for (const [field, delta] of Object.entries(later.stringSetDeltas ?? {})) {
6480
6828
  delete fields[field];
6481
- const merged = Object.assign(memberMap(), hasOwn(stringSetDeltas, field) ? stringSetDeltas[field] : {}, delta);
6829
+ const merged = Object.assign(memberMap(), hasOwn2(stringSetDeltas, field) ? stringSetDeltas[field] : {}, delta);
6482
6830
  if (kind === "create") {
6483
6831
  for (const [member, present] of Object.entries(merged)) if (!present) delete merged[member];
6484
6832
  }
@@ -6533,9 +6881,9 @@ function planRecordLogRecordWrite(input) {
6533
6881
  }
6534
6882
  const op = value;
6535
6883
  const delta = memberMap();
6536
- const held = existing && hasOwn(existing, key) && isStringArray(existing[key]) ? existing[key] : [];
6884
+ const held2 = existing && hasOwn2(existing, key) && isStringArray(existing[key]) ? existing[key] : [];
6537
6885
  if (kind === "patch") {
6538
- if (op.$clear === true) for (const member of held) delta[member] = false;
6886
+ if (op.$clear === true) for (const member of held2) delta[member] = false;
6539
6887
  for (const member of op.$remove ?? []) delta[member] = false;
6540
6888
  }
6541
6889
  for (const member of op.$add ?? []) delta[member] = true;
@@ -6564,41 +6912,41 @@ function planRecordLogDelete(model, recordId, condition) {
6564
6912
  function planRecordLogIncrement(model, recordId, fields, condition) {
6565
6913
  return { model, id: recordId, kind: "increment", fields: { ...fields }, ...guardsOf({ condition }) };
6566
6914
  }
6567
- function foldRecordLogIncrement(held, next) {
6915
+ function foldRecordLogIncrement(held2, next) {
6568
6916
  if (next.kind !== "increment") {
6569
- const mutation2 = held.mutation ? mergeRecordLogMutations(held.mutation, next) : next;
6917
+ const mutation2 = held2.mutation ? mergeRecordLogMutations(held2.mutation, next) : next;
6570
6918
  const named = /* @__PURE__ */ new Set([...Object.keys(next.fields ?? {}), ...Object.keys(next.stringSetDeltas ?? {})]);
6571
- const left = next.kind === "patch" && held.increment ? Object.entries(held.increment.fields ?? {}).filter(([field]) => !named.has(field)) : [];
6919
+ const left = next.kind === "patch" && held2.increment ? Object.entries(held2.increment.fields ?? {}).filter(([field]) => !named.has(field)) : [];
6572
6920
  if (left.length) {
6573
- return { mutation: mutation2, increment: { ...held.increment, fields: Object.fromEntries(left) } };
6921
+ return { mutation: mutation2, increment: { ...held2.increment, fields: Object.fromEntries(left) } };
6574
6922
  }
6575
- const dropped = held.increment?.condition;
6923
+ const dropped = held2.increment?.condition;
6576
6924
  return { mutation: dropped === void 0 ? mutation2 : { ...mutation2, ...conjoined(mutation2.condition, dropped) } };
6577
6925
  }
6578
- const absolute = held.mutation && held.mutation.kind !== "delete" ? held.mutation : void 0;
6926
+ const absolute = held2.mutation && held2.mutation.kind !== "delete" ? held2.mutation : void 0;
6579
6927
  const intoAbsolute = {};
6580
- const deltas = { ...held.increment?.fields ?? {} };
6928
+ const deltas = { ...held2.increment?.fields ?? {} };
6581
6929
  let accumulated = false;
6582
6930
  for (const [field, delta] of Object.entries(next.fields ?? {})) {
6583
- if (absolute && (absolute.kind === "create" || hasOwn(absolute.fields ?? {}, field))) {
6931
+ if (absolute && (absolute.kind === "create" || hasOwn2(absolute.fields ?? {}, field))) {
6584
6932
  intoAbsolute[field] = numericOf(absolute.fields?.[field]) + delta;
6585
6933
  } else {
6586
6934
  deltas[field] = (deltas[field] ?? 0) + delta;
6587
6935
  accumulated = true;
6588
6936
  }
6589
6937
  }
6590
- let mutation = held.mutation;
6938
+ let mutation = held2.mutation;
6591
6939
  if (absolute && Object.keys(intoAbsolute).length) {
6592
6940
  mutation = { ...absolute, fields: { ...absolute.fields ?? {}, ...intoAbsolute } };
6593
6941
  if (!accumulated) mutation = { ...mutation, ...conjoined(absolute.condition, next.condition) };
6594
6942
  }
6595
- if (!accumulated && !held.increment) return { ...mutation ? { mutation } : {} };
6596
- const { condition: _condition, ...base } = held.increment ?? next;
6943
+ if (!accumulated && !held2.increment) return { ...mutation ? { mutation } : {} };
6944
+ const { condition: _condition, ...base } = held2.increment ?? next;
6597
6945
  const increment = {
6598
6946
  ...base,
6599
6947
  kind: "increment",
6600
6948
  fields: deltas,
6601
- ...conjoined(held.increment?.condition, accumulated ? next.condition : void 0)
6949
+ ...conjoined(held2.increment?.condition, accumulated ? next.condition : void 0)
6602
6950
  };
6603
6951
  return { ...mutation ? { mutation } : {}, increment };
6604
6952
  }
@@ -6636,7 +6984,7 @@ function ruleProblem(m) {
6636
6984
  const deltas = Object.entries(m.fields ?? {});
6637
6985
  if (!deltas.length) return "an increment names no field";
6638
6986
  if (m.stringSetDeltas !== void 0) return "an increment carries no stringSetDeltas";
6639
- if (hasOwn(m.fields, "id")) return "an increment cannot change id";
6987
+ if (hasOwn2(m.fields, "id")) return "an increment cannot change id";
6640
6988
  for (const [name, delta] of deltas) {
6641
6989
  const problem = identifierProblem("field", name);
6642
6990
  if (problem) return `${problem}. Rename the field`;
@@ -6745,7 +7093,7 @@ function assertRecordLogEntry(documentId, mutations, report, options = {}) {
6745
7093
  report?.({ documentId, model: first.model, recordId: first.id, error, writes });
6746
7094
  throw error;
6747
7095
  }
6748
- var membersOf, isStringArray, memberMap, hasOwn, numericOf;
7096
+ var membersOf, isStringArray, memberMap, hasOwn2, numericOf;
6749
7097
  var init_write = __esm({
6750
7098
  "src/record-log-client/write.ts"() {
6751
7099
  "use strict";
@@ -6756,7 +7104,7 @@ var init_write = __esm({
6756
7104
  membersOf = (value) => value ? Array.from(value) : [];
6757
7105
  isStringArray = (value) => Array.isArray(value) && valueKind(value) === "stringset";
6758
7106
  memberMap = () => /* @__PURE__ */ Object.create(null);
6759
- hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
7107
+ hasOwn2 = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
6760
7108
  numericOf = (value) => typeof value === "number" ? value : 0;
6761
7109
  }
6762
7110
  });
@@ -7066,9 +7414,9 @@ var init_guess = __esm({
7066
7414
  if (!text.startsWith(prefix)) continue;
7067
7415
  const id = text.slice(prefix.length);
7068
7416
  if (excluding.includes(id)) continue;
7069
- const held = fields.map((field) => row[field]);
7070
- if (held.some((v) => v === void 0 || v === null)) continue;
7071
- if (JSON.stringify(held) === wanted2) return id;
7417
+ const held2 = fields.map((field) => row[field]);
7418
+ if (held2.some((v) => v === void 0 || v === null)) continue;
7419
+ if (JSON.stringify(held2) === wanted2) return id;
7072
7420
  }
7073
7421
  return null;
7074
7422
  }
@@ -8622,6 +8970,13 @@ function whenIndexedCallSite(stack) {
8622
8970
  const outside = frames.find((frame) => !JS_BAO_FRAME.test(frame));
8623
8971
  return outside ? outside.slice(3) : stack;
8624
8972
  }
8973
+ function heldRevisionClears(instance, fieldKey) {
8974
+ const modelConstructor = instance.constructor;
8975
+ const store = modelConstructor.recordViewFor(instance.getDocumentId());
8976
+ if (!store?.declaredCleared) return false;
8977
+ const modelName = modelConstructor.getSchema()?.options?.name;
8978
+ return store.declaredCleared()?.[modelName]?.includes(fieldKey) === true;
8979
+ }
8625
8980
  var import_ulid2, FORMAT2_ROW_PAGE, UniqueConstraintViolationError, VectorFieldFormatError, RecordNotFoundError, SCHEMA_ACCESSORS_KEY, RecordLogTransactionGroup, activeRecordLogTransactions, unboundRecordLogTransaction, recordLogTransactionsOpen, JS_BAO_FRAME, BaseModel2;
8626
8981
  var init_BaseModel = __esm({
8627
8982
  "src/models/BaseModel.ts"() {
@@ -8646,6 +9001,7 @@ var init_BaseModel = __esm({
8646
9001
  init_fieldCoercion();
8647
9002
  init_vector();
8648
9003
  init_vectorFields();
9004
+ init_jsonFields();
8649
9005
  init_indexPlacement();
8650
9006
  init_nearSearch();
8651
9007
  init_OrmContext();
@@ -8724,14 +9080,14 @@ var init_BaseModel = __esm({
8724
9080
  if (write.existing) table.set(mutation, { ...write.existing });
8725
9081
  applyGuess(table, { m: mutation });
8726
9082
  const row = table.row(mutation);
8727
- const held = writes.get(key);
8728
- if (held) {
8729
- held.held = foldRecordLogIncrement(held.held, mutation);
8730
- held.upsertOn ??= write.upsertOn;
8731
- if (write.instance) held.instances.add(write.instance);
8732
- if (write.modelClass) held.classes.add(write.modelClass);
8733
- held.entry.row = row;
8734
- return held.entry;
9083
+ const held2 = writes.get(key);
9084
+ if (held2) {
9085
+ held2.held = foldRecordLogIncrement(held2.held, mutation);
9086
+ held2.upsertOn ??= write.upsertOn;
9087
+ if (write.instance) held2.instances.add(write.instance);
9088
+ if (write.modelClass) held2.classes.add(write.modelClass);
9089
+ held2.entry.row = row;
9090
+ return held2.entry;
8735
9091
  }
8736
9092
  const entry = { model: mutation.model, id: mutation.id, row, loaded: true };
8737
9093
  writes.set(key, {
@@ -9091,11 +9447,11 @@ var init_BaseModel = __esm({
9091
9447
  if (field === "id" || field === "type" || schema.fields.has(field)) return;
9092
9448
  throw new InvalidFieldError(`Unknown field: ${field} in model ${modelName}`, field, modelName);
9093
9449
  };
9094
- const walk = (node) => {
9450
+ const walk2 = (node) => {
9095
9451
  if (!node || typeof node !== "object" || Array.isArray(node)) return;
9096
9452
  for (const [key, value] of Object.entries(node)) {
9097
9453
  if (key === "$and" || key === "$or") {
9098
- if (Array.isArray(value)) value.forEach(walk);
9454
+ if (Array.isArray(value)) value.forEach(walk2);
9099
9455
  } else if (key === "$near") {
9100
9456
  const near = parseNearRead({ $near: value });
9101
9457
  const declared = schema.fields.get(near.field);
@@ -9106,13 +9462,13 @@ var init_BaseModel = __esm({
9106
9462
  );
9107
9463
  }
9108
9464
  nearVectorBytes(near, modelName, typeof declared.dims === "number" ? declared.dims : null);
9109
- walk(near.filter);
9465
+ walk2(near.filter);
9110
9466
  } else if (key !== "$search") {
9111
9467
  check(key);
9112
9468
  }
9113
9469
  }
9114
9470
  };
9115
- walk(filter);
9471
+ walk2(filter);
9116
9472
  const searched = !!filter && Object.prototype.hasOwnProperty.call(filter, "$search");
9117
9473
  const nearing = !!filter && Object.prototype.hasOwnProperty.call(filter, "$near");
9118
9474
  for (const field of Object.keys(options?.sort ?? {})) {
@@ -9180,7 +9536,8 @@ var init_BaseModel = __esm({
9180
9536
  * A plain db3 row as the model API answers it: each declared string set the
9181
9537
  * row carries holds an array, `[]` for none, as an instance reads it, and
9182
9538
  * each vector field its numbers (#5225), with the encoding `vectors` (the
9183
- * row's db3's type) or the model declares; and the same, through
9539
+ * row's db3's type) or the model declares, and each JSON field its object
9540
+ * (#5899); and the same, through
9184
9541
  * `_related`, for every included row of a registered model, at every
9185
9542
  * depth. `own` false shapes only the related rows.
9186
9543
  */
@@ -9188,13 +9545,16 @@ var init_BaseModel = __esm({
9188
9545
  const registry = resolveOrmContext(this).modelRegistry;
9189
9546
  const shape = (record, model, specs, self2) => {
9190
9547
  if (self2) {
9191
- const fields = registry?.getModelClass(model)?.getSchema?.()?.fields;
9548
+ const modelClass = registry?.getModelClass(model);
9549
+ const fields = modelClass?.getSchema?.()?.fields;
9192
9550
  for (const [field, options] of fields ?? []) {
9193
9551
  if (!Object.prototype.hasOwnProperty.call(record, field)) continue;
9194
9552
  if (options?.type === "stringset" && !Array.isArray(record[field])) {
9195
9553
  record[field] = [];
9196
9554
  } else if (options?.type === "vector") {
9197
9555
  record[field] = readVectorValue(model, field, record[field], vectorEncodingFor(vectors, model, field, options));
9556
+ } else if (options?.type === "string" && modelClass && db3JsonDefOf(modelClass, field)) {
9557
+ record[field] = readDb3JsonField(model, field, record[field]);
9198
9558
  }
9199
9559
  }
9200
9560
  }
@@ -9564,6 +9924,7 @@ var init_BaseModel = __esm({
9564
9924
  const format2Store = modelConstructor.recordViewFor(this._metaDocId);
9565
9925
  if (format2Store) {
9566
9926
  format2Store.assertReadable();
9927
+ if (format2Store.declaredCleared?.()?.[modelName]?.includes(fieldKey)) return void 0;
9567
9928
  const staged = recordLogTransactionsOpen > 0 ? stagedForRead(resolveOrmContext(modelConstructor), format2Store, modelName, this.id) : void 0;
9568
9929
  const row = staged !== void 0 ? staged : this._format2Row?.row ?? null;
9569
9930
  const value = row ? row[fieldKey] : void 0;
@@ -9700,9 +10061,14 @@ var init_BaseModel = __esm({
9700
10061
  `[getValue] Field '${fieldKey}' is StringSet type, returning StringSet instance`
9701
10062
  );
9702
10063
  }
10064
+ if (heldRevisionClears(this, fieldKey)) return new StringSet(this, fieldKey, []);
9703
10065
  return this.getOrCreateStringSet(fieldKey);
9704
10066
  }
10067
+ if (fieldOptions?.type === "string" && db3JsonDefOf(this.constructor, fieldKey)) {
10068
+ return readDb3JsonField(schema?.options?.name ?? this.constructor.name, fieldKey, db3JsonText(this, fieldKey));
10069
+ }
9705
10070
  if (this.hasLocalChange(fieldKey)) {
10071
+ if (heldRevisionClears(this, fieldKey)) return void 0;
9706
10072
  if (verboseEnabled) {
9707
10073
  Logger.verbose(
9708
10074
  `[getValue] Field '${fieldKey}' has local changes: ${this._localChanges[fieldKey]}`
@@ -9733,6 +10099,10 @@ var init_BaseModel = __esm({
9733
10099
  }
9734
10100
  if (!this._isLoadingFromYjs) {
9735
10101
  }
10102
+ const jsonDef = fieldOptions?.type === "string" ? db3JsonDefOf(this.constructor, fieldKey) : void 0;
10103
+ if (jsonDef) {
10104
+ value = encodeDb3JsonField(schema?.options?.name ?? this.constructor.name, fieldKey, jsonDef, value);
10105
+ }
9736
10106
  const changes = this.ensureLocalChanges();
9737
10107
  changes[fieldKey] = value;
9738
10108
  this._isDirty = true;
@@ -9775,11 +10145,18 @@ var init_BaseModel = __esm({
9775
10145
  throw new Error(`Field ${fieldKey} is required`);
9776
10146
  }
9777
10147
  }
9778
- validateBeforeSave() {
10148
+ /**
10149
+ * Check the model's own rules before a save writes it.
10150
+ *
10151
+ * @param cleared - Fields the db3's type clears: a build generated while
10152
+ * one was `required` still saves its other fields, as the room stores
10153
+ * nothing for it.
10154
+ */
10155
+ validateBeforeSave(cleared) {
9779
10156
  const schema = this.constructor.getSchema();
9780
10157
  for (const [fieldKey, fieldOptions] of schema.fields.entries()) {
9781
- const currentValue = fieldKey === "id" ? this.id : this.getValue(fieldKey);
9782
- if (fieldOptions.required && (currentValue === null || currentValue === void 0)) {
10158
+ const currentValue = fieldKey === "id" ? this.id : fieldOptions.type === "string" && db3JsonDefOf(this.constructor, fieldKey) ? db3JsonText(this, fieldKey) : this.getValue(fieldKey);
10159
+ if (fieldOptions.required && (currentValue === null || currentValue === void 0) && !cleared?.includes(fieldKey)) {
9783
10160
  throw new Error(`Field ${fieldKey} is required before save`);
9784
10161
  }
9785
10162
  if (fieldOptions.type === "stringset" && currentValue instanceof StringSet) {
@@ -11073,6 +11450,7 @@ var init_BaseModel = __esm({
11073
11450
  Logger.debug(`[${modelName}.save] _localChanges:`, this._localChanges);
11074
11451
  Logger.debug(`[${modelName}.save] _isDirty:`, this._isDirty);
11075
11452
  const dataToSave = this.getCurrentJSState();
11453
+ storeDb3JsonFields(this, dataToSave, schema.fields);
11076
11454
  Logger.debug(
11077
11455
  `[${modelName}.save] getCurrentJSState() returned:`,
11078
11456
  dataToSave
@@ -11527,8 +11905,10 @@ var init_BaseModel = __esm({
11527
11905
  }
11528
11906
  }
11529
11907
  const preTransactCreateStamps = this.applyAutoStampsForSave(schema, existing === null || asCreate);
11530
- this.validateBeforeSave();
11908
+ const heldCleared = store.declaredCleared?.()?.[modelName];
11909
+ this.validateBeforeSave(heldCleared);
11531
11910
  const dataToSave = this.getCurrentJSState();
11911
+ storeDb3JsonFields(this, dataToSave, schema.fields);
11532
11912
  try {
11533
11913
  encodeVectorFields(dataToSave, schema.fields, store.declaredVectors(), modelName, this.id);
11534
11914
  } catch (error) {
@@ -11573,6 +11953,7 @@ var init_BaseModel = __esm({
11573
11953
  const selfJudged = store.marks().localOnly === true;
11574
11954
  for (const constraint of selfJudged ? [] : schema.resolvedUniqueConstraints) {
11575
11955
  if (!store.constraintInForce(constraint.name)) continue;
11956
+ if (heldCleared?.length && constraint.fields.some((field) => heldCleared.includes(field))) continue;
11576
11957
  const values = constraint.fields.map((field) => postMutation[field]);
11577
11958
  if (values.some((value) => value === void 0 || value === null)) continue;
11578
11959
  const holder = await ops.findIdByFields(modelName, constraint.fields, values);
@@ -13575,6 +13956,7 @@ __export(browser_exports, {
13575
13956
  DatabaseFactory: () => BrowserDatabaseFactory,
13576
13957
  Db3DriftExceededError: () => Db3DriftExceededError,
13577
13958
  Db3IndexNotOnDeviceError: () => Db3IndexNotOnDeviceError,
13959
+ Db3JsonValueError: () => Db3JsonValueError,
13578
13960
  Db3ModelOnOtherClientError: () => Db3ModelOnOtherClientError,
13579
13961
  Db3NotResidentError: () => Db3NotResidentError,
13580
13962
  Db3QueryScopeError: () => Db3QueryScopeError,
@@ -13663,8 +14045,10 @@ __export(browser_exports, {
13663
14045
  attachAndRegisterModel: () => attachAndRegisterModel,
13664
14046
  attachSchemaToClass: () => attachSchemaToClass,
13665
14047
  autoRegisterModel: () => autoRegisterModel,
14048
+ bindDb3JsonFields: () => bindDb3JsonFields,
13666
14049
  buildUniqueKey: () => buildUniqueKey,
13667
14050
  buildUniqueKeyFromValues: () => buildUniqueKeyFromValues,
14051
+ canonicalDb3Json: () => canonicalDb3Json,
13668
14052
  canonicalStringSet: () => canonicalStringSet,
13669
14053
  checkVectorModelEnvelope: () => checkVectorModelEnvelope,
13670
14054
  clearMetaSyncCache: () => clearMetaSyncCache,
@@ -13673,6 +14057,7 @@ __export(browser_exports, {
13673
14057
  conditionHolds: () => conditionHolds,
13674
14058
  conditionProblem: () => conditionProblem,
13675
14059
  countViewRows: () => countViewRows,
14060
+ db3JsonText: () => db3JsonText,
13676
14061
  db3ViewTranslator: () => db3ViewTranslator,
13677
14062
  declaredTypeProblem: () => declaredTypeProblem,
13678
14063
  declineRecordLogIndex: () => declineRecordLogIndex,
@@ -13703,7 +14088,7 @@ __export(browser_exports, {
13703
14088
  isAnchorId: () => isAnchorId,
13704
14089
  isBrowser: () => isBrowser,
13705
14090
  isCanonicalStringSet: () => isCanonicalStringSet,
13706
- isNode: () => isNode,
14091
+ isNode: () => isNode2,
13707
14092
  isRecordLogResident: () => isRecordLogResident,
13708
14093
  isRecordLogStoreNotice: () => isRecordLogStoreNotice,
13709
14094
  isRecordLogStoreRequest: () => isRecordLogStoreRequest,
@@ -13752,6 +14137,7 @@ __export(browser_exports, {
13752
14137
  uniqueIndexMapName: () => uniqueIndexMapName,
13753
14138
  uniqueStringsetMessage: () => uniqueStringsetMessage,
13754
14139
  uniqueStringsetViolations: () => uniqueStringsetViolations,
14140
+ validateDb3Json: () => validateDb3Json,
13755
14141
  validateSnapshotManifest: () => validateSnapshotManifest,
13756
14142
  vectorBytes: () => vectorBytes,
13757
14143
  wireEntryOf: () => wireEntryOf,
@@ -14203,7 +14589,7 @@ function detectEnvironment() {
14203
14589
  }
14204
14590
  return "unknown";
14205
14591
  }
14206
- function isNode() {
14592
+ function isNode2() {
14207
14593
  return detectEnvironment() === "node";
14208
14594
  }
14209
14595
  function isBrowser() {
@@ -14217,7 +14603,7 @@ function importNodeOnly(specifier) {
14217
14603
  );
14218
14604
  }
14219
14605
  async function isNodeModuleAvailable(moduleName) {
14220
- if (!isNode()) {
14606
+ if (!isNode2()) {
14221
14607
  return false;
14222
14608
  }
14223
14609
  try {
@@ -14236,7 +14622,7 @@ var features = {
14236
14622
  return isBrowser() && typeof Worker !== "undefined";
14237
14623
  },
14238
14624
  get hasFileSystem() {
14239
- return isNode();
14625
+ return isNode2();
14240
14626
  },
14241
14627
  get hasWebAssembly() {
14242
14628
  return typeof WebAssembly !== "undefined";
@@ -14255,7 +14641,7 @@ var import_meta = {};
14255
14641
  var SQL_WASM_URL = "/sql-wasm.wasm";
14256
14642
  var SQL_WASM_FILENAME = "sql-wasm.wasm";
14257
14643
  async function resolveNodeWasmPath() {
14258
- if (!isNode()) {
14644
+ if (!isNode2()) {
14259
14645
  return null;
14260
14646
  }
14261
14647
  try {
@@ -14277,7 +14663,7 @@ async function resolveNodeWasmPath() {
14277
14663
  return null;
14278
14664
  }
14279
14665
  async function preflightNodeWasm(wasmPath) {
14280
- if (!isNode()) {
14666
+ if (!isNode2()) {
14281
14667
  return;
14282
14668
  }
14283
14669
  if (/^[a-z]+:\/\//i.test(wasmPath)) {
@@ -14333,7 +14719,7 @@ async function guardedLoadSqlJs(locateFile) {
14333
14719
  reason
14334
14720
  )}`
14335
14721
  );
14336
- const nodeProcess = isNode() && typeof process !== "undefined" ? process : void 0;
14722
+ const nodeProcess = isNode2() && typeof process !== "undefined" ? process : void 0;
14337
14723
  const onUnhandled = (reason) => {
14338
14724
  if (runtimeFailed() && !runtimeFailureCaught) {
14339
14725
  runtimeFailureCaught = true;
@@ -14608,10 +14994,10 @@ var SqljsEngine = class _SqljsEngine extends SqliteQueryEngineBase {
14608
14994
  const db = this.db;
14609
14995
  let depth = 0;
14610
14996
  return {
14611
- exec(query, ...bindings) {
14997
+ exec(query, ...bindings2) {
14612
14998
  const stmt = db.prepare(query);
14613
14999
  try {
14614
- if (bindings.length > 0) stmt.bind(bindings);
15000
+ if (bindings2.length > 0) stmt.bind(bindings2);
14615
15001
  const rows = [];
14616
15002
  while (stmt.step()) rows.push(stmt.getAsObject());
14617
15003
  return rows;
@@ -15307,6 +15693,7 @@ var RECORD_LOG_CHANGING_COMMANDS = /* @__PURE__ */ new Set([
15307
15693
  "refused",
15308
15694
  "applyCatchUpPage",
15309
15695
  "completeCatchUp",
15696
+ "applyClears",
15310
15697
  "applyLoadChunk",
15311
15698
  "completeLoad",
15312
15699
  "applySegmentChunk",
@@ -15324,6 +15711,7 @@ var RECORD_LOG_VECTOR_WANT_COMMANDS = /* @__PURE__ */ new Set([
15324
15711
  "refused",
15325
15712
  "applyCatchUpPage",
15326
15713
  "completeCatchUp",
15714
+ "applyClears",
15327
15715
  "applyLoadChunk",
15328
15716
  "completeLoad",
15329
15717
  "applySegmentChunk",
@@ -15550,6 +15938,9 @@ function dispatchRecordLogStoreCommand(store, command) {
15550
15938
  case "completeCatchUp":
15551
15939
  value = store.completeCatchUp(c);
15552
15940
  break;
15941
+ case "applyClears":
15942
+ value = store.applyClears(c);
15943
+ break;
15553
15944
  case "beginReceipt":
15554
15945
  value = store.beginReceipt({
15555
15946
  writer: c.writer,
@@ -15767,6 +16158,70 @@ var VectorJobs = class {
15767
16158
  }
15768
16159
  };
15769
16160
 
16161
+ // src/record-log-client/cleared.ts
16162
+ var held = /* @__PURE__ */ new WeakMap();
16163
+ function heldClearedOf(sql, docId) {
16164
+ let docs = held.get(sql);
16165
+ if (!docs) held.set(sql, docs = /* @__PURE__ */ new Map());
16166
+ if (docs.has(docId)) return docs.get(docId);
16167
+ let cleared = null;
16168
+ let state;
16169
+ try {
16170
+ [state] = Array.from(sql.exec(`SELECT typed, db3_type FROM record_log_state WHERE doc_id = ?`, docId));
16171
+ } catch {
16172
+ return null;
16173
+ }
16174
+ if (state?.typed === "yes" && typeof state.db3_type === "string") {
16175
+ try {
16176
+ const map = JSON.parse(state.db3_type).cleared;
16177
+ if (map && typeof map === "object") {
16178
+ const entries = Object.entries(map).filter(([, names]) => Array.isArray(names) && names.length > 0);
16179
+ if (entries.length) cleared = new Map(entries.map(([model, names]) => [model, new Set(names.map(String))]));
16180
+ }
16181
+ } catch {
16182
+ }
16183
+ }
16184
+ docs.set(docId, cleared);
16185
+ return cleared;
16186
+ }
16187
+ function forgetHeldCleared(sql, docId) {
16188
+ held.get(sql)?.delete(docId);
16189
+ }
16190
+ function clearedOverDocuments(sql, model, documents) {
16191
+ let union;
16192
+ for (const docId of documents) {
16193
+ const names = heldClearedOf(sql, docId)?.get(model);
16194
+ if (!names) continue;
16195
+ if (!union) union = new Set(names);
16196
+ else for (const name of names) union.add(name);
16197
+ }
16198
+ return union;
16199
+ }
16200
+ function clearedReadOf(sql, model, documents) {
16201
+ const unsetFields = clearedOverDocuments(sql, model, documents);
16202
+ if (!unsetFields) return void 0;
16203
+ const distinct = [...new Set(documents)];
16204
+ let unsetFieldDocuments;
16205
+ for (const name of unsetFields) {
16206
+ const hiding = distinct.filter((docId) => heldClearedOf(sql, docId)?.get(model)?.has(name));
16207
+ if (hiding.length < distinct.length) (unsetFieldDocuments ??= /* @__PURE__ */ new Map()).set(name, hiding);
16208
+ }
16209
+ return { unsetFields, ...unsetFieldDocuments ? { unsetFieldDocuments } : {} };
16210
+ }
16211
+ function withoutNames(row, names) {
16212
+ if (!names) return row;
16213
+ let out;
16214
+ for (const name of names) {
16215
+ if (!Object.prototype.hasOwnProperty.call(row, name)) continue;
16216
+ out ??= { ...row };
16217
+ delete out[name];
16218
+ }
16219
+ return out ?? row;
16220
+ }
16221
+ function withoutHeldCleared(sql, docId, model, row) {
16222
+ return withoutNames(row, heldClearedOf(sql, docId)?.get(model));
16223
+ }
16224
+
15770
16225
  // src/record-log-client/store.ts
15771
16226
  var import_ulid3 = require("ulid");
15772
16227
 
@@ -15783,14 +16238,14 @@ function checkConstraints(trial, touched, constraints) {
15783
16238
  );
15784
16239
  if (!mine.length) continue;
15785
16240
  const ids = rows.filter((x) => x.key.model === constraint.model).map((x) => x.key.id);
15786
- const held = /* @__PURE__ */ new Map();
16241
+ const held2 = /* @__PURE__ */ new Map();
15787
16242
  for (const { key, row } of mine) {
15788
16243
  const values = constraintKey(row, constraint.fields);
15789
16244
  if (values === null) continue;
15790
16245
  const text = JSON.stringify(values);
15791
- const other = held.get(text);
16246
+ const other = held2.get(text);
15792
16247
  if (other) return { constraint, key: values, record: key, conflicting: other };
15793
- held.set(text, key);
16248
+ held2.set(text, key);
15794
16249
  const holder = trial.holder(constraint.model, constraint.fields, values, ids);
15795
16250
  if (holder !== null) {
15796
16251
  return {
@@ -15836,12 +16291,12 @@ function fieldLookupPredicates(modelName, fields) {
15836
16291
  };
15837
16292
  }
15838
16293
  function fieldLookupBindings(predicates, modelName, fields, values) {
15839
- const bindings = predicates.bindType ? [modelName] : [];
16294
+ const bindings2 = predicates.bindType ? [modelName] : [];
15840
16295
  for (let i = 0; i < fields.length; i++) {
15841
- if (predicates.bindPaths && fields[i] !== "id") bindings.push(fields[i]);
15842
- bindings.push(values[i]);
16296
+ if (predicates.bindPaths && fields[i] !== "id") bindings2.push(fields[i]);
16297
+ bindings2.push(values[i]);
15843
16298
  }
15844
- return bindings;
16299
+ return bindings2;
15845
16300
  }
15846
16301
 
15847
16302
  // src/record-log/sql.ts
@@ -16256,7 +16711,7 @@ function definitionInSql(sql) {
16256
16711
  if (!at) return null;
16257
16712
  return sql.slice(at.index + at[0].length).replace(/\s+/g, " ").replace(/\(\s+/g, "(").replace(/\s+\)/g, ")").trim();
16258
16713
  }
16259
- var rowsOf = (sql, query, ...bindings) => Array.from(sql.exec(query, ...bindings));
16714
+ var rowsOf = (sql, query, ...bindings2) => Array.from(sql.exec(query, ...bindings2));
16260
16715
  function usable(entry) {
16261
16716
  if (!isValidIdentifier(entry.model)) return `model '${entry.model}' is not an identifier`;
16262
16717
  const bad = entry.fields.find((field) => !isValidIdentifier(field));
@@ -16272,9 +16727,9 @@ function recordLogTextTableName(docId, model) {
16272
16727
  const part = (name) => `${name.length}_${name.toLowerCase()}`;
16273
16728
  return ["idx_record_log_text", part(docId), part(model)].join("_");
16274
16729
  }
16275
- function deviceTableFor(sql, key, canonical, previous) {
16276
- const held = previous.get(key);
16277
- if (held !== void 0) return held;
16730
+ function deviceTableFor(sql, key, canonical2, previous) {
16731
+ const held2 = previous.get(key);
16732
+ if (held2 !== void 0) return held2;
16278
16733
  const taken = (name) => rowsOf(sql, `SELECT 1 FROM sqlite_master WHERE name = ? COLLATE NOCASE`, name).length > 0 || rowsOf(
16279
16734
  sql,
16280
16735
  `SELECT 1 FROM record_log_indexes WHERE members = ? COLLATE NOCASE OR text = ? COLLATE NOCASE OR vector = ? COLLATE NOCASE`,
@@ -16282,8 +16737,8 @@ function deviceTableFor(sql, key, canonical, previous) {
16282
16737
  name,
16283
16738
  name
16284
16739
  ).length > 0 || [...previous.values()].some((other) => other.toLowerCase() === name.toLowerCase());
16285
- if (!taken(canonical)) return canonical;
16286
- for (let n = 2; ; n++) if (!taken(`${canonical}_${n}`)) return `${canonical}_${n}`;
16740
+ if (!taken(canonical2)) return canonical2;
16741
+ for (let n = 2; ; n++) if (!taken(`${canonical2}_${n}`)) return `${canonical2}_${n}`;
16287
16742
  }
16288
16743
  var memberKey = (model, field) => `members\0${model}\0${field}`;
16289
16744
  var textKey = (model) => `text\0${model}`;
@@ -16301,7 +16756,7 @@ function dispositionOf(row, deviceIndexes) {
16301
16756
  if (row.verdict === "accepted") return "build";
16302
16757
  return deviceIndexesExclude(deviceIndexes, row.kind) ? "keep" : "build";
16303
16758
  }
16304
- var cachedRows = (sql, where2 = "", ...bindings) => rowsOf(
16759
+ var cachedRows = (sql, where2 = "", ...bindings2) => rowsOf(
16305
16760
  sql,
16306
16761
  `SELECT i.doc_id, i.model, i.fields, i.kind, i.is_unique, i.room_name, i.members, i.text, i.vector, i.options, p.verdict, s.local_only
16307
16762
  FROM record_log_indexes i
@@ -16309,7 +16764,7 @@ var cachedRows = (sql, where2 = "", ...bindings) => rowsOf(
16309
16764
  LEFT JOIN record_log_state s ON s.doc_id = i.doc_id
16310
16765
  ${where2}
16311
16766
  ORDER BY i.doc_id, i.model, i.fields, i.kind`,
16312
- ...bindings
16767
+ ...bindings2
16313
16768
  );
16314
16769
  var optionsOf = (row) => row.options === null || row.options === void 0 ? null : JSON.parse(String(row.options));
16315
16770
  function entryOptionsText(options) {
@@ -16474,16 +16929,16 @@ function recordLogIndexSkips(sql, docId) {
16474
16929
  );
16475
16930
  }
16476
16931
  function heldDefinitions(sql) {
16477
- const held = /* @__PURE__ */ new Map();
16932
+ const held2 = /* @__PURE__ */ new Map();
16478
16933
  for (const row of rowsOf(sql, `SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index' AND sql IS NOT NULL`)) {
16479
16934
  const name = String(row.name);
16480
16935
  if (!FAMILY.some((f) => f.table === row.tbl_name && name.startsWith(f.prefix))) continue;
16481
16936
  const definition = definitionInSql(String(row.sql));
16482
- if (definition !== null && !held.has(definition)) held.set(definition, name);
16937
+ if (definition !== null && !held2.has(definition)) held2.set(definition, name);
16483
16938
  }
16484
- return held;
16939
+ return held2;
16485
16940
  }
16486
- function wantedScalars(sql, deviceIndexes, held) {
16941
+ function wantedScalars(sql, deviceIndexes, held2) {
16487
16942
  const out = /* @__PURE__ */ new Map();
16488
16943
  for (const row of cachedRows(sql, `WHERE i.kind = 'scalar'`)) {
16489
16944
  const disposition = dispositionOf(row, deviceIndexes);
@@ -16491,7 +16946,7 @@ function wantedScalars(sql, deviceIndexes, held) {
16491
16946
  const model = String(row.model);
16492
16947
  const fields = JSON.parse(String(row.fields));
16493
16948
  const view = definitionOf("record_log_view", model, fields);
16494
- if (disposition === "keep" && !held.has(view)) continue;
16949
+ if (disposition === "keep" && !held2.has(view)) continue;
16495
16950
  let wanted2 = out.get(view);
16496
16951
  if (!wanted2) {
16497
16952
  wanted2 = {
@@ -16511,9 +16966,9 @@ function wantedScalars(sql, deviceIndexes, held) {
16511
16966
  }
16512
16967
  return out;
16513
16968
  }
16514
- function wanted(sql, deviceIndexes, held) {
16969
+ function wanted(sql, deviceIndexes, held2) {
16515
16970
  const out = /* @__PURE__ */ new Map();
16516
- for (const scalar of wantedScalars(sql, deviceIndexes, held).values()) {
16971
+ for (const scalar of wantedScalars(sql, deviceIndexes, held2).values()) {
16517
16972
  out.set(scalar.view.definition, scalar.view);
16518
16973
  if (scalar.rows) out.set(scalar.rows.definition, scalar.rows);
16519
16974
  }
@@ -16564,9 +17019,9 @@ function dropUnwanted(sql, deviceIndexes, support) {
16564
17019
  const table = String(row.text);
16565
17020
  const wantedText = wantedTextOf(row);
16566
17021
  const bodies = textTriggersDDL(table, wantedText);
16567
- const held = tables.get(table) === textTableDDL(table, wantedText.fields, wantedText.options) && TEXT_TRIGGERS.every((suffix, i) => triggers.get(`${table}${suffix}`) === bodies[i]);
17022
+ const held2 = tables.get(table) === textTableDDL(table, wantedText.fields, wantedText.options) && TEXT_TRIGGERS.every((suffix, i) => triggers.get(`${table}${suffix}`) === bodies[i]);
16568
17023
  const declined = dispositionOf(row, deviceIndexes) === "decline";
16569
- if (!declined && held && !texts.has(table)) {
17024
+ if (!declined && held2 && !texts.has(table)) {
16570
17025
  texts.add(table);
16571
17026
  if (wantedText.options.unbuilt !== void 0) markUnbuilt(sql, wantedText, null);
16572
17027
  continue;
@@ -16699,10 +17154,10 @@ function reportUnbuilt(subject, reason) {
16699
17154
  var messageOf = (error) => error instanceof Error ? error.message : String(error);
16700
17155
  function buildWanted(sql, support, deviceIndexes) {
16701
17156
  let created = 0;
16702
- const held = heldDefinitions(sql);
17157
+ const held2 = heldDefinitions(sql);
16703
17158
  const taken = new Set(rowsOf(sql, `SELECT name FROM sqlite_master WHERE type = 'index'`).map((row) => String(row.name)));
16704
- for (const scalar of wantedScalars(sql, deviceIndexes, held).values()) {
16705
- const missing = [scalar.view, ...scalar.rows ? [scalar.rows] : []].filter((index) => !held.has(index.definition));
17159
+ for (const scalar of wantedScalars(sql, deviceIndexes, held2).values()) {
17160
+ const missing = [scalar.view, ...scalar.rows ? [scalar.rows] : []].filter((index) => !held2.has(index.definition));
16706
17161
  const rows = () => cachedRows(sql, `WHERE i.kind = 'scalar' AND i.model = ? AND i.fields = ?`, scalar.model, JSON.stringify(scalar.fields)).filter(
16707
17162
  (row) => dispositionOf(row, deviceIndexes) === "build"
16708
17163
  );
@@ -17019,11 +17474,11 @@ function recordLogTextIndexOf(sql, docId, model, deviceIndexes) {
17019
17474
  if (!row) return null;
17020
17475
  const options = JSON.parse(String(row.options));
17021
17476
  const table = row.text === null || row.text === void 0 ? null : String(row.text);
17022
- const held = table !== null && options.unbuilt === void 0 && rowsOf(sql, `SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?`, table).length > 0;
17477
+ const held2 = table !== null && options.unbuilt === void 0 && rowsOf(sql, `SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?`, table).length > 0;
17023
17478
  const disposition = dispositionOf(row, deviceIndexes);
17024
- const declined = disposition === "decline" ? DECLINED_HERE : disposition === "keep" && !held ? excludedByOption("text") : void 0;
17479
+ const declined = disposition === "decline" ? DECLINED_HERE : disposition === "keep" && !held2 ? excludedByOption("text") : void 0;
17025
17480
  return {
17026
- table: held ? table : null,
17481
+ table: held2 ? table : null,
17027
17482
  fields: JSON.parse(String(row.fields)),
17028
17483
  options,
17029
17484
  roomName: String(row.room_name),
@@ -17082,17 +17537,17 @@ function placementOf(row) {
17082
17537
  if (Number(row.local_only ?? 0) === 1) return "device";
17083
17538
  return optionsOf(row)?.on ?? "both";
17084
17539
  }
17085
- function statusOf(row, deviceIndexes, held) {
17540
+ function statusOf(row, deviceIndexes, held2) {
17086
17541
  const fields = JSON.parse(String(row.fields));
17087
17542
  const kind = String(row.kind);
17088
17543
  const base = { name: String(row.room_name), model: String(row.model), fields, kind, on: placementOf(row) };
17089
17544
  const disposition = dispositionOf(row, deviceIndexes);
17090
17545
  if (disposition === "decline") return { ...base, status: "declined", reason: DECLINED_HERE };
17091
17546
  const options = optionsOf(row) ?? {};
17092
- const built = kind === "scalar" ? held.definitions.has(definitionOf("record_log_view", base.model, fields)) : kind === "members" ? row.members !== null && row.members !== void 0 && memberTableHeld(held.memberTables, held.memberTriggers, String(row.members)) : kind === "text" ? row.text !== null && row.text !== void 0 && options.unbuilt === void 0 && held.texts.has(String(row.text)) : row.vector !== null && row.vector !== void 0 && options.unbuilt === void 0 && held.vectors.has(String(row.vector));
17547
+ const built = kind === "scalar" ? held2.definitions.has(definitionOf("record_log_view", base.model, fields)) : kind === "members" ? row.members !== null && row.members !== void 0 && memberTableHeld(held2.memberTables, held2.memberTriggers, String(row.members)) : kind === "text" ? row.text !== null && row.text !== void 0 && options.unbuilt === void 0 && held2.texts.has(String(row.text)) : row.vector !== null && row.vector !== void 0 && options.unbuilt === void 0 && held2.vectors.has(String(row.vector));
17093
17548
  if (built && kind === "vector") {
17094
17549
  const vector = options;
17095
- const installed = !!vector.ann && held.vectors.has(annTableOf(String(row.vector)));
17550
+ const installed = !!vector.ann && held2.vectors.has(annTableOf(String(row.vector)));
17096
17551
  if (installed && vector.fill) return { ...base, status: "building", mode: "exact" };
17097
17552
  return { ...base, status: "built", mode: installed ? "ann" : "exact" };
17098
17553
  }
@@ -17120,24 +17575,24 @@ function heldObjects(sql) {
17120
17575
  };
17121
17576
  }
17122
17577
  function recordLogIndexStatuses(sql, docId, deviceIndexes) {
17123
- const held = heldObjects(sql);
17124
- return cachedRows(sql, `WHERE i.doc_id = ?`, docId).filter((row) => placementOf(row) !== "server").map((row) => statusOf(row, deviceIndexes, held)).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
17578
+ const held2 = heldObjects(sql);
17579
+ return cachedRows(sql, `WHERE i.doc_id = ?`, docId).filter((row) => placementOf(row) !== "server").map((row) => statusOf(row, deviceIndexes, held2)).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
17125
17580
  }
17126
17581
  function recordLogNamedIndex(sql, docId, name, deviceIndexes) {
17127
17582
  const [row] = cachedRows(sql, `WHERE i.doc_id = ? AND i.room_name = ?`, docId, name);
17128
17583
  if (!row) return null;
17129
- const held = heldObjects(sql);
17130
- const status = statusOf(row, deviceIndexes, held);
17131
- const object = status.status !== "built" ? null : row.kind === "scalar" ? held.definitions.get(definitionOf("record_log_view", status.model, status.fields)) ?? null : row.kind === "members" ? String(row.members) : null;
17584
+ const held2 = heldObjects(sql);
17585
+ const status = statusOf(row, deviceIndexes, held2);
17586
+ const object = status.status !== "built" ? null : row.kind === "scalar" ? held2.definitions.get(definitionOf("record_log_view", status.model, status.fields)) ?? null : row.kind === "members" ? String(row.members) : null;
17132
17587
  return { status, object };
17133
17588
  }
17134
17589
  function recordLogRegistryNames(sql, docId) {
17135
- const held = heldDefinitions(sql);
17590
+ const held2 = heldDefinitions(sql);
17136
17591
  const names = /* @__PURE__ */ new Map();
17137
17592
  for (const row of cachedRows(sql, `WHERE i.doc_id = ?`, docId)) {
17138
17593
  const name = String(row.room_name);
17139
17594
  if (row.kind === "scalar") {
17140
- const object = held.get(definitionOf("record_log_view", String(row.model), JSON.parse(String(row.fields))));
17595
+ const object = held2.get(definitionOf("record_log_view", String(row.model), JSON.parse(String(row.fields))));
17141
17596
  if (object !== void 0) names.set(object, name);
17142
17597
  }
17143
17598
  for (const column of ["members", "text", "vector"]) {
@@ -17221,8 +17676,8 @@ var RECORD_LOG_GROWTH_STATISTICS_MIN_ROWS = 1e3;
17221
17676
  var RECORD_LOG_GROWTH_STATISTICS_FACTOR = 10;
17222
17677
  var highestViewRowid = (sql) => Number(rowsOf(sql, `SELECT MAX(rowid) AS n FROM record_log_view`)[0]?.n ?? 0);
17223
17678
  function heldMemberTables(sql) {
17224
- const held = new Set(familyNames(sql, "table"));
17225
- return rowsOf(sql, `SELECT DISTINCT members FROM record_log_indexes WHERE members IS NOT NULL ORDER BY members`).map((row) => String(row.members)).filter((table) => held.has(table));
17679
+ const held2 = new Set(familyNames(sql, "table"));
17680
+ return rowsOf(sql, `SELECT DISTINCT members FROM record_log_indexes WHERE members IS NOT NULL ORDER BY members`).map((row) => String(row.members)).filter((table) => held2.has(table));
17226
17681
  }
17227
17682
  function gatherRecordLogStatistics(sql) {
17228
17683
  try {
@@ -17325,7 +17780,9 @@ function db3ViewTranslator(model, options = {}) {
17325
17780
  ...options.facetTiesByMember ? { facetTiesByMember: true } : {},
17326
17781
  ...options.textIndex ? { textIndex: options.textIndex } : {},
17327
17782
  ...options.vectorIndex ? { vectorIndex: options.vectorIndex } : {},
17328
- ...options.indexHint ? { indexHint: options.indexHint } : {}
17783
+ ...options.indexHint ? { indexHint: options.indexHint } : {},
17784
+ ...options.unsetFields?.size ? { unsetFields: options.unsetFields } : {},
17785
+ ...options.unsetFields?.size && options.unsetFieldDocuments?.size ? { unsetFieldDocuments: options.unsetFieldDocuments } : {}
17329
17786
  });
17330
17787
  }
17331
17788
  function searchIndexOf(sql, model, documents, support, deviceIndexes) {
@@ -17416,11 +17873,11 @@ function declaredFieldOf(sql, docId, model, field) {
17416
17873
  const [state] = Array.from(sql.exec(`SELECT typed, db3_type FROM record_log_state WHERE doc_id = ?`, docId));
17417
17874
  if (state?.typed !== "yes" || typeof state.db3_type !== "string") return null;
17418
17875
  try {
17419
- const held = JSON.parse(state.db3_type);
17420
- const fields = held.models?.[model];
17876
+ const held2 = JSON.parse(state.db3_type);
17877
+ const fields = held2.models?.[model];
17421
17878
  if (!fields) return null;
17422
17879
  const kind = Object.prototype.hasOwnProperty.call(fields, field) ? fields[field] : null;
17423
- const dims = held.vectors?.[model]?.[field]?.dims;
17880
+ const dims = held2.vectors?.[model]?.[field]?.dims;
17424
17881
  return { kind, ...typeof dims === "number" ? { dims } : {} };
17425
17882
  } catch {
17426
17883
  return null;
@@ -17468,7 +17925,8 @@ function readViewPage(sql, model, filter, options, limits = {}, support, deviceI
17468
17925
  const excluding = selected !== void 0 && Object.values(selected).every((value) => value === 0);
17469
17926
  const direction = options.direction === -1 ? -1 : 1;
17470
17927
  const textIndex = searchedIndex(sql, model, filter, options.documents, support, deviceIndexes);
17471
- const find = (local2) => db3ViewTranslator(model, { tieBreak: true, ...local2, ...forcedOptions(sql, model) }).translateFind(filter, {
17928
+ let unset;
17929
+ const find = (local2) => db3ViewTranslator(model, { tieBreak: true, ...local2, ...forcedOptions(sql, model), ...unset }).translateFind(filter, {
17472
17930
  ...options.sort ? { sort: options.sort } : {},
17473
17931
  ...selected ? { projection: selected } : {},
17474
17932
  ...options.uniqueStartKey ? { uniqueStartKey: options.uniqueStartKey } : {},
@@ -17477,7 +17935,9 @@ function readViewPage(sql, model, filter, options, limits = {}, support, deviceI
17477
17935
  direction,
17478
17936
  documents: [...options.documents]
17479
17937
  });
17480
- const judged = find({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
17938
+ let judged = find({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
17939
+ unset = clearedReadOf(sql, model, options.documents);
17940
+ if (unset) judged = find({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
17481
17941
  const local = deviceIndexReadOptions(sql, model, options.documents, textIndex, vectorIndex);
17482
17942
  const query = local.memberIndexTable ? find(local) : judged;
17483
17943
  const aliased = query.cursorSortValueFields ?? [];
@@ -17516,6 +17976,11 @@ function readViewPage(sql, model, filter, options, limits = {}, support, deviceI
17516
17976
  mint = { ...mint, _distance: distance };
17517
17977
  }
17518
17978
  row = canonicalSets(row, setFields);
17979
+ if (unset) {
17980
+ const cleared = heldClearedOf(sql, String(docId))?.get(model);
17981
+ row = withoutNames(row, cleared);
17982
+ mint = withoutNames(mint, cleared);
17983
+ }
17519
17984
  const bytes = jsonBytes(row);
17520
17985
  if (rows.length > 0 && used + bytes > policy.budgetBytes) {
17521
17986
  hasMore = true;
@@ -17564,13 +18029,16 @@ function resolvePageIncludes(sql, model, rows, documents, includes, policy, used
17564
18029
  const budget = { limit: policy.budgetBytes, used };
17565
18030
  for (const [docId, parents] of groups) {
17566
18031
  const source = {
17567
- translator: (related, path) => db3ViewTranslator(related, { document: docId, ...forcedOptions(sql, related, path) }),
18032
+ translator: (related, path) => {
18033
+ const unsetFields = heldClearedOf(sql, docId)?.get(related);
18034
+ return db3ViewTranslator(related, { document: docId, ...forcedOptions(sql, related, path), ...unsetFields ? { unsetFields } : {} });
18035
+ },
17568
18036
  exec: (text, params) => sql.exec(text, ...params),
17569
- // A related row answers as a parent row does: its fields, no `type`.
17570
- decodeRow: (_related, row) => {
18037
+ // A related row answers as a parent row does: its fields, no `type`, none the db3's type clears.
18038
+ decodeRow: (related, row) => {
17571
18039
  const { type: _type, ...fields } = parseRecordRow(row);
17572
18040
  void _type;
17573
- return fields;
18041
+ return withoutNames(fields, heldClearedOf(sql, docId)?.get(related));
17574
18042
  }
17575
18043
  };
17576
18044
  resolveIncludes(
@@ -17654,8 +18122,13 @@ function readDocumentSync(sql, documents) {
17654
18122
  function countViewRows(sql, model, filter, documents, support, deviceIndexes) {
17655
18123
  const vectorIndex = nearIndexOf(sql, model, filter, void 0, documents, support, deviceIndexes);
17656
18124
  const textIndex = searchedIndex(sql, model, filter, documents, support, deviceIndexes);
17657
- const count = (local2) => db3ViewTranslator(model, { ...local2, ...forcedOptions(sql, model) }).translateCount(filter, { documents: [...documents] });
17658
- const judged = count({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
18125
+ let unset;
18126
+ const count = (local2) => db3ViewTranslator(model, { ...local2, ...forcedOptions(sql, model), ...unset }).translateCount(filter, {
18127
+ documents: [...documents]
18128
+ });
18129
+ let judged = count({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
18130
+ unset = clearedReadOf(sql, model, documents);
18131
+ if (unset) judged = count({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
17659
18132
  const local = deviceIndexReadOptions(sql, model, documents, textIndex, vectorIndex);
17660
18133
  const { sql: text, params } = local.memberIndexTable ? count(local) : judged;
17661
18134
  const [row] = Array.from(sql.exec(text, ...params));
@@ -17667,11 +18140,16 @@ function aggregateViewRows(sql, model, options, documents, setFields = [], limit
17667
18140
  const sets = new Set(setFields);
17668
18141
  const vectorIndex = nearIndexOf(sql, model, options.filter, void 0, documents, support, deviceIndexes);
17669
18142
  const textIndex = searchedIndex(sql, model, options.filter, documents, support, deviceIndexes);
17670
- const aggregate = (local2) => buildAggregate(db3ViewTranslator(model, { ...local2, ...forcedOptions(sql, model) }).aggregateSource({ isSetField: (field) => sets.has(field) }), {
17671
- ...options,
17672
- documents: [...documents]
17673
- });
17674
- const judged = aggregate({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
18143
+ let unset;
18144
+ const aggregate = (local2) => buildAggregate(
18145
+ db3ViewTranslator(model, { ...local2, ...forcedOptions(sql, model), ...unset }).aggregateSource({
18146
+ isSetField: (field) => sets.has(field)
18147
+ }),
18148
+ { ...options, documents: [...documents] }
18149
+ );
18150
+ let judged = aggregate({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
18151
+ unset = clearedReadOf(sql, model, documents);
18152
+ if (unset) judged = aggregate({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
17675
18153
  const local = deviceIndexReadOptions(sql, model, documents, textIndex, vectorIndex);
17676
18154
  const plan = local.memberIndexTable ? aggregate(local) : judged;
17677
18155
  const sqlRows = Array.from(sql.exec(plan.sql, ...plan.params));
@@ -17889,9 +18367,9 @@ function recordingHandle(sql, force, root) {
17889
18367
  let building = { model: root };
17890
18368
  const handle = forceViewReads(
17891
18369
  {
17892
- exec: (query, ...bindings) => {
17893
- if (reportedStatement(query)) runs.push({ ...building, sql: query, bindings });
17894
- return sql.exec(query, ...bindings);
18370
+ exec: (query, ...bindings2) => {
18371
+ if (reportedStatement(query)) runs.push({ ...building, sql: query, bindings: bindings2 });
18372
+ return sql.exec(query, ...bindings2);
17895
18373
  },
17896
18374
  transaction: (fn) => sql.transaction(fn)
17897
18375
  },
@@ -17942,8 +18420,8 @@ function explainViewRead(sql, docId, model, request, setFields, context = {}) {
17942
18420
  }
17943
18421
  throw error;
17944
18422
  }
17945
- const quoted3 = (name) => `"${name.replace(/"/g, '""')}"`;
17946
- if (planned?.memberTable !== void 0 && !runs.some((run) => run.sql.includes(quoted3(planned.memberTable)))) {
18423
+ const quoted4 = (name) => `"${name.replace(/"/g, '""')}"`;
18424
+ if (planned?.memberTable !== void 0 && !runs.some((run) => run.sql.includes(quoted4(planned.memberTable)))) {
17947
18425
  throw cannotServe(
17948
18426
  checked.index,
17949
18427
  model,
@@ -17951,7 +18429,7 @@ function explainViewRead(sql, docId, model, request, setFields, context = {}) {
17951
18429
  `The member index ${checked.index} serves $contains, any-of, a membership level or an unfiltered facet on its field; this read has none`
17952
18430
  );
17953
18431
  }
17954
- if (planned?.scalarIndex !== void 0 && !runs.some((run) => run.sql.includes(`INDEXED BY ${quoted3(planned.scalarIndex)}`))) {
18432
+ if (planned?.scalarIndex !== void 0 && !runs.some((run) => run.sql.includes(`INDEXED BY ${quoted4(planned.scalarIndex)}`))) {
17955
18433
  throw cannotServe(checked.index, model, "shape", `The index ${checked.index} is a field index, and no statement of this read reads ${model}'s records to take it`);
17956
18434
  }
17957
18435
  const registry = recordLogRegistryNames(sql, docId);
@@ -18039,7 +18517,7 @@ function traceViewRead(sql, documents, model, read) {
18039
18517
  init_logger();
18040
18518
  init_schema();
18041
18519
  init_vectorIndex();
18042
- var rowsOf2 = (sql, query, ...bindings) => Array.from(sql.exec(query, ...bindings));
18520
+ var rowsOf2 = (sql, query, ...bindings2) => Array.from(sql.exec(query, ...bindings2));
18043
18521
  var optionsOf2 = (row) => row.options === null || row.options === void 0 ? { on: "device" } : JSON.parse(String(row.options));
18044
18522
  var STORAGE_FAILURE_CODES = /* @__PURE__ */ new Set([5, 6, 8, 9, 10, 13, 14]);
18045
18523
  var STORAGE_FAILURE_NAMES = /^SQLITE_(BUSY|LOCKED|READONLY|INTERRUPT|IOERR|FULL|CANTOPEN)(_|$)/;
@@ -18084,11 +18562,11 @@ function vectorModelWants(sql, docId, deviceIndexes, now = Date.now()) {
18084
18562
  if (row.vector === null || row.vector === void 0 || !builtByPolicy(row, deviceIndexes)) continue;
18085
18563
  const options = optionsOf2(row);
18086
18564
  if (!options.vector || !isAnnIndex(options.vector.index) || options.unbuilt !== void 0 || options.fill) continue;
18087
- const held = trainingHeld(options, now);
18565
+ const held2 = trainingHeld(options, now);
18088
18566
  const name = String(row.room_name);
18089
18567
  const localOnly = Number(row.local_only ?? 0) === 1;
18090
18568
  if (localOnly) {
18091
- if (held || options.ann || options.refused) continue;
18569
+ if (held2 || options.ann || options.refused) continue;
18092
18570
  } else {
18093
18571
  const generation = options.generation;
18094
18572
  if (generation === void 0 || options.revision === void 0) continue;
@@ -18099,7 +18577,7 @@ function vectorModelWants(sql, docId, deviceIndexes, now = Date.now()) {
18099
18577
  wants.push({ name, want: "fetch", generation, revision });
18100
18578
  continue;
18101
18579
  }
18102
- if (held || options.ann) continue;
18580
+ if (held2 || options.ann) continue;
18103
18581
  if (options.refused && options.refused.generation === generation && options.refused.revision === options.revision) continue;
18104
18582
  }
18105
18583
  const rows = liveRows(sql, row);
@@ -18447,6 +18925,58 @@ var RecordLogClient = class {
18447
18925
  if (entry?.void) this.tables.deletePending(this.writer, seq);
18448
18926
  return { touched: [] };
18449
18927
  }
18928
+ /**
18929
+ * Apply model clears a catch-up carries, oldest first, before the rows,
18930
+ * chunks or page they ride with. The cursor does not move: the catch-up's
18931
+ * completion moves it. A clear at or below the cursor, or at or below the
18932
+ * highest clear applied (a resumed download is sent the clears again),
18933
+ * changes nothing.
18934
+ */
18935
+ applyClears(clears) {
18936
+ const out = { touched: [] };
18937
+ const ordered = [...clears].sort((a, b) => a.l - b.l);
18938
+ for (const clear of ordered) {
18939
+ if (clear.l <= this.tables.cursor()) continue;
18940
+ if (this.applyClear(clear.model, clear.l, out)) this.sawEpoch(clear.e);
18941
+ }
18942
+ return out;
18943
+ }
18944
+ /**
18945
+ * Empty `model` for the clear at log number `l`, unless a clear at or past
18946
+ * `l` was applied already; the mark moves with the removal. Answers
18947
+ * whether it removed.
18948
+ */
18949
+ applyClear(model, l, out) {
18950
+ if (l <= this.tables.clearedThrough()) return false;
18951
+ this.changedUnderReplacement({});
18952
+ out.touched.push(...this.tables.clearModel(model));
18953
+ this.tables.setClearedThrough(l, model);
18954
+ if (!(out.cleared ??= []).includes(model)) out.cleared.push(model);
18955
+ return true;
18956
+ }
18957
+ /**
18958
+ * Whether a clear of `model` above log number `l` was applied already: a
18959
+ * catch-up applies the clears it carries before the cursor reaches them,
18960
+ * so a session sharing this store can still be handed results below one.
18961
+ * Such a result's rows of the model were removed by the clear on the room,
18962
+ * and stay removed here.
18963
+ */
18964
+ clearedPast(model, l) {
18965
+ return this.tables.clearedAt(model) > l;
18966
+ }
18967
+ /**
18968
+ * Whether rows of `model` the room read at log number `readAt` (a page's
18969
+ * `lsn`, a load's last log number, a segment's `C`) predate a clear of it
18970
+ * applied already. Another session sharing this store applied that clear
18971
+ * from its own catch-up; the room removed those rows with it and keeps no
18972
+ * tombstone, so putting them back here would keep them for good; and a row
18973
+ * of the model the store holds now was written after the clear, so a
18974
+ * removal read before it does not apply either. Without `readAt` (a caller
18975
+ * that did not say) everything applies.
18976
+ */
18977
+ readBeforeClear(model, readAt) {
18978
+ return readAt !== void 0 && this.clearedPast(model, readAt);
18979
+ }
18450
18980
  /**
18451
18981
  * Something the room relayed. A result is applied to the confirmed rows in
18452
18982
  * log-number order (one ahead of the cursor waits; one at or below it was
@@ -18457,7 +18987,8 @@ var RecordLogClient = class {
18457
18987
  *
18458
18988
  * A compact acknowledgement (no `changes`) is applied, in its turn, by its
18459
18989
  * pending entry's mutations as plain row operations, the rule by which the
18460
- * room vouched for it. With no unwithdrawn pending entry for its `seq` it
18990
+ * room vouched for it. A model clear empties its model in its turn, once
18991
+ * ({@link applyClears}). With no unwithdrawn pending entry for its `seq` it
18461
18992
  * stays buffered, the cursor stops below it, and the outcome names it
18462
18993
  * (`underivable`).
18463
18994
  */
@@ -18496,9 +19027,11 @@ var RecordLogClient = class {
18496
19027
  for (let next = this.tables.buffered(this.tables.cursor() + 1); next; next = this.tables.buffered(this.tables.cursor() + 1)) {
18497
19028
  if (!applied) this.changedUnderReplacement({});
18498
19029
  applied = true;
18499
- if (next.changes) {
19030
+ if (next.clear) {
19031
+ this.applyClear(next.clear.model, next.l, out);
19032
+ } else if (next.changes) {
18500
19033
  for (const change of next.changes) {
18501
- applyChange(confirmed, change);
19034
+ if (!this.clearedPast(change.model, next.l)) applyChange(confirmed, change);
18502
19035
  out.touched.push({ model: change.model, id: change.id });
18503
19036
  }
18504
19037
  } else if (!this.applyOwnEntry(confirmed, next, out)) {
@@ -18529,6 +19062,10 @@ var RecordLogClient = class {
18529
19062
  if (!entry || entry.void) return false;
18530
19063
  for (const m of mutationsOf(entry)) {
18531
19064
  const key = { model: m.model, id: m.id };
19065
+ if (this.clearedPast(m.model, item.l)) {
19066
+ out.touched.push(key);
19067
+ continue;
19068
+ }
18532
19069
  const row = plainRowAfter(confirmed.row(key), m);
18533
19070
  if (row) confirmed.set(key, row);
18534
19071
  else if (m.kind === "delete") confirmed.delete(key);
@@ -18688,6 +19225,10 @@ var RecordLogClient = class {
18688
19225
  * cursor. A page of receipt `receipt`'s remainder is refused with
18689
19226
  * {@link RecordLogStaleReceiptError} before anything changes once another
18690
19227
  * attempt took that receipt over; it does not count as the attempt's change.
19228
+ * A row or gone record of a model whose clear above `readAt` (the log number
19229
+ * the room read the page at) was applied already changes nothing
19230
+ * ({@link readBeforeClear}): a row of it the store holds now was written
19231
+ * after the clear.
18691
19232
  */
18692
19233
  applyCatchUpPage(page) {
18693
19234
  this.assertNotDisplaced(page.receipt);
@@ -18696,10 +19237,12 @@ var RecordLogClient = class {
18696
19237
  const confirmed = this.tables.confirmed();
18697
19238
  const touched = [];
18698
19239
  for (const { model, id, row } of page.rows) {
19240
+ if (this.readBeforeClear(model, page.readAt)) continue;
18699
19241
  confirmed.set({ model, id }, { ...row });
18700
19242
  touched.push({ model, id });
18701
19243
  }
18702
19244
  for (const key of page.gone ?? []) {
19245
+ if (this.readBeforeClear(key.model, page.readAt)) continue;
18703
19246
  confirmed.delete(key);
18704
19247
  touched.push({ model: key.model, id: key.id });
18705
19248
  }
@@ -18727,6 +19270,7 @@ var RecordLogClient = class {
18727
19270
  if (next) {
18728
19271
  const replay = this.receive(next);
18729
19272
  out.touched.push(...replay.touched);
19273
+ if (replay.cleared?.length) out.cleared = [.../* @__PURE__ */ new Set([...out.cleared ?? [], ...replay.cleared])];
18730
19274
  out.acknowledged.push(...replay.acknowledged);
18731
19275
  out.settled.push(...replay.settled);
18732
19276
  if (replay.settlements) (out.settlements ??= []).push(...replay.settlements);
@@ -18916,20 +19460,24 @@ var RecordLogClient = class {
18916
19460
  * with each member once, as the room stores it (#5274). Each key is
18917
19461
  * remembered for a refresh, unless the load's `mode` is `merge`, whose
18918
19462
  * completion removes nothing. An attempt no longer in progress is refused
18919
- * with {@link RecordLogStaleReceiptError} before anything changes.
19463
+ * with {@link RecordLogStaleReceiptError} before anything changes. A chunk
19464
+ * of a model whose clear above `readAt` (the load's last log number) was
19465
+ * applied already changes no row ({@link readBeforeClear}); it still counts
19466
+ * as the attempt's chunk and names its keys.
18920
19467
  *
18921
19468
  * @returns The records whose confirmed row changed.
18922
19469
  */
18923
19470
  applyLoadLines(chunk) {
18924
19471
  const tables = this.receiptTables();
18925
19472
  this.touchReceipt(chunk.attempt, { chunk: true });
19473
+ const lines = this.readBeforeClear(chunk.model, chunk.readAt) ? [] : chunk.lines;
18926
19474
  const batch = this.batchRows(
18927
- chunk.lines.map(({ id }) => ({ model: chunk.model, id })),
19475
+ lines.map(({ id }) => ({ model: chunk.model, id })),
18928
19476
  true
18929
19477
  );
18930
19478
  const confirmed = batch ?? this.tables.confirmed();
18931
19479
  const touched = [];
18932
- for (const { id, patch } of chunk.lines) {
19480
+ for (const { id, patch } of lines) {
18933
19481
  const key = { model: chunk.model, id };
18934
19482
  const existing = confirmed.row(key);
18935
19483
  if (patch._deleted === true) {
@@ -18985,14 +19533,20 @@ var RecordLogClient = class {
18985
19533
  tables.forgetLoad(load2.attempt);
18986
19534
  return { touched };
18987
19535
  }
18988
- /** Put a segment's rows under the replacement `generation`, as receipt `attempt` when it names one. */
19536
+ /**
19537
+ * Put a segment's rows under the replacement `generation`, as receipt
19538
+ * `attempt` when it names one; a row of a model whose clear above `readAt`
19539
+ * (the segment's `C`) was applied already is not put back
19540
+ * ({@link readBeforeClear}).
19541
+ */
18989
19542
  applySegmentRows(segment) {
18990
19543
  this.assertGeneration(segment.generation);
18991
19544
  if (segment.attempt !== void 0) this.touchReceipt(segment.attempt, { chunk: true });
18992
- const batch = this.batchRows(segment.rows, false);
19545
+ const rows = segment.rows.filter(({ model }) => !this.readBeforeClear(model, segment.readAt));
19546
+ const batch = this.batchRows(rows, false);
18993
19547
  const confirmed = batch ?? this.tables.confirmed();
18994
19548
  const touched = [];
18995
- for (const { model, id, row } of segment.rows) {
19549
+ for (const { model, id, row } of rows) {
18996
19550
  confirmed.set({ model, id }, { ...row, id });
18997
19551
  touched.push({ model, id });
18998
19552
  }
@@ -19016,6 +19570,7 @@ var RecordLogClient = class {
19016
19570
  this.assertGeneration(chunk.generation);
19017
19571
  const state = this.receiptTables().receipts();
19018
19572
  if (!state || !state.attempts.some((a) => a.attempt === chunk.attempt)) throw new RecordLogStaleReceiptError(chunk.attempt);
19573
+ if (this.readBeforeClear(chunk.model, chunk.readAt)) return { mismatch: true };
19019
19574
  const entry = this.tables.heldSegment?.()?.chunks.find((c) => c.object === chunk.object);
19020
19575
  const same = entry !== void 0 && entry.model === chunk.model && entry.sha256 === chunk.sha256 && entry.rows === chunk.rows && entry.firstId === chunk.firstId && entry.lastId === chunk.lastId;
19021
19576
  const alone = state.attempts.every((a) => a.attempt === chunk.attempt);
@@ -19027,7 +19582,9 @@ var RecordLogClient = class {
19027
19582
  /**
19028
19583
  * Apply a segment's corrections under the replacement `generation`: a row
19029
19584
  * replaces the record's, a `null` deletes it (one the chunks did not carry
19030
- * changes nothing).
19585
+ * changes nothing). A line of a model whose clear above `readAt` (the
19586
+ * segment's `C`) was applied already changes nothing
19587
+ * ({@link readBeforeClear}).
19031
19588
  */
19032
19589
  applySegmentCorrections(segment) {
19033
19590
  this.assertGeneration(segment.generation);
@@ -19036,6 +19593,7 @@ var RecordLogClient = class {
19036
19593
  const touched = [];
19037
19594
  for (const { model, id, row } of segment.lines) {
19038
19595
  const key = { model, id };
19596
+ if (this.readBeforeClear(model, segment.readAt)) continue;
19039
19597
  if (row === null) {
19040
19598
  if (!confirmed.row(key)) continue;
19041
19599
  confirmed.delete(key);
@@ -19106,6 +19664,8 @@ var MemoryRecordLogTables = class {
19106
19664
  writers = /* @__PURE__ */ new Map();
19107
19665
  counts = /* @__PURE__ */ new Map();
19108
19666
  headValue = null;
19667
+ clearedValue = 0;
19668
+ clearedModels = /* @__PURE__ */ new Map();
19109
19669
  /**
19110
19670
  * @param init - The rows, cursor and epochs to start from.
19111
19671
  */
@@ -19204,6 +19764,23 @@ var MemoryRecordLogTables = class {
19204
19764
  if (!named) this.loadKeys.set(attempt, named = /* @__PURE__ */ new Set());
19205
19765
  for (const key of keys) named.add(keyText(key));
19206
19766
  }
19767
+ clearModel(model) {
19768
+ for (const text of [...this.rows.rows.keys()]) {
19769
+ const at = text.indexOf("\0");
19770
+ if (text.slice(0, at) === model) this.rows.delete({ model, id: text.slice(at + 1) });
19771
+ }
19772
+ return [];
19773
+ }
19774
+ clearedThrough() {
19775
+ return this.clearedValue;
19776
+ }
19777
+ clearedAt(model) {
19778
+ return this.clearedModels.get(model) ?? 0;
19779
+ }
19780
+ setClearedThrough(l, model) {
19781
+ this.clearedValue = Math.max(this.clearedValue, l);
19782
+ this.clearedModels.set(model, Math.max(this.clearedModels.get(model) ?? 0, l));
19783
+ }
19207
19784
  removeUnnamed(attempt, models) {
19208
19785
  const named = this.loadKeys.get(attempt) ?? /* @__PURE__ */ new Set();
19209
19786
  const covered = new Set(models);
@@ -19446,7 +20023,9 @@ function recordLogClientDDL() {
19446
20023
  local_only INTEGER NOT NULL DEFAULT 0,
19447
20024
  local_indexes TEXT,
19448
20025
  known_head INTEGER,
19449
- known_head_at INTEGER
20026
+ known_head_at INTEGER,
20027
+ cleared_lsn INTEGER,
20028
+ cleared_models TEXT
19450
20029
  )`,
19451
20030
  `CREATE TABLE IF NOT EXISTS record_log_writers (
19452
20031
  doc_id TEXT NOT NULL,
@@ -19544,6 +20123,10 @@ var RECORD_LOG_KNOWN_HEAD_COLUMNS = Object.freeze([
19544
20123
  var RECORD_LOG_VECTOR_INDEX_COLUMNS = Object.freeze([
19545
20124
  { table: "record_log_indexes", column: "vector", add: `ALTER TABLE record_log_indexes ADD COLUMN vector TEXT` }
19546
20125
  ]);
20126
+ var RECORD_LOG_CLEAR_MARK_COLUMNS = Object.freeze([
20127
+ { table: "record_log_state", column: "cleared_lsn", add: `ALTER TABLE record_log_state ADD COLUMN cleared_lsn INTEGER` },
20128
+ { table: "record_log_state", column: "cleared_models", add: `ALTER TABLE record_log_state ADD COLUMN cleared_models TEXT` }
20129
+ ]);
19547
20130
  var RECORD_LOG_CLIENT_ADDED_COLUMNS = Object.freeze([
19548
20131
  { table: "record_log_state", column: "receipt", add: `ALTER TABLE record_log_state ADD COLUMN receipt TEXT` },
19549
20132
  { table: "record_log_state", column: "segment", add: `ALTER TABLE record_log_state ADD COLUMN segment TEXT` },
@@ -19553,7 +20136,8 @@ var RECORD_LOG_CLIENT_ADDED_COLUMNS = Object.freeze([
19553
20136
  ...RECORD_LOG_LOCAL_ONLY_COLUMNS,
19554
20137
  ...RECORD_LOG_MEMBER_INDEX_COLUMNS,
19555
20138
  ...RECORD_LOG_KNOWN_HEAD_COLUMNS,
19556
- ...RECORD_LOG_VECTOR_INDEX_COLUMNS
20139
+ ...RECORD_LOG_VECTOR_INDEX_COLUMNS,
20140
+ ...RECORD_LOG_CLEAR_MARK_COLUMNS
19557
20141
  ]);
19558
20142
  function recordLogFieldIndexName(kind, model, name, table = "view") {
19559
20143
  const tag = kind === "field" ? "f" : "u";
@@ -19602,7 +20186,7 @@ function purgeDocumentQueryRows(sql, docId) {
19602
20186
  sql.exec(`DELETE FROM ${quote2(parent)} WHERE "_meta_doc_id" = ?`, docId);
19603
20187
  }
19604
20188
  }
19605
- var RECORD_LOG_STORAGE_VERSION = 11;
20189
+ var RECORD_LOG_STORAGE_VERSION = 12;
19606
20190
  var DATA_TABLES = ["record_log_rows", "record_log_view", "record_log_staged_base"];
19607
20191
  function migrateRecordLogStore(sql, options) {
19608
20192
  let current = 1;
@@ -19718,6 +20302,7 @@ function convertToOneCopy(sql) {
19718
20302
  }
19719
20303
  function addIndexSkips(sql) {
19720
20304
  if (storedDocuments(sql).length > 0) sql.exec(RECORD_LOG_INDEX_SKIPS_DDL);
20305
+ addMissingColumns(sql, RECORD_LOG_CLEAR_MARK_COLUMNS);
19721
20306
  writeStorageVersion(sql, RECORD_LOG_STORAGE_VERSION);
19722
20307
  }
19723
20308
  function regroupLoadKeys(sql) {
@@ -19926,8 +20511,8 @@ function storedData(row) {
19926
20511
  function storedRow(id, data) {
19927
20512
  return rowWithId(String(id), JSON.parse(String(data)));
19928
20513
  }
19929
- function rowsOf3(sql, query, ...bindings) {
19930
- return Array.from(sql.exec(query, ...bindings));
20514
+ function rowsOf3(sql, query, ...bindings2) {
20515
+ return Array.from(sql.exec(query, ...bindings2));
19931
20516
  }
19932
20517
  var BOUND_IDS = 400;
19933
20518
  function idLists(ids) {
@@ -20040,21 +20625,24 @@ var SqlRecordLogTables = class {
20040
20625
  typeState() {
20041
20626
  const state = this.state();
20042
20627
  const typed = state?.typed === "yes" ? "yes" : state?.typed === "no" ? "no" : "unknown";
20043
- const none = { declarations: null, vectors: null, vectorsKnown: true, enums: null, enumsKnown: true };
20628
+ const none = { declarations: null, vectors: null, vectorsKnown: true, enums: null, enumsKnown: true, cleared: null, clearedKnown: true };
20044
20629
  if (typed !== "yes" || !state?.db3_type) return { typed, db3Type: null, ...none };
20045
20630
  try {
20046
- const held = JSON.parse(String(state.db3_type));
20047
- const declarations = held.models ?? null;
20631
+ const held2 = JSON.parse(String(state.db3_type));
20632
+ const declarations = held2.models ?? null;
20048
20633
  return {
20049
20634
  typed,
20050
- db3Type: { name: held.name, hash: held.hash ?? null },
20635
+ db3Type: { name: held2.name, hash: held2.hash ?? null },
20051
20636
  declarations,
20052
- vectors: held.vectors ?? null,
20637
+ vectors: held2.vectors ?? null,
20053
20638
  // An entry with declarations and no `vectors` key was written before vector fields (#5225).
20054
- vectorsKnown: declarations === null || Object.prototype.hasOwnProperty.call(held, "vectors"),
20055
- enums: held.enums ?? null,
20639
+ vectorsKnown: declarations === null || Object.prototype.hasOwnProperty.call(held2, "vectors"),
20640
+ enums: held2.enums ?? null,
20056
20641
  // An entry with declarations and no `enums` key was written before enforced enums (#5897).
20057
- enumsKnown: declarations === null || Object.prototype.hasOwnProperty.call(held, "enums")
20642
+ enumsKnown: declarations === null || Object.prototype.hasOwnProperty.call(held2, "enums"),
20643
+ cleared: held2.cleared ?? null,
20644
+ // An entry with declarations and no `cleared` key was written before cleared fields (#6021).
20645
+ clearedKnown: declarations === null || Object.prototype.hasOwnProperty.call(held2, "cleared")
20058
20646
  };
20059
20647
  } catch {
20060
20648
  return { typed, db3Type: null, ...none };
@@ -20066,16 +20654,18 @@ var SqlRecordLogTables = class {
20066
20654
  */
20067
20655
  setType(update) {
20068
20656
  this.ensureState();
20657
+ forgetHeldCleared(this.sql, this.docId);
20069
20658
  if (update.typed === "no") {
20070
20659
  this.sql.exec(`UPDATE record_log_state SET typed = 'no', db3_type = NULL WHERE doc_id = ?`, this.docId);
20071
20660
  return;
20072
20661
  }
20073
- const held = this.typeState();
20662
+ const held2 = this.typeState();
20074
20663
  const { name, hash, models } = update.db3Type;
20075
- const keepsHeld = models === void 0 && hash !== null && held.db3Type?.hash === hash;
20076
- const kept = models ?? (keepsHeld ? held.declarations : null);
20077
- const vectors = models !== void 0 ? update.db3Type.vectors ?? null : keepsHeld && held.vectorsKnown ? held.vectors : void 0;
20078
- const enums = models !== void 0 ? update.db3Type.enums ?? null : keepsHeld && held.enumsKnown ? held.enums : void 0;
20664
+ const keepsHeld = models === void 0 && hash !== null && held2.db3Type?.hash === hash;
20665
+ const kept = models ?? (keepsHeld ? held2.declarations : null);
20666
+ const vectors = models !== void 0 ? update.db3Type.vectors ?? null : keepsHeld && held2.vectorsKnown ? held2.vectors : void 0;
20667
+ const enums = models !== void 0 ? update.db3Type.enums ?? null : keepsHeld && held2.enumsKnown ? held2.enums : void 0;
20668
+ const cleared = models !== void 0 ? update.db3Type.cleared ?? null : keepsHeld && held2.clearedKnown ? held2.cleared : void 0;
20079
20669
  this.sql.exec(
20080
20670
  `UPDATE record_log_state SET typed = 'yes', db3_type = ? WHERE doc_id = ?`,
20081
20671
  JSON.stringify({
@@ -20083,7 +20673,8 @@ var SqlRecordLogTables = class {
20083
20673
  hash: kept ? hash : null,
20084
20674
  models: kept,
20085
20675
  ...kept && vectors !== void 0 ? { vectors } : {},
20086
- ...kept && enums !== void 0 ? { enums } : {}
20676
+ ...kept && enums !== void 0 ? { enums } : {},
20677
+ ...kept && cleared !== void 0 ? { cleared } : {}
20087
20678
  }),
20088
20679
  this.docId
20089
20680
  );
@@ -20187,7 +20778,9 @@ var SqlRecordLogTables = class {
20187
20778
  }
20188
20779
  /** Records whose view row a confirmed write changed since the last call, each with the row it showed before. */
20189
20780
  takeViewChanged() {
20190
- const out = [...this.viewChanged.values()];
20781
+ const out = [...this.viewChanged.values()].map(
20782
+ (change) => change.before ? { ...change, before: withoutHeldCleared(this.sql, this.docId, change.key.model, change.before) } : change
20783
+ );
20191
20784
  this.viewChanged.clear();
20192
20785
  return out;
20193
20786
  }
@@ -20216,18 +20809,18 @@ var SqlRecordLogTables = class {
20216
20809
  if (state?.replacing === null || state?.replacing === void 0) return false;
20217
20810
  const completed = Number(state.rows_gen ?? 0);
20218
20811
  const within = `doc_id = ? AND _type = ? AND _id >= ? AND _id <= ? AND _gen = ?`;
20219
- const bindings = [this.docId, range.model, range.firstId, range.lastId, completed];
20812
+ const bindings2 = [this.docId, range.model, range.firstId, range.lastId, completed];
20220
20813
  const shown = `${within} AND NOT EXISTS (${OVERLAY_ROW_OF("record_log_view")})`;
20221
- const held = `${within} AND _data IS NOT NULL`;
20814
+ const held2 = `${within} AND _data IS NOT NULL`;
20222
20815
  const [count] = rowsOf3(
20223
20816
  this.sql,
20224
- `SELECT (SELECT COUNT(*) FROM record_log_view WHERE ${shown}) + (SELECT COUNT(*) FROM record_log_rows WHERE ${held}) AS n`,
20225
- ...bindings,
20226
- ...bindings
20817
+ `SELECT (SELECT COUNT(*) FROM record_log_view WHERE ${shown}) + (SELECT COUNT(*) FROM record_log_rows WHERE ${held2}) AS n`,
20818
+ ...bindings2,
20819
+ ...bindings2
20227
20820
  );
20228
20821
  if (Number(count?.n ?? 0) !== range.rows) return false;
20229
- this.sql.exec(`UPDATE record_log_view SET _gen = ? WHERE ${shown}`, Number(state.replacing), ...bindings);
20230
- this.sql.exec(`UPDATE record_log_rows SET _gen = ? WHERE ${held}`, Number(state.replacing), ...bindings);
20822
+ this.sql.exec(`UPDATE record_log_view SET _gen = ? WHERE ${shown}`, Number(state.replacing), ...bindings2);
20823
+ this.sql.exec(`UPDATE record_log_rows SET _gen = ? WHERE ${held2}`, Number(state.replacing), ...bindings2);
20231
20824
  return true;
20232
20825
  }
20233
20826
  noteLoadKeys(attempt, keys) {
@@ -20257,6 +20850,80 @@ var SqlRecordLogTables = class {
20257
20850
  }
20258
20851
  }
20259
20852
  }
20853
+ clearModel(model) {
20854
+ const ctx = this.writeContext();
20855
+ if (ctx.staged) return this.clearStaged(model, ctx);
20856
+ const plain = `record_log_view.doc_id = ? AND record_log_view._type = ?
20857
+ AND NOT EXISTS (${OVERLAY_ROW_OF("record_log_view")}) AND NOT EXISTS (${PENDING_KEY_OF("record_log_view")})`;
20858
+ this.sql.exec(`DELETE FROM record_log_view WHERE ${plain}`, this.docId, model);
20859
+ const guessed = rowsOf3(
20860
+ this.sql,
20861
+ `SELECT _id FROM record_log_rows WHERE doc_id = ? AND _type = ? AND _data IS NOT NULL
20862
+ UNION ALL
20863
+ SELECT _id FROM record_log_view WHERE doc_id = ? AND _type = ? AND NOT EXISTS (${OVERLAY_ROW_OF("record_log_view")})`,
20864
+ this.docId,
20865
+ model,
20866
+ this.docId,
20867
+ model
20868
+ ).map((row) => ({ model, id: String(row._id) }));
20869
+ for (const key of guessed) this.putConfirmed(key, null, ctx);
20870
+ return guessed;
20871
+ }
20872
+ /**
20873
+ * {@link clearModel} under a staged replacement: the view still shows the
20874
+ * completed generation, guessed over the staged base. Each record of the
20875
+ * model, in the view, the overlay or the base, has its confirmed row put
20876
+ * as none under the replacement and its base kept as none, so the view
20877
+ * shows no row of it now and the replacement's completion keeps none.
20878
+ */
20879
+ clearStaged(model, ctx) {
20880
+ const keys = rowsOf3(
20881
+ this.sql,
20882
+ `SELECT _id FROM record_log_view WHERE doc_id = ? AND _type = ?
20883
+ UNION SELECT _id FROM record_log_rows WHERE doc_id = ? AND _type = ?
20884
+ UNION SELECT _id FROM record_log_staged_base WHERE doc_id = ? AND _type = ?`,
20885
+ this.docId,
20886
+ model,
20887
+ this.docId,
20888
+ model,
20889
+ this.docId,
20890
+ model
20891
+ ).map((row) => ({ model, id: String(row._id) }));
20892
+ this.stageBase(keys);
20893
+ this.sql.exec(`UPDATE record_log_staged_base SET _data = NULL WHERE doc_id = ? AND _type = ?`, this.docId, model);
20894
+ for (const key of keys) this.putConfirmed(key, null, ctx);
20895
+ return keys;
20896
+ }
20897
+ clearedThrough() {
20898
+ return Number(this.state()?.cleared_lsn ?? 0);
20899
+ }
20900
+ clearedAt(model) {
20901
+ return this.clearedModels().get(model) ?? 0;
20902
+ }
20903
+ setClearedThrough(l, model) {
20904
+ this.ensureState();
20905
+ const models = this.clearedModels();
20906
+ models.set(model, Math.max(models.get(model) ?? 0, l));
20907
+ this.sql.exec(
20908
+ `UPDATE record_log_state SET cleared_lsn = ?, cleared_models = ? WHERE doc_id = ?`,
20909
+ Math.max(this.clearedThrough(), l),
20910
+ JSON.stringify([...models]),
20911
+ this.docId
20912
+ );
20913
+ }
20914
+ /** Each cleared model's highest clear applied: a JSON list of `[model, l]`, so any model name reads back as it is. */
20915
+ clearedModels() {
20916
+ const text = this.state()?.cleared_models;
20917
+ const out = /* @__PURE__ */ new Map();
20918
+ if (typeof text !== "string") return out;
20919
+ try {
20920
+ for (const pair of JSON.parse(text)) {
20921
+ if (Array.isArray(pair) && typeof pair[0] === "string" && typeof pair[1] === "number") out.set(pair[0], pair[1]);
20922
+ }
20923
+ } catch {
20924
+ }
20925
+ return out;
20926
+ }
20260
20927
  removeUnnamed(attempt, models) {
20261
20928
  const removed = [];
20262
20929
  const ctx = this.writeContext();
@@ -20355,16 +21022,16 @@ var SqlRecordLogTables = class {
20355
21022
  continue;
20356
21023
  }
20357
21024
  const guessed = /* @__PURE__ */ new Set();
20358
- for (const { list, bindings } of idLists(ids)) {
21025
+ for (const { list, bindings: bindings2 } of idLists(ids)) {
20359
21026
  for (const row of this.sql.exec(
20360
21027
  `SELECT _id FROM record_log_rows WHERE doc_id = ? AND _type = ? AND _id IN ${list}
20361
21028
  UNION SELECT _id FROM record_log_pending_keys WHERE doc_id = ? AND _type = ? AND _id IN ${list}`,
20362
21029
  this.docId,
20363
21030
  model,
20364
- ...bindings,
21031
+ ...bindings2,
20365
21032
  this.docId,
20366
21033
  model,
20367
- ...bindings
21034
+ ...bindings2
20368
21035
  )) {
20369
21036
  guessed.add(String(row._id));
20370
21037
  }
@@ -20389,8 +21056,8 @@ var SqlRecordLogTables = class {
20389
21056
  /** Confirmed rows of `model` no guess covers, written into the view at once: `removed` first, then `puts`. */
20390
21057
  viewBatch(model, removed, puts, ctx) {
20391
21058
  const deleted = ctx.replacing ? [...removed, ...puts.map(([id]) => id)] : removed;
20392
- for (const { list, bindings } of idLists(deleted)) {
20393
- this.sql.exec(`DELETE FROM record_log_view WHERE doc_id = ? AND _type = ? AND _id IN ${list}`, this.docId, model, ...bindings);
21059
+ for (const { list, bindings: bindings2 } of idLists(deleted)) {
21060
+ this.sql.exec(`DELETE FROM record_log_view WHERE doc_id = ? AND _type = ? AND _id IN ${list}`, this.docId, model, ...bindings2);
20394
21061
  }
20395
21062
  if (!puts.length) return;
20396
21063
  const [next] = rowsOf3(this.sql, `SELECT ${NEXT_VIEW_ROWID} AS rowid`);
@@ -20425,16 +21092,16 @@ var SqlRecordLogTables = class {
20425
21092
  }
20426
21093
  this.defer(key);
20427
21094
  }
20428
- for (const { list, bindings } of idLists(written.map(({ key }) => key.id))) {
20429
- this.sql.exec(`DELETE FROM record_log_rows WHERE doc_id = ? AND _type = ? AND _id IN ${list}`, this.docId, model, ...bindings);
21095
+ for (const { list, bindings: bindings2 } of idLists(written.map(({ key }) => key.id))) {
21096
+ this.sql.exec(`DELETE FROM record_log_rows WHERE doc_id = ? AND _type = ? AND _id IN ${list}`, this.docId, model, ...bindings2);
20430
21097
  }
20431
- for (const { list, bindings } of idLists(gone)) {
21098
+ for (const { list, bindings: bindings2 } of idLists(gone)) {
20432
21099
  this.sql.exec(
20433
21100
  `INSERT INTO record_log_rows (doc_id, _type, _id, _data, _gen) SELECT ?, ?, value, NULL, ? FROM ${list}`,
20434
21101
  this.docId,
20435
21102
  model,
20436
21103
  generation,
20437
- ...bindings
21104
+ ...bindings2
20438
21105
  );
20439
21106
  }
20440
21107
  if (puts.size) {
@@ -21015,7 +21682,7 @@ function findHolder(sql, table, docId, model, fields, values, excluding) {
21015
21682
  function findConfirmedHolder(sql, docId, model, fields, values, excluding) {
21016
21683
  if (fields.length === 0 || values.some((v) => v === null || v === void 0)) return null;
21017
21684
  const lookup = fieldLookupPredicates(model, fields);
21018
- const bindings = fieldLookupBindings(lookup, model, fields, values.map(lookupBinding));
21685
+ const bindings2 = fieldLookupBindings(lookup, model, fields, values.map(lookupBinding));
21019
21686
  const skip = new Set(excluding);
21020
21687
  for (const row of sql.exec(
21021
21688
  `SELECT _id FROM (
@@ -21024,9 +21691,9 @@ function findConfirmedHolder(sql, docId, model, fields, values, excluding) {
21024
21691
  SELECT _id FROM record_log_rows WHERE doc_id = ? AND ${lookup.where} AND _data IS NOT NULL)
21025
21692
  ORDER BY _id LIMIT ?`,
21026
21693
  docId,
21027
- ...bindings,
21694
+ ...bindings2,
21028
21695
  docId,
21029
- ...bindings,
21696
+ ...bindings2,
21030
21697
  skip.size + 1
21031
21698
  )) {
21032
21699
  const id = String(row._id);
@@ -21262,7 +21929,7 @@ var RecordLogStore = class {
21262
21929
  if (!command.force && live.length > 0) {
21263
21930
  return { purged: false, reason: "pending", pendingOps: live.length, handedBack: [] };
21264
21931
  }
21265
- const [held] = rowsOf3(this.sql, `SELECT COUNT(*) AS n FROM record_log_state WHERE doc_id = ?`, this.docId);
21932
+ const [held2] = rowsOf3(this.sql, `SELECT COUNT(*) AS n FROM record_log_state WHERE doc_id = ?`, this.docId);
21266
21933
  const present = new Set(
21267
21934
  rowsOf3(this.sql, `SELECT name FROM sqlite_master WHERE type = 'table'`).map((row) => String(row.name))
21268
21935
  );
@@ -21275,7 +21942,7 @@ var RecordLogStore = class {
21275
21942
  }
21276
21943
  return {
21277
21944
  purged: true,
21278
- ...Number(held?.n ?? 0) === 0 && live.length === 0 ? { nothingStored: true } : {},
21945
+ ...Number(held2?.n ?? 0) === 0 && live.length === 0 ? { nothingStored: true } : {},
21279
21946
  pendingOps: live.length,
21280
21947
  handedBack: live
21281
21948
  };
@@ -21332,9 +21999,9 @@ var RecordLogStore = class {
21332
21999
  SELECT MIN(_type) FROM ${table} WHERE doc_id = ?
21333
22000
  UNION ALL SELECT (SELECT MIN(_type) FROM ${table} WHERE doc_id = ? AND _type > t.m) FROM t WHERE t.m IS NOT NULL)
21334
22001
  SELECT m AS _type FROM t WHERE m IS NOT NULL`;
21335
- const held = /* @__PURE__ */ new Set();
22002
+ const held2 = /* @__PURE__ */ new Set();
21336
22003
  for (const table of ["record_log_view", "record_log_rows"]) {
21337
- for (const row of rowsOf3(this.sql, skipScan(table), docId, docId)) held.add(String(row._type));
22004
+ for (const row of rowsOf3(this.sql, skipScan(table), docId, docId)) held2.add(String(row._type));
21338
22005
  }
21339
22006
  for (const row of rowsOf3(
21340
22007
  this.sql,
@@ -21343,9 +22010,9 @@ var RecordLogStore = class {
21343
22010
  WHERE p.doc_id = ? AND p.void = 0 AND p.acked IS NULL`,
21344
22011
  docId
21345
22012
  )) {
21346
- held.add(String(row._type));
22013
+ held2.add(String(row._type));
21347
22014
  }
21348
- return [...held].sort();
22015
+ return [...held2].sort();
21349
22016
  }
21350
22017
  /** A writer's unacknowledged, unwithdrawn entries and the records each touches. */
21351
22018
  unackedOf(writer) {
@@ -21380,7 +22047,7 @@ var RecordLogStore = class {
21380
22047
  model,
21381
22048
  id
21382
22049
  );
21383
- return row ? storedRow(id, row._data) : null;
22050
+ return row ? withoutHeldCleared(this.sql, this.docId, model, storedRow(id, row._data)) : null;
21384
22051
  }
21385
22052
  /** Several records' view rows, in the order asked for; a missing one is `null`. */
21386
22053
  readMany(model, ids) {
@@ -21395,7 +22062,7 @@ var RecordLogStore = class {
21395
22062
  model,
21396
22063
  ...slice
21397
22064
  )) {
21398
- found.set(String(row._id), storedRow(row._id, row._data));
22065
+ found.set(String(row._id), withoutHeldCleared(this.sql, this.docId, model, storedRow(row._id, row._data)));
21399
22066
  }
21400
22067
  }
21401
22068
  return ids.map((id) => found.get(id) ?? null);
@@ -21406,7 +22073,7 @@ var RecordLogStore = class {
21406
22073
  this.sql,
21407
22074
  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 ?`,
21408
22075
  ...after === null ? [this.docId, model, limit] : [this.docId, model, after, limit]
21409
- ).map((row) => storedRow(row._id, row._data));
22076
+ ).map((row) => withoutHeldCleared(this.sql, this.docId, model, storedRow(row._id, row._data)));
21410
22077
  }
21411
22078
  /** One page of a model's record ids in id order, after `after`. */
21412
22079
  recordIdsAfter(model, after, limit) {
@@ -21789,9 +22456,9 @@ var RecordLogStore = class {
21789
22456
  if (!row) continue;
21790
22457
  const key = parseKey(text);
21791
22458
  if (key.model !== model || excluding.includes(key.id)) continue;
21792
- const held = fields.map((f) => row[f]);
21793
- if (held.some((v) => v === void 0 || v === null)) continue;
21794
- if (JSON.stringify(held) === wanted2) found.push(text);
22459
+ const held2 = fields.map((f) => row[f]);
22460
+ if (held2.some((v) => v === void 0 || v === null)) continue;
22461
+ if (JSON.stringify(held2) === wanted2) found.push(text);
21795
22462
  }
21796
22463
  const skip = [...excluding, ...[...working.keys()].map(parseKey).filter((k) => k.model === model).map((k) => k.id)];
21797
22464
  for (const id of findHolders(this.sql, "record_log_view", docId, model, fields, values, skip)) {
@@ -21851,9 +22518,9 @@ var RecordLogStore = class {
21851
22518
  const before = view ? storedRow(key.id, view.data) : null;
21852
22519
  const confirmed = overlay ? overlay.data === null ? null : storedRow(key.id, overlay.data) : before;
21853
22520
  const shows = JSON.stringify(row);
21854
- const held = ctx.staged && overlay !== null && overlay.gen === ctx.replacement;
21855
- const settles = !held && JSON.stringify(confirmed) === shows;
21856
- if (!held && !settles && overlay === null) {
22521
+ const held2 = ctx.staged && overlay !== null && overlay.gen === ctx.replacement;
22522
+ const settles = !held2 && JSON.stringify(confirmed) === shows;
22523
+ if (!held2 && !settles && overlay === null) {
21857
22524
  if (view) {
21858
22525
  this.sql.exec(
21859
22526
  `INSERT INTO record_log_rows (doc_id, _type, _id, _data, _gen, _ord)
@@ -22140,10 +22807,12 @@ var RecordLogStore = class {
22140
22807
  const acknowledged = [];
22141
22808
  const settled = [];
22142
22809
  const settlements = [];
22810
+ const cleared = /* @__PURE__ */ new Set();
22143
22811
  let underivable;
22144
22812
  for (const item of command.items) {
22145
22813
  const out = client.receive(item);
22146
22814
  touched.push(...out.touched);
22815
+ for (const model of out.cleared ?? []) cleared.add(model);
22147
22816
  acknowledged.push(...out.acknowledged);
22148
22817
  settled.push(...out.settled);
22149
22818
  settlements.push(...out.settlements ?? []);
@@ -22156,11 +22825,31 @@ var RecordLogStore = class {
22156
22825
  settled,
22157
22826
  ...settlements.length ? { settlements } : {},
22158
22827
  changed,
22828
+ ...cleared.size ? { models: [...cleared] } : {},
22159
22829
  cursor: this.tables.cursor(),
22160
22830
  ...underivable ? { underivable } : {}
22161
22831
  };
22162
22832
  });
22163
22833
  }
22834
+ /**
22835
+ * Apply the model clears a catch-up carries, in one transaction, before
22836
+ * the rows, chunks or page they ride with: every confirmed row of each
22837
+ * model goes, its member, text and vector index entries with it, a record
22838
+ * an unjudged entry touches is guessed again, and the highest clear
22839
+ * applied is recorded with the removal. The cursor does not move. A clear
22840
+ * at or below the cursor or the mark changes nothing, so one sent again
22841
+ * (a resumed download) leaves the rows read since it alone. The reply
22842
+ * names the models emptied in `models`, and in `changed` only the records
22843
+ * an unjudged entry touches.
22844
+ */
22845
+ applyClears(command) {
22846
+ return this.sql.transaction(() => {
22847
+ this.beginWrites();
22848
+ const out = this.client(command.writer).applyClears(command.clears);
22849
+ const changed = this.settleView(out.touched);
22850
+ return { changed, ...out.cleared?.length ? { models: out.cleared } : {}, cursor: this.tables.cursor() };
22851
+ });
22852
+ }
22164
22853
  /** Act on a refusal: hand back what it reaches and answer the frames that move the room past it. */
22165
22854
  refused(command) {
22166
22855
  return this.sql.transaction(() => {
@@ -22237,7 +22926,9 @@ var RecordLogStore = class {
22237
22926
  rows: command.rows,
22238
22927
  gone: command.gone,
22239
22928
  ...command.generation !== void 0 ? { generation: command.generation } : {},
22240
- ...command.receipt !== void 0 ? { receipt: command.receipt } : {}
22929
+ ...command.receipt !== void 0 ? { receipt: command.receipt } : {},
22930
+ // Rows of a model another session's catch-up cleared past `lsn` stay gone (#5994).
22931
+ ...command.lsn !== void 0 ? { readAt: command.lsn } : {}
22241
22932
  });
22242
22933
  client.noteHead(command);
22243
22934
  if (staged) this.beginWrites();
@@ -22275,7 +22966,7 @@ var RecordLogStore = class {
22275
22966
  });
22276
22967
  this.tables.setLastCatchUpAt(command.at ?? Date.now());
22277
22968
  client.noteHead(command);
22278
- const settled = staged ? this.settleReplacement(out.touched, models) : { changed: this.settleView(out.touched), models: [] };
22969
+ const settled = staged ? this.settleReplacement(out.touched, [.../* @__PURE__ */ new Set([...models, ...out.cleared ?? []])]) : { changed: this.settleView(out.touched), models: out.cleared ?? [] };
22279
22970
  return {
22280
22971
  acknowledged: out.acknowledged,
22281
22972
  settled: out.settled,
@@ -22350,7 +23041,8 @@ var RecordLogStore = class {
22350
23041
  attempt: command.attempt,
22351
23042
  model: command.model,
22352
23043
  lines: command.lines,
22353
- ...command.mode !== void 0 ? { mode: command.mode } : {}
23044
+ ...command.mode !== void 0 ? { mode: command.mode } : {},
23045
+ ...command.readAt !== void 0 ? { readAt: command.readAt } : {}
22354
23046
  });
22355
23047
  const touched = new Set(out.touched.map(keyText2));
22356
23048
  const removed = command.lines.filter(
@@ -22412,7 +23104,8 @@ var RecordLogStore = class {
22412
23104
  const out = this.client(command.writer).applySegmentRows({
22413
23105
  generation: command.generation,
22414
23106
  rows: command.rows,
22415
- ...command.attempt !== void 0 ? { attempt: command.attempt } : {}
23107
+ ...command.attempt !== void 0 ? { attempt: command.attempt } : {},
23108
+ ...command.readAt !== void 0 ? { readAt: command.readAt } : {}
22416
23109
  });
22417
23110
  if (staged) {
22418
23111
  this.beginWrites();
@@ -22463,7 +23156,8 @@ var RecordLogStore = class {
22463
23156
  const out = this.client(command.writer).applySegmentCorrections({
22464
23157
  generation: command.generation,
22465
23158
  lines: command.lines,
22466
- ...command.attempt !== void 0 ? { attempt: command.attempt } : {}
23159
+ ...command.attempt !== void 0 ? { attempt: command.attempt } : {},
23160
+ ...command.readAt !== void 0 ? { readAt: command.readAt } : {}
22467
23161
  });
22468
23162
  const touched = new Set(out.touched.map(keyText2));
22469
23163
  const removed = command.lines.filter((l) => l.row === null && touched.has(keyText2(l))).length;
@@ -22488,12 +23182,12 @@ var RecordLogStore = class {
22488
23182
  this.tables.takeViewChanged();
22489
23183
  for (const [model, ids] of idsByModel(keys)) {
22490
23184
  const guessed = /* @__PURE__ */ new Set();
22491
- for (const { list, bindings } of idLists(ids)) {
23185
+ for (const { list, bindings: bindings2 } of idLists(ids)) {
22492
23186
  for (const row of this.sql.exec(
22493
23187
  `SELECT DISTINCT _id FROM record_log_pending_keys WHERE doc_id = ? AND _type = ? AND _id IN ${list}`,
22494
23188
  docId,
22495
23189
  model,
22496
- ...bindings
23190
+ ...bindings2
22497
23191
  )) {
22498
23192
  guessed.add(String(row._id));
22499
23193
  }
@@ -24503,8 +25197,8 @@ var OpfsEngine = class {
24503
25197
  const routing = this.docs.get(docId);
24504
25198
  if (routing && routing.entry === entry) routing.sessions++;
24505
25199
  else this.docs.set(docId, { entry, sessions: 1 });
24506
- const held = this.holdPresence(db3ClientLockName(namespace, docId, options.clientId));
24507
- if (held) this.presence.add(held);
25200
+ const held2 = this.holdPresence(db3ClientLockName(namespace, docId, options.clientId));
25201
+ if (held2) this.presence.add(held2);
24508
25202
  const engine = this;
24509
25203
  let closing = null;
24510
25204
  const closeOnce = async () => {
@@ -24513,7 +25207,7 @@ var OpfsEngine = class {
24513
25207
  entry.docIds.delete(docId);
24514
25208
  engine.docs.delete(docId);
24515
25209
  }
24516
- if (held && engine.presence.delete(held)) held();
25210
+ if (held2 && engine.presence.delete(held2)) held2();
24517
25211
  releaseDocument();
24518
25212
  await host.close();
24519
25213
  };
@@ -25244,9 +25938,9 @@ var OpfsEngine = class {
25244
25938
  `[format2] The worker serving '${docId}' is gone; its '${modelName}' rows cannot be read until the document is reconnected.`
25245
25939
  );
25246
25940
  }
25247
- const held = candidates.get(entry.engine) ?? [];
25248
- held.push(docId);
25249
- candidates.set(entry.engine, held);
25941
+ const held2 = candidates.get(entry.engine) ?? [];
25942
+ held2.push(docId);
25943
+ candidates.set(entry.engine, held2);
25250
25944
  }
25251
25945
  return routeQueryEngine({ mirror: this.mirror, candidates, ordinary, modelName });
25252
25946
  }
@@ -26360,7 +27054,8 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
26360
27054
  return this.run("receive", async () => {
26361
27055
  const cursor = this.mirror.cursor;
26362
27056
  const reply = await this.host.dispatch({ kind: "receive", writer, items, ...heard });
26363
- this.afterChange(reply, "remote");
27057
+ if (reply.models?.length) await this.afterBulk(reply, "remote");
27058
+ else this.afterChange(reply, "remote");
26364
27059
  this.noteSettled(reply);
26365
27060
  if (!reply.changed.length && (heard.head !== void 0 || reply.cursor !== cursor)) this.pendingChanged();
26366
27061
  return reply;
@@ -26418,6 +27113,20 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
26418
27113
  return reply;
26419
27114
  });
26420
27115
  }
27116
+ /**
27117
+ * Apply the model clears a catch-up carries, before its rows, chunks or
27118
+ * page (#5994), as one scheduled operation: each model's rows go at once,
27119
+ * and the listeners hear each model emptied once. One at or below the
27120
+ * store's cursor or its highest clear applied changes nothing.
27121
+ */
27122
+ applyClears(clears, writer = this.writer()) {
27123
+ return this.run("applyClears", async () => {
27124
+ const reply = await this.host.dispatch({ kind: "applyClears", writer, clears });
27125
+ if (reply.models?.length) await this.afterBulk(reply, "remote");
27126
+ else this.afterChange(reply, "remote");
27127
+ return reply;
27128
+ });
27129
+ }
26421
27130
  /**
26422
27131
  * Complete a catch-up at the room's log number; answered `stale` when the store is past it.
26423
27132
  * @param _project - Ignored: a db3's rows live only in the view.
@@ -26561,6 +27270,14 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
26561
27270
  declaredEnums() {
26562
27271
  return this.mirror.typed === "yes" ? this.mirror.enums ?? null : null;
26563
27272
  }
27273
+ /**
27274
+ * The cleared and tombstoned fields of the db3's type the room sent beside
27275
+ * its declarations, per model the sorted names; `null` while the db3 is not
27276
+ * known to be typed, its type clears none, or none were received yet.
27277
+ */
27278
+ declaredCleared() {
27279
+ return this.mirror.typed === "yes" ? this.mirror.cleared ?? null : null;
27280
+ }
26564
27281
  /**
26565
27282
  * Whether the local pre-check should hold a save to a unique constraint:
26566
27283
  * every constraint is checked unless the room has said it keeps it out of
@@ -27210,9 +27927,10 @@ function typeOfOpened(frame, docId) {
27210
27927
  const models = isObject2(type) ? type.models : void 0;
27211
27928
  const vectors = isObject2(type) ? type.vectors : void 0;
27212
27929
  const enums = isObject2(type) ? type.enums : void 0;
27930
+ const cleared = isObject2(type) ? type.cleared : void 0;
27213
27931
  const isValues = (value) => Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string");
27214
27932
  const isEncoding = (value) => isObject2(value) && typeof value.dims === "number" && Number.isInteger(value.dims) && value.dims >= 1 && isVectorElement(value.element);
27215
- const wellFormed = isObject2(type) && typeof type.name === "string" && type.name !== "" && typeof type.hash === "string" && type.hash !== "" && (models === void 0 || isObject2(models) && Object.values(models).every((fields) => isObject2(fields) && Object.values(fields).every((kind) => typeof kind === "string"))) && (vectors === void 0 || models !== void 0 && isObject2(vectors) && Object.values(vectors).every((fields) => isObject2(fields) && Object.values(fields).every(isEncoding))) && (enums === void 0 || models !== void 0 && isObject2(enums) && Object.values(enums).every((fields) => isObject2(fields) && Object.values(fields).every(isValues)));
27933
+ const wellFormed = isObject2(type) && typeof type.name === "string" && type.name !== "" && typeof type.hash === "string" && type.hash !== "" && (models === void 0 || isObject2(models) && Object.values(models).every((fields) => isObject2(fields) && Object.values(fields).every((kind) => typeof kind === "string"))) && (vectors === void 0 || models !== void 0 && isObject2(vectors) && Object.values(vectors).every((fields) => isObject2(fields) && Object.values(fields).every(isEncoding))) && (enums === void 0 || models !== void 0 && isObject2(enums) && Object.values(enums).every((fields) => isObject2(fields) && Object.values(fields).every(isValues))) && (cleared === void 0 || models !== void 0 && isObject2(cleared) && Object.values(cleared).every(isValues));
27216
27934
  if (!wellFormed) {
27217
27935
  Logger.warn(`[record-log] ${docId}: record.opened carried a db3Type this client cannot read; the type it holds is kept`);
27218
27936
  return {};
@@ -27225,7 +27943,8 @@ function typeOfOpened(frame, docId) {
27225
27943
  hash: type.hash,
27226
27944
  ...models !== void 0 ? { models } : {},
27227
27945
  ...vectors !== void 0 ? { vectors } : {},
27228
- ...enums !== void 0 ? { enums } : {}
27946
+ ...enums !== void 0 ? { enums } : {},
27947
+ ...cleared !== void 0 ? { cleared } : {}
27229
27948
  }
27230
27949
  }
27231
27950
  };
@@ -27277,6 +27996,12 @@ function isChunkIntegrityError(error) {
27277
27996
  return name === "IngestChunkError" || name === "SnapshotChunkIntegrityError";
27278
27997
  }
27279
27998
  var errorText = (error) => error instanceof Error ? error.message : String(error);
27999
+ function clearsOf(value) {
28000
+ if (!Array.isArray(value)) return [];
28001
+ return value.filter(
28002
+ (c) => typeof c === "object" && c !== null && typeof c.model === "string" && Number.isInteger(c.l) && Number.isInteger(c.e)
28003
+ ).map((c) => ({ model: c.model, l: c.l, e: c.e }));
28004
+ }
27280
28005
  function answeredSeqs(items, writer) {
27281
28006
  const seqs = [];
27282
28007
  for (const item of items) {
@@ -27631,9 +28356,10 @@ var RecordLogDocumentSession = class {
27631
28356
  ...unfinished ? { unfinished } : {},
27632
28357
  // The type revision whose declarations this device holds: the room
27633
28358
  // sends them again only for another one (#5020). Declarations held
27634
- // without their vector fields (written before #5225) or their enforced
27635
- // enums (before #5897) are asked for again.
27636
- ...typed === "yes" && marks.db3Type?.hash && marks.vectorsKnown !== false && marks.enumsKnown !== false ? { db3TypeHash: marks.db3Type.hash } : {}
28359
+ // without their vector fields (written before #5225), their enforced
28360
+ // enums (before #5897) or their cleared fields (before #6021) are asked
28361
+ // for again.
28362
+ ...typed === "yes" && marks.db3Type?.hash && marks.vectorsKnown !== false && marks.enumsKnown !== false && marks.clearedKnown !== false ? { db3TypeHash: marks.db3Type.hash } : {}
27637
28363
  });
27638
28364
  if (!sendAhead) return;
27639
28365
  const ahead = { declarations: null, refused: false, seqs: [] };
@@ -27659,9 +28385,9 @@ var RecordLogDocumentSession = class {
27659
28385
  * made since do not name its models). The models it names are this open's.
27660
28386
  */
27661
28387
  declarationsFor(pending) {
27662
- const held = new Set(this.store.marks().models ?? []);
27663
- for (const entry of pending) for (const model of modelsOf2(entry)) held.add(model);
27664
- const models = this.host.declarations(this.docId, [...held].sort());
28388
+ const held2 = new Set(this.store.marks().models ?? []);
28389
+ for (const entry of pending) for (const model of modelsOf2(entry)) held2.add(model);
28390
+ const models = this.host.declarations(this.docId, [...held2].sort());
27665
28391
  this.declaredThisOpen = new Set(Object.keys(models));
27666
28392
  return models;
27667
28393
  }
@@ -27954,6 +28680,11 @@ var RecordLogDocumentSession = class {
27954
28680
  const catchUp = frame.catchUp ?? { mode: "inline", rows: [], gone: [], lsn: frame.lsn };
27955
28681
  if (catchUp.mode === "building") return this.waitForSegment(catchUp);
27956
28682
  this.buildingSince = null;
28683
+ const clears = clearsOf(catchUp.clears);
28684
+ if (clears.length) {
28685
+ await this.store.applyClears(clears, this.current.writer);
28686
+ if (generation !== this.generation || !this.current) return;
28687
+ }
27957
28688
  this.phase = "catchingUp";
27958
28689
  if (catchUp.mode === "load") {
27959
28690
  return this.startLoadReceipt(catchUp.load, {
@@ -28152,6 +28883,11 @@ var RecordLogDocumentSession = class {
28152
28883
  const gone = frame.gone ?? [];
28153
28884
  const mine = receipt?.attempt !== void 0 ? { receipt: receipt.attempt } : {};
28154
28885
  const heard = heardOf(frame, receivedAt);
28886
+ const clears = clearsOf(frame.clears);
28887
+ if (clears.length) {
28888
+ await this.store.applyClears(clears, this.current.writer);
28889
+ if (generation !== this.generation || !this.paging || !this.current) return;
28890
+ }
28155
28891
  const page = await this.store.applyCatchUpPage({ rows, gone, lsn, ...fence, ...mine, ...heard }, [], this.current.writer);
28156
28892
  if (generation !== this.generation || !this.paging || !this.current) return;
28157
28893
  if (page.stale) {
@@ -28325,6 +29061,9 @@ var RecordLogDocumentSession = class {
28325
29061
  attempt,
28326
29062
  model: chunk.model,
28327
29063
  mode: pointer.mode,
29064
+ // The rows are the load's as of its last number: a model
29065
+ // another session cleared past it keeps none of them (#5994).
29066
+ readAt: pointer.lastLsn ?? void 0,
28328
29067
  bytes,
28329
29068
  descriptor: {
28330
29069
  model: chunk.model,
@@ -28410,12 +29149,12 @@ var RecordLogDocumentSession = class {
28410
29149
  );
28411
29150
  const { attempt } = start;
28412
29151
  receipt.attempt = attempt;
28413
- const { generation, held } = start.generation !== void 0 ? { generation: start.generation, held: start.held ?? null } : await this.store.beginSegmentReplacement(attempt, receipt.writer);
29152
+ const { generation, held: held2 } = start.generation !== void 0 ? { generation: start.generation, held: start.held ?? null } : await this.store.beginSegmentReplacement(attempt, receipt.writer);
28414
29153
  if (generation === null) throw new ReceiptFailure("the store handed out no replacement generation");
28415
29154
  const overtaken = () => this.serially(
28416
29155
  () => this.receiptStale(receipt, () => this.abandonReceipt(receipt, "another client of the store began replacing it", generation), generation)
28417
29156
  );
28418
- const holds = new Map((held?.chunks ?? []).map((c) => [c.object, c]));
29157
+ const holds = new Map((held2?.chunks ?? []).map((c) => [c.object, c]));
28419
29158
  receipt.kept = 0;
28420
29159
  receipt.fetched = 0;
28421
29160
  this.resuming(receipt, start, segment.chunks.length);
@@ -28440,7 +29179,7 @@ var RecordLogDocumentSession = class {
28440
29179
  const { index: _index, ...range } = mine;
28441
29180
  void _index;
28442
29181
  const kept = await this.store.keepSegmentChunk(
28443
- { generation, attempt, segmentId: segment.segmentId, ...range },
29182
+ { generation, attempt, segmentId: segment.segmentId, ...range, readAt: segment.completedLsn },
28444
29183
  receipt.writer
28445
29184
  );
28446
29185
  if (!this.receiving(receipt)) return;
@@ -28458,7 +29197,7 @@ var RecordLogDocumentSession = class {
28458
29197
  receipt,
28459
29198
  `${base}/${chunk.path}`,
28460
29199
  (bytes) => this.store.applySegmentChunk(
28461
- { generation, attempt, segmentId: segment.segmentId, bytes, descriptor: chunk },
29200
+ { generation, attempt, segmentId: segment.segmentId, readAt: segment.completedLsn, bytes, descriptor: chunk },
28462
29201
  [],
28463
29202
  receipt.writer
28464
29203
  )
@@ -28474,7 +29213,11 @@ var RecordLogDocumentSession = class {
28474
29213
  const corrections = await this.applyChunk(
28475
29214
  receipt,
28476
29215
  `${base}/${segment.corrections.path}`,
28477
- (bytes) => this.store.applySegmentCorrections({ generation, attempt, bytes, descriptor: segment.corrections }, [], receipt.writer)
29216
+ (bytes) => this.store.applySegmentCorrections(
29217
+ { generation, attempt, readAt: segment.completedLsn, bytes, descriptor: segment.corrections },
29218
+ [],
29219
+ receipt.writer
29220
+ )
28478
29221
  );
28479
29222
  if (!corrections || !this.receiving(receipt)) return;
28480
29223
  if (corrections.stale) return overtaken();
@@ -28702,10 +29445,10 @@ var RecordLogDocumentSession = class {
28702
29445
  this.catchUpRetryMs = CATCH_UP_RETRY_MS;
28703
29446
  this.clearGap();
28704
29447
  this.settleAcknowledged(acknowledged);
28705
- const held = this.held;
29448
+ const held2 = this.held;
28706
29449
  this.held = [];
28707
29450
  this.phase = current.orphan ? "draining" : "open";
28708
- for (const answer of held) {
29451
+ for (const answer of held2) {
28709
29452
  if (answer.kind === "results") underivable = await this.applyResults(answer.items, answer.heard) ?? underivable;
28710
29453
  else await this.applyRefusal(answer.refusal);
28711
29454
  }
@@ -29049,9 +29792,9 @@ var RecordLogDocumentSession = class {
29049
29792
  `[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.`
29050
29793
  );
29051
29794
  if (typeof frame.db3Type === "string" && frame.db3Type) {
29052
- const held = this.store.marks().db3Type;
29795
+ const held2 = this.store.marks().db3Type;
29053
29796
  await this.store.setState({
29054
- type: { typed: "yes", db3Type: { name: frame.db3Type, hash: held?.name === frame.db3Type ? held.hash : null } }
29797
+ type: { typed: "yes", db3Type: { name: frame.db3Type, hash: held2?.name === frame.db3Type ? held2.hash : null } }
29055
29798
  });
29056
29799
  }
29057
29800
  this.host.declared?.(this.docId);
@@ -29275,7 +30018,7 @@ var RecordLogSessions = class {
29275
30018
  connection: () => this.connection,
29276
30019
  awaitTypeBeforeDeclaring: this.host.awaitTypeBeforeDeclaring === true,
29277
30020
  scopesDeclarations: this.host.scopesDeclarations === true,
29278
- declarations: (id, held) => this.host.declarations(id, held),
30021
+ declarations: (id, held2) => this.host.declarations(id, held2),
29279
30022
  notify: (records) => this.host.notify(records),
29280
30023
  reportRefused: (event) => this.host.reportRefused(event),
29281
30024
  synced: (id) => {
@@ -29381,10 +30124,10 @@ function namedIndexName(model, name) {
29381
30124
  return `idx_named_${model.toLowerCase()}_${name.toLowerCase()}`;
29382
30125
  }
29383
30126
  function memberIndexName(model, field, taken) {
29384
- const held = new Set([...taken].map((name) => name.toLowerCase()));
30127
+ const held2 = new Set([...taken].map((name) => name.toLowerCase()));
29385
30128
  const base = `idx_members_${model}_${field}`.toLowerCase();
29386
- if (!held.has(base)) return base;
29387
- for (let n = 2; ; n++) if (!held.has(`${base}_${n}`)) return `${base}_${n}`;
30129
+ if (!held2.has(base)) return base;
30130
+ for (let n = 2; ; n++) if (!held2.has(`${base}_${n}`)) return `${base}_${n}`;
29388
30131
  }
29389
30132
  function constraintIndexName(model, constraint) {
29390
30133
  const name = constraint.replace(/[^A-Za-z0-9_]/g, "_");
@@ -29474,7 +30217,7 @@ function localIndexList(declarations, registrations) {
29474
30217
  continue;
29475
30218
  }
29476
30219
  const key = fieldsKey([registration.model, ...registration.fields]);
29477
- const held = byDefinition.get(key);
30220
+ const held2 = byDefinition.get(key);
29478
30221
  const origin = { kind: "named", unique: registration.unique };
29479
30222
  if (registration.members) {
29480
30223
  byDefinition.set(key, {
@@ -29489,9 +30232,9 @@ function localIndexList(declarations, registrations) {
29489
30232
  });
29490
30233
  continue;
29491
30234
  }
29492
- if (held) {
29493
- held.origins = [...held.origins.filter((o) => o.kind !== "named"), origin];
29494
- held.unique = held.origins.some((o) => o.unique);
30235
+ if (held2) {
30236
+ held2.origins = [...held2.origins.filter((o) => o.kind !== "named"), origin];
30237
+ held2.unique = held2.origins.some((o) => o.unique);
29495
30238
  continue;
29496
30239
  }
29497
30240
  byDefinition.set(key, {
@@ -29722,15 +30465,15 @@ function registerLocalIndex(declarations, registrations, body, duplicates, suppo
29722
30465
  function registerTextIndex(declarations, registrations, request) {
29723
30466
  const { model, fields } = request;
29724
30467
  const list = localIndexList(declarations, registrations);
29725
- const held = list.find((index2) => index2.kind === "text" && index2.model === model);
29726
- if (held && fieldsKey(held.fields) !== fieldsKey(fields)) {
30468
+ const held2 = list.find((index2) => index2.kind === "text" && index2.model === model);
30469
+ if (held2 && fieldsKey(held2.fields) !== fieldsKey(fields)) {
29727
30470
  throw new RecordLogLocalIndexError(
29728
30471
  "DB3_INDEX_EXISTS",
29729
- `${model} already has a text index, ${held.name}, on ${held.fields.join(", ")}: a model has one text index, so drop it before registering another`,
29730
- { index: held.name }
30472
+ `${model} already has a text index, ${held2.name}, on ${held2.fields.join(", ")}: a model has one text index, so drop it before registering another`,
30473
+ { index: held2.name }
29731
30474
  );
29732
30475
  }
29733
- if (held) return { registrations: [...registrations], index: held };
30476
+ if (held2) return { registrations: [...registrations], index: held2 };
29734
30477
  const taken = new Set([...list.map((index2) => index2.name), ...registrations.map((r) => r.name)].map((name2) => name2.toLowerCase()));
29735
30478
  const base = textIndexName(model);
29736
30479
  let name = base;
@@ -29744,8 +30487,8 @@ function registerVectorIndex(declarations, registrations, request) {
29744
30487
  const { model } = request;
29745
30488
  const field = request.fields[0];
29746
30489
  const list = localIndexList(declarations, registrations);
29747
- const held = list.find((index2) => index2.kind === "vector" && index2.model === model && index2.fields[0] === field);
29748
- if (held) return { registrations: [...registrations], index: held };
30490
+ const held2 = list.find((index2) => index2.kind === "vector" && index2.model === model && index2.fields[0] === field);
30491
+ if (held2) return { registrations: [...registrations], index: held2 };
29749
30492
  const declared = entriesOf(declarations.find((d) => d.model === model)?.fields ?? {}).find(([name2]) => name2 === field)?.[1];
29750
30493
  const vector = vectorOptionsOf({ ...request.vector ?? {}, dims: declared?.dims, element: declared?.element });
29751
30494
  if (declared?.type !== "vector" || !vector) {
@@ -29839,7 +30582,7 @@ var RecordLogDocumentBinding = class {
29839
30582
  awaitTypeBeforeDeclaring: true,
29840
30583
  // Each db3 is declared the models it uses (#5115).
29841
30584
  scopesDeclarations: true,
29842
- declarations: (docId, held) => this.declarations(docId, held),
30585
+ declarations: (docId, held2) => this.declarations(docId, held2),
29843
30586
  notify: (records) => this.notify(records),
29844
30587
  reportRefused: (event) => this.ormContext.reportRecordLogWriteRefused(event)
29845
30588
  });
@@ -30154,9 +30897,9 @@ var RecordLogDocumentBinding = class {
30154
30897
  * there. Each is its fields with their JSON options and its compound
30155
30898
  * unique constraints. With no `docId`, every active model's.
30156
30899
  */
30157
- declarations(docId, held = []) {
30900
+ declarations(docId, held2 = []) {
30158
30901
  const out = {};
30159
- const wanted2 = new Set(held);
30902
+ const wanted2 = new Set(held2);
30160
30903
  const globalDefault = docId !== void 0 && this.ormContext.getGlobalDefaultDocumentId() === docId;
30161
30904
  for (const [, modelClass] of this.modelRegistry.getActiveModels()) {
30162
30905
  const schema = modelClass.getSchema?.();
@@ -31298,7 +32041,8 @@ function buildDefinedModelSchema(input) {
31298
32041
  name,
31299
32042
  className: input.options?.className,
31300
32043
  uniqueConstraints: input.options?.uniqueConstraints ? [...input.options.uniqueConstraints] : void 0,
31301
- relationships: input.options?.relationships
32044
+ relationships: input.options?.relationships,
32045
+ ...input.options?.removedFields ? { removedFields: [...input.options.removedFields] } : {}
31302
32046
  };
31303
32047
  const schema = {
31304
32048
  name,
@@ -31584,7 +32328,7 @@ var FIELD_CONTEXTS = {
31584
32328
  model: {
31585
32329
  values: "as-written",
31586
32330
  types: FIELD_TYPES,
31587
- keys: ["type", "indexed", "unique", "required", "auto_assign", "auto_stamp", "max_length", "max_count", "default", "enum", "enforce_enum", "dims", "element"]
32331
+ keys: ["type", "indexed", "unique", "required", "auto_assign", "auto_stamp", "max_length", "max_count", "default", "enum", "enforce_enum", "dims", "element", "deprecated", "cleared", "storedAs"]
31588
32332
  },
31589
32333
  property: {
31590
32334
  values: "checked",
@@ -31718,6 +32462,19 @@ var FIELD_KEYS = [
31718
32462
  contexts: { model: "allowed", property: { refused: "a property is never a vector (element)" }, io: { refused: notStored("element") } },
31719
32463
  types: ["vector"]
31720
32464
  },
32465
+ { key: "deprecated", prop: "deprecated", kind: "flag", storage: false, contexts: { model: "allowed", property: "unknown", io: "unknown" }, flagTier: "always" },
32466
+ {
32467
+ key: "cleared",
32468
+ prop: "cleared",
32469
+ kind: "flag",
32470
+ storage: false,
32471
+ contexts: { model: "allowed", property: "unknown", io: "unknown" },
32472
+ flagTier: "always",
32473
+ needs: "deprecated",
32474
+ refusedWith: "required"
32475
+ },
32476
+ // The name records hold for a renamed db3 field; the loader judges the name itself.
32477
+ { key: "storedAs", prop: "storedAs", kind: "string", storage: false, contexts: { model: "allowed", property: "unknown", io: "unknown" } },
31721
32478
  {
31722
32479
  key: "client",
31723
32480
  prop: "client",
@@ -31807,6 +32564,12 @@ function judge(row, value, decl, spec, table) {
31807
32564
  if (row.needs === "enum" && value === true && !(own(table, "enum") && table.enum !== void 0)) {
31808
32565
  return { problem: { code: "enforce-without-enum", key: "enforce_enum" } };
31809
32566
  }
32567
+ if (row.needs === "deprecated" && value === true && table.deprecated !== true) {
32568
+ return { problem: { code: "cleared-without-deprecated", key: "cleared" } };
32569
+ }
32570
+ if (row.refusedWith === "required" && value === true && table.required === true) {
32571
+ return { problem: { code: "cleared-with-required", key: "cleared" } };
32572
+ }
31810
32573
  if (row.flagTier === "always" || !checked) return { value: value === true ? true : void 0 };
31811
32574
  return typeof value === "boolean" ? { value } : { problem: { code: "bad-boolean", key: row.key } };
31812
32575
  case "literal": {
@@ -31902,6 +32665,10 @@ function fieldProblemMessage(problem) {
31902
32665
  return "enum repeats a value";
31903
32666
  case "enforce-without-enum":
31904
32667
  return "enforce_enum needs an enum to enforce";
32668
+ case "cleared-without-deprecated":
32669
+ return "cleared needs deprecated = true beside it: deprecate a field before clearing it";
32670
+ case "cleared-with-required":
32671
+ return "cleared cannot be set on a required field: make the field optional, ship builds generated from that, then clear it";
31905
32672
  }
31906
32673
  }
31907
32674
 
@@ -31909,13 +32676,39 @@ function fieldProblemMessage(problem) {
31909
32676
  var import_smol_toml = require("smol-toml");
31910
32677
  var isTable2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
31911
32678
  var fail = (message) => ({ ok: false, message });
32679
+ var BESIDE_OBJECT_REF = {
32680
+ type: "the field is stored as JSON text in a string field",
32681
+ enum: "the def declares the value's shape",
32682
+ indexed: "an index on JSON text neither orders nor matches the values inside it",
32683
+ unique: "uniqueness of JSON text is not uniqueness of the values inside it",
32684
+ default: "a JSON field has no default",
32685
+ max_length: "bound the value in the def (maxLength, maxItems) instead",
32686
+ max_count: "it bounds a stringset field",
32687
+ auto_assign: "the client writes a JSON field's value",
32688
+ auto_stamp: "the client writes a JSON field's value",
32689
+ dims: "it shapes a vector field",
32690
+ element: "it shapes a vector field"
32691
+ };
32692
+ function besideObjectRef(raw) {
32693
+ const key = Object.keys(raw).find((k) => k !== "ref" && k !== "required");
32694
+ if (key === void 0) return null;
32695
+ const why = Object.prototype.hasOwnProperty.call(BESIDE_OBJECT_REF, key) ? BESIDE_OBJECT_REF[key] : "only required may";
32696
+ return `${key} cannot sit beside a ref to an object def: ${why}, so remove it.`;
32697
+ }
31912
32698
  function expandSharedEnumField(raw, resolve) {
31913
32699
  const has2 = (key) => isTable2(raw) && Object.prototype.hasOwnProperty.call(raw, key);
31914
32700
  if (!has2("ref")) return { ok: true, field: raw };
31915
32701
  const beside = ["type", "enum"].filter(has2);
31916
32702
  const [it, them] = beside.length > 1 ? ["both", "them"] : ["it", "it"];
31917
- if (beside.length > 0) return fail(`${beside.join(" and ")} cannot sit beside ref; the shared enum supplies ${it}, so remove ${them}.`);
32703
+ const enumBeside = () => fail(`${beside.join(" and ")} cannot sit beside ref; the shared enum supplies ${it}, so remove ${them}.`);
31918
32704
  const found = resolve(raw.ref);
32705
+ if (found.ok && "object" in found) {
32706
+ const refused = besideObjectRef(raw);
32707
+ if (refused) return fail(refused);
32708
+ const entries2 = Object.entries(raw).map(([k, v]) => k === "ref" ? ["type", "string"] : [k, v]);
32709
+ return { ok: true, field: Object.fromEntries(entries2), json: { ...found.object } };
32710
+ }
32711
+ if (beside.length > 0) return enumBeside();
31919
32712
  if (!found.ok) return found;
31920
32713
  const entries = Object.entries(raw).flatMap(([k, v]) => k === "ref" ? [["type", "string"], ["enum", found.values]] : [[k, v]]);
31921
32714
  return { ok: true, field: Object.fromEntries(entries), sharedEnum: { file: found.file, name: found.name, values: [...found.values] } };
@@ -31926,7 +32719,8 @@ var KNOWN_MODEL_KEYS = /* @__PURE__ */ new Set([
31926
32719
  "fields",
31927
32720
  "relationships",
31928
32721
  "unique_constraints",
31929
- "class_name"
32722
+ "class_name",
32723
+ "removedFields"
31930
32724
  ]);
31931
32725
  var KNOWN_RELATIONSHIP_KEYS = /* @__PURE__ */ new Set([
31932
32726
  "type",
@@ -31998,6 +32792,8 @@ function parseFieldOptions(raw, context, strict, vectors, fieldName, sharedEnums
31998
32792
  throw new Error(`${context}: \`enum\` values must all be strings.`);
31999
32793
  }
32000
32794
  enforceEnumProblem(raw, decl, problems, context, fieldName, vectors);
32795
+ lifecycleProblem(raw, decl, problems, context, fieldName);
32796
+ const storedAs = storedAsOf(raw, problems, context, fieldName);
32001
32797
  const opts = { type: decl.type };
32002
32798
  if (decl.type === "vector") {
32003
32799
  opts.dims = decl.dims;
@@ -32013,8 +32809,66 @@ function parseFieldOptions(raw, context, strict, vectors, fieldName, sharedEnums
32013
32809
  if (decl.default !== void 0) opts.default = decl.default;
32014
32810
  if (decl.enum !== void 0) opts.enum = [...decl.enum];
32015
32811
  if (decl.enforceEnum === true) opts.enforceEnum = true;
32812
+ if (decl.deprecated === true) opts.deprecated = true;
32813
+ if (decl.cleared === true) opts.cleared = true;
32814
+ if (storedAs !== void 0 && storedAs !== fieldName) opts.storedAs = storedAs;
32016
32815
  return opts;
32017
32816
  }
32817
+ var STORED_NAME_RE = /^[A-Za-z][A-Za-z0-9_]*$/;
32818
+ function storedAsOf(raw, problems, context, fieldName) {
32819
+ if (!Object.prototype.hasOwnProperty.call(raw, "storedAs")) return void 0;
32820
+ const value = raw.storedAs;
32821
+ if (typeof value !== "string" || value === "" || problems.some((p) => "key" in p && p.key === "storedAs" && p.code === "bad-string")) {
32822
+ throw new Error(`${context}: storedAs must be a non-empty string naming the field's stored name`);
32823
+ }
32824
+ if (fieldName === "id") throw new Error(`${context}: storedAs cannot be set on the id field`);
32825
+ if (value === "id") throw new Error(`${context}: storedAs "id" names the record's id; a field's stored name is never id`);
32826
+ const reserved = checkReservedFieldName(value);
32827
+ if (reserved) throw new Error(`${context}: storedAs ${JSON.stringify(value)} is reserved: ${reserved}`);
32828
+ if (!STORED_NAME_RE.test(value)) {
32829
+ throw new Error(`${context}: storedAs ${JSON.stringify(value)} is not an identifier (a letter, then letters, digits or _)`);
32830
+ }
32831
+ return value;
32832
+ }
32833
+ function storedNamesProblem(modelName, declared) {
32834
+ const storedBy = /* @__PURE__ */ new Map();
32835
+ for (const [field, options] of declared) {
32836
+ if (options.storedAs === void 0) continue;
32837
+ const context = `[models.${modelName}.fields.${field}]`;
32838
+ if (declared.has(options.storedAs)) {
32839
+ return `${context}: storedAs ${JSON.stringify(options.storedAs)} is the key of another declared field; a stored name belongs to one field`;
32840
+ }
32841
+ const other = storedBy.get(options.storedAs);
32842
+ if (other !== void 0) {
32843
+ return `${context}: storedAs ${JSON.stringify(options.storedAs)} is also the stored name of ${other}; a stored name belongs to one field`;
32844
+ }
32845
+ storedBy.set(options.storedAs, field);
32846
+ }
32847
+ return null;
32848
+ }
32849
+ function lifecycleProblem(raw, decl, problems, context, fieldName) {
32850
+ for (const key of ["cleared", "deprecated"]) {
32851
+ if (!Object.prototype.hasOwnProperty.call(raw, key)) continue;
32852
+ const problem = problems.find((p) => "key" in p && p.key === key && p.code !== "unknown-key");
32853
+ if (problem) throw new Error(`${context}: ${fieldProblemMessage(problem)}`);
32854
+ if (decl[key] === true && fieldName === "id") throw new Error(`${context}: ${key} cannot be set on the id field`);
32855
+ }
32856
+ }
32857
+ function parseRemovedFields(raw, modelName, declared) {
32858
+ const context = `[models.${modelName}]`;
32859
+ if (!Array.isArray(raw) || !raw.every((name) => typeof name === "string" && name.length > 0)) {
32860
+ throw new Error(`${context}: removedFields must be an array of field names`);
32861
+ }
32862
+ const seen = /* @__PURE__ */ new Set();
32863
+ for (const name of raw) {
32864
+ if (seen.has(name)) throw new Error(`${context}: removedFields names "${name}" twice`);
32865
+ seen.add(name);
32866
+ if (declared.has(name)) {
32867
+ throw new Error(`${context}: removedFields names "${name}", which the model still declares; a field is either declared or removed`);
32868
+ }
32869
+ }
32870
+ return [...raw];
32871
+ }
32018
32872
  function enforceEnumProblem(raw, decl, problems, context, fieldName, vectors) {
32019
32873
  if (!Object.prototype.hasOwnProperty.call(raw, "enforce_enum")) return;
32020
32874
  for (const problem of problems) {
@@ -32154,6 +33008,9 @@ function loadSchemaFromTomlString(tomlString, options = {}) {
32154
33008
  }
32155
33009
  }
32156
33010
  const className = typeof modelDef.class_name === "string" ? modelDef.class_name : void 0;
33011
+ const removedFields = modelDef.removedFields === void 0 ? void 0 : parseRemovedFields(modelDef.removedFields, modelName, /* @__PURE__ */ new Set([...Object.keys(fields), ...declaredFields.keys()]));
33012
+ const storedNames = storedNamesProblem(modelName, declaredFields);
33013
+ if (storedNames) throw new Error(storedNames);
32157
33014
  const vectorConstraint = vectorConstraintProblem(declaredFields, uniqueConstraints);
32158
33015
  if (vectorConstraint) {
32159
33016
  throw new Error(`[[models.${modelName}.unique_constraints]]: ${vectorConstraint}`);
@@ -32177,7 +33034,8 @@ function loadSchemaFromTomlString(tomlString, options = {}) {
32177
33034
  options: {
32178
33035
  className,
32179
33036
  uniqueConstraints,
32180
- relationships
33037
+ relationships,
33038
+ ...removedFields ? { removedFields } : {}
32181
33039
  }
32182
33040
  })
32183
33041
  );
@@ -32678,7 +33536,7 @@ var SWIFT_CODEGEN_RESERVED_NAMES = [
32678
33536
  ];
32679
33537
  var QUERY_TABLE_COLUMNS = ["id", "type"];
32680
33538
  var TYPE_PRECEDENCE = ["string", "number", "boolean", "stringset"];
32681
- var hasOwn2 = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
33539
+ var hasOwn3 = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
32682
33540
  var byCodePoint = (a, b) => a < b ? -1 : a > b ? 1 : 0;
32683
33541
  function pascalCase(name) {
32684
33542
  return name.split("_").filter((segment) => segment.length > 0).map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1)).join("");
@@ -32711,7 +33569,7 @@ function literalDefault(value) {
32711
33569
  return { problem: `${JSON.stringify(value) ?? String(value)} is not a string, a number, a boolean or an array of strings` };
32712
33570
  }
32713
33571
  function option(options, camel, snake) {
32714
- return hasOwn2(options, camel) ? options[camel] : hasOwn2(options, snake) ? options[snake] : void 0;
33572
+ return hasOwn3(options, camel) ? options[camel] : hasOwn3(options, snake) ? options[snake] : void 0;
32715
33573
  }
32716
33574
  function recordLogSchemaToToml(answer, options = {}) {
32717
33575
  const warn = options.warn ?? ((message) => Logger.warn(message));
@@ -32732,12 +33590,18 @@ function recordLogSchemaToToml(answer, options = {}) {
32732
33590
  );
32733
33591
  warn(`[schema-toml] omitted model "${other}": it differs from "${modelName}" only in case; read its records through documents.records()`);
32734
33592
  }
32735
- const names = [.../* @__PURE__ */ new Set([...Object.keys(declared), ...Object.keys(observed)])].filter((field) => field !== "id");
33593
+ const hidden = new Set(Array.isArray(entry.cleared) ? entry.cleared.map(String) : []);
33594
+ for (const field of [...hidden].sort(byCodePoint)) {
33595
+ if (field === "id" || !(hasOwn3(declared, field) || hasOwn3(observed, field))) continue;
33596
+ comments.push(`omitted: field "${field}" (the db3's type clears or tombstones it, so no record answers it)`);
33597
+ warn(`[schema-toml] ${modelName}: omitted field "${field}": the db3's type clears or tombstones it`);
33598
+ }
33599
+ const names = [.../* @__PURE__ */ new Set([...Object.keys(declared), ...Object.keys(observed)])].filter((field) => field !== "id" && !hidden.has(field));
32736
33600
  const fields = {};
32737
- const declaredId = hasOwn2(declared, "id") ? declared.id : null;
33601
+ const declaredId = hasOwn3(declared, "id") ? declared.id : null;
32738
33602
  fields.id = declaredId ? { ...declaredOptions(modelName, "id", declaredId, noteField, warn), type: "id" } : { type: "id", autoAssign: true };
32739
33603
  const kept = [];
32740
- for (const { kept: field, omitted } of caseGroups(names, (name) => hasOwn2(declared, name))) {
33604
+ for (const { kept: field, omitted } of caseGroups(names, (name) => hasOwn3(declared, name))) {
32741
33605
  for (const other of omitted) {
32742
33606
  comments.push(
32743
33607
  `omitted: field "${other}" (it differs from "${field}" only in case, and a query table keeps one column per field name ignoring case); its values stay readable through documents.records()`
@@ -32770,7 +33634,7 @@ function recordLogSchemaToToml(answer, options = {}) {
32770
33634
  return byCodePoint(a, b);
32771
33635
  });
32772
33636
  for (const field of kept) {
32773
- if (hasOwn2(declared, field)) {
33637
+ if (hasOwn3(declared, field)) {
32774
33638
  fields[field] = declaredOptions(modelName, field, declared[field], noteField, warn);
32775
33639
  continue;
32776
33640
  }
@@ -32860,5 +33724,6 @@ function declaredOptions(model, field, declared, noteField, warn) {
32860
33724
 
32861
33725
  // src/browser.ts
32862
33726
  init_documentTypes();
33727
+ init_jsonFields();
32863
33728
  init_vector();
32864
33729
  init_yjsRuntime();