@metamask/snaps-utils 3.2.0 → 4.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 +35 -1
- package/dist/cjs/auxiliary-files.js +6 -19
- package/dist/cjs/auxiliary-files.js.map +1 -1
- package/dist/cjs/checksum.js +22 -5
- package/dist/cjs/checksum.js.map +1 -1
- package/dist/cjs/cronjob.js.map +1 -1
- package/dist/cjs/enum.js.map +1 -1
- package/dist/cjs/errors.js +6 -154
- package/dist/cjs/errors.js.map +1 -1
- package/dist/cjs/handler-types.js +1 -0
- package/dist/cjs/handler-types.js.map +1 -1
- package/dist/cjs/handlers.js +17 -11
- package/dist/cjs/handlers.js.map +1 -1
- package/dist/cjs/index.browser.js +2 -0
- package/dist/cjs/index.browser.js.map +1 -1
- package/dist/cjs/index.js +2 -7
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/localization.js +113 -0
- package/dist/cjs/localization.js.map +1 -0
- package/dist/cjs/manifest/manifest.js +33 -19
- package/dist/cjs/manifest/manifest.js.map +1 -1
- package/dist/cjs/manifest/validation.js +3 -2
- package/dist/cjs/manifest/validation.js.map +1 -1
- package/dist/cjs/namespace.js +5 -1
- package/dist/cjs/namespace.js.map +1 -1
- package/dist/cjs/npm.js +18 -5
- package/dist/cjs/npm.js.map +1 -1
- package/dist/cjs/snaps.js +7 -6
- package/dist/cjs/snaps.js.map +1 -1
- package/dist/cjs/structs.js.map +1 -1
- package/dist/cjs/types.js.map +1 -1
- package/dist/cjs/ui.js +51 -0
- package/dist/cjs/ui.js.map +1 -0
- package/dist/cjs/validation.js +4 -2
- package/dist/cjs/validation.js.map +1 -1
- package/dist/esm/auxiliary-files.js +1 -6
- package/dist/esm/auxiliary-files.js.map +1 -1
- package/dist/esm/checksum.js +25 -6
- package/dist/esm/checksum.js.map +1 -1
- package/dist/esm/cronjob.js +1 -1
- package/dist/esm/cronjob.js.map +1 -1
- package/dist/esm/enum.js.map +1 -1
- package/dist/esm/errors.js +2 -157
- package/dist/esm/errors.js.map +1 -1
- package/dist/esm/handler-types.js +1 -0
- package/dist/esm/handler-types.js.map +1 -1
- package/dist/esm/handlers.js +13 -7
- package/dist/esm/handlers.js.map +1 -1
- package/dist/esm/index.browser.js +2 -0
- package/dist/esm/index.browser.js.map +1 -1
- package/dist/esm/index.js +2 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/localization.js +115 -0
- package/dist/esm/localization.js.map +1 -0
- package/dist/esm/manifest/manifest.js +37 -19
- package/dist/esm/manifest/manifest.js.map +1 -1
- package/dist/esm/manifest/validation.js +4 -3
- package/dist/esm/manifest/validation.js.map +1 -1
- package/dist/esm/namespace.js +3 -2
- package/dist/esm/namespace.js.map +1 -1
- package/dist/esm/npm.js +18 -5
- package/dist/esm/npm.js.map +1 -1
- package/dist/esm/snaps.js +7 -6
- package/dist/esm/snaps.js.map +1 -1
- package/dist/esm/structs.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/esm/ui.js +48 -0
- package/dist/esm/ui.js.map +1 -0
- package/dist/esm/validation.js +4 -2
- package/dist/esm/validation.js.map +1 -1
- package/dist/types/auxiliary-files.d.ts +1 -5
- package/dist/types/checksum.d.ts +9 -2
- package/dist/types/enum.d.ts +1 -21
- package/dist/types/errors.d.ts +1 -109
- package/dist/types/handler-types.d.ts +2 -1
- package/dist/types/handlers.d.ts +73 -152
- package/dist/types/index.browser.d.ts +2 -0
- package/dist/types/index.d.ts +2 -1
- package/dist/types/localization.d.ts +143 -0
- package/dist/types/manifest/manifest.d.ts +16 -7
- package/dist/types/manifest/validation.d.ts +83 -78
- package/dist/types/namespace.d.ts +11 -10
- package/dist/types/npm.d.ts +1 -1
- package/dist/types/snaps.d.ts +13 -43
- package/dist/types/structs.d.ts +23 -0
- package/dist/types/types.d.ts +4 -2
- package/dist/types/ui.d.ts +20 -0
- package/dist/types/validation.d.ts +1 -1
- package/package.json +3 -3
|
@@ -1,9 +1,9 @@
|
|
|
1
|
+
import { getErrorMessage } from '@metamask/snaps-sdk';
|
|
1
2
|
import { assertExhaustive, assert, isPlainObject } from '@metamask/utils';
|
|
2
3
|
import deepEqual from 'fast-deep-equal';
|
|
3
4
|
import { promises as fs } from 'fs';
|
|
4
5
|
import pathUtils from 'path';
|
|
5
6
|
import { deepClone } from '../deep-clone';
|
|
6
|
-
import { getErrorMessage } from '../errors';
|
|
7
7
|
import { readJsonFile } from '../fs';
|
|
8
8
|
import { validateNpmSnap } from '../npm';
|
|
9
9
|
import { getSnapChecksum, ProgrammaticallyFixableSnapError, validateSnapShasum } from '../snaps';
|
|
@@ -38,16 +38,19 @@ const MANIFEST_SORT_ORDER = {
|
|
|
38
38
|
const manifestFile = await readJsonFile(manifestPath);
|
|
39
39
|
const unvalidatedManifest = manifestFile.result;
|
|
40
40
|
const packageFile = await readJsonFile(pathUtils.join(basePath, NpmSnapFileNames.PackageJson));
|
|
41
|
+
const auxiliaryFilePaths = getSnapFilePaths(unvalidatedManifest, (manifest)=>manifest?.source?.files);
|
|
42
|
+
const localizationFilePaths = getSnapFilePaths(unvalidatedManifest, (manifest)=>manifest?.source?.locales);
|
|
41
43
|
const snapFiles = {
|
|
42
44
|
manifest: manifestFile,
|
|
43
45
|
packageJson: packageFile,
|
|
44
46
|
sourceCode: await getSnapSourceCode(basePath, unvalidatedManifest, sourceCode),
|
|
45
47
|
svgIcon: await getSnapIcon(basePath, unvalidatedManifest),
|
|
46
|
-
auxiliaryFiles: await
|
|
48
|
+
auxiliaryFiles: await getSnapFiles(basePath, auxiliaryFilePaths) ?? [],
|
|
49
|
+
localizationFiles: await getSnapFiles(basePath, localizationFilePaths) ?? []
|
|
47
50
|
};
|
|
48
51
|
let manifest;
|
|
49
52
|
try {
|
|
50
|
-
({ manifest } = validateNpmSnap(snapFiles));
|
|
53
|
+
({ manifest } = await validateNpmSnap(snapFiles));
|
|
51
54
|
} catch (error) {
|
|
52
55
|
if (error instanceof ProgrammaticallyFixableSnapError) {
|
|
53
56
|
errors.push(error.message);
|
|
@@ -61,12 +64,12 @@ const MANIFEST_SORT_ORDER = {
|
|
|
61
64
|
// attempt to fix the manifest the same amount of times as there are
|
|
62
65
|
// reasons in the enum.
|
|
63
66
|
for(let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++){
|
|
64
|
-
manifest = fixManifest(manifest ? {
|
|
67
|
+
manifest = await fixManifest(manifest ? {
|
|
65
68
|
...partiallyValidatedFiles,
|
|
66
69
|
manifest
|
|
67
70
|
} : partiallyValidatedFiles, currentError);
|
|
68
71
|
try {
|
|
69
|
-
validateNpmSnapManifest({
|
|
72
|
+
await validateNpmSnapManifest({
|
|
70
73
|
...partiallyValidatedFiles,
|
|
71
74
|
manifest
|
|
72
75
|
});
|
|
@@ -125,7 +128,7 @@ const MANIFEST_SORT_ORDER = {
|
|
|
125
128
|
* @param snapFiles - The contents of all Snap files.
|
|
126
129
|
* @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.
|
|
127
130
|
* @returns A copy of the manifest file where the cause of the error is fixed.
|
|
128
|
-
*/ export function fixManifest(snapFiles, error) {
|
|
131
|
+
*/ export async function fixManifest(snapFiles, error) {
|
|
129
132
|
const { manifest, packageJson } = snapFiles;
|
|
130
133
|
const clonedFile = manifest.clone();
|
|
131
134
|
const manifestCopy = clonedFile.result;
|
|
@@ -140,7 +143,7 @@ const MANIFEST_SORT_ORDER = {
|
|
|
140
143
|
manifestCopy.repository = packageJson.result.repository ? deepClone(packageJson.result.repository) : undefined;
|
|
141
144
|
break;
|
|
142
145
|
case SnapValidationFailureReason.ShasumMismatch:
|
|
143
|
-
manifestCopy.source.shasum = getSnapChecksum(snapFiles);
|
|
146
|
+
manifestCopy.source.shasum = await getSnapChecksum(snapFiles);
|
|
144
147
|
break;
|
|
145
148
|
/* istanbul ignore next */ default:
|
|
146
149
|
assertExhaustive(error.reason);
|
|
@@ -201,22 +204,35 @@ const MANIFEST_SORT_ORDER = {
|
|
|
201
204
|
}
|
|
202
205
|
}
|
|
203
206
|
/**
|
|
204
|
-
*
|
|
205
|
-
* and read them.
|
|
207
|
+
* Get an array of paths from an unvalidated Snap manifest.
|
|
206
208
|
*
|
|
207
|
-
* @param basePath - The path to the folder with the manifest files.
|
|
208
209
|
* @param manifest - The unvalidated Snap manifest file contents.
|
|
209
|
-
* @
|
|
210
|
-
|
|
210
|
+
* @param selector - A function that returns the paths to the files.
|
|
211
|
+
* @returns The paths to the files, if any.
|
|
212
|
+
*/ export function getSnapFilePaths(manifest, selector) {
|
|
211
213
|
if (!isPlainObject(manifest)) {
|
|
212
214
|
return undefined;
|
|
213
215
|
}
|
|
214
|
-
const
|
|
215
|
-
|
|
216
|
+
const snapManifest = manifest;
|
|
217
|
+
const paths = selector(snapManifest);
|
|
218
|
+
if (!Array.isArray(paths)) {
|
|
219
|
+
return undefined;
|
|
220
|
+
}
|
|
221
|
+
return paths;
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Given an unvalidated Snap manifest, attempts to extract the files with the
|
|
225
|
+
* given paths and read them.
|
|
226
|
+
*
|
|
227
|
+
* @param basePath - The path to the folder with the manifest files.
|
|
228
|
+
* @param paths - The paths to the files.
|
|
229
|
+
* @returns A list of auxiliary files and their contents, if any.
|
|
230
|
+
*/ export async function getSnapFiles(basePath, paths) {
|
|
231
|
+
if (!paths) {
|
|
216
232
|
return undefined;
|
|
217
233
|
}
|
|
218
234
|
try {
|
|
219
|
-
return await Promise.all(
|
|
235
|
+
return await Promise.all(paths.map(async (filePath)=>readVirtualFile(pathUtils.join(basePath, filePath), 'utf8')));
|
|
220
236
|
} catch (error) {
|
|
221
237
|
throw new Error(`Failed to read snap files: ${getErrorMessage(error)}`);
|
|
222
238
|
}
|
|
@@ -240,7 +256,7 @@ const MANIFEST_SORT_ORDER = {
|
|
|
240
256
|
return writableManifest;
|
|
241
257
|
}
|
|
242
258
|
/**
|
|
243
|
-
* Validates the fields of an
|
|
259
|
+
* Validates the fields of an NPM Snap manifest that has already passed JSON
|
|
244
260
|
* Schema validation.
|
|
245
261
|
*
|
|
246
262
|
* @param snapFiles - The relevant snap files to validate.
|
|
@@ -249,7 +265,8 @@ const MANIFEST_SORT_ORDER = {
|
|
|
249
265
|
* @param snapFiles.sourceCode - The Snap's source code.
|
|
250
266
|
* @param snapFiles.svgIcon - The Snap's optional icon.
|
|
251
267
|
* @param snapFiles.auxiliaryFiles - Any auxiliary files required by the snap at runtime.
|
|
252
|
-
|
|
268
|
+
* @param snapFiles.localizationFiles - The Snap's localization files.
|
|
269
|
+
*/ export async function validateNpmSnapManifest({ manifest, packageJson, sourceCode, svgIcon, auxiliaryFiles, localizationFiles }) {
|
|
253
270
|
const packageJsonName = packageJson.result.name;
|
|
254
271
|
const packageJsonVersion = packageJson.result.version;
|
|
255
272
|
const packageJsonRepository = packageJson.result.repository;
|
|
@@ -267,11 +284,12 @@ const MANIFEST_SORT_ORDER = {
|
|
|
267
284
|
(packageJsonRepository || manifestRepository) && !deepEqual(packageJsonRepository, manifestRepository)) {
|
|
268
285
|
throw new ProgrammaticallyFixableSnapError(`"${NpmSnapFileNames.Manifest}" "repository" field does not match the "${NpmSnapFileNames.PackageJson}" "repository" field.`, SnapValidationFailureReason.RepositoryMismatch);
|
|
269
286
|
}
|
|
270
|
-
validateSnapShasum({
|
|
287
|
+
await validateSnapShasum({
|
|
271
288
|
manifest,
|
|
272
289
|
sourceCode,
|
|
273
290
|
svgIcon,
|
|
274
|
-
auxiliaryFiles
|
|
291
|
+
auxiliaryFiles,
|
|
292
|
+
localizationFiles
|
|
275
293
|
}, `"${NpmSnapFileNames.Manifest}" "shasum" field does not match computed shasum.`);
|
|
276
294
|
}
|
|
277
295
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/manifest/manifest.ts"],"sourcesContent":["import 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 { getErrorMessage } from '../errors';\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 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:\n (await getSnapAuxiliaryFiles(basePath, unvalidatedManifest)) ?? [],\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = 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 = fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n validateNpmSnapManifest({ ...partiallyValidatedFiles, manifest });\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 function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): 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 = 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 * Given an unvalidated Snap manifest, attempts to extract the auxiliary files\n * and read them.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns A list of auxiliary files and their contents, if any.\n */\nexport async function getSnapAuxiliaryFiles(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile[] | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const filePaths = (manifest as Partial<SnapManifest>).source?.files;\n\n if (!filePaths) {\n return undefined;\n }\n\n try {\n return await Promise.all(\n filePaths.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 */\nexport function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\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 validateSnapShasum(\n { manifest, sourceCode, svgIcon, auxiliaryFiles },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["assertExhaustive","assert","isPlainObject","deepEqual","promises","fs","pathUtils","deepClone","getErrorMessage","readJsonFile","validateNpmSnap","getSnapChecksum","ProgrammaticallyFixableSnapError","validateSnapShasum","NpmSnapFileNames","SnapValidationFailureReason","readVirtualFile","VirtualFile","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","checkManifest","basePath","writeManifest","sourceCode","writeFileFn","writeFile","warnings","errors","updated","manifestPath","join","Manifest","manifestFile","unvalidatedManifest","result","packageFile","PackageJson","snapFiles","manifest","packageJson","getSnapSourceCode","svgIcon","getSnapIcon","auxiliaryFiles","getSnapAuxiliaryFiles","error","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","length","attempts","fixManifest","validateNpmSnapManifest","nextValidationError","Error","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","getWritableManifest","value","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","undefined","ShasumMismatch","shasum","sourceFilePath","filePath","path","virtualFile","iconPath","filePaths","files","Promise","all","map","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository"],"mappings":"AACA,SAASA,gBAAgB,EAAEC,MAAM,EAAEC,aAAa,QAAQ,kBAAkB;AAC1E,OAAOC,eAAe,kBAAkB;AACxC,SAASC,YAAYC,EAAE,QAAQ,KAAK;AACpC,OAAOC,eAAe,OAAO;AAE7B,SAASC,SAAS,QAAQ,gBAAgB;AAC1C,SAASC,eAAe,QAAQ,YAAY;AAC5C,SAASC,YAAY,QAAQ,QAAQ;AACrC,SAASC,eAAe,QAAQ,SAAS;AACzC,SACEC,eAAe,EACfC,gCAAgC,EAChCC,kBAAkB,QACb,WAAW;AAElB,SAASC,gBAAgB,EAAEC,2BAA2B,QAAQ,WAAW;AACzE,SAASC,eAAe,EAAEC,WAAW,QAAQ,kBAAkB;AAG/D,MAAMC,sBAA0D;IAC9DC,SAAS;IACTC,SAAS;IACTC,aAAa;IACbC,cAAc;IACdC,YAAY;IACZC,QAAQ;IACRC,oBAAoB;IACpBC,iBAAiB;AACnB;AAyBA;;;;;;;;;;;CAWC,GACD,OAAO,eAAeC,cACpBC,QAAgB,EAChBC,gBAAgB,IAAI,EACpBC,UAAmB,EACnBC,cAAiC1B,GAAG2B,SAAS;IAE7C,MAAMC,WAAqB,EAAE;IAC7B,MAAMC,SAAmB,EAAE;IAE3B,IAAIC,UAAU;IAEd,MAAMC,eAAe9B,UAAU+B,IAAI,CAACT,UAAUd,iBAAiBwB,QAAQ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AC5H5B,4BAA4B2E,kBAAkB;IAElD;IAEA7E,mBACE;QAAEgC;QAAUf;QAAYkB;QAASE;IAAe,GAChD,CAAC,CAAC,EAAEpC,iBAAiBwB,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 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":["getErrorMessage","assertExhaustive","assert","isPlainObject","deepEqual","promises","fs","pathUtils","deepClone","readJsonFile","validateNpmSnap","getSnapChecksum","ProgrammaticallyFixableSnapError","validateSnapShasum","NpmSnapFileNames","SnapValidationFailureReason","readVirtualFile","VirtualFile","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","checkManifest","basePath","writeManifest","sourceCode","writeFileFn","writeFile","warnings","errors","updated","manifestPath","join","Manifest","manifestFile","unvalidatedManifest","result","packageFile","PackageJson","auxiliaryFilePaths","getSnapFilePaths","manifest","files","localizationFilePaths","locales","snapFiles","packageJson","getSnapSourceCode","svgIcon","getSnapIcon","auxiliaryFiles","getSnapFiles","localizationFiles","error","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","length","attempts","fixManifest","validateNpmSnapManifest","nextValidationError","Error","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","getWritableManifest","value","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","undefined","ShasumMismatch","shasum","sourceFilePath","filePath","path","virtualFile","iconPath","selector","snapManifest","paths","Array","isArray","Promise","all","map","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","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C,qBAAqB,CAAC,EAC5H5B,4BAA4BiF,kBAAkB;IAElD;IAEA,MAAMnF,mBACJ;QAAEiC;QAAUhB;QAAYuB;QAASE;QAAgBE;IAAkB,GACnE,CAAC,CAAC,EAAE3C,iBAAiBwB,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { isValidBIP32PathSegment } from '@metamask/key-tree';
|
|
2
2
|
import { assertStruct, ChecksumStruct, VersionStruct, isValidSemVerRange } from '@metamask/utils';
|
|
3
|
-
import { array, boolean, create, enums, integer, is, literal, object, optional,
|
|
3
|
+
import { array, boolean, create, enums, integer, is, literal, object, optional, refine, record, size, string, type, union } from 'superstruct';
|
|
4
4
|
import { isEqual } from '../array';
|
|
5
5
|
import { CronjobSpecificationArrayStruct } from '../cronjob';
|
|
6
6
|
import { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';
|
|
@@ -103,7 +103,7 @@ export const SnapAuxilaryFilesStruct = array(string());
|
|
|
103
103
|
export const SnapManifestStruct = object({
|
|
104
104
|
version: VersionStruct,
|
|
105
105
|
description: size(string(), 1, 280),
|
|
106
|
-
proposedName: size(
|
|
106
|
+
proposedName: size(string(), 1, 214),
|
|
107
107
|
repository: optional(object({
|
|
108
108
|
type: size(string(), 1, Infinity),
|
|
109
109
|
url: size(string(), 1, Infinity)
|
|
@@ -121,7 +121,8 @@ export const SnapManifestStruct = object({
|
|
|
121
121
|
])
|
|
122
122
|
})
|
|
123
123
|
}),
|
|
124
|
-
files: optional(SnapAuxilaryFilesStruct)
|
|
124
|
+
files: optional(SnapAuxilaryFilesStruct),
|
|
125
|
+
locales: optional(SnapAuxilaryFilesStruct)
|
|
125
126
|
}),
|
|
126
127
|
initialPermissions: PermissionsStruct,
|
|
127
128
|
manifestVersion: literal('0.1'),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n} from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n enums,\n integer,\n is,\n literal,\n object,\n optional,\n pattern,\n refine,\n record,\n size,\n string,\n type,\n union,\n} from 'superstruct';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { KeyringOriginsStruct, RpcOriginsStruct } from '../json-rpc';\nimport { ChainIdStruct } from '../namespace';\nimport { SnapIdStruct } from '../snaps';\nimport { NameStruct, NpmSnapFileNames } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <\n Type extends { path: string[]; curve: string },\n Schema,\n>(\n struct: Struct<Type, Schema>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\nexport const ChainIdsStruct = array(ChainIdStruct);\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:transaction-insight': optional(\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n 'endowment:cronjob': optional(\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n 'endowment:rpc': optional(RpcOriginsStruct),\n 'endowment:name-lookup': optional(ChainIdsStruct),\n 'endowment:keyring': optional(KeyringOriginsStruct),\n snap_dialog: optional(object({})),\n // TODO: Remove\n snap_confirm: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = Infer<typeof PermissionsStruct>;\n\nexport const SnapAuxilaryFilesStruct = array(string());\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(\n pattern(\n string(),\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u,\n ),\n 1,\n 214,\n ),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n files: optional(SnapAuxilaryFilesStruct),\n }),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"],"names":["isValidBIP32PathSegment","assertStruct","ChecksumStruct","VersionStruct","isValidSemVerRange","array","boolean","create","enums","integer","is","literal","object","optional","pattern","refine","record","size","string","type","union","isEqual","CronjobSpecificationArrayStruct","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","KeyringOriginsStruct","RpcOriginsStruct","ChainIdStruct","SnapIdStruct","NameStruct","NpmSnapFileNames","FORBIDDEN_PURPOSES","FORBIDDEN_COIN_TYPES","FORBIDDEN_PATHS","map","coinType","Bip32PathStruct","path","length","slice","some","part","includes","forbiddenPath","join","bip32entropy","struct","value","curve","endsWith","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","Infinity","SemVerRangeStruct","SnapIdsStruct","version","Object","keys","ChainIdsStruct","PermissionsStruct","allowTransactionOrigin","jobs","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","snap_getEntropy","wallet_snap","SnapAuxilaryFilesStruct","SnapManifestStruct","description","proposedName","repository","url","source","shasum","location","npm","filePath","iconPath","packageName","registry","files","initialPermissions","manifestVersion","$schema","isSnapManifest","assertIsSnapManifest","Manifest","createSnapManifest"],"mappings":"AAAA,SAASA,uBAAuB,QAAQ,qBAAqB;AAC7D,SACEC,YAAY,EACZC,cAAc,EACdC,aAAa,EACbC,kBAAkB,QACb,kBAAkB;AAEzB,SACEC,KAAK,EACLC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,EAAE,EACFC,O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AAiB8D,QAAQ,CAAC,YAAY,CAAC;AAE/C;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,mBAAmB9C,KAAc;IAC/C,qEAAqE;IACrE,OAAOxC,OAAOwC,OAAO0B;AACvB"}
|
|
1
|
+
{"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport type { InitialPermissions } from '@metamask/snaps-sdk';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n} from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n enums,\n integer,\n is,\n literal,\n object,\n optional,\n refine,\n record,\n size,\n string,\n type,\n union,\n} from 'superstruct';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { KeyringOriginsStruct, RpcOriginsStruct } from '../json-rpc';\nimport { ChainIdStruct } from '../namespace';\nimport { SnapIdStruct } from '../snaps';\nimport type { InferMatching } from '../structs';\nimport { NameStruct, NpmSnapFileNames } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <\n Type extends { path: string[]; curve: string },\n Schema,\n>(\n struct: Struct<Type, Schema>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\nexport const ChainIdsStruct = array(ChainIdStruct);\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:transaction-insight': optional(\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n 'endowment:cronjob': optional(\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n 'endowment:rpc': optional(RpcOriginsStruct),\n 'endowment:name-lookup': optional(ChainIdsStruct),\n 'endowment:keyring': optional(KeyringOriginsStruct),\n snap_dialog: optional(object({})),\n // TODO: Remove\n snap_confirm: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = InferMatching<\n typeof PermissionsStruct,\n InitialPermissions\n>;\n\nexport const SnapAuxilaryFilesStruct = array(string());\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(string(), 1, 214),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n files: optional(SnapAuxilaryFilesStruct),\n locales: optional(SnapAuxilaryFilesStruct),\n }),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"],"names":["isValidBIP32PathSegment","assertStruct","ChecksumStruct","VersionStruct","isValidSemVerRange","array","boolean","create","enums","integer","is","literal","object","optional","refine","record","size","string","type","union","isEqual","CronjobSpecificationArrayStruct","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","KeyringOriginsStruct","RpcOriginsStruct","ChainIdStruct","SnapIdStruct","NameStruct","NpmSnapFileNames","FORBIDDEN_PURPOSES","FORBIDDEN_COIN_TYPES","FORBIDDEN_PATHS","map","coinType","Bip32PathStruct","path","length","slice","some","part","includes","forbiddenPath","join","bip32entropy","struct","value","curve","endsWith","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","Infinity","SemVerRangeStruct","SnapIdsStruct","version","Object","keys","ChainIdsStruct","PermissionsStruct","allowTransactionOrigin","jobs","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","snap_getEntropy","wallet_snap","SnapAuxilaryFilesStruct","SnapManifestStruct","description","proposedName","repository","url","source","shasum","location","npm","filePath","iconPath","packageName","registry","files","locales","initialPermissions","manifestVersion","$schema","isSnapManifest","assertIsSnapManifest","Manifest","createSnapManifest"],"mappings":"AAAA,SAASA,uBAAuB,QAAQ,qBAAqB;AAE7D,SACEC,YAAY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;IAC3C,OAAOpC,GAAGoC,OAAO0B;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASmB,qBACd7C,KAAc;IAEd7C,aACE6C,OACA0B,oBACA,CAAC,CAAC,EAAE3C,iBAAiB+D,QAAQ,CAAC,YAAY,CAAC;AAE/C;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,mBAAmB/C,KAAc;IAC/C,qEAAqE;IACrE,OAAOvC,OAAOuC,OAAO0B;AACvB"}
|
package/dist/esm/namespace.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { array, is, object, optional, pattern, size, string } from 'superstruct';
|
|
1
|
+
import { array, define, is, object, optional, pattern, size, string } from 'superstruct';
|
|
2
2
|
export const CHAIN_ID_REGEX = RegExp("^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$", "u");
|
|
3
3
|
export const ACCOUNT_ID_REGEX = RegExp("^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$", "u");
|
|
4
4
|
export const ACCOUNT_ADDRESS_REGEX = RegExp("^(?<accountAddress>[a-zA-Z0-9]{1,64})$", "u");
|
|
@@ -42,9 +42,10 @@ export const ACCOUNT_ADDRESS_REGEX = RegExp("^(?<accountAddress>[a-zA-Z0-9]{1,64
|
|
|
42
42
|
* A helper struct for a string with a minimum length of 1 and a maximum length
|
|
43
43
|
* of 40.
|
|
44
44
|
*/ export const LimitedString = size(string(), 1, 40);
|
|
45
|
+
export const ChainIdStringStruct = define('Chain ID', string().validator);
|
|
45
46
|
/**
|
|
46
47
|
* A CAIP-2 chain ID, i.e., a human-readable namespace and reference.
|
|
47
|
-
*/ export const ChainIdStruct = pattern(
|
|
48
|
+
*/ export const ChainIdStruct = pattern(ChainIdStringStruct, CHAIN_ID_REGEX);
|
|
48
49
|
export const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);
|
|
49
50
|
export const AccountIdArrayStruct = array(AccountIdStruct);
|
|
50
51
|
export const AccountAddressStruct = pattern(string(), ACCOUNT_ADDRESS_REGEX);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/namespace.ts"],"sourcesContent":["import type { Infer } from 'superstruct';\nimport {\n array,\n is,\n object,\n optional,\n pattern,\n size,\n string,\n} from 'superstruct';\n\nexport const CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;\n\nexport const ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\nexport const ACCOUNT_ADDRESS_REGEX = /^(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\n/**\n * Parse a chain ID string to an object containing the namespace and reference.\n * This validates the chain ID before parsing it.\n *\n * @param chainId - The chain ID to validate and parse.\n * @returns The parsed chain ID.\n */\nexport function parseChainId(chainId: ChainId): {\n namespace: NamespaceId;\n reference: string;\n} {\n const match = CHAIN_ID_REGEX.exec(chainId);\n if (!match?.groups) {\n throw new Error('Invalid chain ID.');\n }\n\n return {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n };\n}\n\n/**\n * Parse an account ID to an object containing the chain, chain ID and address.\n * This validates the account ID before parsing it.\n *\n * @param accountId - The account ID to validate and parse.\n * @returns The parsed account ID.\n */\nexport function parseAccountId(accountId: AccountId): {\n chain: { namespace: NamespaceId; reference: string };\n chainId: ChainId;\n address: string;\n} {\n const match = ACCOUNT_ID_REGEX.exec(accountId);\n if (!match?.groups) {\n throw new Error('Invalid account ID.');\n }\n\n return {\n address: match.groups.accountAddress,\n chainId: match.groups.chainId as ChainId,\n chain: {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n },\n };\n}\n\n/**\n * A helper struct for a string with a minimum length of 1 and a maximum length\n * of 40.\n */\nexport const LimitedString = size(string(), 1, 40);\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const ChainIdStruct = pattern
|
|
1
|
+
{"version":3,"sources":["../../src/namespace.ts"],"sourcesContent":["import type { AccountId, ChainId } from '@metamask/snaps-sdk';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n define,\n is,\n object,\n optional,\n pattern,\n size,\n string,\n} from 'superstruct';\n\nimport type { InferMatching } from './structs';\n\nexport const CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;\n\nexport const ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\nexport const ACCOUNT_ADDRESS_REGEX = /^(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\n/**\n * Parse a chain ID string to an object containing the namespace and reference.\n * This validates the chain ID before parsing it.\n *\n * @param chainId - The chain ID to validate and parse.\n * @returns The parsed chain ID.\n */\nexport function parseChainId(chainId: ChainId): {\n namespace: NamespaceId;\n reference: string;\n} {\n const match = CHAIN_ID_REGEX.exec(chainId);\n if (!match?.groups) {\n throw new Error('Invalid chain ID.');\n }\n\n return {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n };\n}\n\n/**\n * Parse an account ID to an object containing the chain, chain ID and address.\n * This validates the account ID before parsing it.\n *\n * @param accountId - The account ID to validate and parse.\n * @returns The parsed account ID.\n */\nexport function parseAccountId(accountId: AccountId): {\n chain: { namespace: NamespaceId; reference: string };\n chainId: ChainId;\n address: string;\n} {\n const match = ACCOUNT_ID_REGEX.exec(accountId);\n if (!match?.groups) {\n throw new Error('Invalid account ID.');\n }\n\n return {\n address: match.groups.accountAddress,\n chainId: match.groups.chainId as ChainId,\n chain: {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n },\n };\n}\n\n/**\n * A helper struct for a string with a minimum length of 1 and a maximum length\n * of 40.\n */\nexport const LimitedString = size(string(), 1, 40);\n\nexport const ChainIdStringStruct = define<ChainId>(\n 'Chain ID',\n string().validator,\n);\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const ChainIdStruct = pattern<ChainId, null>(\n ChainIdStringStruct,\n CHAIN_ID_REGEX,\n);\n\nexport type Caip2ChainId = InferMatching<typeof ChainIdStruct, ChainId>;\n\nexport const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);\n\nexport const AccountIdArrayStruct = array(AccountIdStruct);\nexport const AccountAddressStruct = pattern(string(), ACCOUNT_ADDRESS_REGEX);\nexport type AccountAddress = Infer<typeof AccountAddressStruct>;\n\n/**\n * A chain descriptor.\n */\nexport const ChainStruct = object({\n id: ChainIdStruct,\n name: LimitedString,\n});\nexport type Chain = Infer<typeof ChainStruct>;\n\nexport const NamespaceStruct = object({\n /**\n * A list of supported chains in the namespace.\n */\n chains: array(ChainStruct),\n\n /**\n * A list of supported RPC methods on the namespace, that a DApp can call.\n */\n methods: optional(array(LimitedString)),\n\n /**\n * A list of supported RPC events on the namespace, that a DApp can listen to.\n */\n events: optional(array(LimitedString)),\n});\nexport type Namespace = Infer<typeof NamespaceStruct>;\n\n/**\n * A CAIP-2 namespace, i.e., the first part of a chain ID.\n */\nexport const NamespaceIdStruct = pattern(string(), /^[-a-z0-9]{3,8}$/u);\nexport type NamespaceId = Infer<typeof NamespaceIdStruct>;\n\n/**\n * Check if the given value is a CAIP-2 namespace ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 namespace ID.\n */\nexport function isNamespaceId(value: unknown): value is NamespaceId {\n return is(value, NamespaceIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-2 chain ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 chain ID.\n */\nexport function isChainId(value: unknown): value is ChainId {\n return is(value, ChainIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-10 account ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-10 account ID.\n */\nexport function isAccountId(value: unknown): value is AccountId {\n return is(value, AccountIdStruct);\n}\n\n/**\n * Check if the given value is an array of CAIP-10 account IDs.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of CAIP-10 account IDs.\n */\nexport function isAccountIdArray(value: unknown): value is AccountId[] {\n return is(value, AccountIdArrayStruct);\n}\n\n/**\n * Check if a value is a {@link Namespace}.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid {@link Namespace}.\n */\nexport function isNamespace(value: unknown): value is Namespace {\n return is(value, NamespaceStruct);\n}\n"],"names":["array","define","is","object","optional","pattern","size","string","CHAIN_ID_REGEX","ACCOUNT_ID_REGEX","ACCOUNT_ADDRESS_REGEX","parseChainId","chainId","match","exec","groups","Error","namespace","reference","parseAccountId","accountId","address","accountAddress","chain","LimitedString","ChainIdStringStruct","validator","ChainIdStruct","AccountIdStruct","AccountIdArrayStruct","AccountAddressStruct","ChainStruct","id","name","NamespaceStruct","chains","methods","events","NamespaceIdStruct","isNamespaceId","value","isChainId","isAccountId","isAccountIdArray","isNamespace"],"mappings":"AAEA,SACEA,KAAK,EACLC,MAAM,EACNC,EAAE,EACFC,MAAM,EACNC,QAAQ,EACRC,OAAO,EACPC,IAAI,EACJC,MAAM,QACD,cAAc;AAIrB,OAAO,MAAMC,iBACX,+EAAmE;AAErE,OAAO,MAAMC,mBACX,gIAAoH;AAEtH,OAAO,MAAMC,wBAAwB,sDAA0C;AAE/E;;;;;;CAMC,GACD,OAAO,SAASC,aAAaC,OAAgB;IAI3C,MAAMC,QAAQL,eAAeM,IAAI,CAACF;IAClC,IAAI,CAACC,OAAOE,QAAQ;QAClB,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO;QACLC,WAAWJ,MAAME,MAAM,CAACE,SAAS;QACjCC,WAAWL,MAAME,MAAM,CAACG,SAAS;IACnC;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,eAAeC,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;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASe,iBAAiBH,KAAc;IAC7C,OAAOtC,GAAGsC,OAAOX;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASe,YAAYJ,KAAc;IACxC,OAAOtC,GAAGsC,OAAON;AACnB"}
|
package/dist/esm/npm.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { assertIsSnapIcon } from './icon';
|
|
2
|
+
import { getValidatedLocalizationFiles, validateSnapManifestLocalizations } from './localization';
|
|
2
3
|
import { validateNpmSnapManifest } from './manifest/manifest';
|
|
3
4
|
import { assertIsSnapManifest } from './manifest/validation';
|
|
4
5
|
import { assertIsNpmSnapPackageJson, NpmSnapFileNames } from './types';
|
|
@@ -22,14 +23,14 @@ export const SnapFileNameFromKey = {
|
|
|
22
23
|
* if any.
|
|
23
24
|
* @param errorPrefix - The prefix of the error message.
|
|
24
25
|
* @returns A tuple of the Snap manifest object and the Snap source code.
|
|
25
|
-
*/ export function validateNpmSnap(snapFiles, errorPrefix) {
|
|
26
|
+
*/ export async function validateNpmSnap(snapFiles, errorPrefix) {
|
|
26
27
|
EXPECTED_SNAP_FILES.forEach((key)=>{
|
|
27
28
|
if (!snapFiles[key]) {
|
|
28
29
|
throw new Error(`${errorPrefix ?? ''}Missing file "${SnapFileNameFromKey[key]}".`);
|
|
29
30
|
}
|
|
30
31
|
});
|
|
31
32
|
// Typecast: We are assured that the required files exist if we get here.
|
|
32
|
-
const { manifest, packageJson, sourceCode, svgIcon, auxiliaryFiles } = snapFiles;
|
|
33
|
+
const { manifest, packageJson, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } = snapFiles;
|
|
33
34
|
try {
|
|
34
35
|
assertIsSnapManifest(manifest.result);
|
|
35
36
|
} catch (error) {
|
|
@@ -46,12 +47,13 @@ export const SnapFileNameFromKey = {
|
|
|
46
47
|
throw new Error(`${errorPrefix ?? ''}${error.message}`);
|
|
47
48
|
}
|
|
48
49
|
const validatedPackageJson = packageJson;
|
|
49
|
-
validateNpmSnapManifest({
|
|
50
|
+
await validateNpmSnapManifest({
|
|
50
51
|
manifest: validatedManifest,
|
|
51
52
|
packageJson: validatedPackageJson,
|
|
52
53
|
sourceCode,
|
|
53
54
|
svgIcon,
|
|
54
|
-
auxiliaryFiles
|
|
55
|
+
auxiliaryFiles,
|
|
56
|
+
localizationFiles
|
|
55
57
|
});
|
|
56
58
|
if (svgIcon) {
|
|
57
59
|
try {
|
|
@@ -60,12 +62,23 @@ export const SnapFileNameFromKey = {
|
|
|
60
62
|
throw new Error(`${errorPrefix ?? ''}${error.message}`);
|
|
61
63
|
}
|
|
62
64
|
}
|
|
65
|
+
if (localizationFiles) {
|
|
66
|
+
try {
|
|
67
|
+
// This function validates and returns the localization files. We don't
|
|
68
|
+
// use the return value here, but we do want to validate the files.
|
|
69
|
+
getValidatedLocalizationFiles(localizationFiles);
|
|
70
|
+
validateSnapManifestLocalizations(manifest.result, localizationFiles.map((file)=>file.result));
|
|
71
|
+
} catch (error) {
|
|
72
|
+
throw new Error(`${errorPrefix ?? ''}${error.message}`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
63
75
|
return {
|
|
64
76
|
manifest: validatedManifest,
|
|
65
77
|
packageJson: validatedPackageJson,
|
|
66
78
|
sourceCode,
|
|
67
79
|
svgIcon,
|
|
68
|
-
auxiliaryFiles
|
|
80
|
+
auxiliaryFiles,
|
|
81
|
+
localizationFiles
|
|
69
82
|
};
|
|
70
83
|
}
|
|
71
84
|
|
package/dist/esm/npm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/npm.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport type { SnapFiles, UnvalidatedSnapFiles } from './types';\nimport { assertIsNpmSnapPackageJson, NpmSnapFileNames } from './types';\n\nexport const EXPECTED_SNAP_FILES = [\n 'manifest',\n 'packageJson',\n 'sourceCode',\n] as const;\n\nexport const SnapFileNameFromKey = {\n manifest: NpmSnapFileNames.Manifest,\n packageJson: NpmSnapFileNames.PackageJson,\n sourceCode: 'source code bundle',\n} as const;\n\n// TODO: Refactor this to be more shared with other validation.\n\n/**\n * Validates the files extracted from an npm Snap package tarball by ensuring\n * that they're non-empty and that the Json files match their respective schemas\n * and the Snaps publishing specification.\n *\n * @param snapFiles - The object containing the expected Snap file contents,\n * if any.\n * @param errorPrefix - The prefix of the error message.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport function validateNpmSnap(\n snapFiles: UnvalidatedSnapFiles,\n errorPrefix?: `${string}: `,\n): SnapFiles {\n EXPECTED_SNAP_FILES.forEach((key) => {\n if (!snapFiles[key]) {\n throw new Error(\n `${errorPrefix ?? ''}Missing file \"${SnapFileNameFromKey[key]}\".`,\n );\n }\n });\n\n // Typecast: We are assured that the required files exist if we get here.\n const {
|
|
1
|
+
{"version":3,"sources":["../../src/npm.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport {\n getValidatedLocalizationFiles,\n validateSnapManifestLocalizations,\n} from './localization';\nimport { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport type { SnapFiles, UnvalidatedSnapFiles } from './types';\nimport { assertIsNpmSnapPackageJson, NpmSnapFileNames } from './types';\n\nexport const EXPECTED_SNAP_FILES = [\n 'manifest',\n 'packageJson',\n 'sourceCode',\n] as const;\n\nexport const SnapFileNameFromKey = {\n manifest: NpmSnapFileNames.Manifest,\n packageJson: NpmSnapFileNames.PackageJson,\n sourceCode: 'source code bundle',\n} as const;\n\n// TODO: Refactor this to be more shared with other validation.\n\n/**\n * Validates the files extracted from an npm Snap package tarball by ensuring\n * that they're non-empty and that the Json files match their respective schemas\n * and the Snaps publishing specification.\n *\n * @param snapFiles - The object containing the expected Snap file contents,\n * if any.\n * @param errorPrefix - The prefix of the error message.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport async function validateNpmSnap(\n snapFiles: UnvalidatedSnapFiles,\n errorPrefix?: `${string}: `,\n): Promise<SnapFiles> {\n EXPECTED_SNAP_FILES.forEach((key) => {\n if (!snapFiles[key]) {\n throw new Error(\n `${errorPrefix ?? ''}Missing file \"${SnapFileNameFromKey[key]}\".`,\n );\n }\n });\n\n // Typecast: We are assured that the required files exist if we get here.\n const {\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n } = snapFiles as SnapFiles;\n\n try {\n assertIsSnapManifest(manifest.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedManifest = manifest;\n\n const { iconPath } = validatedManifest.result.source.location.npm;\n if (iconPath && !svgIcon) {\n throw new Error(`Missing file \"${iconPath}\".`);\n }\n\n try {\n assertIsNpmSnapPackageJson(packageJson.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n\n const validatedPackageJson = packageJson;\n await validateNpmSnapManifest({\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n });\n\n if (svgIcon) {\n try {\n assertIsSnapIcon(svgIcon);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n }\n\n if (localizationFiles) {\n try {\n // This function validates and returns the localization files. We don't\n // use the return value here, but we do want to validate the files.\n getValidatedLocalizationFiles(localizationFiles);\n\n validateSnapManifestLocalizations(\n manifest.result,\n localizationFiles.map((file) => file.result),\n );\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n }\n\n return {\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n };\n}\n"],"names":["assertIsSnapIcon","getValidatedLocalizationFiles","validateSnapManifestLocalizations","validateNpmSnapManifest","assertIsSnapManifest","assertIsNpmSnapPackageJson","NpmSnapFileNames","EXPECTED_SNAP_FILES","SnapFileNameFromKey","manifest","Manifest","packageJson","PackageJson","sourceCode","validateNpmSnap","snapFiles","errorPrefix","forEach","key","Error","svgIcon","auxiliaryFiles","localizationFiles","result","error","message","validatedManifest","iconPath","source","location","npm","validatedPackageJson","map","file"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,SAAS;AAC1C,SACEC,6BAA6B,EAC7BC,iCAAiC,QAC5B,iBAAiB;AACxB,SAASC,uBAAuB,QAAQ,sBAAsB;AAC9D,SAASC,oBAAoB,QAAQ,wBAAwB;AAE7D,SAASC,0BAA0B,EAAEC,gBAAgB,QAAQ,UAAU;AAEvE,OAAO,MAAMC,sBAAsB;IACjC;IACA;IACA;CACD,CAAU;AAEX,OAAO,MAAMC,sBAAsB;IACjCC,UAAUH,iBAAiBI,QAAQ;IACnCC,aAAaL,iBAAiBM,WAAW;IACzCC,YAAY;AACd,EAAW;AAEX,+DAA+D;AAE/D;;;;;;;;;CASC,GACD,OAAO,eAAeC,gBACpBC,SAA+B,EAC/BC,WAA2B;IAE3BT,oBAAoBU,OAAO,CAAC,CAACC;QAC3B,IAAI,CAACH,SAAS,CAACG,IAAI,EAAE;YACnB,MAAM,IAAIC,MACR,CAAC,EAAEH,eAAe,GAAG,cAAc,EAAER,mBAAmB,CAACU,IAAI,CAAC,EAAE,CAAC;QAErE;IACF;IAEA,yEAAyE;IACzE,MAAM,EACJT,QAAQ,EACRE,WAAW,EACXE,UAAU,EACVO,OAAO,EACPC,cAAc,EACdC,iBAAiB,EAClB,GAAGP;IAEJ,IAAI;QACFX,qBAAqBK,SAASc,MAAM;IACtC,EAAE,OAAOC,OAAO;QACd,MAAM,IAAIL,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEQ,MAAMC,OAAO,CAAC,CAAC;IACxD;IACA,MAAMC,oBAAoBjB;IAE1B,MAAM,EAAEkB,QAAQ,EAAE,GAAGD,kBAAkBH,MAAM,CAACK,MAAM,CAACC,QAAQ,CAACC,GAAG;IACjE,IAAIH,YAAY,CAACP,SAAS;QACxB,MAAM,IAAID,MAAM,CAAC,cAAc,EAAEQ,SAAS,EAAE,CAAC;IAC/C;IAEA,IAAI;QACFtB,2BAA2BM,YAAYY,MAAM;IAC/C,EAAE,OAAOC,OAAO;QACd,MAAM,IAAIL,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEQ,MAAMC,OAAO,CAAC,CAAC;IACxD;IAEA,MAAMM,uBAAuBpB;IAC7B,MAAMR,wBAAwB;QAC5BM,UAAUiB;QACVf,aAAaoB;QACblB;QACAO;QACAC;QACAC;IACF;IAEA,IAAIF,SAAS;QACX,IAAI;YACFpB,iBAAiBoB;QACnB,EAAE,OAAOI,OAAO;YACd,MAAM,IAAIL,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEQ,MAAMC,OAAO,CAAC,CAAC;QACxD;IACF;IAEA,IAAIH,mBAAmB;QACrB,IAAI;YACF,uEAAuE;YACvE,mEAAmE;YACnErB,8BAA8BqB;YAE9BpB,kCACEO,SAASc,MAAM,EACfD,kBAAkBU,GAAG,CAAC,CAACC,OAASA,KAAKV,MAAM;QAE/C,EAAE,OAAOC,OAAO;YACd,MAAM,IAAIL,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEQ,MAAMC,OAAO,CAAC,CAAC;QACxD;IACF;IAEA,OAAO;QACLhB,UAAUiB;QACVf,aAAaoB;QACblB;QACAO;QACAC;QACAC;IACF;AACF"}
|
package/dist/esm/snaps.js
CHANGED
|
@@ -72,15 +72,16 @@ export var SnapStatusEvents;
|
|
|
72
72
|
*
|
|
73
73
|
* @param files - All required Snap files to be included in the checksum.
|
|
74
74
|
* @returns The Base64-encoded SHA-256 digest of the source code.
|
|
75
|
-
*/ export function getSnapChecksum(files) {
|
|
76
|
-
const { manifest, sourceCode, svgIcon, auxiliaryFiles } = files;
|
|
75
|
+
*/ export async function getSnapChecksum(files) {
|
|
76
|
+
const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } = files;
|
|
77
77
|
const all = [
|
|
78
78
|
getChecksummableManifest(manifest),
|
|
79
79
|
sourceCode,
|
|
80
80
|
svgIcon,
|
|
81
|
-
...auxiliaryFiles
|
|
81
|
+
...auxiliaryFiles,
|
|
82
|
+
...localizationFiles
|
|
82
83
|
].filter((file)=>file !== undefined);
|
|
83
|
-
return base64.encode(checksumFiles(all));
|
|
84
|
+
return base64.encode(await checksumFiles(all));
|
|
84
85
|
}
|
|
85
86
|
/**
|
|
86
87
|
* Checks whether the `source.shasum` property of a Snap manifest matches the
|
|
@@ -88,8 +89,8 @@ export var SnapStatusEvents;
|
|
|
88
89
|
*
|
|
89
90
|
* @param files - All required Snap files to be included in the checksum.
|
|
90
91
|
* @param errorMessage - The error message to throw if validation fails.
|
|
91
|
-
*/ export function validateSnapShasum(files, errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.') {
|
|
92
|
-
if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {
|
|
92
|
+
*/ export async function validateSnapShasum(files, errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.') {
|
|
93
|
+
if (files.manifest.result.source.shasum !== await getSnapChecksum(files)) {
|
|
93
94
|
throw new ProgrammaticallyFixableSnapError(errorMessage, SnapValidationFailureReason.ShasumMismatch);
|
|
94
95
|
}
|
|
95
96
|
}
|