@colixsystems/widget-sdk 0.319.2 → 0.320.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -1
- package/dist/contract.cjs +41 -4
- package/dist/contract.js +41 -4
- package/dist/device-storage.js +168 -0
- package/dist/index.d.ts +36 -0
- package/dist/index.js +2 -0
- package/dist/index.native.js +2 -0
- package/package.json +1 -1
- package/src/contract.js +41 -4
package/README.md
CHANGED
|
@@ -42,6 +42,7 @@ The data layer lives in **four separate domain-client packages**, each instantia
|
|
|
42
42
|
| **CORE** | `useRefresh(handler)` | `void` | `ctx.refresh.subscribe` — no scope. Subscribes the handler to the page-level refresh tick (pull-to-refresh on mobile). Handler may return a Promise — the host waits for `allSettled` before clearing the spinner. The three datastore hooks auto-subscribe their own `refetch`; widgets only call this directly to re-run non-datastore work. No-op on a host that doesn't implement refresh. |
|
|
43
43
|
| **CORE** | `useClipboard()` | `{ copy, paste, hasContent }` | platform clipboard (web `navigator.clipboard` / native `expo-clipboard`); rejects with `ClipboardError` — no scope |
|
|
44
44
|
| **CORE** | `useToast()` | `{ showToast }` | `ctx.toast.showToast` — wired by the Player and the Expo export; an authoring preview omits it and the call is a no-op — no scope |
|
|
45
|
+
| **CORE** | `useDeviceStorage(key, initial)` (optional: initial) | `{ value, setValue, remove, loaded, supported, error }` | `ctx.device.storage` — no scope. Keeps a small JSON value on this device across page changes, refreshes and app restarts: a guest's shopping bag before checkout, a dismissed tip, a last-picked filter. `setValue(next)` takes a value or `(previous) => next`; `remove()` returns `value` to `initial`. Every widget in the app using the same key sees a change at once (a header bag count and the bag itself stay in step), and on the web a change in another tab arrives without a reload; the last write wins. `key` is 1-64 letters, digits, `.`, `_` or `-`; a value is at most 16384 bytes as JSON. Values are per workspace and per device, shared by everyone using the app on that device, so never store a secret or personal data. Wait for `loaded` before acting on an empty value. `supported` is false when the device keeps nothing (a private window): the value lasts until the page closes. `error` is `{ code, message }` or null (`INVALID_KEY`, `INVALID_VALUE`, `TOO_LARGE`, `CORRUPT`, `NOT_PERSISTED`, `WRITE_FAILED`). Builder previews keep values in memory only. Web stores in `localStorage`, the Expo export in a file in the app's documents folder; never touch `localStorage` yourself. |
|
|
45
46
|
| **CORE** | `useGeolocation(options)` (optional: options) | `{ latitude, longitude, accuracy, loading, error, getCurrentPosition, backgroundSupported, backgroundWatching, startBackgroundWatch, stopBackgroundWatch }` | `ctx.device.geolocation` — no scope. Capture is IMPERATIVE: call `getCurrentPosition()` from a user gesture (a tap), never on mount. Resolves to `{ latitude, longitude, accuracy }`; rejects with `GeolocationError` (`.code` in `PERMISSION_DENIED \| UNAVAILABLE \| TIMEOUT \| UNSUPPORTED \| INTERNAL`). Identical on web (`navigator.geolocation`) and the Expo export (`expo-location`). **Background watch** — `startBackgroundWatch({ enableHighAccuracy, distanceIntervalMeters, timeIntervalMs })` keeps positions arriving while the app is backgrounded; `stopBackgroundWatch()` releases it. NATIVE-ONLY and opt-in per app: gate the control on `backgroundSupported` (false on web, and in an export whose workspace did not opt in). The watch outlives the widget's mount, and its positions land in the same `latitude`/`longitude`/`accuracy` slots. |
|
|
46
47
|
| **CORE** | `useSpeechToText(options)` (optional: options) | `{ transcript, partial, listening, supported, error, start, stop, abort, reset }` | `ctx.device.speech` — no scope. Dictation with the device's **on-device** recogniser: no audio is uploaded and no AI credit is spent. Capture is IMPERATIVE: call `start()` from a user gesture (a tap), never on mount. `transcript` accumulates finalised speech, `partial` holds the uncommitted guess (needs `options.interimResults`); `stop()` keeps it, `abort()` discards it. Rejects with `SpeechToTextError` (`.code` in `PERMISSION_DENIED \| NO_SPEECH \| LANGUAGE_UNSUPPORTED \| NETWORK \| ABORTED \| UNSUPPORTED \| INTERNAL`). **Gate your mic button on `supported`** — Firefox ships no `SpeechRecognition`. Identical on web (`SpeechRecognition`) and the Expo export (`expo-speech-recognition`). |
|
|
47
48
|
| **CORE** | `useCamera(options)` (optional: options) | `{ asset, loading, error, supported, capture, pick, reset }` | `ctx.device.camera` — no scope. Take a photo (`capture()`) or choose one (`pick()`). Capture is IMPERATIVE: call from a user gesture (a tap), never on mount. Both resolve a normalised `{ uri, name, mimeType, width, height, size, file }`, or **`null` when the user dismisses the picker** — dismissal is not an error, so no `try/catch` is needed on the happy path. Rejects with `CameraError` (`.code` in `PERMISSION_DENIED \| UNSUPPORTED \| INTERNAL`). `asset.file` is already the right upload part for the host, so `fd.append("file", asset.file)` → `ctx.assets.upload(fd)` is ONE code path on both. **Gate your camera button on `supported`.** Identical on web (a live `getUserMedia` preview, phones included; a file input only where getUserMedia is absent) and the Expo export (`expo-image-picker`). |
|
|
@@ -90,7 +91,16 @@ See the design reference for the full architecture: [`docs/architecture/widget-m
|
|
|
90
91
|
|
|
91
92
|
## Status
|
|
92
93
|
|
|
93
|
-
`v0.
|
|
94
|
+
`v0.320.0` — pre-publish. The package surface (types, function names, export paths) is the v1 contract; runtime behaviour for some hooks is stubbed (each hook documents what's wired and what isn't). It is **not yet published to npm**.
|
|
95
|
+
|
|
96
|
+
### What's new in 0.320.0 (contract 1.260.0)
|
|
97
|
+
|
|
98
|
+
**New `useDeviceStorage()` hook: small values that stay on the device.** A widget can now keep a value across page changes, refreshes and app restarts without an account, such as a guest's shopping bag before checkout. `const { value, setValue, loaded } = useDeviceStorage("bag", [])` returns the stored JSON value, or the initial one until something is stored; `setValue` takes a value or `(previous) => next`, and `remove()` clears it. Every widget using the same key follows a change at once, so a header bag count and the bag stay in step, and on the web another tab follows without a reload. Keys are 1-64 letters, digits, `.`, `_` or `-`, and a value is at most 16384 bytes as JSON. Values are kept per workspace and per device, so never store a secret or personal data. `supported` is false where the device keeps nothing (a private window), and `error` names a refused, oversized or unreadable value. The web Player stores in `localStorage` and the Expo export in a file in the app's documents folder; widget code still may not touch `localStorage` itself. Additive.
|
|
99
|
+
|
|
100
|
+
```jsx
|
|
101
|
+
const { value: bag, setValue: setBag, loaded } = useDeviceStorage("bag", []);
|
|
102
|
+
const add = (item) => setBag((items) => [...items, item]);
|
|
103
|
+
```
|
|
94
104
|
|
|
95
105
|
### What's new in 0.319.2 (contract 1.259.0)
|
|
96
106
|
|
package/dist/contract.cjs
CHANGED
|
@@ -3389,6 +3389,37 @@ const HOOKS = [
|
|
|
3389
3389
|
requiredContextSlice: [],
|
|
3390
3390
|
scopes: null,
|
|
3391
3391
|
},
|
|
3392
|
+
// sc-16671 — host-brokered device storage. Optional slice; without it the
|
|
3393
|
+
// value lives in memory and the hook reports supported:false.
|
|
3394
|
+
{
|
|
3395
|
+
name: "useDeviceStorage",
|
|
3396
|
+
signature: "useDeviceStorage(key, initial)",
|
|
3397
|
+
optionalArgs: ["initial"],
|
|
3398
|
+
description:
|
|
3399
|
+
"Keep a small JSON value on this device across page changes, refreshes and app restarts — a guest's shopping bag, " +
|
|
3400
|
+
"a dismissed tip, a last-picked filter. Returns { value, setValue, remove, loaded, supported, error }. `value` is the " +
|
|
3401
|
+
"stored value, or `initial` until one is stored; setValue(next) stores a JSON value or (previous) => next; remove() " +
|
|
3402
|
+
"deletes it. Every widget in the app that uses the same key sees a change at once, and on the web a change in another " +
|
|
3403
|
+
"tab arrives without a reload; the last write wins. `key` is 1-64 letters, digits, '.', '_' or '-'; a value is at most " +
|
|
3404
|
+
"16384 bytes as JSON. Values are kept per workspace and per device, shared by everyone who uses the app on that device, " +
|
|
3405
|
+
"so NEVER store a password, token, card number or other secret or personal data — keep account data in the datastore. " +
|
|
3406
|
+
"Wait for `loaded` before acting on an empty value. `supported` is false when the device keeps nothing (a private " +
|
|
3407
|
+
"window, blocked storage): the value then lasts until the page closes. `error` is { code, message } or null: " +
|
|
3408
|
+
"INVALID_KEY | INVALID_VALUE | TOO_LARGE (nothing changed) | CORRUPT (the stored value was unreadable; `initial` is shown) | " +
|
|
3409
|
+
"NOT_PERSISTED (the device refused it, e.g. full; kept until the app closes) | WRITE_FAILED. In the Builder canvas and " +
|
|
3410
|
+
"widget previews values are kept in memory only. Never touch localStorage or window yourself — the linter refuses it. " +
|
|
3411
|
+
"Identical on web (localStorage) and the Expo export (a file in the app's documents folder).",
|
|
3412
|
+
returnShape: {
|
|
3413
|
+
value: "any // the stored JSON value, or `initial`",
|
|
3414
|
+
setValue: "(next | (previous) => next) => void",
|
|
3415
|
+
remove: "() => void",
|
|
3416
|
+
loaded: "boolean // the stored value has been read",
|
|
3417
|
+
supported: "boolean // false: kept in memory only",
|
|
3418
|
+
error: "{ code, message } | null",
|
|
3419
|
+
},
|
|
3420
|
+
requiredContextSlice: [],
|
|
3421
|
+
scopes: null,
|
|
3422
|
+
},
|
|
3392
3423
|
// sc-6448 — host-brokered camera capture / photo picking. Optional slice;
|
|
3393
3424
|
// the hook reports supported:false rather than throwing at render.
|
|
3394
3425
|
{
|
|
@@ -4699,13 +4730,18 @@ const WIDGET_CONTEXT_SHAPE = {
|
|
|
4699
4730
|
"{ play() -> Promise<void>, pause(), seek(ms) -> Promise<void>, release() } }, " +
|
|
4700
4731
|
"keyboard: { hasKeyboard() -> boolean, subscribe({ keys: string[] | null, onKey({ type: 'down' | 'up', key, character, " +
|
|
4701
4732
|
"repeat, shiftKey, ctrlKey, altKey, metaKey }), onRelease(), onDetected() }) -> unsubscribe }, " +
|
|
4733
|
+
"storage: { isSupported() -> boolean, read(key) -> Promise<string | null>, write(key, raw) -> Promise<boolean>, " +
|
|
4734
|
+
"remove(key) -> Promise<void>, subscribe(key, onChange(raw | null)) -> unsubscribe }, " +
|
|
4702
4735
|
"purchases: { isSupported() -> boolean, getOffering() -> Promise<offering | null>, getEntitlements() -> Promise<string[]>, " +
|
|
4703
4736
|
"purchase(packageId) -> Promise<string[]>, restore() -> Promise<string[]> } }. " +
|
|
4704
4737
|
"purchases backs usePurchases() and is NATIVE-ONLY: the Expo export brokers it through react-native-purchases when the " +
|
|
4705
4738
|
"workspace connected RevenueCat; the web Player never does, because a browser has no store billing. " +
|
|
4706
|
-
"Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer() and
|
|
4707
|
-
"navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder, an <audio> element
|
|
4708
|
-
"expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio and expo-
|
|
4739
|
+
"Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer(), useKeyboard() and useDeviceStorage(). The web Player brokers them via " +
|
|
4740
|
+
"navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder, an <audio> element, window key listeners and localStorage; the Expo export via " +
|
|
4741
|
+
"expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio, expo-key-event and expo-file-system. " +
|
|
4742
|
+
"storage holds strings under keys scoped to the workspace; write resolves false when the device refused the value " +
|
|
4743
|
+
"(kept in memory instead) and notifies every subscriber of that key, as remove does with null; the web broker also " +
|
|
4744
|
+
"delivers other tabs' changes. " +
|
|
4709
4745
|
"keyboard.subscribe delivers only the `keys` named (all when null), stops the browser default of a delivered key " +
|
|
4710
4746
|
"pressed without Ctrl/Cmd/Alt, calls onRelease when the window or app loses focus or a text field opens and onDetected the first time any key " +
|
|
4711
4747
|
"arrives; a Builder preview's broker accepts keys only while focus is inside the preview. " +
|
|
@@ -4746,6 +4782,7 @@ const WIDGET_CONTEXT_SHAPE = {
|
|
|
4746
4782
|
audioRecorder: "object",
|
|
4747
4783
|
audioPlayer: "object",
|
|
4748
4784
|
keyboard: "object",
|
|
4785
|
+
storage: "object",
|
|
4749
4786
|
purchases: "object",
|
|
4750
4787
|
},
|
|
4751
4788
|
},
|
|
@@ -6975,7 +7012,7 @@ const CONTRACT = deepFreeze({
|
|
|
6975
7012
|
// the publish-blocking `payment-kind-required` finding.
|
|
6976
7013
|
// 1.259.0: `useDirectory()` / `useUsers()` rows carry `photo_url`, the
|
|
6977
7014
|
// person's profile photo as an absolute URL or null.
|
|
6978
|
-
version: "1.
|
|
7015
|
+
version: "1.260.0",
|
|
6979
7016
|
sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
|
|
6980
7017
|
hooks: HOOKS,
|
|
6981
7018
|
primitives: PRIMITIVES,
|
package/dist/contract.js
CHANGED
|
@@ -3384,6 +3384,37 @@ const HOOKS = [
|
|
|
3384
3384
|
requiredContextSlice: [],
|
|
3385
3385
|
scopes: null,
|
|
3386
3386
|
},
|
|
3387
|
+
// sc-16671 — host-brokered device storage. Optional slice; without it the
|
|
3388
|
+
// value lives in memory and the hook reports supported:false.
|
|
3389
|
+
{
|
|
3390
|
+
name: "useDeviceStorage",
|
|
3391
|
+
signature: "useDeviceStorage(key, initial)",
|
|
3392
|
+
optionalArgs: ["initial"],
|
|
3393
|
+
description:
|
|
3394
|
+
"Keep a small JSON value on this device across page changes, refreshes and app restarts — a guest's shopping bag, " +
|
|
3395
|
+
"a dismissed tip, a last-picked filter. Returns { value, setValue, remove, loaded, supported, error }. `value` is the " +
|
|
3396
|
+
"stored value, or `initial` until one is stored; setValue(next) stores a JSON value or (previous) => next; remove() " +
|
|
3397
|
+
"deletes it. Every widget in the app that uses the same key sees a change at once, and on the web a change in another " +
|
|
3398
|
+
"tab arrives without a reload; the last write wins. `key` is 1-64 letters, digits, '.', '_' or '-'; a value is at most " +
|
|
3399
|
+
"16384 bytes as JSON. Values are kept per workspace and per device, shared by everyone who uses the app on that device, " +
|
|
3400
|
+
"so NEVER store a password, token, card number or other secret or personal data — keep account data in the datastore. " +
|
|
3401
|
+
"Wait for `loaded` before acting on an empty value. `supported` is false when the device keeps nothing (a private " +
|
|
3402
|
+
"window, blocked storage): the value then lasts until the page closes. `error` is { code, message } or null: " +
|
|
3403
|
+
"INVALID_KEY | INVALID_VALUE | TOO_LARGE (nothing changed) | CORRUPT (the stored value was unreadable; `initial` is shown) | " +
|
|
3404
|
+
"NOT_PERSISTED (the device refused it, e.g. full; kept until the app closes) | WRITE_FAILED. In the Builder canvas and " +
|
|
3405
|
+
"widget previews values are kept in memory only. Never touch localStorage or window yourself — the linter refuses it. " +
|
|
3406
|
+
"Identical on web (localStorage) and the Expo export (a file in the app's documents folder).",
|
|
3407
|
+
returnShape: {
|
|
3408
|
+
value: "any // the stored JSON value, or `initial`",
|
|
3409
|
+
setValue: "(next | (previous) => next) => void",
|
|
3410
|
+
remove: "() => void",
|
|
3411
|
+
loaded: "boolean // the stored value has been read",
|
|
3412
|
+
supported: "boolean // false: kept in memory only",
|
|
3413
|
+
error: "{ code, message } | null",
|
|
3414
|
+
},
|
|
3415
|
+
requiredContextSlice: [],
|
|
3416
|
+
scopes: null,
|
|
3417
|
+
},
|
|
3387
3418
|
// sc-6448 — host-brokered camera capture / photo picking. Optional slice;
|
|
3388
3419
|
// the hook reports supported:false rather than throwing at render.
|
|
3389
3420
|
{
|
|
@@ -4694,13 +4725,18 @@ const WIDGET_CONTEXT_SHAPE = {
|
|
|
4694
4725
|
"{ play() -> Promise<void>, pause(), seek(ms) -> Promise<void>, release() } }, " +
|
|
4695
4726
|
"keyboard: { hasKeyboard() -> boolean, subscribe({ keys: string[] | null, onKey({ type: 'down' | 'up', key, character, " +
|
|
4696
4727
|
"repeat, shiftKey, ctrlKey, altKey, metaKey }), onRelease(), onDetected() }) -> unsubscribe }, " +
|
|
4728
|
+
"storage: { isSupported() -> boolean, read(key) -> Promise<string | null>, write(key, raw) -> Promise<boolean>, " +
|
|
4729
|
+
"remove(key) -> Promise<void>, subscribe(key, onChange(raw | null)) -> unsubscribe }, " +
|
|
4697
4730
|
"purchases: { isSupported() -> boolean, getOffering() -> Promise<offering | null>, getEntitlements() -> Promise<string[]>, " +
|
|
4698
4731
|
"purchase(packageId) -> Promise<string[]>, restore() -> Promise<string[]> } }. " +
|
|
4699
4732
|
"purchases backs usePurchases() and is NATIVE-ONLY: the Expo export brokers it through react-native-purchases when the " +
|
|
4700
4733
|
"workspace connected RevenueCat; the web Player never does, because a browser has no store billing. " +
|
|
4701
|
-
"Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer() and
|
|
4702
|
-
"navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder, an <audio> element
|
|
4703
|
-
"expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio and expo-
|
|
4734
|
+
"Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer(), useKeyboard() and useDeviceStorage(). The web Player brokers them via " +
|
|
4735
|
+
"navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder, an <audio> element, window key listeners and localStorage; the Expo export via " +
|
|
4736
|
+
"expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio, expo-key-event and expo-file-system. " +
|
|
4737
|
+
"storage holds strings under keys scoped to the workspace; write resolves false when the device refused the value " +
|
|
4738
|
+
"(kept in memory instead) and notifies every subscriber of that key, as remove does with null; the web broker also " +
|
|
4739
|
+
"delivers other tabs' changes. " +
|
|
4704
4740
|
"keyboard.subscribe delivers only the `keys` named (all when null), stops the browser default of a delivered key " +
|
|
4705
4741
|
"pressed without Ctrl/Cmd/Alt, calls onRelease when the window or app loses focus or a text field opens and onDetected the first time any key " +
|
|
4706
4742
|
"arrives; a Builder preview's broker accepts keys only while focus is inside the preview. " +
|
|
@@ -4741,6 +4777,7 @@ const WIDGET_CONTEXT_SHAPE = {
|
|
|
4741
4777
|
audioRecorder: "object",
|
|
4742
4778
|
audioPlayer: "object",
|
|
4743
4779
|
keyboard: "object",
|
|
4780
|
+
storage: "object",
|
|
4744
4781
|
purchases: "object",
|
|
4745
4782
|
},
|
|
4746
4783
|
},
|
|
@@ -6970,7 +7007,7 @@ const CONTRACT = deepFreeze({
|
|
|
6970
7007
|
// the publish-blocking `payment-kind-required` finding.
|
|
6971
7008
|
// 1.259.0: `useDirectory()` / `useUsers()` rows carry `photo_url`, the
|
|
6972
7009
|
// person's profile photo as an absolute URL or null.
|
|
6973
|
-
version: "1.
|
|
7010
|
+
version: "1.260.0",
|
|
6974
7011
|
sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
|
|
6975
7012
|
hooks: HOOKS,
|
|
6976
7013
|
primitives: PRIMITIVES,
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// sc-16671 — useDeviceStorage over ctx.device.storage, one source for both hosts.
|
|
2
|
+
// Brokers store strings; JSON, the key rule and the size cap live here.
|
|
3
|
+
|
|
4
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
5
|
+
import { useWidgetContextOrThrow } from "./hooks.js";
|
|
6
|
+
|
|
7
|
+
const DEVICE_STORAGE_KEY_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
|
|
8
|
+
const DEVICE_STORAGE_MAX_BYTES = 16384;
|
|
9
|
+
|
|
10
|
+
function isUsable(client) {
|
|
11
|
+
return Boolean(
|
|
12
|
+
client &&
|
|
13
|
+
typeof client.read === "function" &&
|
|
14
|
+
typeof client.write === "function" &&
|
|
15
|
+
typeof client.remove === "function" &&
|
|
16
|
+
typeof client.subscribe === "function",
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function storageError(code, message) {
|
|
21
|
+
return { code, message };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Keep a small JSON value on this device, shared by every widget in the app
|
|
26
|
+
* that uses the same key. Returns `{ value, setValue, remove, loaded,
|
|
27
|
+
* supported, error }`.
|
|
28
|
+
*
|
|
29
|
+
* - `value` is the stored value, or `initial` until one is stored.
|
|
30
|
+
* - `setValue(next)` stores a JSON value or `(previous) => next`.
|
|
31
|
+
* - `remove()` deletes it; `value` returns to `initial`.
|
|
32
|
+
* - `loaded` turns true once the stored value has been read.
|
|
33
|
+
* - `supported` is false when the device keeps nothing (a private window,
|
|
34
|
+
* blocked storage): the value then lives in memory until the page closes.
|
|
35
|
+
* - `error` is `{ code, message }` or null. Codes: INVALID_KEY, INVALID_VALUE,
|
|
36
|
+
* TOO_LARGE, CORRUPT, NOT_PERSISTED, WRITE_FAILED.
|
|
37
|
+
*/
|
|
38
|
+
export function useDeviceStorage(key, initial) {
|
|
39
|
+
const ctx = useWidgetContextOrThrow("useDeviceStorage");
|
|
40
|
+
const client = ctx.device && ctx.device.storage;
|
|
41
|
+
const validKey = typeof key === "string" && DEVICE_STORAGE_KEY_PATTERN.test(key);
|
|
42
|
+
const usable = validKey && isUsable(client);
|
|
43
|
+
|
|
44
|
+
const initialRef = useRef(initial);
|
|
45
|
+
initialRef.current = initial;
|
|
46
|
+
|
|
47
|
+
const fresh = () => ({
|
|
48
|
+
key,
|
|
49
|
+
value: initial,
|
|
50
|
+
loaded: !usable,
|
|
51
|
+
error: validKey ? null : storageError("INVALID_KEY", "Keys are 1-64 letters, digits, '.', '_' or '-'."),
|
|
52
|
+
});
|
|
53
|
+
const [stored, setState] = useState(fresh);
|
|
54
|
+
// A new key never shows, or builds an update on, the old key's value.
|
|
55
|
+
const state = stored.key === key ? stored : fresh();
|
|
56
|
+
if (state !== stored) setState(state);
|
|
57
|
+
const valueRef = useRef(state.value);
|
|
58
|
+
valueRef.current = state.value;
|
|
59
|
+
const writtenRef = useRef(false);
|
|
60
|
+
const lastWrittenRef = useRef(null);
|
|
61
|
+
|
|
62
|
+
useEffect(() => {
|
|
63
|
+
if (!usable) return undefined;
|
|
64
|
+
let live = true;
|
|
65
|
+
writtenRef.current = false;
|
|
66
|
+
lastWrittenRef.current = null;
|
|
67
|
+
|
|
68
|
+
const apply = (raw, fromRead) => {
|
|
69
|
+
if (!live || (fromRead && writtenRef.current)) return;
|
|
70
|
+
// Our own write echoed back: keep the value we already hold.
|
|
71
|
+
if (!fromRead && raw !== null && raw === lastWrittenRef.current) return;
|
|
72
|
+
lastWrittenRef.current = null;
|
|
73
|
+
if (raw === null || raw === undefined) {
|
|
74
|
+
setState({ key, value: initialRef.current, loaded: true, error: null });
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
setState({ key, value: JSON.parse(raw), loaded: true, error: null });
|
|
79
|
+
} catch {
|
|
80
|
+
setState({
|
|
81
|
+
key,
|
|
82
|
+
value: initialRef.current,
|
|
83
|
+
loaded: true,
|
|
84
|
+
error: storageError("CORRUPT", "The stored value was not valid JSON."),
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const unsubscribe = client.subscribe(key, (raw) => apply(raw, false));
|
|
90
|
+
Promise.resolve()
|
|
91
|
+
.then(() => client.read(key))
|
|
92
|
+
.then(
|
|
93
|
+
(raw) => apply(raw, true),
|
|
94
|
+
() => apply(null, true),
|
|
95
|
+
);
|
|
96
|
+
return () => {
|
|
97
|
+
live = false;
|
|
98
|
+
if (typeof unsubscribe === "function") unsubscribe();
|
|
99
|
+
};
|
|
100
|
+
}, [client, key, usable]);
|
|
101
|
+
|
|
102
|
+
const setValue = useCallback(
|
|
103
|
+
(next) => {
|
|
104
|
+
const resolved = typeof next === "function" ? next(valueRef.current) : next;
|
|
105
|
+
let raw;
|
|
106
|
+
try {
|
|
107
|
+
raw = JSON.stringify(resolved);
|
|
108
|
+
} catch {
|
|
109
|
+
raw = undefined;
|
|
110
|
+
}
|
|
111
|
+
if (raw === undefined) {
|
|
112
|
+
setState((s) => ({ ...s, error: storageError("INVALID_VALUE", "Only JSON values can be stored.") }));
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (new TextEncoder().encode(raw).length > DEVICE_STORAGE_MAX_BYTES) {
|
|
116
|
+
setState((s) => ({
|
|
117
|
+
...s,
|
|
118
|
+
error: storageError("TOO_LARGE", `A stored value may be at most ${DEVICE_STORAGE_MAX_BYTES} bytes as JSON.`),
|
|
119
|
+
}));
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
valueRef.current = resolved;
|
|
123
|
+
setState((s) => ({ ...s, value: resolved, loaded: true, error: null }));
|
|
124
|
+
if (!usable) return;
|
|
125
|
+
writtenRef.current = true;
|
|
126
|
+
lastWrittenRef.current = raw;
|
|
127
|
+
Promise.resolve()
|
|
128
|
+
.then(() => client.write(key, raw))
|
|
129
|
+
.then(
|
|
130
|
+
(persisted) => {
|
|
131
|
+
if (persisted === false) {
|
|
132
|
+
setState((s) => ({
|
|
133
|
+
...s,
|
|
134
|
+
error: storageError("NOT_PERSISTED", "The device refused the value; it is kept until the app closes."),
|
|
135
|
+
}));
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
(err) => {
|
|
139
|
+
setState((s) => ({
|
|
140
|
+
...s,
|
|
141
|
+
error: storageError("WRITE_FAILED", err && err.message ? err.message : String(err)),
|
|
142
|
+
}));
|
|
143
|
+
},
|
|
144
|
+
);
|
|
145
|
+
},
|
|
146
|
+
[client, key, usable],
|
|
147
|
+
);
|
|
148
|
+
|
|
149
|
+
const remove = useCallback(() => {
|
|
150
|
+
valueRef.current = initialRef.current;
|
|
151
|
+
setState({ key, value: initialRef.current, loaded: true, error: null });
|
|
152
|
+
if (!usable) return;
|
|
153
|
+
writtenRef.current = true;
|
|
154
|
+
lastWrittenRef.current = null;
|
|
155
|
+
Promise.resolve()
|
|
156
|
+
.then(() => client.remove(key))
|
|
157
|
+
.catch(() => {});
|
|
158
|
+
}, [client, key, usable]);
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
value: state.value,
|
|
162
|
+
setValue,
|
|
163
|
+
remove,
|
|
164
|
+
loaded: state.loaded,
|
|
165
|
+
supported: usable && (typeof client.isSupported !== "function" || client.isSupported() !== false),
|
|
166
|
+
error: state.error,
|
|
167
|
+
};
|
|
168
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -991,6 +991,15 @@ export interface WidgetContext<TProps = unknown> {
|
|
|
991
991
|
onDetected(): void;
|
|
992
992
|
}): () => void;
|
|
993
993
|
};
|
|
994
|
+
/** sc-16671 — backs useDeviceStorage. Strings under workspace-scoped keys. */
|
|
995
|
+
storage?: {
|
|
996
|
+
isSupported?(): boolean;
|
|
997
|
+
read(key: string): Promise<string | null>;
|
|
998
|
+
/** False when the device refused the value and it is kept in memory. */
|
|
999
|
+
write(key: string, raw: string): Promise<boolean>;
|
|
1000
|
+
remove(key: string): Promise<void>;
|
|
1001
|
+
subscribe(key: string, onChange: (raw: string | null) => void): () => void;
|
|
1002
|
+
};
|
|
994
1003
|
/** sc-15163 — backs usePurchases. Brokered by the Expo export only. */
|
|
995
1004
|
purchases?: {
|
|
996
1005
|
isSupported?(): boolean;
|
|
@@ -3237,6 +3246,33 @@ export interface KeyboardResult {
|
|
|
3237
3246
|
*/
|
|
3238
3247
|
export function useKeyboard(options?: UseKeyboardOptions): KeyboardResult;
|
|
3239
3248
|
|
|
3249
|
+
export type DeviceStorageErrorCode =
|
|
3250
|
+
| "INVALID_KEY"
|
|
3251
|
+
| "INVALID_VALUE"
|
|
3252
|
+
| "TOO_LARGE"
|
|
3253
|
+
| "CORRUPT"
|
|
3254
|
+
| "NOT_PERSISTED"
|
|
3255
|
+
| "WRITE_FAILED";
|
|
3256
|
+
|
|
3257
|
+
export interface DeviceStorageResult<T> {
|
|
3258
|
+
/** The stored value, or `initial` until one is stored. */
|
|
3259
|
+
value: T;
|
|
3260
|
+
setValue(next: T | ((previous: T) => T)): void;
|
|
3261
|
+
remove(): void;
|
|
3262
|
+
/** The stored value has been read. */
|
|
3263
|
+
loaded: boolean;
|
|
3264
|
+
/** False when the device keeps nothing; the value lives in memory. */
|
|
3265
|
+
supported: boolean;
|
|
3266
|
+
error: { code: DeviceStorageErrorCode; message: string } | null;
|
|
3267
|
+
}
|
|
3268
|
+
|
|
3269
|
+
/**
|
|
3270
|
+
* A small JSON value kept on this device per workspace, shared live by every
|
|
3271
|
+
* widget using the same key: localStorage on the web Player, a file in the
|
|
3272
|
+
* documents folder in the Expo export. Never store secrets or personal data.
|
|
3273
|
+
*/
|
|
3274
|
+
export function useDeviceStorage<T = unknown>(key: string, initial?: T): DeviceStorageResult<T>;
|
|
3275
|
+
|
|
3240
3276
|
/** One package of the current offering, as the store prices it. */
|
|
3241
3277
|
export interface PurchasePackage {
|
|
3242
3278
|
id: string;
|
package/dist/index.js
CHANGED
|
@@ -138,6 +138,8 @@ export {
|
|
|
138
138
|
} from "./audio.js";
|
|
139
139
|
// sc-15908 — one host-brokered source for both entries (ctx.device.keyboard).
|
|
140
140
|
export { useKeyboard } from "./keyboard.js";
|
|
141
|
+
// sc-16671 — one host-brokered source for both entries (ctx.device.storage).
|
|
142
|
+
export { useDeviceStorage } from "./device-storage.js";
|
|
141
143
|
// sc-15163 — native-only in-app purchase; the web Player brokers none.
|
|
142
144
|
export { usePurchases, PurchasesError } from "./purchases.js";
|
|
143
145
|
export { useDatastoreFigure } from "./datastore-figure.js";
|
package/dist/index.native.js
CHANGED
|
@@ -136,6 +136,8 @@ export {
|
|
|
136
136
|
} from "./audio.js";
|
|
137
137
|
// sc-15908 — one host-brokered source for both entries (ctx.device.keyboard).
|
|
138
138
|
export { useKeyboard } from "./keyboard.js";
|
|
139
|
+
// sc-16671 — one host-brokered source for both entries (ctx.device.storage).
|
|
140
|
+
export { useDeviceStorage } from "./device-storage.js";
|
|
139
141
|
// sc-15163 — native-only in-app purchase; the web Player brokers none.
|
|
140
142
|
export { usePurchases, PurchasesError } from "./purchases.js";
|
|
141
143
|
export { useDatastoreFigure } from "./datastore-figure.js";
|
package/package.json
CHANGED
package/src/contract.js
CHANGED
|
@@ -3384,6 +3384,37 @@ const HOOKS = [
|
|
|
3384
3384
|
requiredContextSlice: [],
|
|
3385
3385
|
scopes: null,
|
|
3386
3386
|
},
|
|
3387
|
+
// sc-16671 — host-brokered device storage. Optional slice; without it the
|
|
3388
|
+
// value lives in memory and the hook reports supported:false.
|
|
3389
|
+
{
|
|
3390
|
+
name: "useDeviceStorage",
|
|
3391
|
+
signature: "useDeviceStorage(key, initial)",
|
|
3392
|
+
optionalArgs: ["initial"],
|
|
3393
|
+
description:
|
|
3394
|
+
"Keep a small JSON value on this device across page changes, refreshes and app restarts — a guest's shopping bag, " +
|
|
3395
|
+
"a dismissed tip, a last-picked filter. Returns { value, setValue, remove, loaded, supported, error }. `value` is the " +
|
|
3396
|
+
"stored value, or `initial` until one is stored; setValue(next) stores a JSON value or (previous) => next; remove() " +
|
|
3397
|
+
"deletes it. Every widget in the app that uses the same key sees a change at once, and on the web a change in another " +
|
|
3398
|
+
"tab arrives without a reload; the last write wins. `key` is 1-64 letters, digits, '.', '_' or '-'; a value is at most " +
|
|
3399
|
+
"16384 bytes as JSON. Values are kept per workspace and per device, shared by everyone who uses the app on that device, " +
|
|
3400
|
+
"so NEVER store a password, token, card number or other secret or personal data — keep account data in the datastore. " +
|
|
3401
|
+
"Wait for `loaded` before acting on an empty value. `supported` is false when the device keeps nothing (a private " +
|
|
3402
|
+
"window, blocked storage): the value then lasts until the page closes. `error` is { code, message } or null: " +
|
|
3403
|
+
"INVALID_KEY | INVALID_VALUE | TOO_LARGE (nothing changed) | CORRUPT (the stored value was unreadable; `initial` is shown) | " +
|
|
3404
|
+
"NOT_PERSISTED (the device refused it, e.g. full; kept until the app closes) | WRITE_FAILED. In the Builder canvas and " +
|
|
3405
|
+
"widget previews values are kept in memory only. Never touch localStorage or window yourself — the linter refuses it. " +
|
|
3406
|
+
"Identical on web (localStorage) and the Expo export (a file in the app's documents folder).",
|
|
3407
|
+
returnShape: {
|
|
3408
|
+
value: "any // the stored JSON value, or `initial`",
|
|
3409
|
+
setValue: "(next | (previous) => next) => void",
|
|
3410
|
+
remove: "() => void",
|
|
3411
|
+
loaded: "boolean // the stored value has been read",
|
|
3412
|
+
supported: "boolean // false: kept in memory only",
|
|
3413
|
+
error: "{ code, message } | null",
|
|
3414
|
+
},
|
|
3415
|
+
requiredContextSlice: [],
|
|
3416
|
+
scopes: null,
|
|
3417
|
+
},
|
|
3387
3418
|
// sc-6448 — host-brokered camera capture / photo picking. Optional slice;
|
|
3388
3419
|
// the hook reports supported:false rather than throwing at render.
|
|
3389
3420
|
{
|
|
@@ -4694,13 +4725,18 @@ const WIDGET_CONTEXT_SHAPE = {
|
|
|
4694
4725
|
"{ play() -> Promise<void>, pause(), seek(ms) -> Promise<void>, release() } }, " +
|
|
4695
4726
|
"keyboard: { hasKeyboard() -> boolean, subscribe({ keys: string[] | null, onKey({ type: 'down' | 'up', key, character, " +
|
|
4696
4727
|
"repeat, shiftKey, ctrlKey, altKey, metaKey }), onRelease(), onDetected() }) -> unsubscribe }, " +
|
|
4728
|
+
"storage: { isSupported() -> boolean, read(key) -> Promise<string | null>, write(key, raw) -> Promise<boolean>, " +
|
|
4729
|
+
"remove(key) -> Promise<void>, subscribe(key, onChange(raw | null)) -> unsubscribe }, " +
|
|
4697
4730
|
"purchases: { isSupported() -> boolean, getOffering() -> Promise<offering | null>, getEntitlements() -> Promise<string[]>, " +
|
|
4698
4731
|
"purchase(packageId) -> Promise<string[]>, restore() -> Promise<string[]> } }. " +
|
|
4699
4732
|
"purchases backs usePurchases() and is NATIVE-ONLY: the Expo export brokers it through react-native-purchases when the " +
|
|
4700
4733
|
"workspace connected RevenueCat; the web Player never does, because a browser has no store billing. " +
|
|
4701
|
-
"Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer() and
|
|
4702
|
-
"navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder, an <audio> element
|
|
4703
|
-
"expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio and expo-
|
|
4734
|
+
"Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer(), useKeyboard() and useDeviceStorage(). The web Player brokers them via " +
|
|
4735
|
+
"navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder, an <audio> element, window key listeners and localStorage; the Expo export via " +
|
|
4736
|
+
"expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio, expo-key-event and expo-file-system. " +
|
|
4737
|
+
"storage holds strings under keys scoped to the workspace; write resolves false when the device refused the value " +
|
|
4738
|
+
"(kept in memory instead) and notifies every subscriber of that key, as remove does with null; the web broker also " +
|
|
4739
|
+
"delivers other tabs' changes. " +
|
|
4704
4740
|
"keyboard.subscribe delivers only the `keys` named (all when null), stops the browser default of a delivered key " +
|
|
4705
4741
|
"pressed without Ctrl/Cmd/Alt, calls onRelease when the window or app loses focus or a text field opens and onDetected the first time any key " +
|
|
4706
4742
|
"arrives; a Builder preview's broker accepts keys only while focus is inside the preview. " +
|
|
@@ -4741,6 +4777,7 @@ const WIDGET_CONTEXT_SHAPE = {
|
|
|
4741
4777
|
audioRecorder: "object",
|
|
4742
4778
|
audioPlayer: "object",
|
|
4743
4779
|
keyboard: "object",
|
|
4780
|
+
storage: "object",
|
|
4744
4781
|
purchases: "object",
|
|
4745
4782
|
},
|
|
4746
4783
|
},
|
|
@@ -6970,7 +7007,7 @@ const CONTRACT = deepFreeze({
|
|
|
6970
7007
|
// the publish-blocking `payment-kind-required` finding.
|
|
6971
7008
|
// 1.259.0: `useDirectory()` / `useUsers()` rows carry `photo_url`, the
|
|
6972
7009
|
// person's profile photo as an absolute URL or null.
|
|
6973
|
-
version: "1.
|
|
7010
|
+
version: "1.260.0",
|
|
6974
7011
|
sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
|
|
6975
7012
|
hooks: HOOKS,
|
|
6976
7013
|
primitives: PRIMITIVES,
|