@metamask/snaps-utils 7.5.0 → 7.7.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.
Files changed (79) hide show
  1. package/CHANGELOG.md +23 -1
  2. package/dist/{chunk-BZ7BMGXN.mjs → chunk-5ZIWKLVB.mjs} +17 -27
  3. package/dist/chunk-5ZIWKLVB.mjs.map +1 -0
  4. package/dist/{chunk-SWU464Y6.js → chunk-7LOVOG6X.js} +6 -6
  5. package/dist/{chunk-VXLHHSAP.mjs → chunk-BT2AEFEP.mjs} +3 -3
  6. package/dist/chunk-EVHDXNOC.mjs +35 -0
  7. package/dist/chunk-EVHDXNOC.mjs.map +1 -0
  8. package/dist/{chunk-4I22UHIU.mjs → chunk-EXEEDJ6N.mjs} +13 -9
  9. package/dist/chunk-EXEEDJ6N.mjs.map +1 -0
  10. package/dist/{chunk-YC2LIIR4.js → chunk-F72OSQD6.js} +5 -5
  11. package/dist/{chunk-A6E325SZ.js → chunk-HEXZ4DFV.js} +17 -2
  12. package/dist/chunk-HEXZ4DFV.js.map +1 -0
  13. package/dist/{chunk-L4DKSTK6.mjs → chunk-I4TRH6VO.mjs} +3 -2
  14. package/dist/{chunk-L4DKSTK6.mjs.map → chunk-I4TRH6VO.mjs.map} +1 -1
  15. package/dist/{chunk-IHHQU6IS.js → chunk-J5B5YRG5.js} +17 -27
  16. package/dist/chunk-J5B5YRG5.js.map +1 -0
  17. package/dist/{chunk-GTAYOKI4.mjs → chunk-NHGIT2SZ.mjs} +18 -3
  18. package/dist/chunk-NHGIT2SZ.mjs.map +1 -0
  19. package/dist/{chunk-R6VG7F6Y.mjs → chunk-NN2HXPZN.mjs} +3 -3
  20. package/dist/{chunk-ZUSNAQJU.js → chunk-OJM2SKJZ.js} +3 -2
  21. package/dist/chunk-OJM2SKJZ.js.map +1 -0
  22. package/dist/{chunk-MNCFAD4E.mjs → chunk-PTOH2SVI.mjs} +6 -2
  23. package/dist/chunk-PTOH2SVI.mjs.map +1 -0
  24. package/dist/chunk-QGCNQRIQ.js +35 -0
  25. package/dist/chunk-QGCNQRIQ.js.map +1 -0
  26. package/dist/{chunk-M3KAAQFK.js → chunk-W7KRIAIX.js} +9 -5
  27. package/dist/chunk-W7KRIAIX.js.map +1 -0
  28. package/dist/{chunk-LNZLPDBB.js → chunk-ZJKG5Q2C.js} +12 -8
  29. package/dist/chunk-ZJKG5Q2C.js.map +1 -0
  30. package/dist/handlers.js +2 -2
  31. package/dist/handlers.mjs +1 -1
  32. package/dist/icon.js +3 -2
  33. package/dist/icon.mjs +2 -1
  34. package/dist/index.executionenv.js +2 -2
  35. package/dist/index.executionenv.mjs +1 -1
  36. package/dist/index.js +13 -10
  37. package/dist/index.mjs +25 -22
  38. package/dist/manifest/index.js +4 -2
  39. package/dist/manifest/index.mjs +3 -1
  40. package/dist/manifest/manifest.js +7 -4
  41. package/dist/manifest/manifest.mjs +6 -3
  42. package/dist/manifest/node.js +7 -4
  43. package/dist/manifest/node.mjs +6 -3
  44. package/dist/manifest/validation.js +4 -2
  45. package/dist/manifest/validation.mjs +3 -1
  46. package/dist/node.js +14 -11
  47. package/dist/node.mjs +26 -23
  48. package/dist/npm.js +7 -4
  49. package/dist/npm.mjs +6 -3
  50. package/dist/structs.js +4 -2
  51. package/dist/structs.mjs +3 -1
  52. package/dist/svg.js +10 -0
  53. package/dist/svg.js.map +1 -0
  54. package/dist/svg.mjs +10 -0
  55. package/dist/svg.mjs.map +1 -0
  56. package/dist/tsconfig.build.tsbuildinfo +1 -1
  57. package/dist/types/handlers.d.ts +14 -112
  58. package/dist/types/manifest/validation.d.ts +1 -1
  59. package/dist/types/structs.d.ts +5 -1
  60. package/dist/types/svg.d.ts +14 -0
  61. package/dist/types/ui.d.ts +5 -5
  62. package/dist/ui.js +2 -2
  63. package/dist/ui.mjs +1 -1
  64. package/dist/validation.js +7 -4
  65. package/dist/validation.mjs +6 -3
  66. package/package.json +5 -4
  67. package/dist/chunk-4I22UHIU.mjs.map +0 -1
  68. package/dist/chunk-A6E325SZ.js.map +0 -1
  69. package/dist/chunk-BZ7BMGXN.mjs.map +0 -1
  70. package/dist/chunk-GTAYOKI4.mjs.map +0 -1
  71. package/dist/chunk-IHHQU6IS.js.map +0 -1
  72. package/dist/chunk-LNZLPDBB.js.map +0 -1
  73. package/dist/chunk-M3KAAQFK.js.map +0 -1
  74. package/dist/chunk-MNCFAD4E.mjs.map +0 -1
  75. package/dist/chunk-ZUSNAQJU.js.map +0 -1
  76. /package/dist/{chunk-SWU464Y6.js.map → chunk-7LOVOG6X.js.map} +0 -0
  77. /package/dist/{chunk-VXLHHSAP.mjs.map → chunk-BT2AEFEP.mjs.map} +0 -0
  78. /package/dist/{chunk-YC2LIIR4.js.map → chunk-F72OSQD6.js.map} +0 -0
  79. /package/dist/{chunk-R6VG7F6Y.mjs.map → chunk-NN2HXPZN.mjs.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/ui.tsx"],"sourcesContent":["import type { Component } from '@metamask/snaps-sdk';\nimport { NodeType } from '@metamask/snaps-sdk';\nimport type {\n BoldChildren,\n FieldElement,\n ItalicChildren,\n JSXElement,\n LinkElement,\n MaybeArray,\n RowChildren,\n StandardFormattingElement,\n TextChildren,\n} from '@metamask/snaps-sdk/jsx';\nimport {\n Italic,\n Link,\n Bold,\n Row,\n Text,\n Field,\n Image,\n Input,\n Heading,\n Form,\n Divider,\n Spinner,\n Copyable,\n Box,\n Button,\n Address,\n} from '@metamask/snaps-sdk/jsx';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport {\n assert,\n assertExhaustive,\n AssertionError,\n hasProperty,\n isPlainObject,\n} from '@metamask/utils';\nimport { lexer, walkTokens } from 'marked';\nimport type { Token, Tokens } from 'marked';\n\nconst MAX_TEXT_LENGTH = 50_000; // 50 kb\nconst ALLOWED_PROTOCOLS = ['https:', 'mailto:'];\n\n/**\n * Get the button variant from a legacy button component variant.\n *\n * @param variant - The legacy button component variant.\n * @returns The button variant.\n */\nfunction getButtonVariant(variant?: 'primary' | 'secondary' | undefined) {\n switch (variant) {\n case 'primary':\n return 'primary';\n case 'secondary':\n return 'destructive';\n default:\n return undefined;\n }\n}\n\n/**\n * Get the children of a JSX element. If there is only one child, the child is\n * returned directly. Otherwise, the children are returned as an array.\n *\n * @param elements - The JSX elements.\n * @returns The child or children.\n */\nfunction getChildren<Type>(elements: NonEmptyArray<Type>) {\n if (elements.length === 1) {\n return elements[0];\n }\n\n return elements;\n}\n\n/**\n * Get the text of a link token.\n *\n * @param token - The link token.\n * @returns The text of the link token.\n */\nfunction getLinkText(token: Tokens.Link | Tokens.Generic) {\n if (token.tokens && token.tokens.length > 0) {\n return getChildren(\n token.tokens.flatMap(\n getTextChildFromToken,\n ) as NonEmptyArray<TextChildren>,\n );\n }\n\n return token.href;\n}\n\n/**\n * Get the text child from a list of markdown tokens.\n *\n * @param tokens - The markdown tokens.\n * @returns The text child.\n */\nfunction getTextChildFromTokens(tokens: Token[]) {\n return getChildren(\n tokens.flatMap(getTextChildFromToken) as NonEmptyArray<TextChildren>,\n );\n}\n\n/**\n * Get the text child from a markdown token.\n *\n * @param token - The markdown token.\n * @returns The text child.\n */\nfunction getTextChildFromToken(token: Token): TextChildren {\n switch (token.type) {\n case 'link': {\n return <Link href={token.href} children={getLinkText(token)} />;\n }\n\n case 'text':\n return token.text;\n\n case 'strong':\n return (\n <Bold>\n {\n getTextChildFromTokens(\n // Due to the way `marked` is typed, `token.tokens` can be\n // `undefined`, but it's a required field of `Tokens.Bold`, so we\n // can safely cast it to `Token[]`.\n token.tokens as Token[],\n ) as BoldChildren\n }\n </Bold>\n );\n\n case 'em':\n return (\n <Italic>\n {\n getTextChildFromTokens(\n // Due to the way `marked` is typed, `token.tokens` can be\n // `undefined`, but it's a required field of `Tokens.Bold`, so we\n // can safely cast it to `Token[]`.\n token.tokens as Token[],\n ) as ItalicChildren\n }\n </Italic>\n );\n\n default:\n return null;\n }\n}\n\n/**\n * Get all text children from a markdown string.\n *\n * @param value - The markdown string.\n * @returns The text children.\n */\nexport function getTextChildren(\n value: string,\n): NonEmptyArray<string | StandardFormattingElement | LinkElement> {\n const rootTokens = lexer(value, { gfm: false });\n const children: (string | StandardFormattingElement | LinkElement | null)[] =\n [];\n\n walkTokens(rootTokens, (token) => {\n if (token.type === 'paragraph') {\n if (children.length > 0) {\n children.push('\\n\\n');\n }\n\n const { tokens } = token as Tokens.Paragraph;\n children.push(...tokens.flatMap(getTextChildFromToken));\n }\n });\n\n return children.filter((child) => child !== null) as NonEmptyArray<\n string | StandardFormattingElement | LinkElement\n >;\n}\n\n/**\n * Validate the text size of a component. The text size is the total length of\n * all text in the component.\n *\n * @param component - The component to validate.\n * @throws An error if the text size exceeds the maximum allowed size.\n */\nfunction validateComponentTextSize(component: Component) {\n const textSize = getTotalTextLength(component);\n assert(\n textSize <= MAX_TEXT_LENGTH,\n `The text in a Snap UI may not be larger than ${\n MAX_TEXT_LENGTH / 1000\n } kB.`,\n );\n}\n\n/**\n * Get a JSX element from a legacy UI component. This supports all legacy UI\n * components, and maps them to their JSX equivalents where possible.\n *\n * This function validates the text size of the component, but does not validate\n * the total size. The total size of the component should be validated before\n * calling this function.\n *\n * @param legacyComponent - The legacy UI component.\n * @returns The JSX element.\n */\nexport function getJsxElementFromComponent(\n legacyComponent: Component,\n): JSXElement {\n validateComponentTextSize(legacyComponent);\n\n /**\n * Get the JSX element for a component. This function is recursive and will\n * call itself for child components.\n *\n * @param component - The component to convert to a JSX element.\n * @returns The JSX element.\n */\n function getElement(component: Component) {\n switch (component.type) {\n case NodeType.Address:\n return <Address address={component.value} />;\n\n case NodeType.Button:\n return (\n <Button\n name={component.name}\n variant={getButtonVariant(component.variant)}\n type={component.buttonType}\n >\n {component.value}\n </Button>\n );\n\n case NodeType.Copyable:\n return (\n <Copyable value={component.value} sensitive={component.sensitive} />\n );\n\n case NodeType.Divider:\n return <Divider />;\n\n case NodeType.Form:\n return (\n <Form name={component.name}>\n {getChildren(\n component.children.map(getElement) as NonEmptyArray<FieldElement>,\n )}\n </Form>\n );\n\n case NodeType.Heading:\n return <Heading children={component.value} />;\n\n case NodeType.Image:\n // `Image` supports `alt`, but the legacy `Image` component does not.\n return <Image src={component.value} />;\n\n case NodeType.Input:\n return (\n <Field label={component.label} error={component.error}>\n <Input\n name={component.name}\n type={component.inputType}\n value={component.value}\n placeholder={component.placeholder}\n />\n </Field>\n );\n\n case NodeType.Panel:\n // `Panel` is renamed to `Box` in JSX.\n return (\n <Box\n children={getChildren(\n component.children.map(getElement) as NonEmptyArray<JSXElement>,\n )}\n />\n );\n\n case NodeType.Row:\n return (\n <Row label={component.label}>\n {getElement(component.value) as RowChildren}\n </Row>\n );\n\n case NodeType.Spinner:\n return <Spinner />;\n\n case NodeType.Text:\n return <Text>{getChildren(getTextChildren(component.value))}</Text>;\n\n /* istanbul ignore next 2 */\n default:\n return assertExhaustive(component);\n }\n }\n\n return getElement(legacyComponent);\n}\n\n/**\n * Extract all links from a Markdown text string using the `marked` lexer.\n *\n * @param text - The markdown text string.\n * @returns A list of URLs linked to in the string.\n */\nfunction getMarkdownLinks(text: string) {\n const tokens = lexer(text, { gfm: false });\n const links: Tokens.Link[] = [];\n\n // Walk the lexed tokens and collect all link tokens\n walkTokens(tokens, (token) => {\n if (token.type === 'link') {\n links.push(token as Tokens.Link);\n }\n });\n\n return links;\n}\n\n/**\n * Validate a link against the phishing list.\n *\n * @param link - The link to validate.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n */\nfunction validateLink(\n link: string,\n isOnPhishingList: (url: string) => boolean,\n) {\n try {\n const url = new URL(link);\n assert(\n ALLOWED_PROTOCOLS.includes(url.protocol),\n `Protocol must be one of: ${ALLOWED_PROTOCOLS.join(', ')}.`,\n );\n\n const hostname =\n url.protocol === 'mailto:' ? url.pathname.split('@')[1] : url.hostname;\n\n assert(!isOnPhishingList(hostname), 'The specified URL is not allowed.');\n } catch (error) {\n throw new Error(\n `Invalid URL: ${\n error instanceof AssertionError ? error.message : 'Unable to parse URL.'\n }`,\n );\n }\n}\n\n/**\n * Search for Markdown links in a string and checks them against the phishing\n * list.\n *\n * @param text - The text to verify.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n * @throws If the text contains a link that is not allowed.\n */\nexport function validateTextLinks(\n text: string,\n isOnPhishingList: (url: string) => boolean,\n) {\n const links = getMarkdownLinks(text);\n\n for (const link of links) {\n validateLink(link.href, isOnPhishingList);\n }\n}\n\n/**\n * Walk a JSX tree and validate each {@link LinkElement} node against the\n * phishing list.\n *\n * @param node - The JSX node to walk.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n */\nexport function validateJsxLinks(\n node: JSXElement,\n isOnPhishingList: (url: string) => boolean,\n) {\n walkJsx(node, (childNode) => {\n if (childNode.type !== 'Link') {\n return;\n }\n\n validateLink(childNode.props.href, isOnPhishingList);\n });\n}\n\n/**\n * Calculate the total length of all text in the component.\n *\n * @param component - A custom UI component.\n * @returns The total length of all text components in the component.\n */\nexport function getTotalTextLength(component: Component): number {\n const { type } = component;\n\n switch (type) {\n case NodeType.Panel:\n return component.children.reduce<number>(\n // This is a bug in TypeScript: https://github.com/microsoft/TypeScript/issues/48313\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n (sum, node) => sum + getTotalTextLength(node),\n 0,\n );\n\n case NodeType.Row:\n return getTotalTextLength(component.value);\n\n case NodeType.Text:\n return component.value.length;\n\n default:\n return 0;\n }\n}\n\n/**\n * Check if a JSX element has children.\n *\n * @param element - A JSX element.\n * @returns `true` if the element has children, `false` otherwise.\n */\nexport function hasChildren<Element extends JSXElement>(\n element: Element,\n): element is Element & {\n props: { children: MaybeArray<JSXElement | string> };\n} {\n return hasProperty(element.props, 'children');\n}\n\n/**\n * Get the children of a JSX element as an array. If the element has only one\n * child, the child is returned as an array.\n *\n * @param element - A JSX element.\n * @returns The children of the element.\n */\nexport function getJsxChildren(element: JSXElement): (JSXElement | string)[] {\n if (hasChildren(element)) {\n if (Array.isArray(element.props.children)) {\n // @ts-expect-error - Each member of the union type has signatures, but\n // none of those signatures are compatible with each other.\n return element.props.children.filter(Boolean);\n }\n\n if (element.props.children) {\n return [element.props.children];\n }\n }\n\n return [];\n}\n\n/**\n * Walk a JSX tree and call a callback on each node.\n *\n * @param node - The JSX node to walk.\n * @param callback - The callback to call on each node.\n * @returns The result of the callback, if any.\n */\nexport function walkJsx<Value>(\n node: JSXElement | JSXElement[],\n callback: (node: JSXElement) => Value | undefined,\n): Value | undefined {\n if (Array.isArray(node)) {\n for (const child of node) {\n const childResult = walkJsx(child as JSXElement, callback);\n if (childResult !== undefined) {\n return childResult;\n }\n }\n\n return undefined;\n }\n\n const result = callback(node);\n if (result !== undefined) {\n return result;\n }\n\n if (\n hasProperty(node, 'props') &&\n isPlainObject(node.props) &&\n hasProperty(node.props, 'children')\n ) {\n const children = getJsxChildren(node);\n for (const child of children) {\n if (isPlainObject(child)) {\n const childResult = walkJsx(child, callback);\n if (childResult !== undefined) {\n return childResult;\n }\n }\n }\n }\n\n return undefined;\n}\n"],"mappings":";AACA,SAAS,gBAAgB;AAYzB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,OAAO,kBAAkB;AA6ErB;AA1Eb,IAAM,kBAAkB;AACxB,IAAM,oBAAoB,CAAC,UAAU,SAAS;AAQ9C,SAAS,iBAAiB,SAA+C;AACvE,UAAQ,SAAS;AAAA,IACf,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AASA,SAAS,YAAkB,UAA+B;AACxD,MAAI,SAAS,WAAW,GAAG;AACzB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ACT;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/structs.ts"],"sourcesContent":["import { union } from '@metamask/snaps-sdk';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assert, isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport type { Failure } from 'superstruct';\nimport {\n is,\n validate,\n type as superstructType,\n Struct,\n StructError,\n create,\n} from 'superstruct';\nimport type { AnyStruct } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * Infer a struct type, only if it matches the specified type. This is useful\n * for defining types and structs that are related to each other in separate\n * files.\n *\n * @example\n * ```typescript\n * // In file A\n * export type GetFileArgs = {\n * path: string;\n * encoding?: EnumToUnion<AuxiliaryFileEncoding>;\n * };\n *\n * // In file B\n * export const GetFileArgsStruct = object(...);\n *\n * // If the type and struct are in the same file, this will return the type.\n * // Otherwise, it will return `never`.\n * export type GetFileArgs =\n * InferMatching<typeof GetFileArgsStruct, GetFileArgs>;\n * ```\n */\nexport type InferMatching<\n StructType extends Struct<any, any>,\n Type,\n> = StructType['TYPE'] extends Type ? Type : never;\n\n/**\n * Colorize a value with a color function. This is useful for colorizing values\n * in error messages. If colorization is disabled, the original value is\n * returned.\n *\n * @param value - The value to colorize.\n * @param colorFunction - The color function to use.\n * @param enabled - Whether to colorize the value.\n * @returns The colorized value, or the original value if colorization is\n * disabled.\n */\nfunction color(\n value: string,\n colorFunction: (value: string) => string,\n enabled: boolean,\n) {\n if (enabled) {\n return colorFunction(value);\n }\n\n return value;\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n colorize = true,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(\n struct,\n [...failures()],\n colorize,\n )}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n colorize?: boolean;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @param options.colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n colorize,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(\n struct,\n prefix,\n suffix,\n error,\n () => arrayToGenerator(error.failures()),\n colorize,\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n colorize = true,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => color(type, green, colorize));\n }\n\n return null;\n}\n\n/**\n * Get an error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure, colorize = true) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${color(failure.path.join('.'), bold, colorize)} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n colorize = true,\n) {\n const received = color(JSON.stringify(failure.value), red, colorize);\n const prefix = getStructErrorPrefix(failure, colorize);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct, colorize);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(\n /the literal `(.+)`,/u,\n `the value to be \\`${color('$1', green, colorize)}\\`,`,\n )\n .replace(\n /, but received: (.+)/u,\n `, but received: ${color('$1', red, colorize)}`,\n );\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${color(\n failure.path.join('.'),\n bold,\n colorize,\n )}, received: ${received}.`;\n }\n\n if (failure.refinement === 'size') {\n const message = failure.message\n .replace(\n /length between `(\\d+)` and `(\\d+)`/u,\n `length between ${color('$1', green, colorize)} and ${color(\n '$2',\n green,\n colorize,\n )},`,\n )\n .replace(/length of `(\\d+)`/u, `length of ${color('$1', red, colorize)}`)\n .replace(/a array/u, 'an array');\n\n return `${prefix}${message}.`;\n }\n\n return `${prefix}Expected a value of type ${color(\n failure.type,\n green,\n colorize,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n colorize = true,\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure, colorize)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n\n/**\n * Validate a union struct, and throw readable errors if the value does not\n * satisfy the struct. This is useful for improving the error messages returned\n * by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` union struct to validate the value against.\n * This struct must be a union of object structs, and must have at least one\n * shared key to validate against.\n * @param structKey - The key to validate against. This key must be present in\n * all the object structs in the union struct, and is expected to be a literal\n * value.\n * @param coerce - Whether to coerce the value to satisfy the struct. Defaults\n * to `false`.\n * @returns The validated value.\n * @throws If the value does not satisfy the struct.\n * @example\n * const struct = union([\n * object({ type: literal('a'), value: string() }),\n * object({ type: literal('b'), value: number() }),\n * object({ type: literal('c'), value: boolean() }),\n * // ...\n * ]);\n *\n * // At path: type — Expected the value to be one of: \"a\", \"b\", \"c\", but received: \"d\".\n * validateUnion({ type: 'd', value: 'foo' }, struct, 'type');\n *\n * // At path: value — Expected a value of type string, but received: 42.\n * validateUnion({ type: 'a', value: 42 }, struct, 'value');\n */\nexport function validateUnion<Type, Schema extends readonly Struct<any, any>[]>(\n value: unknown,\n struct: Struct<Type, Schema>,\n structKey: keyof Type,\n coerce = false,\n) {\n assert(\n struct.schema,\n 'Expected a struct with a schema. Make sure to use `union` from `@metamask/snaps-sdk`.',\n );\n assert(struct.schema.length > 0, 'Expected a non-empty array of structs.');\n\n const keyUnion = struct.schema.map(\n (innerStruct) => innerStruct.schema[structKey],\n // This is guaranteed to be a non-empty array by the assertion above. We\n // need to cast it since `superstruct` requires a non-empty array of structs\n // for the `union` struct.\n ) as NonEmptyArray<Struct>;\n\n const key = superstructType({\n [structKey]: union(keyUnion),\n });\n\n const [keyError] = validate(value, key, { coerce });\n if (keyError) {\n throw new Error(\n getStructFailureMessage(key, keyError.failures()[0], false),\n );\n }\n\n // At this point it's guaranteed that the value is an object, so we can safely\n // cast it to a Record.\n const objectValue = value as Record<PropertyKey, unknown>;\n const objectStructs = struct.schema.filter((innerStruct) =>\n is(objectValue[structKey], innerStruct.schema[structKey]),\n );\n\n assert(objectStructs.length > 0, 'Expected a struct to match the value.');\n\n // We need to validate the value against all the object structs that match the\n // struct key, and return the first validated value.\n const validationResults = objectStructs.map((objectStruct) =>\n validate(objectValue, objectStruct, { coerce }),\n );\n\n const validatedValue = validationResults.find(([error]) => !error);\n if (validatedValue) {\n return validatedValue[1];\n }\n\n assert(validationResults[0][0], 'Expected at least one error.');\n\n // If there is no validated value, we need to find the error with the least\n // number of failures (with the assumption that it's the most specific error).\n const validationError = validationResults.reduce((error, [innerError]) => {\n assert(innerError, 'Expected an error.');\n if (innerError.failures().length < error.failures().length) {\n return innerError;\n }\n\n return error;\n }, validationResults[0][0]);\n\n throw new Error(\n getStructFailureMessage(struct, validationError.failures()[0], false),\n );\n}\n\n/**\n * Create a value with the coercion logic of a union struct, and throw readable\n * errors if the value does not satisfy the struct. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` union struct to validate the value against.\n * This struct must be a union of object structs, and must have at least one\n * shared key to validate against.\n * @param structKey - The key to validate against. This key must be present in\n * all the object structs in the union struct, and is expected to be a literal\n * value.\n * @returns The validated value.\n * @throws If the value does not satisfy the struct.\n * @see validateUnion\n */\nexport function createUnion<Type, Schema extends readonly Struct<any, any>[]>(\n value: unknown,\n struct: Struct<Type, Schema>,\n structKey: keyof Type,\n) {\n return validateUnion(value, struct, structKey, true);\n}\n"],"mappings":";;;;;AAAA,SAAS,aAAa;AAEtB,SAAS,QAAQ,gBAAgB;AACjC,SAAS,MAAM,OAAO,WAAW;AAEjC;AAAA,EACE;AAAA,EACA;AAAA,EACA,QAAQ;AAAA,EACR;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA2CP,SAAS,MACP,OACA,eACA,SACA;AACA,MAAI,SAAS;AACX,WAAO,cAAc,KAAK;AAAA,EAC5B;AAEA,SAAO;AACT;AAWO,SAAS,MACd,MACA,QACA;AACA,SAAO,IAAI,OAAO;AAAA,IAChB,GAAG;AAAA,IACH,MAAM;AAAA,EACR,CAAC;AACH;AAEO,IAAM,mBAAN,cAA6C,YAAY;AAAA,EAC9D,YACE,QACA,QACA,QACA,SACA,UACA,WAAW,MACX;AACA,UAAM,SAAS,QAAQ;AAEvB,SAAK,OAAO;AACZ,SAAK,UAAU,GAAG,MAAM;AAAA;AAAA,EAAQ;AAAA,MAC9B;AAAA,MACA,CAAC,GAAG,SAAS,CAAC;AAAA,MACd;AAAA,IACF,CAAC,GAAG,SAAS;AAAA;AAAA,EAAO,MA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Z,aAAO,mBAAmB,UAAU,KAAK;AAAA,IAE3C,KAAK,SAAS;AACZ,aAAO,UAAU,MAAM;AAAA,IAEzB;AACE,aAAO;AAAA,EACX;AACF;AAQO,SAAS,YACd,SAGA;AACA,SAAO,YAAY,QAAQ,OAAO,UAAU;AAC9C;AASO,SAAS,eAAe,SAA8C;AAC3E,MAAI,YAAY,OAAO,GAAG;AACxB,QAAI,MAAM,QAAQ,QAAQ,MAAM,QAAQ,GAAG;AAGzC,aAAO,QAAQ,MAAM,SAAS,OAAO,OAAO;AAAA,IAC9C;AAEA,QAAI,QAAQ,MAAM,UAAU;AAC1B,aAAO,CAAC,QAAQ,MAAM,QAAQ;AAAA,IAChC;AAAA,EACF;AAEA,SAAO,CAAC;AACV;AASO,SAAS,QACd,MACA,UACmB;AACnB,MAAI,MAAM,QAAQ,IAAI,GAAG;AACvB,eAAW,SAAS,MAAM;AACxB,YAAM,cAAc,QAAQ,OAAqB,QAAQ;AACzD,UAAI,gBAAgB,QAAW;AAC7B,eAAO;AAAA,MACT;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,SAAS,IAAI;AAC5B,MAAI,WAAW,QAAW;AACxB,WAAO;AAAA,EACT;AAEA,MACE,YAAY,MAAM,OAAO,KACzB,cAAc,KAAK,KAAK,KACxB,YAAY,KAAK,OAAO,UAAU,GAClC;AACA,UAAM,WAAW,eAAe,IAAI;AACpC,eAAW,SAAS,UAAU;AAC5B,UAAI,cAAc,KAAK,GAAG;AACxB,cAAM,cAAc,QAAQ,OAAO,QAAQ;AAC3C,YAAI,gBAAgB,QAAW;AAC7B,iBAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT","sourcesContent":["import type { Component } from '@metamask/snaps-sdk';\nimport { NodeType } from '@metamask/snaps-sdk';\nimport type {\n BoldChildren,\n FieldElement,\n ItalicChildren,\n JSXElement,\n LinkElement,\n MaybeArray,\n RowChildren,\n StandardFormattingElement,\n TextChildren,\n} from '@metamask/snaps-sdk/jsx';\nimport {\n Italic,\n Link,\n Bold,\n Row,\n Text,\n Field,\n Image,\n Input,\n Heading,\n Form,\n Divider,\n Spinner,\n Copyable,\n Box,\n Button,\n Address,\n} from '@metamask/snaps-sdk/jsx';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport {\n assert,\n assertExhaustive,\n AssertionError,\n hasProperty,\n isPlainObject,\n} from '@metamask/utils';\nimport { lexer, walkTokens } from 'marked';\nimport type { Token, Tokens } from 'marked';\n\nconst MAX_TEXT_LENGTH = 50_000; // 50 kb\nconst ALLOWED_PROTOCOLS = ['https:', 'mailto:'];\n\n/**\n * Get the button variant from a legacy button component variant.\n *\n * @param variant - The legacy button component variant.\n * @returns The button variant.\n */\nfunction getButtonVariant(variant?: 'primary' | 'secondary' | undefined) {\n switch (variant) {\n case 'primary':\n return 'primary';\n case 'secondary':\n return 'destructive';\n default:\n return undefined;\n }\n}\n\n/**\n * Get the children of a JSX element. If there is only one child, the child is\n * returned directly. Otherwise, the children are returned as an array.\n *\n * @param elements - The JSX elements.\n * @returns The child or children.\n */\nfunction getChildren<Type>(elements: NonEmptyArray<Type>) {\n if (elements.length === 1) {\n return elements[0];\n }\n\n return elements;\n}\n\n/**\n * Get the text of a link token.\n *\n * @param token - The link token.\n * @returns The text of the link token.\n */\nfunction getLinkText(token: Tokens.Link | Tokens.Generic) {\n if (token.tokens && token.tokens.length > 0) {\n return getChildren(\n token.tokens.flatMap(\n getTextChildFromToken,\n ) as NonEmptyArray<TextChildren>,\n );\n }\n\n return token.href;\n}\n\n/**\n * Get the text child from a list of markdown tokens.\n *\n * @param tokens - The markdown tokens.\n * @returns The text child.\n */\nfunction getTextChildFromTokens(tokens: Token[]) {\n return getChildren(\n tokens.flatMap(getTextChildFromToken) as NonEmptyArray<TextChildren>,\n );\n}\n\n/**\n * Get the text child from a markdown token.\n *\n * @param token - The markdown token.\n * @returns The text child.\n */\nfunction getTextChildFromToken(token: Token): TextChildren {\n switch (token.type) {\n case 'link': {\n return <Link href={token.href} children={getLinkText(token)} />;\n }\n\n case 'text':\n return token.text;\n\n case 'strong':\n return (\n <Bold>\n {\n getTextChildFromTokens(\n // Due to the way `marked` is typed, `token.tokens` can be\n // `undefined`, but it's a required field of `Tokens.Bold`, so we\n // can safely cast it to `Token[]`.\n token.tokens as Token[],\n ) as BoldChildren\n }\n </Bold>\n );\n\n case 'em':\n return (\n <Italic>\n {\n getTextChildFromTokens(\n // Due to the way `marked` is typed, `token.tokens` can be\n // `undefined`, but it's a required field of `Tokens.Bold`, so we\n // can safely cast it to `Token[]`.\n token.tokens as Token[],\n ) as ItalicChildren\n }\n </Italic>\n );\n\n default:\n return null;\n }\n}\n\n/**\n * Get all text children from a markdown string.\n *\n * @param value - The markdown string.\n * @returns The text children.\n */\nexport function getTextChildren(\n value: string,\n): NonEmptyArray<string | StandardFormattingElement | LinkElement> {\n const rootTokens = lexer(value, { gfm: false });\n const children: (string | StandardFormattingElement | LinkElement | null)[] =\n [];\n\n walkTokens(rootTokens, (token) => {\n if (token.type === 'paragraph') {\n if (children.length > 0) {\n children.push('\\n\\n');\n }\n\n const { tokens } = token as Tokens.Paragraph;\n children.push(...tokens.flatMap(getTextChildFromToken));\n }\n });\n\n return children.filter((child) => child !== null) as NonEmptyArray<\n string | StandardFormattingElement | LinkElement\n >;\n}\n\n/**\n * Validate the text size of a component. The text size is the total length of\n * all text in the component.\n *\n * @param component - The component to validate.\n * @throws An error if the text size exceeds the maximum allowed size.\n */\nfunction validateComponentTextSize(component: Component) {\n const textSize = getTotalTextLength(component);\n assert(\n textSize <= MAX_TEXT_LENGTH,\n `The text in a Snap UI may not be larger than ${\n MAX_TEXT_LENGTH / 1000\n } kB.`,\n );\n}\n\n/**\n * Get a JSX element from a legacy UI component. This supports all legacy UI\n * components, and maps them to their JSX equivalents where possible.\n *\n * This function validates the text size of the component, but does not validate\n * the total size. The total size of the component should be validated before\n * calling this function.\n *\n * @param legacyComponent - The legacy UI component.\n * @returns The JSX element.\n */\nexport function getJsxElementFromComponent(\n legacyComponent: Component,\n): JSXElement {\n validateComponentTextSize(legacyComponent);\n\n /**\n * Get the JSX element for a component. This function is recursive and will\n * call itself for child components.\n *\n * @param component - The component to convert to a JSX element.\n * @returns The JSX element.\n */\n function getElement(component: Component) {\n switch (component.type) {\n case NodeType.Address:\n return <Address address={component.value} />;\n\n case NodeType.Button:\n return (\n <Button\n name={component.name}\n variant={getButtonVariant(component.variant)}\n type={component.buttonType}\n >\n {component.value}\n </Button>\n );\n\n case NodeType.Copyable:\n return (\n <Copyable value={component.value} sensitive={component.sensitive} />\n );\n\n case NodeType.Divider:\n return <Divider />;\n\n case NodeType.Form:\n return (\n <Form name={component.name}>\n {getChildren(\n component.children.map(getElement) as NonEmptyArray<FieldElement>,\n )}\n </Form>\n );\n\n case NodeType.Heading:\n return <Heading children={component.value} />;\n\n case NodeType.Image:\n // `Image` supports `alt`, but the legacy `Image` component does not.\n return <Image src={component.value} />;\n\n case NodeType.Input:\n return (\n <Field label={component.label} error={component.error}>\n <Input\n name={component.name}\n type={component.inputType}\n value={component.value}\n placeholder={component.placeholder}\n />\n </Field>\n );\n\n case NodeType.Panel:\n // `Panel` is renamed to `Box` in JSX.\n return (\n <Box\n children={getChildren(\n component.children.map(getElement) as NonEmptyArray<JSXElement>,\n )}\n />\n );\n\n case NodeType.Row:\n return (\n <Row label={component.label}>\n {getElement(component.value) as RowChildren}\n </Row>\n );\n\n case NodeType.Spinner:\n return <Spinner />;\n\n case NodeType.Text:\n return <Text>{getChildren(getTextChildren(component.value))}</Text>;\n\n /* istanbul ignore next 2 */\n default:\n return assertExhaustive(component);\n }\n }\n\n return getElement(legacyComponent);\n}\n\n/**\n * Extract all links from a Markdown text string using the `marked` lexer.\n *\n * @param text - The markdown text string.\n * @returns A list of URLs linked to in the string.\n */\nfunction getMarkdownLinks(text: string) {\n const tokens = lexer(text, { gfm: false });\n const links: Tokens.Link[] = [];\n\n // Walk the lexed tokens and collect all link tokens\n walkTokens(tokens, (token) => {\n if (token.type === 'link') {\n links.push(token as Tokens.Link);\n }\n });\n\n return links;\n}\n\n/**\n * Validate a link against the phishing list.\n *\n * @param link - The link to validate.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n */\nfunction validateLink(\n link: string,\n isOnPhishingList: (url: string) => boolean,\n) {\n try {\n const url = new URL(link);\n assert(\n ALLOWED_PROTOCOLS.includes(url.protocol),\n `Protocol must be one of: ${ALLOWED_PROTOCOLS.join(', ')}.`,\n );\n\n const hostname =\n url.protocol === 'mailto:' ? url.pathname.split('@')[1] : url.hostname;\n\n assert(!isOnPhishingList(hostname), 'The specified URL is not allowed.');\n } catch (error) {\n throw new Error(\n `Invalid URL: ${\n error instanceof AssertionError ? error.message : 'Unable to parse URL.'\n }`,\n );\n }\n}\n\n/**\n * Search for Markdown links in a string and checks them against the phishing\n * list.\n *\n * @param text - The text to verify.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n * @throws If the text contains a link that is not allowed.\n */\nexport function validateTextLinks(\n text: string,\n isOnPhishingList: (url: string) => boolean,\n) {\n const links = getMarkdownLinks(text);\n\n for (const link of links) {\n validateLink(link.href, isOnPhishingList);\n }\n}\n\n/**\n * Walk a JSX tree and validate each {@link LinkElement} node against the\n * phishing list.\n *\n * @param node - The JSX node to walk.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n */\nexport function validateJsxLinks(\n node: JSXElement,\n isOnPhishingList: (url: string) => boolean,\n) {\n walkJsx(node, (childNode) => {\n if (childNode.type !== 'Link') {\n return;\n }\n\n validateLink(childNode.props.href, isOnPhishingList);\n });\n}\n\n/**\n * Calculate the total length of all text in the component.\n *\n * @param component - A custom UI component.\n * @returns The total length of all text components in the component.\n */\nexport function getTotalTextLength(component: Component): number {\n const { type } = component;\n\n switch (type) {\n case NodeType.Panel:\n return component.children.reduce<number>(\n // This is a bug in TypeScript: https://github.com/microsoft/TypeScript/issues/48313\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n (sum, node) => sum + getTotalTextLength(node),\n 0,\n );\n\n case NodeType.Row:\n return getTotalTextLength(component.value);\n\n case NodeType.Text:\n return component.value.length;\n\n default:\n return 0;\n }\n}\n\n/**\n * Check if a JSX element has children.\n *\n * @param element - A JSX element.\n * @returns `true` if the element has children, `false` otherwise.\n */\nexport function hasChildren<Element extends JSXElement>(\n element: Element,\n): element is Element & {\n props: { children: MaybeArray<JSXElement | string> };\n} {\n return hasProperty(element.props, 'children');\n}\n\n/**\n * Get the children of a JSX element as an array. If the element has only one\n * child, the child is returned as an array.\n *\n * @param element - A JSX element.\n * @returns The children of the element.\n */\nexport function getJsxChildren(element: JSXElement): (JSXElement | string)[] {\n if (hasChildren(element)) {\n if (Array.isArray(element.props.children)) {\n // @ts-expect-error - Each member of the union type has signatures, but\n // none of those signatures are compatible with each other.\n return element.props.children.filter(Boolean);\n }\n\n if (element.props.children) {\n return [element.props.children];\n }\n }\n\n return [];\n}\n\n/**\n * Walk a JSX tree and call a callback on each node.\n *\n * @param node - The JSX node to walk.\n * @param callback - The callback to call on each node.\n * @returns The result of the callback, if any.\n */\nexport function walkJsx<Value>(\n node: JSXElement | JSXElement[],\n callback: (node: JSXElement) => Value | undefined,\n): Value | undefined {\n if (Array.isArray(node)) {\n for (const child of node) {\n const childResult = walkJsx(child as JSXElement, callback);\n if (childResult !== undefined) {\n return childResult;\n }\n }\n\n return undefined;\n }\n\n const result = callback(node);\n if (result !== undefined) {\n return result;\n }\n\n if (\n hasProperty(node, 'props') &&\n isPlainObject(node.props) &&\n hasProperty(node.props, 'children')\n ) {\n const children = getJsxChildren(node);\n for (const child of children) {\n if (isPlainObject(child)) {\n const childResult = walkJsx(child, callback);\n if (childResult !== undefined) {\n return childResult;\n }\n }\n }\n }\n\n return undefined;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/manifest/validation.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,+BAA+B;AA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A,EACD,oBAAoB,SAAS,wBAAwB;AAAA,EACrD,oBAAoB;AAAA,EACpB,iBAAiB,QAAQ,KAAK;AAAA,EAC9B,SAAS,SAAS,OAAO,CAAC;AAAA;AAC5B,CAAC;AAUM,SAAS,eAAe,OAAuC;AACpE,SAAO,GAAG,OAAO,kBAAkB;AACrC;AAQO,SAAS,qBACd,OAC+B;AAC/B;AAAA,IACE;AAAA,IACA;AAAA,IACA,uCAA6B;AAAA,EAC/B;AACF;AASO,SAAS,mBAAmB,OAA8B;AAE/D,SAAO,OAAO,OAAO,kBAAkB;AACzC","sourcesContent":["import type { SupportedCurve } from '@metamask/key-tree';\nimport { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport type { EmptyObject, InitialPermissions } from '@metamask/snaps-sdk';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n inMilliseconds,\n Duration,\n} from '@metamask/utils';\nimport type { Describe, Infer, Struct } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n enums,\n integer,\n is,\n literal,\n object,\n optional,\n refine,\n record,\n size,\n string,\n type,\n union,\n intersection,\n assign,\n} from 'superstruct';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { KeyringOriginsStruct, RpcOriginsStruct } from '../json-rpc';\nimport { ChainIdStruct } from '../namespace';\nimport { SnapIdStruct } from '../snaps';\nimport type { InferMatching } from '../structs';\nimport { NameStruct, NpmSnapFileNames, uri } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <\n Type extends { path: string[]; curve: string },\n Schema,\n>(\n struct: Struct<Type, Schema>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\nexport const CurveStruct: Describe<SupportedCurve> = enums([\n 'ed25519',\n 'secp256k1',\n 'ed25519Bip32',\n]);\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: CurveStruct,\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\nexport const ChainIdsStruct = size(array(ChainIdStruct), 1, Infinity);\n\nexport const LookupMatchersStruct = union([\n object({\n tlds: size(array(string()), 1, Infinity),\n }),\n object({\n schemes: size(array(string()), 1, Infinity),\n }),\n object({\n tlds: size(array(string()), 1, Infinity),\n schemes: size(array(string()), 1, Infinity),\n }),\n]);\n\nexport const MINIMUM_REQUEST_TIMEOUT = inMilliseconds(5, Duration.Second);\nexport const MAXIMUM_REQUEST_TIMEOUT = inMilliseconds(3, Duration.Minute);\n\nexport const MaxRequestTimeStruct = size(\n integer(),\n MINIMUM_REQUEST_TIMEOUT,\n MAXIMUM_REQUEST_TIMEOUT,\n);\n\n// Utility type to union with for all handler structs\nexport const HandlerCaveatsStruct = object({\n maxRequestTime: optional(MaxRequestTimeStruct),\n});\n\nexport type HandlerCaveats = Infer<typeof HandlerCaveatsStruct>;\n\nexport const EmptyObjectStruct = object<EmptyObject>({}) as unknown as Struct<\n EmptyObject,\n null\n>;\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct: Describe<InitialPermissions> = type({\n 'endowment:cronjob': optional(\n assign(\n HandlerCaveatsStruct,\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n ),\n 'endowment:ethereum-provider': optional(EmptyObjectStruct),\n 'endowment:keyring': optional(\n assign(HandlerCaveatsStruct, KeyringOriginsStruct),\n ),\n 'endowment:lifecycle-hooks': optional(HandlerCaveatsStruct),\n 'endowment:name-lookup': optional(\n assign(\n HandlerCaveatsStruct,\n object({\n chains: optional(ChainIdsStruct),\n matchers: optional(LookupMatchersStruct),\n }),\n ),\n ),\n 'endowment:network-access': optional(EmptyObjectStruct),\n 'endowment:page-home': optional(HandlerCaveatsStruct),\n 'endowment:rpc': optional(assign(HandlerCaveatsStruct, RpcOriginsStruct)),\n 'endowment:signature-insight': optional(\n assign(\n HandlerCaveatsStruct,\n object({\n allowSignatureOrigin: optional(boolean()),\n }),\n ),\n ),\n 'endowment:transaction-insight': optional(\n assign(\n HandlerCaveatsStruct,\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n ),\n 'endowment:webassembly': optional(EmptyObjectStruct),\n snap_dialog: optional(EmptyObjectStruct),\n snap_manageState: optional(EmptyObjectStruct),\n snap_manageAccounts: optional(EmptyObjectStruct),\n snap_notify: optional(EmptyObjectStruct),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(EmptyObjectStruct),\n snap_getLocale: optional(EmptyObjectStruct),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = InferMatching<\n typeof PermissionsStruct,\n InitialPermissions\n>;\n\nexport const SnapAuxilaryFilesStruct = array(string());\n\nexport const InitialConnectionsStruct = record(\n intersection([string(), uri()]),\n object({}),\n);\n\nexport type InitialConnections = Infer<typeof InitialConnectionsStruct>;\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(string(), 1, 214),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n files: optional(SnapAuxilaryFilesStruct),\n locales: optional(SnapAuxilaryFilesStruct),\n }),\n initialConnections: optional(InitialConnectionsStruct),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/icon.ts"],"names":[],"mappings":";AAAA,SAAS,OAAO,gBAAgB;AAChC,SAAS,QAAQ,qBAAqB;AAI/B,IAAM,oBAAoB;AAC1B,IAAM,yBAAyB,GAAG,KAAK;AAAA,EAC5C,oBAAoB;AACtB,CAAC;AAOM,SAAS,iBAAiB,MAAmB;AAClD,SAAO,KAAK,KAAK,SAAS,MAAM,GAAG,sCAAsC;AAEzE,QAAM,aACJ,OAAO,KAAK,UAAU,WAClB,cAAc,KAAK,KAAK,EAAE,aAC1B,KAAK,MAAM;AAEjB;AAAA,IACE,cAAc;AAAA,IACd,sDAAsD,sBAAsB;AAAA,EAC9E;AAEA,SAAO,MAAM,KAAK,SAAS,CAAC,GAAG,gCAAgC;AACjE;AAQO,SAAS,iBAAiB,KAGxB;AACP,MAAI;AACF,UAAM,SAAS,SAAS,GAAG;AAE3B,UAAM,SAAS,OAAO,UAAU;AAChC,UAAM,QAAQ,OAAO,SAAS;AAE9B,QAAI,UAAU,OAAO;AACnB,aAAO,EAAE,QAAQ,MAAM;AAAA,IACzB;AAEA,UAAM,UAAU,OAAO,WAAW;AAClC,QAAI,SAAS;AAEX,YAAM,CAAC,OAAO,OAAO,cAAc,aAAa,IAAI,QAAQ,MAAM,GAAG;AAErE,UAAI,gBAAgB,eAAe;AACjC,cAAM,cAAc,SAAS,cAAc,EAAE;AAC7C,cAAM,eAAe,SAAS,eAAe,EAAE;AAE/C,eAAO,OAAO,UAAU,WAAW,KAAK,cAAc,CAAC;AACvD,eAAO,OAAO,UAAU,YAAY,KAAK,eAAe,CAAC;AAEzD,eAAO;AAAA,UACL,OAAO;AAAA,UACP,QAAQ;AAAA,QACV;AAAA,MACF;AAAA,IACF;AAAA,EACF,QAAQ;AACN,UAAM,IAAI,MAAM,gCAAgC;AAAA,EAClD;AAEA,SAAO;AACT","sourcesContent":["import { isSvg, parseSvg } from '@metamask/snaps-sdk';\nimport { assert, stringToBytes } from '@metamask/utils';\n\nimport type { VirtualFile } from './virtual-file';\n\nexport const SVG_MAX_BYTE_SIZE = 100_000;\nexport const SVG_MAX_BYTE_SIZE_TEXT = `${Math.floor(\n SVG_MAX_BYTE_SIZE / 1000,\n)}kb`;\n\n/**\n * Assert that a virtual file containing a Snap icon is valid.\n *\n * @param icon - A virtual file containing a Snap icon.\n */\nexport function assertIsSnapIcon(icon: VirtualFile) {\n assert(icon.path.endsWith('.svg'), 'Expected snap icon to end in \".svg\".');\n\n const byteLength =\n typeof icon.value === 'string'\n ? stringToBytes(icon.value).byteLength\n : icon.value.byteLength;\n\n assert(\n byteLength <= SVG_MAX_BYTE_SIZE,\n `The specified SVG icon exceeds the maximum size of ${SVG_MAX_BYTE_SIZE_TEXT}.`,\n );\n\n assert(isSvg(icon.toString()), 'Snap icon must be a valid SVG.');\n}\n\n/**\n * Extract the dimensions of an image from an SVG string if possible.\n *\n * @param svg - An SVG string.\n * @returns The height and width of the SVG or null.\n */\nexport function getSvgDimensions(svg: string): {\n height: number;\n width: number;\n} | null {\n try {\n const parsed = parseSvg(svg);\n\n const height = parsed['@_height'];\n const width = parsed['@_width'];\n\n if (height && width) {\n return { height, width };\n }\n\n const viewBox = parsed['@_viewBox'];\n if (viewBox) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const [_minX, _minY, viewBoxWidth, viewBoxHeight] = viewBox.split(' ');\n\n if (viewBoxWidth && viewBoxHeight) {\n const parsedWidth = parseInt(viewBoxWidth, 10);\n const parsedHeight = parseInt(viewBoxHeight, 10);\n\n assert(Number.isInteger(parsedWidth) && parsedWidth > 0);\n assert(Number.isInteger(parsedHeight) && parsedHeight > 0);\n\n return {\n width: parsedWidth,\n height: parsedHeight,\n };\n }\n }\n } catch {\n throw new Error('Snap icon must be a valid SVG.');\n }\n\n return null;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/icon.ts"],"sourcesContent":["import { isSvg, parseSvg } from '@metamask/snaps-sdk';\nimport { assert, stringToBytes } from '@metamask/utils';\n\nimport type { VirtualFile } from './virtual-file';\n\nexport const SVG_MAX_BYTE_SIZE = 100_000;\nexport const SVG_MAX_BYTE_SIZE_TEXT = `${Math.floor(\n SVG_MAX_BYTE_SIZE / 1000,\n)}kb`;\n\n/**\n * Assert that a virtual file containing a Snap icon is valid.\n *\n * @param icon - A virtual file containing a Snap icon.\n */\nexport function assertIsSnapIcon(icon: VirtualFile) {\n assert(icon.path.endsWith('.svg'), 'Expected snap icon to end in \".svg\".');\n\n const byteLength =\n typeof icon.value === 'string'\n ? stringToBytes(icon.value).byteLength\n : icon.value.byteLength;\n\n assert(\n byteLength <= SVG_MAX_BYTE_SIZE,\n `The specified SVG icon exceeds the maximum size of ${SVG_MAX_BYTE_SIZE_TEXT}.`,\n );\n\n assert(isSvg(icon.toString()), 'Snap icon must be a valid SVG.');\n}\n\n/**\n * Extract the dimensions of an image from an SVG string if possible.\n *\n * @param svg - An SVG string.\n * @returns The height and width of the SVG or null.\n */\nexport function getSvgDimensions(svg: string): {\n height: number;\n width: number;\n} | null {\n try {\n const parsed = parseSvg(svg);\n\n const height = parsed['@_height'];\n const width = parsed['@_width'];\n\n if (height && width) {\n return { height, width };\n }\n\n const viewBox = parsed['@_viewBox'];\n if (viewBox) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const [_minX, _minY, viewBoxWidth, viewBoxHeight] = viewBox.split(' ');\n\n if (viewBoxWidth && viewBoxHeight) {\n const parsedWidth = parseInt(viewBoxWidth, 10);\n const parsedHeight = parseInt(viewBoxHeight, 10);\n\n assert(Number.isInteger(parsedWidth) && parsedWidth > 0);\n assert(Number.isInteger(parsedHeight) && parsedHeight > 0);\n\n return {\n width: parsedWidth,\n height: parsedHeight,\n };\n }\n }\n } catch {\n throw new Error('Snap icon must be a valid SVG.');\n }\n\n return null;\n}\n"],"mappings":";AAAA,SAAS,OAAO,gBAAgB;AAChC,SAAS,QAAQ,qBAAqB;AAI/B,IAAM,oBAAoB;AAC1B,IAAM,yBAAyB,GAAG,KAAK;AAAA,EAC5C,oBAAoB;AACtB,CAAC;AAOM,SAAS,iBAAiB,MAAmB;AAClD,SAAO,KAAK,KAAK,SAAS,MAAM,GAAG,sCAAsC;AAEzE,QAAM,aACJ,OAAO,KAAK,UAAU,WAClB,cAAc,KAAK,KAAK,EAAE,aAC1B,KAAK,MAAM;AAEjB;AAAA,IACE,cAAc;AAAA,IACd,sDAAsD,sBAAsB;AAAA,EAC9E;AAEA,SAAO,MAAM,KAAK,SAAS,CAAC,GAAG,gCAAgC;AACjE;AAQO,SAAS,iBAAiB,KAGxB;AACP,MAAI;AACF,UAAM,SAAS,SAAS,GAAG;AAE3B,UAAM,SAAS,OAAO,UAAU;AAChC,UAAM,QAAQ,OAAO,SAAS;AAE9B,QAAI,UAAU,OAAO;AACnB,aAAO,EAAE,QAAQ,MAAM;AAAA,IACzB;AAEA,UAAM,UAAU,OAAO,WAAW;AAClC,QAAI,SAAS;AAEX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;AACb,CAAC;AAEM,IAAM,2BAA2B,MAAM;AAAA,EAC5C;AAAA,EACA;AACF,CAAC;AAEM,IAAM,0BAA0B,OAAO;AAAA,EAC5C,UAAU,OAAO;AAAA,EACjB,gBAAgB,OAAO;AACzB,CAAC;AAEM,IAAM,yBAAyB,OAAO;AAAA,EAC3C,UAAU,OAAO;AAAA,EACjB,iBAAiB,OAAO;AAC1B,CAAC;AAEM,IAAM,kCAAkC,OAAO;AAAA,EACpD,iBAAiB,KAAK,MAAM,uBAAuB,GAAG,GAAG,QAAQ;AACnE,CAAC;AAEM,IAAM,iCAAiC,OAAO;AAAA,EACnD,mBAAmB,KAAK,MAAM,sBAAsB,GAAG,GAAG,QAAQ;AACpE,CAAC;AAEM,IAAM,6BAA6B;AAAA,EACxC,MAAM,CAAC,iCAAiC,8BAA8B,CAAC;AACzE","sourcesContent":["import type {\n OnCronjobHandler,\n OnHomePageHandler,\n OnInstallHandler,\n OnKeyringRequestHandler,\n OnNameLookupHandler,\n OnRpcRequestHandler,\n OnSignatureHandler,\n OnTransactionHandler,\n OnUpdateHandler,\n OnUserInputHandler,\n} from '@metamask/snaps-sdk';\nimport { ComponentOrElementStruct, SeverityLevel } from '@metamask/snaps-sdk';\nimport {\n assign,\n literal,\n nullable,\n object,\n optional,\n string,\n array,\n size,\n union,\n} from 'superstruct';\n\nimport type { SnapHandler } from './handler-types';\nimport { HandlerType } from './handler-types';\n\nexport type SnapRpcHookArgs = {\n origin: string;\n handler: HandlerType;\n request: Record<string, unknown>;\n};\n\nexport const SNAP_EXPORTS = {\n [HandlerType.OnRpcRequest]: {\n type: HandlerType.OnRpcRequest,\n required: true,\n validator: (snapExport: unknown): snapExport is OnRpcRequestHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnTransaction]: {\n type: HandlerType.OnTransaction,\n required: true,\n validator: (snapExport: unknown): snapExport is OnTransactionHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnCronjob]: {\n type: HandlerType.OnCronjob,\n required: true,\n validator: (snapExport: unknown): snapExport is OnCronjobHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnNameLookup]: {\n type: HandlerType.OnNameLookup,\n required: true,\n validator: (snapExport: unknown): snapExport is OnNameLookupHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnInstall]: {\n type: HandlerType.OnInstall,\n required: false,\n validator: (snapExport: unknown): snapExport is OnInstallHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnUpdate]: {\n type: HandlerType.OnUpdate,\n required: false,\n validator: (snapExport: unknown): snapExport is OnUpdateHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnKeyringRequest]: {\n type: HandlerType.OnKeyringRequest,\n required: true,\n validator: (snapExport: unknown): snapExport is OnKeyringRequestHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnHomePage]: {\n type: HandlerType.OnHomePage,\n required: true,\n validator: (snapExport: unknown): snapExport is OnHomePageHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnSignature]: {\n type: HandlerType.OnSignature,\n required: true,\n validator: (snapExport: unknown): snapExport is OnSignatureHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnUserInput]: {\n type: HandlerType.OnUserInput,\n required: false,\n validator: (snapExport: unknown): snapExport is OnUserInputHandler => {\n return typeof snapExport === 'function';\n },\n },\n} as const;\n\nexport const OnTransactionSeverityResponseStruct = object({\n severity: optional(literal(SeverityLevel.Critical)),\n});\n\nexport const OnTransactionResponseWithIdStruct = assign(\n OnTransactionSeverityResponseStruct,\n object({\n id: string(),\n }),\n);\n\nexport const OnTransactionResponseWithContentStruct = assign(\n OnTransactionSeverityResponseStruct,\n object({\n content: ComponentOrElementStruct,\n }),\n);\n\nexport const OnTransactionResponseStruct = nullable(\n union([\n OnTransactionResponseWithContentStruct,\n OnTransactionResponseWithIdStruct,\n ]),\n);\n\nexport const OnSignatureResponseStruct = OnTransactionResponseStruct;\n\nexport const OnHomePageResponseWithContentStruct = object({\n content: ComponentOrElementStruct,\n});\n\nexport const OnHomePageResponseWithIdStruct = object({\n id: string(),\n});\n\nexport const OnHomePageResponseStruct = union([\n OnHomePageResponseWithContentStruct,\n OnHomePageResponseWithIdStruct,\n]);\n\nexport const AddressResolutionStruct = object({\n protocol: string(),\n resolvedDomain: string(),\n});\n\nexport const DomainResolutionStruct = object({\n protocol: string(),\n resolvedAddress: string(),\n});\n\nexport const AddressResolutionResponseStruct = object({\n resolvedDomains: size(array(AddressResolutionStruct), 1, Infinity),\n});\n\nexport const DomainResolutionResponseStruct = object({\n resolvedAddresses: size(array(DomainResolutionStruct), 1, Infinity),\n});\n\nexport const OnNameLookupResponseStruct = nullable(\n union([AddressResolutionResponseStruct, DomainResolutionResponseStruct]),\n);\n\n/**\n * Utility type for getting the handler function type from a handler type.\n */\nexport type HandlerFunction<Type extends SnapHandler> =\n Type['validator'] extends (snapExport: unknown) => snapExport is infer Handler\n ? Handler\n : never;\n\n/**\n * All the function-based handlers that a snap can implement.\n */\nexport type SnapFunctionExports = {\n [Key in keyof typeof SNAP_EXPORTS]?: HandlerFunction<\n (typeof SNAP_EXPORTS)[Key]\n >;\n};\n\n/**\n * All handlers that a snap can implement.\n */\nexport type SnapExports = SnapFunctionExports;\n"]}