@miden-sdk/miden-sdk 0.15.0-alpha.4 → 0.15.0-alpha.6

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 (59) hide show
  1. package/README.md +139 -9
  2. package/dist/mt/Cargo-C9UbiAcT.js +26202 -0
  3. package/dist/mt/Cargo-C9UbiAcT.js.map +1 -0
  4. package/dist/{api-types.d.ts → mt/api-types.d.ts} +160 -6
  5. package/dist/mt/assets/miden_client_web.wasm +0 -0
  6. package/dist/mt/crates/miden_client_web.d.ts +4821 -0
  7. package/dist/mt/eager.js +38 -0
  8. package/dist/mt/eager.js.map +1 -0
  9. package/dist/{index.d.ts → mt/index.d.ts} +6 -3
  10. package/dist/mt/index.js +3811 -0
  11. package/dist/mt/index.js.map +1 -0
  12. package/dist/{wasm.js → mt/wasm.js} +1 -1
  13. package/dist/mt/wasm.js.map +1 -0
  14. package/dist/mt/workerHelpers.js +28 -0
  15. package/dist/mt/workers/Cargo-C9UbiAcT-Z344cyB1.js +26203 -0
  16. package/dist/mt/workers/Cargo-C9UbiAcT-Z344cyB1.js.map +1 -0
  17. package/dist/mt/workers/assets/miden_client_web.wasm +0 -0
  18. package/dist/mt/workers/web-client-methods-worker.js +26996 -0
  19. package/dist/mt/workers/web-client-methods-worker.js.map +1 -0
  20. package/dist/{workers → mt/workers}/web-client-methods-worker.module.js +71 -2
  21. package/dist/mt/workers/web-client-methods-worker.module.js.map +1 -0
  22. package/dist/mt/workers/workerHelpers.js +28 -0
  23. package/dist/{Cargo-CVlXCH_2.js → st/Cargo-OZMlHpic.js} +721 -496
  24. package/dist/st/Cargo-OZMlHpic.js.map +1 -0
  25. package/dist/st/api-types.d.ts +1144 -0
  26. package/dist/{workers → st}/assets/miden_client_web.wasm +0 -0
  27. package/dist/{crates → st/crates}/miden_client_web.d.ts +357 -197
  28. package/dist/st/docs-entry.d.ts +38 -0
  29. package/dist/{eager.js → st/eager.js} +2 -2
  30. package/dist/st/eager.js.map +1 -0
  31. package/dist/st/index.d.ts +183 -0
  32. package/dist/{index.js → st/index.js} +723 -284
  33. package/dist/st/index.js.map +1 -0
  34. package/dist/st/wasm.js +23 -0
  35. package/dist/st/wasm.js.map +1 -0
  36. package/dist/{workers/Cargo-CVlXCH_2-CWA-5vlh.js → st/workers/Cargo-OZMlHpic-DZjvJlWc.js} +721 -496
  37. package/dist/st/workers/Cargo-OZMlHpic-DZjvJlWc.js.map +1 -0
  38. package/dist/{assets → st/workers/assets}/miden_client_web.wasm +0 -0
  39. package/dist/{workers → st/workers}/web-client-methods-worker.js +792 -498
  40. package/dist/st/workers/web-client-methods-worker.js.map +1 -0
  41. package/dist/st/workers/web-client-methods-worker.module.js +628 -0
  42. package/dist/st/workers/web-client-methods-worker.module.js.map +1 -0
  43. package/js/client.js +190 -7
  44. package/js/node/napi-compat.js +22 -3
  45. package/js/node-index.js +0 -1
  46. package/js/resources/accounts.js +4 -6
  47. package/js/resources/transactions.js +138 -1
  48. package/lazy/package.json +2 -2
  49. package/mt/lazy/package.json +4 -0
  50. package/mt/package.json +4 -0
  51. package/package.json +30 -15
  52. package/dist/Cargo-CVlXCH_2.js.map +0 -1
  53. package/dist/eager.js.map +0 -1
  54. package/dist/index.js.map +0 -1
  55. package/dist/wasm.js.map +0 -1
  56. package/dist/workers/Cargo-CVlXCH_2-CWA-5vlh.js.map +0 -1
  57. package/dist/workers/web-client-methods-worker.js.map +0 -1
  58. package/dist/workers/web-client-methods-worker.module.js.map +0 -1
  59. /package/dist/{docs-entry.d.ts → mt/docs-entry.d.ts} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web-client-methods-worker.module.js","sources":["../wasm.js","../../../js/constants.js","../../../js/workers/web-client-methods-worker.js"],"sourcesContent":["// This is a documented workaround that should avoid issues with Vite projects\n// https://github.com/wasm-tool/rollup-plugin-rust?tab=readme-ov-file#usage-with-vite\n// Also, this effectively disables SSR.\nasync function loadWasm() {\n let wasmModule;\n if (!import.meta.env || (import.meta.env && !import.meta.env.SSR)) {\n wasmModule = await import('./Cargo-OZMlHpic.js');\n // The Cargo glue's __wbg_init TLA is stripped by the rollup build to\n // prevent blocking WKWebView module evaluation. Call it explicitly here\n // with the WASM URL that the Cargo glue pre-resolves (relative to its\n // own import.meta.url, which downstream bundlers handle correctly).\n if (wasmModule && typeof wasmModule.__wbg_init === \"function\") {\n await wasmModule.__wbg_init({\n // eslint-disable-next-line camelcase -- wasm-bindgen init API parameter name\n module_or_path: wasmModule.__wasm_url,\n });\n }\n }\n return wasmModule;\n}\n\nexport { loadWasm as default };\n//# sourceMappingURL=wasm.js.map\n","export const WorkerAction = Object.freeze({\n INIT: \"init\",\n INIT_MOCK: \"initMock\",\n INIT_THREAD_POOL: \"initThreadPool\",\n CALL_METHOD: \"callMethod\",\n EXECUTE_CALLBACK: \"executeCallback\",\n});\n\nexport const CallbackType = Object.freeze({\n GET_KEY: \"getKey\",\n INSERT_KEY: \"insertKey\",\n SIGN: \"sign\",\n});\n\nexport const MethodName = Object.freeze({\n CREATE_CLIENT: \"createClient\",\n APPLY_TRANSACTION: \"applyTransaction\",\n EXECUTE_TRANSACTION: \"executeTransaction\",\n PROVE_TRANSACTION: \"proveTransaction\",\n SUBMIT_NEW_TRANSACTION: \"submitNewTransaction\",\n SUBMIT_NEW_TRANSACTION_MOCK: \"submitNewTransactionMock\",\n SUBMIT_NEW_TRANSACTION_WITH_PROVER: \"submitNewTransactionWithProver\",\n SUBMIT_NEW_TRANSACTION_WITH_PROVER_MOCK: \"submitNewTransactionWithProverMock\",\n SYNC_STATE: \"syncState\",\n SYNC_STATE_MOCK: \"syncStateMock\",\n SYNC_CHAIN: \"syncChain\",\n SYNC_CHAIN_MOCK: \"syncChainMock\",\n SYNC_NOTE_TRANSPORT: \"syncNoteTransport\",\n SYNC_NOTE_TRANSPORT_MOCK: \"syncNoteTransportMock\",\n});\n","import loadWasm from \"../../dist/wasm.js\";\nimport { CallbackType, MethodName, WorkerAction } from \"../constants.js\";\n\nlet wasmModule = null;\n\nconst getWasmOrThrow = async () => {\n if (!wasmModule) {\n wasmModule = await loadWasm();\n }\n if (!wasmModule) {\n throw new Error(\n \"Miden WASM bindings are unavailable in the worker environment.\"\n );\n }\n return wasmModule;\n};\n\nconst serializeUnknown = (value) => {\n if (typeof value === \"string\") {\n return value;\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n};\n\nconst serializeError = (error) => {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack,\n cause: error.cause ? serializeError(error.cause) : undefined,\n code: error.code,\n };\n }\n\n if (typeof error === \"object\" && error !== null) {\n return {\n name: error.name ?? \"Error\",\n message: error.message ?? serializeUnknown(error),\n };\n }\n\n return {\n name: \"Error\",\n message: serializeUnknown(error),\n };\n};\n\n/**\n * Worker for executing WebClient methods in a separate thread.\n *\n * This worker offloads computationally heavy tasks from the main thread by handling\n * WebClient operations asynchronously. It imports the WASM module and instantiates a\n * WASM WebClient, then listens for messages from the main thread to perform one of two actions:\n *\n * 1. **Initialization (init):**\n * - The worker receives an \"init\" message along with user parameters (RPC URL and seed).\n * - It instantiates the WASM WebClient and calls its createClient method.\n * - Once initialization is complete, the worker sends a `{ ready: true }` message back to signal\n * that it is fully initialized.\n *\n * 2. **Method Invocation (callMethod):**\n * - The worker receives a \"callMethod\" message with a specific method name and arguments.\n * - It uses a mapping (defined in `methodHandlers`) to route the call to the corresponding WASM WebClient method.\n * - Complex data is serialized before being sent and deserialized upon return.\n * - The result (or any error) is then posted back to the main thread.\n *\n * The worker uses a message queue to process incoming messages sequentially, ensuring that only one message\n * is handled at a time.\n *\n * Additionally, the worker immediately sends a `{ loaded: true }` message upon script load. This informs the main\n * thread that the worker script is loaded and ready to receive the \"init\" message.\n *\n * Supported actions (defined in `WorkerAction`):\n * - \"init\" : Initialize the WASM WebClient with provided parameters.\n * - \"callMethod\" : Invoke a designated method on the WASM WebClient.\n *\n * Supported method names are defined in the `MethodName` constant.\n */\n\n// Global state variables.\nlet wasmWebClient = null;\nlet wasmSeed = null; // Seed for the WASM WebClient, if needed.\nlet ready = false; // Indicates if the worker is fully initialized.\nlet messageQueue = []; // Queue for sequential processing.\nlet processing = false; // Flag to ensure one message is processed at a time.\n\n// Track pending callback requests\nlet pendingCallbacks = new Map();\n\n// Timeout for pending callbacks (30 seconds)\nconst CALLBACK_TIMEOUT_MS = 30000;\n\n// Define proxy functions for callbacks that communicate with main thread\nconst callbackProxies = {\n getKey: async (pubKey) => {\n return new Promise((resolve, reject) => {\n const requestId = `${CallbackType.GET_KEY}-${Date.now()}-${Math.random()}`;\n const timeoutId = setTimeout(() => {\n if (pendingCallbacks.has(requestId)) {\n pendingCallbacks.delete(requestId);\n reject(new Error(`Callback ${requestId} timed out`));\n }\n }, CALLBACK_TIMEOUT_MS);\n pendingCallbacks.set(requestId, { resolve, reject, timeoutId });\n\n self.postMessage({\n action: WorkerAction.EXECUTE_CALLBACK,\n callbackType: CallbackType.GET_KEY,\n args: [pubKey],\n requestId,\n });\n });\n },\n insertKey: async (pubKey, secretKey) => {\n return new Promise((resolve, reject) => {\n const requestId = `${CallbackType.INSERT_KEY}-${Date.now()}-${Math.random()}`;\n const timeoutId = setTimeout(() => {\n if (pendingCallbacks.has(requestId)) {\n pendingCallbacks.delete(requestId);\n reject(new Error(`Callback ${requestId} timed out`));\n }\n }, CALLBACK_TIMEOUT_MS);\n pendingCallbacks.set(requestId, { resolve, reject, timeoutId });\n\n self.postMessage({\n action: WorkerAction.EXECUTE_CALLBACK,\n callbackType: CallbackType.INSERT_KEY,\n args: [pubKey, secretKey],\n requestId,\n });\n });\n },\n sign: async (pubKey, signingInputs) => {\n return new Promise((resolve, reject) => {\n const requestId = `${CallbackType.SIGN}-${Date.now()}-${Math.random()}`;\n const timeoutId = setTimeout(() => {\n if (pendingCallbacks.has(requestId)) {\n pendingCallbacks.delete(requestId);\n reject(new Error(`Callback ${requestId} timed out`));\n }\n }, CALLBACK_TIMEOUT_MS);\n pendingCallbacks.set(requestId, { resolve, reject, timeoutId });\n\n self.postMessage({\n action: WorkerAction.EXECUTE_CALLBACK,\n callbackType: CallbackType.SIGN,\n args: [pubKey, signingInputs],\n requestId,\n });\n });\n },\n};\n\n// Define a mapping from method names to handler functions.\nconst methodHandlers = {\n [MethodName.SYNC_STATE]: async () => {\n // Call the internal WASM method (sync lock is handled at the JS wrapper level)\n const syncSummary = await wasmWebClient.syncStateImpl();\n const serializedSyncSummary = syncSummary.serialize();\n return serializedSyncSummary.buffer;\n },\n [MethodName.SYNC_NOTE_TRANSPORT]: async () => {\n await wasmWebClient.syncNoteTransportImpl();\n },\n [MethodName.SYNC_CHAIN]: async () => {\n const syncSummary = await wasmWebClient.syncChainImpl();\n const serializedSyncSummary = syncSummary.serialize();\n return serializedSyncSummary.buffer;\n },\n [MethodName.APPLY_TRANSACTION]: async (args) => {\n const wasm = await getWasmOrThrow();\n const [serializedTransactionResult, submissionHeight] = args;\n const transactionResultBytes = new Uint8Array(serializedTransactionResult);\n const transactionResult = wasm.TransactionResult.deserialize(\n transactionResultBytes\n );\n const transactionUpdate = await wasmWebClient.applyTransaction(\n transactionResult,\n submissionHeight\n );\n const serializedUpdate = transactionUpdate.serialize();\n return serializedUpdate.buffer;\n },\n [MethodName.EXECUTE_TRANSACTION]: async (args) => {\n const wasm = await getWasmOrThrow();\n const [accountIdHex, serializedTransactionRequest] = args;\n const accountId = wasm.AccountId.fromHex(accountIdHex);\n const transactionRequestBytes = new Uint8Array(\n serializedTransactionRequest\n );\n const transactionRequest = wasm.TransactionRequest.deserialize(\n transactionRequestBytes\n );\n const result = await wasmWebClient.executeTransaction(\n accountId,\n transactionRequest\n );\n const serializedResult = result.serialize();\n return serializedResult.buffer;\n },\n [MethodName.PROVE_TRANSACTION]: async (args) => {\n const wasm = await getWasmOrThrow();\n const [serializedTransactionResult, proverPayload] = args;\n const transactionResultBytes = new Uint8Array(serializedTransactionResult);\n const transactionResult = wasm.TransactionResult.deserialize(\n transactionResultBytes\n );\n\n const prover = proverPayload\n ? wasm.TransactionProver.deserialize(proverPayload)\n : undefined;\n\n const proven = await wasmWebClient.proveTransaction(\n transactionResult,\n prover\n );\n const serializedProven = proven.serialize();\n return serializedProven.buffer;\n },\n [MethodName.SUBMIT_NEW_TRANSACTION]: async (args) => {\n const wasm = await getWasmOrThrow();\n const [accountIdHex, serializedTransactionRequest] = args;\n const accountId = wasm.AccountId.fromHex(accountIdHex);\n const transactionRequestBytes = new Uint8Array(\n serializedTransactionRequest\n );\n const transactionRequest = wasm.TransactionRequest.deserialize(\n transactionRequestBytes\n );\n\n const result = await wasmWebClient.executeTransaction(\n accountId,\n transactionRequest\n );\n\n const transactionId = result.id().toHex();\n\n const proven = await wasmWebClient.proveTransaction(result);\n const submissionHeight = await wasmWebClient.submitProvenTransaction(\n proven,\n result\n );\n const transactionUpdate = await wasmWebClient.applyTransaction(\n result,\n submissionHeight\n );\n\n return {\n transactionId,\n submissionHeight,\n serializedTransactionResult: result.serialize().buffer,\n serializedTransactionUpdate: transactionUpdate.serialize().buffer,\n };\n },\n [MethodName.SUBMIT_NEW_TRANSACTION_WITH_PROVER]: async (args) => {\n const wasm = await getWasmOrThrow();\n const [accountIdHex, serializedTransactionRequest, proverPayload] = args;\n const accountId = wasm.AccountId.fromHex(accountIdHex);\n const transactionRequestBytes = new Uint8Array(\n serializedTransactionRequest\n );\n const transactionRequest = wasm.TransactionRequest.deserialize(\n transactionRequestBytes\n );\n\n // Deserialize the prover from the serialized payload\n const prover = proverPayload\n ? wasm.TransactionProver.deserialize(proverPayload)\n : undefined;\n\n const result = await wasmWebClient.executeTransaction(\n accountId,\n transactionRequest\n );\n\n const transactionId = result.id().toHex();\n\n const proven = await wasmWebClient.proveTransaction(result, prover);\n const submissionHeight = await wasmWebClient.submitProvenTransaction(\n proven,\n result\n );\n const transactionUpdate = await wasmWebClient.applyTransaction(\n result,\n submissionHeight\n );\n\n return {\n transactionId,\n submissionHeight,\n serializedTransactionResult: result.serialize().buffer,\n serializedTransactionUpdate: transactionUpdate.serialize().buffer,\n };\n },\n};\n\n// Add mock methods to the handler mapping.\nmethodHandlers[MethodName.SYNC_STATE_MOCK] = async (args) => {\n let [serializedMockChain, serializedMockNoteTransportNode] = args;\n serializedMockChain = new Uint8Array(serializedMockChain);\n serializedMockNoteTransportNode = serializedMockNoteTransportNode\n ? new Uint8Array(serializedMockNoteTransportNode)\n : null;\n await wasmWebClient.createMockClient(\n wasmSeed,\n serializedMockChain,\n serializedMockNoteTransportNode\n );\n\n return await methodHandlers[MethodName.SYNC_STATE]();\n};\n\nmethodHandlers[MethodName.SYNC_CHAIN_MOCK] = async (args) => {\n let [serializedMockChain, serializedMockNoteTransportNode] = args;\n serializedMockChain = new Uint8Array(serializedMockChain);\n serializedMockNoteTransportNode = serializedMockNoteTransportNode\n ? new Uint8Array(serializedMockNoteTransportNode)\n : null;\n await wasmWebClient.createMockClient(\n wasmSeed,\n serializedMockChain,\n serializedMockNoteTransportNode\n );\n\n return await methodHandlers[MethodName.SYNC_CHAIN]();\n};\n\nmethodHandlers[MethodName.SYNC_NOTE_TRANSPORT_MOCK] = async (args) => {\n let [serializedMockChain, serializedMockNoteTransportNode] = args;\n serializedMockChain = new Uint8Array(serializedMockChain);\n serializedMockNoteTransportNode = serializedMockNoteTransportNode\n ? new Uint8Array(serializedMockNoteTransportNode)\n : null;\n await wasmWebClient.createMockClient(\n wasmSeed,\n serializedMockChain,\n serializedMockNoteTransportNode\n );\n\n return await methodHandlers[MethodName.SYNC_NOTE_TRANSPORT]();\n};\n\nmethodHandlers[MethodName.SUBMIT_NEW_TRANSACTION_MOCK] = async (args) => {\n const wasm = await getWasmOrThrow();\n let serializedMockNoteTransportNode = args.pop();\n let serializedMockChain = args.pop();\n serializedMockChain = new Uint8Array(serializedMockChain);\n serializedMockNoteTransportNode = serializedMockNoteTransportNode\n ? new Uint8Array(serializedMockNoteTransportNode)\n : null;\n\n wasmWebClient = new wasm.WebClient();\n await wasmWebClient.createMockClient(\n wasmSeed,\n serializedMockChain,\n serializedMockNoteTransportNode\n );\n\n const result = await methodHandlers[MethodName.SUBMIT_NEW_TRANSACTION](args);\n\n const updatedMockChain = (await wasmWebClient.serializeMockChain()).buffer;\n const updatedMockNoteTransportNode = (\n await wasmWebClient.serializeMockNoteTransportNode()\n ).buffer;\n\n return {\n transactionId: result.transactionId,\n submissionHeight: result.submissionHeight,\n serializedTransactionResult: result.serializedTransactionResult,\n serializedTransactionUpdate: result.serializedTransactionUpdate,\n serializedMockChain: updatedMockChain,\n serializedMockNoteTransportNode: updatedMockNoteTransportNode,\n };\n};\n\nmethodHandlers[MethodName.SUBMIT_NEW_TRANSACTION_WITH_PROVER_MOCK] = async (\n args\n) => {\n const wasm = await getWasmOrThrow();\n let serializedMockNoteTransportNode = args.pop();\n let serializedMockChain = args.pop();\n serializedMockChain = new Uint8Array(serializedMockChain);\n serializedMockNoteTransportNode = serializedMockNoteTransportNode\n ? new Uint8Array(serializedMockNoteTransportNode)\n : null;\n\n wasmWebClient = new wasm.WebClient();\n await wasmWebClient.createMockClient(\n wasmSeed,\n serializedMockChain,\n serializedMockNoteTransportNode\n );\n\n const result =\n await methodHandlers[MethodName.SUBMIT_NEW_TRANSACTION_WITH_PROVER](args);\n\n const updatedMockChain = (await wasmWebClient.serializeMockChain()).buffer;\n const updatedMockNoteTransportNode = (\n await wasmWebClient.serializeMockNoteTransportNode()\n ).buffer;\n\n return {\n transactionId: result.transactionId,\n submissionHeight: result.submissionHeight,\n serializedTransactionResult: result.serializedTransactionResult,\n serializedTransactionUpdate: result.serializedTransactionUpdate,\n serializedMockChain: updatedMockChain,\n serializedMockNoteTransportNode: updatedMockNoteTransportNode,\n };\n};\n\n/**\n * Process a single message event.\n */\nasync function processMessage(event) {\n const { action, args, methodName, requestId } = event.data;\n try {\n if (action === WorkerAction.INIT) {\n const [\n rpcUrl,\n noteTransportUrl,\n seed,\n storeName,\n hasGetKeyCb,\n hasInsertKeyCb,\n hasSignCb,\n logLevel,\n numThreads,\n ] = args;\n const wasm = await getWasmOrThrow();\n\n if (logLevel) {\n wasm.setupLogging(logLevel);\n }\n\n // Initialize rayon's thread pool inside THIS worker's WASM instance.\n // The SDK runs every prove call here (NOT on the main thread), so a\n // pool initialized only in main-thread WASM does not parallelize the\n // prove. Without this, par_iter()/par_chunks() in miden-crypto +\n // p3-maybe-rayon return rayon::current_num_threads() == 1 and fall\n // through to sequential code despite the parallel features being on.\n if (\n numThreads &&\n numThreads > 1 &&\n typeof wasm.initThreadPool === \"function\"\n ) {\n await wasm.initThreadPool(numThreads);\n }\n\n wasmWebClient = new wasm.WebClient();\n\n // Check if any callbacks are provided\n const useExternalKeystore = hasGetKeyCb || hasInsertKeyCb || hasSignCb;\n\n if (useExternalKeystore) {\n // Use callback proxies that communicate with the main thread\n await wasmWebClient.createClientWithExternalKeystore(\n rpcUrl,\n noteTransportUrl,\n seed,\n storeName,\n hasGetKeyCb ? callbackProxies.getKey : undefined,\n hasInsertKeyCb ? callbackProxies.insertKey : undefined,\n hasSignCb ? callbackProxies.sign : undefined\n );\n } else {\n await wasmWebClient.createClient(\n rpcUrl,\n noteTransportUrl,\n seed,\n storeName\n );\n }\n\n wasmSeed = seed;\n ready = true;\n self.postMessage({ ready: true });\n return;\n } else if (action === WorkerAction.INIT_MOCK) {\n const [seed, logLevel, numThreads] = args;\n const wasm = await getWasmOrThrow();\n\n if (logLevel) {\n wasm.setupLogging(logLevel);\n }\n\n // Initialize rayon's pool inside THIS worker's WASM instance — same\n // rationale as the INIT path above: all proving executes here, and a\n // pool initialized in any other instance does not parallelize it.\n if (\n numThreads &&\n numThreads > 1 &&\n typeof wasm.initThreadPool === \"function\"\n ) {\n await wasm.initThreadPool(numThreads);\n }\n\n wasmWebClient = new wasm.WebClient();\n await wasmWebClient.createMockClient(seed, undefined, undefined);\n\n wasmSeed = seed;\n ready = true;\n self.postMessage({ ready: true });\n return;\n } else if (action === WorkerAction.CALL_METHOD) {\n if (!ready) {\n throw new Error(\"Worker is not ready. Please initialize first.\");\n }\n if (!wasmWebClient) {\n throw new Error(\"WebClient not initialized in worker.\");\n }\n // Look up the handler from the mapping.\n const handler = methodHandlers[methodName];\n if (!handler) {\n throw new Error(`Unsupported method: ${methodName}`);\n }\n const result = await handler(args);\n self.postMessage({ requestId, result, methodName });\n return;\n } else {\n throw new Error(`Unsupported action: ${action}`);\n }\n } catch (error) {\n const serializedError = serializeError(error);\n console.error(\n \"WORKER: Error occurred - %s\",\n serializedError.message,\n error\n );\n self.postMessage({ requestId, error: serializedError, methodName });\n }\n}\n\n/**\n * Process messages one at a time from the messageQueue.\n */\nasync function processQueue() {\n if (processing || messageQueue.length === 0) return;\n processing = true;\n const event = messageQueue.shift();\n try {\n await processMessage(event);\n } finally {\n processing = false;\n processQueue(); // Process next message in queue.\n }\n}\n\n// Enqueue incoming messages and process them sequentially.\nself.onmessage = (event) => {\n if (\n event.data.callbackRequestId &&\n pendingCallbacks.has(event.data.callbackRequestId)\n ) {\n const { callbackRequestId, callbackResult, callbackError } = event.data;\n const { resolve, reject, timeoutId } =\n pendingCallbacks.get(callbackRequestId);\n clearTimeout(timeoutId);\n pendingCallbacks.delete(callbackRequestId);\n if (!callbackError) {\n resolve(callbackResult);\n } else {\n reject(new Error(callbackError));\n }\n return;\n }\n messageQueue.push(event);\n processQueue();\n};\n\n// Immediately signal that the worker script has loaded.\n// This tells the main thread that the file is fully loaded before sending the \"init\" message.\nself.postMessage({ loaded: true });\n"],"names":[],"mappings":"AAAA;AACA;AACA;AACA,eAAe,QAAQ,GAAG;AAC1B,EAAE,IAAI,UAAU;AAChB,EAAE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;AACrE,IAAI,UAAU,GAAG,MAAM,OAAO,8BAAqB,CAAC;AACpD;AACA;AACA;AACA;AACA,IAAI,IAAI,UAAU,IAAI,OAAO,UAA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AC;;AAED;AACA;AACA,IAAI,CAAC,WAAW,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC"}
package/js/client.js CHANGED
@@ -39,6 +39,80 @@ export class MidenClient {
39
39
  this.keystore = new KeystoreResource(inner, this);
40
40
  }
41
41
 
42
+ /**
43
+ * Escape hatch: runs `fn` with exclusive access to the proxied JS
44
+ * WebClient that backs this MidenClient.
45
+ *
46
+ * The proxy forwards missing properties to the underlying wasm-bindgen
47
+ * `WebClient`, so `fn` can reach lower-level methods like
48
+ * `executeTransaction`, `proveTransaction[WithProver]`,
49
+ * `submitProvenTransaction`, `applyTransaction`,
50
+ * `newSendTransactionRequest`, `newConsumeTransactionRequest`, etc.
51
+ *
52
+ * Intended for advanced consumers that need to split the bundled
53
+ * execute → prove → submit → apply pipeline across contexts — for example,
54
+ * a Chrome MV3 extension that runs `executeTransaction` in its service
55
+ * worker, dispatches the prove step to a `chrome.offscreen` document
56
+ * (where wasm-bindgen-rayon can spawn a real thread pool), then runs
57
+ * `submitProvenTransaction` + `applyTransaction` back in the SW.
58
+ *
59
+ * The callback runs inside `_serializeWasmCall`, so the WASM RefCell is
60
+ * held for the duration of `fn`. Concurrent SDK calls (sync, other
61
+ * transactions, etc.) queue on the same chain and run after `fn`
62
+ * settles. Without this serialization, raw inner-client access would
63
+ * race the proxy's chain and trip wasm-bindgen's "recursive use of an
64
+ * object detected" panic.
65
+ *
66
+ * Re-entrancy: while `fn` is running, the underlying client's
67
+ * `_withInnerLockDepth` counter is bumped so that `_serializeWasmCall`
68
+ * invocations made BY `fn` (or any proxy-dispatched method it calls)
69
+ * run inline rather than enqueuing on the chain. Without this, every
70
+ * `await inner.X(...)` inside `fn` would enqueue behind the outer
71
+ * `_withInnerWebClient` slot which is itself awaiting `fn` —
72
+ * a classic re-entrant-lock deadlock. The depth counter restores the
73
+ * intent of the docstring above: the lock is held for the duration
74
+ * of `fn`, and inner-client calls "borrow" that already-held lock
75
+ * instead of trying to re-acquire it.
76
+ *
77
+ * SAFETY CONTRACT for re-entrancy: callers MUST hold an external
78
+ * mutex preventing concurrent access to this same client instance
79
+ * via other code paths during `fn`. The chain still serializes
80
+ * against external callers — they queue behind the outer slot — but
81
+ * if an external task runs during one of `fn`'s awaits and calls
82
+ * into the SDK, it will see `_withInnerLockDepth > 0` and run
83
+ * inline, racing wasm-bindgen's borrow check. The wallet pattern
84
+ * (own outer mutex around `_withInnerWebClient`) satisfies this.
85
+ *
86
+ * Stability: marked `@internal`. The shape of the proxied client is
87
+ * intentionally not part of the documented public API and may change
88
+ * between SDK versions. If you depend on this method, pin the SDK
89
+ * version and test the lower-level surface carefully on each upgrade.
90
+ * If your use case is common enough to warrant a stable public API,
91
+ * file an issue.
92
+ *
93
+ * @internal
94
+ * @template T
95
+ * @param {(inner: object) => Promise<T>} fn - Async callback receiving
96
+ * the proxied JS WebClient. Must not return references that escape
97
+ * the callback's lifetime (the lock is released on settle).
98
+ * @returns {Promise<T>} The resolved value of `fn`.
99
+ */
100
+ _withInnerWebClient(fn) {
101
+ this.assertNotTerminated();
102
+ if (typeof fn !== "function") {
103
+ throw new TypeError("_withInnerWebClient: fn must be a function");
104
+ }
105
+ const inner = this.#inner;
106
+ return inner._serializeWasmCall(async () => {
107
+ inner._withInnerLockDepth = (inner._withInnerLockDepth || 0) + 1;
108
+ try {
109
+ return await fn(inner);
110
+ } finally {
111
+ inner._withInnerLockDepth--;
112
+ }
113
+ });
114
+ }
115
+
42
116
  /**
43
117
  * Creates and initializes a new MidenClient.
44
118
  *
@@ -67,6 +141,13 @@ export class MidenClient {
67
141
  const rpcUrl = resolveRpcUrl(options?.rpcUrl);
68
142
  const noteTransportUrl = resolveNoteTransportUrl(options?.noteTransportUrl);
69
143
 
144
+ // `useWorker: false` opts out of the Web Worker shim that wraps every
145
+ // WASM call. The shim exists to keep the main thread responsive in
146
+ // browser/extension contexts, but it serializes the prover via
147
+ // `TransactionProver.serialize()` — a format that has no encoding for
148
+ // `newCallbackProver(jsFn)` and silently downgrades it to `"local"`.
149
+ // Mobile/Tauri/native-prover consumers must pass `useWorker: false`.
150
+ const useWorker = options?.useWorker;
70
151
  let inner;
71
152
  if (options?.keystore) {
72
153
  inner = await WebClientClass.createClientWithExternalKeystore(
@@ -77,7 +158,8 @@ export class MidenClient {
77
158
  options.keystore.getKey,
78
159
  options.keystore.insertKey,
79
160
  options.keystore.sign,
80
- options?.debugMode
161
+ options?.debugMode,
162
+ useWorker
81
163
  );
82
164
  } else {
83
165
  inner = await WebClientClass.createClient(
@@ -85,7 +167,8 @@ export class MidenClient {
85
167
  noteTransportUrl,
86
168
  seed,
87
169
  options?.storeName,
88
- options?.debugMode
170
+ options?.debugMode,
171
+ useWorker
89
172
  );
90
173
  }
91
174
 
@@ -142,6 +225,32 @@ export class MidenClient {
142
225
  });
143
226
  }
144
227
 
228
+ /**
229
+ * Resolves once the WASM module is initialized and safe to use.
230
+ *
231
+ * Idempotent and shared across callers: the underlying loader memoizes the
232
+ * in-flight promise, so concurrent `ready()` calls await the same
233
+ * initialization and post-init callers resolve immediately from a cached
234
+ * module. Safe to call from `MidenProvider`, tutorial helpers, and any
235
+ * other consumer simultaneously.
236
+ *
237
+ * Useful on the `/lazy` entry (e.g. Next.js / Capacitor), where no
238
+ * top-level await runs at import time. On the default (eager) entry this
239
+ * is redundant — importing the module already awaits WASM — but calling it
240
+ * is still harmless.
241
+ *
242
+ * @returns {Promise<void>} Resolves when WASM is initialized.
243
+ */
244
+ static async ready() {
245
+ const getWasm = MidenClient._getWasmOrThrow;
246
+ if (!getWasm) {
247
+ throw new Error(
248
+ "MidenClient not initialized. Import from the SDK package entry point."
249
+ );
250
+ }
251
+ await getWasm();
252
+ }
253
+
145
254
  /**
146
255
  * Creates a mock client for testing.
147
256
  *
@@ -177,15 +286,34 @@ export class MidenClient {
177
286
  }
178
287
 
179
288
  /**
180
- * Syncs the client state with the Miden node.
289
+ * Syncs the client: fetches private notes from the Note Transport Layer, then syncs on-chain
290
+ * state with the Miden node. Fails fast on either.
181
291
  *
182
- * @param {object} [opts] - Sync options.
183
- * @param {number} [opts.timeout] - Timeout in milliseconds (0 = no timeout).
184
292
  * @returns {Promise<SyncSummary>} The sync summary.
185
293
  */
186
- async sync(opts) {
294
+ async sync() {
187
295
  this.assertNotTerminated();
188
- return await this.#inner.syncStateWithTimeout(opts?.timeout ?? 0);
296
+ return await this.#inner.syncState();
297
+ }
298
+
299
+ /**
300
+ * Syncs on-chain state only (no NTL fetch).
301
+ *
302
+ * @returns {Promise<SyncSummary>}
303
+ */
304
+ async syncChain() {
305
+ this.assertNotTerminated();
306
+ return await this.#inner.syncChain();
307
+ }
308
+
309
+ /**
310
+ * Fetches private notes from the Note Transport Layer.
311
+ *
312
+ * @returns {Promise<void>}
313
+ */
314
+ async syncNoteTransport() {
315
+ this.assertNotTerminated();
316
+ return await this.#inner.syncNoteTransport();
189
317
  }
190
318
 
191
319
  /**
@@ -198,6 +326,61 @@ export class MidenClient {
198
326
  return await this.#inner.getSyncHeight();
199
327
  }
200
328
 
329
+ /**
330
+ * Resolves once every serialized WASM call that was already on the
331
+ * internal `_serializeWasmCall` chain when `waitForIdle()` was called
332
+ * (execute, submit, prove, apply, sync, or account creation) has
333
+ * settled. Use this from callers that need to perform a non-WASM-side
334
+ * action — e.g. clearing an in-memory auth key on wallet lock — after
335
+ * the kernel finishes, so its auth callback doesn't race with the key
336
+ * being cleared.
337
+ *
338
+ * Does NOT wait for calls enqueued after `waitForIdle()` returns —
339
+ * intentional, so a caller can drain and proceed without being blocked
340
+ * indefinitely by concurrent workload.
341
+ *
342
+ * Caveat for `syncState`: `syncStateWithTimeout` awaits the sync lock
343
+ * (`acquireSyncLock`, which uses Web Locks) BEFORE putting its WASM
344
+ * call onto the chain, so a `syncState` that is queued on the sync
345
+ * lock — but has not yet begun its WASM phase — is not visible to
346
+ * `waitForIdle` and will not be awaited. Other methods (`newWallet`,
347
+ * `executeTransaction`, etc.) route through the chain synchronously
348
+ * on call and are always observed.
349
+ *
350
+ * Safe to call at any time; returns immediately if nothing was in
351
+ * flight.
352
+ *
353
+ * @returns {Promise<void>}
354
+ */
355
+ async waitForIdle() {
356
+ this.assertNotTerminated();
357
+ await this.#inner.waitForIdle();
358
+ }
359
+
360
+ /**
361
+ * Returns the raw JS value that the most recent sign-callback invocation
362
+ * threw, or `null` if the last sign call succeeded (or no call has
363
+ * happened yet).
364
+ *
365
+ * Useful for recovering structured metadata (e.g. a `reason: 'locked'`
366
+ * property) that the kernel-level `auth::request` diagnostic would
367
+ * otherwise erase. Call immediately after catching a failed
368
+ * `transactions.submit` / `transactions.send` / `transactions.consume`.
369
+ *
370
+ * Meaningful only with `useWorker: false`: under the worker shim the
371
+ * sign callback fires against the worker's WASM keystore, while this
372
+ * accessor reads the main-thread instance — which never signed — so it
373
+ * returns `null`. Consumers that need this signal (e.g. external
374
+ * keystores with lock-aware sign callbacks) already require
375
+ * `useWorker: false` for the callback to be reachable at all.
376
+ *
377
+ * @returns {any} The raw thrown value, or `null`.
378
+ */
379
+ lastAuthError() {
380
+ this.assertNotTerminated();
381
+ return this.#inner.lastAuthError();
382
+ }
383
+
201
384
  /**
202
385
  * Terminates the underlying Web Worker. After this, all method calls will throw.
203
386
  */
@@ -61,7 +61,8 @@ function wrapClass(Cls) {
61
61
  * Wraps a raw napi WebClient to normalize API differences with the browser SDK.
62
62
  *
63
63
  * - syncState() -> syncStateImpl() (no browser lock coordination needed)
64
- * - syncStateWithTimeout() -> syncStateImpl() (timeout not applicable)
64
+ * - syncChain() -> syncChainImpl()
65
+ * - syncNoteTransport() -> syncNoteTransportImpl()
65
66
  * - null -> undefined for Option<T> returns
66
67
  * - BigInt/Uint8Array args normalized
67
68
  */
@@ -71,8 +72,11 @@ export function wrapClient(rawClient, storeName) {
71
72
  if (prop === "syncState") {
72
73
  return (...args) => target.syncStateImpl(...args);
73
74
  }
74
- if (prop === "syncStateWithTimeout") {
75
- return (_timeoutMs) => target.syncStateImpl();
75
+ if (prop === "syncChain") {
76
+ return () => target.syncChainImpl();
77
+ }
78
+ if (prop === "syncNoteTransport") {
79
+ return () => target.syncNoteTransportImpl();
76
80
  }
77
81
  if (prop === "storeName") {
78
82
  return storeName || "default";
@@ -91,6 +95,21 @@ export function wrapClient(rawClient, storeName) {
91
95
  if (prop === "onStateChanged") {
92
96
  return () => undefined;
93
97
  }
98
+ // waitForIdle drains the browser SDK's detached `_serializeWasmCall`
99
+ // chain. The napi binding has no such chain — every call is awaited
100
+ // directly by its caller and serialized inside Rust — so there is
101
+ // nothing in flight by the time a caller could invoke this. Resolve
102
+ // immediately to keep the cross-platform MidenClient surface intact.
103
+ if (prop === "waitForIdle") {
104
+ return () => Promise.resolve();
105
+ }
106
+ // lastAuthError surfaces the raw value a JS sign callback threw.
107
+ // The Node binding signs with FilesystemKeyStore (no JS callback can
108
+ // ever run), so "no sign error" is the semantically correct answer,
109
+ // not a stub.
110
+ if (prop === "lastAuthError") {
111
+ return () => null;
112
+ }
94
113
  if (prop === "newWallet") {
95
114
  return (mode, mutable, authScheme, seed) => {
96
115
  const normSeed =
package/js/node-index.js CHANGED
@@ -77,7 +77,6 @@ export const NoteVisibility = Object.freeze({
77
77
  export const StorageMode = Object.freeze({
78
78
  Public: "public",
79
79
  Private: "private",
80
- Network: "network",
81
80
  });
82
81
 
83
82
  // ── Re-exports ───────────────────────────────────────────────────────
@@ -34,6 +34,7 @@ export class AccountsResource {
34
34
  return await this.#inner.newFaucet(
35
35
  storageMode,
36
36
  type === 1 || type === "NonFungibleFaucet",
37
+ opts.name ?? opts.symbol,
37
38
  opts.symbol,
38
39
  opts.decimals,
39
40
  BigInt(opts.maxSupply),
@@ -66,11 +67,9 @@ export class AccountsResource {
66
67
  if (!opts.auth)
67
68
  throw new Error("Contract creation requires an 'auth' (AuthSecretKey)");
68
69
 
69
- // Default to immutable when type is omitted (safer for contracts)
70
- const mutable = opts.type === "MutableContract" || opts.type === 3;
71
- const accountTypeEnum = mutable
72
- ? wasm.AccountType.RegularAccountUpdatableCode
73
- : wasm.AccountType.RegularAccountImmutableCode;
70
+ // The 0.15 protocol has no code-mutability distinction, so the `type`
71
+ // ("ImmutableContract" / "MutableContract") only steers routing here; the
72
+ // account's on-chain visibility is set entirely by `storageMode`.
74
73
  const storageMode = resolveStorageMode(opts.storage ?? "public", wasm);
75
74
  const authComponent =
76
75
  wasm.AccountComponent.createAuthComponentFromSecretKey(opts.auth);
@@ -85,7 +84,6 @@ export class AccountsResource {
85
84
  }
86
85
 
87
86
  let builder = new wasm.AccountBuilder(opts.seed)
88
- .accountType(accountTypeEnum)
89
87
  .storageMode(storageMode)
90
88
  .withAuthComponent(authComponent);
91
89
 
@@ -177,6 +177,72 @@ export class TransactionsResource {
177
177
  return { txId, result };
178
178
  }
179
179
 
180
+ /** Create a partial-swap (PSWAP) note. See {@link PswapCreateOptions}. */
181
+ async pswapCreate(opts) {
182
+ this.#client.assertNotTerminated();
183
+ const wasm = await this.#getWasm();
184
+ const { accountId, request } = await this.#buildPswapCreateRequest(
185
+ opts,
186
+ wasm
187
+ );
188
+
189
+ const { txId, result } = await this.#submitOrSubmitWithProver(
190
+ accountId,
191
+ request,
192
+ opts.prover
193
+ );
194
+
195
+ if (opts.waitForConfirmation) {
196
+ await this.waitFor(txId.toHex(), { timeout: opts.timeout });
197
+ }
198
+
199
+ return { txId, result };
200
+ }
201
+
202
+ /** Consume (fully or partially fill) a PSWAP note. See {@link PswapConsumeOptions}. */
203
+ async pswapConsume(opts) {
204
+ this.#client.assertNotTerminated();
205
+ const wasm = await this.#getWasm();
206
+ const { accountId, request } = await this.#buildPswapConsumeRequest(
207
+ opts,
208
+ wasm
209
+ );
210
+
211
+ const { txId, result } = await this.#submitOrSubmitWithProver(
212
+ accountId,
213
+ request,
214
+ opts.prover
215
+ );
216
+
217
+ if (opts.waitForConfirmation) {
218
+ await this.waitFor(txId.toHex(), { timeout: opts.timeout });
219
+ }
220
+
221
+ return { txId, result };
222
+ }
223
+
224
+ /** Cancel a PSWAP note as its creator and reclaim the offered asset. See {@link PswapCancelOptions}. */
225
+ async pswapCancel(opts) {
226
+ this.#client.assertNotTerminated();
227
+ const wasm = await this.#getWasm();
228
+ const { accountId, request } = await this.#buildPswapCancelRequest(
229
+ opts,
230
+ wasm
231
+ );
232
+
233
+ const { txId, result } = await this.#submitOrSubmitWithProver(
234
+ accountId,
235
+ request,
236
+ opts.prover
237
+ );
238
+
239
+ if (opts.waitForConfirmation) {
240
+ await this.waitFor(txId.toHex(), { timeout: opts.timeout });
241
+ }
242
+
243
+ return { txId, result };
244
+ }
245
+
180
246
  async preview(opts) {
181
247
  this.#client.assertNotTerminated();
182
248
  const wasm = await this.#getWasm();
@@ -201,6 +267,27 @@ export class TransactionsResource {
201
267
  ({ accountId, request } = await this.#buildSwapRequest(opts, wasm));
202
268
  break;
203
269
  }
270
+ case "pswapCreate": {
271
+ ({ accountId, request } = await this.#buildPswapCreateRequest(
272
+ opts,
273
+ wasm
274
+ ));
275
+ break;
276
+ }
277
+ case "pswapConsume": {
278
+ ({ accountId, request } = await this.#buildPswapConsumeRequest(
279
+ opts,
280
+ wasm
281
+ ));
282
+ break;
283
+ }
284
+ case "pswapCancel": {
285
+ ({ accountId, request } = await this.#buildPswapCancelRequest(
286
+ opts,
287
+ wasm
288
+ ));
289
+ break;
290
+ }
204
291
  case "custom": {
205
292
  accountId = resolveAccountRef(opts.account, wasm);
206
293
  request = opts.request;
@@ -353,7 +440,10 @@ export class TransactionsResource {
353
440
  }
354
441
 
355
442
  try {
356
- await this.#inner.syncStateWithTimeout(0);
443
+ // Chain-only sync is sufficient: confirmation only needs on-chain
444
+ // state, and skipping NTL keeps polling alive when the note
445
+ // transport endpoint is unavailable.
446
+ await this.#inner.syncChain();
357
447
  } catch {
358
448
  // Sync may fail transiently; continue polling
359
449
  }
@@ -487,6 +577,53 @@ export class TransactionsResource {
487
577
  return { accountId, request };
488
578
  }
489
579
 
580
+ async #buildPswapCreateRequest(opts, wasm) {
581
+ const accountId = resolveAccountRef(opts.account, wasm);
582
+ const offeredFaucetId = resolveAccountRef(opts.offer.token, wasm);
583
+ const requestedFaucetId = resolveAccountRef(opts.request.token, wasm);
584
+ const noteType = resolveNoteType(opts.type, wasm);
585
+ const paybackNoteType = resolveNoteType(
586
+ opts.paybackType ?? opts.type,
587
+ wasm
588
+ );
589
+
590
+ const request = await this.#inner.newPswapCreateTransactionRequest(
591
+ accountId,
592
+ offeredFaucetId,
593
+ BigInt(opts.offer.amount),
594
+ requestedFaucetId,
595
+ BigInt(opts.request.amount),
596
+ noteType,
597
+ paybackNoteType
598
+ );
599
+ return { accountId, request };
600
+ }
601
+
602
+ async #buildPswapConsumeRequest(opts, wasm) {
603
+ const accountId = resolveAccountRef(opts.account, wasm);
604
+ const note = await this.#resolveNoteInput(opts.note);
605
+ const noteFillAmount = opts.noteFillAmount ?? 0n;
606
+
607
+ const request = await this.#inner.newPswapConsumeTransactionRequest(
608
+ note,
609
+ accountId,
610
+ BigInt(opts.fillAmount),
611
+ BigInt(noteFillAmount)
612
+ );
613
+ return { accountId, request };
614
+ }
615
+
616
+ async #buildPswapCancelRequest(opts, wasm) {
617
+ const accountId = resolveAccountRef(opts.account, wasm);
618
+ const note = await this.#resolveNoteInput(opts.note);
619
+
620
+ const request = await this.#inner.newPswapCancelTransactionRequest(
621
+ note,
622
+ accountId
623
+ );
624
+ return { accountId, request };
625
+ }
626
+
490
627
  async #resolveNoteInput(input) {
491
628
  if (typeof input === "string") {
492
629
  const record = await this.#inner.getInputNote(input);
package/lazy/package.json CHANGED
@@ -1,4 +1,4 @@
1
1
  {
2
- "main": "../dist/index.js",
3
- "types": "../dist/index.d.ts"
2
+ "main": "../dist/st/index.js",
3
+ "types": "../dist/st/index.d.ts"
4
4
  }
@@ -0,0 +1,4 @@
1
+ {
2
+ "main": "../../dist/mt/index.js",
3
+ "types": "../../dist/mt/index.d.ts"
4
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "main": "../dist/mt/eager.js",
3
+ "types": "../dist/mt/index.d.ts"
4
+ }