@invisible-labs/sdk 0.6.0-devnet.3 → 0.6.0-devnet.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +129 -15
  2. package/dist/.invisible-sdk-build-target.json +7 -0
  3. package/dist/{chunk-QQSI3ZD7.js → chunk-3MDHAS4D.js} +109 -17
  4. package/dist/chunk-3MDHAS4D.js.map +1 -0
  5. package/dist/{chunk-NKRVQXRP.js → chunk-3TGQ4CZ3.js} +297 -11
  6. package/dist/chunk-3TGQ4CZ3.js.map +1 -0
  7. package/dist/chunk-DCTYBUY3.js +258 -0
  8. package/dist/chunk-DCTYBUY3.js.map +1 -0
  9. package/dist/{chunk-NHEHCUS5.js → chunk-EBWTAXNT.js} +3 -3
  10. package/dist/{chunk-NHEHCUS5.js.map → chunk-EBWTAXNT.js.map} +1 -1
  11. package/dist/{chunk-V5HXJRBW.js → chunk-HJFMDMPY.js} +3 -3
  12. package/dist/chunk-HJFMDMPY.js.map +1 -0
  13. package/dist/{chunk-GHBQF3A7.js → chunk-QRN46R3F.js} +5 -2
  14. package/dist/chunk-QRN46R3F.js.map +1 -0
  15. package/dist/chunk-Y7AK6RBV.js +4189 -0
  16. package/dist/chunk-Y7AK6RBV.js.map +1 -0
  17. package/dist/{coordinator-VVJ33WF2.js → coordinator-PEWHNZ7I.js} +3 -3
  18. package/dist/{coordinator-VVJ33WF2.js.map → coordinator-PEWHNZ7I.js.map} +1 -1
  19. package/dist/events.js +3 -3
  20. package/dist/index.d.ts +69 -353
  21. package/dist/index.js +161 -43
  22. package/dist/index.js.map +1 -1
  23. package/dist/lp.d.ts +76 -18
  24. package/dist/lp.js +511 -111
  25. package/dist/lp.js.map +1 -1
  26. package/dist/presets.d.ts +7 -40
  27. package/dist/presets.js +10 -68
  28. package/dist/presets.js.map +1 -1
  29. package/dist/stats.js +1 -1
  30. package/dist/storage.js +2 -243
  31. package/dist/storage.js.map +1 -1
  32. package/dist/{errors-N2touVm4.d.ts → types.generated-YhFu9ZBR.d.ts} +65 -4
  33. package/dist/user.d.ts +134 -8
  34. package/dist/user.js +991 -250
  35. package/dist/user.js.map +1 -1
  36. package/package.json +5 -31
  37. package/dist/chunk-BWCGNTN5.js +0 -1153
  38. package/dist/chunk-BWCGNTN5.js.map +0 -1
  39. package/dist/chunk-DIA6U2CV.js +0 -1927
  40. package/dist/chunk-DIA6U2CV.js.map +0 -1
  41. package/dist/chunk-GHBQF3A7.js.map +0 -1
  42. package/dist/chunk-NKRVQXRP.js.map +0 -1
  43. package/dist/chunk-QQSI3ZD7.js.map +0 -1
  44. package/dist/chunk-V5HXJRBW.js.map +0 -1
  45. package/dist/types.generated-BSEBz4jR.d.ts +0 -68
@@ -0,0 +1,258 @@
1
+ import { StorageError } from './chunk-QRN46R3F.js';
2
+
3
+ // src/storage/coordination.ts
4
+ var storageBackings = /* @__PURE__ */ new WeakMap();
5
+ function registerStorageBacking(adapter, backing) {
6
+ storageBackings.set(adapter, backing);
7
+ }
8
+ function getStorageBacking(adapter) {
9
+ return storageBackings.get(adapter) ?? adapter;
10
+ }
11
+
12
+ // src/storage/index.ts
13
+ var STORAGE_KEY_PREFIX = "invisible:sdk:storage:v1:";
14
+ var STORAGE_KEY_SEPARATOR = ":";
15
+ var BASE64URL_PAD = "=";
16
+ var BASE64URL_PLUS = "+";
17
+ var BASE64URL_SLASH = "/";
18
+ var BASE64URL_MINUS = "-";
19
+ var BASE64URL_UNDERSCORE = "_";
20
+ var BYTE_STRING_CHUNK_SIZE = 32768;
21
+ var EXTENSION_TRUSTED_CONTEXTS_ACCESS_LEVEL = "TRUSTED_CONTEXTS";
22
+ function inMemoryStorage() {
23
+ const namespaces = /* @__PURE__ */ new Map();
24
+ const bucket = (namespace) => {
25
+ let inner = namespaces.get(namespace);
26
+ if (!inner) {
27
+ inner = /* @__PURE__ */ new Map();
28
+ namespaces.set(namespace, inner);
29
+ }
30
+ return inner;
31
+ };
32
+ return {
33
+ kind: "memory",
34
+ async put(namespace, key, value) {
35
+ bucket(namespace).set(key, value);
36
+ },
37
+ async get(namespace, key) {
38
+ return namespaces.get(namespace)?.get(key) ?? null;
39
+ },
40
+ async list(namespace) {
41
+ return [...namespaces.get(namespace)?.keys() ?? []];
42
+ },
43
+ async remove(namespace, key) {
44
+ namespaces.get(namespace)?.delete(key);
45
+ }
46
+ };
47
+ }
48
+ function browserStorage(options = {}) {
49
+ const storage = options.storage ?? defaultBrowserStorage();
50
+ if (!storage) throw new StorageError("STORAGE_NOT_AVAILABLE", "localStorage is unavailable");
51
+ const adapter = {
52
+ kind: "browser",
53
+ async put(namespace, key, value) {
54
+ try {
55
+ storage.setItem(storageKey(namespace, key), bytesToBase64Url(value));
56
+ } catch (cause) {
57
+ throw browserOperationError(cause);
58
+ }
59
+ },
60
+ async get(namespace, key) {
61
+ try {
62
+ const value = storage.getItem(storageKey(namespace, key));
63
+ return value === null ? null : base64UrlToBytes(value);
64
+ } catch (cause) {
65
+ throw browserOperationError(cause);
66
+ }
67
+ },
68
+ async list(namespace) {
69
+ try {
70
+ const prefix = storageKeyPrefix(namespace);
71
+ const keys = [];
72
+ for (let index = 0; index < storage.length; index += 1) {
73
+ const storedKey = storage.key(index);
74
+ if (storedKey?.startsWith(prefix)) {
75
+ keys.push(decodeStorageSegment(storedKey.slice(prefix.length)));
76
+ }
77
+ }
78
+ return keys;
79
+ } catch (cause) {
80
+ throw browserOperationError(cause);
81
+ }
82
+ },
83
+ async remove(namespace, key) {
84
+ try {
85
+ storage.removeItem(storageKey(namespace, key));
86
+ } catch (cause) {
87
+ throw browserOperationError(cause);
88
+ }
89
+ }
90
+ };
91
+ registerStorageBacking(adapter, storage);
92
+ return adapter;
93
+ }
94
+ function extensionStorage(options = {}) {
95
+ const storage = options.storage ?? defaultExtensionStorage();
96
+ if (!storage) {
97
+ throw new StorageError("STORAGE_NOT_AVAILABLE", "extension local storage is unavailable");
98
+ }
99
+ const runtime = options.runtime ?? defaultExtensionRuntime();
100
+ const trustedAccess = options.restrictAccessToTrustedContexts === false ? Promise.resolve() : extensionSetAccessLevel(storage, runtime);
101
+ const adapter = {
102
+ kind: "extension",
103
+ async put(namespace, key, value) {
104
+ await trustedAccess;
105
+ await extensionSet(storage, runtime, {
106
+ [storageKey(namespace, key)]: bytesToBase64Url(value)
107
+ });
108
+ },
109
+ async get(namespace, key) {
110
+ await trustedAccess;
111
+ const storedKey = storageKey(namespace, key);
112
+ const values = await extensionGet(storage, runtime, storedKey);
113
+ const value = values[storedKey];
114
+ return typeof value === "string" ? base64UrlToBytes(value) : null;
115
+ },
116
+ async list(namespace) {
117
+ await trustedAccess;
118
+ const prefix = storageKeyPrefix(namespace);
119
+ const values = await extensionGet(storage, runtime, null);
120
+ return Object.keys(values).filter((key) => key.startsWith(prefix)).map((key) => decodeStorageSegment(key.slice(prefix.length)));
121
+ },
122
+ async remove(namespace, key) {
123
+ await trustedAccess;
124
+ await extensionRemove(storage, runtime, storageKey(namespace, key));
125
+ }
126
+ };
127
+ registerStorageBacking(adapter, storage);
128
+ return adapter;
129
+ }
130
+ function storageKey(namespace, key) {
131
+ return `${storageKeyPrefix(namespace)}${encodeStorageSegment(key)}`;
132
+ }
133
+ function storageKeyPrefix(namespace) {
134
+ return `${STORAGE_KEY_PREFIX}${encodeStorageSegment(namespace)}${STORAGE_KEY_SEPARATOR}`;
135
+ }
136
+ function encodeStorageSegment(value) {
137
+ return encodeURIComponent(value);
138
+ }
139
+ function decodeStorageSegment(value) {
140
+ return decodeURIComponent(value);
141
+ }
142
+ function bytesToBase64Url(value) {
143
+ let binary = "";
144
+ for (let index = 0; index < value.length; index += BYTE_STRING_CHUNK_SIZE) {
145
+ binary += String.fromCharCode(...value.slice(index, index + BYTE_STRING_CHUNK_SIZE));
146
+ }
147
+ return btoa(binary).split(BASE64URL_PLUS).join(BASE64URL_MINUS).split(BASE64URL_SLASH).join(BASE64URL_UNDERSCORE).split(BASE64URL_PAD).join("");
148
+ }
149
+ function base64UrlToBytes(value) {
150
+ try {
151
+ const base64 = value.split(BASE64URL_MINUS).join(BASE64URL_PLUS).split(BASE64URL_UNDERSCORE).join(BASE64URL_SLASH).padEnd(Math.ceil(value.length / 4) * 4, BASE64URL_PAD);
152
+ return Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
153
+ } catch (cause) {
154
+ throw new StorageError("STORAGE_DECRYPT_FAILED", "stored value is not valid base64url", {
155
+ cause
156
+ });
157
+ }
158
+ }
159
+ function defaultBrowserStorage() {
160
+ try {
161
+ return globalThis.localStorage;
162
+ } catch (cause) {
163
+ throw new StorageError("STORAGE_NOT_AVAILABLE", "localStorage is unavailable", { cause });
164
+ }
165
+ }
166
+ function browserOperationError(cause) {
167
+ if (cause instanceof StorageError) return cause;
168
+ return new StorageError(
169
+ "STORAGE_NOT_AVAILABLE",
170
+ storageErrorMessage(cause) ?? "localStorage operation failed",
171
+ { cause }
172
+ );
173
+ }
174
+ function defaultExtensionStorage() {
175
+ const global = globalThis;
176
+ return global.chrome?.storage?.local ?? global.browser?.storage?.local;
177
+ }
178
+ function defaultExtensionRuntime() {
179
+ const global = globalThis;
180
+ return global.chrome?.runtime ?? global.browser?.runtime;
181
+ }
182
+ function extensionGet(storage, runtime, keys) {
183
+ return new Promise((resolve, reject) => {
184
+ const maybePromise = storage.get(keys, (items) => {
185
+ const error = extensionLastError(runtime);
186
+ if (error) reject(extensionOperationError(error));
187
+ else resolve(items);
188
+ });
189
+ if (isPromise(maybePromise)) {
190
+ maybePromise.then(resolve, (cause) => reject(extensionOperationError(cause)));
191
+ }
192
+ });
193
+ }
194
+ function extensionSet(storage, runtime, items) {
195
+ return new Promise((resolve, reject) => {
196
+ const maybePromise = storage.set(items, () => {
197
+ const error = extensionLastError(runtime);
198
+ if (error) reject(extensionOperationError(error));
199
+ else resolve();
200
+ });
201
+ if (isPromise(maybePromise))
202
+ maybePromise.then(resolve, (cause) => reject(extensionOperationError(cause)));
203
+ });
204
+ }
205
+ function extensionRemove(storage, runtime, key) {
206
+ return new Promise((resolve, reject) => {
207
+ const maybePromise = storage.remove(key, () => {
208
+ const error = extensionLastError(runtime);
209
+ if (error) reject(extensionOperationError(error));
210
+ else resolve();
211
+ });
212
+ if (isPromise(maybePromise))
213
+ maybePromise.then(resolve, (cause) => reject(extensionOperationError(cause)));
214
+ });
215
+ }
216
+ function extensionSetAccessLevel(storage, runtime) {
217
+ const setAccessLevel = storage.setAccessLevel;
218
+ if (!setAccessLevel) return Promise.resolve();
219
+ return new Promise((resolve, reject) => {
220
+ const maybePromise = setAccessLevel.call(
221
+ storage,
222
+ { accessLevel: EXTENSION_TRUSTED_CONTEXTS_ACCESS_LEVEL },
223
+ () => {
224
+ const error = extensionLastError(runtime);
225
+ if (error) reject(extensionOperationError(error));
226
+ else resolve();
227
+ }
228
+ );
229
+ if (isPromise(maybePromise))
230
+ maybePromise.then(resolve, (cause) => reject(extensionOperationError(cause)));
231
+ });
232
+ }
233
+ function extensionLastError(runtime) {
234
+ return runtime?.lastError ?? null;
235
+ }
236
+ function extensionOperationError(error) {
237
+ if (error instanceof StorageError) return error;
238
+ return new StorageError(
239
+ "STORAGE_NOT_AVAILABLE",
240
+ storageErrorMessage(error) ?? "extension storage operation failed",
241
+ { cause: error }
242
+ );
243
+ }
244
+ function storageErrorMessage(error) {
245
+ if (error instanceof Error) return error.message;
246
+ if (typeof error === "object" && error !== null && "message" in error) {
247
+ const message = error.message;
248
+ if (typeof message === "string") return message;
249
+ }
250
+ return void 0;
251
+ }
252
+ function isPromise(value) {
253
+ return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
254
+ }
255
+
256
+ export { browserStorage, extensionStorage, getStorageBacking, inMemoryStorage };
257
+ //# sourceMappingURL=chunk-DCTYBUY3.js.map
258
+ //# sourceMappingURL=chunk-DCTYBUY3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/storage/coordination.ts","../src/storage/index.ts"],"names":[],"mappings":";;;AAAA,IAAM,eAAA,uBAAsB,OAAA,EA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AAa,IAAA;AAC/B;AAEA,SAAS,wBAAwB,KAAA,EAA8B;AAC7D,EAAA,IAAI,KAAA,YAAiB,cAAc,OAAO,KAAA;AAC1C,EAAA,OAAO,IAAI,YAAA;AAAA,IACT,uBAAA;AAAA,IACA,mBAAA,CAAoB,KAAK,CAAA,IAAK,oCAAA;AAAA,IAC9B,EAAE,OAAO,KAAA;AAAM,GACjB;AACF;AAEA,SAAS,oBAAoB,KAAA,EAAoC;AAC/D,EAAA,IAAI,KAAA,YAAiB,KAAA,EAAO,OAAO,KAAA,CAAM,OAAA;AACzC,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,aAAa,KAAA,EAAO;AACrE,IAAA,MAAM,UAAW,KAAA,CAAgC,OAAA;AACjD,IAAA,IAAI,OAAO,OAAA,KAAY,QAAA,EAAU,OAAO,OAAA;AAAA,EAC1C;AACA,EAAA,OAAO,MAAA;AACT;AAEA,SAAS,UAAa,KAAA,EAAqC;AACzD,EAAA,OACE,OAAO,UAAU,QAAA,IACjB,KAAA,KAAU,QACV,MAAA,IAAU,KAAA,IACV,OAAQ,KAAA,CAA4B,IAAA,KAAS,UAAA;AAEjD","file":"chunk-DCTYBUY3.js","sourcesContent":["const storageBackings = new WeakMap<object, object>();\n\nexport function registerStorageBacking(adapter: object, backing: object): void {\n storageBackings.set(adapter, backing);\n}\n\nexport function getStorageBacking(adapter: object): object {\n return storageBackings.get(adapter) ?? adapter;\n}\n","/**\n * `@invisible-labs/sdk/storage` - storage adapters (spec section 7).\n *\n * The SDK persists recoverable secrets (Recovery Code, LP Position Code, LP\n * Refill Key, withdrawal secret) only through a {@link StorageAdapter}. The\n * `memory`, `browser`, and `extension` adapters are real. Browser and\n * extension adapters persist the bytes provided by the caller; callers that need\n * encrypted-at-rest storage can wrap/encrypt bytes before calling `put`.\n */\n\nimport { StorageError } from \"../core/errors.js\";\nimport { registerStorageBacking } from \"./coordination.js\";\n\nconst STORAGE_KEY_PREFIX = \"invisible:sdk:storage:v1:\";\nconst STORAGE_KEY_SEPARATOR = \":\";\nconst BASE64URL_PAD = \"=\";\nconst BASE64URL_PLUS = \"+\";\nconst BASE64URL_SLASH = \"/\";\nconst BASE64URL_MINUS = \"-\";\nconst BASE64URL_UNDERSCORE = \"_\";\nconst BYTE_STRING_CHUNK_SIZE = 0x8000;\nconst EXTENSION_TRUSTED_CONTEXTS_ACCESS_LEVEL = \"TRUSTED_CONTEXTS\";\n\n/**\n * A namespaced key/value store for the SDK's recoverable secrets. Values are\n * raw bytes. Callers may store plaintext bytes, pre-wrapped bytes, or encrypted\n * bytes depending on their host product's storage model.\n */\nexport interface StorageAdapter {\n /** Which backing the adapter uses. */\n readonly kind: \"browser\" | \"extension\" | \"server-hkdf\" | \"server-custom\" | \"memory\";\n put(namespace: string, key: string, value: Uint8Array): Promise<void>;\n get(namespace: string, key: string): Promise<Uint8Array | null>;\n list(namespace: string): Promise<string[]>;\n remove(namespace: string, key: string): Promise<void>;\n /** `server-hkdf` only: derive a secret from a stable domain context. */\n derive?(namespace: string, context: string): Promise<Uint8Array>;\n}\n\nexport interface BrowserStorageOptions {\n /** Override for tests or custom host environments. Defaults to `globalThis.localStorage`. */\n readonly storage?: StorageLike;\n}\n\nexport interface ExtensionStorageOptions {\n /** Override for tests or custom extension hosts. Defaults to chrome/browser storage local. */\n readonly storage?: ExtensionStorageArea;\n /** Override for tests or custom extension hosts. Defaults to chrome/browser runtime. */\n readonly runtime?: ExtensionRuntimeLike;\n /**\n * Chrome exposes storage.local to content scripts by default. Keep the default\n * trusted-context restriction when the host API supports it.\n */\n readonly restrictAccessToTrustedContexts?: boolean;\n}\n\ninterface StorageLike {\n readonly length: number;\n key(index: number): string | null;\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\ninterface ExtensionStorageArea {\n get(\n keys?: string | string[] | Record<string, unknown> | null,\n callback?: (items: Record<string, unknown>) => void,\n ): Promise<Record<string, unknown>> | void;\n set(items: Record<string, string>, callback?: () => void): Promise<void> | void;\n remove(keys: string | string[], callback?: () => void): Promise<void> | void;\n setAccessLevel?(details: { accessLevel: string }, callback?: () => void): Promise<void> | void;\n}\n\ninterface ExtensionRuntimeLike {\n readonly lastError?: { readonly message?: string } | null;\n}\n\n/**\n * In-memory adapter. Fully functional, unencrypted, non-persistent - intended\n * for tests and ephemeral flows, never for real secrets at rest.\n */\nexport function inMemoryStorage(): StorageAdapter {\n // Each namespace is a separate inner map rather than a flattened composite\n // key, so a namespace or key containing any character (including a separator)\n // can never collide across namespaces.\n const namespaces = new Map<string, Map<string, Uint8Array>>();\n const bucket = (namespace: string) => {\n let inner = namespaces.get(namespace);\n if (!inner) {\n inner = new Map<string, Uint8Array>();\n namespaces.set(namespace, inner);\n }\n return inner;\n };\n return {\n kind: \"memory\",\n async put(namespace, key, value) {\n bucket(namespace).set(key, value);\n },\n async get(namespace, key) {\n return namespaces.get(namespace)?.get(key) ?? null;\n },\n async list(namespace) {\n return [...(namespaces.get(namespace)?.keys() ?? [])];\n },\n async remove(namespace, key) {\n namespaces.get(namespace)?.delete(key);\n },\n };\n}\n\n/**\n * Browser `localStorage` adapter. Values are stored as base64url-encoded bytes.\n * Encrypt or wrap the bytes before `put` if your product requires encrypted\n * local persistence.\n *\n * @throws StorageError `STORAGE_NOT_AVAILABLE` if `localStorage` is unavailable.\n */\nexport function browserStorage(options: BrowserStorageOptions = {}): StorageAdapter {\n const storage = options.storage ?? defaultBrowserStorage();\n if (!storage) throw new StorageError(\"STORAGE_NOT_AVAILABLE\", \"localStorage is unavailable\");\n const adapter: StorageAdapter = {\n kind: \"browser\",\n async put(namespace, key, value) {\n try {\n storage.setItem(storageKey(namespace, key), bytesToBase64Url(value));\n } catch (cause) {\n throw browserOperationError(cause);\n }\n },\n async get(namespace, key) {\n try {\n const value = storage.getItem(storageKey(namespace, key));\n return value === null ? null : base64UrlToBytes(value);\n } catch (cause) {\n throw browserOperationError(cause);\n }\n },\n async list(namespace) {\n try {\n const prefix = storageKeyPrefix(namespace);\n const keys: string[] = [];\n for (let index = 0; index < storage.length; index += 1) {\n const storedKey = storage.key(index);\n if (storedKey?.startsWith(prefix)) {\n keys.push(decodeStorageSegment(storedKey.slice(prefix.length)));\n }\n }\n return keys;\n } catch (cause) {\n throw browserOperationError(cause);\n }\n },\n async remove(namespace, key) {\n try {\n storage.removeItem(storageKey(namespace, key));\n } catch (cause) {\n throw browserOperationError(cause);\n }\n },\n };\n registerStorageBacking(adapter, storage);\n return adapter;\n}\n\n/**\n * Browser-extension (`chrome.storage.local` / `browser.storage.local`) adapter.\n * Values are stored as base64url-encoded bytes. Encrypt or wrap the bytes before\n * `put` if your product requires encrypted local persistence.\n *\n * @throws StorageError `STORAGE_NOT_AVAILABLE` if extension storage is unavailable.\n */\nexport function extensionStorage(options: ExtensionStorageOptions = {}): StorageAdapter {\n const storage = options.storage ?? defaultExtensionStorage();\n if (!storage) {\n throw new StorageError(\"STORAGE_NOT_AVAILABLE\", \"extension local storage is unavailable\");\n }\n const runtime = options.runtime ?? defaultExtensionRuntime();\n const trustedAccess =\n options.restrictAccessToTrustedContexts === false\n ? Promise.resolve()\n : extensionSetAccessLevel(storage, runtime);\n const adapter: StorageAdapter = {\n kind: \"extension\",\n async put(namespace, key, value) {\n await trustedAccess;\n await extensionSet(storage, runtime, {\n [storageKey(namespace, key)]: bytesToBase64Url(value),\n });\n },\n async get(namespace, key) {\n await trustedAccess;\n const storedKey = storageKey(namespace, key);\n const values = await extensionGet(storage, runtime, storedKey);\n const value = values[storedKey];\n return typeof value === \"string\" ? base64UrlToBytes(value) : null;\n },\n async list(namespace) {\n await trustedAccess;\n const prefix = storageKeyPrefix(namespace);\n const values = await extensionGet(storage, runtime, null);\n return Object.keys(values)\n .filter((key) => key.startsWith(prefix))\n .map((key) => decodeStorageSegment(key.slice(prefix.length)));\n },\n async remove(namespace, key) {\n await trustedAccess;\n await extensionRemove(storage, runtime, storageKey(namespace, key));\n },\n };\n registerStorageBacking(adapter, storage);\n return adapter;\n}\n\nfunction storageKey(namespace: string, key: string): string {\n return `${storageKeyPrefix(namespace)}${encodeStorageSegment(key)}`;\n}\n\nfunction storageKeyPrefix(namespace: string): string {\n return `${STORAGE_KEY_PREFIX}${encodeStorageSegment(namespace)}${STORAGE_KEY_SEPARATOR}`;\n}\n\nfunction encodeStorageSegment(value: string): string {\n return encodeURIComponent(value);\n}\n\nfunction decodeStorageSegment(value: string): string {\n return decodeURIComponent(value);\n}\n\nfunction bytesToBase64Url(value: Uint8Array): string {\n let binary = \"\";\n for (let index = 0; index < value.length; index += BYTE_STRING_CHUNK_SIZE) {\n binary += String.fromCharCode(...value.slice(index, index + BYTE_STRING_CHUNK_SIZE));\n }\n return btoa(binary)\n .split(BASE64URL_PLUS)\n .join(BASE64URL_MINUS)\n .split(BASE64URL_SLASH)\n .join(BASE64URL_UNDERSCORE)\n .split(BASE64URL_PAD)\n .join(\"\");\n}\n\nfunction base64UrlToBytes(value: string): Uint8Array {\n try {\n const base64 = value\n .split(BASE64URL_MINUS)\n .join(BASE64URL_PLUS)\n .split(BASE64URL_UNDERSCORE)\n .join(BASE64URL_SLASH)\n .padEnd(Math.ceil(value.length / 4) * 4, BASE64URL_PAD);\n return Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));\n } catch (cause) {\n throw new StorageError(\"STORAGE_DECRYPT_FAILED\", \"stored value is not valid base64url\", {\n cause,\n });\n }\n}\n\nfunction defaultBrowserStorage(): StorageLike | undefined {\n try {\n return globalThis.localStorage;\n } catch (cause) {\n throw new StorageError(\"STORAGE_NOT_AVAILABLE\", \"localStorage is unavailable\", { cause });\n }\n}\n\nfunction browserOperationError(cause: unknown): StorageError {\n if (cause instanceof StorageError) return cause;\n return new StorageError(\n \"STORAGE_NOT_AVAILABLE\",\n storageErrorMessage(cause) ?? \"localStorage operation failed\",\n { cause },\n );\n}\n\nfunction defaultExtensionStorage(): ExtensionStorageArea | undefined {\n const global = globalThis as {\n chrome?: { storage?: { local?: ExtensionStorageArea } };\n browser?: { storage?: { local?: ExtensionStorageArea } };\n };\n return global.chrome?.storage?.local ?? global.browser?.storage?.local;\n}\n\nfunction defaultExtensionRuntime(): ExtensionRuntimeLike | undefined {\n const global = globalThis as {\n chrome?: { runtime?: ExtensionRuntimeLike };\n browser?: { runtime?: ExtensionRuntimeLike };\n };\n return global.chrome?.runtime ?? global.browser?.runtime;\n}\n\nfunction extensionGet(\n storage: ExtensionStorageArea,\n runtime: ExtensionRuntimeLike | undefined,\n keys: string | string[] | Record<string, unknown> | null,\n): Promise<Record<string, unknown>> {\n return new Promise((resolve, reject) => {\n const maybePromise = storage.get(keys, (items) => {\n const error = extensionLastError(runtime);\n if (error) reject(extensionOperationError(error));\n else resolve(items);\n });\n if (isPromise<Record<string, unknown>>(maybePromise)) {\n maybePromise.then(resolve, (cause) => reject(extensionOperationError(cause)));\n }\n });\n}\n\nfunction extensionSet(\n storage: ExtensionStorageArea,\n runtime: ExtensionRuntimeLike | undefined,\n items: Record<string, string>,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n const maybePromise = storage.set(items, () => {\n const error = extensionLastError(runtime);\n if (error) reject(extensionOperationError(error));\n else resolve();\n });\n if (isPromise<void>(maybePromise))\n maybePromise.then(resolve, (cause) => reject(extensionOperationError(cause)));\n });\n}\n\nfunction extensionRemove(\n storage: ExtensionStorageArea,\n runtime: ExtensionRuntimeLike | undefined,\n key: string,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n const maybePromise = storage.remove(key, () => {\n const error = extensionLastError(runtime);\n if (error) reject(extensionOperationError(error));\n else resolve();\n });\n if (isPromise<void>(maybePromise))\n maybePromise.then(resolve, (cause) => reject(extensionOperationError(cause)));\n });\n}\n\nfunction extensionSetAccessLevel(\n storage: ExtensionStorageArea,\n runtime: ExtensionRuntimeLike | undefined,\n): Promise<void> {\n const setAccessLevel = storage.setAccessLevel;\n if (!setAccessLevel) return Promise.resolve();\n return new Promise((resolve, reject) => {\n const maybePromise = setAccessLevel.call(\n storage,\n { accessLevel: EXTENSION_TRUSTED_CONTEXTS_ACCESS_LEVEL },\n () => {\n const error = extensionLastError(runtime);\n if (error) reject(extensionOperationError(error));\n else resolve();\n },\n );\n if (isPromise<void>(maybePromise))\n maybePromise.then(resolve, (cause) => reject(extensionOperationError(cause)));\n });\n}\n\nfunction extensionLastError(\n runtime: ExtensionRuntimeLike | undefined,\n): { readonly message?: string } | null {\n return runtime?.lastError ?? null;\n}\n\nfunction extensionOperationError(error: unknown): StorageError {\n if (error instanceof StorageError) return error;\n return new StorageError(\n \"STORAGE_NOT_AVAILABLE\",\n storageErrorMessage(error) ?? \"extension storage operation failed\",\n { cause: error },\n );\n}\n\nfunction storageErrorMessage(error: unknown): string | undefined {\n if (error instanceof Error) return error.message;\n if (typeof error === \"object\" && error !== null && \"message\" in error) {\n const message = (error as { message?: unknown }).message;\n if (typeof message === \"string\") return message;\n }\n return undefined;\n}\n\nfunction isPromise<T>(value: unknown): value is Promise<T> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"then\" in value &&\n typeof (value as { then: unknown }).then === \"function\"\n );\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { PolicyValidationError, AttestationError } from './chunk-GHBQF3A7.js';
1
+ import { PolicyValidationError, AttestationError } from './chunk-QRN46R3F.js';
2
2
 
3
3
  // src/core/solanaAddress.ts
4
4
  var SOLANA_PUBLIC_KEY_BYTE_LENGTH = 32;
@@ -119,5 +119,5 @@ function assertAttested(session) {
119
119
  }
120
120
 
121
121
  export { assertAttested, hex, lamports, publicKey, requestId, solanaAddressFromPublicKeyBytes };
122
- //# sourceMappingURL=chunk-NHEHCUS5.js.map
123
- //# sourceMappingURL=chunk-NHEHCUS5.js.map
122
+ //# sourceMappingURL=chunk-EBWTAXNT.js.map
123
+ //# sourceMappingURL=chunk-EBWTAXNT.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/solanaAddress.ts","../src/core/brands.ts","../src/session/guards.ts"],"names":[],"mappings":";;;AAEA,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D,EAAA,IAAI,CAAC,QAAQ,QAAA,EAAU;AACrB,IAAA,MAAM,IAAI,gBAAA;AAAA,MACR,cAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF","file":"chunk-NHEHCUS5.js","sourcesContent":["import { PolicyValidationError } from \"./errors.js\";\n\nconst SOLANA_PUBLIC_KEY_BYTE_LENGTH = 32;\nconst SOLANA_ADDRESS_MIN_LENGTH = 32;\nconst SOLANA_ADDRESS_MAX_LENGTH = 44;\nconst BASE58_ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\nconst BASE58_RADIX = BigInt(BASE58_ALPHABET.length);\nconst BASE58_LEADING_ZERO_CHAR = \"1\";\nconst BYTE_MASK = 0xffn;\nconst BYTE_RADIX_BITS = 8n;\nconst MAX_SOLANA_PUBLIC_KEY_VALUE = (1n << (BigInt(SOLANA_PUBLIC_KEY_BYTE_LENGTH) * 8n)) - 1n;\n\nconst BASE58_DIGITS = new Map<string, number>(\n Array.from(BASE58_ALPHABET, (character, index) => [character, index]),\n);\n\nexport function assertCanonicalSolanaAddress(value: unknown): asserts value is string {\n if (typeof value !== \"string\") {\n throw new PolicyValidationError(\n \"INVALID_DESTINATION_ADDRESS\",\n `destination address must be a string, received ${typeof value}`,\n );\n }\n if (\n value.trim() !== value ||\n value.length < SOLANA_ADDRESS_MIN_LENGTH ||\n value.length > SOLANA_ADDRESS_MAX_LENGTH\n ) {\n throwInvalidDestinationAddress(value);\n }\n\n const decoded = decodeBase58SolanaAddress(value);\n if (encodeBase58(decoded) !== value) {\n throwInvalidDestinationAddress(value);\n }\n}\n\n/** Encode a 32-byte Ed25519 public key as its canonical Solana address. */\nexport function solanaAddressFromPublicKeyBytes(bytes: Uint8Array): string {\n if (bytes.byteLength !== SOLANA_PUBLIC_KEY_BYTE_LENGTH) {\n throw new PolicyValidationError(\n \"INVALID_DESTINATION_ADDRESS\",\n `Solana public key must be ${SOLANA_PUBLIC_KEY_BYTE_LENGTH} bytes, received ${bytes.byteLength}`,\n );\n }\n return encodeBase58(bytes);\n}\n\nfunction decodeBase58SolanaAddress(value: string): Uint8Array {\n let decoded = 0n;\n for (const character of value) {\n const digit = BASE58_DIGITS.get(character);\n if (digit === undefined) {\n throwInvalidDestinationAddress(value);\n }\n decoded = decoded * BASE58_RADIX + BigInt(digit);\n if (decoded > MAX_SOLANA_PUBLIC_KEY_VALUE) {\n throwInvalidDestinationAddress(value);\n }\n }\n\n const bytes = new Uint8Array(SOLANA_PUBLIC_KEY_BYTE_LENGTH);\n for (let index = SOLANA_PUBLIC_KEY_BYTE_LENGTH - 1; index >= 0; index -= 1) {\n bytes[index] = Number(decoded & BYTE_MASK);\n decoded >>= BYTE_RADIX_BITS;\n }\n return bytes;\n}\n\nfunction encodeBase58(bytes: Uint8Array): string {\n let leadingZeros = 0;\n for (const byte of bytes) {\n if (byte !== 0) break;\n leadingZeros += 1;\n }\n\n let value = 0n;\n for (const byte of bytes) {\n value = (value << BYTE_RADIX_BITS) + BigInt(byte);\n }\n\n let encoded = \"\";\n while (value > 0n) {\n const digit = Number(value % BASE58_RADIX);\n encoded = BASE58_ALPHABET[digit]! + encoded;\n value /= BASE58_RADIX;\n }\n\n return BASE58_LEADING_ZERO_CHAR.repeat(leadingZeros) + encoded;\n}\n\nfunction throwInvalidDestinationAddress(value: string): never {\n throw new PolicyValidationError(\n \"INVALID_DESTINATION_ADDRESS\",\n `destination address must be a canonical 32-byte Solana address: ${value}`,\n );\n}\n","/**\n * Branded scalar types.\n *\n * Branding makes structurally-identical primitives (a lamport amount, a base58\n * address, a correlation id) non-interchangeable at the type level, so the\n * compiler catches \"passed a request id where an address was expected\" before\n * it reaches the wire. The brand exists only at compile time; at runtime these\n * are plain `number` / `string`.\n *\n * Construct branded values through the smart constructors here. These\n * constructors enforce scalar-level invariants; payout-policy semantics stay in\n * the validation module.\n */\n\nimport { PolicyValidationError } from \"./errors.js\";\nimport { assertCanonicalSolanaAddress } from \"./solanaAddress.js\";\n\n/** Attach a compile-time-only brand `B` to base type `T`. */\nexport type Brand<T, B extends string> = T & { readonly __brand: B };\n\n/** A non-negative integer amount of lamports (1 SOL = 1_000_000_000 lamports). */\nexport type Lamports = Brand<number, \"Lamports\">;\n\n/** A Solana account address as base58 text. */\nexport type PublicKey = Brand<string, \"PublicKey\">;\n\n/** A client-generated correlation id for one logical command. */\nexport type RequestId = Brand<string, \"RequestId\">;\n\n/** Lowercase hexadecimal text (no `0x` prefix). */\nexport type Hex = Brand<string, \"Hex\">;\n\n/**\n * Brand a number as {@link Lamports}.\n *\n * @throws PolicyValidationError `INVALID_AMOUNT` if not a non-negative safe integer.\n */\nexport function lamports(value: number): Lamports {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new PolicyValidationError(\n \"INVALID_AMOUNT\",\n `lamports must be a non-negative safe integer, received ${String(value)}`,\n );\n }\n return value as Lamports;\n}\n\n/**\n * Brand a string as a {@link PublicKey}.\n *\n * Enforces canonical base58 encoding of a 32-byte Solana public key.\n *\n * @throws PolicyValidationError `INVALID_DESTINATION_ADDRESS` if obviously malformed.\n */\nexport function publicKey(value: string): PublicKey {\n assertCanonicalSolanaAddress(value);\n return value as PublicKey;\n}\n\n/**\n * Brand a non-empty string as a {@link RequestId}.\n *\n * @throws PolicyValidationError `INVALID_AMOUNT` is not appropriate here; an empty\n * id is a programming error, so this throws a plain `Error`.\n */\nexport function requestId(value: string): RequestId {\n if (value.length === 0) {\n throw new Error(\"requestId must be a non-empty string\");\n }\n return value as RequestId;\n}\n\n/**\n * Brand a string as lowercase {@link Hex}.\n *\n * @throws Error if the string contains non-hex characters.\n */\nexport function hex(value: string): Hex {\n if (!/^[0-9a-f]*$/.test(value)) {\n throw new Error(`not lowercase hex: ${value}`);\n }\n return value as Hex;\n}\n","/**\n * Session guards used by mutating commands.\n */\n\nimport { AttestationError } from \"../core/errors.js\";\nimport type { Session } from \"../core/session.js\";\n\n/**\n * Assert the session has passed attestation. Every mutating actor command calls\n * this before touching the wire, so an unattested session can never sign or\n * send sensitive material.\n *\n * @throws AttestationError `NOT_ATTESTED` when the session is not attested.\n */\nexport function assertAttested(session: Session): void {\n if (!session.attested) {\n throw new AttestationError(\n \"NOT_ATTESTED\",\n \"session is not attested; sensitive commands are blocked until attestation completes\",\n );\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/core/solanaAddress.ts","../src/core/brands.ts","../src/session/guards.ts"],"names":[],"mappings":";;;AAEA,IAAM,6BAAA,GAAgC,EAAA;AACtC,IAAM,yBAAA,GAA4B,EAAA;AAClC,IAAM,yBAAA,GAA4B,EAAA;AAClC,IAAM,eAAA,GAAkB,4DAAA;AACxB,IAAM,YAAA,GAAe,MAAA,CAAO,eAAA,CAAgB,MAAM,CAAA;AAClD,IAAM,wBAAA,GAA2B,GAAA;AACjC,IAAM,SAAA,GAAY,KAAA;AAClB,IAAM,eAAA,GAAkB,EAAA;AACxB,IAAM,2BAAA,GAAA,CAA+B,EAAA,IAAO,MAAA,CAAO,6BAA6B,IAAI,EAAA,IAAO,EAAA;AAE3F,IAAM,gBAAgB,IAAI,GAAA;AAAA,EACxB,KAAA,CAAM,KAAK,eAAA,EAAiB,CAAC,WAAW,KAAA,KAAU,CAAC,SAAA,EAAW,KAAK,CAAC;AACtE,CAAA;AAEO,SAAS,6BAA6B,KAAA,EAAyC;AACpF,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,MAAM,IAAI,qBAAA;AAAA,MACR,6BAAA;AAAA,MACA,CAAA,+CAAA,EAAkD,OAAO,KAAK,CAAA;AAAA,KAChE;AAAA,EACF;AACA,EAAA,IACE,KAAA,CAAM,MAAK,KAAM,KAAA,IACjB,MAAM,MAAA,GAAS,yBAAA,IACf,KAAA,CAAM,MAAA,GAAS,yBAAA,EACf;AACA,IAAA,8BAAA,CAA+B,KAAK,CAAA;AAAA,EACtC;AAEA,EAAA,MAAM,OAAA,GAAU,0BAA0B,KAAK,CAAA;AAC/C,EAAA,IAAI,YAAA,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AA,OAAO,KAAA;AACT;AAOO,SAAS,IAAI,KAAA,EAAoB;AACtC,EAAA,IAAI,CAAC,aAAA,CAAc,IAAA,CAAK,KAAK,CAAA,EAAG;AAC9B,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,mBAAA,EAAsB,KAAK,CAAA,CAAE,CAAA;AAAA,EAC/C;AACA,EAAA,OAAO,KAAA;AACT;;;ACpEO,SAAS,eAAe,OAAA,EAAwB;AACrD,EAAA,IAAI,CAAC,QAAQ,QAAA,EAAU;AACrB,IAAA,MAAM,IAAI,gBAAA;AAAA,MACR,cAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF","file":"chunk-EBWTAXNT.js","sourcesContent":["import { PolicyValidationError } from \"./errors.js\";\n\nconst SOLANA_PUBLIC_KEY_BYTE_LENGTH = 32;\nconst SOLANA_ADDRESS_MIN_LENGTH = 32;\nconst SOLANA_ADDRESS_MAX_LENGTH = 44;\nconst BASE58_ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\nconst BASE58_RADIX = BigInt(BASE58_ALPHABET.length);\nconst BASE58_LEADING_ZERO_CHAR = \"1\";\nconst BYTE_MASK = 0xffn;\nconst BYTE_RADIX_BITS = 8n;\nconst MAX_SOLANA_PUBLIC_KEY_VALUE = (1n << (BigInt(SOLANA_PUBLIC_KEY_BYTE_LENGTH) * 8n)) - 1n;\n\nconst BASE58_DIGITS = new Map<string, number>(\n Array.from(BASE58_ALPHABET, (character, index) => [character, index]),\n);\n\nexport function assertCanonicalSolanaAddress(value: unknown): asserts value is string {\n if (typeof value !== \"string\") {\n throw new PolicyValidationError(\n \"INVALID_DESTINATION_ADDRESS\",\n `destination address must be a string, received ${typeof value}`,\n );\n }\n if (\n value.trim() !== value ||\n value.length < SOLANA_ADDRESS_MIN_LENGTH ||\n value.length > SOLANA_ADDRESS_MAX_LENGTH\n ) {\n throwInvalidDestinationAddress(value);\n }\n\n const decoded = decodeBase58SolanaAddress(value);\n if (encodeBase58(decoded) !== value) {\n throwInvalidDestinationAddress(value);\n }\n}\n\n/** Encode a 32-byte Ed25519 public key as its canonical Solana address. */\nexport function solanaAddressFromPublicKeyBytes(bytes: Uint8Array): string {\n if (bytes.byteLength !== SOLANA_PUBLIC_KEY_BYTE_LENGTH) {\n throw new PolicyValidationError(\n \"INVALID_DESTINATION_ADDRESS\",\n `Solana public key must be ${SOLANA_PUBLIC_KEY_BYTE_LENGTH} bytes, received ${bytes.byteLength}`,\n );\n }\n return encodeBase58(bytes);\n}\n\nfunction decodeBase58SolanaAddress(value: string): Uint8Array {\n let decoded = 0n;\n for (const character of value) {\n const digit = BASE58_DIGITS.get(character);\n if (digit === undefined) {\n throwInvalidDestinationAddress(value);\n }\n decoded = decoded * BASE58_RADIX + BigInt(digit);\n if (decoded > MAX_SOLANA_PUBLIC_KEY_VALUE) {\n throwInvalidDestinationAddress(value);\n }\n }\n\n const bytes = new Uint8Array(SOLANA_PUBLIC_KEY_BYTE_LENGTH);\n for (let index = SOLANA_PUBLIC_KEY_BYTE_LENGTH - 1; index >= 0; index -= 1) {\n bytes[index] = Number(decoded & BYTE_MASK);\n decoded >>= BYTE_RADIX_BITS;\n }\n return bytes;\n}\n\nfunction encodeBase58(bytes: Uint8Array): string {\n let leadingZeros = 0;\n for (const byte of bytes) {\n if (byte !== 0) break;\n leadingZeros += 1;\n }\n\n let value = 0n;\n for (const byte of bytes) {\n value = (value << BYTE_RADIX_BITS) + BigInt(byte);\n }\n\n let encoded = \"\";\n while (value > 0n) {\n const digit = Number(value % BASE58_RADIX);\n encoded = BASE58_ALPHABET[digit]! + encoded;\n value /= BASE58_RADIX;\n }\n\n return BASE58_LEADING_ZERO_CHAR.repeat(leadingZeros) + encoded;\n}\n\nfunction throwInvalidDestinationAddress(value: string): never {\n throw new PolicyValidationError(\n \"INVALID_DESTINATION_ADDRESS\",\n `destination address must be a canonical 32-byte Solana address: ${value}`,\n );\n}\n","/**\n * Branded scalar types.\n *\n * Branding makes structurally-identical primitives (a lamport amount, a base58\n * address, a correlation id) non-interchangeable at the type level, so the\n * compiler catches \"passed a request id where an address was expected\" before\n * it reaches the wire. The brand exists only at compile time; at runtime these\n * are plain `number` / `string`.\n *\n * Construct branded values through the smart constructors here. These\n * constructors enforce scalar-level invariants; payout-policy semantics stay in\n * the validation module.\n */\n\nimport { PolicyValidationError } from \"./errors.js\";\nimport { assertCanonicalSolanaAddress } from \"./solanaAddress.js\";\n\n/** Attach a compile-time-only brand `B` to base type `T`. */\nexport type Brand<T, B extends string> = T & { readonly __brand: B };\n\n/** A non-negative integer amount of lamports (1 SOL = 1_000_000_000 lamports). */\nexport type Lamports = Brand<number, \"Lamports\">;\n\n/** A Solana account address as base58 text. */\nexport type PublicKey = Brand<string, \"PublicKey\">;\n\n/** A client-generated correlation id for one logical command. */\nexport type RequestId = Brand<string, \"RequestId\">;\n\n/** Lowercase hexadecimal text (no `0x` prefix). */\nexport type Hex = Brand<string, \"Hex\">;\n\n/**\n * Brand a number as {@link Lamports}.\n *\n * @throws PolicyValidationError `INVALID_AMOUNT` if not a non-negative safe integer.\n */\nexport function lamports(value: number): Lamports {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new PolicyValidationError(\n \"INVALID_AMOUNT\",\n `lamports must be a non-negative safe integer, received ${String(value)}`,\n );\n }\n return value as Lamports;\n}\n\n/**\n * Brand a string as a {@link PublicKey}.\n *\n * Enforces canonical base58 encoding of a 32-byte Solana public key.\n *\n * @throws PolicyValidationError `INVALID_DESTINATION_ADDRESS` if obviously malformed.\n */\nexport function publicKey(value: string): PublicKey {\n assertCanonicalSolanaAddress(value);\n return value as PublicKey;\n}\n\n/**\n * Brand a non-empty string as a {@link RequestId}.\n *\n * @throws PolicyValidationError `INVALID_AMOUNT` is not appropriate here; an empty\n * id is a programming error, so this throws a plain `Error`.\n */\nexport function requestId(value: string): RequestId {\n if (value.length === 0) {\n throw new Error(\"requestId must be a non-empty string\");\n }\n return value as RequestId;\n}\n\n/**\n * Brand a string as lowercase {@link Hex}.\n *\n * @throws Error if the string contains non-hex characters.\n */\nexport function hex(value: string): Hex {\n if (!/^[0-9a-f]*$/.test(value)) {\n throw new Error(`not lowercase hex: ${value}`);\n }\n return value as Hex;\n}\n","/**\n * Session guards used by mutating commands.\n */\n\nimport { AttestationError } from \"../core/errors.js\";\nimport type { Session } from \"../core/session.js\";\n\n/**\n * Assert the session has passed attestation. Every mutating actor command calls\n * this before touching the wire, so an unattested session can never sign or\n * send sensitive material.\n *\n * @throws AttestationError `NOT_ATTESTED` when the session is not attested.\n */\nexport function assertAttested(session: Session): void {\n if (!session.attested) {\n throw new AttestationError(\n \"NOT_ATTESTED\",\n \"session is not attested; sensitive commands are blocked until attestation completes\",\n );\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { TransportError } from './chunk-GHBQF3A7.js';
1
+ import { TransportError } from './chunk-QRN46R3F.js';
2
2
 
3
3
  // src/session/state.ts
4
4
  var registry = /* @__PURE__ */ new WeakMap();
@@ -46,5 +46,5 @@ function failSessionClosed(state, cause, options = {}) {
46
46
  }
47
47
 
48
48
  export { closeSessionState, createSessionHandle, failSessionClosed, getSessionState };
49
- //# sourceMappingURL=chunk-V5HXJRBW.js.map
50
- //# sourceMappingURL=chunk-V5HXJRBW.js.map
49
+ //# sourceMappingURL=chunk-HJFMDMPY.js.map
50
+ //# sourceMappingURL=chunk-HJFMDMPY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/session/state.ts"],"names":[],"mappings":";;;AAoDA,IAAM,QAAA,uBAAe,OAAA,EAA+B;AAG7C,SAAS,oBAAoB,KAAA,EAA8B;AAChE,EAAA,MAAM,MAAA,GAAS;AAAA,IACb,IAAI,QAAA,GAAW;AACb,MAAA,OAAO,KAAA,CAAM,QAAA;AAAA,IACf;AAAA,GACF;AACA,EAAA,QAAA,CAAS,GAAA,CAAI,QAAQ,KAAK,CAAA;AAC1B,EAAA,OAAO,MAAA;AACT;AAOO,SAAS,gBAAgB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AChB,IAAA,KAAA,MAAW,OAAA,IAAW,KAAA,CAAM,uBAAA,EAAyB,OAAA,CAAQ,KAAK,CAAA;AAAA,EACpE;AACF","file":"chunk-HJFMDMPY.js","sourcesContent":["/**\n * Internal session state and the opaque-handle registry.\n *\n * The public {@link Session} is opaque: consumers only read `session.attested`.\n * The real state (transport, endpoint pool, attestation result) is held here\n * and reached through {@link getSessionState}, keyed off the handle in a\n * `WeakMap` so it is never reachable from the public surface.\n */\n\nimport type { Session } from \"../core/session.js\";\nimport type { Transport } from \"../transport/types.js\";\nimport type { AttestationResult } from \"../transport/handshake.js\";\nimport type { SecureChannel } from \"./secureChannel.js\";\nimport type { CoordinatorPoolConfig } from \"../schemas/types.generated.js\";\nimport { TransportError } from \"../core/errors.js\";\nimport type { ClientPersistenceState } from \"../storage/clientPersistence.js\";\n\nexport interface SessionState {\n /** Flipped to `true` once attestation passes. */\n attested: boolean;\n /** The byte channel this session runs over. */\n readonly transport: Transport;\n /** The endpoint pool the session was created with. */\n readonly pool: CoordinatorPoolConfig;\n /** The last verified attestation result, or `null` before first attestation. */\n attestation: AttestationResult | null;\n /**\n * The live attested Noise channel, or `null` before/after attestation. All\n * application I/O Noise-encrypts through this.\n */\n channel: SecureChannel | null;\n /**\n * The per-connection 32-byte CSPRNG nonce bound into the attestation request.\n * Retained for re-attestation over the same channel.\n */\n nonce: Uint8Array | null;\n /** The coordinator's pinned Noise static public key, or `null` if unattested. */\n remoteStaticPublicKey: Uint8Array | null;\n /** Pending re-attestation timer, cleared on close. */\n reattestTimer: ReturnType<typeof setTimeout> | null;\n /** In-flight re-attestation shared by explicit and periodic checks. */\n reattestPromise: Promise<AttestationResult> | null;\n /** Fatal secure-channel cause preserved across transport close notifications. */\n lastFatalError: Error | null;\n /** Handlers invoked when an out-of-band re-attestation fails. */\n readonly policyViolationHandlers: Set<(error: Error) => void>;\n /** Resolved opt-in client-persistence policy, kept behind the opaque handle. */\n readonly clientPersistence: ClientPersistenceState;\n /** Tear down the session: clear the re-attest timer and close the channel. */\n close(): void;\n}\n\nconst registry = new WeakMap<Session, SessionState>();\n\n/** Build an opaque {@link Session} handle backed by `state`. */\nexport function createSessionHandle(state: SessionState): Session {\n const handle = {\n get attested() {\n return state.attested;\n },\n } as unknown as Session;\n registry.set(handle, state);\n return handle;\n}\n\n/**\n * Resolve the internal state for a session.\n *\n * @throws Error if the handle was not produced by `createSession`.\n */\nexport function getSessionState(session: Session): SessionState {\n const state = registry.get(session);\n if (!state) {\n throw new Error(\"invalid Session: this handle was not created by createSession\");\n }\n return state;\n}\n\nexport function closeSessionState(state: SessionState): void {\n failSessionClosed(state, new TransportError(\"CONNECTION_LOST\", \"session closed\"), {\n notifyPolicyViolation: false,\n });\n}\n\nexport function failSessionClosed(\n state: SessionState,\n cause: Error,\n options: { readonly notifyPolicyViolation?: boolean } = {},\n): void {\n const notifyPolicyViolation = options.notifyPolicyViolation ?? true;\n const shouldNotify =\n notifyPolicyViolation &&\n (state.attested || state.attestation !== null || state.channel !== null);\n\n if (state.reattestTimer !== null) {\n clearTimeout(state.reattestTimer);\n state.reattestTimer = null;\n }\n state.reattestPromise = null;\n state.lastFatalError = cause;\n\n const channel = state.channel;\n state.attested = false;\n state.attestation = null;\n state.channel = null;\n state.nonce = null;\n state.remoteStaticPublicKey = null;\n\n channel?.close();\n state.transport.close();\n\n if (shouldNotify) {\n for (const handler of state.policyViolationHandlers) handler(cause);\n }\n}\n"]}
@@ -56,6 +56,9 @@ var StorageError = class extends InvisibleError {
56
56
  constructor(code, message, options) {
57
57
  super(message, options);
58
58
  this.code = code;
59
+ if (options?.swapId !== void 0) this.swapId = options.swapId;
60
+ if (options?.phase !== void 0) this.phase = options.phase;
61
+ if (options?.remoteAccepted !== void 0) this.remoteAccepted = options.remoteAccepted;
59
62
  }
60
63
  };
61
64
  var WalletError = class extends InvisibleError {
@@ -122,5 +125,5 @@ function isReadable(value) {
122
125
  }
123
126
 
124
127
  export { AttestationError, CommandError, InvalidDepositAmountError, InvisibleError, LpLifecycleError, NotImplementedError, PolicyValidationError, RoutingError, StorageError, TransportError, WalletError, isInvisibleError, normalizeError };
125
- //# sourceMappingURL=chunk-GHBQF3A7.js.map
126
- //# sourceMappingURL=chunk-GHBQF3A7.js.map
128
+ //# sourceMappingURL=chunk-QRN46R3F.js.map
129
+ //# sourceMappingURL=chunk-QRN46R3F.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/errors.ts"],"names":[],"mappings":";AAgKO,IAAe,cAAA,GAAf,cAAsC,KAAA,CAAM;AAAA,EAIjD,WAAA,CAAY,SAAiB,OAAA,EAAiC;AAC5D,IAAA,KAAA,CAAM,OAAO,CAAA;AAGb,IAAA,IAAI,OAAA,EAAS,UAAU,MAAA,EAAW;AAChC,MAAC,IAAA,CAA6B,QAAQ,OAAA,CAAQ,KAAA;AAAA,IAChD;AACA,IAAA,IAAA,CAAK,OAAO,GAAA,CAAA,MAAA,CAAW,IAAA;AAGvB,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF;AAGO,IAAM,gBAAA,GAAN,cAA+B,cAAA,CAAe;AAAA,EAEnD,WAAA,CAAY,IAAA,EAA4B,OAAA,EAAiB,OAAA,EAAiC;AACxF,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AACtB,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAGO,IAAM,cAAA,GAAN,cAA6B,cAAA,CAAe;AAAA,EAEjD,WAAA,CAAY,IAAA,EAA0B,OAAA,EAAiB,OAAA,EAAiC;AACtF,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AACtB,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAGO,IAAM,YAAA,GAAN,cAA2B,cAAA,CAAe;AAAA,EAE/C,WAAA,CAAY,IAAA,EAAwB,OAAA,EAAiB,OAAA,EAAiC;AACpF,IAAA,KAAA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AA;AAAA,EAC9D;AAEA,EAAA,OAAO,IAAA;AACT;AAEA,SAAS,cAAc,KAAA,EAAsC;AAC3D,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA;AAChD;AAEA,SAAS,UAAA,CAAW,MAAe,OAAA,EAAyB;AAC1D,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,IAAA,CAAK,IAAA,GAAO,MAAA,KAAW,CAAA,EAAG,OAAO,OAAA,CAAQ,IAAA,EAAK;AAC9E,EAAA,MAAM,OAAA,GAAU,KAAK,IAAA,EAAK;AAC1B,EAAA,OAAO,OAAA,CAAQ,QAAA,CAAS,CAAA,CAAA,EAAI,OAAO,GAAG,CAAA,GAAI,OAAA,CAAQ,IAAA,EAAK,GAAI,CAAA,CAAA,EAAI,OAAO,CAAA,EAAA,EAAK,OAAA,CAAQ,MAAM,CAAA,CAAA;AAC3F;AAEA,SAAS,WAAW,KAAA,EAAuC;AACzD,EAAA,IAAI,KAAA,KAAU,MAAM,OAAO,KAAA;AAC3B,EAAA,MAAM,OAAA,GAAU,MAAM,IAAA,EAAK;AAC3B,EAAA,IAAI,OAAA,CAAQ,MAAA,KAAW,CAAA,EAAG,OAAO,KAAA;AACjC,EAAA,OAAO,CAAC,gEAAA,CAAiE,IAAA,CAAK,OAAO,CAAA;AACvF","file":"chunk-QRN46R3F.js","sourcesContent":["/**\n * The closed error taxonomy from docs/sdk-specification.md section 8.3.\n *\n * Every error the SDK throws extends {@link InvisibleError} and carries a\n * `code` drawn from a closed, per-class string-literal union. Consumers can\n * branch on `error instanceof CommandError` and then exhaustively `switch` on\n * `error.code` with compile-time completeness.\n *\n * Error classes are the one deliberate exception to the SDK's \"no classes\"\n * rule: JavaScript errors must extend `Error` to carry a stack and support\n * `instanceof`. This mirrors @solana/kit, whose only class is `SolanaError`.\n * The conformance lint allowlists this file for that reason.\n */\n\n// ---------------------------------------------------------------------------\n// Code unions (closed sets, section 8.3)\n// ---------------------------------------------------------------------------\n\n/** Attestation verification failures. Stop; do not retry without a new pin. */\nexport type AttestationErrorCode =\n | \"CERT_CHAIN_INVALID\"\n | \"TCB_REJECTED\"\n | \"FRESHNESS_NONCE_MISMATCH\"\n | \"NOISE_BINDING_MISMATCH\"\n | \"DEBUG_BIT_SET\"\n | \"MRTD_MISMATCH\"\n | \"RUNTIME_MEASUREMENTS_MISMATCH\"\n | \"RUNTIME_PROFILE_MISMATCH\"\n | \"AZURE_MAA_ISSUER_MISMATCH\"\n | \"AZURE_MAA_JWKS_INVALID\"\n | \"AZURE_MAA_POLICY_HASH_MISMATCH\"\n | \"AZURE_MAA_NOT_COMPLIANT\"\n | \"AZURE_MAA_DCAP_MISMATCH\"\n | \"AZURE_HCL_KEYS_MISMATCH\"\n | \"AZURE_AK_PUB_INVALID\"\n | \"AZURE_TPM_AK_QUOTE_INVALID\"\n | \"AZURE_TPM_QUALIFYING_DATA_MISMATCH\"\n | \"NOT_ATTESTED\";\n\n/** Transport-level failures. Reconnect through the pool and re-attest. */\nexport type TransportErrorCode =\n | \"WS_HANDSHAKE_FAILED\"\n | \"NOISE_HANDSHAKE_FAILED\"\n | \"NOISE_FRAME_TOO_LARGE\"\n | \"CONNECTION_LOST\";\n\n/** Leader/role routing failures. Failover and re-attest. */\nexport type RoutingErrorCode =\n | \"WRONG_ROLE\"\n | \"STALE_LEADER_EPOCH\"\n | \"POOL_DEGRADED\"\n | \"VERSION_NOT_SUPPORTED\";\n\n/** Coordinator-side command rejections. Product decides whether to retry. */\nexport type CommandErrorCode =\n | \"REJECTED_GUARD\"\n | \"REJECTED_STATE\"\n | \"REJECTED_EXPIRED\"\n | \"REJECTED_STALE_JOB\"\n | \"REJECTED_RESOURCE_CAP\";\n\n/** Coordinator wire error code preserved on command rejections. */\nexport type CoordinatorWireErrorCode =\n | \"ERR_INVALID_PAYLOAD\"\n | \"ERR_UNEXPECTED_TYPE\"\n | \"ERR_UNKNOWN_SWAP\"\n | \"ERR_POLICY_VIOLATION\"\n | \"ERR_INVALID_RECOVERY_CODE\"\n | \"ERR_SWAP_NOT_REFUNDABLE\"\n | \"ERR_DKG_FAILURE\"\n | \"ERR_INTERNAL\"\n | \"ERR_INVALID_DEPOSIT\"\n | \"ERR_SETTLEMENT_FAILED\";\n\n/** Local input-validation failures. Never sent on the wire; fix the input. */\nexport type PolicyValidationErrorCode =\n | \"INVALID_PAYOUT_PLAN\"\n | \"INVALID_WITHDRAWAL_PLAN\"\n | \"INVALID_POSITION_AUTH\"\n | \"INVALID_REDEMPTION_PLAN\"\n | \"INVALID_DESTINATION_ADDRESS\"\n | \"INVALID_AMOUNT\";\n\n/** Storage-adapter failures. */\nexport type StorageErrorCode =\n | \"STORAGE_NOT_AVAILABLE\"\n | \"STORAGE_INVALID_ADAPTER\"\n | \"STORAGE_QUOTA_EXCEEDED\"\n | \"STORAGE_KEY_MISSING\"\n | \"STORAGE_DECRYPT_FAILED\";\n\n/** Wallet-adapter failures. Bubble to the integrator UX. */\nexport type WalletErrorCode =\n | \"WALLET_NOT_CONNECTED\"\n | \"WALLET_USER_REJECTED\"\n | \"WALLET_INVALID_SIGNATURE\";\n\n/** LP lifecycle local state that callers can branch on. */\nexport type LpLifecycleErrorCode = \"LP_POSITION_AUTH_MISSING\" | \"LP_REDEMPTION_RECONCILING\";\n\n/** Skeleton-only: a surface that exists but has no implementation yet. */\nexport type NotImplementedErrorCode = \"NOT_IMPLEMENTED\";\n\n/** Every code the SDK can surface, across all classes. */\nexport type InvisibleErrorCode =\n | AttestationErrorCode\n | TransportErrorCode\n | RoutingErrorCode\n | CommandErrorCode\n | PolicyValidationErrorCode\n | StorageErrorCode\n | WalletErrorCode\n | LpLifecycleErrorCode\n | NotImplementedErrorCode;\n\n// ---------------------------------------------------------------------------\n// Error classes\n// ---------------------------------------------------------------------------\n\n/** Options accepted by every {@link InvisibleError}. */\nexport interface InvisibleErrorOptions {\n /** The underlying error, preserved for debugging. */\n readonly cause?: unknown;\n}\n\n/** Context attached to a client-persistence storage failure. */\nexport type StorageErrorPhase =\n | \"session-init\"\n | \"write\"\n | \"allocation\"\n | \"recovery-code\"\n | \"ready\"\n | \"sync\"\n | \"refund\"\n | \"read\"\n | \"remove\"\n | \"purge\";\n\n/** Options accepted by {@link StorageError}. */\nexport interface StorageErrorOptions extends InvisibleErrorOptions {\n /** The affected normal-user swap, when known. */\n readonly swapId?: string;\n /** The client-persistence lifecycle phase that failed. */\n readonly phase?: StorageErrorPhase;\n /** True when the coordinator accepted the command before local failure. */\n readonly remoteAccepted?: boolean;\n}\n\n/** Options accepted by {@link CommandError}. */\nexport interface CommandErrorOptions extends InvisibleErrorOptions {\n /** Exact coordinator `Error` envelope code, when the rejection came from the wire. */\n readonly coordinatorCode?: CoordinatorWireErrorCode;\n /** Request id rejected by the coordinator, when present in the `Error` envelope. */\n readonly failedReqId?: number;\n}\n\n/**\n * Base class for every error the SDK throws. Carries a closed `code` and sets\n * `name` to the concrete subclass name so logs and `instanceof` agree.\n */\nexport abstract class InvisibleError extends Error {\n /** The closed error code for this error's class. */\n abstract readonly code: InvisibleErrorCode;\n\n constructor(message: string, options?: InvisibleErrorOptions) {\n super(message);\n // Set `cause` directly rather than through the Error constructor option so\n // the package stays on the ES2020 lib (the option is ES2022).\n if (options?.cause !== undefined) {\n (this as { cause?: unknown }).cause = options.cause;\n }\n this.name = new.target.name;\n // Restore the prototype chain across the transpiled `Error` boundary so\n // `instanceof` works for subclasses.\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Attestation verification failure. */\nexport class AttestationError extends InvisibleError {\n readonly code: AttestationErrorCode;\n constructor(code: AttestationErrorCode, message: string, options?: InvisibleErrorOptions) {\n super(message, options);\n this.code = code;\n }\n}\n\n/** Transport-level failure. */\nexport class TransportError extends InvisibleError {\n readonly code: TransportErrorCode;\n constructor(code: TransportErrorCode, message: string, options?: InvisibleErrorOptions) {\n super(message, options);\n this.code = code;\n }\n}\n\n/** Leader/role routing failure. */\nexport class RoutingError extends InvisibleError {\n readonly code: RoutingErrorCode;\n constructor(code: RoutingErrorCode, message: string, options?: InvisibleErrorOptions) {\n super(message, options);\n this.code = code;\n }\n}\n\n/** Coordinator-side command rejection. */\nexport class CommandError extends InvisibleError {\n readonly code: CommandErrorCode;\n readonly coordinatorCode?: CoordinatorWireErrorCode;\n readonly failedReqId?: number;\n\n constructor(code: CommandErrorCode, message: string, options?: CommandErrorOptions) {\n super(message, options);\n this.code = code;\n if (options?.coordinatorCode !== undefined) this.coordinatorCode = options.coordinatorCode;\n if (options?.failedReqId !== undefined) this.failedReqId = options.failedReqId;\n }\n}\n\n/** User deposit did not match the coordinator policy amount. */\nexport class InvalidDepositAmountError extends CommandError {\n readonly receivedLamports: bigint;\n readonly expectedLamports: bigint;\n\n constructor(receivedLamports: bigint, expectedLamports: bigint) {\n super(\n \"REJECTED_GUARD\",\n `on-chain deposit balance ${receivedLamports.toString()} does not match expected ${expectedLamports.toString()} lamports`,\n );\n this.name = \"InvalidDepositAmountError\";\n this.receivedLamports = receivedLamports;\n this.expectedLamports = expectedLamports;\n }\n}\n\n/** Local input-validation failure; never reaches the wire. */\nexport class PolicyValidationError extends InvisibleError {\n readonly code: PolicyValidationErrorCode;\n constructor(code: PolicyValidationErrorCode, message: string, options?: InvisibleErrorOptions) {\n super(message, options);\n this.code = code;\n }\n}\n\n/** Storage-adapter failure. */\nexport class StorageError extends InvisibleError {\n readonly code: StorageErrorCode;\n readonly swapId?: string;\n readonly phase?: StorageErrorPhase;\n readonly remoteAccepted?: boolean;\n\n constructor(code: StorageErrorCode, message: string, options?: StorageErrorOptions) {\n super(message, options);\n this.code = code;\n if (options?.swapId !== undefined) this.swapId = options.swapId;\n if (options?.phase !== undefined) this.phase = options.phase;\n if (options?.remoteAccepted !== undefined) this.remoteAccepted = options.remoteAccepted;\n }\n}\n\n/** Wallet-adapter failure. */\nexport class WalletError extends InvisibleError {\n readonly code: WalletErrorCode;\n constructor(code: WalletErrorCode, message: string, options?: InvisibleErrorOptions) {\n super(message, options);\n this.code = code;\n }\n}\n\n/** LP lifecycle state that is local to the SDK client. */\nexport class LpLifecycleError extends InvisibleError {\n readonly code: LpLifecycleErrorCode;\n constructor(code: LpLifecycleErrorCode, message: string, options?: InvisibleErrorOptions) {\n super(message, options);\n this.code = code;\n }\n}\n\n/**\n * A surface that exists in the typed contract but has no runtime behavior yet.\n * The skeleton throws this from every command that is not the connection layer.\n * The message carries the fully-qualified command name (e.g. `user.contractRequest`).\n */\nexport class NotImplementedError extends InvisibleError {\n readonly code = \"NOT_IMPLEMENTED\" as const;\n /** The command that is not yet implemented, e.g. `lp.redeem`. */\n readonly command: string;\n constructor(command: string, options?: InvisibleErrorOptions) {\n super(`${command} is not implemented in this SDK build`, options);\n this.command = command;\n }\n}\n\n/** Type guard: is `value` any SDK error. */\nexport function isInvisibleError(value: unknown): value is InvisibleError {\n return value instanceof InvisibleError;\n}\n\n// ---------------------------------------------------------------------------\n// Normalization (analog of web/src/lib/user-facing-error.ts)\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_ERROR_MESSAGE = \"Something went wrong. Please try again.\";\n\ninterface MessageLike {\n readonly message?: unknown;\n readonly reason?: unknown;\n readonly error?: unknown;\n readonly code?: unknown;\n}\n\n/**\n * Reduce any thrown value to a readable, single-line message. Guarantees the\n * SDK never surfaces `[object Object]` / `[object ErrorEvent]` (spec section\n * 8.3). For an {@link InvisibleError} the code is prefixed as `[CODE] message`.\n */\nexport function normalizeError(error: unknown, fallback: string = DEFAULT_ERROR_MESSAGE): string {\n const direct = extractMessage(error);\n if (isReadable(direct)) return direct;\n if (isReadable(fallback)) return fallback.trim();\n return DEFAULT_ERROR_MESSAGE;\n}\n\nfunction extractMessage(error: unknown): string | null {\n if (error instanceof CommandError && error.coordinatorCode !== undefined) {\n return formatCode(error.coordinatorCode, error.message);\n }\n if (error instanceof InvisibleError) return formatCode(error.code, error.message);\n if (error instanceof Error) return error.message;\n if (typeof error === \"string\") return error;\n if (error === null || error === undefined) return null;\n\n if (isMessageLike(error)) {\n if (typeof error.message === \"string\" && isReadable(error.message)) {\n return formatCode(error.code, error.message);\n }\n const nested = extractMessage(error.error);\n if (isReadable(nested)) return formatCode(error.code, nested);\n const reason = extractMessage(error.reason);\n if (isReadable(reason)) return formatCode(error.code, reason);\n }\n\n return null;\n}\n\nfunction isMessageLike(value: unknown): value is MessageLike {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction formatCode(code: unknown, message: string): string {\n if (typeof code !== \"string\" || code.trim().length === 0) return message.trim();\n const trimmed = code.trim();\n return message.includes(`[${trimmed}]`) ? message.trim() : `[${trimmed}] ${message.trim()}`;\n}\n\nfunction isReadable(value: string | null): value is string {\n if (value === null) return false;\n const trimmed = value.trim();\n if (trimmed.length === 0) return false;\n return !/^\\[object (?:Object|Event|ErrorEvent|PromiseRejectionEvent)\\]$/.test(trimmed);\n}\n"]}