@metamask/snaps-execution-environments 2.0.1 → 3.1.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 (46) hide show
  1. package/CHANGELOG.md +16 -1
  2. package/dist/browserify/iframe/bundle.js +5 -5
  3. package/dist/browserify/node-process/bundle.js +4 -4
  4. package/dist/browserify/node-thread/bundle.js +4 -4
  5. package/dist/browserify/offscreen/bundle.js +4 -4
  6. package/dist/browserify/worker-executor/bundle.js +5 -5
  7. package/dist/browserify/worker-pool/bundle.js +4 -4
  8. package/dist/cjs/common/BaseSnapExecutor.js +37 -27
  9. package/dist/cjs/common/BaseSnapExecutor.js.map +1 -1
  10. package/dist/cjs/common/commands.js +1 -0
  11. package/dist/cjs/common/commands.js.map +1 -1
  12. package/dist/cjs/common/endowments/console.js.map +1 -1
  13. package/dist/cjs/common/endowments/index.js +2 -1
  14. package/dist/cjs/common/endowments/index.js.map +1 -1
  15. package/dist/cjs/common/endowments/interval.js +2 -1
  16. package/dist/cjs/common/endowments/interval.js.map +1 -1
  17. package/dist/cjs/common/endowments/timeout.js +2 -1
  18. package/dist/cjs/common/endowments/timeout.js.map +1 -1
  19. package/dist/cjs/common/globalEvents.js +2 -1
  20. package/dist/cjs/common/globalEvents.js.map +1 -1
  21. package/dist/cjs/common/globalObject.js.map +1 -1
  22. package/dist/cjs/common/utils.js +7 -21
  23. package/dist/cjs/common/utils.js.map +1 -1
  24. package/dist/cjs/common/validation.js +3 -2
  25. package/dist/cjs/common/validation.js.map +1 -1
  26. package/dist/esm/common/BaseSnapExecutor.js +37 -27
  27. package/dist/esm/common/BaseSnapExecutor.js.map +1 -1
  28. package/dist/esm/common/commands.js +1 -0
  29. package/dist/esm/common/commands.js.map +1 -1
  30. package/dist/esm/common/endowments/console.js.map +1 -1
  31. package/dist/esm/common/endowments/index.js +2 -1
  32. package/dist/esm/common/endowments/index.js.map +1 -1
  33. package/dist/esm/common/endowments/interval.js +2 -1
  34. package/dist/esm/common/endowments/interval.js.map +1 -1
  35. package/dist/esm/common/endowments/timeout.js +2 -1
  36. package/dist/esm/common/endowments/timeout.js.map +1 -1
  37. package/dist/esm/common/globalEvents.js +2 -1
  38. package/dist/esm/common/globalEvents.js.map +1 -1
  39. package/dist/esm/common/globalObject.js.map +1 -1
  40. package/dist/esm/common/utils.js +7 -25
  41. package/dist/esm/common/utils.js.map +1 -1
  42. package/dist/esm/common/validation.js +3 -2
  43. package/dist/esm/common/validation.js.map +1 -1
  44. package/dist/types/common/endowments/index.d.ts +1 -1
  45. package/dist/types/common/utils.d.ts +0 -9
  46. package/package.json +21 -23
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/index.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport type { SnapsGlobalObject } from '@metamask/rpc-methods';\nimport type { SnapId } from '@metamask/snaps-utils';\nimport { logWarning } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\nimport buildCommonEndowments from './commonEndowmentFactory';\n\ntype EndowmentFactoryResult = {\n /**\n * A function that performs any necessary teardown when the snap becomes idle.\n *\n * NOTE:** The endowments are not reconstructed if the snap is re-invoked\n * before being terminated, so the teardown operation must not render the\n * endowments unusable; it should simply restore the endowments to their\n * original state.\n */\n teardownFunction?: () => Promise<void> | void;\n [key: string]: unknown;\n};\n\n/**\n * Retrieve consolidated endowment factories for common endowments.\n */\nconst registeredEndowments = buildCommonEndowments();\n\n/**\n * A map of endowment names to their factory functions. Some endowments share\n * the same factory function, but we only call each factory once for each snap.\n * See {@link createEndowments} for details.\n */\nconst endowmentFactories = registeredEndowments.reduce((factories, builder) => {\n builder.names.forEach((name) => {\n factories.set(name, builder.factory);\n });\n return factories;\n}, new Map<string, (options?: EndowmentFactoryOptions) => EndowmentFactoryResult>());\n\n/**\n * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`\n * and `clearTimeout`, must be attenuated so that they can only affect behavior\n * within the Snap's own realm. Therefore, we use factory functions to create\n * such attenuated / modified endowments. Otherwise, the value that's on the\n * root realm global will be used.\n *\n * @param snap - The Snaps global API object.\n * @param ethereum - The Snap's EIP-1193 provider object.\n * @param snapId - The id of the snap that will use the created endowments.\n * @param endowments - The list of endowments to provide to the snap.\n * @returns An object containing the Snap's endowments.\n */\nexport function createEndowments(\n snap: SnapsGlobalObject,\n ethereum: StreamProvider,\n snapId: SnapId,\n endowments: string[] = [],\n): { endowments: Record<string, unknown>; teardown: () => Promise<void> } {\n const attenuatedEndowments: Record<string, unknown> = {};\n\n // TODO: All endowments should be hardened to prevent covert communication\n // channels. Hardening the returned objects breaks tests elsewhere in the\n // monorepo, so further research is needed.\n const result = endowments.reduce<{\n allEndowments: Record<string, unknown>;\n teardowns: (() => Promise<void> | void)[];\n }>(\n ({ allEndowments, teardowns }, endowmentName) => {\n // First, check if the endowment has a factory, and default to that.\n if (endowmentFactories.has(endowmentName)) {\n if (!hasProperty(attenuatedEndowments, endowmentName)) {\n // Call the endowment factory for the current endowment. If the factory\n // creates multiple endowments, they will all be assigned to the\n // `attenuatedEndowments` object, but will only be passed on to the snap\n // if explicitly listed among its endowment.\n // This may not have an actual use case, but, safety first.\n\n // We just confirmed that endowmentFactories has the specified key.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { teardownFunction, ...endowment } = endowmentFactories.get(\n endowmentName,\n )!({ snapId });\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\n }\n allEndowments[endowmentName] = attenuatedEndowments[endowmentName];\n } else if (endowmentName === 'ethereum') {\n // Special case for adding the EIP-1193 provider.\n allEndowments[endowmentName] = ethereum;\n } else if (endowmentName in rootRealmGlobal) {\n logWarning(`Access to unhardened global ${endowmentName}.`);\n // If the endowment doesn't have a factory, just use whatever is on the\n // global object.\n const globalValue = (rootRealmGlobal as Record<string, unknown>)[\n endowmentName\n ];\n allEndowments[endowmentName] = globalValue;\n } else {\n // If we get to this point, we've been passed an endowment that doesn't\n // exist in our current environment.\n throw new Error(`Unknown endowment: \"${endowmentName}\".`);\n }\n return { allEndowments, teardowns };\n },\n {\n allEndowments: { snap },\n teardowns: [],\n },\n );\n\n const teardown = async () => {\n await Promise.all(\n result.teardowns.map((teardownFunction) => teardownFunction()),\n );\n };\n return { endowments: result.allEndowments, teardown };\n}\n"],"names":["logWarning","hasProperty","rootRealmGlobal","buildCommonEndowments","registeredEndowments","endowmentFactories","reduce","factories","builder","names","forEach","name","set","factory","Map","createEndowments","snap","ethereum","snapId","endowments","attenuatedEndowments","result","allEndowments","teardowns","endowmentName","has","teardownFunction","endowment","get","Object","assign","push","globalValue","Error","teardown","Promise","all","map"],"mappings":"AAGA,SAASA,UAAU,QAAQ,wBAAwB;AACnD,SAASC,WAAW,QAAQ,kBAAkB;AAE9C,SAASC,eAAe,QAAQ,kBAAkB;AAElD,OAAOC,2BAA2B,2BAA2B;AAe7D;;CAEC,GACD,MAAMC,uBAAuBD;AAE7B;;;;CAIC,GACD,MAAME,qBAAqBD,qBAAqBE,MAAM,CAAC,CAACC,WAAWC;IACjEA,QAAQC,KAAK,CAACC,OAAO,CAAC,CAACC;QACrBJ,UAAUK,GAAG,CAACD,MAAMH,QAAQK,OAAO;IACrC;IACA,OAAON;AACT,GAAG,IAAIO;AAEP;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,iBACdC,IAAuB,EACvBC,QAAwB,EACxBC,MAAc,EACdC,aAAuB,EAAE;IAEzB,MAAMC,uBAAgD,CAAC;IAEvD,0EAA0E;IAC1E,yEAAyE;IACzE,2CAA2C;IAC3C,MAAMC,SAASF,WAAWb,MAAM,CAI9B,CAAC,EAAEgB,aAAa,EAAEC,SAAS,EAAE,EAAEC;QAC7B,oEAAoE;QACpE,IAAInB,mBAAmBoB,GAAG,CAACD,gBAAgB;YACzC,IAAI,CAACvB,YAAYmB,sBAAsBI,gBAAgB;gBACrD,uEAAuE;gBACvE,gEAAgE;gBAChE,wEAAwE;gBACxE,4CAA4C;gBAC5C,2DAA2D;gBAE3D,mEAAmE;gBACnE,oEAAoE;gBACpE,MAAM,EAAEE,gBAAgB,EAAE,GAAGC,WAAW,GAAGtB,mBAAmBuB,GAAG,CAC/DJ,eACC;oBAAEN;gBAAO;gBACZW,OAAOC,MAAM,CAACV,sBAAsBO;gBACpC,IAAID,kBAAkB;oBACpBH,UAAUQ,IAAI,CAACL;gBACjB;YACF;YACAJ,aAAa,CAACE,cAAc,GAAGJ,oBAAoB,CAACI,cAAc;QACpE,OAAO,IAAIA,kBAAkB,YAAY;YACvC,iDAAiD;YACjDF,aAAa,CAACE,cAAc,GAAGP;QACjC,OAAO,IAAIO,iBAAiBtB,iBAAiB;YAC3CF,WAAW,CAAC,4BAA4B,EAAEwB,cAAc,CAAC,CAAC;YAC1D,uEAAuE;YACvE,iBAAiB;YACjB,MAAMQ,cAAc,AAAC9B,eAA2C,CAC9DsB,cACD;YACDF,aAAa,CAACE,cAAc,GAAGQ;QACjC,OAAO;YACL,uEAAuE;YACvE,oCAAoC;YACpC,MAAM,IAAIC,MAAM,CAAC,oBAAoB,EAAET,cAAc,EAAE,CAAC;QAC1D;QACA,OAAO;YAAEF;YAAeC;QAAU;IACpC,GACA;QACED,eAAe;YAAEN;QAAK;QACtBO,WAAW,EAAE;IACf;IAGF,MAAMW,WAAW;QACf,MAAMC,QAAQC,GAAG,CACff,OAAOE,SAAS,CAACc,GAAG,CAAC,CAACX,mBAAqBA;IAE/C;IACA,OAAO;QAAEP,YAAYE,OAAOC,aAAa;QAAEY;IAAS;AACtD"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/index.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { SnapsGlobalObject } from '@metamask/snaps-rpc-methods';\nimport type { SnapId } from '@metamask/snaps-utils';\nimport { logWarning } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\nimport buildCommonEndowments from './commonEndowmentFactory';\n\ntype EndowmentFactoryResult = {\n /**\n * A function that performs any necessary teardown when the snap becomes idle.\n *\n * NOTE:** The endowments are not reconstructed if the snap is re-invoked\n * before being terminated, so the teardown operation must not render the\n * endowments unusable; it should simply restore the endowments to their\n * original state.\n */\n teardownFunction?: () => Promise<void> | void;\n [key: string]: unknown;\n};\n\n/**\n * Retrieve consolidated endowment factories for common endowments.\n */\nconst registeredEndowments = buildCommonEndowments();\n\n/**\n * A map of endowment names to their factory functions. Some endowments share\n * the same factory function, but we only call each factory once for each snap.\n * See {@link createEndowments} for details.\n */\nconst endowmentFactories = registeredEndowments.reduce((factories, builder) => {\n builder.names.forEach((name) => {\n factories.set(name, builder.factory);\n });\n return factories;\n}, new Map<string, (options?: EndowmentFactoryOptions) => EndowmentFactoryResult>());\n\n/**\n * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`\n * and `clearTimeout`, must be attenuated so that they can only affect behavior\n * within the Snap's own realm. Therefore, we use factory functions to create\n * such attenuated / modified endowments. Otherwise, the value that's on the\n * root realm global will be used.\n *\n * @param snap - The Snaps global API object.\n * @param ethereum - The Snap's EIP-1193 provider object.\n * @param snapId - The id of the snap that will use the created endowments.\n * @param endowments - The list of endowments to provide to the snap.\n * @returns An object containing the Snap's endowments.\n */\nexport function createEndowments(\n snap: SnapsGlobalObject,\n ethereum: StreamProvider,\n snapId: SnapId,\n endowments: string[] = [],\n): { endowments: Record<string, unknown>; teardown: () => Promise<void> } {\n const attenuatedEndowments: Record<string, unknown> = {};\n\n // TODO: All endowments should be hardened to prevent covert communication\n // channels. Hardening the returned objects breaks tests elsewhere in the\n // monorepo, so further research is needed.\n const result = endowments.reduce<{\n allEndowments: Record<string, unknown>;\n teardowns: (() => Promise<void> | void)[];\n }>(\n ({ allEndowments, teardowns }, endowmentName) => {\n // First, check if the endowment has a factory, and default to that.\n if (endowmentFactories.has(endowmentName)) {\n if (!hasProperty(attenuatedEndowments, endowmentName)) {\n // Call the endowment factory for the current endowment. If the factory\n // creates multiple endowments, they will all be assigned to the\n // `attenuatedEndowments` object, but will only be passed on to the snap\n // if explicitly listed among its endowment.\n // This may not have an actual use case, but, safety first.\n\n // We just confirmed that endowmentFactories has the specified key.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { teardownFunction, ...endowment } = endowmentFactories.get(\n endowmentName,\n )!({ snapId });\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\n }\n allEndowments[endowmentName] = attenuatedEndowments[endowmentName];\n } else if (endowmentName === 'ethereum') {\n // Special case for adding the EIP-1193 provider.\n allEndowments[endowmentName] = ethereum;\n } else if (endowmentName in rootRealmGlobal) {\n logWarning(`Access to unhardened global ${endowmentName}.`);\n // If the endowment doesn't have a factory, just use whatever is on the\n // global object.\n const globalValue = (rootRealmGlobal as Record<string, unknown>)[\n endowmentName\n ];\n allEndowments[endowmentName] = globalValue;\n } else {\n // If we get to this point, we've been passed an endowment that doesn't\n // exist in our current environment.\n throw rpcErrors.internal(`Unknown endowment: \"${endowmentName}\".`);\n }\n return { allEndowments, teardowns };\n },\n {\n allEndowments: { snap },\n teardowns: [],\n },\n );\n\n const teardown = async () => {\n await Promise.all(\n result.teardowns.map((teardownFunction) => teardownFunction()),\n );\n };\n return { endowments: result.allEndowments, teardown };\n}\n"],"names":["rpcErrors","logWarning","hasProperty","rootRealmGlobal","buildCommonEndowments","registeredEndowments","endowmentFactories","reduce","factories","builder","names","forEach","name","set","factory","Map","createEndowments","snap","ethereum","snapId","endowments","attenuatedEndowments","result","allEndowments","teardowns","endowmentName","has","teardownFunction","endowment","get","Object","assign","push","globalValue","internal","teardown","Promise","all","map"],"mappings":"AACA,SAASA,SAAS,QAAQ,uBAAuB;AAGjD,SAASC,UAAU,QAAQ,wBAAwB;AACnD,SAASC,WAAW,QAAQ,kBAAkB;AAE9C,SAASC,eAAe,QAAQ,kBAAkB;AAElD,OAAOC,2BAA2B,2BAA2B;AAe7D;;CAEC,GACD,MAAMC,uBAAuBD;AAE7B;;;;CAIC,GACD,MAAME,qBAAqBD,qBAAqBE,MAAM,CAAC,CAACC,WAAWC;IACjEA,QAAQC,KAAK,CAACC,OAAO,CAAC,CAACC;QACrBJ,UAAUK,GAAG,CAACD,MAAMH,QAAQK,OAAO;IACrC;IACA,OAAON;AACT,GAAG,IAAIO;AAEP;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,iBACdC,IAAuB,EACvBC,QAAwB,EACxBC,MAAc,EACdC,aAAuB,EAAE;IAEzB,MAAMC,uBAAgD,CAAC;IAEvD,0EAA0E;IAC1E,yEAAyE;IACzE,2CAA2C;IAC3C,MAAMC,SAASF,WAAWb,MAAM,CAI9B,CAAC,EAAEgB,aAAa,EAAEC,SAAS,EAAE,EAAEC;QAC7B,oEAAoE;QACpE,IAAInB,mBAAmBoB,GAAG,CAACD,gBAAgB;YACzC,IAAI,CAACvB,YAAYmB,sBAAsBI,gBAAgB;gBACrD,uEAAuE;gBACvE,gEAAgE;gBAChE,wEAAwE;gBACxE,4CAA4C;gBAC5C,2DAA2D;gBAE3D,mEAAmE;gBACnE,oEAAoE;gBACpE,MAAM,EAAEE,gBAAgB,EAAE,GAAGC,WAAW,GAAGtB,mBAAmBuB,GAAG,CAC/DJ,eACC;oBAAEN;gBAAO;gBACZW,OAAOC,MAAM,CAACV,sBAAsBO;gBACpC,IAAID,kBAAkB;oBACpBH,UAAUQ,IAAI,CAACL;gBACjB;YACF;YACAJ,aAAa,CAACE,cAAc,GAAGJ,oBAAoB,CAACI,cAAc;QACpE,OAAO,IAAIA,kBAAkB,YAAY;YACvC,iDAAiD;YACjDF,aAAa,CAACE,cAAc,GAAGP;QACjC,OAAO,IAAIO,iBAAiBtB,iBAAiB;YAC3CF,WAAW,CAAC,4BAA4B,EAAEwB,cAAc,CAAC,CAAC;YAC1D,uEAAuE;YACvE,iBAAiB;YACjB,MAAMQ,cAAc,AAAC9B,eAA2C,CAC9DsB,cACD;YACDF,aAAa,CAACE,cAAc,GAAGQ;QACjC,OAAO;YACL,uEAAuE;YACvE,oCAAoC;YACpC,MAAMjC,UAAUkC,QAAQ,CAAC,CAAC,oBAAoB,EAAET,cAAc,EAAE,CAAC;QACnE;QACA,OAAO;YAAEF;YAAeC;QAAU;IACpC,GACA;QACED,eAAe;YAAEN;QAAK;QACtBO,WAAW,EAAE;IACf;IAGF,MAAMW,WAAW;QACf,MAAMC,QAAQC,GAAG,CACff,OAAOE,SAAS,CAACc,GAAG,CAAC,CAACX,mBAAqBA;IAE/C;IACA,OAAO;QAAEP,YAAYE,OAAOC,aAAa;QAAEY;IAAS;AACtD"}
@@ -1,3 +1,4 @@
1
+ import { rpcErrors } from '@metamask/rpc-errors';
1
2
  const MINIMUM_INTERVAL = 10;
2
3
  /**
3
4
  * Creates a pair of `setInterval` and `clearInterval` functions attenuated such
@@ -12,7 +13,7 @@ const MINIMUM_INTERVAL = 10;
12
13
  const registeredHandles = new Map();
13
14
  const _setInterval = (handler, timeout)=>{
14
15
  if (typeof handler !== 'function') {
15
- throw new Error(`The interval handler must be a function. Received: ${typeof handler}`);
16
+ throw rpcErrors.invalidInput(`The interval handler must be a function. Received: ${typeof handler}.`);
16
17
  }
17
18
  harden(handler);
18
19
  const handle = Object.freeze(Object.create(null));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/interval.ts"],"sourcesContent":["const MINIMUM_INTERVAL = 10;\n\n/**\n * Creates a pair of `setInterval` and `clearInterval` functions attenuated such\n * that:\n * - `setInterval` throws if its \"handler\" parameter is not a function.\n * - `clearInterval` only clears timeouts created by its sibling `setInterval`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setInterval` and `clearInterval`\n * functions.\n */\nconst createInterval = () => {\n const registeredHandles = new Map<unknown, unknown>();\n\n const _setInterval = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw new Error(\n `The interval handler must be a function. Received: ${typeof handler}`,\n );\n }\n harden(handler);\n const handle = Object.freeze(Object.create(null));\n const platformHandle = setInterval(\n handler,\n Math.max(MINIMUM_INTERVAL, timeout ?? 0),\n );\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearInterval = (handle: unknown): void => {\n harden(handle);\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearInterval(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearInterval(handle);\n }\n };\n\n return {\n setInterval: harden(_setInterval),\n clearInterval: harden(_clearInterval),\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setInterval', 'clearInterval'] as const,\n factory: createInterval,\n};\nexport default endowmentModule;\n"],"names":["MINIMUM_INTERVAL","createInterval","registeredHandles","Map","_setInterval","handler","timeout","Error","harden","handle","Object","freeze","create","platformHandle","setInterval","Math","max","set","_clearInterval","get","undefined","clearInterval","delete","teardownFunction","keys","endowmentModule","names","factory"],"mappings":"AAAA,MAAMA,mBAAmB;AAEzB;;;;;;;;;CASC,GACD,MAAMC,iBAAiB;IACrB,MAAMC,oBAAoB,IAAIC;IAE9B,MAAMC,eAAe,CAACC,SAAuBC;QAC3C,IAAI,OAAOD,YAAY,YAAY;YACjC,MAAM,IAAIE,MACR,CAAC,mDAAmD,EAAE,OAAOF,QAAQ,CAAC;QAE1E;QACAG,OAAOH;QACP,MAAMI,SAASC,OAAOC,MAAM,CAACD,OAAOE,MAAM,CAAC;QAC3C,MAAMC,iBAAiBC,YACrBT,SACAU,KAAKC,GAAG,CAAChB,kBAAkBM,WAAW;QAExCJ,kBAAkBe,GAAG,CAACR,QAAQI;QAC9B,OAAOJ;IACT;IAEA,MAAMS,iBAAiB,CAACT;QACtBD,OAAOC;QACP,MAAMI,iBAAiBX,kBAAkBiB,GAAG,CAACV;QAC7C,IAAII,mBAAmBO,WAAW;YAChCC,cAAcR;YACdX,kBAAkBoB,MAAM,CAACb;QAC3B;IACF;IAEA,MAAMc,mBAAmB;QACvB,KAAK,MAAMd,UAAUP,kBAAkBsB,IAAI,GAAI;YAC7CN,eAAeT;QACjB;IACF;IAEA,OAAO;QACLK,aAAaN,OAAOJ;QACpBiB,eAAeb,OAAOU;QACtBK;IACF;AACF;AAEA,MAAME,kBAAkB;IACtBC,OAAO;QAAC;QAAe;KAAgB;IACvCC,SAAS1B;AACX;AACA,eAAewB,gBAAgB"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/interval.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\n\nconst MINIMUM_INTERVAL = 10;\n\n/**\n * Creates a pair of `setInterval` and `clearInterval` functions attenuated such\n * that:\n * - `setInterval` throws if its \"handler\" parameter is not a function.\n * - `clearInterval` only clears timeouts created by its sibling `setInterval`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setInterval` and `clearInterval`\n * functions.\n */\nconst createInterval = () => {\n const registeredHandles = new Map<unknown, unknown>();\n\n const _setInterval = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw rpcErrors.invalidInput(\n `The interval handler must be a function. Received: ${typeof handler}.`,\n );\n }\n harden(handler);\n const handle = Object.freeze(Object.create(null));\n const platformHandle = setInterval(\n handler,\n Math.max(MINIMUM_INTERVAL, timeout ?? 0),\n );\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearInterval = (handle: unknown): void => {\n harden(handle);\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearInterval(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearInterval(handle);\n }\n };\n\n return {\n setInterval: harden(_setInterval),\n clearInterval: harden(_clearInterval),\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setInterval', 'clearInterval'] as const,\n factory: createInterval,\n};\nexport default endowmentModule;\n"],"names":["rpcErrors","MINIMUM_INTERVAL","createInterval","registeredHandles","Map","_setInterval","handler","timeout","invalidInput","harden","handle","Object","freeze","create","platformHandle","setInterval","Math","max","set","_clearInterval","get","undefined","clearInterval","delete","teardownFunction","keys","endowmentModule","names","factory"],"mappings":"AAAA,SAASA,SAAS,QAAQ,uBAAuB;AAEjD,MAAMC,mBAAmB;AAEzB;;;;;;;;;CASC,GACD,MAAMC,iBAAiB;IACrB,MAAMC,oBAAoB,IAAIC;IAE9B,MAAMC,eAAe,CAACC,SAAuBC;QAC3C,IAAI,OAAOD,YAAY,YAAY;YACjC,MAAMN,UAAUQ,YAAY,CAC1B,CAAC,mDAAmD,EAAE,OAAOF,QAAQ,CAAC,CAAC;QAE3E;QACAG,OAAOH;QACP,MAAMI,SAASC,OAAOC,MAAM,CAACD,OAAOE,MAAM,CAAC;QAC3C,MAAMC,iBAAiBC,YACrBT,SACAU,KAAKC,GAAG,CAAChB,kBAAkBM,WAAW;QAExCJ,kBAAkBe,GAAG,CAACR,QAAQI;QAC9B,OAAOJ;IACT;IAEA,MAAMS,iBAAiB,CAACT;QACtBD,OAAOC;QACP,MAAMI,iBAAiBX,kBAAkBiB,GAAG,CAACV;QAC7C,IAAII,mBAAmBO,WAAW;YAChCC,cAAcR;YACdX,kBAAkBoB,MAAM,CAACb;QAC3B;IACF;IAEA,MAAMc,mBAAmB;QACvB,KAAK,MAAMd,UAAUP,kBAAkBsB,IAAI,GAAI;YAC7CN,eAAeT;QACjB;IACF;IAEA,OAAO;QACLK,aAAaN,OAAOJ;QACpBiB,eAAeb,OAAOU;QACtBK;IACF;AACF;AAEA,MAAME,kBAAkB;IACtBC,OAAO;QAAC;QAAe;KAAgB;IACvCC,SAAS1B;AACX;AACA,eAAewB,gBAAgB"}
@@ -1,3 +1,4 @@
1
+ import { rpcErrors } from '@metamask/rpc-errors';
1
2
  const MINIMUM_TIMEOUT = 10;
2
3
  /**
3
4
  * Creates a pair of `setTimeout` and `clearTimeout` functions attenuated such
@@ -12,7 +13,7 @@ const MINIMUM_TIMEOUT = 10;
12
13
  const registeredHandles = new Map();
13
14
  const _setTimeout = (handler, timeout)=>{
14
15
  if (typeof handler !== 'function') {
15
- throw new Error(`The timeout handler must be a function. Received: ${typeof handler}`);
16
+ throw rpcErrors.internal(`The timeout handler must be a function. Received: ${typeof handler}.`);
16
17
  }
17
18
  harden(handler);
18
19
  const handle = Object.freeze(Object.create(null));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/timeout.ts"],"sourcesContent":["const MINIMUM_TIMEOUT = 10;\n\n/**\n * Creates a pair of `setTimeout` and `clearTimeout` functions attenuated such\n * that:\n * - `setTimeout` throws if its \"handler\" parameter is not a function.\n * - `clearTimeout` only clears timeouts created by its sibling `setTimeout`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setTimeout` and `clearTimeout`\n * functions.\n */\nconst createTimeout = () => {\n const registeredHandles = new Map<unknown, unknown>();\n const _setTimeout = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw new Error(\n `The timeout handler must be a function. Received: ${typeof handler}`,\n );\n }\n harden(handler);\n const handle = Object.freeze(Object.create(null));\n const platformHandle = setTimeout(() => {\n registeredHandles.delete(handle);\n handler();\n }, Math.max(MINIMUM_TIMEOUT, timeout ?? 0));\n\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearTimeout = (handle: unknown): void => {\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearTimeout(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearTimeout(handle);\n }\n };\n\n return {\n setTimeout: harden(_setTimeout),\n clearTimeout: harden(_clearTimeout),\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setTimeout', 'clearTimeout'] as const,\n factory: createTimeout,\n};\nexport default endowmentModule;\n"],"names":["MINIMUM_TIMEOUT","createTimeout","registeredHandles","Map","_setTimeout","handler","timeout","Error","harden","handle","Object","freeze","create","platformHandle","setTimeout","delete","Math","max","set","_clearTimeout","get","undefined","clearTimeout","teardownFunction","keys","endowmentModule","names","factory"],"mappings":"AAAA,MAAMA,kBAAkB;AAExB;;;;;;;;;CASC,GACD,MAAMC,gBAAgB;IACpB,MAAMC,oBAAoB,IAAIC;IAC9B,MAAMC,cAAc,CAACC,SAAuBC;QAC1C,IAAI,OAAOD,YAAY,YAAY;YACjC,MAAM,IAAIE,MACR,CAAC,kDAAkD,EAAE,OAAOF,QAAQ,CAAC;QAEzE;QACAG,OAAOH;QACP,MAAMI,SAASC,OAAOC,MAAM,CAACD,OAAOE,MAAM,CAAC;QAC3C,MAAMC,iBAAiBC,WAAW;YAChCZ,kBAAkBa,MAAM,CAACN;YACzBJ;QACF,GAAGW,KAAKC,GAAG,CAACjB,iBAAiBM,WAAW;QAExCJ,kBAAkBgB,GAAG,CAACT,QAAQI;QAC9B,OAAOJ;IACT;IAEA,MAAMU,gBAAgB,CAACV;QACrB,MAAMI,iBAAiBX,kBAAkBkB,GAAG,CAACX;QAC7C,IAAII,mBAAmBQ,WAAW;YAChCC,aAAaT;YACbX,kBAAkBa,MAAM,CAACN;QAC3B;IACF;IAEA,MAAMc,mBAAmB;QACvB,KAAK,MAAMd,UAAUP,kBAAkBsB,IAAI,GAAI;YAC7CL,cAAcV;QAChB;IACF;IAEA,OAAO;QACLK,YAAYN,OAAOJ;QACnBkB,cAAcd,OAAOW;QACrBI;IACF;AACF;AAEA,MAAME,kBAAkB;IACtBC,OAAO;QAAC;QAAc;KAAe;IACrCC,SAAS1B;AACX;AACA,eAAewB,gBAAgB"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/timeout.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\n\nconst MINIMUM_TIMEOUT = 10;\n\n/**\n * Creates a pair of `setTimeout` and `clearTimeout` functions attenuated such\n * that:\n * - `setTimeout` throws if its \"handler\" parameter is not a function.\n * - `clearTimeout` only clears timeouts created by its sibling `setTimeout`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setTimeout` and `clearTimeout`\n * functions.\n */\nconst createTimeout = () => {\n const registeredHandles = new Map<unknown, unknown>();\n const _setTimeout = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw rpcErrors.internal(\n `The timeout handler must be a function. Received: ${typeof handler}.`,\n );\n }\n harden(handler);\n const handle = Object.freeze(Object.create(null));\n const platformHandle = setTimeout(() => {\n registeredHandles.delete(handle);\n handler();\n }, Math.max(MINIMUM_TIMEOUT, timeout ?? 0));\n\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearTimeout = (handle: unknown): void => {\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearTimeout(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearTimeout(handle);\n }\n };\n\n return {\n setTimeout: harden(_setTimeout),\n clearTimeout: harden(_clearTimeout),\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setTimeout', 'clearTimeout'] as const,\n factory: createTimeout,\n};\nexport default endowmentModule;\n"],"names":["rpcErrors","MINIMUM_TIMEOUT","createTimeout","registeredHandles","Map","_setTimeout","handler","timeout","internal","harden","handle","Object","freeze","create","platformHandle","setTimeout","delete","Math","max","set","_clearTimeout","get","undefined","clearTimeout","teardownFunction","keys","endowmentModule","names","factory"],"mappings":"AAAA,SAASA,SAAS,QAAQ,uBAAuB;AAEjD,MAAMC,kBAAkB;AAExB;;;;;;;;;CASC,GACD,MAAMC,gBAAgB;IACpB,MAAMC,oBAAoB,IAAIC;IAC9B,MAAMC,cAAc,CAACC,SAAuBC;QAC1C,IAAI,OAAOD,YAAY,YAAY;YACjC,MAAMN,UAAUQ,QAAQ,CACtB,CAAC,kDAAkD,EAAE,OAAOF,QAAQ,CAAC,CAAC;QAE1E;QACAG,OAAOH;QACP,MAAMI,SAASC,OAAOC,MAAM,CAACD,OAAOE,MAAM,CAAC;QAC3C,MAAMC,iBAAiBC,WAAW;YAChCZ,kBAAkBa,MAAM,CAACN;YACzBJ;QACF,GAAGW,KAAKC,GAAG,CAACjB,iBAAiBM,WAAW;QAExCJ,kBAAkBgB,GAAG,CAACT,QAAQI;QAC9B,OAAOJ;IACT;IAEA,MAAMU,gBAAgB,CAACV;QACrB,MAAMI,iBAAiBX,kBAAkBkB,GAAG,CAACX;QAC7C,IAAII,mBAAmBQ,WAAW;YAChCC,aAAaT;YACbX,kBAAkBa,MAAM,CAACN;QAC3B;IACF;IAEA,MAAMc,mBAAmB;QACvB,KAAK,MAAMd,UAAUP,kBAAkBsB,IAAI,GAAI;YAC7CL,cAAcV;QAChB;IACF;IAEA,OAAO;QACLK,YAAYN,OAAOJ;QACnBkB,cAAcd,OAAOW;QACrBI;IACF;AACF;AAEA,MAAME,kBAAkB;IACtBC,OAAO;QAAC;QAAc;KAAe;IACrCC,SAAS1B;AACX;AACA,eAAewB,gBAAgB"}
@@ -1,3 +1,4 @@
1
+ import { rpcErrors } from '@metamask/rpc-errors';
1
2
  import { rootRealmGlobal } from './globalObject';
2
3
  /**
3
4
  * Adds an event listener platform agnostically, trying both `globalThis.addEventListener` and `globalThis.process.on`
@@ -13,7 +14,7 @@ import { rootRealmGlobal } from './globalObject';
13
14
  if (rootRealmGlobal.process && 'on' in rootRealmGlobal.process && typeof rootRealmGlobal.process.on === 'function') {
14
15
  return rootRealmGlobal.process.on(event, listener);
15
16
  }
16
- throw new Error('Platform agnostic addEventListener failed');
17
+ throw rpcErrors.internal('Platform agnostic addEventListener failed.');
17
18
  }
18
19
  /**
19
20
  * Removes an event listener platform agnostically, trying both `globalThis.removeEventListener` and `globalThis.process.removeListener`
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/globalEvents.ts"],"sourcesContent":["import { rootRealmGlobal } from './globalObject';\n\n/**\n * Adds an event listener platform agnostically, trying both `globalThis.addEventListener` and `globalThis.process.on`\n *\n * @param event - The event to listen for.\n * @param listener - The listener to be triggered when the event occurs.\n * @returns The result of the platform agnostic operation if any.\n * @throws If none of the platform options are present.\n */\nexport function addEventListener(\n event: string,\n listener: (...args: any[]) => void,\n) {\n if (\n 'addEventListener' in rootRealmGlobal &&\n typeof rootRealmGlobal.addEventListener === 'function'\n ) {\n return rootRealmGlobal.addEventListener(event.toLowerCase(), listener);\n }\n\n if (\n rootRealmGlobal.process &&\n 'on' in rootRealmGlobal.process &&\n typeof rootRealmGlobal.process.on === 'function'\n ) {\n return rootRealmGlobal.process.on(event, listener);\n }\n\n throw new Error('Platform agnostic addEventListener failed');\n}\n\n/**\n * Removes an event listener platform agnostically, trying both `globalThis.removeEventListener` and `globalThis.process.removeListener`\n *\n * @param event - The event to remove the listener for.\n * @param listener - The currently attached listener.\n * @returns The result of the platform agnostic operation if any.\n * @throws If none of the platform options are present.\n */\nexport function removeEventListener(\n event: string,\n listener: (...args: any[]) => void,\n) {\n if (\n 'removeEventListener' in rootRealmGlobal &&\n typeof rootRealmGlobal.removeEventListener === 'function'\n ) {\n return rootRealmGlobal.removeEventListener(event.toLowerCase(), listener);\n }\n\n if (\n rootRealmGlobal.process &&\n 'removeListener' in rootRealmGlobal.process &&\n typeof rootRealmGlobal.process.removeListener === 'function'\n ) {\n return rootRealmGlobal.process.removeListener(event, listener);\n }\n\n throw new Error('Platform agnostic removeEventListener failed');\n}\n"],"names":["rootRealmGlobal","addEventListener","event","listener","toLowerCase","process","on","Error","removeEventListener","removeListener"],"mappings":"AAAA,SAASA,eAAe,QAAQ,iBAAiB;AAEjD;;;;;;;CAOC,GACD,OAAO,SAASC,iBACdC,KAAa,EACbC,QAAkC;IAElC,IACE,sBAAsBH,mBACtB,OAAOA,gBAAgBC,gBAAgB,KAAK,YAC5C;QACA,OAAOD,gBAAgBC,gBAAgB,CAACC,MAAME,WAAW,IAAID;IAC/D;IAEA,IACEH,gBAAgBK,OAAO,IACvB,QAAQL,gBAAgBK,OAAO,IAC/B,OAAOL,gBAAgBK,OAAO,CAACC,EAAE,KAAK,YACtC;QACA,OAAON,gBAAgBK,OAAO,CAACC,EAAE,CAACJ,OAAOC;IAC3C;IAEA,MAAM,IAAII,MAAM;AAClB;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC,oBACdN,KAAa,EACbC,QAAkC;IAElC,IACE,yBAAyBH,mBACzB,OAAOA,gBAAgBQ,mBAAmB,KAAK,YAC/C;QACA,OAAOR,gBAAgBQ,mBAAmB,CAACN,MAAME,WAAW,IAAID;IAClE;IAEA,IACEH,gBAAgBK,OAAO,IACvB,oBAAoBL,gBAAgBK,OAAO,IAC3C,OAAOL,gBAAgBK,OAAO,CAACI,cAAc,KAAK,YAClD;QACA,OAAOT,gBAAgBK,OAAO,CAACI,cAAc,CAACP,OAAOC;IACvD;IAEA,MAAM,IAAII,MAAM;AAClB"}
1
+ {"version":3,"sources":["../../../src/common/globalEvents.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\n\nimport { rootRealmGlobal } from './globalObject';\n\n/**\n * Adds an event listener platform agnostically, trying both `globalThis.addEventListener` and `globalThis.process.on`\n *\n * @param event - The event to listen for.\n * @param listener - The listener to be triggered when the event occurs.\n * @returns The result of the platform agnostic operation if any.\n * @throws If none of the platform options are present.\n */\nexport function addEventListener(\n event: string,\n listener: (...args: any[]) => void,\n) {\n if (\n 'addEventListener' in rootRealmGlobal &&\n typeof rootRealmGlobal.addEventListener === 'function'\n ) {\n return rootRealmGlobal.addEventListener(event.toLowerCase(), listener);\n }\n\n if (\n rootRealmGlobal.process &&\n 'on' in rootRealmGlobal.process &&\n typeof rootRealmGlobal.process.on === 'function'\n ) {\n return rootRealmGlobal.process.on(event, listener);\n }\n\n throw rpcErrors.internal('Platform agnostic addEventListener failed.');\n}\n\n/**\n * Removes an event listener platform agnostically, trying both `globalThis.removeEventListener` and `globalThis.process.removeListener`\n *\n * @param event - The event to remove the listener for.\n * @param listener - The currently attached listener.\n * @returns The result of the platform agnostic operation if any.\n * @throws If none of the platform options are present.\n */\nexport function removeEventListener(\n event: string,\n listener: (...args: any[]) => void,\n) {\n if (\n 'removeEventListener' in rootRealmGlobal &&\n typeof rootRealmGlobal.removeEventListener === 'function'\n ) {\n return rootRealmGlobal.removeEventListener(event.toLowerCase(), listener);\n }\n\n if (\n rootRealmGlobal.process &&\n 'removeListener' in rootRealmGlobal.process &&\n typeof rootRealmGlobal.process.removeListener === 'function'\n ) {\n return rootRealmGlobal.process.removeListener(event, listener);\n }\n\n throw new Error('Platform agnostic removeEventListener failed');\n}\n"],"names":["rpcErrors","rootRealmGlobal","addEventListener","event","listener","toLowerCase","process","on","internal","removeEventListener","removeListener","Error"],"mappings":"AAAA,SAASA,SAAS,QAAQ,uBAAuB;AAEjD,SAASC,eAAe,QAAQ,iBAAiB;AAEjD;;;;;;;CAOC,GACD,OAAO,SAASC,iBACdC,KAAa,EACbC,QAAkC;IAElC,IACE,sBAAsBH,mBACtB,OAAOA,gBAAgBC,gBAAgB,KAAK,YAC5C;QACA,OAAOD,gBAAgBC,gBAAgB,CAACC,MAAME,WAAW,IAAID;IAC/D;IAEA,IACEH,gBAAgBK,OAAO,IACvB,QAAQL,gBAAgBK,OAAO,IAC/B,OAAOL,gBAAgBK,OAAO,CAACC,EAAE,KAAK,YACtC;QACA,OAAON,gBAAgBK,OAAO,CAACC,EAAE,CAACJ,OAAOC;IAC3C;IAEA,MAAMJ,UAAUQ,QAAQ,CAAC;AAC3B;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC,oBACdN,KAAa,EACbC,QAAkC;IAElC,IACE,yBAAyBH,mBACzB,OAAOA,gBAAgBQ,mBAAmB,KAAK,YAC/C;QACA,OAAOR,gBAAgBQ,mBAAmB,CAACN,MAAME,WAAW,IAAID;IAClE;IAEA,IACEH,gBAAgBK,OAAO,IACvB,oBAAoBL,gBAAgBK,OAAO,IAC3C,OAAOL,gBAAgBK,OAAO,CAACI,cAAc,KAAK,YAClD;QACA,OAAOT,gBAAgBK,OAAO,CAACI,cAAc,CAACP,OAAOC;IACvD;IAEA,MAAM,IAAIO,MAAM;AAClB"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/globalObject.ts"],"sourcesContent":["enum GlobalObjectNames {\n // The globalThis entry is incorrectly identified as shadowing the global\n // globalThis.\n /* eslint-disable @typescript-eslint/naming-convention */\n // eslint-disable-next-line @typescript-eslint/no-shadow\n globalThis = 'globalThis',\n global = 'global',\n self = 'self',\n window = 'window',\n /* eslint-enavle @typescript-eslint/naming-convention */\n}\n\nlet _rootRealmGlobal: typeof globalThis;\nlet _rootRealmGlobalName: string;\n\n/* istanbul ignore next */\n/* eslint-disable no-negated-condition */\nif (typeof globalThis !== 'undefined') {\n _rootRealmGlobal = globalThis;\n _rootRealmGlobalName = GlobalObjectNames.globalThis;\n} else if (typeof self !== 'undefined') {\n _rootRealmGlobal = self;\n _rootRealmGlobalName = GlobalObjectNames.self;\n} else if (typeof window !== 'undefined') {\n _rootRealmGlobal = window;\n _rootRealmGlobalName = GlobalObjectNames.window;\n} else if (typeof global !== 'undefined') {\n _rootRealmGlobal = global;\n _rootRealmGlobalName = GlobalObjectNames.global;\n} else {\n throw new Error('Unknown realm type; failed to identify global object.');\n}\n/* eslint-enable no-negated-condition */\n\n/**\n * A platform-agnostic alias for the root realm global object.\n */\nconst rootRealmGlobal = _rootRealmGlobal;\n\n/**\n * The string literal corresponding to the name of the root realm global object.\n */\nconst rootRealmGlobalName = _rootRealmGlobalName;\n\nexport { rootRealmGlobal, rootRealmGlobalName };\n"],"names":["GlobalObjectNames","globalThis","global","self","window","_rootRealmGlobal","_rootRealmGlobalName","Error","rootRealmGlobal","rootRealmGlobalName"],"mappings":"IAAA;UAAKA,iBAAiB;IAAjBA,kBACH,yEAAyE;IACzE,cAAc;IACd,uDAAuD,GACvD,wDAAwD;IACxDC,gBAAAA;IALGD,kBAMHE,YAAAA;IANGF,kBAOHG,UAAAA;IAPGH,kBAQHI,YAAAA;GARGJ,sBAAAA;AAYL,IAAIK;AACJ,IAAIC;AAEJ,wBAAwB,GACxB,uCAAuC,GACvC,IAAI,OAAOL,eAAe,aAAa;IACrCI,mBAAmBJ;IACnBK,uBAAuBN,kBAAkBC,UAAU;AACrD,OAAO,IAAI,OAAOE,SAAS,aAAa;IACtCE,mBAAmBF;IACnBG,uBAAuBN,kBAAkBG,IAAI;AAC/C,OAAO,IAAI,OAAOC,WAAW,aAAa;IACxCC,mBAAmBD;IACnBE,uBAAuBN,kBAAkBI,MAAM;AACjD,OAAO,IAAI,OAAOF,WAAW,aAAa;IACxCG,mBAAmBH;IACnBI,uBAAuBN,kBAAkBE,MAAM;AACjD,OAAO;IACL,MAAM,IAAIK,MAAM;AAClB;AACA,sCAAsC,GAEtC;;CAEC,GACD,MAAMC,kBAAkBH;AAExB;;CAEC,GACD,MAAMI,sBAAsBH;AAE5B,SAASE,eAAe,EAAEC,mBAAmB,GAAG"}
1
+ {"version":3,"sources":["../../../src/common/globalObject.ts"],"sourcesContent":["enum GlobalObjectNames {\n // The globalThis entry is incorrectly identified as shadowing the global\n // globalThis.\n /* eslint-disable @typescript-eslint/naming-convention */\n // eslint-disable-next-line @typescript-eslint/no-shadow\n globalThis = 'globalThis',\n global = 'global',\n self = 'self',\n window = 'window',\n /* eslint-enable @typescript-eslint/naming-convention */\n}\n\nlet _rootRealmGlobal: typeof globalThis;\nlet _rootRealmGlobalName: string;\n\n/* istanbul ignore next */\n/* eslint-disable no-negated-condition */\nif (typeof globalThis !== 'undefined') {\n _rootRealmGlobal = globalThis;\n _rootRealmGlobalName = GlobalObjectNames.globalThis;\n} else if (typeof self !== 'undefined') {\n _rootRealmGlobal = self;\n _rootRealmGlobalName = GlobalObjectNames.self;\n} else if (typeof window !== 'undefined') {\n _rootRealmGlobal = window;\n _rootRealmGlobalName = GlobalObjectNames.window;\n} else if (typeof global !== 'undefined') {\n _rootRealmGlobal = global;\n _rootRealmGlobalName = GlobalObjectNames.global;\n} else {\n throw new Error('Unknown realm type; failed to identify global object.');\n}\n/* eslint-enable no-negated-condition */\n\n/**\n * A platform-agnostic alias for the root realm global object.\n */\nconst rootRealmGlobal = _rootRealmGlobal;\n\n/**\n * The string literal corresponding to the name of the root realm global object.\n */\nconst rootRealmGlobalName = _rootRealmGlobalName;\n\nexport { rootRealmGlobal, rootRealmGlobalName };\n"],"names":["GlobalObjectNames","globalThis","global","self","window","_rootRealmGlobal","_rootRealmGlobalName","Error","rootRealmGlobal","rootRealmGlobalName"],"mappings":"IAAA;UAAKA,iBAAiB;IAAjBA,kBACH,yEAAyE;IACzE,cAAc;IACd,uDAAuD,GACvD,wDAAwD;IACxDC,gBAAAA;IALGD,kBAMHE,YAAAA;IANGF,kBAOHG,UAAAA;IAPGH,kBAQHI,YAAAA;GARGJ,sBAAAA;AAYL,IAAIK;AACJ,IAAIC;AAEJ,wBAAwB,GACxB,uCAAuC,GACvC,IAAI,OAAOL,eAAe,aAAa;IACrCI,mBAAmBJ;IACnBK,uBAAuBN,kBAAkBC,UAAU;AACrD,OAAO,IAAI,OAAOE,SAAS,aAAa;IACtCE,mBAAmBF;IACnBG,uBAAuBN,kBAAkBG,IAAI;AAC/C,OAAO,IAAI,OAAOC,WAAW,aAAa;IACxCC,mBAAmBD;IACnBE,uBAAuBN,kBAAkBI,MAAM;AACjD,OAAO,IAAI,OAAOF,WAAW,aAAa;IACxCG,mBAAmBH;IACnBI,uBAAuBN,kBAAkBE,MAAM;AACjD,OAAO;IACL,MAAM,IAAIK,MAAM;AAClB;AACA,sCAAsC,GAEtC;;CAEC,GACD,MAAMC,kBAAkBH;AAExB;;CAEC,GACD,MAAMI,sBAAsBH;AAE5B,SAASE,eAAe,EAAEC,mBAAmB,GAAG"}
@@ -1,24 +1,6 @@
1
+ import { rpcErrors } from '@metamask/rpc-errors';
1
2
  import { assert, assertStruct, getSafeJson, JsonStruct } from '@metamask/utils';
2
- import { ethErrors } from 'eth-rpc-errors';
3
3
  import { log } from '../logging';
4
- /**
5
- * Takes an error that was thrown, determines if it is
6
- * an error object. If it is then it will return that. Otherwise,
7
- * an error object is created with the original error message.
8
- *
9
- * @param originalError - The error that was originally thrown.
10
- * @returns An error object.
11
- */ export function constructError(originalError) {
12
- let _originalError;
13
- if (originalError instanceof Error) {
14
- _originalError = originalError;
15
- } else if (typeof originalError === 'string') {
16
- _originalError = new Error(originalError);
17
- // The stack is useless in this case.
18
- delete _originalError.stack;
19
- }
20
- return _originalError;
21
- }
22
4
  /**
23
5
  * Make proxy for Promise and handle the teardown process properly.
24
6
  * If the teardown is called in the meanwhile, Promise result will not be
@@ -104,13 +86,13 @@ export const BLOCKED_RPC_METHODS = Object.freeze([
104
86
  * @param args - The arguments to validate.
105
87
  */ export function assertSnapOutboundRequest(args) {
106
88
  // Disallow any non `wallet_` or `snap_` methods for separation of concerns.
107
- assert(String.prototype.startsWith.call(args.method, 'wallet_') || String.prototype.startsWith.call(args.method, 'snap_'), 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.');
108
- assert(!BLOCKED_RPC_METHODS.includes(args.method), ethErrors.rpc.methodNotFound({
89
+ assert(String.prototype.startsWith.call(args.method, 'wallet_') || String.prototype.startsWith.call(args.method, 'snap_'), 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.', rpcErrors.methodNotSupported);
90
+ assert(!BLOCKED_RPC_METHODS.includes(args.method), rpcErrors.methodNotFound({
109
91
  data: {
110
92
  method: args.method
111
93
  }
112
94
  }));
113
- assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');
95
+ assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible', rpcErrors.invalidParams);
114
96
  }
115
97
  /**
116
98
  * Asserts the validity of request arguments for an ethereum outbound request using the `ethereum.request` API.
@@ -118,17 +100,17 @@ export const BLOCKED_RPC_METHODS = Object.freeze([
118
100
  * @param args - The arguments to validate.
119
101
  */ export function assertEthereumOutboundRequest(args) {
120
102
  // Disallow snaps methods for separation of concerns.
121
- assert(!String.prototype.startsWith.call(args.method, 'snap_'), ethErrors.rpc.methodNotFound({
103
+ assert(!String.prototype.startsWith.call(args.method, 'snap_'), rpcErrors.methodNotFound({
122
104
  data: {
123
105
  method: args.method
124
106
  }
125
107
  }));
126
- assert(!BLOCKED_RPC_METHODS.includes(args.method), ethErrors.rpc.methodNotFound({
108
+ assert(!BLOCKED_RPC_METHODS.includes(args.method), rpcErrors.methodNotFound({
127
109
  data: {
128
110
  method: args.method
129
111
  }
130
112
  }));
131
- assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');
113
+ assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible', rpcErrors.invalidParams);
132
114
  }
133
115
  /**
134
116
  * Gets a sanitized value to be used for passing to the underlying MetaMask provider.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/utils.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { assert, assertStruct, getSafeJson, JsonStruct } from '@metamask/utils';\nimport { ethErrors } from 'eth-rpc-errors';\n\nimport { log } from '../logging';\n\n/**\n * Takes an error that was thrown, determines if it is\n * an error object. If it is then it will return that. Otherwise,\n * an error object is created with the original error message.\n *\n * @param originalError - The error that was originally thrown.\n * @returns An error object.\n */\nexport function constructError(originalError: unknown) {\n let _originalError: Error | undefined;\n if (originalError instanceof Error) {\n _originalError = originalError;\n } else if (typeof originalError === 'string') {\n _originalError = new Error(originalError);\n // The stack is useless in this case.\n delete _originalError.stack;\n }\n return _originalError;\n}\n\n/**\n * Make proxy for Promise and handle the teardown process properly.\n * If the teardown is called in the meanwhile, Promise result will not be\n * exposed to the snap anymore and warning will be logged to the console.\n *\n * @param originalPromise - Original promise.\n * @param teardownRef - Reference containing teardown count.\n * @param teardownRef.lastTeardown - Number of the last teardown.\n * @returns New proxy promise.\n */\nexport async function withTeardown<Type>(\n originalPromise: Promise<Type>,\n teardownRef: { lastTeardown: number },\n): Promise<Type> {\n const myTeardown = teardownRef.lastTeardown;\n return new Promise<Type>((resolve, reject) => {\n originalPromise\n .then((value) => {\n if (teardownRef.lastTeardown === myTeardown) {\n resolve(value);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n })\n .catch((reason) => {\n if (teardownRef.lastTeardown === myTeardown) {\n reject(reason);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n });\n });\n}\n\n/**\n * Returns a Proxy that narrows down (attenuates) the fields available on\n * the StreamProvider and replaces the request implementation.\n *\n * @param provider - Instance of a StreamProvider to be limited.\n * @param request - Custom attenuated request object.\n * @returns Proxy to the StreamProvider instance.\n */\nexport function proxyStreamProvider(\n provider: StreamProvider,\n request: unknown,\n): StreamProvider {\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const proxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return (\n typeof prop === 'string' &&\n ['request', 'on', 'removeListener'].includes(prop)\n );\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n } else if (['on', 'removeListener'].includes(prop)) {\n return provider[prop];\n }\n\n return undefined;\n },\n },\n );\n\n return proxy as StreamProvider;\n}\n\n// We're blocking these RPC methods for v1, will revisit later.\nexport const BLOCKED_RPC_METHODS = Object.freeze([\n 'wallet_requestSnaps',\n 'wallet_requestPermissions',\n // We disallow all of these confirmations for now, since the screens are not ready for Snaps.\n 'eth_sendRawTransaction',\n 'eth_sendTransaction',\n 'eth_sign',\n 'eth_signTypedData',\n 'eth_signTypedData_v1',\n 'eth_signTypedData_v3',\n 'eth_signTypedData_v4',\n 'eth_decrypt',\n 'eth_getEncryptionPublicKey',\n 'wallet_addEthereumChain',\n 'wallet_switchEthereumChain',\n 'wallet_watchAsset',\n 'wallet_registerOnboarding',\n 'wallet_scanQRCode',\n]);\n\n/**\n * Asserts the validity of request arguments for a snap outbound request using the `snap.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertSnapOutboundRequest(args: RequestArguments) {\n // Disallow any non `wallet_` or `snap_` methods for separation of concerns.\n assert(\n String.prototype.startsWith.call(args.method, 'wallet_') ||\n String.prototype.startsWith.call(args.method, 'snap_'),\n 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.',\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');\n}\n\n/**\n * Asserts the validity of request arguments for an ethereum outbound request using the `ethereum.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertEthereumOutboundRequest(args: RequestArguments) {\n // Disallow snaps methods for separation of concerns.\n assert(\n !String.prototype.startsWith.call(args.method, 'snap_'),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');\n}\n\n/**\n * Gets a sanitized value to be used for passing to the underlying MetaMask provider.\n *\n * @param value - An unsanitized value from a snap.\n * @returns A sanitized value ready to be passed to a MetaMask provider.\n */\nexport function sanitizeRequestArguments(value: unknown): RequestArguments {\n // Before passing to getSafeJson we run the value through JSON serialization.\n // This lets request arguments contain undefined which is normally disallowed.\n const json = JSON.parse(JSON.stringify(value));\n return getSafeJson(json) as RequestArguments;\n}\n"],"names":["assert","assertStruct","getSafeJson","JsonStruct","ethErrors","log","constructError","originalError","_originalError","Error","stack","withTeardown","originalPromise","teardownRef","myTeardown","lastTeardown","Promise","resolve","reject","then","value","catch","reason","proxyStreamProvider","provider","request","proxy","Proxy","has","_target","prop","includes","get","undefined","BLOCKED_RPC_METHODS","Object","freeze","assertSnapOutboundRequest","args","String","prototype","startsWith","call","method","rpc","methodNotFound","data","assertEthereumOutboundRequest","sanitizeRequestArguments","json","JSON","parse","stringify"],"mappings":"AAEA,SAASA,MAAM,EAAEC,YAAY,EAAEC,WAAW,EAAEC,UAAU,QAAQ,kBAAkB;AAChF,SAASC,SAAS,QAAQ,iBAAiB;AAE3C,SAASC,GAAG,QAAQ,aAAa;AAEjC;;;;;;;CAOC,GACD,OAAO,SAASC,eAAeC,aAAsB;IACnD,IAAIC;IACJ,IAAID,yBAAyBE,OAAO;QAClCD,iBAAiBD;IACnB,OAAO,IAAI,OAAOA,kBAAkB,UAAU;QAC5CC,iBAAiB,IAAIC,MAAMF;QAC3B,qCAAqC;QACrC,OAAOC,eAAeE,KAAK;IAC7B;IACA,OAAOF;AACT;AAEA;;;;;;;;;CASC,GACD,OAAO,eAAeG,aACpBC,eAA8B,EAC9BC,WAAqC;IAErC,MAAMC,aAAaD,YAAYE,YAAY;IAC3C,OAAO,IAAIC,QAAc,CAACC,SAASC;QACjCN,gBACGO,IAAI,CAAC,CAACC;YACL,IAAIP,YAAYE,YAAY,KAAKD,YAAY;gBAC3CG,QAAQG;YACV,OAAO;gBACLf,IACE;YAEJ;QACF,GACCgB,KAAK,CAAC,CAACC;YACN,IAAIT,YAAYE,YAAY,KAAKD,YAAY;gBAC3CI,OAAOI;YACT,OAAO;gBACLjB,IACE;YAEJ;QACF;IACJ;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,SAASkB,oBACdC,QAAwB,EACxBC,OAAgB;IAEhB,qEAAqE;IACrE,sDAAsD;IACtD,MAAMC,QAAQ,IAAIC,MAChB,CAAC,GACD;QACEC,KAAIC,OAAe,EAAEC,IAAqB;YACxC,OACE,OAAOA,SAAS,YAChB;gBAAC;gBAAW;gBAAM;aAAiB,CAACC,QAAQ,CAACD;QAEjD;QACAE,KAAIH,OAAO,EAAEC,IAA0B;YACrC,IAAIA,SAAS,WAAW;gBACtB,OAAOL;YACT,OAAO,IAAI;gBAAC;gBAAM;aAAiB,CAACM,QAAQ,CAACD,OAAO;gBAClD,OAAON,QAAQ,CAACM,KAAK;YACvB;YAEA,OAAOG;QACT;IACF;IAGF,OAAOP;AACT;AAEA,+DAA+D;AAC/D,OAAO,MAAMQ,sBAAsBC,OAAOC,MAAM,CAAC;IAC/C;IACA;IACA,6FAA6F;IAC7F;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,EAAE;AAEH;;;;CAIC,GACD,OAAO,SAASC,0BAA0BC,IAAsB;IAC9D,4EAA4E;IAC5EtC,OACEuC,OAAOC,SAAS,CAACC,UAAU,CAACC,IAAI,CAACJ,KAAKK,MAAM,EAAE,cAC5CJ,OAAOC,SAAS,CAACC,UAAU,CAACC,IAAI,CAACJ,KAAKK,MAAM,EAAE,UAChD;IAEF3C,OACE,CAACkC,oBAAoBH,QAAQ,CAACO,KAAKK,MAAM,GACzCvC,UAAUwC,GAAG,CAACC,cAAc,CAAC;QAC3BC,MAAM;YACJH,QAAQL,KAAKK,MAAM;QACrB;IACF;IAEF1C,aAAaqC,MAAMnC,YAAY;AACjC;AAEA;;;;CAIC,GACD,OAAO,SAAS4C,8BAA8BT,IAAsB;IAClE,qDAAqD;IACrDtC,OACE,CAACuC,OAAOC,SAAS,CAACC,UAAU,CAACC,IAAI,CAACJ,KAAKK,MAAM,EAAE,UAC/CvC,UAAUwC,GAAG,CAACC,cAAc,CAAC;QAC3BC,MAAM;YACJH,QAAQL,KAAKK,MAAM;QACrB;IACF;IAEF3C,OACE,CAACkC,oBAAoBH,QAAQ,CAACO,KAAKK,MAAM,GACzCvC,UAAUwC,GAAG,CAACC,cAAc,CAAC;QAC3BC,MAAM;YACJH,QAAQL,KAAKK,MAAM;QACrB;IACF;IAEF1C,aAAaqC,MAAMnC,YAAY;AACjC;AAEA;;;;;CAKC,GACD,OAAO,SAAS6C,yBAAyB5B,KAAc;IACrD,6EAA6E;IAC7E,8EAA8E;IAC9E,MAAM6B,OAAOC,KAAKC,KAAK,CAACD,KAAKE,SAAS,CAAChC;IACvC,OAAOlB,YAAY+C;AACrB"}
1
+ {"version":3,"sources":["../../../src/common/utils.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { assert, assertStruct, getSafeJson, JsonStruct } from '@metamask/utils';\n\nimport { log } from '../logging';\n/**\n * Make proxy for Promise and handle the teardown process properly.\n * If the teardown is called in the meanwhile, Promise result will not be\n * exposed to the snap anymore and warning will be logged to the console.\n *\n * @param originalPromise - Original promise.\n * @param teardownRef - Reference containing teardown count.\n * @param teardownRef.lastTeardown - Number of the last teardown.\n * @returns New proxy promise.\n */\nexport async function withTeardown<Type>(\n originalPromise: Promise<Type>,\n teardownRef: { lastTeardown: number },\n): Promise<Type> {\n const myTeardown = teardownRef.lastTeardown;\n return new Promise<Type>((resolve, reject) => {\n originalPromise\n .then((value) => {\n if (teardownRef.lastTeardown === myTeardown) {\n resolve(value);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n })\n .catch((reason) => {\n if (teardownRef.lastTeardown === myTeardown) {\n reject(reason);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n });\n });\n}\n\n/**\n * Returns a Proxy that narrows down (attenuates) the fields available on\n * the StreamProvider and replaces the request implementation.\n *\n * @param provider - Instance of a StreamProvider to be limited.\n * @param request - Custom attenuated request object.\n * @returns Proxy to the StreamProvider instance.\n */\nexport function proxyStreamProvider(\n provider: StreamProvider,\n request: unknown,\n): StreamProvider {\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const proxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return (\n typeof prop === 'string' &&\n ['request', 'on', 'removeListener'].includes(prop)\n );\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n } else if (['on', 'removeListener'].includes(prop)) {\n return provider[prop];\n }\n\n return undefined;\n },\n },\n );\n\n return proxy as StreamProvider;\n}\n\n// We're blocking these RPC methods for v1, will revisit later.\nexport const BLOCKED_RPC_METHODS = Object.freeze([\n 'wallet_requestSnaps',\n 'wallet_requestPermissions',\n // We disallow all of these confirmations for now, since the screens are not ready for Snaps.\n 'eth_sendRawTransaction',\n 'eth_sendTransaction',\n 'eth_sign',\n 'eth_signTypedData',\n 'eth_signTypedData_v1',\n 'eth_signTypedData_v3',\n 'eth_signTypedData_v4',\n 'eth_decrypt',\n 'eth_getEncryptionPublicKey',\n 'wallet_addEthereumChain',\n 'wallet_switchEthereumChain',\n 'wallet_watchAsset',\n 'wallet_registerOnboarding',\n 'wallet_scanQRCode',\n]);\n\n/**\n * Asserts the validity of request arguments for a snap outbound request using the `snap.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertSnapOutboundRequest(args: RequestArguments) {\n // Disallow any non `wallet_` or `snap_` methods for separation of concerns.\n assert(\n String.prototype.startsWith.call(args.method, 'wallet_') ||\n String.prototype.startsWith.call(args.method, 'snap_'),\n 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.',\n rpcErrors.methodNotSupported,\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n rpcErrors.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(\n args,\n JsonStruct,\n 'Provided value is not JSON-RPC compatible',\n rpcErrors.invalidParams,\n );\n}\n\n/**\n * Asserts the validity of request arguments for an ethereum outbound request using the `ethereum.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertEthereumOutboundRequest(args: RequestArguments) {\n // Disallow snaps methods for separation of concerns.\n assert(\n !String.prototype.startsWith.call(args.method, 'snap_'),\n rpcErrors.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n rpcErrors.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(\n args,\n JsonStruct,\n 'Provided value is not JSON-RPC compatible',\n rpcErrors.invalidParams,\n );\n}\n\n/**\n * Gets a sanitized value to be used for passing to the underlying MetaMask provider.\n *\n * @param value - An unsanitized value from a snap.\n * @returns A sanitized value ready to be passed to a MetaMask provider.\n */\nexport function sanitizeRequestArguments(value: unknown): RequestArguments {\n // Before passing to getSafeJson we run the value through JSON serialization.\n // This lets request arguments contain undefined which is normally disallowed.\n const json = JSON.parse(JSON.stringify(value));\n return getSafeJson(json) as RequestArguments;\n}\n"],"names":["rpcErrors","assert","assertStruct","getSafeJson","JsonStruct","log","withTeardown","originalPromise","teardownRef","myTeardown","lastTeardown","Promise","resolve","reject","then","value","catch","reason","proxyStreamProvider","provider","request","proxy","Proxy","has","_target","prop","includes","get","undefined","BLOCKED_RPC_METHODS","Object","freeze","assertSnapOutboundRequest","args","String","prototype","startsWith","call","method","methodNotSupported","methodNotFound","data","invalidParams","assertEthereumOutboundRequest","sanitizeRequestArguments","json","JSON","parse","stringify"],"mappings":"AAEA,SAASA,SAAS,QAAQ,uBAAuB;AACjD,SAASC,MAAM,EAAEC,YAAY,EAAEC,WAAW,EAAEC,UAAU,QAAQ,kBAAkB;AAEhF,SAASC,GAAG,QAAQ,aAAa;AACjC;;;;;;;;;CASC,GACD,OAAO,eAAeC,aACpBC,eAA8B,EAC9BC,WAAqC;IAErC,MAAMC,aAAaD,YAAYE,YAAY;IAC3C,OAAO,IAAIC,QAAc,CAACC,SAASC;QACjCN,gBACGO,IAAI,CAAC,CAACC;YACL,IAAIP,YAAYE,YAAY,KAAKD,YAAY;gBAC3CG,QAAQG;YACV,OAAO;gBACLV,IACE;YAEJ;QACF,GACCW,KAAK,CAAC,CAACC;YACN,IAAIT,YAAYE,YAAY,KAAKD,YAAY;gBAC3CI,OAAOI;YACT,OAAO;gBACLZ,IACE;YAEJ;QACF;IACJ;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,SAASa,oBACdC,QAAwB,EACxBC,OAAgB;IAEhB,qEAAqE;IACrE,sDAAsD;IACtD,MAAMC,QAAQ,IAAIC,MAChB,CAAC,GACD;QACEC,KAAIC,OAAe,EAAEC,IAAqB;YACxC,OACE,OAAOA,SAAS,YAChB;gBAAC;gBAAW;gBAAM;aAAiB,CAACC,QAAQ,CAACD;QAEjD;QACAE,KAAIH,OAAO,EAAEC,IAA0B;YACrC,IAAIA,SAAS,WAAW;gBACtB,OAAOL;YACT,OAAO,IAAI;gBAAC;gBAAM;aAAiB,CAACM,QAAQ,CAACD,OAAO;gBAClD,OAAON,QAAQ,CAACM,KAAK;YACvB;YAEA,OAAOG;QACT;IACF;IAGF,OAAOP;AACT;AAEA,+DAA+D;AAC/D,OAAO,MAAMQ,sBAAsBC,OAAOC,MAAM,CAAC;IAC/C;IACA;IACA,6FAA6F;IAC7F;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,EAAE;AAEH;;;;CAIC,GACD,OAAO,SAASC,0BAA0BC,IAAsB;IAC9D,4EAA4E;IAC5EhC,OACEiC,OAAOC,SAAS,CAACC,UAAU,CAACC,IAAI,CAACJ,KAAKK,MAAM,EAAE,cAC5CJ,OAAOC,SAAS,CAACC,UAAU,CAACC,IAAI,CAACJ,KAAKK,MAAM,EAAE,UAChD,sFACAtC,UAAUuC,kBAAkB;IAE9BtC,OACE,CAAC4B,oBAAoBH,QAAQ,CAACO,KAAKK,MAAM,GACzCtC,UAAUwC,cAAc,CAAC;QACvBC,MAAM;YACJH,QAAQL,KAAKK,MAAM;QACrB;IACF;IAEFpC,aACE+B,MACA7B,YACA,6CACAJ,UAAU0C,aAAa;AAE3B;AAEA;;;;CAIC,GACD,OAAO,SAASC,8BAA8BV,IAAsB;IAClE,qDAAqD;IACrDhC,OACE,CAACiC,OAAOC,SAAS,CAACC,UAAU,CAACC,IAAI,CAACJ,KAAKK,MAAM,EAAE,UAC/CtC,UAAUwC,cAAc,CAAC;QACvBC,MAAM;YACJH,QAAQL,KAAKK,MAAM;QACrB;IACF;IAEFrC,OACE,CAAC4B,oBAAoBH,QAAQ,CAACO,KAAKK,MAAM,GACzCtC,UAAUwC,cAAc,CAAC;QACvBC,MAAM;YACJH,QAAQL,KAAKK,MAAM;QACrB;IACF;IAEFpC,aACE+B,MACA7B,YACA,6CACAJ,UAAU0C,aAAa;AAE3B;AAEA;;;;;CAKC,GACD,OAAO,SAASE,yBAAyB7B,KAAc;IACrD,6EAA6E;IAC7E,8EAA8E;IAC9E,MAAM8B,OAAOC,KAAKC,KAAK,CAACD,KAAKE,SAAS,CAACjC;IACvC,OAAOZ,YAAY0C;AACrB"}
@@ -1,3 +1,4 @@
1
+ import { rpcErrors } from '@metamask/rpc-errors';
1
2
  import { ChainIdStruct, HandlerType } from '@metamask/snaps-utils';
2
3
  import { assertStruct, JsonRpcIdStruct, JsonRpcRequestStruct, JsonRpcSuccessStruct, JsonStruct } from '@metamask/utils';
3
4
  import { array, assign, enums, is, literal, nullable, object, omit, optional, record, string, tuple, union } from 'superstruct';
@@ -59,7 +60,7 @@ export const OnTransactionRequestArgumentsStruct = object({
59
60
  * @throws If the value is not a valid {@link OnTransactionRequestArguments}
60
61
  * object.
61
62
  */ export function assertIsOnTransactionRequestArguments(value) {
62
- assertStruct(value, OnTransactionRequestArgumentsStruct, 'Invalid request params');
63
+ assertStruct(value, OnTransactionRequestArgumentsStruct, 'Invalid request params', rpcErrors.invalidParams);
63
64
  }
64
65
  const baseNameLookupArgs = {
65
66
  chainId: ChainIdStruct
@@ -84,7 +85,7 @@ export const OnNameLookupRequestArgumentsStruct = union([
84
85
  * @throws If the value is not a valid {@link OnNameLookupRequestArguments}
85
86
  * object.
86
87
  */ export function assertIsOnNameLookupRequestArguments(value) {
87
- assertStruct(value, OnNameLookupRequestArgumentsStruct, 'Invalid request params');
88
+ assertStruct(value, OnNameLookupRequestArgumentsStruct, 'Invalid request params', rpcErrors.invalidParams);
88
89
  }
89
90
  const OkResponseStruct = assign(JsonRpcSuccessStruct, object({
90
91
  result: OkStruct
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/validation.ts"],"sourcesContent":["import { ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcSuccess } from '@metamask/utils';\nimport {\n assertStruct,\n JsonRpcIdStruct,\n JsonRpcRequestStruct,\n JsonRpcSuccessStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n enums,\n is,\n literal,\n nullable,\n object,\n omit,\n optional,\n record,\n string,\n tuple,\n union,\n} from 'superstruct';\n\nexport const JsonRpcRequestWithoutIdStruct = assign(\n omit(JsonRpcRequestStruct, ['id']),\n object({\n id: optional(JsonRpcIdStruct),\n }),\n);\n\nexport type JsonRpcRequestWithoutId = Infer<\n typeof JsonRpcRequestWithoutIdStruct\n>;\n\nexport const EndowmentStruct = string();\nexport type Endowment = Infer<typeof EndowmentStruct>;\n\n/**\n * Check if the given value is an endowment.\n *\n * @param value - The value to check.\n * @returns Whether the value is an endowment.\n */\nexport function isEndowment(value: unknown): value is Endowment {\n return is(value, EndowmentStruct);\n}\n\n/**\n * Check if the given value is an array of endowments.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of endowments.\n */\nexport function isEndowmentsArray(value: unknown): value is Endowment[] {\n return Array.isArray(value) && value.every(isEndowment);\n}\n\nconst OkStruct = literal('OK');\n\nexport const PingRequestArgumentsStruct = optional(\n union([literal(undefined), array()]),\n);\n\nexport const TerminateRequestArgumentsStruct = union([\n literal(undefined),\n array(),\n]);\n\nexport const ExecuteSnapRequestArgumentsStruct = tuple([\n string(),\n string(),\n optional(array(EndowmentStruct)),\n]);\n\nexport const SnapRpcRequestArgumentsStruct = tuple([\n string(),\n enums(Object.values(HandlerType)),\n string(),\n assign(\n JsonRpcRequestWithoutIdStruct,\n object({\n params: optional(record(string(), JsonStruct)),\n }),\n ),\n]);\n\nexport type PingRequestArguments = Infer<typeof PingRequestArgumentsStruct>;\nexport type TerminateRequestArguments = Infer<\n typeof TerminateRequestArgumentsStruct\n>;\n\nexport type ExecuteSnapRequestArguments = Infer<\n typeof ExecuteSnapRequestArgumentsStruct\n>;\n\nexport type SnapRpcRequestArguments = Infer<\n typeof SnapRpcRequestArgumentsStruct\n>;\n\nexport type RequestArguments =\n | PingRequestArguments\n | TerminateRequestArguments\n | ExecuteSnapRequestArguments\n | SnapRpcRequestArguments;\n\nexport const OnTransactionRequestArgumentsStruct = object({\n // TODO: Improve `transaction` type.\n transaction: record(string(), JsonStruct),\n chainId: ChainIdStruct,\n transactionOrigin: nullable(string()),\n});\n\nexport type OnTransactionRequestArguments = Infer<\n typeof OnTransactionRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnTransactionRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnTransactionRequestArguments}\n * object.\n */\nexport function assertIsOnTransactionRequestArguments(\n value: unknown,\n): asserts value is OnTransactionRequestArguments {\n assertStruct(\n value,\n OnTransactionRequestArgumentsStruct,\n 'Invalid request params',\n );\n}\n\nconst baseNameLookupArgs = { chainId: ChainIdStruct };\nconst domainRequestStruct = object({\n ...baseNameLookupArgs,\n address: string(),\n});\nconst addressRequestStruct = object({\n ...baseNameLookupArgs,\n domain: string(),\n});\n\nexport const OnNameLookupRequestArgumentsStruct = union([\n domainRequestStruct,\n addressRequestStruct,\n]);\n\nexport type OnNameLookupRequestArguments = Infer<\n typeof OnNameLookupRequestArgumentsStruct\n>;\n\nexport type PossibleLookupRequestArgs = typeof baseNameLookupArgs & {\n address?: string;\n domain?: string;\n};\n\n/**\n * Asserts that the given value is a valid {@link OnNameLookupRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnNameLookupRequestArguments}\n * object.\n */\nexport function assertIsOnNameLookupRequestArguments(\n value: unknown,\n): asserts value is OnNameLookupRequestArguments {\n assertStruct(\n value,\n OnNameLookupRequestArgumentsStruct,\n 'Invalid request params',\n );\n}\n\nconst OkResponseStruct = assign(\n JsonRpcSuccessStruct,\n object({\n result: OkStruct,\n }),\n);\n\nconst SnapRpcResponse = JsonRpcSuccessStruct;\n\nexport type OkResponse = Infer<typeof OkResponseStruct>;\nexport type SnapRpcResponse = Infer<typeof SnapRpcResponse>;\n\nexport type Response = OkResponse | SnapRpcResponse;\n\ntype RequestParams<Params extends unknown[] | undefined> =\n Params extends undefined ? [] : Params;\n\ntype RequestFunction<\n Args extends RequestArguments,\n ResponseType extends JsonRpcSuccess<Json>,\n> = (...args: RequestParams<Args>) => Promise<ResponseType['result']>;\n\nexport type Ping = RequestFunction<PingRequestArguments, OkResponse>;\nexport type Terminate = RequestFunction<TerminateRequestArguments, OkResponse>;\nexport type ExecuteSnap = RequestFunction<\n ExecuteSnapRequestArguments,\n OkResponse\n>;\nexport type SnapRpc = RequestFunction<SnapRpcRequestArguments, SnapRpcResponse>;\n"],"names":["ChainIdStruct","HandlerType","assertStruct","JsonRpcIdStruct","JsonRpcRequestStruct","JsonRpcSuccessStruct","JsonStruct","array","assign","enums","is","literal","nullable","object","omit","optional","record","string","tuple","union","JsonRpcRequestWithoutIdStruct","id","EndowmentStruct","isEndowment","value","isEndowmentsArray","Array","isArray","every","OkStruct","PingRequestArgumentsStruct","undefined","TerminateRequestArgumentsStruct","ExecuteSnapRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","Object","values","params","OnTransactionRequestArgumentsStruct","transaction","chainId","transactionOrigin","assertIsOnTransactionRequestArguments","baseNameLookupArgs","domainRequestStruct","address","addressRequestStruct","domain","OnNameLookupRequestArgumentsStruct","assertIsOnNameLookupRequestArguments","OkResponseStruct","result","SnapRpcResponse"],"mappings":"AAAA,SAASA,aAAa,EAAEC,WAAW,QAAQ,wBAAwB;AAEnE,SACEC,YAAY,EACZC,eAAe,EACfC,oBAAoB,EACpBC,oBAAoB,EACpBC,UAAU,QACL,kBAAkB;AAEzB,SACEC,KAAK,EACLC,MAAM,EACNC,KAAK,EACLC,EAAE,EACFC,OAAO,EACPC,QAAQ,EACRC,MAAM,EACNC,IAAI,EACJC,QAAQ,EACRC,MAAM,EACNC,MAAM,EACNC,KAAK,EACLC,KAAK,QACA,cAAc;AAErB,OAAO,MAAMC,gCAAgCZ,OAC3CM,KAAKV,sBAAsB;IAAC;CAAK,GACjCS,OAAO;IACLQ,IAAIN,SAASZ;AACf,IACA;AAMF,OAAO,MAAMmB,kBAAkBL,SAAS;AAGxC;;;;;CAKC,GACD,OAAO,SAASM,YAAYC,KAAc;IACxC,OAAOd,GAAGc,OAAOF;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASG,kBAAkBD,KAAc;IAC9C,OAAOE,MAAMC,OAAO,CAACH,UAAUA,MAAMI,KAAK,CAACL;AAC7C;AAEA,MAAMM,WAAWlB,QAAQ;AAEzB,OAAO,MAAMmB,6BAA6Bf,SACxCI,MAAM;IAACR,QAAQoB;IAAYxB;CAAQ,GACnC;AAEF,OAAO,MAAMyB,kCAAkCb,MAAM;IACnDR,QAAQoB;IACRxB;CACD,EAAE;AAEH,OAAO,MAAM0B,oCAAoCf,MAAM;IACrDD;IACAA;IACAF,SAASR,MAAMe;CAChB,EAAE;AAEH,OAAO,MAAMY,gCAAgChB,MAAM;IACjDD;IACAR,MAAM0B,OAAOC,MAAM,CAACnC;IACpBgB;IACAT,OACEY,+BACAP,OAAO;QACLwB,QAAQtB,SAASC,OAAOC,UAAUX;IACpC;CAEH,EAAE;AAqBH,OAAO,MAAMgC,sCAAsCzB,OAAO;IACxD,oCAAoC;IACpC0B,aAAavB,OAAOC,UAAUX;IAC9BkC,SAASxC;IACTyC,mBAAmB7B,SAASK;AAC9B,GAAG;AAMH;;;;;;;CAOC,GACD,OAAO,SAASyB,sCACdlB,KAAc;IAEdtB,aACEsB,OACAc,qCACA;AAEJ;AAEA,MAAMK,qBAAqB;IAAEH,SAASxC;AAAc;AACpD,MAAM4C,sBAAsB/B,OAAO;IACjC,GAAG8B,kBAAkB;IACrBE,SAAS5B;AACX;AACA,MAAM6B,uBAAuBjC,OAAO;IAClC,GAAG8B,kBAAkB;IACrBI,QAAQ9B;AACV;AAEA,OAAO,MAAM+B,qCAAqC7B,MAAM;IACtDyB;IACAE;CACD,EAAE;AAWH;;;;;;;CAOC,GACD,OAAO,SAASG,qCACdzB,KAAc;IAEdtB,aACEsB,OACAwB,oCACA;AAEJ;AAEA,MAAME,mBAAmB1C,OACvBH,sBACAQ,OAAO;IACLsC,QAAQtB;AACV;AAGF,MAAMuB,kBAAkB/C"}
1
+ {"version":3,"sources":["../../../src/common/validation.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport { ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcSuccess } from '@metamask/utils';\nimport {\n assertStruct,\n JsonRpcIdStruct,\n JsonRpcRequestStruct,\n JsonRpcSuccessStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n enums,\n is,\n literal,\n nullable,\n object,\n omit,\n optional,\n record,\n string,\n tuple,\n union,\n} from 'superstruct';\n\nexport const JsonRpcRequestWithoutIdStruct = assign(\n omit(JsonRpcRequestStruct, ['id']),\n object({\n id: optional(JsonRpcIdStruct),\n }),\n);\n\nexport type JsonRpcRequestWithoutId = Infer<\n typeof JsonRpcRequestWithoutIdStruct\n>;\n\nexport const EndowmentStruct = string();\nexport type Endowment = Infer<typeof EndowmentStruct>;\n\n/**\n * Check if the given value is an endowment.\n *\n * @param value - The value to check.\n * @returns Whether the value is an endowment.\n */\nexport function isEndowment(value: unknown): value is Endowment {\n return is(value, EndowmentStruct);\n}\n\n/**\n * Check if the given value is an array of endowments.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of endowments.\n */\nexport function isEndowmentsArray(value: unknown): value is Endowment[] {\n return Array.isArray(value) && value.every(isEndowment);\n}\n\nconst OkStruct = literal('OK');\n\nexport const PingRequestArgumentsStruct = optional(\n union([literal(undefined), array()]),\n);\n\nexport const TerminateRequestArgumentsStruct = union([\n literal(undefined),\n array(),\n]);\n\nexport const ExecuteSnapRequestArgumentsStruct = tuple([\n string(),\n string(),\n optional(array(EndowmentStruct)),\n]);\n\nexport const SnapRpcRequestArgumentsStruct = tuple([\n string(),\n enums(Object.values(HandlerType)),\n string(),\n assign(\n JsonRpcRequestWithoutIdStruct,\n object({\n params: optional(record(string(), JsonStruct)),\n }),\n ),\n]);\n\nexport type PingRequestArguments = Infer<typeof PingRequestArgumentsStruct>;\nexport type TerminateRequestArguments = Infer<\n typeof TerminateRequestArgumentsStruct\n>;\n\nexport type ExecuteSnapRequestArguments = Infer<\n typeof ExecuteSnapRequestArgumentsStruct\n>;\n\nexport type SnapRpcRequestArguments = Infer<\n typeof SnapRpcRequestArgumentsStruct\n>;\n\nexport type RequestArguments =\n | PingRequestArguments\n | TerminateRequestArguments\n | ExecuteSnapRequestArguments\n | SnapRpcRequestArguments;\n\nexport const OnTransactionRequestArgumentsStruct = object({\n // TODO: Improve `transaction` type.\n transaction: record(string(), JsonStruct),\n chainId: ChainIdStruct,\n transactionOrigin: nullable(string()),\n});\n\nexport type OnTransactionRequestArguments = Infer<\n typeof OnTransactionRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnTransactionRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnTransactionRequestArguments}\n * object.\n */\nexport function assertIsOnTransactionRequestArguments(\n value: unknown,\n): asserts value is OnTransactionRequestArguments {\n assertStruct(\n value,\n OnTransactionRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst baseNameLookupArgs = { chainId: ChainIdStruct };\nconst domainRequestStruct = object({\n ...baseNameLookupArgs,\n address: string(),\n});\nconst addressRequestStruct = object({\n ...baseNameLookupArgs,\n domain: string(),\n});\n\nexport const OnNameLookupRequestArgumentsStruct = union([\n domainRequestStruct,\n addressRequestStruct,\n]);\n\nexport type OnNameLookupRequestArguments = Infer<\n typeof OnNameLookupRequestArgumentsStruct\n>;\n\nexport type PossibleLookupRequestArgs = typeof baseNameLookupArgs & {\n address?: string;\n domain?: string;\n};\n\n/**\n * Asserts that the given value is a valid {@link OnNameLookupRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnNameLookupRequestArguments}\n * object.\n */\nexport function assertIsOnNameLookupRequestArguments(\n value: unknown,\n): asserts value is OnNameLookupRequestArguments {\n assertStruct(\n value,\n OnNameLookupRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst OkResponseStruct = assign(\n JsonRpcSuccessStruct,\n object({\n result: OkStruct,\n }),\n);\n\nconst SnapRpcResponse = JsonRpcSuccessStruct;\n\nexport type OkResponse = Infer<typeof OkResponseStruct>;\nexport type SnapRpcResponse = Infer<typeof SnapRpcResponse>;\n\nexport type Response = OkResponse | SnapRpcResponse;\n\ntype RequestParams<Params extends unknown[] | undefined> =\n Params extends undefined ? [] : Params;\n\ntype RequestFunction<\n Args extends RequestArguments,\n ResponseType extends JsonRpcSuccess<Json>,\n> = (...args: RequestParams<Args>) => Promise<ResponseType['result']>;\n\nexport type Ping = RequestFunction<PingRequestArguments, OkResponse>;\nexport type Terminate = RequestFunction<TerminateRequestArguments, OkResponse>;\nexport type ExecuteSnap = RequestFunction<\n ExecuteSnapRequestArguments,\n OkResponse\n>;\nexport type SnapRpc = RequestFunction<SnapRpcRequestArguments, SnapRpcResponse>;\n"],"names":["rpcErrors","ChainIdStruct","HandlerType","assertStruct","JsonRpcIdStruct","JsonRpcRequestStruct","JsonRpcSuccessStruct","JsonStruct","array","assign","enums","is","literal","nullable","object","omit","optional","record","string","tuple","union","JsonRpcRequestWithoutIdStruct","id","EndowmentStruct","isEndowment","value","isEndowmentsArray","Array","isArray","every","OkStruct","PingRequestArgumentsStruct","undefined","TerminateRequestArgumentsStruct","ExecuteSnapRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","Object","values","params","OnTransactionRequestArgumentsStruct","transaction","chainId","transactionOrigin","assertIsOnTransactionRequestArguments","invalidParams","baseNameLookupArgs","domainRequestStruct","address","addressRequestStruct","domain","OnNameLookupRequestArgumentsStruct","assertIsOnNameLookupRequestArguments","OkResponseStruct","result","SnapRpcResponse"],"mappings":"AAAA,SAASA,SAAS,QAAQ,uBAAuB;AACjD,SAASC,aAAa,EAAEC,WAAW,QAAQ,wBAAwB;AAEnE,SACEC,YAAY,EACZC,eAAe,EACfC,oBAAoB,EACpBC,oBAAoB,EACpBC,UAAU,QACL,kBAAkB;AAEzB,SACEC,KAAK,EACLC,MAAM,EACNC,KAAK,EACLC,EAAE,EACFC,OAAO,EACPC,QAAQ,EACRC,MAAM,EACNC,IAAI,EACJC,QAAQ,EACRC,MAAM,EACNC,MAAM,EACNC,KAAK,EACLC,KAAK,QACA,cAAc;AAErB,OAAO,MAAMC,gCAAgCZ,OAC3CM,KAAKV,sBAAsB;IAAC;CAAK,GACjCS,OAAO;IACLQ,IAAIN,SAASZ;AACf,IACA;AAMF,OAAO,MAAMmB,kBAAkBL,SAAS;AAGxC;;;;;CAKC,GACD,OAAO,SAASM,YAAYC,KAAc;IACxC,OAAOd,GAAGc,OAAOF;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASG,kBAAkBD,KAAc;IAC9C,OAAOE,MAAMC,OAAO,CAACH,UAAUA,MAAMI,KAAK,CAACL;AAC7C;AAEA,MAAMM,WAAWlB,QAAQ;AAEzB,OAAO,MAAMmB,6BAA6Bf,SACxCI,MAAM;IAACR,QAAQoB;IAAYxB;CAAQ,GACnC;AAEF,OAAO,MAAMyB,kCAAkCb,MAAM;IACnDR,QAAQoB;IACRxB;CACD,EAAE;AAEH,OAAO,MAAM0B,oCAAoCf,MAAM;IACrDD;IACAA;IACAF,SAASR,MAAMe;CAChB,EAAE;AAEH,OAAO,MAAMY,gCAAgChB,MAAM;IACjDD;IACAR,MAAM0B,OAAOC,MAAM,CAACnC;IACpBgB;IACAT,OACEY,+BACAP,OAAO;QACLwB,QAAQtB,SAASC,OAAOC,UAAUX;IACpC;CAEH,EAAE;AAqBH,OAAO,MAAMgC,sCAAsCzB,OAAO;IACxD,oCAAoC;IACpC0B,aAAavB,OAAOC,UAAUX;IAC9BkC,SAASxC;IACTyC,mBAAmB7B,SAASK;AAC9B,GAAG;AAMH;;;;;;;CAOC,GACD,OAAO,SAASyB,sCACdlB,KAAc;IAEdtB,aACEsB,OACAc,qCACA,0BACAvC,UAAU4C,aAAa;AAE3B;AAEA,MAAMC,qBAAqB;IAAEJ,SAASxC;AAAc;AACpD,MAAM6C,sBAAsBhC,OAAO;IACjC,GAAG+B,kBAAkB;IACrBE,SAAS7B;AACX;AACA,MAAM8B,uBAAuBlC,OAAO;IAClC,GAAG+B,kBAAkB;IACrBI,QAAQ/B;AACV;AAEA,OAAO,MAAMgC,qCAAqC9B,MAAM;IACtD0B;IACAE;CACD,EAAE;AAWH;;;;;;;CAOC,GACD,OAAO,SAASG,qCACd1B,KAAc;IAEdtB,aACEsB,OACAyB,oCACA,0BACAlD,UAAU4C,aAAa;AAE3B;AAEA,MAAMQ,mBAAmB3C,OACvBH,sBACAQ,OAAO;IACLuC,QAAQvB;AACV;AAGF,MAAMwB,kBAAkBhD"}
@@ -1,5 +1,5 @@
1
1
  import type { StreamProvider } from '@metamask/providers';
2
- import type { SnapsGlobalObject } from '@metamask/rpc-methods';
2
+ import type { SnapsGlobalObject } from '@metamask/snaps-rpc-methods';
3
3
  import type { SnapId } from '@metamask/snaps-utils';
4
4
  /**
5
5
  * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`
@@ -1,14 +1,5 @@
1
1
  import type { StreamProvider } from '@metamask/providers';
2
2
  import type { RequestArguments } from '@metamask/providers/dist/BaseProvider';
3
- /**
4
- * Takes an error that was thrown, determines if it is
5
- * an error object. If it is then it will return that. Otherwise,
6
- * an error object is created with the original error message.
7
- *
8
- * @param originalError - The error that was originally thrown.
9
- * @returns An error object.
10
- */
11
- export declare function constructError(originalError: unknown): Error | undefined;
12
3
  /**
13
4
  * Make proxy for Promise and handle the teardown process properly.
14
5
  * If the teardown is called in the meanwhile, Promise result will not be
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/snaps-execution-environments",
3
- "version": "2.0.1",
3
+ "version": "3.1.0",
4
4
  "description": "Snap sandbox environments for executing SES javascript",
5
5
  "repository": {
6
6
  "type": "git",
@@ -19,7 +19,7 @@
19
19
  "scripts": {
20
20
  "test": "rimraf coverage && jest && yarn test:browser && yarn posttest",
21
21
  "posttest": "ts-node scripts/coverage.ts && rimraf coverage/jest coverage/wdio",
22
- "test:browser": "wdio run wdio.config.ts",
22
+ "test:browser": "wdio run wdio.config.js",
23
23
  "test:ci": "yarn test",
24
24
  "test:watch": "jest --watch",
25
25
  "lint:eslint": "eslint . --cache --ext js,ts,jsx,tsx",
@@ -38,34 +38,33 @@
38
38
  "build:lavamoat": "lavamoat scripts/build.js --policy lavamoat/build-system/policy.json --policyOverride lavamoat/build-system/policy-override.json",
39
39
  "build:lavamoat:policy": "yarn build:lavamoat --writeAutoPolicy && node scripts/build.js --writeAutoPolicy",
40
40
  "auto-changelog-init": "auto-changelog init",
41
- "prepare-manifest:preview": "../../scripts/prepare-preview-manifest.sh",
42
41
  "publish:preview": "yarn npm publish --tag preview",
43
42
  "lint:ci": "yarn lint",
44
43
  "start": "node scripts/start.js",
45
44
  "lint:dependencies": "depcheck"
46
45
  },
47
46
  "dependencies": {
47
+ "@metamask/json-rpc-engine": "^7.1.1",
48
48
  "@metamask/object-multiplex": "^1.2.0",
49
49
  "@metamask/post-message-stream": "^7.0.0",
50
- "@metamask/providers": "^11.1.1",
51
- "@metamask/rpc-methods": "^2.0.0",
52
- "@metamask/snaps-utils": "^2.0.1",
50
+ "@metamask/providers": "^13.0.0",
51
+ "@metamask/rpc-errors": "^6.1.0",
52
+ "@metamask/snaps-rpc-methods": "^3.1.0",
53
+ "@metamask/snaps-utils": "^3.1.0",
53
54
  "@metamask/utils": "^8.1.0",
54
- "eth-rpc-errors": "^4.0.3",
55
- "json-rpc-engine": "^6.1.0",
56
55
  "nanoid": "^3.1.31",
57
56
  "superstruct": "^1.0.3"
58
57
  },
59
58
  "devDependencies": {
60
- "@babel/core": "^7.20.12",
61
- "@babel/preset-env": "^7.20.12",
62
- "@babel/preset-typescript": "^7.20.12",
59
+ "@babel/core": "^7.23.2",
60
+ "@babel/preset-env": "^7.23.2",
61
+ "@babel/preset-typescript": "^7.23.2",
63
62
  "@esbuild-plugins/node-globals-polyfill": "^0.2.3",
64
63
  "@esbuild-plugins/node-modules-polyfill": "^0.2.2",
65
64
  "@lavamoat/allow-scripts": "^2.5.1",
66
65
  "@lavamoat/lavapack": "^5.4.1",
67
66
  "@lavamoat/lavatube": "^0.2.3",
68
- "@metamask/auto-changelog": "^3.1.0",
67
+ "@metamask/auto-changelog": "^3.3.0",
69
68
  "@metamask/eslint-config": "^12.1.0",
70
69
  "@metamask/eslint-config-jest": "^12.1.0",
71
70
  "@metamask/eslint-config-nodejs": "^12.1.0",
@@ -78,17 +77,17 @@
78
77
  "@types/node": "18.14.2",
79
78
  "@typescript-eslint/eslint-plugin": "^5.42.1",
80
79
  "@typescript-eslint/parser": "^5.42.1",
81
- "@wdio/browser-runner": "^8.15.9",
82
- "@wdio/cli": "^8.15.9",
83
- "@wdio/globals": "^8.15.9",
84
- "@wdio/mocha-framework": "^8.15.9",
85
- "@wdio/spec-reporter": "^8.15.7",
86
- "@wdio/static-server-service": "^8.15.7",
80
+ "@wdio/browser-runner": "^8.19.0",
81
+ "@wdio/cli": "^8.19.0",
82
+ "@wdio/globals": "^8.19.0",
83
+ "@wdio/mocha-framework": "^8.19.0",
84
+ "@wdio/spec-reporter": "^8.19.0",
85
+ "@wdio/static-server-service": "^8.19.0",
87
86
  "babel-plugin-tsconfig-paths-module-resolver": "^1.0.4",
88
87
  "babelify": "^10.0.0",
89
88
  "browserify": "^17.0.0",
90
89
  "deepmerge": "^4.2.2",
91
- "depcheck": "^1.4.5",
90
+ "depcheck": "^1.4.7",
92
91
  "esbuild": "^0.18.10",
93
92
  "eslint": "^8.27.0",
94
93
  "eslint-config-prettier": "^8.5.0",
@@ -98,8 +97,7 @@
98
97
  "eslint-plugin-n": "^15.7.0",
99
98
  "eslint-plugin-prettier": "^4.2.1",
100
99
  "eslint-plugin-promise": "^6.1.1",
101
- "expect-webdriverio": "^4.1.2",
102
- "express": "^4.18.2",
100
+ "expect-webdriverio": "^4.4.1",
103
101
  "istanbul-lib-coverage": "^3.2.0",
104
102
  "istanbul-lib-report": "^3.0.0",
105
103
  "istanbul-reports": "^3.1.5",
@@ -120,11 +118,11 @@
120
118
  "vite-tsconfig-paths": "^4.0.5",
121
119
  "wdio-chromedriver-service": "^8.1.1",
122
120
  "wdio-geckodriver-service": "^5.0.2",
123
- "webdriverio": "^8.15.9",
121
+ "webdriverio": "^8.19.0",
124
122
  "yargs": "^17.7.1"
125
123
  },
126
124
  "engines": {
127
- "node": ">=16.0.0"
125
+ "node": "^18.16 || >=20"
128
126
  },
129
127
  "publishConfig": {
130
128
  "access": "public",