@proveanything/smartlinks 1.9.23 → 1.10.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.
@@ -371,17 +371,48 @@ export interface BulkUpsertResult {
371
371
  export interface BulkDeleteResult {
372
372
  deleted: number;
373
373
  }
374
+ /**
375
+ * Input for the bulk-delete endpoint.
376
+ * Use **refs mode** to delete explicit records by ref,
377
+ * or **scope mode** to delete all records anchored to a scope.
378
+ */
379
+ export type BulkDeleteInput = {
380
+ refs: string[];
381
+ recordType?: string;
382
+ scope?: never;
383
+ } | {
384
+ scope: Omit<RecordScope, 'facets'>;
385
+ recordType?: string;
386
+ refs?: never;
387
+ };
388
+ /**
389
+ * Indicates which scope dimension caused a record to match during `match()`.
390
+ * Follows specificity order: proof > batch > variant > product > facet > universal.
391
+ */
392
+ export type MatchedAtLevel = 'proof' | 'batch' | 'variant' | 'product' | 'facet' | 'universal';
393
+ /**
394
+ * An AppRecord augmented with `matchedAt` — present only on records returned
395
+ * by the `match` endpoint. Use this to display attribution such as
396
+ * "Inherited from product" or "Batch-specific" without inspecting scope fields.
397
+ */
398
+ export interface MatchedRecord extends AppRecord {
399
+ /**
400
+ * The most specific scope dimension that caused this record to match.
401
+ * 'universal' means the record has an empty scope and matches all contexts.
402
+ */
403
+ matchedAt: MatchedAtLevel;
404
+ }
374
405
  /**
375
406
  * Response from the match endpoint.
376
407
  */
377
408
  export interface MatchResult {
378
409
  /** Matched records ordered by specificity descending (most specific first) */
379
- records: AppRecord[];
410
+ records: MatchedRecord[];
380
411
  /**
381
412
  * Only present when strategy is 'best'.
382
413
  * The single highest-specificity record per recordType.
383
414
  */
384
- best?: Record<string, AppRecord>;
415
+ best?: Record<string, MatchedRecord>;
385
416
  }
386
417
  /**
387
418
  * Request body for the upsert endpoint.
@@ -442,7 +473,9 @@ export interface AppRecord {
442
473
  customId: string | null;
443
474
  sourceSystem: string | null;
444
475
  status: string | null;
476
+ /** @deprecated use scope.productId instead */
445
477
  productId: string | null;
478
+ /** @deprecated use scope.proofId instead */
446
479
  proofId: string | null;
447
480
  contactId: string | null;
448
481
  authorId: string | null;
@@ -524,9 +557,7 @@ export interface RecordListQueryParams extends ListQueryParams {
524
557
  refPrefix?: string;
525
558
  customId?: string;
526
559
  sourceSystem?: string;
527
- status?: string;
528
560
  proofId?: string;
529
- productId?: string;
530
561
  /** Filter by scope.variantId (JSONB lookup) */
531
562
  variantId?: string;
532
563
  /** Filter by scope.batchId (JSONB lookup) */
@@ -548,6 +579,8 @@ export interface RecordListQueryParams extends ListQueryParams {
548
579
  */
549
580
  at?: string;
550
581
  contactId?: string;
582
+ /** Include soft-deleted records (non-null deletedAt). Admin only. Default false. */
583
+ includeDeleted?: boolean;
551
584
  }
552
585
  /**
553
586
  * Response from case related endpoint
@@ -1,6 +1,6 @@
1
1
  # Smartlinks API Summary
2
2
 
3
- Version: 1.9.23 | Generated: 2026-04-25T12:36:26.919Z
3
+ Version: 1.10.0 | Generated: 2026-04-25T13:26:09.113Z
4
4
 
5
5
  This is a concise summary of all available API functions and types.
6
6
 
@@ -1953,10 +1953,10 @@ interface BulkDeleteResult {
1953
1953
  **MatchResult** (interface)
1954
1954
  ```typescript
1955
1955
  interface MatchResult {
1956
- records: AppRecord[]
1956
+ records: MatchedRecord[]
1957
1957
  * Only present when strategy is 'best'.
1958
1958
  * The single highest-specificity record per recordType.
1959
- best?: Record<string, AppRecord>
1959
+ best?: Record<string, MatchedRecord>
1960
1960
  }
1961
1961
  ```
1962
1962
 
@@ -2004,8 +2004,8 @@ interface AppRecord {
2004
2004
  customId: string | null
2005
2005
  sourceSystem: string | null
2006
2006
  status: string | null
2007
- productId: string | null // @deprecated — use scope.productId
2008
- proofId: string | null // @deprecated — use scope.proofId
2007
+ productId: string | null
2008
+ proofId: string | null
2009
2009
  contactId: string | null
2010
2010
  authorId: string | null
2011
2011
  authorType: string
@@ -2138,6 +2138,10 @@ interface PublicCreateBranch {
2138
2138
 
2139
2139
  **CallerRole** = `'admin' | 'owner' | 'public'`
2140
2140
 
2141
+ **BulkDeleteInput** = ``
2142
+
2143
+ **MatchedAtLevel** = ``
2144
+
2141
2145
  ### asset
2142
2146
 
2143
2147
  **Asset** (interface)
@@ -7299,7 +7303,7 @@ Upsert up to 500 records in a single transaction. Each row is individually error
7299
7303
 
7300
7304
  **bulkDelete**(collectionId: string,
7301
7305
  appId: string,
7302
- input: { refs: string[]; recordType?: string } | { scope: Omit<RecordScope, 'facets'>; recordType?: string }) → `Promise<BulkDeleteResult>`
7306
+ input: BulkDeleteInput) → `Promise<BulkDeleteResult>`
7303
7307
  Soft-delete records in bulk. Supports two modes: - **refs mode**: explicit list of refs (max 1000) - **scope mode**: delete by scope anchor (productId / variantId / etc.) POST /records/bulk-delete (admin only) ```ts // Refs mode await app.records.bulkDelete(collectionId, appId, { refs: ['product:prod_abc', 'product:prod_xyz'], recordType: 'nutrition', }); // Scope mode await app.records.bulkDelete(collectionId, appId, { scope: { productId: 'prod_abc' }, }); ```
7304
7308
 
7305
7309
  ### app.threads
@@ -523,6 +523,7 @@ const { records } = await app.records.match(collectionId, appId, {
523
523
  recordType: 'nutrition',
524
524
  }, true);
525
525
  // records is ordered by specificity descending — most specific first
526
+ // each record carries a `matchedAt` field indicating which scope dimension matched
526
527
 
527
528
  // Or use strategy: 'best' to get the single winner per recordType
528
529
  const { best } = await app.records.match(collectionId, appId, {
@@ -537,6 +538,31 @@ Facet matching rules:
537
538
  - Values within a single clause are **ORed** — any matching value satisfies it
538
539
  - A record with no facet clauses is satisfied by any target
539
540
 
541
+ #### `matchedAt` — match attribution
542
+
543
+ Every record in the response includes a `matchedAt` field indicating **which scope dimension caused the match**. Use it to render attribution labels without inspecting scope fields:
544
+
545
+ ```typescript
546
+ const { records } = await app.records.match(collectionId, appId, { target, recordType: 'nutrition' }, true);
547
+
548
+ for (const record of records) {
549
+ switch (record.matchedAt) {
550
+ case 'proof': /* "Scan-specific" */ break;
551
+ case 'batch': /* "Batch-specific" */ break;
552
+ case 'variant': /* "Size-specific" */ break;
553
+ case 'product': /* "Inherited from product" */ break;
554
+ case 'facet': /* "Tier-specific" */ break;
555
+ case 'universal': /* "Default" */ break;
556
+ }
557
+ }
558
+ ```
559
+
560
+ Precedence follows specificity order: `proof > batch > variant > product > facet > universal`.
561
+
562
+ #### React — `useResolvedRecord`
563
+
564
+ For React consumers, the `useResolvedRecord` hook in `@proveanything/smartlinks-utils-ui` wraps `records.match()` and returns the best-matching record with loading and error states. The raw `records.match()` API exists for non-React consumers and custom resolution logic.
565
+
540
566
  ### Upsert
541
567
 
542
568
  Create-or-update a record by `ref` in a single call:
@@ -575,13 +601,106 @@ await app.records.bulkDelete(collectionId, appId, {
575
601
  });
576
602
  ```
577
603
 
578
- ### Restore a Soft-Deleted Record
604
+ ### Soft-Delete Semantics
605
+
606
+ `delete` and `bulkDelete` **soft-delete** records: the row is retained with a non-null `deletedAt` and excluded from all queries by default. Records are **recoverable indefinitely** — there is no expiry on `deletedAt`.
579
607
 
580
608
  ```typescript
609
+ // Single-record restore
581
610
  const restored = await app.records.restore(collectionId, appId, recordId);
611
+
612
+ // List including deleted records (admin only)
613
+ const all = await app.records.list(collectionId, appId, {
614
+ recordType: 'nutrition',
615
+ includeDeleted: true,
616
+ }, true);
617
+ // all.data includes records with non-null deletedAt
618
+ ```
619
+
620
+ `bulkDelete` is fully reversible: rows survive with their IDs intact. Restore individually via `restore`, or re-write via `bulkUpsert` (which will find the existing row by `ref` and update it, clearing `deletedAt` in the process).
621
+
622
+ ### Text Search
623
+
624
+ The `q` parameter on `GET /records` performs a **case-insensitive substring match** (`ILIKE`) on `data->>'label'`. It works on both admin and public list endpoints today:
625
+
626
+ ```typescript
627
+ const results = await app.records.list(collectionId, appId, {
628
+ recordType: 'product',
629
+ q: 'premium',
630
+ }, true);
631
+ // returns records where data.label contains 'premium' (case-insensitive)
582
632
  ```
583
633
 
584
- ### Scheduling Filters
634
+ > `q` is not a full-text index and does not return ranked results. For ranked relevance search over large corpora, use the Elasticsearch integration.
635
+
636
+ ### External ID / ETL Workflow
637
+
638
+ `customId` and `sourceSystem` provide a stable external key pair for loading records from external systems (CMS, ERP, PIM, etc.):
639
+
640
+ - Both fields are **indexed** via a composite index on `(sourceSystem, customIdNormalized)`.
641
+ - `customId` is **filterable** on `GET /records?customId=x&sourceSystem=y`.
642
+ - The pair is **not unique** — the same external ID can exist across different `recordType` values by design (a CMS slug can appear in both a `content` and a `nutrition` record).
643
+ - `upsert` currently keys on `ref`, not `customId`. The recommended ETL pattern is to derive a stable `ref` from the external ID and pass `customId` alongside:
644
+
645
+ ```typescript
646
+ // Idiomatic ETL upsert: ref is derived from the external key, customId carries it too
647
+ await app.records.upsert(collectionId, appId, {
648
+ ref: `cms:${slug}`, // stable find-or-create key
649
+ customId: slug,
650
+ sourceSystem: 'contentful',
651
+ recordType: 'content_page',
652
+ scope: { productId },
653
+ data: { title, body },
654
+ });
655
+ // upsert finds-or-creates by ref deterministically,
656
+ // customId is stored for later reverse-lookup via ?customId=&sourceSystem=
657
+ ```
658
+
659
+ ### Counts by Record Type
660
+
661
+ `aggregate()` returns counts grouped by `record_type` in a single round-trip — no separate endpoint needed:
662
+
663
+ ```typescript
664
+ const stats = await app.records.aggregate(collectionId, appId, {
665
+ groupBy: ['record_type'],
666
+ metrics: ['count'],
667
+ // Optionally narrow the corpus:
668
+ filters: { status: 'active' },
669
+ }, true);
670
+ // stats.groups → [{ record_type: 'nutrition', count: 42 }, { record_type: 'loyalty_promo', count: 7 }, ...]
671
+ // Ordered by count descending
672
+ ```
673
+
674
+ You can also combine with other filters:
675
+
676
+ ```typescript
677
+ // Counts per type for a specific product
678
+ await app.records.aggregate(collectionId, appId, {
679
+ groupBy: ['record_type'],
680
+ metrics: ['count'],
681
+ filters: { product_id: 'prod_abc' },
682
+ }, true);
683
+ ```
684
+
685
+ ### Canonical Ref Format
686
+
687
+ The `ref` field is **server-derived** when you provide a `scope` and omit `ref`. Clients should never construct ref strings manually. The authoritative grammar is slash-joined:
688
+
689
+ ```
690
+ [facet:{key}={val1}+{val2}/][product:{productId}/][variant:{variantId}/][batch:{batchId}/][proof:{proofId}]
691
+ ```
692
+
693
+ Examples:
694
+
695
+ | Scope | Derived ref |
696
+ |-------|-------------|
697
+ | `{ productId: 'prod_abc' }` | `product:prod_abc` |
698
+ | `{ productId: 'prod_abc', variantId: 'var_500ml' }` | `product:prod_abc/variant:var_500ml` |
699
+ | `{ batchId: 'batch_q1' }` | `batch:batch_q1` |
700
+ | `{ facets: [{ key: 'tier', valueKeys: ['gold'] }] }` | `facet:tier=gold` |
701
+ | `{}` | `''` (universal) |
702
+
703
+ `parseRef` / `buildRef` in `data/refs.ts` should be used for **display and URL round-tripping only**, never as upsert keys. For ETL use cases, set an explicit `ref` using a stable external key (see [External ID / ETL Workflow](#external-id--etl-workflow)).
585
704
 
586
705
  `startsAt` and `expiresAt` control record active windows. The list and match endpoints respect scheduling by default (only returning currently-active records). Override with:
587
706
 
@@ -30,7 +30,7 @@ Without a shared pattern, every app reinvents:
30
30
  - CSV import/export
31
31
  - bulk operations
32
32
 
33
- The result is drift: each app feels different and admins have to re-learn the model. This guide locks the model down at the SDK level so the matching UI primitives in `@proveanything/ui-utils` (see the [companion guide](ui-utils.md)) can stay simple.
33
+ The result is drift: each app feels different and admins have to re-learn the model. This guide locks the model down at the SDK level so the matching UI primitives in `@proveanything/smartlinks-utils-ui` (see the [companion guide](ui-utils.md)) can stay simple.
34
34
 
35
35
  ---
36
36
 
@@ -71,20 +71,35 @@ variant:<productId>:<variantId>
71
71
  batch:<productId>:<batchId>
72
72
  proof:<proofId>
73
73
  facet:<facetKey>:<valueKey>
74
- default
74
+ '' (universal / collection-wide fallback)
75
75
  ```
76
76
 
77
77
  Notes:
78
78
 
79
79
  - Variants and batches are **always nested under a product** in the SDK, so their refs include `productId`.
80
80
  - `facet:` refs are **collection-wide** — facets cross products by design.
81
- - `default` is a single record per (app, recordType) used as the global fallback.
81
+ - `''` (empty ref) is the **universal** record — one per `(app, recordType)` with no scope restrictions; the collection-wide fallback.
82
82
  - Refs are opaque to the SDK. Apps parse them. A helper module (`@proveanything/smartlinks-utils-ui/records-admin`) exports `parseRef`/`buildRef` so all apps agree on syntax. See Appendix A for the full implementation.
83
83
 
84
84
  ### Adding scopes later
85
85
 
86
86
  If a new axis appears (e.g. `region:eu`), pick a new prefix and document it. Never reuse a prefix with different semantics.
87
87
 
88
+ ### Writing records
89
+
90
+ When creating or upserting a record, send a structured **`RecordScope`** — the server derives `ref` from it:
91
+
92
+ ```ts
93
+ await app.records.upsert(collectionId, appId, {
94
+ recordType: 'nutrition',
95
+ scope: { productId: 'prod_abc', variantId: 'var_500ml' }, // server → ref: 'product:prod_abc/variant:var_500ml'
96
+ data: { calories: 260 },
97
+ });
98
+ ```
99
+
100
+ - `ref` is for **display, URL routing, and resolution output only** — never construct one to use as an upsert key.
101
+ - `customId` / `sourceSystem` are for external references (filterable via `list()`) but are **not unique** — the same external ID can exist across `recordType` values. Do not upsert on `customId` either.
102
+
88
103
  ---
89
104
 
90
105
  ## 4. Resolution order (REQUIRED)
@@ -92,7 +107,7 @@ If a new axis appears (e.g. `region:eu`), pick a new prefix and document it. Nev
92
107
  When the **public** side of an app needs "the data that applies to this proof / product / context", it walks the chain from most-specific to least-specific and returns the first match:
93
108
 
94
109
  ```
95
- proof → batch → variant → product → facet(*) → default
110
+ proof → batch → variant → product → facet(*) → universal
96
111
  ```
97
112
 
98
113
  `facet(*)` means: walk every facet attached to the product in a deterministic order (alphabetical by `facetKey`, then `valueKey`) and use the first matching facet record.
@@ -208,7 +223,7 @@ If you are using `<RecordsAdminShell>`, the bulk actions menu is included and wi
208
223
 
209
224
  ## 9. CSV import / export
210
225
 
211
- Adopt this column shape across all records-based apps:
226
+ If your app exposes CSV import/export, use this column shape so files round-trip across apps:
212
227
 
213
228
  ```
214
229
  scope,scopeRef,<field1>,<field2>,...
@@ -220,18 +235,22 @@ facet,bread_type/sourdough,240,11.0,...
220
235
 
221
236
  - `scope` is the kind; `scopeRef` is the human-readable reference (the shell maps it to the canonical `ref`).
222
237
  - Validation errors return a downloadable annotated CSV with an `error` column appended.
223
- - Round-tripping (export → reimport unchanged) MUST be a no-op.
238
+
239
+ #### If you ship CSV
240
+
241
+ - Round-tripping (export → reimport unchanged) must be a no-op.
224
242
 
225
243
  ---
226
244
 
227
245
  ## 10. Public-side hook contract
228
246
 
229
- To keep widgets consistent across apps, expose one hook per record type (implemented in `@proveanything/ui-utils`):
247
+ To keep widgets consistent across apps, expose one hook per record type (from `@proveanything/smartlinks-utils-ui`):
230
248
 
231
249
  ```ts
232
250
  import { useResolvedRecord } from '@proveanything/smartlinks-utils-ui/records-admin';
233
251
 
234
252
  const { data, source, isLoading } = useResolvedRecord({
253
+ SL,
235
254
  appId,
236
255
  recordType: 'nutrition',
237
256
  // any combination of these — the hook walks the chain:
@@ -239,13 +258,13 @@ const { data, source, isLoading } = useResolvedRecord({
239
258
  });
240
259
  ```
241
260
 
242
- `source` is one of `'proof' | 'batch' | 'variant' | 'product' | 'facet' | 'default' | null`. UI can show a badge ("Showing batch-specific values") when useful.
261
+ `source` is one of `'proof' | 'batch' | 'variant' | 'product' | 'facet' | 'universal' | null`. UI can show a badge ("Showing batch-specific values") when useful.
243
262
 
244
263
  ---
245
264
 
246
265
  ## 11. Telemetry
247
266
 
248
- All admin shells emit these events. The `<RecordsAdminShell>` from `@proveanything/ui-utils` wires them automatically using `interactions.appendEvent` from the SDK — apps don't call this themselves.
267
+ All admin shells emit these events. The `<RecordsAdminShell>` from `@proveanything/smartlinks-utils-ui` wires them automatically using `interactions.appendEvent` from the SDK — apps don't call this themselves.
249
268
 
250
269
  | Event | Props |
251
270
  |------------------------|------------------------------------------------------|
@@ -278,11 +297,11 @@ All admin shells emit these events. The `<RecordsAdminShell>` from `@proveanythi
278
297
 
279
298
  ## Appendix A — `ref` parser reference
280
299
 
281
- This is the canonical implementation. Copy it into your app or import from `@proveanything/ui-utils/records`.
300
+ This is the canonical implementation. Copy it into your app or import from `@proveanything/smartlinks-utils-ui/records-admin`.
282
301
 
283
302
  ```ts
284
303
  type ParsedRef =
285
- | { kind: 'default' }
304
+ | { kind: 'universal' }
286
305
  | { kind: 'product'; productId: string }
287
306
  | { kind: 'variant'; productId: string; variantId: string }
288
307
  | { kind: 'batch'; productId: string; batchId: string }
@@ -291,7 +310,7 @@ type ParsedRef =
291
310
 
292
311
  export const buildRef = (p: ParsedRef): string => {
293
312
  switch (p.kind) {
294
- case 'default': return 'default';
313
+ case 'universal': return '';
295
314
  case 'product': return `product:${p.productId}`;
296
315
  case 'variant': return `variant:${p.productId}:${p.variantId}`;
297
316
  case 'batch': return `batch:${p.productId}:${p.batchId}`;
@@ -301,7 +320,7 @@ export const buildRef = (p: ParsedRef): string => {
301
320
  };
302
321
 
303
322
  export const parseRef = (ref: string): ParsedRef | null => {
304
- if (ref === 'default') return { kind: 'default' };
323
+ if (!ref) return { kind: 'universal' };
305
324
  const [head, ...rest] = ref.split(':');
306
325
  switch (head) {
307
326
  case 'product': return rest.length === 1 ? { kind: 'product', productId: rest[0] } : null;
package/docs/ui-utils.md CHANGED
@@ -82,7 +82,7 @@ import * as SL from '@proveanything/smartlinks';
82
82
  scopes={['facet', 'product', 'variant', 'batch']}
83
83
  contextScope={{ productId, variantId, batchId }} // from iframe URL — optional
84
84
  defaultData={() => ({})}
85
- csvSchema={{ columns: [/* ... */] }}
85
+ csvSchema={{ columns: [/* ... */] }} // optional — omit to disable CSV import/export
86
86
  renderEditor={(ctx) => <NutritionForm ctx={ctx} />}
87
87
  renderPreview={({ resolved }) => <pre>{JSON.stringify(resolved, null, 2)}</pre>}
88
88
  />
@@ -97,7 +97,7 @@ import * as SL from '@proveanything/smartlinks';
97
97
  - **Collection-aware tabs**: calls `collection.get` and hides Variants / Batches tabs unless `collection.variants` / `collection.batches` are true — no flicker
98
98
  - **Server-side pagination** via `useInfiniteQuery` — handles thousands of products with a "Load more" button
99
99
  - **Context-aware**: pass `contextScope` from your iframe URL (`productId` / `variantId` / `batchId`) and the browser is constrained to that subtree with the right tab auto-selected
100
- - **CSV import / export** with a schema you define; failed rows come back as an annotated CSV
100
+ - **CSV import / export** (optional provide `csvSchema` to enable); failed rows come back as an annotated CSV
101
101
  - **Bulk actions menu** (apply-to-many, copy-from, clear) via `bulkUpsert` / `bulkDelete`
102
102
  - **Telemetry hook** (`onTelemetry`) emits typed events for save, delete, scope change, CSV import/export, bulk apply
103
103
  - **i18n strings** fully overridable
@@ -136,7 +136,7 @@ const { data, source, isLoading } = useResolvedRecord({
136
136
  batchId, // optional
137
137
  proofId, // optional
138
138
  });
139
- // source: 'proof' | 'batch' | 'variant' | 'product' | 'facet' | 'default' | null
139
+ // source: 'proof' | 'batch' | 'variant' | 'product' | 'facet' | 'universal' | null
140
140
  ```
141
141
 
142
142
  Walks the resolution chain defined in [records-admin-pattern.md §4](records-admin-pattern.md#4-resolution-order-required). Use this on the **public widget side** to read the correct value for a given context.