js-bao 0.4.0 → 0.4.2

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/node.js CHANGED
@@ -2550,6 +2550,9 @@ var init_BaseModel = __esm({
2550
2550
  static connectedDocuments = /* @__PURE__ */ new Map();
2551
2551
  static documentYMaps = /* @__PURE__ */ new Map();
2552
2552
  // Maps docId to YMap for that document
2553
+ // Tracks nested-Y.Map stringset fields we've already attached observers to,
2554
+ // so attachStringSetObserversToRecord() is idempotent across re-entry.
2555
+ static _observedStringSetMaps = /* @__PURE__ */ new WeakSet();
2553
2556
  // Copy-on-write state management
2554
2557
  _localChanges = null;
2555
2558
  _isDirty = false;
@@ -3069,16 +3072,15 @@ var init_BaseModel = __esm({
3069
3072
  this._isDirty = true;
3070
3073
  }
3071
3074
  getStringSetCurrentValues(fieldName) {
3072
- const yjsData = this.getFromYjs(fieldName);
3073
- if (yjsData && typeof yjsData === "object") {
3074
- return Object.keys(yjsData);
3075
- }
3076
- return [];
3075
+ return this.getStringSetFromYjs(fieldName);
3077
3076
  }
3078
3077
  getStringSetFromYjs(fieldName) {
3079
3078
  const yjsData = this.getFromYjs(fieldName);
3079
+ if (yjsData instanceof Y2.Map) {
3080
+ return Array.from(yjsData.keys());
3081
+ }
3080
3082
  if (yjsData && typeof yjsData === "object") {
3081
- return Object.keys(yjsData);
3083
+ return Object.keys(yjsData).filter((k) => Boolean(yjsData[k]));
3082
3084
  }
3083
3085
  return [];
3084
3086
  }
@@ -3689,7 +3691,7 @@ var init_BaseModel = __esm({
3689
3691
  Logger.debug(
3690
3692
  `[_diffWithYjsData] No unsaved changes, returning empty diff`
3691
3693
  );
3692
- return { added: {}, modified: {}, removed: [] };
3694
+ return { added: {}, modified: {}, removed: [], stringSetChanges: {} };
3693
3695
  }
3694
3696
  const modelConstructor = this.constructor;
3695
3697
  const schema = modelConstructor.getSchema();
@@ -3720,6 +3722,7 @@ var init_BaseModel = __esm({
3720
3722
  const added = {};
3721
3723
  const modified = {};
3722
3724
  const removed = [];
3725
+ const stringSetChanges = {};
3723
3726
  if (!recordYMap) {
3724
3727
  Logger.debug(
3725
3728
  `[_diffWithYjsData] No existing recordYMap, treating all local changes as 'added'`
@@ -3728,11 +3731,12 @@ var init_BaseModel = __esm({
3728
3731
  for (const [key, value] of Object.entries(this._localChanges)) {
3729
3732
  Logger.debug(`[_diffWithYjsData] Adding field '${key}': ${value}`);
3730
3733
  if (value && value.type === "stringset") {
3731
- const stringSetData = {};
3732
- for (const addition of value.additions) {
3733
- stringSetData[addition] = true;
3734
+ if (value.additions.size > 0 || value.removals.size > 0) {
3735
+ stringSetChanges[key] = {
3736
+ additions: value.additions,
3737
+ removals: value.removals
3738
+ };
3734
3739
  }
3735
- added[key] = stringSetData;
3736
3740
  } else {
3737
3741
  added[key] = value;
3738
3742
  }
@@ -3741,9 +3745,10 @@ var init_BaseModel = __esm({
3741
3745
  Logger.debug(`[_diffWithYjsData] Final diff for new record:`, {
3742
3746
  added,
3743
3747
  modified: {},
3744
- removed: []
3748
+ removed: [],
3749
+ stringSetChanges
3745
3750
  });
3746
- return { added, modified, removed: [] };
3751
+ return { added, modified, removed: [], stringSetChanges };
3747
3752
  }
3748
3753
  Logger.debug(
3749
3754
  `[_diffWithYjsData] Existing record found, comparing local changes with Y.js data`
@@ -3760,21 +3765,11 @@ var init_BaseModel = __esm({
3760
3765
  `[_diffWithYjsData] Processing field '${key}' with local value: ${localValue}`
3761
3766
  );
3762
3767
  if (localValue && localValue.type === "stringset") {
3763
- const currentYjsData = recordYMap.get(key) || {};
3764
- const newStringSetData = {
3765
- ...currentYjsData
3766
- };
3767
- for (const addition of localValue.additions) {
3768
- newStringSetData[addition] = true;
3769
- }
3770
- for (const removal of localValue.removals) {
3771
- delete newStringSetData[removal];
3772
- }
3773
- const yjsValue = recordYMap.get(key);
3774
- if (yjsValue === void 0) {
3775
- added[key] = newStringSetData;
3776
- } else if (!this._deepEqual(yjsValue, newStringSetData)) {
3777
- modified[key] = newStringSetData;
3768
+ if (localValue.additions.size > 0 || localValue.removals.size > 0) {
3769
+ stringSetChanges[key] = {
3770
+ additions: localValue.additions,
3771
+ removals: localValue.removals
3772
+ };
3778
3773
  }
3779
3774
  } else {
3780
3775
  const yjsValue = recordYMap.get(key);
@@ -3800,14 +3795,43 @@ var init_BaseModel = __esm({
3800
3795
  Logger.debug(`[_diffWithYjsData] Final diff result:`, {
3801
3796
  added,
3802
3797
  modified,
3803
- removed
3798
+ removed,
3799
+ stringSetChanges
3804
3800
  });
3805
3801
  Logger.verbose(`[${modelConstructor.name}] Diff for ${this.id}:`, {
3806
3802
  added: Object.keys(added),
3807
3803
  modified: Object.keys(modified),
3808
- removed
3804
+ removed,
3805
+ stringSetChanges: Object.keys(stringSetChanges)
3809
3806
  });
3810
- return { added, modified, removed };
3807
+ return { added, modified, removed, stringSetChanges };
3808
+ }
3809
+ /**
3810
+ * Apply a stringset change set to the parent record's Y.Map by mutating a
3811
+ * nested Y.Map keyed by member. Migrates from a legacy plain-object value
3812
+ * if the field hasn't been touched since the wire-format change in #561.
3813
+ */
3814
+ applyStringSetChangeToYMap(recordYMap, fieldName, change) {
3815
+ let nested = recordYMap.get(fieldName);
3816
+ if (!(nested instanceof Y2.Map)) {
3817
+ const migrated = new Y2.Map();
3818
+ if (nested && typeof nested === "object") {
3819
+ for (const [member, marker] of Object.entries(
3820
+ nested
3821
+ )) {
3822
+ if (Boolean(marker)) migrated.set(member, true);
3823
+ }
3824
+ }
3825
+ recordYMap.set(fieldName, migrated);
3826
+ nested = migrated;
3827
+ }
3828
+ const target = nested;
3829
+ for (const member of change.additions) {
3830
+ target.set(member, true);
3831
+ }
3832
+ for (const member of change.removals) {
3833
+ target.delete(member);
3834
+ }
3811
3835
  }
3812
3836
  /**
3813
3837
  * Deep equality check for comparing field values
@@ -4046,7 +4070,7 @@ var init_BaseModel = __esm({
4046
4070
  Logger.debug(`[${modelName}.save] About to calculate diff`);
4047
4071
  const diff = this._diffWithYjsData();
4048
4072
  Logger.debug(`[${modelName}.save] Diff result:`, diff);
4049
- const hasChanges = Object.keys(diff.added).length > 0 || Object.keys(diff.modified).length > 0 || diff.removed.length > 0;
4073
+ const hasChanges = Object.keys(diff.added).length > 0 || Object.keys(diff.modified).length > 0 || diff.removed.length > 0 || Object.keys(diff.stringSetChanges).length > 0;
4050
4074
  Logger.debug(`[${modelName}.save] hasChanges: ${hasChanges}`);
4051
4075
  if (!hasChanges && isUpdate) {
4052
4076
  Logger.verbose(
@@ -4164,6 +4188,16 @@ var init_BaseModel = __esm({
4164
4188
  Logger.debug(`[${modelName}.save] Removing field '${key}'`);
4165
4189
  recordYMap.delete(key);
4166
4190
  }
4191
+ for (const [fieldName, change] of Object.entries(diff.stringSetChanges)) {
4192
+ Logger.debug(
4193
+ `[${modelName}.save] Applying stringset change to field '${fieldName}':`,
4194
+ {
4195
+ additions: Array.from(change.additions),
4196
+ removals: Array.from(change.removals)
4197
+ }
4198
+ );
4199
+ this.applyStringSetChangeToYMap(recordYMap, fieldName, change);
4200
+ }
4167
4201
  Logger.debug(
4168
4202
  `[${modelName}.save] After applying changes, recordYMap contents:`,
4169
4203
  Object.fromEntries(recordYMap.entries())
@@ -5348,6 +5382,39 @@ var init_BaseModel = __esm({
5348
5382
  _BaseModel.prototype.setValue = originalSetValue;
5349
5383
  }
5350
5384
  }
5385
+ /**
5386
+ * Attach a one-shot observer to a nested-Y.Map stringset field. Calls
5387
+ * notifyListeners() when the nested map's keys change (i.e. when a remote
5388
+ * member arrives via Y.applyUpdate, or a local per-member set/delete).
5389
+ * Idempotent — re-calling on the same Y.Map is a no-op.
5390
+ */
5391
+ static observeStringSetMapOnce(nestedMap) {
5392
+ if (_BaseModel._observedStringSetMaps.has(nestedMap)) return;
5393
+ _BaseModel._observedStringSetMaps.add(nestedMap);
5394
+ const modelConstructor = this;
5395
+ nestedMap.observe(() => {
5396
+ Logger.verbose(
5397
+ `[${modelConstructor.name}] Nested stringset Y.Map changed; notifying listeners`
5398
+ );
5399
+ modelConstructor.notifyListeners();
5400
+ });
5401
+ }
5402
+ /**
5403
+ * Walk the schema's stringset fields on `recordYMap` and observe any nested
5404
+ * Y.Map values. Called from observer setup and from the parent observer body
5405
+ * so newly-arrived stringset Y.Maps (local migration or remote create) get
5406
+ * an observer too.
5407
+ */
5408
+ static attachStringSetObserversToRecord(recordYMap, schema) {
5409
+ if (!schema?.fields) return;
5410
+ for (const [fieldKey, fieldOptions] of schema.fields) {
5411
+ if (fieldOptions?.type !== "stringset") continue;
5412
+ const value = recordYMap.get(fieldKey);
5413
+ if (value instanceof Y2.Map) {
5414
+ this.observeStringSetMapOnce(value);
5415
+ }
5416
+ }
5417
+ }
5351
5418
  /**
5352
5419
  * Sets up deep observation on a nested YMap to sync field-level changes to the database
5353
5420
  */
@@ -5364,11 +5431,13 @@ var init_BaseModel = __esm({
5364
5431
  Logger.verbose(
5365
5432
  `[${modelName}] Setting up nested YMap observer for record ${recordId}`
5366
5433
  );
5434
+ modelConstructor.attachStringSetObserversToRecord(recordYMap, schema);
5367
5435
  recordYMap.observe(async (event) => {
5368
5436
  Logger.verbose(
5369
5437
  `[${modelName}] Nested YMap change detected for record ${recordId}:`,
5370
5438
  event
5371
5439
  );
5440
+ modelConstructor.attachStringSetObserversToRecord(recordYMap, schema);
5372
5441
  const currentDbInstance = _BaseModel.dbInstance;
5373
5442
  if (!currentDbInstance) {
5374
5443
  Logger.error(
@@ -5442,11 +5511,13 @@ var init_BaseModel = __esm({
5442
5511
  Logger.verbose(
5443
5512
  `[${modelName}] Setting up nested YMap observer for record ${recordId} in document ${docId}`
5444
5513
  );
5514
+ modelConstructor.attachStringSetObserversToRecord(recordYMap, schema);
5445
5515
  recordYMap.observe(async (event) => {
5446
5516
  Logger.verbose(
5447
5517
  `[${modelName}] Nested YMap change detected for record ${recordId} in document ${docId}:`,
5448
5518
  event
5449
5519
  );
5520
+ modelConstructor.attachStringSetObserversToRecord(recordYMap, schema);
5450
5521
  const currentDbInstance = _BaseModel.dbInstance;
5451
5522
  if (!currentDbInstance) {
5452
5523
  Logger.error(
@@ -6902,6 +6973,7 @@ function defineModelSchema(input) {
6902
6973
  const { name, fields } = input;
6903
6974
  const options = {
6904
6975
  name,
6976
+ className: input.options?.className,
6905
6977
  uniqueConstraints: input.options?.uniqueConstraints ? [...input.options.uniqueConstraints] : void 0,
6906
6978
  relationships: input.options?.relationships
6907
6979
  };
@@ -7001,18 +7073,13 @@ function resolveUniqueConstraints(modelName, fields, customConstraints) {
7001
7073
  function attachSchemaToClass(modelClass, schema) {
7002
7074
  modelClass.schema = schema;
7003
7075
  modelClass.modelName = schema.options.name;
7004
- if (!modelClass.getSchema) {
7005
- Object.defineProperty(modelClass, "getSchema", {
7006
- value: function() {
7007
- return schema.buildRuntimeShape(modelClass);
7008
- },
7009
- writable: false
7010
- });
7011
- } else {
7012
- modelClass.getSchema = function() {
7076
+ Object.defineProperty(modelClass, "getSchema", {
7077
+ value: function() {
7013
7078
  return schema.buildRuntimeShape(modelClass);
7014
- };
7015
- }
7079
+ },
7080
+ writable: false,
7081
+ configurable: true
7082
+ });
7016
7083
  const runtimeShape = schema.buildRuntimeShape(modelClass);
7017
7084
  BaseModel2.attachFieldAccessors(modelClass, runtimeShape.fields);
7018
7085
  return runtimeShape;
@@ -7245,12 +7312,52 @@ var VALID_FIELD_TYPES = /* @__PURE__ */ new Set([
7245
7312
  "id",
7246
7313
  "stringset"
7247
7314
  ]);
7248
- function parseFieldOptions(raw) {
7315
+ var KNOWN_FIELD_KEYS = /* @__PURE__ */ new Set([
7316
+ "type",
7317
+ "indexed",
7318
+ "unique",
7319
+ "required",
7320
+ "auto_assign",
7321
+ "max_length",
7322
+ "max_count",
7323
+ "default"
7324
+ ]);
7325
+ var KNOWN_MODEL_KEYS = /* @__PURE__ */ new Set([
7326
+ "fields",
7327
+ "relationships",
7328
+ "unique_constraints",
7329
+ "class_name"
7330
+ ]);
7331
+ var KNOWN_RELATIONSHIP_KEYS = /* @__PURE__ */ new Set([
7332
+ "type",
7333
+ "model",
7334
+ "related_id_field",
7335
+ "join_model",
7336
+ "join_model_local_field",
7337
+ "join_model_related_field",
7338
+ "order_by_field",
7339
+ "order_direction",
7340
+ "join_model_order_by_field",
7341
+ "join_model_order_direction"
7342
+ ]);
7343
+ var KNOWN_UNIQUE_CONSTRAINT_KEYS = /* @__PURE__ */ new Set(["name", "fields"]);
7344
+ function checkUnknownKeys(raw, known, context, strict) {
7345
+ if (!strict) return;
7346
+ for (const key of Object.keys(raw)) {
7347
+ if (!known.has(key)) {
7348
+ throw new Error(
7349
+ `${context}: unknown key "${key}". Allowed: ${[...known].join(", ")}`
7350
+ );
7351
+ }
7352
+ }
7353
+ }
7354
+ function parseFieldOptions(raw, context, strict) {
7249
7355
  if (!raw.type || !VALID_FIELD_TYPES.has(raw.type)) {
7250
7356
  throw new Error(
7251
7357
  `Invalid field type "${raw.type}". Must be one of: ${[...VALID_FIELD_TYPES].join(", ")}`
7252
7358
  );
7253
7359
  }
7360
+ checkUnknownKeys(raw, KNOWN_FIELD_KEYS, context, strict);
7254
7361
  const opts = { type: raw.type };
7255
7362
  if (raw.indexed === true) opts.indexed = true;
7256
7363
  if (raw.unique === true) opts.unique = true;
@@ -7266,8 +7373,9 @@ function requireField(raw, field, context) {
7266
7373
  throw new Error(`Relationship ${context}: missing required field "${field}"`);
7267
7374
  }
7268
7375
  }
7269
- function parseRelationship(raw) {
7376
+ function parseRelationship(raw, context, strict) {
7270
7377
  const type = raw.type;
7378
+ checkUnknownKeys(raw, KNOWN_RELATIONSHIP_KEYS, context, strict);
7271
7379
  if (type === "refersTo") {
7272
7380
  requireField(raw, "model", "refersTo");
7273
7381
  requireField(raw, "related_id_field", "refersTo");
@@ -7309,7 +7417,8 @@ function parseRelationship(raw) {
7309
7417
  }
7310
7418
  throw new Error(`Unknown relationship type: ${type}`);
7311
7419
  }
7312
- function loadSchemaFromTomlString(tomlString) {
7420
+ function loadSchemaFromTomlString(tomlString, options = {}) {
7421
+ const strict = options.strict !== false;
7313
7422
  const parsed = parseToml(tomlString);
7314
7423
  const models = parsed.models;
7315
7424
  if (!models || typeof models !== "object") {
@@ -7317,10 +7426,20 @@ function loadSchemaFromTomlString(tomlString) {
7317
7426
  }
7318
7427
  const schemas = [];
7319
7428
  for (const [modelName, modelDef] of Object.entries(models)) {
7429
+ checkUnknownKeys(
7430
+ modelDef,
7431
+ KNOWN_MODEL_KEYS,
7432
+ `[models.${modelName}]`,
7433
+ strict
7434
+ );
7320
7435
  const fields = {};
7321
7436
  if (modelDef.fields) {
7322
7437
  for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
7323
- fields[fieldName] = parseFieldOptions(fieldDef);
7438
+ fields[fieldName] = parseFieldOptions(
7439
+ fieldDef,
7440
+ `[models.${modelName}.fields.${fieldName}]`,
7441
+ strict
7442
+ );
7324
7443
  }
7325
7444
  }
7326
7445
  let relationships;
@@ -7329,24 +7448,36 @@ function loadSchemaFromTomlString(tomlString) {
7329
7448
  for (const [relName, relDef] of Object.entries(
7330
7449
  modelDef.relationships
7331
7450
  )) {
7332
- relationships[relName] = parseRelationship(relDef);
7451
+ relationships[relName] = parseRelationship(
7452
+ relDef,
7453
+ `[models.${modelName}.relationships.${relName}]`,
7454
+ strict
7455
+ );
7333
7456
  }
7334
7457
  }
7335
7458
  let uniqueConstraints;
7336
7459
  if (modelDef.unique_constraints) {
7337
7460
  uniqueConstraints = [];
7338
7461
  for (const raw of modelDef.unique_constraints) {
7462
+ checkUnknownKeys(
7463
+ raw,
7464
+ KNOWN_UNIQUE_CONSTRAINT_KEYS,
7465
+ `[[models.${modelName}.unique_constraints]]`,
7466
+ strict
7467
+ );
7339
7468
  uniqueConstraints.push({
7340
7469
  name: raw.name,
7341
7470
  fields: [...raw.fields]
7342
7471
  });
7343
7472
  }
7344
7473
  }
7474
+ const className = typeof modelDef.class_name === "string" ? modelDef.class_name : void 0;
7345
7475
  schemas.push(
7346
7476
  defineModelSchema({
7347
7477
  name: modelName,
7348
7478
  fields,
7349
7479
  options: {
7480
+ className,
7350
7481
  uniqueConstraints,
7351
7482
  relationships
7352
7483
  }
@@ -7355,10 +7486,10 @@ function loadSchemaFromTomlString(tomlString) {
7355
7486
  }
7356
7487
  return schemas;
7357
7488
  }
7358
- async function loadSchemaFromToml(filePath) {
7489
+ async function loadSchemaFromToml(filePath, options = {}) {
7359
7490
  const { readFile } = await import("fs/promises");
7360
7491
  const content = await readFile(filePath, "utf-8");
7361
- return loadSchemaFromTomlString(content);
7492
+ return loadSchemaFromTomlString(content, options);
7362
7493
  }
7363
7494
 
7364
7495
  // src/node.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "js-bao",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "description": "A library providing data modeling capabilities which support live updates and queries.",
5
5
  "types": "dist/index.d.ts",
6
6
  "type": "module",
@@ -51,10 +51,12 @@
51
51
  },
52
52
  "bin": {
53
53
  "js-bao-codegen": "./dist/codegen.cjs",
54
- "jsbao-codegen": "./dist/codegen.cjs"
54
+ "jsbao-codegen": "./dist/codegen.cjs",
55
+ "js-bao-codegen-v2": "./dist/codegen-v2.cjs",
56
+ "jsbao-codegen-v2": "./dist/codegen-v2.cjs"
55
57
  },
56
58
  "scripts": {
57
- "build": "pnpm build:cli && pnpm codegen && rm -f dist/index.* dist/node.* dist/browser.* dist/cloudflare.* dist/cloudflare-do.* dist/client.* && pnpm build:main",
59
+ "build": "pnpm build:cli && pnpm build:cli-v2 && pnpm codegen && rm -f dist/index.* dist/node.* dist/browser.* dist/cloudflare.* dist/cloudflare-do.* dist/client.* && pnpm build:main",
58
60
  "build:main": "pnpm build:browser && pnpm build:node && pnpm build:universal && pnpm build:cloudflare && pnpm build:cloudflare-do && pnpm build:client",
59
61
  "build:browser": "tsup src/browser.ts --format esm,cjs --dts --platform browser --external better-sqlite3 --external sql.js --external async-mutex --external ulid --external yjs --external fs --no-splitting",
60
62
  "build:node": "tsup src/node.ts --format esm,cjs --dts --platform node --external better-sqlite3 --external sql.js --external async-mutex --external ulid --external yjs --no-splitting",
@@ -63,6 +65,7 @@
63
65
  "build:cloudflare-do": "tsup src/cloudflare-do.ts --format esm,cjs --dts --platform neutral --external better-sqlite3 --external sql.js --external async-mutex --external ulid --external yjs --external fs --no-splitting",
64
66
  "build:client": "tsup src/client.ts --format esm,cjs --dts --platform browser --external better-sqlite3 --external sql.js --external async-mutex --external ulid --external yjs --external fs --no-splitting",
65
67
  "build:cli": "tsup src/cli/codegen.ts --format cjs --dts --platform node --target node18 --external commander --external typescript --external fs --external path --external util --no-splitting",
68
+ "build:cli-v2": "tsup src/cli/codegen-v2.ts --format cjs --dts --platform node --target node18 --external commander --external typescript --external fs --external path --external util --no-splitting",
66
69
  "dev": "pnpm build:cli && concurrently \"pnpm codegen:watch\" \"pnpm dev:main\"",
67
70
  "dev:main": "concurrently \"pnpm build:browser:dev --watch\" \"pnpm build:node:dev --watch\" \"pnpm build:universal:dev --watch\"",
68
71
  "dev:simple": "pnpm build:cli && pnpm codegen && pnpm build:main --watch",
@@ -116,11 +119,5 @@
116
119
  "workers"
117
120
  ],
118
121
  "author": "Primitive LLC",
119
- "license": "UNLICENSED",
120
- "pnpm": {
121
- "onlyBuiltDependencies": [
122
- "better-sqlite3",
123
- "esbuild"
124
- ]
125
- }
122
+ "license": "UNLICENSED"
126
123
  }