@proveanything/smartlinks 2.1.17 → 2.1.19

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.
Files changed (80) hide show
  1. package/dist/adminViews.d.ts +104 -0
  2. package/dist/adminViews.js +275 -0
  3. package/dist/api/ai.d.ts +15 -5
  4. package/dist/api/ai.js +15 -9
  5. package/dist/api/aiGuide.d.ts +108 -0
  6. package/dist/api/aiGuide.js +161 -0
  7. package/dist/api/appObjects.d.ts +21 -0
  8. package/dist/api/appObjects.js +33 -1
  9. package/dist/api/authKit.d.ts +37 -1
  10. package/dist/api/authKit.js +51 -0
  11. package/dist/api/index.d.ts +2 -0
  12. package/dist/api/index.js +2 -0
  13. package/dist/api/operations.d.ts +36 -0
  14. package/dist/api/operations.js +56 -0
  15. package/dist/api/order.d.ts +12 -1
  16. package/dist/api/order.js +15 -0
  17. package/dist/api/userGroups.d.ts +78 -0
  18. package/dist/api/userGroups.js +124 -0
  19. package/dist/docs/API_SUMMARY.md +1111 -80
  20. package/dist/docs/admin-lists-and-pickers.md +140 -0
  21. package/dist/docs/admin-views.md +147 -0
  22. package/dist/docs/app-data-storage.md +277 -276
  23. package/dist/docs/app-manifest.md +2 -0
  24. package/dist/docs/auth-kit.md +872 -741
  25. package/dist/docs/comms.md +686 -644
  26. package/dist/docs/customer-guide.md +70 -0
  27. package/dist/docs/headless-providers.md +112 -112
  28. package/dist/docs/operations.md +281 -0
  29. package/dist/docs/overview.md +3 -0
  30. package/dist/docs/server-functions.md +87 -1
  31. package/dist/docs/ui-utils.md +123 -121
  32. package/dist/docs/user-groups.md +175 -0
  33. package/dist/docs/utils.md +17 -0
  34. package/dist/headless.js +38 -2
  35. package/dist/http.js +8 -0
  36. package/dist/iframeResponder.d.ts +15 -0
  37. package/dist/iframeResponder.js +39 -1
  38. package/dist/index.d.ts +3 -1
  39. package/dist/index.js +2 -0
  40. package/dist/live.d.ts +80 -0
  41. package/dist/live.js +315 -0
  42. package/dist/openapi.yaml +1864 -48
  43. package/dist/testing/index.d.ts +35 -0
  44. package/dist/testing/index.js +86 -0
  45. package/dist/types/appManifest.d.ts +297 -1
  46. package/dist/types/appOptions.d.ts +32 -0
  47. package/dist/types/appOptions.js +3 -0
  48. package/dist/types/authKit.d.ts +193 -4
  49. package/dist/types/comms.d.ts +41 -2
  50. package/dist/types/containers.d.ts +8 -0
  51. package/dist/types/headless.d.ts +49 -1
  52. package/dist/types/iframeResponder.d.ts +16 -1
  53. package/dist/types/index.d.ts +3 -0
  54. package/dist/types/index.js +3 -0
  55. package/dist/types/operations.d.ts +598 -0
  56. package/dist/types/operations.js +8 -0
  57. package/dist/types/order.d.ts +35 -6
  58. package/dist/types/userGroups.d.ts +103 -0
  59. package/dist/types/userGroups.js +5 -0
  60. package/dist/utils/conditions.d.ts +7 -0
  61. package/dist/utils/conditions.js +16 -9
  62. package/docs/API_SUMMARY.md +1111 -80
  63. package/docs/admin-lists-and-pickers.md +140 -0
  64. package/docs/admin-views.md +147 -0
  65. package/docs/app-data-storage.md +277 -276
  66. package/docs/app-manifest.md +2 -0
  67. package/docs/auth-kit.md +872 -741
  68. package/docs/comms.md +686 -644
  69. package/docs/customer-guide.md +70 -0
  70. package/docs/headless-providers.md +112 -112
  71. package/docs/operations.md +281 -0
  72. package/docs/overview.md +3 -0
  73. package/docs/server-functions.md +87 -1
  74. package/docs/ui-utils.md +123 -121
  75. package/docs/user-groups.md +175 -0
  76. package/docs/utils.md +17 -0
  77. package/openapi.yaml +1864 -48
  78. package/package.json +1 -1
  79. package/scripts/doctor.mjs +454 -428
  80. package/scripts/lib/keyed-app-data.mjs +21 -0
@@ -134,6 +134,19 @@ This decides what `ctx.sl` can do.
134
134
  `authority` **defaults to `caller`** — secure by default. `event`- and `cron`-triggered
135
135
  functions have no external caller, so they always run as `collection`.
136
136
 
137
+ ### Limiting it to some people: `userGroups`
138
+
139
+ An `http` function can name the [user groups](user-groups.md) allowed to call it:
140
+
141
+ ```jsonc
142
+ "userGroups": ["qc-controller", "manager"] // the caller must be in at least one
143
+ ```
144
+
145
+ The platform checks this before your code runs. A signed-in caller in none of them gets
146
+ `403 NOT_IN_USER_GROUP`; an anonymous one gets `401 SIGN_IN_REQUIRED`; a collection admin always
147
+ passes. Inside any function, `ctx.caller.userGroups` lists the caller's own keys for finer rules.
148
+ `userGroups` doesn't replace `elevated: true` on a `public` + `collection` function.
149
+
137
150
  ### The combinations
138
151
 
139
152
  - **`http` + `admin` + `caller`** — a delegated admin function; runs as the signed-in admin.
@@ -203,6 +216,7 @@ interface ServerFunctionContext {
203
216
  origin?: string | null // http
204
217
  ip?: string | null // http
205
218
  via: 'http' | 'event' | 'cron'
219
+ userGroups: readonly string[] // keys of the user groups the caller is in ([] when anonymous)
206
220
  }
207
221
 
208
222
  /** Outbound HTTP — present only if you declared `network` (host-scoped if `network:<host>`). */
@@ -514,6 +528,10 @@ Prefer the platform primitives above over a dependency; when you do need one, pi
514
528
  | Read ANOTHER app's data (as the caller may see it) | `ctx.sl.app('other-app').data.get()` — caller-authority, this collection, public-filtered, read-only | `sl:data:read` |
515
529
  | Guarantee a UNIQUE claim (one entry per tag, one-per-user, idempotency key, a number nobody else holds) | `ctx.sl.appRecords.claim({ …, singletonPer, customId })` → `{ record, created, conflict? }` — see below | `sl:records:write` |
516
530
  | Hand out the next number (tickets, order numbers) | `ctx.sl.counters.next('tickets')` — atomic, distinct per caller | `sl:data:write` |
531
+ | Track a job through its stages (a production job, a repair, a fulfilment) | `ctx.sl.workOrders` — the shared work order; stages, holds, progress → `operations.md` | `sl:workorders:write` |
532
+ | Know how much of something there is and where; move, allocate, hold or count it | `ctx.sl.stock` — quantities in containers, changed by movements, never below zero → `operations.md` | `sl:stock:write` |
533
+ | Ask whether you will run short, and when | `ctx.sl.stock.position({ productId, horizonDays })` — on hand, on order, being made, needed, first short day | `sl:stock:read` |
534
+ | Say what a product is made of, or what a batch really used | `ctx.sl.boms`, `ctx.sl.madeFrom` → `operations.md` | `sl:boms:write`, `sl:madefrom:write` |
517
535
  | Change numbers in a record (stock, counts, balances) without losing updates | `ctx.sl.appRecords.adjust(id, { qty: -5 }, { atLeast: { qty: 0 } })` — in place, conditions checked after the change | `sl:records:write` |
518
536
  | Several record writes that land together or not at all (a stock move) | `ctx.sl.transaction([ops], { idempotencyKey })` — see below | `sl:records:write` |
519
537
  | Totals: stock per location, forecast per SKU | `ctx.sl.appRecords.aggregate({ groupBy: ['data.location'], metrics: ['sum:qty'] })` | `sl:records:read` |
@@ -521,6 +539,7 @@ Prefer the platform primitives above over a dependency; when you do need one, pi
521
539
  | Check a tapped tag is real | `ctx.sl.tags.resolve(proofId)` → `{ id, claimSetId, code }` or `null` | `sl:tags:read` |
522
540
  | Put a visitor's details on a contact | `ctx.sl.contacts.upsert({ email, firstName, … })` → `{ contactId, created }` (fills empty fields only) | `sl:contacts:write` |
523
541
  | Record "they did X" | `ctx.sl.interactions.record({ interactionId, contactId, outcome, metadata })` | `sl:interactions:write` |
542
+ | Message one person: a confirmation, a reminder, a cancellation, an update | `ctx.sl.messages.send({ to: 'caller' \| contactId, templateId \| message: { subject, body }, about: { type, id, view?, params? } })` → `{ ok, channel }` or `{ ok: false, reason }` — their preferred channel, their opt-outs respected, logged with your app and what it's about; see [comms.md](comms.md#messaging-one-person-from-an-app) | `sl:messages:write` |
524
543
  | Land a loyalty / CRM provider's view of a person (member id, tier, points, tags, external ids) | `ctx.sl.members.apply({ identity, contact?, loyalty?, tags?, externalIds? }, { provider })` → `{ contactId, op }` — matches by id, external id, email or phone; profile fields fill-empty only; see [connectors.md](connectors.md#loyalty-and-crm-connectors) | `sl:members:write` |
525
544
  | Invoke a connector's action — redeem, enrol, issue a coupon, raise a ticket — with the connector's credentials | `ctx.sl.connectors.call('acme-loyalty', 'redeem', { rewardId })` → the action's result; `ctx.sl.connectors.actions(appId)` lists them; see [connectors.md](connectors.md#actions-provider-operations-on-demand) | `sl:connectors:write` |
526
545
  | Ask "is this person gold or above?" without holding their member record | `ctx.sl.entitlements.check('tier>=gold')` → `{ allowed, basis, asOf, attributes }` for the signed-in caller (or `{ identity, token, fallback }`); see [entitlements.md](entitlements.md) | `sl:entitlements:read` |
@@ -750,7 +769,7 @@ overlaps, idempotency, holds): `ctx.memory.bookings`.
750
769
  model, no agent loop. Declare each tool as a capability: `tools:pdf.create`, or `tools:pdf.*` for the
751
770
  whole family. Open to functions: `pdf.create`, `pdf.merge`, `pdf.fill`, `pdf.inspect`, `pdf.render`,
752
771
  `pdf.decodeBarcodes`, `pdf.inspectGraphics`, `pdf.preflight`, `pdf.printReady`, `pdf.edit`,
753
- `image.transform` (arguments as in [ai.md](ai.md)).
772
+ `image.transform`, `image.ocr`, and `pdf.extract` (a PDF + a JSON schema → its fields; it calls a model, so it is refused when the collection's AI budget is used up) (arguments as in [ai.md](ai.md)). A site's server code may use them too.
754
773
 
755
774
  - **Identity:** the call runs as the function's collection, whatever the caller. An anonymous caller
756
775
  holding only your own key gets the same result; the work is attributed and billed to the collection.
@@ -794,6 +813,73 @@ export async function printLabel(ctx, event) {
794
813
  - **Verify:** `pdf.decodeBarcodes` on a `signedUrl` reads the codes back deterministically, so you can
795
814
  confirm the digits before answering.
796
815
 
816
+ ## Files — `ctx.sl.assets`
817
+
818
+ The collection's assets are its lasting files: a record per file, kept as long as the asset is. Server
819
+ code reads them (a PDF to parse, a photo to check) and saves what it makes (a job sheet, a label, a
820
+ report) as assets of its own app. Declare `sl:assets:read` or `sl:assets:write`, with **collection
821
+ authority** (an asset belongs to the collection, not to a visitor).
822
+
823
+ ```ts
824
+ // capabilities: ["sl:assets:write", "tools:pdf.create"], authority: "collection"
825
+ const pdf = await ctx.sl.tools.run('pdf.create', { format: 'A4', html, return: 'base64' })
826
+ const sheet = await ctx.sl.assets.create({
827
+ name: `Job ${job.ref}.pdf`, contentType: 'application/pdf', base64: pdf.base64,
828
+ labels: ['job-sheet'], metadata: { workOrderId: job.id },
829
+ })
830
+ // later: the bytes back
831
+ const { base64, contentType } = await ctx.sl.assets.read(sheet.id)
832
+ ```
833
+
834
+ - **Reads see every asset** in the collection: `get`, `list({ productId?, proofId?, appId?, labels? })`,
835
+ `read(id)` (base64, or `{ as: 'text' }`).
836
+ - **Writes act on this app's own assets only.** `create` stamps the asset with your app;
837
+ `replace(id, file)` keeps the old file as a version (same id, same `assetUrl`); `update(id, { name,
838
+ labels, metadata })`; `remove(id)`. Changing another app's asset is refused (`NOT_YOURS`).
839
+ - **Size.** `read`, `create` and `replace` carry the file as base64, so up to **7 MB**. Bigger files go
840
+ straight to storage, never through SmartLinks:
841
+
842
+ ```ts
843
+ // capabilities add: "network:storage.googleapis.com"
844
+ const { uploadId, sessionUrl } = await ctx.sl.assets.startUpload({ name: 'line-3.mp4', contentType: 'video/mp4' })
845
+ await ctx.fetch(sessionUrl, { method: 'PUT', body: bytes }) // one request, or chunks with Content-Range
846
+ const video = await ctx.sl.assets.finishUpload(uploadId)
847
+ ```
848
+
849
+ To read a large file, fetch its `url` (declare the CDN host, `network:cdn.smartlinks.app`).
850
+ - **Who can open the file.** An asset's file is served from the CDN under an unguessable address, as
851
+ every asset is. Keep the address to the people who should have it.
852
+
853
+ ## AI — `ctx.sl.ai`
854
+
855
+ `ctx.sl.ai.generate({ prompt, system?, files?, schema?, quality? })` asks a model. `files` are PDFs,
856
+ photos or text (`{ assetId }`, `{ base64, contentType }` or `{ text }`); with a `schema` (JSON
857
+ Schema) the answer is parsed into `data`. Declare `sl:ai:write`; any authority may use it.
858
+
859
+ ```ts
860
+ // capabilities: ["sl:ai:write", "sl:assets:read"], authority: "collection"
861
+ const { data } = await ctx.sl.ai.generate({
862
+ prompt: 'Read this sales order.',
863
+ files: [{ assetId }],
864
+ schema: { type: 'object', properties: { salesOrderNumber: { type: 'string' }, lines: { type: 'array', items: { type: 'object', properties: { code: { type: 'string' }, qty: { type: 'number' } } } } } },
865
+ })
866
+ ```
867
+
868
+ - **Budget, enforced.** Every call is recorded and priced against the collection and your app. When the
869
+ collection's monthly AI budget or credits are used up, the call throws `AI_BUDGET_EXCEEDED` /
870
+ `AI_CREDITS_EXHAUSTED` (402) before anything is spent. Catch it and tell the person plainly.
871
+ - **Quality.** `'fast'` (the default) is quick and cheap; `'best'` thinks harder and costs more.
872
+ - **Limits.** Up to 10 files and 7 MB in all; 5 calls a second per collection (bursts wait).
873
+ - **Failure.** `AI_BAD_JSON` (502) when the answer wasn't JSON of the shape asked for: try again, or ask
874
+ for less at once.
875
+
876
+ ### Uploaded files on a site
877
+
878
+ In a site's own functions, a file posted to the function arrives intact: `event.rawBytes` holds the
879
+ exact bytes of any request, and a multipart form's files are in `event.files` as
880
+ `[{ field, filename, contentType, size, base64 }]` (its text fields in `event.body`). `base64` goes
881
+ straight into `ctx.sl.assets.create` or `ctx.sl.ai.generate`.
882
+
797
883
  ### Making an email attachment
798
884
 
799
885
  A flow step can attach a file your function makes: `"attach": [{ "function": "receiptPdf" }]` in a
@@ -1,121 +1,123 @@
1
- # UI Utils — `@proveanything/smartlinks-utils-ui`
2
-
3
- The standardised, **admin-only** React toolkit for SmartLinks microapps. This page
4
- is self-contained: the table and examples below are enough to build with. The
5
- exhaustive per-component reference (props, slots, hooks, design tokens) ships
6
- **inside the package** — read it from `node_modules/@proveanything/smartlinks-utils-ui/docs/`
7
- after install. Nothing here depends on an external site.
8
-
9
- - **NPM:** [`@proveanything/smartlinks-utils-ui`](https://www.npmjs.com/package/@proveanything/smartlinks-utils-ui)
10
- - **Per-component reference:** `node_modules/@proveanything/smartlinks-utils-ui/docs/*.md`
11
- (`records-admin-shell.md`, `admin-page-header.md`, `asset-picker.md`, `conditions-editor.md`,
12
- `facet-rule-editor.md`, `link-picker.md`, `records-admin-hooks.md`, `public-consumption.md`, …)
13
- - **Tracks:** `@proveanything/smartlinks ≥ 2.0` (peer dep)
14
-
15
- ## Admin is standardised; the consumer surface is bespoke
16
-
17
- Two different design mandates, and the split is deliberate:
18
-
19
- - **Admin surfaces** (the desktop `admin.html` a brand operator uses) are a
20
- **product family** — like Salesforce: consistent, predictable chrome across every
21
- app an operator opens. Do **not** hand-roll admin tables, editors or page headers.
22
- Mount `RecordsAdminShell` for anything record-shaped; otherwise wrap the page in
23
- `AdminPageHeader` and use the pickers. That consistency *is* the product.
24
- - **Consumer / public surfaces** (the container, widgets, public pages the
25
- end-customer sees) are **bespoke and brand-led** — entirely your design. utils-ui
26
- belongs here only as read-side hooks (`useResolvedRecord`, `useResolveAllRecords`),
27
- never as UI.
28
-
29
- ## Install
30
-
31
- ```bash
32
- npm install @proveanything/smartlinks-utils-ui
33
- # Peer deps you probably already have:
34
- npm install react react-dom @proveanything/smartlinks @tanstack/react-query
35
- ```
36
-
37
- Import the styles **once** in your admin entry (typically `src/admin-main.tsx`):
38
-
39
- ```ts
40
- import '@proveanything/smartlinks-utils-ui/styles.css';
41
- ```
42
-
43
- Components inherit your shadcn-compatible CSS variables (`--primary`,
44
- `--background`, `--border`, …) — no extra theming required.
45
-
46
- > **Admin-only.** Every component in this package calls the SDK with
47
- > `admin: true` somewhere (save, upload, etc.). Never import it from a
48
- > public widget or from `MobileAdminContainer`.
49
-
50
- ## What's in the box
51
-
52
- | Module | Subpath import | Use it for |
53
- |---|---|---|
54
- | **RecordsAdminShell** | `/records-admin` | Full admin UI for the `app.records` pattern. Top-level scopes: **Global** (`'collection'`), **Rule** (`'rule'`, AND-of-OR over facets), and **Product** — with automatic variant & batch drill-down where the collection enables them. Browser pane, editor pane with sticky save/discard/delete, optimistic save, deep-linking, lifecycle hooks, conflict handling. Decide **cardinality** up front: `'singleton'` (one winning record per scope — warranty, nutrition) vs `'list'` (many records per scope — auction items, FAQs, gallery). See `docs/records-admin-shell.md`. |
55
- | **Records hooks** | `/records-admin` | `useResolvedRecord`, `useMergedRecord`, `useCollectedRecords`, `useResolveAllRecords`, `useRulePreview`, … for the **public widget** side. See `docs/records-admin-hooks.md`. |
56
- | **AdminPageHeader** | (root) | Standardised title / subtitle / icon / help / actions header. **Required** for any admin app that doesn't mount `RecordsAdminShell` (which embeds it). No bespoke admin chrome. |
57
- | **AssetPicker** | `/asset-picker` | Pick / upload / paste / URL-import / AI-generate / stock-search / crop media assets. MIME filtering, scope-aware, tag editor. |
58
- | **IconPicker** | `/icon-picker` | Searchable Font Awesome 7 Pro picker (requires the FA kit script on the host page). |
59
- | **FontPicker** | `/font-picker` | Google Fonts catalogue + custom uploaded font families with live previews. |
60
- | **ConditionsEditor** | `/conditions-editor` | Recursive AND/OR rule builder (12 condition types, facet-aware). |
61
- | **FacetRuleEditor** | `/facet-rule-editor` | Author server-side facet rules (AND-of-OR) for record targeting. |
62
- | **LinkPicker** | `/link-picker` | Universal navigation picker: external URL, an installed app, or a deep link inside an app. Stores a `LinkTarget` discriminated union — never a resolved URL. Ships with `resolveLink` and `useLinkTargets`. |
63
- | **Liquid editors** | `/liquid-editor` | Author Liquid templates with a code or rich (TipTap) editor, variable autocomplete. |
64
- | **Hints** | (root) | `useHintsPreference`, `useIntroState`, `HintsPreferenceToggle` — global "show/hide intro hints" preference shared across admin apps. |
65
-
66
- Each module has a per-subpath export so bundlers tree-shake the rest:
67
-
68
- ```ts
69
- import { RecordsAdminShell } from '@proveanything/smartlinks-utils-ui/records-admin';
70
- import { AssetPicker } from '@proveanything/smartlinks-utils-ui/asset-picker';
71
- ```
72
-
73
- ## Minimal examples
74
-
75
- ### Records admin (most apps need this)
76
-
77
- ```tsx
78
- import { RecordsAdminShell } from '@proveanything/smartlinks-utils-ui/records-admin';
79
- import * as SL from '@proveanything/smartlinks';
80
-
81
- <RecordsAdminShell
82
- SL={SL}
83
- collectionId={collectionId}
84
- appId={appId}
85
- recordType="nutrition"
86
- label="Nutrition info"
87
- scopes={['collection', 'rule', 'product']} // canonical top-level tabs
88
- // items={{ cardinality: 'list' }} // ← opt in for multi-item apps
89
- defaultData={() => ({})}
90
- renderEditor={(ctx) => <NutritionForm ctx={ctx} />}
91
- />
92
- ```
93
-
94
- ### Public widget — read the resolved value
95
-
96
- ```tsx
97
- import { useResolvedRecord } from '@proveanything/smartlinks-utils-ui/records-admin';
98
-
99
- const { data, source } = useResolvedRecord({
100
- SL, appId, recordType: 'nutrition',
101
- collectionId, productId, variantId, batchId,
102
- });
103
- // source: 'proof' | 'batch' | 'variant' | 'product' | 'rule' | 'collection' | null
104
- ```
105
-
106
- For multi-item (`cardinality: 'list'`) apps, use `useResolveAllRecords` /
107
- `app.records.resolveAll()` instead — it returns every applicable record, not
108
- just the winner.
109
-
110
- For everything else (props, slots, cardinality decisions, deep-link adapters,
111
- lifecycle hooks, conflict handling, design tokens) → **read the matching file in
112
- `node_modules/@proveanything/smartlinks-utils-ui/docs/`**.
113
-
114
- ## Prerequisites
115
-
116
- All components assume `SL.initializeApi()` has already run.
117
-
118
- ## Where to go next
119
-
120
- - Per-component reference (shipped with the package): `node_modules/@proveanything/smartlinks-utils-ui/docs/`
121
- - Records pattern (concepts, scope inheritance, resolution order): [`app-records-pattern.md`](./app-records-pattern.md)
1
+ # UI Utils — `@proveanything/smartlinks-utils-ui`
2
+
3
+ The standardised, **admin-only** React toolkit for SmartLinks microapps. This page
4
+ is self-contained: the table and examples below are enough to build with. The
5
+ exhaustive per-component reference (props, slots, hooks, design tokens) ships
6
+ **inside the package** — read it from `node_modules/@proveanything/smartlinks-utils-ui/docs/`
7
+ after install. Nothing here depends on an external site.
8
+
9
+ - **NPM:** [`@proveanything/smartlinks-utils-ui`](https://www.npmjs.com/package/@proveanything/smartlinks-utils-ui)
10
+ - **Per-component reference:** `node_modules/@proveanything/smartlinks-utils-ui/docs/*.md`
11
+ (`records-admin-shell.md`, `admin-page-header.md`, `asset-picker.md`, `conditions-editor.md`,
12
+ `facet-rule-editor.md`, `link-picker.md`, `records-admin-hooks.md`, `public-consumption.md`, …)
13
+ - **Tracks:** `@proveanything/smartlinks ≥ 2.0` (peer dep)
14
+
15
+ ## Admin is standardised; the consumer surface is bespoke
16
+
17
+ Two different design mandates, and the split is deliberate:
18
+
19
+ - **Admin surfaces** (the desktop `admin.html` a brand operator uses) are a
20
+ **product family** — like Salesforce: consistent, predictable chrome across every
21
+ app an operator opens. Do **not** hand-roll admin tables, editors or page headers.
22
+ Mount `RecordsAdminShell` for anything record-shaped; otherwise wrap the page in
23
+ `AdminPageHeader` and use the pickers. That consistency *is* the product.
24
+ - **Consumer / public surfaces** (the container, widgets, public pages the
25
+ end-customer sees) are **bespoke and brand-led** — entirely your design. utils-ui
26
+ belongs here only as read-side hooks (`useResolvedRecord`, `useResolveAllRecords`),
27
+ never as UI.
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ npm install @proveanything/smartlinks-utils-ui
33
+ # Peer deps you probably already have:
34
+ npm install react react-dom @proveanything/smartlinks @tanstack/react-query
35
+ ```
36
+
37
+ Import the styles **once** in your admin entry (typically `src/admin-main.tsx`):
38
+
39
+ ```ts
40
+ import '@proveanything/smartlinks-utils-ui/styles.css';
41
+ ```
42
+
43
+ Components inherit your shadcn-compatible CSS variables (`--primary`,
44
+ `--background`, `--border`, …) — no extra theming required.
45
+
46
+ > **Admin-only.** Every component in this package calls the SDK with
47
+ > `admin: true` somewhere (save, upload, etc.). Never import it from a
48
+ > public widget or from `MobileAdminContainer`.
49
+
50
+ ## What's in the box
51
+
52
+ | Module | Subpath import | Use it for |
53
+ |---|---|---|
54
+ | **RecordsAdminShell** | `/records-admin` | Full admin UI for the `app.records` pattern. Top-level scopes: **Global** (`'collection'`), **Rule** (`'rule'`, AND-of-OR over facets), and **Product** — with automatic variant & batch drill-down where the collection enables them. Browser pane, editor pane with sticky save/discard/delete, optimistic save, deep-linking, lifecycle hooks, conflict handling. Decide **cardinality** up front: `'singleton'` (one winning record per scope — warranty, nutrition) vs `'list'` (many records per scope — auction items, FAQs, gallery). See `docs/records-admin-shell.md`. |
55
+ | **Records hooks** | `/records-admin` | `useResolvedRecord`, `useMergedRecord`, `useCollectedRecords`, `useResolveAllRecords`, `useRulePreview`, … for the **public widget** side. See `docs/records-admin-hooks.md`. |
56
+ | **AdminPageHeader** | (root) | Standardised title / subtitle / icon / help / actions header. **Required** for any admin app that doesn't mount `RecordsAdminShell` (which embeds it). No bespoke admin chrome. |
57
+ | **AssetPicker** | `/asset-picker` | Pick / upload / paste / URL-import / AI-generate / stock-search / crop media assets. MIME filtering, scope-aware, tag editor. |
58
+ | **IconPicker** | `/icon-picker` | Searchable Font Awesome 7 Pro picker (requires the FA kit script on the host page). |
59
+ | **FontPicker** | `/font-picker` | Google Fonts catalogue + custom uploaded font families with live previews. |
60
+ | **ConditionsEditor** | `/conditions-editor` | Recursive AND/OR rule builder (12 condition types, facet-aware). |
61
+ | **FacetRuleEditor** | `/facet-rule-editor` | Author server-side facet rules (AND-of-OR) for record targeting. |
62
+ | **LinkPicker** | `/link-picker` | Universal navigation picker: external URL, an installed app, or a deep link inside an app. Stores a `LinkTarget` discriminated union — never a resolved URL. Ships with `resolveLink` and `useLinkTargets`. |
63
+ | **RecordPicker / ValuePicker** | `/option-picker` | Pick one of the app's records of a declared type, or a value from a value list. Reads the cached options call; switched-off entries stay labelled. See `docs/admin-lists-and-pickers.md`. |
64
+ | **SetupPanel** | `/setup-editor` | Generated list + form for every declared set-up type (`setup: true`) and editable value list. Use it instead of hand-building set-up tabs. |
65
+ | **Liquid editors** | `/liquid-editor` | Author Liquid templates with a code or rich (TipTap) editor, variable autocomplete. |
66
+ | **Hints** | (root) | `useHintsPreference`, `useIntroState`, `HintsPreferenceToggle` — global "show/hide intro hints" preference shared across admin apps. |
67
+
68
+ Each module has a per-subpath export so bundlers tree-shake the rest:
69
+
70
+ ```ts
71
+ import { RecordsAdminShell } from '@proveanything/smartlinks-utils-ui/records-admin';
72
+ import { AssetPicker } from '@proveanything/smartlinks-utils-ui/asset-picker';
73
+ ```
74
+
75
+ ## Minimal examples
76
+
77
+ ### Records admin (most apps need this)
78
+
79
+ ```tsx
80
+ import { RecordsAdminShell } from '@proveanything/smartlinks-utils-ui/records-admin';
81
+ import * as SL from '@proveanything/smartlinks';
82
+
83
+ <RecordsAdminShell
84
+ SL={SL}
85
+ collectionId={collectionId}
86
+ appId={appId}
87
+ recordType="nutrition"
88
+ label="Nutrition info"
89
+ scopes={['collection', 'rule', 'product']} // canonical top-level tabs
90
+ // items={{ cardinality: 'list' }} // ← opt in for multi-item apps
91
+ defaultData={() => ({})}
92
+ renderEditor={(ctx) => <NutritionForm ctx={ctx} />}
93
+ />
94
+ ```
95
+
96
+ ### Public widget — read the resolved value
97
+
98
+ ```tsx
99
+ import { useResolvedRecord } from '@proveanything/smartlinks-utils-ui/records-admin';
100
+
101
+ const { data, source } = useResolvedRecord({
102
+ SL, appId, recordType: 'nutrition',
103
+ collectionId, productId, variantId, batchId,
104
+ });
105
+ // source: 'proof' | 'batch' | 'variant' | 'product' | 'rule' | 'collection' | null
106
+ ```
107
+
108
+ For multi-item (`cardinality: 'list'`) apps, use `useResolveAllRecords` /
109
+ `app.records.resolveAll()` instead — it returns every applicable record, not
110
+ just the winner.
111
+
112
+ For everything else (props, slots, cardinality decisions, deep-link adapters,
113
+ lifecycle hooks, conflict handling, design tokens) → **read the matching file in
114
+ `node_modules/@proveanything/smartlinks-utils-ui/docs/`**.
115
+
116
+ ## Prerequisites
117
+
118
+ All components assume `SL.initializeApi()` has already run.
119
+
120
+ ## Where to go next
121
+
122
+ - Per-component reference (shipped with the package): `node_modules/@proveanything/smartlinks-utils-ui/docs/`
123
+ - Records pattern (concepts, scope inheritance, resolution order): [`app-records-pattern.md`](./app-records-pattern.md)
@@ -0,0 +1,175 @@
1
+ # User groups
2
+
3
+ A **user group** is a named list of people in a collection: "QC Controllers", "Warehouse", "Approved
4
+ partners". Use them to say who may do what, for staff who aren't collection admins and for third
5
+ parties alike.
6
+
7
+ > There is no separate "roles" object. A role is a user group: "Sam has the QC role" and "Sam is in
8
+ > the QC Controllers user group" are the same fact.
9
+
10
+ ## The three things you do with them
11
+
12
+ | You want to… | Use |
13
+ |---|---|
14
+ | **Protect** an action, so only some people can do it | `userGroups` on the server function's declaration |
15
+ | **Decide** something finer inside a function | `ctx.caller.userGroups` |
16
+ | **Show or hide** a button or a screen | `userGroups.mine(collectionId)`, or a `group` condition |
17
+
18
+ Only the first two protect anything. Hiding a button doesn't stop someone calling the function behind
19
+ it, so limit the function as well.
20
+
21
+ ## A user group
22
+
23
+ ```ts
24
+ {
25
+ id: 'k3Jd…', // random, never changes
26
+ key: 'qc-controller', // the name code uses; set once, kept through a rename
27
+ name: 'QC Controllers', // what people see; free to change
28
+ description: 'Sign off finished batches',
29
+ members: ['uid_1', 'uid_2'] // user ids
30
+ }
31
+ ```
32
+
33
+ - **Refer to user groups by `key`** in code and manifests, never by name or id.
34
+ - A key is lowercase letters, digits and hyphens. It's made from the name when you don't give one
35
+ ("QC Controllers" → `qc-controllers`), and it's unique in the collection.
36
+ - Members are people who sign in: on the site's own login, or with a SmartLinks account.
37
+ - Collection admins pass every user group check. They don't need adding.
38
+
39
+ ## Limit a server function
40
+
41
+ In the manifest (see [server-functions.md](server-functions.md)):
42
+
43
+ ```jsonc
44
+ {
45
+ "name": "releaseBatch",
46
+ "trigger": { "type": "http", "methods": ["POST"] },
47
+ "visibility": "public",
48
+ "authority": "collection",
49
+ "elevated": true,
50
+ "userGroups": ["qc-controller", "manager"], // in at least ONE of these
51
+ "capabilities": ["sl:records:write"]
52
+ }
53
+ ```
54
+
55
+ The platform checks this before any of your code runs:
56
+
57
+ | Caller | Result |
58
+ |---|---|
59
+ | In one of the user groups, or a collection admin | The function runs |
60
+ | Signed in, in none of them | `403 { error: 'NOT_IN_USER_GROUP' }` |
61
+ | Not signed in | `401 { error: 'SIGN_IN_REQUIRED' }` |
62
+
63
+ - `http` functions only: `event` and `cron` functions have no caller.
64
+ - `userGroups` doesn't replace `elevated: true` on a `public` + `collection` function. Declare both.
65
+
66
+ ## Decide inside a function
67
+
68
+ Every function sees the caller's keys:
69
+
70
+ ```ts
71
+ export async function adjustQuantity(ctx, event) {
72
+ const isManager = ctx.caller.userGroups.includes('manager')
73
+ if (event.body.delta > 100 && !isManager) {
74
+ return new Response(JSON.stringify({ error: 'Over 100 needs a manager' }), { status: 403 })
75
+ }
76
+ // …
77
+ }
78
+ ```
79
+
80
+ `ctx.caller.userGroups` is `[]` when nobody is signed in, and for `event` / `cron` runs.
81
+
82
+ ## Show or hide in a screen
83
+
84
+ ```ts
85
+ import { userGroups } from '@proveanything/smartlinks'
86
+
87
+ const { userGroups: mine } = await userGroups.mine(collectionId)
88
+ const showReleaseButton = mine.includes('qc-controller')
89
+ ```
90
+
91
+ - `mine()` returns `{ userGroups: string[], userGroupIds: string[] }`: keys for code, and ids for
92
+ older saved conditions. Both are empty when nobody is signed in.
93
+ - It is never cached, so a change an admin makes shows on the next call.
94
+ - A person can only ask about themselves.
95
+
96
+ With conditions (see [utils.md](utils.md)):
97
+
98
+ ```ts
99
+ const { userGroups: keys, userGroupIds } = await userGroups.mine(collectionId)
100
+
101
+ await utils.validateCondition({
102
+ condition: { type: 'and', conditions: [{ type: 'user', userType: 'group', groupIds: ['qc-controller'] }] },
103
+ user: { valid: true, uid, groups: [...keys, ...userGroupIds] },
104
+ })
105
+ ```
106
+
107
+ ## Manage them (admin)
108
+
109
+ ```ts
110
+ const qc = await userGroups.create(collectionId, { name: 'QC Controllers' }) // key: 'qc-controllers'
111
+
112
+ await userGroups.addMember(collectionId, qc.id, { email: 'sam@example.com', name: 'Sam' })
113
+ await userGroups.addMember(collectionId, qc.id, { userId: 'uid_2' })
114
+ await userGroups.removeMember(collectionId, qc.id, 'uid_2')
115
+
116
+ await userGroups.members(collectionId, qc.id) // [{ uid, name, email }]
117
+ await userGroups.ofUser(collectionId, 'uid_1') // [{ id, key, name }]
118
+ await userGroups.list(collectionId)
119
+ await userGroups.update(collectionId, qc.id, { name: 'Quality control' }) // key stays 'qc-controllers'
120
+ await userGroups.remove(collectionId, qc.id)
121
+ ```
122
+
123
+ - **Add and remove one person at a time** with `addMember` / `removeMember`. Saving a whole `members`
124
+ list through `update` can overwrite a change someone else made at the same moment.
125
+ - Adding by email finds the person in the collection's logins, or adds them. No welcome email is sent.
126
+ - A change takes up to a minute to reach function checks.
127
+
128
+ Errors: `KEY_INVALID`, `KEY_TAKEN` (409), `KEY_FIXED` (409, a key can't be changed once set),
129
+ `MISSING_FIELDS`, `NOT_FOUND`.
130
+
131
+ ## Who changed what
132
+
133
+ Every change is recorded: a user group created, renamed or deleted, and each person added or removed,
134
+ with the admin who did it and when.
135
+
136
+ ```ts
137
+ await userGroups.history(collectionId, { userGroupId: qc.id }) // one user group
138
+ await userGroups.history(collectionId, { userId: 'uid_1' }) // everything about one person
139
+ // [{ at, type: 'usergroup.member-added', actorId: 'uid_admin', data: { key: 'qc-controllers', userId: 'uid_1', … } }]
140
+ ```
141
+
142
+ It covers the last 30 days unless you pass `from` / `to` (up to 400 days), and takes about a second.
143
+ Entries hold ids only, never names or emails.
144
+
145
+ ## In a site
146
+
147
+ It works the same way. A site's functions run in the site's own worker, and the site's function
148
+ runtime applies `userGroups` from `public/app.manifest.json` before your handler runs, with the same
149
+ `401` / `403` answers. `ctx.caller.userId` and `ctx.caller.userGroups` are filled in for a signed-in
150
+ visitor.
151
+
152
+ A site made before this existed has no `src/site/lib/fn-access.ts`. There, `userGroups` in the
153
+ manifest is ignored until the site is updated.
154
+
155
+ ## Testing
156
+
157
+ ```ts
158
+ import { createFunctionTestContext } from '@proveanything/smartlinks/testing'
159
+
160
+ const ctx = createFunctionTestContext({
161
+ def: { trigger: { type: 'http' }, capabilities: ['sl:records:write'] },
162
+ caller: { userId: 'sam', userGroups: ['qc-controller'] },
163
+ })
164
+ ctx.caller.userGroups // ['qc-controller']
165
+ ```
166
+
167
+ The test context gives your handler the caller you describe. It doesn't apply the declaration's
168
+ `userGroups` limit: that check happens on the platform before your handler is called.
169
+
170
+ ## Who is in a user group (server code)
171
+
172
+ `ctx.sl.userGroups.members(keys?)` lists the people in the named user groups (every keyed group when
173
+ `keys` is empty): `[{ userId, name, email, userGroups }]`, sorted by name, at most 500. For staff lists
174
+ ("who is on QC") and for addressing a team (a notification to every Manager). Needs
175
+ `sl:usergroups:read` and collection authority. Members whose account no longer exists are left out.
@@ -479,6 +479,23 @@ await utils.validateCondition({
479
479
 
480
480
  User types: `'valid'`, `'invalid'`, `'owner'`, `'admin'`, `'group'`
481
481
 
482
+ `'group'` passes when the signed-in user is in at least one of the named [user groups](user-groups.md).
483
+ Name them in `groupIds` (keys or ids), and pass the user's own in `user.groups`:
484
+
485
+ ```typescript
486
+ const { userGroups: keys, userGroupIds } = await userGroups.mine(collectionId)
487
+
488
+ await utils.validateCondition({
489
+ condition: {
490
+ type: 'and',
491
+ conditions: [{ type: 'user', userType: 'group', groupIds: ['qc-controller'] }]
492
+ },
493
+ user: { valid: true, uid: 'user123', groups: [...keys, ...userGroupIds] }
494
+ })
495
+ ```
496
+
497
+ A condition only shows or hides. To protect an action, limit the server function behind it.
498
+
482
499
  #### Date & Time Conditions
483
500
  Show/hide content based on dates:
484
501
 
package/dist/headless.js CHANGED
@@ -87,6 +87,9 @@ function mismatch(field, value) {
87
87
  case 'datetime':
88
88
  return typeof value === 'string' && !Number.isNaN(Date.parse(value)) ? null : 'expected an ISO date-time';
89
89
  case 'enum':
90
+ // A value list's values are the admin's, so an example can only be checked for being a code.
91
+ if (field.list && !field.options)
92
+ return typeof value === 'string' && value ? null : 'expected a value code (a string)';
90
93
  return (field.options || []).includes(value) ? null : `expected one of ${(field.options || []).join(', ')}`;
91
94
  case 'image':
92
95
  case 'file':
@@ -180,8 +183,16 @@ export function validate(manifest, opts = {}) {
180
183
  err(fat, `unknown type "${f && f.type}" (one of ${[...FIELD_TYPES].join(', ')})`);
181
184
  continue;
182
185
  }
183
- if (f.type === 'enum' && !(f.options && f.options.length))
184
- err(fat, 'an enum needs options');
186
+ if (f.type === 'enum') {
187
+ if (f.list && f.options)
188
+ err(fat, 'an enum has options (fixed) or a list (edited by the admin), not both');
189
+ else if (f.list) {
190
+ if (!(data.lists && data.lists[f.list]))
191
+ err(fat, `"${f.list}" isn't a list in data.lists`);
192
+ }
193
+ else if (!(f.options && f.options.length))
194
+ err(fat, 'an enum needs options, or a list the admin edits');
195
+ }
185
196
  if ((f.type === 'ref' || f.type === 'ref[]') && !(f.to && (typeIds.has(f.to) || PLATFORM_REFS.has(f.to)))) {
186
197
  err(fat, `"to" must name a declared type or product/contact/proof`);
187
198
  }
@@ -190,6 +201,15 @@ export function validate(manifest, opts = {}) {
190
201
  if (f.public && f.zone && f.zone !== 'data')
191
202
  err(fat, `a ${f.zone}-zone field can't be public — only the data zone is readable publicly`);
192
203
  }
204
+ for (const k of ['label', 'sublabel', 'activeField', 'orderField']) {
205
+ const name = type[k];
206
+ if (name !== undefined && !(typeof name === 'string' && name in fields))
207
+ err(`${at}.${k}`, `"${name}" isn't a field`);
208
+ }
209
+ if (type.activeField && fields[type.activeField] && fields[type.activeField].type !== 'boolean')
210
+ err(`${at}.activeField`, 'must name a boolean field');
211
+ if (type.orderField && fields[type.orderField] && fields[type.orderField].type !== 'number')
212
+ err(`${at}.orderField`, 'must name a number field');
193
213
  for (const k of (type.listing && type.listing.sort) || [])
194
214
  if (!(k.replace(/^-/, '') in fields))
195
215
  err(`${at}.listing.sort`, `"${k}" isn't a field`);
@@ -205,6 +225,22 @@ export function validate(manifest, opts = {}) {
205
225
  const get = (type.read && type.read.get) || std.get;
206
226
  recipes[typeId] = Object.assign(Object.assign({ list: (type.read && type.read.list) || std.list }, (get ? { get } : {})), responseShape(type));
207
227
  }
228
+ for (const [listId, list] of Object.entries(data.lists || {})) {
229
+ const at = `data.lists.${listId}`;
230
+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(listId))
231
+ err(at, 'list ids are lowercase letters, digits and dashes (e.g. "hold-reasons")');
232
+ if (!list || !list.label)
233
+ err(`${at}.label`, 'say what the list is, e.g. "Hold reasons"');
234
+ const codes = new Set();
235
+ for (const [i, v] of ((list && list.values) || []).entries()) {
236
+ if (!v || typeof v.code !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(v.code))
237
+ err(`${at}.values[${i}]`, 'each value needs a code: letters, digits, dots, dashes');
238
+ else if (codes.has(v.code))
239
+ err(`${at}.values[${i}]`, `"${v.code}" is in the list twice`);
240
+ else
241
+ codes.add(v.code);
242
+ }
243
+ }
208
244
  }
209
245
  // ---- headless
210
246
  if (headless) {