dynamo-bao 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,6 +24,7 @@ DynamoBao is the tool I wish I had when I started.
24
24
  - Return total read/write consumed capacity (even when multiple operations were performed)
25
25
  - Request-scoped capacity aggregation for usage metering and billing
26
26
  - Easily iterate over all items in a model for batch processing or migrations
27
+ - Declarative substring search across iterable models with parallel cross-bucket fan-out (`searchAll`/`searchBucket`)
27
28
  - ESM (ECMAScript Modules) support for modern JavaScript projects
28
29
  - StringSetField for storing sets of strings with efficient diffing on save
29
30
 
@@ -319,7 +320,7 @@ app.use(async (req, res, next) => {
319
320
 
320
321
  DynamoBao makes it easy to iterate over all items in a model, which is useful for tasks like data migration, backfills, or reporting.
321
322
 
322
- By default, all models are created with `iterable: true`. This automatically sets up a dedicated index that allows you to use the `iterateAll()` method on the model class.
323
+ Iteration is **opt-in** — set `iterable: true` in the model's YAML to enable the dedicated index that backs `iterateAll()`. Iteration adds one GSI write per row mutation, so leaving it off is the safer default; turn it on when you actually need to scan the model.
323
324
 
324
325
  #### Basic Usage
325
326
 
@@ -410,15 +411,15 @@ This convenience comes at a cost: every `create`, `update`, or `delete` operatio
410
411
 
411
412
  To prevent "hot partitions" on large models, the iteration index is automatically split into 10 "buckets" or partitions. The `iterateAll()` method handles fetching from all buckets seamlessly.
412
413
 
413
- **Opting Out**
414
+ **Default**
414
415
 
415
- For high-volume, write-heavy models where you know you will never need to iterate (e.g., logging tables), you can disable this feature to save costs:
416
+ `iterable` defaults to `false`. To opt in, set it explicitly in the YAML — high-volume models like logging tables can leave it off; models you'll need to scan should set `iterable: true`:
416
417
 
417
418
  ```yaml
418
419
  models:
419
420
  AnalyticsEvent:
420
421
  modelPrefix: "ae"
421
- iterable: false # Disabling iteration for this write-heavy model
422
+ # iterable defaults to false — leave it off for write-heavy logs
422
423
  fields:
423
424
  # ...
424
425
  ```
@@ -119,9 +119,15 @@ function generateModelClass(
119
119
  .join("\n")
120
120
  : "";
121
121
 
122
- // Handle iteration configuration
122
+ // Handle iteration configuration. `??` (not `||`) so a deliberate 0
123
+ // from applyModelDefaults (non-iterable models get iterationBuckets=0)
124
+ // isn't silently bumped back to 100.
123
125
  const iterable = modelConfig.iterable === true;
124
- const iterationBuckets = modelConfig.iterationBuckets || 100;
126
+ const iterationBuckets =
127
+ modelConfig.iterationBuckets !== undefined &&
128
+ modelConfig.iterationBuckets !== null
129
+ ? modelConfig.iterationBuckets
130
+ : 100;
125
131
 
126
132
  // Handle searchable configuration. modelConfig.searchable is either `false`
127
133
  // or a fully-validated object (validated by applyModelDefaults in
@@ -10,8 +10,11 @@ const SEARCHABLE_KNOWN_OPTIONS = new Set([
10
10
  ]);
11
11
 
12
12
  function applyIterableDefaults(modelDef) {
13
+ // Default `iterable` to false. Iteration adds a per-row write to the
14
+ // iter_search_index GSI on every save, doubling write cost — opt-in is
15
+ // safer than opt-out. Mapping tables default to false either way.
13
16
  if (modelDef.iterable === undefined) {
14
- modelDef.iterable = modelDef.tableType !== "mapping";
17
+ modelDef.iterable = false;
15
18
  }
16
19
  if (modelDef.iterationBuckets === undefined) {
17
20
  modelDef.iterationBuckets = modelDef.iterable ? 10 : 0;
@@ -107,6 +110,22 @@ function applyModelDefaults(models) {
107
110
  for (const [modelName, modelDef] of Object.entries(models)) {
108
111
  applyIterableDefaults(modelDef);
109
112
  validateSearchable(modelName, modelDef);
113
+ // searchable on a non-iterable model is a supported combination
114
+ // (partition-scoped _searchText filtering), but searchAll/searchBucket
115
+ // require iteration buckets and will throw at runtime. Warn so users
116
+ // who forgot to opt into iteration find out at codegen, not in prod.
117
+ if (
118
+ modelDef.searchable &&
119
+ typeof modelDef.searchable === "object" &&
120
+ !modelDef.iterable
121
+ ) {
122
+ console.warn(
123
+ `[dynamo-bao] Model "${modelName}" has \`searchable\` configured but ` +
124
+ `\`iterable\` is false. _searchText will populate and filter on it ` +
125
+ `via the standard query API works, but searchAll/searchBucket will ` +
126
+ `throw. Set \`iterable: true\` to enable cross-bucket parallel search.`,
127
+ );
128
+ }
110
129
  }
111
130
  return models;
112
131
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dynamo-bao",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
6
  "exports": {
@@ -1,5 +1,29 @@
1
1
  const { defaultLogger: logger } = require("./utils/logger");
2
2
  const { QueryError, ValidationError } = require("./exceptions");
3
+ const { SEARCH_TEXT_FIELD } = require("./constants");
4
+
5
+ // System fields that don't appear in `model.fields` but are still allowed
6
+ // targets for FilterExpressions. _searchText is the auto-populated search
7
+ // column on `searchable` models — see src/utils/search-text.js. The values
8
+ // here describe how to convert the user-supplied filter value into the
9
+ // shape stored on the row, since system fields don't have a Field instance
10
+ // with `.toDy()` to do that for us.
11
+ const SYSTEM_FILTERABLE_FIELDS = {
12
+ [SEARCH_TEXT_FIELD]: {
13
+ convertValue(value, model) {
14
+ // Mirror the write-time normalization so user input matches what's
15
+ // stored. `normalizeSearchTerm` is idempotent so callers who already
16
+ // normalized the value pay no penalty for re-running it. Falls back
17
+ // to a plain String() when the model has no searchConfig (e.g. the
18
+ // model is non-searchable but its rows happen to carry the attribute).
19
+ if (model.searchConfig) {
20
+ const { normalizeSearchTerm } = require("./utils/search-text");
21
+ return normalizeSearchTerm(String(value), model.searchConfig);
22
+ }
23
+ return String(value);
24
+ },
25
+ },
26
+ };
3
27
 
4
28
  /**
5
29
  * Supporting class for building DynamoDB filter expressions.
@@ -34,6 +58,10 @@ class FilterExpressionBuilder {
34
58
 
35
59
  // Simplified value conversion - let the field handle it
36
60
  convertValue(value, model, fieldName) {
61
+ const systemField = SYSTEM_FILTERABLE_FIELDS[fieldName];
62
+ if (systemField) {
63
+ return systemField.convertValue(value, model);
64
+ }
37
65
  const field = model.fields[fieldName];
38
66
  return field.toDy(value);
39
67
  }
@@ -65,7 +93,12 @@ class FilterExpressionBuilder {
65
93
  if (!Array.isArray(value)) {
66
94
  throw new ValidationError("$in operator requires an array value");
67
95
  }
68
- const valueKeys = value.map((v) => this.generateValue(v));
96
+ // Run each element through convertValue (same as $eq does) so
97
+ // system fields like _searchText auto-normalize their values and
98
+ // user fields with meaningful toDy() (dates, etc.) get coerced.
99
+ const valueKeys = value.map((v) =>
100
+ this.generateValue(this.convertValue(v, model, fieldName)),
101
+ );
69
102
  return `${nameKey} IN (${valueKeys.join(", ")})`;
70
103
  case "$exists":
71
104
  if (typeof value !== "boolean") {
@@ -262,10 +295,17 @@ class FilterExpressionBuilder {
262
295
  continue;
263
296
  }
264
297
 
265
- // Validate field exists in model
266
- const field = model.fields[key];
267
- if (!field) {
268
- throw new QueryError(`Unknown field in filter: ${key}`);
298
+ // Allow whitelisted system fields (e.g., _searchText) without
299
+ // requiring a matching entry in model.fields. Operator validation
300
+ // below still runs so bad operators are rejected the same way.
301
+ const isSystemField = !!SYSTEM_FILTERABLE_FIELDS[key];
302
+
303
+ if (!isSystemField) {
304
+ // Validate field exists in model
305
+ const field = model.fields[key];
306
+ if (!field) {
307
+ throw new QueryError(`Unknown field in filter: ${key}`);
308
+ }
269
309
  }
270
310
 
271
311
  // Recursively validate nested conditions
package/src/model.js CHANGED
@@ -298,63 +298,329 @@ class BaoModel {
298
298
  }
299
299
  }
300
300
 
301
- static async *searchAll(terms, options = {}) {
301
+ /**
302
+ * @description
303
+ * Search a `searchable: { fields: [...] }`-configured iterable model by
304
+ * substring(s) of `_searchText`. Each term becomes one
305
+ * `contains(_searchText, :term)` predicate. Multiple terms are combined
306
+ * with `$and` (default) or `$or`. Each term is normalized with the same
307
+ * rules used to build `_searchText` at write time, so user input matches
308
+ * what's stored.
309
+ *
310
+ * Reads from the bucketed `iter_search_index` GSI. By default fans out
311
+ * across every bucket in parallel; sequential mode is available via
312
+ * `parallel: false`. Returns one page of results plus an opaque cursor
313
+ * for resumption. To paginate, pass the cursor back on subsequent calls;
314
+ * `cursor === null` indicates the search is exhausted.
315
+ *
316
+ * @param {string[]} terms - One or more substring terms. Empty/whitespace
317
+ * terms are dropped; throws if zero usable terms remain after
318
+ * normalization.
319
+ * @param {Object} [options]
320
+ * @param {('$and'|'$or')} [options.operator='$and'] - How multi-term queries
321
+ * are combined.
322
+ * @param {number} [options.batchSize=100] - DynamoDB Query Limit per page.
323
+ * Each Query examines up to this many items before applying
324
+ * FilterExpression.
325
+ * @param {number} [options.limit=100] - Maximum total items returned by
326
+ * this call. Pass `Infinity` to opt out (caller is responsible for
327
+ * ensuring the call doesn't exhaust capacity).
328
+ * @param {number} [options.maxQueriesPerBucket=50] - Per-bucket cap on
329
+ * DynamoDB Query roundtrips per call. Bounds worst-case capacity for
330
+ * sparse-match searches. When hit, the call returns whatever it found
331
+ * plus a non-null cursor pointing at the next page.
332
+ * @param {boolean} [options.parallel=true] - When true, all unexhausted
333
+ * buckets are queried concurrently in rounds; results are interleaved.
334
+ * When false, buckets are walked sequentially in order.
335
+ * @param {string|null} [options.cursor=null] - Opaque cursor from a
336
+ * previous call. Pass to resume; omit (or pass `null`) for a fresh
337
+ * search. Cursor is invalidated if `terms`, `operator`, or the model's
338
+ * `searchConfig` change.
339
+ * @param {Object} [options.filter] - Additional filter combined via AND
340
+ * with the search predicate. Must reference only attributes projected
341
+ * on `iter_search_index` (i.e., `_searchText` and the index/base keys).
342
+ * @returns {Promise<{items: BaoModel[], cursor: string|null}>} `items` is
343
+ * never longer than `limit`. `cursor` is `null` when the search is
344
+ * fully exhausted; otherwise pass it back to get the next page.
345
+ * @throws {Error} If the model is not `searchable`, not `iterable`, the
346
+ * resolved iteration index is not `iter_search_index`, `limit` is
347
+ * invalid, the cursor is malformed, or the cursor was generated for a
348
+ * different query.
349
+ * @example
350
+ * // First page
351
+ * const { items, cursor } = await Post.searchAll(["alice"], { limit: 50 });
352
+ * // "Load more"
353
+ * const next = await Post.searchAll(["alice"], { limit: 50, cursor });
354
+ * // Drain everything
355
+ * let cur = null, all = [];
356
+ * do {
357
+ * const page = await Post.searchAll(["alice"], { limit: 100, cursor: cur });
358
+ * all.push(...page.items);
359
+ * cur = page.cursor;
360
+ * } while (cur);
361
+ */
362
+ static async searchAll(terms, options = {}) {
302
363
  this._assertSearchable();
364
+ return this._searchPaged({
365
+ terms,
366
+ options,
367
+ activeBucketIndices: Array.from(
368
+ { length: this.iterationBuckets },
369
+ (_, b) => b,
370
+ ),
371
+ });
372
+ }
373
+
374
+ /**
375
+ * @description
376
+ * Search a single iteration bucket. Same predicate semantics and return
377
+ * shape as {@link BaoModel.searchAll}, but scoped to one bucket. Useful
378
+ * for partitioned workers (each handles a subset of buckets).
379
+ *
380
+ * @param {number} bucketNum - Bucket index, in `[0, iterationBuckets)`.
381
+ * @param {string[]} terms - Substring terms (see `searchAll`).
382
+ * @param {Object} [options] - Same options as `searchAll` (cursor scoped
383
+ * to this bucket).
384
+ * @returns {Promise<{items: BaoModel[], cursor: string|null}>}
385
+ * @throws {Error} On invalid bucket number, non-searchable model, etc.
386
+ */
387
+ static async searchBucket(bucketNum, terms, options = {}) {
388
+ this._assertSearchable();
389
+ if (
390
+ !Number.isInteger(bucketNum) ||
391
+ bucketNum < 0 ||
392
+ bucketNum >= this.iterationBuckets
393
+ ) {
394
+ throw new Error(
395
+ `Invalid bucket number ${bucketNum}. Must be 0-${this.iterationBuckets - 1}`,
396
+ );
397
+ }
398
+ return this._searchPaged({
399
+ terms,
400
+ options,
401
+ activeBucketIndices: [bucketNum],
402
+ });
403
+ }
404
+
405
+ /**
406
+ * @private
407
+ * Shared paged-search engine for searchAll and searchBucket. Honors the
408
+ * `parallel`, `limit`, `maxQueriesPerBucket`, and `cursor` options;
409
+ * returns `{ items, cursor }` with `cursor === null` on exhaustion.
410
+ */
411
+ static async _searchPaged({ terms, options, activeBucketIndices }) {
303
412
  const {
304
413
  buildSearchPredicate,
414
+ validateLimit,
415
+ predicateHash,
416
+ encodeCursor,
417
+ decodeCursor,
305
418
  } = require("./utils/search-text");
306
- const { operator = "$and", batchSize = 100, filter = null } = options;
419
+
420
+ const {
421
+ operator = "$and",
422
+ batchSize = 100,
423
+ filter = null,
424
+ limit = 100,
425
+ maxQueriesPerBucket = 50,
426
+ parallel = true,
427
+ cursor: incomingCursor = null,
428
+ } = options;
429
+
430
+ validateLimit(limit);
431
+ if (
432
+ !Number.isInteger(maxQueriesPerBucket) ||
433
+ maxQueriesPerBucket < 1
434
+ ) {
435
+ throw new Error(
436
+ "maxQueriesPerBucket must be a positive integer.",
437
+ );
438
+ }
439
+
307
440
  const searchPredicate = buildSearchPredicate(terms, this.searchConfig, {
308
441
  operator,
309
442
  });
443
+ const expectedHash = predicateHash(terms, operator, this.searchConfig);
444
+ // Tenant is baked into iter_pk values stashed in bucketCursors, so a
445
+ // cursor from one tenant can't safely be resumed under another. Capture
446
+ // the current tenant for write-side; validate on resume below.
447
+ const currentTenantId = this.manager.getTenantId() || null;
448
+
449
+ // Decode the cursor or initialize per-bucket state for a fresh call.
450
+ // bucketCursors maps bucketIdx -> lek (or null for "start of bucket").
451
+ // pendingItemKeys is the over-pull from a previous parallel round.
452
+ let bucketCursors;
453
+ let pendingItemKeys = [];
454
+ if (incomingCursor) {
455
+ const decoded = decodeCursor(incomingCursor);
456
+ if (decoded.predicateHash !== expectedHash) {
457
+ throw new Error(
458
+ `Cursor was generated for a different query (terms/operator/searchConfig changed). Start a new search.`,
459
+ );
460
+ }
461
+ if (decoded.modelPrefix !== this.modelPrefix) {
462
+ throw new Error(
463
+ `Cursor was generated for model "${decoded.modelPrefix}", not "${this.modelPrefix}".`,
464
+ );
465
+ }
466
+ // Cross-tenant cursor reuse would Query under tenant B with a
467
+ // tenant-A iter_pk in ExclusiveStartKey — DynamoDB rejects with an
468
+ // opaque ValidationException. Surface a clear error first.
469
+ if (decoded.tenantId !== currentTenantId) {
470
+ throw new Error(
471
+ `Cursor was generated under tenant "${decoded.tenantId || "(none)"}", ` +
472
+ `not "${currentTenantId || "(none)"}". Cursors are tenant-scoped.`,
473
+ );
474
+ }
475
+ // Cursors are scoped to the bucket set used to generate them, so a
476
+ // searchAll cursor can't be passed into searchBucket(N) (and vice
477
+ // versa) without silently mixing items across scopes via
478
+ // pendingItemKeys. Reject mismatch with a clear message.
479
+ const decodedScope = (decoded.scope || []).slice().sort((a, b) => a - b);
480
+ const expectedScope = activeBucketIndices.slice().sort((a, b) => a - b);
481
+ const scopesMatch =
482
+ decodedScope.length === expectedScope.length &&
483
+ decodedScope.every((s, i) => s === expectedScope[i]);
484
+ if (!scopesMatch) {
485
+ throw new Error(
486
+ `Cursor scope mismatch. Cursor was generated for buckets ` +
487
+ `[${decodedScope.join(", ")}], but this call covers ` +
488
+ `[${expectedScope.join(", ")}]. Resume the cursor with the same ` +
489
+ `API call (searchAll or searchBucket) that produced it.`,
490
+ );
491
+ }
492
+ bucketCursors = { ...decoded.bucketCursors };
493
+ pendingItemKeys = decoded.pendingItemKeys || [];
494
+ } else {
495
+ bucketCursors = {};
496
+ for (const b of activeBucketIndices) bucketCursors[b] = null;
497
+ }
310
498
 
311
- if (this.iterationBuckets === 1) {
312
- yield* this._iterateSingleBucket(null, {
499
+ const items = [];
500
+
501
+ // Phase 1: drain pending items from a prior over-pull. Hydrate via
502
+ // batchFind (current row state — deletions surface as missing items).
503
+ // Preserve insertion order from the original pendingItemKeys list so
504
+ // the user sees a deterministic page-to-page sequence.
505
+ if (pendingItemKeys.length > 0) {
506
+ const { items: found } = await this.batchFind(pendingItemKeys);
507
+ for (const k of pendingItemKeys) {
508
+ if (found[k]) items.push(found[k]);
509
+ }
510
+ }
511
+
512
+ const queriesByBucket = {};
513
+ for (const b of Object.keys(bucketCursors)) queriesByBucket[b] = 0;
514
+
515
+ // Collapse the iterationBuckets===1 case: PK shape uses null bucketArg,
516
+ // but we still index state by 0 internally for consistency.
517
+ const bucketArg = (b) => (this.iterationBuckets === 1 ? null : b);
518
+
519
+ const pullPage = async (bucketIdx) => {
520
+ const lek = bucketCursors[bucketIdx];
521
+ queriesByBucket[bucketIdx] = (queriesByBucket[bucketIdx] || 0) + 1;
522
+ const page = await this._searchSingleBucketPage(bucketArg(bucketIdx), {
313
523
  batchSize,
314
524
  filter,
315
525
  searchPredicate,
526
+ exclusiveStartKey: lek || null,
316
527
  });
528
+ if (page.lek) bucketCursors[bucketIdx] = page.lek;
529
+ else delete bucketCursors[bucketIdx]; // exhausted
530
+ return page.items;
531
+ };
532
+
533
+ const eligibleBuckets = () =>
534
+ Object.keys(bucketCursors)
535
+ .map((b) => parseInt(b, 10))
536
+ .filter((b) => (queriesByBucket[b] || 0) < maxQueriesPerBucket)
537
+ .sort((a, b) => a - b);
538
+
539
+ if (parallel) {
540
+ while (items.length < limit && eligibleBuckets().length > 0) {
541
+ const round = eligibleBuckets();
542
+ const pages = await Promise.all(round.map(pullPage));
543
+ for (const pageItems of pages) items.push(...pageItems);
544
+ }
317
545
  } else {
318
- for (let bucket = 0; bucket < this.iterationBuckets; bucket++) {
319
- yield* this._iterateSingleBucket(bucket, {
320
- batchSize,
321
- filter,
322
- searchPredicate,
323
- });
546
+ // Sequential: walk eligible buckets in order, pulling pages until
547
+ // exhausted / per-bucket cap / global limit hit.
548
+ for (const bucket of eligibleBuckets()) {
549
+ while (
550
+ bucketCursors[bucket] !== undefined &&
551
+ (queriesByBucket[bucket] || 0) < maxQueriesPerBucket &&
552
+ items.length < limit
553
+ ) {
554
+ const pageItems = await pullPage(bucket);
555
+ items.push(...pageItems);
556
+ }
557
+ if (items.length >= limit) break;
324
558
  }
325
559
  }
326
- }
327
560
 
328
- static async *searchBucket(bucketNum, terms, options = {}) {
329
- this._assertSearchable();
330
- if (bucketNum < 0 || bucketNum >= this.iterationBuckets) {
331
- throw new Error(
332
- `Invalid bucket number ${bucketNum}. Must be 0-${this.iterationBuckets - 1}`,
333
- );
561
+ // Slice to limit; over-pull at the boundary gets stashed in the cursor
562
+ // as pendingItemKeys for the next call to return first. Both modes can
563
+ // over-pull: parallel mode by up to (active buckets - 1) × batchSize,
564
+ // sequential mode by up to one batchSize (its loop guard is at the top
565
+ // so the page that pushes us past `limit` is fully kept).
566
+ let kept = items;
567
+ let overflowKeys = [];
568
+ if (items.length > limit) {
569
+ kept = items.slice(0, limit);
570
+ overflowKeys = items
571
+ .slice(limit)
572
+ .map((m) => m.getPrimaryId());
334
573
  }
335
- const {
336
- buildSearchPredicate,
337
- } = require("./utils/search-text");
338
- const { operator = "$and", batchSize = 100, filter = null } = options;
339
- const searchPredicate = buildSearchPredicate(terms, this.searchConfig, {
340
- operator,
341
- });
342
- yield* this._iterateSingleBucket(bucketNum, {
343
- batchSize,
344
- filter,
345
- searchPredicate,
346
- });
574
+
575
+ const bucketsRemaining = Object.keys(bucketCursors).length > 0;
576
+ const hasMore = bucketsRemaining || overflowKeys.length > 0;
577
+ const cursorOut = hasMore
578
+ ? encodeCursor({
579
+ bucketCursors,
580
+ predicateHash: expectedHash,
581
+ modelPrefix: this.modelPrefix,
582
+ scope: activeBucketIndices,
583
+ tenantId: currentTenantId,
584
+ pendingItemKeys: overflowKeys,
585
+ })
586
+ : null;
587
+
588
+ return { items: kept, cursor: cursorOut };
347
589
  }
348
590
 
591
+ /**
592
+ * @description
593
+ * Split a free-form query string into an array of terms suitable for
594
+ * passing to {@link BaoModel.searchAll}. Whitespace separates terms;
595
+ * double-quoted phrases are kept together as a single term.
596
+ *
597
+ * @param {string} queryString - Raw user input.
598
+ * @returns {string[]} Array of terms (possibly empty).
599
+ * @example
600
+ * Post.tokenizeSearchQuery('"hello world" foo');
601
+ * // => ["hello world", "foo"]
602
+ */
349
603
  static tokenizeSearchQuery(queryString) {
350
604
  const { tokenizeSearchQuery } = require("./utils/search-text");
351
605
  return tokenizeSearchQuery(queryString);
352
606
  }
353
607
 
354
- // Normalize a single search term using the same rules the model used to
355
- // build `_searchText`. Useful when post-filtering hydrated rows in JS:
356
- // const term = Post.normalizeSearchTerm(userInput);
357
- // results.filter(p => p._dyData._searchText?.includes(term));
608
+ /**
609
+ * @description
610
+ * Normalize a single search term using the same rules the model used to
611
+ * build `_searchText` at write time: lowercase (unless
612
+ * `caseSensitive: true`), strip punctuation, collapse whitespace. Useful
613
+ * when post-filtering hydrated rows in JS, or when manually constructing
614
+ * a `_searchText` filter against a model that has no `searchConfig`.
615
+ *
616
+ * Idempotent — calling multiple times returns the same result.
617
+ *
618
+ * @param {string} term - Raw user input.
619
+ * @returns {string} Normalized term.
620
+ * @example
621
+ * const term = Post.normalizeSearchTerm("Hello, World!"); // "hello world"
622
+ * results.filter((p) => p._dyData._searchText?.includes(term));
623
+ */
358
624
  static normalizeSearchTerm(term) {
359
625
  const { normalizeSearchTerm } = require("./utils/search-text");
360
626
  return normalizeSearchTerm(term, this.searchConfig || {});
@@ -415,6 +681,130 @@ class BaoModel {
415
681
  : `${this.modelPrefix}#iter#${bucket}`;
416
682
  }
417
683
 
684
+ /**
685
+ * @private
686
+ * Send a Query against the iteration GSI, translating DynamoDB's
687
+ * "missing index" ValidationException into a friendlier error pointing
688
+ * at `bao-update-table`. Single source of truth for both the streaming
689
+ * `_iterateSingleBucket` and the paged `_searchSingleBucketPage` paths
690
+ * — keeping the translation in one place prevents the two from drifting.
691
+ *
692
+ * @param {Object} params - Full QueryCommand input.
693
+ * @param {string} indexName - The expected index (used in the error
694
+ * message; pre-resolved by callers via getIterationIndexName()).
695
+ * @returns {Promise<Object>} The raw QueryCommand response.
696
+ */
697
+ static async _runIterationQuery(params, indexName) {
698
+ const { QueryCommand } = require("./dynamodb-client");
699
+ try {
700
+ return await this.documentClient.send(new QueryCommand(params));
701
+ } catch (error) {
702
+ // DynamoDB reports a missing index as a ValidationException with a
703
+ // message like "The table does not have the specified index: <name>".
704
+ // We only translate when the message explicitly references an index
705
+ // — translating raw ResourceNotFoundException would mask a missing
706
+ // *table* with a "run bao-update-table" hint that wouldn't help.
707
+ const message = error.message || "";
708
+ const isMissingIndex =
709
+ /does not have the specified index/i.test(message) ||
710
+ message.includes(`specified index: ${indexName}`) ||
711
+ (error.name === "ResourceNotFoundException" &&
712
+ message.toLowerCase().includes("index"));
713
+ if (isMissingIndex) {
714
+ throw new Error(
715
+ `Index '${indexName}' is missing on table '${this.table}'. ` +
716
+ `Run 'bao-update-table' to add it.`,
717
+ );
718
+ }
719
+ throw error;
720
+ }
721
+ }
722
+
723
+ /**
724
+ * @private
725
+ * Single Query roundtrip against the iter_search_index for one bucket.
726
+ * Returns hydrated items + lastEvaluatedKey. Used by the paged
727
+ * searchAll/searchBucket implementation that needs explicit page-by-page
728
+ * control (instead of the do/while loop in _iterateSingleBucket).
729
+ *
730
+ * @param {number|null} bucketNum - Bucket index, or `null` for single-bucket models.
731
+ * @param {Object} options
732
+ * @param {number} options.batchSize - DynamoDB Query Limit.
733
+ * @param {Object} [options.filter] - User filter.
734
+ * @param {Object} [options.searchPredicate] - Predicate from buildSearchPredicate.
735
+ * @param {Object} [options.exclusiveStartKey] - DynamoDB LEK to resume from.
736
+ * @returns {Promise<{items: BaoModel[], lek: Object|null}>}
737
+ */
738
+ static async _searchSingleBucketPage(bucketNum, options = {}) {
739
+ const {
740
+ batchSize = 100,
741
+ filter = null,
742
+ searchPredicate = null,
743
+ exclusiveStartKey = null,
744
+ } = options;
745
+ const iterPk = this._getIterationPk(bucketNum);
746
+ const indexName = this.manager.getIterationIndexName();
747
+
748
+ const params = {
749
+ TableName: this.table,
750
+ IndexName: indexName,
751
+ KeyConditionExpression: "#pk = :pk",
752
+ ExpressionAttributeNames: { "#pk": ITERATION_PK_FIELD },
753
+ ExpressionAttributeValues: { ":pk": iterPk },
754
+ Limit: batchSize,
755
+ ReturnConsumedCapacity: "TOTAL",
756
+ };
757
+ if (exclusiveStartKey) params.ExclusiveStartKey = exclusiveStartKey;
758
+
759
+ const filterParts = [];
760
+ if (filter) {
761
+ const { FilterExpressionBuilder } = require("./filter-expression");
762
+ const filterBuilder = new FilterExpressionBuilder();
763
+ const filterExpression = filterBuilder.build(filter, this);
764
+ if (filterExpression) {
765
+ this._assertFilterFitsIterIndex(
766
+ indexName,
767
+ filterExpression.ExpressionAttributeNames,
768
+ );
769
+ filterParts.push(filterExpression.FilterExpression);
770
+ Object.assign(
771
+ params.ExpressionAttributeNames,
772
+ filterExpression.ExpressionAttributeNames,
773
+ );
774
+ Object.assign(
775
+ params.ExpressionAttributeValues,
776
+ filterExpression.ExpressionAttributeValues,
777
+ );
778
+ }
779
+ }
780
+ if (searchPredicate) {
781
+ filterParts.push(searchPredicate.FilterExpression);
782
+ Object.assign(
783
+ params.ExpressionAttributeNames,
784
+ searchPredicate.ExpressionAttributeNames,
785
+ );
786
+ Object.assign(
787
+ params.ExpressionAttributeValues,
788
+ searchPredicate.ExpressionAttributeValues,
789
+ );
790
+ }
791
+ if (filterParts.length > 0) {
792
+ params.FilterExpression = filterParts
793
+ .map((p) => `(${p})`)
794
+ .join(" AND ");
795
+ }
796
+
797
+ const response = await this._runIterationQuery(params, indexName);
798
+
799
+ let items = [];
800
+ if (response.Items && response.Items.length > 0) {
801
+ const objectIds = response.Items.map((item) => item[ITERATION_SK_FIELD]);
802
+ const { items: found } = await this.batchFind(objectIds);
803
+ items = Object.values(found);
804
+ }
805
+ return { items, lek: response.LastEvaluatedKey || null };
806
+ }
807
+
418
808
  static async *_iterateSingleBucket(bucketNum, options = {}) {
419
809
  const { batchSize = 100, filter = null, searchPredicate = null } = options;
420
810
  const iterPk = this._getIterationPk(bucketNum);
@@ -423,7 +813,6 @@ class BaoModel {
423
813
  let lastEvaluatedKey = null;
424
814
 
425
815
  do {
426
- const { QueryCommand } = require("./dynamodb-client");
427
816
  const params = {
428
817
  TableName: this.table,
429
818
  IndexName: indexName,
@@ -478,29 +867,7 @@ class BaoModel {
478
867
  params.FilterExpression = filterParts.map((p) => `(${p})`).join(" AND ");
479
868
  }
480
869
 
481
- let response;
482
- try {
483
- response = await this.documentClient.send(new QueryCommand(params));
484
- } catch (error) {
485
- // DynamoDB reports a missing index as a ValidationException with a
486
- // message like "The table does not have the specified index: <name>".
487
- // We only translate when the message explicitly references an index
488
- // — translating raw ResourceNotFoundException would mask a missing
489
- // *table* with a "run bao-update-table" hint that wouldn't help.
490
- const message = error.message || "";
491
- const isMissingIndex =
492
- /does not have the specified index/i.test(message) ||
493
- message.includes(`specified index: ${indexName}`) ||
494
- (error.name === "ResourceNotFoundException" &&
495
- message.toLowerCase().includes("index"));
496
- if (isMissingIndex) {
497
- throw new Error(
498
- `Index '${indexName}' is missing on table '${this.table}'. ` +
499
- `Run 'bao-update-table' to add it.`,
500
- );
501
- }
502
- throw error;
503
- }
870
+ const response = await this._runIterationQuery(params, indexName);
504
871
 
505
872
  if (response.Items && response.Items.length > 0) {
506
873
  const objectIds = response.Items.map(
@@ -166,10 +166,16 @@ function buildSearchPredicate(terms, searchConfig, options = {}) {
166
166
  );
167
167
  }
168
168
 
169
+ // Mirror the write-side filter: terms shorter than minTermLength are
170
+ // dropped from the predicate so the user can't silently get zero matches
171
+ // by querying for a term the index doesn't store. Length is counted in
172
+ // Unicode code points to match buildSearchText's [...tok].length check.
173
+ const minTermLength =
174
+ (searchConfig && searchConfig.minTermLength) || 1;
169
175
  const normalized = [];
170
176
  for (const t of terms) {
171
177
  const n = normalizeSearchTerm(t, searchConfig || {});
172
- if (n) normalized.push(n);
178
+ if (n && [...n].length >= minTermLength) normalized.push(n);
173
179
  }
174
180
  if (normalized.length === 0) {
175
181
  throw new Error("searchAll requires at least one non-empty term.");
@@ -197,10 +203,217 @@ function buildSearchPredicate(terms, searchConfig, options = {}) {
197
203
  };
198
204
  }
199
205
 
206
+ // Validate a `limit` option value. Accepts positive integers and Infinity.
207
+ // Anything else throws — saves the caller from passing 0 or a float and
208
+ // silently getting weird behavior downstream.
209
+ function validateLimit(limit) {
210
+ if (limit === Infinity) return;
211
+ if (
212
+ typeof limit !== "number" ||
213
+ Number.isNaN(limit) ||
214
+ !Number.isInteger(limit) ||
215
+ limit < 1
216
+ ) {
217
+ throw new Error("limit must be a positive integer or Infinity.");
218
+ }
219
+ }
220
+
221
+ // Take an async iterable of arrays (batches) and re-yield them, capping the
222
+ // total flattened item count at `limit`. The last batch yielded is sliced to
223
+ // fit so the consumer never sees more than `limit` items in total. Stops
224
+ // pulling from the source once the cap is hit, so a generator-backed source
225
+ // is suspended (no further DynamoDB Query calls, no further bucket scans).
226
+ async function* applyLimit(asyncIterable, limit) {
227
+ if (limit === Infinity) {
228
+ yield* asyncIterable;
229
+ return;
230
+ }
231
+ let yielded = 0;
232
+ for await (const batch of asyncIterable) {
233
+ const room = limit - yielded;
234
+ if (room <= 0) return;
235
+ if (batch.length === 0) {
236
+ yield batch;
237
+ continue;
238
+ }
239
+ if (batch.length <= room) {
240
+ yield batch;
241
+ yielded += batch.length;
242
+ if (yielded >= limit) return;
243
+ } else {
244
+ yield batch.slice(0, room);
245
+ return;
246
+ }
247
+ }
248
+ }
249
+
250
+ // Stable, deterministic hash of a search predicate. Used to invalidate a
251
+ // cursor if the caller resumes with different terms / operator / config —
252
+ // otherwise a continuation key from the old query would silently splice
253
+ // rows from a different result set into the new one. Not cryptographic;
254
+ // just a reliable equality check.
255
+ function predicateHash(terms, operator, searchConfig) {
256
+ const cfg = searchConfig || {};
257
+ const normalized = (terms || []).map((t) =>
258
+ normalizeSearchTerm(String(t), cfg),
259
+ );
260
+ const payload = JSON.stringify({
261
+ terms: normalized,
262
+ operator: operator || "$and",
263
+ caseSensitive: !!cfg.caseSensitive,
264
+ minTermLength: cfg.minTermLength || 1,
265
+ dedupe: !!cfg.dedupe,
266
+ });
267
+ // Simple FNV-1a 32-bit. Collisions are astronomically rare for our
268
+ // input space and we don't need cryptographic strength.
269
+ let h = 0x811c9dc5;
270
+ for (let i = 0; i < payload.length; i++) {
271
+ h ^= payload.charCodeAt(i);
272
+ h = Math.imul(h, 0x01000193);
273
+ }
274
+ return (h >>> 0).toString(36);
275
+ }
276
+
277
+ const CURSOR_REQUIRED_FIELDS = [
278
+ "bucketCursors",
279
+ "predicateHash",
280
+ "modelPrefix",
281
+ "scope",
282
+ "tenantId",
283
+ ];
284
+
285
+ // URL-safe base64 with manual character replacement so we don't depend on
286
+ // Node's "base64url" encoding token (Node 16+ only — README still claims
287
+ // 12.17.0+ as the floor). Manual form works on every Node version that
288
+ // supports Buffer.
289
+ function _toBase64url(utf8) {
290
+ return Buffer.from(utf8, "utf8")
291
+ .toString("base64")
292
+ .replace(/\+/g, "-")
293
+ .replace(/\//g, "_")
294
+ .replace(/=+$/, "");
295
+ }
296
+
297
+ function _fromBase64url(s) {
298
+ let padded = s.replace(/-/g, "+").replace(/_/g, "/");
299
+ while (padded.length % 4) padded += "=";
300
+ // Validate the input contains only base64-alphabet characters; otherwise
301
+ // Node's Buffer is permissive and silently drops garbage characters.
302
+ if (!/^[A-Za-z0-9+/=]*$/.test(padded)) {
303
+ throw new Error("Invalid cursor: not valid base64url.");
304
+ }
305
+ return Buffer.from(padded, "base64").toString("utf8");
306
+ }
307
+
308
+ function encodeCursor(state) {
309
+ if (!state || typeof state !== "object") {
310
+ throw new Error("encodeCursor: invalid state.");
311
+ }
312
+ for (const f of CURSOR_REQUIRED_FIELDS) {
313
+ if (!(f in state)) {
314
+ throw new Error(`encodeCursor: missing required field "${f}".`);
315
+ }
316
+ }
317
+ const json = JSON.stringify({
318
+ bucketCursors: state.bucketCursors,
319
+ predicateHash: state.predicateHash,
320
+ modelPrefix: state.modelPrefix,
321
+ scope: state.scope,
322
+ tenantId: state.tenantId,
323
+ pendingItemKeys: state.pendingItemKeys || [],
324
+ });
325
+ return _toBase64url(json);
326
+ }
327
+
328
+ function decodeCursor(encoded) {
329
+ if (typeof encoded !== "string" || encoded.length === 0) {
330
+ throw new Error("Invalid cursor: must be a non-empty string.");
331
+ }
332
+ let json;
333
+ try {
334
+ json = _fromBase64url(encoded);
335
+ } catch (e) {
336
+ throw new Error(e.message || "Invalid cursor: not valid base64url.");
337
+ }
338
+ let parsed;
339
+ try {
340
+ parsed = JSON.parse(json);
341
+ } catch (e) {
342
+ throw new Error("Invalid cursor: payload is not valid JSON.");
343
+ }
344
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
345
+ throw new Error("Invalid cursor: payload is not an object.");
346
+ }
347
+ for (const f of CURSOR_REQUIRED_FIELDS) {
348
+ if (!(f in parsed)) {
349
+ throw new Error(`Invalid cursor: missing required field "${f}".`);
350
+ }
351
+ }
352
+ // Defense-in-depth: validate field types. Cursors round-trip through
353
+ // user-controlled storage, so a malformed payload that parses as JSON
354
+ // shouldn't crash deep in _searchPaged with an opaque TypeError —
355
+ // surface the shape problem at decode.
356
+ if (
357
+ !parsed.bucketCursors ||
358
+ typeof parsed.bucketCursors !== "object" ||
359
+ Array.isArray(parsed.bucketCursors)
360
+ ) {
361
+ throw new Error(
362
+ "Invalid cursor: bucketCursors must be an object map.",
363
+ );
364
+ }
365
+ if (typeof parsed.predicateHash !== "string") {
366
+ throw new Error("Invalid cursor: predicateHash must be a string.");
367
+ }
368
+ if (
369
+ parsed.modelPrefix !== null &&
370
+ typeof parsed.modelPrefix !== "string"
371
+ ) {
372
+ throw new Error("Invalid cursor: modelPrefix must be a string or null.");
373
+ }
374
+ if (!Array.isArray(parsed.scope)) {
375
+ throw new Error("Invalid cursor: scope must be an array.");
376
+ }
377
+ for (const s of parsed.scope) {
378
+ if (!Number.isInteger(s) || s < 0) {
379
+ throw new Error(
380
+ "Invalid cursor: scope must contain non-negative integers.",
381
+ );
382
+ }
383
+ }
384
+ if (
385
+ parsed.tenantId !== null &&
386
+ typeof parsed.tenantId !== "string"
387
+ ) {
388
+ throw new Error("Invalid cursor: tenantId must be a string or null.");
389
+ }
390
+ if (
391
+ parsed.pendingItemKeys !== undefined &&
392
+ !Array.isArray(parsed.pendingItemKeys)
393
+ ) {
394
+ throw new Error("Invalid cursor: pendingItemKeys must be an array.");
395
+ }
396
+ if (Array.isArray(parsed.pendingItemKeys)) {
397
+ for (const k of parsed.pendingItemKeys) {
398
+ if (typeof k !== "string") {
399
+ throw new Error(
400
+ "Invalid cursor: pendingItemKeys must contain strings.",
401
+ );
402
+ }
403
+ }
404
+ }
405
+ return parsed;
406
+ }
407
+
200
408
  module.exports = {
201
409
  buildSearchText,
202
410
  normalizeSearchTerm,
203
411
  tokenizeSearchQuery,
204
412
  computeSearchTextUpdate,
205
413
  buildSearchPredicate,
414
+ applyLimit,
415
+ validateLimit,
416
+ predicateHash,
417
+ encodeCursor,
418
+ decodeCursor,
206
419
  };