@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 +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 './enum';\nexport * from './errors';\nexport * from './handlers';\nexport * from './handler-types';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\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 './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"}
|
|
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 './enum';\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;qBACA"}
|
package/dist/cjs/index.js
CHANGED
|
@@ -2,12 +2,6 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", {
|
|
3
3
|
value: true
|
|
4
4
|
});
|
|
5
|
-
Object.defineProperty(exports, "assertLinksAreSafe", {
|
|
6
|
-
enumerable: true,
|
|
7
|
-
get: function() {
|
|
8
|
-
return _snapsui.assertLinksAreSafe;
|
|
9
|
-
}
|
|
10
|
-
});
|
|
11
5
|
_export_star(require("./array"), exports);
|
|
12
6
|
_export_star(require("./auxiliary-files"), exports);
|
|
13
7
|
_export_star(require("./caveats"), exports);
|
|
@@ -25,6 +19,7 @@ _export_star(require("./handler-types"), exports);
|
|
|
25
19
|
_export_star(require("./iframe"), exports);
|
|
26
20
|
_export_star(require("./json"), exports);
|
|
27
21
|
_export_star(require("./json-rpc"), exports);
|
|
22
|
+
_export_star(require("./localization"), exports);
|
|
28
23
|
_export_star(require("./logging"), exports);
|
|
29
24
|
_export_star(require("./manifest"), exports);
|
|
30
25
|
_export_star(require("./mock"), exports);
|
|
@@ -36,10 +31,10 @@ _export_star(require("./snaps"), exports);
|
|
|
36
31
|
_export_star(require("./strings"), exports);
|
|
37
32
|
_export_star(require("./structs"), exports);
|
|
38
33
|
_export_star(require("./types"), exports);
|
|
34
|
+
_export_star(require("./ui"), exports);
|
|
39
35
|
_export_star(require("./validation"), exports);
|
|
40
36
|
_export_star(require("./versions"), exports);
|
|
41
37
|
_export_star(require("./virtual-file"), exports);
|
|
42
|
-
const _snapsui = require("@metamask/snaps-ui");
|
|
43
38
|
function _export_star(from, to) {
|
|
44
39
|
Object.keys(from).forEach(function(k) {
|
|
45
40
|
if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) {
|
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 './enum';\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 './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 './
|
|
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 './enum';\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;qBACA"}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
function _export(target, all) {
|
|
6
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: all[name]
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
_export(exports, {
|
|
12
|
+
LOCALIZABLE_FIELDS: function() {
|
|
13
|
+
return LOCALIZABLE_FIELDS;
|
|
14
|
+
},
|
|
15
|
+
LocalizationFileStruct: function() {
|
|
16
|
+
return LocalizationFileStruct;
|
|
17
|
+
},
|
|
18
|
+
getValidatedLocalizationFiles: function() {
|
|
19
|
+
return getValidatedLocalizationFiles;
|
|
20
|
+
},
|
|
21
|
+
getLocalizationFile: function() {
|
|
22
|
+
return getLocalizationFile;
|
|
23
|
+
},
|
|
24
|
+
TRANSLATION_REGEX: function() {
|
|
25
|
+
return TRANSLATION_REGEX;
|
|
26
|
+
},
|
|
27
|
+
translate: function() {
|
|
28
|
+
return translate;
|
|
29
|
+
},
|
|
30
|
+
getLocalizedSnapManifest: function() {
|
|
31
|
+
return getLocalizedSnapManifest;
|
|
32
|
+
},
|
|
33
|
+
validateSnapManifestLocalizations: function() {
|
|
34
|
+
return validateSnapManifestLocalizations;
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
const _snapssdk = require("@metamask/snaps-sdk");
|
|
38
|
+
const _superstruct = require("superstruct");
|
|
39
|
+
const _json = require("./json");
|
|
40
|
+
const LOCALIZABLE_FIELDS = [
|
|
41
|
+
'description',
|
|
42
|
+
'proposedName'
|
|
43
|
+
];
|
|
44
|
+
const LocalizationFileStruct = (0, _superstruct.object)({
|
|
45
|
+
locale: (0, _superstruct.string)(),
|
|
46
|
+
messages: (0, _superstruct.record)((0, _superstruct.string)(), (0, _superstruct.object)({
|
|
47
|
+
message: (0, _superstruct.string)(),
|
|
48
|
+
description: (0, _superstruct.optional)((0, _superstruct.string)())
|
|
49
|
+
}))
|
|
50
|
+
});
|
|
51
|
+
function getValidatedLocalizationFiles(localizationFiles) {
|
|
52
|
+
for (const file of localizationFiles){
|
|
53
|
+
try {
|
|
54
|
+
file.result = (0, _superstruct.create)((0, _json.parseJson)(file.toString()), LocalizationFileStruct);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (error instanceof _superstruct.StructError) {
|
|
57
|
+
throw new Error(`Failed to validate localization file "${file.path}": ${error.message}.`);
|
|
58
|
+
}
|
|
59
|
+
if (error instanceof SyntaxError) {
|
|
60
|
+
throw new Error(`Failed to parse localization file "${file.path}" as JSON.`);
|
|
61
|
+
}
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return localizationFiles;
|
|
66
|
+
}
|
|
67
|
+
function getLocalizationFile(locale, localizationFiles) {
|
|
68
|
+
const file = localizationFiles.find((localizationFile)=>localizationFile.locale === locale);
|
|
69
|
+
if (!file) {
|
|
70
|
+
return localizationFiles.find((localizationFile)=>localizationFile.locale === 'en');
|
|
71
|
+
}
|
|
72
|
+
return file;
|
|
73
|
+
}
|
|
74
|
+
const TRANSLATION_REGEX = /\{\{\s?([a-zA-Z0-9-_\s]+)\s?\}\}/gu;
|
|
75
|
+
function translate(value, file) {
|
|
76
|
+
const matches = value.matchAll(TRANSLATION_REGEX);
|
|
77
|
+
const array = Array.from(matches);
|
|
78
|
+
return array.reduce((result, [match, key])=>{
|
|
79
|
+
if (!file) {
|
|
80
|
+
throw new Error(`Failed to translate "${value}": No localization file found.`);
|
|
81
|
+
}
|
|
82
|
+
const translation = file.messages[key.trim()];
|
|
83
|
+
if (!translation) {
|
|
84
|
+
throw new Error(`Failed to translate "${value}": No translation found for "${key.trim()}" in "${file.locale}" file.`);
|
|
85
|
+
}
|
|
86
|
+
return result.replace(match, translation.message);
|
|
87
|
+
}, value);
|
|
88
|
+
}
|
|
89
|
+
function getLocalizedSnapManifest(snapManifest, locale, localizationFiles) {
|
|
90
|
+
const file = getLocalizationFile(locale, localizationFiles);
|
|
91
|
+
return LOCALIZABLE_FIELDS.reduce((manifest, field)=>{
|
|
92
|
+
const translation = translate(manifest[field], file);
|
|
93
|
+
return {
|
|
94
|
+
...manifest,
|
|
95
|
+
[field]: translation
|
|
96
|
+
};
|
|
97
|
+
}, snapManifest);
|
|
98
|
+
}
|
|
99
|
+
function validateSnapManifestLocalizations(snapManifest, localizationFiles) {
|
|
100
|
+
try {
|
|
101
|
+
// `translate` throws if the manifest cannot be localized, so we just attempt
|
|
102
|
+
// to translate the manifest using all localization files.
|
|
103
|
+
localizationFiles.filter((file)=>file.locale !== 'en').forEach((file)=>{
|
|
104
|
+
getLocalizedSnapManifest(snapManifest, file.locale, localizationFiles);
|
|
105
|
+
});
|
|
106
|
+
// The manifest must be localizable in English.
|
|
107
|
+
getLocalizedSnapManifest(snapManifest, 'en', localizationFiles);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
throw new Error(`Failed to localize Snap manifest: ${(0, _snapssdk.getErrorMessage)(error)}`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
//# sourceMappingURL=localization.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/localization.ts"],"sourcesContent":["import { getErrorMessage } from '@metamask/snaps-sdk';\nimport type { Infer } from 'superstruct';\nimport {\n create,\n object,\n optional,\n record,\n string,\n StructError,\n} from 'superstruct';\n\nimport { parseJson } from './json';\nimport type { SnapManifest } from './manifest';\nimport type { VirtualFile } from './virtual-file';\n\nexport const LOCALIZABLE_FIELDS = ['description', 'proposedName'] as const;\n\nexport const LocalizationFileStruct = object({\n locale: string(),\n messages: record(\n string(),\n object({\n message: string(),\n description: optional(string()),\n }),\n ),\n});\n\nexport type LocalizationFile = Infer<typeof LocalizationFileStruct>;\n\n/**\n * Validate a list of localization files.\n *\n * @param localizationFiles - The localization files to validate.\n * @returns The validated localization files.\n * @throws If any of the files are considered invalid.\n */\nexport function getValidatedLocalizationFiles(\n localizationFiles: VirtualFile[],\n): VirtualFile<LocalizationFile>[] {\n for (const file of localizationFiles) {\n try {\n file.result = create(parseJson(file.toString()), LocalizationFileStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(\n `Failed to validate localization file \"${file.path}\": ${error.message}.`,\n );\n }\n\n if (error instanceof SyntaxError) {\n throw new Error(\n `Failed to parse localization file \"${file.path}\" as JSON.`,\n );\n }\n\n throw error;\n }\n }\n\n return localizationFiles as VirtualFile<LocalizationFile>[];\n}\n\n/**\n * Get the localization file for a given locale. If the locale is not found,\n * the English localization file will be returned.\n *\n * @param locale - The locale to use.\n * @param localizationFiles - The localization files to use.\n * @returns The localization file, or `undefined` if no localization file was\n * found.\n */\nexport function getLocalizationFile(\n locale: string,\n localizationFiles: LocalizationFile[],\n) {\n const file = localizationFiles.find(\n (localizationFile) => localizationFile.locale === locale,\n );\n\n if (!file) {\n return localizationFiles.find(\n (localizationFile) => localizationFile.locale === 'en',\n );\n }\n\n return file;\n}\n\nexport const TRANSLATION_REGEX = /\\{\\{\\s?([a-zA-Z0-9-_\\s]+)\\s?\\}\\}/gu;\n\n/**\n * Translate a string using a localization file. This will replace all instances\n * of `{{key}}` with the localized version of `key`.\n *\n * @param value - The string to translate.\n * @param file - The localization file to use, or `undefined` if no localization\n * file was found.\n * @returns The translated string.\n * @throws If the string contains a key that is not present in the localization\n * file, or if no localization file was found.\n */\nexport function translate(value: string, file: LocalizationFile | undefined) {\n const matches = value.matchAll(TRANSLATION_REGEX);\n const array = Array.from(matches);\n\n return array.reduce<string>((result, [match, key]) => {\n if (!file) {\n throw new Error(\n `Failed to translate \"${value}\": No localization file found.`,\n );\n }\n\n const translation = file.messages[key.trim()];\n if (!translation) {\n throw new Error(\n `Failed to translate \"${value}\": No translation found for \"${key.trim()}\" in \"${\n file.locale\n }\" file.`,\n );\n }\n\n return result.replace(match, translation.message);\n }, value);\n}\n\n/**\n * Get the localized Snap manifest for a given locale. This will replace all\n * localized strings in the manifest with the localized version.\n *\n * @param snapManifest - The Snap manifest to localize.\n * @param locale - The locale to use.\n * @param localizationFiles - The localization files to use.\n * @returns The localized Snap manifest.\n */\nexport function getLocalizedSnapManifest(\n snapManifest: SnapManifest,\n locale: string,\n localizationFiles: LocalizationFile[],\n) {\n const file = getLocalizationFile(locale, localizationFiles);\n\n return LOCALIZABLE_FIELDS.reduce((manifest, field) => {\n const translation = translate(manifest[field], file);\n return {\n ...manifest,\n [field]: translation,\n };\n }, snapManifest);\n}\n\n/**\n * Validate the localization files for a Snap manifest.\n *\n * @param snapManifest - The Snap manifest to validate.\n * @param localizationFiles - The localization files to validate.\n * @throws If the manifest cannot be localized.\n */\nexport function validateSnapManifestLocalizations(\n snapManifest: SnapManifest,\n localizationFiles: LocalizationFile[],\n) {\n try {\n // `translate` throws if the manifest cannot be localized, so we just attempt\n // to translate the manifest using all localization files.\n localizationFiles\n .filter((file) => file.locale !== 'en')\n .forEach((file) => {\n getLocalizedSnapManifest(snapManifest, file.locale, localizationFiles);\n });\n\n // The manifest must be localizable in English.\n getLocalizedSnapManifest(snapManifest, 'en', localizationFiles);\n } catch (error) {\n throw new Error(\n `Failed to localize Snap manifest: ${getErrorMessage(error)}`,\n );\n }\n}\n"],"names":["LOCALIZABLE_FIELDS","LocalizationFileStruct","getValidatedLocalizationFiles","getLocalizationFile","TRANSLATION_REGEX","translate","getLocalizedSnapManifest","validateSnapManifestLocalizations","object","locale","string","messages","record","message","description","optional","localizationFiles","file","result","create","parseJson","toString","error","StructError","Error","path","SyntaxError","find","localizationFile","value","matches","matchAll","array","Array","from","reduce","match","key","translation","trim","replace","snapManifest","manifest","field","filter","forEach","getErrorMessage"],"mappings":";;;;;;;;;;;IAeaA,kBAAkB;eAAlBA;;IAEAC,sBAAsB;eAAtBA;;IAoBGC,6BAA6B;eAA7BA;;IAmCAC,mBAAmB;eAAnBA;;IAiBHC,iBAAiB;eAAjBA;;IAaGC,SAAS;eAATA;;IAiCAC,wBAAwB;eAAxBA;;IAuBAC,iCAAiC;eAAjCA;;;0BA9JgB;6BASzB;sBAEmB;AAInB,MAAMP,qBAAqB;IAAC;IAAe;CAAe;AAE1D,MAAMC,yBAAyBO,IAAAA,mBAAM,EAAC;IAC3CC,QAAQC,IAAAA,mBAAM;IACdC,UAAUC,IAAAA,mBAAM,EACdF,IAAAA,mBAAM,KACNF,IAAAA,mBAAM,E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IAAI,CAACD,aAAa;YAChB,MAAM,IAAId,MACR,CAAC,qBAAqB,EAAEK,MAAM,6BAA6B,EAAEQ,IAAIE,IAAI,GAAG,MAAM,EAC5EtB,KAAKR,MAAM,CACZ,OAAO,CAAC;QAEb;QAEA,OAAOS,OAAOsB,OAAO,CAACJ,OAAOE,YAAYzB,OAAO;IAClD,GAAGgB;AACL;AAWO,SAASvB,yBACdmC,YAA0B,EAC1BhC,MAAc,EACdO,iBAAqC;IAErC,MAAMC,OAAOd,oBAAoBM,QAAQO;IAEzC,OAAOhB,mBAAmBmC,MAAM,CAAC,CAACO,UAAUC;QAC1C,MAAML,cAAcjC,UAAUqC,QAAQ,CAACC,MAAM,EAAE1B;QAC/C,OAAO;YACL,GAAGyB,QAAQ;YACX,CAACC,MAAM,EAAEL;QACX;IACF,GAAGG;AACL;AASO,SAASlC,kCACdkC,YAA0B,EAC1BzB,iBAAqC;IAErC,IAAI;QACF,6EAA6E;QAC7E,0DAA0D;QAC1DA,kBACG4B,MAAM,CAAC,CAAC3B,OAASA,KAAKR,MAAM,KAAK,MACjCoC,OAAO,CAAC,CAAC5B;YACRX,yBAAyBmC,cAAcxB,KAAKR,MAAM,EAAEO;QACtD;QAEF,+CAA+C;QAC/CV,yBAAyBmC,cAAc,MAAMzB;IAC/C,EAAE,OAAOM,OAAO;QACd,MAAM,IAAIE,MACR,CAAC,kCAAkC,EAAEsB,IAAAA,yBAAe,EAACxB,OAAO,CAAC;IAEjE;AACF"}
|
|
@@ -21,8 +21,11 @@ _export(exports, {
|
|
|
21
21
|
getSnapIcon: function() {
|
|
22
22
|
return getSnapIcon;
|
|
23
23
|
},
|
|
24
|
-
|
|
25
|
-
return
|
|
24
|
+
getSnapFilePaths: function() {
|
|
25
|
+
return getSnapFilePaths;
|
|
26
|
+
},
|
|
27
|
+
getSnapFiles: function() {
|
|
28
|
+
return getSnapFiles;
|
|
26
29
|
},
|
|
27
30
|
getWritableManifest: function() {
|
|
28
31
|
return getWritableManifest;
|
|
@@ -31,12 +34,12 @@ _export(exports, {
|
|
|
31
34
|
return validateNpmSnapManifest;
|
|
32
35
|
}
|
|
33
36
|
});
|
|
37
|
+
const _snapssdk = require("@metamask/snaps-sdk");
|
|
34
38
|
const _utils = require("@metamask/utils");
|
|
35
39
|
const _fastdeepequal = /*#__PURE__*/ _interop_require_default(require("fast-deep-equal"));
|
|
36
40
|
const _fs = require("fs");
|
|
37
41
|
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
|
|
38
42
|
const _deepclone = require("../deep-clone");
|
|
39
|
-
const _errors = require("../errors");
|
|
40
43
|
const _fs1 = require("../fs");
|
|
41
44
|
const _npm = require("../npm");
|
|
42
45
|
const _snaps = require("../snaps");
|
|
@@ -65,16 +68,19 @@ async function checkManifest(basePath, writeManifest = true, sourceCode, writeFi
|
|
|
65
68
|
const manifestFile = await (0, _fs1.readJsonFile)(manifestPath);
|
|
66
69
|
const unvalidatedManifest = manifestFile.result;
|
|
67
70
|
const packageFile = await (0, _fs1.readJsonFile)(_path.default.join(basePath, _types.NpmSnapFileNames.PackageJson));
|
|
71
|
+
const auxiliaryFilePaths = getSnapFilePaths(unvalidatedManifest, (manifest)=>manifest?.source?.files);
|
|
72
|
+
const localizationFilePaths = getSnapFilePaths(unvalidatedManifest, (manifest)=>manifest?.source?.locales);
|
|
68
73
|
const snapFiles = {
|
|
69
74
|
manifest: manifestFile,
|
|
70
75
|
packageJson: packageFile,
|
|
71
76
|
sourceCode: await getSnapSourceCode(basePath, unvalidatedManifest, sourceCode),
|
|
72
77
|
svgIcon: await getSnapIcon(basePath, unvalidatedManifest),
|
|
73
|
-
auxiliaryFiles: await
|
|
78
|
+
auxiliaryFiles: await getSnapFiles(basePath, auxiliaryFilePaths) ?? [],
|
|
79
|
+
localizationFiles: await getSnapFiles(basePath, localizationFilePaths) ?? []
|
|
74
80
|
};
|
|
75
81
|
let manifest;
|
|
76
82
|
try {
|
|
77
|
-
({ manifest } = (0, _npm.validateNpmSnap)(snapFiles));
|
|
83
|
+
({ manifest } = await (0, _npm.validateNpmSnap)(snapFiles));
|
|
78
84
|
} catch (error) {
|
|
79
85
|
if (error instanceof _snaps.ProgrammaticallyFixableSnapError) {
|
|
80
86
|
errors.push(error.message);
|
|
@@ -88,12 +94,12 @@ async function checkManifest(basePath, writeManifest = true, sourceCode, writeFi
|
|
|
88
94
|
// attempt to fix the manifest the same amount of times as there are
|
|
89
95
|
// reasons in the enum.
|
|
90
96
|
for(let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++){
|
|
91
|
-
manifest = fixManifest(manifest ? {
|
|
97
|
+
manifest = await fixManifest(manifest ? {
|
|
92
98
|
...partiallyValidatedFiles,
|
|
93
99
|
manifest
|
|
94
100
|
} : partiallyValidatedFiles, currentError);
|
|
95
101
|
try {
|
|
96
|
-
validateNpmSnapManifest({
|
|
102
|
+
await validateNpmSnapManifest({
|
|
97
103
|
...partiallyValidatedFiles,
|
|
98
104
|
manifest
|
|
99
105
|
});
|
|
@@ -144,7 +150,7 @@ async function checkManifest(basePath, writeManifest = true, sourceCode, writeFi
|
|
|
144
150
|
errors
|
|
145
151
|
};
|
|
146
152
|
}
|
|
147
|
-
function fixManifest(snapFiles, error) {
|
|
153
|
+
async function fixManifest(snapFiles, error) {
|
|
148
154
|
const { manifest, packageJson } = snapFiles;
|
|
149
155
|
const clonedFile = manifest.clone();
|
|
150
156
|
const manifestCopy = clonedFile.result;
|
|
@@ -159,7 +165,7 @@ function fixManifest(snapFiles, error) {
|
|
|
159
165
|
manifestCopy.repository = packageJson.result.repository ? (0, _deepclone.deepClone)(packageJson.result.repository) : undefined;
|
|
160
166
|
break;
|
|
161
167
|
case _types.SnapValidationFailureReason.ShasumMismatch:
|
|
162
|
-
manifestCopy.source.shasum = (0, _snaps.getSnapChecksum)(snapFiles);
|
|
168
|
+
manifestCopy.source.shasum = await (0, _snaps.getSnapChecksum)(snapFiles);
|
|
163
169
|
break;
|
|
164
170
|
/* istanbul ignore next */ default:
|
|
165
171
|
(0, _utils.assertExhaustive)(error.reason);
|
|
@@ -186,7 +192,7 @@ async function getSnapSourceCode(basePath, manifest, sourceCode) {
|
|
|
186
192
|
const virtualFile = await (0, _virtualfile.readVirtualFile)(_path.default.join(basePath, sourceFilePath), 'utf8');
|
|
187
193
|
return virtualFile;
|
|
188
194
|
} catch (error) {
|
|
189
|
-
throw new Error(`Failed to read snap bundle file: ${(0,
|
|
195
|
+
throw new Error(`Failed to read snap bundle file: ${(0, _snapssdk.getErrorMessage)(error)}`);
|
|
190
196
|
}
|
|
191
197
|
}
|
|
192
198
|
async function getSnapIcon(basePath, manifest) {
|
|
@@ -201,21 +207,28 @@ async function getSnapIcon(basePath, manifest) {
|
|
|
201
207
|
const virtualFile = await (0, _virtualfile.readVirtualFile)(_path.default.join(basePath, iconPath), 'utf8');
|
|
202
208
|
return virtualFile;
|
|
203
209
|
} catch (error) {
|
|
204
|
-
throw new Error(`Failed to read snap icon file: ${(0,
|
|
210
|
+
throw new Error(`Failed to read snap icon file: ${(0, _snapssdk.getErrorMessage)(error)}`);
|
|
205
211
|
}
|
|
206
212
|
}
|
|
207
|
-
|
|
213
|
+
function getSnapFilePaths(manifest, selector) {
|
|
208
214
|
if (!(0, _utils.isPlainObject)(manifest)) {
|
|
209
215
|
return undefined;
|
|
210
216
|
}
|
|
211
|
-
const
|
|
212
|
-
|
|
217
|
+
const snapManifest = manifest;
|
|
218
|
+
const paths = selector(snapManifest);
|
|
219
|
+
if (!Array.isArray(paths)) {
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
return paths;
|
|
223
|
+
}
|
|
224
|
+
async function getSnapFiles(basePath, paths) {
|
|
225
|
+
if (!paths) {
|
|
213
226
|
return undefined;
|
|
214
227
|
}
|
|
215
228
|
try {
|
|
216
|
-
return await Promise.all(
|
|
229
|
+
return await Promise.all(paths.map(async (filePath)=>(0, _virtualfile.readVirtualFile)(_path.default.join(basePath, filePath), 'utf8')));
|
|
217
230
|
} catch (error) {
|
|
218
|
-
throw new Error(`Failed to read snap files: ${(0,
|
|
231
|
+
throw new Error(`Failed to read snap files: ${(0, _snapssdk.getErrorMessage)(error)}`);
|
|
219
232
|
}
|
|
220
233
|
}
|
|
221
234
|
function getWritableManifest(manifest) {
|
|
@@ -230,7 +243,7 @@ function getWritableManifest(manifest) {
|
|
|
230
243
|
}), {});
|
|
231
244
|
return writableManifest;
|
|
232
245
|
}
|
|
233
|
-
function validateNpmSnapManifest({ manifest, packageJson, sourceCode, svgIcon, auxiliaryFiles }) {
|
|
246
|
+
async function validateNpmSnapManifest({ manifest, packageJson, sourceCode, svgIcon, auxiliaryFiles, localizationFiles }) {
|
|
234
247
|
const packageJsonName = packageJson.result.name;
|
|
235
248
|
const packageJsonVersion = packageJson.result.version;
|
|
236
249
|
const packageJsonRepository = packageJson.result.repository;
|
|
@@ -248,11 +261,12 @@ function validateNpmSnapManifest({ manifest, packageJson, sourceCode, svgIcon, a
|
|
|
248
261
|
(packageJsonRepository || manifestRepository) && !(0, _fastdeepequal.default)(packageJsonRepository, manifestRepository)) {
|
|
249
262
|
throw new _snaps.ProgrammaticallyFixableSnapError(`"${_types.NpmSnapFileNames.Manifest}" "repository" field does not match the "${_types.NpmSnapFileNames.PackageJson}" "repository" field.`, _types.SnapValidationFailureReason.RepositoryMismatch);
|
|
250
263
|
}
|
|
251
|
-
(0, _snaps.validateSnapShasum)({
|
|
264
|
+
await (0, _snaps.validateSnapShasum)({
|
|
252
265
|
manifest,
|
|
253
266
|
sourceCode,
|
|
254
267
|
svgIcon,
|
|
255
|
-
auxiliaryFiles
|
|
268
|
+
auxiliaryFiles,
|
|
269
|
+
localizationFiles
|
|
256
270
|
}, `"${_types.NpmSnapFileNames.Manifest}" "shasum" field does not match computed shasum.`);
|
|
257
271
|
}
|
|
258
272
|
|
|
@@ -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":["checkManifest","fixManifest","getSnapSourceCode","getSnapIcon","getSnapAuxiliaryFiles","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","snapFiles","manifest","packageJson","svgIcon","auxiliaryFiles","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","filePaths","files","Promise","all","map","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository","deepEqual","validateSnapShasum"],"mappings":";;;;;;;;;;;IAkEsBA,aAAa;eAAbA;;IA+INC,WAAW;eAAXA;;IA8CMC,iBAAiB;eAAjBA;;IA4CAC,WAAW;eAAXA;;IAkCAC,qBAAqB;eAArBA;;IAgCNC,mBAAmB;eAAnBA;;IA+BAC,uBAAuB;eAAvBA;;;uBA3YwC;sEAClC;oBACS;6DACT;2BAEI;wBACM;qBACH;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,eAAef,cACpBgB,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,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EAAED,uBAAgB,CAACO,WAAW,CAAC,qBAAqB,CAAC,EAC5HiB,kCAA2B,CAAC4B,kBAAkB;IAElD;IAEAiC,IAAAA,yBAAkB,EAChB;QAAE5E;QAAUnB;QAAYqB;QAASC;IAAe,GAChD,CAAC,CAAC,EAAEZ,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 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;eAAXA;;IAiCNC,gBAAgB;eAAhBA;;IA0BMC,YAAY;eAAZA;;IA0BNC,mBAAmB;eAAnBA;;IAgCMC,uBAAuB;eAAvBA;;;0BA9aU;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,MAA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AC,CAAC,EAAEpB,uBAAgB,CAACC,QAAQ,CAAC,yCAAyC,EAAED,uBAAgB,CAACO,WAAW,CAAC,qBAAqB,CAAC,EAC5HsB,kCAA2B,CAAC4B,kBAAkB;IAElD;IAEA,MAAMoC,IAAAA,yBAAkB,EACtB;QAAEpF;QAAUnB;QAAYyB;QAASC;QAAgBC;IAAkB,GACnE,CAAC,CAAC,EAAEjB,uBAAgB,CAACC,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
|
|
@@ -156,7 +156,7 @@ const SnapAuxilaryFilesStruct = (0, _superstruct.array)((0, _superstruct.string)
|
|
|
156
156
|
const SnapManifestStruct = (0, _superstruct.object)({
|
|
157
157
|
version: _utils.VersionStruct,
|
|
158
158
|
description: (0, _superstruct.size)((0, _superstruct.string)(), 1, 280),
|
|
159
|
-
proposedName: (0, _superstruct.size)((0, _superstruct.
|
|
159
|
+
proposedName: (0, _superstruct.size)((0, _superstruct.string)(), 1, 214),
|
|
160
160
|
repository: (0, _superstruct.optional)((0, _superstruct.object)({
|
|
161
161
|
type: (0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity),
|
|
162
162
|
url: (0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity)
|
|
@@ -174,7 +174,8 @@ const SnapManifestStruct = (0, _superstruct.object)({
|
|
|
174
174
|
])
|
|
175
175
|
})
|
|
176
176
|
}),
|
|
177
|
-
files: (0, _superstruct.optional)(SnapAuxilaryFilesStruct)
|
|
177
|
+
files: (0, _superstruct.optional)(SnapAuxilaryFilesStruct),
|
|
178
|
+
locales: (0, _superstruct.optional)(SnapAuxilaryFilesStruct)
|
|
178
179
|
}),
|
|
179
180
|
initialPermissions: PermissionsStruct,
|
|
180
181
|
manifestVersion: (0, _superstruct.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":["FORBIDDEN_COIN_TYPES","Bip32PathStruct","bip32entropy","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","SemVerRangeStruct","SnapIdsStruct","ChainIdsStruct","PermissionsStruct","SnapAuxilaryFilesStruct","SnapManifestStruct","isSnapManifest","assertIsSnapManifest","createSnapManifest","FORBIDDEN_PURPOSES","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","FORBIDDEN_PATHS","map","coinType","refine","array","string","path","length","slice","some","part","isValidBIP32PathSegment","includes","forbiddenPath","isEqual","join","struct","value","curve","endsWith","type","enums","size","Infinity","isValidSemVerRange","record","SnapIdStruct","object","version","optional","Object","keys","ChainIdStruct","allowTransactionOrigin","boolean","jobs","CronjobSpecificationArrayStruct","RpcOriginsStruct","KeyringOriginsStruct","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","integer","snap_getEntropy","wallet_snap","VersionStruct","description","proposedName","pattern","repository","url","source","shasum","ChecksumStruct","location","npm","filePath","iconPath","packageName","NameStruct","registry","union","literal","files","initialPermissions","manifestVersion","$schema","is","assertStruct","NpmSnapFileNames","Manifest","create"],"mappings":";;;;;;;;;;;IA0CaA,oBAAoB;eAApBA;;IAOAC,eAAe;eAAfA;;IAsCAC,YAAY;eAAZA;;IAkBAC,kBAAkB;eAAlBA;;IASAC,oCAAoC;eAApCA;;IAMAC,iBAAiB;eAAjBA;;IAOAC,aAAa;eAAbA;;IAcAC,cAAc;eAAdA;;IAGAC,iBAAiB;eAAjBA;;IAoCAC,uBAAuB;eAAvBA;;I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AACjB,IAAAA,mBAAM,KAAI,GAAGkB;QACxBgC,KAAKjC,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;IACzB;IAEFiC,QAAQ7B,IAAAA,mBAAM,EAAC;QACb8B,QAAQC,qBAAc;QACtBC,UAAUhC,IAAAA,mBAAM,EAAC;YACfiC,KAAKjC,IAAAA,mBAAM,EAAC;gBACVkC,UAAUvC,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;gBAC5BuC,UAAUjC,IAAAA,qBAAQ,EAACP,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;gBACrCwC,aAAaC,iBAAU;gBACvBC,UAAUC,IAAAA,kBAAK,EAAC;oBACdC,IAAAA,oBAAO,EAAC;oBACRA,IAAAA,oBAAO,EAAC;iBACT;YACH;QACF;QACAC,OAAOvC,IAAAA,qBAAQ,EAACrC;IAClB;IACA6E,oBAAoB9E;IACpB+E,iBAAiBH,IAAAA,oBAAO,EAAC;IACzBI,SAAS1C,IAAAA,qBAAQ,EAACxB,IAAAA,mBAAM;AAC1B;AAUO,SAASX,eAAeuB,KAAc;IAC3C,OAAOuD,IAAAA,eAAE,EAACvD,OAAOxB;AACnB;AAQO,SAASE,qBACdsB,KAAc;IAEdwD,IAAAA,mBAAY,EACVxD,OACAxB,oBACA,CAAC,CAAC,EAAEiF,uBAAgB,CAACC,QAAQ,CAAC,YAAY,CAAC;AAE/C;AASO,SAAS/E,mBAAmBqB,KAAc;IAC/C,qEAAqE;IACrE,OAAO2D,IAAAA,mBAAM,EAAC3D,OAAOxB;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":["FORBIDDEN_COIN_TYPES","Bip32PathStruct","bip32entropy","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","SemVerRangeStruct","SnapIdsStruct","ChainIdsStruct","PermissionsStruct","SnapAuxilaryFilesStruct","SnapManifestStruct","isSnapManifest","assertIsSnapManifest","createSnapManifest","FORBIDDEN_PURPOSES","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","FORBIDDEN_PATHS","map","coinType","refine","array","string","path","length","slice","some","part","isValidBIP32PathSegment","includes","forbiddenPath","isEqual","join","struct","value","curve","endsWith","type","enums","size","Infinity","isValidSemVerRange","record","SnapIdStruct","object","version","optional","Object","keys","ChainIdStruct","allowTransactionOrigin","boolean","jobs","CronjobSpecificationArrayStruct","RpcOriginsStruct","KeyringOriginsStruct","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","integer","snap_getEntropy","wallet_snap","VersionStruct","description","proposedName","repository","url","source","shasum","ChecksumStruct","location","npm","filePath","iconPath","packageName","NameStruct","registry","union","literal","files","locales","initialPermissions","manifestVersion","$schema","is","assertStruct","NpmSnapFileNames","Manifest","create"],"mappings":";;;;;;;;;;;IA2CaA,oBAAoB;eAApBA;;IAOAC,eAAe;eAAfA;;IAsCAC,YAAY;eAAZA;;IAkBAC,kBAAkB;eAAlBA;;IASAC,oCAAoC;eAApCA;;IAMAC,iBAAiB;eAAjBA;;IAOAC,aAAa;eAAbA;;IAcAC,cAAc;eAAdA;;IAGAC,iBAAiB;eAAjBA;;IAuCAC,uBAAuB;eAAvBA;;IAEAC,kBAAkB;eAAlBA;;IAuCGC,cAAc;eAAdA;;IAUAC,oBAAoB;eAApBA;;IAiBAC,kBAAkB;eAAlBA;;;yBA5PwB;uBAOjC;6BAkBA;uBAEiB;yBACwB;yBACgB;yBACT;2BACzB;uBACD;uBAEgB;A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;YACfgC,KAAKhC,IAAAA,mBAAM,EAAC;gBACViC,UAAUtC,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;gBAC5BsC,UAAUhC,IAAAA,qBAAQ,EAACP,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;gBACrCuC,aAAaC,iBAAU;gBACvBC,UAAUC,IAAAA,kBAAK,EAAC;oBACdC,IAAAA,oBAAO,EAAC;oBACRA,IAAAA,oBAAO,EAAC;iBACT;YACH;QACF;QACAC,OAAOtC,IAAAA,qBAAQ,EAACrC;QAChB4E,SAASvC,IAAAA,qBAAQ,EAACrC;IACpB;IACA6E,oBAAoB9E;IACpB+E,iBAAiBJ,IAAAA,oBAAO,EAAC;IACzBK,SAAS1C,IAAAA,qBAAQ,EAACxB,IAAAA,mBAAM;AAC1B;AAUO,SAASX,eAAeuB,KAAc;IAC3C,OAAOuD,IAAAA,eAAE,EAACvD,OAAOxB;AACnB;AAQO,SAASE,qBACdsB,KAAc;IAEdwD,IAAAA,mBAAY,EACVxD,OACAxB,oBACA,CAAC,CAAC,EAAEiF,uBAAgB,CAACC,QAAQ,CAAC,YAAY,CAAC;AAE/C;AASO,SAAS/E,mBAAmBqB,KAAc;IAC/C,qEAAqE;IACrE,OAAO2D,IAAAA,mBAAM,EAAC3D,OAAOxB;AACvB"}
|
package/dist/cjs/namespace.js
CHANGED
|
@@ -27,6 +27,9 @@ _export(exports, {
|
|
|
27
27
|
LimitedString: function() {
|
|
28
28
|
return LimitedString;
|
|
29
29
|
},
|
|
30
|
+
ChainIdStringStruct: function() {
|
|
31
|
+
return ChainIdStringStruct;
|
|
32
|
+
},
|
|
30
33
|
ChainIdStruct: function() {
|
|
31
34
|
return ChainIdStruct;
|
|
32
35
|
},
|
|
@@ -93,7 +96,8 @@ function parseAccountId(accountId) {
|
|
|
93
96
|
};
|
|
94
97
|
}
|
|
95
98
|
const LimitedString = (0, _superstruct.size)((0, _superstruct.string)(), 1, 40);
|
|
96
|
-
const
|
|
99
|
+
const ChainIdStringStruct = (0, _superstruct.define)('Chain ID', (0, _superstruct.string)().validator);
|
|
100
|
+
const ChainIdStruct = (0, _superstruct.pattern)(ChainIdStringStruct, CHAIN_ID_REGEX);
|
|
97
101
|
const AccountIdStruct = (0, _superstruct.pattern)((0, _superstruct.string)(), ACCOUNT_ID_REGEX);
|
|
98
102
|
const AccountIdArrayStruct = (0, _superstruct.array)(AccountIdStruct);
|
|
99
103
|
const AccountAddressStruct = (0, _superstruct.pattern)((0, _superstruct.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":["CHAIN_ID_REGEX","ACCOUNT_ID_REGEX","ACCOUNT_ADDRESS_REGEX","parseChainId","parseAccountId","LimitedString","ChainIdStringStruct","ChainIdStruct","AccountIdStruct","AccountIdArrayStruct","AccountAddressStruct","ChainStruct","NamespaceStruct","NamespaceIdStruct","isNamespaceId","isChainId","isAccountId","isAccountIdArray","isNamespace","chainId","match","exec","groups","Error","namespace","reference","accountId","address","accountAddress","chain","size","string","define","validator","pattern","array","object","id","name","chains","methods","optional","events","value","is"],"mappings":";;;;;;;;;;;IAeaA,cAAc;eAAdA;;IAGAC,gBAAgB;eAAhBA;;IAGAC,qBAAqB;eAArBA;;IASGC,YAAY;eAAZA;;IAsBAC,cAAc;eAAdA;;IAwBHC,aAAa;eAAbA;;IAEAC,mBAAmB;eAAnBA;;IAQAC,aAAa;eAAbA;;IAOAC,eAAe;eAAfA;;IAEAC,oBAAoB;eAApBA;;IAC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