@assistant-ui/react-statewire 0.33.0 → 0.34.1
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/localStorage.d.ts
CHANGED
|
@@ -5,8 +5,8 @@ import type { StatewireThread } from "./StatewireThread.js";
|
|
|
5
5
|
export declare const LocalStorageComposerDrafts: import("@assistant-ui/tap").Resource<StatewireThread.ComposerStorage, [LocalStorageComposerDrafts.Options]>;
|
|
6
6
|
/** The localStorage backend `LocalStorageSession` writes through; pass it to `readOutboxes` / `subscribeOutboxes`. */
|
|
7
7
|
export declare const localStorageSessionBackend: KeyValueSessionStorage.Backend;
|
|
8
|
-
/** The namespace `LocalStorageSession` stores
|
|
9
|
-
export declare const localStorageSessionNamespace
|
|
8
|
+
/** The namespace `LocalStorageSession` stores sessions under; pass it with the principal to `readOutboxes` / `subscribeOutboxes`. */
|
|
9
|
+
export declare const localStorageSessionNamespace = "aui:statewire-session:";
|
|
10
10
|
/** Session storage on localStorage, keyed per principal and thread; sharers serialize through a per-key Web Lock. */
|
|
11
11
|
export declare const LocalStorageSession: import("@assistant-ui/tap").Resource<StatewireClient.SessionStorage, [LocalStorageSession.Options]>;
|
|
12
12
|
export declare namespace LocalStorageSession {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localStorage.d.ts","sourceRoot":"","sources":["../src/localStorage.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAE,6BAA0B;AAyKzD,+GAA+G;AAC/G,eAAO,MAAM,0BAA0B,6GAEtC,CAAC;
|
|
1
|
+
{"version":3,"file":"localStorage.d.ts","sourceRoot":"","sources":["../src/localStorage.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC3D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8 +125,6 @@ const useLocalStorageSession = ({ threadId, migrate, principal, protocol, retent
|
|
|
125
125
|
if (typeof localStorage === "undefined") throw new Error("statewire: LocalStorageSession requires localStorage");
|
|
126
126
|
if (typeof navigator === "undefined" || navigator.locks === void 0) throw new Error("statewire: LocalStorageSession requires the Web Locks API (navigator.locks)");
|
|
127
127
|
const scopeKey = scopedKey("", principal, threadId);
|
|
128
|
-
const namespace = scopePrefix(SESSION_PREFIX, principal);
|
|
129
|
-
usePrincipal(principal);
|
|
130
128
|
const storageKey = SESSION_PREFIX + scopeKey;
|
|
131
129
|
const lockName = SESSION_LOCK_PREFIX + scopeKey;
|
|
132
130
|
const [tabId] = useState(() => crypto.randomUUID());
|
|
@@ -157,7 +155,8 @@ const useLocalStorageSession = ({ threadId, migrate, principal, protocol, retent
|
|
|
157
155
|
const storage = useResource(KeyValueSessionStorage({
|
|
158
156
|
backend: sessionBackend,
|
|
159
157
|
key: encodeURIComponent(threadId),
|
|
160
|
-
namespace,
|
|
158
|
+
namespace: SESSION_PREFIX,
|
|
159
|
+
principal,
|
|
161
160
|
...migrate === void 0 ? {} : { migrate },
|
|
162
161
|
...protocol === void 0 ? {} : { protocol },
|
|
163
162
|
...retention === void 0 ? {} : { retention },
|
|
@@ -189,8 +188,8 @@ const useLocalStorageSession = ({ threadId, migrate, principal, protocol, retent
|
|
|
189
188
|
};
|
|
190
189
|
/** The localStorage backend `LocalStorageSession` writes through; pass it to `readOutboxes` / `subscribeOutboxes`. */
|
|
191
190
|
const localStorageSessionBackend = sessionBackend;
|
|
192
|
-
/** The namespace `LocalStorageSession` stores
|
|
193
|
-
const localStorageSessionNamespace =
|
|
191
|
+
/** The namespace `LocalStorageSession` stores sessions under; pass it with the principal to `readOutboxes` / `subscribeOutboxes`. */
|
|
192
|
+
const localStorageSessionNamespace = SESSION_PREFIX;
|
|
194
193
|
/** Session storage on localStorage, keyed per principal and thread; sharers serialize through a per-key Web Lock. */
|
|
195
194
|
const LocalStorageSession = resource(useLocalStorageSession);
|
|
196
195
|
export { LocalStorageComposerDrafts, LocalStorageSession, localStorageSessionBackend, localStorageSessionNamespace };
|
package/dist/localStorage.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localStorage.js","names":["useEffect","useMemo","useRef","useState","resource","useResource","KeyValueSessionStorage","StatewireClient","StatewireThread","PREFIX","SESSION_PREFIX","DAY","scopePrefix","prefix","principal","Error","encodeURIComponent","scopedKey","threadId","usePrincipal","initial","current","StoredDraft","text","attachments","ComposerDraft","ts","isRecord","value","Record","Array","isArray","isOptionalString","undefined","isUserMessagePart","audio","StoredAttachment","isStoredAttachment","status","every","isStoredDraft","Number","isFinite","loadStored","key","validate","T","raw","localStorage","getItem","JSON","parse","removeItem","sweep","scope","ttl","max","entries","keys","from","length","_","index","startsWith","stored","push","now","Date","fresh","filter","sort","a","b","slice","useLocalStorageComposerDrafts","LocalStorageComposerDrafts","Options","ComposerStorage","storageKey","read","write","draft","setItem","stringify","clear","SESSION_LOCK_PREFIX","SESSION_ACTIVE_PREFIX","TAB_LOCK_PREFIX","NOTIFY_LOCK_PREFIX","sessionBackend","Backend","getAllKeys","withUnused","action","navigator","locks","request","ifAvailable","lock","subscribe","listener","onStorage","event","StorageEvent","window","addEventListener","removeEventListener","useLocalStorageSession","migrate","protocol","retention","limits","onError","onEvict","LocalStorageSession","SessionStorage","scopeKey","namespace","lockName","tabId","crypto","randomUUID","latestOnError","release","held","Promise","resolve","catch","error","disposed","mode","storage","backend","fn","notifyLock","owner","id","whenGone","signal","localStorageSessionBackend","localStorageSessionNamespace"],"sources":["../src/localStorage.ts"],"sourcesContent":["import { useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport { KeyValueSessionStorage } from \"statewire/storage\";\nimport type { StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nconst PREFIX = \"aui:composer-draft:\";\nconst SESSION_PREFIX = \"aui:statewire-session:\";\nconst DAY = 86_400_000;\n\nconst scopePrefix = (prefix: string, principal: string) => {\n if (typeof principal !== \"string\" || principal === \"\")\n throw new Error(\"statewire: storage requires a non-empty principal\");\n return `${prefix}${encodeURIComponent(principal)}:`;\n};\n\nconst scopedKey = (prefix: string, principal: string, threadId: string) =>\n `${scopePrefix(prefix, principal)}${encodeURIComponent(threadId)}`;\n\nconst usePrincipal = (principal: string) => {\n const initial = useRef(principal);\n if (initial.current !== principal)\n throw new Error(\n \"statewire: principal changed; remount the account's thread/session\",\n );\n};\n\ntype StoredDraft = {\n text: string;\n attachments: StatewireThread.ComposerDraft[\"attachments\"];\n ts: number;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isOptionalString = (value: unknown): boolean =>\n value === undefined || typeof value === \"string\";\n\nconst isUserMessagePart = (value: unknown): boolean => {\n if (!isRecord(value)) return false;\n switch (value[\"type\"]) {\n case \"text\":\n return typeof value[\"text\"] === \"string\";\n case \"image\":\n return (\n typeof value[\"image\"] === \"string\" &&\n isOptionalString(value[\"filename\"])\n );\n case \"file\":\n return (\n typeof value[\"data\"] === \"string\" &&\n typeof value[\"mimeType\"] === \"string\" &&\n isOptionalString(value[\"filename\"])\n );\n case \"data\":\n return typeof value[\"name\"] === \"string\";\n case \"audio\": {\n const audio = value[\"audio\"];\n return (\n isRecord(audio) &&\n typeof audio[\"data\"] === \"string\" &&\n (audio[\"format\"] === \"mp3\" || audio[\"format\"] === \"wav\")\n );\n }\n default:\n return false;\n }\n};\n\ntype StoredAttachment = StoredDraft[\"attachments\"][number];\n\nconst isStoredAttachment = (value: unknown): value is StoredAttachment => {\n if (!isRecord(value)) return false;\n const status = value[\"status\"];\n return (\n typeof value[\"id\"] === \"string\" &&\n typeof value[\"type\"] === \"string\" &&\n typeof value[\"name\"] === \"string\" &&\n isOptionalString(value[\"contentType\"]) &&\n value[\"file\"] === undefined &&\n isRecord(status) &&\n status[\"type\"] === \"complete\" &&\n Array.isArray(value[\"content\"]) &&\n value[\"content\"].every(isUserMessagePart)\n );\n};\n\nconst isStoredDraft = (value: unknown): value is StoredDraft =>\n isRecord(value) &&\n typeof value[\"text\"] === \"string\" &&\n Array.isArray(value[\"attachments\"]) &&\n value[\"attachments\"].every(isStoredAttachment) &&\n typeof value[\"ts\"] === \"number\" &&\n Number.isFinite(value[\"ts\"]);\n\nconst loadStored = <T>(\n key: string,\n validate: (value: unknown) => value is T,\n): T | null => {\n const raw = localStorage.getItem(key);\n if (raw === null) return null;\n try {\n const value: unknown = JSON.parse(raw);\n if (validate(value)) return value;\n } catch {}\n localStorage.removeItem(key);\n return null;\n};\n\nconst sweep = (scope: string, ttl: number, max: number) => {\n const entries: { key: string; ts: number }[] = [];\n const keys = Array.from({ length: localStorage.length }, (_, index) =>\n localStorage.key(index),\n );\n for (const key of keys) {\n if (key === null || !key.startsWith(scope)) continue;\n const stored = loadStored(key, isStoredDraft);\n if (stored !== null) entries.push({ key, ts: stored.ts });\n }\n const now = Date.now();\n const fresh = entries.filter(({ key, ts }) => {\n if (now - ts <= ttl) return true;\n localStorage.removeItem(key);\n return false;\n });\n fresh.sort((a, b) => b.ts - a.ts);\n for (const { key } of fresh.slice(max)) localStorage.removeItem(key);\n};\n\nconst useLocalStorageComposerDrafts = ({\n threadId,\n principal,\n ttl = 7 * DAY,\n max = 50,\n}: LocalStorageComposerDrafts.Options): StatewireThread.ComposerStorage => {\n if (typeof localStorage === \"undefined\")\n throw new Error(\n \"statewire: LocalStorageComposerDrafts requires localStorage\",\n );\n\n const scope = scopePrefix(PREFIX, principal);\n usePrincipal(principal);\n useEffect(() => {\n sweep(scope, ttl, max);\n }, [scope, ttl, max]);\n\n const storageKey = scopedKey(PREFIX, principal, threadId);\n return useMemo(\n (): StatewireThread.ComposerStorage => ({\n read: () => {\n const stored = loadStored(storageKey, isStoredDraft);\n if (stored === null) return undefined;\n return { text: stored.text, attachments: stored.attachments };\n },\n write: (draft) => {\n if (draft.text === \"\" && draft.attachments.length === 0) {\n localStorage.removeItem(storageKey);\n return;\n }\n localStorage.setItem(\n storageKey,\n JSON.stringify({ ...draft, ts: Date.now() }),\n );\n },\n clear: () => {\n localStorage.removeItem(storageKey);\n },\n }),\n [storageKey],\n );\n};\n\n/** Composer draft storage on localStorage, keyed per principal and thread; stale drafts are swept on mount. */\nexport const LocalStorageComposerDrafts = resource(\n useLocalStorageComposerDrafts,\n);\n\nconst SESSION_LOCK_PREFIX = \"aui:statewire-session-lock:\";\n\nconst SESSION_ACTIVE_PREFIX = \"aui:statewire-session-active:\";\n\nconst TAB_LOCK_PREFIX = \"statewire-tab:\";\n\nconst NOTIFY_LOCK_PREFIX = \"statewire-notify:\";\n\nconst sessionBackend: KeyValueSessionStorage.Backend = {\n getItem: (key) => localStorage.getItem(key),\n setItem: (key, value) => localStorage.setItem(key, value),\n removeItem: (key) => localStorage.removeItem(key),\n getAllKeys: () =>\n Array.from({ length: localStorage.length }, (_, index) =>\n localStorage.key(index),\n ).filter((key): key is string => key !== null),\n withUnused: (key, action) =>\n navigator.locks.request(\n SESSION_ACTIVE_PREFIX + key,\n { ifAvailable: true },\n (lock) =>\n lock === null\n ? undefined\n : navigator.locks.request(\n SESSION_LOCK_PREFIX + key.slice(SESSION_PREFIX.length),\n { ifAvailable: true },\n (lock) => (lock === null ? undefined : action()),\n ),\n ),\n subscribe: (listener) => {\n const onStorage = (event: StorageEvent) => {\n if (event.key !== null) listener(event.key);\n };\n window.addEventListener(\"storage\", onStorage);\n return () => window.removeEventListener(\"storage\", onStorage);\n },\n};\n\nconst useLocalStorageSession = ({\n threadId,\n migrate,\n principal,\n protocol,\n retention,\n limits,\n onError,\n onEvict,\n}: LocalStorageSession.Options): StatewireClient.SessionStorage => {\n if (typeof localStorage === \"undefined\")\n throw new Error(\"statewire: LocalStorageSession requires localStorage\");\n if (typeof navigator === \"undefined\" || navigator.locks === undefined)\n throw new Error(\n \"statewire: LocalStorageSession requires the Web Locks API (navigator.locks)\",\n );\n const scopeKey = scopedKey(\"\", principal, threadId);\n const namespace = scopePrefix(SESSION_PREFIX, principal);\n usePrincipal(principal);\n const storageKey = SESSION_PREFIX + scopeKey;\n const lockName = SESSION_LOCK_PREFIX + scopeKey;\n const [tabId] = useState(() => crypto.randomUUID());\n const latestOnError = useRef(onError);\n latestOnError.current = onError;\n useEffect(() => {\n let release: (() => void) | undefined;\n const held = new Promise<void>((resolve) => {\n release = resolve;\n });\n void navigator.locks\n .request(TAB_LOCK_PREFIX + tabId, () => held)\n .catch((error: unknown) => latestOnError.current?.(error));\n return () => release?.();\n }, [tabId]);\n useEffect(() => {\n let release: (() => void) | undefined;\n let disposed = false;\n void navigator.locks\n .request(SESSION_ACTIVE_PREFIX + storageKey, { mode: \"shared\" }, () => {\n if (disposed) return;\n return new Promise<void>((resolve) => {\n release = resolve;\n });\n })\n .catch((error: unknown) => onError?.(error));\n return () => {\n disposed = true;\n release?.();\n };\n }, [storageKey, onError]);\n const storage = useResource(\n KeyValueSessionStorage({\n backend: sessionBackend,\n key: encodeURIComponent(threadId),\n namespace,\n ...(migrate === undefined ? {} : { migrate }),\n ...(protocol === undefined ? {} : { protocol }),\n ...(retention === undefined ? {} : { retention }),\n ...(limits === undefined ? {} : { limits }),\n ...(onError === undefined ? {} : { onError }),\n ...(onEvict === undefined ? {} : { onEvict }),\n }),\n );\n return useMemo(\n (): StatewireClient.SessionStorage => ({\n ...storage,\n lock: (fn) => navigator.locks.request(lockName, async () => fn()),\n notifyLock: (fn) =>\n navigator.locks.request(NOTIFY_LOCK_PREFIX + storageKey, fn),\n owner: {\n id: tabId,\n whenGone: (id, signal) =>\n navigator.locks.request(TAB_LOCK_PREFIX + id, { signal }, () => {}),\n },\n subscribe: (listener) => {\n const onStorage = (event: StorageEvent) => {\n if (event.key === storageKey) listener();\n };\n window.addEventListener(\"storage\", onStorage);\n return () => window.removeEventListener(\"storage\", onStorage);\n },\n }),\n [storage, storageKey, lockName, tabId],\n );\n};\n\n/** The localStorage backend `LocalStorageSession` writes through; pass it to `readOutboxes` / `subscribeOutboxes`. */\nexport const localStorageSessionBackend = sessionBackend;\n\n/** The namespace `LocalStorageSession` stores a principal's sessions under. */\nexport const localStorageSessionNamespace = (principal: string) =>\n scopePrefix(SESSION_PREFIX, principal);\n\n/** Session storage on localStorage, keyed per principal and thread; sharers serialize through a per-key Web Lock. */\nexport const LocalStorageSession = resource(useLocalStorageSession);\n\nexport namespace LocalStorageSession {\n export type Options = {\n protocol?: KeyValueSessionStorage.Options[\"protocol\"];\n retention?: KeyValueSessionStorage.Options[\"retention\"];\n limits?: KeyValueSessionStorage.Options[\"limits\"];\n onError?: KeyValueSessionStorage.Options[\"onError\"];\n onEvict?: KeyValueSessionStorage.Options[\"onEvict\"];\n /** Upgrade incompatible queued commands, or return null to discard the saved session. */\n migrate?: StatewireClient.SessionStorage[\"migrate\"];\n /** The thread whose session this storage holds. */\n threadId: string;\n /** The account whose commands this storage holds. */\n principal: string;\n };\n}\n\nexport namespace LocalStorageComposerDrafts {\n export type Options = {\n /** The thread whose draft this storage holds. */\n threadId: string;\n /** The account whose draft this storage holds. */\n principal: string;\n /** Draft lifetime in milliseconds, enforced by the mount sweep. Default 7 days. */\n ttl?: number | undefined;\n /** Newest drafts kept across the principal's threads, enforced by the mount sweep. Default 50. */\n max?: number | undefined;\n };\n}\n"],"mappings":";;;;AAMA,MAAMS,SAAS;AACf,MAAMC,iBAAiB;AACvB,MAAMC,MAAM;AAEZ,MAAMC,eAAeC,QAAgBC,cAAsB;CACzD,IAAI,OAAOA,cAAc,YAAYA,cAAc,IACjD,MAAM,IAAIC,MAAM,mDAAmD;CACrE,OAAO,GAAGF,SAASG,mBAAmBF,SAAS,EAAC;AAClD;AAEA,MAAMG,aAAaJ,QAAgBC,WAAmBI,aACpD,GAAGN,YAAYC,QAAQC,SAAS,IAAIE,mBAAmBE,QAAQ;AAEjE,MAAMC,gBAAgBL,cAAsB;CAE1C,IADgBZ,OAAOY,SACnBM,CAAO,CAACC,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aG,OAAOE,oBAAoB,WAAWL,SAAS;EAC9D;CACF,IACA;EAAC8B;EAASrD;EAAYwC;EAAUC;CAAK,CACvC;AACF;;AAGA,MAAaoB,6BAA6BlD;;AAG1C,MAAamD,gCAAgC9H,cAC3CF,YAAYF,gBAAgBI,SAAS;;AAGvC,MAAaoG,sBAAsB9G,SAASuG,sBAAsB"}
|
|
1
|
+
{"version":3,"file":"localStorage.js","names":["useEffect","useMemo","useRef","useState","resource","useResource","KeyValueSessionStorage","StatewireClient","StatewireThread","PREFIX","SESSION_PREFIX","DAY","scopePrefix","prefix","principal","Error","encodeURIComponent","scopedKey","threadId","usePrincipal","initial","current","StoredDraft","text","attachments","ComposerDraft","ts","isRecord","value","Record","Array","isArray","isOptionalString","undefined","isUserMessagePart","audio","StoredAttachment","isStoredAttachment","status","every","isStoredDraft","Number","isFinite","loadStored","key","validate","T","raw","localStorage","getItem","JSON","parse","removeItem","sweep","scope","ttl","max","entries","keys","from","length","_","index","startsWith","stored","push","now","Date","fresh","filter","sort","a","b","slice","useLocalStorageComposerDrafts","LocalStorageComposerDrafts","Options","ComposerStorage","storageKey","read","write","draft","setItem","stringify","clear","SESSION_LOCK_PREFIX","SESSION_ACTIVE_PREFIX","TAB_LOCK_PREFIX","NOTIFY_LOCK_PREFIX","sessionBackend","Backend","getAllKeys","withUnused","action","navigator","locks","request","ifAvailable","lock","subscribe","listener","onStorage","event","StorageEvent","window","addEventListener","removeEventListener","useLocalStorageSession","migrate","protocol","retention","limits","onError","onEvict","LocalStorageSession","SessionStorage","scopeKey","lockName","tabId","crypto","randomUUID","latestOnError","release","held","Promise","resolve","catch","error","disposed","mode","storage","backend","namespace","fn","notifyLock","owner","id","whenGone","signal","localStorageSessionBackend","localStorageSessionNamespace"],"sources":["../src/localStorage.ts"],"sourcesContent":["import { useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport { KeyValueSessionStorage } from \"statewire/storage\";\nimport type { StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nconst PREFIX = \"aui:composer-draft:\";\nconst SESSION_PREFIX = \"aui:statewire-session:\";\nconst DAY = 86_400_000;\n\nconst scopePrefix = (prefix: string, principal: string) => {\n if (typeof principal !== \"string\" || principal === \"\")\n throw new Error(\"statewire: storage requires a non-empty principal\");\n return `${prefix}${encodeURIComponent(principal)}:`;\n};\n\nconst scopedKey = (prefix: string, principal: string, threadId: string) =>\n `${scopePrefix(prefix, principal)}${encodeURIComponent(threadId)}`;\n\nconst usePrincipal = (principal: string) => {\n const initial = useRef(principal);\n if (initial.current !== principal)\n throw new Error(\n \"statewire: principal changed; remount the account's thread/session\",\n );\n};\n\ntype StoredDraft = {\n text: string;\n attachments: StatewireThread.ComposerDraft[\"attachments\"];\n ts: number;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isOptionalString = (value: unknown): boolean =>\n value === undefined || typeof value === \"string\";\n\nconst isUserMessagePart = (value: unknown): boolean => {\n if (!isRecord(value)) return false;\n switch (value[\"type\"]) {\n case \"text\":\n return typeof value[\"text\"] === \"string\";\n case \"image\":\n return (\n typeof value[\"image\"] === \"string\" &&\n isOptionalString(value[\"filename\"])\n );\n case \"file\":\n return (\n typeof value[\"data\"] === \"string\" &&\n typeof value[\"mimeType\"] === \"string\" &&\n isOptionalString(value[\"filename\"])\n );\n case \"data\":\n return typeof value[\"name\"] === \"string\";\n case \"audio\": {\n const audio = value[\"audio\"];\n return (\n isRecord(audio) &&\n typeof audio[\"data\"] === \"string\" &&\n (audio[\"format\"] === \"mp3\" || audio[\"format\"] === \"wav\")\n );\n }\n default:\n return false;\n }\n};\n\ntype StoredAttachment = StoredDraft[\"attachments\"][number];\n\nconst isStoredAttachment = (value: unknown): value is StoredAttachment => {\n if (!isRecord(value)) return false;\n const status = value[\"status\"];\n return (\n typeof value[\"id\"] === \"string\" &&\n typeof value[\"type\"] === \"string\" &&\n typeof value[\"name\"] === \"string\" &&\n isOptionalString(value[\"contentType\"]) &&\n value[\"file\"] === undefined &&\n isRecord(status) &&\n status[\"type\"] === \"complete\" &&\n Array.isArray(value[\"content\"]) &&\n value[\"content\"].every(isUserMessagePart)\n );\n};\n\nconst isStoredDraft = (value: unknown): value is StoredDraft =>\n isRecord(value) &&\n typeof value[\"text\"] === \"string\" &&\n Array.isArray(value[\"attachments\"]) &&\n value[\"attachments\"].every(isStoredAttachment) &&\n typeof value[\"ts\"] === \"number\" &&\n Number.isFinite(value[\"ts\"]);\n\nconst loadStored = <T>(\n key: string,\n validate: (value: unknown) => value is T,\n): T | null => {\n const raw = localStorage.getItem(key);\n if (raw === null) return null;\n try {\n const value: unknown = JSON.parse(raw);\n if (validate(value)) return value;\n } catch {}\n localStorage.removeItem(key);\n return null;\n};\n\nconst sweep = (scope: string, ttl: number, max: number) => {\n const entries: { key: string; ts: number }[] = [];\n const keys = Array.from({ length: localStorage.length }, (_, index) =>\n localStorage.key(index),\n );\n for (const key of keys) {\n if (key === null || !key.startsWith(scope)) continue;\n const stored = loadStored(key, isStoredDraft);\n if (stored !== null) entries.push({ key, ts: stored.ts });\n }\n const now = Date.now();\n const fresh = entries.filter(({ key, ts }) => {\n if (now - ts <= ttl) return true;\n localStorage.removeItem(key);\n return false;\n });\n fresh.sort((a, b) => b.ts - a.ts);\n for (const { key } of fresh.slice(max)) localStorage.removeItem(key);\n};\n\nconst useLocalStorageComposerDrafts = ({\n threadId,\n principal,\n ttl = 7 * DAY,\n max = 50,\n}: LocalStorageComposerDrafts.Options): StatewireThread.ComposerStorage => {\n if (typeof localStorage === \"undefined\")\n throw new Error(\n \"statewire: LocalStorageComposerDrafts requires localStorage\",\n );\n\n const scope = scopePrefix(PREFIX, principal);\n usePrincipal(principal);\n useEffect(() => {\n sweep(scope, ttl, max);\n }, [scope, ttl, max]);\n\n const storageKey = scopedKey(PREFIX, principal, threadId);\n return useMemo(\n (): StatewireThread.ComposerStorage => ({\n read: () => {\n const stored = loadStored(storageKey, isStoredDraft);\n if (stored === null) return undefined;\n return { text: stored.text, attachments: stored.attachments };\n },\n write: (draft) => {\n if (draft.text === \"\" && draft.attachments.length === 0) {\n localStorage.removeItem(storageKey);\n return;\n }\n localStorage.setItem(\n storageKey,\n JSON.stringify({ ...draft, ts: Date.now() }),\n );\n },\n clear: () => {\n localStorage.removeItem(storageKey);\n },\n }),\n [storageKey],\n );\n};\n\n/** Composer draft storage on localStorage, keyed per principal and thread; stale drafts are swept on mount. */\nexport const LocalStorageComposerDrafts = resource(\n useLocalStorageComposerDrafts,\n);\n\nconst SESSION_LOCK_PREFIX = \"aui:statewire-session-lock:\";\n\nconst SESSION_ACTIVE_PREFIX = \"aui:statewire-session-active:\";\n\nconst TAB_LOCK_PREFIX = \"statewire-tab:\";\n\nconst NOTIFY_LOCK_PREFIX = \"statewire-notify:\";\n\nconst sessionBackend: KeyValueSessionStorage.Backend = {\n getItem: (key) => localStorage.getItem(key),\n setItem: (key, value) => localStorage.setItem(key, value),\n removeItem: (key) => localStorage.removeItem(key),\n getAllKeys: () =>\n Array.from({ length: localStorage.length }, (_, index) =>\n localStorage.key(index),\n ).filter((key): key is string => key !== null),\n withUnused: (key, action) =>\n navigator.locks.request(\n SESSION_ACTIVE_PREFIX + key,\n { ifAvailable: true },\n (lock) =>\n lock === null\n ? undefined\n : navigator.locks.request(\n SESSION_LOCK_PREFIX + key.slice(SESSION_PREFIX.length),\n { ifAvailable: true },\n (lock) => (lock === null ? undefined : action()),\n ),\n ),\n subscribe: (listener) => {\n const onStorage = (event: StorageEvent) => {\n if (event.key !== null) listener(event.key);\n };\n window.addEventListener(\"storage\", onStorage);\n return () => window.removeEventListener(\"storage\", onStorage);\n },\n};\n\nconst useLocalStorageSession = ({\n threadId,\n migrate,\n principal,\n protocol,\n retention,\n limits,\n onError,\n onEvict,\n}: LocalStorageSession.Options): StatewireClient.SessionStorage => {\n if (typeof localStorage === \"undefined\")\n throw new Error(\"statewire: LocalStorageSession requires localStorage\");\n if (typeof navigator === \"undefined\" || navigator.locks === undefined)\n throw new Error(\n \"statewire: LocalStorageSession requires the Web Locks API (navigator.locks)\",\n );\n const scopeKey = scopedKey(\"\", principal, threadId);\n const storageKey = SESSION_PREFIX + scopeKey;\n const lockName = SESSION_LOCK_PREFIX + scopeKey;\n const [tabId] = useState(() => crypto.randomUUID());\n const latestOnError = useRef(onError);\n latestOnError.current = onError;\n useEffect(() => {\n let release: (() => void) | undefined;\n const held = new Promise<void>((resolve) => {\n release = resolve;\n });\n void navigator.locks\n .request(TAB_LOCK_PREFIX + tabId, () => held)\n .catch((error: unknown) => latestOnError.current?.(error));\n return () => release?.();\n }, [tabId]);\n useEffect(() => {\n let release: (() => void) | undefined;\n let disposed = false;\n void navigator.locks\n .request(SESSION_ACTIVE_PREFIX + storageKey, { mode: \"shared\" }, () => {\n if (disposed) return;\n return new Promise<void>((resolve) => {\n release = resolve;\n });\n })\n .catch((error: unknown) => onError?.(error));\n return () => {\n disposed = true;\n release?.();\n };\n }, [storageKey, onError]);\n const storage = useResource(\n KeyValueSessionStorage({\n backend: sessionBackend,\n key: encodeURIComponent(threadId),\n namespace: SESSION_PREFIX,\n principal,\n ...(migrate === undefined ? {} : { migrate }),\n ...(protocol === undefined ? {} : { protocol }),\n ...(retention === undefined ? {} : { retention }),\n ...(limits === undefined ? {} : { limits }),\n ...(onError === undefined ? {} : { onError }),\n ...(onEvict === undefined ? {} : { onEvict }),\n }),\n );\n return useMemo(\n (): StatewireClient.SessionStorage => ({\n ...storage,\n lock: (fn) => navigator.locks.request(lockName, async () => fn()),\n notifyLock: (fn) =>\n navigator.locks.request(NOTIFY_LOCK_PREFIX + storageKey, fn),\n owner: {\n id: tabId,\n whenGone: (id, signal) =>\n navigator.locks.request(TAB_LOCK_PREFIX + id, { signal }, () => {}),\n },\n subscribe: (listener) => {\n const onStorage = (event: StorageEvent) => {\n if (event.key === storageKey) listener();\n };\n window.addEventListener(\"storage\", onStorage);\n return () => window.removeEventListener(\"storage\", onStorage);\n },\n }),\n [storage, storageKey, lockName, tabId],\n );\n};\n\n/** The localStorage backend `LocalStorageSession` writes through; pass it to `readOutboxes` / `subscribeOutboxes`. */\nexport const localStorageSessionBackend = sessionBackend;\n\n/** The namespace `LocalStorageSession` stores sessions under; pass it with the principal to `readOutboxes` / `subscribeOutboxes`. */\nexport const localStorageSessionNamespace = SESSION_PREFIX;\n\n/** Session storage on localStorage, keyed per principal and thread; sharers serialize through a per-key Web Lock. */\nexport const LocalStorageSession = resource(useLocalStorageSession);\n\nexport namespace LocalStorageSession {\n export type Options = {\n protocol?: KeyValueSessionStorage.Options[\"protocol\"];\n retention?: KeyValueSessionStorage.Options[\"retention\"];\n limits?: KeyValueSessionStorage.Options[\"limits\"];\n onError?: KeyValueSessionStorage.Options[\"onError\"];\n onEvict?: KeyValueSessionStorage.Options[\"onEvict\"];\n /** Upgrade incompatible queued commands, or return null to discard the saved session. */\n migrate?: StatewireClient.SessionStorage[\"migrate\"];\n /** The thread whose session this storage holds. */\n threadId: string;\n /** The account whose commands this storage holds. */\n principal: string;\n };\n}\n\nexport namespace LocalStorageComposerDrafts {\n export type Options = {\n /** The thread whose draft this storage holds. */\n threadId: string;\n /** The account whose draft this storage holds. */\n principal: string;\n /** Draft lifetime in milliseconds, enforced by the mount sweep. Default 7 days. */\n ttl?: number | undefined;\n /** Newest drafts kept across the principal's threads, enforced by the mount sweep. Default 50. */\n max?: number | undefined;\n };\n}\n"],"mappings":";;;;AAMA,MAAMS,SAAS;AACf,MAAMC,iBAAiB;AACvB,MAAMC,MAAM;AAEZ,MAAMC,eAAeC,QAAgBC,cAAsB;CACzD,IAAI,OAAOA,cAAc,YAAYA,cAAc,IACjD,MAAM,IAAIC,MAAM,mDAAmD;CACrE,OAAO,GAAGF,SAASG,mBAAmBF,SAAS,EAAC;AAClD;AAEA,MAAMG,aAAaJ,QAAgBC,WAAmBI,aACpD,GAAGN,YAAYC,QAAQC,SAAS,IAAIE,mBAAmBE,Q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iB,WAAWJ,SAAS;GAC5C,aAAaG,OAAOE,oBAAoB,WAAWL,SAAS;EAC9D;CACF,IACA;EAAC6B;EAASpD;EAAYuC;EAAUC;CAAK,CACvC;AACF;;AAGA,MAAaqB,6BAA6BlD;;AAG1C,MAAamD,+BAA+BlI;;AAG5C,MAAawG,sBAAsB9G,SAASuG,sBAAsB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@assistant-ui/react-statewire",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.34.1",
|
|
4
4
|
"description": "assistant-ui thread binding for statewire backends",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"@assistant-ui/store": "^0.3.22",
|
|
40
40
|
"@assistant-ui/tap": "^0.9.24",
|
|
41
41
|
"assistant-stream": "^0.3.53",
|
|
42
|
-
"statewire": "^0.
|
|
42
|
+
"statewire": "^0.26.0"
|
|
43
43
|
},
|
|
44
44
|
"peerDependencies": {
|
|
45
45
|
"@assistant-ui/core": ">=0.3.12",
|
package/src/localStorage.test.ts
CHANGED
|
@@ -235,7 +235,8 @@ describe("LocalStorageSession", () => {
|
|
|
235
235
|
root.getValue().save(record);
|
|
236
236
|
expect(JSON.parse(localStorage.getItem(`${SESSION_PREFIX}t1`)!)).toEqual({
|
|
237
237
|
...record,
|
|
238
|
-
|
|
238
|
+
principal: "u1",
|
|
239
|
+
statewireStorageVersion: 6,
|
|
239
240
|
savedAt: expect.any(Number),
|
|
240
241
|
});
|
|
241
242
|
expect(root.getValue().load()).toEqual(record);
|
package/src/localStorage.ts
CHANGED
|
@@ -231,8 +231,6 @@ const useLocalStorageSession = ({
|
|
|
231
231
|
"statewire: LocalStorageSession requires the Web Locks API (navigator.locks)",
|
|
232
232
|
);
|
|
233
233
|
const scopeKey = scopedKey("", principal, threadId);
|
|
234
|
-
const namespace = scopePrefix(SESSION_PREFIX, principal);
|
|
235
|
-
usePrincipal(principal);
|
|
236
234
|
const storageKey = SESSION_PREFIX + scopeKey;
|
|
237
235
|
const lockName = SESSION_LOCK_PREFIX + scopeKey;
|
|
238
236
|
const [tabId] = useState(() => crypto.randomUUID());
|
|
@@ -268,7 +266,8 @@ const useLocalStorageSession = ({
|
|
|
268
266
|
KeyValueSessionStorage({
|
|
269
267
|
backend: sessionBackend,
|
|
270
268
|
key: encodeURIComponent(threadId),
|
|
271
|
-
namespace,
|
|
269
|
+
namespace: SESSION_PREFIX,
|
|
270
|
+
principal,
|
|
272
271
|
...(migrate === undefined ? {} : { migrate }),
|
|
273
272
|
...(protocol === undefined ? {} : { protocol }),
|
|
274
273
|
...(retention === undefined ? {} : { retention }),
|
|
@@ -303,9 +302,8 @@ const useLocalStorageSession = ({
|
|
|
303
302
|
/** The localStorage backend `LocalStorageSession` writes through; pass it to `readOutboxes` / `subscribeOutboxes`. */
|
|
304
303
|
export const localStorageSessionBackend = sessionBackend;
|
|
305
304
|
|
|
306
|
-
/** The namespace `LocalStorageSession` stores
|
|
307
|
-
export const localStorageSessionNamespace =
|
|
308
|
-
scopePrefix(SESSION_PREFIX, principal);
|
|
305
|
+
/** The namespace `LocalStorageSession` stores sessions under; pass it with the principal to `readOutboxes` / `subscribeOutboxes`. */
|
|
306
|
+
export const localStorageSessionNamespace = SESSION_PREFIX;
|
|
309
307
|
|
|
310
308
|
/** Session storage on localStorage, keyed per principal and thread; sharers serialize through a per-key Web Lock. */
|
|
311
309
|
export const LocalStorageSession = resource(useLocalStorageSession);
|