@metamask/snaps-cli 0.14.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +5 -2
  2. package/dist/builders.d.ts +6 -0
  3. package/dist/builders.js +20 -1
  4. package/dist/builders.js.map +1 -1
  5. package/dist/cli.d.ts +7 -0
  6. package/dist/cli.js +8 -0
  7. package/dist/cli.js.map +1 -1
  8. package/dist/cmds/build/buildHandler.d.ts +4 -4
  9. package/dist/cmds/build/buildHandler.js +4 -4
  10. package/dist/cmds/build/buildHandler.js.map +1 -1
  11. package/dist/cmds/build/bundle.d.ts +4 -2
  12. package/dist/cmds/build/bundle.js +13 -4
  13. package/dist/cmds/build/bundle.js.map +1 -1
  14. package/dist/cmds/build/utils.d.ts +21 -8
  15. package/dist/cmds/build/utils.js +21 -8
  16. package/dist/cmds/build/utils.js.map +1 -1
  17. package/dist/cmds/eval/eval-worker.js +19 -9
  18. package/dist/cmds/eval/eval-worker.js.map +1 -1
  19. package/dist/cmds/eval/evalHandler.d.ts +7 -0
  20. package/dist/cmds/eval/evalHandler.js +7 -0
  21. package/dist/cmds/eval/evalHandler.js.map +1 -1
  22. package/dist/cmds/eval/mock.d.ts +11 -0
  23. package/dist/cmds/eval/mock.js +36 -1
  24. package/dist/cmds/eval/mock.js.map +1 -1
  25. package/dist/cmds/eval/workerEval.d.ts +7 -0
  26. package/dist/cmds/eval/workerEval.js +11 -6
  27. package/dist/cmds/eval/workerEval.js.map +1 -1
  28. package/dist/cmds/index.d.ts +1 -0
  29. package/dist/cmds/init/index.js +13 -1
  30. package/dist/cmds/init/index.js.map +1 -1
  31. package/dist/cmds/init/init-template.json +5 -1
  32. package/dist/cmds/init/initHandler.d.ts +11 -0
  33. package/dist/cmds/init/initHandler.js +38 -3
  34. package/dist/cmds/init/initHandler.js.map +1 -1
  35. package/dist/cmds/init/initUtils.d.ts +21 -4
  36. package/dist/cmds/init/initUtils.js +55 -7
  37. package/dist/cmds/init/initUtils.js.map +1 -1
  38. package/dist/cmds/manifest/manifestHandler.d.ts +1 -0
  39. package/dist/cmds/manifest/manifestHandler.js +6 -0
  40. package/dist/cmds/manifest/manifestHandler.js.map +1 -1
  41. package/dist/cmds/serve/index.js +2 -44
  42. package/dist/cmds/serve/index.js.map +1 -1
  43. package/dist/cmds/serve/serveHandler.d.ts +10 -0
  44. package/dist/cmds/serve/serveHandler.js +51 -0
  45. package/dist/cmds/serve/serveHandler.js.map +1 -0
  46. package/dist/cmds/serve/serveUtils.d.ts +17 -0
  47. package/dist/cmds/serve/serveUtils.js +17 -0
  48. package/dist/cmds/serve/serveUtils.js.map +1 -1
  49. package/dist/cmds/watch/index.js +3 -0
  50. package/dist/cmds/watch/index.js.map +1 -1
  51. package/dist/cmds/watch/watchHandler.d.ts +4 -4
  52. package/dist/cmds/watch/watchHandler.js +12 -6
  53. package/dist/cmds/watch/watchHandler.js.map +1 -1
  54. package/dist/utils/fs.d.ts +5 -5
  55. package/dist/utils/fs.js +5 -5
  56. package/dist/utils/fs.js.map +1 -1
  57. package/dist/utils/misc.d.ts +16 -13
  58. package/dist/utils/misc.js +19 -15
  59. package/dist/utils/misc.js.map +1 -1
  60. package/dist/utils/readline.d.ts +25 -0
  61. package/dist/utils/readline.js +25 -0
  62. package/dist/utils/readline.js.map +1 -1
  63. package/dist/utils/snap-config.d.ts +15 -0
  64. package/dist/utils/snap-config.js +18 -4
  65. package/dist/utils/snap-config.js.map +1 -1
  66. package/dist/utils/validate-fs.d.ts +19 -18
  67. package/dist/utils/validate-fs.js +21 -20
  68. package/dist/utils/validate-fs.js.map +1 -1
  69. package/package.json +20 -19
  70. package/CHANGELOG.md +0 -209
@@ -6,6 +6,7 @@ import { YargsArgs } from '../../types/yargs';
6
6
  * fails.
7
7
  *
8
8
  * @param argv - The Yargs `argv` object.
9
+ * @param argv.writeManifest - Whether to write the fixed manifest to disk.
9
10
  */
10
11
  export declare function manifestHandler({ writeManifest, }: YargsArgs): Promise<void>;
11
12
  /**
@@ -20,6 +20,7 @@ const ManifestSortOrder = {
20
20
  * fails.
21
21
  *
22
22
  * @param argv - The Yargs `argv` object.
23
+ * @param argv.writeManifest - Whether to write the fixed manifest to disk.
23
24
  */
24
25
  async function manifestHandler({ writeManifest, }) {
25
26
  let didUpdate = false;
@@ -96,6 +97,11 @@ async function manifestHandler({ writeManifest, }) {
96
97
  else {
97
98
  console.log(`Manifest Success: Validated snap.manifest.json!`);
98
99
  }
100
+ /**
101
+ * Logs a manifest warning, if `suppressWarnings` is not enabled.
102
+ *
103
+ * @param message - The message to log.
104
+ */
99
105
  function logManifestWarning(message) {
100
106
  if (!global.snaps.suppressWarnings) {
101
107
  hasWarnings = true;
@@ -1 +1 @@
1
- {"version":3,"file":"manifestHandler.js","sourceRoot":"","sources":["../../../src/cmds/manifest/manifestHandler.ts"],"names":[],"mappings":";;;AAAA,2BAAoC;AAEpC,uEASqD;AACrD,uCAAsD;AAGtD,MAAM,WAAW,GAAG,kBAAkB,CAAC;AAEvC,MAAM,iBAAiB,GAAuC;IAC5D,OAAO,EAAE,CAAC;IACV,YAAY,EAAE,CAAC;IACf,WAAW,EAAE,CAAC;IACd,UAAU,EAAE,CAAC;IACb,MAAM,EAAE,CAAC;IACT,kBAAkB,EAAE,CAAC;IACrB,eAAe,EAAE,CAAC;CACnB,CAAC;AAEF;;;;;;GAMG;AACI,KAAK,UAAU,eAAe,CAAC,EACpC,aAAa,GACH;IACV,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,IAAI,WAAW,GAAG,KAAK,CAAC;IAExB,MAAM,mBAAmB,GAAG,MAAM,gBAAgB,CAAC,wBAAgB,CAAC,QAAQ,CAAC,CAAC;IAE9E,MAAM,QAAQ,GACZ,mBAAmB,IAAI,OAAO,mBAAmB,KAAK,QAAQ;QAC5D,CAAC,CAAE,mBAA6C,CAAC,MAAM,EAAE,QAAQ,EAAE,GAAG;YAClE,EAAE,QAAQ;QACd,CAAC,CAAC,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,CAAC;SAC3D,MAAM,CAAC,CAAC,WAAW,EAAE,GAAG,EAAE,EAAE;QAC1B,WAAmB,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;QAC1C,OAAO,WAAW,CAAC;IACrB,CAAC,EAAE,EAAkB,CAAC,CAAC;AAC3B,CAAC;AAZD,kDAYC","sourcesContent":["import { promises as fs } from 'fs';\nimport type { Json, SnapManifest } from '@metamask/snap-controllers';\nimport {\n NpmSnapFileNames,\n UnvalidatedSnapFiles,\n validateNpmSnap,\n validateNpmSnapManifest,\n getSnapSourceShasum,\n ProgrammaticallyFixableSnapError,\n SnapValidationFailureReason,\n SnapFiles,\n} from '@metamask/snap-controllers/dist/snaps/utils';\nimport { deepClone, readJsonFile } from '../../utils';\nimport { YargsArgs } from '../../types/yargs';\n\nconst errorPrefix = 'Manifest Error: ';\n\nconst ManifestSortOrder: Record<keyof SnapManifest, number> = {\n version: 1,\n proposedName: 2,\n description: 2,\n repository: 3,\n source: 4,\n initialPermissions: 5,\n manifestVersion: 6,\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 argv - The Yargs `argv` object.\n */\nexport async function manifestHandler({\n writeManifest,\n}: YargsArgs): Promise<void> {\n let didUpdate = false;\n let hasWarnings = false;\n\n const unvalidatedManifest = await readSnapJsonFile(NpmSnapFileNames.Manifest);\n\n const iconPath =\n unvalidatedManifest && typeof unvalidatedManifest === 'object'\n ? (unvalidatedManifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath\n : undefined;\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: unvalidatedManifest,\n packageJson: await readSnapJsonFile(NpmSnapFileNames.PackageJson),\n sourceCode: await getSnapSourceCode(unvalidatedManifest),\n svgIcon: iconPath && (await fs.readFile(iconPath, 'utf8')),\n };\n\n let manifest: SnapManifest | undefined;\n try {\n ({ manifest } = validateNpmSnap(snapFiles, errorPrefix));\n } catch (error) {\n if (writeManifest && error instanceof ProgrammaticallyFixableSnapError) {\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 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 for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = fixManifest(partiallyValidatedFiles, error);\n\n try {\n validateNpmSnapManifest(\n { ...partiallyValidatedFiles, manifest },\n errorPrefix,\n );\n\n isInvalid = false;\n } catch (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 }\n\n didUpdate = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript doesn't see that the 'manifest' variable must be of type\n // SnapManifest at this point, so we cast it.\n const validatedManifest = manifest as SnapManifest;\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 logManifestWarning(\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 // Validation complete, finish work and notify user.\n\n if (writeManifest) {\n try {\n await fs.writeFile(\n NpmSnapFileNames.Manifest,\n `${JSON.stringify(getWritableManifest(validatedManifest), null, 2)}\\n`,\n );\n\n if (didUpdate) {\n console.log(`Manifest: Updated snap.manifest.json`);\n }\n } catch (error) {\n throw new Error(\n `${errorPrefix}Failed to update snap.manifest.json: ${error.message}`,\n );\n }\n }\n\n if (hasWarnings) {\n console.log(\n `Manifest Warning: Validation of snap.manifest.json completed with warnings. See above.`,\n );\n } else {\n console.log(`Manifest Success: Validated snap.manifest.json!`);\n }\n\n function logManifestWarning(message: string) {\n if (!global.snaps.suppressWarnings) {\n hasWarnings = true;\n console.warn(`Manifest Warning: ${message}`);\n }\n }\n}\n\n/**\n * Utility function for reading `package.json` or the Snap manifest file.\n * These are assumed to be in the current working directory.\n *\n * @param snapJsonFileName - The name of the file to read.\n * @returns The parsed JSON file.\n */\nasync function readSnapJsonFile(\n snapJsonFileName: NpmSnapFileNames,\n): Promise<Json> {\n try {\n return await readJsonFile(snapJsonFileName);\n } catch (error) {\n if (error.code === 'ENOENT') {\n throw new Error(\n `${errorPrefix}Could not find '${snapJsonFileName}'. Please ensure that ` +\n `you are running the command in the project root directory.`,\n );\n }\n throw new Error(`${errorPrefix}${error.message}`);\n }\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 manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the bundle file, if any.\n */\nasync function getSnapSourceCode(manifest: Json): Promise<string | undefined> {\n if (manifest && typeof manifest === 'object' && !Array.isArray(manifest)) {\n /* istanbul ignore next: optional chaining */\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n try {\n return sourceFilePath\n ? await fs.readFile(sourceFilePath, 'utf8')\n : undefined;\n } catch (error) {\n throw new Error(\n `Manifest Error: Failed to read Snap bundle file: ${error.message}`,\n );\n }\n }\n return undefined;\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 */\nfunction fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): SnapManifest {\n const { manifest, packageJson, sourceCode } = snapFiles;\n const manifestCopy = deepClone(manifest);\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.repository\n ? deepClone(packageJson.repository)\n : null;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapSourceShasum(sourceCode);\n break;\n\n /* istanbul ignore next */\n default:\n // eslint-disable-next-line no-case-declarations\n const failureReason: never = error.reason;\n throw new Error(\n `Unrecognized validation failure reason: '${failureReason}'`,\n );\n }\n\n return manifestCopy;\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 return (\n Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[]\n )\n .sort((a, b) => ManifestSortOrder[a] - ManifestSortOrder[b])\n .reduce((outManifest, key) => {\n (outManifest as any)[key] = manifest[key];\n return outManifest;\n }, {} as SnapManifest);\n}\n"]}
1
+ {"version":3,"file":"manifestHandler.js","sourceRoot":"","sources":["../../../src/cmds/manifest/manifestHandler.ts"],"names":[],"mappings":";;;AAAA,2BAAoC;AAEpC,uEASqD;AACrD,uCAAsD;AAGtD,MAAM,WAAW,GAAG,kBAAkB,CAAC;AAEvC,MAAM,iBAAiB,GAAuC;IAC5D,OAAO,EAAE,CAAC;IACV,YAAY,EAAE,CAAC;IACf,WAAW,EAAE,CAAC;IACd,UAAU,EAAE,CAAC;IACb,MAAM,EAAE,CAAC;IACT,kBAAkB,EAAE,CAAC;IACrB,eAAe,EAAE,CAAC;CACnB,CAAC;AAEF;;;;;;;GAOG;AACI,KAAK,UAAU,eAAe,CAAC,EACp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GAMG;AACH,SAAgB,mBAAmB,CAAC,QAAsB;IACxD,MAAM,EAAE,UAAU,EAAE,GAAG,SAAS,EAAE,GAAG,QAAQ,CAAC;IAC9C,OACE,MAAM,CAAC,IAAI,CACT,UAAU,CAAC,CAAC,CAAC,EAAE,GAAG,SAAS,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,SAAS,CAExD;SACE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,iBAAiB,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAAC;SAC3D,MAAM,CAAC,CAAC,WAAW,EAAE,GAAG,EAAE,EAAE;QAC1B,WAAmB,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;QAC1C,OAAO,WAAW,CAAC;IACrB,CAAC,EAAE,EAAkB,CAAC,CAAC;AAC3B,CAAC;AAZD,kDAYC","sourcesContent":["import { promises as fs } from 'fs';\nimport type { Json, SnapManifest } from '@metamask/snap-controllers';\nimport {\n NpmSnapFileNames,\n UnvalidatedSnapFiles,\n validateNpmSnap,\n validateNpmSnapManifest,\n getSnapSourceShasum,\n ProgrammaticallyFixableSnapError,\n SnapValidationFailureReason,\n SnapFiles,\n} from '@metamask/snap-controllers/dist/snaps/utils';\nimport { deepClone, readJsonFile } from '../../utils';\nimport { YargsArgs } from '../../types/yargs';\n\nconst errorPrefix = 'Manifest Error: ';\n\nconst ManifestSortOrder: Record<keyof SnapManifest, number> = {\n version: 1,\n proposedName: 2,\n description: 2,\n repository: 3,\n source: 4,\n initialPermissions: 5,\n manifestVersion: 6,\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 argv - The Yargs `argv` object.\n * @param argv.writeManifest - Whether to write the fixed manifest to disk.\n */\nexport async function manifestHandler({\n writeManifest,\n}: YargsArgs): Promise<void> {\n let didUpdate = false;\n let hasWarnings = false;\n\n const unvalidatedManifest = await readSnapJsonFile(NpmSnapFileNames.Manifest);\n\n const iconPath =\n unvalidatedManifest && typeof unvalidatedManifest === 'object'\n ? (unvalidatedManifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath\n : undefined;\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: unvalidatedManifest,\n packageJson: await readSnapJsonFile(NpmSnapFileNames.PackageJson),\n sourceCode: await getSnapSourceCode(unvalidatedManifest),\n svgIcon: iconPath && (await fs.readFile(iconPath, 'utf8')),\n };\n\n let manifest: SnapManifest | undefined;\n try {\n ({ manifest } = validateNpmSnap(snapFiles, errorPrefix));\n } catch (error) {\n if (writeManifest && error instanceof ProgrammaticallyFixableSnapError) {\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 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 for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = fixManifest(partiallyValidatedFiles, error);\n\n try {\n validateNpmSnapManifest(\n { ...partiallyValidatedFiles, manifest },\n errorPrefix,\n );\n\n isInvalid = false;\n } catch (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 }\n\n didUpdate = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript doesn't see that the 'manifest' variable must be of type\n // SnapManifest at this point, so we cast it.\n const validatedManifest = manifest as SnapManifest;\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 logManifestWarning(\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 // Validation complete, finish work and notify user.\n\n if (writeManifest) {\n try {\n await fs.writeFile(\n NpmSnapFileNames.Manifest,\n `${JSON.stringify(getWritableManifest(validatedManifest), null, 2)}\\n`,\n );\n\n if (didUpdate) {\n console.log(`Manifest: Updated snap.manifest.json`);\n }\n } catch (error) {\n throw new Error(\n `${errorPrefix}Failed to update snap.manifest.json: ${error.message}`,\n );\n }\n }\n\n if (hasWarnings) {\n console.log(\n `Manifest Warning: Validation of snap.manifest.json completed with warnings. See above.`,\n );\n } else {\n console.log(`Manifest Success: Validated snap.manifest.json!`);\n }\n\n /**\n * Logs a manifest warning, if `suppressWarnings` is not enabled.\n *\n * @param message - The message to log.\n */\n function logManifestWarning(message: string) {\n if (!global.snaps.suppressWarnings) {\n hasWarnings = true;\n console.warn(`Manifest Warning: ${message}`);\n }\n }\n}\n\n/**\n * Utility function for reading `package.json` or the Snap manifest file.\n * These are assumed to be in the current working directory.\n *\n * @param snapJsonFileName - The name of the file to read.\n * @returns The parsed JSON file.\n */\nasync function readSnapJsonFile(\n snapJsonFileName: NpmSnapFileNames,\n): Promise<Json> {\n try {\n return await readJsonFile(snapJsonFileName);\n } catch (error) {\n if (error.code === 'ENOENT') {\n throw new Error(\n `${errorPrefix}Could not find '${snapJsonFileName}'. Please ensure that ` +\n `you are running the command in the project root directory.`,\n );\n }\n throw new Error(`${errorPrefix}${error.message}`);\n }\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 manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the bundle file, if any.\n */\nasync function getSnapSourceCode(manifest: Json): Promise<string | undefined> {\n if (manifest && typeof manifest === 'object' && !Array.isArray(manifest)) {\n /* istanbul ignore next: optional chaining */\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n try {\n return sourceFilePath\n ? await fs.readFile(sourceFilePath, 'utf8')\n : undefined;\n } catch (error) {\n throw new Error(\n `Manifest Error: Failed to read Snap bundle file: ${error.message}`,\n );\n }\n }\n return undefined;\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 */\nfunction fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): SnapManifest {\n const { manifest, packageJson, sourceCode } = snapFiles;\n const manifestCopy = deepClone(manifest);\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.repository\n ? deepClone(packageJson.repository)\n : null;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapSourceShasum(sourceCode);\n break;\n\n /* istanbul ignore next */\n default:\n // eslint-disable-next-line no-case-declarations\n const failureReason: never = error.reason;\n throw new Error(\n `Unrecognized validation failure reason: '${failureReason}'`,\n );\n }\n\n return manifestCopy;\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 return (\n Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[]\n )\n .sort((a, b) => ManifestSortOrder[a] - ManifestSortOrder[b])\n .reduce((outManifest, key) => {\n (outManifest as any)[key] = manifest[key];\n return outManifest;\n }, {} as SnapManifest);\n}\n"]}
@@ -2,56 +2,14 @@
2
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
- const http_1 = __importDefault(require("http"));
6
- const serve_handler_1 = __importDefault(require("serve-handler"));
7
5
  const builders_1 = __importDefault(require("../../builders"));
8
- const utils_1 = require("../../utils");
9
- const serveUtils_1 = require("./serveUtils");
10
- /**
11
- * Starts a local, static HTTP server on the given port with the given root
12
- * directory.
13
- *
14
- * @param argv - arguments as an object generated by yargs
15
- * @param argv.root - The root directory path string
16
- * @param argv.port - The server port
17
- */
18
- async function serve(argv) {
19
- const { port, root: rootDir } = argv;
20
- await (0, utils_1.validateDirPath)(rootDir, true);
21
- console.log(`\nStarting server...`);
22
- const server = http_1.default.createServer(async (req, res) => {
23
- await (0, serve_handler_1.default)(req, res, {
24
- public: rootDir,
25
- headers: [
26
- {
27
- source: '**/*',
28
- headers: [
29
- {
30
- key: 'Cache-Control',
31
- value: 'no-cache',
32
- },
33
- ],
34
- },
35
- ],
36
- });
37
- });
38
- server.listen({ port }, () => (0, serveUtils_1.logServerListening)(port));
39
- server.on('request', (request) => (0, serveUtils_1.logRequest)(request));
40
- server.on('error', (error) => {
41
- (0, serveUtils_1.logServerError)(error, argv.port);
42
- process.exitCode = 1;
43
- });
44
- server.on('close', () => {
45
- console.log('Server closed');
46
- process.exitCode = 1;
47
- });
48
- }
6
+ const serveHandler_1 = require("./serveHandler");
49
7
  module.exports = {
50
8
  command: ['serve', 's'],
51
9
  desc: 'Locally serve Snap file(s) for testing',
52
10
  builder: (yarg) => {
53
11
  yarg.option('root', builders_1.default.root).option('port', builders_1.default.port);
54
12
  },
55
- handler: (argv) => serve(argv),
13
+ handler: (argv) => (0, serveHandler_1.serve)(argv),
56
14
  };
57
15
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/serve/index.ts"],"names":[],"mappings":";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AAC,QAAQ,GAAG,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;AACL,CAAC;AAtDD,iBAAS;IACP,OAAO,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC;IACvB,IAAI,EAAE,wCAAwC;IAC9C,OAAO,EAAE,CAAC,IAAgB,EAAE,EAAE;QAC5B,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC,CAAC;IACnE,CAAC;IACD,OAAO,EAAE,CAAC,IAAe,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC;CAC1C,CAAC","sourcesContent":["import http from 'http';\nimport serveHandler from 'serve-handler';\nimport yargs from 'yargs';\nimport builders from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { validateDirPath } from '../../utils';\nimport { logRequest, logServerError, logServerListening } from './serveUtils';\n\nexport = {\n command: ['serve', 's'],\n desc: 'Locally serve Snap file(s) for testing',\n builder: (yarg: yargs.Argv) => {\n yarg.option('root', builders.root).option('port', builders.port);\n },\n handler: (argv: YargsArgs) => serve(argv),\n};\n\n/**\n * Starts a local, static HTTP server on the given port with the given root\n * directory.\n *\n * @param argv - arguments as an object generated by yargs\n * @param argv.root - The root directory path string\n * @param argv.port - The server port\n */\nasync function serve(argv: YargsArgs): Promise<void> {\n const { port, root: rootDir } = argv;\n\n await validateDirPath(rootDir as string, true);\n\n console.log(`\\nStarting server...`);\n\n const server = http.createServer(async (req, res) => {\n await serveHandler(req, res, {\n public: rootDir as string,\n headers: [\n {\n source: '**/*',\n headers: [\n {\n key: 'Cache-Control',\n value: 'no-cache',\n },\n ],\n },\n ],\n });\n });\n\n server.listen({ port }, () => logServerListening(port));\n\n server.on('request', (request) => logRequest(request));\n\n server.on('error', (error) => {\n logServerError(error, argv.port);\n process.exitCode = 1;\n });\n\n server.on('close', () => {\n console.log('Server closed');\n process.exitCode = 1;\n });\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/serve/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AAEtC,iDAAuC;AAEvC,iBAAS;IACP,OAAO,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC;IACvB,IAAI,EAAE,wCAAwC;IAC9C,OAAO,EAAE,CAAC,IAAgB,EAAE,EAAE;QAC5B,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC,CAAC;IACnE,CAAC;IACD,OAAO,EAAE,CAAC,IAAe,EAAE,EAAE,CAAC,IAAA,oBAAK,EAAC,IAAI,CAAC;CAC1C,CAAC","sourcesContent":["import yargs from 'yargs';\nimport builders from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { serve } from './serveHandler';\n\nexport = {\n command: ['serve', 's'],\n desc: 'Locally serve Snap file(s) for testing',\n builder: (yarg: yargs.Argv) => {\n yarg.option('root', builders.root).option('port', builders.port);\n },\n handler: (argv: YargsArgs) => serve(argv),\n};\n"]}
@@ -0,0 +1,10 @@
1
+ import { YargsArgs } from '../../types/yargs';
2
+ /**
3
+ * Starts a local, static HTTP server on the given port with the given root
4
+ * directory.
5
+ *
6
+ * @param argv - Arguments as an object generated by Yargs.
7
+ * @param argv.root - The root directory path string.
8
+ * @param argv.port - The server port.
9
+ */
10
+ export declare function serve(argv: YargsArgs): Promise<void>;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.serve = void 0;
7
+ const http_1 = __importDefault(require("http"));
8
+ const serve_handler_1 = __importDefault(require("serve-handler"));
9
+ const utils_1 = require("../../utils");
10
+ const serveUtils_1 = require("./serveUtils");
11
+ /**
12
+ * Starts a local, static HTTP server on the given port with the given root
13
+ * directory.
14
+ *
15
+ * @param argv - Arguments as an object generated by Yargs.
16
+ * @param argv.root - The root directory path string.
17
+ * @param argv.port - The server port.
18
+ */
19
+ async function serve(argv) {
20
+ const { port, root: rootDir } = argv;
21
+ await (0, utils_1.validateDirPath)(rootDir, true);
22
+ console.log(`\nStarting server...`);
23
+ const server = http_1.default.createServer(async (req, res) => {
24
+ await (0, serve_handler_1.default)(req, res, {
25
+ public: rootDir,
26
+ headers: [
27
+ {
28
+ source: '**/*',
29
+ headers: [
30
+ {
31
+ key: 'Cache-Control',
32
+ value: 'no-cache',
33
+ },
34
+ ],
35
+ },
36
+ ],
37
+ });
38
+ });
39
+ server.listen({ port }, () => (0, serveUtils_1.logServerListening)(port));
40
+ server.on('request', (request) => (0, serveUtils_1.logRequest)(request));
41
+ server.on('error', (error) => {
42
+ (0, serveUtils_1.logServerError)(error, argv.port);
43
+ process.exitCode = 1;
44
+ });
45
+ server.on('close', () => {
46
+ console.log('Server closed');
47
+ process.exitCode = 1;
48
+ });
49
+ }
50
+ exports.serve = serve;
51
+ //# sourceMappingURL=serveHandler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serveHandler.js","sourceRoot":"","sources":["../../../src/cmds/serve/serveHandler.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAwB;AACxB,kEAAyC;AAEzC,uCAA8C;AAC9C,6CAA8E;AAE9E;;;;;;;GAOG;AACI,KAAK,UAAU,KAAK,CAAC,IAAe;IACzC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAErC,MAAM,IAAA,uBAAe,EAAC,OAAiB,EAAE,IAAI,CAAC,CAAC;IAE/C,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;IAEpC,MAAM,MAAM,GAAG,cAAI,CAAC,YAAY,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE;QAClD,MAAM,IAAA,uBAAY,EAAC,GAAG,EAAE,GAAG,EAAE;YAC3B,MAAM,EAAE,OAAiB;YACzB,OAAO,EAAE;gBACP;oBACE,MAAM,EAAE,MAAM;oBACd,OAAO,EAAE;wBACP;4BACE,GAAG,EAAE,eAAe;4BACpB,KAAK,EAAE,UAAU;yBAClB;qBACF;iBACF;aACF;SACF,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,EAAE,GAAG,EAAE,CAAC,IAAA,+BAAkB,EAAC,IAAI,CAAC,CAAC,CAAC;IAExD,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,IAAA,uBAAU,EAAC,OAAO,CAAC,CAAC,CAAC;IAEvD,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE;QAC3B,IAAA,2BAAc,EAAC,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QACjC,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;IAEH,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE;QACtB,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;QAC7B,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;AACL,CAAC;AArCD,sBAqCC","sourcesContent":["import http from 'http';\nimport serveHandler from 'serve-handler';\nimport { YargsArgs } from '../../types/yargs';\nimport { validateDirPath } from '../../utils';\nimport { logRequest, logServerError, logServerListening } from './serveUtils';\n\n/**\n * Starts a local, static HTTP server on the given port with the given root\n * directory.\n *\n * @param argv - Arguments as an object generated by Yargs.\n * @param argv.root - The root directory path string.\n * @param argv.port - The server port.\n */\nexport async function serve(argv: YargsArgs): Promise<void> {\n const { port, root: rootDir } = argv;\n\n await validateDirPath(rootDir as string, true);\n\n console.log(`\\nStarting server...`);\n\n const server = http.createServer(async (req, res) => {\n await serveHandler(req, res, {\n public: rootDir as string,\n headers: [\n {\n source: '**/*',\n headers: [\n {\n key: 'Cache-Control',\n value: 'no-cache',\n },\n ],\n },\n ],\n });\n });\n\n server.listen({ port }, () => logServerListening(port));\n\n server.on('request', (request) => logRequest(request));\n\n server.on('error', (error) => {\n logServerError(error, argv.port);\n process.exitCode = 1;\n });\n\n server.on('close', () => {\n console.log('Server closed');\n process.exitCode = 1;\n });\n}\n"]}
@@ -1,5 +1,22 @@
1
+ /**
2
+ * Log a message with the URL and port of the server.
3
+ *
4
+ * @param port - The port that the server is running on.
5
+ */
1
6
  export declare function logServerListening(port: number): void;
7
+ /**
8
+ * Log a message with the request URL.
9
+ *
10
+ * @param request - The request object.
11
+ * @param request.url - The URL of the request.
12
+ */
2
13
  export declare function logRequest(request: {
3
14
  url: string;
4
15
  }): void;
16
+ /**
17
+ * Log an error message.
18
+ *
19
+ * @param error - The error to log.
20
+ * @param port - The port that the server is running on.
21
+ */
5
22
  export declare function logServerError(error: Error, port: number): void;
@@ -2,14 +2,31 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.logServerError = exports.logRequest = exports.logServerListening = void 0;
4
4
  const utils_1 = require("../../utils");
5
+ /**
6
+ * Log a message with the URL and port of the server.
7
+ *
8
+ * @param port - The port that the server is running on.
9
+ */
5
10
  function logServerListening(port) {
6
11
  console.log(`Server listening on: http://localhost:${port}`);
7
12
  }
8
13
  exports.logServerListening = logServerListening;
14
+ /**
15
+ * Log a message with the request URL.
16
+ *
17
+ * @param request - The request object.
18
+ * @param request.url - The URL of the request.
19
+ */
9
20
  function logRequest(request) {
10
21
  console.log(`Handling incoming request for: ${request.url}`);
11
22
  }
12
23
  exports.logRequest = logRequest;
24
+ /**
25
+ * Log an error message.
26
+ *
27
+ * @param error - The error to log.
28
+ * @param port - The port that the server is running on.
29
+ */
13
30
  function logServerError(error, port) {
14
31
  if (error.code === 'EADDRINUSE') {
15
32
  (0, utils_1.logError)(`Server error: Port ${port} already in use.`);
@@ -1 +1 @@
1
- {"version":3,"file":"serveUtils.js","sourceRoot":"","sources":["../../../src/cmds/serve/serveUtils.ts"],"names":[],"mappings":";;;AAAA,uCAAuC;AAEvC,SAAgB,kBAAkB,CAAC,IAAY;IAC7C,OAAO,CAAC,GAAG,CAAC,yCAAyC,IAAI,EAAE,CAAC,CAAC;AAC/D,CAAC;AAFD,gDAEC;AAED,SAAgB,UAAU,CAAC,OAAwB;IACjD,OAAO,CAAC,GAAG,CAAC,kCAAkC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;AAC/D,CAAC;AAFD,gCAEC;AAED,SAAgB,cAAc,CAAC,KAAY,EAAE,IAAY;IACvD,IAAK,KAAa,CAAC,IAAI,KAAK,YAAY,EAAE;QACxC,IAAA,gBAAQ,EAAC,sBAAsB,IAAI,kBAAkB,CAAC,CAAC;KACxD;SAAM;QACL,IAAA,gBAAQ,EAAC,iBAAiB,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,CAAC,CAAC;KACnD;AACH,CAAC;AAND,wCAMC","sourcesContent":["import { logError } from '../../utils';\n\nexport function logServerListening(port: number) {\n console.log(`Server listening on: http://localhost:${port}`);\n}\n\nexport function logRequest(request: { url: string }) {\n console.log(`Handling incoming request for: ${request.url}`);\n}\n\nexport function logServerError(error: Error, port: number) {\n if ((error as any).code === 'EADDRINUSE') {\n logError(`Server error: Port ${port} already in use.`);\n } else {\n logError(`Server error: ${error.message}`, error);\n }\n}\n"]}
1
+ {"version":3,"file":"serveUtils.js","sourceRoot":"","sources":["../../../src/cmds/serve/serveUtils.ts"],"names":[],"mappings":";;;AAAA,uCAAuC;AAEvC;;;;GAIG;AACH,SAAgB,kBAAkB,CAAC,IAAY;IAC7C,OAAO,CAAC,GAAG,CAAC,yCAAyC,IAAI,EAAE,CAAC,CAAC;AAC/D,CAAC;AAFD,gDAEC;AAED;;;;;GAKG;AACH,SAAgB,UAAU,CAAC,OAAwB;IACjD,OAAO,CAAC,GAAG,CAAC,kCAAkC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;AAC/D,CAAC;AAFD,gCAEC;AAED;;;;;GAKG;AACH,SAAgB,cAAc,CAAC,KAAY,EAAE,IAAY;IACvD,IAAK,KAAa,CAAC,IAAI,KAAK,YAAY,EAAE;QACxC,IAAA,gBAAQ,EAAC,sBAAsB,IAAI,kBAAkB,CAAC,CAAC;KACxD;SAAM;QACL,IAAA,gBAAQ,EAAC,iBAAiB,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,CAAC,CAAC;KACnD;AACH,CAAC;AAND,wCAMC","sourcesContent":["import { logError } from '../../utils';\n\n/**\n * Log a message with the URL and port of the server.\n *\n * @param port - The port that the server is running on.\n */\nexport function logServerListening(port: number) {\n console.log(`Server listening on: http://localhost:${port}`);\n}\n\n/**\n * Log a message with the request URL.\n *\n * @param request - The request object.\n * @param request.url - The URL of the request.\n */\nexport function logRequest(request: { url: string }) {\n console.log(`Handling incoming request for: ${request.url}`);\n}\n\n/**\n * Log an error message.\n *\n * @param error - The error to log.\n * @param port - The port that the server is running on.\n */\nexport function logServerError(error: Error, port: number) {\n if ((error as any).code === 'EADDRINUSE') {\n logError(`Server error: Port ${port} already in use.`);\n } else {\n logError(`Server error: ${error.message}`, error);\n }\n}\n"]}
@@ -21,6 +21,9 @@ module.exports = {
21
21
  .option('depsToTranspile', builders_1.default.depsToTranspile)
22
22
  .option('manifest', builders_1.default.manifest)
23
23
  .option('writeManifest', builders_1.default.writeManifest)
24
+ .option('serve', builders_1.default.serve)
25
+ .option('root', builders_1.default.root)
26
+ .option('port', builders_1.default.port)
24
27
  .implies('writeManifest', 'manifest')
25
28
  .implies('depsToTranspile', 'transpilationMode')
26
29
  .middleware((argv) => (0, utils_1.processInvalidTranspilation)(argv));
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/watch/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AAEtC,0CAA6D;AAC7D,iDAAuC;AAEvC,iBAAS;IACP,OAAO,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC;IACvB,IAAI,EAAE,sBAAsB;IAC5B,OAAO,EAAE,CAAC,IAAgB,EAAE,EAAE;QAC5B,IAAI;aACD,MAAM,CAAC,KAAK,EAAE,kBAAQ,CAAC,GAAG,CAAC;aAC3B,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC;aAC7B,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC;aAC7B,MAAM,CAAC,aAAa,EAAE,kBAAQ,CAAC,WAAW,CAAC;aAC3C,MAAM,CAAC,YAAY,EAAE,kBAAQ,CAAC,UAAU,CAAC;aACzC,MAAM,CAAC,eAAe,EAAE,kBAAQ,CAAC,aAAa,CAAC;aAC/C,MAAM,CAAC,uBAAuB,EAAE,kBAAQ,CAAC,qBAAqB,CAAC;aAC/D,MAAM,CAAC,mBAAmB,EAAE,kBAAQ,CAAC,iBAAiB,CAAC;aACvD,MAAM,CAAC,iBAAiB,EAAE,kBAAQ,CAAC,eAAe,CAAC;aACnD,MAAM,CAAC,UAAU,EAAE,kBAAQ,CAAC,QAAQ,CAAC;aACrC,MAAM,CAAC,eAAe,EAAE,kBAAQ,CAAC,aAAa,CAAC;aAC/C,OAAO,CAAC,eAAe,EAAE,UAAU,CAAC;aACpC,OAAO,CAAC,iBAAiB,EAAE,mBAAmB,CAAC;aAC/C,UAAU,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAA,mCAA2B,EAAC,IAAW,CAAC,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,EAAE,CAAC,IAAe,EAAE,EAAE,CAAC,IAAA,oBAAK,EAAC,IAAI,CAAC;CAC1C,CAAC","sourcesContent":["import yargs from 'yargs';\nimport builders from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { processInvalidTranspilation } from '../build/utils';\nimport { watch } from './watchHandler';\n\nexport = {\n command: ['watch', 'w'],\n desc: 'Build Snap on change',\n builder: (yarg: yargs.Argv) => {\n yarg\n .option('src', builders.src)\n .option('eval', builders.eval)\n .option('dist', builders.dist)\n .option('outfileName', builders.outfileName)\n .option('sourceMaps', builders.sourceMaps)\n .option('stripComments', builders.stripComments)\n .option('transformHtmlComments', builders.transformHtmlComments)\n .option('transpilationMode', builders.transpilationMode)\n .option('depsToTranspile', builders.depsToTranspile)\n .option('manifest', builders.manifest)\n .option('writeManifest', builders.writeManifest)\n .implies('writeManifest', 'manifest')\n .implies('depsToTranspile', 'transpilationMode')\n .middleware((argv) => processInvalidTranspilation(argv as any));\n },\n handler: (argv: YargsArgs) => watch(argv),\n};\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/watch/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AAEtC,0CAA6D;AAC7D,iDAAuC;AAEvC,iBAAS;IACP,OAAO,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC;IACvB,IAAI,EAAE,sBAAsB;IAC5B,OAAO,EAAE,CAAC,IAAgB,EAAE,EAAE;QAC5B,IAAI;aACD,MAAM,CAAC,KAAK,EAAE,kBAAQ,CAAC,GAAG,CAAC;aAC3B,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC;aAC7B,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC;aAC7B,MAAM,CAAC,aAAa,EAAE,kBAAQ,CAAC,WAAW,CAAC;aAC3C,MAAM,CAAC,YAAY,EAAE,kBAAQ,CAAC,UAAU,CAAC;aACzC,MAAM,CAAC,eAAe,EAAE,kBAAQ,CAAC,aAAa,CAAC;aAC/C,MAAM,CAAC,uBAAuB,EAAE,kBAAQ,CAAC,qBAAqB,CAAC;aAC/D,MAAM,CAAC,mBAAmB,EAAE,kBAAQ,CAAC,iBAAiB,CAAC;aACvD,MAAM,CAAC,iBAAiB,EAAE,kBAAQ,CAAC,eAAe,CAAC;aACnD,MAAM,CAAC,UAAU,EAAE,kBAAQ,CAAC,QAAQ,CAAC;aACrC,MAAM,CAAC,eAAe,EAAE,kBAAQ,CAAC,aAAa,CAAC;aAC/C,MAAM,CAAC,OAAO,EAAE,kBAAQ,CAAC,KAAK,CAAC;aAC/B,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC;aAC7B,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC;aAC7B,OAAO,CAAC,eAAe,EAAE,UAAU,CAAC;aACpC,OAAO,CAAC,iBAAiB,EAAE,mBAAmB,CAAC;aAC/C,UAAU,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAA,mCAA2B,EAAC,IAAW,CAAC,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,EAAE,CAAC,IAAe,EAAE,EAAE,CAAC,IAAA,oBAAK,EAAC,IAAI,CAAC;CAC1C,CAAC","sourcesContent":["import yargs from 'yargs';\nimport builders from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { processInvalidTranspilation } from '../build/utils';\nimport { watch } from './watchHandler';\n\nexport = {\n command: ['watch', 'w'],\n desc: 'Build Snap on change',\n builder: (yarg: yargs.Argv) => {\n yarg\n .option('src', builders.src)\n .option('eval', builders.eval)\n .option('dist', builders.dist)\n .option('outfileName', builders.outfileName)\n .option('sourceMaps', builders.sourceMaps)\n .option('stripComments', builders.stripComments)\n .option('transformHtmlComments', builders.transformHtmlComments)\n .option('transpilationMode', builders.transpilationMode)\n .option('depsToTranspile', builders.depsToTranspile)\n .option('manifest', builders.manifest)\n .option('writeManifest', builders.writeManifest)\n .option('serve', builders.serve)\n .option('root', builders.root)\n .option('port', builders.port)\n .implies('writeManifest', 'manifest')\n .implies('depsToTranspile', 'transpilationMode')\n .middleware((argv) => processInvalidTranspilation(argv as any));\n },\n handler: (argv: YargsArgs) => watch(argv),\n};\n"]}
@@ -6,9 +6,9 @@ import { YargsArgs } from '../../types/yargs';
6
6
  * Ignores 'node_modules' and dotfiles.
7
7
  * Creates destination directory if it doesn't exist.
8
8
  *
9
- * @param argv - arguments as an object generated by yargs
10
- * @param argv.src - The source file path
11
- * @param argv.dist - The output directory path
12
- * @param argv.'outfileName' - The output file name
9
+ * @param argv - Arguments as an object generated by Yargs.
10
+ * @param argv.src - The source file path.
11
+ * @param argv.dist - The output directory path.
12
+ * @param argv.'outfileName' - The output file name.
13
13
  */
14
14
  export declare function watch(argv: YargsArgs): Promise<void>;
@@ -9,6 +9,7 @@ const utils_1 = require("../../utils");
9
9
  const bundle_1 = require("../build/bundle");
10
10
  const evalHandler_1 = require("../eval/evalHandler");
11
11
  const manifestHandler_1 = require("../manifest/manifestHandler");
12
+ const serveHandler_1 = require("../serve/serveHandler");
12
13
  /**
13
14
  * Watch a directory and its subdirectories for changes, and build when files
14
15
  * are added or changed.
@@ -16,13 +17,13 @@ const manifestHandler_1 = require("../manifest/manifestHandler");
16
17
  * Ignores 'node_modules' and dotfiles.
17
18
  * Creates destination directory if it doesn't exist.
18
19
  *
19
- * @param argv - arguments as an object generated by yargs
20
- * @param argv.src - The source file path
21
- * @param argv.dist - The output directory path
22
- * @param argv.'outfileName' - The output file name
20
+ * @param argv - Arguments as an object generated by Yargs.
21
+ * @param argv.src - The source file path.
22
+ * @param argv.dist - The output directory path.
23
+ * @param argv.'outfileName' - The output file name.
23
24
  */
24
25
  async function watch(argv) {
25
- const { dist, eval: shouldEval, manifest, outfileName, src } = argv;
26
+ const { dist, eval: shouldEval, manifest, outfileName, src, serve: shouldServe, } = argv;
26
27
  if (outfileName) {
27
28
  (0, utils_1.validateOutfileName)(outfileName);
28
29
  }
@@ -63,7 +64,12 @@ async function watch(argv) {
63
64
  (str) => str !== '.' && str.startsWith('.'),
64
65
  ],
65
66
  })
66
- .on('ready', buildSnap)
67
+ .on('ready', async () => {
68
+ await buildSnap();
69
+ if (shouldServe) {
70
+ await (0, serveHandler_1.serve)(argv);
71
+ }
72
+ })
67
73
  .on('add', (path) => buildSnap(path, `File added: ${path}`))
68
74
  .on('change', (path) => buildSnap(path, `File changed: ${path}`))
69
75
  .on('unlink', (path) => console.log(`File removed: ${path}`))
@@ -1 +1 @@
1
- {"version":3,"file":"watchHandler.js","sourceRoot":"","sources":["../../../src/cmds/watch/watchHandler.ts"],"names":[],"mappings":";;;;;;AAAA,wDAAgC;AAEhC,uCAOqB;AACrB,4CAAyC;AACzC,qDAA+C;AAC/C,iEAA8D;AAE9D;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,KAAK,CAAC,IAAe;IACzC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,WAAW,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IACpE,IAAI,WAAW,EAAE;QACf,IAAA,2BAAmB,EAAC,WAAqB,CAAC,CAAC;KAC5C;IACD,MAAM,IAAA,wBAAgB,EAAC,GAAG,CAAC,CAAC;IAC5B,MAAM,IAAA,uBAAe,EAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,MAAM,OAAO,GACX,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;IAC7E,MAAM,WAAW,GAAG,IAAA,sBAAc,EAAC,IAAI,EAAE,WAAqB,CAAC,CAAC;IAEhE,MAAM,SAAS,GAAG,KAAK,EAAE,IAAa,EAAE,UAAmB,EAAE,EAAE;QAC7D,IAAI,UAAU,KAAK,SAAS,EAAE;YAC5B,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;SACzB;QAED,IAAI;YACF,MAAM,IAAA,eAAM,EAAC,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,IAAA,kBAAU,GAAE,CAAC,iBAAiB,CAAC,CAAC;YAErE,IAAI,QAAQ,EAAE;gBACZ,MAAM,IAAA,iCAAe,EAAC,IAAI,CAAC,C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AAC,aAAa,OAAO,kBAAkB,CAAC,CAAC;AACtD,CAAC;AAhED,sBAgEC","sourcesContent":["import chokidar from 'chokidar';\nimport { YargsArgs } from '../../types/yargs';\nimport {\n getOutfilePath,\n loadConfig,\n logError,\n validateDirPath,\n validateFilePath,\n validateOutfileName,\n} from '../../utils';\nimport { bundle } from '../build/bundle';\nimport { snapEval } from '../eval/evalHandler';\nimport { manifestHandler } from '../manifest/manifestHandler';\n\n/**\n * Watch a directory and its subdirectories for changes, and build when files\n * are added or changed.\n *\n * Ignores 'node_modules' and dotfiles.\n * Creates destination directory if it doesn't exist.\n *\n * @param argv - arguments as an object generated by yargs\n * @param argv.src - The source file path\n * @param argv.dist - The output directory path\n * @param argv.'outfileName' - The output file name\n */\nexport async function watch(argv: YargsArgs): Promise<void> {\n const { dist, eval: shouldEval, manifest, outfileName, src } = argv;\n if (outfileName) {\n validateOutfileName(outfileName as string);\n }\n await validateFilePath(src);\n await validateDirPath(dist, true);\n const rootDir =\n src.indexOf('/') === -1 ? '.' : src.substring(0, src.lastIndexOf('/') + 1);\n const outfilePath = getOutfilePath(dist, outfileName as string);\n\n const buildSnap = async (path?: string, logMessage?: string) => {\n if (logMessage !== undefined) {\n console.log(logMessage);\n }\n\n try {\n await bundle(src, outfilePath, argv, loadConfig().bundlerCustomizer);\n\n if (manifest) {\n await manifestHandler(argv);\n }\n\n if (shouldEval) {\n await snapEval({ ...argv, bundle: outfilePath });\n }\n } catch (error) {\n logError(\n `Error ${\n path === undefined\n ? 'during initial build'\n : `while processing \"${path}\"`\n }.`,\n error,\n );\n }\n };\n\n chokidar\n .watch(rootDir, {\n ignoreInitial: true,\n ignored: [\n '**/node_modules/**',\n `**/${dist}/**`,\n `**/test/**`,\n `**/tests/**`,\n `**/*.test.js`,\n `**/*.test.ts`,\n /* istanbul ignore next */\n (str: string) => str !== '.' && str.startsWith('.'),\n ],\n })\n\n .on('ready', buildSnap)\n .on('add', (path) => buildSnap(path, `File added: ${path}`))\n .on('change', (path) => buildSnap(path, `File changed: ${path}`))\n .on('unlink', (path) => console.log(`File removed: ${path}`))\n .on('error', (error: Error) => {\n logError(`Watcher error: ${error.message}`, error);\n })\n\n .add(rootDir);\n\n console.log(`Watching '${rootDir}' for changes...`);\n}\n"]}
1
+ {"version":3,"file":"watchHandler.js","sourceRoot":"","sources":["../../../src/cmds/watch/watchHandler.ts"],"names":[],"mappings":";;;;;;AAAA,wDAAgC;AAEhC,uCAOqB;AACrB,4CAAyC;AACzC,qDAA+C;AAC/C,iEAA8D;AAC9D,wDAA8C;AAE9C;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,KAAK,CAAC,IAAe;IACzC,MAAM,EACJ,IAAI,EACJ,IAAI,EAAE,UAAU,EAChB,QAAQ,EACR,WAAW,EACX,GAAG,EACH,KAAK,EAAE,WAAW,GACnB,GAAG,IAAI,CAAC;IACT,IAAI,WAAW,EAAE;QACf,IAAA,2BAAmB,EAAC,WAAqB,CAAC,CAAC;KAC5C;IACD,MAAM,IAAA,wBAAgB,EAAC,GAAG,CAAC,CAAC;IAC5B,MAAM,IAAA,uBAAe,EAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,MAAM,OAAO,GACX,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;IAC7E,MAAM,WAAW,GAAG,IAAA,sBAAc,EAAC,IAAI,EAAE,WAAqB,CAAC,CAAC;IAEhE,MAAM,SAAS,GAAG,KAAK,EAAE,IAAa,EAAE,UAAmB,EAAE,EAAE;QAC7D,IAAI,UAAU,KAAK,SAAS,EAAE;YAC5B,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;SACzB;QAED,IAAI;YACF,MAAM,IAAA,eAAM,EAAC,GAAG,EAAE,WAAW,EAA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AG,CAAC,iBAAiB,IAAI,EAAE,CAAC,CAAC;SAC5D,EAAE,CAAC,OAAO,EAAE,CAAC,KAAY,EAAE,EAAE;QAC5B,IAAA,gBAAQ,EAAC,kBAAkB,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,CAAC,CAAC;IACrD,CAAC,CAAC;SAED,GAAG,CAAC,OAAO,CAAC,CAAC;IAEhB,OAAO,CAAC,GAAG,CAAC,aAAa,OAAO,kBAAkB,CAAC,CAAC;AACtD,CAAC;AA5ED,sBA4EC","sourcesContent":["import chokidar from 'chokidar';\nimport { YargsArgs } from '../../types/yargs';\nimport {\n getOutfilePath,\n loadConfig,\n logError,\n validateDirPath,\n validateFilePath,\n validateOutfileName,\n} from '../../utils';\nimport { bundle } from '../build/bundle';\nimport { snapEval } from '../eval/evalHandler';\nimport { manifestHandler } from '../manifest/manifestHandler';\nimport { serve } from '../serve/serveHandler';\n\n/**\n * Watch a directory and its subdirectories for changes, and build when files\n * are added or changed.\n *\n * Ignores 'node_modules' and dotfiles.\n * Creates destination directory if it doesn't exist.\n *\n * @param argv - Arguments as an object generated by Yargs.\n * @param argv.src - The source file path.\n * @param argv.dist - The output directory path.\n * @param argv.'outfileName' - The output file name.\n */\nexport async function watch(argv: YargsArgs): Promise<void> {\n const {\n dist,\n eval: shouldEval,\n manifest,\n outfileName,\n src,\n serve: shouldServe,\n } = argv;\n if (outfileName) {\n validateOutfileName(outfileName as string);\n }\n await validateFilePath(src);\n await validateDirPath(dist, true);\n const rootDir =\n src.indexOf('/') === -1 ? '.' : src.substring(0, src.lastIndexOf('/') + 1);\n const outfilePath = getOutfilePath(dist, outfileName as string);\n\n const buildSnap = async (path?: string, logMessage?: string) => {\n if (logMessage !== undefined) {\n console.log(logMessage);\n }\n\n try {\n await bundle(src, outfilePath, argv, loadConfig().bundlerCustomizer);\n\n if (manifest) {\n await manifestHandler(argv);\n }\n\n if (shouldEval) {\n await snapEval({ ...argv, bundle: outfilePath });\n }\n } catch (error) {\n logError(\n `Error ${\n path === undefined\n ? 'during initial build'\n : `while processing \"${path}\"`\n }.`,\n error,\n );\n }\n };\n\n chokidar\n .watch(rootDir, {\n ignoreInitial: true,\n ignored: [\n '**/node_modules/**',\n `**/${dist}/**`,\n `**/test/**`,\n `**/tests/**`,\n `**/*.test.js`,\n `**/*.test.ts`,\n /* istanbul ignore next */\n (str: string) => str !== '.' && str.startsWith('.'),\n ],\n })\n\n .on('ready', async () => {\n await buildSnap();\n if (shouldServe) {\n await serve(argv);\n }\n })\n .on('add', (path) => buildSnap(path, `File added: ${path}`))\n .on('change', (path) => buildSnap(path, `File changed: ${path}`))\n .on('unlink', (path) => console.log(`File removed: ${path}`))\n .on('error', (error: Error) => {\n logError(`Watcher error: ${error.message}`, error);\n })\n\n .add(rootDir);\n\n console.log(`Watching '${rootDir}' for changes...`);\n}\n"]}
@@ -3,16 +3,16 @@ import type { Json } from '@metamask/snap-controllers';
3
3
  * Checks whether the given path string resolves to an existing directory, and
4
4
  * optionally creates the directory if it doesn't exist.
5
5
  *
6
- * @param pathString - The path string to check
7
- * @param createDir - Whether to create the directory if it doesn't exist
8
- * @returns - Whether the given path is an existing directory
6
+ * @param pathString - The path string to check.
7
+ * @param createDir - Whether to create the directory if it doesn't exist.
8
+ * @returns Whether the given path is an existing directory.
9
9
  */
10
10
  export declare function isDirectory(pathString: string, createDir: boolean): Promise<boolean>;
11
11
  /**
12
12
  * Checks whether the given path string resolves to an existing file.
13
13
  *
14
- * @param pathString - The path string to check
15
- * @returns Whether the given path is an existing file
14
+ * @param pathString - The path string to check.
15
+ * @returns Whether the given path is an existing file.
16
16
  */
17
17
  export declare function isFile(pathString: string): Promise<boolean>;
18
18
  /**
package/dist/utils/fs.js CHANGED
@@ -7,9 +7,9 @@ const misc_1 = require("./misc");
7
7
  * Checks whether the given path string resolves to an existing directory, and
8
8
  * optionally creates the directory if it doesn't exist.
9
9
  *
10
- * @param pathString - The path string to check
11
- * @param createDir - Whether to create the directory if it doesn't exist
12
- * @returns - Whether the given path is an existing directory
10
+ * @param pathString - The path string to check.
11
+ * @param createDir - Whether to create the directory if it doesn't exist.
12
+ * @returns Whether the given path is an existing directory.
13
13
  */
14
14
  async function isDirectory(pathString, createDir) {
15
15
  try {
@@ -37,8 +37,8 @@ exports.isDirectory = isDirectory;
37
37
  /**
38
38
  * Checks whether the given path string resolves to an existing file.
39
39
  *
40
- * @param pathString - The path string to check
41
- * @returns Whether the given path is an existing file
40
+ * @param pathString - The path string to check.
41
+ * @returns Whether the given path is an existing file.
42
42
  */
43
43
  async function isFile(pathString) {
44
44
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"fs.js","sourceRoot":"","sources":["../../src/utils/fs.ts"],"names":[],"mappings":";;;AAAA,2BAAoC;AAEpC,iCAAkC;AAElC;;;;;;;GAOG;AACI,KAAK,UAAU,WAAW,CAC/B,UAAkB,EAClB,SAAkB;IAElB,IAAI;QACF,MAAM,KAAK,GAAG,MAAM,aAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACxC,OAAO,KAAK,CAAC,WAAW,EAAE,CAAC;KAC5B;IAAC,OAAO,KAAK,EAAE;QACd,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE;YAC3B,IAAI,CAAC,SAAS,EAAE;gBACd,OAAO,KAAK,CAAC;aACd;YAED,IAAI;gBACF,MAAM,aAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;gBAC3B,OAAO,IAAI,CAAC;aACb;YAAC,OAAO,UAAU,EAAE;gBACnB,IAAA,eAAQ,EAAC,cAAc,UAAU,yBAAyB,EAAE,UAAU,CAAC,CAAC;gBACxE,MAAM,UAAU,CAAC;aAClB;SACF;QACD,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAvBD,kCAuBC;AAED;;;;;GAKG;AACI,KAAK,UAAU,MAAM,CAAC,UAAkB;IAC7C,IAAI;QACF,MAAM,KAAK,GAAG,MAAM,aAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACxC,OAAO,KAAK,CAAC,MAAM,EAAE,CAAC;KACvB;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAPD,wBAOC;AAED;;;;;GAKG;AACI,KAAK,UAAU,YAAY,CAAC,UAAkB;IACnD,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;QACjC,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;KAC/D;IAED,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,aAAE,CAAC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;AAC3D,CAAC;AAND,oCAMC","sourcesContent":["import { promises as fs } from 'fs';\nimport type { Json } from '@metamask/snap-controllers';\nimport { logError } from './misc';\n\n/**\n * Checks whether the given path string resolves to an existing directory, and\n * optionally creates the directory if it doesn't exist.\n *\n * @param pathString - The path string to check\n * @param createDir - Whether to create the directory if it doesn't exist\n * @returns - Whether the given path is an existing directory\n */\nexport async function isDirectory(\n pathString: string,\n createDir: boolean,\n): Promise<boolean> {\n try {\n const stats = await fs.stat(pathString);\n return stats.isDirectory();\n } catch (error) {\n if (error.code === 'ENOENT') {\n if (!createDir) {\n return false;\n }\n\n try {\n await fs.mkdir(pathString);\n return true;\n } catch (mkdirError) {\n logError(`Directory '${pathString}' could not be created.`, mkdirError);\n throw mkdirError;\n }\n }\n return false;\n }\n}\n\n/**\n * Checks whether the given path string resolves to an existing file.\n *\n * @param pathString - The path string to check\n * @returns Whether the given path is an existing file\n */\nexport async function isFile(pathString: string): Promise<boolean> {\n try {\n const stats = await fs.stat(pathString);\n return stats.isFile();\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Reads a `.json` file, parses its contents, and returns them.\n *\n * @param pathString - The path to the JSON file.\n * @returns The parsed contents of the JSON file.\n */\nexport async function readJsonFile(pathString: string): Promise<Json> {\n if (!pathString.endsWith('.json')) {\n throw new Error('The specified file must be a \".json\" file.');\n }\n\n return JSON.parse(await fs.readFile(pathString, 'utf8'));\n}\n"]}
1
+ {"version":3,"file":"fs.js","sourceRoot":"","sources":["../../src/utils/fs.ts"],"names":[],"mappings":";;;AAAA,2BAAoC;AAEpC,iCAAkC;AAElC;;;;;;;GAOG;AACI,KAAK,UAAU,WAAW,CAC/B,UAAkB,EAClB,SAAkB;IAElB,IAAI;QACF,MAAM,KAAK,GAAG,MAAM,aAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACxC,OAAO,KAAK,CAAC,WAAW,EAAE,CAAC;KAC5B;IAAC,OAAO,KAAK,EAAE;QACd,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE;YAC3B,IAAI,CAAC,SAAS,EAAE;gBACd,OAAO,KAAK,CAAC;aACd;YAED,IAAI;gBACF,MAAM,aAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;gBAC3B,OAAO,IAAI,CAAC;aACb;YAAC,OAAO,UAAU,EAAE;gBACnB,IAAA,eAAQ,EAAC,cAAc,UAAU,yBAAyB,EAAE,UAAU,CAAC,CAAC;gBACxE,MAAM,UAAU,CAAC;aAClB;SACF;QACD,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAvBD,kCAuBC;AAED;;;;;GAKG;AACI,KAAK,UAAU,MAAM,CAAC,UAAkB;IAC7C,IAAI;QACF,MAAM,KAAK,GAAG,MAAM,aAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACxC,OAAO,KAAK,CAAC,MAAM,EAAE,CAAC;KACvB;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAPD,wBAOC;AAED;;;;;GAKG;AACI,KAAK,UAAU,YAAY,CAAC,UAAkB;IACnD,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;QACjC,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;KAC/D;IAED,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,aAAE,CAAC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;AAC3D,CAAC;AAND,oCAMC","sourcesContent":["import { promises as fs } from 'fs';\nimport type { Json } from '@metamask/snap-controllers';\nimport { logError } from './misc';\n\n/**\n * Checks whether the given path string resolves to an existing directory, and\n * optionally creates the directory if it doesn't exist.\n *\n * @param pathString - The path string to check.\n * @param createDir - Whether to create the directory if it doesn't exist.\n * @returns Whether the given path is an existing directory.\n */\nexport async function isDirectory(\n pathString: string,\n createDir: boolean,\n): Promise<boolean> {\n try {\n const stats = await fs.stat(pathString);\n return stats.isDirectory();\n } catch (error) {\n if (error.code === 'ENOENT') {\n if (!createDir) {\n return false;\n }\n\n try {\n await fs.mkdir(pathString);\n return true;\n } catch (mkdirError) {\n logError(`Directory '${pathString}' could not be created.`, mkdirError);\n throw mkdirError;\n }\n }\n return false;\n }\n}\n\n/**\n * Checks whether the given path string resolves to an existing file.\n *\n * @param pathString - The path string to check.\n * @returns Whether the given path is an existing file.\n */\nexport async function isFile(pathString: string): Promise<boolean> {\n try {\n const stats = await fs.stat(pathString);\n return stats.isFile();\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Reads a `.json` file, parses its contents, and returns them.\n *\n * @param pathString - The path to the JSON file.\n * @returns The parsed contents of the JSON file.\n */\nexport async function readJsonFile(pathString: string): Promise<Json> {\n if (!pathString.endsWith('.json')) {\n throw new Error('The specified file must be a \".json\" file.');\n }\n\n return JSON.parse(await fs.readFile(pathString, 'utf8'));\n}\n"]}
@@ -4,16 +4,17 @@ export declare const permRequestKeys: string[];
4
4
  export declare const CONFIG_FILE = "snap.config.js";
5
5
  /**
6
6
  * Sets global variable snaps which tracks user settings:
7
- * watch mode activation, verbose errors messages, and whether to suppress warnings.
7
+ * watch mode activation, verbose errors messages, and whether to suppress
8
+ * warnings.
8
9
  *
9
- * @param argv - arguments as an object generated by yargs
10
+ * @param argv - Arguments as an object generated by `yargs`.
10
11
  */
11
12
  export declare function setSnapGlobals(argv: Arguments): void;
12
13
  /**
13
14
  * Attempts to convert a string to a boolean and throws if the value is invalid.
14
15
  *
15
16
  * @param value - The value to convert to a boolean.
16
- * @return `true` if the value is the string `"true"`, `false` if it is the
17
+ * @returns `true` if the value is the string `"true"`, `false` if it is the
17
18
  * string `"false"`, the value if it is already a boolean, or an error
18
19
  * otherwise.
19
20
  */
@@ -22,30 +23,32 @@ export declare function booleanStringToBoolean(value: unknown): boolean;
22
23
  * Sanitizes inputs. Currently normalizes "./" paths to ".".
23
24
  * Yargs handles other path normalization as specified in builders.
24
25
  *
25
- * @param argv - arguments as an object generated by yargs
26
+ * @param argv - Arguments as an object generated by yargs.
26
27
  */
27
28
  export declare function sanitizeInputs(argv: Arguments): void;
28
29
  /**
29
30
  * Logs an error message to console. Logs original error if it exists and
30
31
  * the verboseErrors global is true.
31
32
  *
32
- * @param msg - The error message
33
- * @param err - The original error
33
+ * @param msg - The error message.
34
+ * @param err - The original error.
34
35
  */
35
36
  export declare function logError(msg: string, err?: Error): void;
36
37
  /**
37
38
  * Logs a warning message to console.
38
39
  *
39
- * @param msg - The warning message
40
+ * @param msg - The warning message.
41
+ * @param error - The original error.
40
42
  */
41
43
  export declare function logWarning(msg: string, error?: Error): void;
42
44
  /**
43
- * Logs an error, attempts to unlink the destination file, and exits.
45
+ * Logs an error, attempts to unlink the destination file, and kills the
46
+ * process.
44
47
  *
45
- * @param prefix - The message prefix
46
- * @param msg - The error message
47
- * @param err - The original error
48
- * @param destFilePath - The output file path
48
+ * @param prefix - The message prefix.
49
+ * @param msg - The error message.
50
+ * @param err - The original error.
51
+ * @param destFilePath - The output file path.
49
52
  */
50
53
  export declare function writeError(prefix: string, msg: string, err: Error, destFilePath?: string): Promise<void>;
51
54
  /**
@@ -53,6 +56,6 @@ export declare function writeError(prefix: string, msg: string, err: Error, dest
53
56
  * given path string.
54
57
  *
55
58
  * @param pathString - The path string to trim.
56
- * @returns - The trimmed path string.
59
+ * @returns The trimmed path string.
57
60
  */
58
61
  export declare function trimPathString(pathString: string): string;