@metamask/snaps-utils 0.37.1-flask.1 → 0.37.2-flask.1

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.
@@ -0,0 +1,163 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ literal: function() {
13
+ return literal;
14
+ },
15
+ union: function() {
16
+ return union;
17
+ },
18
+ file: function() {
19
+ return file;
20
+ },
21
+ named: function() {
22
+ return named;
23
+ },
24
+ SnapsStructError: function() {
25
+ return SnapsStructError;
26
+ },
27
+ arrayToGenerator: function() {
28
+ return arrayToGenerator;
29
+ },
30
+ getError: function() {
31
+ return getError;
32
+ },
33
+ createFromStruct: function() {
34
+ return createFromStruct;
35
+ },
36
+ getStructFromPath: function() {
37
+ return getStructFromPath;
38
+ },
39
+ getUnionStructNames: function() {
40
+ return getUnionStructNames;
41
+ },
42
+ getStructErrorPrefix: function() {
43
+ return getStructErrorPrefix;
44
+ },
45
+ getStructFailureMessage: function() {
46
+ return getStructFailureMessage;
47
+ },
48
+ getStructErrorMessage: function() {
49
+ return getStructErrorMessage;
50
+ }
51
+ });
52
+ const _utils = require("@metamask/utils");
53
+ const _chalk = require("chalk");
54
+ const _path = require("path");
55
+ const _superstruct = require("superstruct");
56
+ const _strings = require("./strings");
57
+ function literal(value) {
58
+ return (0, _superstruct.define)(JSON.stringify(value), (0, _superstruct.literal)(value).validator);
59
+ }
60
+ function union([head, ...tail]) {
61
+ const struct = (0, _superstruct.union)([
62
+ head,
63
+ ...tail
64
+ ]);
65
+ return new _superstruct.Struct({
66
+ ...struct,
67
+ schema: [
68
+ head,
69
+ ...tail
70
+ ]
71
+ });
72
+ }
73
+ function file() {
74
+ return (0, _superstruct.coerce)((0, _superstruct.string)(), (0, _superstruct.string)(), (value)=>{
75
+ return (0, _path.resolve)(process.cwd(), value);
76
+ });
77
+ }
78
+ function named(name, struct) {
79
+ return new _superstruct.Struct({
80
+ ...struct,
81
+ type: name
82
+ });
83
+ }
84
+ class SnapsStructError extends _superstruct.StructError {
85
+ constructor(struct, prefix, suffix, failure, failures){
86
+ super(failure, failures);
87
+ this.name = 'SnapsStructError';
88
+ this.message = `${prefix}.\n\n${getStructErrorMessage(struct, [
89
+ ...failures()
90
+ ])}${suffix ? `\n\n${suffix}` : ''}`;
91
+ }
92
+ }
93
+ function* arrayToGenerator(array) {
94
+ for (const item of array){
95
+ yield item;
96
+ }
97
+ }
98
+ function getError({ struct, prefix, suffix = '', error }) {
99
+ return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()));
100
+ }
101
+ function createFromStruct(value, struct, prefix, suffix = '') {
102
+ try {
103
+ return (0, _superstruct.create)(value, struct);
104
+ } catch (error) {
105
+ if (error instanceof _superstruct.StructError) {
106
+ throw getError({
107
+ struct,
108
+ prefix,
109
+ suffix,
110
+ error
111
+ });
112
+ }
113
+ throw error;
114
+ }
115
+ }
116
+ function getStructFromPath(struct, path) {
117
+ return path.reduce((result, key)=>{
118
+ if ((0, _utils.isObject)(struct.schema) && struct.schema[key]) {
119
+ return struct.schema[key];
120
+ }
121
+ return result;
122
+ }, struct);
123
+ }
124
+ function getUnionStructNames(struct) {
125
+ if (Array.isArray(struct.schema)) {
126
+ return struct.schema.map(({ type })=>(0, _chalk.green)(type));
127
+ }
128
+ return null;
129
+ }
130
+ function getStructErrorPrefix(failure) {
131
+ if (failure.type === 'never' || failure.path.length === 0) {
132
+ return '';
133
+ }
134
+ return `At path: ${(0, _chalk.bold)(failure.path.join('.'))} — `;
135
+ }
136
+ function getStructFailureMessage(struct, failure) {
137
+ const received = (0, _chalk.red)(JSON.stringify(failure.value));
138
+ const prefix = getStructErrorPrefix(failure);
139
+ if (failure.type === 'union') {
140
+ const childStruct = getStructFromPath(struct, failure.path);
141
+ const unionNames = getUnionStructNames(childStruct);
142
+ if (unionNames) {
143
+ return `${prefix}Expected the value to be one of: ${unionNames.join(', ')}, but received: ${received}.`;
144
+ }
145
+ return `${prefix}${failure.message}.`;
146
+ }
147
+ if (failure.type === 'literal') {
148
+ // Superstruct's failure does not provide information about which literal
149
+ // value was expected, so we need to parse the message to get the literal.
150
+ const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${(0, _chalk.green)('$1')}\`,`).replace(/, but received: (.+)/u, `, but received: ${(0, _chalk.red)('$1')}`);
151
+ return `${prefix}${message}.`;
152
+ }
153
+ if (failure.type === 'never') {
154
+ return `Unknown key: ${(0, _chalk.bold)(failure.path.join('.'))}, received: ${received}.`;
155
+ }
156
+ return `${prefix}Expected a value of type ${(0, _chalk.green)(failure.type)}, but received: ${received}.`;
157
+ }
158
+ function getStructErrorMessage(struct, failures) {
159
+ const formattedFailures = failures.map((failure)=>(0, _strings.indent)(`• ${getStructFailureMessage(struct, failure)}`));
160
+ return formattedFailures.join('\n');
161
+ }
162
+
163
+ //# sourceMappingURL=structs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/structs.ts"],"sourcesContent":["import { isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure, Infer } from 'superstruct';\nimport {\n Struct,\n StructError,\n define,\n literal as superstructLiteral,\n union as superstructUnion,\n create,\n string,\n coerce,\n} from 'superstruct';\nimport type { AnyStruct, InferStructTuple } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * A wrapper of `superstruct`'s `literal` struct that also defines the name of\n * the struct as the literal value.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n * For example, instead of returning an error like:\n *\n * ```\n * Expected the value to satisfy a union of `literal | literal`, but received: \\\"baz\\\"\n * ```\n *\n * This struct will return an error like:\n *\n * ```\n * Expected the value to satisfy a union of `\"foo\" | \"bar\"`, but received: \\\"baz\\\"\n * ```\n *\n * @param value - The literal value.\n * @returns The `superstruct` struct, which validates that the value is equal\n * to the literal value.\n */\nexport function literal<Type extends string | number | boolean>(value: Type) {\n return define<Type>(\n JSON.stringify(value),\n superstructLiteral(value).validator,\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `union` struct that also defines the schema as\n * the union of the schemas of the structs.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param structs - The structs to union.\n * @param structs.\"0\" - The first struct.\n * @param structs.\"1\" - The remaining structs.\n * @returns The `superstruct` struct, which validates that the value satisfies\n * one of the structs.\n */\nexport function union<Head extends AnyStruct, Tail extends AnyStruct[]>([\n head,\n ...tail\n]: [head: Head, ...tail: Tail]): Struct<\n Infer<Head> | InferStructTuple<Tail>[number],\n [head: Head, ...tail: Tail]\n> {\n const struct = superstructUnion([head, ...tail]);\n\n return new Struct({\n ...struct,\n schema: [head, ...tail],\n });\n}\n\n/**\n * A wrapper of `superstruct`'s `string` struct that coerces a value to a string\n * and resolves it relative to the current working directory. This is useful\n * for specifying file paths in a configuration file, as it allows the user to\n * use both relative and absolute paths.\n *\n * @returns The `superstruct` struct, which validates that the value is a\n * string, and resolves it relative to the current working directory.\n * @example\n * ```ts\n * const config = struct({\n * file: file(),\n * // ...\n * });\n *\n * const value = create({ file: 'path/to/file' }, config);\n * console.log(value.file); // /process/cwd/path/to/file\n * ```\n */\nexport function file() {\n return coerce(string(), string(), (value) => {\n return resolve(process.cwd(), value);\n });\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(struct, [\n ...failures(),\n ])}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(struct, prefix, suffix, error, () =>\n arrayToGenerator(error.failures()),\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => green(type));\n }\n\n return null;\n}\n\n/**\n * Get a error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${bold(failure.path.join('.'))} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n) {\n const received = red(JSON.stringify(failure.value));\n const prefix = getStructErrorPrefix(failure);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(/the literal `(.+)`,/u, `the value to be \\`${green('$1')}\\`,`)\n .replace(/, but received: (.+)/u, `, but received: ${red('$1')}`);\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${bold(\n failure.path.join('.'),\n )}, received: ${received}.`;\n }\n\n return `${prefix}Expected a value of type ${green(\n failure.type,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n"],"names":["literal","union","file","named","SnapsStructError","arrayToGenerator","getError","createFromStruct","getStructFromPath","getUnionStructNames","getStructErrorPrefix","getStructFailureMessage","getStructErrorMessage","value","define","JSON","stringify","superstructLiteral","validator","head","tail","struct","superstructUnion","Struct","schema","coerce","string","resolve","process","cwd","name","type","StructError","constructor","prefix","suffix","failure","failures","message","array","item","error","create","path","reduce","result","key","isObject","Array","isArray","map","green","length","bold","join","received","red","childStruct","unionNames","replace","formattedFailures","indent"],"mappings":";;;;;;;;;;;IAuCgBA,OAAO;eAAPA;;IAmBAC,KAAK;eAALA;;IAkCAC,IAAI;eAAJA;;IAeAC,KAAK;eAALA;;IAUHC,gBAAgB;eAAhBA;;IAgCIC,gBAAgB;eAAhBA;;IAmBDC,QAAQ;eAARA;;IAuBAC,gBAAgB;eAAhBA;;IAwBAC,iBAAiB;eAAjBA;;IAoBAC,mBAAmB;eAAnBA;;IAiBAC,oBAAoB;eAApBA;;IAiBAC,uBAAuB;eAAvBA;;IAiDAC,qBAAqB;eAArBA;;;uBA9TS;uBACQ;sBACT;6BAWjB;yBAGgB;AAuBhB,SAASZ,QAAgDa,KAAW;IACzE,OAAOC,IAAAA,mBAAM,EACXC,KAAKC,SAAS,CAACH,QACfI,IAAAA,oBAAkB,EAACJ,OAAOK,SAAS;AAEvC;AAcO,SAASjB,MAAwD,CACtEkB,MACA,GAAGC,KACyB;IAI5B,MAAMC,SAASC,IAAAA,kBAAgB,EAAC;QAACH;WAASC;KAAK;IAE/C,OAAO,IAAIG,mBAAM,CAAC;Q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yEAAyE;QACzE,0EAA0E;QAC1E,MAAMO,UAAUF,QAAQE,OAAO,CAC5BqB,OAAO,CAAC,wBAAwB,CAAC,kBAAkB,EAAER,IAAAA,YAAK,EAAC,MAAM,GAAG,CAAC,EACrEQ,OAAO,CAAC,yBAAyB,CAAC,gBAAgB,EAAEH,IAAAA,UAAG,EAAC,MAAM,CAAC;QAElE,OAAO,CAAC,EAAEtB,OAAO,EAAEI,QAAQ,CAAC,CAAC;IAC/B;IAEA,IAAIF,QAAQL,IAAI,KAAK,SAAS;QAC5B,OAAO,CAAC,aAAa,EAAEsB,IAAAA,WAAI,EACzBjB,QAAQO,IAAI,CAACW,IAAI,CAAC,MAClB,YAAY,EAAEC,SAAS,CAAC,CAAC;IAC7B;IAEA,OAAO,CAAC,EAAErB,OAAO,yBAAyB,EAAEiB,IAAAA,YAAK,EAC/Cf,QAAQL,IAAI,EACZ,gBAAgB,EAAEwB,SAAS,CAAC,CAAC;AACjC;AAUO,SAAS3C,sBACdS,MAA4B,EAC5BgB,QAAmB;IAEnB,MAAMuB,oBAAoBvB,SAASa,GAAG,CAAC,CAACd,UACtCyB,IAAAA,eAAM,EAAC,CAAC,EAAE,EAAElD,wBAAwBU,QAAQe,SAAS,CAAC;IAGxD,OAAOwB,kBAAkBN,IAAI,CAAC;AAChC"}
package/dist/esm/enum.js CHANGED
@@ -1,4 +1,4 @@
1
- import { literal } from 'superstruct';
1
+ import { literal } from './structs';
2
2
  /**
3
3
  * Superstruct struct for validating an enum value. This allows using both the
4
4
  * enum string values and the enum itself as values.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/enum.ts"],"sourcesContent":["import type { Struct } from 'superstruct';\nimport { literal } from 'superstruct';\n\n/**\n * Get the enum values as union type. This allows using both the enum string\n * values and the enum itself as values.\n *\n * Note: This only works for string enums.\n *\n * @example\n * ```typescript\n * enum Foo {\n * Bar = 'bar',\n * Baz = 'baz',\n * }\n *\n * type FooValue = EnumToUnion<Foo>;\n * // FooValue is 'bar' | 'baz'\n *\n * const foo: FooValue = Foo.Bar; // Works\n * const foo: FooValue = 'bar'; // Also works\n * ```\n */\nexport type EnumToUnion<Type extends string> = `${Type}`;\n\n/**\n * Superstruct struct for validating an enum value. This allows using both the\n * enum string values and the enum itself as values.\n *\n * @param constant - The enum to validate against.\n * @returns The superstruct struct.\n */\nexport function enumValue<Type extends string>(\n constant: Type,\n): Struct<EnumToUnion<Type>, EnumToUnion<Type>> {\n return literal(constant as EnumToUnion<Type>);\n}\n"],"names":["literal","enumValue","constant"],"mappings":"AACA,SAASA,OAAO,QAAQ,cAAc;AAwBtC;;;;;;CAMC,GACD,OAAO,SAASC,UACdC,QAAc;IAEd,OAAOF,QAAQE;AACjB"}
1
+ {"version":3,"sources":["../../src/enum.ts"],"sourcesContent":["import type { Struct } from 'superstruct';\n\nimport { literal } from './structs';\n\n/**\n * Get the enum values as union type. This allows using both the enum string\n * values and the enum itself as values.\n *\n * Note: This only works for string enums.\n *\n * @example\n * ```typescript\n * enum Foo {\n * Bar = 'bar',\n * Baz = 'baz',\n * }\n *\n * type FooValue = EnumToUnion<Foo>;\n * // FooValue is 'bar' | 'baz'\n *\n * const foo: FooValue = Foo.Bar; // Works\n * const foo: FooValue = 'bar'; // Also works\n * ```\n */\nexport type EnumToUnion<Type extends string> = `${Type}`;\n\n/**\n * Superstruct struct for validating an enum value. This allows using both the\n * enum string values and the enum itself as values.\n *\n * @param constant - The enum to validate against.\n * @returns The superstruct struct.\n */\nexport function enumValue<Type extends string>(\n constant: Type,\n): Struct<EnumToUnion<Type>, null> {\n return literal(constant as EnumToUnion<Type>);\n}\n"],"names":["literal","enumValue","constant"],"mappings":"AAEA,SAASA,OAAO,QAAQ,YAAY;AAwBpC;;;;;;CAMC,GACD,OAAO,SAASC,UACdC,QAAc;IAEd,OAAOF,QAAQE;AACjB"}
package/dist/esm/eval.js CHANGED
@@ -1,6 +1,28 @@
1
+ function _define_property(obj, key, value) {
2
+ if (key in obj) {
3
+ Object.defineProperty(obj, key, {
4
+ value: value,
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true
8
+ });
9
+ } else {
10
+ obj[key] = value;
11
+ }
12
+ return obj;
13
+ }
14
+ import { assert } from '@metamask/utils';
1
15
  import { fork } from 'child_process';
2
16
  import { join } from 'path';
3
17
  import { validateFilePath } from './fs';
18
+ export class SnapEvalError extends Error {
19
+ constructor(message, output){
20
+ super(message);
21
+ _define_property(this, "output", void 0);
22
+ this.name = 'SnapEvalError';
23
+ this.output = output;
24
+ }
25
+ }
4
26
  /**
5
27
  * Spawn a new process to run the provided bundle in.
6
28
  *
@@ -12,12 +34,30 @@ import { validateFilePath } from './fs';
12
34
  return new Promise((resolve, reject)=>{
13
35
  const worker = fork(join(__dirname, 'eval-worker.js'), [
14
36
  bundlePath
15
- ]);
37
+ ], {
38
+ // To avoid printing the output of the worker to the console, we set
39
+ // `stdio` to `pipe` and handle the output ourselves.
40
+ stdio: 'pipe'
41
+ });
42
+ let stdout = '';
43
+ let stderr = '';
44
+ assert(worker.stdout, '`stdout` should be defined.');
45
+ assert(worker.stderr, '`stderr` should be defined.');
46
+ worker.stdout.on('data', (data)=>{
47
+ stdout += data.toString();
48
+ });
49
+ worker.stderr.on('data', (data)=>{
50
+ stderr += data.toString();
51
+ });
16
52
  worker.on('exit', (exitCode)=>{
53
+ const output = {
54
+ stdout,
55
+ stderr
56
+ };
17
57
  if (exitCode === 0) {
18
- return resolve(null);
58
+ return resolve(output);
19
59
  }
20
- return reject(new Error(`Process exited with non-zero exit code: ${exitCode}`));
60
+ return reject(new SnapEvalError(`Process exited with non-zero exit code: ${exitCode}.`, output));
21
61
  });
22
62
  });
23
63
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/eval.ts"],"sourcesContent":["import { fork } from 'child_process';\nimport { join } from 'path';\n\nimport { validateFilePath } from './fs';\n\n/**\n * Spawn a new process to run the provided bundle in.\n *\n * @param bundlePath - The path to the bundle to run.\n * @returns `null` if the worker ran successfully.\n * @throws If the worker failed to run successfully.\n */\nexport async function evalBundle(bundlePath: string): Promise<null> {\n await validateFilePath(bundlePath);\n\n return new Promise((resolve, reject) => {\n const worker = fork(join(__dirname, 'eval-worker.js'), [bundlePath]);\n\n worker.on('exit', (exitCode: number) => {\n if (exitCode === 0) {\n return resolve(null);\n }\n\n return reject(\n new Error(`Process exited with non-zero exit code: ${exitCode}`),\n );\n });\n });\n}\n"],"names":["fork","join","validateFilePath","evalBundle","bundlePath","Promise","resolve","reject","worker","__dirname","on","exitCode","Error"],"mappings":"AAAA,SAASA,IAAI,QAAQ,gBAAgB;AACrC,SAASC,IAAI,QAAQ,OAAO;AAE5B,SAASC,gBAAgB,QAAQ,OAAO;AAExC;;;;;;CAMC,GACD,OAAO,eAAeC,WAAWC,UAAkB;IACjD,MAAMF,iBAAiBE;IAEvB,OAAO,IAAIC,QAAQ,CAACC,SAASC;QAC3B,MAAMC,SAASR,KAAKC,KAAKQ,WAAW,mBAAmB;YAACL;SAAW;QAEnEI,OAAOE,EAAE,CAAC,QAAQ,CAACC;YACjB,IAAIA,aAAa,GAAG;gBAClB,OAAOL,QAAQ;YACjB;YAEA,OAAOC,OACL,IAAIK,MAAM,CAAC,wCAAwC,EAAED,SAAS,CAAC;QAEnE;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/eval.ts"],"sourcesContent":["import { assert } from '@metamask/utils';\nimport { fork } from 'child_process';\nimport { join } from 'path';\n\nimport { validateFilePath } from './fs';\n\nexport type EvalOutput = {\n stdout: string;\n stderr: string;\n};\n\nexport class SnapEvalError extends Error {\n readonly output: EvalOutput;\n\n constructor(message: string, output: EvalOutput) {\n super(message);\n\n this.name = 'SnapEvalError';\n this.output = output;\n }\n}\n\n/**\n * Spawn a new process to run the provided bundle in.\n *\n * @param bundlePath - The path to the bundle to run.\n * @returns `null` if the worker ran successfully.\n * @throws If the worker failed to run successfully.\n */\nexport async function evalBundle(bundlePath: string): Promise<EvalOutput> {\n await validateFilePath(bundlePath);\n\n return new Promise((resolve, reject) => {\n const worker = fork(join(__dirname, 'eval-worker.js'), [bundlePath], {\n // To avoid printing the output of the worker to the console, we set\n // `stdio` to `pipe` and handle the output ourselves.\n stdio: 'pipe',\n });\n\n let stdout = '';\n let stderr = '';\n\n assert(worker.stdout, '`stdout` should be defined.');\n assert(worker.stderr, '`stderr` should be defined.');\n\n worker.stdout.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n worker.stderr.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n worker.on('exit', (exitCode: number) => {\n const output = {\n stdout,\n stderr,\n };\n\n if (exitCode === 0) {\n return resolve(output);\n }\n\n return reject(\n new SnapEvalError(\n `Process exited with non-zero exit code: ${exitCode}.`,\n output,\n ),\n );\n });\n });\n}\n"],"names":["assert","fork","join","validateFilePath","SnapEvalError","Error","constructor","message","output","name","evalBundle","bundlePath","Promise","resolve","reject","worker","__dirname","stdio","stdout","stderr","on","data","toString","exitCode"],"mappings":";;;;;;;;;;;;;AAAA,SAASA,MAAM,QAAQ,kBAAkB;AACzC,SAASC,IAAI,QAAQ,gBAAgB;AACrC,SAASC,IAAI,QAAQ,OAAO;AAE5B,SAASC,gBAAgB,QAAQ,OAAO;AAOxC,OAAO,MAAMC,sBAAsBC;IAGjCC,YAAYC,OAAe,EAAEC,MAAkB,CAAE;QAC/C,KAAK,CAACD;QAHR,uBAASC,UAAT,KAAA;QAKE,IAAI,CAACC,IAAI,GAAG;QACZ,IAAI,CAACD,MAAM,GAAGA;IAChB;AACF;AAEA;;;;;;CAMC,GACD,OAAO,eAAeE,WAAWC,UAAkB;IACjD,MAAMR,iBAAiBQ;IAEvB,OAAO,IAAIC,QAAQ,CAACC,SAASC;QAC3B,MAAMC,SAASd,KAAKC,KAAKc,WAAW,mBAAmB;YAACL;SAAW,EAAE;YACnE,oEAAoE;YACpE,qDAAqD;YACrDM,OAAO;QACT;QAEA,IAAIC,SAAS;QACb,IAAIC,SAAS;QAEbnB,OAAOe,OAAOG,MAAM,EAAE;QACtBlB,OAAOe,OAAOI,MAAM,EAAE;QAEtBJ,OAAOG,MAAM,CAACE,EAAE,CAAC,QAAQ,CAACC;YACxBH,UAAUG,KAAKC,QAAQ;QACzB;QAEAP,OAAOI,MAAM,CAACC,EAAE,CAAC,QAAQ,CAACC;YACxBF,UAAUE,KAAKC,QAAQ;QACzB;QAEAP,OAAOK,EAAE,CAAC,QAAQ,CAACG;YACjB,MAAMf,SAAS;gBACbU;gBACAC;YACF;YAEA,IAAII,aAAa,GAAG;gBAClB,OAAOV,QAAQL;YACjB;YAEA,OAAOM,OACL,IAAIV,cACF,CAAC,wCAAwC,EAAEmB,SAAS,CAAC,CAAC,EACtDf;QAGN;IACF;AACF"}
@@ -15,6 +15,8 @@ export * from './manifest/index.browser';
15
15
  export * from './namespace';
16
16
  export * from './path';
17
17
  export * from './snaps';
18
+ export * from './strings';
19
+ export * from './structs';
18
20
  export * from './types';
19
21
  export * from './validation';
20
22
  export * from './versions';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './path';\nexport * from './snaps';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"],"names":[],"mappings":"AAAA,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,eAAe;AAC7B,cAAc,uBAAuB;AACrC,cAAc,YAAY;AAC1B,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,2BAA2B;AACzC,cAAc,cAAc;AAC5B,cAAc,SAAS;AACvB,cAAc,UAAU;AACxB,cAAc,UAAU;AACxB,cAAc,eAAe;AAC7B,cAAc,aAAa;AAC3B,cAAc,+BAA+B"}
1
+ {"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './path';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"],"names":[],"mappings":"AAAA,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,eAAe;AAC7B,cAAc,uBAAuB;AACrC,cAAc,YAAY;AAC1B,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,2BAA2B;AACzC,cAAc,cAAc;AAC5B,cAAc,SAAS;AACvB,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,UAAU;AACxB,cAAc,eAAe;AAC7B,cAAc,aAAa;AAC3B,cAAc,+BAA+B"}
package/dist/esm/index.js CHANGED
@@ -20,6 +20,8 @@ export * from './npm';
20
20
  export * from './path';
21
21
  export * from './post-process';
22
22
  export * from './snaps';
23
+ export * from './strings';
24
+ export * from './structs';
23
25
  export * from './types';
24
26
  export * from './validation';
25
27
  export * from './versions';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './eval';\nexport * from './fs';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file';\n"],"names":[],"mappings":"AAAA,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,eAAe;AAC7B,cAAc,uBAAuB;AACrC,cAAc,YAAY;AAC1B,cAAc,SAAS;AACvB,cAAc,SAAS;AACvB,cAAc,OAAO;AACrB,cAAc,aAAa;AAC3B,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,SAAS;AACvB,cAAc,cAAc;AAC5B,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB,cAAc,iBAAiB;AAC/B,cAAc,UAAU;AACxB,cAAc,UAAU;AACxB,cAAc,eAAe;AAC7B,cAAc,aAAa;AAC3B,cAAc,iBAAiB"}
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './eval';\nexport * from './fs';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file';\n"],"names":[],"mappings":"AAAA,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,eAAe;AAC7B,cAAc,uBAAuB;AACrC,cAAc,YAAY;AAC1B,cAAc,SAAS;AACvB,cAAc,SAAS;AACvB,cAAc,OAAO;AACrB,cAAc,aAAa;AAC3B,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,SAAS;AACvB,cAAc,cAAc;AAC5B,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB,cAAc,iBAAiB;AAC/B,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,UAAU;AACxB,cAAc,eAAe;AAC7B,cAAc,aAAa;AAC3B,cAAc,iBAAiB"}
@@ -26,9 +26,10 @@ const MANIFEST_SORT_ORDER = {
26
26
  * @param basePath - The path to the folder with the manifest files.
27
27
  * @param writeManifest - Whether to write the fixed manifest to disk.
28
28
  * @param sourceCode - The source code of the Snap.
29
+ * @param writeFileFn - The function to use to write the manifest to disk.
29
30
  * @returns Whether the manifest was updated, and an array of warnings that
30
31
  * were encountered during processing of the manifest files.
31
- */ export async function checkManifest(basePath, writeManifest = true, sourceCode) {
32
+ */ export async function checkManifest(basePath, writeManifest = true, sourceCode, writeFileFn = fs.writeFile) {
32
33
  const warnings = [];
33
34
  const errors = [];
34
35
  let updated = false;
@@ -99,7 +100,7 @@ const MANIFEST_SORT_ORDER = {
99
100
  try {
100
101
  const newManifest = `${JSON.stringify(getWritableManifest(validatedManifest), null, 2)}\n`;
101
102
  if (updated || newManifest !== manifestFile.value) {
102
- await fs.writeFile(pathUtils.join(basePath, NpmSnapFileNames.Manifest), newManifest);
103
+ await writeFileFn(pathUtils.join(basePath, NpmSnapFileNames.Manifest), newManifest);
103
104
  }
104
105
  } catch (error) {
105
106
  // Note: This error isn't pushed to the errors array, because it's not an
@@ -172,7 +173,7 @@ const MANIFEST_SORT_ORDER = {
172
173
  const virtualFile = await readVirtualFile(pathUtils.join(basePath, sourceFilePath), 'utf8');
173
174
  return virtualFile;
174
175
  } catch (error) {
175
- throw new Error(`Failed to read Snap bundle file: ${error.message}`);
176
+ throw new Error(`Failed to read snap bundle file: ${error.message}`);
176
177
  }
177
178
  }
178
179
  /**
@@ -194,7 +195,7 @@ const MANIFEST_SORT_ORDER = {
194
195
  const virtualFile = await readVirtualFile(pathUtils.join(basePath, iconPath), 'utf8');
195
196
  return virtualFile;
196
197
  } catch (error) {
197
- throw new Error(`Failed to read Snap icon file: ${error.message}`);
198
+ throw new Error(`Failed to read snap icon file: ${error.message}`);
198
199
  }
199
200
  }
200
201
  /**
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/manifest/manifest.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\nimport { NpmSnapFileNames, SnapValidationFailureReason } from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file';\nimport type { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n $schema: 1,\n version: 2,\n description: 3,\n proposedName: 4,\n repository: 5,\n source: 6,\n initialPermissions: 7,\n manifestVersion: 8,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\n};\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n let currentError = error;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the `SnapValidationFailureReason` enum, so we only\n // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n validateNpmSnapManifest({ ...partiallyValidatedFiles, manifest });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = nextValidationError;\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n warnings.push(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await fs.writeFile(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nexport function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): VirtualFile<SnapManifest> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read Snap bundle file: ${error.message}`);\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read Snap icon file: ${error.message}`);\n }\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an npm Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n */\nexport function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n validateSnapShasum(\n { manifest, sourceCode, svgIcon },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["assertExhaustive","assert","isPlainObject","deepEqual","promises","fs","pathUtils","deepClone","readJsonFile","validateNpmSnap","getSnapChecksum","ProgrammaticallyFixableSnapError","validateSnapShasum","NpmSnapFileNames","SnapValidationFailureReason","readVirtualFile","VirtualFile","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","checkManifest","basePath","writeManifest","sourceCode","warnings","errors","updated","manifestPath","join","Manifest","manifestFile","unvalidatedManifest","result","packageFile","PackageJson","snapFiles","manifest","packageJson","getSnapSourceCode","svgIcon","getSnapIcon","error","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","length","attempts","fixManifest","validateNpmSnapManifest","nextValidationError","Error","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","getWritableManifest","value","writeFile","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","undefined","ShasumMismatch","shasum","sourceFilePath","filePath","path","virtualFile","iconPath","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository"],"mappings":"AACA,SAASA,gBAAgB,EAAEC,MAAM,EAAEC,aAAa,QAAQ,kBAAkB;AAC1E,OAAOC,eAAe,kBAAkB;AACxC,SAASC,YAAYC,EAAE,QAAQ,KAAK;AACpC,OAAOC,eAAe,OAAO;AAE7B,SAASC,SAAS,QAAQ,gBAAgB;AAC1C,SAASC,YAAY,QAAQ,QAAQ;AACrC,SAASC,eAAe,QAAQ,SAAS;AACzC,SACEC,eAAe,EACfC,gCAAgC,EAChCC,kBAAkB,QACb,WAAW;AAElB,SAASC,gBAAgB,EAAEC,2BAA2B,QAAQ,WAAW;AACzE,SAASC,eAAe,EAAEC,WAAW,QAAQ,kBAAkB;AAG/D,MAAMC,sBAA0D;IAC9DC,SAAS;IACTC,SAAS;IACTC,aAAa;IACbC,cAAc;IACdC,YAAY;IACZC,QAAQ;IACRC,oBAAoB;IACpBC,iBAAiB;AACnB;AAuBA;;;;;;;;;;CAUC,GACD,OAAO,eAAeC,cACpBC,QAAgB,EAChBC,gBAAgB,IAAI,EACpBC,UAAmB;IAEnB,MAAMC,WAAqB,EAAE;IAC7B,MAAMC,SAAmB,EAAE;IAE3B,IAAIC,UAAU;IAEd,MAAMC,eAAe3B,UAAU4B,IAAI,CAACP,UAAUd,iBAAiBsB,QAAQ;IACvE,MAAMC,eAAe,MAAM5B,aAAayB;IACxC,MAAMI,sBAAsBD,aAAaE,MAAM;IAE/C,MAAMC,cAAc,MAAM/B,aACxBF,UAAU4B,IAAI,CAACP,UAAUd,iBAAiB2B,WAAW;IAGvD,MAAMC,YAAkC;QACtCC,UAAUN;QACVO,aAAaJ;QACbV,YAAY,MAAMe,kBAChBjB,UACAU,qBACAR;QAEFgB,SAAS,MAAMC,YAAYnB,UAAUU;IACvC;I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AAEE,iBAAiBsB,QAAQ,CAAC,wBAAwB,EAAEqE,uBAAuB,uBAAuB,EAAE3F,iBAAiB2B,WAAW,CAAC,oBAAoB,EAAE6D,mBAAmB,GAAG,CAAC,EAClLvF,4BAA4BuE,eAAe;IAE/C;IAEA,IAGE,AAFA,4EAA4E;IAC5E,wDAAwD;IACvDiB,CAAAA,yBAAyBG,kBAAiB,KAC3C,CAACtG,UAAUmG,uBAAuBG,qBAClC;QACA,MAAM,IAAI9F,iCACR,CAAC,CAAC,EAAEE,iBAAiBsB,QAAQ,CAAC,yCAAyC,EAAEtB,iBAAiB2B,WAAW,CAAC,qBAAqB,CAAC,EAC5H1B,4BAA4BwE,kBAAkB;IAElD;IAEA1E,mBACE;QAAE8B;QAAUb;QAAYgB;IAAQ,GAChC,CAAC,CAAC,EAAEhC,iBAAiBsB,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
1
+ {"version":3,"sources":["../../../src/manifest/manifest.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\nimport { NpmSnapFileNames, SnapValidationFailureReason } from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file';\nimport type { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n $schema: 1,\n version: 2,\n description: 3,\n proposedName: 4,\n repository: 5,\n source: 6,\n initialPermissions: 7,\n manifestVersion: 8,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\n};\n\nexport type WriteFileFunction = (path: string, data: string) => Promise<void>;\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @param writeFileFn - The function to use to write the manifest to disk.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n writeFileFn: WriteFileFunction = fs.writeFile,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n let currentError = error;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the `SnapValidationFailureReason` enum, so we only\n // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n validateNpmSnapManifest({ ...partiallyValidatedFiles, manifest });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = nextValidationError;\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n warnings.push(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await writeFileFn(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nexport function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): VirtualFile<SnapManifest> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read snap bundle file: ${error.message}`);\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read snap icon file: ${error.message}`);\n }\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an npm Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n */\nexport function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n validateSnapShasum(\n { manifest, sourceCode, svgIcon },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["assertExhaustive","assert","isPlainObject","deepEqual","promises","fs","pathUtils","deepClone","readJsonFile","validateNpmSnap","getSnapChecksum","ProgrammaticallyFixableSnapError","validateSnapShasum","NpmSnapFileNames","SnapValidationFailureReason","readVirtualFile","VirtualFile","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","checkManifest","basePath","writeManifest","sourceCode","writeFileFn","writeFile","warnings","errors","updated","manifestPath","join","Manifest","manifestFile","unvalidatedManifest","result","packageFile","PackageJson","snapFiles","manifest","packageJson","getSnapSourceCode","svgIcon","getSnapIcon","error","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","length","attempts","fixManifest","validateNpmSnapManifest","nextValidationError","Error","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","getWritableManifest","value","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","undefined","ShasumMismatch","shasum","sourceFilePath","filePath","path","virtualFile","iconPath","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository"],"mappings":"AACA,SAASA,gBAAgB,EAAEC,MAAM,EAAEC,aAAa,QAAQ,kBAAkB;AAC1E,OAAOC,eAAe,kBAAkB;AACxC,SAASC,YAAYC,EAAE,QAAQ,KAAK;AACpC,OAAOC,eAAe,OAAO;AAE7B,SAASC,SAAS,QAAQ,gBAAgB;AAC1C,SAASC,YAAY,QAAQ,QAAQ;AACrC,SAASC,eAAe,QAAQ,SAAS;AACzC,SACEC,eAAe,EACfC,gCAAgC,EAChCC,kBAAkB,QACb,WAAW;AAElB,SAASC,gBAAgB,EAAEC,2BAA2B,QAAQ,WAAW;AACzE,SAASC,eAAe,EAAEC,WAAW,QAAQ,kBAAkB;AAG/D,MAAMC,sBAA0D;IAC9DC,SAAS;IACTC,SAAS;IACTC,aAAa;IACbC,cAAc;IACdC,YAAY;IACZC,QAAQ;IACRC,oBAAoB;IACpBC,iBAAiB;AACnB;AAyBA;;;;;;;;;;;CAWC,GACD,OAAO,eAAeC,cACpBC,QAAgB,EAChBC,gBAAgB,IAAI,EACpBC,UAAmB,EACnBC,cAAiCzB,GAAG0B,SAAS;IAE7C,MAAMC,WAAqB,EAAE;IAC7B,MAAMC,SAAmB,EAAE;IAE3B,IAAIC,UAAU;IAEd,MAAMC,eAAe7B,UAAU8B,IAAI,CAACT,UAAUd,iBAAiBwB,QAAQ;IACvE,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B;QAC3C,MAAM,IAAI7F,iCACR,CAAC,CAAC,EAAEE,iBAAiBwB,QAAQ,CAAC,qBAAqB,EAAEmE,oBAAoB,uBAAuB,EAAE3F,iBAAiB6B,WAAW,CAAC,iBAAiB,EAAE2D,gBAAgB,GAAG,CAAC,EACtKvF,4BAA4BmE,YAAY;IAE5C;IAEA,IAAIqB,uBAAuBG,wBAAwB;QACjD,MAAM,IAAI9F,iCACR,CAAC,CAAC,EAAEE,iBAAiBwB,QAAQ,CAAC,wBAAwB,EAAEoE,uBAAuB,uBAAuB,EAAE5F,iBAAiB6B,WAAW,CAAC,oBAAoB,EAAE4D,mBAAmB,GAAG,CAAC,EAClLxF,4BAA4BwE,eAAe;IAE/C;IAEA,IAGE,AAFA,4EAA4E;IAC5E,wDAAwD;IACvDiB,CAAAA,yBAAyBG,kBAAiB,KAC3C,CAACvG,UAAUoG,uBAAuBG,qBAClC;QACA,MAAM,IAAI/F,iCACR,CAAC,CAAC,EAAEE,iBAAiBwB,QAAQ,CAAC,yCAAyC,EAAExB,iBAAiB6B,WAAW,CAAC,qBAAqB,CAAC,EAC5H5B,4BAA4ByE,kBAAkB;IAElD;IAEA3E,mBACE;QAAEgC;QAAUf;QAAYkB;IAAQ,GAChC,CAAC,CAAC,EAAElC,iBAAiBwB,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Indent a message by adding a number of spaces to the beginning of each line.
3
+ *
4
+ * @param message - The message to indent.
5
+ * @param spaces - The number of spaces to indent by. Defaults to 2.
6
+ * @returns The indented message.
7
+ */ export function indent(message, spaces = 2) {
8
+ return message.replace(/^/gmu, ' '.repeat(spaces));
9
+ }
10
+
11
+ //# sourceMappingURL=strings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/strings.ts"],"sourcesContent":["/**\n * Indent a message by adding a number of spaces to the beginning of each line.\n *\n * @param message - The message to indent.\n * @param spaces - The number of spaces to indent by. Defaults to 2.\n * @returns The indented message.\n */\nexport function indent(message: string, spaces = 2) {\n return message.replace(/^/gmu, ' '.repeat(spaces));\n}\n"],"names":["indent","message","spaces","replace","repeat"],"mappings":"AAAA;;;;;;CAMC,GACD,OAAO,SAASA,OAAOC,OAAe,EAAEC,SAAS,CAAC;IAChD,OAAOD,QAAQE,OAAO,CAAC,QAAQ,IAAIC,MAAM,CAACF;AAC5C"}