@metamask/utils 8.1.0 → 8.2.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.
- package/CHANGELOG.md +19 -1
- package/dist/assert.js +16 -0
- package/dist/assert.js.map +1 -0
- package/dist/assert.mjs +16 -0
- package/dist/assert.mjs.map +1 -0
- package/dist/base64.js +11 -0
- package/dist/base64.js.map +1 -0
- package/dist/base64.mjs +11 -0
- package/dist/base64.mjs.map +1 -0
- package/dist/bytes.js +43 -0
- package/dist/bytes.js.map +1 -0
- package/dist/bytes.mjs +43 -0
- package/dist/bytes.mjs.map +1 -0
- package/dist/caip-types.js +40 -0
- package/dist/caip-types.js.map +1 -0
- package/dist/caip-types.mjs +40 -0
- package/dist/caip-types.mjs.map +1 -0
- package/dist/checksum.js +12 -0
- package/dist/checksum.js.map +1 -0
- package/dist/checksum.mjs +12 -0
- package/dist/checksum.mjs.map +1 -0
- package/dist/chunk-2LBGT4GH.js +15 -0
- package/dist/chunk-2LBGT4GH.js.map +1 -0
- package/dist/chunk-2TBCL6EF.js +1 -0
- package/dist/chunk-2TBCL6EF.js.map +1 -0
- package/dist/chunk-3W5G4CYI.js +25 -0
- package/dist/chunk-3W5G4CYI.js.map +1 -0
- package/dist/chunk-4D6XQBHA.js +69 -0
- package/dist/chunk-4D6XQBHA.js.map +1 -0
- package/dist/chunk-4RMX5YWE.js +34 -0
- package/dist/chunk-4RMX5YWE.js.map +1 -0
- package/dist/chunk-52OU772R.mjs +122 -0
- package/dist/chunk-52OU772R.mjs.map +1 -0
- package/dist/chunk-6C35XQOF.mjs +257 -0
- package/dist/chunk-6C35XQOF.mjs.map +1 -0
- package/dist/chunk-6NZW4WK4.js +35 -0
- package/dist/chunk-6NZW4WK4.js.map +1 -0
- package/dist/chunk-6ZDHSOUV.js +59 -0
- package/dist/chunk-6ZDHSOUV.js.map +1 -0
- package/dist/chunk-74DGVJVE.mjs +59 -0
- package/dist/chunk-74DGVJVE.mjs.map +1 -0
- package/dist/chunk-AY6FDCBT.mjs +1 -0
- package/dist/chunk-AY6FDCBT.mjs.map +1 -0
- package/dist/chunk-BFQDMI3M.js +122 -0
- package/dist/chunk-BFQDMI3M.js.map +1 -0
- package/dist/chunk-DHVKFDHQ.js +95 -0
- package/dist/chunk-DHVKFDHQ.js.map +1 -0
- package/dist/chunk-DYMCEQIV.mjs +1 -0
- package/dist/chunk-DYMCEQIV.mjs.map +1 -0
- package/dist/chunk-E4C7EW4R.js +16 -0
- package/dist/chunk-E4C7EW4R.js.map +1 -0
- package/dist/chunk-EQMZL4XU.js +1 -0
- package/dist/chunk-EQMZL4XU.js.map +1 -0
- package/dist/chunk-GZS3IQBZ.mjs +16 -0
- package/dist/chunk-GZS3IQBZ.mjs.map +1 -0
- package/dist/chunk-H4YFDLB7.mjs +70 -0
- package/dist/chunk-H4YFDLB7.mjs.map +1 -0
- package/dist/chunk-I575FZFH.mjs +1 -0
- package/dist/chunk-I575FZFH.mjs.map +1 -0
- package/dist/chunk-IZC266HS.js +55 -0
- package/dist/chunk-IZC266HS.js.map +1 -0
- package/dist/chunk-JPAL7Q5S.mjs +90 -0
- package/dist/chunk-JPAL7Q5S.mjs.map +1 -0
- package/dist/chunk-LC2CRSWD.js +1 -0
- package/dist/chunk-LC2CRSWD.js.map +1 -0
- package/dist/chunk-NQMRFZHB.mjs +35 -0
- package/dist/chunk-NQMRFZHB.mjs.map +1 -0
- package/dist/chunk-O3EIM33O.mjs +95 -0
- package/dist/chunk-O3EIM33O.mjs.map +1 -0
- package/dist/chunk-OLLG4H35.js +257 -0
- package/dist/chunk-OLLG4H35.js.map +1 -0
- package/dist/chunk-QEPVHEP7.js +273 -0
- package/dist/chunk-QEPVHEP7.js.map +1 -0
- package/dist/chunk-QVEKZRZ2.js +70 -0
- package/dist/chunk-QVEKZRZ2.js.map +1 -0
- package/dist/chunk-RIRDOQPX.mjs +15 -0
- package/dist/chunk-RIRDOQPX.mjs.map +1 -0
- package/dist/chunk-RKRGAFXY.js +1 -0
- package/dist/chunk-RKRGAFXY.js.map +1 -0
- package/dist/chunk-ROQSKDP5.mjs +69 -0
- package/dist/chunk-ROQSKDP5.mjs.map +1 -0
- package/dist/chunk-RRYOWRCV.mjs +1 -0
- package/dist/chunk-RRYOWRCV.mjs.map +1 -0
- package/dist/chunk-S3UHBN2Z.mjs +44 -0
- package/dist/chunk-S3UHBN2Z.mjs.map +1 -0
- package/dist/chunk-TGOMTREC.mjs +75 -0
- package/dist/chunk-TGOMTREC.mjs.map +1 -0
- package/dist/chunk-THNLGEXV.mjs +34 -0
- package/dist/chunk-THNLGEXV.mjs.map +1 -0
- package/dist/chunk-U7ZUGCE7.js +75 -0
- package/dist/chunk-U7ZUGCE7.js.map +1 -0
- package/dist/chunk-UOTVU7OQ.js +1 -0
- package/dist/chunk-UOTVU7OQ.js.map +1 -0
- package/dist/chunk-VA2DRBDE.mjs +273 -0
- package/dist/chunk-VA2DRBDE.mjs.map +1 -0
- package/dist/chunk-VFXTVNXN.js +44 -0
- package/dist/chunk-VFXTVNXN.js.map +1 -0
- package/dist/chunk-WA4DHIND.mjs +1 -0
- package/dist/chunk-WA4DHIND.mjs.map +1 -0
- package/dist/chunk-X66SUIEF.mjs +25 -0
- package/dist/chunk-X66SUIEF.mjs.map +1 -0
- package/dist/chunk-XYGUOY6N.mjs +55 -0
- package/dist/chunk-XYGUOY6N.mjs.map +1 -0
- package/dist/chunk-Z2RGWDD7.js +90 -0
- package/dist/chunk-Z2RGWDD7.js.map +1 -0
- package/dist/coercers.js +18 -0
- package/dist/coercers.js.map +1 -0
- package/dist/coercers.mjs +18 -0
- package/dist/coercers.mjs.map +1 -0
- package/dist/collections.js +10 -0
- package/dist/collections.js.map +1 -0
- package/dist/collections.mjs +10 -0
- package/dist/collections.mjs.map +1 -0
- package/dist/encryption-types.js +2 -0
- package/dist/encryption-types.js.map +1 -0
- package/dist/encryption-types.mjs +2 -0
- package/dist/encryption-types.mjs.map +1 -0
- package/dist/errors.js +17 -0
- package/dist/errors.js.map +1 -0
- package/dist/errors.mjs +17 -0
- package/dist/errors.mjs.map +1 -0
- package/dist/fs.js +26 -0
- package/dist/fs.js.map +1 -0
- package/dist/fs.mjs +26 -0
- package/dist/fs.mjs.map +1 -0
- package/dist/hex.js +35 -0
- package/dist/hex.js.map +1 -0
- package/dist/hex.mjs +35 -0
- package/dist/hex.mjs.map +1 -0
- package/dist/index.js +289 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +289 -0
- package/dist/index.mjs.map +1 -0
- package/dist/json.js +75 -0
- package/dist/json.js.map +1 -0
- package/dist/json.mjs +75 -0
- package/dist/json.mjs.map +1 -0
- package/dist/keyring.js +2 -0
- package/dist/keyring.js.map +1 -0
- package/dist/keyring.mjs +2 -0
- package/dist/keyring.mjs.map +1 -0
- package/dist/logging.js +10 -0
- package/dist/logging.js.map +1 -0
- package/dist/logging.mjs +10 -0
- package/dist/logging.mjs.map +1 -0
- package/dist/misc.js +28 -0
- package/dist/misc.js.map +1 -0
- package/dist/misc.mjs +28 -0
- package/dist/misc.mjs.map +1 -0
- package/dist/node.js +309 -0
- package/dist/node.js.map +1 -0
- package/dist/node.mjs +309 -0
- package/dist/node.mjs.map +1 -0
- package/dist/number.js +18 -0
- package/dist/number.js.map +1 -0
- package/dist/number.mjs +18 -0
- package/dist/number.mjs.map +1 -0
- package/dist/opaque.js +2 -0
- package/dist/opaque.js.map +1 -0
- package/dist/opaque.mjs +2 -0
- package/dist/opaque.mjs.map +1 -0
- package/dist/time.js +12 -0
- package/dist/time.js.map +1 -0
- package/dist/time.mjs +12 -0
- package/dist/time.mjs.map +1 -0
- package/dist/transaction-types.js +2 -0
- package/dist/transaction-types.js.map +1 -0
- package/dist/transaction-types.mjs +2 -0
- package/dist/transaction-types.mjs.map +1 -0
- package/dist/types/assert.d.ts.map +1 -1
- package/dist/types/bytes.d.ts +14 -0
- package/dist/types/bytes.d.ts.map +1 -1
- package/dist/types/errors.d.ts +58 -0
- package/dist/types/errors.d.ts.map +1 -0
- package/dist/types/fs.d.ts +133 -0
- package/dist/types/fs.d.ts.map +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/json.d.ts +83 -44
- package/dist/types/json.d.ts.map +1 -1
- package/dist/types/node.d.ts +3 -0
- package/dist/types/node.d.ts.map +1 -0
- package/dist/versions.js +27 -0
- package/dist/versions.js.map +1 -0
- package/dist/versions.mjs +27 -0
- package/dist/versions.mjs.map +1 -0
- package/package.json +22 -21
- package/dist/cjs/assert.js +0 -116
- package/dist/cjs/assert.js.map +0 -1
- package/dist/cjs/base64.js +0 -32
- package/dist/cjs/base64.js.map +0 -1
- package/dist/cjs/bytes.js +0 -255
- package/dist/cjs/bytes.js.map +0 -1
- package/dist/cjs/caip-types.js +0 -115
- package/dist/cjs/caip-types.js.map +0 -1
- package/dist/cjs/checksum.js +0 -17
- package/dist/cjs/checksum.js.map +0 -1
- package/dist/cjs/coercers.js +0 -96
- package/dist/cjs/coercers.js.map +0 -1
- package/dist/cjs/collections.js +0 -157
- package/dist/cjs/collections.js.map +0 -1
- package/dist/cjs/encryption-types.js +0 -6
- package/dist/cjs/encryption-types.js.map +0 -1
- package/dist/cjs/hex.js +0 -107
- package/dist/cjs/hex.js.map +0 -1
- package/dist/cjs/index.js +0 -37
- package/dist/cjs/index.js.map +0 -1
- package/dist/cjs/json.js +0 -265
- package/dist/cjs/json.js.map +0 -1
- package/dist/cjs/keyring.js +0 -6
- package/dist/cjs/keyring.js.map +0 -1
- package/dist/cjs/logging.js +0 -33
- package/dist/cjs/logging.js.map +0 -1
- package/dist/cjs/misc.js +0 -111
- package/dist/cjs/misc.js.map +0 -1
- package/dist/cjs/number.js +0 -52
- package/dist/cjs/number.js.map +0 -1
- package/dist/cjs/opaque.js +0 -8
- package/dist/cjs/opaque.js.map +0 -1
- package/dist/cjs/time.js +0 -63
- package/dist/cjs/time.js.map +0 -1
- package/dist/cjs/transaction-types.js +0 -6
- package/dist/cjs/transaction-types.js.map +0 -1
- package/dist/cjs/versions.js +0 -79
- package/dist/cjs/versions.js.map +0 -1
- package/dist/esm/assert.js +0 -133
- package/dist/esm/assert.js.map +0 -1
- package/dist/esm/base64.js +0 -28
- package/dist/esm/base64.js.map +0 -1
- package/dist/esm/bytes.js +0 -334
- package/dist/esm/bytes.js.map +0 -1
- package/dist/esm/caip-types.js +0 -99
- package/dist/esm/caip-types.js.map +0 -1
- package/dist/esm/checksum.js +0 -7
- package/dist/esm/checksum.js.map +0 -1
- package/dist/esm/coercers.js +0 -153
- package/dist/esm/coercers.js.map +0 -1
- package/dist/esm/collections.js +0 -140
- package/dist/esm/collections.js.map +0 -1
- package/dist/esm/encryption-types.js +0 -3
- package/dist/esm/encryption-types.js.map +0 -1
- package/dist/esm/hex.js +0 -108
- package/dist/esm/hex.js.map +0 -1
- package/dist/esm/index.js +0 -20
- package/dist/esm/index.js.map +0 -1
- package/dist/esm/json.js +0 -303
- package/dist/esm/json.js.map +0 -1
- package/dist/esm/keyring.js +0 -3
- package/dist/esm/keyring.js.map +0 -1
- package/dist/esm/logging.js +0 -34
- package/dist/esm/logging.js.map +0 -1
- package/dist/esm/misc.js +0 -129
- package/dist/esm/misc.js.map +0 -1
- package/dist/esm/number.js +0 -92
- package/dist/esm/number.js.map +0 -1
- package/dist/esm/opaque.js +0 -5
- package/dist/esm/opaque.js.map +0 -1
- package/dist/esm/package.json +0 -1
- package/dist/esm/time.js +0 -53
- package/dist/esm/time.js.map +0 -1
- package/dist/esm/transaction-types.js +0 -3
- package/dist/esm/transaction-types.js.map +0 -1
- package/dist/esm/versions.js +0 -78
- package/dist/esm/versions.js.map +0 -1
- package/dist/types/caip-types.test-d.d.ts +0 -2
- package/dist/types/caip-types.test-d.d.ts.map +0 -1
- package/dist/types/hex.test-d.d.ts +0 -2
- package/dist/types/hex.test-d.d.ts.map +0 -1
- package/dist/types/json.test-d.d.ts +0 -2
- package/dist/types/json.test-d.d.ts.map +0 -1
- package/dist/types/misc.test-d.d.ts +0 -2
- package/dist/types/misc.test-d.d.ts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/fs.ts"],"sourcesContent":["// This file is intended to be used only in a Node.js context.\n/* eslint-disable import/no-nodejs-modules */\n\nimport fs from 'fs';\nimport os from 'os';\nimport path from 'path';\n\nimport { isErrorWithCode, wrapError } from './errors';\nimport type { Json } from './json';\n\n/**\n * Information about the file sandbox provided to tests that need temporary\n * access to the filesystem.\n */\nexport type FileSandbox = {\n directoryPath: string;\n withinSandbox: (\n test: (args: { directoryPath: string }) => Promise<void>,\n ) => Promise<void>;\n};\n\n/**\n * Read the file at the given path, assuming its content is encoded as UTF-8.\n *\n * @param filePath - The path to the file.\n * @returns The content of the file.\n * @throws An error with a stack trace if reading fails in any way.\n */\nexport async function readFile(filePath: string): Promise<string> {\n try {\n return await fs.promises.readFile(filePath, 'utf8');\n } catch (error) {\n throw wrapError(error, `Could not read file '${filePath}'`);\n }\n}\n\n/**\n * Write content to the file at the given path, creating the directory structure\n * for the file automatically if necessary.\n *\n * @param filePath - The path to the file.\n * @param content - The new content of the file.\n * @throws An error with a stack trace if writing fails in any way.\n */\nexport async function writeFile(\n filePath: string,\n content: string,\n): Promise<void> {\n try {\n await fs.promises.mkdir(path.dirname(filePath), { recursive: true });\n await fs.promises.writeFile(filePath, content);\n } catch (error) {\n throw wrapError(error, `Could not write file '${filePath}'`);\n }\n}\n\n/**\n * Read the assumed JSON file at the given path, attempts to parse it, and\n * get the resulting object. Supports a custom parser (in case you want to\n * use the [JSON5](https://www.npmjs.com/package/json5) package instead).\n *\n * @param filePath - The path segments pointing to the JSON file. Will be passed\n * to path.join().\n * @param options - Options to this function.\n * @param options.parser - The parser object to use. Defaults to `JSON`.\n * @param options.parser.parse - A function that parses JSON data.\n * @returns The object corresponding to the parsed JSON file, typed against the\n * struct.\n * @throws An error with a stack trace if reading fails in any way, or if the\n * parsed value is not a plain object.\n */\nexport async function readJsonFile<Value extends Json>(\n filePath: string,\n {\n parser = JSON,\n }: {\n parser?: {\n parse: (\n text: Parameters<typeof JSON.parse>[0],\n ) => ReturnType<typeof JSON.parse>;\n };\n } = {},\n): Promise<Value> {\n try {\n const content = await fs.promises.readFile(filePath, 'utf8');\n return parser.parse(content);\n } catch (error) {\n throw wrapError(error, `Could not read JSON file '${filePath}'`);\n }\n}\n\n/**\n * Attempt to write the given JSON-like value to the file at the given path,\n * creating the directory structure for the file automatically if necessary.\n * Adds a newline to the end of the file. Supports a custom parser (in case you\n * want to use the [JSON5](https://www.npmjs.com/package/json5) package\n * instead).\n *\n * @param filePath - The path to write the JSON file to, including the file\n * itself.\n * @param jsonValue - The JSON-like value to write to the file. Make sure that\n * JSON.stringify can handle it.\n * @param options - The options to this function.\n * @param options.prettify - Whether to format the JSON as it is turned into a\n * string such that it is broken up into separate lines (using 2 spaces as\n * indentation).\n * @param options.stringifier - The stringifier to use. Defaults to `JSON`.\n * @param options.stringifier.stringify - A function that stringifies JSON.\n * @returns The object corresponding to the parsed JSON file, typed against the\n * struct.\n * @throws An error with a stack trace if writing fails in any way.\n */\nexport async function writeJsonFile(\n filePath: string,\n jsonValue: Json,\n {\n stringifier = JSON,\n prettify = false,\n }: {\n stringifier?: {\n stringify: typeof JSON.stringify;\n };\n prettify?: boolean;\n } = {},\n): Promise<void> {\n try {\n await fs.promises.mkdir(path.dirname(filePath), { recursive: true });\n const json = prettify\n ? stringifier.stringify(jsonValue, null, ' ')\n : stringifier.stringify(jsonValue);\n await fs.promises.writeFile(filePath, json);\n } catch (error) {\n throw wrapError(error, `Could not write JSON file '${filePath}'`);\n }\n}\n\n/**\n * Test the given path to determine whether it represents a file.\n *\n * @param filePath - The path to a (supposed) file on the filesystem.\n * @returns A promise for true if the file exists or false otherwise.\n * @throws An error with a stack trace if reading fails in any way.\n */\nexport async function fileExists(filePath: string): Promise<boolean> {\n try {\n const stats = await fs.promises.stat(filePath);\n return stats.isFile();\n } catch (error) {\n if (isErrorWithCode(error) && error.code === 'ENOENT') {\n return false;\n }\n\n throw wrapError(error, `Could not determine if file exists '${filePath}'`);\n }\n}\n\n/**\n * Test the given path to determine whether it represents a directory.\n *\n * @param directoryPath - The path to a (supposed) directory on the filesystem.\n * @returns A promise for true if the file exists or false otherwise.\n * @throws An error with a stack trace if reading fails in any way.\n */\nexport async function directoryExists(directoryPath: string): Promise<boolean> {\n try {\n const stats = await fs.promises.stat(directoryPath);\n return stats.isDirectory();\n } catch (error) {\n if (isErrorWithCode(error) && error.code === 'ENOENT') {\n return false;\n }\n\n throw wrapError(\n error,\n `Could not determine if directory exists '${directoryPath}'`,\n );\n }\n}\n\n/**\n * Create the given directory along with any directories leading up to the\n * directory, or do nothing if the directory already exists.\n *\n * @param directoryPath - The path to the desired directory.\n * @throws An error with a stack trace if reading fails in any way.\n */\nexport async function ensureDirectoryStructureExists(\n directoryPath: string,\n): Promise<void> {\n try {\n await fs.promises.mkdir(directoryPath, { recursive: true });\n } catch (error) {\n throw wrapError(\n error,\n `Could not create directory structure '${directoryPath}'`,\n );\n }\n}\n\n/**\n * Remove the given file or directory if it exists, or do nothing if it does\n * not.\n *\n * @param entryPath - The path to the file or directory.\n * @throws An error with a stack trace if removal fails in any way.\n */\nexport async function forceRemove(entryPath: string): Promise<void> {\n try {\n return await fs.promises.rm(entryPath, {\n recursive: true,\n force: true,\n });\n } catch (error) {\n throw wrapError(error, `Could not remove file or directory '${entryPath}'`);\n }\n}\n\n/**\n * Construct a sandbox object which can be used in tests that need temporary\n * access to the filesystem.\n *\n * @param projectName - The name of the project.\n * @returns The sandbox object. This contains a `withinSandbox` function which\n * can be used in tests (see example).\n * @example\n * ```typescript\n * const { withinSandbox } = createSandbox('utils');\n *\n * // ... later ...\n *\n * it('does something with the filesystem', async () => {\n * await withinSandbox(async ({ directoryPath }) => {\n * await fs.promises.writeFile(\n * path.join(directoryPath, 'some-file'),\n * 'some content',\n * 'utf8'\n * );\n * })\n * });\n * ```\n */\nexport function createSandbox(projectName: string): FileSandbox {\n const timestamp = new Date().getTime();\n const directoryPath = path.join(os.tmpdir(), `${projectName}--${timestamp}`);\n\n return {\n directoryPath,\n async withinSandbox(\n test: (args: { directoryPath: string }) => Promise<void>,\n ) {\n if (await directoryExists(directoryPath)) {\n throw new Error(`${directoryPath} already exists. Cannot continue.`);\n }\n\n await ensureDirectoryStructureExists(directoryPath);\n\n try {\n await test({ directoryPath });\n } finally {\n await forceRemove(directoryPath);\n }\n },\n };\n}\n"],"mappings":"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","names":[]}
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import {
|
|
2
|
+
assertStruct
|
|
3
|
+
} from "./chunk-74DGVJVE.mjs";
|
|
4
|
+
import {
|
|
5
|
+
hasProperty
|
|
6
|
+
} from "./chunk-H4YFDLB7.mjs";
|
|
7
|
+
|
|
8
|
+
// src/json.ts
|
|
9
|
+
import {
|
|
10
|
+
any,
|
|
11
|
+
array,
|
|
12
|
+
boolean,
|
|
13
|
+
coerce,
|
|
14
|
+
create,
|
|
15
|
+
define,
|
|
16
|
+
integer,
|
|
17
|
+
is,
|
|
18
|
+
lazy,
|
|
19
|
+
literal,
|
|
20
|
+
nullable,
|
|
21
|
+
number,
|
|
22
|
+
object as superstructObject,
|
|
23
|
+
optional,
|
|
24
|
+
record,
|
|
25
|
+
string,
|
|
26
|
+
union,
|
|
27
|
+
unknown,
|
|
28
|
+
Struct
|
|
29
|
+
} from "superstruct";
|
|
30
|
+
var object = (schema) => (
|
|
31
|
+
// The type is slightly different from a regular object struct, because we
|
|
32
|
+
// want to make properties with `undefined` in their type optional, but not
|
|
33
|
+
// `undefined` itself. This means that we need a type cast.
|
|
34
|
+
superstructObject(schema)
|
|
35
|
+
);
|
|
36
|
+
function hasOptional({ path, branch }) {
|
|
37
|
+
const field = path[path.length - 1];
|
|
38
|
+
return hasProperty(branch[branch.length - 2], field);
|
|
39
|
+
}
|
|
40
|
+
function exactOptional(struct) {
|
|
41
|
+
return new Struct({
|
|
42
|
+
...struct,
|
|
43
|
+
type: `optional ${struct.type}`,
|
|
44
|
+
validator: (value, context) => !hasOptional(context) || struct.validator(value, context),
|
|
45
|
+
refiner: (value, context) => !hasOptional(context) || struct.refiner(value, context)
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
var finiteNumber = () => define("finite number", (value) => {
|
|
49
|
+
return is(value, number()) && Number.isFinite(value);
|
|
50
|
+
});
|
|
51
|
+
var UnsafeJsonStruct = union([
|
|
52
|
+
literal(null),
|
|
53
|
+
boolean(),
|
|
54
|
+
finiteNumber(),
|
|
55
|
+
string(),
|
|
56
|
+
array(lazy(() => UnsafeJsonStruct)),
|
|
57
|
+
record(
|
|
58
|
+
string(),
|
|
59
|
+
lazy(() => UnsafeJsonStruct)
|
|
60
|
+
)
|
|
61
|
+
]);
|
|
62
|
+
var JsonStruct = coerce(UnsafeJsonStruct, any(), (value) => {
|
|
63
|
+
assertStruct(value, UnsafeJsonStruct);
|
|
64
|
+
return JSON.parse(
|
|
65
|
+
JSON.stringify(value, (propKey, propValue) => {
|
|
66
|
+
if (propKey === "__proto__" || propKey === "constructor") {
|
|
67
|
+
return void 0;
|
|
68
|
+
}
|
|
69
|
+
return propValue;
|
|
70
|
+
})
|
|
71
|
+
);
|
|
72
|
+
});
|
|
73
|
+
function isValidJson(value) {
|
|
74
|
+
try {
|
|
75
|
+
getSafeJson(value);
|
|
76
|
+
return true;
|
|
77
|
+
} catch {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function getSafeJson(value) {
|
|
82
|
+
return create(value, JsonStruct);
|
|
83
|
+
}
|
|
84
|
+
function getJsonSize(value) {
|
|
85
|
+
assertStruct(value, JsonStruct, "Invalid JSON value");
|
|
86
|
+
const json = JSON.stringify(value);
|
|
87
|
+
return new TextEncoder().encode(json).byteLength;
|
|
88
|
+
}
|
|
89
|
+
var jsonrpc2 = "2.0";
|
|
90
|
+
var JsonRpcVersionStruct = literal(jsonrpc2);
|
|
91
|
+
var JsonRpcIdStruct = nullable(union([number(), string()]));
|
|
92
|
+
var JsonRpcErrorStruct = object({
|
|
93
|
+
code: integer(),
|
|
94
|
+
message: string(),
|
|
95
|
+
data: exactOptional(JsonStruct),
|
|
96
|
+
stack: exactOptional(string())
|
|
97
|
+
});
|
|
98
|
+
var JsonRpcParamsStruct = union([record(string(), JsonStruct), array(JsonStruct)]);
|
|
99
|
+
var JsonRpcRequestStruct = object({
|
|
100
|
+
id: JsonRpcIdStruct,
|
|
101
|
+
jsonrpc: JsonRpcVersionStruct,
|
|
102
|
+
method: string(),
|
|
103
|
+
params: exactOptional(JsonRpcParamsStruct)
|
|
104
|
+
});
|
|
105
|
+
var JsonRpcNotificationStruct = object({
|
|
106
|
+
jsonrpc: JsonRpcVersionStruct,
|
|
107
|
+
method: string(),
|
|
108
|
+
params: exactOptional(JsonRpcParamsStruct)
|
|
109
|
+
});
|
|
110
|
+
function isJsonRpcNotification(value) {
|
|
111
|
+
return is(value, JsonRpcNotificationStruct);
|
|
112
|
+
}
|
|
113
|
+
function assertIsJsonRpcNotification(value, ErrorWrapper) {
|
|
114
|
+
assertStruct(
|
|
115
|
+
value,
|
|
116
|
+
JsonRpcNotificationStruct,
|
|
117
|
+
"Invalid JSON-RPC notification",
|
|
118
|
+
ErrorWrapper
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
function isJsonRpcRequest(value) {
|
|
122
|
+
return is(value, JsonRpcRequestStruct);
|
|
123
|
+
}
|
|
124
|
+
function assertIsJsonRpcRequest(value, ErrorWrapper) {
|
|
125
|
+
assertStruct(
|
|
126
|
+
value,
|
|
127
|
+
JsonRpcRequestStruct,
|
|
128
|
+
"Invalid JSON-RPC request",
|
|
129
|
+
ErrorWrapper
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
var PendingJsonRpcResponseStruct = superstructObject({
|
|
133
|
+
id: JsonRpcIdStruct,
|
|
134
|
+
jsonrpc: JsonRpcVersionStruct,
|
|
135
|
+
result: optional(unknown()),
|
|
136
|
+
error: optional(JsonRpcErrorStruct)
|
|
137
|
+
});
|
|
138
|
+
var JsonRpcSuccessStruct = object({
|
|
139
|
+
id: JsonRpcIdStruct,
|
|
140
|
+
jsonrpc: JsonRpcVersionStruct,
|
|
141
|
+
result: JsonStruct
|
|
142
|
+
});
|
|
143
|
+
var JsonRpcFailureStruct = object({
|
|
144
|
+
id: JsonRpcIdStruct,
|
|
145
|
+
jsonrpc: JsonRpcVersionStruct,
|
|
146
|
+
error: JsonRpcErrorStruct
|
|
147
|
+
});
|
|
148
|
+
var JsonRpcResponseStruct = union([
|
|
149
|
+
JsonRpcSuccessStruct,
|
|
150
|
+
JsonRpcFailureStruct
|
|
151
|
+
]);
|
|
152
|
+
function isPendingJsonRpcResponse(response) {
|
|
153
|
+
return is(response, PendingJsonRpcResponseStruct);
|
|
154
|
+
}
|
|
155
|
+
function assertIsPendingJsonRpcResponse(response, ErrorWrapper) {
|
|
156
|
+
assertStruct(
|
|
157
|
+
response,
|
|
158
|
+
PendingJsonRpcResponseStruct,
|
|
159
|
+
"Invalid pending JSON-RPC response",
|
|
160
|
+
ErrorWrapper
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
function isJsonRpcResponse(response) {
|
|
164
|
+
return is(response, JsonRpcResponseStruct);
|
|
165
|
+
}
|
|
166
|
+
function assertIsJsonRpcResponse(value, ErrorWrapper) {
|
|
167
|
+
assertStruct(
|
|
168
|
+
value,
|
|
169
|
+
JsonRpcResponseStruct,
|
|
170
|
+
"Invalid JSON-RPC response",
|
|
171
|
+
ErrorWrapper
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
function isJsonRpcSuccess(value) {
|
|
175
|
+
return is(value, JsonRpcSuccessStruct);
|
|
176
|
+
}
|
|
177
|
+
function assertIsJsonRpcSuccess(value, ErrorWrapper) {
|
|
178
|
+
assertStruct(
|
|
179
|
+
value,
|
|
180
|
+
JsonRpcSuccessStruct,
|
|
181
|
+
"Invalid JSON-RPC success response",
|
|
182
|
+
ErrorWrapper
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
function isJsonRpcFailure(value) {
|
|
186
|
+
return is(value, JsonRpcFailureStruct);
|
|
187
|
+
}
|
|
188
|
+
function assertIsJsonRpcFailure(value, ErrorWrapper) {
|
|
189
|
+
assertStruct(
|
|
190
|
+
value,
|
|
191
|
+
JsonRpcFailureStruct,
|
|
192
|
+
"Invalid JSON-RPC failure response",
|
|
193
|
+
ErrorWrapper
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
function isJsonRpcError(value) {
|
|
197
|
+
return is(value, JsonRpcErrorStruct);
|
|
198
|
+
}
|
|
199
|
+
function assertIsJsonRpcError(value, ErrorWrapper) {
|
|
200
|
+
assertStruct(
|
|
201
|
+
value,
|
|
202
|
+
JsonRpcErrorStruct,
|
|
203
|
+
"Invalid JSON-RPC error",
|
|
204
|
+
ErrorWrapper
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
function getJsonRpcIdValidator(options) {
|
|
208
|
+
const { permitEmptyString, permitFractions, permitNull } = {
|
|
209
|
+
permitEmptyString: true,
|
|
210
|
+
permitFractions: false,
|
|
211
|
+
permitNull: true,
|
|
212
|
+
...options
|
|
213
|
+
};
|
|
214
|
+
const isValidJsonRpcId = (id) => {
|
|
215
|
+
return Boolean(
|
|
216
|
+
typeof id === "number" && (permitFractions || Number.isInteger(id)) || typeof id === "string" && (permitEmptyString || id.length > 0) || permitNull && id === null
|
|
217
|
+
);
|
|
218
|
+
};
|
|
219
|
+
return isValidJsonRpcId;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export {
|
|
223
|
+
object,
|
|
224
|
+
exactOptional,
|
|
225
|
+
UnsafeJsonStruct,
|
|
226
|
+
JsonStruct,
|
|
227
|
+
isValidJson,
|
|
228
|
+
getSafeJson,
|
|
229
|
+
getJsonSize,
|
|
230
|
+
jsonrpc2,
|
|
231
|
+
JsonRpcVersionStruct,
|
|
232
|
+
JsonRpcIdStruct,
|
|
233
|
+
JsonRpcErrorStruct,
|
|
234
|
+
JsonRpcParamsStruct,
|
|
235
|
+
JsonRpcRequestStruct,
|
|
236
|
+
JsonRpcNotificationStruct,
|
|
237
|
+
isJsonRpcNotification,
|
|
238
|
+
assertIsJsonRpcNotification,
|
|
239
|
+
isJsonRpcRequest,
|
|
240
|
+
assertIsJsonRpcRequest,
|
|
241
|
+
PendingJsonRpcResponseStruct,
|
|
242
|
+
JsonRpcSuccessStruct,
|
|
243
|
+
JsonRpcFailureStruct,
|
|
244
|
+
JsonRpcResponseStruct,
|
|
245
|
+
isPendingJsonRpcResponse,
|
|
246
|
+
assertIsPendingJsonRpcResponse,
|
|
247
|
+
isJsonRpcResponse,
|
|
248
|
+
assertIsJsonRpcResponse,
|
|
249
|
+
isJsonRpcSuccess,
|
|
250
|
+
assertIsJsonRpcSuccess,
|
|
251
|
+
isJsonRpcFailure,
|
|
252
|
+
assertIsJsonRpcFailure,
|
|
253
|
+
isJsonRpcError,
|
|
254
|
+
assertIsJsonRpcError,
|
|
255
|
+
getJsonRpcIdValidator
|
|
256
|
+
};
|
|
257
|
+
//# sourceMappingURL=chunk-6C35XQOF.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/json.ts"],"sourcesContent":["import type { Context, Infer } from 'superstruct';\nimport {\n any,\n array,\n boolean,\n coerce,\n create,\n define,\n integer,\n is,\n lazy,\n literal,\n nullable,\n number,\n object as superstructObject,\n optional,\n record,\n string,\n union,\n unknown,\n Struct,\n} from 'superstruct';\nimport type {\n ObjectSchema,\n Optionalize,\n Simplify,\n} from 'superstruct/dist/utils';\n\nimport type { AssertionErrorConstructor } from './assert';\nimport { assertStruct } from './assert';\nimport { hasProperty } from './misc';\n\n/**\n * Any JSON-compatible value.\n */\nexport type Json =\n | null\n | boolean\n | number\n | string\n | Json[]\n | { [prop: string]: Json };\n\n/**\n * A helper type to make properties with `undefined` in their type optional, but\n * not `undefined` itself.\n *\n * @example\n * ```ts\n * type Foo = ObjectOptional<{ foo: string | undefined }>;\n * // Foo is equivalent to { foo?: string }\n * ```\n */\nexport type ObjectOptional<Schema extends Record<string, unknown>> = {\n [Key in keyof Schema as Schema[Key] extends ExactOptionalGuard\n ? Key\n : never]?: Schema[Key] extends ExactOptionalGuard & infer Original\n ? Original\n : never;\n} & {\n [Key in keyof Schema as Schema[Key] extends ExactOptionalGuard\n ? never\n : Key]: Schema[Key];\n};\n\n/**\n * An object type with support for exact optionals. This is used by the `object`\n * struct. This uses the {@link ObjectOptional} helper to make properties with\n * `undefined` in their type optional, but not `undefined` itself.\n */\nexport type ObjectType<Schema extends ObjectSchema> = Simplify<\n ObjectOptional<\n Optionalize<{\n [Key in keyof Schema]: Infer<Schema[Key]>;\n }>\n >\n>;\n\n/**\n * A struct to check if the given value is a valid object, with support for\n * {@link exactOptional} types.\n *\n * @param schema - The schema of the object.\n * @returns A struct to check if the given value is an object.\n */\nexport const object = <Schema extends ObjectSchema>(\n schema: Schema,\n): Struct<ObjectType<Schema>> =>\n // The type is slightly different from a regular object struct, because we\n // want to make properties with `undefined` in their type optional, but not\n // `undefined` itself. This means that we need a type cast.\n superstructObject(schema) as unknown as Struct<ObjectType<Schema>>;\n\ndeclare const exactOptionalSymbol: unique symbol;\ntype ExactOptionalGuard = {\n _exactOptionalGuard?: typeof exactOptionalSymbol;\n};\n\n/**\n * Check the last field of a path is present.\n *\n * @param context - The context to check.\n * @param context.path - The path to check.\n * @param context.branch - The branch to check.\n * @returns Whether the last field of a path is present.\n */\nfunction hasOptional({ path, branch }: Context): boolean {\n const field = path[path.length - 1];\n return hasProperty(branch[branch.length - 2], field);\n}\n\n/**\n * A struct which allows the property of an object to be absent, or to be present\n * as long as it's valid and not set to `undefined`.\n *\n * This struct should be used in conjunction with the {@link object} from this\n * library, to get proper type inference.\n *\n * @param struct - The struct to check the value against, if present.\n * @returns A struct to check if the given value is valid, or not present.\n * @example\n * ```ts\n * const struct = object({\n * foo: exactOptional(string()),\n * bar: exactOptional(number()),\n * baz: optional(boolean()),\n * qux: unknown(),\n * });\n *\n * type Type = Infer<typeof struct>;\n * // Type is equivalent to:\n * // {\n * // foo?: string;\n * // bar?: number;\n * // baz?: boolean | undefined;\n * // qux: unknown;\n * // }\n * ```\n */\nexport function exactOptional<Type, Schema>(\n struct: Struct<Type, Schema>,\n): Struct<Type & ExactOptionalGuard, Schema> {\n return new Struct<Type & ExactOptionalGuard, Schema>({\n ...struct,\n\n type: `optional ${struct.type}`,\n validator: (value, context) =>\n !hasOptional(context) || struct.validator(value, context),\n\n refiner: (value, context) =>\n !hasOptional(context) || struct.refiner(value as Type, context),\n });\n}\n\n/**\n * A struct to check if the given value is finite number. Superstruct's\n * `number()` struct does not check if the value is finite.\n *\n * @returns A struct to check if the given value is finite number.\n */\nconst finiteNumber = () =>\n define<number>('finite number', (value) => {\n return is(value, number()) && Number.isFinite(value);\n });\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * Note that this struct is unsafe. For safe validation, use {@link JsonStruct}.\n */\n// We cannot infer the type of the struct, because it is recursive.\nexport const UnsafeJsonStruct: Struct<Json> = union([\n literal(null),\n boolean(),\n finiteNumber(),\n string(),\n array(lazy(() => UnsafeJsonStruct)),\n record(\n string(),\n lazy(() => UnsafeJsonStruct),\n ),\n]);\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * This struct sanitizes the value before validating it, so that it is safe to\n * use with untrusted input.\n */\nexport const JsonStruct = coerce(UnsafeJsonStruct, any(), (value) => {\n assertStruct(value, UnsafeJsonStruct);\n return JSON.parse(\n JSON.stringify(value, (propKey, propValue) => {\n // Strip __proto__ and constructor properties to prevent prototype pollution.\n if (propKey === '__proto__' || propKey === 'constructor') {\n return undefined;\n }\n return propValue;\n }),\n );\n});\n\n/**\n * Check if the given value is a valid {@link Json} value, i.e., a value that is\n * serializable to JSON.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link Json} value.\n */\nexport function isValidJson(value: unknown): value is Json {\n try {\n getSafeJson(value);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Validate and return sanitized JSON.\n *\n * Note:\n * This function uses sanitized JsonStruct for validation\n * that applies stringify and then parse of a value provided\n * to ensure that there are no getters which can have side effects\n * that can cause security issues.\n *\n * @param value - JSON structure to be processed.\n * @returns Sanitized JSON structure.\n */\nexport function getSafeJson<Type extends Json = Json>(value: unknown): Type {\n return create(value, JsonStruct) as Type;\n}\n\n/**\n * Get the size of a JSON value in bytes. This also validates the value.\n *\n * @param value - The JSON value to get the size of.\n * @returns The size of the JSON value in bytes.\n */\nexport function getJsonSize(value: unknown): number {\n assertStruct(value, JsonStruct, 'Invalid JSON value');\n\n const json = JSON.stringify(value);\n return new TextEncoder().encode(json).byteLength;\n}\n\n/**\n * The string '2.0'.\n */\nexport const jsonrpc2 = '2.0' as const;\nexport const JsonRpcVersionStruct = literal(jsonrpc2);\n\n/**\n * A String specifying the version of the JSON-RPC protocol.\n * MUST be exactly \"2.0\".\n */\nexport type JsonRpcVersion2 = typeof jsonrpc2;\n\nexport const JsonRpcIdStruct = nullable(union([number(), string()]));\n\n/**\n * An identifier established by the Client that MUST contain a String, Number,\n * or NULL value if included. If it is not included it is assumed to be a\n * notification. The value SHOULD normally not be Null and Numbers SHOULD\n * NOT contain fractional parts.\n */\nexport type JsonRpcId = Infer<typeof JsonRpcIdStruct>;\n\nexport const JsonRpcErrorStruct = object({\n code: integer(),\n message: string(),\n data: exactOptional(JsonStruct),\n stack: exactOptional(string()),\n});\n\n/**\n * Mark a certain key of a type as optional.\n */\nexport type OptionalField<\n Type extends Record<string, unknown>,\n Key extends keyof Type,\n> = Omit<Type, Key> & Partial<Pick<Type, Key>>;\n\n/**\n * A JSON-RPC error object.\n *\n * Note that TypeScript infers `unknown | undefined` as `unknown`, meaning that\n * the `data` field is not optional. To make it optional, we use the\n * `OptionalField` helper, to explicitly make it optional.\n */\nexport type JsonRpcError = OptionalField<\n Infer<typeof JsonRpcErrorStruct>,\n 'data'\n>;\n\nexport const JsonRpcParamsStruct: Struct<Json[] | Record<string, Json>, null> =\n union([record(string(), JsonStruct), array(JsonStruct)]);\n\nexport type JsonRpcParams = Json[] | Record<string, Json>;\n\nexport const JsonRpcRequestStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: exactOptional(JsonRpcParamsStruct),\n});\n\nexport type InferWithParams<\n Type extends Struct<any>,\n Params extends JsonRpcParams,\n> = Infer<Type> & {\n params?: Params;\n};\n\n/**\n * A JSON-RPC request object.\n */\nexport type JsonRpcRequest<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcRequestStruct, Params>;\n\nexport const JsonRpcNotificationStruct = object({\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: exactOptional(JsonRpcParamsStruct),\n});\n\n/**\n * A JSON-RPC notification object.\n */\nexport type JsonRpcNotification<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcNotificationStruct, Params>;\n\n/**\n * Check if the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcNotification}\n * object.\n */\nexport function isJsonRpcNotification(\n value: unknown,\n): value is JsonRpcNotification {\n return is(value, JsonRpcNotificationStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcNotification} object.\n */\nexport function assertIsJsonRpcNotification(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcNotification {\n assertStruct(\n value,\n JsonRpcNotificationStruct,\n 'Invalid JSON-RPC notification',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcRequest} object.\n */\nexport function isJsonRpcRequest(value: unknown): value is JsonRpcRequest {\n return is(value, JsonRpcRequestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The JSON-RPC request or notification to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcRequest} object.\n */\nexport function assertIsJsonRpcRequest(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcRequest {\n assertStruct(\n value,\n JsonRpcRequestStruct,\n 'Invalid JSON-RPC request',\n ErrorWrapper,\n );\n}\n\nexport const PendingJsonRpcResponseStruct = superstructObject({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: optional(unknown()),\n error: optional(JsonRpcErrorStruct),\n});\n\n/**\n * A JSON-RPC response object that has not yet been resolved.\n */\nexport type PendingJsonRpcResponse<Result extends Json> = Omit<\n Infer<typeof PendingJsonRpcResponseStruct>,\n 'result'\n> & {\n result?: Result;\n};\n\nexport const JsonRpcSuccessStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: JsonStruct,\n});\n\n/**\n * A successful JSON-RPC response object.\n */\nexport type JsonRpcSuccess<Result extends Json> = Omit<\n Infer<typeof JsonRpcSuccessStruct>,\n 'result'\n> & {\n result: Result;\n};\n\nexport const JsonRpcFailureStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n error: JsonRpcErrorStruct as Struct<JsonRpcError>,\n});\n\n/**\n * A failed JSON-RPC response object.\n */\nexport type JsonRpcFailure = Infer<typeof JsonRpcFailureStruct>;\n\nexport const JsonRpcResponseStruct = union([\n JsonRpcSuccessStruct,\n JsonRpcFailureStruct,\n]);\n\n/**\n * A JSON-RPC response object. Must be checked to determine whether it's a\n * success or failure.\n *\n * @template Result - The type of the result.\n */\nexport type JsonRpcResponse<Result extends Json> =\n | JsonRpcSuccess<Result>\n | JsonRpcFailure;\n\n/**\n * Type guard to check whether specified JSON-RPC response is a\n * {@link PendingJsonRpcResponse}.\n *\n * @param response - The JSON-RPC response to check.\n * @returns Whether the specified JSON-RPC response is pending.\n */\nexport function isPendingJsonRpcResponse(\n response: unknown,\n): response is PendingJsonRpcResponse<Json> {\n return is(response, PendingJsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link PendingJsonRpcResponse} object.\n *\n * @param response - The JSON-RPC response to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link PendingJsonRpcResponse}\n * object.\n */\nexport function assertIsPendingJsonRpcResponse(\n response: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts response is PendingJsonRpcResponse<Json> {\n assertStruct(\n response,\n PendingJsonRpcResponseStruct,\n 'Invalid pending JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Type guard to check if a value is a {@link JsonRpcResponse}.\n *\n * @param response - The object to check.\n * @returns Whether the object is a JsonRpcResponse.\n */\nexport function isJsonRpcResponse(\n response: unknown,\n): response is JsonRpcResponse<Json> {\n return is(response, JsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcResponse} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcResponse} object.\n */\nexport function assertIsJsonRpcResponse(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcResponse<Json> {\n assertStruct(\n value,\n JsonRpcResponseStruct,\n 'Invalid JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcSuccess} object.\n */\nexport function isJsonRpcSuccess(\n value: unknown,\n): value is JsonRpcSuccess<Json> {\n return is(value, JsonRpcSuccessStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcSuccess} object.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcSuccess<Json> {\n assertStruct(\n value,\n JsonRpcSuccessStruct,\n 'Invalid JSON-RPC success response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcFailure} object.\n */\nexport function isJsonRpcFailure(value: unknown): value is JsonRpcFailure {\n return is(value, JsonRpcFailureStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcFailure} object.\n */\nexport function assertIsJsonRpcFailure(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcFailure {\n assertStruct(\n value,\n JsonRpcFailureStruct,\n 'Invalid JSON-RPC failure response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcError} object.\n */\nexport function isJsonRpcError(value: unknown): value is JsonRpcError {\n return is(value, JsonRpcErrorStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcError} object.\n */\nexport function assertIsJsonRpcError(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcError {\n assertStruct(\n value,\n JsonRpcErrorStruct,\n 'Invalid JSON-RPC error',\n ErrorWrapper,\n );\n}\n\ntype JsonRpcValidatorOptions = {\n permitEmptyString?: boolean;\n permitFractions?: boolean;\n permitNull?: boolean;\n};\n\n/**\n * Gets a function for validating JSON-RPC request / response `id` values.\n *\n * By manipulating the options of this factory, you can control the behavior\n * of the resulting validator for some edge cases. This is useful because e.g.\n * `null` should sometimes but not always be permitted.\n *\n * Note that the empty string (`''`) is always permitted by the JSON-RPC\n * specification, but that kind of sucks and you may want to forbid it in some\n * instances anyway.\n *\n * For more details, see the\n * [JSON-RPC Specification](https://www.jsonrpc.org/specification).\n *\n * @param options - An options object.\n * @param options.permitEmptyString - Whether the empty string (i.e. `''`)\n * should be treated as a valid ID. Default: `true`\n * @param options.permitFractions - Whether fractional numbers (e.g. `1.2`)\n * should be treated as valid IDs. Default: `false`\n * @param options.permitNull - Whether `null` should be treated as a valid ID.\n * Default: `true`\n * @returns The JSON-RPC ID validator function.\n */\nexport function getJsonRpcIdValidator(options?: JsonRpcValidatorOptions) {\n const { permitEmptyString, permitFractions, permitNull } = {\n permitEmptyString: true,\n permitFractions: false,\n permitNull: true,\n ...options,\n };\n\n /**\n * Type guard for {@link JsonRpcId}.\n *\n * @param id - The JSON-RPC ID value to check.\n * @returns Whether the given ID is valid per the options given to the\n * factory.\n */\n const isValidJsonRpcId = (id: unknown): id is JsonRpcId => {\n return Boolean(\n (typeof id === 'number' && (permitFractions || Number.isInteger(id))) ||\n (typeof id === 'string' && (permitEmptyString || id.length > 0)) ||\n (permitNull && id === null),\n );\n };\n\n return isValidJsonRpcId;\n}\n"],"mappings":"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","names":[]}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
|
|
2
|
+
|
|
3
|
+
var _chunk6ZDHSOUVjs = require('./chunk-6ZDHSOUV.js');
|
|
4
|
+
|
|
5
|
+
// src/base64.ts
|
|
6
|
+
var _superstruct = require('superstruct');
|
|
7
|
+
var base64 = (struct, options = {}) => {
|
|
8
|
+
const paddingRequired = _nullishCoalesce(options.paddingRequired, () => ( false));
|
|
9
|
+
const characterSet = _nullishCoalesce(options.characterSet, () => ( "base64"));
|
|
10
|
+
let letters;
|
|
11
|
+
if (characterSet === "base64") {
|
|
12
|
+
letters = String.raw`[A-Za-z0-9+\/]`;
|
|
13
|
+
} else {
|
|
14
|
+
_chunk6ZDHSOUVjs.assert.call(void 0, characterSet === "base64url");
|
|
15
|
+
letters = String.raw`[-_A-Za-z0-9]`;
|
|
16
|
+
}
|
|
17
|
+
let re;
|
|
18
|
+
if (paddingRequired) {
|
|
19
|
+
re = new RegExp(
|
|
20
|
+
`^(?:${letters}{4})*(?:${letters}{3}=|${letters}{2}==)?$`,
|
|
21
|
+
"u"
|
|
22
|
+
);
|
|
23
|
+
} else {
|
|
24
|
+
re = new RegExp(
|
|
25
|
+
`^(?:${letters}{4})*(?:${letters}{2,3}|${letters}{3}=|${letters}{2}==)?$`,
|
|
26
|
+
"u"
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
return _superstruct.pattern.call(void 0, struct, re);
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
exports.base64 = base64;
|
|
35
|
+
//# sourceMappingURL=chunk-6NZW4WK4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/base64.ts"],"names":[],"mappings":";;;;;AACA,SAAS,eAAe;AA4BjB,IAAM,SAAS,CACpB,QACA,UAAyB,CAAC,MACvB;AACH,QAAM,kBAAkB,QAAQ,mBAAmB;AACnD,QAAM,eAAe,QAAQ,gBAAgB;AAE7C,MAAI;AACJ,MAAI,iBAAiB,UAAU;AAC7B,cAAU,OAAO;AAAA,EACnB,OAAO;AACL,WAAO,iBAAiB,WAAW;AACnC,cAAU,OAAO;AAAA,EACnB;AAEA,MAAI;AACJ,MAAI,iBAAiB;AACnB,SAAK,IAAI;AAAA,MACP,OAAO,OAAO,WAAW,OAAO,QAAQ,OAAO;AAAA,MAC/C;AAAA,IACF;AAAA,EACF,OAAO;AACL,SAAK,IAAI;AAAA,MACP,OAAO,OAAO,WAAW,OAAO,SAAS,OAAO,QAAQ,OAAO;AAAA,MAC/D;AAAA,IACF;AAAA,EACF;AAEA,SAAO,QAAQ,QAAQ,EAAE;AAC3B","sourcesContent":["import type { Struct } from 'superstruct';\nimport { pattern } from 'superstruct';\n\nimport { assert } from './assert';\n\nexport type Base64Options = {\n /**\n * Is the `=` padding at the end required or not.\n *\n * @default false\n */\n // Padding is optional in RFC 4648, that's why the default value is false\n paddingRequired?: boolean;\n /**\n * Which character set should be used.\n * The sets are based on {@link https://datatracker.ietf.org/doc/html/rfc4648 RFC 4648}.\n *\n * @default 'base64'\n */\n characterSet?: 'base64' | 'base64url';\n};\n\n/**\n * Ensure that a provided string-based struct is valid base64.\n *\n * @param struct - The string based struct.\n * @param options - Optional options to specialize base64 validation. See {@link Base64Options} documentation.\n * @returns A superstruct validating base64.\n */\nexport const base64 = <Type extends string, Schema>(\n struct: Struct<Type, Schema>,\n options: Base64Options = {},\n) => {\n const paddingRequired = options.paddingRequired ?? false;\n const characterSet = options.characterSet ?? 'base64';\n\n let letters: string;\n if (characterSet === 'base64') {\n letters = String.raw`[A-Za-z0-9+\\/]`;\n } else {\n assert(characterSet === 'base64url');\n letters = String.raw`[-_A-Za-z0-9]`;\n }\n\n let re: RegExp;\n if (paddingRequired) {\n re = new RegExp(\n `^(?:${letters}{4})*(?:${letters}{3}=|${letters}{2}==)?$`,\n 'u',\n );\n } else {\n re = new RegExp(\n `^(?:${letters}{4})*(?:${letters}{2,3}|${letters}{3}=|${letters}{2}==)?$`,\n 'u',\n );\n }\n\n return pattern(struct, re);\n};\n"]}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
|
+
|
|
3
|
+
var _chunkIZC266HSjs = require('./chunk-IZC266HS.js');
|
|
4
|
+
|
|
5
|
+
// src/assert.ts
|
|
6
|
+
var _superstruct = require('superstruct');
|
|
7
|
+
function isConstructable(fn) {
|
|
8
|
+
return Boolean(typeof _optionalChain([fn, 'optionalAccess', _ => _.prototype, 'optionalAccess', _2 => _2.constructor, 'optionalAccess', _3 => _3.name]) === "string");
|
|
9
|
+
}
|
|
10
|
+
function getErrorMessageWithoutTrailingPeriod(error) {
|
|
11
|
+
return _chunkIZC266HSjs.getErrorMessage.call(void 0, error).replace(/\.$/u, "");
|
|
12
|
+
}
|
|
13
|
+
function getError(ErrorWrapper, message) {
|
|
14
|
+
if (isConstructable(ErrorWrapper)) {
|
|
15
|
+
return new ErrorWrapper({
|
|
16
|
+
message
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
return ErrorWrapper({
|
|
20
|
+
message
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
var AssertionError = class extends Error {
|
|
24
|
+
constructor(options) {
|
|
25
|
+
super(options.message);
|
|
26
|
+
this.code = "ERR_ASSERTION";
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
function assert(value, message = "Assertion failed.", ErrorWrapper = AssertionError) {
|
|
30
|
+
if (!value) {
|
|
31
|
+
if (message instanceof Error) {
|
|
32
|
+
throw message;
|
|
33
|
+
}
|
|
34
|
+
throw getError(ErrorWrapper, message);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function assertStruct(value, struct, errorPrefix = "Assertion failed", ErrorWrapper = AssertionError) {
|
|
38
|
+
try {
|
|
39
|
+
_superstruct.assert.call(void 0, value, struct);
|
|
40
|
+
} catch (error) {
|
|
41
|
+
throw getError(
|
|
42
|
+
ErrorWrapper,
|
|
43
|
+
`${errorPrefix}: ${getErrorMessageWithoutTrailingPeriod(error)}.`
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function assertExhaustive(_object) {
|
|
48
|
+
throw new Error(
|
|
49
|
+
"Invalid branch reached. Should be detected during compilation."
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
exports.AssertionError = AssertionError; exports.assert = assert; exports.assertStruct = assertStruct; exports.assertExhaustive = assertExhaustive;
|
|
59
|
+
//# sourceMappingURL=chunk-6ZDHSOUV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/assert.ts"],"names":[],"mappings":";;;;;AACA,SAAS,UAAU,yBAAyB;AAe5C,SAAS,gBACP,IACgD;AAEhD,SAAO,QAAQ,OAAO,IAAI,WAAW,aAAa,SAAS,QAAQ;AACrE;AAYA,SAAS,qCAAqC,OAAwB;AAEpE,SAAO,gBAAgB,KAAK,EAAE,QAAQ,QAAQ,EAAE;AAClD;AAUA,SAAS,SAAS,cAAyC,SAAiB;AAC1E,MAAI,gBAAgB,YAAY,GAAG;AACjC,WAAO,IAAI,aAAa;AAAA,MACtB;AAAA,IACF,CAAC;AAAA,EACH;AACA,SAAO,aAAa;AAAA,IAClB;AAAA,EACF,CAAC;AACH;AAKO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAGxC,YAAY,SAA8B;AACxC,UAAM,QAAQ,OAAO;AAHvB,SAAS,OAAO;AAAA,EAIhB;AACF;AAcO,SAAS,OACd,OACA,UAA0B,qBAE1B,eAA0C,gBAC3B;AACf,MAAI,CAAC,OAAO;AACV,QAAI,mBAAmB,OAAO;AAC5B,YAAM;AAAA,IACR;AAEA,UAAM,SAAS,cAAc,OAAO;AAAA,EACtC;AACF;AAaO,SAAS,aACd,OACA,QACA,cAAc,oBAEd,eAA0C,gBACnB;AACvB,MAAI;AACF,sBAAkB,OAAO,MAAM;AAAA,EACjC,SAAS,OAAO;AACd,UAAM;AAAA,MACJ;AAAA,MACA,GAAG,WAAW,KAAK,qCAAqC,KAAK,CAAC;AAAA,IAChE;AAAA,EACF;AACF;AAqBO,SAAS,iBAAiB,SAAuB;AACtD,QAAM,IAAI;AAAA,IACR;AAAA,EACF;AACF","sourcesContent":["import type { Struct } from 'superstruct';\nimport { assert as assertSuperstruct } from 'superstruct';\n\nimport { getErrorMessage } from './errors';\n\nexport type AssertionErrorConstructor =\n | (new (args: { message: string }) => Error)\n | ((args: { message: string }) => Error);\n\n/**\n * Check if a value is a constructor, i.e., a function that can be called with\n * the `new` keyword.\n *\n * @param fn - The value to check.\n * @returns `true` if the value is a constructor, or `false` otherwise.\n */\nfunction isConstructable(\n fn: AssertionErrorConstructor,\n): fn is new (args: { message: string }) => Error {\n /* istanbul ignore next */\n return Boolean(typeof fn?.prototype?.constructor?.name === 'string');\n}\n\n/**\n * Attempts to obtain the message from a possible error object. If it is\n * possible to do so, any trailing period will be removed from the message;\n * otherwise an empty string is returned.\n *\n * @param error - The error object to get the message from.\n * @returns The message without any trailing period if `error` is an object\n * with a `message` property; the string version of `error` without any trailing\n * period if it is not `undefined` or `null`; otherwise an empty string.\n */\nfunction getErrorMessageWithoutTrailingPeriod(error: unknown): string {\n // We'll add our own period.\n return getErrorMessage(error).replace(/\\.$/u, '');\n}\n\n/**\n * Initialise an {@link AssertionErrorConstructor} error.\n *\n * @param ErrorWrapper - The error class to use.\n * @param message - The error message.\n * @returns The error object.\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction getError(ErrorWrapper: AssertionErrorConstructor, message: string) {\n if (isConstructable(ErrorWrapper)) {\n return new ErrorWrapper({\n message,\n });\n }\n return ErrorWrapper({\n message,\n });\n}\n\n/**\n * The default error class that is thrown if an assertion fails.\n */\nexport class AssertionError extends Error {\n readonly code = 'ERR_ASSERTION';\n\n constructor(options: { message: string }) {\n super(options.message);\n }\n}\n\n/**\n * Same as Node.js assert.\n * If the value is falsy, throws an error, does nothing otherwise.\n *\n * @throws {@link AssertionError} If value is falsy.\n * @param value - The test that should be truthy to pass.\n * @param message - Message to be passed to {@link AssertionError} or an\n * {@link Error} instance to throw.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}. If a custom error class is provided for\n * the `message` argument, this argument is ignored.\n */\nexport function assert(\n value: any,\n message: string | Error = 'Assertion failed.',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper: AssertionErrorConstructor = AssertionError,\n): asserts value {\n if (!value) {\n if (message instanceof Error) {\n throw message;\n }\n\n throw getError(ErrorWrapper, message);\n }\n}\n\n/**\n * Assert a value against a Superstruct struct.\n *\n * @param value - The value to validate.\n * @param struct - The struct to validate against.\n * @param errorPrefix - A prefix to add to the error message. Defaults to\n * \"Assertion failed\".\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the value is not valid.\n */\nexport function assertStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n errorPrefix = 'Assertion failed',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper: AssertionErrorConstructor = AssertionError,\n): asserts value is Type {\n try {\n assertSuperstruct(value, struct);\n } catch (error) {\n throw getError(\n ErrorWrapper,\n `${errorPrefix}: ${getErrorMessageWithoutTrailingPeriod(error)}.`,\n );\n }\n}\n\n/**\n * Use in the default case of a switch that you want to be fully exhaustive.\n * Using this function forces the compiler to enforce exhaustivity during\n * compile-time.\n *\n * @example\n * ```\n * const number = 1;\n * switch (number) {\n * case 0:\n * ...\n * case 1:\n * ...\n * default:\n * assertExhaustive(snapPrefix);\n * }\n * ```\n * @param _object - The object on which the switch is being operated.\n */\nexport function assertExhaustive(_object: never): never {\n throw new Error(\n 'Invalid branch reached. Should be detected during compilation.',\n );\n}\n"]}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getErrorMessage
|
|
3
|
+
} from "./chunk-XYGUOY6N.mjs";
|
|
4
|
+
|
|
5
|
+
// src/assert.ts
|
|
6
|
+
import { assert as assertSuperstruct } from "superstruct";
|
|
7
|
+
function isConstructable(fn) {
|
|
8
|
+
return Boolean(typeof fn?.prototype?.constructor?.name === "string");
|
|
9
|
+
}
|
|
10
|
+
function getErrorMessageWithoutTrailingPeriod(error) {
|
|
11
|
+
return getErrorMessage(error).replace(/\.$/u, "");
|
|
12
|
+
}
|
|
13
|
+
function getError(ErrorWrapper, message) {
|
|
14
|
+
if (isConstructable(ErrorWrapper)) {
|
|
15
|
+
return new ErrorWrapper({
|
|
16
|
+
message
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
return ErrorWrapper({
|
|
20
|
+
message
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
var AssertionError = class extends Error {
|
|
24
|
+
constructor(options) {
|
|
25
|
+
super(options.message);
|
|
26
|
+
this.code = "ERR_ASSERTION";
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
function assert(value, message = "Assertion failed.", ErrorWrapper = AssertionError) {
|
|
30
|
+
if (!value) {
|
|
31
|
+
if (message instanceof Error) {
|
|
32
|
+
throw message;
|
|
33
|
+
}
|
|
34
|
+
throw getError(ErrorWrapper, message);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function assertStruct(value, struct, errorPrefix = "Assertion failed", ErrorWrapper = AssertionError) {
|
|
38
|
+
try {
|
|
39
|
+
assertSuperstruct(value, struct);
|
|
40
|
+
} catch (error) {
|
|
41
|
+
throw getError(
|
|
42
|
+
ErrorWrapper,
|
|
43
|
+
`${errorPrefix}: ${getErrorMessageWithoutTrailingPeriod(error)}.`
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function assertExhaustive(_object) {
|
|
48
|
+
throw new Error(
|
|
49
|
+
"Invalid branch reached. Should be detected during compilation."
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export {
|
|
54
|
+
AssertionError,
|
|
55
|
+
assert,
|
|
56
|
+
assertStruct,
|
|
57
|
+
assertExhaustive
|
|
58
|
+
};
|
|
59
|
+
//# sourceMappingURL=chunk-74DGVJVE.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/assert.ts"],"sourcesContent":["import type { Struct } from 'superstruct';\nimport { assert as assertSuperstruct } from 'superstruct';\n\nimport { getErrorMessage } from './errors';\n\nexport type AssertionErrorConstructor =\n | (new (args: { message: string }) => Error)\n | ((args: { message: string }) => Error);\n\n/**\n * Check if a value is a constructor, i.e., a function that can be called with\n * the `new` keyword.\n *\n * @param fn - The value to check.\n * @returns `true` if the value is a constructor, or `false` otherwise.\n */\nfunction isConstructable(\n fn: AssertionErrorConstructor,\n): fn is new (args: { message: string }) => Error {\n /* istanbul ignore next */\n return Boolean(typeof fn?.prototype?.constructor?.name === 'string');\n}\n\n/**\n * Attempts to obtain the message from a possible error object. If it is\n * possible to do so, any trailing period will be removed from the message;\n * otherwise an empty string is returned.\n *\n * @param error - The error object to get the message from.\n * @returns The message without any trailing period if `error` is an object\n * with a `message` property; the string version of `error` without any trailing\n * period if it is not `undefined` or `null`; otherwise an empty string.\n */\nfunction getErrorMessageWithoutTrailingPeriod(error: unknown): string {\n // We'll add our own period.\n return getErrorMessage(error).replace(/\\.$/u, '');\n}\n\n/**\n * Initialise an {@link AssertionErrorConstructor} error.\n *\n * @param ErrorWrapper - The error class to use.\n * @param message - The error message.\n * @returns The error object.\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction getError(ErrorWrapper: AssertionErrorConstructor, message: string) {\n if (isConstructable(ErrorWrapper)) {\n return new ErrorWrapper({\n message,\n });\n }\n return ErrorWrapper({\n message,\n });\n}\n\n/**\n * The default error class that is thrown if an assertion fails.\n */\nexport class AssertionError extends Error {\n readonly code = 'ERR_ASSERTION';\n\n constructor(options: { message: string }) {\n super(options.message);\n }\n}\n\n/**\n * Same as Node.js assert.\n * If the value is falsy, throws an error, does nothing otherwise.\n *\n * @throws {@link AssertionError} If value is falsy.\n * @param value - The test that should be truthy to pass.\n * @param message - Message to be passed to {@link AssertionError} or an\n * {@link Error} instance to throw.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}. If a custom error class is provided for\n * the `message` argument, this argument is ignored.\n */\nexport function assert(\n value: any,\n message: string | Error = 'Assertion failed.',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper: AssertionErrorConstructor = AssertionError,\n): asserts value {\n if (!value) {\n if (message instanceof Error) {\n throw message;\n }\n\n throw getError(ErrorWrapper, message);\n }\n}\n\n/**\n * Assert a value against a Superstruct struct.\n *\n * @param value - The value to validate.\n * @param struct - The struct to validate against.\n * @param errorPrefix - A prefix to add to the error message. Defaults to\n * \"Assertion failed\".\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the value is not valid.\n */\nexport function assertStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n errorPrefix = 'Assertion failed',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper: AssertionErrorConstructor = AssertionError,\n): asserts value is Type {\n try {\n assertSuperstruct(value, struct);\n } catch (error) {\n throw getError(\n ErrorWrapper,\n `${errorPrefix}: ${getErrorMessageWithoutTrailingPeriod(error)}.`,\n );\n }\n}\n\n/**\n * Use in the default case of a switch that you want to be fully exhaustive.\n * Using this function forces the compiler to enforce exhaustivity during\n * compile-time.\n *\n * @example\n * ```\n * const number = 1;\n * switch (number) {\n * case 0:\n * ...\n * case 1:\n * ...\n * default:\n * assertExhaustive(snapPrefix);\n * }\n * ```\n * @param _object - The object on which the switch is being operated.\n */\nexport function assertExhaustive(_object: never): never {\n throw new Error(\n 'Invalid branch reached. Should be detected during compilation.',\n );\n}\n"],"mappings":";;;;;AACA,SAAS,UAAU,yBAAyB;AAe5C,SAAS,gBACP,IACgD;AAEhD,SAAO,QAAQ,OAAO,IAAI,WAAW,aAAa,SAAS,QAAQ;AACrE;AAYA,SAAS,qCAAqC,OAAwB;AAEpE,SAAO,gBAAgB,KAAK,EAAE,QAAQ,QAAQ,EAAE;AAClD;AAUA,SAAS,SAAS,cAAyC,SAAiB;AAC1E,MAAI,gBAAgB,YAAY,GAAG;AACjC,WAAO,IAAI,aAAa;AAAA,MACtB;AAAA,IACF,CAAC;AAAA,EACH;AACA,SAAO,aAAa;AAAA,IAClB;AAAA,EACF,CAAC;AACH;AAKO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAGxC,YAAY,SAA8B;AACxC,UAAM,QAAQ,OAAO;AAHvB,SAAS,OAAO;AAAA,EAIhB;AACF;AAcO,SAAS,OACd,OACA,UAA0B,qBAE1B,eAA0C,gBAC3B;AACf,MAAI,CAAC,OAAO;AACV,QAAI,mBAAmB,OAAO;AAC5B,YAAM;AAAA,IACR;AAEA,UAAM,SAAS,cAAc,OAAO;AAAA,EACtC;AACF;AAaO,SAAS,aACd,OACA,QACA,cAAc,oBAEd,eAA0C,gBACnB;AACvB,MAAI;AACF,sBAAkB,OAAO,MAAM;AAAA,EACjC,SAAS,OAAO;AACd,UAAM;AAAA,MACJ;AAAA,MACA,GAAG,WAAW,KAAK,qCAAqC,KAAK,CAAC;AAAA,IAChE;AAAA,EACF;AACF;AAqBO,SAAS,iBAAiB,SAAuB;AACtD,QAAM,IAAI;AAAA,IACR;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=chunk-AY6FDCBT.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
var _chunkIZC266HSjs = require('./chunk-IZC266HS.js');
|
|
5
|
+
|
|
6
|
+
// src/fs.ts
|
|
7
|
+
var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
|
|
8
|
+
var _os = require('os'); var _os2 = _interopRequireDefault(_os);
|
|
9
|
+
var _path = require('path'); var _path2 = _interopRequireDefault(_path);
|
|
10
|
+
async function readFile(filePath) {
|
|
11
|
+
try {
|
|
12
|
+
return await _fs2.default.promises.readFile(filePath, "utf8");
|
|
13
|
+
} catch (error) {
|
|
14
|
+
throw _chunkIZC266HSjs.wrapError.call(void 0, error, `Could not read file '${filePath}'`);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
async function writeFile(filePath, content) {
|
|
18
|
+
try {
|
|
19
|
+
await _fs2.default.promises.mkdir(_path2.default.dirname(filePath), { recursive: true });
|
|
20
|
+
await _fs2.default.promises.writeFile(filePath, content);
|
|
21
|
+
} catch (error) {
|
|
22
|
+
throw _chunkIZC266HSjs.wrapError.call(void 0, error, `Could not write file '${filePath}'`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
async function readJsonFile(filePath, {
|
|
26
|
+
parser = JSON
|
|
27
|
+
} = {}) {
|
|
28
|
+
try {
|
|
29
|
+
const content = await _fs2.default.promises.readFile(filePath, "utf8");
|
|
30
|
+
return parser.parse(content);
|
|
31
|
+
} catch (error) {
|
|
32
|
+
throw _chunkIZC266HSjs.wrapError.call(void 0, error, `Could not read JSON file '${filePath}'`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
async function writeJsonFile(filePath, jsonValue, {
|
|
36
|
+
stringifier = JSON,
|
|
37
|
+
prettify = false
|
|
38
|
+
} = {}) {
|
|
39
|
+
try {
|
|
40
|
+
await _fs2.default.promises.mkdir(_path2.default.dirname(filePath), { recursive: true });
|
|
41
|
+
const json = prettify ? stringifier.stringify(jsonValue, null, " ") : stringifier.stringify(jsonValue);
|
|
42
|
+
await _fs2.default.promises.writeFile(filePath, json);
|
|
43
|
+
} catch (error) {
|
|
44
|
+
throw _chunkIZC266HSjs.wrapError.call(void 0, error, `Could not write JSON file '${filePath}'`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
async function fileExists(filePath) {
|
|
48
|
+
try {
|
|
49
|
+
const stats = await _fs2.default.promises.stat(filePath);
|
|
50
|
+
return stats.isFile();
|
|
51
|
+
} catch (error) {
|
|
52
|
+
if (_chunkIZC266HSjs.isErrorWithCode.call(void 0, error) && error.code === "ENOENT") {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
throw _chunkIZC266HSjs.wrapError.call(void 0, error, `Could not determine if file exists '${filePath}'`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
async function directoryExists(directoryPath) {
|
|
59
|
+
try {
|
|
60
|
+
const stats = await _fs2.default.promises.stat(directoryPath);
|
|
61
|
+
return stats.isDirectory();
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (_chunkIZC266HSjs.isErrorWithCode.call(void 0, error) && error.code === "ENOENT") {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
throw _chunkIZC266HSjs.wrapError.call(void 0,
|
|
67
|
+
error,
|
|
68
|
+
`Could not determine if directory exists '${directoryPath}'`
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async function ensureDirectoryStructureExists(directoryPath) {
|
|
73
|
+
try {
|
|
74
|
+
await _fs2.default.promises.mkdir(directoryPath, { recursive: true });
|
|
75
|
+
} catch (error) {
|
|
76
|
+
throw _chunkIZC266HSjs.wrapError.call(void 0,
|
|
77
|
+
error,
|
|
78
|
+
`Could not create directory structure '${directoryPath}'`
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async function forceRemove(entryPath) {
|
|
83
|
+
try {
|
|
84
|
+
return await _fs2.default.promises.rm(entryPath, {
|
|
85
|
+
recursive: true,
|
|
86
|
+
force: true
|
|
87
|
+
});
|
|
88
|
+
} catch (error) {
|
|
89
|
+
throw _chunkIZC266HSjs.wrapError.call(void 0, error, `Could not remove file or directory '${entryPath}'`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function createSandbox(projectName) {
|
|
93
|
+
const timestamp = (/* @__PURE__ */ new Date()).getTime();
|
|
94
|
+
const directoryPath = _path2.default.join(_os2.default.tmpdir(), `${projectName}--${timestamp}`);
|
|
95
|
+
return {
|
|
96
|
+
directoryPath,
|
|
97
|
+
async withinSandbox(test) {
|
|
98
|
+
if (await directoryExists(directoryPath)) {
|
|
99
|
+
throw new Error(`${directoryPath} already exists. Cannot continue.`);
|
|
100
|
+
}
|
|
101
|
+
await ensureDirectoryStructureExists(directoryPath);
|
|
102
|
+
try {
|
|
103
|
+
await test({ directoryPath });
|
|
104
|
+
} finally {
|
|
105
|
+
await forceRemove(directoryPath);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
exports.readFile = readFile; exports.writeFile = writeFile; exports.readJsonFile = readJsonFile; exports.writeJsonFile = writeJsonFile; exports.fileExists = fileExists; exports.directoryExists = directoryExists; exports.ensureDirectoryStructureExists = ensureDirectoryStructureExists; exports.forceRemove = forceRemove; exports.createSandbox = createSandbox;
|
|
122
|
+
//# sourceMappingURL=chunk-BFQDMI3M.js.map
|