@proveanything/smartlinks 2.2.1 → 2.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/realtime.d.ts +3 -0
- package/dist/api/realtime.js +10 -2
- package/dist/dataChanged.d.ts +74 -0
- package/dist/dataChanged.js +162 -0
- package/dist/docs/API_SUMMARY.md +4 -4
- package/dist/docs/caching.md +32 -3
- package/dist/docs/data-changed.md +91 -0
- package/dist/docs/iframe-responder.md +11 -0
- package/dist/docs/overview.md +1 -0
- package/dist/docs/realtime.md +10 -0
- package/dist/docs/standard-query.md +12 -3
- package/dist/http.d.ts +6 -3
- package/dist/http.js +48 -19
- package/dist/iframeResponder.d.ts +7 -0
- package/dist/iframeResponder.js +10 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/types/realtime.d.ts +5 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/docs/API_SUMMARY.md +4 -4
- package/docs/caching.md +32 -3
- package/docs/data-changed.md +91 -0
- package/docs/iframe-responder.md +11 -0
- package/docs/overview.md +1 -0
- package/docs/realtime.md +10 -0
- package/docs/standard-query.md +12 -3
- package/package.json +1 -1
package/dist/api/realtime.d.ts
CHANGED
|
@@ -25,6 +25,9 @@ export declare function channel(scope: RealtimeScope & {
|
|
|
25
25
|
* records, products). Filter by `type` ('product' | 'proof' | 'asset' | 'record' | 'collection' |
|
|
26
26
|
* 'collection.apps' | 'settings'), `id`, `appId`, `recordType`, `productId`, `proofId`.
|
|
27
27
|
*
|
|
28
|
+
* A change with no `id` means many things of that type changed (an import): a `{ type, id }` filter
|
|
29
|
+
* hears it too, so check `change.id` before assuming it is yours.
|
|
30
|
+
*
|
|
28
31
|
* ```ts
|
|
29
32
|
* const off = realtime.onChange({ collectionId }, { type: "record", appId, recordType: "entry" }, () => refetch())
|
|
30
33
|
* ```
|
package/dist/api/realtime.js
CHANGED
|
@@ -194,8 +194,13 @@ export function channel(scope, name) {
|
|
|
194
194
|
}
|
|
195
195
|
function matches(change, filter) {
|
|
196
196
|
for (const k of ["type", "id", "appId", "recordType", "productId", "proofId", "kind"]) {
|
|
197
|
-
if (filter[k]
|
|
198
|
-
|
|
197
|
+
if (filter[k] === undefined || change[k] === filter[k])
|
|
198
|
+
continue;
|
|
199
|
+
// A change that names no id is about many things of its type (an import sends one
|
|
200
|
+
// { type: 'product' } in place of thousands): whoever follows one of them by type and id hears it.
|
|
201
|
+
if (k === "id" && change.id == null && filter.type !== undefined)
|
|
202
|
+
continue;
|
|
203
|
+
return false;
|
|
199
204
|
}
|
|
200
205
|
return true;
|
|
201
206
|
}
|
|
@@ -206,6 +211,9 @@ function matches(change, filter) {
|
|
|
206
211
|
* records, products). Filter by `type` ('product' | 'proof' | 'asset' | 'record' | 'collection' |
|
|
207
212
|
* 'collection.apps' | 'settings'), `id`, `appId`, `recordType`, `productId`, `proofId`.
|
|
208
213
|
*
|
|
214
|
+
* A change with no `id` means many things of that type changed (an import): a `{ type, id }` filter
|
|
215
|
+
* hears it too, so check `change.id` before assuming it is yours.
|
|
216
|
+
*
|
|
209
217
|
* ```ts
|
|
210
218
|
* const off = realtime.onChange({ collectionId }, { type: "record", appId, recordType: "entry" }, () => refetch())
|
|
211
219
|
* ```
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/** One thing that changed. The same words as a realtime change (`RealtimeChangeEvent`). */
|
|
2
|
+
export interface DataChange {
|
|
3
|
+
/** 'product' | 'proof' | 'asset' | 'record' | 'contact' | 'collection' | 'settings' | 'appConfig' | … */
|
|
4
|
+
type: string;
|
|
5
|
+
id?: string;
|
|
6
|
+
productId?: string;
|
|
7
|
+
proofId?: string;
|
|
8
|
+
appId?: string;
|
|
9
|
+
recordType?: string;
|
|
10
|
+
/** 'created' | 'updated' | 'deleted', when the host knows. */
|
|
11
|
+
status?: string;
|
|
12
|
+
}
|
|
13
|
+
/** What the host sends (and what `postDataChanged` takes). */
|
|
14
|
+
export interface DataChangedMessage {
|
|
15
|
+
collectionId?: string;
|
|
16
|
+
/** What changed. Leave out (or empty) when the host can't say: "something in this collection changed". */
|
|
17
|
+
changes?: DataChange[];
|
|
18
|
+
/** Who made the change, when the host knows: 'assistant' | 'app' | 'person' | … */
|
|
19
|
+
source?: string;
|
|
20
|
+
}
|
|
21
|
+
/** What an app's listener is given. */
|
|
22
|
+
export interface DataChangedEvent {
|
|
23
|
+
collectionId?: string;
|
|
24
|
+
/** What changed. Empty means the host couldn't say: treat everything you show as possibly changed. */
|
|
25
|
+
changes: DataChange[];
|
|
26
|
+
source?: string;
|
|
27
|
+
/**
|
|
28
|
+
* Does this event say (or leave open) that this thing changed? True when a change matches every field
|
|
29
|
+
* given, and always true when the host couldn't say what changed.
|
|
30
|
+
*
|
|
31
|
+
* @example if (e.touches({ type: 'product', id: productId })) refetch()
|
|
32
|
+
*/
|
|
33
|
+
touches(what: Partial<DataChange>): boolean;
|
|
34
|
+
}
|
|
35
|
+
export declare const DATA_CHANGED = "smartlinks:data-changed";
|
|
36
|
+
type Forget = (pathPart?: string) => void;
|
|
37
|
+
/** The event an app's listener gets, from a raw message. Null when the message isn't one of ours. */
|
|
38
|
+
export declare function toDataChangedEvent(data: unknown): DataChangedEvent | null;
|
|
39
|
+
/**
|
|
40
|
+
* Start listening for the host's message (once, and only inside a frame). `initializeApi` calls this
|
|
41
|
+
* with the cache's own forget, so kept reads are dropped even in an app that never calls
|
|
42
|
+
* `onDataChanged`.
|
|
43
|
+
*/
|
|
44
|
+
export declare function watchDataChanged(forgetFn?: Forget): void;
|
|
45
|
+
/**
|
|
46
|
+
* Hear when the host says records changed behind this page's back (the assistant applied a change,
|
|
47
|
+
* another app saved). By the time the listener runs, the SDK has already forgotten the reads it kept
|
|
48
|
+
* for them: read again and show what comes back. Only messages from the parent window are taken.
|
|
49
|
+
* Returns a function that stops listening. Does nothing outside a frame.
|
|
50
|
+
*
|
|
51
|
+
* A form the person has started typing in should not be overwritten: re-fill it only when it is
|
|
52
|
+
* untouched, otherwise say the record was changed elsewhere and offer the new version.
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* // React Query: re-read the open product and the list
|
|
56
|
+
* useEffect(() => SL.onDataChanged((e) => {
|
|
57
|
+
* if (e.collectionId && e.collectionId !== collectionId) return
|
|
58
|
+
* if (e.touches({ type: 'product' })) queryClient.invalidateQueries({ queryKey: ['products'] })
|
|
59
|
+
* if (e.touches({ type: 'product', id: productId })) queryClient.invalidateQueries({ queryKey: ['product', collectionId, productId] })
|
|
60
|
+
* }), [collectionId, productId])
|
|
61
|
+
*/
|
|
62
|
+
export declare function onDataChanged(handler: (e: DataChangedEvent) => void): () => void;
|
|
63
|
+
/**
|
|
64
|
+
* Host side: tell an embedded app that records changed. Send it after a change the app did not make
|
|
65
|
+
* itself: an assistant's change set applied or undone, a save in another app, a change heard on the
|
|
66
|
+
* realtime feed. Leave `changes` out when you can't say what changed.
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* SL.postDataChanged(iframe.contentWindow, { collectionId, changes: [{ type: 'product', id }], source: 'assistant' })
|
|
70
|
+
*/
|
|
71
|
+
export declare function postDataChanged(target: Window | null | undefined, message?: DataChangedMessage, targetOrigin?: string): void;
|
|
72
|
+
/** Tests only: forget every listener and the cache hand-over, and stop listening. */
|
|
73
|
+
export declare function _resetDataChanged(): void;
|
|
74
|
+
export {};
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// src/dataChanged.ts
|
|
2
|
+
// DATA CHANGED — the host tells an embedded app that records changed behind its back: the assistant
|
|
3
|
+
// applied a change, another app saved, another person edited. One message:
|
|
4
|
+
// host → app { type: 'smartlinks:data-changed', collectionId?, changes?: DataChange[], source? }
|
|
5
|
+
// The SDK in the app's frame forgets the reads it kept for those records, then calls the app's
|
|
6
|
+
// listeners so the open screen can read again. Ids only, never data: the app re-reads through the
|
|
7
|
+
// normal API. See docs/data-changed.md.
|
|
8
|
+
//
|
|
9
|
+
// This file must not import ./http (http starts the listener): the cache is handed in.
|
|
10
|
+
export const DATA_CHANGED = 'smartlinks:data-changed';
|
|
11
|
+
const FIELDS = ['id', 'productId', 'proofId', 'appId', 'recordType', 'status'];
|
|
12
|
+
let forget = null;
|
|
13
|
+
let listening = false;
|
|
14
|
+
const handlers = new Set();
|
|
15
|
+
function inIframe() {
|
|
16
|
+
return typeof window !== 'undefined' && !!window.parent && window.parent !== window;
|
|
17
|
+
}
|
|
18
|
+
function clean(list) {
|
|
19
|
+
if (!Array.isArray(list))
|
|
20
|
+
return [];
|
|
21
|
+
const out = [];
|
|
22
|
+
for (const raw of list) {
|
|
23
|
+
if (!raw || typeof raw !== 'object')
|
|
24
|
+
continue;
|
|
25
|
+
const o = raw;
|
|
26
|
+
if (typeof o.type !== 'string' || !o.type)
|
|
27
|
+
continue;
|
|
28
|
+
const c = { type: o.type };
|
|
29
|
+
for (const k of FIELDS)
|
|
30
|
+
if (typeof o[k] === 'string' && o[k])
|
|
31
|
+
c[k] = o[k];
|
|
32
|
+
out.push(c);
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
/** Does `change` match every field given in `what`? */
|
|
37
|
+
function matches(change, what) {
|
|
38
|
+
if (what.type && change.type !== what.type)
|
|
39
|
+
return false;
|
|
40
|
+
for (const k of FIELDS) {
|
|
41
|
+
if (k === 'status')
|
|
42
|
+
continue;
|
|
43
|
+
// A change that doesn't name the field leaves it open: "a product changed" touches every product.
|
|
44
|
+
if (what[k] != null && change[k] != null && change[k] !== what[k])
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
/** The event an app's listener gets, from a raw message. Null when the message isn't one of ours. */
|
|
50
|
+
export function toDataChangedEvent(data) {
|
|
51
|
+
if (!data || typeof data !== 'object')
|
|
52
|
+
return null;
|
|
53
|
+
const d = data;
|
|
54
|
+
if (d.type !== DATA_CHANGED)
|
|
55
|
+
return null;
|
|
56
|
+
const changes = clean(d.changes);
|
|
57
|
+
return Object.assign(Object.assign(Object.assign(Object.assign({}, (typeof d.collectionId === 'string' && d.collectionId ? { collectionId: d.collectionId } : {})), { changes }), (typeof d.source === 'string' && d.source ? { source: d.source } : {})), { touches: (what) => changes.length === 0 || changes.some((c) => matches(c, what || {})) });
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Forget the reads the SDK kept for what changed. Products and proofs have known addresses; anything
|
|
61
|
+
* else, or "something changed", clears everything kept for the collection (everything, with no collection).
|
|
62
|
+
*/
|
|
63
|
+
function forgetKept(e) {
|
|
64
|
+
if (!forget)
|
|
65
|
+
return;
|
|
66
|
+
const cid = e.collectionId ? `/collection/${encodeURIComponent(e.collectionId)}` : '';
|
|
67
|
+
const known = e.changes.length > 0 && e.changes.every((c) => c.type === 'product' || c.type === 'proof');
|
|
68
|
+
try {
|
|
69
|
+
if (!known) {
|
|
70
|
+
forget(cid || undefined);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
// One product, its lists, and the proofs under it all live below these.
|
|
74
|
+
forget(`${cid}/product`);
|
|
75
|
+
if (e.changes.some((c) => c.type === 'proof'))
|
|
76
|
+
forget(`${cid}/proof`);
|
|
77
|
+
}
|
|
78
|
+
catch (_a) {
|
|
79
|
+
/* a cache that can't be cleared must not stop the app hearing about the change */
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function onMessage(ev) {
|
|
83
|
+
if (ev.source !== window.parent)
|
|
84
|
+
return;
|
|
85
|
+
const e = toDataChangedEvent(ev.data);
|
|
86
|
+
if (!e)
|
|
87
|
+
return;
|
|
88
|
+
forgetKept(e);
|
|
89
|
+
for (const h of [...handlers]) {
|
|
90
|
+
try {
|
|
91
|
+
h(e);
|
|
92
|
+
}
|
|
93
|
+
catch ( /* one listener failing must not stop the others */_a) { /* one listener failing must not stop the others */ }
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Start listening for the host's message (once, and only inside a frame). `initializeApi` calls this
|
|
98
|
+
* with the cache's own forget, so kept reads are dropped even in an app that never calls
|
|
99
|
+
* `onDataChanged`.
|
|
100
|
+
*/
|
|
101
|
+
export function watchDataChanged(forgetFn) {
|
|
102
|
+
if (forgetFn)
|
|
103
|
+
forget = forgetFn;
|
|
104
|
+
if (listening || !inIframe())
|
|
105
|
+
return;
|
|
106
|
+
listening = true;
|
|
107
|
+
window.addEventListener('message', onMessage);
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Hear when the host says records changed behind this page's back (the assistant applied a change,
|
|
111
|
+
* another app saved). By the time the listener runs, the SDK has already forgotten the reads it kept
|
|
112
|
+
* for them: read again and show what comes back. Only messages from the parent window are taken.
|
|
113
|
+
* Returns a function that stops listening. Does nothing outside a frame.
|
|
114
|
+
*
|
|
115
|
+
* A form the person has started typing in should not be overwritten: re-fill it only when it is
|
|
116
|
+
* untouched, otherwise say the record was changed elsewhere and offer the new version.
|
|
117
|
+
*
|
|
118
|
+
* @example
|
|
119
|
+
* // React Query: re-read the open product and the list
|
|
120
|
+
* useEffect(() => SL.onDataChanged((e) => {
|
|
121
|
+
* if (e.collectionId && e.collectionId !== collectionId) return
|
|
122
|
+
* if (e.touches({ type: 'product' })) queryClient.invalidateQueries({ queryKey: ['products'] })
|
|
123
|
+
* if (e.touches({ type: 'product', id: productId })) queryClient.invalidateQueries({ queryKey: ['product', collectionId, productId] })
|
|
124
|
+
* }), [collectionId, productId])
|
|
125
|
+
*/
|
|
126
|
+
export function onDataChanged(handler) {
|
|
127
|
+
if (typeof handler !== 'function' || !inIframe())
|
|
128
|
+
return () => { };
|
|
129
|
+
watchDataChanged();
|
|
130
|
+
handlers.add(handler);
|
|
131
|
+
return () => { handlers.delete(handler); };
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Host side: tell an embedded app that records changed. Send it after a change the app did not make
|
|
135
|
+
* itself: an assistant's change set applied or undone, a save in another app, a change heard on the
|
|
136
|
+
* realtime feed. Leave `changes` out when you can't say what changed.
|
|
137
|
+
*
|
|
138
|
+
* @example
|
|
139
|
+
* SL.postDataChanged(iframe.contentWindow, { collectionId, changes: [{ type: 'product', id }], source: 'assistant' })
|
|
140
|
+
*/
|
|
141
|
+
export function postDataChanged(target, message = {}, targetOrigin = '*') {
|
|
142
|
+
if (!target)
|
|
143
|
+
return;
|
|
144
|
+
try {
|
|
145
|
+
target.postMessage(Object.assign(Object.assign(Object.assign({ type: DATA_CHANGED }, (message.collectionId ? { collectionId: message.collectionId } : {})), { changes: clean(message.changes) }), (message.source ? { source: message.source } : {})), targetOrigin);
|
|
146
|
+
}
|
|
147
|
+
catch (_a) {
|
|
148
|
+
/* ignore */
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/** Tests only: forget every listener and the cache hand-over, and stop listening. */
|
|
152
|
+
export function _resetDataChanged() {
|
|
153
|
+
handlers.clear();
|
|
154
|
+
forget = null;
|
|
155
|
+
if (listening && typeof window !== 'undefined') {
|
|
156
|
+
try {
|
|
157
|
+
window.removeEventListener('message', onMessage);
|
|
158
|
+
}
|
|
159
|
+
catch ( /* ignore */_a) { /* ignore */ }
|
|
160
|
+
}
|
|
161
|
+
listening = false;
|
|
162
|
+
}
|
package/dist/docs/API_SUMMARY.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Smartlinks API Summary
|
|
2
2
|
|
|
3
|
-
Version: 2.2.
|
|
3
|
+
Version: 2.2.4 | Generated: 2026-12-02T15:08:47.460Z
|
|
4
4
|
|
|
5
5
|
This is a concise summary of all available API functions and types.
|
|
6
6
|
|
|
@@ -260,7 +260,7 @@ Returns true if the SDK currently has any auth credential set (bearer token or A
|
|
|
260
260
|
serveStaleOnOffline?: boolean
|
|
261
261
|
clearOnPageLoad?: boolean
|
|
262
262
|
}) → `void`
|
|
263
|
-
Configure the SDK's built-in in-memory GET cache. The cache is transparent — it sits inside the HTTP layer and requires no changes to your existing API calls.
|
|
263
|
+
Configure the SDK's built-in in-memory GET cache. The cache is transparent — it sits inside the HTTP layer and requires no changes to your existing API calls. Public GET requests benefit automatically. Admin GETs (`/admin/...`) are never kept, whatever is set here: see docs/caching.md. Per-resource rules (collections/products → 1 h, proofs → 30 s, etc.) override this value. in-memory only (`'none'`, default). Ignored in Node.js. fallback, from the original fetch time (default: 7 days). `SmartlinksOfflineError` with stale data instead of propagating the network error. caches on page load/refresh. IndexedDB persists for offline. ```ts // Enable IndexedDB persistence for offline support configureSdkCache({ persistence: 'indexeddb' }) // Disable cache entirely in test environments configureSdkCache({ enabled: false }) // Keep caches across page refreshes (not recommended for production) configureSdkCache({ clearOnPageLoad: false }) ```
|
|
264
264
|
|
|
265
265
|
**invalidateCache**(urlPattern?: string, options?: InvalidateCacheOptions) → `void`
|
|
266
266
|
Manually invalidate entries in the SDK's GET cache. Note: the GET cache is **in-memory, per page load** (with an optional L2 IndexedDB layer when persistence is enabled) — it does not persist across reloads unless you opt into persistence, so it rarely needs disabling "for correctness". *contains* this string is removed). With `{ exact: true }`, matches the path precisely. Omit to wipe the entire cache. ```ts invalidateCache() // clear everything invalidateCache('/collection/abc123') // that collection AND everything under it invalidateCache('/collection/abc123', { exact: true }) // ONLY that collection entry invalidateCache('/products/') // all canonical plural product responses ```
|
|
@@ -271,7 +271,7 @@ Manually invalidate entries in the SDK's GET cache. Note: the GET cache is **in-
|
|
|
271
271
|
Upload a FormData payload via proxy with progress events using chunked postMessage. Parent is expected to implement the counterpart protocol.
|
|
272
272
|
|
|
273
273
|
**request**(path: string) → `Promise<T>`
|
|
274
|
-
Internal helper that performs a GET request to `${baseURL}${path}`, injecting headers for apiKey or bearerToken if present. Cache pipeline (when caching is not skipped): L1 hit → return from memory (no I/O) L2 hit → return from IndexedDB, promote to L1 (no network) Miss → fetch from network, store in L1 + L2 Offline → serve stale L2 entry via SmartlinksOfflineError (if persistence enabled) Concurrent identical GETs share one in-flight promise (deduplication). Node-safe: IndexedDB calls are no-ops when IDB is unavailable.
|
|
274
|
+
Internal helper that performs a GET request to `${baseURL}${path}`, injecting headers for apiKey or bearerToken if present. Cache pipeline (when caching is not skipped): L1 hit → return from memory (no I/O) L2 hit → return from IndexedDB, promote to L1 (no network) Miss → fetch from network, store in L1 + L2 Offline → serve stale L2 entry via SmartlinksOfflineError (if persistence enabled) Admin paths (`/admin/...`) are never kept (see isAdminPath): every call goes to the network. Concurrent identical GETs share one in-flight promise (deduplication), admin ones included. Node-safe: IndexedDB calls are no-ops when IDB is unavailable.
|
|
275
275
|
|
|
276
276
|
**post**(path: string,
|
|
277
277
|
body: any,
|
|
@@ -16547,7 +16547,7 @@ Reset rate limit for a user
|
|
|
16547
16547
|
One of your app's declared channels (manifest `realtime.channels`). ```ts const draw = realtime.channel({ collectionId, appId }, "draw") const off = draw.subscribe("status", (m) => setStatus(m.data)) await draw.publish("status", { phase: "spinning" }) // if the channel lets this viewer publish ```
|
|
16548
16548
|
|
|
16549
16549
|
**onChange**(scope: RealtimeScope, filter: RealtimeChangeFilter, onChangeFn: (change: RealtimeChangeEvent) → `void`
|
|
16550
|
-
Something changed: refetch it. IDs only — never data. Admins of the collection see every change; everyone else sees changes to public things (public app records, products). Filter by `type` ('product' | 'proof' | 'asset' | 'record' | 'collection' | 'collection.apps' | 'settings'), `id`, `appId`, `recordType`, `productId`, `proofId`. ```ts const off = realtime.onChange({ collectionId }, { type: "record", appId, recordType: "entry" }, () => refetch()) ```
|
|
16550
|
+
Something changed: refetch it. IDs only — never data. Admins of the collection see every change; everyone else sees changes to public things (public app records, products). Filter by `type` ('product' | 'proof' | 'asset' | 'record' | 'collection' | 'collection.apps' | 'settings'), `id`, `appId`, `recordType`, `productId`, `proofId`. A change with no `id` means many things of that type changed (an import): a `{ type, id }` filter hears it too, so check `change.id` before assuming it is yours. ```ts const off = realtime.onChange({ collectionId }, { type: "record", appId, recordType: "entry" }, () => refetch()) ```
|
|
16551
16551
|
|
|
16552
16552
|
**onStaffChange**(scope: RealtimeScope & { appId: string }, filter: RealtimeChangeFilter, onChangeFn: (change: RealtimeChangeEvent) → `void`
|
|
16553
16553
|
Something this APP works on changed: one of its work orders, a container or stock it moved, or one of its own records. For the people who use the app, admins or not: someone hears these when they are in one of the app's user groups (the ones its server functions are limited to, or `realtime.staff` in its manifest), and so does a collection admin. IDs only — refetch through your own API. Types: 'workOrder' (`id`, `appId`), 'container' (`id`, `kind` = its container type), 'stock' (`id` = the container, `productId`), 'record' (`id`, `recordType`). Filter as with `onChange`; an empty filter hears them all. ```ts // A production app's screens refetch when anything on the floor changes. useEffect(() => realtime.onStaffChange({ collectionId, appId }, {}, () => queryClient.invalidateQueries()), [collectionId, appId]) ```
|
package/dist/docs/caching.md
CHANGED
|
@@ -23,7 +23,7 @@ This ensures that **page refreshes always fetch fresh data from the server**, wh
|
|
|
23
23
|
### How It Works
|
|
24
24
|
|
|
25
25
|
1. **During browsing (same page load)**:
|
|
26
|
-
- API requests are cached in memory and sessionStorage
|
|
26
|
+
- Public API requests are cached in memory and sessionStorage (admin requests never are, see below)
|
|
27
27
|
- Subsequent identical requests serve from cache (fast!)
|
|
28
28
|
- TTL rules determine cache freshness (30s - 1h depending on resource)
|
|
29
29
|
|
|
@@ -99,9 +99,35 @@ configureSdkCache({
|
|
|
99
99
|
- **Only used as offline fallback**, not for normal requests
|
|
100
100
|
- ~50MB+ quota
|
|
101
101
|
|
|
102
|
+
## Admin reads are never kept
|
|
103
|
+
|
|
104
|
+
Since 2.2.2, a GET on an admin path (`/admin/...`) always goes to the network. Its answer is not kept in
|
|
105
|
+
memory and not written to IndexedDB, whatever `configureSdkCache` says.
|
|
106
|
+
|
|
107
|
+
Why: an admin screen is where records change, and not only through your page. Another app in another
|
|
108
|
+
frame, the assistant, or another person may have saved since you last read. Each frame has its own cache
|
|
109
|
+
and a write only forgets reads of its own address, so a kept admin answer showed old data. Worse, code
|
|
110
|
+
that reads a record, changes part of it and saves the whole wrote the old data back over the newer.
|
|
111
|
+
|
|
112
|
+
What this means for an admin app:
|
|
113
|
+
|
|
114
|
+
- `products.get(collectionId, productId, true)`, `proof.get(..., true)`, `appConfiguration.getConfig({ admin: true })`
|
|
115
|
+
and every other admin read return what the server has now.
|
|
116
|
+
- You no longer need `invalidateCache(...)` before a read that feeds a save or fills an edit form. Calls
|
|
117
|
+
already in your code are harmless.
|
|
118
|
+
- Identical admin GETs asked at the same moment still share one network call, so several components
|
|
119
|
+
mounting together do not multiply requests.
|
|
120
|
+
- Your own page state is still yours: a query library's `staleTime`, or a form filled once on load, will
|
|
121
|
+
show what it loaded until you re-read. Re-read before a save that replaces a whole record.
|
|
122
|
+
- To hear that a record changed behind your page's back (the assistant applied a change, another app
|
|
123
|
+
saved), use `onDataChanged`: see `docs/data-changed.md`. The SDK forgets the reads it kept for what
|
|
124
|
+
changed before it tells you.
|
|
125
|
+
|
|
126
|
+
Public reads (`/public/...`) keep the rules below.
|
|
127
|
+
|
|
102
128
|
## TTL Rules
|
|
103
129
|
|
|
104
|
-
Different API resources have different cache lifetimes:
|
|
130
|
+
Different public API resources have different cache lifetimes:
|
|
105
131
|
|
|
106
132
|
| Resource | TTL | Reason |
|
|
107
133
|
|----------|-----|--------|
|
|
@@ -110,7 +136,10 @@ Different API resources have different cache lifetimes:
|
|
|
110
136
|
| `/product/*` | 1 hour | Products are relatively stable |
|
|
111
137
|
| `/variant/*` | 1 hour | Variants rarely change |
|
|
112
138
|
| `/collection/*` | 1 hour | Collections are stable |
|
|
113
|
-
| Everything else |
|
|
139
|
+
| Everything else | 15 seconds | Default safety |
|
|
140
|
+
|
|
141
|
+
Never kept, on any path: every `/admin/...` read (above), sign-in and account calls, `/me` calls, bookings,
|
|
142
|
+
user groups, option pickers, tag ranges, realtime tokens and a collection's translation revision.
|
|
114
143
|
|
|
115
144
|
## Manual Cache Control
|
|
116
145
|
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# Data changed: an open screen reads again
|
|
2
|
+
|
|
3
|
+
Since 2.2.3.
|
|
4
|
+
|
|
5
|
+
An admin screen is not the only thing that changes records. The assistant applies a change, another app
|
|
6
|
+
saves, another person edits. The screen that is open keeps showing what it loaded, and the person has to
|
|
7
|
+
reload to see the change. **Data changed** is the host telling the app, so it can read again.
|
|
8
|
+
|
|
9
|
+
It is one message, host to app:
|
|
10
|
+
|
|
11
|
+
```js
|
|
12
|
+
{ type: 'smartlinks:data-changed', collectionId: 'acme', changes: [{ type: 'product', id: 'p_1', status: 'updated' }], source: 'assistant' }
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Ids only, never data. The app reads again through the normal API, with the normal permissions.
|
|
16
|
+
|
|
17
|
+
## In an app
|
|
18
|
+
|
|
19
|
+
```tsx
|
|
20
|
+
import * as SL from '@proveanything/smartlinks'
|
|
21
|
+
|
|
22
|
+
useEffect(() => SL.onDataChanged((e) => {
|
|
23
|
+
if (e.collectionId && e.collectionId !== collectionId) return
|
|
24
|
+
if (e.touches({ type: 'product' })) queryClient.invalidateQueries({ queryKey: ['products'] })
|
|
25
|
+
if (e.touches({ type: 'product', id: productId })) queryClient.invalidateQueries({ queryKey: ['product', collectionId, productId] })
|
|
26
|
+
}), [collectionId, productId])
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
- `SL.onDataChanged(listener)` returns a function that stops listening. It does nothing outside a frame.
|
|
30
|
+
- Before your listener runs, the SDK has already forgotten the reads it kept for what changed, so the
|
|
31
|
+
next read returns what the server has now. This happens even in an app that never calls `onDataChanged`.
|
|
32
|
+
- `e.changes` is what changed. It is **empty when the host can't say**: treat everything you show from
|
|
33
|
+
the collection as possibly changed.
|
|
34
|
+
- `e.touches({ type, id })` answers "might this be about my record?". It is true when a change matches
|
|
35
|
+
every field you give, and always true when `e.changes` is empty.
|
|
36
|
+
- `e.source` is who made the change when the host knows (`'assistant'`, `'app'`, `'person'`).
|
|
37
|
+
|
|
38
|
+
### A form the person is filling in
|
|
39
|
+
|
|
40
|
+
Reading again must not throw away typing.
|
|
41
|
+
|
|
42
|
+
- **Untouched form:** fill it again from the new record.
|
|
43
|
+
- **Form with changes in it:** keep what the person typed. Say plainly that the record was changed
|
|
44
|
+
elsewhere, and offer to load the new version. Do not save the old copy over the new one without asking.
|
|
45
|
+
|
|
46
|
+
Compare the record you loaded with the one you just read (its `updatedAt`, or the fields the form shows)
|
|
47
|
+
before saying anything: "something changed" is not always about the record on screen.
|
|
48
|
+
|
|
49
|
+
### One change word per kind of record
|
|
50
|
+
|
|
51
|
+
`type` uses the same words as realtime changes (`docs/realtime.md`): `product`, `proof`, `asset`, `record`,
|
|
52
|
+
`collection`, `collection.apps`, `settings`. A host may also send its own words for other records
|
|
53
|
+
(`contact`, `appConfig`). `id` is the record's id; `productId`, `proofId`, `appId` and `recordType` say
|
|
54
|
+
where it lives when that helps.
|
|
55
|
+
|
|
56
|
+
## In a host
|
|
57
|
+
|
|
58
|
+
Send it after a change the app did not make itself.
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
// Any host
|
|
62
|
+
SL.postDataChanged(iframe.contentWindow, { collectionId, changes: [{ type: 'product', id }], source: 'assistant' })
|
|
63
|
+
|
|
64
|
+
// With IframeResponder
|
|
65
|
+
responder.dataChanged({ collectionId, changes: [{ type: 'product', id }] })
|
|
66
|
+
|
|
67
|
+
// When you can't say what changed
|
|
68
|
+
SL.postDataChanged(iframe.contentWindow, { collectionId })
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Studio sends it to every open app frame when an assistant change set is applied or undone, when the
|
|
72
|
+
assistant finishes a step that writes, and when its turn ends.
|
|
73
|
+
|
|
74
|
+
## What it is not
|
|
75
|
+
|
|
76
|
+
- It is not the realtime feed. `SL.realtime.onChange` (`docs/realtime.md`) is the server telling a page
|
|
77
|
+
that something changed, over a live connection. Data changed is the host passing a change it already
|
|
78
|
+
knows about into a frame, with no connection of the app's own. A host that listens to the realtime
|
|
79
|
+
feed can pass those changes on with the same message, so an app needs only `onDataChanged`.
|
|
80
|
+
- It does not carry data and it is not a save. Nothing is written by sending or hearing it.
|
|
81
|
+
|
|
82
|
+
## What the SDK forgets
|
|
83
|
+
|
|
84
|
+
| The host says | The SDK forgets |
|
|
85
|
+
|---|---|
|
|
86
|
+
| Only products and proofs changed | Everything kept under that collection's products (the product, its lists, its proofs) |
|
|
87
|
+
| Anything else, or nothing specific | Everything kept for that collection |
|
|
88
|
+
| No collection given | Everything kept |
|
|
89
|
+
|
|
90
|
+
Admin reads are never kept in the first place (`docs/caching.md`), so this matters for public reads an
|
|
91
|
+
admin screen makes, and for apps on an SDK before 2.2.2.
|
|
@@ -430,6 +430,17 @@ The responder handles these message types from the iframe:
|
|
|
430
430
|
}
|
|
431
431
|
```
|
|
432
432
|
|
|
433
|
+
### Data changed
|
|
434
|
+
|
|
435
|
+
Parent → Iframe, after a change the app did not make itself (an assistant's change applied, a save in
|
|
436
|
+
another app). The app's SDK forgets the reads it kept and its open screen reads again. See
|
|
437
|
+
`docs/data-changed.md`.
|
|
438
|
+
|
|
439
|
+
```ts
|
|
440
|
+
responder.dataChanged({ collectionId, changes: [{ type: 'product', id }], source: 'assistant' })
|
|
441
|
+
// → { type: 'smartlinks:data-changed', collectionId, changes: [...], source }
|
|
442
|
+
```
|
|
443
|
+
|
|
433
444
|
## TypeScript Support
|
|
434
445
|
|
|
435
446
|
All types are exported for full TypeScript support:
|
package/dist/docs/overview.md
CHANGED
|
@@ -100,6 +100,7 @@ The SmartLinks SDK (`@proveanything/smartlinks`) includes comprehensive document
|
|
|
100
100
|
| **App Data Storage** | `docs/app-data-storage.md` | Decision guide: pick between `appConfiguration` / `userAppData` / `app.records` |
|
|
101
101
|
| **Attestations** | `docs/attestations.md` | Postgres attestations API (proof-level user/admin data; replaces the legacy Firestore path) |
|
|
102
102
|
| **Caching** | `docs/caching.md` | SDK GET cache tiers + TTLs, `invalidateCache({ exact })`, and `force`/push guidance |
|
|
103
|
+
| **Data Changed** | `docs/data-changed.md` | The host tells an open admin screen that records changed behind its back (the assistant, another app): `onDataChanged`, `postDataChanged`, and what to do with a form in mid-edit |
|
|
103
104
|
| **Comms & Broadcasts** | `docs/comms.md` | Transactional comms, campaigns, consent, push |
|
|
104
105
|
| **Container Tracking** | `docs/container-tracking.md` | Physical/logical **item** container groupings — *not* app containers (see containers.md) |
|
|
105
106
|
| **Lots** | `docs/lots.md` | Cross-SKU production "Lot" entity |
|
package/dist/docs/realtime.md
CHANGED
|
@@ -31,6 +31,10 @@ off()
|
|
|
31
31
|
installed, removed or switched), `settings`.
|
|
32
32
|
- **Filter fields:** `type`, `id`, `appId`, `recordType`, `productId`, `proofId`. Every field you give
|
|
33
33
|
must match.
|
|
34
|
+
- **Many at once:** a large import doesn't send thousands of product changes. After the first few it
|
|
35
|
+
sends one `{ type: 'product' }` with no `id`, meaning "many products changed". A listener that follows
|
|
36
|
+
one thing, `{ type: 'product', id }`, hears that too (from SDK 2.2.4), since its product may be among
|
|
37
|
+
them. Read again as usual; `change.id` is empty, so don't rely on it.
|
|
34
38
|
- **Who hears what:**
|
|
35
39
|
- a collection's **admins** hear every change;
|
|
36
40
|
- **everyone else** hears changes to public things (public app records, products).
|
|
@@ -136,3 +140,9 @@ example, `scan`: a tag they just scanned with Sidekick on another device.
|
|
|
136
140
|
`realtime.getPublicToken()` and `realtime.getAdminToken()` return raw provider tokens for the old
|
|
137
141
|
`collection:{id}:*` and `interaction:{uid}` channels. They still work, but publishing is now limited to
|
|
138
142
|
the collection's admins. Move to `channel` / `onChange` / `onMine`.
|
|
143
|
+
|
|
144
|
+
## Changes the host already knows about
|
|
145
|
+
|
|
146
|
+
An app inside Studio does not need its own connection to hear that the assistant or another app changed
|
|
147
|
+
a record: the host passes that into the frame as `smartlinks:data-changed`. Listen with
|
|
148
|
+
`SL.onDataChanged` (`docs/data-changed.md`).
|
|
@@ -100,9 +100,18 @@ await app.records.query(collectionId, appId, {
|
|
|
100
100
|
|
|
101
101
|
## Sorting and paging
|
|
102
102
|
|
|
103
|
-
`orderBy` takes up to 3 `{ field: 'asc' | 'desc' }
|
|
104
|
-
|
|
105
|
-
|
|
103
|
+
`orderBy` takes up to 3 `{ field: 'asc' | 'desc' }`, on the fields that can sort (ask `queryFields`: their
|
|
104
|
+
`can` includes `sort`). A few of them can be empty, such as an app record's `startsAt` and `expiresAt`:
|
|
105
|
+
the rows without one come **last**, whichever way you sort, and paging carries on through them. Pass the
|
|
106
|
+
answer's `nextCursor` as `cursor` for the next page, with the **same** `where` and `orderBy`; a cursor from
|
|
107
|
+
a different query is refused.
|
|
108
|
+
|
|
109
|
+
```typescript
|
|
110
|
+
// An app's events, latest first; any without a date at the end
|
|
111
|
+
await app.records.query(collectionId, appId, { where: { recordType: 'event' }, orderBy: [{ startsAt: 'desc' }], limit: 100 })
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
A page holds at most 200 rows (`limit` 1–200). To read more, follow `nextCursor`.
|
|
106
115
|
|
|
107
116
|
```typescript
|
|
108
117
|
let cursor: string | null = null
|
package/dist/http.d.ts
CHANGED
|
@@ -178,9 +178,10 @@ export declare function hasAuthCredentials(): boolean;
|
|
|
178
178
|
* Configure the SDK's built-in in-memory GET cache.
|
|
179
179
|
*
|
|
180
180
|
* The cache is transparent — it sits inside the HTTP layer and requires no
|
|
181
|
-
* changes to your existing API calls.
|
|
181
|
+
* changes to your existing API calls. Public GET requests benefit automatically.
|
|
182
|
+
* Admin GETs (`/admin/...`) are never kept, whatever is set here: see docs/caching.md.
|
|
182
183
|
*
|
|
183
|
-
* @param options.enabled
|
|
184
|
+
* @param options.enabled - Turn caching on/off entirely (default: `true`)
|
|
184
185
|
* @param options.ttlMs - Default time-to-live in milliseconds (default: `60_000`).
|
|
185
186
|
* Per-resource rules (collections/products → 1 h,
|
|
186
187
|
* proofs → 30 s, etc.) override this value.
|
|
@@ -263,7 +264,9 @@ export declare function proxyUploadFormData<T>(path: string, formData: FormData,
|
|
|
263
264
|
* Miss → fetch from network, store in L1 + L2
|
|
264
265
|
* Offline → serve stale L2 entry via SmartlinksOfflineError (if persistence enabled)
|
|
265
266
|
*
|
|
266
|
-
*
|
|
267
|
+
* Admin paths (`/admin/...`) are never kept (see isAdminPath): every call goes to the network.
|
|
268
|
+
*
|
|
269
|
+
* Concurrent identical GETs share one in-flight promise (deduplication), admin ones included.
|
|
267
270
|
* Node-safe: IndexedDB calls are no-ops when IDB is unavailable.
|
|
268
271
|
*/
|
|
269
272
|
export declare function request<T>(path: string): Promise<T>;
|
package/dist/http.js
CHANGED
|
@@ -259,6 +259,18 @@ function shouldSkipCache(path) {
|
|
|
259
259
|
return true;
|
|
260
260
|
return false;
|
|
261
261
|
}
|
|
262
|
+
/**
|
|
263
|
+
* Admin reads are never kept: not in memory, not in IndexedDB.
|
|
264
|
+
*
|
|
265
|
+
* An admin screen is where records change, and not only through this page: another app in another frame,
|
|
266
|
+
* the assistant, another person. Each frame has its own cache and a write only forgets reads of its own
|
|
267
|
+
* address, so a kept answer showed old data, and code that reads a record, changes part of it and saves the
|
|
268
|
+
* whole wrote the old data back over the newer. Admin calls are few; they always go to the network.
|
|
269
|
+
* Identical admin GETs asked at the same moment still share one network call.
|
|
270
|
+
*/
|
|
271
|
+
function isAdminPath(path) {
|
|
272
|
+
return /^\/?admin(\/|\?|$)/i.test(path);
|
|
273
|
+
}
|
|
262
274
|
/** Evict the oldest (LRU) entry when the cache is at capacity. */
|
|
263
275
|
function evictLruIfNeeded() {
|
|
264
276
|
while (httpCache.size >= cacheMaxEntries) {
|
|
@@ -322,6 +334,12 @@ function setHttpCacheEntry(cacheKey, data) {
|
|
|
322
334
|
evictLruIfNeeded();
|
|
323
335
|
httpCache.set(cacheKey, { data, timestamp: Date.now() });
|
|
324
336
|
}
|
|
337
|
+
/** A shared call that is not kept has finished: drop its entry, unless a newer call has taken the key. */
|
|
338
|
+
function forgetInFlight(cacheKey, promise) {
|
|
339
|
+
var _a;
|
|
340
|
+
if (((_a = httpCache.get(cacheKey)) === null || _a === void 0 ? void 0 : _a.promise) === promise)
|
|
341
|
+
httpCache.delete(cacheKey);
|
|
342
|
+
}
|
|
325
343
|
/**
|
|
326
344
|
* Auto-invalidate all cached GET entries whose key contains `path`.
|
|
327
345
|
* Called automatically after any mutating request (POST / PUT / PATCH / DELETE).
|
|
@@ -543,8 +561,11 @@ function normalizeErrorResponse(responseBody, statusCode) {
|
|
|
543
561
|
* @property {boolean} [options.proxyMode] - (Optional) Tells the API that it is running in an iframe via parent proxy
|
|
544
562
|
*/
|
|
545
563
|
import { iframe } from './iframe.js';
|
|
564
|
+
import { watchDataChanged } from './dataChanged.js';
|
|
546
565
|
export function initializeApi(options) {
|
|
547
566
|
var _a;
|
|
567
|
+
// The host may say records changed behind this page's back (docs/data-changed.md): forget kept reads then.
|
|
568
|
+
watchDataChanged((pathPart) => invalidateCache(pathPart));
|
|
548
569
|
// Normalize baseURL by removing trailing slashes.
|
|
549
570
|
const normalizedBaseURL = options.baseURL.replace(/\/+$/g, "");
|
|
550
571
|
// ------------------------------------------------------------------
|
|
@@ -757,9 +778,10 @@ export function hasAuthCredentials() {
|
|
|
757
778
|
* Configure the SDK's built-in in-memory GET cache.
|
|
758
779
|
*
|
|
759
780
|
* The cache is transparent — it sits inside the HTTP layer and requires no
|
|
760
|
-
* changes to your existing API calls.
|
|
781
|
+
* changes to your existing API calls. Public GET requests benefit automatically.
|
|
782
|
+
* Admin GETs (`/admin/...`) are never kept, whatever is set here: see docs/caching.md.
|
|
761
783
|
*
|
|
762
|
-
* @param options.enabled
|
|
784
|
+
* @param options.enabled - Turn caching on/off entirely (default: `true`)
|
|
763
785
|
* @param options.ttlMs - Default time-to-live in milliseconds (default: `60_000`).
|
|
764
786
|
* Per-resource rules (collections/products → 1 h,
|
|
765
787
|
* proofs → 30 s, etc.) override this value.
|
|
@@ -1333,21 +1355,25 @@ export async function proxyUploadFormData(path, formData, onProgress) {
|
|
|
1333
1355
|
* Miss → fetch from network, store in L1 + L2
|
|
1334
1356
|
* Offline → serve stale L2 entry via SmartlinksOfflineError (if persistence enabled)
|
|
1335
1357
|
*
|
|
1336
|
-
*
|
|
1358
|
+
* Admin paths (`/admin/...`) are never kept (see isAdminPath): every call goes to the network.
|
|
1359
|
+
*
|
|
1360
|
+
* Concurrent identical GETs share one in-flight promise (deduplication), admin ones included.
|
|
1337
1361
|
* Node-safe: IndexedDB calls are no-ops when IDB is unavailable.
|
|
1338
1362
|
*/
|
|
1339
1363
|
export async function request(path) {
|
|
1340
1364
|
await ensureAuthReady();
|
|
1341
1365
|
const skipCache = shouldSkipCache(path);
|
|
1366
|
+
// keep = the answer may be served again later; without it (admin) only the in-flight call is shared.
|
|
1367
|
+
const keep = !skipCache && !isAdminPath(path);
|
|
1342
1368
|
const cacheKey = buildCacheKey(path);
|
|
1343
|
-
const ttl =
|
|
1344
|
-
if (
|
|
1369
|
+
const ttl = keep ? getTtlForPath(path) : 0;
|
|
1370
|
+
if (!keep) {
|
|
1345
1371
|
httpCacheStats.skips++;
|
|
1346
|
-
httpDebug('GET skip-cache', { path });
|
|
1372
|
+
httpDebug(skipCache ? 'GET skip-cache' : 'GET admin (not kept)', { path });
|
|
1347
1373
|
}
|
|
1348
1374
|
if (!skipCache) {
|
|
1349
1375
|
// 1. L1 hit — return from memory immediately
|
|
1350
|
-
const l1 = getHttpCacheHit(cacheKey, ttl);
|
|
1376
|
+
const l1 = keep ? getHttpCacheHit(cacheKey, ttl) : null;
|
|
1351
1377
|
if (l1 !== null) {
|
|
1352
1378
|
httpCacheStats.l1Hits++;
|
|
1353
1379
|
httpDebug('GET L1 hit', { path, ttlMs: ttl });
|
|
@@ -1370,7 +1396,7 @@ export async function request(path) {
|
|
|
1370
1396
|
const fetchPromise = (async () => {
|
|
1371
1397
|
// 3a. L2 (IndexedDB) check — warms L1 from persistent storage without a
|
|
1372
1398
|
// network round-trip. First await → in-flight registration runs before this resolves.
|
|
1373
|
-
if (
|
|
1399
|
+
if (keep && cachePersistence !== 'none') {
|
|
1374
1400
|
const l2 = await idbGet(cacheKey);
|
|
1375
1401
|
if (l2 && Date.now() - l2.timestamp <= ttl) {
|
|
1376
1402
|
httpCacheStats.l2Hits++;
|
|
@@ -1428,7 +1454,7 @@ export async function request(path) {
|
|
|
1428
1454
|
data = (await response.json());
|
|
1429
1455
|
}
|
|
1430
1456
|
// Persist to L2 on success (fire-and-forget — never blocks the caller)
|
|
1431
|
-
if (
|
|
1457
|
+
if (keep && cachePersistence !== 'none') {
|
|
1432
1458
|
idbSet(cacheKey, { data, timestamp: Date.now(), persistedAt: Date.now() }).catch(() => { });
|
|
1433
1459
|
}
|
|
1434
1460
|
return data;
|
|
@@ -1436,7 +1462,7 @@ export async function request(path) {
|
|
|
1436
1462
|
catch (fetchErr) {
|
|
1437
1463
|
// 3c. Offline fallback: when the network fails, serve stale L2 data if
|
|
1438
1464
|
// it's still within the persistence TTL window.
|
|
1439
|
-
if (
|
|
1465
|
+
if (keep && cachePersistence !== 'none' && cacheServeStaleOnOffline && isNetworkError(fetchErr)) {
|
|
1440
1466
|
const l2 = await idbGet(cacheKey);
|
|
1441
1467
|
if (l2 && Date.now() - l2.timestamp <= cachePersistenceTtlMs) {
|
|
1442
1468
|
logDebug('[smartlinks] GET offline fallback (L2)', { path, cachedAt: l2.timestamp });
|
|
@@ -1447,11 +1473,12 @@ export async function request(path) {
|
|
|
1447
1473
|
}
|
|
1448
1474
|
})();
|
|
1449
1475
|
// Register the in-flight promise so concurrent identical GETs share it.
|
|
1450
|
-
// On resolve → promote to L1; on reject → remove so the
|
|
1476
|
+
// On resolve → promote to L1 (or, for an answer that is not kept, forget it); on reject → remove so the
|
|
1477
|
+
// next call retries.
|
|
1451
1478
|
if (!skipCache) {
|
|
1452
1479
|
evictLruIfNeeded();
|
|
1453
1480
|
httpCache.set(cacheKey, { data: null, timestamp: Date.now(), promise: fetchPromise });
|
|
1454
|
-
fetchPromise.then((data) => setHttpCacheEntry(cacheKey, data), () => httpCache.delete(cacheKey));
|
|
1481
|
+
fetchPromise.then((data) => (keep ? setHttpCacheEntry(cacheKey, data) : forgetInFlight(cacheKey, fetchPromise)), () => httpCache.delete(cacheKey));
|
|
1455
1482
|
}
|
|
1456
1483
|
return fetchPromise;
|
|
1457
1484
|
}
|
|
@@ -1653,11 +1680,13 @@ export async function requestWithOptions(path, options) {
|
|
|
1653
1680
|
const method = (options.method || 'GET').toUpperCase();
|
|
1654
1681
|
const isGet = method === 'GET';
|
|
1655
1682
|
const skipCache = isGet ? shouldSkipCache(path) : true;
|
|
1683
|
+
// As in request(): an admin answer is never kept, only its in-flight call is shared.
|
|
1684
|
+
const keep = !skipCache && !isAdminPath(path);
|
|
1656
1685
|
const cacheKey = buildCacheKey(path);
|
|
1657
|
-
const ttl =
|
|
1686
|
+
const ttl = keep ? getTtlForPath(path) : 0;
|
|
1658
1687
|
if (!skipCache) {
|
|
1659
1688
|
// L1 hit
|
|
1660
|
-
const cached = getHttpCacheHit(cacheKey, ttl);
|
|
1689
|
+
const cached = keep ? getHttpCacheHit(cacheKey, ttl) : null;
|
|
1661
1690
|
if (cached !== null) {
|
|
1662
1691
|
logDebug('[smartlinks] GET cache hit (requestWithOptions/L1)', { path });
|
|
1663
1692
|
return cached;
|
|
@@ -1671,7 +1700,7 @@ export async function requestWithOptions(path, options) {
|
|
|
1671
1700
|
}
|
|
1672
1701
|
const fetchPromise = (async () => {
|
|
1673
1702
|
// L2 (IndexedDB) check for GETs — first await, so in-flight registration runs before it resolves
|
|
1674
|
-
if (
|
|
1703
|
+
if (keep && cachePersistence !== 'none') {
|
|
1675
1704
|
const l2 = await idbGet(cacheKey);
|
|
1676
1705
|
if (l2 && Date.now() - l2.timestamp <= ttl) {
|
|
1677
1706
|
logDebug('[smartlinks] GET cache hit (requestWithOptions/L2)', { path });
|
|
@@ -1686,7 +1715,7 @@ export async function requestWithOptions(path, options) {
|
|
|
1686
1715
|
if (!isGet) {
|
|
1687
1716
|
invalidateCacheForPath(path);
|
|
1688
1717
|
}
|
|
1689
|
-
else if (
|
|
1718
|
+
else if (keep && cachePersistence !== 'none') {
|
|
1690
1719
|
idbSet(cacheKey, { data: result, timestamp: Date.now(), persistedAt: Date.now() }).catch(() => { });
|
|
1691
1720
|
}
|
|
1692
1721
|
return result;
|
|
@@ -1737,14 +1766,14 @@ export async function requestWithOptions(path, options) {
|
|
|
1737
1766
|
if (!isGet) {
|
|
1738
1767
|
invalidateCacheForPath(path);
|
|
1739
1768
|
}
|
|
1740
|
-
else if (
|
|
1769
|
+
else if (keep && cachePersistence !== 'none') {
|
|
1741
1770
|
idbSet(cacheKey, { data: rwoResult, timestamp: Date.now(), persistedAt: Date.now() }).catch(() => { });
|
|
1742
1771
|
}
|
|
1743
1772
|
return rwoResult;
|
|
1744
1773
|
}
|
|
1745
1774
|
catch (fetchErr) {
|
|
1746
1775
|
// Offline fallback for GETs
|
|
1747
|
-
if (isGet &&
|
|
1776
|
+
if (isGet && keep && cachePersistence !== 'none' && cacheServeStaleOnOffline && isNetworkError(fetchErr)) {
|
|
1748
1777
|
const l2 = await idbGet(cacheKey);
|
|
1749
1778
|
if (l2 && Date.now() - l2.timestamp <= cachePersistenceTtlMs) {
|
|
1750
1779
|
logDebug('[smartlinks] GET offline fallback (requestWithOptions/L2)', { path, cachedAt: l2.timestamp });
|
|
@@ -1758,7 +1787,7 @@ export async function requestWithOptions(path, options) {
|
|
|
1758
1787
|
if (!skipCache) {
|
|
1759
1788
|
evictLruIfNeeded();
|
|
1760
1789
|
httpCache.set(cacheKey, { data: null, timestamp: Date.now(), promise: fetchPromise });
|
|
1761
|
-
fetchPromise.then((data) => setHttpCacheEntry(cacheKey, data), () => httpCache.delete(cacheKey));
|
|
1790
|
+
fetchPromise.then((data) => (keep ? setHttpCacheEntry(cacheKey, data) : forgetInFlight(cacheKey, fetchPromise)), () => httpCache.delete(cacheKey));
|
|
1762
1791
|
}
|
|
1763
1792
|
return fetchPromise;
|
|
1764
1793
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { IframeResponderOptions, CachedData } from './types/iframeResponder.js';
|
|
2
|
+
import type { DataChangedMessage } from './dataChanged.js';
|
|
2
3
|
/**
|
|
3
4
|
* Parent-side iframe responder for SmartLinks microapp embedding.
|
|
4
5
|
*
|
|
@@ -63,6 +64,12 @@ export declare class IframeResponder {
|
|
|
63
64
|
params?: Record<string, string>;
|
|
64
65
|
highlight?: string;
|
|
65
66
|
}): boolean;
|
|
67
|
+
/**
|
|
68
|
+
* Tell the app that records changed behind its back (an assistant's change applied, a save in another
|
|
69
|
+
* app): its SDK forgets the reads it kept and its open screen reads again. Leave `changes` out when you
|
|
70
|
+
* can't say what changed. See docs/data-changed.md.
|
|
71
|
+
*/
|
|
72
|
+
dataChanged(message?: DataChangedMessage): void;
|
|
66
73
|
/** True once the app has said it follows `smartlinks:navigate`. */
|
|
67
74
|
get isNavigable(): boolean;
|
|
68
75
|
/**
|
package/dist/iframeResponder.js
CHANGED
|
@@ -5,6 +5,7 @@ import * as cache from './cache.js';
|
|
|
5
5
|
import { collection } from './api/collection.js';
|
|
6
6
|
import { getBaseURL, hasAuthCredentials } from './http.js';
|
|
7
7
|
import { trackTranslation } from './translationActivity.js';
|
|
8
|
+
import { postDataChanged } from './dataChanged.js';
|
|
8
9
|
/**
|
|
9
10
|
* Parent-side iframe responder for SmartLinks microapp embedding.
|
|
10
11
|
*
|
|
@@ -110,6 +111,15 @@ export class IframeResponder {
|
|
|
110
111
|
return false;
|
|
111
112
|
}
|
|
112
113
|
}
|
|
114
|
+
/**
|
|
115
|
+
* Tell the app that records changed behind its back (an assistant's change applied, a save in another
|
|
116
|
+
* app): its SDK forgets the reads it kept and its open screen reads again. Leave `changes` out when you
|
|
117
|
+
* can't say what changed. See docs/data-changed.md.
|
|
118
|
+
*/
|
|
119
|
+
dataChanged(message = {}) {
|
|
120
|
+
var _a;
|
|
121
|
+
postDataChanged((_a = this.iframe) === null || _a === void 0 ? void 0 : _a.contentWindow, message);
|
|
122
|
+
}
|
|
113
123
|
/** True once the app has said it follows `smartlinks:navigate`. */
|
|
114
124
|
get isNavigable() {
|
|
115
125
|
return this.navigable;
|
package/dist/index.d.ts
CHANGED
|
@@ -6,6 +6,8 @@ export { readContext } from "./context.js";
|
|
|
6
6
|
export * as i18n from "./i18n.js";
|
|
7
7
|
export * as adminViews from "./adminViews.js";
|
|
8
8
|
export type { NavigateRequest, NavigateTarget, OpenAppRequest, Destination, DestinationInfo, DestinationAbout, OpenParams, OpenResult } from "./adminViews.js";
|
|
9
|
+
export { onDataChanged, postDataChanged } from "./dataChanged.js";
|
|
10
|
+
export type { DataChange, DataChangedEvent, DataChangedMessage } from "./dataChanged.js";
|
|
9
11
|
export { widgetStyleVars, widgetStyleControls, readableOn, WIDGET_STYLE_VARS } from "./widgetStyle.js";
|
|
10
12
|
export type { WidgetStyling } from "./widgetStyle.js";
|
|
11
13
|
export type { SmartLinksContext } from "./context.js";
|
package/dist/index.js
CHANGED
|
@@ -11,6 +11,8 @@ import * as i18n_1 from "./i18n.js";
|
|
|
11
11
|
export { i18n_1 as i18n };
|
|
12
12
|
import * as adminViews_1 from "./adminViews.js";
|
|
13
13
|
export { adminViews_1 as adminViews };
|
|
14
|
+
// Data changed: the host tells an open screen to read again (docs/data-changed.md)
|
|
15
|
+
export { onDataChanged, postDataChanged } from "./dataChanged.js";
|
|
14
16
|
export { widgetStyleVars, widgetStyleControls, readableOn, WIDGET_STYLE_VARS } from "./widgetStyle.js";
|
|
15
17
|
import * as cache_1 from './cache.js';
|
|
16
18
|
export { cache_1 as cache };
|
package/dist/types/realtime.d.ts
CHANGED
|
@@ -62,6 +62,7 @@ export interface RealtimeChangeEvent {
|
|
|
62
62
|
* and, on an app's staff feed (`onStaffChange`): 'workOrder' | 'container' | 'stock'.
|
|
63
63
|
*/
|
|
64
64
|
type: string;
|
|
65
|
+
/** The thing that changed. Absent when many of this type changed at once (an import): read them all again. */
|
|
65
66
|
id?: string;
|
|
66
67
|
appId?: string;
|
|
67
68
|
recordType?: string;
|
|
@@ -73,7 +74,10 @@ export interface RealtimeChangeEvent {
|
|
|
73
74
|
kind?: string;
|
|
74
75
|
at: number;
|
|
75
76
|
}
|
|
76
|
-
/**
|
|
77
|
+
/**
|
|
78
|
+
* Which changes to hear about — every field given must match. One exception: with `type` and `id`
|
|
79
|
+
* given, a change of that type that names no id ("many changed") is heard too.
|
|
80
|
+
*/
|
|
77
81
|
export interface RealtimeChangeFilter {
|
|
78
82
|
type?: string;
|
|
79
83
|
id?: string;
|
package/dist/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const SDK_VERSION = "2.2.
|
|
1
|
+
export declare const SDK_VERSION = "2.2.4";
|
package/dist/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// Generated by scripts/write-version.mjs from package.json. Do not edit.
|
|
2
|
-
export const SDK_VERSION = "2.2.
|
|
2
|
+
export const SDK_VERSION = "2.2.4";
|
package/docs/API_SUMMARY.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Smartlinks API Summary
|
|
2
2
|
|
|
3
|
-
Version: 2.2.
|
|
3
|
+
Version: 2.2.4 | Generated: 2026-12-02T15:08:47.460Z
|
|
4
4
|
|
|
5
5
|
This is a concise summary of all available API functions and types.
|
|
6
6
|
|
|
@@ -260,7 +260,7 @@ Returns true if the SDK currently has any auth credential set (bearer token or A
|
|
|
260
260
|
serveStaleOnOffline?: boolean
|
|
261
261
|
clearOnPageLoad?: boolean
|
|
262
262
|
}) → `void`
|
|
263
|
-
Configure the SDK's built-in in-memory GET cache. The cache is transparent — it sits inside the HTTP layer and requires no changes to your existing API calls.
|
|
263
|
+
Configure the SDK's built-in in-memory GET cache. The cache is transparent — it sits inside the HTTP layer and requires no changes to your existing API calls. Public GET requests benefit automatically. Admin GETs (`/admin/...`) are never kept, whatever is set here: see docs/caching.md. Per-resource rules (collections/products → 1 h, proofs → 30 s, etc.) override this value. in-memory only (`'none'`, default). Ignored in Node.js. fallback, from the original fetch time (default: 7 days). `SmartlinksOfflineError` with stale data instead of propagating the network error. caches on page load/refresh. IndexedDB persists for offline. ```ts // Enable IndexedDB persistence for offline support configureSdkCache({ persistence: 'indexeddb' }) // Disable cache entirely in test environments configureSdkCache({ enabled: false }) // Keep caches across page refreshes (not recommended for production) configureSdkCache({ clearOnPageLoad: false }) ```
|
|
264
264
|
|
|
265
265
|
**invalidateCache**(urlPattern?: string, options?: InvalidateCacheOptions) → `void`
|
|
266
266
|
Manually invalidate entries in the SDK's GET cache. Note: the GET cache is **in-memory, per page load** (with an optional L2 IndexedDB layer when persistence is enabled) — it does not persist across reloads unless you opt into persistence, so it rarely needs disabling "for correctness". *contains* this string is removed). With `{ exact: true }`, matches the path precisely. Omit to wipe the entire cache. ```ts invalidateCache() // clear everything invalidateCache('/collection/abc123') // that collection AND everything under it invalidateCache('/collection/abc123', { exact: true }) // ONLY that collection entry invalidateCache('/products/') // all canonical plural product responses ```
|
|
@@ -271,7 +271,7 @@ Manually invalidate entries in the SDK's GET cache. Note: the GET cache is **in-
|
|
|
271
271
|
Upload a FormData payload via proxy with progress events using chunked postMessage. Parent is expected to implement the counterpart protocol.
|
|
272
272
|
|
|
273
273
|
**request**(path: string) → `Promise<T>`
|
|
274
|
-
Internal helper that performs a GET request to `${baseURL}${path}`, injecting headers for apiKey or bearerToken if present. Cache pipeline (when caching is not skipped): L1 hit → return from memory (no I/O) L2 hit → return from IndexedDB, promote to L1 (no network) Miss → fetch from network, store in L1 + L2 Offline → serve stale L2 entry via SmartlinksOfflineError (if persistence enabled) Concurrent identical GETs share one in-flight promise (deduplication). Node-safe: IndexedDB calls are no-ops when IDB is unavailable.
|
|
274
|
+
Internal helper that performs a GET request to `${baseURL}${path}`, injecting headers for apiKey or bearerToken if present. Cache pipeline (when caching is not skipped): L1 hit → return from memory (no I/O) L2 hit → return from IndexedDB, promote to L1 (no network) Miss → fetch from network, store in L1 + L2 Offline → serve stale L2 entry via SmartlinksOfflineError (if persistence enabled) Admin paths (`/admin/...`) are never kept (see isAdminPath): every call goes to the network. Concurrent identical GETs share one in-flight promise (deduplication), admin ones included. Node-safe: IndexedDB calls are no-ops when IDB is unavailable.
|
|
275
275
|
|
|
276
276
|
**post**(path: string,
|
|
277
277
|
body: any,
|
|
@@ -16547,7 +16547,7 @@ Reset rate limit for a user
|
|
|
16547
16547
|
One of your app's declared channels (manifest `realtime.channels`). ```ts const draw = realtime.channel({ collectionId, appId }, "draw") const off = draw.subscribe("status", (m) => setStatus(m.data)) await draw.publish("status", { phase: "spinning" }) // if the channel lets this viewer publish ```
|
|
16548
16548
|
|
|
16549
16549
|
**onChange**(scope: RealtimeScope, filter: RealtimeChangeFilter, onChangeFn: (change: RealtimeChangeEvent) → `void`
|
|
16550
|
-
Something changed: refetch it. IDs only — never data. Admins of the collection see every change; everyone else sees changes to public things (public app records, products). Filter by `type` ('product' | 'proof' | 'asset' | 'record' | 'collection' | 'collection.apps' | 'settings'), `id`, `appId`, `recordType`, `productId`, `proofId`. ```ts const off = realtime.onChange({ collectionId }, { type: "record", appId, recordType: "entry" }, () => refetch()) ```
|
|
16550
|
+
Something changed: refetch it. IDs only — never data. Admins of the collection see every change; everyone else sees changes to public things (public app records, products). Filter by `type` ('product' | 'proof' | 'asset' | 'record' | 'collection' | 'collection.apps' | 'settings'), `id`, `appId`, `recordType`, `productId`, `proofId`. A change with no `id` means many things of that type changed (an import): a `{ type, id }` filter hears it too, so check `change.id` before assuming it is yours. ```ts const off = realtime.onChange({ collectionId }, { type: "record", appId, recordType: "entry" }, () => refetch()) ```
|
|
16551
16551
|
|
|
16552
16552
|
**onStaffChange**(scope: RealtimeScope & { appId: string }, filter: RealtimeChangeFilter, onChangeFn: (change: RealtimeChangeEvent) → `void`
|
|
16553
16553
|
Something this APP works on changed: one of its work orders, a container or stock it moved, or one of its own records. For the people who use the app, admins or not: someone hears these when they are in one of the app's user groups (the ones its server functions are limited to, or `realtime.staff` in its manifest), and so does a collection admin. IDs only — refetch through your own API. Types: 'workOrder' (`id`, `appId`), 'container' (`id`, `kind` = its container type), 'stock' (`id` = the container, `productId`), 'record' (`id`, `recordType`). Filter as with `onChange`; an empty filter hears them all. ```ts // A production app's screens refetch when anything on the floor changes. useEffect(() => realtime.onStaffChange({ collectionId, appId }, {}, () => queryClient.invalidateQueries()), [collectionId, appId]) ```
|
package/docs/caching.md
CHANGED
|
@@ -23,7 +23,7 @@ This ensures that **page refreshes always fetch fresh data from the server**, wh
|
|
|
23
23
|
### How It Works
|
|
24
24
|
|
|
25
25
|
1. **During browsing (same page load)**:
|
|
26
|
-
- API requests are cached in memory and sessionStorage
|
|
26
|
+
- Public API requests are cached in memory and sessionStorage (admin requests never are, see below)
|
|
27
27
|
- Subsequent identical requests serve from cache (fast!)
|
|
28
28
|
- TTL rules determine cache freshness (30s - 1h depending on resource)
|
|
29
29
|
|
|
@@ -99,9 +99,35 @@ configureSdkCache({
|
|
|
99
99
|
- **Only used as offline fallback**, not for normal requests
|
|
100
100
|
- ~50MB+ quota
|
|
101
101
|
|
|
102
|
+
## Admin reads are never kept
|
|
103
|
+
|
|
104
|
+
Since 2.2.2, a GET on an admin path (`/admin/...`) always goes to the network. Its answer is not kept in
|
|
105
|
+
memory and not written to IndexedDB, whatever `configureSdkCache` says.
|
|
106
|
+
|
|
107
|
+
Why: an admin screen is where records change, and not only through your page. Another app in another
|
|
108
|
+
frame, the assistant, or another person may have saved since you last read. Each frame has its own cache
|
|
109
|
+
and a write only forgets reads of its own address, so a kept admin answer showed old data. Worse, code
|
|
110
|
+
that reads a record, changes part of it and saves the whole wrote the old data back over the newer.
|
|
111
|
+
|
|
112
|
+
What this means for an admin app:
|
|
113
|
+
|
|
114
|
+
- `products.get(collectionId, productId, true)`, `proof.get(..., true)`, `appConfiguration.getConfig({ admin: true })`
|
|
115
|
+
and every other admin read return what the server has now.
|
|
116
|
+
- You no longer need `invalidateCache(...)` before a read that feeds a save or fills an edit form. Calls
|
|
117
|
+
already in your code are harmless.
|
|
118
|
+
- Identical admin GETs asked at the same moment still share one network call, so several components
|
|
119
|
+
mounting together do not multiply requests.
|
|
120
|
+
- Your own page state is still yours: a query library's `staleTime`, or a form filled once on load, will
|
|
121
|
+
show what it loaded until you re-read. Re-read before a save that replaces a whole record.
|
|
122
|
+
- To hear that a record changed behind your page's back (the assistant applied a change, another app
|
|
123
|
+
saved), use `onDataChanged`: see `docs/data-changed.md`. The SDK forgets the reads it kept for what
|
|
124
|
+
changed before it tells you.
|
|
125
|
+
|
|
126
|
+
Public reads (`/public/...`) keep the rules below.
|
|
127
|
+
|
|
102
128
|
## TTL Rules
|
|
103
129
|
|
|
104
|
-
Different API resources have different cache lifetimes:
|
|
130
|
+
Different public API resources have different cache lifetimes:
|
|
105
131
|
|
|
106
132
|
| Resource | TTL | Reason |
|
|
107
133
|
|----------|-----|--------|
|
|
@@ -110,7 +136,10 @@ Different API resources have different cache lifetimes:
|
|
|
110
136
|
| `/product/*` | 1 hour | Products are relatively stable |
|
|
111
137
|
| `/variant/*` | 1 hour | Variants rarely change |
|
|
112
138
|
| `/collection/*` | 1 hour | Collections are stable |
|
|
113
|
-
| Everything else |
|
|
139
|
+
| Everything else | 15 seconds | Default safety |
|
|
140
|
+
|
|
141
|
+
Never kept, on any path: every `/admin/...` read (above), sign-in and account calls, `/me` calls, bookings,
|
|
142
|
+
user groups, option pickers, tag ranges, realtime tokens and a collection's translation revision.
|
|
114
143
|
|
|
115
144
|
## Manual Cache Control
|
|
116
145
|
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# Data changed: an open screen reads again
|
|
2
|
+
|
|
3
|
+
Since 2.2.3.
|
|
4
|
+
|
|
5
|
+
An admin screen is not the only thing that changes records. The assistant applies a change, another app
|
|
6
|
+
saves, another person edits. The screen that is open keeps showing what it loaded, and the person has to
|
|
7
|
+
reload to see the change. **Data changed** is the host telling the app, so it can read again.
|
|
8
|
+
|
|
9
|
+
It is one message, host to app:
|
|
10
|
+
|
|
11
|
+
```js
|
|
12
|
+
{ type: 'smartlinks:data-changed', collectionId: 'acme', changes: [{ type: 'product', id: 'p_1', status: 'updated' }], source: 'assistant' }
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Ids only, never data. The app reads again through the normal API, with the normal permissions.
|
|
16
|
+
|
|
17
|
+
## In an app
|
|
18
|
+
|
|
19
|
+
```tsx
|
|
20
|
+
import * as SL from '@proveanything/smartlinks'
|
|
21
|
+
|
|
22
|
+
useEffect(() => SL.onDataChanged((e) => {
|
|
23
|
+
if (e.collectionId && e.collectionId !== collectionId) return
|
|
24
|
+
if (e.touches({ type: 'product' })) queryClient.invalidateQueries({ queryKey: ['products'] })
|
|
25
|
+
if (e.touches({ type: 'product', id: productId })) queryClient.invalidateQueries({ queryKey: ['product', collectionId, productId] })
|
|
26
|
+
}), [collectionId, productId])
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
- `SL.onDataChanged(listener)` returns a function that stops listening. It does nothing outside a frame.
|
|
30
|
+
- Before your listener runs, the SDK has already forgotten the reads it kept for what changed, so the
|
|
31
|
+
next read returns what the server has now. This happens even in an app that never calls `onDataChanged`.
|
|
32
|
+
- `e.changes` is what changed. It is **empty when the host can't say**: treat everything you show from
|
|
33
|
+
the collection as possibly changed.
|
|
34
|
+
- `e.touches({ type, id })` answers "might this be about my record?". It is true when a change matches
|
|
35
|
+
every field you give, and always true when `e.changes` is empty.
|
|
36
|
+
- `e.source` is who made the change when the host knows (`'assistant'`, `'app'`, `'person'`).
|
|
37
|
+
|
|
38
|
+
### A form the person is filling in
|
|
39
|
+
|
|
40
|
+
Reading again must not throw away typing.
|
|
41
|
+
|
|
42
|
+
- **Untouched form:** fill it again from the new record.
|
|
43
|
+
- **Form with changes in it:** keep what the person typed. Say plainly that the record was changed
|
|
44
|
+
elsewhere, and offer to load the new version. Do not save the old copy over the new one without asking.
|
|
45
|
+
|
|
46
|
+
Compare the record you loaded with the one you just read (its `updatedAt`, or the fields the form shows)
|
|
47
|
+
before saying anything: "something changed" is not always about the record on screen.
|
|
48
|
+
|
|
49
|
+
### One change word per kind of record
|
|
50
|
+
|
|
51
|
+
`type` uses the same words as realtime changes (`docs/realtime.md`): `product`, `proof`, `asset`, `record`,
|
|
52
|
+
`collection`, `collection.apps`, `settings`. A host may also send its own words for other records
|
|
53
|
+
(`contact`, `appConfig`). `id` is the record's id; `productId`, `proofId`, `appId` and `recordType` say
|
|
54
|
+
where it lives when that helps.
|
|
55
|
+
|
|
56
|
+
## In a host
|
|
57
|
+
|
|
58
|
+
Send it after a change the app did not make itself.
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
// Any host
|
|
62
|
+
SL.postDataChanged(iframe.contentWindow, { collectionId, changes: [{ type: 'product', id }], source: 'assistant' })
|
|
63
|
+
|
|
64
|
+
// With IframeResponder
|
|
65
|
+
responder.dataChanged({ collectionId, changes: [{ type: 'product', id }] })
|
|
66
|
+
|
|
67
|
+
// When you can't say what changed
|
|
68
|
+
SL.postDataChanged(iframe.contentWindow, { collectionId })
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Studio sends it to every open app frame when an assistant change set is applied or undone, when the
|
|
72
|
+
assistant finishes a step that writes, and when its turn ends.
|
|
73
|
+
|
|
74
|
+
## What it is not
|
|
75
|
+
|
|
76
|
+
- It is not the realtime feed. `SL.realtime.onChange` (`docs/realtime.md`) is the server telling a page
|
|
77
|
+
that something changed, over a live connection. Data changed is the host passing a change it already
|
|
78
|
+
knows about into a frame, with no connection of the app's own. A host that listens to the realtime
|
|
79
|
+
feed can pass those changes on with the same message, so an app needs only `onDataChanged`.
|
|
80
|
+
- It does not carry data and it is not a save. Nothing is written by sending or hearing it.
|
|
81
|
+
|
|
82
|
+
## What the SDK forgets
|
|
83
|
+
|
|
84
|
+
| The host says | The SDK forgets |
|
|
85
|
+
|---|---|
|
|
86
|
+
| Only products and proofs changed | Everything kept under that collection's products (the product, its lists, its proofs) |
|
|
87
|
+
| Anything else, or nothing specific | Everything kept for that collection |
|
|
88
|
+
| No collection given | Everything kept |
|
|
89
|
+
|
|
90
|
+
Admin reads are never kept in the first place (`docs/caching.md`), so this matters for public reads an
|
|
91
|
+
admin screen makes, and for apps on an SDK before 2.2.2.
|
package/docs/iframe-responder.md
CHANGED
|
@@ -430,6 +430,17 @@ The responder handles these message types from the iframe:
|
|
|
430
430
|
}
|
|
431
431
|
```
|
|
432
432
|
|
|
433
|
+
### Data changed
|
|
434
|
+
|
|
435
|
+
Parent → Iframe, after a change the app did not make itself (an assistant's change applied, a save in
|
|
436
|
+
another app). The app's SDK forgets the reads it kept and its open screen reads again. See
|
|
437
|
+
`docs/data-changed.md`.
|
|
438
|
+
|
|
439
|
+
```ts
|
|
440
|
+
responder.dataChanged({ collectionId, changes: [{ type: 'product', id }], source: 'assistant' })
|
|
441
|
+
// → { type: 'smartlinks:data-changed', collectionId, changes: [...], source }
|
|
442
|
+
```
|
|
443
|
+
|
|
433
444
|
## TypeScript Support
|
|
434
445
|
|
|
435
446
|
All types are exported for full TypeScript support:
|
package/docs/overview.md
CHANGED
|
@@ -100,6 +100,7 @@ The SmartLinks SDK (`@proveanything/smartlinks`) includes comprehensive document
|
|
|
100
100
|
| **App Data Storage** | `docs/app-data-storage.md` | Decision guide: pick between `appConfiguration` / `userAppData` / `app.records` |
|
|
101
101
|
| **Attestations** | `docs/attestations.md` | Postgres attestations API (proof-level user/admin data; replaces the legacy Firestore path) |
|
|
102
102
|
| **Caching** | `docs/caching.md` | SDK GET cache tiers + TTLs, `invalidateCache({ exact })`, and `force`/push guidance |
|
|
103
|
+
| **Data Changed** | `docs/data-changed.md` | The host tells an open admin screen that records changed behind its back (the assistant, another app): `onDataChanged`, `postDataChanged`, and what to do with a form in mid-edit |
|
|
103
104
|
| **Comms & Broadcasts** | `docs/comms.md` | Transactional comms, campaigns, consent, push |
|
|
104
105
|
| **Container Tracking** | `docs/container-tracking.md` | Physical/logical **item** container groupings — *not* app containers (see containers.md) |
|
|
105
106
|
| **Lots** | `docs/lots.md` | Cross-SKU production "Lot" entity |
|
package/docs/realtime.md
CHANGED
|
@@ -31,6 +31,10 @@ off()
|
|
|
31
31
|
installed, removed or switched), `settings`.
|
|
32
32
|
- **Filter fields:** `type`, `id`, `appId`, `recordType`, `productId`, `proofId`. Every field you give
|
|
33
33
|
must match.
|
|
34
|
+
- **Many at once:** a large import doesn't send thousands of product changes. After the first few it
|
|
35
|
+
sends one `{ type: 'product' }` with no `id`, meaning "many products changed". A listener that follows
|
|
36
|
+
one thing, `{ type: 'product', id }`, hears that too (from SDK 2.2.4), since its product may be among
|
|
37
|
+
them. Read again as usual; `change.id` is empty, so don't rely on it.
|
|
34
38
|
- **Who hears what:**
|
|
35
39
|
- a collection's **admins** hear every change;
|
|
36
40
|
- **everyone else** hears changes to public things (public app records, products).
|
|
@@ -136,3 +140,9 @@ example, `scan`: a tag they just scanned with Sidekick on another device.
|
|
|
136
140
|
`realtime.getPublicToken()` and `realtime.getAdminToken()` return raw provider tokens for the old
|
|
137
141
|
`collection:{id}:*` and `interaction:{uid}` channels. They still work, but publishing is now limited to
|
|
138
142
|
the collection's admins. Move to `channel` / `onChange` / `onMine`.
|
|
143
|
+
|
|
144
|
+
## Changes the host already knows about
|
|
145
|
+
|
|
146
|
+
An app inside Studio does not need its own connection to hear that the assistant or another app changed
|
|
147
|
+
a record: the host passes that into the frame as `smartlinks:data-changed`. Listen with
|
|
148
|
+
`SL.onDataChanged` (`docs/data-changed.md`).
|
package/docs/standard-query.md
CHANGED
|
@@ -100,9 +100,18 @@ await app.records.query(collectionId, appId, {
|
|
|
100
100
|
|
|
101
101
|
## Sorting and paging
|
|
102
102
|
|
|
103
|
-
`orderBy` takes up to 3 `{ field: 'asc' | 'desc' }
|
|
104
|
-
|
|
105
|
-
|
|
103
|
+
`orderBy` takes up to 3 `{ field: 'asc' | 'desc' }`, on the fields that can sort (ask `queryFields`: their
|
|
104
|
+
`can` includes `sort`). A few of them can be empty, such as an app record's `startsAt` and `expiresAt`:
|
|
105
|
+
the rows without one come **last**, whichever way you sort, and paging carries on through them. Pass the
|
|
106
|
+
answer's `nextCursor` as `cursor` for the next page, with the **same** `where` and `orderBy`; a cursor from
|
|
107
|
+
a different query is refused.
|
|
108
|
+
|
|
109
|
+
```typescript
|
|
110
|
+
// An app's events, latest first; any without a date at the end
|
|
111
|
+
await app.records.query(collectionId, appId, { where: { recordType: 'event' }, orderBy: [{ startsAt: 'desc' }], limit: 100 })
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
A page holds at most 200 rows (`limit` 1–200). To read more, follow `nextCursor`.
|
|
106
115
|
|
|
107
116
|
```typescript
|
|
108
117
|
let cursor: string | null = null
|