@shopify/cli-kit 3.70.0 → 3.71.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 (85) hide show
  1. package/dist/cli/api/graphql/admin/generated/theme_files_upsert.d.ts +21 -0
  2. package/dist/cli/api/graphql/admin/generated/theme_files_upsert.js +82 -0
  3. package/dist/cli/api/graphql/admin/generated/theme_files_upsert.js.map +1 -0
  4. package/dist/private/node/api.d.ts +1 -1
  5. package/dist/private/node/api.js +30 -2
  6. package/dist/private/node/api.js.map +1 -1
  7. package/dist/private/node/constants.d.ts +2 -0
  8. package/dist/private/node/constants.js +2 -0
  9. package/dist/private/node/constants.js.map +1 -1
  10. package/dist/private/node/session/exchange.js +2 -2
  11. package/dist/private/node/session/exchange.js.map +1 -1
  12. package/dist/private/node/session/scopes.js +3 -5
  13. package/dist/private/node/session/scopes.js.map +1 -1
  14. package/dist/private/node/session.js +2 -3
  15. package/dist/private/node/session.js.map +1 -1
  16. package/dist/private/node/ui/alert.js +1 -3
  17. package/dist/private/node/ui/alert.js.map +1 -1
  18. package/dist/private/node/ui/components/ConcurrentOutput.js +0 -2
  19. package/dist/private/node/ui/components/ConcurrentOutput.js.map +1 -1
  20. package/dist/private/node/ui/components/Link.js +3 -0
  21. package/dist/private/node/ui/components/Link.js.map +1 -1
  22. package/dist/private/node/ui/components/Link.test.js +23 -0
  23. package/dist/private/node/ui/components/Link.test.js.map +1 -1
  24. package/dist/private/node/ui.js +1 -1
  25. package/dist/private/node/ui.js.map +1 -1
  26. package/dist/public/common/version.d.ts +1 -1
  27. package/dist/public/common/version.js +1 -1
  28. package/dist/public/common/version.js.map +1 -1
  29. package/dist/public/node/api/admin.js +11 -1
  30. package/dist/public/node/api/admin.js.map +1 -1
  31. package/dist/public/node/api/graphql.d.ts +2 -0
  32. package/dist/public/node/api/graphql.js +2 -2
  33. package/dist/public/node/api/graphql.js.map +1 -1
  34. package/dist/public/node/api/webhooks.d.ts +13 -0
  35. package/dist/public/node/api/webhooks.js +34 -0
  36. package/dist/public/node/api/webhooks.js.map +1 -0
  37. package/dist/public/node/cli-launcher.d.ts +12 -0
  38. package/dist/public/node/cli-launcher.js +29 -0
  39. package/dist/public/node/cli-launcher.js.map +1 -0
  40. package/dist/public/node/cli.d.ts +12 -10
  41. package/dist/public/node/cli.js +38 -100
  42. package/dist/public/node/cli.js.map +1 -1
  43. package/dist/public/node/context/fqdn.js +11 -7
  44. package/dist/public/node/context/fqdn.js.map +1 -1
  45. package/dist/public/node/context/local.d.ts +7 -0
  46. package/dist/public/node/context/local.js +9 -0
  47. package/dist/public/node/context/local.js.map +1 -1
  48. package/dist/public/node/environment.d.ts +7 -0
  49. package/dist/public/node/environment.js +11 -0
  50. package/dist/public/node/environment.js.map +1 -1
  51. package/dist/public/node/error-handler.js +1 -3
  52. package/dist/public/node/error-handler.js.map +1 -1
  53. package/dist/public/node/hooks/prerun.js +0 -2
  54. package/dist/public/node/hooks/prerun.js.map +1 -1
  55. package/dist/public/node/json-schema.d.ts +2 -1
  56. package/dist/public/node/json-schema.js +8 -3
  57. package/dist/public/node/json-schema.js.map +1 -1
  58. package/dist/public/node/notifications-system.d.ts +3 -1
  59. package/dist/public/node/notifications-system.js +9 -1
  60. package/dist/public/node/notifications-system.js.map +1 -1
  61. package/dist/public/node/output.d.ts +1 -6
  62. package/dist/public/node/output.js +1 -5
  63. package/dist/public/node/output.js.map +1 -1
  64. package/dist/public/node/path.d.ts +3 -3
  65. package/dist/public/node/path.js +4 -5
  66. package/dist/public/node/path.js.map +1 -1
  67. package/dist/public/node/system.js +14 -2
  68. package/dist/public/node/system.js.map +1 -1
  69. package/dist/public/node/themes/api.js +67 -8
  70. package/dist/public/node/themes/api.js.map +1 -1
  71. package/dist/public/node/themes/factories.d.ts +1 -3
  72. package/dist/public/node/themes/factories.js +0 -16
  73. package/dist/public/node/themes/factories.js.map +1 -1
  74. package/dist/public/node/tree-kill.js +0 -2
  75. package/dist/public/node/tree-kill.js.map +1 -1
  76. package/dist/public/node/ui.js +30 -80
  77. package/dist/public/node/ui.js.map +1 -1
  78. package/dist/public/node/vendor/dev_server/DevServer.d.ts +19 -0
  79. package/dist/public/node/vendor/dev_server/DevServer.js +170 -0
  80. package/dist/public/node/vendor/dev_server/DevServer.js.map +1 -0
  81. package/dist/tsconfig.tsbuildinfo +1 -1
  82. package/package.json +7 -4
  83. package/dist/private/node/demo-recorder.d.ts +0 -17
  84. package/dist/private/node/demo-recorder.js +0 -121
  85. package/dist/private/node/demo-recorder.js.map +0 -1
@@ -102,9 +102,9 @@ export declare function cwd(): string;
102
102
  */
103
103
  export declare function sniffForPath(argv?: string[]): string | undefined;
104
104
  /**
105
- * Returns whether the `--json` flag is present in the arguments.
105
+ * Returns whether the `--json` or `-j` flags are present in the arguments.
106
106
  *
107
- * @param argv - The arguments to search for the `--json` flag.
108
- * @returns Whether the `--json` flag is present in the arguments.
107
+ * @param argv - The arguments to search for the `--json` and `-j` flags.
108
+ * @returns Whether the `--json` or `-j` flag is present in the arguments.
109
109
  */
110
110
  export declare function sniffForJson(argv?: string[]): boolean;
@@ -149,13 +149,12 @@ export function sniffForPath(argv = process.argv) {
149
149
  return pathFlag;
150
150
  }
151
151
  /**
152
- * Returns whether the `--json` flag is present in the arguments.
152
+ * Returns whether the `--json` or `-j` flags are present in the arguments.
153
153
  *
154
- * @param argv - The arguments to search for the `--json` flag.
155
- * @returns Whether the `--json` flag is present in the arguments.
154
+ * @param argv - The arguments to search for the `--json` and `-j` flags.
155
+ * @returns Whether the `--json` or `-j` flag is present in the arguments.
156
156
  */
157
157
  export function sniffForJson(argv = process.argv) {
158
- const jsonFlagIndex = argv.indexOf('--json');
159
- return jsonFlagIndex !== -1;
158
+ return argv.includes('--json') || argv.includes('-j');
160
159
  }
161
160
  //# sourceMappingURL=path.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"path.js","sourceRoot":"","sources":["../../../src/public/node/path.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,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C,IAAI,aAAa,KAAK,CAAC,CAAC,EAAE;QACxB,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAA;QAC7D,OAAO,OAAO,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;KAC9B;IACD,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,GAAG,CAAC,CAAC,CAAA;IACxC,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,OAAM;IACjD,OAAO,QAAQ,CAAA;AACjB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI;IAC9C,MAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAA;IAC5C,OAAO,aAAa,KAAK,CAAC,CAAC,CAAA;AAC7B,CAAC","sourcesContent":["import commondir from 'commondir'\nimport {\n relative,\n dirname as patheDirname,\n join,\n normalize,\n resolve,\n basename as basenamePathe,\n extname as extnamePathe,\n isAbsolute,\n} from 'pathe'\nimport {fileURLToPath} from 'url'\n// eslint-disable-next-line node/prefer-global/url\nimport type {URL} from 'url'\n\n/**\n * Joins a list of paths together.\n *\n * @param paths - Paths to join.\n * @returns Joined path.\n */\nexport function joinPath(...paths: string[]): string {\n return join(...paths)\n}\n\n/**\n * Normalizes a path.\n *\n * @param path - Path to normalize.\n * @returns Normalized path.\n */\nexport function normalizePath(path: string): string {\n return normalize(path)\n}\n\n/**\n * Resolves a list of paths together.\n *\n * @param paths - Paths to resolve.\n * @returns Resolved path.\n */\nexport function resolvePath(...paths: string[]): string {\n return resolve(...paths)\n}\n\n/**\n * Returns the relative path from one path to another.\n *\n * @param from - Path to resolve from.\n * @param to - Path to resolve to.\n * @returns Relative path.\n */\nexport function relativePath(from: string, to: string): string {\n return relative(from, to)\n}\n\n/**\n * Returns whether the path is absolute.\n *\n * @param path - Path to check.\n * @returns Whether the path is absolute.\n */\nexport function isAbsolutePath(path: string): boolean {\n return isAbsolute(path)\n}\n\n/**\n * Returns the directory name of a path.\n *\n * @param path - Path to get the directory name of.\n * @returns Directory name.\n */\nexport function dirname(path: string): string {\n return patheDirname(path)\n}\n\n/**\n * Returns the base name of a path.\n *\n * @param path - Path to get the base name of.\n * @param ext - Optional extension to remove from the result.\n * @returns Base name.\n */\nexport function basename(path: string, ext?: string): string {\n return basenamePathe(path, ext)\n}\n\n/**\n * Returns the extension of the path.\n *\n * @param path - Path to get the extension of.\n * @returns Extension.\n */\nexport function extname(path: string): string {\n return extnamePathe(path)\n}\n\n/**\n * Given an absolute filesystem path, it makes it relative to\n * the current working directory. This is useful when logging paths\n * to allow the users to click on the file and let the OS open it\n * in the editor of choice.\n *\n * @param path - Path to relativize.\n * @param dir - Current working directory.\n * @returns Relativized path.\n */\nexport function relativizePath(path: string, dir: string = cwd()): string {\n const result = commondir([path, dir])\n const relativePath = relative(dir, path)\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const relativeComponents = relativePath.split('/').filter((component) => component === '..').length\n if (result === '/' || relativePath === '' || relativeComponents > 2) {\n return path\n } else {\n return relativePath\n }\n}\n\n/**\n * Given 2 paths, it returns whether the second path is a subpath of the first path.\n *\n * @param mainPath - The main path.\n * @param subpath - The subpath.\n * @returns Whether the subpath is a subpath of the main path.\n */\nexport function isSubpath(mainPath: string, subpath: string): boolean {\n const relativePath = relative(mainPath, subpath)\n return !relativePath.startsWith('..') && !isAbsolutePath(relativePath)\n}\n\n/**\n * Given a module's import.meta.url it returns the directory containing the module.\n *\n * @param moduleURL - The value of import.meta.url in the context of the caller module.\n * @returns The path to the directory containing the caller module.\n */\nexport function moduleDirectory(moduleURL: string | URL): string {\n return dirname(fileURLToPath(moduleURL))\n}\n\n/**\n * When running a script using `npm run`, something interesting happens. If the current\n * folder does not have a `package.json` or a `node_modules` folder, npm will traverse\n * the directory tree upwards until it finds one. Then it will run the script and set\n * `process.cwd()` to that folder, while the actual path is stored in the INIT_CWD\n * environment variable (see here: https://docs.npmjs.com/cli/v9/commands/npm-run-script#description).\n *\n * @returns The path to the current working directory.\n */\nexport function cwd(): string {\n // eslint-disable-next-line @shopify/cli/no-process-cwd\n return normalize(process.env.INIT_CWD ? process.env.INIT_CWD : process.cwd())\n}\n\n/**\n * Tries to get the value of the `--path` argument, if provided.\n *\n * @param argv - The arguments to search for the `--path` argument.\n * @returns The value of the `--path` argument, if provided.\n */\nexport function sniffForPath(argv = process.argv): string | undefined {\n const pathFlagIndex = argv.indexOf('--path')\n if (pathFlagIndex === -1) {\n const pathArg = argv.find((arg) => arg.startsWith('--path='))\n return pathArg?.split('=')[1]\n }\n const pathFlag = argv[pathFlagIndex + 1]\n if (!pathFlag || pathFlag.startsWith('-')) return\n return pathFlag\n}\n\n/**\n * Returns whether the `--json` flag is present in the arguments.\n *\n * @param argv - The arguments to search for the `--json` flag.\n * @returns Whether the `--json` flag is present in the arguments.\n */\nexport function sniffForJson(argv = process.argv): boolean {\n const jsonFlagIndex = argv.indexOf('--json')\n return jsonFlagIndex !== -1\n}\n"]}
1
+ {"version":3,"file":"path.js","sourceRoot":"","sources":["../../../src/public/node/path.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,WAAW,CAAA;AACjC,OAAO,EACL,QAAQ,EACR,OAAO,IAAI,YAAY,EACvB,IAAI,EACJ,SAAS,EACT,OAAO,EACP,QAAQ,IAAI,aAAa,EACzB,OAAO,IAAI,YAAY,EACvB,UAAU,GACX,MAAM,OAAO,CAAA;AACd,OAAO,EAAC,aAAa,EAAC,MAAM,KAAK,CAAA;AAIjC;;;;;GAKG;AACH,MAAM,UAAU,QAAQ,CAAC,GAAG,KAAe;IACzC,OAAO,IAAI,CAAC,GAAG,KAAK,CAAC,CAAA;AACvB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,aAAa,C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M;IACjD,OAAO,QAAQ,CAAA;AACjB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI;IAC9C,OAAO,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAA;AACvD,CAAC","sourcesContent":["import commondir from 'commondir'\nimport {\n relative,\n dirname as patheDirname,\n join,\n normalize,\n resolve,\n basename as basenamePathe,\n extname as extnamePathe,\n isAbsolute,\n} from 'pathe'\nimport {fileURLToPath} from 'url'\n// eslint-disable-next-line node/prefer-global/url\nimport type {URL} from 'url'\n\n/**\n * Joins a list of paths together.\n *\n * @param paths - Paths to join.\n * @returns Joined path.\n */\nexport function joinPath(...paths: string[]): string {\n return join(...paths)\n}\n\n/**\n * Normalizes a path.\n *\n * @param path - Path to normalize.\n * @returns Normalized path.\n */\nexport function normalizePath(path: string): string {\n return normalize(path)\n}\n\n/**\n * Resolves a list of paths together.\n *\n * @param paths - Paths to resolve.\n * @returns Resolved path.\n */\nexport function resolvePath(...paths: string[]): string {\n return resolve(...paths)\n}\n\n/**\n * Returns the relative path from one path to another.\n *\n * @param from - Path to resolve from.\n * @param to - Path to resolve to.\n * @returns Relative path.\n */\nexport function relativePath(from: string, to: string): string {\n return relative(from, to)\n}\n\n/**\n * Returns whether the path is absolute.\n *\n * @param path - Path to check.\n * @returns Whether the path is absolute.\n */\nexport function isAbsolutePath(path: string): boolean {\n return isAbsolute(path)\n}\n\n/**\n * Returns the directory name of a path.\n *\n * @param path - Path to get the directory name of.\n * @returns Directory name.\n */\nexport function dirname(path: string): string {\n return patheDirname(path)\n}\n\n/**\n * Returns the base name of a path.\n *\n * @param path - Path to get the base name of.\n * @param ext - Optional extension to remove from the result.\n * @returns Base name.\n */\nexport function basename(path: string, ext?: string): string {\n return basenamePathe(path, ext)\n}\n\n/**\n * Returns the extension of the path.\n *\n * @param path - Path to get the extension of.\n * @returns Extension.\n */\nexport function extname(path: string): string {\n return extnamePathe(path)\n}\n\n/**\n * Given an absolute filesystem path, it makes it relative to\n * the current working directory. This is useful when logging paths\n * to allow the users to click on the file and let the OS open it\n * in the editor of choice.\n *\n * @param path - Path to relativize.\n * @param dir - Current working directory.\n * @returns Relativized path.\n */\nexport function relativizePath(path: string, dir: string = cwd()): string {\n const result = commondir([path, dir])\n const relativePath = relative(dir, path)\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const relativeComponents = relativePath.split('/').filter((component) => component === '..').length\n if (result === '/' || relativePath === '' || relativeComponents > 2) {\n return path\n } else {\n return relativePath\n }\n}\n\n/**\n * Given 2 paths, it returns whether the second path is a subpath of the first path.\n *\n * @param mainPath - The main path.\n * @param subpath - The subpath.\n * @returns Whether the subpath is a subpath of the main path.\n */\nexport function isSubpath(mainPath: string, subpath: string): boolean {\n const relativePath = relative(mainPath, subpath)\n return !relativePath.startsWith('..') && !isAbsolutePath(relativePath)\n}\n\n/**\n * Given a module's import.meta.url it returns the directory containing the module.\n *\n * @param moduleURL - The value of import.meta.url in the context of the caller module.\n * @returns The path to the directory containing the caller module.\n */\nexport function moduleDirectory(moduleURL: string | URL): string {\n return dirname(fileURLToPath(moduleURL))\n}\n\n/**\n * When running a script using `npm run`, something interesting happens. If the current\n * folder does not have a `package.json` or a `node_modules` folder, npm will traverse\n * the directory tree upwards until it finds one. Then it will run the script and set\n * `process.cwd()` to that folder, while the actual path is stored in the INIT_CWD\n * environment variable (see here: https://docs.npmjs.com/cli/v9/commands/npm-run-script#description).\n *\n * @returns The path to the current working directory.\n */\nexport function cwd(): string {\n // eslint-disable-next-line @shopify/cli/no-process-cwd\n return normalize(process.env.INIT_CWD ? process.env.INIT_CWD : process.cwd())\n}\n\n/**\n * Tries to get the value of the `--path` argument, if provided.\n *\n * @param argv - The arguments to search for the `--path` argument.\n * @returns The value of the `--path` argument, if provided.\n */\nexport function sniffForPath(argv = process.argv): string | undefined {\n const pathFlagIndex = argv.indexOf('--path')\n if (pathFlagIndex === -1) {\n const pathArg = argv.find((arg) => arg.startsWith('--path='))\n return pathArg?.split('=')[1]\n }\n const pathFlag = argv[pathFlagIndex + 1]\n if (!pathFlag || pathFlag.startsWith('-')) return\n return pathFlag\n}\n\n/**\n * Returns whether the `--json` or `-j` flags are present in the arguments.\n *\n * @param argv - The arguments to search for the `--json` and `-j` flags.\n * @returns Whether the `--json` or `-j` flag is present in the arguments.\n */\nexport function sniffForJson(argv = process.argv): boolean {\n return argv.includes('--json') || argv.includes('-j')\n}\n"]}
@@ -1,9 +1,11 @@
1
- import { ExternalError } from './error.js';
2
- import { cwd } from './path.js';
1
+ import { AbortError, ExternalError } from './error.js';
2
+ import { cwd, dirname } from './path.js';
3
3
  import { treeKill } from './tree-kill.js';
4
4
  import { isTruthy } from './context/utilities.js';
5
+ import { renderWarning } from './ui.js';
5
6
  import { shouldDisplayColors, outputDebug } from '../../public/node/output.js';
6
7
  import { execa } from 'execa';
8
+ import which from 'which';
7
9
  /**
8
10
  * Opens a URL in the user's default browser.
9
11
  *
@@ -81,6 +83,7 @@ function buildExec(command, args, options) {
81
83
  if (shouldDisplayColors()) {
82
84
  env.FORCE_COLOR = '1';
83
85
  }
86
+ checkCommandSafety(command);
84
87
  const commandProcess = execa(command, args, {
85
88
  env,
86
89
  cwd: options?.cwd,
@@ -100,6 +103,15 @@ Running system process:
100
103
  `);
101
104
  return commandProcess;
102
105
  }
106
+ function checkCommandSafety(command) {
107
+ const commandDirectory = dirname(which.sync(command));
108
+ if (commandDirectory === cwd()) {
109
+ const headline = ['Skipped run of unsecure binary', { command }, 'found in the current directory.'];
110
+ const body = 'Please remove that file or review your current PATH.';
111
+ renderWarning({ headline, body });
112
+ throw new AbortError(headline, body);
113
+ }
114
+ }
103
115
  /**
104
116
  * Waits for a given number of seconds.
105
117
  *
@@ -1 +1 @@
1
- {"version":3,"file":"system.js","sourceRoot":"","sources":["../../../src/public/node/system.ts"],"names":[],"mappings":"AACA,O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AK;QACrB,KAAK,EAAE,OAAO,EAAE,KAAK;QACrB,KAAK,EAAE,OAAO,EAAE,KAAK;QACrB,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS;QAC7D,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS;QAC7D,mEAAmE;QACnE,mDAAmD;QACnD,WAAW,EAAE,KAAK;KACnB,CAAC,CAAA;IACF,WAAW,CAAC;;eAEC,OAAO,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;yBACf,OAAO,EAAE,GAAG,IAAI,GAAG,EAAE;CAC7C,CAAC,CAAA;IACA,OAAO,cAAc,CAAA;AACvB,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,KAAK,CAAC,OAAe;IACzC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,UAAU,CAAC,OAAO,EAAE,IAAI,GAAG,OAAO,CAAC,CAAA;IACrC,CAAC,CAAC,CAAA;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,yBAAyB;IACvC,IAAI,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE;QAC5B,OAAO,KAAK,CAAA;KACb;IACD,OAAO,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AAC7D,CAAC","sourcesContent":["import {AbortSignal} from './abort.js'\nimport {ExternalError} from './error.js'\nimport {cwd} from './path.js'\nimport {treeKill} from './tree-kill.js'\nimport {isTruthy} from './context/utilities.js'\nimport {shouldDisplayColors, outputDebug} from '../../public/node/output.js'\nimport {execa, ExecaChildProcess} from 'execa'\nimport type {Writable, Readable} from 'stream'\n\nexport interface ExecOptions {\n cwd?: string\n env?: {[key: string]: string | undefined}\n stdin?: Readable | 'inherit'\n stdout?: Writable | 'inherit'\n stderr?: Writable | 'inherit'\n stdio?: 'inherit'\n input?: string\n signal?: AbortSignal\n // Custom handler if process exits with a non-zero code\n externalErrorHandler?: (error: unknown) => Promise<void>\n}\n\n/**\n * Opens a URL in the user's default browser.\n *\n * @param url - URL to open.\n */\nexport async function openURL(url: string): Promise<void> {\n const externalOpen = await import('open')\n await externalOpen.default(url)\n}\n\n/**\n * Runs a command asynchronously, aggregates the stdout data, and returns it.\n *\n * @param command - Command to be executed.\n * @param args - Arguments to pass to the command.\n * @param options - Optional settings for how to run the command.\n * @returns A promise that resolves with the aggregatted stdout of the command.\n */\nexport async function captureOutput(command: string, args: string[], options?: ExecOptions): Promise<string> {\n const result = await buildExec(command, args, options)\n return result.stdout\n}\n\n/**\n * Runs a command asynchronously.\n *\n * @param command - Command to be executed.\n * @param args - Arguments to pass to the command.\n * @param options - Optional settings for how to run the command.\n */\nexport async function exec(command: string, args: string[], options?: ExecOptions): Promise<void> {\n const commandProcess = buildExec(command, args, options)\n if (options?.stderr && options.stderr !== 'inherit') {\n commandProcess.stderr?.pipe(options.stderr, {end: false})\n }\n if (options?.stdout && options.stdout !== 'inherit') {\n commandProcess.stdout?.pipe(options.stdout, {end: false})\n }\n let aborted = false\n options?.signal?.addEventListener('abort', () => {\n const pid = commandProcess.pid\n if (pid) {\n outputDebug(`Killing process ${pid}: ${command} ${args.join(' ')}`)\n aborted = true\n treeKill(pid, 'SIGTERM')\n }\n })\n try {\n await commandProcess\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (processError: any) {\n // Windows will throw an error whenever the process is killed, no matter the reason.\n // The aborted flag tell use that we killed it, so we can ignore the error.\n if (aborted) return\n if (options?.externalErrorHandler) {\n await options.externalErrorHandler(processError)\n } else {\n const abortError = new ExternalError(processError.message, command, args)\n abortError.stack = processError.stack\n throw abortError\n }\n }\n}\n\n/**\n * Runs a command asynchronously.\n *\n * @param command - Command to be executed.\n * @param args - Arguments to pass to the command.\n * @param options - Optional settings for how to run the command.\n * @returns A promise for a result with stdout and stderr properties.\n */\nfunction buildExec(command: string, args: string[], options?: ExecOptions): ExecaChildProcess {\n const env = options?.env ?? process.env\n if (shouldDisplayColors()) {\n env.FORCE_COLOR = '1'\n }\n const commandProcess = execa(command, args, {\n env,\n cwd: options?.cwd,\n input: options?.input,\n stdio: options?.stdio,\n stdin: options?.stdin,\n stdout: options?.stdout === 'inherit' ? 'inherit' : undefined,\n stderr: options?.stderr === 'inherit' ? 'inherit' : undefined,\n // Setting this to false makes it possible to kill the main process\n // and all its sub-processes with Ctrl+C on Windows\n windowsHide: false,\n })\n outputDebug(`\nRunning system process:\n · Command: ${command} ${args.join(' ')}\n · Working directory: ${options?.cwd ?? cwd()}\n`)\n return commandProcess\n}\n\n/**\n * Waits for a given number of seconds.\n *\n * @param seconds - Number of seconds to wait.\n * @returns A Promise resolving after the number of seconds.\n */\nexport async function sleep(seconds: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, 1000 * seconds)\n })\n}\n\n/**\n * Check if the standard input and output streams support prompting.\n *\n * @returns True if the standard input and output streams support prompting.\n */\nexport function terminalSupportsPrompting(): boolean {\n if (isTruthy(process.env.CI)) {\n return false\n }\n return Boolean(process.stdin.isTTY && process.stdout.isTTY)\n}\n"]}
1
+ {"version":3,"file":"system.js","sourceRoot":"","sources":["../../../src/public/node/system.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,UAAU,EAAE,aAAa,EAAC,MAAM,YAAY,CAAA;AACpD,OAAO,EAAC,GAAG,EAAE,OAAO,EAAC,MAAM,WAAW,CAAA;AACtC,OAAO,EAAC,QAAQ,EAAC,MAAM,gBAAgB,CAAA;AACvC,OAAO,EAAC,QAAQ,EAAC,MAAM,wBAAwB,CAAA;AAC/C,OAAO,EAAC,aAAa,EAAC,MAAM,SAAS,CAAA;AACrC,OAAO,EAAC,mBAAmB,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AAC5E,O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ortSignal} from './abort.js'\nimport {AbortError, ExternalError} from './error.js'\nimport {cwd, dirname} from './path.js'\nimport {treeKill} from './tree-kill.js'\nimport {isTruthy} from './context/utilities.js'\nimport {renderWarning} from './ui.js'\nimport {shouldDisplayColors, outputDebug} from '../../public/node/output.js'\nimport {execa, ExecaChildProcess} from 'execa'\nimport which from 'which'\nimport type {Writable, Readable} from 'stream'\n\nexport interface ExecOptions {\n cwd?: string\n env?: {[key: string]: string | undefined}\n stdin?: Readable | 'inherit'\n stdout?: Writable | 'inherit'\n stderr?: Writable | 'inherit'\n stdio?: 'inherit'\n input?: string\n signal?: AbortSignal\n // Custom handler if process exits with a non-zero code\n externalErrorHandler?: (error: unknown) => Promise<void>\n}\n\n/**\n * Opens a URL in the user's default browser.\n *\n * @param url - URL to open.\n */\nexport async function openURL(url: string): Promise<void> {\n const externalOpen = await import('open')\n await externalOpen.default(url)\n}\n\n/**\n * Runs a command asynchronously, aggregates the stdout data, and returns it.\n *\n * @param command - Command to be executed.\n * @param args - Arguments to pass to the command.\n * @param options - Optional settings for how to run the command.\n * @returns A promise that resolves with the aggregatted stdout of the command.\n */\nexport async function captureOutput(command: string, args: string[], options?: ExecOptions): Promise<string> {\n const result = await buildExec(command, args, options)\n return result.stdout\n}\n\n/**\n * Runs a command asynchronously.\n *\n * @param command - Command to be executed.\n * @param args - Arguments to pass to the command.\n * @param options - Optional settings for how to run the command.\n */\nexport async function exec(command: string, args: string[], options?: ExecOptions): Promise<void> {\n const commandProcess = buildExec(command, args, options)\n if (options?.stderr && options.stderr !== 'inherit') {\n commandProcess.stderr?.pipe(options.stderr, {end: false})\n }\n if (options?.stdout && options.stdout !== 'inherit') {\n commandProcess.stdout?.pipe(options.stdout, {end: false})\n }\n let aborted = false\n options?.signal?.addEventListener('abort', () => {\n const pid = commandProcess.pid\n if (pid) {\n outputDebug(`Killing process ${pid}: ${command} ${args.join(' ')}`)\n aborted = true\n treeKill(pid, 'SIGTERM')\n }\n })\n try {\n await commandProcess\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (processError: any) {\n // Windows will throw an error whenever the process is killed, no matter the reason.\n // The aborted flag tell use that we killed it, so we can ignore the error.\n if (aborted) return\n if (options?.externalErrorHandler) {\n await options.externalErrorHandler(processError)\n } else {\n const abortError = new ExternalError(processError.message, command, args)\n abortError.stack = processError.stack\n throw abortError\n }\n }\n}\n\n/**\n * Runs a command asynchronously.\n *\n * @param command - Command to be executed.\n * @param args - Arguments to pass to the command.\n * @param options - Optional settings for how to run the command.\n * @returns A promise for a result with stdout and stderr properties.\n */\nfunction buildExec(command: string, args: string[], options?: ExecOptions): ExecaChildProcess {\n const env = options?.env ?? process.env\n if (shouldDisplayColors()) {\n env.FORCE_COLOR = '1'\n }\n checkCommandSafety(command)\n const commandProcess = execa(command, args, {\n env,\n cwd: options?.cwd,\n input: options?.input,\n stdio: options?.stdio,\n stdin: options?.stdin,\n stdout: options?.stdout === 'inherit' ? 'inherit' : undefined,\n stderr: options?.stderr === 'inherit' ? 'inherit' : undefined,\n // Setting this to false makes it possible to kill the main process\n // and all its sub-processes with Ctrl+C on Windows\n windowsHide: false,\n })\n outputDebug(`\nRunning system process:\n · Command: ${command} ${args.join(' ')}\n · Working directory: ${options?.cwd ?? cwd()}\n`)\n return commandProcess\n}\n\nfunction checkCommandSafety(command: string) {\n const commandDirectory = dirname(which.sync(command))\n if (commandDirectory === cwd()) {\n const headline = ['Skipped run of unsecure binary', {command}, 'found in the current directory.']\n const body = 'Please remove that file or review your current PATH.'\n renderWarning({headline, body})\n throw new AbortError(headline, body)\n }\n}\n\n/**\n * Waits for a given number of seconds.\n *\n * @param seconds - Number of seconds to wait.\n * @returns A Promise resolving after the number of seconds.\n */\nexport async function sleep(seconds: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, 1000 * seconds)\n })\n}\n\n/**\n * Check if the standard input and output streams support prompting.\n *\n * @returns True if the standard input and output streams support prompting.\n */\nexport function terminalSupportsPrompting(): boolean {\n if (isTruthy(process.env.CI)) {\n return false\n }\n return Boolean(process.stdin.isTTY && process.stdout.isTTY)\n}\n"]}
@@ -6,9 +6,11 @@ import { ThemeDelete } from '../../../cli/api/graphql/admin/generated/theme_dele
6
6
  import { ThemePublish } from '../../../cli/api/graphql/admin/generated/theme_publish.js';
7
7
  import { GetThemeFileBodies } from '../../../cli/api/graphql/admin/generated/get_theme_file_bodies.js';
8
8
  import { GetThemeFileChecksums } from '../../../cli/api/graphql/admin/generated/get_theme_file_checksums.js';
9
+ import { ThemeFilesUpsert, } from '../../../cli/api/graphql/admin/generated/theme_files_upsert.js';
9
10
  import { restRequest, adminRequestDoc } from '@shopify/cli-kit/node/api/admin';
10
11
  import { AbortError } from '@shopify/cli-kit/node/error';
11
- import { buildBulkUploadResults, buildTheme } from '@shopify/cli-kit/node/themes/factories';
12
+ import { buildTheme } from '@shopify/cli-kit/node/themes/factories';
13
+ import { Operation } from '@shopify/cli-kit/node/themes/types';
12
14
  import { outputDebug } from '@shopify/cli-kit/node/output';
13
15
  import { sleep } from '@shopify/cli-kit/node/system';
14
16
  export async function fetchTheme(id, session) {
@@ -46,7 +48,7 @@ export async function fetchThemeAssets(id, filenames, session) {
46
48
  });
47
49
  if (!response.theme?.files?.nodes || !response.theme?.files?.pageInfo) {
48
50
  const userErrors = response.theme?.files?.userErrors.map((error) => error.filename).join(', ');
49
- throw new AbortError(`Error fetching assets: ${userErrors}`);
51
+ unexpectedGraphQLError(`Error fetching assets: ${userErrors}`);
50
52
  }
51
53
  const { nodes, pageInfo } = response.theme.files;
52
54
  assets.push(
@@ -72,11 +74,70 @@ export async function deleteThemeAsset(id, key, session) {
72
74
  return response.status === 200;
73
75
  }
74
76
  export async function bulkUploadThemeAssets(id, assets, session) {
75
- const response = await request('PUT', `/themes/${id}/assets/bulk`, session, { assets });
76
- if (response.status !== 207) {
77
- throw new AbortError('Upload failed, could not reach the server');
77
+ const results = [];
78
+ for (let i = 0; i < assets.length; i += 50) {
79
+ const chunk = assets.slice(i, i + 50);
80
+ const files = prepareFilesForUpload(chunk);
81
+ // eslint-disable-next-line no-await-in-loop
82
+ const uploadResults = await uploadFiles(id, files, session);
83
+ results.push(...processUploadResults(uploadResults));
78
84
  }
79
- return buildBulkUploadResults(response.json.results, assets);
85
+ return results;
86
+ }
87
+ function prepareFilesForUpload(assets) {
88
+ return assets.map((asset) => {
89
+ if (asset.value) {
90
+ return {
91
+ filename: asset.key,
92
+ body: {
93
+ type: 'TEXT',
94
+ value: asset.value,
95
+ },
96
+ };
97
+ }
98
+ else if (asset.attachment) {
99
+ return {
100
+ filename: asset.key,
101
+ body: {
102
+ type: 'BASE64',
103
+ value: asset.attachment,
104
+ },
105
+ };
106
+ }
107
+ else {
108
+ unexpectedGraphQLError('Asset must have a value or attachment');
109
+ }
110
+ });
111
+ }
112
+ async function uploadFiles(themeId, files, session) {
113
+ return adminRequestDoc(ThemeFilesUpsert, session, { themeId: themeGid(themeId), files });
114
+ }
115
+ function processUploadResults(uploadResults) {
116
+ const { themeFilesUpsert } = uploadResults;
117
+ if (!themeFilesUpsert) {
118
+ unexpectedGraphQLError('Failed to upload theme files');
119
+ }
120
+ const { upsertedThemeFiles, userErrors } = themeFilesUpsert;
121
+ const results = [];
122
+ upsertedThemeFiles?.forEach((file) => {
123
+ results.push({
124
+ key: file.filename,
125
+ success: true,
126
+ operation: Operation.Upload,
127
+ });
128
+ });
129
+ userErrors.forEach((error) => {
130
+ if (!error.filename) {
131
+ unexpectedGraphQLError(`Error uploading theme files: ${error.message}`);
132
+ }
133
+ results.push({
134
+ key: error.filename,
135
+ success: false,
136
+ operation: Operation.Upload,
137
+ errors: { asset: [error.message] },
138
+ });
139
+ });
140
+ return results;
80
141
  }
81
142
  export async function fetchChecksums(id, session) {
82
143
  const checksums = [];
@@ -266,10 +327,8 @@ async function parseThemeFileContent(body) {
266
327
  switch (body.__typename) {
267
328
  case 'OnlineStoreThemeFileBodyText':
268
329
  return body.content;
269
- break;
270
330
  case 'OnlineStoreThemeFileBodyBase64':
271
331
  return Buffer.from(body.contentBase64, 'base64').toString();
272
- break;
273
332
  case 'OnlineStoreThemeFileBodyUrl':
274
333
  try {
275
334
  const response = await fetch(body.url);
@@ -1 +1 @@
1
- {"version":3,"file":"api.js","sourceRoot":"","sources":["../../../../src/public/node/themes/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,aAAa,EAAC,MAAM,WAAW,CAAA;AACvC,OAAO,EAAC,eAAe,EAAE,QAAQ,EAAC,MAAM,YAAY,CAAA;AACpD,OAAO,KAAK,SAAS,MAAM,8BAA8B,CAAA;AACzD,OAAO,EAAC,WAAW,EAAC,MAAM,0DAA0D,CAAA;AACpF,OAAO,EAAC,WAAW,EAAC,MAAM,0DAA0D,CAAA;AACpF,OAAO,EAAC,YAAY,EAAC,MAAM,2DAA2D,CAAA;AACtF,OAAO,EAAC,kBAAkB,EAAC,MAAM,mEAAmE,CAAA;AACpG,OAAO,EAAC,qBAAqB,EAAC,MAAM,sEAAsE,CAAA;AAC1G,OAAO,EAAC,WAAW,EAAgB,eAAe,EAAC,MAAM,iCAAiC,CAAA;AAE1F,OAAO,EAAC,UAAU,EAAC,MAAM,6BAA6B,CAAA;AACtD,OAAO,EAAC,sBAAsB,EAAE,UAAU,EAAC,MAAM,wCAAwC,CAAA;AAEzF,OAAO,EAAC,WAAW,EAAC,MAAM,8BAA8B,CAAA;AACxD,OAAO,EAAC,KAAK,EAAC,MAAM,8BAA8B,CAAA;AAKlD,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,EAAU,EAAE,OAAqB;IAChE,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,EAAC,MAAM,EAAE,yBAAyB,EAAC,CAAC,CAAA;IAC/G,OAAO,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;AACxC,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,OAAq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AAK,UAAU,oBAAoB,CAAC,EAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAwB;IACrF,IAAI,OAAO,IAAI,CAAC,EAAE;QAChB,IAAI,EAAE,CAAA;KACP;IAED,WAAW,CAAC,IAAI,OAAO,eAAe,IAAI,cAAc,CAAC,CAAA;IAEzD,MAAM,KAAK,CAAC,GAAG,CAAC,CAAA;IAChB,OAAO,KAAK,EAAE,CAAA;AAChB,CAAC;AAED,SAAS,QAAQ,CAAC,EAAU;IAC1B,OAAO,kCAAkC,EAAE,EAAE,CAAA;AAC/C,CAAC;AAOD,KAAK,UAAU,qBAAqB,CAAC,IAA8B;IACjE,QAAQ,IAAI,CAAC,UAAU,EAAE;QACvB,KAAK,8BAA8B;YACjC,OAAO,IAAI,CAAC,OAAO,CAAA;YACnB,MAAK;QACP,KAAK,gCAAgC;YACnC,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC,QAAQ,EAAE,CAAA;YAC3D,MAAK;QACP,KAAK,6BAA6B;YAChC,IAAI;gBACF,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;gBACtC,OAAO,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;aAC7B;YAAC,OAAO,KAAK,EAAE;gBACd,4CAA4C;gBAC5C,MAAM,IAAI,UAAU,CAAC,uCAAuC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAA;aACxE;KACJ;AACH,CAAC","sourcesContent":["import {storeAdminUrl} from './urls.js'\nimport {composeThemeGid, parseGid} from './utils.js'\nimport * as throttler from '../api/rest-api-throttler.js'\nimport {ThemeUpdate} from '../../../cli/api/graphql/admin/generated/theme_update.js'\nimport {ThemeDelete} from '../../../cli/api/graphql/admin/generated/theme_delete.js'\nimport {ThemePublish} from '../../../cli/api/graphql/admin/generated/theme_publish.js'\nimport {GetThemeFileBodies} from '../../../cli/api/graphql/admin/generated/get_theme_file_bodies.js'\nimport {GetThemeFileChecksums} from '../../../cli/api/graphql/admin/generated/get_theme_file_checksums.js'\nimport {restRequest, RestResponse, adminRequestDoc} from '@shopify/cli-kit/node/api/admin'\nimport {AdminSession} from '@shopify/cli-kit/node/session'\nimport {AbortError} from '@shopify/cli-kit/node/error'\nimport {buildBulkUploadResults, buildTheme} from '@shopify/cli-kit/node/themes/factories'\nimport {Result, Checksum, Key, Theme, ThemeAsset} from '@shopify/cli-kit/node/themes/types'\nimport {outputDebug} from '@shopify/cli-kit/node/output'\nimport {sleep} from '@shopify/cli-kit/node/system'\n\nexport type ThemeParams = Partial<Pick<Theme, 'name' | 'role' | 'processing' | 'src'>>\nexport type AssetParams = Pick<ThemeAsset, 'key'> & Partial<Pick<ThemeAsset, 'value' | 'attachment'>>\n\nexport async function fetchTheme(id: number, session: AdminSession): Promise<Theme | undefined> {\n const response = await request('GET', `/themes/${id}`, session, undefined, {fields: 'id,name,role,processing'})\n return buildTheme(response.json.theme)\n}\n\nexport async function fetchThemes(session: AdminSession): Promise<Theme[]> {\n const response = await request('GET', '/themes', session, undefined, {fields: 'id,name,role,processing'})\n const themes = response.json?.themes\n if (themes?.length > 0) return themes.map(buildTheme)\n return []\n}\n\nexport async function createTheme(params: ThemeParams, session: AdminSession): Promise<Theme | undefined> {\n const response = await request('POST', '/themes', session, {theme: {...params}})\n\n if (!params.src) {\n const minimumThemeAssets = [\n {key: 'config/settings_schema.json', value: '[]'},\n {key: 'layout/password.liquid', value: '{{ content_for_header }}{{ content_for_layout }}'},\n {key: 'layout/theme.liquid', value: '{{ content_for_header }}{{ content_for_layout }}'},\n ]\n\n await bulkUploadThemeAssets(response.json.theme.id, minimumThemeAssets, session)\n }\n\n return buildTheme({...response.json.theme, createdAtRuntime: true})\n}\n\nexport async function fetchThemeAssets(id: number, filenames: Key[], session: AdminSession): Promise<ThemeAsset[]> {\n const assets: ThemeAsset[] = []\n let after: string | null = null\n\n while (true) {\n // eslint-disable-next-line no-await-in-loop\n const response = await adminRequestDoc(GetThemeFileBodies, session, {\n id: themeGid(id),\n filenames,\n after,\n })\n\n if (!response.theme?.files?.nodes || !response.theme?.files?.pageInfo) {\n const userErrors = response.theme?.files?.userErrors.map((error) => error.filename).join(', ')\n throw new AbortError(`Error fetching assets: ${userErrors}`)\n }\n\n const {nodes, pageInfo} = response.theme.files\n\n assets.push(\n // eslint-disable-next-line no-await-in-loop\n ...(await Promise.all(\n nodes.map(async (file) => {\n const content = await parseThemeFileContent(file.body)\n return {\n key: file.filename,\n checksum: file.checksumMd5 as string,\n value: content,\n }\n }),\n )),\n )\n\n if (!pageInfo.hasNextPage) {\n return assets\n }\n\n after = pageInfo.endCursor as string\n }\n}\n\nexport async function deleteThemeAsset(id: number, key: Key, session: AdminSession): Promise<boolean> {\n const response = await request('DELETE', `/themes/${id}/assets`, session, undefined, {\n 'asset[key]': key,\n })\n return response.status === 200\n}\n\nexport async function bulkUploadThemeAssets(\n id: number,\n assets: AssetParams[],\n session: AdminSession,\n): Promise<Result[]> {\n const response = await request('PUT', `/themes/${id}/assets/bulk`, session, {assets})\n if (response.status !== 207) {\n throw new AbortError('Upload failed, could not reach the server')\n }\n return buildBulkUploadResults(response.json.results, assets)\n}\n\nexport async function fetchChecksums(id: number, session: AdminSession): Promise<Checksum[]> {\n const checksums: Checksum[] = []\n let after: string | null = null\n\n while (true) {\n // eslint-disable-next-line no-await-in-loop\n const response = await adminRequestDoc(GetThemeFileChecksums, session, {id: themeGid(id), after})\n\n if (!response?.theme?.files?.nodes || !response?.theme?.files?.pageInfo) {\n const userErrors = response.theme?.files?.userErrors.map((error) => error.filename).join(', ')\n throw new AbortError(`Failed to fetch checksums for: ${userErrors}`)\n }\n\n const {nodes, pageInfo} = response.theme.files\n\n checksums.push(\n ...nodes.map((file) => ({\n key: file.filename,\n checksum: file.checksumMd5 as string,\n })),\n )\n\n if (!pageInfo.hasNextPage) {\n return checksums\n }\n\n after = pageInfo.endCursor as string\n }\n}\n\nexport async function themeUpdate(id: number, params: ThemeParams, session: AdminSession): Promise<Theme | undefined> {\n const name = params.name\n const input: {[key: string]: string} = {}\n if (name) {\n input.name = name\n }\n\n const {themeUpdate} = await adminRequestDoc(ThemeUpdate, session, {id: composeThemeGid(id), input})\n if (!themeUpdate) {\n // An unexpected error occurred during the GraphQL request execution\n unexpectedGraphQLError('Failed to update theme')\n }\n\n const {theme, userErrors} = themeUpdate\n if (userErrors.length) {\n const userErrors = themeUpdate.userErrors.map((error) => error.message).join(', ')\n throw new AbortError(userErrors)\n }\n\n if (!theme) {\n // An unexpected error if neither theme nor userErrors are returned\n unexpectedGraphQLError('Failed to update theme')\n }\n\n return buildTheme({\n id: parseGid(theme.id),\n name: theme.name,\n role: theme.role.toLowerCase(),\n })\n}\n\nexport async function themePublish(id: number, session: AdminSession): Promise<Theme | undefined> {\n const {themePublish} = await adminRequestDoc(ThemePublish, session, {id: composeThemeGid(id)})\n if (!themePublish) {\n // An unexpected error occurred during the GraphQL request execution\n unexpectedGraphQLError('Failed to update theme')\n }\n\n const {theme, userErrors} = themePublish\n if (userErrors.length) {\n const userErrors = themePublish.userErrors.map((error) => error.message).join(', ')\n throw new AbortError(userErrors)\n }\n\n if (!theme) {\n // An unexpected error if neither theme nor userErrors are returned\n unexpectedGraphQLError('Failed to update theme')\n }\n\n return buildTheme({\n id: parseGid(theme.id),\n name: theme.name,\n role: theme.role.toLowerCase(),\n })\n}\n\nexport async function themeDelete(id: number, session: AdminSession): Promise<boolean | undefined> {\n const {themeDelete} = await adminRequestDoc(ThemeDelete, session, {id: composeThemeGid(id)})\n if (!themeDelete) {\n // An unexpected error occurred during the GraphQL request execution\n unexpectedGraphQLError('Failed to update theme')\n }\n\n const {deletedThemeId, userErrors} = themeDelete\n if (userErrors.length) {\n const userErrors = themeDelete.userErrors.map((error) => error.message).join(', ')\n throw new AbortError(userErrors)\n }\n\n if (!deletedThemeId) {\n // An unexpected error if neither theme nor userErrors are returned\n unexpectedGraphQLError('Failed to update theme')\n }\n\n return true\n}\n\nasync function request<T>(\n method: string,\n path: string,\n session: AdminSession,\n params?: T,\n searchParams: {[name: string]: string} = {},\n retries = 1,\n): Promise<RestResponse> {\n const response = await throttler.throttle(() => restRequest(method, path, session, params, searchParams))\n\n const status = response.status\n\n throttler.updateApiCallLimitFromResponse(response)\n\n switch (true) {\n case status >= 200 && status <= 399:\n // Returns the successful reponse\n return response\n case status === 404:\n // Defer the decision when a resource is not found\n return response\n case status === 429:\n // Retry following the \"retry-after\" header\n return throttler.delayAwareRetry(response, () => request(method, path, session, params, searchParams))\n case status === 403:\n return handleForbiddenError(response, session)\n case status === 401:\n /**\n * We need to resolve the call to the refresh function at runtime to\n * avoid a circular reference.\n *\n * This won't be necessary when https://github.com/Shopify/cli/issues/4769\n * gets resolved, and this condition must be removed then.\n */\n if ('refresh' in session) {\n const refresh = session.refresh as () => Promise<void>\n await refresh()\n }\n\n // Retry 401 errors to be resilient to authentication errors.\n return handleRetriableError({\n path,\n retries,\n retry: () => {\n return request(method, path, session, params, searchParams, retries + 1)\n },\n fail: () => {\n throw new AbortError(`[${status}] API request unauthorized error`)\n },\n })\n case status === 422:\n throw new AbortError(`[${status}] API request unprocessable content: ${errors(response)}`)\n case status >= 400 && status <= 499:\n throw new AbortError(`[${status}] API request client error`)\n case status >= 500 && status <= 599:\n // Retry 500-family of errors as that may solve the issue (especially in 503 errors)\n return handleRetriableError({\n path,\n retries,\n retry: () => {\n return request(method, path, session, params, searchParams, retries + 1)\n },\n fail: () => {\n throw new AbortError(`[${status}] API request server error`)\n },\n })\n default:\n throw new AbortError(`[${status}] API request unexpected error`)\n }\n}\n\nfunction handleForbiddenError(response: RestResponse, session: AdminSession): never {\n const store = session.storeFqdn\n const adminUrl = storeAdminUrl(session)\n const error = errorMessage(response)\n\n if (error.match(/Cannot delete generated asset/) !== null) {\n throw new AbortError(error)\n }\n\n throw new AbortError(\n `You are not authorized to edit themes on \"${store}\".`,\n \"You can't use Shopify CLI with development stores if you only have Partner staff \" +\n 'member access. If you want to use Shopify CLI to work on a development store, then ' +\n 'you should be the store owner or create a staff account on the store.' +\n '\\n\\n' +\n \"If you're the store owner, then you need to log in to the store directly using the \" +\n `store URL at least once (for example, using \"${adminUrl}\") before you log in using ` +\n 'Shopify CLI. Logging in to the Shopify admin directly connects the development ' +\n 'store with your Shopify login.',\n )\n}\n\nfunction errors(response: RestResponse) {\n return JSON.stringify(response.json?.errors)\n}\n\nfunction errorMessage(response: RestResponse): string {\n const message = response.json?.message\n\n if (typeof message === 'string') {\n return message\n }\n\n return ''\n}\n\nfunction unexpectedGraphQLError(message: string): never {\n throw new AbortError(message)\n}\n\ninterface RetriableErrorOptions {\n path: string\n retries: number\n retry: () => Promise<RestResponse>\n fail: () => never\n}\n\nasync function handleRetriableError({path, retries, retry, fail}: RetriableErrorOptions): Promise<RestResponse> {\n if (retries >= 3) {\n fail()\n }\n\n outputDebug(`[${retries}] Retrying '${path}' request...`)\n\n await sleep(0.2)\n return retry()\n}\n\nfunction themeGid(id: number): string {\n return `gid://shopify/OnlineStoreTheme/${id}`\n}\n\ntype OnlineStoreThemeFileBody =\n | {__typename: 'OnlineStoreThemeFileBodyBase64'; contentBase64: string}\n | {__typename: 'OnlineStoreThemeFileBodyText'; content: string}\n | {__typename: 'OnlineStoreThemeFileBodyUrl'; url: string}\n\nasync function parseThemeFileContent(body: OnlineStoreThemeFileBody): Promise<string> {\n switch (body.__typename) {\n case 'OnlineStoreThemeFileBodyText':\n return body.content\n break\n case 'OnlineStoreThemeFileBodyBase64':\n return Buffer.from(body.contentBase64, 'base64').toString()\n break\n case 'OnlineStoreThemeFileBodyUrl':\n try {\n const response = await fetch(body.url)\n return await response.text()\n } catch (error) {\n // Raise error if we can't download the file\n throw new AbortError(`Error downloading content from URL: ${body.url}`)\n }\n }\n}\n"]}
1
+ {"version":3,"file":"api.js","sourceRoot":"","sources":["../../../../src/public/node/themes/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,aAAa,EAAC,MAAM,WAAW,C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M,QAAQ,CAAC,IAAI,EAAE,CAAA;aAC7B;YAAC,OAAO,KAAK,EAAE;gBACd,4CAA4C;gBAC5C,MAAM,IAAI,UAAU,CAAC,uCAAuC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAA;aACxE;KACJ;AACH,CAAC","sourcesContent":["import {storeAdminUrl} from './urls.js'\nimport {composeThemeGid, parseGid} from './utils.js'\nimport * as throttler from '../api/rest-api-throttler.js'\nimport {ThemeUpdate} from '../../../cli/api/graphql/admin/generated/theme_update.js'\nimport {ThemeDelete} from '../../../cli/api/graphql/admin/generated/theme_delete.js'\nimport {ThemePublish} from '../../../cli/api/graphql/admin/generated/theme_publish.js'\nimport {GetThemeFileBodies} from '../../../cli/api/graphql/admin/generated/get_theme_file_bodies.js'\nimport {GetThemeFileChecksums} from '../../../cli/api/graphql/admin/generated/get_theme_file_checksums.js'\nimport {\n ThemeFilesUpsert,\n ThemeFilesUpsertMutation,\n} from '../../../cli/api/graphql/admin/generated/theme_files_upsert.js'\nimport {\n OnlineStoreThemeFileBodyInputType,\n OnlineStoreThemeFilesUpsertFileInput,\n} from '../../../cli/api/graphql/admin/generated/types.js'\nimport {restRequest, RestResponse, adminRequestDoc} from '@shopify/cli-kit/node/api/admin'\nimport {AdminSession} from '@shopify/cli-kit/node/session'\nimport {AbortError} from '@shopify/cli-kit/node/error'\nimport {buildTheme} from '@shopify/cli-kit/node/themes/factories'\nimport {Result, Checksum, Key, Theme, ThemeAsset, Operation} from '@shopify/cli-kit/node/themes/types'\nimport {outputDebug} from '@shopify/cli-kit/node/output'\nimport {sleep} from '@shopify/cli-kit/node/system'\n\nexport type ThemeParams = Partial<Pick<Theme, 'name' | 'role' | 'processing' | 'src'>>\nexport type AssetParams = Pick<ThemeAsset, 'key'> & Partial<Pick<ThemeAsset, 'value' | 'attachment'>>\n\nexport async function fetchTheme(id: number, session: AdminSession): Promise<Theme | undefined> {\n const response = await request('GET', `/themes/${id}`, session, undefined, {fields: 'id,name,role,processing'})\n return buildTheme(response.json.theme)\n}\n\nexport async function fetchThemes(session: AdminSession): Promise<Theme[]> {\n const response = await request('GET', '/themes', session, undefined, {fields: 'id,name,role,processing'})\n const themes = response.json?.themes\n if (themes?.length > 0) return themes.map(buildTheme)\n return []\n}\n\nexport async function createTheme(params: ThemeParams, session: AdminSession): Promise<Theme | undefined> {\n const response = await request('POST', '/themes', session, {theme: {...params}})\n\n if (!params.src) {\n const minimumThemeAssets = [\n {key: 'config/settings_schema.json', value: '[]'},\n {key: 'layout/password.liquid', value: '{{ content_for_header }}{{ content_for_layout }}'},\n {key: 'layout/theme.liquid', value: '{{ content_for_header }}{{ content_for_layout }}'},\n ]\n\n await bulkUploadThemeAssets(response.json.theme.id, minimumThemeAssets, session)\n }\n\n return buildTheme({...response.json.theme, createdAtRuntime: true})\n}\n\nexport async function fetchThemeAssets(id: number, filenames: Key[], session: AdminSession): Promise<ThemeAsset[]> {\n const assets: ThemeAsset[] = []\n let after: string | null = null\n\n while (true) {\n // eslint-disable-next-line no-await-in-loop\n const response = await adminRequestDoc(GetThemeFileBodies, session, {\n id: themeGid(id),\n filenames,\n after,\n })\n\n if (!response.theme?.files?.nodes || !response.theme?.files?.pageInfo) {\n const userErrors = response.theme?.files?.userErrors.map((error) => error.filename).join(', ')\n unexpectedGraphQLError(`Error fetching assets: ${userErrors}`)\n }\n\n const {nodes, pageInfo} = response.theme.files\n\n assets.push(\n // eslint-disable-next-line no-await-in-loop\n ...(await Promise.all(\n nodes.map(async (file) => {\n const content = await parseThemeFileContent(file.body)\n return {\n key: file.filename,\n checksum: file.checksumMd5 as string,\n value: content,\n }\n }),\n )),\n )\n\n if (!pageInfo.hasNextPage) {\n return assets\n }\n\n after = pageInfo.endCursor as string\n }\n}\n\nexport async function deleteThemeAsset(id: number, key: Key, session: AdminSession): Promise<boolean> {\n const response = await request('DELETE', `/themes/${id}/assets`, session, undefined, {\n 'asset[key]': key,\n })\n return response.status === 200\n}\n\nexport async function bulkUploadThemeAssets(\n id: number,\n assets: AssetParams[],\n session: AdminSession,\n): Promise<Result[]> {\n const results: Result[] = []\n for (let i = 0; i < assets.length; i += 50) {\n const chunk = assets.slice(i, i + 50)\n const files = prepareFilesForUpload(chunk)\n // eslint-disable-next-line no-await-in-loop\n const uploadResults = await uploadFiles(id, files, session)\n results.push(...processUploadResults(uploadResults))\n }\n return results\n}\n\nfunction prepareFilesForUpload(assets: AssetParams[]): OnlineStoreThemeFilesUpsertFileInput[] {\n return assets.map((asset) => {\n if (asset.value) {\n return {\n filename: asset.key,\n body: {\n type: 'TEXT' as const,\n value: asset.value,\n },\n }\n } else if (asset.attachment) {\n return {\n filename: asset.key,\n body: {\n type: 'BASE64' as const,\n value: asset.attachment,\n },\n }\n } else {\n unexpectedGraphQLError('Asset must have a value or attachment')\n }\n })\n}\n\nasync function uploadFiles(\n themeId: number,\n files: {filename: string; body: {type: OnlineStoreThemeFileBodyInputType; value: string}}[],\n session: AdminSession,\n): Promise<ThemeFilesUpsertMutation> {\n return adminRequestDoc(ThemeFilesUpsert, session, {themeId: themeGid(themeId), files})\n}\n\nfunction processUploadResults(uploadResults: ThemeFilesUpsertMutation): Result[] {\n const {themeFilesUpsert} = uploadResults\n\n if (!themeFilesUpsert) {\n unexpectedGraphQLError('Failed to upload theme files')\n }\n\n const {upsertedThemeFiles, userErrors} = themeFilesUpsert\n\n const results: Result[] = []\n\n upsertedThemeFiles?.forEach((file) => {\n results.push({\n key: file.filename,\n success: true,\n operation: Operation.Upload,\n })\n })\n\n userErrors.forEach((error) => {\n if (!error.filename) {\n unexpectedGraphQLError(`Error uploading theme files: ${error.message}`)\n }\n results.push({\n key: error.filename,\n success: false,\n operation: Operation.Upload,\n errors: {asset: [error.message]},\n })\n })\n\n return results\n}\n\nexport async function fetchChecksums(id: number, session: AdminSession): Promise<Checksum[]> {\n const checksums: Checksum[] = []\n let after: string | null = null\n\n while (true) {\n // eslint-disable-next-line no-await-in-loop\n const response = await adminRequestDoc(GetThemeFileChecksums, session, {id: themeGid(id), after})\n\n if (!response?.theme?.files?.nodes || !response?.theme?.files?.pageInfo) {\n const userErrors = response.theme?.files?.userErrors.map((error) => error.filename).join(', ')\n throw new AbortError(`Failed to fetch checksums for: ${userErrors}`)\n }\n\n const {nodes, pageInfo} = response.theme.files\n\n checksums.push(\n ...nodes.map((file) => ({\n key: file.filename,\n checksum: file.checksumMd5 as string,\n })),\n )\n\n if (!pageInfo.hasNextPage) {\n return checksums\n }\n\n after = pageInfo.endCursor as string\n }\n}\n\nexport async function themeUpdate(id: number, params: ThemeParams, session: AdminSession): Promise<Theme | undefined> {\n const name = params.name\n const input: {[key: string]: string} = {}\n if (name) {\n input.name = name\n }\n\n const {themeUpdate} = await adminRequestDoc(ThemeUpdate, session, {id: composeThemeGid(id), input})\n if (!themeUpdate) {\n // An unexpected error occurred during the GraphQL request execution\n unexpectedGraphQLError('Failed to update theme')\n }\n\n const {theme, userErrors} = themeUpdate\n if (userErrors.length) {\n const userErrors = themeUpdate.userErrors.map((error) => error.message).join(', ')\n throw new AbortError(userErrors)\n }\n\n if (!theme) {\n // An unexpected error if neither theme nor userErrors are returned\n unexpectedGraphQLError('Failed to update theme')\n }\n\n return buildTheme({\n id: parseGid(theme.id),\n name: theme.name,\n role: theme.role.toLowerCase(),\n })\n}\n\nexport async function themePublish(id: number, session: AdminSession): Promise<Theme | undefined> {\n const {themePublish} = await adminRequestDoc(ThemePublish, session, {id: composeThemeGid(id)})\n if (!themePublish) {\n // An unexpected error occurred during the GraphQL request execution\n unexpectedGraphQLError('Failed to update theme')\n }\n\n const {theme, userErrors} = themePublish\n if (userErrors.length) {\n const userErrors = themePublish.userErrors.map((error) => error.message).join(', ')\n throw new AbortError(userErrors)\n }\n\n if (!theme) {\n // An unexpected error if neither theme nor userErrors are returned\n unexpectedGraphQLError('Failed to update theme')\n }\n\n return buildTheme({\n id: parseGid(theme.id),\n name: theme.name,\n role: theme.role.toLowerCase(),\n })\n}\n\nexport async function themeDelete(id: number, session: AdminSession): Promise<boolean | undefined> {\n const {themeDelete} = await adminRequestDoc(ThemeDelete, session, {id: composeThemeGid(id)})\n if (!themeDelete) {\n // An unexpected error occurred during the GraphQL request execution\n unexpectedGraphQLError('Failed to update theme')\n }\n\n const {deletedThemeId, userErrors} = themeDelete\n if (userErrors.length) {\n const userErrors = themeDelete.userErrors.map((error) => error.message).join(', ')\n throw new AbortError(userErrors)\n }\n\n if (!deletedThemeId) {\n // An unexpected error if neither theme nor userErrors are returned\n unexpectedGraphQLError('Failed to update theme')\n }\n\n return true\n}\n\nasync function request<T>(\n method: string,\n path: string,\n session: AdminSession,\n params?: T,\n searchParams: {[name: string]: string} = {},\n retries = 1,\n): Promise<RestResponse> {\n const response = await throttler.throttle(() => restRequest(method, path, session, params, searchParams))\n\n const status = response.status\n\n throttler.updateApiCallLimitFromResponse(response)\n\n switch (true) {\n case status >= 200 && status <= 399:\n // Returns the successful reponse\n return response\n case status === 404:\n // Defer the decision when a resource is not found\n return response\n case status === 429:\n // Retry following the \"retry-after\" header\n return throttler.delayAwareRetry(response, () => request(method, path, session, params, searchParams))\n case status === 403:\n return handleForbiddenError(response, session)\n case status === 401:\n /**\n * We need to resolve the call to the refresh function at runtime to\n * avoid a circular reference.\n *\n * This won't be necessary when https://github.com/Shopify/cli/issues/4769\n * gets resolved, and this condition must be removed then.\n */\n if ('refresh' in session) {\n const refresh = session.refresh as () => Promise<void>\n await refresh()\n }\n\n // Retry 401 errors to be resilient to authentication errors.\n return handleRetriableError({\n path,\n retries,\n retry: () => {\n return request(method, path, session, params, searchParams, retries + 1)\n },\n fail: () => {\n throw new AbortError(`[${status}] API request unauthorized error`)\n },\n })\n case status === 422:\n throw new AbortError(`[${status}] API request unprocessable content: ${errors(response)}`)\n case status >= 400 && status <= 499:\n throw new AbortError(`[${status}] API request client error`)\n case status >= 500 && status <= 599:\n // Retry 500-family of errors as that may solve the issue (especially in 503 errors)\n return handleRetriableError({\n path,\n retries,\n retry: () => {\n return request(method, path, session, params, searchParams, retries + 1)\n },\n fail: () => {\n throw new AbortError(`[${status}] API request server error`)\n },\n })\n default:\n throw new AbortError(`[${status}] API request unexpected error`)\n }\n}\n\nfunction handleForbiddenError(response: RestResponse, session: AdminSession): never {\n const store = session.storeFqdn\n const adminUrl = storeAdminUrl(session)\n const error = errorMessage(response)\n\n if (error.match(/Cannot delete generated asset/) !== null) {\n throw new AbortError(error)\n }\n\n throw new AbortError(\n `You are not authorized to edit themes on \"${store}\".`,\n \"You can't use Shopify CLI with development stores if you only have Partner staff \" +\n 'member access. If you want to use Shopify CLI to work on a development store, then ' +\n 'you should be the store owner or create a staff account on the store.' +\n '\\n\\n' +\n \"If you're the store owner, then you need to log in to the store directly using the \" +\n `store URL at least once (for example, using \"${adminUrl}\") before you log in using ` +\n 'Shopify CLI. Logging in to the Shopify admin directly connects the development ' +\n 'store with your Shopify login.',\n )\n}\n\nfunction errors(response: RestResponse) {\n return JSON.stringify(response.json?.errors)\n}\n\nfunction errorMessage(response: RestResponse): string {\n const message = response.json?.message\n\n if (typeof message === 'string') {\n return message\n }\n\n return ''\n}\n\nfunction unexpectedGraphQLError(message: string): never {\n throw new AbortError(message)\n}\n\ninterface RetriableErrorOptions {\n path: string\n retries: number\n retry: () => Promise<RestResponse>\n fail: () => never\n}\n\nasync function handleRetriableError({path, retries, retry, fail}: RetriableErrorOptions): Promise<RestResponse> {\n if (retries >= 3) {\n fail()\n }\n\n outputDebug(`[${retries}] Retrying '${path}' request...`)\n\n await sleep(0.2)\n return retry()\n}\n\nfunction themeGid(id: number): string {\n return `gid://shopify/OnlineStoreTheme/${id}`\n}\n\ntype OnlineStoreThemeFileBody =\n | {__typename: 'OnlineStoreThemeFileBodyBase64'; contentBase64: string}\n | {__typename: 'OnlineStoreThemeFileBodyText'; content: string}\n | {__typename: 'OnlineStoreThemeFileBodyUrl'; url: string}\n\nasync function parseThemeFileContent(body: OnlineStoreThemeFileBody): Promise<string> {\n switch (body.__typename) {\n case 'OnlineStoreThemeFileBodyText':\n return body.content\n case 'OnlineStoreThemeFileBodyBase64':\n return Buffer.from(body.contentBase64, 'base64').toString()\n case 'OnlineStoreThemeFileBodyUrl':\n try {\n const response = await fetch(body.url)\n return await response.text()\n } catch (error) {\n // Raise error if we can't download the file\n throw new AbortError(`Error downloading content from URL: ${body.url}`)\n }\n }\n}\n"]}
@@ -1,5 +1,4 @@
1
- import { AssetParams } from './api.js';
2
- import { Result, Checksum, Theme, ThemeAsset } from '@shopify/cli-kit/node/themes/types';
1
+ import { Checksum, Theme, ThemeAsset } from '@shopify/cli-kit/node/themes/types';
3
2
  interface RemoteThemeResponse {
4
3
  id: number;
5
4
  name: string;
@@ -26,5 +25,4 @@ export declare function buildTheme(themeJson?: RemoteThemeResponse): Theme | und
26
25
  export declare function buildChecksum(asset?: RemoteAssetResponse): Checksum | undefined;
27
26
  export declare function buildThemeAsset(asset: undefined): undefined;
28
27
  export declare function buildThemeAsset(asset: RemoteAssetResponse): ThemeAsset;
29
- export declare function buildBulkUploadResults(bulkUploadResponse: RemoteBulkUploadResponse[], assets: AssetParams[]): Result[];
30
28
  export {};
@@ -1,4 +1,3 @@
1
- import { Operation } from '@shopify/cli-kit/node/themes/types';
2
1
  export function buildTheme(themeJson) {
3
2
  if (!themeJson)
4
3
  return;
@@ -27,19 +26,4 @@ export function buildThemeAsset(asset) {
27
26
  const stats = { size: (value || attachment || '').length, mtime: Date.now() };
28
27
  return { key, checksum, attachment, value, stats };
29
28
  }
30
- export function buildBulkUploadResults(bulkUploadResponse, assets) {
31
- if (!bulkUploadResponse) {
32
- return [];
33
- }
34
- return bulkUploadResponse.map((bulkUpload, index) => {
35
- return {
36
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
37
- key: assets[index].key,
38
- success: bulkUpload.code === 200,
39
- errors: bulkUpload.body.errors || {},
40
- asset: bulkUpload.body.asset,
41
- operation: Operation.Upload,
42
- };
43
- });
44
- }
45
29
  //# sourceMappingURL=factories.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"factories.js","sourceRoot":"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C,EAC9C,MAAqB;IAErB,IAAI,CAAC,kBAAkB,EAAE;QACvB,OAAO,EAAE,CAAA;KACV;IAED,OAAO,kBAAkB,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,KAAK,EAAE,EAAE;QAClD,OAAO;YACL,oEAAoE;YACpE,GAAG,EAAE,MAAM,CAAC,KAAK,CAAE,CAAC,GAAG;YACvB,OAAO,EAAE,UAAU,CAAC,IAAI,KAAK,GAAG;YAChC,MAAM,EAAE,UAAU,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE;YACpC,KAAK,EAAE,UAAU,CAAC,IAAI,CAAC,KAAK;YAC5B,SAAS,EAAE,SAAS,CAAC,MAAM;SAC5B,CAAA;IACH,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import {AssetParams} from './api.js'\nimport {Result, Checksum, Theme, ThemeAsset, Operation} from '@shopify/cli-kit/node/themes/types'\n\ninterface RemoteThemeResponse {\n id: number\n name: string\n role: string\n createdAtRuntime?: boolean\n processing?: boolean\n}\n\ninterface RemoteAssetResponse {\n key: string\n checksum: string\n attachment: string | undefined\n // value is an empty string ('') when the file is empty\n value: string\n}\n\nexport interface RemoteBulkUploadResponse {\n body: {asset?: RemoteAssetResponse; errors?: {asset: string[]}}\n code: number\n}\n\nexport function buildTheme(themeJson?: RemoteThemeResponse): Theme | undefined {\n if (!themeJson) return\n\n themeJson.processing ??= false\n themeJson.createdAtRuntime ??= false\n\n const {id, name, role, processing, createdAtRuntime} = themeJson\n\n return {\n id,\n name,\n processing,\n createdAtRuntime,\n role: role === 'main' ? 'live' : role,\n }\n}\n\nexport function buildChecksum(asset?: RemoteAssetResponse): Checksum | undefined {\n if (!asset) return\n\n const {key, checksum} = asset\n return {key, checksum}\n}\n\nexport function buildThemeAsset(asset: undefined): undefined\nexport function buildThemeAsset(asset: RemoteAssetResponse): ThemeAsset\nexport function buildThemeAsset(asset?: RemoteAssetResponse): ThemeAsset | undefined {\n if (!asset) return\n\n const {key, checksum, attachment, value} = asset\n // Note: for attachments, this is the size of the base64 string, not the real length of the file\n const stats = {size: (value || attachment || '').length, mtime: Date.now()}\n return {key, checksum, attachment, value, stats}\n}\n\nexport function buildBulkUploadResults(\n bulkUploadResponse: RemoteBulkUploadResponse[],\n assets: AssetParams[],\n): Result[] {\n if (!bulkUploadResponse) {\n return []\n }\n\n return bulkUploadResponse.map((bulkUpload, index) => {\n return {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n key: assets[index]!.key,\n success: bulkUpload.code === 200,\n errors: bulkUpload.body.errors || {},\n asset: bulkUpload.body.asset,\n operation: Operation.Upload,\n }\n })\n}\n"]}
1
+ {"version":3,"file":"factories.js","sourceRoot":"","sources":["../../../../src/public/node/themes/factories.ts"],"names":[],"mappings":"AAuBA,MAAM,UAAU,UAAU,CAAC,SAA+B;IACxD,IAAI,CAAC,SAAS;QAAE,OAAM;IAEtB,SAAS,CAAC,UAAU,KAApB,SAAS,CAAC,UAAU,GAAK,KAAK,EAAA;IAC9B,SAAS,CAAC,gBAAgB,KAA1B,SAAS,CAAC,gBAAgB,GAAK,KAAK,EAAA;IAEpC,MAAM,EAAC,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,UAAU,EAAE,gBAAgB,EAAC,GAAG,SAAS,CAAA;IAEhE,OAAO;QACL,EAAE;QACF,IAAI;QACJ,UAAU;QACV,gBAAgB;QAChB,IAAI,EAAE,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI;KACtC,CAAA;AACH,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,KAA2B;IACvD,IAAI,CAAC,KAAK;QAAE,OAAM;IAElB,MAAM,EAAC,GAAG,EAAE,QAAQ,EAAC,GAAG,KAAK,CAAA;IAC7B,OAAO,EAAC,GAAG,EAAE,QAAQ,EAAC,CAAA;AACxB,CAAC;AAID,MAAM,UAAU,eAAe,CAAC,KAA2B;IACzD,IAAI,CAAC,KAAK;QAAE,OAAM;IAElB,MAAM,EAAC,GAAG,EAAE,QAAQ,EAAE,UAAU,EAAE,KAAK,EAAC,GAAG,KAAK,CAAA;IAChD,gGAAgG;IAChG,MAAM,KAAK,GAAG,EAAC,IAAI,EAAE,CAAC,KAAK,IAAI,UAAU,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI,CAAC,GAAG,EAAE,EAAC,CAAA;IAC3E,OAAO,EAAC,GAAG,EAAE,QAAQ,EAAE,UAAU,EAAE,KAAK,EAAE,KAAK,EAAC,CAAA;AAClD,CAAC","sourcesContent":["import {Checksum, Theme, ThemeAsset} from '@shopify/cli-kit/node/themes/types'\n\ninterface RemoteThemeResponse {\n id: number\n name: string\n role: string\n createdAtRuntime?: boolean\n processing?: boolean\n}\n\ninterface RemoteAssetResponse {\n key: string\n checksum: string\n attachment: string | undefined\n // value is an empty string ('') when the file is empty\n value: string\n}\n\nexport interface RemoteBulkUploadResponse {\n body: {asset?: RemoteAssetResponse; errors?: {asset: string[]}}\n code: number\n}\n\nexport function buildTheme(themeJson?: RemoteThemeResponse): Theme | undefined {\n if (!themeJson) return\n\n themeJson.processing ??= false\n themeJson.createdAtRuntime ??= false\n\n const {id, name, role, processing, createdAtRuntime} = themeJson\n\n return {\n id,\n name,\n processing,\n createdAtRuntime,\n role: role === 'main' ? 'live' : role,\n }\n}\n\nexport function buildChecksum(asset?: RemoteAssetResponse): Checksum | undefined {\n if (!asset) return\n\n const {key, checksum} = asset\n return {key, checksum}\n}\n\nexport function buildThemeAsset(asset: undefined): undefined\nexport function buildThemeAsset(asset: RemoteAssetResponse): ThemeAsset\nexport function buildThemeAsset(asset?: RemoteAssetResponse): ThemeAsset | undefined {\n if (!asset) return\n\n const {key, checksum, attachment, value} = asset\n // Note: for attachments, this is the size of the base64 string, not the real length of the file\n const stats = {size: (value || attachment || '').length, mtime: Date.now()}\n return {key, checksum, attachment, value, stats}\n}\n"]}
@@ -3,7 +3,6 @@
3
3
  /* eslint-disable jsdoc/require-throws */
4
4
  /* eslint-disable no-restricted-imports */
5
5
  import { outputDebug } from './output.js';
6
- import { printEventsJson } from '../../private/node/demo-recorder.js';
7
6
  import { exec, spawn } from 'child_process';
8
7
  /**
9
8
  * Kills the process that calls the method and all its children.
@@ -19,7 +18,6 @@ export function treeKill(pid = process.pid, killSignal = 'SIGTERM', killRoot = t
19
18
  if (error)
20
19
  outputDebug(`Failed to kill process ${pid}: ${error}`);
21
20
  });
22
- printEventsJson();
23
21
  adaptedTreeKill(pid, killSignal, killRoot, after);
24
22
  }
25
23
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"tree-kill.js","sourceRoot":"","sources":["../../../src/public/node/tree-kill.ts"],"names":[],"mappings":"AAAA,6DAA6D;AAC7D,sDAAsD;AACtD,yCAAyC;AACzC,0CAA0C;AAE1C,OAAO,EAAC,WAAW,EAAC,MAAM,aAAa,CAAA;AACvC,OAAO,EAAC,eAAe,EAAC,MAAM,qCAAqC,CAAA;AACnE,OAAO,EAAC,IAAI,EAAE,KAAK,EAAC,MAAM,eAAe,CAAA;AAQzC;;;;;;;GAOG;AACH,MAAM,UAAU,QAAQ,CACtB,MAAuB,OAAO,CAAC,GAAG,EAClC,UAAU,GAAG,SAAS,EACtB,QAAQ,GAAG,IAAI,EACf,QAA4B;IAE5B,MAAM,KAAK,GACT,QAAQ;QACR,CAAC,CAAC,KAAa,EAAE,EAAE;YACjB,IAAI,KAAK;gBAAE,WAAW,CAAC,0BAA0B,GAAG,KAAK,KAAK,EAAE,CAAC,CAAA;QACnE,CAAC,CAAC,CAAA;IACJ,eAAe,EAAE,CAAA;IACjB,eAAe,CAAC,GAAG,EAAE,UAAU,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;AACnD,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,SAAS,eAAe,CACtB,GAAoB,EACpB,UAAkB,EAClB,QAAiB,EACjB,QAAiC;IAEjC,MAAM,OAAO,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,GAA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AAE,IAAI,EAAE,aAAa,EAAE,uBAAuB,EAAE,EAAE,CAAC,CAAA;aACxE;QACH,CAAC,CAAC,CAAA;IACN,CAAC,CAAA;IAED,EAAE,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;AACzB,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/* eslint-disable @typescript-eslint/ban-ts-comment */\n/* eslint-disable jsdoc/require-throws */\n/* eslint-disable no-restricted-imports */\n\nimport {outputDebug} from './output.js'\nimport {printEventsJson} from '../../private/node/demo-recorder.js'\nimport {exec, spawn} from 'child_process'\n\ninterface ProcessTree {\n [key: string]: string[]\n}\n\ntype AfterKillCallback = (error?: Error) => void\n\n/**\n * Kills the process that calls the method and all its children.\n *\n * @param pid - Pid of the process to kill.\n * @param killSignal - Type of kill signal to be used.\n * @param killRoot - Whether to kill the root process.\n * @param callback - Optional callback to run after killing the processes.\n */\nexport function treeKill(\n pid: number | string = process.pid,\n killSignal = 'SIGTERM',\n killRoot = true,\n callback?: AfterKillCallback,\n): void {\n const after =\n callback ??\n ((error?: Error) => {\n if (error) outputDebug(`Failed to kill process ${pid}: ${error}`)\n })\n printEventsJson()\n adaptedTreeKill(pid, killSignal, killRoot, after)\n}\n\n/**\n * Adapted from https://github.com/pkrumins/node-tree-kill.\n *\n * Our implementation allows to skip killing the root process. This is useful for example when\n * gracefully exiting the 'dev' process, as the default tree-kill implementation will cause it\n * to exit with a non-zero code. Instead, we want to treat it as a graceful termination.\n * In addition, we also add debug logging for better visibility in what tree-kill is doing.\n *\n * @param pid - Pid of the process to kill.\n * @param killSignal - Type of kill signal to be used.\n * @param killRoot - Whether to kill the root process.\n * @param callback - Optional callback to run after killing the processes.\n */\nfunction adaptedTreeKill(\n pid: number | string,\n killSignal: string,\n killRoot: boolean,\n callback: (error?: Error) => void,\n): void {\n const rootPid = typeof pid === 'number' ? pid.toString() : pid\n\n if (Number.isNaN(rootPid)) {\n if (callback) {\n callback(new Error('pid must be a number'))\n return\n } else {\n throw new Error('pid must be a number')\n }\n }\n\n // A map from parent pid to an array of children pids\n const tree: ProcessTree = {}\n tree[rootPid] = []\n\n // A set of pids to visit. We use it to recursively find all the children pids\n const pidsToProcess = new Set<string>()\n pidsToProcess.add(rootPid)\n\n switch (process.platform) {\n case 'win32':\n // @ts-ignore\n exec(`taskkill /pid ${pid} /T /F`, callback)\n break\n case 'darwin':\n buildProcessTree(\n rootPid,\n tree,\n pidsToProcess,\n function (parentPid: string) {\n return spawn('pgrep', ['-lfP', parentPid])\n },\n function () {\n killAll(tree, killSignal, rootPid, killRoot, callback)\n },\n )\n break\n // Linux\n default:\n buildProcessTree(\n rootPid,\n tree,\n pidsToProcess,\n function (parentPid: string) {\n return spawn('ps', ['-o', 'pid command', '--no-headers', '--ppid', parentPid])\n },\n function () {\n killAll(tree, killSignal, rootPid, killRoot, callback)\n },\n )\n break\n }\n}\n\n/**\n * Kills all processes in the process tree.\n *\n * @param tree - Process tree.\n * @param killSignal - Type of kill signal to be used.\n * @param rootPid - Pid of the root process.\n * @param killRoot - Whether to kill the root process.\n * @param callback - Optional callback to run after killing the processes.\n */\nfunction killAll(\n tree: ProcessTree,\n killSignal: string,\n rootPid: string,\n killRoot: boolean,\n callback: AfterKillCallback,\n): void {\n const killed = new Set<string>()\n try {\n Object.keys(tree).forEach(function (pid) {\n tree[pid]!.forEach(function (pidpid) {\n if (!killed.has(pidpid)) {\n killPid(pidpid, killSignal)\n killed.add(pidpid)\n }\n })\n if (pid === rootPid && killRoot && !killed.has(pid)) {\n killPid(pid, killSignal)\n killed.add(pid)\n }\n })\n } catch (err: unknown) {\n if (callback) {\n // @ts-ignore\n callback(err)\n return\n } else {\n throw err\n }\n }\n if (callback) {\n callback()\n }\n}\n\n/**\n * Kills a process.\n *\n * @param pid - Pid of the process to kill.\n * @param killSignal - Type of kill signal to be used.\n */\nfunction killPid(pid: string, killSignal: string) {\n try {\n process.kill(parseInt(pid, 10), killSignal)\n } catch (err) {\n // @ts-ignore\n if (err.code !== 'ESRCH') throw err\n }\n}\n\n/**\n * Builds a process tree.\n *\n * @param parentPid - Pid of the parent process.\n * @param tree - Process tree.\n * @param pidsToProcess - Pids to process.\n * @param spawnChildProcessesList - Function to spawn child processes.\n * @param cb - Callback to run after building the process tree.\n */\nfunction buildProcessTree(\n parentPid: string,\n tree: ProcessTree,\n pidsToProcess: Set<string>,\n spawnChildProcessesList: (parentPid: string) => ReturnType<typeof spawn>,\n cb: () => void,\n) {\n const ps = spawnChildProcessesList(parentPid)\n let allData = ''\n ps.stdout?.on('data', function (data: Buffer) {\n const dataStr = data.toString('ascii')\n allData += dataStr\n })\n\n const onClose = (code: number) => {\n pidsToProcess.delete(parentPid)\n\n if (code !== 0) {\n // no more parent processes\n if (pidsToProcess.size === 0) {\n cb()\n return\n }\n return\n }\n\n allData\n .trim()\n .split('\\n')\n .forEach(function (line) {\n const match = line.match(/^(\\d+)\\s(.*)$/)\n if (match) {\n const pid = match[1]!\n const cmd = match[2]!\n tree[parentPid]!.push(pid)\n tree[pid] = []\n outputDebug(`Killing process ${pid}: ${cmd}`)\n pidsToProcess.add(pid)\n buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb)\n }\n })\n }\n\n ps.on('close', onClose)\n}\n"]}
1
+ {"version":3,"file":"tree-kill.js","sourceRoot":"","sources":["../../../src/public/node/tree-kill.ts"],"names":[],"mappings":"AAAA,6DAA6D;AAC7D,sDAAsD;AACtD,yCAAyC;AACzC,0CAA0C;AAE1C,OAAO,EAAC,WAAW,EAAC,MAAM,aAAa,CAAA;AACvC,OAAO,EAAC,IAAI,EAAE,KAAK,EAAC,MAAM,eAAe,CAAA;AAQzC;;;;;;;GAOG;AACH,MAAM,UAAU,QAAQ,CACtB,MAAuB,OAAO,CAAC,GAAG,EAClC,UAAU,GAAG,SAAS,EACtB,QAAQ,GAAG,IAAI,EACf,QAA4B;IAE5B,MAAM,KAAK,GACT,QAAQ;QACR,CAAC,CAAC,KAAa,EAA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T,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,CAAE,CAAA;gBACrB,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,CAAE,CAAA;gBACrB,IAAI,CAAC,SAAS,CAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;gBAC1B,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,CAAA;gBACd,WAAW,CAAC,mBAAmB,GAAG,KAAK,GAAG,EAAE,CAAC,CAAA;gBAC7C,aAAa,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;gBACtB,gBAAgB,CAAC,GAAG,EAAE,IAAI,EAAE,aAAa,EAAE,uBAAuB,EAAE,EAAE,CAAC,CAAA;aACxE;QACH,CAAC,CAAC,CAAA;IACN,CAAC,CAAA;IAED,EAAE,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;AACzB,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/* eslint-disable @typescript-eslint/ban-ts-comment */\n/* eslint-disable jsdoc/require-throws */\n/* eslint-disable no-restricted-imports */\n\nimport {outputDebug} from './output.js'\nimport {exec, spawn} from 'child_process'\n\ninterface ProcessTree {\n [key: string]: string[]\n}\n\ntype AfterKillCallback = (error?: Error) => void\n\n/**\n * Kills the process that calls the method and all its children.\n *\n * @param pid - Pid of the process to kill.\n * @param killSignal - Type of kill signal to be used.\n * @param killRoot - Whether to kill the root process.\n * @param callback - Optional callback to run after killing the processes.\n */\nexport function treeKill(\n pid: number | string = process.pid,\n killSignal = 'SIGTERM',\n killRoot = true,\n callback?: AfterKillCallback,\n): void {\n const after =\n callback ??\n ((error?: Error) => {\n if (error) outputDebug(`Failed to kill process ${pid}: ${error}`)\n })\n adaptedTreeKill(pid, killSignal, killRoot, after)\n}\n\n/**\n * Adapted from https://github.com/pkrumins/node-tree-kill.\n *\n * Our implementation allows to skip killing the root process. This is useful for example when\n * gracefully exiting the 'dev' process, as the default tree-kill implementation will cause it\n * to exit with a non-zero code. Instead, we want to treat it as a graceful termination.\n * In addition, we also add debug logging for better visibility in what tree-kill is doing.\n *\n * @param pid - Pid of the process to kill.\n * @param killSignal - Type of kill signal to be used.\n * @param killRoot - Whether to kill the root process.\n * @param callback - Optional callback to run after killing the processes.\n */\nfunction adaptedTreeKill(\n pid: number | string,\n killSignal: string,\n killRoot: boolean,\n callback: (error?: Error) => void,\n): void {\n const rootPid = typeof pid === 'number' ? pid.toString() : pid\n\n if (Number.isNaN(rootPid)) {\n if (callback) {\n callback(new Error('pid must be a number'))\n return\n } else {\n throw new Error('pid must be a number')\n }\n }\n\n // A map from parent pid to an array of children pids\n const tree: ProcessTree = {}\n tree[rootPid] = []\n\n // A set of pids to visit. We use it to recursively find all the children pids\n const pidsToProcess = new Set<string>()\n pidsToProcess.add(rootPid)\n\n switch (process.platform) {\n case 'win32':\n // @ts-ignore\n exec(`taskkill /pid ${pid} /T /F`, callback)\n break\n case 'darwin':\n buildProcessTree(\n rootPid,\n tree,\n pidsToProcess,\n function (parentPid: string) {\n return spawn('pgrep', ['-lfP', parentPid])\n },\n function () {\n killAll(tree, killSignal, rootPid, killRoot, callback)\n },\n )\n break\n // Linux\n default:\n buildProcessTree(\n rootPid,\n tree,\n pidsToProcess,\n function (parentPid: string) {\n return spawn('ps', ['-o', 'pid command', '--no-headers', '--ppid', parentPid])\n },\n function () {\n killAll(tree, killSignal, rootPid, killRoot, callback)\n },\n )\n break\n }\n}\n\n/**\n * Kills all processes in the process tree.\n *\n * @param tree - Process tree.\n * @param killSignal - Type of kill signal to be used.\n * @param rootPid - Pid of the root process.\n * @param killRoot - Whether to kill the root process.\n * @param callback - Optional callback to run after killing the processes.\n */\nfunction killAll(\n tree: ProcessTree,\n killSignal: string,\n rootPid: string,\n killRoot: boolean,\n callback: AfterKillCallback,\n): void {\n const killed = new Set<string>()\n try {\n Object.keys(tree).forEach(function (pid) {\n tree[pid]!.forEach(function (pidpid) {\n if (!killed.has(pidpid)) {\n killPid(pidpid, killSignal)\n killed.add(pidpid)\n }\n })\n if (pid === rootPid && killRoot && !killed.has(pid)) {\n killPid(pid, killSignal)\n killed.add(pid)\n }\n })\n } catch (err: unknown) {\n if (callback) {\n // @ts-ignore\n callback(err)\n return\n } else {\n throw err\n }\n }\n if (callback) {\n callback()\n }\n}\n\n/**\n * Kills a process.\n *\n * @param pid - Pid of the process to kill.\n * @param killSignal - Type of kill signal to be used.\n */\nfunction killPid(pid: string, killSignal: string) {\n try {\n process.kill(parseInt(pid, 10), killSignal)\n } catch (err) {\n // @ts-ignore\n if (err.code !== 'ESRCH') throw err\n }\n}\n\n/**\n * Builds a process tree.\n *\n * @param parentPid - Pid of the parent process.\n * @param tree - Process tree.\n * @param pidsToProcess - Pids to process.\n * @param spawnChildProcessesList - Function to spawn child processes.\n * @param cb - Callback to run after building the process tree.\n */\nfunction buildProcessTree(\n parentPid: string,\n tree: ProcessTree,\n pidsToProcess: Set<string>,\n spawnChildProcessesList: (parentPid: string) => ReturnType<typeof spawn>,\n cb: () => void,\n) {\n const ps = spawnChildProcessesList(parentPid)\n let allData = ''\n ps.stdout?.on('data', function (data: Buffer) {\n const dataStr = data.toString('ascii')\n allData += dataStr\n })\n\n const onClose = (code: number) => {\n pidsToProcess.delete(parentPid)\n\n if (code !== 0) {\n // no more parent processes\n if (pidsToProcess.size === 0) {\n cb()\n return\n }\n return\n }\n\n allData\n .trim()\n .split('\\n')\n .forEach(function (line) {\n const match = line.match(/^(\\d+)\\s(.*)$/)\n if (match) {\n const pid = match[1]!\n const cmd = match[2]!\n tree[parentPid]!.push(pid)\n tree[pid] = []\n outputDebug(`Killing process ${pid}: ${cmd}`)\n pidsToProcess.add(pid)\n buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb)\n }\n })\n }\n\n ps.on('close', onClose)\n}\n"]}