@haex-space/vault-sdk 4.5.0 → 4.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +40 -0
  2. package/dist/cli/index.mjs.map +1 -1
  3. package/dist/{client-Dw2uH1EM.d.ts → client-DS-j-fHu.d.mts} +179 -2
  4. package/dist/{client-D4VYF0bP.d.mts → client-DkVe1o-u.d.ts} +179 -2
  5. package/dist/{config-D_HXjsEV.d.mts → config-P_6DqTHl.d.mts} +2 -1
  6. package/dist/{config-D_HXjsEV.d.ts → config-P_6DqTHl.d.ts} +2 -1
  7. package/dist/index.d.mts +42 -8
  8. package/dist/index.d.ts +42 -8
  9. package/dist/index.js +143 -5
  10. package/dist/index.js.map +1 -1
  11. package/dist/index.mjs +140 -5
  12. package/dist/index.mjs.map +1 -1
  13. package/dist/node.d.mts +4 -3
  14. package/dist/node.d.ts +4 -3
  15. package/dist/node.mjs +1 -1
  16. package/dist/node.mjs.map +1 -1
  17. package/dist/nuxt.d.mts +2 -1
  18. package/dist/nuxt.d.ts +2 -1
  19. package/dist/nuxt.js +1 -1
  20. package/dist/nuxt.js.map +1 -1
  21. package/dist/react.d.mts +3 -2
  22. package/dist/react.d.ts +3 -2
  23. package/dist/react.js +139 -5
  24. package/dist/react.js.map +1 -1
  25. package/dist/react.mjs +138 -4
  26. package/dist/react.mjs.map +1 -1
  27. package/dist/runtime/nuxt.plugin.client.d.mts +4 -3
  28. package/dist/runtime/nuxt.plugin.client.d.ts +4 -3
  29. package/dist/runtime/nuxt.plugin.client.js +128 -1
  30. package/dist/runtime/nuxt.plugin.client.js.map +1 -1
  31. package/dist/runtime/nuxt.plugin.client.mjs +128 -1
  32. package/dist/runtime/nuxt.plugin.client.mjs.map +1 -1
  33. package/dist/svelte.d.mts +3 -2
  34. package/dist/svelte.d.ts +3 -2
  35. package/dist/svelte.js +139 -5
  36. package/dist/svelte.js.map +1 -1
  37. package/dist/svelte.mjs +138 -4
  38. package/dist/svelte.mjs.map +1 -1
  39. package/dist/{types-CYuW3glJ.d.mts → types-snPkjDCj.d.mts} +10 -1
  40. package/dist/{types-CYuW3glJ.d.ts → types-snPkjDCj.d.ts} +10 -1
  41. package/dist/vite.d.mts +2 -1
  42. package/dist/vite.d.ts +2 -1
  43. package/dist/vue.d.mts +3 -2
  44. package/dist/vue.d.ts +3 -2
  45. package/dist/vue.js +139 -5
  46. package/dist/vue.js.map +1 -1
  47. package/dist/vue.mjs +138 -4
  48. package/dist/vue.mjs.map +1 -1
  49. package/package.json +3 -3
package/README.md CHANGED
@@ -1120,6 +1120,46 @@ The permission kind `encryptedFolder` (target `<storageId>/<folderId>`, `read` o
1120
1120
  granted only at runtime and can never be declared in `manifest.json`: the host refuses such a
1121
1121
  bundle. A damaged entry fails with `HostErrorCode.ENCRYPTED_DATA_DAMAGED` (3010).
1122
1122
 
1123
+ ### Models
1124
+
1125
+ Jobs on the host's language and vision models, instead of bringing your own access and keys. You
1126
+ describe each step with its instruction, its input (text, images, or a part of an earlier step's
1127
+ result) and the format of its answer as a JSON Schema; the host picks a model the user allowed for
1128
+ your extension, caps the effort and returns only a result that fits the format. Broken output (empty,
1129
+ a loop, a script switch, invalid JSON) is dropped, and the host tries the next allowed model.
1130
+
1131
+ ```ts
1132
+ const end = await client.models.runAsync({
1133
+ steps: [
1134
+ {
1135
+ id: "fix",
1136
+ needs: ["text"],
1137
+ instruction: "Correct the spelling only.",
1138
+ input: { text: "Ths is a tset." },
1139
+ format: {
1140
+ name: "text-fix",
1141
+ version: 1,
1142
+ schema: {
1143
+ type: "object",
1144
+ required: ["text"],
1145
+ properties: { text: { type: "string" } },
1146
+ },
1147
+ },
1148
+ effort: "low",
1149
+ },
1150
+ ],
1151
+ });
1152
+ if (end.status === "completed") console.log(end.result?.final, end.provenance);
1153
+ else console.warn(end.error?.code, end.error?.message);
1154
+ ```
1155
+
1156
+ The user decides at run time which model your extension may use and up to which effort, and gives
1157
+ consent before anything goes to a destination outside the device; the SDK waits for these answers
1158
+ and starts the job again. `models.listAsync()` names the allowed models with their place and
1159
+ capabilities, never an address or a key; `models.startAsync`, `models.onCompleted` and
1160
+ `models.cancelAsync` give you the job's id and its end separately. A job has no tools and sees only
1161
+ the input you send.
1162
+
1123
1163
  ### Database Operations
1124
1164
 
1125
1165
  #### Query
@@ -1 +1 @@
1
- {"version":3,"sources":["../../node_modules/.pnpm/tsup@8.5.1_jiti@2.7.0_postcss@8.5.30_typescript@6.0.3_yaml@2.9.0/node_modules/tsup/assets/esm_shims.js","../../src/config.ts","../../src/manifest.ts","../../src/bundle/wasm/haex_bundle.js","../../src/bundle/index.ts","../../src/crypto/signing.ts","../../src/cli/index.ts"],"names":["path","__dirname","resolvePath","readFileSync","ptr","existsSync","fs","path2","relative"],"mappings":";;;;;;;;;AAIA,IAAM,WAAA,GAAc,MAAM,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA;AACvD,IAAM,UAAA,GAAa,MAAMA,cAAA,CAAK,OAAA,CAAQ,aAAa,CAAA;AAE5C,IAAMC,8BAA4B,UAAA,EAAW;AC0B7C,SAAS,qBAAA,CAAsB,OAAA,GAAkB,OAAA,CAAQ,GAAA,EAAI,EAA6B;AAC/F,EAAA,MAAM,UAAA,GAAa,OAAA,CAAQ,OAAA,EAAS,yBAAyB,CAAA;AAE7D,EAAA,IAAI,CAAC,UAAA,CAAW,UAAU,CAAA,EAAG;AAC3B,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,IAAI;AACF,IAAA,MAAM,OAAA,GAAU,YAAA,CAAa,UAAA,EAAY,OAAO,CAAA;AAChD,IAAA,OAAO,IAAA,CAAK,MAAM,OAAO,CAAA;AAAA,EAC3B,SAAS,KAAA,EAAO;AACd,IAAA,OAAA,CAAQ,IAAA,CAAK,CAAA,yCAAA,EAA4C,KAAK,CAAA,CAAE,CAAA;AAChE,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAKO,SAAS,eAAA,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,CAAM,UAAU,KAAK,CAAA;AAC7B,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB;AACF,CAAC,CAAA;AAEH,OAAA,CACG,OAAA,CAAQ,eAAe,CAAA,CACvB,WAAA,CAAY,CAAA,gBAAA,EAAmB,wBAAwB,CAAA,kCAAA,CAAoC,CAAA,CAC3F,MAAA,CAAO,OAAO,IAAA,KAAiB;AAC9B,EAAA,MAAM,MAAA,GAAS,MAAM,eAAA,CAAgB,aAAA,CAAc,IAAI,CAAA;AACvD,EAAA,IAAI,OAAO,KAAA,EAAO;AAChB,IAAA,MAAM,EAAE,IAAA,EAAM,OAAA,EAAS,SAAA,KAAc,MAAA,CAAO,QAAA;AAC5C,IAAA,OAAA,CAAQ,IAAI,CAAA,OAAA,EAAU,MAAA,CAAO,IAAI,CAAC,IAAI,MAAA,CAAO,OAAO,CAAC,CAAA,EAAA,EAAK,OAAO,KAAA,CAAM,MAAM,eAAe,MAAA,CAAO,SAAS,CAAC,CAAA,CAAE,CAAA;AAC/G,IAAA;AAAA,EACF;AACA,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,IAAA,KAAS,eAAA,GAAkB,CAAA,SAAA,EAAY,KAAK,SAAA,CAAU,MAAA,CAAO,IAAI,CAAC,CAAA,EAAA,CAAA,GAAO,EAAA;AAC9F,EAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,SAAA,EAAY,MAAA,CAAO,IAAI,GAAG,KAAK;AAAA,EAAA,EAAO,MAAA,CAAO,KAAK,CAAA,CAAE,CAAA;AAClE,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAChB,CAAC,CAAA;AAEH,OAAA,CAAQ,KAAA,EAAM","file":"index.mjs","sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * Utility to read haextension.config.json\n */\nimport { readFileSync, existsSync } from 'fs'\nimport { resolve } from 'path'\n\nexport interface HaextensionConfig {\n dev?: {\n port?: number\n host?: string\n haextension_dir?: string\n }\n keys?: {\n public_key_path?: string\n private_key_path?: string\n }\n build?: {\n distDir?: string\n /**\n * Source path for migrations directory (relative to project root).\n * If manifest.migrationsDir is set, this directory will be copied\n * to the bundle at the path specified in migrationsDir.\n * Default: \"app/{migrationsDir}\" (for Nuxt projects)\n * Example: \"app/database/migrations\" -> copies to \"database/migrations\" in bundle\n */\n migrationsSourceDir?: string\n }\n}\n\n/**\n * Read haextension.config.json from the project root\n * Returns null if file doesn't exist\n */\nexport function readHaextensionConfig(rootDir: string = process.cwd()): HaextensionConfig | null {\n const configPath = resolve(rootDir, 'haextension.config.json')\n \n if (!existsSync(configPath)) {\n return null\n }\n\n try {\n const content = readFileSync(configPath, 'utf-8')\n return JSON.parse(content)\n } catch (error) {\n console.warn(`Failed to parse haextension.config.json: ${error}`)\n return null\n }\n}\n\n/**\n * Get extension directory from config or use default\n */\nexport function getExtensionDir(rootDir: string = process.cwd()): string {\n const config = readHaextensionConfig(rootDir)\n return config?.dev?.haextension_dir || 'haextension'\n}\n","/**\n * Utility for reading and processing extension manifest files\n */\nimport { readFileSync } from \"node:fs\";\nimport { resolve as resolvePath } from \"node:path\";\nimport type { ExtensionManifest } from \"./types\";\n\nexport interface ReadManifestOptions {\n /** Root directory of the project */\n rootDir: string;\n /** Path to manifest.json (if not provided, will use extensionDir) */\n manifestPath?: string;\n /** Directory containing extension files (default: \"haextension\") */\n extensionDir?: string;\n}\n\n/**\n * Reads and processes the extension manifest.json file\n * Falls back to package.json version if manifest doesn't specify one\n */\nexport function readManifest(options: ReadManifestOptions): ExtensionManifest | null {\n const { rootDir, manifestPath, extensionDir = \"haextension\" } = options;\n\n // Determine manifest path\n const resolvedManifestPath = manifestPath\n ? resolvePath(rootDir, manifestPath)\n : resolvePath(rootDir, extensionDir, \"manifest.json\");\n\n try {\n const manifestContent = readFileSync(resolvedManifestPath, \"utf-8\");\n // `signature` belonged to the pre-v2 bundle format; signing now writes `haextension/signature.json`.\n const { signature: _legacySignature, ...parsed } = JSON.parse(manifestContent) as Partial<ExtensionManifest> & {\n signature?: unknown;\n };\n\n // Read fallback values from package.json\n let packageJson: { name?: string; version?: string; author?: string; homepage?: string } = {};\n try {\n const packageJsonPath = resolvePath(rootDir, \"package.json\");\n packageJson = JSON.parse(readFileSync(packageJsonPath, \"utf-8\"));\n } catch {\n console.warn(`[@haex-space/vault-sdk] Warning: Could not read package.json`);\n }\n\n // Always use package.json name as stable technical identifier\n // Display names are handled via i18n in the manifest\n const name = packageJson.name;\n const version = parsed.version ?? packageJson.version;\n const author = parsed.author ?? packageJson.author ?? null;\n const homepage = parsed.homepage ?? packageJson.homepage ?? null;\n\n if (!name) {\n console.warn(`[@haex-space/vault-sdk] Warning: No name found in manifest or package.json`);\n return null;\n }\n\n if (!version) {\n console.warn(`[@haex-space/vault-sdk] Warning: No version found in manifest or package.json`);\n return null;\n }\n\n const manifest: ExtensionManifest = {\n // Keep every field the developer wrote (e.g. displayName); the fallbacks below win.\n ...parsed,\n name,\n version,\n author,\n entry: parsed.entry ?? null,\n icon: parsed.icon ?? null,\n publicKey: parsed.publicKey ?? \"\",\n permissions: parsed.permissions ?? {\n database: [],\n filesystem: [],\n http: [],\n shell: [],\n },\n homepage,\n description: parsed.description ?? null,\n singleInstance: parsed.singleInstance ?? null,\n displayMode: parsed.displayMode ?? null,\n migrationsDir: parsed.migrationsDir ?? null,\n i18n: parsed.i18n ?? null,\n tools: parsed.tools ?? null,\n };\n\n console.log(`✓ [@haex-space/vault-sdk] Loaded ${resolvedManifestPath}`);\n return manifest;\n } catch {\n console.warn(\n `[@haex-space/vault-sdk] Warning: manifest.json not found at ${resolvedManifestPath}, extension info will not be available`\n );\n return null;\n }\n}\n","/* @ts-self-types=\"./haex_bundle.d.ts\" */\n\n/**\n * Collects the files of a bundle and builds the signed archive.\n */\nexport class BundleBuilder {\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n BundleBuilderFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_bundlebuilder_free(ptr, 0);\n }\n /**\n * Adds an app file (no control file).\n * @param {string} path\n * @param {Uint8Array} data\n */\n addFile(path, data) {\n const ptr0 = passStringToWasm0(path, wasm.__wbindgen_export, wasm.__wbindgen_export2);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(data, wasm.__wbindgen_export);\n const len1 = WASM_VECTOR_LEN;\n wasm.bundlebuilder_addFile(this.__wbg_ptr, ptr0, len0, ptr1, len1);\n }\n /**\n * Signs with the PKCS#8 Ed25519 key, writes the archive and verifies it. `manifest_json` is\n * the manifest without `signature`; its `publicKey` is set from the key. Throws the JSON of a\n * `BundleError` (`{kind, message, path?}`).\n * @param {string} manifest_json\n * @param {Uint8Array} private_key_pkcs8\n * @returns {Uint8Array}\n */\n build(manifest_json, private_key_pkcs8) {\n try {\n const ptr = this.__destroy_into_raw();\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(manifest_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(private_key_pkcs8, wasm.__wbindgen_export);\n const len1 = WASM_VECTOR_LEN;\n wasm.bundlebuilder_build(retptr, ptr, ptr0, len0, ptr1, len1);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v3 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_export3(r0, r1 * 1, 1);\n return v3;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n constructor() {\n const ret = wasm.bundlebuilder_new();\n this.__wbg_ptr = ret;\n BundleBuilderFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n}\nif (Symbol.dispose) BundleBuilder.prototype[Symbol.dispose] = BundleBuilder.prototype.free;\n\n/**\n * Every error kind as JSON array, so the SDK can test its `BundleErrorKind` type against it.\n * @returns {string}\n */\nexport function errorKinds() {\n let deferred1_0;\n let deferred1_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.errorKinds(retptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n deferred1_0 = r0;\n deferred1_1 = r1;\n return getStringFromWasm0(r0, r1);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_export3(deferred1_0, deferred1_1, 1);\n }\n}\n\n/**\n * Largest archive a host accepts, so callers can refuse a bigger file before reading it.\n * @returns {number}\n */\nexport function maxArchiveBytes() {\n const ret = wasm.maxArchiveBytes();\n return ret;\n}\n\n/**\n * Verifies a `.xt` archive exactly like a host does. Returns\n * `{\"valid\":true,\"manifest\":…,\"files\":[…],\"migrations\":[…]}` or\n * `{\"valid\":false,\"kind\":…,\"message\":…,\"path\"?:…}`.\n * @param {Uint8Array} archive\n * @returns {string}\n */\nexport function verifyArchive(archive) {\n let deferred2_0;\n let deferred2_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(archive, wasm.__wbindgen_export);\n const len0 = WASM_VECTOR_LEN;\n wasm.verifyArchive(retptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n deferred2_0 = r0;\n deferred2_1 = r1;\n return getStringFromWasm0(r0, r1);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_export3(deferred2_0, deferred2_1, 1);\n }\n}\nfunction __wbg_get_imports() {\n const import0 = {\n __proto__: null,\n __wbg___wbindgen_throw_41e9ee4f547fc59a: function(arg0, arg1) {\n throw new Error(getStringFromWasm0(arg0, arg1));\n },\n __wbindgen_generic_0000000000000001: function(arg0, arg1) {\n // Cast intrinsic for `Ref(String) -> Externref`.\n const ret = getStringFromWasm0(arg0, arg1);\n return addHeapObject(ret);\n },\n };\n return {\n __proto__: null,\n \"./haex_bundle_bg.js\": import0,\n };\n}\n\nconst BundleBuilderFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_bundlebuilder_free(ptr, 1));\n\nfunction addHeapObject(obj) {\n if (heap_next === heap.length) heap.push(heap.length + 1);\n const idx = heap_next;\n heap_next = heap[idx];\n\n heap[idx] = obj;\n return idx;\n}\n\nfunction dropObject(idx) {\n if (idx < 1028) return;\n heap[idx] = heap_next;\n heap_next = idx;\n}\n\nfunction getArrayU8FromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);\n}\n\nlet cachedDataViewMemory0 = null;\nfunction getDataViewMemory0() {\n if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {\n cachedDataViewMemory0 = new DataView(wasm.memory.buffer);\n }\n return cachedDataViewMemory0;\n}\n\nfunction getStringFromWasm0(ptr, len) {\n return decodeText(ptr >>> 0, len);\n}\n\nlet cachedUint8ArrayMemory0 = null;\nfunction getUint8ArrayMemory0() {\n if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {\n cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);\n }\n return cachedUint8ArrayMemory0;\n}\n\nfunction getObject(idx) { return heap[idx]; }\n\nlet heap = new Array(1024).fill(undefined);\nheap.push(undefined, null, true, false);\n\nlet heap_next = heap.length;\n\nfunction passArray8ToWasm0(arg, malloc) {\n const ptr = malloc(arg.length * 1, 1) >>> 0;\n getUint8ArrayMemory0().set(arg, ptr / 1);\n WASM_VECTOR_LEN = arg.length;\n return ptr;\n}\n\nfunction passStringToWasm0(arg, malloc, realloc) {\n if (realloc === undefined) {\n const buf = cachedTextEncoder.encode(arg);\n const ptr = malloc(buf.length, 1) >>> 0;\n getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);\n WASM_VECTOR_LEN = buf.length;\n return ptr;\n }\n\n let len = arg.length;\n let ptr = malloc(len, 1) >>> 0;\n\n const mem = getUint8ArrayMemory0();\n\n let offset = 0;\n\n for (; offset < len; offset++) {\n const code = arg.charCodeAt(offset);\n if (code > 0x7F) break;\n mem[ptr + offset] = code;\n }\n if (offset !== len) {\n if (offset !== 0) {\n arg = arg.slice(offset);\n }\n ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;\n const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);\n const ret = cachedTextEncoder.encodeInto(arg, view);\n\n offset += ret.written;\n ptr = realloc(ptr, len, offset, 1) >>> 0;\n }\n\n WASM_VECTOR_LEN = offset;\n return ptr;\n}\n\nfunction takeObject(idx) {\n const ret = getObject(idx);\n dropObject(idx);\n return ret;\n}\n\nlet cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\ncachedTextDecoder.decode();\nconst MAX_SAFARI_DECODE_BYTES = 2146435072;\nlet numBytesDecoded = 0;\nfunction decodeText(ptr, len) {\n numBytesDecoded += len;\n if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {\n cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\n cachedTextDecoder.decode();\n numBytesDecoded = len;\n }\n return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));\n}\n\nconst cachedTextEncoder = new TextEncoder();\n\nif (!('encodeInto' in cachedTextEncoder)) {\n cachedTextEncoder.encodeInto = function (arg, view) {\n const buf = cachedTextEncoder.encode(arg);\n view.set(buf);\n return {\n read: arg.length,\n written: buf.length\n };\n };\n}\n\nlet WASM_VECTOR_LEN = 0;\n\nlet wasmModule, wasmInstance, wasm;\nfunction __wbg_finalize_init(instance, module) {\n wasmInstance = instance;\n wasm = instance.exports;\n wasmModule = module;\n cachedDataViewMemory0 = null;\n cachedUint8ArrayMemory0 = null;\n return wasm;\n}\n\nasync function __wbg_load(module, imports) {\n if (typeof Response === 'function' && module instanceof Response) {\n if (!module.ok) {\n throw new Error(`failed to fetch Wasm: ${module.status} ${module.statusText} fetching '${module.url}'`);\n }\n\n if (typeof WebAssembly.instantiateStreaming === 'function') {\n try {\n return await WebAssembly.instantiateStreaming(module, imports);\n } catch (e) {\n const validResponse = expectedResponseType(module.type);\n\n if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {\n console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n } else { throw e; }\n }\n }\n\n const bytes = await module.arrayBuffer();\n return await WebAssembly.instantiate(bytes, imports);\n } else {\n const instance = await WebAssembly.instantiate(module, imports);\n\n if (instance instanceof WebAssembly.Instance) {\n return { instance, module };\n } else {\n return instance;\n }\n }\n\n function expectedResponseType(type) {\n switch (type) {\n case 'basic': case 'cors': case 'default': return true;\n }\n return false;\n }\n}\n\nfunction initSync(module) {\n if (wasm !== undefined) return wasm;\n\n\n if (module !== undefined) {\n if (Object.getPrototypeOf(module) === Object.prototype) {\n ({module} = module)\n } else {\n console.warn('using deprecated parameters for `initSync()`; pass a single object instead')\n }\n }\n\n const imports = __wbg_get_imports();\n if (!(module instanceof WebAssembly.Module)) {\n module = new WebAssembly.Module(module);\n }\n const instance = new WebAssembly.Instance(module, imports);\n return __wbg_finalize_init(instance, module);\n}\n\nasync function __wbg_init(module_or_path) {\n if (wasm !== undefined) return wasm;\n\n\n if (module_or_path !== undefined) {\n if (Object.getPrototypeOf(module_or_path) === Object.prototype) {\n ({module_or_path} = module_or_path)\n } else {\n console.warn('using deprecated parameters for the initialization function; pass a single object instead')\n }\n }\n\n if (module_or_path === undefined) {\n module_or_path = new URL('haex_bundle_bg.wasm', import.meta.url);\n }\n const imports = __wbg_get_imports();\n\n if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {\n module_or_path = fetch(module_or_path);\n }\n\n const { instance, module } = await __wbg_load(await module_or_path, imports);\n\n return __wbg_finalize_init(instance, module);\n}\n\nexport { initSync, __wbg_init as default };\n","/**\n * Bundle format `haextension-bundle/2` for the `haex` tool (Node.js only).\n *\n * Every rule lives in the Rust crate `crates/haex-bundle`, which hosts such as holzi use natively;\n * this module only calls its WebAssembly build (`pnpm build:wasm`). Nothing of the format is\n * implemented here, so the tool and the hosts cannot drift apart.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { BundleBuilder, initSync, maxArchiveBytes, verifyArchive } from \"./wasm/haex_bundle\";\n\nexport const BUNDLE_FILE_EXTENSION = \".xt\";\n\n/** The error kinds of the crate (`ErrorKind::ALL`, checked by `src/bundle/__tests__/wasm.test.ts`). */\nexport const BUNDLE_ERROR_KINDS = [\n \"archive_too_large\",\n \"archive_invalid\",\n \"entry_path_invalid\",\n \"entry_duplicate\",\n \"entry_too_large\",\n \"entry_ratio\",\n \"entry_kind\",\n \"manifest_not_canonical\",\n \"manifest_invalid\",\n \"file_mismatch\",\n \"public_key_mismatch\",\n \"signature_invalid\",\n \"legacy_signature_format\",\n] as const;\n\nexport type BundleErrorKind = (typeof BUNDLE_ERROR_KINDS)[number];\n\n/** One file of a bundle: its path inside the archive and its exact bytes. */\nexport interface BundleEntry {\n path: string;\n data: Uint8Array;\n}\n\nexport interface SignedFile {\n path: string;\n sha256: string;\n size: number;\n}\n\nexport interface VerifiedBundle {\n manifest: Record<string, unknown>;\n /** Every entry except `signature.json`, in UTF-8 byte order. */\n files: SignedFile[];\n /** The migrations in the order they apply. */\n migrations: { name: string; path: string }[];\n}\n\n/**\n * A rejected bundle. `kind` is one of the error kinds of `test-vectors/bundles/README.md`;\n * `path` names the entry for entry-level errors and the first differing file for `file_mismatch`.\n */\nexport class BundleError extends Error {\n constructor(\n public readonly kind: BundleErrorKind,\n message: string,\n public readonly path?: string,\n ) {\n super(`${kind}: ${message}`);\n this.name = \"BundleError\";\n }\n}\n\nconst WASM_FILE = \"haex_bundle_bg.wasm\";\n\n/**\n * The module ships once as `dist/haex_bundle_bg.wasm`. The bundled entries live in `dist/` and\n * `dist/cli/`; from the sources (tests) it is the generated `wasm/` folder next to this file.\n */\nfunction wasmPath(): string {\n const candidates = [join(__dirname, WASM_FILE), join(__dirname, \"..\", WASM_FILE), join(__dirname, \"wasm\", WASM_FILE)];\n const found = candidates.find((candidate) => existsSync(candidate));\n if (!found) throw new Error(`${WASM_FILE} not found next to ${__dirname}; run \\`pnpm build:wasm\\``);\n return found;\n}\n\nlet state: \"new\" | \"ready\" | \"crashed\" = \"new\";\n\n/**\n * Runs `call` in the module. A panic in Rust traps (`panic = \"abort\"`) and leaves the instance in\n * an undefined state, so the module is not used again in this process.\n */\nfunction inModule<T>(call: () => T): T {\n if (state === \"crashed\") throw new Error(\"haex-bundle crashed earlier in this process; restart it\");\n if (state === \"new\") {\n initSync({ module: readFileSync(wasmPath()) });\n state = \"ready\";\n }\n try {\n return call();\n } catch (error) {\n if (error instanceof WebAssembly.RuntimeError) {\n state = \"crashed\";\n throw new Error(`haex-bundle crashed (a bug, please report it): ${error.message}`, { cause: error });\n }\n throw error;\n }\n}\n\n/** Largest `.xt` file a host accepts; check it before reading a file into memory. */\nexport function maxBundleBytes(): number {\n return inModule(() => maxArchiveBytes());\n}\n\n/** Verifies a `.xt` archive exactly like a host does. Throws a `BundleError` for the first failing rule. */\nexport function verifyBundle(archive: Uint8Array): VerifiedBundle {\n const result = JSON.parse(inModule(() => verifyArchive(archive))) as\n | ({ valid: true } & VerifiedBundle)\n | { valid: false; kind: BundleErrorKind; message: string; path?: string };\n if (!result.valid) throw new BundleError(result.kind, result.message, result.path);\n return { manifest: result.manifest, files: result.files, migrations: result.migrations };\n}\n\n/** A lone UTF-16 surrogate, which would silently become U+FFFD on the way into the module. */\nconst LONE_SURROGATE = /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/;\n\n/**\n * Signs the app files with the manifest (without `signature`; its `publicKey` is set from the\n * key), writes the deterministic archive and verifies it. `privateKeyPkcs8` is the Ed25519 key\n * as `haex keygen` writes it. Throws a `BundleError`.\n */\nexport function buildBundle(\n files: readonly BundleEntry[],\n manifest: Record<string, unknown>,\n privateKeyPkcs8: Uint8Array,\n): Uint8Array {\n for (const file of files) {\n if (LONE_SURROGATE.test(file.path)) {\n throw new BundleError(\"entry_path_invalid\", \"path is not valid Unicode (lone surrogate)\", file.path);\n }\n }\n return inModule(() => {\n const builder = new BundleBuilder();\n for (const file of files) builder.addFile(file.path, file.data);\n try {\n return builder.build(JSON.stringify(manifest), privateKeyPkcs8);\n } catch (error) {\n if (typeof error !== \"string\") throw error;\n const { kind, message, path } = JSON.parse(error) as { kind: BundleErrorKind; message: string; path?: string };\n throw new BundleError(kind, message, path);\n }\n });\n}\n","// Signing and packaging of extension bundles, format `haextension-bundle/2` (Node.js only).\nimport { webcrypto } from \"crypto\";\nimport * as fs from \"fs/promises\";\nimport * as path from \"path\";\nimport { getExtensionDir, readHaextensionConfig } from \"~/config\";\nimport { readManifest } from \"~/manifest\";\nimport {\n BUNDLE_FILE_EXTENSION,\n BundleError,\n buildBundle,\n maxBundleBytes,\n verifyBundle,\n type BundleEntry,\n type BundleErrorKind,\n type SignedFile,\n type VerifiedBundle,\n} from \"~/bundle\";\n\nexport const EXTENSION_FILE_EXTENSION = BUNDLE_FILE_EXTENSION;\n\nexport type PackageVerifyResult =\n | { valid: true; manifest: Record<string, unknown>; files: SignedFile[] }\n | { valid: false; kind: BundleErrorKind | \"io_error\"; path?: string; error: string };\n\n/** Files of the extension directory that never go into a bundle or are generated by signing. */\nconst EXTENSION_DIR_SKIPPED = new Set([\"manifest.json\", \"signature.json\", \"public.key\", \"private.key\"]);\n\nexport class ExtensionSigner {\n /** Generates an Ed25519 keypair: raw public key and PKCS#8 private key, both hex. */\n static async generateKeypair(): Promise<{ publicKey: string; privateKey: string }> {\n const keypair = (await webcrypto.subtle.generateKey({ name: \"Ed25519\" }, true, [\n \"sign\",\n \"verify\",\n ])) as unknown as CryptoKeyPair;\n const publicKeyBuffer = await webcrypto.subtle.exportKey(\"raw\", keypair.publicKey);\n const privateKeyBuffer = await webcrypto.subtle.exportKey(\"pkcs8\", keypair.privateKey);\n return {\n publicKey: Buffer.from(publicKeyBuffer).toString(\"hex\"),\n privateKey: Buffer.from(privateKeyBuffer).toString(\"hex\"),\n };\n }\n\n /**\n * Collects the regular files below `rootDir` with `lstat`, so a symlink is\n * never followed: it aborts packaging, as does any other non-regular file.\n * Paths are relative to `rootDir`, `/`-separated and prefixed with `prefix`.\n */\n static async collectFilesAsync(\n rootDir: string,\n prefix = \"\",\n skip: (relativePath: string) => boolean = () => false,\n ): Promise<BundleEntry[]> {\n const entries: BundleEntry[] = [];\n const walk = async (dir: string): Promise<void> => {\n for (const name of await fs.readdir(dir)) {\n const fullPath = path.join(dir, name);\n const relative = path.relative(rootDir, fullPath).split(path.sep).join(\"/\");\n const stats = await fs.lstat(fullPath);\n if (stats.isSymbolicLink()) {\n throw new BundleError(\"entry_kind\", `symlinks are not allowed in a bundle: ${fullPath}`, relative);\n }\n if (stats.isDirectory()) {\n await walk(fullPath);\n } else if (!stats.isFile()) {\n throw new BundleError(\"entry_kind\", `not a regular file: ${fullPath}`, relative);\n } else if (!skip(relative)) {\n entries.push({ path: `${prefix}${relative}`, data: new Uint8Array(await fs.readFile(fullPath)) });\n }\n }\n };\n await walk(rootDir);\n return entries;\n }\n\n /**\n * Builds, signs and writes a v2 bundle from the build output `extensionPath`,\n * the extension directory (manifest and extra files, never keys) and the\n * migrations, then verifies the written file. Returns the output path.\n */\n static async packageExtension(extensionPath: string, privateKeyHex: string, outputPath?: string): Promise<string> {\n const rootDir = process.cwd();\n const extensionDir = getExtensionDir(rootDir);\n const manifest = readManifest({ rootDir, extensionDir });\n if (!manifest) throw new Error(\"Failed to read manifest.json\");\n\n const files = await this.collectFilesAsync(extensionPath);\n files.push(\n ...(await this.collectFilesAsync(path.resolve(rootDir, extensionDir), \"haextension/\", (relative) =>\n EXTENSION_DIR_SKIPPED.has(relative),\n )),\n );\n\n // `./db/` and `db` name the same folder; the manifest and the bundle paths must both use `db`.\n manifest.migrationsDir = manifest.migrationsDir?.replace(/^(?:\\.\\/)+/, \"\").replace(/\\/+$/, \"\") || null;\n if (manifest.migrationsDir) {\n const config = readHaextensionConfig(rootDir);\n const sourceDir = config?.build?.migrationsSourceDir || `app/${manifest.migrationsDir}`;\n const sourcePath = path.resolve(rootDir, sourceDir);\n const exists = await fs.stat(sourcePath).then(\n (stats) => stats.isDirectory(),\n () => false,\n );\n if (exists) {\n files.push(...(await this.collectFilesAsync(sourcePath, `${manifest.migrationsDir}/`)));\n console.log(`✓ Adding migrations from ${sourceDir} as ${manifest.migrationsDir}`);\n } else {\n console.warn(`⚠ Migrations directory not found: ${sourcePath}`);\n }\n }\n\n const privateKey = privateKeyHex.trim();\n if (!/^(?:[0-9a-fA-F]{2})+$/.test(privateKey)) throw new Error(\"private key is not hex\");\n // Signs, writes the archive and verifies it like a host before returning it.\n const archive = buildBundle(\n files,\n manifest as unknown as Record<string, unknown>,\n Buffer.from(privateKey, \"hex\"),\n );\n const finalOutputPath = outputPath || `${manifest.name}-${manifest.version}${BUNDLE_FILE_EXTENSION}`;\n await fs.writeFile(finalOutputPath, archive);\n console.log(`✓ Extension packaged: ${finalOutputPath} (${files.length + 2} files)`);\n return finalOutputPath;\n }\n\n /** Reads and verifies a `.xt` file; throws a `BundleError` naming the first failing rule. */\n private static async verifyFileAsync(packagePath: string): Promise<VerifiedBundle> {\n const { size } = await fs.stat(packagePath);\n if (size > maxBundleBytes()) {\n throw new BundleError(\"archive_too_large\", `archive is larger than ${maxBundleBytes()} bytes`);\n }\n return verifyBundle(await fs.readFile(packagePath));\n }\n\n /** Verifies a `.xt` file exactly like a host does (bundle format v2). */\n static async verifyPackage(packagePath: string): Promise<PackageVerifyResult> {\n try {\n const { manifest, files } = await this.verifyFileAsync(packagePath);\n return { valid: true, manifest, files };\n } catch (error) {\n if (error instanceof BundleError) {\n return { valid: false, kind: error.kind, path: error.path, error: error.message };\n }\n // Only a failing file system call is an I/O error; anything else is a bug and propagates.\n if (error instanceof Error && \"code\" in error) {\n return { valid: false, kind: \"io_error\", error: error.message };\n }\n throw error;\n }\n }\n}\n","#!/usr/bin/env node\n// `haex`: extension development tools of @haex-space/vault-sdk\n\nimport { Command } from \"commander\";\nimport * as fs from \"fs/promises\";\nimport * as path from \"path\";\nimport { ExtensionSigner, EXTENSION_FILE_EXTENSION } from \"~/crypto/signing\";\nimport { existsSync } from \"fs\";\n\nconst program = new Command();\n\nprogram\n .name(\"haex\")\n .description(\"haex extension development tools\")\n .version(\"1.0.0\");\n\nprogram\n .command(\"init\")\n .description(\"Initialize a new haex extension in your project\")\n .option(\"-n, --name <name>\", \"Extension name\")\n .option(\"-d, --description <desc>\", \"Extension description\")\n .option(\"--author <author>\", \"Extension author\")\n .option(\"--dir <dir>\", \"Extension directory\", \"./haextension\")\n .action(async (options) => {\n try {\n const cwd = process.cwd();\n const extDir = path.resolve(cwd, options.dir);\n\n // Check if haextension directory already exists\n if (existsSync(extDir)) {\n console.error(`❌ Directory ${options.dir} already exists!`);\n process.exit(1);\n }\n\n // Read package.json if it exists\n interface PackageJson {\n name?: string;\n description?: string;\n scripts?: Record<string, string>;\n build?: string;\n }\n let packageJson: PackageJson = {};\n const packageJsonPath = path.join(cwd, \"package.json\");\n if (existsSync(packageJsonPath)) {\n const content = await fs.readFile(packageJsonPath, \"utf-8\");\n packageJson = JSON.parse(content) as PackageJson;\n }\n\n console.log(\"🚀 Initializing haex extension...\\n\");\n\n // 1. Create haextension directory\n await fs.mkdir(extDir, { recursive: true });\n console.log(`✓ Created directory: ${options.dir}`);\n\n // 2. Generate keypair\n const { publicKey, privateKey } = await ExtensionSigner.generateKeypair();\n await fs.writeFile(path.join(extDir, \"public.key\"), publicKey);\n await fs.writeFile(path.join(extDir, \"private.key\"), privateKey);\n console.log(\"✓ Generated keypair\");\n\n // 3. Create manifest.json (only required fields, optional fields come from package.json)\n const manifest: Record<string, unknown> = {\n publicKey: publicKey,\n permissions: {\n database: [],\n filesystem: [],\n http: [],\n shell: [],\n },\n singleInstance: false,\n displayMode: \"auto\",\n };\n\n // Only add description if provided via CLI or not in package.json\n if (options.description) {\n manifest.description = options.description;\n } else if (!packageJson.description) {\n manifest.description = \"A haex extension\";\n }\n\n await fs.writeFile(\n path.join(extDir, \"manifest.json\"),\n JSON.stringify(manifest, null, 2)\n );\n console.log(\"✓ Created manifest.json\");\n\n // 4. Create/update .gitignore\n const gitignorePath = path.join(cwd, \".gitignore\");\n // Remove leading ./ from dir path for gitignore\n const gitignoreDir = options.dir.replace(/^\\.\\//, '');\n const gitignoreEntries = [\n \"\\n# haex extension\",\n `${gitignoreDir}/private.key`,\n `*${EXTENSION_FILE_EXTENSION}`,\n ];\n\n if (existsSync(gitignorePath)) {\n const existing = await fs.readFile(gitignorePath, \"utf-8\");\n if (!existing.includes(`${gitignoreDir}/private.key`)) {\n await fs.appendFile(gitignorePath, gitignoreEntries.join(\"\\n\"));\n console.log(\"✓ Updated .gitignore\");\n }\n } else {\n await fs.writeFile(gitignorePath, gitignoreEntries.join(\"\\n\"));\n console.log(\"✓ Created .gitignore\");\n }\n\n // 5. Create haextension.config.json\n const config = {\n dev: {\n port: 5173,\n host: \"localhost\",\n haextension_dir: options.dir,\n },\n keys: {\n public_key_path: `${options.dir}/public.key`,\n private_key_path: `${options.dir}/private.key`,\n },\n build: {\n distDir: \"dist\",\n },\n };\n\n await fs.writeFile(\n path.join(cwd, \"haextension.config.json\"),\n JSON.stringify(config, null, 2)\n );\n console.log(\"✓ Created haextension.config.json\");\n\n // 6. Update package.json scripts\n if (existsSync(packageJsonPath)) {\n packageJson.scripts = packageJson.scripts || {};\n packageJson.scripts[\"ext:dev\"] =\n packageJson.scripts[\"ext:dev\"] || packageJson.scripts.dev || \"vite\";\n packageJson.scripts[\"ext:build\"] =\n packageJson.scripts[\"ext:build\"] ||\n `${packageJson.scripts.build || \"vite build\"} && haex sign dist -k ${options.dir}/private.key`;\n\n await fs.writeFile(\n packageJsonPath,\n JSON.stringify(packageJson, null, 2)\n );\n console.log(\"✓ Updated package.json scripts\");\n }\n\n console.log(\"\\n✨ Extension initialized successfully!\\n\");\n console.log(\"📝 Next steps:\");\n console.log(` 1. Edit ${options.dir}/manifest.json to configure your extension`);\n console.log(\" 2. Run 'npm run ext:dev' to start development mode\");\n console.log(\" 3. Run 'npm run ext:build' to build and sign your extension\");\n console.log(\"\\n⚠️ Important: Never commit your private key:\");\n console.log(` - ${options.dir}/private.key has been added to .gitignore`);\n console.log(\" - haextension.config.json is safe to commit (contains only paths)\\n\");\n } catch (error) {\n console.error(\"❌ Error:\", error);\n process.exit(1);\n }\n });\n\nprogram\n .command(\"keygen\")\n .description(\"Generate a new keypair for signing extensions\")\n .option(\"-o, --output <path>\", \"Output directory\", \"./haextension\")\n .action(async (options) => {\n const { publicKey, privateKey } = await ExtensionSigner.generateKeypair();\n\n const keyDir = path.resolve(options.output);\n await fs.mkdir(keyDir, { recursive: true });\n\n await fs.writeFile(path.join(keyDir, \"public.key\"), publicKey);\n await fs.writeFile(path.join(keyDir, \"private.key\"), privateKey);\n\n console.log(\"✓ Keypair generated:\");\n console.log(` Public: ${path.join(keyDir, \"public.key\")}`);\n console.log(` Private: ${path.join(keyDir, \"private.key\")}`);\n console.log(\"\\n⚠️ Keep your private key safe and never commit it!\");\n });\n\nprogram\n .command(\"sign <extension-path>\")\n .description(\"Sign and package an extension\")\n .option(\"-k, --key <path>\", \"Private key file\", \"./haextension/private.key\")\n .option(\"-o, --output <path>\", `Output path for the ${EXTENSION_FILE_EXTENSION} file`)\n .action(async (extensionPath, options) => {\n try {\n const privateKey = await fs.readFile(options.key, \"utf-8\");\n const outputPath = await ExtensionSigner.packageExtension(\n extensionPath,\n privateKey.trim(),\n options.output\n );\n console.log(`\\n✓ Extension signed and packaged: ${outputPath}`);\n } catch (error) {\n console.error(\"Error:\", error);\n process.exit(1);\n }\n });\n\nprogram\n .command(\"verify <file>\")\n .description(`Verify a signed ${EXTENSION_FILE_EXTENSION} bundle exactly like the host does`)\n .action(async (file: string) => {\n const result = await ExtensionSigner.verifyPackage(file);\n if (result.valid) {\n const { name, version, publicKey } = result.manifest;\n console.log(`valid: ${String(name)} ${String(version)}, ${result.files.length} files, key ${String(publicKey)}`);\n return;\n }\n const where = result.kind === \"file_mismatch\" ? ` { path: ${JSON.stringify(result.path)} }` : \"\";\n console.error(`invalid: ${result.kind}${where}\\n ${result.error}`);\n process.exit(1);\n });\n\nprogram.parse();\n"]}
1
+ {"version":3,"sources":["../../node_modules/.pnpm/tsup@9.0.0_jiti@2.7.0_postcss@8.5.31_typescript@6.0.3_yaml@2.9.0/node_modules/tsup/assets/esm_shims.js","../../src/config.ts","../../src/manifest.ts","../../src/bundle/wasm/haex_bundle.js","../../src/bundle/index.ts","../../src/crypto/signing.ts","../../src/cli/index.ts"],"names":["path","__dirname","resolvePath","readFileSync","ptr","existsSync","fs","path2","relative"],"mappings":";;;;;;;;;AAIA,IAAM,WAAA,GAAc,MAAM,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA;AACvD,IAAM,UAAA,GAAa,MAAMA,cAAA,CAAK,OAAA,CAAQ,aAAa,CAAA;AAE5C,IAAMC,8BAA4B,UAAA,EA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MAAA,CAAO,IAAA,KAAS,eAAA,GAAkB,CAAA,SAAA,EAAY,KAAK,SAAA,CAAU,MAAA,CAAO,IAAI,CAAC,CAAA,EAAA,CAAA,GAAO,EAAA;AAC9F,EAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,SAAA,EAAY,MAAA,CAAO,IAAI,GAAG,KAAK;AAAA,EAAA,EAAO,MAAA,CAAO,KAAK,CAAA,CAAE,CAAA;AAClE,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAChB,CAAC,CAAA;AAEH,OAAA,CAAQ,KAAA,EAAM","file":"index.mjs","sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * Utility to read haextension.config.json\n */\nimport { readFileSync, existsSync } from 'fs'\nimport { resolve } from 'path'\n\nexport interface HaextensionConfig {\n dev?: {\n port?: number\n host?: string\n haextension_dir?: string\n }\n keys?: {\n public_key_path?: string\n private_key_path?: string\n }\n build?: {\n distDir?: string\n /**\n * Source path for migrations directory (relative to project root).\n * If manifest.migrationsDir is set, this directory will be copied\n * to the bundle at the path specified in migrationsDir.\n * Default: \"app/{migrationsDir}\" (for Nuxt projects)\n * Example: \"app/database/migrations\" -> copies to \"database/migrations\" in bundle\n */\n migrationsSourceDir?: string\n }\n}\n\n/**\n * Read haextension.config.json from the project root\n * Returns null if file doesn't exist\n */\nexport function readHaextensionConfig(rootDir: string = process.cwd()): HaextensionConfig | null {\n const configPath = resolve(rootDir, 'haextension.config.json')\n \n if (!existsSync(configPath)) {\n return null\n }\n\n try {\n const content = readFileSync(configPath, 'utf-8')\n return JSON.parse(content)\n } catch (error) {\n console.warn(`Failed to parse haextension.config.json: ${error}`)\n return null\n }\n}\n\n/**\n * Get extension directory from config or use default\n */\nexport function getExtensionDir(rootDir: string = process.cwd()): string {\n const config = readHaextensionConfig(rootDir)\n return config?.dev?.haextension_dir || 'haextension'\n}\n","/**\n * Utility for reading and processing extension manifest files\n */\nimport { readFileSync } from \"node:fs\";\nimport { resolve as resolvePath } from \"node:path\";\nimport type { ExtensionManifest } from \"./types\";\n\nexport interface ReadManifestOptions {\n /** Root directory of the project */\n rootDir: string;\n /** Path to manifest.json (if not provided, will use extensionDir) */\n manifestPath?: string;\n /** Directory containing extension files (default: \"haextension\") */\n extensionDir?: string;\n}\n\n/**\n * Reads and processes the extension manifest.json file\n * Falls back to package.json version if manifest doesn't specify one\n */\nexport function readManifest(options: ReadManifestOptions): ExtensionManifest | null {\n const { rootDir, manifestPath, extensionDir = \"haextension\" } = options;\n\n // Determine manifest path\n const resolvedManifestPath = manifestPath\n ? resolvePath(rootDir, manifestPath)\n : resolvePath(rootDir, extensionDir, \"manifest.json\");\n\n try {\n const manifestContent = readFileSync(resolvedManifestPath, \"utf-8\");\n // `signature` belonged to the pre-v2 bundle format; signing now writes `haextension/signature.json`.\n const { signature: _legacySignature, ...parsed } = JSON.parse(manifestContent) as Partial<ExtensionManifest> & {\n signature?: unknown;\n };\n\n // Read fallback values from package.json\n let packageJson: { name?: string; version?: string; author?: string; homepage?: string } = {};\n try {\n const packageJsonPath = resolvePath(rootDir, \"package.json\");\n packageJson = JSON.parse(readFileSync(packageJsonPath, \"utf-8\"));\n } catch {\n console.warn(`[@haex-space/vault-sdk] Warning: Could not read package.json`);\n }\n\n // Always use package.json name as stable technical identifier\n // Display names are handled via i18n in the manifest\n const name = packageJson.name;\n const version = parsed.version ?? packageJson.version;\n const author = parsed.author ?? packageJson.author ?? null;\n const homepage = parsed.homepage ?? packageJson.homepage ?? null;\n\n if (!name) {\n console.warn(`[@haex-space/vault-sdk] Warning: No name found in manifest or package.json`);\n return null;\n }\n\n if (!version) {\n console.warn(`[@haex-space/vault-sdk] Warning: No version found in manifest or package.json`);\n return null;\n }\n\n const manifest: ExtensionManifest = {\n // Keep every field the developer wrote (e.g. displayName); the fallbacks below win.\n ...parsed,\n name,\n version,\n author,\n entry: parsed.entry ?? null,\n icon: parsed.icon ?? null,\n publicKey: parsed.publicKey ?? \"\",\n permissions: parsed.permissions ?? {\n database: [],\n filesystem: [],\n http: [],\n shell: [],\n },\n homepage,\n description: parsed.description ?? null,\n singleInstance: parsed.singleInstance ?? null,\n displayMode: parsed.displayMode ?? null,\n migrationsDir: parsed.migrationsDir ?? null,\n i18n: parsed.i18n ?? null,\n tools: parsed.tools ?? null,\n };\n\n console.log(`✓ [@haex-space/vault-sdk] Loaded ${resolvedManifestPath}`);\n return manifest;\n } catch {\n console.warn(\n `[@haex-space/vault-sdk] Warning: manifest.json not found at ${resolvedManifestPath}, extension info will not be available`\n );\n return null;\n }\n}\n","/* @ts-self-types=\"./haex_bundle.d.ts\" */\n\n/**\n * Collects the files of a bundle and builds the signed archive.\n */\nexport class BundleBuilder {\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n BundleBuilderFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_bundlebuilder_free(ptr, 0);\n }\n /**\n * Adds an app file (no control file).\n * @param {string} path\n * @param {Uint8Array} data\n */\n addFile(path, data) {\n const ptr0 = passStringToWasm0(path, wasm.__wbindgen_export, wasm.__wbindgen_export2);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(data, wasm.__wbindgen_export);\n const len1 = WASM_VECTOR_LEN;\n wasm.bundlebuilder_addFile(this.__wbg_ptr, ptr0, len0, ptr1, len1);\n }\n /**\n * Signs with the PKCS#8 Ed25519 key, writes the archive and verifies it. `manifest_json` is\n * the manifest without `signature`; its `publicKey` is set from the key. Throws the JSON of a\n * `BundleError` (`{kind, message, path?}`).\n * @param {string} manifest_json\n * @param {Uint8Array} private_key_pkcs8\n * @returns {Uint8Array}\n */\n build(manifest_json, private_key_pkcs8) {\n try {\n const ptr = this.__destroy_into_raw();\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(manifest_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(private_key_pkcs8, wasm.__wbindgen_export);\n const len1 = WASM_VECTOR_LEN;\n wasm.bundlebuilder_build(retptr, ptr, ptr0, len0, ptr1, len1);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v3 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_export3(r0, r1 * 1, 1);\n return v3;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n constructor() {\n const ret = wasm.bundlebuilder_new();\n this.__wbg_ptr = ret;\n BundleBuilderFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n}\nif (Symbol.dispose) BundleBuilder.prototype[Symbol.dispose] = BundleBuilder.prototype.free;\n\n/**\n * Every error kind as JSON array, so the SDK can test its `BundleErrorKind` type against it.\n * @returns {string}\n */\nexport function errorKinds() {\n let deferred1_0;\n let deferred1_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.errorKinds(retptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n deferred1_0 = r0;\n deferred1_1 = r1;\n return getStringFromWasm0(r0, r1);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_export3(deferred1_0, deferred1_1, 1);\n }\n}\n\n/**\n * Largest archive a host accepts, so callers can refuse a bigger file before reading it.\n * @returns {number}\n */\nexport function maxArchiveBytes() {\n const ret = wasm.maxArchiveBytes();\n return ret;\n}\n\n/**\n * Verifies a `.xt` archive exactly like a host does. Returns\n * `{\"valid\":true,\"manifest\":…,\"files\":[…],\"migrations\":[…]}` or\n * `{\"valid\":false,\"kind\":…,\"message\":…,\"path\"?:…}`.\n * @param {Uint8Array} archive\n * @returns {string}\n */\nexport function verifyArchive(archive) {\n let deferred2_0;\n let deferred2_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(archive, wasm.__wbindgen_export);\n const len0 = WASM_VECTOR_LEN;\n wasm.verifyArchive(retptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n deferred2_0 = r0;\n deferred2_1 = r1;\n return getStringFromWasm0(r0, r1);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_export3(deferred2_0, deferred2_1, 1);\n }\n}\nfunction __wbg_get_imports() {\n const import0 = {\n __proto__: null,\n __wbg___wbindgen_throw_41e9ee4f547fc59a: function(arg0, arg1) {\n throw new Error(getStringFromWasm0(arg0, arg1));\n },\n __wbindgen_generic_0000000000000001: function(arg0, arg1) {\n // Cast intrinsic for `Ref(String) -> Externref`.\n const ret = getStringFromWasm0(arg0, arg1);\n return addHeapObject(ret);\n },\n };\n return {\n __proto__: null,\n \"./haex_bundle_bg.js\": import0,\n };\n}\n\nconst BundleBuilderFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_bundlebuilder_free(ptr, 1));\n\nfunction addHeapObject(obj) {\n if (heap_next === heap.length) heap.push(heap.length + 1);\n const idx = heap_next;\n heap_next = heap[idx];\n\n heap[idx] = obj;\n return idx;\n}\n\nfunction dropObject(idx) {\n if (idx < 1028) return;\n heap[idx] = heap_next;\n heap_next = idx;\n}\n\nfunction getArrayU8FromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);\n}\n\nlet cachedDataViewMemory0 = null;\nfunction getDataViewMemory0() {\n if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {\n cachedDataViewMemory0 = new DataView(wasm.memory.buffer);\n }\n return cachedDataViewMemory0;\n}\n\nfunction getStringFromWasm0(ptr, len) {\n return decodeText(ptr >>> 0, len);\n}\n\nlet cachedUint8ArrayMemory0 = null;\nfunction getUint8ArrayMemory0() {\n if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {\n cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);\n }\n return cachedUint8ArrayMemory0;\n}\n\nfunction getObject(idx) { return heap[idx]; }\n\nlet heap = new Array(1024).fill(undefined);\nheap.push(undefined, null, true, false);\n\nlet heap_next = heap.length;\n\nfunction passArray8ToWasm0(arg, malloc) {\n const ptr = malloc(arg.length * 1, 1) >>> 0;\n getUint8ArrayMemory0().set(arg, ptr / 1);\n WASM_VECTOR_LEN = arg.length;\n return ptr;\n}\n\nfunction passStringToWasm0(arg, malloc, realloc) {\n if (realloc === undefined) {\n const buf = cachedTextEncoder.encode(arg);\n const ptr = malloc(buf.length, 1) >>> 0;\n getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);\n WASM_VECTOR_LEN = buf.length;\n return ptr;\n }\n\n let len = arg.length;\n let ptr = malloc(len, 1) >>> 0;\n\n const mem = getUint8ArrayMemory0();\n\n let offset = 0;\n\n for (; offset < len; offset++) {\n const code = arg.charCodeAt(offset);\n if (code > 0x7F) break;\n mem[ptr + offset] = code;\n }\n if (offset !== len) {\n if (offset !== 0) {\n arg = arg.slice(offset);\n }\n ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;\n const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);\n const ret = cachedTextEncoder.encodeInto(arg, view);\n\n offset += ret.written;\n ptr = realloc(ptr, len, offset, 1) >>> 0;\n }\n\n WASM_VECTOR_LEN = offset;\n return ptr;\n}\n\nfunction takeObject(idx) {\n const ret = getObject(idx);\n dropObject(idx);\n return ret;\n}\n\nlet cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\ncachedTextDecoder.decode();\nconst MAX_SAFARI_DECODE_BYTES = 2146435072;\nlet numBytesDecoded = 0;\nfunction decodeText(ptr, len) {\n numBytesDecoded += len;\n if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {\n cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\n cachedTextDecoder.decode();\n numBytesDecoded = len;\n }\n return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));\n}\n\nconst cachedTextEncoder = new TextEncoder();\n\nif (!('encodeInto' in cachedTextEncoder)) {\n cachedTextEncoder.encodeInto = function (arg, view) {\n const buf = cachedTextEncoder.encode(arg);\n view.set(buf);\n return {\n read: arg.length,\n written: buf.length\n };\n };\n}\n\nlet WASM_VECTOR_LEN = 0;\n\nlet wasmModule, wasmInstance, wasm;\nfunction __wbg_finalize_init(instance, module) {\n wasmInstance = instance;\n wasm = instance.exports;\n wasmModule = module;\n cachedDataViewMemory0 = null;\n cachedUint8ArrayMemory0 = null;\n return wasm;\n}\n\nasync function __wbg_load(module, imports) {\n if (typeof Response === 'function' && module instanceof Response) {\n if (!module.ok) {\n throw new Error(`failed to fetch Wasm: ${module.status} ${module.statusText} fetching '${module.url}'`);\n }\n\n if (typeof WebAssembly.instantiateStreaming === 'function') {\n try {\n return await WebAssembly.instantiateStreaming(module, imports);\n } catch (e) {\n const validResponse = expectedResponseType(module.type);\n\n if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {\n console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n } else { throw e; }\n }\n }\n\n const bytes = await module.arrayBuffer();\n return await WebAssembly.instantiate(bytes, imports);\n } else {\n const instance = await WebAssembly.instantiate(module, imports);\n\n if (instance instanceof WebAssembly.Instance) {\n return { instance, module };\n } else {\n return instance;\n }\n }\n\n function expectedResponseType(type) {\n switch (type) {\n case 'basic': case 'cors': case 'default': return true;\n }\n return false;\n }\n}\n\nfunction initSync(module) {\n if (wasm !== undefined) return wasm;\n\n\n if (module !== undefined) {\n if (Object.getPrototypeOf(module) === Object.prototype) {\n ({module} = module)\n } else {\n console.warn('using deprecated parameters for `initSync()`; pass a single object instead')\n }\n }\n\n const imports = __wbg_get_imports();\n if (!(module instanceof WebAssembly.Module)) {\n module = new WebAssembly.Module(module);\n }\n const instance = new WebAssembly.Instance(module, imports);\n return __wbg_finalize_init(instance, module);\n}\n\nasync function __wbg_init(module_or_path) {\n if (wasm !== undefined) return wasm;\n\n\n if (module_or_path !== undefined) {\n if (Object.getPrototypeOf(module_or_path) === Object.prototype) {\n ({module_or_path} = module_or_path)\n } else {\n console.warn('using deprecated parameters for the initialization function; pass a single object instead')\n }\n }\n\n if (module_or_path === undefined) {\n module_or_path = new URL('haex_bundle_bg.wasm', import.meta.url);\n }\n const imports = __wbg_get_imports();\n\n if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {\n module_or_path = fetch(module_or_path);\n }\n\n const { instance, module } = await __wbg_load(await module_or_path, imports);\n\n return __wbg_finalize_init(instance, module);\n}\n\nexport { initSync, __wbg_init as default };\n","/**\n * Bundle format `haextension-bundle/2` for the `haex` tool (Node.js only).\n *\n * Every rule lives in the Rust crate `crates/haex-bundle`, which hosts such as holzi use natively;\n * this module only calls its WebAssembly build (`pnpm build:wasm`). Nothing of the format is\n * implemented here, so the tool and the hosts cannot drift apart.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { BundleBuilder, initSync, maxArchiveBytes, verifyArchive } from \"./wasm/haex_bundle\";\n\nexport const BUNDLE_FILE_EXTENSION = \".xt\";\n\n/** The error kinds of the crate (`ErrorKind::ALL`, checked by `src/bundle/__tests__/wasm.test.ts`). */\nexport const BUNDLE_ERROR_KINDS = [\n \"archive_too_large\",\n \"archive_invalid\",\n \"entry_path_invalid\",\n \"entry_duplicate\",\n \"entry_too_large\",\n \"entry_ratio\",\n \"entry_kind\",\n \"manifest_not_canonical\",\n \"manifest_invalid\",\n \"file_mismatch\",\n \"public_key_mismatch\",\n \"signature_invalid\",\n \"legacy_signature_format\",\n] as const;\n\nexport type BundleErrorKind = (typeof BUNDLE_ERROR_KINDS)[number];\n\n/** One file of a bundle: its path inside the archive and its exact bytes. */\nexport interface BundleEntry {\n path: string;\n data: Uint8Array;\n}\n\nexport interface SignedFile {\n path: string;\n sha256: string;\n size: number;\n}\n\nexport interface VerifiedBundle {\n manifest: Record<string, unknown>;\n /** Every entry except `signature.json`, in UTF-8 byte order. */\n files: SignedFile[];\n /** The migrations in the order they apply. */\n migrations: { name: string; path: string }[];\n}\n\n/**\n * A rejected bundle. `kind` is one of the error kinds of `test-vectors/bundles/README.md`;\n * `path` names the entry for entry-level errors and the first differing file for `file_mismatch`.\n */\nexport class BundleError extends Error {\n constructor(\n public readonly kind: BundleErrorKind,\n message: string,\n public readonly path?: string,\n ) {\n super(`${kind}: ${message}`);\n this.name = \"BundleError\";\n }\n}\n\nconst WASM_FILE = \"haex_bundle_bg.wasm\";\n\n/**\n * The module ships once as `dist/haex_bundle_bg.wasm`. The bundled entries live in `dist/` and\n * `dist/cli/`; from the sources (tests) it is the generated `wasm/` folder next to this file.\n */\nfunction wasmPath(): string {\n const candidates = [join(__dirname, WASM_FILE), join(__dirname, \"..\", WASM_FILE), join(__dirname, \"wasm\", WASM_FILE)];\n const found = candidates.find((candidate) => existsSync(candidate));\n if (!found) throw new Error(`${WASM_FILE} not found next to ${__dirname}; run \\`pnpm build:wasm\\``);\n return found;\n}\n\nlet state: \"new\" | \"ready\" | \"crashed\" = \"new\";\n\n/**\n * Runs `call` in the module. A panic in Rust traps (`panic = \"abort\"`) and leaves the instance in\n * an undefined state, so the module is not used again in this process.\n */\nfunction inModule<T>(call: () => T): T {\n if (state === \"crashed\") throw new Error(\"haex-bundle crashed earlier in this process; restart it\");\n if (state === \"new\") {\n initSync({ module: readFileSync(wasmPath()) });\n state = \"ready\";\n }\n try {\n return call();\n } catch (error) {\n if (error instanceof WebAssembly.RuntimeError) {\n state = \"crashed\";\n throw new Error(`haex-bundle crashed (a bug, please report it): ${error.message}`, { cause: error });\n }\n throw error;\n }\n}\n\n/** Largest `.xt` file a host accepts; check it before reading a file into memory. */\nexport function maxBundleBytes(): number {\n return inModule(() => maxArchiveBytes());\n}\n\n/** Verifies a `.xt` archive exactly like a host does. Throws a `BundleError` for the first failing rule. */\nexport function verifyBundle(archive: Uint8Array): VerifiedBundle {\n const result = JSON.parse(inModule(() => verifyArchive(archive))) as\n | ({ valid: true } & VerifiedBundle)\n | { valid: false; kind: BundleErrorKind; message: string; path?: string };\n if (!result.valid) throw new BundleError(result.kind, result.message, result.path);\n return { manifest: result.manifest, files: result.files, migrations: result.migrations };\n}\n\n/** A lone UTF-16 surrogate, which would silently become U+FFFD on the way into the module. */\nconst LONE_SURROGATE = /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/;\n\n/**\n * Signs the app files with the manifest (without `signature`; its `publicKey` is set from the\n * key), writes the deterministic archive and verifies it. `privateKeyPkcs8` is the Ed25519 key\n * as `haex keygen` writes it. Throws a `BundleError`.\n */\nexport function buildBundle(\n files: readonly BundleEntry[],\n manifest: Record<string, unknown>,\n privateKeyPkcs8: Uint8Array,\n): Uint8Array {\n for (const file of files) {\n if (LONE_SURROGATE.test(file.path)) {\n throw new BundleError(\"entry_path_invalid\", \"path is not valid Unicode (lone surrogate)\", file.path);\n }\n }\n return inModule(() => {\n const builder = new BundleBuilder();\n for (const file of files) builder.addFile(file.path, file.data);\n try {\n return builder.build(JSON.stringify(manifest), privateKeyPkcs8);\n } catch (error) {\n if (typeof error !== \"string\") throw error;\n const { kind, message, path } = JSON.parse(error) as { kind: BundleErrorKind; message: string; path?: string };\n throw new BundleError(kind, message, path);\n }\n });\n}\n","// Signing and packaging of extension bundles, format `haextension-bundle/2` (Node.js only).\nimport { webcrypto } from \"crypto\";\nimport * as fs from \"fs/promises\";\nimport * as path from \"path\";\nimport { getExtensionDir, readHaextensionConfig } from \"~/config\";\nimport { readManifest } from \"~/manifest\";\nimport {\n BUNDLE_FILE_EXTENSION,\n BundleError,\n buildBundle,\n maxBundleBytes,\n verifyBundle,\n type BundleEntry,\n type BundleErrorKind,\n type SignedFile,\n type VerifiedBundle,\n} from \"~/bundle\";\n\nexport const EXTENSION_FILE_EXTENSION = BUNDLE_FILE_EXTENSION;\n\nexport type PackageVerifyResult =\n | { valid: true; manifest: Record<string, unknown>; files: SignedFile[] }\n | { valid: false; kind: BundleErrorKind | \"io_error\"; path?: string; error: string };\n\n/** Files of the extension directory that never go into a bundle or are generated by signing. */\nconst EXTENSION_DIR_SKIPPED = new Set([\"manifest.json\", \"signature.json\", \"public.key\", \"private.key\"]);\n\nexport class ExtensionSigner {\n /** Generates an Ed25519 keypair: raw public key and PKCS#8 private key, both hex. */\n static async generateKeypair(): Promise<{ publicKey: string; privateKey: string }> {\n const keypair = (await webcrypto.subtle.generateKey({ name: \"Ed25519\" }, true, [\n \"sign\",\n \"verify\",\n ])) as unknown as CryptoKeyPair;\n const publicKeyBuffer = await webcrypto.subtle.exportKey(\"raw\", keypair.publicKey);\n const privateKeyBuffer = await webcrypto.subtle.exportKey(\"pkcs8\", keypair.privateKey);\n return {\n publicKey: Buffer.from(publicKeyBuffer).toString(\"hex\"),\n privateKey: Buffer.from(privateKeyBuffer).toString(\"hex\"),\n };\n }\n\n /**\n * Collects the regular files below `rootDir` with `lstat`, so a symlink is\n * never followed: it aborts packaging, as does any other non-regular file.\n * Paths are relative to `rootDir`, `/`-separated and prefixed with `prefix`.\n */\n static async collectFilesAsync(\n rootDir: string,\n prefix = \"\",\n skip: (relativePath: string) => boolean = () => false,\n ): Promise<BundleEntry[]> {\n const entries: BundleEntry[] = [];\n const walk = async (dir: string): Promise<void> => {\n for (const name of await fs.readdir(dir)) {\n const fullPath = path.join(dir, name);\n const relative = path.relative(rootDir, fullPath).split(path.sep).join(\"/\");\n const stats = await fs.lstat(fullPath);\n if (stats.isSymbolicLink()) {\n throw new BundleError(\"entry_kind\", `symlinks are not allowed in a bundle: ${fullPath}`, relative);\n }\n if (stats.isDirectory()) {\n await walk(fullPath);\n } else if (!stats.isFile()) {\n throw new BundleError(\"entry_kind\", `not a regular file: ${fullPath}`, relative);\n } else if (!skip(relative)) {\n entries.push({ path: `${prefix}${relative}`, data: new Uint8Array(await fs.readFile(fullPath)) });\n }\n }\n };\n await walk(rootDir);\n return entries;\n }\n\n /**\n * Builds, signs and writes a v2 bundle from the build output `extensionPath`,\n * the extension directory (manifest and extra files, never keys) and the\n * migrations, then verifies the written file. Returns the output path.\n */\n static async packageExtension(extensionPath: string, privateKeyHex: string, outputPath?: string): Promise<string> {\n const rootDir = process.cwd();\n const extensionDir = getExtensionDir(rootDir);\n const manifest = readManifest({ rootDir, extensionDir });\n if (!manifest) throw new Error(\"Failed to read manifest.json\");\n\n const files = await this.collectFilesAsync(extensionPath);\n files.push(\n ...(await this.collectFilesAsync(path.resolve(rootDir, extensionDir), \"haextension/\", (relative) =>\n EXTENSION_DIR_SKIPPED.has(relative),\n )),\n );\n\n // `./db/` and `db` name the same folder; the manifest and the bundle paths must both use `db`.\n manifest.migrationsDir = manifest.migrationsDir?.replace(/^(?:\\.\\/)+/, \"\").replace(/\\/+$/, \"\") || null;\n if (manifest.migrationsDir) {\n const config = readHaextensionConfig(rootDir);\n const sourceDir = config?.build?.migrationsSourceDir || `app/${manifest.migrationsDir}`;\n const sourcePath = path.resolve(rootDir, sourceDir);\n const exists = await fs.stat(sourcePath).then(\n (stats) => stats.isDirectory(),\n () => false,\n );\n if (exists) {\n files.push(...(await this.collectFilesAsync(sourcePath, `${manifest.migrationsDir}/`)));\n console.log(`✓ Adding migrations from ${sourceDir} as ${manifest.migrationsDir}`);\n } else {\n console.warn(`⚠ Migrations directory not found: ${sourcePath}`);\n }\n }\n\n const privateKey = privateKeyHex.trim();\n if (!/^(?:[0-9a-fA-F]{2})+$/.test(privateKey)) throw new Error(\"private key is not hex\");\n // Signs, writes the archive and verifies it like a host before returning it.\n const archive = buildBundle(\n files,\n manifest as unknown as Record<string, unknown>,\n Buffer.from(privateKey, \"hex\"),\n );\n const finalOutputPath = outputPath || `${manifest.name}-${manifest.version}${BUNDLE_FILE_EXTENSION}`;\n await fs.writeFile(finalOutputPath, archive);\n console.log(`✓ Extension packaged: ${finalOutputPath} (${files.length + 2} files)`);\n return finalOutputPath;\n }\n\n /** Reads and verifies a `.xt` file; throws a `BundleError` naming the first failing rule. */\n private static async verifyFileAsync(packagePath: string): Promise<VerifiedBundle> {\n const { size } = await fs.stat(packagePath);\n if (size > maxBundleBytes()) {\n throw new BundleError(\"archive_too_large\", `archive is larger than ${maxBundleBytes()} bytes`);\n }\n return verifyBundle(await fs.readFile(packagePath));\n }\n\n /** Verifies a `.xt` file exactly like a host does (bundle format v2). */\n static async verifyPackage(packagePath: string): Promise<PackageVerifyResult> {\n try {\n const { manifest, files } = await this.verifyFileAsync(packagePath);\n return { valid: true, manifest, files };\n } catch (error) {\n if (error instanceof BundleError) {\n return { valid: false, kind: error.kind, path: error.path, error: error.message };\n }\n // Only a failing file system call is an I/O error; anything else is a bug and propagates.\n if (error instanceof Error && \"code\" in error) {\n return { valid: false, kind: \"io_error\", error: error.message };\n }\n throw error;\n }\n }\n}\n","#!/usr/bin/env node\n// `haex`: extension development tools of @haex-space/vault-sdk\n\nimport { Command } from \"commander\";\nimport * as fs from \"fs/promises\";\nimport * as path from \"path\";\nimport { ExtensionSigner, EXTENSION_FILE_EXTENSION } from \"~/crypto/signing\";\nimport { existsSync } from \"fs\";\n\nconst program = new Command();\n\nprogram\n .name(\"haex\")\n .description(\"haex extension development tools\")\n .version(\"1.0.0\");\n\nprogram\n .command(\"init\")\n .description(\"Initialize a new haex extension in your project\")\n .option(\"-n, --name <name>\", \"Extension name\")\n .option(\"-d, --description <desc>\", \"Extension description\")\n .option(\"--author <author>\", \"Extension author\")\n .option(\"--dir <dir>\", \"Extension directory\", \"./haextension\")\n .action(async (options) => {\n try {\n const cwd = process.cwd();\n const extDir = path.resolve(cwd, options.dir);\n\n // Check if haextension directory already exists\n if (existsSync(extDir)) {\n console.error(`❌ Directory ${options.dir} already exists!`);\n process.exit(1);\n }\n\n // Read package.json if it exists\n interface PackageJson {\n name?: string;\n description?: string;\n scripts?: Record<string, string>;\n build?: string;\n }\n let packageJson: PackageJson = {};\n const packageJsonPath = path.join(cwd, \"package.json\");\n if (existsSync(packageJsonPath)) {\n const content = await fs.readFile(packageJsonPath, \"utf-8\");\n packageJson = JSON.parse(content) as PackageJson;\n }\n\n console.log(\"🚀 Initializing haex extension...\\n\");\n\n // 1. Create haextension directory\n await fs.mkdir(extDir, { recursive: true });\n console.log(`✓ Created directory: ${options.dir}`);\n\n // 2. Generate keypair\n const { publicKey, privateKey } = await ExtensionSigner.generateKeypair();\n await fs.writeFile(path.join(extDir, \"public.key\"), publicKey);\n await fs.writeFile(path.join(extDir, \"private.key\"), privateKey);\n console.log(\"✓ Generated keypair\");\n\n // 3. Create manifest.json (only required fields, optional fields come from package.json)\n const manifest: Record<string, unknown> = {\n publicKey: publicKey,\n permissions: {\n database: [],\n filesystem: [],\n http: [],\n shell: [],\n },\n singleInstance: false,\n displayMode: \"auto\",\n };\n\n // Only add description if provided via CLI or not in package.json\n if (options.description) {\n manifest.description = options.description;\n } else if (!packageJson.description) {\n manifest.description = \"A haex extension\";\n }\n\n await fs.writeFile(\n path.join(extDir, \"manifest.json\"),\n JSON.stringify(manifest, null, 2)\n );\n console.log(\"✓ Created manifest.json\");\n\n // 4. Create/update .gitignore\n const gitignorePath = path.join(cwd, \".gitignore\");\n // Remove leading ./ from dir path for gitignore\n const gitignoreDir = options.dir.replace(/^\\.\\//, '');\n const gitignoreEntries = [\n \"\\n# haex extension\",\n `${gitignoreDir}/private.key`,\n `*${EXTENSION_FILE_EXTENSION}`,\n ];\n\n if (existsSync(gitignorePath)) {\n const existing = await fs.readFile(gitignorePath, \"utf-8\");\n if (!existing.includes(`${gitignoreDir}/private.key`)) {\n await fs.appendFile(gitignorePath, gitignoreEntries.join(\"\\n\"));\n console.log(\"✓ Updated .gitignore\");\n }\n } else {\n await fs.writeFile(gitignorePath, gitignoreEntries.join(\"\\n\"));\n console.log(\"✓ Created .gitignore\");\n }\n\n // 5. Create haextension.config.json\n const config = {\n dev: {\n port: 5173,\n host: \"localhost\",\n haextension_dir: options.dir,\n },\n keys: {\n public_key_path: `${options.dir}/public.key`,\n private_key_path: `${options.dir}/private.key`,\n },\n build: {\n distDir: \"dist\",\n },\n };\n\n await fs.writeFile(\n path.join(cwd, \"haextension.config.json\"),\n JSON.stringify(config, null, 2)\n );\n console.log(\"✓ Created haextension.config.json\");\n\n // 6. Update package.json scripts\n if (existsSync(packageJsonPath)) {\n packageJson.scripts = packageJson.scripts || {};\n packageJson.scripts[\"ext:dev\"] =\n packageJson.scripts[\"ext:dev\"] || packageJson.scripts.dev || \"vite\";\n packageJson.scripts[\"ext:build\"] =\n packageJson.scripts[\"ext:build\"] ||\n `${packageJson.scripts.build || \"vite build\"} && haex sign dist -k ${options.dir}/private.key`;\n\n await fs.writeFile(\n packageJsonPath,\n JSON.stringify(packageJson, null, 2)\n );\n console.log(\"✓ Updated package.json scripts\");\n }\n\n console.log(\"\\n✨ Extension initialized successfully!\\n\");\n console.log(\"📝 Next steps:\");\n console.log(` 1. Edit ${options.dir}/manifest.json to configure your extension`);\n console.log(\" 2. Run 'npm run ext:dev' to start development mode\");\n console.log(\" 3. Run 'npm run ext:build' to build and sign your extension\");\n console.log(\"\\n⚠️ Important: Never commit your private key:\");\n console.log(` - ${options.dir}/private.key has been added to .gitignore`);\n console.log(\" - haextension.config.json is safe to commit (contains only paths)\\n\");\n } catch (error) {\n console.error(\"❌ Error:\", error);\n process.exit(1);\n }\n });\n\nprogram\n .command(\"keygen\")\n .description(\"Generate a new keypair for signing extensions\")\n .option(\"-o, --output <path>\", \"Output directory\", \"./haextension\")\n .action(async (options) => {\n const { publicKey, privateKey } = await ExtensionSigner.generateKeypair();\n\n const keyDir = path.resolve(options.output);\n await fs.mkdir(keyDir, { recursive: true });\n\n await fs.writeFile(path.join(keyDir, \"public.key\"), publicKey);\n await fs.writeFile(path.join(keyDir, \"private.key\"), privateKey);\n\n console.log(\"✓ Keypair generated:\");\n console.log(` Public: ${path.join(keyDir, \"public.key\")}`);\n console.log(` Private: ${path.join(keyDir, \"private.key\")}`);\n console.log(\"\\n⚠️ Keep your private key safe and never commit it!\");\n });\n\nprogram\n .command(\"sign <extension-path>\")\n .description(\"Sign and package an extension\")\n .option(\"-k, --key <path>\", \"Private key file\", \"./haextension/private.key\")\n .option(\"-o, --output <path>\", `Output path for the ${EXTENSION_FILE_EXTENSION} file`)\n .action(async (extensionPath, options) => {\n try {\n const privateKey = await fs.readFile(options.key, \"utf-8\");\n const outputPath = await ExtensionSigner.packageExtension(\n extensionPath,\n privateKey.trim(),\n options.output\n );\n console.log(`\\n✓ Extension signed and packaged: ${outputPath}`);\n } catch (error) {\n console.error(\"Error:\", error);\n process.exit(1);\n }\n });\n\nprogram\n .command(\"verify <file>\")\n .description(`Verify a signed ${EXTENSION_FILE_EXTENSION} bundle exactly like the host does`)\n .action(async (file: string) => {\n const result = await ExtensionSigner.verifyPackage(file);\n if (result.valid) {\n const { name, version, publicKey } = result.manifest;\n console.log(`valid: ${String(name)} ${String(version)}, ${result.files.length} files, key ${String(publicKey)}`);\n return;\n }\n const where = result.kind === \"file_mismatch\" ? ` { path: ${JSON.stringify(result.path)} }` : \"\";\n console.error(`invalid: ${result.kind}${where}\\n ${result.error}`);\n process.exit(1);\n });\n\nprogram.parse();\n"]}
@@ -1,4 +1,4 @@
1
- import { b as HaexHubEvent, c as EXTERNAL_EVENTS, D as DatabaseQueryResult, M as Migration, d as MigrationResult, W as WebRequestOptions, e as WebResponse, f as EventCallback, a as ExtensionManifest, H as HaexHubConfig, E as ExtensionInfo, A as ApplicationContext, g as DatabasePermissionRequest, P as PermissionResponse, S as SearchResult, R as RequestOptions } from './types-CYuW3glJ.js';
1
+ import { b as HaexHubEvent, c as EXTERNAL_EVENTS, D as DatabaseQueryResult, M as Migration, d as MigrationResult, W as WebRequestOptions, e as WebResponse, f as EventCallback, a as ExtensionManifest, H as HaexHubConfig, E as ExtensionInfo, A as ApplicationContext, g as DatabasePermissionRequest, P as PermissionResponse, S as SearchResult, R as RequestOptions } from './types-snPkjDCj.mjs';
2
2
  import { SqliteRemoteDatabase } from 'drizzle-orm/sqlite-proxy';
3
3
 
4
4
  /**
@@ -1676,6 +1676,133 @@ declare class ContactsAPI {
1676
1676
  photoAsync(hash: string): Promise<Uint8Array>;
1677
1677
  }
1678
1678
 
1679
+ /**
1680
+ * Types of model jobs (holzi spec 055, `contracts/job-format.md` and `contracts/bridge.md`).
1681
+ */
1682
+ /** Where a model runs. Outside this device the user consents before anything is sent. */
1683
+ type ModelPlace = "this_device" | "network" | "cloud";
1684
+ /** The effort a step wishes for; the host caps it at what the user allowed. */
1685
+ type ModelEffort = "none" | "low" | "medium" | "high";
1686
+ /** A model the user allowed to this extension. */
1687
+ interface ExtensionModel {
1688
+ /** The host's model id, only to show and recognise it. */
1689
+ id: string;
1690
+ name: string;
1691
+ /** The display name of the provider. */
1692
+ provider: string;
1693
+ place: ModelPlace;
1694
+ capabilities: {
1695
+ image: boolean;
1696
+ /** `levels`: low, medium and high take effect; `managed`: the model decides itself. */
1697
+ effort: "none" | "managed" | "levels";
1698
+ };
1699
+ /** The highest effort the user allowed. */
1700
+ maxEffort: ModelEffort;
1701
+ }
1702
+ /** An image as Base64, at most 25 MiB raw; at most 8 per job. */
1703
+ interface ModelJobImage {
1704
+ mimeType: "image/jpeg" | "image/png" | "image/webp";
1705
+ data: string;
1706
+ }
1707
+ /** The format a step's answer must have; `schema` is the host's JSON Schema subset. */
1708
+ interface ModelJobFormat {
1709
+ name: string;
1710
+ version: number;
1711
+ schema: Record<string, unknown>;
1712
+ }
1713
+ interface ModelJobStep {
1714
+ /** `[a-z][a-z0-9_-]{0,31}`, unique in the job. */
1715
+ id: string;
1716
+ /** Always `text`; `image` exactly when the step has images. */
1717
+ needs: ("text" | "image")[];
1718
+ /** The extension's instruction to the model, at most 16 KiB. */
1719
+ instruction: string;
1720
+ input: {
1721
+ text?: string;
1722
+ images?: ModelJobImage[];
1723
+ /** A part of an earlier step's result, by JSON Pointer (RFC 6901); empty means all of it. */
1724
+ from?: {
1725
+ step: string;
1726
+ pointer: string;
1727
+ };
1728
+ };
1729
+ format: ModelJobFormat;
1730
+ effort?: ModelEffort;
1731
+ /** Up to the host's limit (default 4096, at most 16384). */
1732
+ maxOutputTokens?: number;
1733
+ }
1734
+ /** One to four steps; a later step can build on an earlier one with `from`. */
1735
+ interface ModelJob {
1736
+ steps: ModelJobStep[];
1737
+ }
1738
+ /** One model the host tried for a step. */
1739
+ interface ModelJobAttempt {
1740
+ model: string;
1741
+ place: ModelPlace;
1742
+ effort: ModelEffort | "managed";
1743
+ outcome: "used" | "unusable" | "unavailable" | "timeout";
1744
+ reason?: string;
1745
+ }
1746
+ /** What produced a step's result. */
1747
+ interface ModelJobProvenance {
1748
+ stepId: string;
1749
+ formatName: string;
1750
+ formatVersion: number;
1751
+ attempts: ModelJobAttempt[];
1752
+ }
1753
+ type ModelJobErrorCode = "unusable" | "unavailable" | "timeout" | "cancelled" | "consent_denied" | "no_capable_model";
1754
+ /** The end of a job, as the event `haextension:model-job:completed` carries it. */
1755
+ interface ModelJobCompletion {
1756
+ jobId: string;
1757
+ status: "completed" | "failed" | "cancelled";
1758
+ /** Each step's checked result, and the last one's as `final`. */
1759
+ result?: {
1760
+ steps: {
1761
+ id: string;
1762
+ result: unknown;
1763
+ }[];
1764
+ final: unknown;
1765
+ };
1766
+ provenance: ModelJobProvenance[];
1767
+ error?: {
1768
+ code: ModelJobErrorCode;
1769
+ message: string;
1770
+ stepId?: string;
1771
+ };
1772
+ }
1773
+
1774
+ /**
1775
+ * Jobs on the host's language and vision models (holzi spec 055), instead of bringing own access
1776
+ * and keys. The extension describes each step with its instruction, input and the format of the
1777
+ * answer; the host picks a model the user allowed for this extension, caps the effort, drops
1778
+ * broken output and returns only a result that fits the format.
1779
+ *
1780
+ * The user decides at run time: the first job asks which model the extension may use and up to
1781
+ * which effort, and before data goes to a destination outside this device it asks for consent.
1782
+ * The SDK waits for these answers and starts the job again, like for every other permission.
1783
+ */
1784
+ declare class ModelsAPI {
1785
+ private client;
1786
+ constructor(client: HaexVaultSdk);
1787
+ /** The models the user allowed to this extension; empty without any. */
1788
+ listAsync(): Promise<ExtensionModel[]>;
1789
+ /** Starts a job; its end comes as {@link onCompleted}. Use {@link runAsync} to await it. */
1790
+ startAsync(job: ModelJob): Promise<{
1791
+ jobId: string;
1792
+ }>;
1793
+ /** Cancels a running job of this frame; `false` when it is unknown or already ended. */
1794
+ cancelAsync(jobId: string): Promise<boolean>;
1795
+ /** Listens for the end of this frame's jobs. Returns an unsubscribe function. */
1796
+ onCompleted(handler: (completion: ModelJobCompletion) => void): () => void;
1797
+ /**
1798
+ * Starts a job and resolves with its end: `completed` with the result, or `failed` or
1799
+ * `cancelled` with the error. Errors of the start itself (an invalid job, a refused model or
1800
+ * consent, no fitting model) reject. The end can arrive before the start answers; it is kept
1801
+ * until then.
1802
+ */
1803
+ runAsync(job: ModelJob): Promise<ModelJobCompletion>;
1804
+ }
1805
+
1679
1806
  /**
1680
1807
  * Mail types — IMAP fetch + SMTP send.
1681
1808
  *
@@ -1766,6 +1893,34 @@ type FetchRange = {
1766
1893
  type: "uidList";
1767
1894
  uids: number[];
1768
1895
  };
1896
+ /**
1897
+ * Criteria of `MailAPI.searchMessagesAsync`. All given criteria must hold. Texts are matched
1898
+ * ignoring case, are at most 200 characters long, not blank and contain no control characters;
1899
+ * leave a criterion out instead of passing `""`. Dates must name real days. At least one
1900
+ * criterion is required. This is not an IMAP expression: the host builds the command itself.
1901
+ */
1902
+ interface MailSearchCriteria {
1903
+ /** Header and body text. */
1904
+ text?: string;
1905
+ from?: string;
1906
+ to?: string;
1907
+ subject?: string;
1908
+ /** `YYYY-MM-DD`, inclusive. */
1909
+ since?: string;
1910
+ /** `YYYY-MM-DD`, exclusive. */
1911
+ before?: string;
1912
+ /** `true` for unread, `false` for read messages. */
1913
+ unseen?: boolean;
1914
+ /** `true` for flagged, `false` for not flagged messages. */
1915
+ flagged?: boolean;
1916
+ }
1917
+ /** The newest hits of a search and the number of all hits. */
1918
+ interface MailSearchResult {
1919
+ /** UIDs of the newest hits, newest (highest UID) first. */
1920
+ uids: number[];
1921
+ /** How many messages matched in all. */
1922
+ total: number;
1923
+ }
1769
1924
  interface OutgoingAttachment {
1770
1925
  filename: string;
1771
1926
  contentType: string;
@@ -1831,6 +1986,26 @@ declare class MailAPI {
1831
1986
  * viewing or downloading.
1832
1987
  */
1833
1988
  fetchAttachmentAsync(imap: ImapConfig, mailbox: string, uid: number, partIndex: number): Promise<string>;
1989
+ /**
1990
+ * Search a whole mailbox on the server. Answers the UIDs of the newest `limit` hits (1 to 1000;
1991
+ * all that fit one answer when omitted), newest first, and the number of all hits. Fetch their
1992
+ * envelopes with `fetchEnvelopesAsync` and a `uidList` range.
1993
+ */
1994
+ searchMessagesAsync(imap: ImapConfig, mailbox: string, criteria: MailSearchCriteria, limit?: number): Promise<MailSearchResult>;
1995
+ /**
1996
+ * Create a mailbox. Resolves to `false`, not an error, when it already existed. The name may
1997
+ * contain the server's hierarchy delimiter; `*` and `%` are not allowed.
1998
+ */
1999
+ createMailboxAsync(imap: ImapConfig, mailbox: string): Promise<boolean>;
2000
+ /**
2001
+ * Delete messages for good: flags exactly these UIDs `\Deleted` and expunges exactly them, so
2002
+ * other messages marked `\Deleted` stay. Refused with an error on a server without UIDPLUS,
2003
+ * before anything is marked. If the expunge fails after marking, the messages stay in the
2004
+ * mailbox flagged `\Deleted` and the call rejects; do not show them as deleted. At most 1000 UIDs
2005
+ * per call. For a message that can still be recovered, use `moveMessagesAsync` into the trash
2006
+ * instead.
2007
+ */
2008
+ deleteMessagesAsync(imap: ImapConfig, mailbox: string, uids: number[]): Promise<void>;
1834
2009
  /**
1835
2010
  * Set or unset IMAP flags. Use `flags=["\\Seen"]` + `add=true` to
1836
2011
  * mark messages as read; `add=false` removes the flag(s).
@@ -2106,6 +2281,7 @@ declare class HaexVaultSdk {
2106
2281
  readonly shell: ShellAPI;
2107
2282
  readonly passwords: PasswordsAPI;
2108
2283
  readonly contacts: ContactsAPI;
2284
+ readonly models: ModelsAPI;
2109
2285
  readonly mail: MailAPI;
2110
2286
  readonly notifications: NotificationsAPI;
2111
2287
  readonly tab: TabAPI;
@@ -2162,4 +2338,5 @@ declare class HaexVaultSdk {
2162
2338
  private log;
2163
2339
  }
2164
2340
 
2165
- export { type MailboxInfo as $, type AuthorizedClient as A, type BlockedClient as B, type ConfirmOptions as C, DatabaseAPI as D, type EncryptedFolderAccess as E, type ExternalRequestHandler as F, type ExternalRequestPayload as G, HaexVaultSdk as H, type ExternalResponse as I, type FileStat as J, FilesystemAPI as K, type ImapConfig as L, KnownPath as M, type KnownPaths as N, LOCALSEND_EVENTS as O, LocalSendAPI as P, type LocalSendEvent as Q, type FileInfo as R, StorageAPI as S, type LocalSendSettings as T, MailAPI as U, type MailAccount as V, type MailAddress as W, type Attachment as X, type FetchRange as Y, type MailMessage as Z, type MailNewMessagesEvent as _, type ConnectionSecurity as a, type MessageEnvelope as a0, type NotificationAction as a1, type NotificationClickEvent as a2, type NotificationOptions as a3, NotificationsAPI as a4, type OutgoingAttachment as a5, type OutgoingMessage as a6, type PasswordInput as a7, type PasswordItemFull as a8, type PasswordItemSummary as a9, ShellAPI as aA, type ShellCreateOptions as aB, type ShellCreateResponse as aC, type ShellExitEvent as aD, type ShellOutputEvent as aE, type SmtpConfig as aF, type SpaceAccessTokenInfo as aG, type SpaceAssignment as aH, type SpaceInvite as aI, type SpaceKeyGrantInfo as aJ, type SpaceMember as aK, type SpaceMemberInfo as aL, SpacesAPI as aM, type SyncBackendInfo as aN, TabAPI as aO, type ToolContext as aP, type ToolHandler as aQ, ToolsAPI as aR, type TransferDirection as aS, type TransferProgress as aT, type TransferState as aU, WebAPI as aV, canExternalClientSendRequests as aW, isExternalClientConnected as aX, type PasswordKeyValue as aa, type PasswordKeyValueInput as ab, PasswordsAPI as ac, type PendingAuthorization as ad, type PendingTransfer as ae, PermissionsAPI as af, type AddBackendRequest as ag, type FolderBackendInfo as ah, type S3BackendInfo as ai, type S3Config as aj, type S3Proposal as ak, type S3PublicConfig as al, type SftpProposal as am, RemoteStorageAPI as an, type StorageBackendInfo as ao, type StorageBackendType as ap, type StorageObjectInfo as aq, type UpdateBackendRequest as ar, type WebDavProposal as as, type RequestedExtension as at, type SelectFileOptions as au, type SelectFolderOptions as av, type ServerInfo as aw, type ServerStatus as ax, type SessionAuthorization as ay, type SharedSpace as az, type ContactDetail as b, type ContactHolziAddresses as c, type ContactHolziDevice as d, type ContactList as e, type ContactListOptions as f, type ContactSummary as g, type ContactValue as h, ContactsAPI as i, type DecryptedSpace as j, type DeepLink as k, type Device as l, type DeviceInfo as m, type DeviceType as n, DialogAPI as o, type DirEntry as p, type EncryptedFolderChoice as q, type EncryptedFolderEntry as r, type EncryptedFolderProviderErrorKind as s, EncryptedFoldersAPI as t, type ExternalAuthDecision as u, type ExternalConnection as v, ExternalConnectionErrorCode as w, ExternalConnectionState as x, type ExternalRequest as y, type ExternalRequestEvent as z };
2341
+ export { DatabaseAPI as D, HaexVaultSdk as H, FilesystemAPI as L, KnownPath as N, LOCALSEND_EVENTS as P, LocalSendAPI as Q, StorageAPI as S, MailAPI as V, RemoteStorageAPI as aB, ShellAPI as aO, SpacesAPI as a_, ModelsAPI as ae, NotificationsAPI as ai, PasswordsAPI as aq, PermissionsAPI as at, TabAPI as b0, ToolsAPI as b3, WebAPI as b7, canExternalClientSendRequests as b8, isExternalClientConnected as b9, ContactsAPI as i, DialogAPI as o, EncryptedFoldersAPI as t, ExternalConnectionErrorCode as x, ExternalConnectionState as y };
2342
+ export type { MailNewMessagesEvent as $, AuthorizedClient as A, BlockedClient as B, ConfirmOptions as C, EncryptedFolderAccess as E, ExternalRequestEvent as F, ExternalRequestHandler as G, ExternalRequestPayload as I, ExternalResponse as J, FileStat as K, ImapConfig as M, KnownPaths as O, LocalSendEvent as R, FileInfo as T, LocalSendSettings as U, MailAccount as W, MailAddress as X, Attachment as Y, FetchRange as Z, MailMessage as _, ConnectionSecurity as a, SyncBackendInfo as a$, MailSearchCriteria as a0, MailSearchResult as a1, MailboxInfo as a2, MessageEnvelope as a3, ModelEffort as a4, ModelJob as a5, ModelJobAttempt as a6, ModelJobCompletion as a7, ModelJobErrorCode as a8, ModelJobFormat as a9, SftpProposal as aA, StorageBackendInfo as aC, StorageBackendType as aD, StorageObjectInfo as aE, UpdateBackendRequest as aF, WebDavProposal as aG, RequestedExtension as aH, SelectFileOptions as aI, SelectFolderOptions as aJ, ServerInfo as aK, ServerStatus as aL, SessionAuthorization as aM, SharedSpace as aN, ShellCreateOptions as aP, ShellCreateResponse as aQ, ShellExitEvent as aR, ShellOutputEvent as aS, SmtpConfig as aT, SpaceAccessTokenInfo as aU, SpaceAssignment as aV, SpaceInvite as aW, SpaceKeyGrantInfo as aX, SpaceMember as aY, SpaceMemberInfo as aZ, ModelJobImage as aa, ModelJobProvenance as ab, ModelJobStep as ac, ModelPlace as ad, NotificationAction as af, NotificationClickEvent as ag, NotificationOptions as ah, OutgoingAttachment as aj, OutgoingMessage as ak, PasswordInput as al, PasswordItemFull as am, PasswordItemSummary as an, PasswordKeyValue as ao, PasswordKeyValueInput as ap, PendingAuthorization as ar, PendingTransfer as as, AddBackendRequest as au, FolderBackendInfo as av, S3BackendInfo as aw, S3Config as ax, S3Proposal as ay, S3PublicConfig as az, ContactDetail as b, ToolContext as b1, ToolHandler as b2, TransferDirection as b4, TransferProgress as b5, TransferState as b6, ContactHolziAddresses as c, ContactHolziDevice as d, ContactList as e, ContactListOptions as f, ContactSummary as g, ContactValue as h, DecryptedSpace as j, DeepLink as k, Device as l, DeviceInfo as m, DeviceType as n, DirEntry as p, EncryptedFolderChoice as q, EncryptedFolderEntry as r, EncryptedFolderProviderErrorKind as s, ExtensionModel as u, ExternalAuthDecision as v, ExternalConnection as w, ExternalRequest as z };