@metamask/snaps-utils 4.0.0 → 5.0.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.
- package/CHANGELOG.md +17 -1
- package/dist/cjs/cronjob.js +6 -7
- package/dist/cjs/cronjob.js.map +1 -1
- package/dist/cjs/index.browser.js +0 -1
- package/dist/cjs/index.browser.js.map +1 -1
- package/dist/cjs/index.js +0 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/manifest/manifest.js +4 -3
- package/dist/cjs/manifest/manifest.js.map +1 -1
- package/dist/cjs/structs.js +0 -22
- package/dist/cjs/structs.js.map +1 -1
- package/dist/cjs/ui.js +16 -14
- package/dist/cjs/ui.js.map +1 -1
- package/dist/esm/cronjob.js +8 -9
- package/dist/esm/cronjob.js.map +1 -1
- package/dist/esm/index.browser.js +0 -1
- package/dist/esm/index.browser.js.map +1 -1
- package/dist/esm/index.js +0 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/manifest/manifest.js +5 -3
- package/dist/esm/manifest/manifest.js.map +1 -1
- package/dist/esm/structs.js +1 -48
- package/dist/esm/structs.js.map +1 -1
- package/dist/esm/ui.js +18 -16
- package/dist/esm/ui.js.map +1 -1
- package/dist/types/cronjob.d.ts +15 -15
- package/dist/types/handlers.d.ts +72 -0
- package/dist/types/index.browser.d.ts +0 -1
- package/dist/types/index.d.ts +0 -1
- package/dist/types/localization.d.ts +1 -1
- package/dist/types/manifest/manifest.d.ts +3 -1
- package/dist/types/manifest/validation.d.ts +17 -17
- package/dist/types/structs.d.ts +2 -40
- package/dist/types/ui.d.ts +1 -1
- package/package.json +4 -4
- package/dist/cjs/enum.js +0 -16
- package/dist/cjs/enum.js.map +0 -1
- package/dist/esm/enum.js +0 -12
- package/dist/esm/enum.js.map +0 -1
- package/dist/types/enum.d.ts +0 -10
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [5.0.0]
|
|
10
|
+
### Changed
|
|
11
|
+
- Bump several MetaMask dependencies ([#1964](https://github.com/MetaMask/snaps/pull/1964))
|
|
12
|
+
|
|
13
|
+
### Removed
|
|
14
|
+
- **BREAKING:** Move `enumValue`, `literal` and `union` to `snaps-sdk` ([#1968](https://github.com/MetaMask/snaps/pull/1968))
|
|
15
|
+
|
|
16
|
+
### Fixed
|
|
17
|
+
- Fix issues generating checksum with binary auxiliary files ([#1975](https://github.com/MetaMask/snaps/pull/1975))
|
|
18
|
+
|
|
19
|
+
## [4.0.1]
|
|
20
|
+
### Fixed
|
|
21
|
+
- Change `validateTextLinks` to only get URL in markdown links ([#1914](https://github.com/MetaMask/snaps/pull/1914))
|
|
22
|
+
|
|
9
23
|
## [4.0.0]
|
|
10
24
|
### Changed
|
|
11
25
|
- Use `SubtleCrypto` for checksum calculation if available ([#1953](https://github.com/MetaMask/snaps/pull/1953))
|
|
@@ -103,7 +117,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
103
117
|
- The version of the package no longer needs to match the version of all other
|
|
104
118
|
MetaMask Snaps packages.
|
|
105
119
|
|
|
106
|
-
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@
|
|
120
|
+
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@5.0.0...HEAD
|
|
121
|
+
[5.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@4.0.1...@metamask/snaps-utils@5.0.0
|
|
122
|
+
[4.0.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@4.0.0...@metamask/snaps-utils@4.0.1
|
|
107
123
|
[4.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.3.0...@metamask/snaps-utils@4.0.0
|
|
108
124
|
[3.3.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.2.0...@metamask/snaps-utils@3.3.0
|
|
109
125
|
[3.2.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.1.0...@metamask/snaps-utils@3.2.0
|
package/dist/cjs/cronjob.js
CHANGED
|
@@ -34,13 +34,12 @@ _export(exports, {
|
|
|
34
34
|
const _utils = require("@metamask/utils");
|
|
35
35
|
const _cronparser = require("cron-parser");
|
|
36
36
|
const _superstruct = require("superstruct");
|
|
37
|
-
const CronjobRpcRequestStruct = (0, _superstruct.
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
]));
|
|
37
|
+
const CronjobRpcRequestStruct = (0, _superstruct.object)({
|
|
38
|
+
jsonrpc: (0, _superstruct.optional)(_utils.JsonRpcVersionStruct),
|
|
39
|
+
id: (0, _superstruct.optional)(_utils.JsonRpcIdStruct),
|
|
40
|
+
method: (0, _superstruct.string)(),
|
|
41
|
+
params: (0, _superstruct.optional)(_utils.JsonRpcParamsStruct)
|
|
42
|
+
});
|
|
44
43
|
const CronExpressionStruct = (0, _superstruct.refine)((0, _superstruct.coerce)((0, _superstruct.string)(), (0, _superstruct.object)({
|
|
45
44
|
minute: (0, _superstruct.optional)((0, _superstruct.string)()),
|
|
46
45
|
hour: (0, _superstruct.optional)((0, _superstruct.string)()),
|
package/dist/cjs/cronjob.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cronjob.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../src/cronjob.ts"],"sourcesContent":["import {\n JsonRpcIdStruct,\n JsonRpcParamsStruct,\n JsonRpcVersionStruct,\n} from '@metamask/utils';\nimport { parseExpression } from 'cron-parser';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n coerce,\n create,\n object,\n optional,\n refine,\n string,\n} from 'superstruct';\n\nexport const CronjobRpcRequestStruct = object({\n jsonrpc: optional(JsonRpcVersionStruct),\n id: optional(JsonRpcIdStruct),\n method: string(),\n params: optional(JsonRpcParamsStruct),\n});\n\nexport type CronjobRpcRequest = Infer<typeof CronjobRpcRequestStruct>;\n\nexport const CronExpressionStruct = refine(\n coerce(\n string(),\n object({\n minute: optional(string()),\n hour: optional(string()),\n dayOfMonth: optional(string()),\n month: optional(string()),\n dayOfWeek: optional(string()),\n }),\n (value) =>\n `${value.minute ?? '*'} ${value.hour ?? '*'} ${value.dayOfMonth ?? '*'} ${\n value.month ?? '*'\n } ${value.dayOfWeek ?? '*'}`,\n ),\n 'CronExpression',\n (value) => {\n try {\n parseExpression(value);\n return true;\n } catch {\n return false;\n }\n },\n);\n\nexport type CronExpression = Infer<typeof CronExpressionStruct>;\n\n/**\n * Parses a cron expression.\n *\n * @param expression - Expression to parse.\n * @returns A CronExpression class instance.\n */\nexport function parseCronExpression(expression: string | object) {\n const ensureStringExpression = create(expression, CronExpressionStruct);\n return parseExpression(ensureStringExpression);\n}\n\nexport const CronjobSpecificationStruct = object({\n expression: CronExpressionStruct,\n request: CronjobRpcRequestStruct,\n});\nexport type CronjobSpecification = Infer<typeof CronjobSpecificationStruct>;\n\n/**\n * Check if the given value is a {@link CronjobSpecification} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link CronjobSpecification} object.\n */\nexport function isCronjobSpecification(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationStruct);\n return true;\n } catch {\n return false;\n }\n}\n\nexport const CronjobSpecificationArrayStruct = array(\n CronjobSpecificationStruct,\n);\n\n/**\n * Check if the given value is an array of {@link CronjobSpecification} objects.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid array of {@link CronjobSpecification} objects.\n */\nexport function isCronjobSpecificationArray(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationArrayStruct);\n return true;\n } catch {\n return false;\n }\n}\n"],"names":["CronjobRpcRequestStruct","CronExpressionStruct","parseCronExpression","CronjobSpecificationStruct","isCronjobSpecification","CronjobSpecificationArrayStruct","isCronjobSpecificationArray","object","jsonrpc","optional","JsonRpcVersionStruct","id","JsonRpcIdStruct","method","string","params","JsonRpcParamsStruct","refine","coerce","minute","hour","dayOfMonth","month","dayOfWeek","value","parseExpression","expression","ensureStringExpression","create","request","array"],"mappings":";;;;;;;;;;;IAiBaA,uBAAuB;eAAvBA;;IASAC,oBAAoB;eAApBA;;IAkCGC,mBAAmB;eAAnBA;;IAKHC,0BAA0B;eAA1BA;;IAYGC,sBAAsB;eAAtBA;;IASHC,+BAA+B;eAA/BA;;IAUGC,2BAA2B;eAA3BA;;;uBA5FT;4BACyB;6BAUzB;AAEA,MAAMN,0BAA0BO,IAAAA,mBAAM,EAAC;IAC5CC,SAASC,IAAAA,qBAAQ,EAACC,2BAAoB;IACtCC,IAAIF,IAAAA,qBAAQ,EAACG,sBAAe;IAC5BC,QAAQC,IAAAA,mBAAM;IACdC,QAAQN,IAAAA,qBAAQ,EAACO,0BAAmB;AACtC;AAIO,MAAMf,uBAAuBgB,IAAAA,mBAAM,EACxCC,IAAAA,mBAAM,EACJJ,IAAAA,mBAAM,KACNP,IAAAA,mBAAM,EAAC;IACLY,QAAQV,IAAAA,qBAAQ,EAACK,IAAAA,mBAAM;IACvBM,MAAMX,IAAAA,qBAAQ,EAACK,IAAAA,mBAAM;IACrBO,YAAYZ,IAAAA,qBAAQ,EAACK,IAAAA,mBAAM;IAC3BQ,OAAOb,IAAAA,qBAAQ,EAACK,IAAAA,mBAAM;IACtBS,WAAWd,IAAAA,qBAAQ,EAACK,IAAAA,mBAAM;AAC5B,IACA,CAACU,QACC,CAAC,EAAEA,MAAML,MAAM,IAAI,IAAI,CAAC,EAAEK,MAAMJ,IAAI,IAAI,IAAI,CAAC,EAAEI,MAAMH,UAAU,IAAI,IAAI,CAAC,EACtEG,MAAMF,KAAK,IAAI,IAChB,CAAC,EAAEE,MAAMD,SAAS,IAAI,IAAI,CAAC,GAEhC,kBACA,CAACC;IACC,IAAI;QACFC,IAAAA,2BAAe,EAACD;QAChB,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAWK,SAAStB,oBAAoBwB,UAA2B;IAC7D,MAAMC,yBAAyBC,IAAAA,mBAAM,EAACF,YAAYzB;IAClD,OAAOwB,IAAAA,2BAAe,EAACE;AACzB;AAEO,MAAMxB,6BAA6BI,IAAAA,mBAAM,EAAC;IAC/CmB,YAAYzB;IACZ4B,SAAS7B;AACX;AASO,SAASI,uBAAuBoB,KAAc;IACnD,IAAI;QACFI,IAAAA,mBAAM,EAACJ,OAAOrB;QACd,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEO,MAAME,kCAAkCyB,IAAAA,kBAAK,EAClD3B;AASK,SAASG,4BAA4BkB,KAAc;IACxD,IAAI;QACFI,IAAAA,mBAAM,EAACJ,OAAOnB;QACd,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
|
|
@@ -10,7 +10,6 @@ _export_star(require("./cronjob"), exports);
|
|
|
10
10
|
_export_star(require("./deep-clone"), exports);
|
|
11
11
|
_export_star(require("./default-endowments"), exports);
|
|
12
12
|
_export_star(require("./entropy"), exports);
|
|
13
|
-
_export_star(require("./enum"), exports);
|
|
14
13
|
_export_star(require("./errors"), exports);
|
|
15
14
|
_export_star(require("./handlers"), exports);
|
|
16
15
|
_export_star(require("./handler-types"), exports);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './
|
|
1
|
+
{"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './errors';\nexport * from './handlers';\nexport * from './handler-types';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './localization';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './path';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './ui';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"],"names":[],"mappings":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
|
package/dist/cjs/index.js
CHANGED
|
@@ -10,7 +10,6 @@ _export_star(require("./checksum"), exports);
|
|
|
10
10
|
_export_star(require("./deep-clone"), exports);
|
|
11
11
|
_export_star(require("./default-endowments"), exports);
|
|
12
12
|
_export_star(require("./entropy"), exports);
|
|
13
|
-
_export_star(require("./enum"), exports);
|
|
14
13
|
_export_star(require("./eval"), exports);
|
|
15
14
|
_export_star(require("./errors"), exports);
|
|
16
15
|
_export_star(require("./fs"), exports);
|
package/dist/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './eval';\nexport * from './errors';\nexport * from './fs';\nexport * from './handlers';\nexport * from './handler-types';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './localization';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './ui';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file';\n"],"names":[],"mappings":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
|
|
@@ -75,7 +75,8 @@ async function checkManifest(basePath, writeManifest = true, sourceCode, writeFi
|
|
|
75
75
|
packageJson: packageFile,
|
|
76
76
|
sourceCode: await getSnapSourceCode(basePath, unvalidatedManifest, sourceCode),
|
|
77
77
|
svgIcon: await getSnapIcon(basePath, unvalidatedManifest),
|
|
78
|
-
|
|
78
|
+
// Intentionally pass null as the encoding here since the files may be binary
|
|
79
|
+
auxiliaryFiles: await getSnapFiles(basePath, auxiliaryFilePaths, null) ?? [],
|
|
79
80
|
localizationFiles: await getSnapFiles(basePath, localizationFilePaths) ?? []
|
|
80
81
|
};
|
|
81
82
|
let manifest;
|
|
@@ -221,12 +222,12 @@ function getSnapFilePaths(manifest, selector) {
|
|
|
221
222
|
}
|
|
222
223
|
return paths;
|
|
223
224
|
}
|
|
224
|
-
async function getSnapFiles(basePath, paths) {
|
|
225
|
+
async function getSnapFiles(basePath, paths, encoding = 'utf8') {
|
|
225
226
|
if (!paths) {
|
|
226
227
|
return undefined;
|
|
227
228
|
}
|
|
228
229
|
try {
|
|
229
|
-
return await Promise.all(paths.map(async (filePath)=>(0, _virtualfile.readVirtualFile)(_path.default.join(basePath, filePath),
|
|
230
|
+
return await Promise.all(paths.map(async (filePath)=>(0, _virtualfile.readVirtualFile)(_path.default.join(basePath, filePath), encoding)));
|
|
230
231
|
} catch (error) {
|
|
231
232
|
throw new Error(`Failed to read snap files: ${(0, _snapssdk.getErrorMessage)(error)}`);
|
|
232
233
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/manifest/manifest.ts"],"sourcesContent":["import { getErrorMessage } from '@metamask/snaps-sdk';\nimport type { Json } from '@metamask/utils';\nimport { assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\nimport { NpmSnapFileNames, SnapValidationFailureReason } from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file';\nimport type { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n $schema: 1,\n version: 2,\n description: 3,\n proposedName: 4,\n repository: 5,\n source: 6,\n initialPermissions: 7,\n manifestVersion: 8,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\n};\n\nexport type WriteFileFunction = (path: string, data: string) => Promise<void>;\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @param writeFileFn - The function to use to write the manifest to disk.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n writeFileFn: WriteFileFunction = fs.writeFile,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const auxiliaryFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.files,\n );\n\n const localizationFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.locales,\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n auxiliaryFiles: (await getSnapFiles(basePath, auxiliaryFilePaths)) ?? [],\n localizationFiles:\n (await getSnapFiles(basePath, localizationFilePaths)) ?? [],\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = await validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n let currentError = error;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the `SnapValidationFailureReason` enum, so we only\n // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = await fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n await validateNpmSnapManifest({\n ...partiallyValidatedFiles,\n manifest,\n });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = nextValidationError;\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n warnings.push(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await writeFileFn(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nexport async function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): Promise<VirtualFile<SnapManifest>> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = await getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(\n `Failed to read snap bundle file: ${getErrorMessage(error)}`,\n );\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read snap icon file: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Get an array of paths from an unvalidated Snap manifest.\n *\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param selector - A function that returns the paths to the files.\n * @returns The paths to the files, if any.\n */\nexport function getSnapFilePaths(\n manifest: Json,\n selector: (manifest: Partial<SnapManifest>) => string[] | undefined,\n) {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const snapManifest = manifest as Partial<SnapManifest>;\n const paths = selector(snapManifest);\n\n if (!Array.isArray(paths)) {\n return undefined;\n }\n\n return paths;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the files with the\n * given paths and read them.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param paths - The paths to the files.\n * @returns A list of auxiliary files and their contents, if any.\n */\nexport async function getSnapFiles(\n basePath: string,\n paths: string[] | undefined,\n): Promise<VirtualFile[] | undefined> {\n if (!paths) {\n return undefined;\n }\n\n try {\n return await Promise.all(\n paths.map(async (filePath) =>\n readVirtualFile(pathUtils.join(basePath, filePath), 'utf8'),\n ),\n );\n } catch (error) {\n throw new Error(`Failed to read snap files: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an NPM Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n * @param snapFiles.auxiliaryFiles - Any auxiliary files required by the snap at runtime.\n * @param snapFiles.localizationFiles - The Snap's localization files.\n */\nexport async function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n await validateSnapShasum(\n { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["checkManifest","fixManifest","getSnapSourceCode","getSnapIcon","getSnapFilePaths","getSnapFiles","getWritableManifest","validateNpmSnapManifest","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","basePath","writeManifest","sourceCode","writeFileFn","fs","writeFile","warnings","errors","updated","manifestPath","pathUtils","join","NpmSnapFileNames","Manifest","manifestFile","readJsonFile","unvalidatedManifest","result","packageFile","PackageJson","auxiliaryFilePaths","manifest","files","localizationFilePaths","locales","snapFiles","packageJson","svgIcon","auxiliaryFiles","localizationFiles","validateNpmSnap","error","ProgrammaticallyFixableSnapError","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","SnapValidationFailureReason","length","attempts","nextValidationError","Error","assert","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","value","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","deepClone","undefined","ShasumMismatch","shasum","getSnapChecksum","assertExhaustive","isPlainObject","sourceFilePath","filePath","VirtualFile","path","virtualFile","readVirtualFile","getErrorMessage","iconPath","selector","snapManifest","paths","Array","isArray","Promise","all","map","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository","deepEqual","validateSnapShasum"],"mappings":";;;;;;;;;;;IAkEsBA,aAAa;eAAbA;;IA6JAC,WAAW;eAAXA;;IA8CAC,iBAAiB;eAAjBA;;IA4CAC,WAAW;e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AAgBC;IAAkB,GACnE,CAAC,CAAC,EAAEjB,uBAAgB,CAACC,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/manifest/manifest.ts"],"sourcesContent":["import { getErrorMessage } from '@metamask/snaps-sdk';\nimport type { Json } from '@metamask/utils';\nimport { assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\nimport { NpmSnapFileNames, SnapValidationFailureReason } from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file';\nimport type { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n $schema: 1,\n version: 2,\n description: 3,\n proposedName: 4,\n repository: 5,\n source: 6,\n initialPermissions: 7,\n manifestVersion: 8,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\n};\n\nexport type WriteFileFunction = (path: string, data: string) => Promise<void>;\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @param writeFileFn - The function to use to write the manifest to disk.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n writeFileFn: WriteFileFunction = fs.writeFile,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const auxiliaryFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.files,\n );\n\n const localizationFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.locales,\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n // Intentionally pass null as the encoding here since the files may be binary\n auxiliaryFiles:\n (await getSnapFiles(basePath, auxiliaryFilePaths, null)) ?? [],\n localizationFiles:\n (await getSnapFiles(basePath, localizationFilePaths)) ?? [],\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = await validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n let currentError = error;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the `SnapValidationFailureReason` enum, so we only\n // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = await fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n await validateNpmSnapManifest({\n ...partiallyValidatedFiles,\n manifest,\n });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = nextValidationError;\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n warnings.push(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await writeFileFn(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nexport async function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): Promise<VirtualFile<SnapManifest>> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = await getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(\n `Failed to read snap bundle file: ${getErrorMessage(error)}`,\n );\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read snap icon file: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Get an array of paths from an unvalidated Snap manifest.\n *\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param selector - A function that returns the paths to the files.\n * @returns The paths to the files, if any.\n */\nexport function getSnapFilePaths(\n manifest: Json,\n selector: (manifest: Partial<SnapManifest>) => string[] | undefined,\n) {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const snapManifest = manifest as Partial<SnapManifest>;\n const paths = selector(snapManifest);\n\n if (!Array.isArray(paths)) {\n return undefined;\n }\n\n return paths;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the files with the\n * given paths and read them.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param paths - The paths to the files.\n * @param encoding - An optional encoding to pass down to readVirtualFile.\n * @returns A list of auxiliary files and their contents, if any.\n */\nexport async function getSnapFiles(\n basePath: string,\n paths: string[] | undefined,\n encoding: BufferEncoding | null = 'utf8',\n): Promise<VirtualFile[] | undefined> {\n if (!paths) {\n return undefined;\n }\n\n try {\n return await Promise.all(\n paths.map(async (filePath) =>\n readVirtualFile(pathUtils.join(basePath, filePath), encoding),\n ),\n );\n } catch (error) {\n throw new Error(`Failed to read snap files: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an NPM Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n * @param snapFiles.auxiliaryFiles - Any auxiliary files required by the snap at runtime.\n * @param snapFiles.localizationFiles - The Snap's localization files.\n */\nexport async function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n await validateSnapShasum(\n { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["checkManifest","fixManifest","getSnapSourceCode","getSnapIcon","getSnapFilePaths","getSnapFiles","getWritableManifest","validateNpmSnapManifest","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","basePath","writeManifest","sourceCode","writeFileFn","fs","writeFile","warnings","errors","updated","manifestPath","pathUtils","join","NpmSnapFileNames","Manifest","manifestFile","readJsonFile","unvalidatedManifest","result","packageFile","PackageJson","auxiliaryFilePaths","manifest","files","localizationFilePaths","locales","snapFiles","packageJson","svgIcon","auxiliaryFiles","localizationFiles","validateNpmSnap","error","ProgrammaticallyFixableSnapError","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","SnapValidationFailureReason","length","attempts","nextValidationError","Error","assert","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","value","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","deepClone","undefined","ShasumMismatch","shasum","getSnapChecksum","assertExhaustive","isPlainObject","sourceFilePath","filePath","VirtualFile","path","virtualFile","readVirtualFile","getErrorMessage","iconPath","selector","snapManifest","paths","Array","isArray","encoding","Promise","all","map","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository","deepEqual","validateSnapShasum"],"mappings":";;;;;;;;;;;IAkEsBA,aAAa;eAAbA;;IA+JAC,WAAW;eAAXA;;IA8CAC,iBAAiB;eAAjBA;;IA4CAC,WAAW;eAAXA;;IAiCNC,gBAAgB;eAAhBA;;IA2BMC,YAAY;eAAZA;;IA2BNC,mBAAmB;eAAnBA;;IAgCMC,uBAAuB;eAAvBA;;;0BAlbU;uBAEwB;sEAClC;oBACS;6DACT;2BAEI;qBACG;qBACG;uBAKzB;uBAEuD;6BACjB;;;;;;AAG7C,MAAMC,sBAA0D;IAC9DC,SAAS;IACTC,SAAS;IACTC,aAAa;IACbC,cAAc;IACdC,YAAY;IACZC,QAAQ;IACRC,oBAAoB;IACpBC,iBAAiB;AACnB;AAqCO,eAAehB,cACpBiB,QAAgB,EAChBC,gBAAgB,IAAI,EACpBC,UAAmB,EACnBC,cAAiCC,YAAE,CAACC,SAAS;IAE7C,MAAMC,WAAqB,EAAE;IAC7B,MAAMC,SAAmB,EAAE;IAE3B,IAAIC,UAAU;IAEd,MAAMC,eAAeC,aAAS,CAACC,IAAI,CAACX,UAAUY,uBAAgB,CAACC,QAAQ;IACvE,MAAMC,eAAe,MAAMC,IAAAA,iBAAY,EAACN;IACxC,MAAMO,sBAAsBF,aAAaG,MAAM;IAE/C,MAAMC,cAAc,MAAMH,IAAAA,iBAAY,EACpCL,aAAS,CAACC,IAAI,CAACX,UAAUY,uBAAgB,CAACO,WAAW;IAGvD,MAAMC,qBAAqBjC,iBACzB6B,qBACA,CAACK,WAAaA,UAAUxB,QAAQyB;IAGlC,MAAMC,wBAAwBpC,iBAC5B6B,qBACA,CAACK,WAAaA,UAAUxB,QAAQ2B;IAGlC,MAAMC,YAAkC;QACtCJ,UAAUP;QACVY,aAAaR;QACbhB,YAAY,MAAMjB,kBAChBe,UACAgB,qBACAd;QAEFyB,SAAS,MAAMzC,YAAYc,UAAUgB;QACrC,6EAA6E;QAC7EY,gB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AC,EAAEpB,uBAAgB,CAACC,QAAQ,CAAC,yCAAyC,EAAED,uBAAgB,CAACO,WAAW,CAAC,qBAAqB,CAAC,EAC5HsB,kCAA2B,CAAC4B,kBAAkB;IAElD;IAEA,MAAMqC,IAAAA,yBAAkB,EACtB;QAAErF;QAAUnB;QAAYyB;QAASC;QAAgBC;IAAkB,GACnE,CAAC,CAAC,EAAEjB,uBAAgB,CAACC,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
|
package/dist/cjs/structs.js
CHANGED
|
@@ -9,12 +9,6 @@ function _export(target, all) {
|
|
|
9
9
|
});
|
|
10
10
|
}
|
|
11
11
|
_export(exports, {
|
|
12
|
-
literal: function() {
|
|
13
|
-
return literal;
|
|
14
|
-
},
|
|
15
|
-
union: function() {
|
|
16
|
-
return union;
|
|
17
|
-
},
|
|
18
12
|
file: function() {
|
|
19
13
|
return file;
|
|
20
14
|
},
|
|
@@ -54,22 +48,6 @@ const _chalk = require("chalk");
|
|
|
54
48
|
const _path = require("path");
|
|
55
49
|
const _superstruct = require("superstruct");
|
|
56
50
|
const _strings = require("./strings");
|
|
57
|
-
function literal(value) {
|
|
58
|
-
return (0, _superstruct.define)(JSON.stringify(value), (0, _superstruct.literal)(value).validator);
|
|
59
|
-
}
|
|
60
|
-
function union([head, ...tail]) {
|
|
61
|
-
const struct = (0, _superstruct.union)([
|
|
62
|
-
head,
|
|
63
|
-
...tail
|
|
64
|
-
]);
|
|
65
|
-
return new _superstruct.Struct({
|
|
66
|
-
...struct,
|
|
67
|
-
schema: [
|
|
68
|
-
head,
|
|
69
|
-
...tail
|
|
70
|
-
]
|
|
71
|
-
});
|
|
72
|
-
}
|
|
73
51
|
function file() {
|
|
74
52
|
return (0, _superstruct.coerce)((0, _superstruct.string)(), (0, _superstruct.string)(), (value)=>{
|
|
75
53
|
return (0, _path.resolve)(process.cwd(), value);
|
package/dist/cjs/structs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/structs.ts"],"sourcesContent":["import { isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure, Infer } from 'superstruct';\nimport {\n Struct,\n StructError,\n define,\n literal as superstructLiteral,\n union as superstructUnion,\n create,\n string,\n coerce,\n} from 'superstruct';\nimport type { AnyStruct, InferStructTuple } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * Infer a struct type, only if it matches the specified type. This is useful\n * for defining types and structs that are related to each other in separate\n * files.\n *\n * @example\n * ```typescript\n * // In file A\n * export type GetFileArgs = {\n * path: string;\n * encoding?: EnumToUnion<AuxiliaryFileEncoding>;\n * };\n *\n * // In file B\n * export const GetFileArgsStruct = object(...);\n *\n * // If the type and struct are in the same file, this will return the type.\n * // Otherwise, it will return `never`.\n * export type GetFileArgs =\n * InferMatching<typeof GetFileArgsStruct, GetFileArgs>;\n * ```\n */\nexport type InferMatching<\n StructType extends Struct<any, any>,\n Type,\n> = StructType['TYPE'] extends Type ? Type : never;\n\n/**\n * A wrapper of `superstruct`'s `literal` struct that also defines the name of\n * the struct as the literal value.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n * For example, instead of returning an error like:\n *\n * ```\n * Expected the value to satisfy a union of `literal | literal`, but received: \\\"baz\\\"\n * ```\n *\n * This struct will return an error like:\n *\n * ```\n * Expected the value to satisfy a union of `\"foo\" | \"bar\"`, but received: \\\"baz\\\"\n * ```\n *\n * @param value - The literal value.\n * @returns The `superstruct` struct, which validates that the value is equal\n * to the literal value.\n */\nexport function literal<Type extends string | number | boolean>(value: Type) {\n return define<Type>(\n JSON.stringify(value),\n superstructLiteral(value).validator,\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `union` struct that also defines the schema as\n * the union of the schemas of the structs.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param structs - The structs to union.\n * @param structs.\"0\" - The first struct.\n * @param structs.\"1\" - The remaining structs.\n * @returns The `superstruct` struct, which validates that the value satisfies\n * one of the structs.\n */\nexport function union<Head extends AnyStruct, Tail extends AnyStruct[]>([\n head,\n ...tail\n]: [head: Head, ...tail: Tail]): Struct<\n Infer<Head> | InferStructTuple<Tail>[number],\n [head: Head, ...tail: Tail]\n> {\n const struct = superstructUnion([head, ...tail]);\n\n return new Struct({\n ...struct,\n schema: [head, ...tail],\n });\n}\n\n/**\n * A wrapper of `superstruct`'s `string` struct that coerces a value to a string\n * and resolves it relative to the current working directory. This is useful\n * for specifying file paths in a configuration file, as it allows the user to\n * use both relative and absolute paths.\n *\n * @returns The `superstruct` struct, which validates that the value is a\n * string, and resolves it relative to the current working directory.\n * @example\n * ```ts\n * const config = struct({\n * file: file(),\n * // ...\n * });\n *\n * const value = create({ file: 'path/to/file' }, config);\n * console.log(value.file); // /process/cwd/path/to/file\n * ```\n */\nexport function file() {\n return coerce(string(), string(), (value) => {\n return resolve(process.cwd(), value);\n });\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(struct, [\n ...failures(),\n ])}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(struct, prefix, suffix, error, () =>\n arrayToGenerator(error.failures()),\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => green(type));\n }\n\n return null;\n}\n\n/**\n * Get a error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${bold(failure.path.join('.'))} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n) {\n const received = red(JSON.stringify(failure.value));\n const prefix = getStructErrorPrefix(failure);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(/the literal `(.+)`,/u, `the value to be \\`${green('$1')}\\`,`)\n .replace(/, but received: (.+)/u, `, but received: ${red('$1')}`);\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${bold(\n failure.path.join('.'),\n )}, received: ${received}.`;\n }\n\n return `${prefix}Expected a value of type ${green(\n failure.type,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n"],"names":["literal","union","file","named","SnapsStructError","arrayToGenerator","getError","createFromStruct","getStructFromPath","getUnionStructNames","getStructErrorPrefix","getStructFailureMessage","getStructErrorMessage","value","define","JSON","stringify","superstructLiteral","validator","head","tail","struct","superstructUnion","Struct","schema","coerce","string","resolve","process","cwd","name","type","StructError","constructor","prefix","suffix","failure","failures","message","array","item","error","create","path","reduce","result","key","isObject","Array","isArray","map","green","length","bold","join","received","red","childStruct","unionNames","replace","formattedFailures","indent"],"mappings":";;;;;;;;;;;IAkEgBA,OAAO;eAAPA;;IAmBAC,KAAK;eAALA;;IAkCAC,IAAI;eAAJA;;IAeAC,KAAK;eAALA;;IAUHC,gBAAgB;eAAhBA;;IAgCIC,gBAAgB;eAAhBA;;IAmBDC,QAAQ;eAARA;;IAuBAC,gBAAgB;eAAhBA;;IAwBAC,iBAAiB;eAAjBA;;IAoBAC,mBAAmB;eAAnBA;;IAiBAC,oBAAoB;eAApBA;;IAiBAC,uBAAuB;eAAvBA;;IAiDAC,qBAAqB;eAArBA;;;uBAzVS;uBACQ;sBACT;6BAWjB;yBAGgB;AAkDhB,SAASZ,QAAgDa,KAAW;IACzE,OAAOC,IAAAA,mBAAM,EACXC,KAAKC,SAAS,CAACH,QACfI,IAAAA,oBAAkB,EAACJ,OAAOK,SAAS;AAEvC;AAcO,SAASjB,MAAwD,CACtEkB,MACA,GAAGC,KACyB;IAI5B,MAAMC,SAASC,IAAAA,kBAAgB,EAAC;QAACH;WAASC;KAAK;IAE/C,OAAO,IAAIG,mBAAM,CAAC;QAChB,GAAGF,MAAM;QACTG,QAAQ;YAACL;eAASC;SAAK;IACzB;AACF;AAqBO,SAASlB;IACd,OAAOuB,IAAAA,mBAAM,EAACC,IAAAA,mBAAM,KAAIA,IAAAA,mBAAM,KAAI,CAACb;QACjC,OAAOc,IAAAA,aAAO,EAACC,QAAQC,GAAG,IAAIhB;IAChC;AACF;AAWO,SAASV,MACd2B,IAAY,EACZT,MAA4B;IAE5B,OAAO,IAAIE,mBAAM,CAAC;QAChB,GAAGF,MAAM;QACTU,MAAMD;IAC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AS;QAC5B,OAAO,CAAC,aAAa,EAAEsB,IAAAA,WAAI,EACzBjB,QAAQO,IAAI,CAACW,IAAI,CAAC,MAClB,YAAY,EAAEC,SAAS,CAAC,CAAC;IAC7B;IAEA,OAAO,CAAC,EAAErB,OAAO,yBAAyB,EAAEiB,IAAAA,YAAK,EAC/Cf,QAAQL,IAAI,EACZ,gBAAgB,EAAEwB,SAAS,CAAC,CAAC;AACjC;AAUO,SAAS3C,sBACdS,MAA4B,EAC5BgB,QAAmB;IAEnB,MAAMuB,oBAAoBvB,SAASa,GAAG,CAAC,CAACd,UACtCyB,IAAAA,eAAM,EAAC,CAAC,EAAE,EAAElD,wBAAwBU,QAAQe,SAAS,CAAC;IAGxD,OAAOwB,kBAAkBN,IAAI,CAAC;AAChC"}
|
|
1
|
+
{"version":3,"sources":["../../src/structs.ts"],"sourcesContent":["import { isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure } from 'superstruct';\nimport { Struct, StructError, create, string, coerce } from 'superstruct';\nimport type { AnyStruct } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * Infer a struct type, only if it matches the specified type. This is useful\n * for defining types and structs that are related to each other in separate\n * files.\n *\n * @example\n * ```typescript\n * // In file A\n * export type GetFileArgs = {\n * path: string;\n * encoding?: EnumToUnion<AuxiliaryFileEncoding>;\n * };\n *\n * // In file B\n * export const GetFileArgsStruct = object(...);\n *\n * // If the type and struct are in the same file, this will return the type.\n * // Otherwise, it will return `never`.\n * export type GetFileArgs =\n * InferMatching<typeof GetFileArgsStruct, GetFileArgs>;\n * ```\n */\nexport type InferMatching<\n StructType extends Struct<any, any>,\n Type,\n> = StructType['TYPE'] extends Type ? Type : never;\n\n/**\n * A wrapper of `superstruct`'s `string` struct that coerces a value to a string\n * and resolves it relative to the current working directory. This is useful\n * for specifying file paths in a configuration file, as it allows the user to\n * use both relative and absolute paths.\n *\n * @returns The `superstruct` struct, which validates that the value is a\n * string, and resolves it relative to the current working directory.\n * @example\n * ```ts\n * const config = struct({\n * file: file(),\n * // ...\n * });\n *\n * const value = create({ file: 'path/to/file' }, config);\n * console.log(value.file); // /process/cwd/path/to/file\n * ```\n */\nexport function file() {\n return coerce(string(), string(), (value) => {\n return resolve(process.cwd(), value);\n });\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(struct, [\n ...failures(),\n ])}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(struct, prefix, suffix, error, () =>\n arrayToGenerator(error.failures()),\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => green(type));\n }\n\n return null;\n}\n\n/**\n * Get a error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${bold(failure.path.join('.'))} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n) {\n const received = red(JSON.stringify(failure.value));\n const prefix = getStructErrorPrefix(failure);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(/the literal `(.+)`,/u, `the value to be \\`${green('$1')}\\`,`)\n .replace(/, but received: (.+)/u, `, but received: ${red('$1')}`);\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${bold(\n failure.path.join('.'),\n )}, received: ${received}.`;\n }\n\n return `${prefix}Expected a value of type ${green(\n failure.type,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n"],"names":["file","named","SnapsStructError","arrayToGenerator","getError","createFromStruct","getStructFromPath","getUnionStructNames","getStructErrorPrefix","getStructFailureMessage","getStructErrorMessage","coerce","string","value","resolve","process","cwd","name","struct","Struct","type","StructError","constructor","prefix","suffix","failure","failures","message","array","item","error","create","path","reduce","result","key","isObject","schema","Array","isArray","map","green","length","bold","join","received","red","JSON","stringify","childStruct","unionNames","replace","formattedFailures","indent"],"mappings":";;;;;;;;;;;IAuDgBA,IAAI;eAAJA;;IAeAC,KAAK;eAALA;;IAUHC,gBAAgB;eAAhBA;;IAgCIC,gBAAgB;eAAhBA;;IAmBDC,QAAQ;eAARA;;IAuBAC,gBAAg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CAAC,EAAEtB,OAAO,EAAEE,QAAQE,OAAO,CAAC,CAAC,CAAC;IACvC;IAEA,IAAIF,QAAQL,IAAI,KAAK,WAAW;QAC9B,yEAAyE;QACzE,0EAA0E;QAC1E,MAAMO,UAAUF,QAAQE,OAAO,CAC5BwB,OAAO,CAAC,wBAAwB,CAAC,kBAAkB,EAAEV,IAAAA,YAAK,EAAC,MAAM,GAAG,CAAC,EACrEU,OAAO,CAAC,yBAAyB,CAAC,gBAAgB,EAAEL,IAAAA,UAAG,EAAC,MAAM,CAAC;QAElE,OAAO,CAAC,EAAEvB,OAAO,EAAEI,QAAQ,CAAC,CAAC;IAC/B;IAEA,IAAIF,QAAQL,IAAI,KAAK,SAAS;QAC5B,OAAO,CAAC,aAAa,EAAEuB,IAAAA,WAAI,EACzBlB,QAAQO,IAAI,CAACY,IAAI,CAAC,MAClB,YAAY,EAAEC,SAAS,CAAC,CAAC;IAC7B;IAEA,OAAO,CAAC,EAAEtB,OAAO,yBAAyB,EAAEkB,IAAAA,YAAK,EAC/ChB,QAAQL,IAAI,EACZ,gBAAgB,EAAEyB,SAAS,CAAC,CAAC;AACjC;AAUO,SAASnC,sBACdQ,MAA4B,EAC5BQ,QAAmB;IAEnB,MAAM0B,oBAAoB1B,SAASc,GAAG,CAAC,CAACf,UACtC4B,IAAAA,eAAM,EAAC,CAAC,EAAE,EAAE5C,wBAAwBS,QAAQO,SAAS,CAAC;IAGxD,OAAO2B,kBAAkBR,IAAI,CAAC;AAChC"}
|
package/dist/cjs/ui.js
CHANGED
|
@@ -18,24 +18,26 @@ _export(exports, {
|
|
|
18
18
|
});
|
|
19
19
|
const _snapssdk = require("@metamask/snaps-sdk");
|
|
20
20
|
const _utils = require("@metamask/utils");
|
|
21
|
-
const
|
|
21
|
+
const MARKDOWN_LINK_REGEX = RegExp("\\[(?<name>[^\\]]*)\\]\\((?<url>[^)]+)\\)", "giu");
|
|
22
22
|
const ALLOWED_PROTOCOLS = [
|
|
23
23
|
'https:',
|
|
24
24
|
'mailto:'
|
|
25
25
|
];
|
|
26
26
|
function validateTextLinks(text, isOnPhishingList) {
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
})
|
|
27
|
+
const matches = String.prototype.matchAll.call(text, MARKDOWN_LINK_REGEX);
|
|
28
|
+
for (const { groups } of matches){
|
|
29
|
+
const link = groups?.url;
|
|
30
|
+
/* This case should never happen with the regex but the TS type allows for undefined */ /* istanbul ignore next */ if (!link) {
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
const url = new URL(link);
|
|
35
|
+
(0, _utils.assert)(ALLOWED_PROTOCOLS.includes(url.protocol), `Protocol must be one of: ${ALLOWED_PROTOCOLS.join(', ')}.`);
|
|
36
|
+
const hostname = url.protocol === 'mailto:' ? url.pathname.split('@')[1] : url.hostname;
|
|
37
|
+
(0, _utils.assert)(!isOnPhishingList(hostname), 'The specified URL is not allowed.');
|
|
38
|
+
} catch (error) {
|
|
39
|
+
throw new Error(`Invalid URL: ${error instanceof _utils.AssertionError ? error.message : 'Unable to parse URL.'}`);
|
|
40
|
+
}
|
|
39
41
|
}
|
|
40
42
|
}
|
|
41
43
|
function validateComponentLinks(component, isOnPhishingList) {
|
|
@@ -43,7 +45,7 @@ function validateComponentLinks(component, isOnPhishingList) {
|
|
|
43
45
|
if (type === _snapssdk.NodeType.Panel) {
|
|
44
46
|
component.children.forEach((node)=>validateComponentLinks(node, isOnPhishingList));
|
|
45
47
|
}
|
|
46
|
-
if (
|
|
48
|
+
if (type === _snapssdk.NodeType.Text) {
|
|
47
49
|
validateTextLinks(component.value, isOnPhishingList);
|
|
48
50
|
}
|
|
49
51
|
}
|
package/dist/cjs/ui.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ui.ts"],"sourcesContent":["import type { Component } from '@metamask/snaps-sdk';\nimport { NodeType } from '@metamask/snaps-sdk';\nimport { assert, AssertionError
|
|
1
|
+
{"version":3,"sources":["../../src/ui.ts"],"sourcesContent":["import type { Component } from '@metamask/snaps-sdk';\nimport { NodeType } from '@metamask/snaps-sdk';\nimport { assert, AssertionError } from '@metamask/utils';\n\nconst MARKDOWN_LINK_REGEX = /\\[(?<name>[^\\]]*)\\]\\((?<url>[^)]+)\\)/giu;\n\nconst ALLOWED_PROTOCOLS = ['https:', 'mailto:'];\n\n/**\n * Searches for markdown links in a string and checks them against the phishing list.\n *\n * @param text - The text to verify.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n * @throws If the text contains a link that is not allowed.\n */\nexport function validateTextLinks(\n text: string,\n isOnPhishingList: (url: string) => boolean,\n) {\n const matches = String.prototype.matchAll.call(text, MARKDOWN_LINK_REGEX);\n\n for (const { groups } of matches) {\n const link = groups?.url;\n\n /* This case should never happen with the regex but the TS type allows for undefined */\n /* istanbul ignore next */\n if (!link) {\n continue;\n }\n\n try {\n const url = new URL(link);\n assert(\n ALLOWED_PROTOCOLS.includes(url.protocol),\n `Protocol must be one of: ${ALLOWED_PROTOCOLS.join(', ')}.`,\n );\n\n const hostname =\n url.protocol === 'mailto:' ? url.pathname.split('@')[1] : url.hostname;\n\n assert(!isOnPhishingList(hostname), 'The specified URL is not allowed.');\n } catch (error) {\n throw new Error(\n `Invalid URL: ${\n error instanceof AssertionError\n ? error.message\n : 'Unable to parse URL.'\n }`,\n );\n }\n }\n}\n\n/**\n * Search for links in UI components and check that the URL they are trying to\n * pass in is not in the phishing list.\n *\n * @param component - The custom UI component.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n * @throws If the component contains a link that is not allowed.\n */\nexport function validateComponentLinks(\n component: Component,\n isOnPhishingList: (url: string) => boolean,\n) {\n const { type } = component;\n if (type === NodeType.Panel) {\n component.children.forEach((node) =>\n validateComponentLinks(node, isOnPhishingList),\n );\n }\n\n if (type === NodeType.Text) {\n validateTextLinks(component.value, isOnPhishingList);\n }\n}\n"],"names":["validateTextLinks","validateComponentLinks","MARKDOWN_LINK_REGEX","ALLOWED_PROTOCOLS","text","isOnPhishingList","matches","String","prototype","matchAll","call","groups","link","url","URL","assert","includes","protocol","join","hostname","pathname","split","error","Error","AssertionError","message","component","type","NodeType","Panel","children","forEach","node","Text","value"],"mappings":";;;;;;;;;;;IAgBgBA,iBAAiB;eAAjBA;;IA+CAC,sBAAsB;eAAtBA;;;0BA9DS;uBACc;AAEvC,MAAMC,sBAAsB;AAE5B,MAAMC,oBAAoB;IAAC;IAAU;CAAU;AAUxC,SAASH,kBACdI,IAAY,EACZC,gBAA0C;IAE1C,MAAMC,UAAUC,OAAOC,SAAS,CAACC,QAAQ,CAACC,IAAI,CAACN,MAAMF;IAErD,KAAK,MAAM,EAAES,MAAM,EAAE,IAAIL,QAAS;QAChC,MAAMM,OAAOD,QAAQE;QAErB,qFAAqF,GACrF,wBAAwB,GACxB,IAAI,CAACD,MAAM;YACT;QACF;QAEA,IAAI;YACF,MAAMC,MAAM,IAAIC,IAAIF;YACpBG,IAAAA,aAAM,EACJZ,kBAAkBa,QAAQ,CAACH,IAAII,QAAQ,GACvC,CAAC,yBAAyB,EAAEd,kBAAkBe,IAAI,CAAC,MAAM,CAAC,CAAC;YAG7D,MAAMC,WACJN,IAAII,QAAQ,KAAK,YAAYJ,IAAIO,QAAQ,CAACC,KAAK,CAAC,IAAI,CAAC,EAAE,GAAGR,IAAIM,QAAQ;YAExEJ,IAAAA,aAAM,EAAC,CAACV,iBAAiBc,WAAW;QACtC,EAAE,OAAOG,OAAO;YACd,MAAM,IAAIC,MACR,CAAC,aAAa,EACZD,iBAAiBE,qBAAc,GAC3BF,MAAMG,OAAO,GACb,uBACL,CAAC;QAEN;IACF;AACF;AAWO,SAASxB,uBACdyB,SAAoB,EACpBrB,gBAA0C;IAE1C,MAAM,EAAEsB,IAAI,EAAE,GAAGD;IACjB,IAAIC,SAASC,kBAAQ,CAACC,KAAK,EAAE;QAC3BH,UAAUI,QAAQ,CAACC,OAAO,CAAC,CAACC,OAC1B/B,uBAAuB+B,MAAM3B;IAEjC;IAEA,IAAIsB,SAASC,kBAAQ,CAACK,IAAI,EAAE;QAC1BjC,kBAAkB0B,UAAUQ,KAAK,EAAE7B;IACrC;AACF"}
|
package/dist/esm/cronjob.js
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { JsonRpcIdStruct, JsonRpcParamsStruct, JsonRpcVersionStruct } from '@metamask/utils';
|
|
2
2
|
import { parseExpression } from 'cron-parser';
|
|
3
|
-
import {
|
|
4
|
-
export const CronjobRpcRequestStruct =
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
]));
|
|
3
|
+
import { array, coerce, create, object, optional, refine, string } from 'superstruct';
|
|
4
|
+
export const CronjobRpcRequestStruct = object({
|
|
5
|
+
jsonrpc: optional(JsonRpcVersionStruct),
|
|
6
|
+
id: optional(JsonRpcIdStruct),
|
|
7
|
+
method: string(),
|
|
8
|
+
params: optional(JsonRpcParamsStruct)
|
|
9
|
+
});
|
|
11
10
|
export const CronExpressionStruct = refine(coerce(string(), object({
|
|
12
11
|
minute: optional(string()),
|
|
13
12
|
hour: optional(string()),
|
package/dist/esm/cronjob.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cronjob.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../src/cronjob.ts"],"sourcesContent":["import {\n JsonRpcIdStruct,\n JsonRpcParamsStruct,\n JsonRpcVersionStruct,\n} from '@metamask/utils';\nimport { parseExpression } from 'cron-parser';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n coerce,\n create,\n object,\n optional,\n refine,\n string,\n} from 'superstruct';\n\nexport const CronjobRpcRequestStruct = object({\n jsonrpc: optional(JsonRpcVersionStruct),\n id: optional(JsonRpcIdStruct),\n method: string(),\n params: optional(JsonRpcParamsStruct),\n});\n\nexport type CronjobRpcRequest = Infer<typeof CronjobRpcRequestStruct>;\n\nexport const CronExpressionStruct = refine(\n coerce(\n string(),\n object({\n minute: optional(string()),\n hour: optional(string()),\n dayOfMonth: optional(string()),\n month: optional(string()),\n dayOfWeek: optional(string()),\n }),\n (value) =>\n `${value.minute ?? '*'} ${value.hour ?? '*'} ${value.dayOfMonth ?? '*'} ${\n value.month ?? '*'\n } ${value.dayOfWeek ?? '*'}`,\n ),\n 'CronExpression',\n (value) => {\n try {\n parseExpression(value);\n return true;\n } catch {\n return false;\n }\n },\n);\n\nexport type CronExpression = Infer<typeof CronExpressionStruct>;\n\n/**\n * Parses a cron expression.\n *\n * @param expression - Expression to parse.\n * @returns A CronExpression class instance.\n */\nexport function parseCronExpression(expression: string | object) {\n const ensureStringExpression = create(expression, CronExpressionStruct);\n return parseExpression(ensureStringExpression);\n}\n\nexport const CronjobSpecificationStruct = object({\n expression: CronExpressionStruct,\n request: CronjobRpcRequestStruct,\n});\nexport type CronjobSpecification = Infer<typeof CronjobSpecificationStruct>;\n\n/**\n * Check if the given value is a {@link CronjobSpecification} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link CronjobSpecification} object.\n */\nexport function isCronjobSpecification(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationStruct);\n return true;\n } catch {\n return false;\n }\n}\n\nexport const CronjobSpecificationArrayStruct = array(\n CronjobSpecificationStruct,\n);\n\n/**\n * Check if the given value is an array of {@link CronjobSpecification} objects.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid array of {@link CronjobSpecification} objects.\n */\nexport function isCronjobSpecificationArray(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationArrayStruct);\n return true;\n } catch {\n return false;\n }\n}\n"],"names":["JsonRpcIdStruct","JsonRpcParamsStruct","JsonRpcVersionStruct","parseExpression","array","coerce","create","object","optional","refine","string","CronjobRpcRequestStruct","jsonrpc","id","method","params","CronExpressionStruct","minute","hour","dayOfMonth","month","dayOfWeek","value","parseCronExpression","expression","ensureStringExpression","CronjobSpecificationStruct","request","isCronjobSpecification","CronjobSpecificationArrayStruct","isCronjobSpecificationArray"],"mappings":"AAAA,SACEA,eAAe,EACfC,mBAAmB,EACnBC,oBAAoB,QACf,kBAAkB;AACzB,SAASC,eAAe,QAAQ,cAAc;AAE9C,SACEC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,MAAM,EACNC,QAAQ,EACRC,MAAM,EACNC,MAAM,QACD,cAAc;AAErB,OAAO,MAAMC,0BAA0BJ,OAAO;IAC5CK,SAASJ,SAASN;IAClBW,IAAIL,SAASR;IACbc,QAAQJ;IACRK,QAAQP,SAASP;AACnB,GAAG;AAIH,OAAO,MAAMe,uBAAuBP,OAClCJ,OACEK,UACAH,OAAO;IACLU,QAAQT,SAASE;IACjBQ,MAAMV,SAASE;IACfS,YAAYX,SAASE;IACrBU,OAAOZ,SAASE;IAChBW,WAAWb,SAASE;AACtB,IACA,CAACY,QACC,CAAC,EAAEA,MAAML,MAAM,IAAI,IAAI,CAAC,EAAEK,MAAMJ,IAAI,IAAI,IAAI,CAAC,EAAEI,MAAMH,UAAU,IAAI,IAAI,CAAC,EACtEG,MAAMF,KAAK,IAAI,IAChB,CAAC,EAAEE,MAAMD,SAAS,IAAI,IAAI,CAAC,GAEhC,kBACA,CAACC;IACC,IAAI;QACFnB,gBAAgBmB;QAChB,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF,GACA;AAIF;;;;;CAKC,GACD,OAAO,SAASC,oBAAoBC,UAA2B;IAC7D,MAAMC,yBAAyBnB,OAAOkB,YAAYR;IAClD,OAAOb,gBAAgBsB;AACzB;AAEA,OAAO,MAAMC,6BAA6BnB,OAAO;IAC/CiB,YAAYR;IACZW,SAAShB;AACX,GAAG;AAGH;;;;;CAKC,GACD,OAAO,SAASiB,uBAAuBN,KAAc;IACnD,IAAI;QACFhB,OAAOgB,OAAOI;QACd,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA,OAAO,MAAMG,kCAAkCzB,MAC7CsB,4BACA;AAEF;;;;;CAKC,GACD,OAAO,SAASI,4BAA4BR,KAAc;IACxD,IAAI;QACFhB,OAAOgB,OAAOO;QACd,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './
|
|
1
|
+
{"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './errors';\nexport * from './handlers';\nexport * from './handler-types';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './localization';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './path';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './ui';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"],"names":[],"mappings":"AAAA,cAAc,UAAU;AACxB,cAAc,oBAAoB;AAClC,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,eAAe;AAC7B,cAAc,uBAAuB;AACrC,cAAc,YAAY;AAC1B,cAAc,WAAW;AACzB,cAAc,aAAa;AAC3B,cAAc,kBAAkB;AAChC,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,iBAAiB;AAC/B,cAAc,YAAY;AAC1B,cAAc,2BAA2B;AACzC,cAAc,cAAc;AAC5B,cAAc,SAAS;AACvB,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,UAAU;AACxB,cAAc,OAAO;AACrB,cAAc,eAAe;AAC7B,cAAc,aAAa;AAC3B,cAAc,+BAA+B"}
|
package/dist/esm/index.js
CHANGED
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './eval';\nexport * from './errors';\nexport * from './fs';\nexport * from './handlers';\nexport * from './handler-types';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './localization';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './ui';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file';\n"],"names":[],"mappings":"AAAA,cAAc,UAAU;AACxB,cAAc,oBAAoB;AAClC,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,eAAe;AAC7B,cAAc,uBAAuB;AACrC,cAAc,YAAY;AAC1B,cAAc,SAAS;AACvB,cAAc,WAAW;AACzB,cAAc,OAAO;AACrB,cAAc,aAAa;AAC3B,cAAc,kBAAkB;AAChC,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,iBAAiB;AAC/B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,SAAS;AACvB,cAAc,cAAc;AAC5B,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB,cAAc,iBAAiB;AAC/B,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,UAAU;AACxB,cAAc,OAAO;AACrB,cAAc,eAAe;AAC7B,cAAc,aAAa;AAC3B,cAAc,iBAAiB"}
|
|
@@ -45,7 +45,8 @@ const MANIFEST_SORT_ORDER = {
|
|
|
45
45
|
packageJson: packageFile,
|
|
46
46
|
sourceCode: await getSnapSourceCode(basePath, unvalidatedManifest, sourceCode),
|
|
47
47
|
svgIcon: await getSnapIcon(basePath, unvalidatedManifest),
|
|
48
|
-
|
|
48
|
+
// Intentionally pass null as the encoding here since the files may be binary
|
|
49
|
+
auxiliaryFiles: await getSnapFiles(basePath, auxiliaryFilePaths, null) ?? [],
|
|
49
50
|
localizationFiles: await getSnapFiles(basePath, localizationFilePaths) ?? []
|
|
50
51
|
};
|
|
51
52
|
let manifest;
|
|
@@ -226,13 +227,14 @@ const MANIFEST_SORT_ORDER = {
|
|
|
226
227
|
*
|
|
227
228
|
* @param basePath - The path to the folder with the manifest files.
|
|
228
229
|
* @param paths - The paths to the files.
|
|
230
|
+
* @param encoding - An optional encoding to pass down to readVirtualFile.
|
|
229
231
|
* @returns A list of auxiliary files and their contents, if any.
|
|
230
|
-
*/ export async function getSnapFiles(basePath, paths) {
|
|
232
|
+
*/ export async function getSnapFiles(basePath, paths, encoding = 'utf8') {
|
|
231
233
|
if (!paths) {
|
|
232
234
|
return undefined;
|
|
233
235
|
}
|
|
234
236
|
try {
|
|
235
|
-
return await Promise.all(paths.map(async (filePath)=>readVirtualFile(pathUtils.join(basePath, filePath),
|
|
237
|
+
return await Promise.all(paths.map(async (filePath)=>readVirtualFile(pathUtils.join(basePath, filePath), encoding)));
|
|
236
238
|
} catch (error) {
|
|
237
239
|
throw new Error(`Failed to read snap files: ${getErrorMessage(error)}`);
|
|
238
240
|
}
|