@metamask/snaps-jest 0.35.2-flask.1 → 0.36.0-flask.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [0.36.0-flask.1]
|
|
10
|
+
### Changed
|
|
11
|
+
- Default to newline instead of empty string for network mocking ([#1560](https://github.com/MetaMask/snaps/pull/1560))
|
|
12
|
+
|
|
9
13
|
## [0.35.2-flask.1]
|
|
10
14
|
### Fixed
|
|
11
15
|
- Fix type issue introduced by [#1532](https://github.com/MetaMask/snaps/pull/1532) ([#1541](https://github.com/MetaMask/snaps/pull/1541))
|
|
@@ -18,7 +22,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
18
22
|
### Added
|
|
19
23
|
- Initial release ([#1438](https://github.com/MetaMask/snaps/pull/1438), [#1488](https://github.com/MetaMask/snaps/pull/1488), [#1519](https://github.com/MetaMask/snaps/pull/1519), [#1532](https://github.com/MetaMask/snaps/pull/1532))
|
|
20
24
|
|
|
21
|
-
[Unreleased]: https://github.com/MetaMask/snaps/compare/v0.
|
|
25
|
+
[Unreleased]: https://github.com/MetaMask/snaps/compare/v0.36.0-flask.1...HEAD
|
|
26
|
+
[0.36.0-flask.1]: https://github.com/MetaMask/snaps/compare/v0.35.2-flask.1...v0.36.0-flask.1
|
|
22
27
|
[0.35.2-flask.1]: https://github.com/MetaMask/snaps/compare/v0.35.1-flask.1...v0.35.2-flask.1
|
|
23
28
|
[0.35.1-flask.1]: https://github.com/MetaMask/snaps/compare/v0.35.0-flask.1...v0.35.1-flask.1
|
|
24
29
|
[0.35.0-flask.1]: https://github.com/MetaMask/snaps/releases/tag/v0.35.0-flask.1
|
package/README.md
CHANGED
|
@@ -57,7 +57,7 @@ matchers by adding them to your Jest configuration manually:
|
|
|
57
57
|
```js
|
|
58
58
|
module.exports = {
|
|
59
59
|
testEnvironment: '@metamask/snaps-jest',
|
|
60
|
-
setupFilesAfterEnv: ['@metamask/snaps-jest/dist/setup.js'],
|
|
60
|
+
setupFilesAfterEnv: ['@metamask/snaps-jest/dist/cjs/setup.js'],
|
|
61
61
|
};
|
|
62
62
|
```
|
|
63
63
|
|
|
@@ -38,7 +38,9 @@ const MockOptionsBaseStruct = (0, _superstruct.object)({
|
|
|
38
38
|
status: (0, _superstruct.defaulted)((0, _superstruct.number)(), 200),
|
|
39
39
|
headers: (0, _superstruct.defaulted)((0, _superstruct.record)((0, _superstruct.string)(), (0, _superstruct.unknown)()), DEFAULT_HEADERS),
|
|
40
40
|
contentType: (0, _superstruct.defaulted)((0, _superstruct.string)(), 'text/plain'),
|
|
41
|
-
|
|
41
|
+
// Note: We default to a newline here, because the fetch request never
|
|
42
|
+
// resolves if the body is empty.
|
|
43
|
+
body: (0, _superstruct.defaulted)((0, _superstruct.string)(), '\n')
|
|
42
44
|
}), {})
|
|
43
45
|
});
|
|
44
46
|
const MockOptionsUrlStruct = (0, _superstruct.object)({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/internals/network.ts"],"sourcesContent":["import { JSON_RPC_ENDPOINT } from '@metamask/snaps-simulator';\nimport { createModuleLogger, UnsafeJsonStruct } from '@metamask/utils';\nimport { Page, HTTPRequest } from 'puppeteer';\nimport {\n assign,\n boolean,\n create,\n defaulted,\n Infer,\n number,\n object,\n optional,\n record,\n regexp,\n string,\n Struct,\n union,\n unknown,\n func,\n} from 'superstruct';\n\nimport { DeepPartial } from '../types';\nimport { rootLogger } from './logger';\n\n/**\n * The default headers to use for mocked responses. These headers are used to\n * enable CORS.\n */\nconst DEFAULT_HEADERS = {\n /* eslint-disable @typescript-eslint/naming-convention */\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Credentials': 'true',\n 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',\n 'Access-Control-Allow-Headers':\n 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers',\n /* eslint-enable @typescript-eslint/naming-convention */\n};\n\nconst log = createModuleLogger(rootLogger, 'network');\n\nexport type Unmock = () => Promise<void>;\n\nexport type Mock = {\n /**\n * A function that can be used to unmock the URL.\n */\n unmock: Unmock;\n};\n\n/**\n * A function that can return `true` if the given request should be mocked, or\n * false if not.\n *\n * @param request - The request to check.\n * @returns Whether to mock the request.\n */\nexport type ConditionFunction = (request: HTTPRequest) => boolean;\n\nconst MockOptionsBaseStruct = object({\n response: defaulted(\n object({\n status: defaulted(number(), 200),\n headers: defaulted(record(string(), unknown()), DEFAULT_HEADERS),\n contentType: defaulted(string(), 'text/plain'),\n body: defaulted(string(), ''),\n }),\n {},\n ),\n});\n\nconst MockOptionsUrlStruct = object({\n url: union([string(), regexp()]),\n partial: optional(boolean()),\n});\n\nconst MockOptionsConditionStruct = object({\n condition: func() as unknown as Struct<ConditionFunction, null>,\n});\n\nexport const MockOptionsStruct = union([\n assign(MockOptionsBaseStruct, MockOptionsUrlStruct),\n assign(MockOptionsBaseStruct, MockOptionsConditionStruct),\n]);\n\n/**\n * The options for the network mocking.\n *\n * @property url - The URL to mock. If a string is provided, the URL will be\n * matched exactly. If a RegExp is provided, the URL will be matched against it.\n * This option is incompatible with the `condition` option.\n * @property partial - If enabled, the request will be mocked if the URL starts\n * with the given URL. This option is ignored if a RegExp is provided to the\n * `url` option. This option is incompatible with the `condition` option.\n * @property condition - A function which gets the {@link HTTPRequest} as\n * parameter and returns a boolean to indicate whether the response should be\n * mocked or not. This option is incompatible with the `url` and `partial`\n * options.\n * @property response - The response to send for the request.\n * @property response.status - The status code to send for the response.\n * Defaults to `200`.\n * @property response.headers - The headers to send for the response. Defaults\n * to headers that enable CORS.\n * @property response.contentType - The content type to send for the response.\n * Defaults to `text/plain`.\n */\nexport type MockOptions = Infer<typeof MockOptionsStruct>;\n\n/**\n * Check if the given URL matches the given request, or if the condition\n * function returns `true`.\n *\n * @param request - The request to check.\n * @param options - The options for the network mocking.\n * @returns Whether the URL matches the request.\n */\nfunction matches(request: HTTPRequest, options: MockOptions) {\n if ('url' in options) {\n const { url, partial } = options;\n if (typeof url === 'string') {\n if (partial) {\n return request.url().startsWith(url);\n }\n\n return url === request.url();\n }\n\n return url.test(request.url());\n }\n\n const { condition } = options;\n return condition(request);\n}\n\n/**\n * Enable network mocking for the given page, and all its sub-frames.\n *\n * @param page - The page to enable network mocking on.\n * @param options - The options for the network mocking.\n * @returns A {@link Mock} object, with an `unmock` function.\n */\nexport async function mock(\n page: Page,\n options: DeepPartial<MockOptions>,\n): Promise<Mock> {\n await page.setRequestInterception(true);\n\n const parsedOptions = create(options, MockOptionsStruct);\n\n /**\n * The mock handler.\n *\n * @param request - The request to handle.\n */\n function handler(request: HTTPRequest) {\n // If the request is already handled, Puppeteer will throw an error if we\n // try to continue the request.\n if (request.isInterceptResolutionHandled()) {\n return;\n }\n\n if (!matches(request, parsedOptions)) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n request.continue();\n return;\n }\n\n log('Mocking request to %s', request.url());\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n request.respond(parsedOptions.response);\n }\n\n /**\n * Unmock the page.\n */\n async function unmock() {\n await page.setRequestInterception(false);\n page.off('request', handler);\n }\n\n page.on('request', handler);\n\n return {\n unmock,\n };\n}\n\nconst MockJsonRpcOptionsStruct = object({\n method: string(),\n result: UnsafeJsonStruct,\n});\n\nexport type MockJsonRpcOptions = Infer<typeof MockJsonRpcOptionsStruct>;\n\n/**\n * Mock an Ethereum JSON-RPC request. This intercepts all requests to the\n * Ethereum provider, and returns the `result` instead.\n *\n * @param page - The page to enable network JSON-RPC mocking on.\n * @param options - The options for the JSON-RPC mock.\n * @param options.method - The JSON-RPC method to mock. Any other methods will be\n * forwarded to the provider.\n * @param options.result - The JSON response to return.\n * @returns A {@link Mock} object, with an `unmock` function.\n */\nexport async function mockJsonRpc(\n page: Page,\n { method, result }: MockJsonRpcOptions,\n) {\n return await mock(page, {\n condition: (request: HTTPRequest) => {\n if (request.url() !== JSON_RPC_ENDPOINT) {\n return false;\n }\n\n const body = request.postData();\n if (!body) {\n return false;\n }\n\n try {\n const json = JSON.parse(body);\n return json.method === method;\n } catch (error) {\n log(\n `Unable to mock \"${method}\" request to Ethereum provider: %s`,\n error.message,\n );\n return false;\n }\n },\n response: {\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n result,\n }),\n },\n });\n}\n"],"names":["MockOptionsStruct","mock","mockJsonRpc","DEFAULT_HEADERS","log","createModuleLogger","rootLogger","MockOptionsBaseStruct","object","response","defaulted","status","number","headers","record","string","unknown","contentType","body","MockOptionsUrlStruct","url","union","regexp","partial","optional","boolean","MockOptionsConditionStruct","condition","func","assign","matches","request","options","startsWith","test","page","setRequestInterception","parsedOptions","create","handler","isInterceptResolutionHandled","continue","respond","unmock","off","on","MockJsonRpcOptionsStruct","method","result","UnsafeJsonStruct","JSON_RPC_ENDPOINT","postData","json","JSON","parse","error","message","stringify","jsonrpc","id"],"mappings":";;;;;;;;;;;IA+EaA,iBAAiB;eAAjBA;;IA6DSC,IAAI;eAAJA;;IAiEAC,WAAW;eAAXA;;;gCA7MY;uBACmB;6BAkB9C;wBAGoB;AAE3B;;;CAGC,GACD,MAAMC,kBAAkB;IACtB,uDAAuD,GACvD,+BAA+B;IAC/B,oCAAoC;IACpC,gCAAgC;IAChC,gCACE;AAEJ;AAEA,MAAMC,MAAMC,IAAAA,yBAAkB,EAACC,kBAAU,EAAE;AAoB3C,MAAMC,wBAAwBC,IAAAA,mBAAM,EAAC;IACnCC,UAAUC,IAAAA,sBAAS,EACjBF,IAAAA,mBAAM,EAAC;QACLG,QAAQD,IAAAA,sBAAS,EAACE,IAAAA,mBAAM,KAAI;QAC5BC,SAASH,IAAAA,sB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4BAA4B,IAAI;YAC1C;QACF;QAEA,IAAI,CAACV,QAAQC,SAASM,gBAAgB;YACpC,mEAAmE;YACnEN,QAAQU,QAAQ;YAChB;QACF;QAEArC,IAAI,yBAAyB2B,QAAQX,GAAG;QAExC,mEAAmE;QACnEW,QAAQW,OAAO,CAACL,cAAc5B,QAAQ;IACxC;IAEA;;GAEC,GACD,eAAekC;QACb,MAAMR,KAAKC,sBAAsB,CAAC;QAClCD,KAAKS,GAAG,CAAC,WAAWL;IACtB;IAEAJ,KAAKU,EAAE,CAAC,WAAWN;IAEnB,OAAO;QACLI;IACF;AACF;AAEA,MAAMG,2BAA2BtC,IAAAA,mBAAM,EAAC;IACtCuC,QAAQhC,IAAAA,mBAAM;IACdiC,QAAQC,uBAAgB;AAC1B;AAeO,eAAe/C,YACpBiC,IAAU,EACV,EAAEY,MAAM,EAAEC,MAAM,EAAsB;IAEtC,OAAO,MAAM/C,KAAKkC,MAAM;QACtBR,WAAW,CAACI;YACV,IAAIA,QAAQX,GAAG,OAAO8B,iCAAiB,EAAE;gBACvC,OAAO;YACT;YAEA,MAAMhC,OAAOa,QAAQoB,QAAQ;YAC7B,IAAI,CAACjC,MAAM;gBACT,OAAO;YACT;YAEA,IAAI;gBACF,MAAMkC,OAAOC,KAAKC,KAAK,CAACpC;gBACxB,OAAOkC,KAAKL,MAAM,KAAKA;YACzB,EAAE,OAAOQ,OAAO;gBACdnD,IACE,CAAC,gBAAgB,EAAE2C,OAAO,kCAAkC,CAAC,EAC7DQ,MAAMC,OAAO;gBAEf,OAAO;YACT;QACF;QACA/C,UAAU;YACRE,QAAQ;YACRM,aAAa;YACbC,MAAMmC,KAAKI,SAAS,CAAC;gBACnBC,SAAS;gBACTC,IAAI;gBACJX;YACF;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/internals/network.ts"],"sourcesContent":["import { JSON_RPC_ENDPOINT } from '@metamask/snaps-simulator';\nimport { createModuleLogger, UnsafeJsonStruct } from '@metamask/utils';\nimport { Page, HTTPRequest } from 'puppeteer';\nimport {\n assign,\n boolean,\n create,\n defaulted,\n Infer,\n number,\n object,\n optional,\n record,\n regexp,\n string,\n Struct,\n union,\n unknown,\n func,\n} from 'superstruct';\n\nimport { DeepPartial } from '../types';\nimport { rootLogger } from './logger';\n\n/**\n * The default headers to use for mocked responses. These headers are used to\n * enable CORS.\n */\nconst DEFAULT_HEADERS = {\n /* eslint-disable @typescript-eslint/naming-convention */\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Credentials': 'true',\n 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',\n 'Access-Control-Allow-Headers':\n 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers',\n /* eslint-enable @typescript-eslint/naming-convention */\n};\n\nconst log = createModuleLogger(rootLogger, 'network');\n\nexport type Unmock = () => Promise<void>;\n\nexport type Mock = {\n /**\n * A function that can be used to unmock the URL.\n */\n unmock: Unmock;\n};\n\n/**\n * A function that can return `true` if the given request should be mocked, or\n * false if not.\n *\n * @param request - The request to check.\n * @returns Whether to mock the request.\n */\nexport type ConditionFunction = (request: HTTPRequest) => boolean;\n\nconst MockOptionsBaseStruct = object({\n response: defaulted(\n object({\n status: defaulted(number(), 200),\n headers: defaulted(record(string(), unknown()), DEFAULT_HEADERS),\n contentType: defaulted(string(), 'text/plain'),\n\n // Note: We default to a newline here, because the fetch request never\n // resolves if the body is empty.\n body: defaulted(string(), '\\n'),\n }),\n {},\n ),\n});\n\nconst MockOptionsUrlStruct = object({\n url: union([string(), regexp()]),\n partial: optional(boolean()),\n});\n\nconst MockOptionsConditionStruct = object({\n condition: func() as unknown as Struct<ConditionFunction, null>,\n});\n\nexport const MockOptionsStruct = union([\n assign(MockOptionsBaseStruct, MockOptionsUrlStruct),\n assign(MockOptionsBaseStruct, MockOptionsConditionStruct),\n]);\n\n/**\n * The options for the network mocking.\n *\n * @property url - The URL to mock. If a string is provided, the URL will be\n * matched exactly. If a RegExp is provided, the URL will be matched against it.\n * This option is incompatible with the `condition` option.\n * @property partial - If enabled, the request will be mocked if the URL starts\n * with the given URL. This option is ignored if a RegExp is provided to the\n * `url` option. This option is incompatible with the `condition` option.\n * @property condition - A function which gets the {@link HTTPRequest} as\n * parameter and returns a boolean to indicate whether the response should be\n * mocked or not. This option is incompatible with the `url` and `partial`\n * options.\n * @property response - The response to send for the request.\n * @property response.status - The status code to send for the response.\n * Defaults to `200`.\n * @property response.headers - The headers to send for the response. Defaults\n * to headers that enable CORS.\n * @property response.contentType - The content type to send for the response.\n * Defaults to `text/plain`.\n */\nexport type MockOptions = Infer<typeof MockOptionsStruct>;\n\n/**\n * Check if the given URL matches the given request, or if the condition\n * function returns `true`.\n *\n * @param request - The request to check.\n * @param options - The options for the network mocking.\n * @returns Whether the URL matches the request.\n */\nfunction matches(request: HTTPRequest, options: MockOptions) {\n if ('url' in options) {\n const { url, partial } = options;\n if (typeof url === 'string') {\n if (partial) {\n return request.url().startsWith(url);\n }\n\n return url === request.url();\n }\n\n return url.test(request.url());\n }\n\n const { condition } = options;\n return condition(request);\n}\n\n/**\n * Enable network mocking for the given page, and all its sub-frames.\n *\n * @param page - The page to enable network mocking on.\n * @param options - The options for the network mocking.\n * @returns A {@link Mock} object, with an `unmock` function.\n */\nexport async function mock(\n page: Page,\n options: DeepPartial<MockOptions>,\n): Promise<Mock> {\n await page.setRequestInterception(true);\n\n const parsedOptions = create(options, MockOptionsStruct);\n\n /**\n * The mock handler.\n *\n * @param request - The request to handle.\n */\n function handler(request: HTTPRequest) {\n // If the request is already handled, Puppeteer will throw an error if we\n // try to continue the request.\n if (request.isInterceptResolutionHandled()) {\n return;\n }\n\n if (!matches(request, parsedOptions)) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n request.continue();\n return;\n }\n\n log('Mocking request to %s', request.url());\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n request.respond(parsedOptions.response);\n }\n\n /**\n * Unmock the page.\n */\n async function unmock() {\n await page.setRequestInterception(false);\n page.off('request', handler);\n }\n\n page.on('request', handler);\n\n return {\n unmock,\n };\n}\n\nconst MockJsonRpcOptionsStruct = object({\n method: string(),\n result: UnsafeJsonStruct,\n});\n\nexport type MockJsonRpcOptions = Infer<typeof MockJsonRpcOptionsStruct>;\n\n/**\n * Mock an Ethereum JSON-RPC request. This intercepts all requests to the\n * Ethereum provider, and returns the `result` instead.\n *\n * @param page - The page to enable network JSON-RPC mocking on.\n * @param options - The options for the JSON-RPC mock.\n * @param options.method - The JSON-RPC method to mock. Any other methods will be\n * forwarded to the provider.\n * @param options.result - The JSON response to return.\n * @returns A {@link Mock} object, with an `unmock` function.\n */\nexport async function mockJsonRpc(\n page: Page,\n { method, result }: MockJsonRpcOptions,\n) {\n return await mock(page, {\n condition: (request: HTTPRequest) => {\n if (request.url() !== JSON_RPC_ENDPOINT) {\n return false;\n }\n\n const body = request.postData();\n if (!body) {\n return false;\n }\n\n try {\n const json = JSON.parse(body);\n return json.method === method;\n } catch (error) {\n log(\n `Unable to mock \"${method}\" request to Ethereum provider: %s`,\n error.message,\n );\n return false;\n }\n },\n response: {\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n result,\n }),\n },\n });\n}\n"],"names":["MockOptionsStruct","mock","mockJsonRpc","DEFAULT_HEADERS","log","createModuleLogger","rootLogger","MockOptionsBaseStruct","object","response","defaulted","status","number","headers","record","string","unknown","contentType","body","MockOptionsUrlStruct","url","union","regexp","partial","optional","boolean","MockOptionsConditionStruct","condition","func","assign","matches","request","options","startsWith","test","page","setRequestInterception","parsedOptions","create","handler","isInterceptResolutionHandled","continue","respond","unmock","off","on","MockJsonRpcOptionsStruct","method","result","UnsafeJsonStruct","JSON_RPC_ENDPOINT","postData","json","JSON","parse","error","message","stringify","jsonrpc","id"],"mappings":";;;;;;;;;;;IAkFaA,iBAAiB;eAAjBA;;IA6DSC,IAAI;eAAJA;;IAiEAC,WAA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BACxB,OAAOkC,KAAKL,MAAM,KAAKA;YACzB,EAAE,OAAOQ,OAAO;gBACdnD,IACE,CAAC,gBAAgB,EAAE2C,OAAO,kCAAkC,CAAC,EAC7DQ,MAAMC,OAAO;gBAEf,OAAO;YACT;QACF;QACA/C,UAAU;YACRE,QAAQ;YACRM,aAAa;YACbC,MAAMmC,KAAKI,SAAS,CAAC;gBACnBC,SAAS;gBACTC,IAAI;gBACJX;YACF;QACF;IACF;AACF"}
|
|
@@ -17,7 +17,9 @@ const MockOptionsBaseStruct = object({
|
|
|
17
17
|
status: defaulted(number(), 200),
|
|
18
18
|
headers: defaulted(record(string(), unknown()), DEFAULT_HEADERS),
|
|
19
19
|
contentType: defaulted(string(), 'text/plain'),
|
|
20
|
-
|
|
20
|
+
// Note: We default to a newline here, because the fetch request never
|
|
21
|
+
// resolves if the body is empty.
|
|
22
|
+
body: defaulted(string(), '\n')
|
|
21
23
|
}), {})
|
|
22
24
|
});
|
|
23
25
|
const MockOptionsUrlStruct = object({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/internals/network.ts"],"sourcesContent":["import { JSON_RPC_ENDPOINT } from '@metamask/snaps-simulator';\nimport { createModuleLogger, UnsafeJsonStruct } from '@metamask/utils';\nimport { Page, HTTPRequest } from 'puppeteer';\nimport {\n assign,\n boolean,\n create,\n defaulted,\n Infer,\n number,\n object,\n optional,\n record,\n regexp,\n string,\n Struct,\n union,\n unknown,\n func,\n} from 'superstruct';\n\nimport { DeepPartial } from '../types';\nimport { rootLogger } from './logger';\n\n/**\n * The default headers to use for mocked responses. These headers are used to\n * enable CORS.\n */\nconst DEFAULT_HEADERS = {\n /* eslint-disable @typescript-eslint/naming-convention */\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Credentials': 'true',\n 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',\n 'Access-Control-Allow-Headers':\n 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers',\n /* eslint-enable @typescript-eslint/naming-convention */\n};\n\nconst log = createModuleLogger(rootLogger, 'network');\n\nexport type Unmock = () => Promise<void>;\n\nexport type Mock = {\n /**\n * A function that can be used to unmock the URL.\n */\n unmock: Unmock;\n};\n\n/**\n * A function that can return `true` if the given request should be mocked, or\n * false if not.\n *\n * @param request - The request to check.\n * @returns Whether to mock the request.\n */\nexport type ConditionFunction = (request: HTTPRequest) => boolean;\n\nconst MockOptionsBaseStruct = object({\n response: defaulted(\n object({\n status: defaulted(number(), 200),\n headers: defaulted(record(string(), unknown()), DEFAULT_HEADERS),\n contentType: defaulted(string(), 'text/plain'),\n body: defaulted(string(), ''),\n }),\n {},\n ),\n});\n\nconst MockOptionsUrlStruct = object({\n url: union([string(), regexp()]),\n partial: optional(boolean()),\n});\n\nconst MockOptionsConditionStruct = object({\n condition: func() as unknown as Struct<ConditionFunction, null>,\n});\n\nexport const MockOptionsStruct = union([\n assign(MockOptionsBaseStruct, MockOptionsUrlStruct),\n assign(MockOptionsBaseStruct, MockOptionsConditionStruct),\n]);\n\n/**\n * The options for the network mocking.\n *\n * @property url - The URL to mock. If a string is provided, the URL will be\n * matched exactly. If a RegExp is provided, the URL will be matched against it.\n * This option is incompatible with the `condition` option.\n * @property partial - If enabled, the request will be mocked if the URL starts\n * with the given URL. This option is ignored if a RegExp is provided to the\n * `url` option. This option is incompatible with the `condition` option.\n * @property condition - A function which gets the {@link HTTPRequest} as\n * parameter and returns a boolean to indicate whether the response should be\n * mocked or not. This option is incompatible with the `url` and `partial`\n * options.\n * @property response - The response to send for the request.\n * @property response.status - The status code to send for the response.\n * Defaults to `200`.\n * @property response.headers - The headers to send for the response. Defaults\n * to headers that enable CORS.\n * @property response.contentType - The content type to send for the response.\n * Defaults to `text/plain`.\n */\nexport type MockOptions = Infer<typeof MockOptionsStruct>;\n\n/**\n * Check if the given URL matches the given request, or if the condition\n * function returns `true`.\n *\n * @param request - The request to check.\n * @param options - The options for the network mocking.\n * @returns Whether the URL matches the request.\n */\nfunction matches(request: HTTPRequest, options: MockOptions) {\n if ('url' in options) {\n const { url, partial } = options;\n if (typeof url === 'string') {\n if (partial) {\n return request.url().startsWith(url);\n }\n\n return url === request.url();\n }\n\n return url.test(request.url());\n }\n\n const { condition } = options;\n return condition(request);\n}\n\n/**\n * Enable network mocking for the given page, and all its sub-frames.\n *\n * @param page - The page to enable network mocking on.\n * @param options - The options for the network mocking.\n * @returns A {@link Mock} object, with an `unmock` function.\n */\nexport async function mock(\n page: Page,\n options: DeepPartial<MockOptions>,\n): Promise<Mock> {\n await page.setRequestInterception(true);\n\n const parsedOptions = create(options, MockOptionsStruct);\n\n /**\n * The mock handler.\n *\n * @param request - The request to handle.\n */\n function handler(request: HTTPRequest) {\n // If the request is already handled, Puppeteer will throw an error if we\n // try to continue the request.\n if (request.isInterceptResolutionHandled()) {\n return;\n }\n\n if (!matches(request, parsedOptions)) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n request.continue();\n return;\n }\n\n log('Mocking request to %s', request.url());\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n request.respond(parsedOptions.response);\n }\n\n /**\n * Unmock the page.\n */\n async function unmock() {\n await page.setRequestInterception(false);\n page.off('request', handler);\n }\n\n page.on('request', handler);\n\n return {\n unmock,\n };\n}\n\nconst MockJsonRpcOptionsStruct = object({\n method: string(),\n result: UnsafeJsonStruct,\n});\n\nexport type MockJsonRpcOptions = Infer<typeof MockJsonRpcOptionsStruct>;\n\n/**\n * Mock an Ethereum JSON-RPC request. This intercepts all requests to the\n * Ethereum provider, and returns the `result` instead.\n *\n * @param page - The page to enable network JSON-RPC mocking on.\n * @param options - The options for the JSON-RPC mock.\n * @param options.method - The JSON-RPC method to mock. Any other methods will be\n * forwarded to the provider.\n * @param options.result - The JSON response to return.\n * @returns A {@link Mock} object, with an `unmock` function.\n */\nexport async function mockJsonRpc(\n page: Page,\n { method, result }: MockJsonRpcOptions,\n) {\n return await mock(page, {\n condition: (request: HTTPRequest) => {\n if (request.url() !== JSON_RPC_ENDPOINT) {\n return false;\n }\n\n const body = request.postData();\n if (!body) {\n return false;\n }\n\n try {\n const json = JSON.parse(body);\n return json.method === method;\n } catch (error) {\n log(\n `Unable to mock \"${method}\" request to Ethereum provider: %s`,\n error.message,\n );\n return false;\n }\n },\n response: {\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n result,\n }),\n },\n });\n}\n"],"names":["JSON_RPC_ENDPOINT","createModuleLogger","UnsafeJsonStruct","assign","boolean","create","defaulted","number","object","optional","record","regexp","string","union","unknown","func","rootLogger","DEFAULT_HEADERS","log","MockOptionsBaseStruct","response","status","headers","contentType","body","MockOptionsUrlStruct","url","partial","MockOptionsConditionStruct","condition","MockOptionsStruct","matches","request","options","startsWith","test","mock","page","setRequestInterception","parsedOptions","handler","isInterceptResolutionHandled","continue","respond","unmock","off","on","MockJsonRpcOptionsStruct","method","result","mockJsonRpc","postData","json","JSON","parse","error","message","stringify","jsonrpc","id"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,4BAA4B;AAC9D,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,kBAAkB;AAEvE,SACEC,MAAM,EACNC,OAAO,EACPC,MAAM,EACNC,SAAS,EAETC,MAAM,EACNC,MAAM,EACNC,QAAQ,EACRC,MAAM,EACNC,MAAM,EACNC,MAAM,EAENC,KAAK,EACLC,OAAO,EACPC,IAAI,QACC,cAAc;AAGrB,SAASC,UAAU,QAAQ,WAAW;AAEtC;;;CAGC,GACD,MAAMC,kBAAkB;IACtB,uDAAuD,GACvD,+BAA+B;IAC/B,oCAAoC;IACpC,gCAAgC;IAChC,gCACE;AAEJ;AAEA,MAAMC,MAAMjB,mBAAmBe,YAAY;AAoB3C,MAAMG,wBAAwBX,OAAO;IACnCY,UAAUd,UACRE,OAAO;QACLa,QAAQf,UAAUC,UAAU;QAC5Be,SAAShB,UAAUI,OAAOE,UAAUE,Y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sBAAsB,CAAC;QAClCD,KAAKQ,GAAG,CAAC,WAAWL;IACtB;IAEAH,KAAKS,EAAE,CAAC,WAAWN;IAEnB,OAAO;QACLI;IACF;AACF;AAEA,MAAMG,2BAA2BvC,OAAO;IACtCwC,QAAQpC;IACRqC,QAAQ/C;AACV;AAIA;;;;;;;;;;CAUC,GACD,OAAO,eAAegD,YACpBb,IAAU,EACV,EAAEW,MAAM,EAAEC,MAAM,EAAsB;IAEtC,OAAO,MAAMb,KAAKC,MAAM;QACtBR,WAAW,CAACG;YACV,IAAIA,QAAQN,GAAG,OAAO1B,mBAAmB;gBACvC,OAAO;YACT;YAEA,MAAMwB,OAAOQ,QAAQmB,QAAQ;YAC7B,IAAI,CAAC3B,MAAM;gBACT,OAAO;YACT;YAEA,IAAI;gBACF,MAAM4B,OAAOC,KAAKC,KAAK,CAAC9B;gBACxB,OAAO4B,KAAKJ,MAAM,KAAKA;YACzB,EAAE,OAAOO,OAAO;gBACdrC,IACE,CAAC,gBAAgB,EAAE8B,OAAO,kCAAkC,CAAC,EAC7DO,MAAMC,OAAO;gBAEf,OAAO;YACT;QACF;QACApC,UAAU;YACRC,QAAQ;YACRE,aAAa;YACbC,MAAM6B,KAAKI,SAAS,CAAC;gBACnBC,SAAS;gBACTC,IAAI;gBACJV;YACF;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/internals/network.ts"],"sourcesContent":["import { JSON_RPC_ENDPOINT } from '@metamask/snaps-simulator';\nimport { createModuleLogger, UnsafeJsonStruct } from '@metamask/utils';\nimport { Page, HTTPRequest } from 'puppeteer';\nimport {\n assign,\n boolean,\n create,\n defaulted,\n Infer,\n number,\n object,\n optional,\n record,\n regexp,\n string,\n Struct,\n union,\n unknown,\n func,\n} from 'superstruct';\n\nimport { DeepPartial } from '../types';\nimport { rootLogger } from './logger';\n\n/**\n * The default headers to use for mocked responses. These headers are used to\n * enable CORS.\n */\nconst DEFAULT_HEADERS = {\n /* eslint-disable @typescript-eslint/naming-convention */\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Credentials': 'true',\n 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',\n 'Access-Control-Allow-Headers':\n 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers',\n /* eslint-enable @typescript-eslint/naming-convention */\n};\n\nconst log = createModuleLogger(rootLogger, 'network');\n\nexport type Unmock = () => Promise<void>;\n\nexport type Mock = {\n /**\n * A function that can be used to unmock the URL.\n */\n unmock: Unmock;\n};\n\n/**\n * A function that can return `true` if the given request should be mocked, or\n * false if not.\n *\n * @param request - The request to check.\n * @returns Whether to mock the request.\n */\nexport type ConditionFunction = (request: HTTPRequest) => boolean;\n\nconst MockOptionsBaseStruct = object({\n response: defaulted(\n object({\n status: defaulted(number(), 200),\n headers: defaulted(record(string(), unknown()), DEFAULT_HEADERS),\n contentType: defaulted(string(), 'text/plain'),\n\n // Note: We default to a newline here, because the fetch request never\n // resolves if the body is empty.\n body: defaulted(string(), '\\n'),\n }),\n {},\n ),\n});\n\nconst MockOptionsUrlStruct = object({\n url: union([string(), regexp()]),\n partial: optional(boolean()),\n});\n\nconst MockOptionsConditionStruct = object({\n condition: func() as unknown as Struct<ConditionFunction, null>,\n});\n\nexport const MockOptionsStruct = union([\n assign(MockOptionsBaseStruct, MockOptionsUrlStruct),\n assign(MockOptionsBaseStruct, MockOptionsConditionStruct),\n]);\n\n/**\n * The options for the network mocking.\n *\n * @property url - The URL to mock. If a string is provided, the URL will be\n * matched exactly. If a RegExp is provided, the URL will be matched against it.\n * This option is incompatible with the `condition` option.\n * @property partial - If enabled, the request will be mocked if the URL starts\n * with the given URL. This option is ignored if a RegExp is provided to the\n * `url` option. This option is incompatible with the `condition` option.\n * @property condition - A function which gets the {@link HTTPRequest} as\n * parameter and returns a boolean to indicate whether the response should be\n * mocked or not. This option is incompatible with the `url` and `partial`\n * options.\n * @property response - The response to send for the request.\n * @property response.status - The status code to send for the response.\n * Defaults to `200`.\n * @property response.headers - The headers to send for the response. Defaults\n * to headers that enable CORS.\n * @property response.contentType - The content type to send for the response.\n * Defaults to `text/plain`.\n */\nexport type MockOptions = Infer<typeof MockOptionsStruct>;\n\n/**\n * Check if the given URL matches the given request, or if the condition\n * function returns `true`.\n *\n * @param request - The request to check.\n * @param options - The options for the network mocking.\n * @returns Whether the URL matches the request.\n */\nfunction matches(request: HTTPRequest, options: MockOptions) {\n if ('url' in options) {\n const { url, partial } = options;\n if (typeof url === 'string') {\n if (partial) {\n return request.url().startsWith(url);\n }\n\n return url === request.url();\n }\n\n return url.test(request.url());\n }\n\n const { condition } = options;\n return condition(request);\n}\n\n/**\n * Enable network mocking for the given page, and all its sub-frames.\n *\n * @param page - The page to enable network mocking on.\n * @param options - The options for the network mocking.\n * @returns A {@link Mock} object, with an `unmock` function.\n */\nexport async function mock(\n page: Page,\n options: DeepPartial<MockOptions>,\n): Promise<Mock> {\n await page.setRequestInterception(true);\n\n const parsedOptions = create(options, MockOptionsStruct);\n\n /**\n * The mock handler.\n *\n * @param request - The request to handle.\n */\n function handler(request: HTTPRequest) {\n // If the request is already handled, Puppeteer will throw an error if we\n // try to continue the request.\n if (request.isInterceptResolutionHandled()) {\n return;\n }\n\n if (!matches(request, parsedOptions)) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n request.continue();\n return;\n }\n\n log('Mocking request to %s', request.url());\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n request.respond(parsedOptions.response);\n }\n\n /**\n * Unmock the page.\n */\n async function unmock() {\n await page.setRequestInterception(false);\n page.off('request', handler);\n }\n\n page.on('request', handler);\n\n return {\n unmock,\n };\n}\n\nconst MockJsonRpcOptionsStruct = object({\n method: string(),\n result: UnsafeJsonStruct,\n});\n\nexport type MockJsonRpcOptions = Infer<typeof MockJsonRpcOptionsStruct>;\n\n/**\n * Mock an Ethereum JSON-RPC request. This intercepts all requests to the\n * Ethereum provider, and returns the `result` instead.\n *\n * @param page - The page to enable network JSON-RPC mocking on.\n * @param options - The options for the JSON-RPC mock.\n * @param options.method - The JSON-RPC method to mock. Any other methods will be\n * forwarded to the provider.\n * @param options.result - The JSON response to return.\n * @returns A {@link Mock} object, with an `unmock` function.\n */\nexport async function mockJsonRpc(\n page: Page,\n { method, result }: MockJsonRpcOptions,\n) {\n return await mock(page, {\n condition: (request: HTTPRequest) => {\n if (request.url() !== JSON_RPC_ENDPOINT) {\n return false;\n }\n\n const body = request.postData();\n if (!body) {\n return false;\n }\n\n try {\n const json = JSON.parse(body);\n return json.method === method;\n } catch (error) {\n log(\n `Unable to mock \"${method}\" request to Ethereum provider: %s`,\n error.message,\n );\n return false;\n }\n },\n response: {\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n result,\n }),\n },\n });\n}\n"],"names":["JSON_RPC_ENDPOINT","createModuleLogger","UnsafeJsonStruct","assign","boolean","create","defaulted","number","object","optional","record","regexp","string","union","unknown","func","rootLogger","DEFAULT_HEADERS","log","MockOptionsBaseStruct","response","status","headers","contentType","body","MockOptionsUrlStruct","url","partial","MockOptionsConditionStruct","condition","MockOptionsStruct","matches","request","options","startsWith","test","mock","page","setRequestInterception","parsedOptions","handler","isInterceptResolutionHandled","continue","respond","unmock","off","on","MockJsonRpcOptionsStruct","method","result","mockJsonRpc","postData","json","JSON","parse","error","message","stringify","jsonrpc","id"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,4BAA4B;AAC9D,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,kBAAkB;AAEvE,SACEC,MAAM,EACNC,OAAO,EACPC,MAAM,EACNC,SAAS,EAETC,MAAM,EACNC,MAAM,EACNC,QAAQ,EACRC,MAAM,EACNC,MAAM,EACNC,MAAM,EAENC,KAAK,EACLC,OAAO,EACPC,IAAI,QACC,cAAc;AAGrB,SAASC,UAAU,QAAQ,WAAW;AAEtC;;;CAGC,GACD,MAAMC,kBAAkB;IACtB,uDAAuD,GAC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,IAAI;YAC1C;QACF;QAEA,IAAI,CAACV,QAAQC,SAASO,gBAAgB;YACpC,mEAAmE;YACnEP,QAAQU,QAAQ;YAChB;QACF;QAEAxB,IAAI,yBAAyBc,QAAQN,GAAG;QAExC,mEAAmE;QACnEM,QAAQW,OAAO,CAACJ,cAAcnB,QAAQ;IACxC;IAEA;;GAEC,GACD,eAAewB;QACb,MAAMP,KAAKC,sBAAsB,CAAC;QAClCD,KAAKQ,GAAG,CAAC,WAAWL;IACtB;IAEAH,KAAKS,EAAE,CAAC,WAAWN;IAEnB,OAAO;QACLI;IACF;AACF;AAEA,MAAMG,2BAA2BvC,OAAO;IACtCwC,QAAQpC;IACRqC,QAAQ/C;AACV;AAIA;;;;;;;;;;CAUC,GACD,OAAO,eAAegD,YACpBb,IAAU,EACV,EAAEW,MAAM,EAAEC,MAAM,EAAsB;IAEtC,OAAO,MAAMb,KAAKC,MAAM;QACtBR,WAAW,CAACG;YACV,IAAIA,QAAQN,GAAG,OAAO1B,mBAAmB;gBACvC,OAAO;YACT;YAEA,MAAMwB,OAAOQ,QAAQmB,QAAQ;YAC7B,IAAI,CAAC3B,MAAM;gBACT,OAAO;YACT;YAEA,IAAI;gBACF,MAAM4B,OAAOC,KAAKC,KAAK,CAAC9B;gBACxB,OAAO4B,KAAKJ,MAAM,KAAKA;YACzB,EAAE,OAAOO,OAAO;gBACdrC,IACE,CAAC,gBAAgB,EAAE8B,OAAO,kCAAkC,CAAC,EAC7DO,MAAMC,OAAO;gBAEf,OAAO;YACT;QACF;QACApC,UAAU;YACRC,QAAQ;YACRE,aAAa;YACbC,MAAM6B,KAAKI,SAAS,CAAC;gBACnBC,SAAS;gBACTC,IAAI;gBACJV;YACF;QACF;IACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/snaps-jest",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.36.0-flask.1",
|
|
4
4
|
"description": "A Jest preset for end-to-end testing MetaMask Snaps, including a Jest environment, and a set of Jest matchers.",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"main": "./dist/cjs/index.js",
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"build:esm": "swc src --out-dir dist/esm --config-file ../../.swcrc.build.json --config module.type=es6",
|
|
29
29
|
"build:cjs": "swc src --out-dir dist/cjs --config-file ../../.swcrc.build.json --config module.type=commonjs",
|
|
30
30
|
"build:clean": "yarn clean && yarn build",
|
|
31
|
-
"clean": "rimraf '*.tsbuildinfo' 'dist
|
|
31
|
+
"clean": "rimraf '*.tsbuildinfo' 'dist'",
|
|
32
32
|
"prepare-manifest:preview": "../../scripts/prepare-preview-manifest.sh",
|
|
33
33
|
"publish:preview": "yarn npm publish --tag preview"
|
|
34
34
|
},
|
|
@@ -37,11 +37,11 @@
|
|
|
37
37
|
"@jest/expect": "^29.5.0",
|
|
38
38
|
"@jest/globals": "^29.5.0",
|
|
39
39
|
"@jest/types": "^29.5.0",
|
|
40
|
-
"@metamask/rpc-methods": "^0.
|
|
41
|
-
"@metamask/snaps-execution-environments": "^0.
|
|
42
|
-
"@metamask/snaps-simulator": "^0.
|
|
43
|
-
"@metamask/snaps-ui": "^0.
|
|
44
|
-
"@metamask/snaps-utils": "^0.
|
|
40
|
+
"@metamask/rpc-methods": "^0.36.0-flask.1",
|
|
41
|
+
"@metamask/snaps-execution-environments": "^0.36.0-flask.1",
|
|
42
|
+
"@metamask/snaps-simulator": "^0.36.0-flask.1",
|
|
43
|
+
"@metamask/snaps-ui": "^0.36.0-flask.1",
|
|
44
|
+
"@metamask/snaps-utils": "^0.36.0-flask.1",
|
|
45
45
|
"@metamask/utils": "^6.0.1",
|
|
46
46
|
"express": "^4.18.2",
|
|
47
47
|
"jest-environment-node": "^29.5.0",
|