@proveanything/smartlinks 2.2.0 → 2.2.3
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/dataChanged.d.ts +74 -0
- package/dist/dataChanged.js +162 -0
- package/dist/docs/API_SUMMARY.md +3 -3
- package/dist/docs/caching.md +32 -3
- package/dist/docs/data-changed.md +91 -0
- package/dist/docs/i18n.md +41 -287
- package/dist/docs/iframe-responder.md +11 -0
- package/dist/docs/overview.md +1 -0
- package/dist/docs/realtime.md +6 -0
- package/dist/docs/standard-query.md +12 -3
- package/dist/http.d.ts +6 -3
- package/dist/http.js +48 -19
- package/dist/i18n.d.ts +14 -2
- package/dist/i18n.js +23 -6
- 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/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/docs/API_SUMMARY.md +3 -3
- package/docs/caching.md +32 -3
- package/docs/data-changed.md +91 -0
- package/docs/i18n.md +41 -287
- package/docs/iframe-responder.md +11 -0
- package/docs/overview.md +1 -0
- package/docs/realtime.md +6 -0
- package/docs/standard-query.md +12 -3
- package/package.json +1 -1
package/dist/docs/i18n.md
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
# Internationalization (i18n): an app's own words
|
|
2
2
|
|
|
3
|
-
**Use the SDK's `i18n` helper** (SDK 2.1
|
|
4
|
-
|
|
3
|
+
**Use the SDK's `i18n` helper** (SDK 2.2.1+). Don't build your own language system (a `LanguageContext`,
|
|
4
|
+
your own detection, English/German/French written into components): that was the old scaffold, and
|
|
5
|
+
Forge's step 21 moves an app off it.
|
|
5
6
|
|
|
6
7
|
## How it works
|
|
7
8
|
|
|
8
9
|
1. **Your app keeps its English as keys** in `public/i18n/en.json`. The build ships it at
|
|
9
10
|
`<bundle>/i18n/en.json`. That is your only translation job: don't hard-code English in components.
|
|
10
|
-
2. **The platform translates.** When your app is published, SmartLinks translates the English into
|
|
11
|
-
|
|
11
|
+
2. **The platform translates, once.** When your app is published, SmartLinks translates the English into
|
|
12
|
+
the common languages it supports and adds `<bundle>/i18n/<lang>.json`: static files, one small fetch
|
|
13
|
+
before the first render, no lookups per label and no flash of English. Keys whose
|
|
12
14
|
English hasn't changed keep their earlier (possibly human-reviewed) translation. If you ship your own
|
|
13
15
|
`public/i18n/<lang>.json`, its keys win and the platform fills only the gaps.
|
|
14
16
|
3. **The host says which language.** Studio passes the person's own Studio language as `?lang=`, and later
|
|
@@ -29,7 +31,7 @@ export function useT() {
|
|
|
29
31
|
useSyncExternalStore(i18n.subscribe, i18n.snapshot)
|
|
30
32
|
return i18n.t
|
|
31
33
|
}
|
|
32
|
-
export const fmt = i18n.format // dates and
|
|
34
|
+
export const fmt = i18n.format // numbers, dates and money in the current language
|
|
33
35
|
```
|
|
34
36
|
|
|
35
37
|
```tsx
|
|
@@ -37,6 +39,7 @@ const t = useT()
|
|
|
37
39
|
<Button>{t('contacts.add')}</Button>
|
|
38
40
|
<span>{t('contacts.count', { count: rows.length })}</span>
|
|
39
41
|
<span>{fmt.date(contact.createdAt)}</span>
|
|
42
|
+
<span>{fmt.money(order.total, order.currency)}</span> {/* minor units: "1.299,50 €" in German */}
|
|
40
43
|
```
|
|
41
44
|
|
|
42
45
|
`public/i18n/en.json`:
|
|
@@ -61,297 +64,41 @@ const t = useT()
|
|
|
61
64
|
- `i18n.language()` is the language in use; `i18n.setLanguage(code)` switches; `i18n.has(key)` says
|
|
62
65
|
whether a real translation exists.
|
|
63
66
|
|
|
64
|
-
|
|
67
|
+
## Which languages: the business decides
|
|
65
68
|
|
|
66
|
-
|
|
69
|
+
An app shows only the languages the site has turned on. In Portal and Hub the host passes the visitor's
|
|
70
|
+
language (already limited to the site's languages); in Studio it's the person's Studio language. A
|
|
71
|
+
standalone page with no host should pass the site's languages, so a browser language is used only when
|
|
72
|
+
the site offers it:
|
|
67
73
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
This document explains the i18n system for SmartLinks apps, covering URL-based language selection, static translations, and dynamic overrides.
|
|
71
|
-
|
|
72
|
-
---
|
|
73
|
-
|
|
74
|
-
## Overview
|
|
75
|
-
|
|
76
|
-
The i18n system supports:
|
|
77
|
-
|
|
78
|
-
- **URL parameter language selection** (`?lang=de`) - Ideal for iframe embedding
|
|
79
|
-
- **Static translations** in JSON files - Fast, no API calls
|
|
80
|
-
- **Dynamic overrides** via SmartLinks appConfig - Customer-configurable
|
|
81
|
-
- **Type-safe translation keys** - Compile-time safety
|
|
82
|
-
- **Widget support** - Translations can be passed to embedded widgets
|
|
83
|
-
|
|
84
|
-
---
|
|
85
|
-
|
|
86
|
-
## Quick Start
|
|
87
|
-
|
|
88
|
-
### Using Translations in Components
|
|
89
|
-
|
|
90
|
-
```typescript
|
|
91
|
-
import { useLanguage } from '@/i18n';
|
|
92
|
-
|
|
93
|
-
export const MyComponent = () => {
|
|
94
|
-
const { t, lang } = useLanguage();
|
|
95
|
-
|
|
96
|
-
return (
|
|
97
|
-
<div>
|
|
98
|
-
<h1>{t('public.title')}</h1>
|
|
99
|
-
<p>{t('public.description')}</p>
|
|
100
|
-
<small>Language: {lang}</small>
|
|
101
|
-
</div>
|
|
102
|
-
);
|
|
103
|
-
};
|
|
104
|
-
```
|
|
105
|
-
|
|
106
|
-
### With Parameter Interpolation
|
|
107
|
-
|
|
108
|
-
```typescript
|
|
109
|
-
const { t } = useLanguage();
|
|
110
|
-
|
|
111
|
-
// Translation: "Hello, {{name}}!"
|
|
112
|
-
t('greeting', { name: 'John' }); // "Hello, John!"
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
---
|
|
116
|
-
|
|
117
|
-
## Language Detection Priority
|
|
118
|
-
|
|
119
|
-
The system detects language from multiple sources (in order):
|
|
120
|
-
|
|
121
|
-
| Priority | Source | Example |
|
|
122
|
-
|----------|--------|---------|
|
|
123
|
-
| 1 | URL parameter | `?lang=de` |
|
|
124
|
-
| 2 | localStorage | `smartlinks-lang` key |
|
|
125
|
-
| 3 | Browser language | `navigator.language` |
|
|
126
|
-
| 4 | Default | `en` |
|
|
127
|
-
|
|
128
|
-
For iframe apps, the SmartLinks platform passes the language via URL parameter.
|
|
129
|
-
|
|
130
|
-
---
|
|
131
|
-
|
|
132
|
-
## File Structure
|
|
133
|
-
|
|
134
|
-
```text
|
|
135
|
-
src/i18n/
|
|
136
|
-
├── index.ts # Main exports
|
|
137
|
-
├── LanguageContext.tsx # React context + provider
|
|
138
|
-
├── types.ts # TypeScript types
|
|
139
|
-
└── locales/
|
|
140
|
-
├── en.json # English translations
|
|
141
|
-
├── de.json # German translations
|
|
142
|
-
└── fr.json # French translations
|
|
143
|
-
```
|
|
144
|
-
|
|
145
|
-
---
|
|
146
|
-
|
|
147
|
-
## Adding New Translations
|
|
148
|
-
|
|
149
|
-
### 1. Add the Key to Types
|
|
150
|
-
|
|
151
|
-
```typescript
|
|
152
|
-
// src/i18n/types.ts
|
|
153
|
-
export type TranslationKey =
|
|
154
|
-
| 'common.loading'
|
|
155
|
-
| 'common.error'
|
|
156
|
-
| 'myFeature.title' // Add new key
|
|
157
|
-
| 'myFeature.description';
|
|
158
|
-
```
|
|
159
|
-
|
|
160
|
-
### 2. Add Translations to All Locales
|
|
161
|
-
|
|
162
|
-
```json
|
|
163
|
-
// src/i18n/locales/en.json
|
|
164
|
-
{
|
|
165
|
-
"myFeature.title": "My Feature",
|
|
166
|
-
"myFeature.description": "Description of my feature"
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
// src/i18n/locales/de.json
|
|
170
|
-
{
|
|
171
|
-
"myFeature.title": "Meine Funktion",
|
|
172
|
-
"myFeature.description": "Beschreibung meiner Funktion"
|
|
173
|
-
}
|
|
174
|
-
```
|
|
175
|
-
|
|
176
|
-
### 3. Use in Components
|
|
177
|
-
|
|
178
|
-
```typescript
|
|
179
|
-
const { t } = useLanguage();
|
|
180
|
-
return <h1>{t('myFeature.title')}</h1>;
|
|
181
|
-
```
|
|
182
|
-
|
|
183
|
-
---
|
|
184
|
-
|
|
185
|
-
## Adding New Languages
|
|
186
|
-
|
|
187
|
-
### 1. Create the Locale File
|
|
188
|
-
|
|
189
|
-
```json
|
|
190
|
-
// src/i18n/locales/es.json
|
|
191
|
-
{
|
|
192
|
-
"common.loading": "Cargando...",
|
|
193
|
-
"common.error": "Algo salió mal",
|
|
194
|
-
// ... all other keys
|
|
195
|
-
}
|
|
196
|
-
```
|
|
197
|
-
|
|
198
|
-
### 2. Import in LanguageContext
|
|
199
|
-
|
|
200
|
-
```typescript
|
|
201
|
-
// src/i18n/LanguageContext.tsx
|
|
202
|
-
import es from './locales/es.json';
|
|
203
|
-
|
|
204
|
-
const staticTranslations: Record<string, PartialTranslations> = {
|
|
205
|
-
en: en as PartialTranslations,
|
|
206
|
-
de: de as PartialTranslations,
|
|
207
|
-
fr: fr as PartialTranslations,
|
|
208
|
-
es: es as PartialTranslations, // Add new language
|
|
209
|
-
};
|
|
210
|
-
|
|
211
|
-
const SUPPORTED_LANGUAGES = ['en', 'de', 'fr', 'es']; // Add to list
|
|
212
|
-
```
|
|
213
|
-
|
|
214
|
-
---
|
|
215
|
-
|
|
216
|
-
## Dynamic Translations (SmartLinks appConfig)
|
|
217
|
-
|
|
218
|
-
For customer-configurable translations, store them in SmartLinks appConfig:
|
|
219
|
-
|
|
220
|
-
### Config Structure
|
|
221
|
-
|
|
222
|
-
```json
|
|
223
|
-
{
|
|
224
|
-
"i18n": {
|
|
225
|
-
"supportedLanguages": ["en", "de"],
|
|
226
|
-
"defaultLanguage": "en",
|
|
227
|
-
"translations": {
|
|
228
|
-
"en": {
|
|
229
|
-
"public.title": "Custom Brand Title",
|
|
230
|
-
"public.description": "Custom brand description"
|
|
231
|
-
},
|
|
232
|
-
"de": {
|
|
233
|
-
"public.title": "Benutzerdefinierter Markentitel",
|
|
234
|
-
"public.description": "Benutzerdefinierte Markenbeschreibung"
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
```
|
|
240
|
-
|
|
241
|
-
### Loading Dynamic Translations
|
|
242
|
-
|
|
243
|
-
```typescript
|
|
244
|
-
import { useCollectionAppConfig } from '@/hooks/useSmartLinksData';
|
|
245
|
-
import { LanguageProvider } from '@/i18n';
|
|
246
|
-
|
|
247
|
-
const App = () => {
|
|
248
|
-
const { data: config } = useCollectionAppConfig(collectionId, appId);
|
|
249
|
-
|
|
250
|
-
return (
|
|
251
|
-
<LanguageProvider dynamicTranslations={config?.i18n?.translations}>
|
|
252
|
-
<MyApp />
|
|
253
|
-
</LanguageProvider>
|
|
254
|
-
);
|
|
255
|
-
};
|
|
256
|
-
```
|
|
257
|
-
|
|
258
|
-
Dynamic translations override static ones, so customers can customize specific strings while inheriting defaults.
|
|
259
|
-
|
|
260
|
-
---
|
|
261
|
-
|
|
262
|
-
## Widgets
|
|
263
|
-
|
|
264
|
-
Widgets receive language context via props rather than React context (since they may run outside the provider).
|
|
265
|
-
|
|
266
|
-
### Widget Props
|
|
267
|
-
|
|
268
|
-
```typescript
|
|
269
|
-
interface SmartLinksWidgetProps {
|
|
270
|
-
// ... other props
|
|
271
|
-
lang?: string;
|
|
272
|
-
translations?: Record<string, string>;
|
|
273
|
-
}
|
|
274
|
-
```
|
|
275
|
-
|
|
276
|
-
### Using in Widgets
|
|
277
|
-
|
|
278
|
-
```typescript
|
|
279
|
-
import { createTranslator } from '@/i18n';
|
|
280
|
-
|
|
281
|
-
export const MyWidget: React.FC<SmartLinksWidgetProps> = ({
|
|
282
|
-
lang = 'en',
|
|
283
|
-
translations = {},
|
|
284
|
-
...props
|
|
285
|
-
}) => {
|
|
286
|
-
const t = createTranslator(lang, translations);
|
|
287
|
-
|
|
288
|
-
return <div>{t('widget.title')}</div>;
|
|
289
|
-
};
|
|
290
|
-
```
|
|
291
|
-
|
|
292
|
-
The `createTranslator` function creates a standalone translation function that doesn't require React context.
|
|
293
|
-
|
|
294
|
-
---
|
|
295
|
-
|
|
296
|
-
## URL Examples
|
|
297
|
-
|
|
298
|
-
```
|
|
299
|
-
# English (default)
|
|
300
|
-
/#/?collectionId=abc&appId=pamphlet
|
|
301
|
-
|
|
302
|
-
# German
|
|
303
|
-
/#/?collectionId=abc&appId=pamphlet&lang=de
|
|
304
|
-
|
|
305
|
-
# French
|
|
306
|
-
/#/?collectionId=abc&appId=pamphlet&lang=fr
|
|
307
|
-
```
|
|
308
|
-
|
|
309
|
-
---
|
|
310
|
-
|
|
311
|
-
## Best Practices
|
|
312
|
-
|
|
313
|
-
1. **Use dot notation** for key namespacing: `category.subcategory.key`
|
|
314
|
-
2. **Keep translations flat** - avoid nested objects in locale files
|
|
315
|
-
3. **Add keys to types.ts first** - ensures type safety
|
|
316
|
-
4. **Provide fallbacks** - English is always the fallback language
|
|
317
|
-
5. **Test all languages** - Use `?lang=xx` to switch during development
|
|
318
|
-
|
|
319
|
-
---
|
|
320
|
-
|
|
321
|
-
## API Reference
|
|
322
|
-
|
|
323
|
-
### `useLanguage()`
|
|
324
|
-
|
|
325
|
-
Hook to access language context.
|
|
326
|
-
|
|
327
|
-
```typescript
|
|
328
|
-
const {
|
|
329
|
-
lang, // Current language code
|
|
330
|
-
setLang, // Function to change language
|
|
331
|
-
t, // Translation function
|
|
332
|
-
supportedLanguages // Array of supported language codes
|
|
333
|
-
} = useLanguage();
|
|
74
|
+
```ts
|
|
75
|
+
await i18n.init({ languages: collection.languages?.map((l) => l.code) })
|
|
334
76
|
```
|
|
335
77
|
|
|
336
|
-
|
|
78
|
+
Never add your own language picker, and never translate into a language because the browser asks for it.
|
|
79
|
+
If a site is English only, it stays English (a visitor can still use their browser's own translation).
|
|
337
80
|
|
|
338
|
-
|
|
81
|
+
## Hand-written translations are welcome
|
|
339
82
|
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
t('custom.key'); // "Custom value"
|
|
344
|
-
```
|
|
83
|
+
For a fixed set of labels you know well (a regulated product passport, a spec sheet), ship your own
|
|
84
|
+
`public/i18n/<lang>.json` files, as many languages as you like. Your keys win; the platform only fills
|
|
85
|
+
what you left out. That's faster to read and exact. What you should not do is hand-write the machinery.
|
|
345
86
|
|
|
346
|
-
|
|
87
|
+
## Numbers, money and dates
|
|
347
88
|
|
|
348
|
-
|
|
89
|
+
Formats differ: "1,299.50" in English is "1.299,50" in German and "1 299,50" in French; dates and the
|
|
90
|
+
currency symbol move too. Always format in the language in use:
|
|
349
91
|
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
92
|
+
- `i18n.format.number(n)`, `i18n.format.date(d)`, `i18n.format.dateTime(d)`, `i18n.format.money(minor, currency)`.
|
|
93
|
+
- Outside the helper: `n.toLocaleString(utils.pageLocale())`, `utils.formatMinor(minor, currency)`,
|
|
94
|
+
`shop.formatMoney(...)`, `subscriptions.describePrice(...)`.
|
|
95
|
+
- Never a bare `toLocaleString()` / `toLocaleDateString()` (that's the browser's language, not the one the
|
|
96
|
+
visitor chose), never a fixed `'en-US'` or `'en-GB'`, never `(x / 100).toFixed(2)` or a hard-coded £/€/$.
|
|
97
|
+
Amounts are minor units in the currency's own decimals (whole units for JPY and KRW).
|
|
98
|
+
- **Reading what people type**: a German seller writes 12,99. Accept both decimal marks (the last `.` or
|
|
99
|
+
`,` followed by one or two digits is the decimal mark; the rest are thousands separators). Never strip
|
|
100
|
+
commas and never `Number(text)` a price field directly.
|
|
101
|
+
- Content (product names, page text) isn't your job: the platform translates it (`translations.resolve`).
|
|
355
102
|
|
|
356
103
|
## Right-to-left languages (Arabic, Hebrew, Persian, Urdu)
|
|
357
104
|
|
|
@@ -361,3 +108,10 @@ live `smartlinks:root-state`). For the layout to mirror, write direction-neutral
|
|
|
361
108
|
`ms-*`/`me-*`, `ps-*`/`pe-*`, `start-*`/`end-*`, `text-start`/`text-end`, `border-s`/`border-e`,
|
|
362
109
|
`rounded-s`/`rounded-e` instead of the left/right forms, and flip arrow icons that mean "forward" or
|
|
363
110
|
"back" with `rtl:-scale-x-100`.
|
|
111
|
+
|
|
112
|
+
## Moving off the older scaffold
|
|
113
|
+
|
|
114
|
+
Apps built with the copied-in `src/i18n/` scaffold (`LanguageContext`, `src/i18n/locales/*.json`,
|
|
115
|
+
`createTranslator`) still work, but move them: put the English in `public/i18n/en.json` (keep any
|
|
116
|
+
hand-written languages as `public/i18n/<lang>.json`), read it with the helper above, and delete the
|
|
117
|
+
scaffold. In Forge this is step 21, "Speak the visitor's language".
|
|
@@ -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
|
@@ -136,3 +136,9 @@ example, `scan`: a tag they just scanned with Sidekick on another device.
|
|
|
136
136
|
`realtime.getPublicToken()` and `realtime.getAdminToken()` return raw provider tokens for the old
|
|
137
137
|
`collection:{id}:*` and `interaction:{uid}` channels. They still work, but publishing is now limited to
|
|
138
138
|
the collection's admins. Move to `channel` / `onChange` / `onMine`.
|
|
139
|
+
|
|
140
|
+
## Changes the host already knows about
|
|
141
|
+
|
|
142
|
+
An app inside Studio does not need its own connection to hear that the assistant or another app changed
|
|
143
|
+
a record: the host passes that into the frame as `smartlinks:data-changed`. Listen with
|
|
144
|
+
`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
|
}
|