@atscript/db-mongo 0.1.182 → 0.1.184

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/index.cjs CHANGED
@@ -385,20 +385,20 @@ var CollectionPatcher = class {
385
385
  const topLevelArray = flatType?.metadata?.get("db.__topLevelArray");
386
386
  const isObjectValue = typeof value === "object" && value !== null && !Array.isArray(value);
387
387
  if (isObjectValue && topLevelArray && !flatType?.metadata?.has("db.json")) this.parseArrayPatch(key, value, flatType);
388
- else if (isObjectValue && flatType?.metadata?.get("db.patch.strategy") === "merge") this.flattenPayload(value, key);
389
- else if (isObjectValue && flatType?.type.kind === "object" && !flatType.metadata?.has("db.json")) this._flattenReplaceObject(value, key, flatType);
388
+ else if (isObjectValue && this.collection.mergePaths.has(key)) this.flattenPayload(value, key);
389
+ else if (isObjectValue && (0, _atscript_db.storedObjectType)(flatType) && !flatType.metadata?.has("db.json")) this._flattenReplaceObject(value, key, flatType);
390
390
  else if (key !== "_id") this._setLeaf(key, value, flatType);
391
391
  }
392
392
  return this.updatePipeline;
393
393
  }
394
394
  /**
395
- * Walk the schema's props for a replace-strategy nested object so omitted
396
- * optional children become explicit nulls (parity with SQL `column = NULL`).
397
- * Required-missing leaves are caught earlier by the strict validator.
395
+ * Walk the schema's props for a replace-strategy nested object (a `T | null`
396
+ * one included, `storedObjectType`) so omitted optional children become
397
+ * explicit nulls (parity with SQL `column = NULL`). Required-missing leaves
398
+ * are caught earlier by the strict validator.
398
399
  */
399
400
  _flattenReplaceObject(value, prefix, flatType) {
400
- const propsMap = flatType.type.props;
401
- for (const [propKey, propType] of propsMap) {
401
+ for (const [propKey, propType] of (0, _atscript_db.storedObjectType)(flatType).type.props) {
402
402
  const childKey = `${prefix}.${propKey}`;
403
403
  const childValue = value[propKey];
404
404
  if (childValue === void 0) {
@@ -407,15 +407,17 @@ var CollectionPatcher = class {
407
407
  }
408
408
  const childIsObject = typeof childValue === "object" && childValue !== null && !Array.isArray(childValue);
409
409
  const propIsJson = propType.metadata?.has("db.json");
410
- const propIsMerge = propType.metadata?.get("db.patch.strategy") === "merge";
411
410
  const childFlatType = this.collection.flatMap.get(childKey);
412
411
  if (childIsObject && !propIsJson && childFlatType?.metadata?.get("db.__topLevelArray")) {
413
412
  this.parseArrayPatch(childKey, childValue, childFlatType);
414
413
  continue;
415
414
  }
416
- if (childIsObject && propType.type.kind === "object" && !propIsJson) {
417
- if (propIsMerge) this.flattenPayload(childValue, childKey);
418
- else this._flattenReplaceObject(childValue, childKey, propType);
415
+ if (childIsObject && this.collection.mergePaths.has(childKey)) {
416
+ this.flattenPayload(childValue, childKey);
417
+ continue;
418
+ }
419
+ if (childIsObject && (0, _atscript_db.storedObjectType)(propType) && !propIsJson) {
420
+ this._flattenReplaceObject(childValue, childKey, propType);
419
421
  continue;
420
422
  }
421
423
  this._setLeaf(childKey, childValue, propType);
@@ -442,8 +444,8 @@ var CollectionPatcher = class {
442
444
  return;
443
445
  }
444
446
  this._remove(key, toRemove, keys, flatType);
445
- this._update(key, toUpdate, keys, flatType);
446
- this._upsert(key, toUpsert, keys, flatType);
447
+ this._update(key, toUpdate, keys);
448
+ this._upsert(key, toUpsert, keys);
447
449
  this._insert(key, toInsert, keys, flatType);
448
450
  }
449
451
  /**
@@ -545,13 +547,13 @@ var CollectionPatcher = class {
545
547
  * or append when none has it
546
548
  * - key-less → append unless an equal element is stored
547
549
  */
548
- _upsert(key, input, keys, flatType) {
550
+ _upsert(key, input, keys) {
549
551
  if (!input?.length) return;
550
552
  if (keys.length === 0) {
551
553
  this._appendAbsent(key, input);
552
554
  return;
553
555
  }
554
- const mergeStrategy = flatType.metadata?.get("db.patch.strategy") === "merge";
556
+ const mergeStrategy = this.collection.mergePaths.has(key);
555
557
  this._appendUnless(key, input, this._keyStored(keys), { $map: {
556
558
  input: "$$value",
557
559
  as: "el",
@@ -569,9 +571,9 @@ var CollectionPatcher = class {
569
571
  * 0.1.180, as on every other adapter; before, the items were added to
570
572
  * the array as a set union)
571
573
  */
572
- _update(key, input, keys, flatType) {
574
+ _update(key, input, keys) {
573
575
  if (!input?.length || keys.length === 0) return;
574
- const mergeStrategy = flatType.metadata?.get("db.patch.strategy") === "merge";
576
+ const mergeStrategy = this.collection.mergePaths.has(key);
575
577
  this._set(key, { $reduce: {
576
578
  input: literal(input),
577
579
  initialValue: { $ifNull: [`$${key}`, []] },
@@ -1368,25 +1370,44 @@ function textRunOptions(plan, query) {
1368
1370
  defaultSort: RELEVANCE_SORT
1369
1371
  } : {};
1370
1372
  }
1373
+ /**
1374
+ * Field the `vectorSearchScore` rides in through the pipeline. Renamed to the
1375
+ * public `$score` after fetch — a field name cannot start with `$`.
1376
+ */
1377
+ const SCORE_FIELD = "__atscript_score";
1371
1378
  /** Vector search via $vectorSearch aggregation stage. */
1372
1379
  async function vectorSearchImpl(host, vector, query, indexName) {
1373
1380
  const controls = query.controls || {};
1374
1381
  const plan = buildVectorSearchPlan(host, vector, query, indexName);
1375
1382
  const threshold = resolveThreshold(host, controls, indexName);
1376
- return runSearchPipeline(host, plan.stage, query, "vectorSearch", {
1377
- threshold,
1383
+ return (await runSearchPipeline(host, plan.stage, query, "vectorSearch", {
1384
+ vector: { threshold },
1378
1385
  filterStages: plan.filterStages
1379
- });
1386
+ })).map((row) => renameComputed(row, SCORE_FIELD, "$score"));
1380
1387
  }
1381
1388
  /** Vector search with faceted count. */
1382
1389
  async function vectorSearchWithCountImpl(host, vector, query, indexName) {
1383
1390
  const controls = query.controls || {};
1384
1391
  const plan = buildVectorSearchPlan(host, vector, query, indexName);
1385
1392
  const threshold = resolveThreshold(host, controls, indexName);
1386
- return runSearchWithCountPipeline(host, plan.stage, query, "vectorSearchWithCount", {
1387
- threshold,
1393
+ const result = await runSearchWithCountPipeline(host, plan.stage, query, "vectorSearchWithCount", {
1394
+ vector: { threshold },
1388
1395
  filterStages: plan.filterStages
1389
1396
  });
1397
+ return {
1398
+ data: result.data.map((row) => renameComputed(row, SCORE_FIELD, "$score")),
1399
+ count: result.count
1400
+ };
1401
+ }
1402
+ /**
1403
+ * The stages right after `$vectorSearch`: its score into {@link SCORE_FIELD}
1404
+ * (the `$meta` is read here, ahead of any `$facet`) and, with a threshold,
1405
+ * the `$match` on it.
1406
+ */
1407
+ function vectorScoreStages(threshold) {
1408
+ const stages = [{ $addFields: { [SCORE_FIELD]: { $meta: "vectorSearchScore" } } }];
1409
+ if (threshold !== void 0) stages.push({ $match: { [SCORE_FIELD]: { $gte: threshold } } });
1410
+ return stages;
1390
1411
  }
1391
1412
  /**
1392
1413
  * Field name `$geoNear` writes the computed distance into. Renamed to the
@@ -1400,9 +1421,9 @@ async function geoSearchImpl(host, point, query, indexName) {
1400
1421
  const pipeline = buildGeoNearStages(host, point, query, indexName);
1401
1422
  if (controls.$skip) pipeline.push({ $skip: controls.$skip });
1402
1423
  pipeline.push({ $limit: controls.$limit || 1e3 });
1403
- pushGeoProjection(pipeline, query.controls);
1424
+ pushProjection(pipeline, query.controls, DISTANCE_FIELD);
1404
1425
  host._log("aggregate (geoSearch)", pipeline);
1405
- return (await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray())).map((row) => renameDistance(row));
1426
+ return (await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray())).map((row) => renameComputed(row, DISTANCE_FIELD, "$distance"));
1406
1427
  }
1407
1428
  /** Geo search with faceted count (rows within the distance window). */
1408
1429
  async function geoSearchWithCountImpl(host, point, query, indexName) {
@@ -1410,7 +1431,7 @@ async function geoSearchWithCountImpl(host, point, query, indexName) {
1410
1431
  const dataStages = [];
1411
1432
  if (controls.$skip) dataStages.push({ $skip: controls.$skip });
1412
1433
  if (controls.$limit) dataStages.push({ $limit: controls.$limit });
1413
- pushGeoProjection(dataStages, query.controls);
1434
+ pushProjection(dataStages, query.controls, DISTANCE_FIELD);
1414
1435
  const pipeline = [...buildGeoNearStages(host, point, query, indexName), { $facet: {
1415
1436
  data: dataStages,
1416
1437
  meta: [{ $count: "count" }]
@@ -1418,7 +1439,7 @@ async function geoSearchWithCountImpl(host, point, query, indexName) {
1418
1439
  host._log("aggregate (geoSearchWithCount)", pipeline);
1419
1440
  const result = await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray());
1420
1441
  return {
1421
- data: (result[0]?.data || []).map((row) => renameDistance(row)),
1442
+ data: (result[0]?.data || []).map((row) => renameComputed(row, DISTANCE_FIELD, "$distance")),
1422
1443
  count: result[0]?.meta?.[0]?.count || 0
1423
1444
  };
1424
1445
  }
@@ -1459,27 +1480,28 @@ function resolveGeoKeyPath(host, indexName) {
1459
1480
  return field;
1460
1481
  }
1461
1482
  /**
1462
- * Appends a `$project` stage, keeping the computed distance in inclusion mode.
1463
- * The distance key goes on a COPY: `asProjection` (and `dedupeProjection`)
1464
- * hand back the caller's own `$select` map when nothing needs rewriting — an
1465
- * object the caller may share across queries (moost-db memoizes, and in dev /
1466
- * test deep-freezes, the projection of a read without `$select`).
1483
+ * Appends the `$select` `$project` stage, keeping the computed field `keep`
1484
+ * (the geo distance, the vector score) in inclusion mode. That key goes on a
1485
+ * COPY: `asProjection` (and `dedupeProjection`) hand back the caller's own
1486
+ * `$select` map when nothing needs rewriting — an object the caller may share
1487
+ * across queries (moost-db memoizes, and in dev / test deep-freezes, the
1488
+ * projection of a read without `$select`).
1467
1489
  */
1468
- function pushGeoProjection(stages, controls) {
1490
+ function pushProjection(stages, controls, keep) {
1469
1491
  const projection = controls?.$select?.asProjection;
1470
1492
  if (!projection) return;
1471
1493
  const deduped = dedupeProjection(projection);
1472
- const isInclusion = Object.values(deduped).some((v) => v === 1);
1494
+ const isInclusion = keep !== void 0 && Object.values(deduped).some((v) => v === 1);
1473
1495
  stages.push({ $project: isInclusion ? {
1474
1496
  ...deduped,
1475
- [DISTANCE_FIELD]: 1
1497
+ [keep]: 1
1476
1498
  } : deduped });
1477
1499
  }
1478
- /** Renames the internal distance field to the public `$distance` pseudo-field. */
1479
- function renameDistance(row) {
1480
- if (DISTANCE_FIELD in row) {
1481
- row.$distance = row[DISTANCE_FIELD];
1482
- delete row[DISTANCE_FIELD];
1500
+ /** Renames an internal computed field to its public `$`-prefixed name (in place). */
1501
+ function renameComputed(row, field, name) {
1502
+ if (field in row) {
1503
+ row[name] = row[field];
1504
+ delete row[field];
1483
1505
  }
1484
1506
  return row;
1485
1507
  }
@@ -1775,13 +1797,11 @@ function buildVectorSearchStage(host, vector, indexName, limit, skip) {
1775
1797
  };
1776
1798
  }
1777
1799
  /** Runs a search/vector pipeline and returns results. Shared by search + vectorSearch. */
1778
- async function runSearchPipeline(host, stage, query, label, { threshold, classicText = false, defaultSort, filterStages } = {}) {
1800
+ async function runSearchPipeline(host, stage, query, label, { vector, classicText = false, defaultSort, filterStages } = {}) {
1779
1801
  const controls = query.controls || {};
1780
1802
  const pipeline = [stage];
1781
- if (threshold !== void 0) {
1782
- pipeline.push({ $addFields: { _score: { $meta: "vectorSearchScore" } } });
1783
- pipeline.push({ $match: { _score: { $gte: threshold } } });
1784
- } else if (classicText) pipeline.push({ $addFields: { _score: { $meta: "textScore" } } });
1803
+ if (vector) pipeline.push(...vectorScoreStages(vector.threshold));
1804
+ else if (classicText) pipeline.push({ $addFields: { _score: { $meta: "textScore" } } });
1785
1805
  pipeline.push(...filterStages ?? require_mongo_accumulator.mongoFilterStages(query.filter, filterOptionsOf(host)));
1786
1806
  const { stages: sorted, cleanup } = require_mongo_accumulator.sortStages(controls);
1787
1807
  if (sorted.length > 0) pipeline.push(...sorted);
@@ -1790,10 +1810,7 @@ async function runSearchPipeline(host, stage, query, label, { threshold, classic
1790
1810
  if (controls.$limit) pipeline.push({ $limit: controls.$limit });
1791
1811
  else pipeline.push({ $limit: 1e3 });
1792
1812
  if (cleanup) pipeline.push(cleanup);
1793
- if (controls.$select) {
1794
- const projection = controls.$select.asProjection;
1795
- if (projection) pipeline.push({ $project: dedupeProjection(projection) });
1796
- }
1813
+ pushProjection(pipeline, controls, vector ? SCORE_FIELD : void 0);
1797
1814
  host._log(`aggregate (${label})`, pipeline);
1798
1815
  return wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray());
1799
1816
  }
@@ -1807,22 +1824,17 @@ async function runSearchPipeline(host, stage, query, label, { threshold, classic
1807
1824
  * `count: total` — the same counts `$$SEARCH_META` reports), concurrently
1808
1825
  * outside a transaction.
1809
1826
  */
1810
- async function runSearchWithCountPipeline(host, stage, query, label, { threshold, classicText = false, defaultSort, filterStages } = {}) {
1827
+ async function runSearchWithCountPipeline(host, stage, query, label, { vector, classicText = false, defaultSort, filterStages } = {}) {
1811
1828
  const controls = query.controls || {};
1812
1829
  const preStages = [];
1813
- if (threshold !== void 0) {
1814
- preStages.push({ $addFields: { _score: { $meta: "vectorSearchScore" } } });
1815
- preStages.push({ $match: { _score: { $gte: threshold } } });
1816
- } else if (classicText) preStages.push({ $addFields: { _score: { $meta: "textScore" } } });
1830
+ if (vector) preStages.push(...vectorScoreStages(vector.threshold));
1831
+ else if (classicText) preStages.push({ $addFields: { _score: { $meta: "textScore" } } });
1817
1832
  const { stages: dataStages, cleanup } = require_mongo_accumulator.sortStages(controls);
1818
1833
  if (dataStages.length === 0 && defaultSort) dataStages.push(defaultSort);
1819
1834
  if (controls.$skip) dataStages.push({ $skip: controls.$skip });
1820
1835
  if (controls.$limit) dataStages.push({ $limit: controls.$limit });
1821
1836
  if (cleanup) dataStages.push(cleanup);
1822
- if (controls.$select) {
1823
- const projection = controls.$select.asProjection;
1824
- if (projection) dataStages.push({ $project: dedupeProjection(projection) });
1825
- }
1837
+ pushProjection(dataStages, controls, vector ? SCORE_FIELD : void 0);
1826
1838
  const stages = filterStages ?? require_mongo_accumulator.mongoFilterStages(query.filter, filterOptionsOf(host));
1827
1839
  if ("$search" in stage && preStages.length === 0 && stages.every(isNoopMatch)) return runSearchWithMeta(host, stage, dataStages, label);
1828
1840
  const pipeline = [
@@ -2596,8 +2608,8 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2596
2608
  _hasExplicitId = false;
2597
2609
  /** Unique fields accumulated during onFieldScanned, returned via getMetadataOverrides. */
2598
2610
  _pendingUniqueFields = [];
2599
- /** {@link _patcherFlatMap}'s memo. */
2600
- _patcherFlatMapMemo;
2611
+ /** {@link _patcherMaps}' memo. */
2612
+ _patcherMapsMemo;
2601
2613
  constructor(db, client, options = {}) {
2602
2614
  super();
2603
2615
  this.db = db;
@@ -2913,7 +2925,7 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2913
2925
  /** Returns the context object used by CollectionPatcher. */
2914
2926
  getPatcherContext() {
2915
2927
  return {
2916
- flatMap: this._patcherFlatMap(),
2928
+ ...this._patcherMaps(),
2917
2929
  prepareId: (id) => this.prepareIdFromIdType(id),
2918
2930
  createValidator: (opts) => this._table.createValidator(opts)
2919
2931
  };
@@ -2923,21 +2935,26 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2923
2935
  * with `@db.column` names already applied (`translatePatchKeys`), so a
2924
2936
  * renamed union / `@db.json` field is found — and replaced, not merged —
2925
2937
  * under its stored name. Derived fields are left out (they map to their
2926
- * source's path). Built once per flat map.
2938
+ * source's path). The merge-strategy paths are keyed the same way. Built
2939
+ * once per flat map.
2927
2940
  */
2928
- _patcherFlatMap() {
2941
+ _patcherMaps() {
2929
2942
  const src = this._table.flatMap;
2930
- let memo = this._patcherFlatMapMemo;
2943
+ let memo = this._patcherMapsMemo;
2931
2944
  if (memo?.src !== src) {
2932
2945
  const meta = this._table.getMetadata();
2933
2946
  const map = /* @__PURE__ */ new Map();
2934
2947
  for (const [path, type] of src) if (!meta.derivedFields.has(path)) map.set(meta.documentPath(path), type);
2935
- memo = this._patcherFlatMapMemo = {
2948
+ const mergePaths = new Set([...meta.mergePaths].map((path) => meta.documentPath(path)));
2949
+ memo = this._patcherMapsMemo = {
2936
2950
  src,
2937
- map
2951
+ maps: {
2952
+ flatMap: map,
2953
+ mergePaths
2954
+ }
2938
2955
  };
2939
2956
  }
2940
- return memo.map;
2957
+ return memo.maps;
2941
2958
  }
2942
2959
  async nativePatch(filter, patch, ops, expectedVersion, opts) {
2943
2960
  const mongoFilter = await this._buildCasFilter(filter, expectedVersion, "nativePatch");
package/dist/index.d.cts CHANGED
@@ -11,6 +11,8 @@ import { AggregateFn, BucketUnit } from "@uniqu/core";
11
11
  */
12
12
  interface TCollectionPatcherContext {
13
13
  flatMap: Map<string, TAtscriptAnnotatedType>;
14
+ /** The document paths whose merge strategy applies (`TableMetadata.mergePaths`). */
15
+ mergePaths: ReadonlySet<string>;
14
16
  prepareId(id: any): any;
15
17
  createValidator(opts?: Partial<TValidatorOptions>): Validator<any>;
16
18
  }
@@ -94,9 +96,10 @@ declare class CollectionPatcher {
94
96
  */
95
97
  private flattenPayload;
96
98
  /**
97
- * Walk the schema's props for a replace-strategy nested object so omitted
98
- * optional children become explicit nulls (parity with SQL `column = NULL`).
99
- * Required-missing leaves are caught earlier by the strict validator.
99
+ * Walk the schema's props for a replace-strategy nested object (a `T | null`
100
+ * one included, `storedObjectType`) so omitted optional children become
101
+ * explicit nulls (parity with SQL `column = NULL`). Required-missing leaves
102
+ * are caught earlier by the strict validator.
100
103
  */
101
104
  private _flattenReplaceObject;
102
105
  /**
@@ -345,8 +348,8 @@ declare class MongoAdapter extends BaseDbAdapter {
345
348
  protected _hasExplicitId: boolean;
346
349
  /** Unique fields accumulated during onFieldScanned, returned via getMetadataOverrides. */
347
350
  private _pendingUniqueFields;
348
- /** {@link _patcherFlatMap}'s memo. */
349
- private _patcherFlatMapMemo?;
351
+ /** {@link _patcherMaps}' memo. */
352
+ private _patcherMapsMemo?;
350
353
  constructor(db: Db, client?: MongoClient | undefined, options?: TMongoAdapterOptions);
351
354
  private get _client();
352
355
  /** Every adapter over this client (or database handle) shares one session (since 0.1.128). */
@@ -514,9 +517,10 @@ declare class MongoAdapter extends BaseDbAdapter {
514
517
  * with `@db.column` names already applied (`translatePatchKeys`), so a
515
518
  * renamed union / `@db.json` field is found — and replaced, not merged —
516
519
  * under its stored name. Derived fields are left out (they map to their
517
- * source's path). Built once per flat map.
520
+ * source's path). The merge-strategy paths are keyed the same way. Built
521
+ * once per flat map.
518
522
  */
519
- private _patcherFlatMap;
523
+ private _patcherMaps;
520
524
  nativePatch(filter: FilterExpr, patch: unknown, ops?: TFieldOps, expectedVersion?: number, opts?: TDbUpdateOptions): Promise<TDbUpdateResult>;
521
525
  /**
522
526
  * `updateMany` with array operators (since 0.1.182): the pipeline
package/dist/index.d.mts CHANGED
@@ -11,6 +11,8 @@ import { TAtscriptAnnotatedType, TMetadataMap, TValidatorOptions, TValidatorPlug
11
11
  */
12
12
  interface TCollectionPatcherContext {
13
13
  flatMap: Map<string, TAtscriptAnnotatedType>;
14
+ /** The document paths whose merge strategy applies (`TableMetadata.mergePaths`). */
15
+ mergePaths: ReadonlySet<string>;
14
16
  prepareId(id: any): any;
15
17
  createValidator(opts?: Partial<TValidatorOptions>): Validator<any>;
16
18
  }
@@ -94,9 +96,10 @@ declare class CollectionPatcher {
94
96
  */
95
97
  private flattenPayload;
96
98
  /**
97
- * Walk the schema's props for a replace-strategy nested object so omitted
98
- * optional children become explicit nulls (parity with SQL `column = NULL`).
99
- * Required-missing leaves are caught earlier by the strict validator.
99
+ * Walk the schema's props for a replace-strategy nested object (a `T | null`
100
+ * one included, `storedObjectType`) so omitted optional children become
101
+ * explicit nulls (parity with SQL `column = NULL`). Required-missing leaves
102
+ * are caught earlier by the strict validator.
100
103
  */
101
104
  private _flattenReplaceObject;
102
105
  /**
@@ -345,8 +348,8 @@ declare class MongoAdapter extends BaseDbAdapter {
345
348
  protected _hasExplicitId: boolean;
346
349
  /** Unique fields accumulated during onFieldScanned, returned via getMetadataOverrides. */
347
350
  private _pendingUniqueFields;
348
- /** {@link _patcherFlatMap}'s memo. */
349
- private _patcherFlatMapMemo?;
351
+ /** {@link _patcherMaps}' memo. */
352
+ private _patcherMapsMemo?;
350
353
  constructor(db: Db, client?: MongoClient | undefined, options?: TMongoAdapterOptions);
351
354
  private get _client();
352
355
  /** Every adapter over this client (or database handle) shares one session (since 0.1.128). */
@@ -514,9 +517,10 @@ declare class MongoAdapter extends BaseDbAdapter {
514
517
  * with `@db.column` names already applied (`translatePatchKeys`), so a
515
518
  * renamed union / `@db.json` field is found — and replaced, not merged —
516
519
  * under its stored name. Derived fields are left out (they map to their
517
- * source's path). Built once per flat map.
520
+ * source's path). The merge-strategy paths are keyed the same way. Built
521
+ * once per flat map.
518
522
  */
519
- private _patcherFlatMap;
523
+ private _patcherMaps;
520
524
  nativePatch(filter: FilterExpr, patch: unknown, ops?: TFieldOps, expectedVersion?: number, opts?: TDbUpdateOptions): Promise<TDbUpdateResult>;
521
525
  /**
522
526
  * `updateMany` with array operators (since 0.1.182): the pipeline
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { a as buildMongoQuery, c as planStages, f as sortStages, h as queryNodeToExpr, i as buildMongoFilter, l as correlate, m as orNull, n as distinctCountExpr, o as collationOfAdapter, p as exprToMongo, r as REL_FILTER_TEMP_PREFIX, s as mongoFilterStages, t as buildAccumulator, u as hasNullsPlacement } from "./mongo-accumulator-CFVRBDiw.mjs";
2
2
  import { t as dynamicSearchEncryptedMessage } from "./search-messages-mQSpJ4GD.mjs";
3
- import { ALL_AGGREGATE_FNS, ALL_BUCKET_UNITS, ALL_VIEW_CAPABILITIES, BaseDbAdapter, DbError, DbSpace, andFilters, bucketTimeZoneUnavailable, computeInsights, constraintViolation, containsRelationFilter, createChangeRecorder, createFailureCollector, defaultFulltextIndex, geoIndexNotFoundMessage, getDbFieldOp, getKeyProps, getPath, isAtscriptDbView, isFieldRef, isPlainObject, isViewType, parseDefaultLiteral, queryReadColumns, relationStaticFilter, resolveDesignType, searchIndexNotFoundMessage, searchTermInteger, tableNameOf, translateQueryTree, uniqueKeyTuple, unknownWithRelation, vectorIndexNotFoundMessage } from "@atscript/db";
3
+ import { ALL_AGGREGATE_FNS, ALL_BUCKET_UNITS, ALL_VIEW_CAPABILITIES, BaseDbAdapter, DbError, DbSpace, andFilters, bucketTimeZoneUnavailable, computeInsights, constraintViolation, containsRelationFilter, createChangeRecorder, createFailureCollector, defaultFulltextIndex, geoIndexNotFoundMessage, getDbFieldOp, getKeyProps, getPath, isAtscriptDbView, isFieldRef, isPlainObject, isViewType, parseDefaultLiteral, queryReadColumns, relationStaticFilter, resolveDesignType, searchIndexNotFoundMessage, searchTermInteger, storedObjectType, tableNameOf, translateQueryTree, uniqueKeyTuple, unknownWithRelation, vectorIndexNotFoundMessage } from "@atscript/db";
4
4
  import { MongoClient, ObjectId } from "mongodb";
5
5
  import { resolveAggregateSearch } from "@atscript/db/agg";
6
6
  //#region src/lib/path-utils.ts
@@ -384,20 +384,20 @@ var CollectionPatcher = class {
384
384
  const topLevelArray = flatType?.metadata?.get("db.__topLevelArray");
385
385
  const isObjectValue = typeof value === "object" && value !== null && !Array.isArray(value);
386
386
  if (isObjectValue && topLevelArray && !flatType?.metadata?.has("db.json")) this.parseArrayPatch(key, value, flatType);
387
- else if (isObjectValue && flatType?.metadata?.get("db.patch.strategy") === "merge") this.flattenPayload(value, key);
388
- else if (isObjectValue && flatType?.type.kind === "object" && !flatType.metadata?.has("db.json")) this._flattenReplaceObject(value, key, flatType);
387
+ else if (isObjectValue && this.collection.mergePaths.has(key)) this.flattenPayload(value, key);
388
+ else if (isObjectValue && storedObjectType(flatType) && !flatType.metadata?.has("db.json")) this._flattenReplaceObject(value, key, flatType);
389
389
  else if (key !== "_id") this._setLeaf(key, value, flatType);
390
390
  }
391
391
  return this.updatePipeline;
392
392
  }
393
393
  /**
394
- * Walk the schema's props for a replace-strategy nested object so omitted
395
- * optional children become explicit nulls (parity with SQL `column = NULL`).
396
- * Required-missing leaves are caught earlier by the strict validator.
394
+ * Walk the schema's props for a replace-strategy nested object (a `T | null`
395
+ * one included, `storedObjectType`) so omitted optional children become
396
+ * explicit nulls (parity with SQL `column = NULL`). Required-missing leaves
397
+ * are caught earlier by the strict validator.
397
398
  */
398
399
  _flattenReplaceObject(value, prefix, flatType) {
399
- const propsMap = flatType.type.props;
400
- for (const [propKey, propType] of propsMap) {
400
+ for (const [propKey, propType] of storedObjectType(flatType).type.props) {
401
401
  const childKey = `${prefix}.${propKey}`;
402
402
  const childValue = value[propKey];
403
403
  if (childValue === void 0) {
@@ -406,15 +406,17 @@ var CollectionPatcher = class {
406
406
  }
407
407
  const childIsObject = typeof childValue === "object" && childValue !== null && !Array.isArray(childValue);
408
408
  const propIsJson = propType.metadata?.has("db.json");
409
- const propIsMerge = propType.metadata?.get("db.patch.strategy") === "merge";
410
409
  const childFlatType = this.collection.flatMap.get(childKey);
411
410
  if (childIsObject && !propIsJson && childFlatType?.metadata?.get("db.__topLevelArray")) {
412
411
  this.parseArrayPatch(childKey, childValue, childFlatType);
413
412
  continue;
414
413
  }
415
- if (childIsObject && propType.type.kind === "object" && !propIsJson) {
416
- if (propIsMerge) this.flattenPayload(childValue, childKey);
417
- else this._flattenReplaceObject(childValue, childKey, propType);
414
+ if (childIsObject && this.collection.mergePaths.has(childKey)) {
415
+ this.flattenPayload(childValue, childKey);
416
+ continue;
417
+ }
418
+ if (childIsObject && storedObjectType(propType) && !propIsJson) {
419
+ this._flattenReplaceObject(childValue, childKey, propType);
418
420
  continue;
419
421
  }
420
422
  this._setLeaf(childKey, childValue, propType);
@@ -441,8 +443,8 @@ var CollectionPatcher = class {
441
443
  return;
442
444
  }
443
445
  this._remove(key, toRemove, keys, flatType);
444
- this._update(key, toUpdate, keys, flatType);
445
- this._upsert(key, toUpsert, keys, flatType);
446
+ this._update(key, toUpdate, keys);
447
+ this._upsert(key, toUpsert, keys);
446
448
  this._insert(key, toInsert, keys, flatType);
447
449
  }
448
450
  /**
@@ -544,13 +546,13 @@ var CollectionPatcher = class {
544
546
  * or append when none has it
545
547
  * - key-less → append unless an equal element is stored
546
548
  */
547
- _upsert(key, input, keys, flatType) {
549
+ _upsert(key, input, keys) {
548
550
  if (!input?.length) return;
549
551
  if (keys.length === 0) {
550
552
  this._appendAbsent(key, input);
551
553
  return;
552
554
  }
553
- const mergeStrategy = flatType.metadata?.get("db.patch.strategy") === "merge";
555
+ const mergeStrategy = this.collection.mergePaths.has(key);
554
556
  this._appendUnless(key, input, this._keyStored(keys), { $map: {
555
557
  input: "$$value",
556
558
  as: "el",
@@ -568,9 +570,9 @@ var CollectionPatcher = class {
568
570
  * 0.1.180, as on every other adapter; before, the items were added to
569
571
  * the array as a set union)
570
572
  */
571
- _update(key, input, keys, flatType) {
573
+ _update(key, input, keys) {
572
574
  if (!input?.length || keys.length === 0) return;
573
- const mergeStrategy = flatType.metadata?.get("db.patch.strategy") === "merge";
575
+ const mergeStrategy = this.collection.mergePaths.has(key);
574
576
  this._set(key, { $reduce: {
575
577
  input: literal(input),
576
578
  initialValue: { $ifNull: [`$${key}`, []] },
@@ -1367,25 +1369,44 @@ function textRunOptions(plan, query) {
1367
1369
  defaultSort: RELEVANCE_SORT
1368
1370
  } : {};
1369
1371
  }
1372
+ /**
1373
+ * Field the `vectorSearchScore` rides in through the pipeline. Renamed to the
1374
+ * public `$score` after fetch — a field name cannot start with `$`.
1375
+ */
1376
+ const SCORE_FIELD = "__atscript_score";
1370
1377
  /** Vector search via $vectorSearch aggregation stage. */
1371
1378
  async function vectorSearchImpl(host, vector, query, indexName) {
1372
1379
  const controls = query.controls || {};
1373
1380
  const plan = buildVectorSearchPlan(host, vector, query, indexName);
1374
1381
  const threshold = resolveThreshold(host, controls, indexName);
1375
- return runSearchPipeline(host, plan.stage, query, "vectorSearch", {
1376
- threshold,
1382
+ return (await runSearchPipeline(host, plan.stage, query, "vectorSearch", {
1383
+ vector: { threshold },
1377
1384
  filterStages: plan.filterStages
1378
- });
1385
+ })).map((row) => renameComputed(row, SCORE_FIELD, "$score"));
1379
1386
  }
1380
1387
  /** Vector search with faceted count. */
1381
1388
  async function vectorSearchWithCountImpl(host, vector, query, indexName) {
1382
1389
  const controls = query.controls || {};
1383
1390
  const plan = buildVectorSearchPlan(host, vector, query, indexName);
1384
1391
  const threshold = resolveThreshold(host, controls, indexName);
1385
- return runSearchWithCountPipeline(host, plan.stage, query, "vectorSearchWithCount", {
1386
- threshold,
1392
+ const result = await runSearchWithCountPipeline(host, plan.stage, query, "vectorSearchWithCount", {
1393
+ vector: { threshold },
1387
1394
  filterStages: plan.filterStages
1388
1395
  });
1396
+ return {
1397
+ data: result.data.map((row) => renameComputed(row, SCORE_FIELD, "$score")),
1398
+ count: result.count
1399
+ };
1400
+ }
1401
+ /**
1402
+ * The stages right after `$vectorSearch`: its score into {@link SCORE_FIELD}
1403
+ * (the `$meta` is read here, ahead of any `$facet`) and, with a threshold,
1404
+ * the `$match` on it.
1405
+ */
1406
+ function vectorScoreStages(threshold) {
1407
+ const stages = [{ $addFields: { [SCORE_FIELD]: { $meta: "vectorSearchScore" } } }];
1408
+ if (threshold !== void 0) stages.push({ $match: { [SCORE_FIELD]: { $gte: threshold } } });
1409
+ return stages;
1389
1410
  }
1390
1411
  /**
1391
1412
  * Field name `$geoNear` writes the computed distance into. Renamed to the
@@ -1399,9 +1420,9 @@ async function geoSearchImpl(host, point, query, indexName) {
1399
1420
  const pipeline = buildGeoNearStages(host, point, query, indexName);
1400
1421
  if (controls.$skip) pipeline.push({ $skip: controls.$skip });
1401
1422
  pipeline.push({ $limit: controls.$limit || 1e3 });
1402
- pushGeoProjection(pipeline, query.controls);
1423
+ pushProjection(pipeline, query.controls, DISTANCE_FIELD);
1403
1424
  host._log("aggregate (geoSearch)", pipeline);
1404
- return (await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray())).map((row) => renameDistance(row));
1425
+ return (await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray())).map((row) => renameComputed(row, DISTANCE_FIELD, "$distance"));
1405
1426
  }
1406
1427
  /** Geo search with faceted count (rows within the distance window). */
1407
1428
  async function geoSearchWithCountImpl(host, point, query, indexName) {
@@ -1409,7 +1430,7 @@ async function geoSearchWithCountImpl(host, point, query, indexName) {
1409
1430
  const dataStages = [];
1410
1431
  if (controls.$skip) dataStages.push({ $skip: controls.$skip });
1411
1432
  if (controls.$limit) dataStages.push({ $limit: controls.$limit });
1412
- pushGeoProjection(dataStages, query.controls);
1433
+ pushProjection(dataStages, query.controls, DISTANCE_FIELD);
1413
1434
  const pipeline = [...buildGeoNearStages(host, point, query, indexName), { $facet: {
1414
1435
  data: dataStages,
1415
1436
  meta: [{ $count: "count" }]
@@ -1417,7 +1438,7 @@ async function geoSearchWithCountImpl(host, point, query, indexName) {
1417
1438
  host._log("aggregate (geoSearchWithCount)", pipeline);
1418
1439
  const result = await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray());
1419
1440
  return {
1420
- data: (result[0]?.data || []).map((row) => renameDistance(row)),
1441
+ data: (result[0]?.data || []).map((row) => renameComputed(row, DISTANCE_FIELD, "$distance")),
1421
1442
  count: result[0]?.meta?.[0]?.count || 0
1422
1443
  };
1423
1444
  }
@@ -1458,27 +1479,28 @@ function resolveGeoKeyPath(host, indexName) {
1458
1479
  return field;
1459
1480
  }
1460
1481
  /**
1461
- * Appends a `$project` stage, keeping the computed distance in inclusion mode.
1462
- * The distance key goes on a COPY: `asProjection` (and `dedupeProjection`)
1463
- * hand back the caller's own `$select` map when nothing needs rewriting — an
1464
- * object the caller may share across queries (moost-db memoizes, and in dev /
1465
- * test deep-freezes, the projection of a read without `$select`).
1482
+ * Appends the `$select` `$project` stage, keeping the computed field `keep`
1483
+ * (the geo distance, the vector score) in inclusion mode. That key goes on a
1484
+ * COPY: `asProjection` (and `dedupeProjection`) hand back the caller's own
1485
+ * `$select` map when nothing needs rewriting — an object the caller may share
1486
+ * across queries (moost-db memoizes, and in dev / test deep-freezes, the
1487
+ * projection of a read without `$select`).
1466
1488
  */
1467
- function pushGeoProjection(stages, controls) {
1489
+ function pushProjection(stages, controls, keep) {
1468
1490
  const projection = controls?.$select?.asProjection;
1469
1491
  if (!projection) return;
1470
1492
  const deduped = dedupeProjection(projection);
1471
- const isInclusion = Object.values(deduped).some((v) => v === 1);
1493
+ const isInclusion = keep !== void 0 && Object.values(deduped).some((v) => v === 1);
1472
1494
  stages.push({ $project: isInclusion ? {
1473
1495
  ...deduped,
1474
- [DISTANCE_FIELD]: 1
1496
+ [keep]: 1
1475
1497
  } : deduped });
1476
1498
  }
1477
- /** Renames the internal distance field to the public `$distance` pseudo-field. */
1478
- function renameDistance(row) {
1479
- if (DISTANCE_FIELD in row) {
1480
- row.$distance = row[DISTANCE_FIELD];
1481
- delete row[DISTANCE_FIELD];
1499
+ /** Renames an internal computed field to its public `$`-prefixed name (in place). */
1500
+ function renameComputed(row, field, name) {
1501
+ if (field in row) {
1502
+ row[name] = row[field];
1503
+ delete row[field];
1482
1504
  }
1483
1505
  return row;
1484
1506
  }
@@ -1774,13 +1796,11 @@ function buildVectorSearchStage(host, vector, indexName, limit, skip) {
1774
1796
  };
1775
1797
  }
1776
1798
  /** Runs a search/vector pipeline and returns results. Shared by search + vectorSearch. */
1777
- async function runSearchPipeline(host, stage, query, label, { threshold, classicText = false, defaultSort, filterStages } = {}) {
1799
+ async function runSearchPipeline(host, stage, query, label, { vector, classicText = false, defaultSort, filterStages } = {}) {
1778
1800
  const controls = query.controls || {};
1779
1801
  const pipeline = [stage];
1780
- if (threshold !== void 0) {
1781
- pipeline.push({ $addFields: { _score: { $meta: "vectorSearchScore" } } });
1782
- pipeline.push({ $match: { _score: { $gte: threshold } } });
1783
- } else if (classicText) pipeline.push({ $addFields: { _score: { $meta: "textScore" } } });
1802
+ if (vector) pipeline.push(...vectorScoreStages(vector.threshold));
1803
+ else if (classicText) pipeline.push({ $addFields: { _score: { $meta: "textScore" } } });
1784
1804
  pipeline.push(...filterStages ?? mongoFilterStages(query.filter, filterOptionsOf(host)));
1785
1805
  const { stages: sorted, cleanup } = sortStages(controls);
1786
1806
  if (sorted.length > 0) pipeline.push(...sorted);
@@ -1789,10 +1809,7 @@ async function runSearchPipeline(host, stage, query, label, { threshold, classic
1789
1809
  if (controls.$limit) pipeline.push({ $limit: controls.$limit });
1790
1810
  else pipeline.push({ $limit: 1e3 });
1791
1811
  if (cleanup) pipeline.push(cleanup);
1792
- if (controls.$select) {
1793
- const projection = controls.$select.asProjection;
1794
- if (projection) pipeline.push({ $project: dedupeProjection(projection) });
1795
- }
1812
+ pushProjection(pipeline, controls, vector ? SCORE_FIELD : void 0);
1796
1813
  host._log(`aggregate (${label})`, pipeline);
1797
1814
  return wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray());
1798
1815
  }
@@ -1806,22 +1823,17 @@ async function runSearchPipeline(host, stage, query, label, { threshold, classic
1806
1823
  * `count: total` — the same counts `$$SEARCH_META` reports), concurrently
1807
1824
  * outside a transaction.
1808
1825
  */
1809
- async function runSearchWithCountPipeline(host, stage, query, label, { threshold, classicText = false, defaultSort, filterStages } = {}) {
1826
+ async function runSearchWithCountPipeline(host, stage, query, label, { vector, classicText = false, defaultSort, filterStages } = {}) {
1810
1827
  const controls = query.controls || {};
1811
1828
  const preStages = [];
1812
- if (threshold !== void 0) {
1813
- preStages.push({ $addFields: { _score: { $meta: "vectorSearchScore" } } });
1814
- preStages.push({ $match: { _score: { $gte: threshold } } });
1815
- } else if (classicText) preStages.push({ $addFields: { _score: { $meta: "textScore" } } });
1829
+ if (vector) preStages.push(...vectorScoreStages(vector.threshold));
1830
+ else if (classicText) preStages.push({ $addFields: { _score: { $meta: "textScore" } } });
1816
1831
  const { stages: dataStages, cleanup } = sortStages(controls);
1817
1832
  if (dataStages.length === 0 && defaultSort) dataStages.push(defaultSort);
1818
1833
  if (controls.$skip) dataStages.push({ $skip: controls.$skip });
1819
1834
  if (controls.$limit) dataStages.push({ $limit: controls.$limit });
1820
1835
  if (cleanup) dataStages.push(cleanup);
1821
- if (controls.$select) {
1822
- const projection = controls.$select.asProjection;
1823
- if (projection) dataStages.push({ $project: dedupeProjection(projection) });
1824
- }
1836
+ pushProjection(dataStages, controls, vector ? SCORE_FIELD : void 0);
1825
1837
  const stages = filterStages ?? mongoFilterStages(query.filter, filterOptionsOf(host));
1826
1838
  if ("$search" in stage && preStages.length === 0 && stages.every(isNoopMatch)) return runSearchWithMeta(host, stage, dataStages, label);
1827
1839
  const pipeline = [
@@ -2595,8 +2607,8 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
2595
2607
  _hasExplicitId = false;
2596
2608
  /** Unique fields accumulated during onFieldScanned, returned via getMetadataOverrides. */
2597
2609
  _pendingUniqueFields = [];
2598
- /** {@link _patcherFlatMap}'s memo. */
2599
- _patcherFlatMapMemo;
2610
+ /** {@link _patcherMaps}' memo. */
2611
+ _patcherMapsMemo;
2600
2612
  constructor(db, client, options = {}) {
2601
2613
  super();
2602
2614
  this.db = db;
@@ -2912,7 +2924,7 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
2912
2924
  /** Returns the context object used by CollectionPatcher. */
2913
2925
  getPatcherContext() {
2914
2926
  return {
2915
- flatMap: this._patcherFlatMap(),
2927
+ ...this._patcherMaps(),
2916
2928
  prepareId: (id) => this.prepareIdFromIdType(id),
2917
2929
  createValidator: (opts) => this._table.createValidator(opts)
2918
2930
  };
@@ -2922,21 +2934,26 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
2922
2934
  * with `@db.column` names already applied (`translatePatchKeys`), so a
2923
2935
  * renamed union / `@db.json` field is found — and replaced, not merged —
2924
2936
  * under its stored name. Derived fields are left out (they map to their
2925
- * source's path). Built once per flat map.
2937
+ * source's path). The merge-strategy paths are keyed the same way. Built
2938
+ * once per flat map.
2926
2939
  */
2927
- _patcherFlatMap() {
2940
+ _patcherMaps() {
2928
2941
  const src = this._table.flatMap;
2929
- let memo = this._patcherFlatMapMemo;
2942
+ let memo = this._patcherMapsMemo;
2930
2943
  if (memo?.src !== src) {
2931
2944
  const meta = this._table.getMetadata();
2932
2945
  const map = /* @__PURE__ */ new Map();
2933
2946
  for (const [path, type] of src) if (!meta.derivedFields.has(path)) map.set(meta.documentPath(path), type);
2934
- memo = this._patcherFlatMapMemo = {
2947
+ const mergePaths = new Set([...meta.mergePaths].map((path) => meta.documentPath(path)));
2948
+ memo = this._patcherMapsMemo = {
2935
2949
  src,
2936
- map
2950
+ maps: {
2951
+ flatMap: map,
2952
+ mergePaths
2953
+ }
2937
2954
  };
2938
2955
  }
2939
- return memo.map;
2956
+ return memo.maps;
2940
2957
  }
2941
2958
  async nativePatch(filter, patch, ops, expectedVersion, opts) {
2942
2959
  const mongoFilter = await this._buildCasFilter(filter, expectedVersion, "nativePatch");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/db-mongo",
3
- "version": "0.1.182",
3
+ "version": "0.1.184",
4
4
  "description": "Mongodb plugin for atscript.",
5
5
  "keywords": [
6
6
  "atscript",
@@ -58,7 +58,7 @@
58
58
  "@atscript/typescript": "^0.2.13",
59
59
  "@uniqu/core": "^0.2.2",
60
60
  "mongodb": "^6.17.0",
61
- "@atscript/db": "^0.1.182"
61
+ "@atscript/db": "^0.1.184"
62
62
  },
63
63
  "scripts": {
64
64
  "build": "vp pack",