@shopify/cli-kit 4.1.0 → 4.3.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 (72) hide show
  1. package/assets/graphiql/favicon.ico +0 -0
  2. package/assets/graphiql/style.css +58 -0
  3. package/dist/private/common/array.js +2 -1
  4. package/dist/private/common/array.js.map +1 -1
  5. package/dist/private/node/api/headers.js +6 -3
  6. package/dist/private/node/api/headers.js.map +1 -1
  7. package/dist/private/node/session/device-authorization.js +4 -16
  8. package/dist/private/node/session/device-authorization.js.map +1 -1
  9. package/dist/private/node/session/store.js +10 -1
  10. package/dist/private/node/session/store.js.map +1 -1
  11. package/dist/private/node/ui.js +4 -1
  12. package/dist/private/node/ui.js.map +1 -1
  13. package/dist/public/common/gid.d.ts +24 -0
  14. package/dist/public/common/gid.js +32 -0
  15. package/dist/public/common/gid.js.map +1 -0
  16. package/dist/public/common/url.d.ts +16 -0
  17. package/dist/public/common/url.js +39 -0
  18. package/dist/public/common/url.js.map +1 -1
  19. package/dist/public/common/version.d.ts +1 -1
  20. package/dist/public/common/version.js +1 -1
  21. package/dist/public/common/version.js.map +1 -1
  22. package/dist/public/node/analytics.js +3 -5
  23. package/dist/public/node/analytics.js.map +1 -1
  24. package/dist/public/node/cli.d.ts +13 -0
  25. package/dist/public/node/cli.js +12 -0
  26. package/dist/public/node/cli.js.map +1 -1
  27. package/dist/public/node/context/fqdn.js +1 -1
  28. package/dist/public/node/context/fqdn.js.map +1 -1
  29. package/dist/public/node/error-handler.js +1 -1
  30. package/dist/public/node/error-handler.js.map +1 -1
  31. package/dist/public/node/graphiql/server.d.ts +80 -0
  32. package/dist/public/node/graphiql/server.js +234 -0
  33. package/dist/public/node/graphiql/server.js.map +1 -0
  34. package/dist/public/node/graphiql/templates/graphiql.d.ts +12 -0
  35. package/dist/public/node/graphiql/templates/graphiql.js +314 -0
  36. package/dist/public/node/graphiql/templates/graphiql.js.map +1 -0
  37. package/dist/public/node/graphiql/templates/unauthorized.d.ts +5 -0
  38. package/dist/public/node/graphiql/templates/unauthorized.js +111 -0
  39. package/dist/public/node/graphiql/templates/unauthorized.js.map +1 -0
  40. package/dist/public/node/graphiql/utilities.d.ts +12 -0
  41. package/dist/public/node/graphiql/utilities.js +44 -0
  42. package/dist/public/node/graphiql/utilities.js.map +1 -0
  43. package/dist/public/node/graphql.d.ts +19 -0
  44. package/dist/public/node/graphql.js +41 -0
  45. package/dist/public/node/graphql.js.map +1 -0
  46. package/dist/public/node/hooks/postrun.js +12 -2
  47. package/dist/public/node/hooks/postrun.js.map +1 -1
  48. package/dist/public/node/http.js +27 -31
  49. package/dist/public/node/http.js.map +1 -1
  50. package/dist/public/node/json-schema.js +22 -6
  51. package/dist/public/node/json-schema.js.map +1 -1
  52. package/dist/public/node/metadata.d.ts +3 -0
  53. package/dist/public/node/metadata.js.map +1 -1
  54. package/dist/public/node/monorail.d.ts +3 -1
  55. package/dist/public/node/monorail.js +1 -1
  56. package/dist/public/node/monorail.js.map +1 -1
  57. package/dist/public/node/output.js +20 -11
  58. package/dist/public/node/output.js.map +1 -1
  59. package/dist/public/node/session.d.ts +2 -1
  60. package/dist/public/node/session.js +3 -2
  61. package/dist/public/node/session.js.map +1 -1
  62. package/dist/public/node/system.js +3 -0
  63. package/dist/public/node/system.js.map +1 -1
  64. package/dist/public/node/tcp.js +11 -3
  65. package/dist/public/node/tcp.js.map +1 -1
  66. package/dist/public/node/themes/api.js +76 -4
  67. package/dist/public/node/themes/api.js.map +1 -1
  68. package/dist/public/node/toml/toml-file.d.ts +3 -2
  69. package/dist/public/node/toml/toml-file.js +3 -2
  70. package/dist/public/node/toml/toml-file.js.map +1 -1
  71. package/dist/tsconfig.tsbuildinfo +1 -1
  72. package/package.json +34 -29
@@ -0,0 +1,41 @@
1
+ import { parse } from 'graphql';
2
+ /**
3
+ * Returns true if the GraphQL document contains a mutation operation that
4
+ * would actually be executed for the given (optional) operation name.
5
+ *
6
+ * - When `operationName` is provided, only the matching operation is checked.
7
+ * - When `operationName` is omitted and the document has a single operation,
8
+ * that operation is checked.
9
+ * - When the document has multiple operations and no operation name is given,
10
+ * any mutation in the document is treated as a mutation request (the GraphQL
11
+ * server would reject the ambiguous request anyway).
12
+ *
13
+ * Returns false for queries, subscriptions, fragment-only documents, and any
14
+ * input that fails to parse as GraphQL.
15
+ *
16
+ * @param query - The GraphQL document to inspect.
17
+ * @param operationName - Optional name of the operation to check; when set, only that operation is considered.
18
+ * @returns True if the relevant operation is a mutation; false otherwise.
19
+ */
20
+ export function containsMutation(query, operationName) {
21
+ let document;
22
+ try {
23
+ document = parse(query);
24
+ // eslint-disable-next-line no-catch-all/no-catch-all -- swallowing parse errors is the entire purpose
25
+ }
26
+ catch {
27
+ return false;
28
+ }
29
+ const operations = document.definitions.filter((definition) => definition.kind === 'OperationDefinition');
30
+ if (operations.length === 0)
31
+ return false;
32
+ if (operationName) {
33
+ const target = operations.find((operation) => operation.name?.value === operationName);
34
+ return target?.operation === 'mutation';
35
+ }
36
+ if (operations.length === 1) {
37
+ return operations[0].operation === 'mutation';
38
+ }
39
+ return operations.some((operation) => operation.operation === 'mutation');
40
+ }
41
+ //# sourceMappingURL=graphql.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graphql.js","sourceRoot":"","sources":["../../../src/public/node/graphql.ts"],"names":[],"mappings":"AAAA,OAAO,EAA0B,KAAK,EAAC,MAAM,SAAS,CAAA;AAEtD;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,gBAAgB,CAAC,KAAa,EAAE,aAAsB;IACpE,IAAI,QAAQ,CAAA;IACZ,IAAI,CAAC;QACH,QAAQ,GAAG,KAAK,CAAC,KAAK,CAAC,CAAA;QACvB,sGAAsG;IACxG,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAA;IACd,CAAC;IAED,MAAM,UAAU,GAAG,QAAQ,CAAC,WAAW,CAAC,MAAM,CAC5C,CAAC,UAAU,EAAyC,EAAE,CAAC,UAAU,CAAC,IAAI,KAAK,qBAAqB,CACjG,CAAA;IAED,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAA;IAEzC,IAAI,aAAa,EAAE,CAAC;QAClB,MAAM,MAAM,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,KAAK,aAAa,CAAC,CAAA;QACtF,OAAO,MAAM,EAAE,SAAS,KAAK,UAAU,CAAA;IACzC,CAAC;IAED,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC5B,OAAO,UAAU,CAAC,CAAC,CAAE,CAAC,SAAS,KAAK,UAAU,CAAA;IAChD,CAAC;IAED,OAAO,UAAU,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,SAAS,KAAK,UAAU,CAAC,CAAA;AAC3E,CAAC","sourcesContent":["import {OperationDefinitionNode, parse} from 'graphql'\n\n/**\n * Returns true if the GraphQL document contains a mutation operation that\n * would actually be executed for the given (optional) operation name.\n *\n * - When `operationName` is provided, only the matching operation is checked.\n * - When `operationName` is omitted and the document has a single operation,\n * that operation is checked.\n * - When the document has multiple operations and no operation name is given,\n * any mutation in the document is treated as a mutation request (the GraphQL\n * server would reject the ambiguous request anyway).\n *\n * Returns false for queries, subscriptions, fragment-only documents, and any\n * input that fails to parse as GraphQL.\n *\n * @param query - The GraphQL document to inspect.\n * @param operationName - Optional name of the operation to check; when set, only that operation is considered.\n * @returns True if the relevant operation is a mutation; false otherwise.\n */\nexport function containsMutation(query: string, operationName?: string): boolean {\n let document\n try {\n document = parse(query)\n // eslint-disable-next-line no-catch-all/no-catch-all -- swallowing parse errors is the entire purpose\n } catch {\n return false\n }\n\n const operations = document.definitions.filter(\n (definition): definition is OperationDefinitionNode => definition.kind === 'OperationDefinition',\n )\n\n if (operations.length === 0) return false\n\n if (operationName) {\n const target = operations.find((operation) => operation.name?.value === operationName)\n return target?.operation === 'mutation'\n }\n\n if (operations.length === 1) {\n return operations[0]!.operation === 'mutation'\n }\n\n return operations.some((operation) => operation.operation === 'mutation')\n}\n"]}
@@ -50,8 +50,16 @@ export function waitForPostRunHookAndExit() {
50
50
  // This hook is called after each successful command run. More info: https://oclif.io/docs/hooks
51
51
  export const hook = async ({ config, Command }) => {
52
52
  await detectStopCommand(Command);
53
- const { reportAnalyticsEvent } = await import('../analytics.js');
54
- await reportAnalyticsEvent({ config, exitMode: 'ok' });
53
+ const metadata = await import('../metadata.js');
54
+ const { commandStartOptions } = metadata.getAllSensitiveMetadata();
55
+ if (commandStartOptions) {
56
+ await metadata.addSensitiveMetadata(() => ({
57
+ commandStartOptions: {
58
+ ...commandStartOptions,
59
+ endTime: new Date().getTime(),
60
+ },
61
+ }));
62
+ }
55
63
  const { postrun: deprecationsHook } = await import('./deprecations.js');
56
64
  deprecationsHook(Command);
57
65
  const { outputDebug } = await import('../output.js');
@@ -59,6 +67,8 @@ export const hook = async ({ config, Command }) => {
59
67
  outputDebug(`Completed command ${command}`);
60
68
  if (!command.includes('notifications') && !command.includes('upgrade'))
61
69
  await autoUpgradeIfNeeded();
70
+ const { reportAnalyticsEvent } = await import('../analytics.js');
71
+ await reportAnalyticsEvent({ config, exitMode: 'ok' });
62
72
  postRunHookCompleted = true;
63
73
  };
64
74
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"postrun.js","sourceRoot":"","sources":["../../../../src/public/node/hooks/postrun.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAC,QAAQ,EAAC,MAAM,iBAAiB,CAAA;AAGxC,IAAI,oBAAoB,GAAG,KAAK,CAAA;AAEhC;;;;GAIG;AACH,MAAM,UAAU,uBAAuB;IACrC,OAAO,oBAAoB,CAAA;AAC7B,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,yBAAyB;IACvC,MAAM,cAAc,GAAG,GAAG,CAAA;IAC1B,oFAAoF;IACpF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AC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;YAClF,MAAM,CAAC,qBAAqB,CAAC;YAC7B,MAAM,CAAC,iBAAiB,CAAC;SAC1B,CAAC,CAAA;QACF,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,YAAY,CAAC,EAAE;YAC3D,cAAc,EAAE,+BAA+B,EAAE;YACjD,QAAQ,EAAE,OAAO,CAAC,QAAQ;YAC1B,UAAU,EAAE,eAAe;SAC5B,CAAC,CAAA;QACF,MAAM,kBAAkB,CAAC,aAAa,EAAE,gBAAgB,CAAC,CAAA;IAC3D,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,iBAAiB,CAAC,YAA2B;IAC1D,MAAM,WAAW,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAA;IACxC,+DAA+D;IAC/D,IACE,YAAY;QACZ,sBAAsB,IAAI,YAAY;QACtC,OAAO,YAAY,CAAC,oBAAoB,KAAK,UAAU,EACvD,CAAC;QACD,8DAA8D;QAC9D,MAAM,WAAW,GAAI,YAAoB,CAAC,oBAAoB,EAAE,CAAA;QAChE,IAAI,WAAW,EAAE,CAAC;YAChB,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,gBAAgB,CAAC,CAAA;YAC/C,MAAM,EAAC,mBAAmB,EAAC,GAAG,QAAQ,CAAC,uBAAuB,EAAE,CAAA;YAChE,IAAI,CAAC,mBAAmB;gBAAE,OAAM;YAChC,MAAM,QAAQ,CAAC,oBAAoB,CAAC,GAAG,EAAE,CAAC,CAAC;gBACzC,mBAAmB,EAAE;oBACnB,GAAG,mBAAmB;oBACtB,SAAS,EAAE,WAAW;oBACtB,YAAY,EAAE,WAAW;iBAC1B;aACF,CAAC,CAAC,CAAA;QACL,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/**\n * Postrun hook — uses dynamic imports to avoid loading heavy modules (base-command, analytics)\n * at module evaluation time. These are only needed after the command has already finished.\n */\nimport {treeKill} from '../tree-kill.js'\nimport {Command, Hook} from '@oclif/core'\n\nlet postRunHookCompleted = false\n\n/**\n * Check if post run hook has completed.\n *\n * @returns Whether post run hook has completed.\n */\nexport function postRunHookHasCompleted(): boolean {\n return postRunHookCompleted\n}\n\n/**\n * Wait for the postrun hook to finish (so auto-upgrade has a chance to run) and then\n * tree-kill the current process tree before exiting.\n *\n * Long-running interactive commands like `app dev` need this when the user terminates\n * the command via `q` or Ctrl+C. The dev sub-processes such as servers and watchers keep\n * the event loop alive, so even after oclif's postrun hook completes the node process\n * won't exit on its own and we have to `treeKill` the process tree. We must not do that\n * before the postrun hook has actually finished running auto-upgrade, otherwise we would\n * kill the upgrade mid-way while `npm install` is still running.\n *\n * The flag `postRunHookCompleted` is flipped at the very end of the hook after\n * `autoUpgradeIfNeeded` resolves, so polling it here is safe.\n */\nexport function waitForPostRunHookAndExit(): void {\n const pollIntervalMs = 100\n // Auto-upgrade can take a while (npm/pnpm/yarn install). Cap the wait generously so\n // a stuck upgrade still terminates the process eventually.\n const maxWaitMs = 120000\n\n let elapsed = 0\n let terminating = false\n const handle = setInterval(() => {\n if (terminating) return\n if (postRunHookHasCompleted() || elapsed >= maxWaitMs) {\n terminating = true\n clearInterval(handle)\n treeKill(process.pid, 'SIGINT', false, () => {\n process.exit(0)\n })\n return\n }\n elapsed += pollIntervalMs\n }, pollIntervalMs)\n}\n\n// This hook is called after each successful command run. More info: https://oclif.io/docs/hooks\nexport const hook: Hook.Postrun = async ({config, Command}) => {\n await detectStopCommand(Command as unknown as typeof Command)\n\n const {reportAnalyticsEvent} = await import('../analytics.js')\n await reportAnalyticsEvent({config, exitMode: 'ok'})\n\n const {postrun: deprecationsHook} = await import('./deprecations.js')\n deprecationsHook(Command)\n\n const {outputDebug} = await import('../output.js')\n const command = Command.id.replace(/:/g, ' ')\n outputDebug(`Completed command ${command}`)\n\n if (!command.includes('notifications') && !command.includes('upgrade')) await autoUpgradeIfNeeded()\n postRunHookCompleted = true\n}\n\n/**\n * Auto-upgrades the CLI after a command completes, if a newer version is available.\n * The entire flow is rate-limited to once per day unless forced via SHOPIFY_CLI_FORCE_AUTO_UPGRADE.\n *\n * @returns Resolves when the upgrade attempt (or fallback warning) is complete.\n */\nexport async function autoUpgradeIfNeeded(): Promise<void> {\n const {versionToAutoUpgrade, warnIfUpgradeAvailable} = await import('../upgrade.js')\n const newerVersion = versionToAutoUpgrade()\n if (!newerVersion) {\n await warnIfUpgradeAvailable()\n return\n }\n\n const forced = process.env.SHOPIFY_CLI_FORCE_AUTO_UPGRADE === '1'\n\n // SHOPIFY_CLI_FORCE_AUTO_UPGRADE bypasses the daily rate limit so tests and intentional upgrades always run.\n if (forced) {\n await performAutoUpgrade(newerVersion)\n } else {\n const {runAtMinimumInterval} = await import('../../../private/node/conf-store.js')\n // Rate-limit the entire upgrade flow to once per day to avoid repeated attempts and major-version warnings.\n await runAtMinimumInterval('auto-upgrade', {days: 1}, async () => {\n await performAutoUpgrade(newerVersion)\n })\n }\n}\n\nasync function performAutoUpgrade(newerVersion: string): Promise<void> {\n const [\n {CLI_KIT_VERSION},\n {isMajorVersionChange},\n {outputWarn, outputDebug},\n {getOutputUpdateCLIReminder, runCLIUpgrade, hasBlockingAutoUpgradeNotification},\n metadata,\n ] = await Promise.all([\n import('../../common/version.js'),\n import('../version.js'),\n import('../output.js'),\n import('../upgrade.js'),\n import('../metadata.js'),\n ])\n\n if (isMajorVersionChange(CLI_KIT_VERSION, newerVersion)) {\n outputWarn(getOutputUpdateCLIReminder(newerVersion, true))\n await metadata.addPublicMetadata(() => ({\n env_auto_upgrade_skipped_reason: 'major_version',\n }))\n return\n }\n\n // Notification kill switch: an `error`-type notification on the `autoupgrade` surface\n // silently disables auto-upgrade. Checked last — after every other gate, including the\n // daily rate limit and the major-version check — so the network fetch only happens when\n // we're about to actually run the upgrade.\n if (await hasBlockingAutoUpgradeNotification()) {\n await metadata.addPublicMetadata(() => ({\n env_auto_upgrade_skipped_reason: 'blocked_by_notification',\n }))\n return\n }\n\n try {\n await runCLIUpgrade({autoupgrade: true})\n await metadata.addPublicMetadata(() => ({env_auto_upgrade_success: true}))\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n const errorMessage = `Auto-upgrade failed: ${error}`\n outputDebug(errorMessage)\n outputWarn(getOutputUpdateCLIReminder(newerVersion))\n await metadata.addPublicMetadata(() => ({env_auto_upgrade_success: false}))\n // Report to Observe as a handled error without showing anything extra to the user\n const [{sendErrorToBugsnag}, {inferPackageManagerForGlobalCLI}] = await Promise.all([\n import('../error-handler.js'),\n import('../is-global.js'),\n ])\n const enrichedError = Object.assign(new Error(errorMessage), {\n packageManager: inferPackageManagerForGlobalCLI(),\n platform: process.platform,\n cliVersion: CLI_KIT_VERSION,\n })\n await sendErrorToBugsnag(enrichedError, 'expected_error')\n }\n}\n\n/**\n * Override the command name with the stop one for analytics purposes.\n *\n * @param commandClass - Command.Class.\n */\nasync function detectStopCommand(commandClass: Command.Class): Promise<void> {\n const currentTime = new Date().getTime()\n // Check for analyticsStopCommand without importing BaseCommand\n if (\n commandClass &&\n 'analyticsStopCommand' in commandClass &&\n typeof commandClass.analyticsStopCommand === 'function'\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const stopCommand = (commandClass as any).analyticsStopCommand()\n if (stopCommand) {\n const metadata = await import('../metadata.js')\n const {commandStartOptions} = metadata.getAllSensitiveMetadata()\n if (!commandStartOptions) return\n await metadata.addSensitiveMetadata(() => ({\n commandStartOptions: {\n ...commandStartOptions,\n startTime: currentTime,\n startCommand: stopCommand,\n },\n }))\n }\n }\n}\n"]}
1
+ {"version":3,"file":"postrun.js","sourceRoot":"","sources":["../../../../src/public/node/hooks/postrun.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAC,QAAQ,EAAC,MAAM,iBAAiB,CAAA;AAGxC,IAAI,oBAAoB,GAAG,KAAK,CAAA;AAEhC;;;;GAIG;AACH,MAAM,UAAU,uBAAuB;IACrC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E,IAAI,WAAW,EAAE,CAAC;YAChB,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,gBAAgB,CAAC,CAAA;YAC/C,MAAM,EAAC,mBAAmB,EAAC,GAAG,QAAQ,CAAC,uBAAuB,EAAE,CAAA;YAChE,IAAI,CAAC,mBAAmB;gBAAE,OAAM;YAChC,MAAM,QAAQ,CAAC,oBAAoB,CAAC,GAAG,EAAE,CAAC,CAAC;gBACzC,mBAAmB,EAAE;oBACnB,GAAG,mBAAmB;oBACtB,SAAS,EAAE,WAAW;oBACtB,YAAY,EAAE,WAAW;iBAC1B;aACF,CAAC,CAAC,CAAA;QACL,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/**\n * Postrun hook — uses dynamic imports to avoid loading heavy modules (base-command, analytics)\n * at module evaluation time. These are only needed after the command has already finished.\n */\nimport {treeKill} from '../tree-kill.js'\nimport {Command, Hook} from '@oclif/core'\n\nlet postRunHookCompleted = false\n\n/**\n * Check if post run hook has completed.\n *\n * @returns Whether post run hook has completed.\n */\nexport function postRunHookHasCompleted(): boolean {\n return postRunHookCompleted\n}\n\n/**\n * Wait for the postrun hook to finish (so auto-upgrade has a chance to run) and then\n * tree-kill the current process tree before exiting.\n *\n * Long-running interactive commands like `app dev` need this when the user terminates\n * the command via `q` or Ctrl+C. The dev sub-processes such as servers and watchers keep\n * the event loop alive, so even after oclif's postrun hook completes the node process\n * won't exit on its own and we have to `treeKill` the process tree. We must not do that\n * before the postrun hook has actually finished running auto-upgrade, otherwise we would\n * kill the upgrade mid-way while `npm install` is still running.\n *\n * The flag `postRunHookCompleted` is flipped at the very end of the hook after\n * `autoUpgradeIfNeeded` resolves, so polling it here is safe.\n */\nexport function waitForPostRunHookAndExit(): void {\n const pollIntervalMs = 100\n // Auto-upgrade can take a while (npm/pnpm/yarn install). Cap the wait generously so\n // a stuck upgrade still terminates the process eventually.\n const maxWaitMs = 120000\n\n let elapsed = 0\n let terminating = false\n const handle = setInterval(() => {\n if (terminating) return\n if (postRunHookHasCompleted() || elapsed >= maxWaitMs) {\n terminating = true\n clearInterval(handle)\n treeKill(process.pid, 'SIGINT', false, () => {\n process.exit(0)\n })\n return\n }\n elapsed += pollIntervalMs\n }, pollIntervalMs)\n}\n\n// This hook is called after each successful command run. More info: https://oclif.io/docs/hooks\nexport const hook: Hook.Postrun = async ({config, Command}) => {\n await detectStopCommand(Command as unknown as typeof Command)\n\n const metadata = await import('../metadata.js')\n const {commandStartOptions} = metadata.getAllSensitiveMetadata()\n if (commandStartOptions) {\n await metadata.addSensitiveMetadata(() => ({\n commandStartOptions: {\n ...commandStartOptions,\n endTime: new Date().getTime(),\n },\n }))\n }\n\n const {postrun: deprecationsHook} = await import('./deprecations.js')\n deprecationsHook(Command)\n\n const {outputDebug} = await import('../output.js')\n const command = Command.id.replace(/:/g, ' ')\n outputDebug(`Completed command ${command}`)\n\n if (!command.includes('notifications') && !command.includes('upgrade')) await autoUpgradeIfNeeded()\n\n const {reportAnalyticsEvent} = await import('../analytics.js')\n await reportAnalyticsEvent({config, exitMode: 'ok'})\n\n postRunHookCompleted = true\n}\n\n/**\n * Auto-upgrades the CLI after a command completes, if a newer version is available.\n * The entire flow is rate-limited to once per day unless forced via SHOPIFY_CLI_FORCE_AUTO_UPGRADE.\n *\n * @returns Resolves when the upgrade attempt (or fallback warning) is complete.\n */\nexport async function autoUpgradeIfNeeded(): Promise<void> {\n const {versionToAutoUpgrade, warnIfUpgradeAvailable} = await import('../upgrade.js')\n const newerVersion = versionToAutoUpgrade()\n if (!newerVersion) {\n await warnIfUpgradeAvailable()\n return\n }\n\n const forced = process.env.SHOPIFY_CLI_FORCE_AUTO_UPGRADE === '1'\n\n // SHOPIFY_CLI_FORCE_AUTO_UPGRADE bypasses the daily rate limit so tests and intentional upgrades always run.\n if (forced) {\n await performAutoUpgrade(newerVersion)\n } else {\n const {runAtMinimumInterval} = await import('../../../private/node/conf-store.js')\n // Rate-limit the entire upgrade flow to once per day to avoid repeated attempts and major-version warnings.\n await runAtMinimumInterval('auto-upgrade', {days: 1}, async () => {\n await performAutoUpgrade(newerVersion)\n })\n }\n}\n\nasync function performAutoUpgrade(newerVersion: string): Promise<void> {\n const [\n {CLI_KIT_VERSION},\n {isMajorVersionChange},\n {outputWarn, outputDebug},\n {getOutputUpdateCLIReminder, runCLIUpgrade, hasBlockingAutoUpgradeNotification},\n metadata,\n ] = await Promise.all([\n import('../../common/version.js'),\n import('../version.js'),\n import('../output.js'),\n import('../upgrade.js'),\n import('../metadata.js'),\n ])\n\n if (isMajorVersionChange(CLI_KIT_VERSION, newerVersion)) {\n outputWarn(getOutputUpdateCLIReminder(newerVersion, true))\n await metadata.addPublicMetadata(() => ({\n env_auto_upgrade_skipped_reason: 'major_version',\n }))\n return\n }\n\n // Notification kill switch: an `error`-type notification on the `autoupgrade` surface\n // silently disables auto-upgrade. Checked last — after every other gate, including the\n // daily rate limit and the major-version check — so the network fetch only happens when\n // we're about to actually run the upgrade.\n if (await hasBlockingAutoUpgradeNotification()) {\n await metadata.addPublicMetadata(() => ({\n env_auto_upgrade_skipped_reason: 'blocked_by_notification',\n }))\n return\n }\n\n try {\n await runCLIUpgrade({autoupgrade: true})\n await metadata.addPublicMetadata(() => ({env_auto_upgrade_success: true}))\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n const errorMessage = `Auto-upgrade failed: ${error}`\n outputDebug(errorMessage)\n outputWarn(getOutputUpdateCLIReminder(newerVersion))\n await metadata.addPublicMetadata(() => ({env_auto_upgrade_success: false}))\n // Report to Observe as a handled error without showing anything extra to the user\n const [{sendErrorToBugsnag}, {inferPackageManagerForGlobalCLI}] = await Promise.all([\n import('../error-handler.js'),\n import('../is-global.js'),\n ])\n const enrichedError = Object.assign(new Error(errorMessage), {\n packageManager: inferPackageManagerForGlobalCLI(),\n platform: process.platform,\n cliVersion: CLI_KIT_VERSION,\n })\n await sendErrorToBugsnag(enrichedError, 'expected_error')\n }\n}\n\n/**\n * Override the command name with the stop one for analytics purposes.\n *\n * @param commandClass - Command.Class.\n */\nasync function detectStopCommand(commandClass: Command.Class): Promise<void> {\n const currentTime = new Date().getTime()\n // Check for analyticsStopCommand without importing BaseCommand\n if (\n commandClass &&\n 'analyticsStopCommand' in commandClass &&\n typeof commandClass.analyticsStopCommand === 'function'\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const stopCommand = (commandClass as any).analyticsStopCommand()\n if (stopCommand) {\n const metadata = await import('../metadata.js')\n const {commandStartOptions} = metadata.getAllSensitiveMetadata()\n if (!commandStartOptions) return\n await metadata.addSensitiveMetadata(() => ({\n commandStartOptions: {\n ...commandStartOptions,\n startTime: currentTime,\n startCommand: stopCommand,\n },\n }))\n }\n }\n}\n"]}
@@ -9,6 +9,7 @@ import { simpleRequestWithDebugLog } from '../../private/node/api.js';
9
9
  import { DEFAULT_MAX_TIME_MS } from '../../private/node/sleep-with-backoff.js';
10
10
  import FormData from 'form-data';
11
11
  import nodeFetch from 'node-fetch';
12
+ import { pipeline } from 'stream/promises';
12
13
  export { FetchError, Request, Response } from 'node-fetch';
13
14
  /**
14
15
  * Create a new FormData object.
@@ -170,39 +171,34 @@ export async function shopifyFetch(url, init, preferredBehaviour) {
170
171
  export function downloadFile(url, to) {
171
172
  const sanitizedUrl = sanitizeURL(url);
172
173
  outputDebug(`Downloading ${sanitizedUrl} to ${to}`);
173
- return runWithTimer('cmd_all_timing_network_ms')(() => {
174
- return new Promise((resolve, reject) => {
175
- if (!fileExistsSync(dirname(to))) {
176
- mkdirSync(dirname(to));
177
- }
178
- const file = createFileWriteStream(to);
179
- // if we can't remove the file for some reason (seen on windows), that's ok -- it's in a temporary directory
180
- const tryToRemoveFile = () => {
181
- try {
174
+ return runWithTimer('cmd_all_timing_network_ms')(async () => {
175
+ if (!fileExistsSync(dirname(to))) {
176
+ mkdirSync(dirname(to));
177
+ }
178
+ // if we can't remove the file for some reason (seen on windows), that's ok -- it's in a temporary directory
179
+ const tryToRemoveFile = () => {
180
+ try {
181
+ if (fileExistsSync(to)) {
182
182
  unlinkFileSync(to);
183
- // eslint-disable-next-line no-catch-all/no-catch-all
184
183
  }
185
- catch (err) {
186
- outputDebug(outputContent `Failed to remove file ${outputToken.path(to)}: ${outputToken.raw(String(err))}`);
187
- }
188
- };
189
- file.on('finish', () => {
190
- file.close();
191
- resolve(to);
192
- });
193
- file.on('error', (err) => {
194
- tryToRemoveFile();
195
- reject(err);
196
- });
197
- nodeFetch(url, { redirect: 'follow' })
198
- .then((res) => {
199
- res.body?.pipe(file);
200
- })
201
- .catch((err) => {
202
- tryToRemoveFile();
203
- reject(err instanceof Error ? err : new Error(String(err)));
204
- });
205
- });
184
+ // eslint-disable-next-line no-catch-all/no-catch-all
185
+ }
186
+ catch (err) {
187
+ outputDebug(outputContent `Failed to remove file ${outputToken.path(to)}: ${outputToken.raw(String(err))}`);
188
+ }
189
+ };
190
+ try {
191
+ const res = await nodeFetch(url, { redirect: 'follow' });
192
+ if (!res.body) {
193
+ throw new Error(`No response body received when downloading ${sanitizedUrl}`);
194
+ }
195
+ await pipeline(res.body, createFileWriteStream(to));
196
+ return to;
197
+ }
198
+ catch (err) {
199
+ tryToRemoveFile();
200
+ throw err instanceof Error ? err : new Error(String(err));
201
+ }
206
202
  });
207
203
  }
208
204
  //# sourceMappingURL=http.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"http.js","sourceRoot":"","sources":["../../../src/public/node/http.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,OAAO,EAAC,MAAM,WAAW,CAAA;AACjC,OAAO,EAAC,qBAAqB,EAAE,cAAc,EAAE,SAAS,EAAE,cAAc,EAAC,MAAM,SAAS,CAAA;AACxF,OAAO,EAAC,YAAY,EAAC,MAAM,eAAe,CAAA;AAC1C,OAAO,EAAC,+BAA+B,EAAE,qBAAqB,EAAC,MAAM,kBAAkB,CAAA;AACvF,OAAO,EAAC,aAAa,EAAE,WAAW,EAAE,WAAW,EAAC,MAAM,aAAa,CAAA;AACnE,OAAO,EAAC,WAAW,EA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,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;YAC7D,CAAC,CAAC,CAAA;QACN,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import {dirname} from './path.js'\nimport {createFileWriteStream, fileExistsSync, mkdirSync, unlinkFileSync} from './fs.js'\nimport {runWithTimer} from './metadata.js'\nimport {maxRequestTimeForNetworkCallsMs, skipNetworkLevelRetry} from './environment.js'\nimport {outputContent, outputDebug, outputToken} from './output.js'\nimport {sanitizeURL} from '../../private/node/api/urls.js'\nimport {httpsAgent, sanitizedHeadersOutput} from '../../private/node/api/headers.js'\nimport {NetworkRetryBehaviour, simpleRequestWithDebugLog} from '../../private/node/api.js'\nimport {DEFAULT_MAX_TIME_MS} from '../../private/node/sleep-with-backoff.js'\n\nimport FormData from 'form-data'\nimport nodeFetch, {RequestInfo, RequestInit, Response} from 'node-fetch'\n\nexport {FetchError, Request, Response} from 'node-fetch'\n\n/**\n * Create a new FormData object.\n *\n * @returns A FormData object.\n */\nexport function formData(): FormData {\n return new FormData()\n}\n\ntype AbortSignal = RequestInit['signal']\n\ntype PresetFetchBehaviour = 'default' | 'non-blocking' | 'slow-request'\n\ntype AutomaticCancellationBehaviour =\n | {\n useAbortSignal: true\n timeoutMs: number\n }\n | {\n useAbortSignal: false\n }\n | {\n useAbortSignal: AbortSignal | (() => AbortSignal)\n }\n\nexport type RequestBehaviour = NetworkRetryBehaviour & AutomaticCancellationBehaviour\n\nexport type RequestModeInput = PresetFetchBehaviour | RequestBehaviour\n\n/**\n * Specify the behaviour of a network request.\n *\n * - default: Requests are automatically retried, and are subject to automatic cancellation if they're taking too long.\n * This is generally desirable.\n * - non-blocking: Requests are not retried if they fail with a network error, and are automatically cancelled if\n * they're taking too long. This is good for throwaway requests, like polling or tracking.\n * - slow-request: Requests are not retried if they fail with a network error, and are not automatically cancelled.\n * This is good for slow requests that should be give the chance to complete, and are unlikely to be safe to retry.\n *\n * Some request behaviours may be de-activated by the environment, and this function takes care of that concern. You\n * can also provide a customised request behaviour.\n *\n * @param preset - The preset to use.\n * @param env - Process environment variables.\n * @returns A request behaviour object.\n */\nexport function requestMode(\n preset: RequestModeInput = 'default',\n env: NodeJS.ProcessEnv = process.env,\n): RequestBehaviour {\n const networkLevelRetryIsSupported = !skipNetworkLevelRetry(env)\n switch (preset) {\n case 'default':\n return {\n useNetworkLevelRetry: networkLevelRetryIsSupported,\n maxRetryTimeMs: DEFAULT_MAX_TIME_MS,\n useAbortSignal: true,\n timeoutMs: maxRequestTimeForNetworkCallsMs(env),\n }\n case 'non-blocking':\n return {\n useNetworkLevelRetry: false,\n useAbortSignal: true,\n timeoutMs: maxRequestTimeForNetworkCallsMs(env),\n }\n case 'slow-request':\n return {\n useNetworkLevelRetry: false,\n useAbortSignal: false,\n }\n }\n return {\n ...preset,\n useNetworkLevelRetry: networkLevelRetryIsSupported && preset.useNetworkLevelRetry,\n } as RequestBehaviour\n}\n\ninterface FetchOptions {\n url: RequestInfo\n behaviour: RequestBehaviour\n init?: RequestInit\n logRequest: boolean\n useHttpsAgent: boolean\n}\n\n/**\n * Create an AbortSignal for automatic request cancellation, from a request behaviour.\n *\n * @param behaviour - The request behaviour.\n * @returns An AbortSignal.\n */\nexport function abortSignalFromRequestBehaviour(behaviour: RequestBehaviour): AbortSignal {\n let signal: AbortSignal\n if (behaviour.useAbortSignal === true) {\n signal = AbortSignal.timeout(behaviour.timeoutMs)\n } else if (behaviour.useAbortSignal && typeof behaviour.useAbortSignal === 'function') {\n signal = behaviour.useAbortSignal()\n } else if (behaviour.useAbortSignal) {\n signal = behaviour.useAbortSignal\n }\n return signal\n}\n\nasync function innerFetch({url, behaviour, init, logRequest, useHttpsAgent}: FetchOptions): Promise<Response> {\n if (logRequest) {\n outputDebug(outputContent`Sending ${init?.method ?? 'GET'} request to URL ${sanitizeURL(url.toString())}\nWith request headers:\n${sanitizedHeadersOutput((init?.headers ?? {}) as Record<string, string>)}\n`)\n }\n\n let agent: RequestInit['agent']\n if (useHttpsAgent) {\n agent = await httpsAgent()\n }\n\n const request = async () => {\n // each time we make the request, we need to potentially reset the abort signal, as the request logic may make\n // the same request multiple times.\n let signal = abortSignalFromRequestBehaviour(behaviour)\n\n // it's possible to provide a signal through the request's init structure.\n if (init?.signal) {\n signal = init.signal\n }\n\n return nodeFetch(url, {...init, agent, signal})\n }\n\n return runWithTimer('cmd_all_timing_network_ms')(async () => {\n return simpleRequestWithDebugLog({\n url: url.toString(),\n request,\n ...behaviour,\n })\n })\n}\n\n/**\n * An interface that abstracts way node-fetch. When Node has built-in\n * support for \"fetch\" in the standard library, we can drop the node-fetch\n * dependency from here.\n * Note that we are exposing types from \"node-fetch\". The reason being is that\n * they are consistent with the Web API so if we drop node-fetch in the future\n * it won't require changes from the callers.\n *\n * The CLI's fetch function supports special behaviours, like automatic retries. These are disabled by default through\n * this function.\n *\n * @param url - This defines the resource that you wish to fetch.\n * @param init - An object containing any custom settings that you want to apply to the request.\n * @param preferredBehaviour - A request behaviour object that overrides the default behaviour.\n * @returns A promise that resolves with the response.\n */\nexport async function fetch(\n url: RequestInfo,\n init?: RequestInit,\n preferredBehaviour?: RequestModeInput,\n): Promise<Response> {\n const options = {\n url,\n init,\n logRequest: false,\n useHttpsAgent: false,\n // all special behaviours are disabled by default\n behaviour: preferredBehaviour ? requestMode(preferredBehaviour) : requestMode('non-blocking'),\n } as const\n\n return innerFetch(options)\n}\n\n/**\n * A fetch function to use with Shopify services. The function ensures the right\n * TLS configuragion is used based on the environment in which the service is running\n * (e.g. Local). NB: headers/auth are the responsibility of the caller.\n *\n * By default, the CLI's fetch function's special behaviours, like automatic retries, are enabled.\n *\n * @param url - This defines the resource that you wish to fetch.\n * @param init - An object containing any custom settings that you want to apply to the request.\n * @param preferredBehaviour - A request behaviour object that overrides the default behaviour.\n * @returns A promise that resolves with the response.\n */\nexport async function shopifyFetch(\n url: RequestInfo,\n init?: RequestInit,\n preferredBehaviour?: RequestModeInput,\n): Promise<Response> {\n const options = {\n url,\n init,\n logRequest: true,\n useHttpsAgent: true,\n // special behaviours enabled by default\n behaviour: preferredBehaviour ? requestMode(preferredBehaviour) : requestMode(),\n }\n\n return innerFetch(options)\n}\n\n/**\n * Download a file from a URL to a local path.\n *\n * @param url - The URL to download from.\n * @param to - The local path to download to.\n * @returns - A promise that resolves with the local path.\n */\nexport function downloadFile(url: string, to: string): Promise<string> {\n const sanitizedUrl = sanitizeURL(url)\n outputDebug(`Downloading ${sanitizedUrl} to ${to}`)\n\n return runWithTimer('cmd_all_timing_network_ms')(() => {\n return new Promise<string>((resolve, reject) => {\n if (!fileExistsSync(dirname(to))) {\n mkdirSync(dirname(to))\n }\n\n const file = createFileWriteStream(to)\n\n // if we can't remove the file for some reason (seen on windows), that's ok -- it's in a temporary directory\n const tryToRemoveFile = () => {\n try {\n unlinkFileSync(to)\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (err: unknown) {\n outputDebug(outputContent`Failed to remove file ${outputToken.path(to)}: ${outputToken.raw(String(err))}`)\n }\n }\n\n file.on('finish', () => {\n file.close()\n resolve(to)\n })\n\n file.on('error', (err) => {\n tryToRemoveFile()\n reject(err)\n })\n\n nodeFetch(url, {redirect: 'follow'})\n .then((res) => {\n res.body?.pipe(file)\n })\n .catch((err) => {\n tryToRemoveFile()\n reject(err instanceof Error ? err : new Error(String(err)))\n })\n })\n })\n}\n"]}
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../../../src/public/node/http.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,OAAO,EAAC,MAAM,WAAW,CAAA;AACjC,OAAO,EAAC,qBAAqB,EAAE,cAAc,EAAE,SAAS,EAAE,cAAc,EAAC,MAAM,SAAS,CAAA;AACxF,OAAO,EAAC,YAAY,EAAC,MAAM,eAAe,CAAA;AAC1C,OAAO,EAAC,+BAA+B,EAAE,qBAAqB,EAAC,MAAM,kBAAkB,CAAA;AACvF,OAAO,EAAC,aAAa,EAA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A;AACJ,CAAC","sourcesContent":["import {dirname} from './path.js'\nimport {createFileWriteStream, fileExistsSync, mkdirSync, unlinkFileSync} from './fs.js'\nimport {runWithTimer} from './metadata.js'\nimport {maxRequestTimeForNetworkCallsMs, skipNetworkLevelRetry} from './environment.js'\nimport {outputContent, outputDebug, outputToken} from './output.js'\nimport {sanitizeURL} from '../../private/node/api/urls.js'\nimport {httpsAgent, sanitizedHeadersOutput} from '../../private/node/api/headers.js'\nimport {NetworkRetryBehaviour, simpleRequestWithDebugLog} from '../../private/node/api.js'\nimport {DEFAULT_MAX_TIME_MS} from '../../private/node/sleep-with-backoff.js'\n\nimport FormData from 'form-data'\nimport nodeFetch, {RequestInfo, RequestInit, Response} from 'node-fetch'\nimport {pipeline} from 'stream/promises'\n\nexport {FetchError, Request, Response} from 'node-fetch'\n\n/**\n * Create a new FormData object.\n *\n * @returns A FormData object.\n */\nexport function formData(): FormData {\n return new FormData()\n}\n\ntype AbortSignal = RequestInit['signal']\n\ntype PresetFetchBehaviour = 'default' | 'non-blocking' | 'slow-request'\n\ntype AutomaticCancellationBehaviour =\n | {\n useAbortSignal: true\n timeoutMs: number\n }\n | {\n useAbortSignal: false\n }\n | {\n useAbortSignal: AbortSignal | (() => AbortSignal)\n }\n\nexport type RequestBehaviour = NetworkRetryBehaviour & AutomaticCancellationBehaviour\n\nexport type RequestModeInput = PresetFetchBehaviour | RequestBehaviour\n\n/**\n * Specify the behaviour of a network request.\n *\n * - default: Requests are automatically retried, and are subject to automatic cancellation if they're taking too long.\n * This is generally desirable.\n * - non-blocking: Requests are not retried if they fail with a network error, and are automatically cancelled if\n * they're taking too long. This is good for throwaway requests, like polling or tracking.\n * - slow-request: Requests are not retried if they fail with a network error, and are not automatically cancelled.\n * This is good for slow requests that should be give the chance to complete, and are unlikely to be safe to retry.\n *\n * Some request behaviours may be de-activated by the environment, and this function takes care of that concern. You\n * can also provide a customised request behaviour.\n *\n * @param preset - The preset to use.\n * @param env - Process environment variables.\n * @returns A request behaviour object.\n */\nexport function requestMode(\n preset: RequestModeInput = 'default',\n env: NodeJS.ProcessEnv = process.env,\n): RequestBehaviour {\n const networkLevelRetryIsSupported = !skipNetworkLevelRetry(env)\n switch (preset) {\n case 'default':\n return {\n useNetworkLevelRetry: networkLevelRetryIsSupported,\n maxRetryTimeMs: DEFAULT_MAX_TIME_MS,\n useAbortSignal: true,\n timeoutMs: maxRequestTimeForNetworkCallsMs(env),\n }\n case 'non-blocking':\n return {\n useNetworkLevelRetry: false,\n useAbortSignal: true,\n timeoutMs: maxRequestTimeForNetworkCallsMs(env),\n }\n case 'slow-request':\n return {\n useNetworkLevelRetry: false,\n useAbortSignal: false,\n }\n }\n return {\n ...preset,\n useNetworkLevelRetry: networkLevelRetryIsSupported && preset.useNetworkLevelRetry,\n } as RequestBehaviour\n}\n\ninterface FetchOptions {\n url: RequestInfo\n behaviour: RequestBehaviour\n init?: RequestInit\n logRequest: boolean\n useHttpsAgent: boolean\n}\n\n/**\n * Create an AbortSignal for automatic request cancellation, from a request behaviour.\n *\n * @param behaviour - The request behaviour.\n * @returns An AbortSignal.\n */\nexport function abortSignalFromRequestBehaviour(behaviour: RequestBehaviour): AbortSignal {\n let signal: AbortSignal\n if (behaviour.useAbortSignal === true) {\n signal = AbortSignal.timeout(behaviour.timeoutMs)\n } else if (behaviour.useAbortSignal && typeof behaviour.useAbortSignal === 'function') {\n signal = behaviour.useAbortSignal()\n } else if (behaviour.useAbortSignal) {\n signal = behaviour.useAbortSignal\n }\n return signal\n}\n\nasync function innerFetch({url, behaviour, init, logRequest, useHttpsAgent}: FetchOptions): Promise<Response> {\n if (logRequest) {\n outputDebug(outputContent`Sending ${init?.method ?? 'GET'} request to URL ${sanitizeURL(url.toString())}\nWith request headers:\n${sanitizedHeadersOutput((init?.headers ?? {}) as Record<string, string>)}\n`)\n }\n\n let agent: RequestInit['agent']\n if (useHttpsAgent) {\n agent = await httpsAgent()\n }\n\n const request = async () => {\n // each time we make the request, we need to potentially reset the abort signal, as the request logic may make\n // the same request multiple times.\n let signal = abortSignalFromRequestBehaviour(behaviour)\n\n // it's possible to provide a signal through the request's init structure.\n if (init?.signal) {\n signal = init.signal\n }\n\n return nodeFetch(url, {...init, agent, signal})\n }\n\n return runWithTimer('cmd_all_timing_network_ms')(async () => {\n return simpleRequestWithDebugLog({\n url: url.toString(),\n request,\n ...behaviour,\n })\n })\n}\n\n/**\n * An interface that abstracts way node-fetch. When Node has built-in\n * support for \"fetch\" in the standard library, we can drop the node-fetch\n * dependency from here.\n * Note that we are exposing types from \"node-fetch\". The reason being is that\n * they are consistent with the Web API so if we drop node-fetch in the future\n * it won't require changes from the callers.\n *\n * The CLI's fetch function supports special behaviours, like automatic retries. These are disabled by default through\n * this function.\n *\n * @param url - This defines the resource that you wish to fetch.\n * @param init - An object containing any custom settings that you want to apply to the request.\n * @param preferredBehaviour - A request behaviour object that overrides the default behaviour.\n * @returns A promise that resolves with the response.\n */\nexport async function fetch(\n url: RequestInfo,\n init?: RequestInit,\n preferredBehaviour?: RequestModeInput,\n): Promise<Response> {\n const options = {\n url,\n init,\n logRequest: false,\n useHttpsAgent: false,\n // all special behaviours are disabled by default\n behaviour: preferredBehaviour ? requestMode(preferredBehaviour) : requestMode('non-blocking'),\n } as const\n\n return innerFetch(options)\n}\n\n/**\n * A fetch function to use with Shopify services. The function ensures the right\n * TLS configuragion is used based on the environment in which the service is running\n * (e.g. Local). NB: headers/auth are the responsibility of the caller.\n *\n * By default, the CLI's fetch function's special behaviours, like automatic retries, are enabled.\n *\n * @param url - This defines the resource that you wish to fetch.\n * @param init - An object containing any custom settings that you want to apply to the request.\n * @param preferredBehaviour - A request behaviour object that overrides the default behaviour.\n * @returns A promise that resolves with the response.\n */\nexport async function shopifyFetch(\n url: RequestInfo,\n init?: RequestInit,\n preferredBehaviour?: RequestModeInput,\n): Promise<Response> {\n const options = {\n url,\n init,\n logRequest: true,\n useHttpsAgent: true,\n // special behaviours enabled by default\n behaviour: preferredBehaviour ? requestMode(preferredBehaviour) : requestMode(),\n }\n\n return innerFetch(options)\n}\n\n/**\n * Download a file from a URL to a local path.\n *\n * @param url - The URL to download from.\n * @param to - The local path to download to.\n * @returns - A promise that resolves with the local path.\n */\nexport function downloadFile(url: string, to: string): Promise<string> {\n const sanitizedUrl = sanitizeURL(url)\n outputDebug(`Downloading ${sanitizedUrl} to ${to}`)\n\n return runWithTimer('cmd_all_timing_network_ms')(async () => {\n if (!fileExistsSync(dirname(to))) {\n mkdirSync(dirname(to))\n }\n\n // if we can't remove the file for some reason (seen on windows), that's ok -- it's in a temporary directory\n const tryToRemoveFile = () => {\n try {\n if (fileExistsSync(to)) {\n unlinkFileSync(to)\n }\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (err: unknown) {\n outputDebug(outputContent`Failed to remove file ${outputToken.path(to)}: ${outputToken.raw(String(err))}`)\n }\n }\n\n try {\n const res = await nodeFetch(url, {redirect: 'follow'})\n if (!res.body) {\n throw new Error(`No response body received when downloading ${sanitizedUrl}`)\n }\n await pipeline(res.body, createFileWriteStream(to))\n return to\n } catch (err) {\n tryToRemoveFile()\n throw err instanceof Error ? err : new Error(String(err))\n }\n })\n}\n"]}
@@ -75,6 +75,22 @@ export function jsonSchemaValidate(subject, schema, handleInvalidAdditionalPrope
75
75
  rawErrors: undefined,
76
76
  };
77
77
  }
78
+ /**
79
+ * Get a more precise type name for JSON Schema error messages.
80
+ *
81
+ * @param value - The value to get the type of.
82
+ * @returns A string representing the type (e.g., 'array', 'null', 'object').
83
+ */
84
+ function getJsonSchemaValueType(value) {
85
+ if (Array.isArray(value))
86
+ return 'array';
87
+ if (value === null)
88
+ return 'null';
89
+ return typeof value;
90
+ }
91
+ function getJsonSchemaErrorValue(subject, path) {
92
+ return path.length === 0 ? subject : getPathValue(subject, path);
93
+ }
78
94
  /**
79
95
  * Converts errors from Ajv into a zod-like format.
80
96
  *
@@ -97,15 +113,15 @@ function convertJsonSchemaErrors(rawErrors, subject, schema) {
97
113
  const expectedType = Array.isArray(error.params.type)
98
114
  ? error.params.type.join(', ')
99
115
  : error.params.type;
100
- const actualType = getPathValue(subject, path.join('.'));
101
- return { path, message: `Expected ${expectedType}, received ${typeof actualType}` };
116
+ const actualType = getJsonSchemaErrorValue(subject, path);
117
+ return { path, message: `Expected ${expectedType}, received ${getJsonSchemaValueType(actualType)}` };
102
118
  }
103
119
  if (error.keyword === 'anyOf' || error.keyword === 'oneOf') {
104
120
  return { path, message: 'Invalid input' };
105
121
  }
106
122
  if (error.params.allowedValues) {
107
123
  const allowedValues = error.params.allowedValues;
108
- const actualValue = getPathValue(subject, path.join('.'));
124
+ const actualValue = getJsonSchemaErrorValue(subject, path);
109
125
  return {
110
126
  path,
111
127
  message: `Invalid enum value. Expected ${allowedValues
@@ -116,7 +132,7 @@ function convertJsonSchemaErrors(rawErrors, subject, schema) {
116
132
  if (error.params.comparison) {
117
133
  const comparison = error.params.comparison;
118
134
  const limit = error.params.limit;
119
- const actualValue = getPathValue(subject, path.join('.'));
135
+ const actualValue = getJsonSchemaErrorValue(subject, path);
120
136
  let comparisonText = comparison;
121
137
  switch (comparison) {
122
138
  case '<=':
@@ -190,7 +206,7 @@ function simplifyUnionErrors(rawErrors, subject, schema) {
190
206
  const dottedSchemaPath = unionError.schemaPath.replace('#/', '').replace(/\//g, '.');
191
207
  const unionSchemas = getPathValue(schema, dottedSchemaPath);
192
208
  // and the slice of the subject that caused the issue
193
- const subjectValue = getPathValue(subject, unionError.instancePath.split('/').slice(1).join('.'));
209
+ const subjectValue = getJsonSchemaErrorValue(subject, unionError.instancePath.split('/').slice(1));
194
210
  if (unionSchemas !== undefined && subjectValue !== undefined) {
195
211
  // we know that none of the union schemas are correct, but for each of them we can measure how wrong they are
196
212
  const correctValuesAndErrors = unionSchemas
@@ -203,7 +219,7 @@ function simplifyUnionErrors(rawErrors, subject, schema) {
203
219
  const candidatesObjectProperties = Object.keys(candidateSchemaFromUnion.properties);
204
220
  score = candidatesObjectProperties.reduce((acc, propertyName) => {
205
221
  const subSchema = candidateSchemaFromUnion.properties[propertyName];
206
- const subjectValueSlice = getPathValue(subjectValue, propertyName);
222
+ const subjectValueSlice = getJsonSchemaErrorValue(subjectValue, [propertyName]);
207
223
  const subValidator = createAjvValidator('fail', subSchema);
208
224
  if (subValidator(subjectValueSlice)) {
209
225
  return acc + 1;
@@ -1 +1 @@
1
- {"version":3,"file":"json-schema.js","sourceRoot":"","sources":["../../../src/public/node/json-schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,MAAM,aAAa,CAAA;AAEtC,OAAO,EAAC,YAAY,EAAC,MAAM,qBAAqB,CAAA;AAEhD,OAAO,EAAC,UAAU,EAAC,MAAM,qBAAqB,CAAA;AAC9C,OAAO,EAAC,GAAG,EAA8C,MAAM,KAAK,CAAA;AACpE,OAAO,UAAU,MAAM,qCAAqC,CAAA;AAC5D,OAAO,SAAS,MAAM,qBAAqB,CAAA;AAM3C;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CAAC,MAAc;IACtD,0FAA0F;IAC1F,MAAM,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;IACvC,MAAM,UAAU,CAAC,WAAW,CAAC,YAAY,EAAE,EAAC,OAAO,EAAE,EAAC,QAAQ,EAAE,KAAK,EAAC,EAAC,CAAC,CAAA;IACxE,OAAO,YAAY,CAAA;AACrB,CAAC;AAED,SAAS,kBAAkB,CACzB,iCAAoE,EACpE,MAAoB;IAEpB,kEAAkE;IAClE,IAAI,iCAAiC,KAAK,OAAO,EAAE,CAAC;QAClD,gFAAgF;QAChF,MAAM,CAAC,oBAAoB,GAAG,IAAI,CAAA;IACpC,CAAC;IAED,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,EAAC,eAAe,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAC,CAAC,CAAA;IAC5E,GAAG,CAAC,UAAU,CAAC,SAAS,CAAC,CAAA;IAE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+EAA+E;oBAC/E,4BAA4B,GAAG;wBAC7B,UAAU;wBACV,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;4BAChC,GAAG,SAAS;4BACZ,YAAY,EAAE,UAAU,CAAC,YAAY,GAAG,SAAS,CAAC,YAAY;yBAC/D,CAAC,CAAC;qBACJ,CAAA;gBACH,CAAC;YACH,CAAC;QACH,CAAC;QACD,MAAM,GAAG,CAAC,GAAG,eAAe,EAAE,GAAG,4BAA4B,CAAC,CAAA;QAE9D,mBAAmB,CAAC,GAAG,CAAC,UAAU,CAAC,YAAY,CAAC,CAAA;IAClD,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import {randomUUID} from './crypto.js'\nimport {ParseConfigurationResult} from './schema.js'\nimport {getPathValue} from '../common/object.js'\n\nimport {capitalize} from '../common/string.js'\nimport {Ajv, ErrorObject, SchemaObject, ValidateFunction} from 'ajv'\nimport $RefParser from '@apidevtools/json-schema-ref-parser'\nimport cloneDeep from 'lodash/cloneDeep.js'\n\nexport type HandleInvalidAdditionalProperties = 'strip' | 'fail'\n\ntype AjvError = ErrorObject<string, Record<string, unknown>>\n\n/**\n * Normalises a JSON Schema by standardising it's internal implementation.\n *\n * We prefer to not use $ref elements in our schemas, so we inline them; it's easier then to process errors.\n *\n * @param schema - The JSON schema (as a string) to normalise.\n * @returns The normalised JSON schema.\n */\nexport async function normaliseJsonSchema(schema: string): Promise<SchemaObject> {\n // we want to modify the schema, removing any $ref elements and inlining with their source\n const parsedSchema = JSON.parse(schema)\n await $RefParser.dereference(parsedSchema, {resolve: {external: false}})\n return parsedSchema\n}\n\nfunction createAjvValidator(\n handleInvalidAdditionalProperties: HandleInvalidAdditionalProperties,\n schema: SchemaObject,\n) {\n // allowUnionTypes: Allows types like `type: [\"string\", \"number\"]`\n if (handleInvalidAdditionalProperties === 'strip') {\n // we need to let additional properties through, so that we can strip them later\n schema.additionalProperties = true\n }\n\n const ajv = new Ajv({allowUnionTypes: true, allErrors: true, verbose: true})\n ajv.addKeyword('x-taplo')\n\n const validator = ajv.compile(schema)\n\n return validator\n}\n\nconst validatorsCache = new Map<string, ValidateFunction>()\n\n/**\n * Given a subject object and a JSON schema contract, validate the subject against the contract.\n *\n * Errors are returned in a zod-like format, and processed to better handle unions.\n *\n * @param subject - The object to validate.\n * @param schema - The JSON schema to validate against.\n * @param handleInvalidAdditionalProperties - Whether to strip or fail on invalid additional properties.\n * @param identifier - The identifier of the schema being validated, used to cache the validator.\n * @returns The result of the validation. If the state is 'error', the errors will be in a zod-like format.\n */\nexport function jsonSchemaValidate(\n subject: object,\n schema: SchemaObject,\n handleInvalidAdditionalProperties: HandleInvalidAdditionalProperties,\n identifier?: string,\n): ParseConfigurationResult<unknown> & {rawErrors?: AjvError[]} {\n const subjectToModify = cloneDeep(subject)\n\n const cacheKey = identifier ?? randomUUID()\n\n const validator = validatorsCache.get(cacheKey) ?? createAjvValidator(handleInvalidAdditionalProperties, schema)\n validatorsCache.set(cacheKey, validator)\n\n validator(subjectToModify)\n\n // Errors from the contract are post-processed to be more zod-like and to deal with unions better\n let jsonSchemaErrors\n if (validator.errors && validator.errors.length > 0) {\n jsonSchemaErrors = convertJsonSchemaErrors(validator.errors, subjectToModify, schema)\n return {\n state: 'error',\n data: undefined,\n errors: jsonSchemaErrors,\n rawErrors: validator.errors,\n }\n }\n\n if (handleInvalidAdditionalProperties === 'strip') {\n const topLevelSchemaProperties = Object.keys(schema.properties ?? {})\n // strip any properties that are not in the top level schema from subjectToModify\n Object.keys(subjectToModify).forEach((key) => {\n if (!topLevelSchemaProperties.includes(key)) {\n // this isn't actually dynamic, because key came from Object.keys\n\n delete subjectToModify[key as keyof typeof subjectToModify]\n }\n })\n }\n\n return {\n state: 'ok',\n data: subjectToModify,\n errors: undefined,\n rawErrors: undefined,\n }\n}\n\n/**\n * Converts errors from Ajv into a zod-like format.\n *\n * @param rawErrors - JSON Schema errors taken directly from Ajv.\n * @param subject - The object being validated.\n * @param schema - The JSON schema to validated against.\n * @returns The errors in a zod-like format.\n */\nfunction convertJsonSchemaErrors(rawErrors: AjvError[], subject: object, schema: SchemaObject) {\n // This reduces the number of errors by simplifying errors coming from different branches of a union\n const errors = simplifyUnionErrors(rawErrors, subject, schema)\n\n // Now we can remap errors to be more zod-like\n return errors.map((error) => {\n const path: string[] = error.instancePath.split('/').slice(1)\n if (error.params.missingProperty) {\n const missingProperty = error.params.missingProperty as string\n return {path: [...path, missingProperty], message: 'Required'}\n }\n\n if (error.params.type) {\n const expectedType = Array.isArray(error.params.type)\n ? error.params.type.join(', ')\n : (error.params.type as string)\n const actualType = getPathValue(subject, path.join('.'))\n return {path, message: `Expected ${expectedType}, received ${typeof actualType}`}\n }\n\n if (error.keyword === 'anyOf' || error.keyword === 'oneOf') {\n return {path, message: 'Invalid input'}\n }\n\n if (error.params.allowedValues) {\n const allowedValues = error.params.allowedValues as string[]\n const actualValue = getPathValue(subject, path.join('.'))\n return {\n path,\n message: `Invalid enum value. Expected ${allowedValues\n .map((value) => JSON.stringify(value))\n .join(' | ')}, received ${JSON.stringify(actualValue)}`.replace(/\"/g, \"'\"),\n }\n }\n\n if (error.params.comparison) {\n const comparison = error.params.comparison as string\n const limit = error.params.limit\n const actualValue = getPathValue(subject, path.join('.'))\n\n let comparisonText = comparison\n switch (comparison) {\n case '<=':\n comparisonText = 'less than or equal to'\n break\n case '<':\n comparisonText = 'less than'\n break\n case '>=':\n comparisonText = 'greater than or equal to'\n break\n case '>':\n comparisonText = 'greater than'\n break\n }\n\n return {\n path,\n message: capitalize(`${typeof actualValue} must be ${comparisonText} ${limit}`),\n }\n }\n\n if (error.params.additionalProperty) {\n const supportedProperties = Object.keys(error.parentSchema?.properties ?? {})\n\n // if a property was already set, remove it from here\n const alreadySetProperties = Object.keys(error.data ?? {})\n const remainingProperties = supportedProperties.filter((property) => !alreadySetProperties.includes(property))\n\n if (remainingProperties.length > 0) {\n return {\n path: [...path, error.params.additionalProperty as string],\n message: `No additional properties allowed. You can set ${remainingProperties.sort().join(', ')}.`,\n }\n }\n }\n\n return {\n path,\n message: error.message,\n }\n })\n}\n\n/**\n * If a JSON schema specifies a union (anyOf, oneOf), and the subject doesn't meet any of the 'candidates' for the\n * union, then the error list received ends up being quite long: you get an error for the union property itself, and\n * then additional errors for each of the candidate branches.\n *\n * This function simplifies the error collection. By default it strips anything other than the union error itself.\n *\n * In some cases, it can be possible to identify what the intended branch of the union was -- for instance, maybe there\n * is a discriminating field like `type` that is unique between the branches. We inspect each candidate branch and if\n * one branch is less wrong than the others -- e.g. It had a valid `type`, but problems elsewhere -- then we keep the\n * errors for that branch.\n *\n * This is complex but in practise gives much more actionable errors.\n *\n * @param rawErrors - JSON Schema errors taken directly from Ajv.\n * @param subject - The object being validated.\n * @param schema - The JSON schema to validated against.\n * @returns A simplified list of errors.\n */\nfunction simplifyUnionErrors(rawErrors: AjvError[], subject: object, schema: SchemaObject): AjvError[] {\n let errors = rawErrors\n\n const resolvedUnionErrors = new Set()\n while (true) {\n const unionError = errors.filter(\n (error) =>\n (error.keyword === 'oneOf' || error.keyword === 'anyOf') && !resolvedUnionErrors.has(error.instancePath),\n )[0]\n if (unionError === undefined) {\n break\n }\n // split errors into those sharing an instance path and those not\n const unrelatedErrors = errors.filter((error) => !error.instancePath.startsWith(unionError.instancePath))\n\n // we start by assuming only the union error itself is useful, and not the errors from the candidate schemas\n let simplifiedUnionRelatedErrors: AjvError[] = [unionError]\n\n // get the schema list from where the union issue occured\n const dottedSchemaPath = unionError.schemaPath.replace('#/', '').replace(/\\//g, '.')\n const unionSchemas = getPathValue<SchemaObject[]>(schema, dottedSchemaPath)\n // and the slice of the subject that caused the issue\n const subjectValue = getPathValue(subject, unionError.instancePath.split('/').slice(1).join('.'))\n\n if (unionSchemas !== undefined && subjectValue !== undefined) {\n // we know that none of the union schemas are correct, but for each of them we can measure how wrong they are\n const correctValuesAndErrors = unionSchemas\n .map((candidateSchemaFromUnion: SchemaObject) => {\n const candidateSchemaValidator = createAjvValidator('fail', candidateSchemaFromUnion)\n candidateSchemaValidator(subjectValue)\n\n let score = 0\n if (candidateSchemaFromUnion.type === 'object') {\n // provided the schema is an object, we can measure how many properties are good\n const candidatesObjectProperties = Object.keys(candidateSchemaFromUnion.properties)\n score = candidatesObjectProperties.reduce((acc, propertyName) => {\n const subSchema = candidateSchemaFromUnion.properties[propertyName] as SchemaObject\n const subjectValueSlice = getPathValue(subjectValue, propertyName)\n\n const subValidator = createAjvValidator('fail', subSchema)\n if (subValidator(subjectValueSlice)) {\n return acc + 1\n }\n return acc\n }, score)\n }\n\n return [score, candidateSchemaValidator.errors!] as const\n })\n .sort(([scoreA], [scoreB]) => scoreA - scoreB)\n\n if (correctValuesAndErrors.length >= 2) {\n const [bestScore, bestErrors] = correctValuesAndErrors[correctValuesAndErrors.length - 1]!\n const [penultimateScore] = correctValuesAndErrors[correctValuesAndErrors.length - 2]!\n\n if (bestScore !== penultimateScore) {\n // If there's a winner, show the errors for the best schema as they'll likely be actionable.\n // We got these through a nested schema, so we need to adjust the instance path\n simplifiedUnionRelatedErrors = [\n unionError,\n ...bestErrors.map((bestError) => ({\n ...bestError,\n instancePath: unionError.instancePath + bestError.instancePath,\n })),\n ]\n }\n }\n }\n errors = [...unrelatedErrors, ...simplifiedUnionRelatedErrors]\n\n resolvedUnionErrors.add(unionError.instancePath)\n }\n return errors\n}\n"]}
1
+ {"version":3,"file":"json-schema.js","sourceRoot":"","sources":["../../../src/public/node/json-schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,MAAM,aAAa,CAAA;AAEtC,OAAO,EAAC,YAAY,EAAC,MAAM,qBAAqB,CAAA;AAEhD,OAAO,EAAC,UAAU,EAAC,MAAM,qBAAqB,CAAA;AAC9C,OAAO,EAAC,GAAG,EAA8C,MAAM,KAAK,CAAA;AACpE,OAAO,UAAU,MAAM,qCAAqC,CAAA;AAC5D,OAAO,SAAS,MAAM,qBAAqB,CAAA;AAM3C;;;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ACH,CAAC;QACD,MAAM,GAAG,CAAC,GAAG,eAAe,EAAE,GAAG,4BAA4B,CAAC,CAAA;QAE9D,mBAAmB,CAAC,GAAG,CAAC,UAAU,CAAC,YAAY,CAAC,CAAA;IAClD,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import {randomUUID} from './crypto.js'\nimport {ParseConfigurationResult} from './schema.js'\nimport {getPathValue} from '../common/object.js'\n\nimport {capitalize} from '../common/string.js'\nimport {Ajv, ErrorObject, SchemaObject, ValidateFunction} from 'ajv'\nimport $RefParser from '@apidevtools/json-schema-ref-parser'\nimport cloneDeep from 'lodash/cloneDeep.js'\n\nexport type HandleInvalidAdditionalProperties = 'strip' | 'fail'\n\ntype AjvError = ErrorObject<string, Record<string, unknown>>\n\n/**\n * Normalises a JSON Schema by standardising it's internal implementation.\n *\n * We prefer to not use $ref elements in our schemas, so we inline them; it's easier then to process errors.\n *\n * @param schema - The JSON schema (as a string) to normalise.\n * @returns The normalised JSON schema.\n */\nexport async function normaliseJsonSchema(schema: string): Promise<SchemaObject> {\n // we want to modify the schema, removing any $ref elements and inlining with their source\n const parsedSchema = JSON.parse(schema)\n await $RefParser.dereference(parsedSchema, {resolve: {external: false}})\n return parsedSchema\n}\n\nfunction createAjvValidator(\n handleInvalidAdditionalProperties: HandleInvalidAdditionalProperties,\n schema: SchemaObject,\n) {\n // allowUnionTypes: Allows types like `type: [\"string\", \"number\"]`\n if (handleInvalidAdditionalProperties === 'strip') {\n // we need to let additional properties through, so that we can strip them later\n schema.additionalProperties = true\n }\n\n const ajv = new Ajv({allowUnionTypes: true, allErrors: true, verbose: true})\n ajv.addKeyword('x-taplo')\n\n const validator = ajv.compile(schema)\n\n return validator\n}\n\nconst validatorsCache = new Map<string, ValidateFunction>()\n\n/**\n * Given a subject object and a JSON schema contract, validate the subject against the contract.\n *\n * Errors are returned in a zod-like format, and processed to better handle unions.\n *\n * @param subject - The object to validate.\n * @param schema - The JSON schema to validate against.\n * @param handleInvalidAdditionalProperties - Whether to strip or fail on invalid additional properties.\n * @param identifier - The identifier of the schema being validated, used to cache the validator.\n * @returns The result of the validation. If the state is 'error', the errors will be in a zod-like format.\n */\nexport function jsonSchemaValidate(\n subject: object,\n schema: SchemaObject,\n handleInvalidAdditionalProperties: HandleInvalidAdditionalProperties,\n identifier?: string,\n): ParseConfigurationResult<unknown> & {rawErrors?: AjvError[]} {\n const subjectToModify = cloneDeep(subject)\n\n const cacheKey = identifier ?? randomUUID()\n\n const validator = validatorsCache.get(cacheKey) ?? createAjvValidator(handleInvalidAdditionalProperties, schema)\n validatorsCache.set(cacheKey, validator)\n\n validator(subjectToModify)\n\n // Errors from the contract are post-processed to be more zod-like and to deal with unions better\n let jsonSchemaErrors\n if (validator.errors && validator.errors.length > 0) {\n jsonSchemaErrors = convertJsonSchemaErrors(validator.errors, subjectToModify, schema)\n return {\n state: 'error',\n data: undefined,\n errors: jsonSchemaErrors,\n rawErrors: validator.errors,\n }\n }\n\n if (handleInvalidAdditionalProperties === 'strip') {\n const topLevelSchemaProperties = Object.keys(schema.properties ?? {})\n // strip any properties that are not in the top level schema from subjectToModify\n Object.keys(subjectToModify).forEach((key) => {\n if (!topLevelSchemaProperties.includes(key)) {\n // this isn't actually dynamic, because key came from Object.keys\n\n delete subjectToModify[key as keyof typeof subjectToModify]\n }\n })\n }\n\n return {\n state: 'ok',\n data: subjectToModify,\n errors: undefined,\n rawErrors: undefined,\n }\n}\n\n/**\n * Get a more precise type name for JSON Schema error messages.\n *\n * @param value - The value to get the type of.\n * @returns A string representing the type (e.g., 'array', 'null', 'object').\n */\nfunction getJsonSchemaValueType(value: unknown): string {\n if (Array.isArray(value)) return 'array'\n if (value === null) return 'null'\n return typeof value\n}\n\nfunction getJsonSchemaErrorValue(subject: object, path: string[]): unknown {\n return path.length === 0 ? subject : getPathValue(subject, path)\n}\n\n/**\n * Converts errors from Ajv into a zod-like format.\n *\n * @param rawErrors - JSON Schema errors taken directly from Ajv.\n * @param subject - The object being validated.\n * @param schema - The JSON schema to validated against.\n * @returns The errors in a zod-like format.\n */\nfunction convertJsonSchemaErrors(rawErrors: AjvError[], subject: object, schema: SchemaObject) {\n // This reduces the number of errors by simplifying errors coming from different branches of a union\n const errors = simplifyUnionErrors(rawErrors, subject, schema)\n\n // Now we can remap errors to be more zod-like\n return errors.map((error) => {\n const path: string[] = error.instancePath.split('/').slice(1)\n if (error.params.missingProperty) {\n const missingProperty = error.params.missingProperty as string\n return {path: [...path, missingProperty], message: 'Required'}\n }\n\n if (error.params.type) {\n const expectedType = Array.isArray(error.params.type)\n ? error.params.type.join(', ')\n : (error.params.type as string)\n const actualType = getJsonSchemaErrorValue(subject, path)\n return {path, message: `Expected ${expectedType}, received ${getJsonSchemaValueType(actualType)}`}\n }\n\n if (error.keyword === 'anyOf' || error.keyword === 'oneOf') {\n return {path, message: 'Invalid input'}\n }\n\n if (error.params.allowedValues) {\n const allowedValues = error.params.allowedValues as string[]\n const actualValue = getJsonSchemaErrorValue(subject, path)\n return {\n path,\n message: `Invalid enum value. Expected ${allowedValues\n .map((value) => JSON.stringify(value))\n .join(' | ')}, received ${JSON.stringify(actualValue)}`.replace(/\"/g, \"'\"),\n }\n }\n\n if (error.params.comparison) {\n const comparison = error.params.comparison as string\n const limit = error.params.limit\n const actualValue = getJsonSchemaErrorValue(subject, path)\n\n let comparisonText = comparison\n switch (comparison) {\n case '<=':\n comparisonText = 'less than or equal to'\n break\n case '<':\n comparisonText = 'less than'\n break\n case '>=':\n comparisonText = 'greater than or equal to'\n break\n case '>':\n comparisonText = 'greater than'\n break\n }\n\n return {\n path,\n message: capitalize(`${typeof actualValue} must be ${comparisonText} ${limit}`),\n }\n }\n\n if (error.params.additionalProperty) {\n const supportedProperties = Object.keys(error.parentSchema?.properties ?? {})\n\n // if a property was already set, remove it from here\n const alreadySetProperties = Object.keys(error.data ?? {})\n const remainingProperties = supportedProperties.filter((property) => !alreadySetProperties.includes(property))\n\n if (remainingProperties.length > 0) {\n return {\n path: [...path, error.params.additionalProperty as string],\n message: `No additional properties allowed. You can set ${remainingProperties.sort().join(', ')}.`,\n }\n }\n }\n\n return {\n path,\n message: error.message,\n }\n })\n}\n\n/**\n * If a JSON schema specifies a union (anyOf, oneOf), and the subject doesn't meet any of the 'candidates' for the\n * union, then the error list received ends up being quite long: you get an error for the union property itself, and\n * then additional errors for each of the candidate branches.\n *\n * This function simplifies the error collection. By default it strips anything other than the union error itself.\n *\n * In some cases, it can be possible to identify what the intended branch of the union was -- for instance, maybe there\n * is a discriminating field like `type` that is unique between the branches. We inspect each candidate branch and if\n * one branch is less wrong than the others -- e.g. It had a valid `type`, but problems elsewhere -- then we keep the\n * errors for that branch.\n *\n * This is complex but in practise gives much more actionable errors.\n *\n * @param rawErrors - JSON Schema errors taken directly from Ajv.\n * @param subject - The object being validated.\n * @param schema - The JSON schema to validated against.\n * @returns A simplified list of errors.\n */\nfunction simplifyUnionErrors(rawErrors: AjvError[], subject: object, schema: SchemaObject): AjvError[] {\n let errors = rawErrors\n\n const resolvedUnionErrors = new Set()\n while (true) {\n const unionError = errors.filter(\n (error) =>\n (error.keyword === 'oneOf' || error.keyword === 'anyOf') && !resolvedUnionErrors.has(error.instancePath),\n )[0]\n if (unionError === undefined) {\n break\n }\n // split errors into those sharing an instance path and those not\n const unrelatedErrors = errors.filter((error) => !error.instancePath.startsWith(unionError.instancePath))\n\n // we start by assuming only the union error itself is useful, and not the errors from the candidate schemas\n let simplifiedUnionRelatedErrors: AjvError[] = [unionError]\n\n // get the schema list from where the union issue occured\n const dottedSchemaPath = unionError.schemaPath.replace('#/', '').replace(/\\//g, '.')\n const unionSchemas = getPathValue<SchemaObject[]>(schema, dottedSchemaPath)\n // and the slice of the subject that caused the issue\n const subjectValue = getJsonSchemaErrorValue(subject, unionError.instancePath.split('/').slice(1))\n\n if (unionSchemas !== undefined && subjectValue !== undefined) {\n // we know that none of the union schemas are correct, but for each of them we can measure how wrong they are\n const correctValuesAndErrors = unionSchemas\n .map((candidateSchemaFromUnion: SchemaObject) => {\n const candidateSchemaValidator = createAjvValidator('fail', candidateSchemaFromUnion)\n candidateSchemaValidator(subjectValue)\n\n let score = 0\n if (candidateSchemaFromUnion.type === 'object') {\n // provided the schema is an object, we can measure how many properties are good\n const candidatesObjectProperties = Object.keys(candidateSchemaFromUnion.properties)\n score = candidatesObjectProperties.reduce((acc, propertyName) => {\n const subSchema = candidateSchemaFromUnion.properties[propertyName] as SchemaObject\n const subjectValueSlice = getJsonSchemaErrorValue(subjectValue as object, [propertyName])\n\n const subValidator = createAjvValidator('fail', subSchema)\n if (subValidator(subjectValueSlice)) {\n return acc + 1\n }\n return acc\n }, score)\n }\n\n return [score, candidateSchemaValidator.errors!] as const\n })\n .sort(([scoreA], [scoreB]) => scoreA - scoreB)\n\n if (correctValuesAndErrors.length >= 2) {\n const [bestScore, bestErrors] = correctValuesAndErrors[correctValuesAndErrors.length - 1]!\n const [penultimateScore] = correctValuesAndErrors[correctValuesAndErrors.length - 2]!\n\n if (bestScore !== penultimateScore) {\n // If there's a winner, show the errors for the best schema as they'll likely be actionable.\n // We got these through a nested schema, so we need to adjust the instance path\n simplifiedUnionRelatedErrors = [\n unionError,\n ...bestErrors.map((bestError) => ({\n ...bestError,\n instancePath: unionError.instancePath + bestError.instancePath,\n })),\n ]\n }\n }\n }\n errors = [...unrelatedErrors, ...simplifiedUnionRelatedErrors]\n\n resolvedUnionErrors.add(unionError.instancePath)\n }\n return errors\n}\n"]}
@@ -38,6 +38,7 @@ type CmdFieldsFromMonorail = PickByPrefix<MonorailEventPublic, 'cmd_all_'> & Pic
38
38
  declare const coreData: RuntimeMetadataManager<CmdFieldsFromMonorail, {
39
39
  commandStartOptions: {
40
40
  startTime: number;
41
+ endTime?: number;
41
42
  startCommand: string;
42
43
  startTopic?: string;
43
44
  startArgs: string[];
@@ -58,6 +59,7 @@ declare const coreData: RuntimeMetadataManager<CmdFieldsFromMonorail, {
58
59
  export declare const getAllPublicMetadata: () => Partial<CmdFieldsFromMonorail>, getAllSensitiveMetadata: () => Partial<{
59
60
  commandStartOptions: {
60
61
  startTime: number;
62
+ endTime?: number;
61
63
  startCommand: string;
62
64
  startTopic?: string;
63
65
  startArgs: string[];
@@ -77,6 +79,7 @@ export declare const getAllPublicMetadata: () => Partial<CmdFieldsFromMonorail>,
77
79
  }, "store_", never>>, addPublicMetadata: (getData: ProvideMetadata<CmdFieldsFromMonorail>, onError?: MetadataErrorHandling) => Promise<void>, addSensitiveMetadata: (getData: ProvideMetadata<{
78
80
  commandStartOptions: {
79
81
  startTime: number;
82
+ endTime?: number;
80
83
  startCommand: string;
81
84
  startTopic?: string;
82
85
  startArgs: string[];
@@ -1 +1 @@
1
- {"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../../src/public/node/metadata.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,MAAM,oBAAoB,CAAA;AAC7C,OAAO,EAAC,WAAW,EAAC,MAAM,iBAAiB,CAAA;AAe3C;;;;GAIG;AACH,SAAS,gCAAgC;IACvC,IAAI,UAAU,EAAE,EAAE,CAAC;QACjB,OAAO,QAAQ,CAAA;IACjB,CAAC;IACD,OAAO,iBAAiB,CAAA;AAC1B,CAAC;AA4BD;;;;;;GAMG;AACH,MAAM,UAAU,8BAA8B,CAG5C,wBAA0C,EAAE;IAC5C,MAAM,GAAG,GAA+D;QACtE,SAAS,EAAE,EAAE;QACb,MAAM,EAAE;YACN,GAAG,qBAAqB;SACzB;KACF,CAAA;IACD,MAAM,SAAS,GAAG,CAAC,IAAsB,EAAE,EAAE;QAC3C,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;IACjC,CAAC,CAAA;IACD,MAAM,YAAY,GAAG,CAAC,IAAyB,EAAE,EAAE;QACjD,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,CAAA;IACpC,CAAC,CAAA;IAED,MAAM,WAAW,GAAG,KAAK,EACvB,KAAiC,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AG;wBACH,8DAA8D;qBACxD,CAAC,CAAA;oBAET,sCAAsC;oBACtC,IAAI,YAAY,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAW,CAAA;oBACrD,YAAY,IAAI,QAAQ,CAAA;oBAExB,wFAAwF;oBACxF,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,YAA8C,CAAA;gBACpE,CAAC;YACH,CAAC,CAAA;QACH,CAAC;KACF,CAAA;AACH,CAAC;AAWD,MAAM,QAAQ,GAAG,8BAA8B,CAU7C,EAAC,yBAAyB,EAAE,CAAC,EAAE,yBAAyB,EAAE,CAAC,EAAC,CAAC,CAAA;AAE/D,MAAM,CAAC,MAAM,EAAC,oBAAoB,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,YAAY,EAAC,GACjH,QAAQ,CAAA","sourcesContent":["import {isUnitTest} from './context/local.js'\nimport {performance} from 'node:perf_hooks'\nimport type {PickByPrefix} from '../common/ts/pick-by-prefix.js'\nimport type {AnyJson} from '../../private/common/json.js'\nimport type {MonorailEventPublic, MonorailEventSensitive} from './monorail.js'\n\ntype ProvideMetadata<T> = () => Partial<T> | Promise<Partial<T>>\n\ntype MetadataErrorHandling =\n // Mute & report errors in production, throw them whilst testing\n | 'auto'\n // Errors are not reported to the user and do not stop execution, but they are reported to Bugsnag\n | 'mute-and-report'\n // Errors are not caught and will bubble out as normal\n | 'bubble'\n\n/**\n * Get the error handling strategy for metadata.\n *\n * @returns 'mute-and-report' in production, 'bubble' in tests.\n */\nfunction getMetadataErrorHandlingStrategy(): 'mute-and-report' | 'bubble' {\n if (isUnitTest()) {\n return 'bubble'\n }\n return 'mute-and-report'\n}\n\n/**\n * Any key in T that has a numeric value.\n */\ntype NumericKeyOf<T> = {\n [K in keyof T]: T[K] extends number ? (K extends string ? K : never) : never\n}[keyof T]\n\nexport interface RuntimeMetadataManager<TPublic extends AnyJson, TSensitive extends AnyJson> {\n /** Add some public metadata -- this should not contain any PII. */\n addPublicMetadata: (getData: ProvideMetadata<TPublic>, onError?: MetadataErrorHandling) => Promise<void>\n /**\n * Add some potentially sensitive metadata -- this may include PII, but unnecessary data should never be tracked\n * (this is a good fit for command args for instance).\n */\n addSensitiveMetadata: (getData: ProvideMetadata<TSensitive>, onError?: MetadataErrorHandling) => Promise<void>\n /** Get a snapshot of the tracked public data. */\n getAllPublicMetadata: () => Partial<TPublic>\n /** Get a snapshot of the tracked sensitive data. */\n getAllSensitiveMetadata: () => Partial<TSensitive>\n /** Run a function, monitoring how long it takes, and adding the elapsed time to a running total. */\n runWithTimer: (field: NumericKeyOf<TPublic>) => <T>(fn: () => Promise<T>) => Promise<T>\n}\n\nexport type PublicSchema<T> = T extends RuntimeMetadataManager<infer TPublic, infer _TSensitive> ? TPublic : never\nexport type SensitiveSchema<T> = T extends RuntimeMetadataManager<infer _TPublic, infer TSensitive> ? TSensitive : never\n\n/**\n * Creates a container for metadata collected at runtime.\n * The container provides async-safe functions for extracting the gathered metadata, and for setting it.\n *\n * @param defaultPublicMetadata - Optional, default data for the container.\n * @returns A container for the metadata.\n */\nexport function createRuntimeMetadataContainer<\n TPublic extends AnyJson,\n TSensitive extends AnyJson = Record<string, never>,\n>(defaultPublicMetadata: Partial<TPublic> = {}): RuntimeMetadataManager<TPublic, TSensitive> {\n const raw: {sensitive: Partial<TSensitive>; public: Partial<TPublic>} = {\n sensitive: {},\n public: {\n ...defaultPublicMetadata,\n },\n }\n const addPublic = (data: Partial<TPublic>) => {\n Object.assign(raw.public, data)\n }\n const addSensitive = (data: Partial<TSensitive>) => {\n Object.assign(raw.sensitive, data)\n }\n\n const addMetadata = async <T>(\n addFn: (data: Partial<T>) => void,\n getFn: ProvideMetadata<T>,\n onError: MetadataErrorHandling,\n ) => {\n const errorHandling = onError === 'auto' ? getMetadataErrorHandlingStrategy() : onError\n const getAndSet = async () => {\n const data = await getFn()\n addFn(data)\n }\n\n if (errorHandling === 'bubble') {\n await getAndSet()\n } else {\n try {\n await getAndSet()\n // eslint-disable-next-line no-catch-all/no-catch-all, @typescript-eslint/no-explicit-any\n } catch (error: any) {\n // This is very prone to becoming a circular dependency, so we import it dynamically\n const {sendErrorToBugsnag} = await import('./error-handler.js')\n await sendErrorToBugsnag(error, 'unexpected_error')\n }\n }\n }\n\n // See `runWithTimer` below.\n const durationStack: number[] = []\n\n return {\n getAllPublicMetadata: () => {\n return {...raw.public}\n },\n getAllSensitiveMetadata: () => {\n return {...raw.sensitive}\n },\n addPublicMetadata: async (getData: ProvideMetadata<TPublic>, onError: MetadataErrorHandling = 'auto') => {\n return addMetadata(addPublic, getData, onError)\n },\n addSensitiveMetadata: async (getData: ProvideMetadata<TSensitive>, onError: MetadataErrorHandling = 'auto') => {\n return addMetadata(addSensitive, getData, onError)\n },\n runWithTimer: (field: NumericKeyOf<TPublic>): (<T>(fn: () => Promise<T>) => Promise<T>) => {\n return async (fn) => {\n /**\n * For nested timers, we subtract the inner timer's duration from the outer timer's. We use a stack to track the\n * cumulative durations of nested timers. On starting a timer, we push a zero onto the stack to initialize the total\n * duration for subsequent nested timers. Before logging, we pop the stack to get the total nested timers' duration.\n * We subtract this from the current timer's actual duration to get its measurable duration. We then add the current\n * timer's actual duration to the stack's top, allowing any parent timer to deduct it from its own duration.\n */\n\n // Initialise the running total duration for all nested timers\n durationStack.push(0)\n\n // Do the work, and time it\n const start = performance.now()\n try {\n const result = await fn()\n return result\n } finally {\n let end = performance.now()\n // For very short durations, the end time can be before the start time(!) - we flatten this out to zero.\n end = Math.max(start, end)\n\n // The top of the stack is the total time for all nested timers\n const wallClockDuration = Math.max(end - start, 0)\n\n const childDurations = durationStack.pop()!\n const duration = Math.max(wallClockDuration - childDurations, 0)\n\n // If this is the topmost timer, the stack will be empty.\n if (durationStack.length > 0) {\n durationStack[durationStack.length - 1] = (durationStack[durationStack.length - 1] ?? 0) + wallClockDuration\n }\n\n // Log it -- we include it in the metadata, but also log via the standard performance API. The TS types for this library are not quite right, so we have to cast to `any` here.\n performance.measure(`${field}#measurable`, {\n start,\n duration,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n performance.measure(`${field}#wall`, {\n start,\n end,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n\n // There might not be a value set, yet\n let currentValue = (raw.public[field] || 0) as number\n currentValue += duration\n\n // TS is not quite smart enough to realise that raw.public[field] must be a numeric type\n raw.public[field] = currentValue as TPublic[NumericKeyOf<TPublic>]\n }\n }\n },\n }\n}\n\n// We want to track anything that ends up getting sent to monorail as `cmd_all_*`,\n// `cmd_app_*`, `cmd_theme_*`, `store_*`, and `env_auto_upgrade_*`\ntype CmdFieldsFromMonorail = PickByPrefix<MonorailEventPublic, 'cmd_all_'> &\n PickByPrefix<MonorailEventPublic, 'cmd_app_'> &\n PickByPrefix<MonorailEventPublic, 'cmd_create_app_'> &\n PickByPrefix<MonorailEventPublic, 'cmd_theme_'> &\n PickByPrefix<MonorailEventPublic, 'store_'> &\n PickByPrefix<MonorailEventPublic, 'env_auto_upgrade_'>\n\nconst coreData = createRuntimeMetadataContainer<\n CmdFieldsFromMonorail,\n {\n commandStartOptions: {\n startTime: number\n startCommand: string\n startTopic?: string\n startArgs: string[]\n }\n } & {environmentFlags: string} & PickByPrefix<MonorailEventSensitive, 'store_'>\n>({cmd_all_timing_network_ms: 0, cmd_all_timing_prompts_ms: 0})\n\nexport const {getAllPublicMetadata, getAllSensitiveMetadata, addPublicMetadata, addSensitiveMetadata, runWithTimer} =\n coreData\n\nexport type Public = PublicSchema<typeof coreData>\nexport type Sensitive = SensitiveSchema<typeof coreData>\n"]}
1
+ {"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../../src/public/node/metadata.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,MAAM,oBAAoB,CAAA;AAC7C,OAAO,EAAC,WAAW,EAAC,MAAM,iBAAiB,CAAA;AAe3C;;;;GAIG;AACH,SAAS,gCAAgC;IACvC,IAAI,UA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cAAc,GAAG,aAAa,CAAC,GAAG,EAAG,CAAA;oBAC3C,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,iBAAiB,GAAG,cAAc,EAAE,CAAC,CAAC,CAAA;oBAEhE,yDAAyD;oBACzD,IAAI,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;wBAC7B,aAAa,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,aAAa,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,iBAAiB,CAAA;oBAC9G,CAAC;oBAED,+KAA+K;oBAC/K,WAAW,CAAC,OAAO,CAAC,GAAG,KAAK,aAAa,EAAE;wBACzC,KAAK;wBACL,QAAQ;wBACR,8DAA8D;qBACxD,CAAC,CAAA;oBACT,WAAW,CAAC,OAAO,CAAC,GAAG,KAAK,OAAO,EAAE;wBACnC,KAAK;wBACL,GAAG;wBACH,8DAA8D;qBACxD,CAAC,CAAA;oBAET,sCAAsC;oBACtC,IAAI,YAAY,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAW,CAAA;oBACrD,YAAY,IAAI,QAAQ,CAAA;oBAExB,wFAAwF;oBACxF,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,YAA8C,CAAA;gBACpE,CAAC;YACH,CAAC,CAAA;QACH,CAAC;KACF,CAAA;AACH,CAAC;AAWD,MAAM,QAAQ,GAAG,8BAA8B,CAW7C,EAAC,yBAAyB,EAAE,CAAC,EAAE,yBAAyB,EAAE,CAAC,EAAC,CAAC,CAAA;AAE/D,MAAM,CAAC,MAAM,EAAC,oBAAoB,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,YAAY,EAAC,GACjH,QAAQ,CAAA","sourcesContent":["import {isUnitTest} from './context/local.js'\nimport {performance} from 'node:perf_hooks'\nimport type {PickByPrefix} from '../common/ts/pick-by-prefix.js'\nimport type {AnyJson} from '../../private/common/json.js'\nimport type {MonorailEventPublic, MonorailEventSensitive} from './monorail.js'\n\ntype ProvideMetadata<T> = () => Partial<T> | Promise<Partial<T>>\n\ntype MetadataErrorHandling =\n // Mute & report errors in production, throw them whilst testing\n | 'auto'\n // Errors are not reported to the user and do not stop execution, but they are reported to Bugsnag\n | 'mute-and-report'\n // Errors are not caught and will bubble out as normal\n | 'bubble'\n\n/**\n * Get the error handling strategy for metadata.\n *\n * @returns 'mute-and-report' in production, 'bubble' in tests.\n */\nfunction getMetadataErrorHandlingStrategy(): 'mute-and-report' | 'bubble' {\n if (isUnitTest()) {\n return 'bubble'\n }\n return 'mute-and-report'\n}\n\n/**\n * Any key in T that has a numeric value.\n */\ntype NumericKeyOf<T> = {\n [K in keyof T]: T[K] extends number ? (K extends string ? K : never) : never\n}[keyof T]\n\nexport interface RuntimeMetadataManager<TPublic extends AnyJson, TSensitive extends AnyJson> {\n /** Add some public metadata -- this should not contain any PII. */\n addPublicMetadata: (getData: ProvideMetadata<TPublic>, onError?: MetadataErrorHandling) => Promise<void>\n /**\n * Add some potentially sensitive metadata -- this may include PII, but unnecessary data should never be tracked\n * (this is a good fit for command args for instance).\n */\n addSensitiveMetadata: (getData: ProvideMetadata<TSensitive>, onError?: MetadataErrorHandling) => Promise<void>\n /** Get a snapshot of the tracked public data. */\n getAllPublicMetadata: () => Partial<TPublic>\n /** Get a snapshot of the tracked sensitive data. */\n getAllSensitiveMetadata: () => Partial<TSensitive>\n /** Run a function, monitoring how long it takes, and adding the elapsed time to a running total. */\n runWithTimer: (field: NumericKeyOf<TPublic>) => <T>(fn: () => Promise<T>) => Promise<T>\n}\n\nexport type PublicSchema<T> = T extends RuntimeMetadataManager<infer TPublic, infer _TSensitive> ? TPublic : never\nexport type SensitiveSchema<T> = T extends RuntimeMetadataManager<infer _TPublic, infer TSensitive> ? TSensitive : never\n\n/**\n * Creates a container for metadata collected at runtime.\n * The container provides async-safe functions for extracting the gathered metadata, and for setting it.\n *\n * @param defaultPublicMetadata - Optional, default data for the container.\n * @returns A container for the metadata.\n */\nexport function createRuntimeMetadataContainer<\n TPublic extends AnyJson,\n TSensitive extends AnyJson = Record<string, never>,\n>(defaultPublicMetadata: Partial<TPublic> = {}): RuntimeMetadataManager<TPublic, TSensitive> {\n const raw: {sensitive: Partial<TSensitive>; public: Partial<TPublic>} = {\n sensitive: {},\n public: {\n ...defaultPublicMetadata,\n },\n }\n const addPublic = (data: Partial<TPublic>) => {\n Object.assign(raw.public, data)\n }\n const addSensitive = (data: Partial<TSensitive>) => {\n Object.assign(raw.sensitive, data)\n }\n\n const addMetadata = async <T>(\n addFn: (data: Partial<T>) => void,\n getFn: ProvideMetadata<T>,\n onError: MetadataErrorHandling,\n ) => {\n const errorHandling = onError === 'auto' ? getMetadataErrorHandlingStrategy() : onError\n const getAndSet = async () => {\n const data = await getFn()\n addFn(data)\n }\n\n if (errorHandling === 'bubble') {\n await getAndSet()\n } else {\n try {\n await getAndSet()\n // eslint-disable-next-line no-catch-all/no-catch-all, @typescript-eslint/no-explicit-any\n } catch (error: any) {\n // This is very prone to becoming a circular dependency, so we import it dynamically\n const {sendErrorToBugsnag} = await import('./error-handler.js')\n await sendErrorToBugsnag(error, 'unexpected_error')\n }\n }\n }\n\n // See `runWithTimer` below.\n const durationStack: number[] = []\n\n return {\n getAllPublicMetadata: () => {\n return {...raw.public}\n },\n getAllSensitiveMetadata: () => {\n return {...raw.sensitive}\n },\n addPublicMetadata: async (getData: ProvideMetadata<TPublic>, onError: MetadataErrorHandling = 'auto') => {\n return addMetadata(addPublic, getData, onError)\n },\n addSensitiveMetadata: async (getData: ProvideMetadata<TSensitive>, onError: MetadataErrorHandling = 'auto') => {\n return addMetadata(addSensitive, getData, onError)\n },\n runWithTimer: (field: NumericKeyOf<TPublic>): (<T>(fn: () => Promise<T>) => Promise<T>) => {\n return async (fn) => {\n /**\n * For nested timers, we subtract the inner timer's duration from the outer timer's. We use a stack to track the\n * cumulative durations of nested timers. On starting a timer, we push a zero onto the stack to initialize the total\n * duration for subsequent nested timers. Before logging, we pop the stack to get the total nested timers' duration.\n * We subtract this from the current timer's actual duration to get its measurable duration. We then add the current\n * timer's actual duration to the stack's top, allowing any parent timer to deduct it from its own duration.\n */\n\n // Initialise the running total duration for all nested timers\n durationStack.push(0)\n\n // Do the work, and time it\n const start = performance.now()\n try {\n const result = await fn()\n return result\n } finally {\n let end = performance.now()\n // For very short durations, the end time can be before the start time(!) - we flatten this out to zero.\n end = Math.max(start, end)\n\n // The top of the stack is the total time for all nested timers\n const wallClockDuration = Math.max(end - start, 0)\n\n const childDurations = durationStack.pop()!\n const duration = Math.max(wallClockDuration - childDurations, 0)\n\n // If this is the topmost timer, the stack will be empty.\n if (durationStack.length > 0) {\n durationStack[durationStack.length - 1] = (durationStack[durationStack.length - 1] ?? 0) + wallClockDuration\n }\n\n // Log it -- we include it in the metadata, but also log via the standard performance API. The TS types for this library are not quite right, so we have to cast to `any` here.\n performance.measure(`${field}#measurable`, {\n start,\n duration,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n performance.measure(`${field}#wall`, {\n start,\n end,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n\n // There might not be a value set, yet\n let currentValue = (raw.public[field] || 0) as number\n currentValue += duration\n\n // TS is not quite smart enough to realise that raw.public[field] must be a numeric type\n raw.public[field] = currentValue as TPublic[NumericKeyOf<TPublic>]\n }\n }\n },\n }\n}\n\n// We want to track anything that ends up getting sent to monorail as `cmd_all_*`,\n// `cmd_app_*`, `cmd_theme_*`, `store_*`, and `env_auto_upgrade_*`\ntype CmdFieldsFromMonorail = PickByPrefix<MonorailEventPublic, 'cmd_all_'> &\n PickByPrefix<MonorailEventPublic, 'cmd_app_'> &\n PickByPrefix<MonorailEventPublic, 'cmd_create_app_'> &\n PickByPrefix<MonorailEventPublic, 'cmd_theme_'> &\n PickByPrefix<MonorailEventPublic, 'store_'> &\n PickByPrefix<MonorailEventPublic, 'env_auto_upgrade_'>\n\nconst coreData = createRuntimeMetadataContainer<\n CmdFieldsFromMonorail,\n {\n commandStartOptions: {\n startTime: number\n endTime?: number\n startCommand: string\n startTopic?: string\n startArgs: string[]\n }\n } & {environmentFlags: string} & PickByPrefix<MonorailEventSensitive, 'store_'>\n>({cmd_all_timing_network_ms: 0, cmd_all_timing_prompts_ms: 0})\n\nexport const {getAllPublicMetadata, getAllSensitiveMetadata, addPublicMetadata, addSensitiveMetadata, runWithTimer} =\n coreData\n\nexport type Public = PublicSchema<typeof coreData>\nexport type Sensitive = SensitiveSchema<typeof coreData>\n"]}
@@ -2,7 +2,7 @@ import { JsonMap } from '../../private/common/json.js';
2
2
  import { DeepRequired } from '../common/ts/deep-required.js';
3
3
  export { DeepRequired };
4
4
  type Optional<T> = T | null;
5
- export declare const MONORAIL_COMMAND_TOPIC = "app_cli3_command/1.24";
5
+ export declare const MONORAIL_COMMAND_TOPIC = "app_cli3_command/1.28";
6
6
  export interface Schemas {
7
7
  [MONORAIL_COMMAND_TOPIC]: {
8
8
  sensitive: {
@@ -19,6 +19,7 @@ export interface Schemas {
19
19
  public: {
20
20
  business_platform_id?: Optional<number>;
21
21
  partner_id?: Optional<number>;
22
+ store_id?: Optional<number>;
22
23
  command: string;
23
24
  project_type?: Optional<string>;
24
25
  time_start: number;
@@ -33,6 +34,7 @@ export interface Schemas {
33
34
  is_employee: boolean;
34
35
  store_fqdn_hash?: Optional<string>;
35
36
  store_fqdn_validated?: Optional<boolean>;
37
+ store_domain?: Optional<string>;
36
38
  user_id: string;
37
39
  cmd_all_alias_used?: Optional<string>;
38
40
  cmd_all_launcher?: Optional<string>;
@@ -2,7 +2,7 @@ import { fetch } from './http.js';
2
2
  import { outputDebug, outputContent, outputToken } from './output.js';
3
3
  const url = 'https://monorail-edge.shopifysvc.com/v1/produce';
4
4
  // This is the topic name of the main event we log to Monorail, the command tracker
5
- export const MONORAIL_COMMAND_TOPIC = 'app_cli3_command/1.24';
5
+ export const MONORAIL_COMMAND_TOPIC = 'app_cli3_command/1.28';
6
6
  const publishedCommandNames = new Set();
7
7
  /**
8
8
  * Publishes an event to Monorail.