@metamask/snaps-utils 0.25.0 → 0.26.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.
@@ -9,5 +9,5 @@ export * from './notification';
9
9
  export * from './object';
10
10
  export * from './snaps';
11
11
  export * from './types';
12
- export * from './url';
13
12
  export * from './versions';
13
+ export * from './virtual-file/index.browser';
@@ -25,6 +25,6 @@ __exportStar(require("./notification"), exports);
25
25
  __exportStar(require("./object"), exports);
26
26
  __exportStar(require("./snaps"), exports);
27
27
  __exportStar(require("./types"), exports);
28
- __exportStar(require("./url"), exports);
29
28
  __exportStar(require("./versions"), exports);
29
+ __exportStar(require("./virtual-file/index.browser"), exports);
30
30
  //# sourceMappingURL=index.browser.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.browser.js","sourceRoot":"","sources":["../src/index.browser.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA0B;AAC1B,+CAA6B;AAC7B,uDAAqC;AACrC,4CAA0B;AAC1B,6CAA2B;AAC3B,2DAAyC;AACzC,8CAA4B;AAC5B,iDAA+B;AAC/B,2CAAyB;AACzB,0CAAwB;AACxB,0CAAwB;AACxB,wCAAsB;AACtB,6CAA2B","sourcesContent":["export * from './caveats';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './flatMap';\nexport * from './json-rpc';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './notification';\nexport * from './object';\nexport * from './snaps';\nexport * from './types';\nexport * from './url';\nexport * from './versions';\n"]}
1
+ {"version":3,"file":"index.browser.js","sourceRoot":"","sources":["../src/index.browser.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA0B;AAC1B,+CAA6B;AAC7B,uDAAqC;AACrC,4CAA0B;AAC1B,6CAA2B;AAC3B,2DAAyC;AACzC,8CAA4B;AAC5B,iDAA+B;AAC/B,2CAAyB;AACzB,0CAAwB;AACxB,0CAAwB;AACxB,6CAA2B;AAC3B,+DAA6C","sourcesContent":["export * from './caveats';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './flatMap';\nexport * from './json-rpc';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './notification';\nexport * from './object';\nexport * from './snaps';\nexport * from './types';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"]}
package/dist/index.d.ts CHANGED
@@ -15,5 +15,5 @@ export * from './object';
15
15
  export * from './post-process';
16
16
  export * from './snaps';
17
17
  export * from './types';
18
- export * from './url';
19
18
  export * from './versions';
19
+ export * from './virtual-file';
package/dist/index.js CHANGED
@@ -31,6 +31,6 @@ __exportStar(require("./object"), exports);
31
31
  __exportStar(require("./post-process"), exports);
32
32
  __exportStar(require("./snaps"), exports);
33
33
  __exportStar(require("./types"), exports);
34
- __exportStar(require("./url"), exports);
35
34
  __exportStar(require("./versions"), exports);
35
+ __exportStar(require("./virtual-file"), exports);
36
36
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA0B;AAC1B,4CAA0B;AAC1B,+CAA6B;AAC7B,uDAAqC;AACrC,yCAAuB;AACvB,4CAA0B;AAC1B,uCAAqB;AACrB,6CAA2B;AAC3B,6CAA2B;AAC3B,yCAAuB;AACvB,8CAA4B;AAC5B,iDAA+B;AAC/B,wCAAsB;AACtB,2CAAyB;AACzB,iDAA+B;AAC/B,0CAAwB;AACxB,0CAAwB;AACxB,wCAAsB;AACtB,6CAA2B","sourcesContent":["export * from './caveats';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './eval';\nexport * from './flatMap';\nexport * from './fs';\nexport * from './json-rpc';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './notification';\nexport * from './npm';\nexport * from './object';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './types';\nexport * from './url';\nexport * from './versions';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA0B;AAC1B,4CAA0B;AAC1B,+CAA6B;AAC7B,uDAAqC;AACrC,yCAAuB;AACvB,4CAA0B;AAC1B,uCAAqB;AACrB,6CAA2B;AAC3B,6CAA2B;AAC3B,yCAAuB;AACvB,8CAA4B;AAC5B,iDAA+B;AAC/B,wCAAsB;AACtB,2CAAyB;AACzB,iDAA+B;AAC/B,0CAAwB;AACxB,0CAAwB;AACxB,6CAA2B;AAC3B,iDAA+B","sourcesContent":["export * from './caveats';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './eval';\nexport * from './flatMap';\nexport * from './fs';\nexport * from './json-rpc';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './notification';\nexport * from './npm';\nexport * from './object';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './types';\nexport * from './versions';\nexport * from './virtual-file';\n"]}
@@ -186,8 +186,9 @@ function postProcessBundle(code, { stripComments = true, sourceMap: sourceMaps,
186
186
  // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.
187
187
  if (node.property.type === 'Identifier' &&
188
188
  node.property.name === 'eval' &&
189
- // If the expression is already wrapped we can ignore it
190
- path.parent.type !== 'SequenceExpression') {
189
+ // We only apply this to MemberExpressions that are the callee of CallExpression
190
+ path.parent.type === 'CallExpression' &&
191
+ path.parent.callee === node) {
191
192
  path.replaceWith(objectEvalWrapper({
192
193
  OBJECT: node.object,
193
194
  REF: node.property,
@@ -1 +1 @@
1
- {"version":3,"file":"post-process.js","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings":";;;AAAA,wDAAwD;AACxD,sCAAgF;AAChF,wCAQsB;AAgDtB,IAAY,kBAEX;AAFD,WAAY,kBAAkB;IAC5B,+HAAyG,CAAA;AAC3G,CAAC,EAFW,kBAAkB,GAAlB,0BAAkB,K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,IAAI,CAAE,IAAI,CAAA,EAAE;YACf,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;SAC3C;QAED,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,SAAS,EAAE,IAAI,CAAC,GAAG;YACnB,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC;SAC/B,CAAC;KACH;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAI,KAAK,CAAC,iCAAiC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;KACnE;AACH,CAAC;AAnQD,8CAmQC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-shadow\nimport { transformSync, Node, Visitor, template, PluginObj } from '@babel/core';\nimport {\n binaryExpression,\n Expression,\n Identifier,\n stringLiteral,\n TemplateElement,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the bundle. This is not a secure source of randomness.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // @ts-expect-error `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // If the expression is already wrapped we can ignore it\n path.parent.type !== 'SequenceExpression'\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const source = path.getSource();\n\n // Throw an error if HTML comments are used as a binary expression.\n if (source.includes('<!--') || source.includes('-->')) {\n throw new Error(\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.',\n );\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"]}
1
+ {"version":3,"file":"post-process.js","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings":";;;AAAA,wDAAwD;AACxD,sCAAgF;AAChF,wCAQsB;AAgDtB,IAAY,kBAEX;AAFD,WAAY,kBAAkB;IAC5B,+HAAyG,CAAA;AAC3G,CAAC,EAFW,kBAAkB,GAAlB,0BAAkB,KAAlB,0BAAkB,QAE7B;AAED,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAM,WAAW,GAAG,sCAAsC,CAAC;AAE3D,4EAA4E;AAC5E,cAAc;AACd,MAAM,sBAAsB,GAAG,IAAA,uBAAe,EAAC,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC;AAExE,MAAM,WAAW,GAAG,eAAQ,CAAC,SAAS,CAAC;;CAEtC,CAAC,CAAC;AAEH,MAAM,iBAAiB,GAAG,eAAQ,CAAC,SAAS,CAAC;;CAE5C,CAAC,CAAC;AAEH,MAAM,yBAAyB,GAAG,eAAQ,CAAC,SAAS,CAAC;;CAEpD,CAAC,CAAC;AAEH;;;;;;;;;;;GAWG;AACH,SAAS,WAAW,CAAC,KAAa;IAChC,MAAM,MAAM,GAAG,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IACxC,OAAO,CACL,MAAM;QACJ,oEAAoE;QACpE,sEAAsE;SACrE,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,EAAE,IAAI,KAAK,KAAK,SAAS,CAAC,CAC1D,CAA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,CACrB,CAAC;aACH;QACH,CAAC;KACF,CAAC;IAEF,IAAI;QACF,MAAM,IAAI,GAAG,IAAA,oBAAa,EAAC,IAAI,EAAE;YAC/B,kDAAkD;YAClD,UAAU,EAAE,KAAK;YAEjB,UAAU,EAAE;gBACV,sEAAsE;gBACtE,UAAU,EAAE,IAAI;gBAEhB,sEAAsE;gBACtE,wEAAwE;gBACxE,aAAa,EAAE,CAAC,aAAa;aAC9B;YAED,mEAAmE;YACnE,yEAAyE;YACzE,OAAO,EAAE,KAAK;YAEd,uEAAuE;YACvE,wEAAwE;YACxE,mEAAmE;YACnE,cAAc;YACd,UAAU;YAEV,OAAO,EAAE;gBACP,GAAG,EAAE,CAAC,CAAC;oBACL,GAAG;oBACH,OAAO;iBACR,CAAC;aACH;SACF,CAAC,CAAC;QAEH,IAAI,CAAC,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,IAAI,CAAA,EAAE;YACf,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;SAC3C;QAED,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,SAAS,EAAE,IAAI,CAAC,GAAG;YACnB,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC;SAC/B,CAAC;KACH;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAI,KAAK,CAAC,iCAAiC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;KACnE;AACH,CAAC;AApQD,8CAoQC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-shadow\nimport { transformSync, Node, Visitor, template, PluginObj } from '@babel/core';\nimport {\n binaryExpression,\n Expression,\n Identifier,\n stringLiteral,\n TemplateElement,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the bundle. This is not a secure source of randomness.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // @ts-expect-error `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const source = path.getSource();\n\n // Throw an error if HTML comments are used as a binary expression.\n if (source.includes('<!--') || source.includes('-->')) {\n throw new Error(\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.',\n );\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"]}
package/dist/snaps.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { Json } from '@metamask/utils';
2
2
  import { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';
3
+ import { Struct } from 'superstruct';
3
4
  import { SnapManifest, SnapPermissions } from './manifest/validation';
4
5
  import { SnapId, SnapIdPrefixes, SnapValidationFailureReason } from './types';
5
6
  import { SemVerVersion } from './versions';
6
- export declare const LOCALHOST_HOSTNAMES: Set<string>;
7
7
  export declare const SNAP_PREFIX = "wallet_snap_";
8
8
  export declare const SNAP_PREFIX_REGEX: RegExp;
9
9
  export declare const PROPOSED_NAME_REGEX: RegExp;
@@ -136,6 +136,10 @@ export declare type ValidatedSnapId = `local:${string}` | `npm:${string}`;
136
136
  * @param errorMessage - The error message to throw if validation fails.
137
137
  */
138
138
  export declare function validateSnapShasum(manifest: SnapManifest, sourceCode: string, errorMessage?: string): void;
139
+ export declare const LOCALHOST_HOSTNAMES: readonly ["localhost", "127.0.0.1", "[::1]"];
140
+ export declare const LocalSnapIdStruct: Struct<string, null>;
141
+ export declare const NpmSnapIdStruct: Struct<string, null>;
142
+ export declare const HttpSnapIdStruct: Struct<string, null>;
139
143
  /**
140
144
  * Extracts the snap prefix from a snap ID.
141
145
  *
package/dist/snaps.js CHANGED
@@ -1,10 +1,15 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isCaipChainId = exports.validateSnapId = exports.getSnapPermissionName = exports.getSnapPrefix = exports.validateSnapShasum = exports.getSnapSourceShasum = exports.ProgrammaticallyFixableSnapError = exports.SnapStatusEvents = exports.SnapStatus = exports.PROPOSED_NAME_REGEX = exports.SNAP_PREFIX_REGEX = exports.SNAP_PREFIX = exports.LOCALHOST_HOSTNAMES = void 0;
6
+ exports.isCaipChainId = exports.validateSnapId = exports.getSnapPermissionName = exports.getSnapPrefix = exports.HttpSnapIdStruct = exports.NpmSnapIdStruct = exports.LocalSnapIdStruct = exports.LOCALHOST_HOSTNAMES = exports.validateSnapShasum = exports.getSnapSourceShasum = exports.ProgrammaticallyFixableSnapError = exports.SnapStatusEvents = exports.SnapStatus = exports.PROPOSED_NAME_REGEX = exports.SNAP_PREFIX_REGEX = exports.SNAP_PREFIX = void 0;
7
+ const utils_1 = require("@metamask/utils");
4
8
  const sha256_1 = require("@noble/hashes/sha256");
5
9
  const base_1 = require("@scure/base");
10
+ const superstruct_1 = require("superstruct");
11
+ const validate_npm_package_name_1 = __importDefault(require("validate-npm-package-name"));
6
12
  const types_1 = require("./types");
7
- exports.LOCALHOST_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1']);
8
13
  exports.SNAP_PREFIX = 'wallet_snap_';
9
14
  exports.SNAP_PREFIX_REGEX = new RegExp(`^${exports.SNAP_PREFIX}`, 'u');
10
15
  // This RegEx matches valid npm package names (with some exceptions) and space-
@@ -67,6 +72,50 @@ function validateSnapShasum(manifest, sourceCode, errorMessage = 'Invalid Snap m
67
72
  }
68
73
  }
69
74
  exports.validateSnapShasum = validateSnapShasum;
75
+ exports.LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'];
76
+ const LocalSnapIdSubUrlStruct = (0, types_1.uri)({
77
+ protocol: (0, superstruct_1.enums)(['http:', 'https:']),
78
+ hostname: (0, superstruct_1.enums)(exports.LOCALHOST_HOSTNAMES),
79
+ hash: (0, superstruct_1.empty)((0, superstruct_1.string)()),
80
+ search: (0, superstruct_1.empty)((0, superstruct_1.string)()),
81
+ });
82
+ exports.LocalSnapIdStruct = (0, superstruct_1.refine)((0, superstruct_1.string)(), 'local Snap Id', (value) => {
83
+ if (!value.startsWith(types_1.SnapIdPrefixes.local)) {
84
+ return `Expected local Snap ID, got "${value}".`;
85
+ }
86
+ const [error] = (0, superstruct_1.validate)(value.slice(types_1.SnapIdPrefixes.local.length), LocalSnapIdSubUrlStruct);
87
+ return error !== null && error !== void 0 ? error : true;
88
+ });
89
+ exports.NpmSnapIdStruct = (0, superstruct_1.intersection)([
90
+ (0, superstruct_1.string)(),
91
+ (0, types_1.uri)({
92
+ protocol: (0, superstruct_1.literal)(types_1.SnapIdPrefixes.npm),
93
+ pathname: (0, superstruct_1.refine)((0, superstruct_1.string)(), 'package name', function* (value) {
94
+ const normalized = value.startsWith('/') ? value.slice(1) : value;
95
+ const { errors, validForNewPackages, warnings } = (0, validate_npm_package_name_1.default)(normalized);
96
+ if (!validForNewPackages) {
97
+ if (errors === undefined) {
98
+ (0, utils_1.assert)(warnings !== undefined);
99
+ yield* warnings;
100
+ }
101
+ else {
102
+ yield* errors;
103
+ }
104
+ }
105
+ return true;
106
+ }),
107
+ search: (0, superstruct_1.empty)((0, superstruct_1.string)()),
108
+ hash: (0, superstruct_1.empty)((0, superstruct_1.string)()),
109
+ }),
110
+ ]);
111
+ exports.HttpSnapIdStruct = (0, superstruct_1.intersection)([
112
+ (0, superstruct_1.string)(),
113
+ (0, types_1.uri)({
114
+ protocol: (0, superstruct_1.enums)(['http:', 'https:']),
115
+ search: (0, superstruct_1.empty)((0, superstruct_1.string)()),
116
+ hash: (0, superstruct_1.empty)((0, superstruct_1.string)()),
117
+ }),
118
+ ]);
70
119
  /**
71
120
  * Extracts the snap prefix from a snap ID.
72
121
  *
@@ -106,7 +155,7 @@ function validateSnapId(snapId) {
106
155
  return;
107
156
  }
108
157
  }
109
- throw new Error(`Invalid snap id. Unknown prefix. Received: "${snapId}"`);
158
+ throw new Error(`Invalid snap id. Unknown prefix. Received: "${snapId}".`);
110
159
  }
111
160
  exports.validateSnapId = validateSnapId;
112
161
  /**
package/dist/snaps.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"snaps.js","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";;;AACA,iDAA8C;AAC9C,sCAAqC;AAIrC,mCAA8E;AAGjE,QAAA,mBAAmB,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,WAAW,EAAE,KAAK,CAAC,CAAC,CAAC;AACjE,QAAA,WAAW,GAAG,cAAc,CAAC;AAE7B,QAAA,iBAAiB,GAAG,IAAI,MAAM,CAAC,IAAI,mBAAW,EAAE,EAAE,GAAG,CAAC,CAAC;AAEpE,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACtH,QAAA,mBAAmB,GAC9B,kHAAkH,CAAC;AAarH,IAAY,UAMX;AAND,WAAY,UAA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IACD,MAAM,IAAI,KAAK,CAAC,mCAAmC,MAAM,GAAG,CAAC,CAAC;AAChE,CAAC;AARD,sCAQC;AAED;;;;;GAKG;AACH,SAAgB,qBAAqB,CAAC,MAAc;IAClD,OAAO,mBAAW,GAAG,MAAM,CAAC;AAC9B,CAAC;AAFD,sDAEC;AAED;;;;;GAKG;AACH,SAAgB,cAAc,CAC5B,MAAe;IAEf,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;QACzC,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;KACnD;IAED,KAAK,MAAM,MAAM,IAAI,MAAM,CAAC,MAAM,CAAC,sBAAc,CAAC,EAAE;QAClD,IAAI,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACtE,OAAO;SACR;KACF;IAED,MAAM,IAAI,KAAK,CAAC,+CAA+C,MAAM,GAAG,CAAC,CAAC;AAC5E,CAAC;AAdD,wCAcC;AAED;;;;;GAKG;AACH,SAAgB,aAAa,CAAC,OAAgB;IAC5C,OAAO,CACL,OAAO,OAAO,KAAK,QAAQ;QAC3B,kEAAkE,CAAC,IAAI,CACrE,OAAO,CACR,CACF,CAAC;AACJ,CAAC;AAPD,sCAOC","sourcesContent":["import { Json } from '@metamask/utils';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { base64 } from '@scure/base';\nimport { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';\n\nimport { SnapManifest, SnapPermissions } from './manifest/validation';\nimport { SnapId, SnapIdPrefixes, SnapValidationFailureReason } from './types';\nimport { SemVerVersion } from './versions';\n\nexport const LOCALHOST_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1']);\nexport const SNAP_PREFIX = 'wallet_snap_';\n\nexport const SNAP_PREFIX_REGEX = new RegExp(`^${SNAP_PREFIX}`, 'u');\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\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/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport type BlockedSnapInfo = { infoUrl?: string; reason?: string };\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: string };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type PersistedSnap = Snap & {\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n};\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: SnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockedSnapInfo;\n\n /**\n * The name of the permission used to invoke the Snap.\n */\n permissionName: string;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'permissionName'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult =\n | TruncatedSnap\n | { error: SerializedEthereumRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of a Snap source code string.\n *\n * @param sourceCode - The UTF-8 string source code of a Snap.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapSourceShasum(sourceCode: string): string {\n return base64.encode(sha256(sourceCode));\n}\n\nexport type ValidatedSnapId = `local:${string}` | `npm:${string}`;\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of a snap source code string.\n *\n * @param manifest - The manifest whose shasum to validate.\n * @param sourceCode - The source code of the snap.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n manifest: SnapManifest,\n sourceCode: string,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (manifest.source.shasum !== getSnapSourceShasum(sourceCode)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Computes the permission name of a snap from its snap ID.\n *\n * @param snapId - The snap ID.\n * @returns The permission name corresponding to the given snap ID.\n */\nexport function getSnapPermissionName(snapId: string): string {\n return SNAP_PREFIX + snapId;\n}\n\n/**\n * Asserts the provided object is a snapId with a supported prefix.\n *\n * @param snapId - The object to validate.\n * @throws {@link Error}. If the validation fails.\n */\nexport function validateSnapId(\n snapId: unknown,\n): asserts snapId is ValidatedSnapId {\n if (!snapId || typeof snapId !== 'string') {\n throw new Error(`Invalid snap id. Not a string.`);\n }\n\n for (const prefix of Object.values(SnapIdPrefixes)) {\n if (snapId.startsWith(prefix) && snapId.replace(prefix, '').length > 0) {\n return;\n }\n }\n\n throw new Error(`Invalid snap id. Unknown prefix. Received: \"${snapId}\"`);\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n"]}
1
+ {"version":3,"file":"snaps.js","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";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AC;IACF,IAAI,MAAM,KAAK,SAAS,EAAE;QACxB,OAAO,MAAM,CAAC;KACf;IACD,MAAM,IAAI,KAAK,CAAC,mCAAmC,MAAM,GAAG,CAAC,CAAC;AAChE,CAAC;AARD,sCAQC;AAED;;;;;GAKG;AACH,SAAgB,qBAAqB,CAAC,MAAc;IAClD,OAAO,mBAAW,GAAG,MAAM,CAAC;AAC9B,CAAC;AAFD,sDAEC;AAED;;;;;GAKG;AACH,SAAgB,cAAc,CAC5B,MAAe;IAEf,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;QACzC,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;KACnD;IAED,KAAK,MAAM,MAAM,IAAI,MAAM,CAAC,MAAM,CAAC,sBAAc,CAAC,EAAE;QAClD,IAAI,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACtE,OAAO;SACR;KACF;IAED,MAAM,IAAI,KAAK,CAAC,+CAA+C,MAAM,IAAI,CAAC,CAAC;AAC7E,CAAC;AAdD,wCAcC;AAED;;;;;GAKG;AACH,SAAgB,aAAa,CAAC,OAAgB;IAC5C,OAAO,CACL,OAAO,OAAO,KAAK,QAAQ;QAC3B,kEAAkE,CAAC,IAAI,CACrE,OAAO,CACR,CACF,CAAC;AACJ,CAAC;AAPD,sCAOC","sourcesContent":["import { assert, Json } from '@metamask/utils';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { base64 } from '@scure/base';\nimport { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';\nimport {\n empty,\n enums,\n intersection,\n literal,\n refine,\n string,\n Struct,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapManifest, SnapPermissions } from './manifest/validation';\nimport {\n SnapId,\n SnapIdPrefixes,\n SnapValidationFailureReason,\n uri,\n} from './types';\nimport { SemVerVersion } from './versions';\n\nexport const SNAP_PREFIX = 'wallet_snap_';\n\nexport const SNAP_PREFIX_REGEX = new RegExp(`^${SNAP_PREFIX}`, 'u');\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\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/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport type BlockedSnapInfo = { infoUrl?: string; reason?: string };\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: string };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type PersistedSnap = Snap & {\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n};\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: SnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockedSnapInfo;\n\n /**\n * The name of the permission used to invoke the Snap.\n */\n permissionName: string;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'permissionName'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult =\n | TruncatedSnap\n | { error: SerializedEthereumRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of a Snap source code string.\n *\n * @param sourceCode - The UTF-8 string source code of a Snap.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapSourceShasum(sourceCode: string): string {\n return base64.encode(sha256(sourceCode));\n}\n\nexport type ValidatedSnapId = `local:${string}` | `npm:${string}`;\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of a snap source code string.\n *\n * @param manifest - The manifest whose shasum to validate.\n * @param sourceCode - The source code of the snap.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n manifest: SnapManifest,\n sourceCode: string,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (manifest.source.shasum !== getSnapSourceShasum(sourceCode)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\nexport const LocalSnapIdStruct = refine(string(), 'local Snap Id', (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local Snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n});\nexport const NpmSnapIdStruct = intersection([\n string(),\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n string(),\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Computes the permission name of a snap from its snap ID.\n *\n * @param snapId - The snap ID.\n * @returns The permission name corresponding to the given snap ID.\n */\nexport function getSnapPermissionName(snapId: string): string {\n return SNAP_PREFIX + snapId;\n}\n\n/**\n * Asserts the provided object is a snapId with a supported prefix.\n *\n * @param snapId - The object to validate.\n * @throws {@link Error}. If the validation fails.\n */\nexport function validateSnapId(\n snapId: unknown,\n): asserts snapId is ValidatedSnapId {\n if (!snapId || typeof snapId !== 'string') {\n throw new Error(`Invalid snap id. Not a string.`);\n }\n\n for (const prefix of Object.values(SnapIdPrefixes)) {\n if (snapId.startsWith(prefix) && snapId.replace(prefix, '').length > 0) {\n return;\n }\n }\n\n throw new Error(`Invalid snap id. Unknown prefix. Received: \"${snapId}\".`);\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n"]}
package/dist/types.d.ts CHANGED
@@ -1,13 +1,13 @@
1
1
  import { SnapFunctionExports, SnapKeyring as Keyring } from '@metamask/snaps-types';
2
2
  import { Json } from '@metamask/utils';
3
- import { Infer } from 'superstruct';
3
+ import { Infer, Struct } from 'superstruct';
4
4
  import { SnapManifest } from './manifest/validation';
5
5
  export declare enum NpmSnapFileNames {
6
6
  PackageJson = "package.json",
7
7
  Manifest = "snap.manifest.json"
8
8
  }
9
- export declare const NameStruct: import("superstruct").Struct<string, null>;
10
- export declare const NpmSnapPackageJsonStruct: import("superstruct").Struct<{
9
+ export declare const NameStruct: Struct<string, null>;
10
+ export declare const NpmSnapPackageJsonStruct: Struct<{
11
11
  name: string;
12
12
  version: import("./versions").SemVerVersion;
13
13
  repository?: {
@@ -16,15 +16,15 @@ export declare const NpmSnapPackageJsonStruct: import("superstruct").Struct<{
16
16
  } | undefined;
17
17
  main?: string | undefined;
18
18
  }, {
19
- version: import("superstruct").Struct<import("./versions").SemVerVersion, null>;
20
- name: import("superstruct").Struct<string, null>;
21
- main: import("superstruct").Struct<string | undefined, null>;
22
- repository: import("superstruct").Struct<{
19
+ version: Struct<import("./versions").SemVerVersion, null>;
20
+ name: Struct<string, null>;
21
+ main: Struct<string | undefined, null>;
22
+ repository: Struct<{
23
23
  type: string;
24
24
  url: string;
25
25
  } | undefined, {
26
- type: import("superstruct").Struct<string, null>;
27
- url: import("superstruct").Struct<string, null>;
26
+ type: Struct<string, null>;
27
+ url: Struct<string, null>;
28
28
  }>;
29
29
  }>;
30
30
  export declare type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> & Record<string, any>;
@@ -104,4 +104,21 @@ declare const brand: unique symbol;
104
104
  export declare type Opaque<Base, Brand extends symbol> = Base & {
105
105
  [brand]: Brand;
106
106
  };
107
+ declare type UriOptions<T extends string> = {
108
+ protocol?: Struct<T>;
109
+ hash?: Struct<T>;
110
+ port?: Struct<T>;
111
+ hostname?: Struct<T>;
112
+ pathname?: Struct<T>;
113
+ search?: Struct<T>;
114
+ };
115
+ export declare const uri: (opts?: UriOptions<any>) => Struct<string | URL, null>;
116
+ /**
117
+ * Returns whether a given value is a valid URL.
118
+ *
119
+ * @param url - The value to check.
120
+ * @param opts - Optional constraints for url checking.
121
+ * @returns Whether `url` is valid URL or not.
122
+ */
123
+ export declare function isValidUrl(url: unknown, opts?: UriOptions<any>): url is string | URL;
107
124
  export {};
package/dist/types.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SNAP_EXPORT_NAMES = exports.HandlerType = exports.SNAP_STREAM_NAMES = exports.SnapValidationFailureReason = exports.SnapIdPrefixes = exports.assertIsNpmSnapPackageJson = exports.isNpmSnapPackageJson = exports.NpmSnapPackageJsonStruct = exports.NameStruct = exports.NpmSnapFileNames = void 0;
3
+ exports.isValidUrl = exports.uri = exports.SNAP_EXPORT_NAMES = exports.HandlerType = exports.SNAP_STREAM_NAMES = exports.SnapValidationFailureReason = exports.SnapIdPrefixes = exports.assertIsNpmSnapPackageJson = exports.isNpmSnapPackageJson = exports.NpmSnapPackageJsonStruct = exports.NameStruct = exports.NpmSnapFileNames = void 0;
4
4
  const utils_1 = require("@metamask/utils");
5
5
  const superstruct_1 = require("superstruct");
6
6
  const versions_1 = require("./versions");
@@ -76,4 +76,27 @@ var HandlerType;
76
76
  HandlerType["OnCronjob"] = "onCronjob";
77
77
  })(HandlerType = exports.HandlerType || (exports.HandlerType = {}));
78
78
  exports.SNAP_EXPORT_NAMES = Object.values(HandlerType);
79
+ const uri = (opts = {}) => (0, superstruct_1.refine)((0, superstruct_1.union)([(0, superstruct_1.string)(), (0, superstruct_1.instance)(URL)]), 'uri', (value) => {
80
+ try {
81
+ const url = new URL(value);
82
+ const UrlStruct = (0, superstruct_1.type)(opts);
83
+ (0, superstruct_1.assert)(url, UrlStruct);
84
+ return true;
85
+ }
86
+ catch (_a) {
87
+ return `Expected URL, got "${value.toString()}".`;
88
+ }
89
+ });
90
+ exports.uri = uri;
91
+ /**
92
+ * Returns whether a given value is a valid URL.
93
+ *
94
+ * @param url - The value to check.
95
+ * @param opts - Optional constraints for url checking.
96
+ * @returns Whether `url` is valid URL or not.
97
+ */
98
+ function isValidUrl(url, opts = {}) {
99
+ return (0, superstruct_1.is)(url, (0, exports.uri)(opts));
100
+ }
101
+ exports.isValidUrl = isValidUrl;
79
102
  //# sourceMappingURL=types.js.map
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAI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AgB,CAAA;AAClB,CAAC,EAHW,cAAc,GAAd,sBAAc,KAAd,sBAAc,QAGzB;AAKD;;;GAGG;AACH,IAAY,2BAKX;AALD,WAAY,2BAA2B;IACrC,uEAAsC,CAAA;IACtC,6EAA4C,CAAA;IAC5C,mFAAkD,CAAA;IAClD,2EAA0C,CAAA;AAC5C,CAAC,EALW,2BAA2B,GAA3B,mCAA2B,KAA3B,mCAA2B,QAKtC;AAED,yDAAyD;AACzD,IAAY,iBAGX;AAHD,WAAY,iBAAiB;IAC3B,yCAAoB,CAAA;IACpB,wCAAmB,CAAA;AACrB,CAAC,EAHW,iBAAiB,GAAjB,yBAAiB,KAAjB,yBAAiB,QAG5B;AACD,wDAAwD;AAExD,IAAY,WAKX;AALD,WAAY,WAAW;IACrB,4CAA6B,CAAA;IAC7B,8CAA+B,CAAA;IAC/B,sCAAuB,CAAA;IACvB,sCAAuB,CAAA;AACzB,CAAC,EALW,WAAW,GAAX,mBAAW,KAAX,mBAAW,QAKtB;AAEY,QAAA,iBAAiB,GAAG,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC","sourcesContent":["import {\n SnapFunctionExports,\n SnapKeyring as Keyring,\n} from '@metamask/snaps-types';\nimport { assertStruct, Json } from '@metamask/utils';\nimport {\n Infer,\n is,\n object,\n optional,\n pattern,\n size,\n string,\n type,\n} from 'superstruct';\n\nimport { SnapManifest } from './manifest/validation';\nimport { VersionStruct } from './versions';\n\nexport enum NpmSnapFileNames {\n PackageJson = 'package.json',\n Manifest = 'snap.manifest.json',\n}\n\nexport const NameStruct = size(\n pattern(\n string(),\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/u,\n ),\n 1,\n 214,\n);\n\n// Note we use `type` instead of `object` here, because the latter does not\n// allow unknown keys.\nexport const NpmSnapPackageJsonStruct = type({\n version: VersionStruct,\n name: NameStruct,\n main: optional(size(string(), 1, Infinity)),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n});\n\nexport type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> &\n Record<string, any>;\n\n/**\n * Check if the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link NpmSnapPackageJson} object.\n */\nexport function isNpmSnapPackageJson(\n value: unknown,\n): value is NpmSnapPackageJson {\n return is(value, NpmSnapPackageJsonStruct);\n}\n\n/**\n * Asserts that the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link NpmSnapPackageJson} object.\n */\nexport function assertIsNpmSnapPackageJson(\n value: unknown,\n): asserts value is NpmSnapPackageJson {\n assertStruct(\n value,\n NpmSnapPackageJsonStruct,\n `\"${NpmSnapFileNames.PackageJson}\" is invalid`,\n );\n}\n\n/**\n * An object for storing parsed but unvalidated Snap file contents.\n */\nexport type UnvalidatedSnapFiles = {\n manifest?: Json;\n packageJson?: Json;\n sourceCode?: string;\n svgIcon?: string;\n};\n\n/**\n * An object for storing the contents of Snap files that have passed JSON\n * Schema validation, or are non-empty if they are strings.\n */\nexport type SnapFiles = {\n manifest: SnapManifest;\n packageJson: NpmSnapPackageJson;\n sourceCode: string;\n svgIcon?: string;\n};\n\n/**\n * The possible prefixes for snap ids.\n */\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SnapIdPrefixes {\n npm = 'npm:',\n local = 'local:',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapId = string;\n\n/**\n * Snap validation failure reason codes that are programmatically fixable\n * if validation occurs during development.\n */\nexport enum SnapValidationFailureReason {\n NameMismatch = '\"name\" field mismatch',\n VersionMismatch = '\"version\" field mismatch',\n RepositoryMismatch = '\"repository\" field mismatch',\n ShasumMismatch = '\"shasum\" field mismatch',\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SNAP_STREAM_NAMES {\n JSON_RPC = 'jsonRpc',\n COMMAND = 'command',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnTransaction = 'onTransaction',\n SnapKeyring = 'keyring',\n OnCronjob = 'onCronjob',\n}\n\nexport const SNAP_EXPORT_NAMES = Object.values(HandlerType);\n\nexport type SnapRpcHookArgs = {\n origin: string;\n handler: HandlerType;\n request: Record<string, unknown>;\n};\n\n// The snap is the callee\nexport type SnapRpcHook = (options: SnapRpcHookArgs) => Promise<unknown>;\n\ntype ObjectParameters<\n Type extends Record<string, (...args: any[]) => unknown>,\n> = Parameters<Type[keyof Type]>;\n\ntype KeyringParameter<Fn> = Fn extends (...args: any[]) => unknown\n ? Parameters<Fn>\n : never;\n\ntype KeyringParameters = KeyringParameter<Keyring[keyof Keyring]>;\n\nexport type SnapExportsParameters =\n | ObjectParameters<SnapFunctionExports>\n | KeyringParameters;\n\n// We use a symbol property name instead of { _type: Brand }, because that would show up in IDE suggestions,\n// while internal symbols do not.\ndeclare const brand: unique symbol;\nexport type Opaque<Base, Brand extends symbol> = Base & { [brand]: Brand };\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAIA,2CAAqD;AACrD,6CAcqB;AAGrB,yCAA2C;AAE3C,IAAY,gBAGX;AAHD,WAAY,gBAAgB;IAC1B,gDAA4B,CAAA;IAC5B,mDAA+B,CAAA;AACjC,CAAC,EAHW,gBAAgB,GAAhB,wBAAgB,KAAhB,wBAAgB,QAG3B;AAEY,QAAA,UAAU,GAAG,IAAA,kBAAI,EAC5B,IAAA,qBAAO,EACL,IAAA,oBAAM,GAAE,EACR,6DAA6D,CAC9D,EACD,CAAC,EACD,GAAG,CACJ,CAAC;AAEF,2EAA2E;AAC3E,sBAAsB;AACT,QAAA,wBAAwB,GAAG,IAAA,kBAAI,EAAC;IAC3C,OAAO,EAAE,wBAAa;IACtB,IAAI,EAAE,kBAAU;IAChB,IAAI,EAAE,IAAA,s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IACrB,4CAA6B,CAAA;IAC7B,8CAA+B,CAAA;IAC/B,sCAAuB,CAAA;IACvB,sCAAuB,CAAA;AACzB,CAAC,EALW,WAAW,GAAX,mBAAW,KAAX,mBAAW,QAKtB;AAEY,QAAA,iBAAiB,GAAG,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;AAsCrD,MAAM,GAAG,GAAG,CAAC,OAAwB,EAAE,EAAE,EAAE,CAChD,IAAA,oBAAM,EAAC,IAAA,mBAAK,EAAC,CAAC,IAAA,oBAAM,GAAE,EAAE,IAAA,sBAAQ,EAAC,GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,KAAK,EAAE,EAAE;IACxD,IAAI;QACF,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;QAE3B,MAAM,SAAS,GAAG,IAAA,kBAAI,EAAC,IAAI,CAAC,CAAC;QAC7B,IAAA,oBAAiB,EAAC,GAAG,EAAE,SAAS,CAAC,CAAC;QAClC,OAAO,IAAI,CAAC;KACb;IAAC,WAAM;QACN,OAAO,sBAAsB,KAAK,CAAC,QAAQ,EAAE,IAAI,CAAC;KACnD;AACH,CAAC,CAAC,CAAC;AAXQ,QAAA,GAAG,OAWX;AAEL;;;;;;GAMG;AACH,SAAgB,UAAU,CACxB,GAAY,EACZ,OAAwB,EAAE;IAE1B,OAAO,IAAA,gBAAE,EAAC,GAAG,EAAE,IAAA,WAAG,EAAC,IAAI,CAAC,CAAC,CAAC;AAC5B,CAAC;AALD,gCAKC","sourcesContent":["import {\n SnapFunctionExports,\n SnapKeyring as Keyring,\n} from '@metamask/snaps-types';\nimport { assertStruct, Json } from '@metamask/utils';\nimport {\n Infer,\n instance,\n is,\n object,\n optional,\n pattern,\n refine,\n size,\n string,\n Struct,\n type,\n union,\n assert as assertSuperstruct,\n} from 'superstruct';\n\nimport { SnapManifest } from './manifest/validation';\nimport { VersionStruct } from './versions';\n\nexport enum NpmSnapFileNames {\n PackageJson = 'package.json',\n Manifest = 'snap.manifest.json',\n}\n\nexport const NameStruct = size(\n pattern(\n string(),\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/u,\n ),\n 1,\n 214,\n);\n\n// Note we use `type` instead of `object` here, because the latter does not\n// allow unknown keys.\nexport const NpmSnapPackageJsonStruct = type({\n version: VersionStruct,\n name: NameStruct,\n main: optional(size(string(), 1, Infinity)),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n});\n\nexport type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> &\n Record<string, any>;\n\n/**\n * Check if the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link NpmSnapPackageJson} object.\n */\nexport function isNpmSnapPackageJson(\n value: unknown,\n): value is NpmSnapPackageJson {\n return is(value, NpmSnapPackageJsonStruct);\n}\n\n/**\n * Asserts that the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link NpmSnapPackageJson} object.\n */\nexport function assertIsNpmSnapPackageJson(\n value: unknown,\n): asserts value is NpmSnapPackageJson {\n assertStruct(\n value,\n NpmSnapPackageJsonStruct,\n `\"${NpmSnapFileNames.PackageJson}\" is invalid`,\n );\n}\n\n/**\n * An object for storing parsed but unvalidated Snap file contents.\n */\nexport type UnvalidatedSnapFiles = {\n manifest?: Json;\n packageJson?: Json;\n sourceCode?: string;\n svgIcon?: string;\n};\n\n/**\n * An object for storing the contents of Snap files that have passed JSON\n * Schema validation, or are non-empty if they are strings.\n */\nexport type SnapFiles = {\n manifest: SnapManifest;\n packageJson: NpmSnapPackageJson;\n sourceCode: string;\n svgIcon?: string;\n};\n\n/**\n * The possible prefixes for snap ids.\n */\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SnapIdPrefixes {\n npm = 'npm:',\n local = 'local:',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapId = string;\n\n/**\n * Snap validation failure reason codes that are programmatically fixable\n * if validation occurs during development.\n */\nexport enum SnapValidationFailureReason {\n NameMismatch = '\"name\" field mismatch',\n VersionMismatch = '\"version\" field mismatch',\n RepositoryMismatch = '\"repository\" field mismatch',\n ShasumMismatch = '\"shasum\" field mismatch',\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SNAP_STREAM_NAMES {\n JSON_RPC = 'jsonRpc',\n COMMAND = 'command',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnTransaction = 'onTransaction',\n SnapKeyring = 'keyring',\n OnCronjob = 'onCronjob',\n}\n\nexport const SNAP_EXPORT_NAMES = Object.values(HandlerType);\n\nexport type SnapRpcHookArgs = {\n origin: string;\n handler: HandlerType;\n request: Record<string, unknown>;\n};\n\n// The snap is the callee\nexport type SnapRpcHook = (options: SnapRpcHookArgs) => Promise<unknown>;\n\ntype ObjectParameters<\n Type extends Record<string, (...args: any[]) => unknown>,\n> = Parameters<Type[keyof Type]>;\n\ntype KeyringParameter<Fn> = Fn extends (...args: any[]) => unknown\n ? Parameters<Fn>\n : never;\n\ntype KeyringParameters = KeyringParameter<Keyring[keyof Keyring]>;\n\nexport type SnapExportsParameters =\n | ObjectParameters<SnapFunctionExports>\n | KeyringParameters;\n\n// We use a symbol property name instead of { _type: Brand }, because that would show up in IDE suggestions,\n// while internal symbols do not.\ndeclare const brand: unique symbol;\nexport type Opaque<Base, Brand extends symbol> = Base & { [brand]: Brand };\n\ntype UriOptions<T extends string> = {\n protocol?: Struct<T>;\n hash?: Struct<T>;\n port?: Struct<T>;\n hostname?: Struct<T>;\n pathname?: Struct<T>;\n search?: Struct<T>;\n};\nexport const uri = (opts: UriOptions<any> = {}) =>\n refine(union([string(), instance(URL)]), 'uri', (value) => {\n try {\n const url = new URL(value);\n\n const UrlStruct = type(opts);\n assertSuperstruct(url, UrlStruct);\n return true;\n } catch {\n return `Expected URL, got \"${value.toString()}\".`;\n }\n });\n\n/**\n * Returns whether a given value is a valid URL.\n *\n * @param url - The value to check.\n * @param opts - Optional constraints for url checking.\n * @returns Whether `url` is valid URL or not.\n */\nexport function isValidUrl(\n url: unknown,\n opts: UriOptions<any> = {},\n): url is string | URL {\n return is(url, uri(opts));\n}\n"]}
@@ -83,6 +83,14 @@ export declare function assertIsSemVerRange(range: unknown): asserts range is Se
83
83
  * @returns `version1 > version2`.
84
84
  */
85
85
  export declare function gtVersion(version1: SemVerVersion, version2: SemVerVersion): boolean;
86
+ /**
87
+ * Checks whether a SemVer version is greater than all possibilities in a range.
88
+ *
89
+ * @param version - A SemvVer version.
90
+ * @param range - The range to check against.
91
+ * @returns `version > range`.
92
+ */
93
+ export declare function gtRange(version: SemVerVersion, range: SemVerRange): boolean;
86
94
  /**
87
95
  * Returns whether a SemVer version satisfies a SemVer range.
88
96
  *
package/dist/versions.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resolveVersionRange = exports.getTargetVersion = exports.satisfiesVersionRange = exports.gtVersion = exports.assertIsSemVerRange = exports.assertIsSemVerVersion = exports.isValidSemVerRange = exports.isValidSemVerVersion = exports.VersionRangeStruct = exports.VersionStruct = exports.DEFAULT_REQUESTED_SNAP_VERSION = void 0;
3
+ exports.resolveVersionRange = exports.getTargetVersion = exports.satisfiesVersionRange = exports.gtRange = exports.gtVersion = exports.assertIsSemVerRange = exports.assertIsSemVerVersion = exports.isValidSemVerRange = exports.isValidSemVerVersion = exports.VersionRangeStruct = exports.VersionStruct = exports.DEFAULT_REQUESTED_SNAP_VERSION = void 0;
4
4
  const utils_1 = require("@metamask/utils");
5
5
  const semver_1 = require("semver");
6
6
  const superstruct_1 = require("superstruct");
@@ -69,6 +69,17 @@ function gtVersion(version1, version2) {
69
69
  return (0, semver_1.gt)(version1, version2);
70
70
  }
71
71
  exports.gtVersion = gtVersion;
72
+ /**
73
+ * Checks whether a SemVer version is greater than all possibilities in a range.
74
+ *
75
+ * @param version - A SemvVer version.
76
+ * @param range - The range to check against.
77
+ * @returns `version > range`.
78
+ */
79
+ function gtRange(version, range) {
80
+ return (0, semver_1.gtr)(version, range);
81
+ }
82
+ exports.gtRange = gtRange;
72
83
  /**
73
84
  * Returns whether a SemVer version satisfies a SemVer range.
74
85
  *
@@ -1 +1 @@
1
- {"version":3,"file":"versions.js","sourceRoot":"","sources":["../src/versions.ts"],"names":[],"mappings":";;;AAAA,2CAAqD;AACrD,mCAMgB;AAChB,6CAAmE;AAItD,QAAA,8BAA8B,GAAG,GAAkB,CAAC;AA8CjE;;GAEG;AACU,QAAA,aAAa,GAAG,IAAA,oBAAM,EACjC,IAAA,oBAAM,GAA4C,EAClD,SAAS,EACT,CAAC,KAAK,EAAE,EAAE;IACR,IAAI,IAAA,cAAkB,EAAC,KAAK,CAAC,KAAK,IAAI,EAAE;QACtC,OAAO,iCAAiC,KAAK,GAAG,CAAC;KAClD;IACD,OAAO,IAAI,CAAC;AACd,CAAC,CACF,CAAC;AAEW,QAAA,kBAAkB,GAAG,IAAA,oBAAM,EACtC,IAAA,oBAAM,GAA0C,EAChD,eAAe,EACf,CAAC,KAAK,EAAE,EAAE;IACR,IAAI,IAAA,mBAAgB,EAAC,KAAK,CAAC,KAAK,IAAI,EAAE;QACpC,OAAO,+BAA+B,KAAK,GAAG,CAAC;KAChD;IACD,OAAO,IAAI,CAAC;AACd,CAAC,CACF,CAAC;AAEF;;;;;GAKG;AACH,SAAgB,oBAAoB,CAClC,OAAgB;IAEhB,OAAO,IAAA,gBAAE,EAAC,OAAO,EAAE,qBAAa,CAAC,CAAC;AACpC,CAAC;AAJD,oDAIC;AAED;;;;;GAKG;AACH,SAAgB,kBAAkB,CAChC,YAAqB;IAErB,OAAO,IAAA,gBAAE,EAAC,YAAY,EAAE,0BAAkB,CAAC,CAAC;AAC9C,CAAC;AAJD,gDAIC;AAED;;;;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, Json } from '@metamask/utils';\nimport {\n gt as gtSemver,\n maxSatisfying as maxSatisfyingSemver,\n satisfies as satisfiesSemver,\n valid as validSemVerVersion,\n validRange as validSemVerRange,\n} from 'semver';\nimport { is, refine, string, Struct, validate } from 'superstruct';\n\nimport { Opaque } from './types';\n\nexport const DEFAULT_REQUESTED_SNAP_VERSION = '*' as SemVerRange;\n\n/**\n * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for SemVer ranges.\n *\n * @example Use {@link assertIsSemVerRange} and {@link isValidSemVerRange} to cast to proper type.\n * ```typescript\n * const unsafeRange: string = dataFromUser();\n * assertIsSemVerRange(unsafeRange);\n * unsafeRange\n * // ^? SemVerRange\n * ```\n * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.\n * ```typescript\n * const unsafeRange: string = dataFromUser();\n * unsafeRange as SemVerRange;\n * // ^? SemVerRange\n * ```\n * @see {@link assertIsSemVerRange}\n * @see {@link isValidSemVerRange}\n */\nexport type SemVerRange = Opaque<string, typeof semVerRange>;\ndeclare const semVerRange: unique symbol;\n\n/**\n * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for singular SemVer version.\n *\n * @example Use {@link assertIsSemVerVersion} and {@link isValidSemVerVersion} to cast to proper type.\n * ```typescript\n * const unsafeVersion: string = dataFromUser();\n * assertIsSemVerVersion(unsafeRange);\n * unsafeVersion\n * // ^? SemVerVersion\n * ```\n * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.\n * ```typescript\n * const unsafeVersion: string = dataFromUser();\n * unsafeRange as SemVerVersion;\n * // ^? SemVerVersion\n * ```\n * @see {@link assertIsSemVerVersion}\n * @see {@link isValidSemVerVersion}\n */\nexport type SemVerVersion = Opaque<string, typeof semVerVersion>;\ndeclare const semVerVersion: unique symbol;\n\n/**\n * A struct for validating a version string.\n */\nexport const VersionStruct = refine<SemVerVersion, null>(\n string() as unknown as Struct<SemVerVersion, null>,\n 'Version',\n (value) => {\n if (validSemVerVersion(value) === null) {\n return `Expected SemVer version, got \"${value}\"`;\n }\n return true;\n },\n);\n\nexport const VersionRangeStruct = refine<SemVerRange, null>(\n string() as unknown as Struct<SemVerRange, null>,\n 'Version range',\n (value) => {\n if (validSemVerRange(value) === null) {\n return `Expected SemVer range, got \"${value}\"`;\n }\n return true;\n },\n);\n\n/**\n * Checks whether a SemVer version is valid.\n *\n * @param version - A potential version.\n * @returns `true` if the version is valid, and `false` otherwise.\n */\nexport function isValidSemVerVersion(\n version: unknown,\n): version is SemVerVersion {\n return is(version, VersionStruct);\n}\n\n/**\n * Checks whether a SemVer version range is valid.\n *\n * @param versionRange - A potential version range.\n * @returns `true` if the version range is valid, and `false` otherwise.\n */\nexport function isValidSemVerRange(\n versionRange: unknown,\n): versionRange is SemVerRange {\n return is(versionRange, VersionRangeStruct);\n}\n\n/**\n * Asserts that a value is a valid concrete SemVer version.\n *\n * @param version - A potential SemVer concrete version.\n */\nexport function assertIsSemVerVersion(\n version: unknown,\n): asserts version is SemVerVersion {\n assertStruct(version, VersionStruct);\n}\n\n/**\n * Asserts that a value is a valid SemVer range.\n *\n * @param range - A potential SemVer range.\n */\nexport function assertIsSemVerRange(\n range: unknown,\n): asserts range is SemVerRange {\n assertStruct(range, VersionRangeStruct);\n}\n\n/**\n * Checks whether a SemVer version is greater than another.\n *\n * @param version1 - The left-hand version.\n * @param version2 - The right-hand version.\n * @returns `version1 > version2`.\n */\nexport function gtVersion(\n version1: SemVerVersion,\n version2: SemVerVersion,\n): boolean {\n return gtSemver(version1, version2);\n}\n\n/**\n * Returns whether a SemVer version satisfies a SemVer range.\n *\n * @param version - The SemVer version to check.\n * @param versionRange - The SemVer version range to check against.\n * @returns Whether the version satisfied the version range.\n */\nexport function satisfiesVersionRange(\n version: SemVerVersion,\n versionRange: SemVerRange,\n): boolean {\n return satisfiesSemver(version, versionRange, {\n includePrerelease: true,\n });\n}\n\n/**\n * Return the highest version in the list that satisfies the range, or `null` if\n * none of them do. For the satisfaction check, pre-release versions will only\n * be checked if no satisfactory non-prerelease version is found first.\n *\n * @param versions - The list of version to check.\n * @param versionRange - The SemVer version range to check against.\n * @returns The highest version in the list that satisfies the range,\n * or `null` if none of them do.\n */\nexport function getTargetVersion(\n versions: SemVerVersion[],\n versionRange: SemVerRange,\n): SemVerVersion | null {\n const maxSatisfyingNonPreRelease = maxSatisfyingSemver(\n versions,\n versionRange,\n );\n\n // By default don't use pre-release versions\n if (maxSatisfyingNonPreRelease) {\n return maxSatisfyingNonPreRelease;\n }\n\n // If no satisfying release version is found by default, try pre-release versions\n return maxSatisfyingSemver(versions, versionRange, {\n includePrerelease: true,\n });\n}\n\n/**\n * Parse a version received by some subject attempting to access a snap.\n *\n * @param version - The received version value.\n * @returns `*` if the version is `undefined` or `latest\", otherwise returns\n * the specified version.\n */\nexport function resolveVersionRange(\n version?: Json,\n): [error: undefined, range: SemVerRange] | [error: Error, range: undefined] {\n if (version === undefined || version === 'latest') {\n return [undefined, DEFAULT_REQUESTED_SNAP_VERSION];\n }\n return validate(version, VersionRangeStruct);\n}\n"]}
1
+ {"version":3,"file":"versions.js","sourceRoot":"","sources":["../src/versions.ts"],"names":[],"mappings":";;;AAAA,2CAAqD;AACrD,mCAOgB;AAChB,6CAAmE;AAItD,QAAA,8BAA8B,GAAG,GAAkB,CAAC;AA8CjE;;GAEG;AACU,QAAA,aAAa,GAAG,IAAA,oBAAM,EACjC,IAAA,oBAAM,GAA4C,EAClD,SAAS,EACT,CAAC,KAAK,EAAE,EAAE;IACR,IAAI,IAAA,cAAkB,EAAC,KAAK,CAAC,KAAK,IAAI,EAAE;QACtC,OAAO,iCAAiC,KAAK,GAAG,CAAC;KAClD;IACD,OAAO,IAAI,CAAC;AACd,CAAC,CACF,CAAC;AAEW,QAAA,kBAAkB,GAAG,IAAA,oBAAM,EACtC,IAAA,oBAAM,GAA0C,EAChD,eAAe,EACf,CAAC,KAAK,EAAE,EAAE;IACR,IAAI,IAAA,mBAAgB,EAAC,KAAK,CAAC,KAAK,IAAI,EAAE;QACpC,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,EACR,YAAY,CACb,CAAC;IAEF,4CAA4C;IAC5C,IAAI,0BAA0B,EAAE;QAC9B,OAAO,0BAA0B,CAAC;KACnC;IAED,iFAAiF;IACjF,OAAO,IAAA,sBAAmB,EAAC,QAAQ,EAAE,YAAY,EAAE;QACjD,iBAAiB,EAAE,IAAI;KACxB,CAAC,CAAC;AACL,CAAC;AAlBD,4CAkBC;AAED;;;;;;GAMG;AACH,SAAgB,mBAAmB,CACjC,OAAc;IAEd,IAAI,OAAO,KAAK,SAAS,IAAI,OAAO,KAAK,QAAQ,EAAE;QACjD,OAAO,CAAC,SAAS,EAAE,sCAA8B,CAAC,CAAC;KACpD;IACD,OAAO,IAAA,sBAAQ,EAAC,OAAO,EAAE,0BAAkB,CAAC,CAAC;AAC/C,CAAC;AAPD,kDAOC","sourcesContent":["import { assertStruct, Json } from '@metamask/utils';\nimport {\n gt as gtSemver,\n gtr as gtrSemver,\n maxSatisfying as maxSatisfyingSemver,\n satisfies as satisfiesSemver,\n valid as validSemVerVersion,\n validRange as validSemVerRange,\n} from 'semver';\nimport { is, refine, string, Struct, validate } from 'superstruct';\n\nimport { Opaque } from './types';\n\nexport const DEFAULT_REQUESTED_SNAP_VERSION = '*' as SemVerRange;\n\n/**\n * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for SemVer ranges.\n *\n * @example Use {@link assertIsSemVerRange} and {@link isValidSemVerRange} to cast to proper type.\n * ```typescript\n * const unsafeRange: string = dataFromUser();\n * assertIsSemVerRange(unsafeRange);\n * unsafeRange\n * // ^? SemVerRange\n * ```\n * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.\n * ```typescript\n * const unsafeRange: string = dataFromUser();\n * unsafeRange as SemVerRange;\n * // ^? SemVerRange\n * ```\n * @see {@link assertIsSemVerRange}\n * @see {@link isValidSemVerRange}\n */\nexport type SemVerRange = Opaque<string, typeof semVerRange>;\ndeclare const semVerRange: unique symbol;\n\n/**\n * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for singular SemVer version.\n *\n * @example Use {@link assertIsSemVerVersion} and {@link isValidSemVerVersion} to cast to proper type.\n * ```typescript\n * const unsafeVersion: string = dataFromUser();\n * assertIsSemVerVersion(unsafeRange);\n * unsafeVersion\n * // ^? SemVerVersion\n * ```\n * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.\n * ```typescript\n * const unsafeVersion: string = dataFromUser();\n * unsafeRange as SemVerVersion;\n * // ^? SemVerVersion\n * ```\n * @see {@link assertIsSemVerVersion}\n * @see {@link isValidSemVerVersion}\n */\nexport type SemVerVersion = Opaque<string, typeof semVerVersion>;\ndeclare const semVerVersion: unique symbol;\n\n/**\n * A struct for validating a version string.\n */\nexport const VersionStruct = refine<SemVerVersion, null>(\n string() as unknown as Struct<SemVerVersion, null>,\n 'Version',\n (value) => {\n if (validSemVerVersion(value) === null) {\n return `Expected SemVer version, got \"${value}\"`;\n }\n return true;\n },\n);\n\nexport const VersionRangeStruct = refine<SemVerRange, null>(\n string() as unknown as Struct<SemVerRange, null>,\n 'Version range',\n (value) => {\n if (validSemVerRange(value) === null) {\n return `Expected SemVer range, got \"${value}\"`;\n }\n return true;\n },\n);\n\n/**\n * Checks whether a SemVer version is valid.\n *\n * @param version - A potential version.\n * @returns `true` if the version is valid, and `false` otherwise.\n */\nexport function isValidSemVerVersion(\n version: unknown,\n): version is SemVerVersion {\n return is(version, VersionStruct);\n}\n\n/**\n * Checks whether a SemVer version range is valid.\n *\n * @param versionRange - A potential version range.\n * @returns `true` if the version range is valid, and `false` otherwise.\n */\nexport function isValidSemVerRange(\n versionRange: unknown,\n): versionRange is SemVerRange {\n return is(versionRange, VersionRangeStruct);\n}\n\n/**\n * Asserts that a value is a valid concrete SemVer version.\n *\n * @param version - A potential SemVer concrete version.\n */\nexport function assertIsSemVerVersion(\n version: unknown,\n): asserts version is SemVerVersion {\n assertStruct(version, VersionStruct);\n}\n\n/**\n * Asserts that a value is a valid SemVer range.\n *\n * @param range - A potential SemVer range.\n */\nexport function assertIsSemVerRange(\n range: unknown,\n): asserts range is SemVerRange {\n assertStruct(range, VersionRangeStruct);\n}\n\n/**\n * Checks whether a SemVer version is greater than another.\n *\n * @param version1 - The left-hand version.\n * @param version2 - The right-hand version.\n * @returns `version1 > version2`.\n */\nexport function gtVersion(\n version1: SemVerVersion,\n version2: SemVerVersion,\n): boolean {\n return gtSemver(version1, version2);\n}\n\n/**\n * Checks whether a SemVer version is greater than all possibilities in a range.\n *\n * @param version - A SemvVer version.\n * @param range - The range to check against.\n * @returns `version > range`.\n */\nexport function gtRange(version: SemVerVersion, range: SemVerRange): boolean {\n return gtrSemver(version, range);\n}\n\n/**\n * Returns whether a SemVer version satisfies a SemVer range.\n *\n * @param version - The SemVer version to check.\n * @param versionRange - The SemVer version range to check against.\n * @returns Whether the version satisfied the version range.\n */\nexport function satisfiesVersionRange(\n version: SemVerVersion,\n versionRange: SemVerRange,\n): boolean {\n return satisfiesSemver(version, versionRange, {\n includePrerelease: true,\n });\n}\n\n/**\n * Return the highest version in the list that satisfies the range, or `null` if\n * none of them do. For the satisfaction check, pre-release versions will only\n * be checked if no satisfactory non-prerelease version is found first.\n *\n * @param versions - The list of version to check.\n * @param versionRange - The SemVer version range to check against.\n * @returns The highest version in the list that satisfies the range,\n * or `null` if none of them do.\n */\nexport function getTargetVersion(\n versions: SemVerVersion[],\n versionRange: SemVerRange,\n): SemVerVersion | null {\n const maxSatisfyingNonPreRelease = maxSatisfyingSemver(\n versions,\n versionRange,\n );\n\n // By default don't use pre-release versions\n if (maxSatisfyingNonPreRelease) {\n return maxSatisfyingNonPreRelease;\n }\n\n // If no satisfying release version is found by default, try pre-release versions\n return maxSatisfyingSemver(versions, versionRange, {\n includePrerelease: true,\n });\n}\n\n/**\n * Parse a version received by some subject attempting to access a snap.\n *\n * @param version - The received version value.\n * @returns `*` if the version is `undefined` or `latest\", otherwise returns\n * the specified version.\n */\nexport function resolveVersionRange(\n version?: Json,\n): [error: undefined, range: SemVerRange] | [error: Error, range: undefined] {\n if (version === undefined || version === 'latest') {\n return [undefined, DEFAULT_REQUESTED_SNAP_VERSION];\n }\n return validate(version, VersionRangeStruct);\n}\n"]}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * This map registers the type of the {@link VirtualFile.data} key of a {@link VirtualFile}.
3
+ *
4
+ * This type can be augmented to register custom `data` types.
5
+ *
6
+ * @example
7
+ * declare module '@metamask/snaps-utils' {
8
+ * interface DataMap {
9
+ * // `file.data.name` is typed as `string`
10
+ * name: string
11
+ * }
12
+ * }
13
+ */
14
+ export interface DataMap {
15
+ }
16
+ export declare type Value = string | Uint8Array;
17
+ export declare type Compatible<Result = unknown> = string | Uint8Array | Options<Result>;
18
+ export declare type Data = Record<string, unknown> & Partial<DataMap>;
19
+ export declare type Options<Result = unknown> = {
20
+ value: Value;
21
+ path?: string;
22
+ data?: Data;
23
+ result?: Result;
24
+ };
25
+ export declare class VirtualFile<Result = unknown> {
26
+ constructor(value?: Compatible<Result>);
27
+ value: Value;
28
+ result: Result;
29
+ data: Data;
30
+ path: string;
31
+ toString(encoding?: string): string;
32
+ clone(): VirtualFile<Result>;
33
+ }
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VirtualFile = void 0;
4
+ // TODO(ritave): Move into separate package @metamask/vfile / @metamask/utils + @metamask/to-vfile when passes code review
5
+ // TODO(ritave): Streaming vfile contents similar to vinyl maybe?
6
+ // TODO(ritave): Move fixing manifest in cli and bundler plugins to write messages to vfile
7
+ // similar to unified instead of throwing "ProgrammaticallyFixableErrors".
8
+ //
9
+ // Using https://github.com/vfile/vfile would be helpful, but they only support ESM and we need to support CommonJS.
10
+ // https://github.com/gulpjs/vinyl is also good, but they normalize paths, which we can't do, because
11
+ // we're calculating checksums based on original path.
12
+ const utils_1 = require("@metamask/utils");
13
+ const deep_clone_1 = require("../deep-clone");
14
+ class VirtualFile {
15
+ constructor(value) {
16
+ var _a, _b, _c, _d;
17
+ let options;
18
+ if (typeof value === 'string' || value instanceof Uint8Array) {
19
+ options = { value };
20
+ }
21
+ else {
22
+ options = value;
23
+ }
24
+ this.value = (_a = options === null || options === void 0 ? void 0 : options.value) !== null && _a !== void 0 ? _a : '';
25
+ // This situations happens when there's no .result used,
26
+ // we expect the file to have default generic in that situation:
27
+ // VirtualFile<unknown> which will handle undefined properly
28
+ //
29
+ // While not 100% type safe, it'll be way less frustrating to work with.
30
+ // The alternative would be to have VirtualFile.result be Result | undefined
31
+ // and that would result in needing to branch out and check in all situations.
32
+ //
33
+ // In short, optimizing for most common use case.
34
+ this.result = (_b = options === null || options === void 0 ? void 0 : options.result) !== null && _b !== void 0 ? _b : undefined;
35
+ this.data = (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {};
36
+ this.path = (_d = options === null || options === void 0 ? void 0 : options.path) !== null && _d !== void 0 ? _d : '/';
37
+ }
38
+ toString(encoding) {
39
+ if (typeof this.value === 'string') {
40
+ (0, utils_1.assert)(encoding === undefined, 'Tried to encode string.');
41
+ return this.value;
42
+ }
43
+ const decoder = new TextDecoder(encoding);
44
+ return decoder.decode(this.value);
45
+ }
46
+ clone() {
47
+ const vfile = new VirtualFile();
48
+ if (typeof this.value === 'string') {
49
+ vfile.value = this.value;
50
+ }
51
+ else {
52
+ // deep-clone doesn't clone Buffer properly, even if it's a sub-class of Uint8Array
53
+ vfile.value = this.value.slice(0);
54
+ }
55
+ vfile.result = (0, deep_clone_1.deepClone)(this.result);
56
+ vfile.data = (0, deep_clone_1.deepClone)(this.data);
57
+ vfile.path = this.path;
58
+ return vfile;
59
+ }
60
+ }
61
+ exports.VirtualFile = VirtualFile;
62
+ //# sourceMappingURL=VirtualFile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"VirtualFile.js","sourceRoot":"","sources":["../../src/virtual-file/VirtualFile.ts"],"names":[],"mappings":";;;AAAA,0HAA0H;AAC1H,iEAAiE;AACjE,2FAA2F;AAC3F,wFAAwF;AACxF,EAAE;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,OAAO,IAAI,CAAC,KAAK,KAAK,QAAQ,EAAE;YAClC,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;SAC1B;aAAM;YACL,mFAAmF;YACnF,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;SACnC;QACD,KAAK,CAAC,MAAM,GAAG,IAAA,sBAAS,EAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACtC,KAAK,CAAC,IAAI,GAAG,IAAA,sBAAS,EAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAClC,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QACvB,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAtDD,kCAsDC","sourcesContent":["// TODO(ritave): Move into separate package @metamask/vfile / @metamask/utils + @metamask/to-vfile when passes code review\n// TODO(ritave): Streaming vfile contents similar to vinyl maybe?\n// TODO(ritave): Move fixing manifest in cli and bundler plugins to write messages to vfile\n// similar to unified instead of throwing \"ProgrammaticallyFixableErrors\".\n//\n// Using https://github.com/vfile/vfile would be helpful, but they only support ESM and we need to support CommonJS.\n// https://github.com/gulpjs/vinyl is also good, but they normalize paths, which we can't do, because\n// we're calculating checksums based on original path.\nimport { assert } from '@metamask/utils';\n\nimport { deepClone } from '../deep-clone';\n\n/**\n * This map registers the type of the {@link VirtualFile.data} key of a {@link VirtualFile}.\n *\n * This type can be augmented to register custom `data` types.\n *\n * @example\n * declare module '@metamask/snaps-utils' {\n * interface DataMap {\n * // `file.data.name` is typed as `string`\n * name: string\n * }\n * }\n */\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions, @typescript-eslint/no-empty-interface\nexport interface DataMap {}\n\nexport type Value = string | Uint8Array;\nexport type Compatible<Result = unknown> =\n | string\n | Uint8Array\n | Options<Result>;\nexport type Data = Record<string, unknown> & Partial<DataMap>;\nexport type Options<Result = unknown> = {\n value: Value;\n path?: string;\n data?: Data;\n result?: Result;\n};\n\nexport class VirtualFile<Result = unknown> {\n constructor(value?: Compatible<Result>) {\n let options: Options | undefined;\n if (typeof value === 'string' || value instanceof Uint8Array) {\n options = { value };\n } else {\n options = value;\n }\n\n this.value = options?.value ?? '';\n // This situations happens when there's no .result used,\n // we expect the file to have default generic in that situation:\n // VirtualFile<unknown> which will handle undefined properly\n //\n // While not 100% type safe, it'll be way less frustrating to work with.\n // The alternative would be to have VirtualFile.result be Result | undefined\n // and that would result in needing to branch out and check in all situations.\n //\n // In short, optimizing for most common use case.\n this.result = options?.result ?? (undefined as any);\n this.data = options?.data ?? {};\n this.path = options?.path ?? '/';\n }\n\n value: Value;\n\n result: Result;\n\n data: Data;\n\n path: string;\n\n toString(encoding?: string) {\n if (typeof this.value === 'string') {\n assert(encoding === undefined, 'Tried to encode string.');\n return this.value;\n }\n const decoder = new TextDecoder(encoding);\n return decoder.decode(this.value);\n }\n\n clone() {\n const vfile = new VirtualFile<Result>();\n if (typeof this.value === 'string') {\n vfile.value = this.value;\n } else {\n // deep-clone doesn't clone Buffer properly, even if it's a sub-class of Uint8Array\n vfile.value = this.value.slice(0);\n }\n vfile.result = deepClone(this.result);\n vfile.data = deepClone(this.data);\n vfile.path = this.path;\n return vfile;\n }\n}\n"]}
@@ -0,0 +1 @@
1
+ export * from './VirtualFile';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./VirtualFile"), exports);
18
+ //# sourceMappingURL=index.browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.browser.js","sourceRoot":"","sources":["../../src/virtual-file/index.browser.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,gDAA8B","sourcesContent":["export * from './VirtualFile';\n"]}
@@ -0,0 +1,2 @@
1
+ export * from './toVirtualFile';
2
+ export * from './VirtualFile';
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./toVirtualFile"), exports);
18
+ __exportStar(require("./VirtualFile"), exports);
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/virtual-file/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,kDAAgC;AAChC,gDAA8B","sourcesContent":["export * from './toVirtualFile';\nexport * from './VirtualFile';\n"]}
@@ -0,0 +1,21 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import fsPromises from 'fs/promises';
4
+ import { VirtualFile } from './VirtualFile';
5
+ /**
6
+ * Reads a file from filesystem and creates a vfile.
7
+ *
8
+ * @param path - Filesystem path to load the contents from.
9
+ * @param encoding - Optional encoding to pass down to fs.readFile.
10
+ * @returns Promise returning VFile with loaded file contents.
11
+ */
12
+ export declare function readVirtualFile(path: string, encoding?: BufferEncoding | null): Promise<VirtualFile<unknown>>;
13
+ declare type WriteVFileOptions = Exclude<Parameters<typeof fsPromises['writeFile']>[2], undefined>;
14
+ /**
15
+ * Writes vfile to filesystem.
16
+ *
17
+ * @param vfile - The vfile to write.
18
+ * @param options - Options to pass down to fs.writeFile.
19
+ */
20
+ export declare function writeVirtualFile(vfile: VirtualFile, options?: WriteVFileOptions): Promise<void>;
21
+ export {};
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.writeVirtualFile = exports.readVirtualFile = void 0;
7
+ const promises_1 = __importDefault(require("fs/promises"));
8
+ const VirtualFile_1 = require("./VirtualFile");
9
+ /**
10
+ * Reads a file from filesystem and creates a vfile.
11
+ *
12
+ * @param path - Filesystem path to load the contents from.
13
+ * @param encoding - Optional encoding to pass down to fs.readFile.
14
+ * @returns Promise returning VFile with loaded file contents.
15
+ */
16
+ async function readVirtualFile(path, encoding = null) {
17
+ return new VirtualFile_1.VirtualFile({
18
+ path,
19
+ value: await promises_1.default.readFile(path, { encoding }),
20
+ });
21
+ }
22
+ exports.readVirtualFile = readVirtualFile;
23
+ /**
24
+ * Writes vfile to filesystem.
25
+ *
26
+ * @param vfile - The vfile to write.
27
+ * @param options - Options to pass down to fs.writeFile.
28
+ */
29
+ async function writeVirtualFile(vfile, options) {
30
+ return promises_1.default.writeFile(vfile.path, vfile.value, options);
31
+ }
32
+ exports.writeVirtualFile = writeVirtualFile;
33
+ //# sourceMappingURL=toVirtualFile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toVirtualFile.js","sourceRoot":"","sources":["../../src/virtual-file/toVirtualFile.ts"],"names":[],"mappings":";;;;;;AAAA,2DAAqC;AAErC,+CAA4C;AAE5C;;;;;;GAMG;AACI,KAAK,UAAU,eAAe,CACnC,IAAY,EACZ,WAAkC,IAAI;IAEtC,OAAO,IAAI,yBAAW,CAAC;QACrB,IAAI;QACJ,KAAK,EAAE,MAAM,kBAAU,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,CAAC;KACrD,CAAC,CAAC;AACL,CAAC;AARD,0CAQC;AAOD;;;;;GAKG;AACI,KAAK,UAAU,gBAAgB,CACpC,KAAkB,EAClB,OAA2B;IAE3B,OAAO,kBAAU,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AAChE,CAAC;AALD,4CAKC","sourcesContent":["import fsPromises from 'fs/promises';\n\nimport { VirtualFile } from './VirtualFile';\n\n/**\n * Reads a file from filesystem and creates a vfile.\n *\n * @param path - Filesystem path to load the contents from.\n * @param encoding - Optional encoding to pass down to fs.readFile.\n * @returns Promise returning VFile with loaded file contents.\n */\nexport async function readVirtualFile(\n path: string,\n encoding: BufferEncoding | null = null,\n) {\n return new VirtualFile({\n path,\n value: await fsPromises.readFile(path, { encoding }),\n });\n}\n\ntype WriteVFileOptions = Exclude<\n Parameters<typeof fsPromises['writeFile']>[2],\n undefined\n>;\n\n/**\n * Writes vfile to filesystem.\n *\n * @param vfile - The vfile to write.\n * @param options - Options to pass down to fs.writeFile.\n */\nexport async function writeVirtualFile(\n vfile: VirtualFile,\n options?: WriteVFileOptions,\n) {\n return fsPromises.writeFile(vfile.path, vfile.value, options);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/snaps-utils",
3
- "version": "0.25.0",
3
+ "version": "0.26.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/MetaMask/snaps-monorepo.git"
@@ -52,7 +52,7 @@
52
52
  "dependencies": {
53
53
  "@babel/core": "^7.18.6",
54
54
  "@babel/types": "^7.18.7",
55
- "@metamask/snaps-types": "^0.25.0",
55
+ "@metamask/snaps-types": "^0.26.0",
56
56
  "@metamask/utils": "^3.3.1",
57
57
  "@noble/hashes": "^1.1.3",
58
58
  "@scure/base": "^1.1.1",
@@ -62,7 +62,8 @@
62
62
  "rfdc": "^1.3.0",
63
63
  "semver": "^7.3.7",
64
64
  "ses": "^0.17.0",
65
- "superstruct": "^0.16.7"
65
+ "superstruct": "^0.16.7",
66
+ "validate-npm-package-name": "^5.0.0"
66
67
  },
67
68
  "devDependencies": {
68
69
  "@lavamoat/allow-scripts": "^2.0.3",
@@ -73,6 +74,7 @@
73
74
  "@metamask/eslint-config-typescript": "^11.0.0",
74
75
  "@types/jest": "^27.5.1",
75
76
  "@types/semver": "^7.3.10",
77
+ "@types/validate-npm-package-name": "^4.0.0",
76
78
  "@typescript-eslint/eslint-plugin": "^5.42.1",
77
79
  "@typescript-eslint/parser": "^5.42.1",
78
80
  "deepmerge": "^4.2.2",
@@ -85,7 +87,7 @@
85
87
  "eslint-plugin-prettier": "^4.2.1",
86
88
  "jest": "^29.0.2",
87
89
  "jest-it-up": "^2.0.0",
88
- "memfs": "^3.4.7",
90
+ "memfs": "^3.4.12",
89
91
  "prettier": "^2.7.1",
90
92
  "prettier-plugin-packagejson": "^2.2.11",
91
93
  "rimraf": "^3.0.2",
package/dist/url.d.ts DELETED
@@ -1,7 +0,0 @@
1
- /**
2
- * Checks whether a URL is valid.
3
- *
4
- * @param maybeUrl - The string to check.
5
- * @returns Whether the specified string is a valid URL.
6
- */
7
- export declare function isValidUrl(maybeUrl: string): maybeUrl is string;
package/dist/url.js DELETED
@@ -1,19 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isValidUrl = void 0;
4
- /**
5
- * Checks whether a URL is valid.
6
- *
7
- * @param maybeUrl - The string to check.
8
- * @returns Whether the specified string is a valid URL.
9
- */
10
- function isValidUrl(maybeUrl) {
11
- try {
12
- return Boolean(new URL(maybeUrl));
13
- }
14
- catch (_error) {
15
- return false;
16
- }
17
- }
18
- exports.isValidUrl = isValidUrl;
19
- //# sourceMappingURL=url.js.map
package/dist/url.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"url.js","sourceRoot":"","sources":["../src/url.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACH,SAAgB,UAAU,CAAC,QAAgB;IACzC,IAAI;QACF,OAAO,OAAO,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC;KACnC;IAAC,OAAO,MAAM,EAAE;QACf,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAND,gCAMC","sourcesContent":["/**\n * Checks whether a URL is valid.\n *\n * @param maybeUrl - The string to check.\n * @returns Whether the specified string is a valid URL.\n */\nexport function isValidUrl(maybeUrl: string): maybeUrl is string {\n try {\n return Boolean(new URL(maybeUrl));\n } catch (_error) {\n return false;\n }\n}\n"]}