@shopify/cli 3.63.2 → 3.64.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/dist/assets/cli-ruby/lib/shopify_cli/reporting_configuration_controller.rb +2 -37
  2. package/dist/assets/cli-ruby/lib/shopify_cli/theme/file.rb +5 -1
  3. package/dist/assets/dev-console/extensions/dev-console/assets/index-Cgb-oKsM.css +1 -0
  4. package/dist/assets/dev-console/extensions/dev-console/assets/{index-Dui3DO9f.js → index-D7F9wNys.js} +12 -12
  5. package/dist/assets/dev-console/index.html +2 -2
  6. package/dist/assets/hydrogen/starter/.graphqlrc.ts +27 -0
  7. package/dist/assets/hydrogen/starter/CHANGELOG.md +108 -6
  8. package/dist/assets/hydrogen/starter/app/components/AddToCartButton.tsx +37 -0
  9. package/dist/assets/hydrogen/starter/app/components/CartLineItem.tsx +150 -0
  10. package/dist/assets/hydrogen/starter/app/components/CartMain.tsx +68 -0
  11. package/dist/assets/hydrogen/starter/app/components/CartSummary.tsx +101 -0
  12. package/dist/assets/hydrogen/starter/app/components/Header.tsx +3 -3
  13. package/dist/assets/hydrogen/starter/app/components/PageLayout.tsx +2 -2
  14. package/dist/assets/hydrogen/starter/app/components/ProductForm.tsx +80 -0
  15. package/dist/assets/hydrogen/starter/app/components/ProductImage.tsx +23 -0
  16. package/dist/assets/hydrogen/starter/app/components/ProductPrice.tsx +27 -0
  17. package/dist/assets/hydrogen/starter/app/root.tsx +11 -17
  18. package/dist/assets/hydrogen/starter/app/routes/cart.tsx +1 -1
  19. package/dist/assets/hydrogen/starter/app/routes/products.$handle.tsx +51 -232
  20. package/dist/assets/hydrogen/starter/package.json +11 -11
  21. package/dist/assets/hydrogen/tailwind/package.json +1 -6
  22. package/dist/assets/hydrogen/tailwind/tailwind.css +6 -3
  23. package/dist/assets/hydrogen/vanilla-extract/package.json +2 -3
  24. package/dist/assets/hydrogen/virtual-routes/components/{Layout.jsx → PageLayout.jsx} +2 -2
  25. package/dist/assets/hydrogen/virtual-routes/virtual-root.jsx +8 -30
  26. package/dist/{chunk-YAYFJITA.js → chunk-2DXCIFDK.js} +3 -3
  27. package/dist/{chunk-EQR6CWKL.js → chunk-63D4EGTO.js} +3 -3
  28. package/dist/{chunk-EZYMDZPN.js → chunk-6PJAGL2L.js} +5 -5
  29. package/dist/{chunk-S4VBXFXP.js → chunk-7PVTYKQI.js} +220 -16
  30. package/dist/{chunk-IRWSC76I.js → chunk-7TIDA343.js} +3 -3
  31. package/dist/{chunk-NPLAQVTF.js → chunk-7W6SRTYP.js} +3 -3
  32. package/dist/{chunk-UJYIV6JP.js → chunk-ARCFCLME.js} +5 -5
  33. package/dist/{chunk-DIZHFZTJ.js → chunk-ATGUMSCJ.js} +4 -4
  34. package/dist/chunk-B3D5VLUA.js +12 -0
  35. package/dist/{chunk-UNPXLODI.js → chunk-B7RN7IRD.js} +3 -4
  36. package/dist/{chunk-5BLMIE7F.js → chunk-DX43V2L4.js} +4 -4
  37. package/dist/{chunk-6UDFXWNE.js → chunk-EJITPGUJ.js} +21 -4
  38. package/dist/chunk-FDLU3RD4.js +29 -0
  39. package/dist/{chunk-7OCUVNSF.js → chunk-H6AQTECB.js} +1485 -2977
  40. package/dist/{chunk-T54B5GJP.js → chunk-JNUJZFQL.js} +2 -2
  41. package/dist/{chunk-XER2L725.js → chunk-KUVX423E.js} +2 -2
  42. package/dist/{chunk-R5KML52V.js → chunk-KZTALMEV.js} +4 -4
  43. package/dist/{chunk-CM4H6QMH.js → chunk-M6KGRVDD.js} +3 -3
  44. package/dist/{chunk-3MDI6LZT.js → chunk-NLE3ZLU6.js} +905 -896
  45. package/dist/{chunk-WADS2TV5.js → chunk-NO7MYZEO.js} +5 -4
  46. package/dist/{chunk-LH533WG4.js → chunk-NPH2SXRO.js} +2 -2
  47. package/dist/{chunk-VZUWS5IH.js → chunk-OVWFZSJT.js} +3 -3
  48. package/dist/{chunk-UQUO22Q5.js → chunk-OXMHVKM3.js} +5 -5
  49. package/dist/{chunk-PNFEODLY.js → chunk-QNI6VLVR.js} +3 -3
  50. package/dist/{chunk-MCT2524Y.js → chunk-QYT42J3T.js} +4 -4
  51. package/dist/{chunk-VQTHQBEC.js → chunk-S3HWVIGJ.js} +9 -14
  52. package/dist/{chunk-23OKKZ5V.js → chunk-S7A7BHNA.js} +4 -4
  53. package/dist/{chunk-3TGMDPDI.js → chunk-SSAUIEBT.js} +2 -2
  54. package/dist/{chunk-YMPGWFWU.js → chunk-UQQI7TQG.js} +3 -3
  55. package/dist/{chunk-UZUD5DRI.js → chunk-UXA5YROL.js} +2 -2
  56. package/dist/{chunk-K3CVGV3F.js → chunk-V7NH4SZB.js} +3 -3
  57. package/dist/{chunk-7AVKIH7O.js → chunk-WVY52EEZ.js} +5 -5
  58. package/dist/{chunk-QEOBHRRQ.js → chunk-X3OUSYUQ.js} +17912 -17444
  59. package/dist/{chunk-EARPFFS7.js → chunk-XNCQBHNR.js} +241 -4
  60. package/dist/{chunk-EQPYUHNM.js → chunk-ZIGJPI5N.js} +1497 -112
  61. package/dist/{chunk-A2UVOX6O.js → chunk-ZKWHKX2C.js} +7066 -6051
  62. package/dist/{chunk-GPMHDCWK.js → chunk-ZRGD2HUL.js} +3 -3
  63. package/dist/{chunk-PQKGBYDC.js → chunk-ZVT2WZZF.js} +3 -3
  64. package/dist/cli/commands/auth/logout.js +14 -19
  65. package/dist/cli/commands/auth/logout.test.js +17 -21
  66. package/dist/cli/commands/debug/command-flags.js +11 -15
  67. package/dist/cli/commands/demo/catalog.js +13 -18
  68. package/dist/cli/commands/demo/generate-file.js +13 -18
  69. package/dist/cli/commands/demo/index.js +13 -18
  70. package/dist/cli/commands/demo/print-ai-prompt.js +13 -18
  71. package/dist/cli/commands/docs/generate.js +11 -15
  72. package/dist/cli/commands/docs/generate.test.js +11 -15
  73. package/dist/cli/commands/help.js +11 -15
  74. package/dist/cli/commands/kitchen-sink/async.js +12 -16
  75. package/dist/cli/commands/kitchen-sink/async.test.js +12 -16
  76. package/dist/cli/commands/kitchen-sink/index.js +14 -18
  77. package/dist/cli/commands/kitchen-sink/index.test.js +14 -18
  78. package/dist/cli/commands/kitchen-sink/prompts.js +12 -16
  79. package/dist/cli/commands/kitchen-sink/prompts.test.js +12 -16
  80. package/dist/cli/commands/kitchen-sink/static.js +12 -16
  81. package/dist/cli/commands/kitchen-sink/static.test.js +12 -16
  82. package/dist/cli/commands/search.js +12 -16
  83. package/dist/cli/commands/upgrade.js +11 -15
  84. package/dist/cli/commands/version.js +12 -16
  85. package/dist/cli/commands/version.test.js +12 -16
  86. package/dist/cli/services/commands/search.js +4 -4
  87. package/dist/cli/services/commands/search.test.js +4 -4
  88. package/dist/cli/services/commands/version.js +6 -7
  89. package/dist/cli/services/commands/version.test.js +7 -8
  90. package/dist/cli/services/demo.js +5 -6
  91. package/dist/cli/services/demo.test.js +5 -6
  92. package/dist/cli/services/kitchen-sink/async.js +4 -4
  93. package/dist/cli/services/kitchen-sink/prompts.js +4 -4
  94. package/dist/cli/services/kitchen-sink/static.js +4 -4
  95. package/dist/cli/services/upgrade.js +5 -6
  96. package/dist/cli/services/upgrade.test.js +7 -8
  97. package/dist/{constants-3CLHB4LQ.js → constants-EVER32LA.js} +3 -3
  98. package/dist/{custom-oclif-loader-D4H5EJW6.js → custom-oclif-loader-BQAFOUNG.js} +13 -6
  99. package/dist/{error-handler-HUI4HW3X.js → error-handler-S56KHSGD.js} +10 -8
  100. package/dist/hooks/postrun.js +12 -14
  101. package/dist/hooks/prerun.js +8 -11
  102. package/dist/index.js +7811 -7490
  103. package/dist/{local-7IRDZWLW.js → local-UQAQKOVL.js} +4 -4
  104. package/dist/{morph-6NYGHGNT.js → morph-DN4AZJZW.js} +9 -9
  105. package/dist/{node-UIH7JP3D.js → node-GZYZUMBW.js} +21 -19
  106. package/dist/{node-package-manager-2LWT2MNN.js → node-package-manager-AOVZD6TP.js} +5 -6
  107. package/dist/{path-JVVXOELJ.js → path-KUSF6CYC.js} +2 -2
  108. package/dist/{system-4HHX42JS.js → system-G7DVECOP.js} +4 -4
  109. package/dist/templates/ui-extensions/projects/web_pixel_extension/package.json.liquid +1 -1
  110. package/dist/tsconfig.tsbuildinfo +1 -1
  111. package/dist/{ui-NFBKMC4P.js → ui-2AOZFYFM.js} +4 -4
  112. package/dist/{workerd-4HFD3PS4.js → workerd-2MO23YDQ.js} +22 -19
  113. package/oclif.manifest.json +265 -4
  114. package/package.json +7 -10
  115. package/dist/assets/dev-console/extensions/dev-console/assets/index-Bi7y6lI5.css +0 -1
  116. package/dist/assets/hydrogen/css-modules/package.json +0 -6
  117. package/dist/assets/hydrogen/postcss/package.json +0 -10
  118. package/dist/assets/hydrogen/postcss/postcss.config.js +0 -8
  119. package/dist/assets/hydrogen/starter/.graphqlrc.yml +0 -12
  120. package/dist/assets/hydrogen/starter/app/components/Cart.tsx +0 -364
  121. package/dist/assets/hydrogen/tailwind/postcss.config.js +0 -10
  122. package/dist/assets/hydrogen/tailwind/tailwind.config.js +0 -8
  123. package/dist/chunk-4WBV3WP3.js +0 -221
  124. package/dist/chunk-OWICSMFV.js +0 -12
  125. package/dist/chunk-QCDYZY46.js +0 -1070
  126. package/dist/chunk-QEKTVN5A.js +0 -4385
  127. package/dist/chunk-QOUOFEGO.js +0 -35
  128. package/dist/chunk-WP234IUO.js +0 -265
  129. package/dist/chunk-XLPMGRR3.js +0 -496
  130. package/dist/chunk-XSKJYEAZ.js +0 -1453
  131. package/dist/error-handler-QDDLQDOJ.js +0 -43
@@ -1,1070 +0,0 @@
1
- import {
2
- ClientError,
3
- fetch,
4
- require_form_data,
5
- require_src,
6
- require_src2,
7
- require_src3,
8
- require_src4,
9
- require_src5,
10
- require_src6
11
- } from "./chunk-A2UVOX6O.js";
12
- import {
13
- getEnvironmentData,
14
- getSensitiveEnvironmentData
15
- } from "./chunk-VQTHQBEC.js";
16
- import {
17
- platformAndArch
18
- } from "./chunk-YAYFJITA.js";
19
- import {
20
- CLI_KIT_VERSION
21
- } from "./chunk-OWICSMFV.js";
22
- import {
23
- require_semver
24
- } from "./chunk-PRJ3U7MR.js";
25
- import {
26
- AbortError,
27
- AbortSilentError,
28
- alwaysLogAnalytics,
29
- alwaysLogMetrics,
30
- analyticsDisabled,
31
- appendFile,
32
- captureOutput,
33
- exec,
34
- fileExists,
35
- findPathUp,
36
- firstPartyDev,
37
- getAllPublicMetadata,
38
- getAllSensitiveMetadata,
39
- getArrayContainsDuplicates,
40
- getArrayRejectingUndefined,
41
- import_ts_error,
42
- isShopify,
43
- isSpinEnvironment,
44
- isTruthy,
45
- isUnitTest,
46
- mkdir,
47
- opentelemetryDomain,
48
- outputContent,
49
- outputDebug,
50
- outputToken,
51
- readFile,
52
- runWithTimer,
53
- serviceEnvironment,
54
- spinFqdn,
55
- touchFile,
56
- useEmbeddedThemeCLI
57
- } from "./chunk-3MDI6LZT.js";
58
- import {
59
- envPaths,
60
- environmentVariables,
61
- pathConstants,
62
- systemEnvironmentVariables
63
- } from "./chunk-WADS2TV5.js";
64
- import {
65
- cwd,
66
- dirname,
67
- joinPath
68
- } from "./chunk-UNPXLODI.js";
69
- import {
70
- __toESM,
71
- init_cjs_shims
72
- } from "./chunk-ZPL24Y2D.js";
73
-
74
- // ../cli-kit/src/public/node/plugins.ts
75
- init_cjs_shims();
76
- async function fanoutHooks(config, event, options, timeout) {
77
- const res = await config.runHook(event, options, timeout);
78
- return Object.fromEntries(res.successes.map(({ result, plugin }) => [plugin.name, result]));
79
- }
80
- async function getListOfTunnelPlugins(config) {
81
- const hooks = await fanoutHooks(config, "tunnel_provider", {});
82
- const names = getArrayRejectingUndefined(Object.values(hooks).map((key) => key?.name));
83
- if (getArrayContainsDuplicates(names))
84
- return { plugins: names, error: "multiple-plugins-for-provider" };
85
- return { plugins: names };
86
- }
87
-
88
- // ../cli-kit/src/public/node/analytics.ts
89
- init_cjs_shims();
90
-
91
- // ../cli-kit/src/public/node/ruby.ts
92
- init_cjs_shims();
93
-
94
- // ../cli-kit/src/public/node/environment.ts
95
- init_cjs_shims();
96
- function getEnvironmentVariables() {
97
- return process.env;
98
- }
99
- function getPartnersToken() {
100
- return getEnvironmentVariables()[environmentVariables.partnersToken];
101
- }
102
- function getOrganization() {
103
- return getEnvironmentVariables()[environmentVariables.organization];
104
- }
105
- function getBackendPort() {
106
- const backendPort = getEnvironmentVariables()[systemEnvironmentVariables.backendPort];
107
- if (backendPort && !isNaN(Number(backendPort))) {
108
- return Number(backendPort);
109
- }
110
- return void 0;
111
- }
112
- function getIdentityTokenInformation() {
113
- const identityToken = getEnvironmentVariables()[environmentVariables.identityToken];
114
- const refreshToken = getEnvironmentVariables()[environmentVariables.refreshToken];
115
- if (!identityToken || !refreshToken)
116
- return void 0;
117
- return {
118
- accessToken: identityToken,
119
- refreshToken
120
- };
121
- }
122
-
123
- // ../cli-kit/src/public/node/ruby.ts
124
- var import_semver = __toESM(require_semver(), 1);
125
- import { fileURLToPath } from "url";
126
- var RubyCLIVersion = "2.35.0";
127
- var MinBundlerVersion = "2.3.11";
128
- var MinRubyVersion = "2.7.5";
129
- var MinWdmWindowsVersion = "0.1.0";
130
- async function execCLI2(args, options = {}) {
131
- const currentEnv = getEnvironmentVariables();
132
- const embedded = useEmbeddedThemeCLI(currentEnv) && !currentEnv.SHOPIFY_CLI_2_0_DIRECTORY;
133
- await installCLIDependencies(options.stdout ?? process.stdout, embedded);
134
- const env = {
135
- ...currentEnv,
136
- SHOPIFY_CLI_STOREFRONT_RENDERER_AUTH_TOKEN: options.storefrontToken,
137
- SHOPIFY_CLI_ADMIN_AUTH_TOKEN: options.adminToken,
138
- SHOPIFY_SHOP: options.store,
139
- SHOPIFY_CLI_AUTH_TOKEN: options.token,
140
- SHOPIFY_CLI_RUN_AS_SUBPROCESS: "true",
141
- SHOPIFY_CLI_RUBY_BIN: rubyExecutable(),
142
- // Bundler uses this Gemfile to understand which gems are available in the
143
- // environment. We use this to specify our own Gemfile for CLI2, which exists
144
- // outside the user's project directory.
145
- BUNDLE_GEMFILE: joinPath(await shopifyCLIDirectory(embedded), "Gemfile"),
146
- ...await getSpinEnvironmentVariables(),
147
- SHOPIFY_CLI_1P_DEV: firstPartyDev() ? "1" : "0",
148
- SHOPIFY_CLI_VERSION: CLI_KIT_VERSION
149
- };
150
- try {
151
- const shopifyExecutable = embedded ? [rubyExecutable(), await embeddedCLIExecutable()] : ["shopify"];
152
- await runBundler(["exec", ...shopifyExecutable, ...args], {
153
- ...options.stdout === void 0 && { stdio: "inherit" },
154
- cwd: options.directory ?? cwd(),
155
- env,
156
- ...options.stdout !== void 0 && { stdout: options.stdout, stderr: options.stderr },
157
- signal: options.signal
158
- });
159
- } catch (error) {
160
- throw new AbortSilentError();
161
- }
162
- }
163
- async function installCLIDependencies(stdout, embedded = false) {
164
- const localCLI = await shopifyCLIDirectory(embedded);
165
- const exists = await fileExists(localCLI);
166
- if (!exists)
167
- stdout.write("Installing theme dependencies...");
168
- const usingLocalCLI2 = embedded || isTruthy(getEnvironmentVariables().SHOPIFY_CLI_2_0_DIRECTORY);
169
- await validateRubyEnv();
170
- if (usingLocalCLI2) {
171
- await bundleInstallLocalShopifyCLI(localCLI);
172
- } else {
173
- await createShopifyCLIWorkingDirectory();
174
- await createShopifyCLIGemfile();
175
- await bundleInstallShopifyCLI();
176
- }
177
- if (!exists)
178
- stdout.write("Installed theme dependencies!");
179
- }
180
- async function validateRubyEnv() {
181
- await validateRuby();
182
- await validateBundler();
183
- }
184
- async function validateRuby() {
185
- let version2;
186
- try {
187
- const stdout = await captureOutput(rubyExecutable(), ["-v"]);
188
- version2 = (0, import_semver.coerce)(stdout);
189
- } catch {
190
- throw new AbortError(
191
- "Ruby environment not found",
192
- `Make sure you have Ruby installed on your system. ${outputContent`${outputToken.link("Documentation.", "https://www.ruby-lang.org/en/documentation/installation/")}`.value}`
193
- );
194
- }
195
- const isValid = version2?.compare(MinRubyVersion);
196
- if (isValid === -1 || isValid === void 0) {
197
- throw new AbortError(
198
- `Ruby version ${outputContent`${outputToken.yellow(version2?.raw ?? "unknown")}`.value} is not supported`,
199
- `Make sure you have at least Ruby ${outputContent`${outputToken.yellow(MinRubyVersion)}`.value} installed on your system. ${outputContent`${outputToken.link("Documentation.", "https://www.ruby-lang.org/en/documentation/installation/")}`.value}`
200
- );
201
- }
202
- }
203
- async function validateBundler() {
204
- let version2;
205
- try {
206
- const stdout = await captureOutput(bundleExecutable(), ["-v"], { env: { BUNDLE_USER_HOME: bundleUserHome() } });
207
- version2 = (0, import_semver.coerce)(stdout);
208
- } catch {
209
- throw new AbortError(
210
- "Bundler not found",
211
- `To install the latest version of Bundler, run ${outputContent`${outputToken.genericShellCommand(`${gemExecutable()} install bundler`)}`.value}`
212
- );
213
- }
214
- const isValid = version2?.compare(MinBundlerVersion);
215
- if (isValid === -1 || isValid === void 0) {
216
- throw new AbortError(
217
- `Bundler version ${outputContent`${outputToken.yellow(version2?.raw ?? "unknown")}`.value} is not supported`,
218
- `To update to the latest version of Bundler, run ${outputContent`${outputToken.genericShellCommand(`${gemExecutable()} install bundler`)}`.value}`
219
- );
220
- }
221
- }
222
- async function createShopifyCLIWorkingDirectory() {
223
- return mkdir(await shopifyCLIDirectory());
224
- }
225
- async function createShopifyCLIGemfile() {
226
- const directory = await shopifyCLIDirectory();
227
- const gemfileContent = getBaseGemfileContent().concat(getWindowsDependencies());
228
- await addContentToGemfile(directory, gemfileContent);
229
- }
230
- async function bundleInstallLocalShopifyCLI(directory) {
231
- await addContentToGemfile(directory, getWindowsDependencies());
232
- await shopifyBundleInstall(directory);
233
- }
234
- function getBaseGemfileContent() {
235
- return ["source 'https://rubygems.org'", `gem 'shopify-cli', '${RubyCLIVersion}'`];
236
- }
237
- function getWindowsDependencies() {
238
- if (platformAndArch().platform === "windows") {
239
- return [`gem 'wdm', '>= ${MinWdmWindowsVersion}'`];
240
- }
241
- return [];
242
- }
243
- async function addContentToGemfile(gemfileDirectory, content) {
244
- const gemfilePath = joinPath(gemfileDirectory, "Gemfile");
245
- if (!await fileExists(gemfilePath))
246
- await touchFile(gemfilePath);
247
- const gemContent = await readFile(gemfilePath, { encoding: "utf8" });
248
- const contentNoExisting = content.filter((line) => !gemContent.includes(line)).join("\n");
249
- if (contentNoExisting)
250
- await appendFile(gemfilePath, contentNoExisting.concat("\n"));
251
- }
252
- async function bundleInstallShopifyCLI() {
253
- await shopifyBundleInstall(await shopifyCLIDirectory());
254
- }
255
- async function shopifyCLIDirectory(embedded = false) {
256
- const embeddedDirectory = await findPathUp("assets/cli-ruby", {
257
- type: "directory",
258
- cwd: dirname(fileURLToPath(import.meta.url))
259
- });
260
- const bundledDirectory = joinPath(pathConstants.directories.cache.vendor.path(), "ruby-cli", RubyCLIVersion);
261
- return embedded ? embeddedDirectory : getEnvironmentVariables().SHOPIFY_CLI_2_0_DIRECTORY ?? bundledDirectory;
262
- }
263
- async function version() {
264
- const parseOutput = (version2) => version2.match(/ruby (\d+\.\d+\.\d+)/)?.[1];
265
- return captureOutput(rubyExecutable(), ["-v"]).then(parseOutput).catch(() => void 0);
266
- }
267
- function getRubyBinDir() {
268
- return getEnvironmentVariables().SHOPIFY_RUBY_BINDIR;
269
- }
270
- function rubyExecutable() {
271
- const rubyBinDir = getRubyBinDir();
272
- return rubyBinDir ? joinPath(rubyBinDir, "ruby") : "ruby";
273
- }
274
- function bundleExecutable() {
275
- const rubyBinDir = getRubyBinDir();
276
- return rubyBinDir ? joinPath(rubyBinDir, "bundle") : "bundle";
277
- }
278
- function gemExecutable() {
279
- const rubyBinDir = getRubyBinDir();
280
- return rubyBinDir ? joinPath(rubyBinDir, "gem") : "gem";
281
- }
282
- async function embeddedCLIExecutable() {
283
- const cliDirectory = await shopifyCLIDirectory(true);
284
- return joinPath(cliDirectory, "bin", "shopify");
285
- }
286
- async function getSpinEnvironmentVariables() {
287
- if (!isSpinEnvironment())
288
- return {};
289
- return {
290
- SPIN_FQDN: await spinFqdn(),
291
- SPIN: "1"
292
- };
293
- }
294
- async function shopifyBundleInstall(directory) {
295
- return runWithTimer("cmd_all_timing_network_ms")(async () => {
296
- await runBundler(["install"], { cwd: directory });
297
- });
298
- }
299
- function bundleUserHome() {
300
- if (platformAndArch().platform === "windows" && process.env.PUBLIC) {
301
- return joinPath(process.env.PUBLIC, "AppData", "Local", "shopify-bundler-nodejs", "Cache");
302
- } else {
303
- return void 0;
304
- }
305
- }
306
- async function runBundler(args, options) {
307
- return exec(bundleExecutable(), args, {
308
- ...options,
309
- env: {
310
- ...options.env,
311
- BUNDLE_USER_HOME: bundleUserHome(),
312
- BUNDLE_WITHOUT: "development:test",
313
- BUNDLE_PATH: envPaths("shopify-gems").cache
314
- }
315
- });
316
- }
317
-
318
- // ../cli-kit/src/public/node/monorail.ts
319
- init_cjs_shims();
320
-
321
- // ../cli-kit/src/public/node/http.ts
322
- init_cjs_shims();
323
-
324
- // ../cli-kit/src/private/node/api/headers.ts
325
- init_cjs_shims();
326
- import https from "https";
327
- var RequestClientError = class extends import_ts_error.ExtendableError {
328
- constructor(message, statusCode) {
329
- super(message);
330
- this.statusCode = statusCode;
331
- }
332
- };
333
- var GraphQLClientError = class extends RequestClientError {
334
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
335
- constructor(message, statusCode, errors) {
336
- super(message, statusCode);
337
- this.errors = errors;
338
- this.stack = void 0;
339
- }
340
- };
341
- function sanitizedHeadersOutput(headers) {
342
- const sanitized = {};
343
- const keywords = ["token", "authorization", "subject_token"];
344
- Object.keys(headers).forEach((header) => {
345
- if (keywords.find((keyword) => header.toLocaleLowerCase().includes(keyword)) === void 0) {
346
- sanitized[header] = headers[header];
347
- }
348
- });
349
- return Object.keys(sanitized).map((header) => {
350
- return ` - ${header}: ${sanitized[header]}`;
351
- }).join("\n");
352
- }
353
- function buildHeaders(token) {
354
- const userAgent = `Shopify CLI; v=${CLI_KIT_VERSION}`;
355
- const headers = {
356
- "User-Agent": userAgent,
357
- "Keep-Alive": "timeout=30",
358
- // 'Sec-CH-UA': secCHUA, This header requires the Git sha.
359
- "Sec-CH-UA-PLATFORM": process.platform,
360
- "Content-Type": "application/json",
361
- ...firstPartyDev() && { "X-Shopify-Cli-Employee": "1" }
362
- };
363
- if (token) {
364
- const authString = token.match(/^shp(at|ua|ca)/) ? token : `Bearer ${token}`;
365
- headers["authorization"] = authString;
366
- headers["X-Shopify-Access-Token"] = authString;
367
- }
368
- return headers;
369
- }
370
- async function httpsAgent() {
371
- return new https.Agent({
372
- rejectUnauthorized: await shouldRejectUnauthorizedRequests(),
373
- keepAlive: true
374
- });
375
- }
376
- async function shouldRejectUnauthorizedRequests() {
377
- return await serviceEnvironment() !== "spin" /* Spin */;
378
- }
379
-
380
- // ../cli-kit/src/private/node/api/urls.ts
381
- init_cjs_shims();
382
- function sanitizeURL(url2) {
383
- const parsedUrl = new URL(url2);
384
- if (parsedUrl.searchParams.has("subject_token")) {
385
- parsedUrl.searchParams.set("subject_token", "****");
386
- }
387
- if (parsedUrl.searchParams.has("token")) {
388
- parsedUrl.searchParams.set("token", "****");
389
- }
390
- return parsedUrl.toString();
391
- }
392
-
393
- // ../cli-kit/src/private/node/api.ts
394
- init_cjs_shims();
395
- import { performance } from "perf_hooks";
396
- var allAPIs = ["admin", "storefront-renderer", "partners", "business-platform", "app-management"];
397
- var interestingResponseHeaders = /* @__PURE__ */ new Set(["cache-control", "content-type", "etag", "x-request-id"]);
398
- async function debugLogResponseInfo({ request, url: url2 }, errorHandler) {
399
- const t0 = performance.now();
400
- const responseHeaders = {};
401
- let response = {};
402
- try {
403
- response = await request;
404
- response.headers.forEach((value, key) => {
405
- if (interestingResponseHeaders.has(key))
406
- responseHeaders[key] = value;
407
- });
408
- } catch (err) {
409
- if (err instanceof ClientError) {
410
- if (err.response?.headers) {
411
- for (const [key, value] of err.response?.headers) {
412
- if (interestingResponseHeaders.has(key))
413
- responseHeaders[key] = value;
414
- }
415
- }
416
- }
417
- if (errorHandler) {
418
- throw errorHandler(err, responseHeaders["x-request-id"]);
419
- } else {
420
- throw err;
421
- }
422
- } finally {
423
- const t1 = performance.now();
424
- outputDebug(`Request to ${sanitizeURL(url2)} completed in ${Math.round(t1 - t0)} ms
425
- With response headers:
426
- ${sanitizedHeadersOutput(responseHeaders)}
427
- `);
428
- }
429
- return response;
430
- }
431
-
432
- // ../cli-kit/src/public/node/http.ts
433
- var import_form_data = __toESM(require_form_data(), 1);
434
- function formData() {
435
- return new import_form_data.default();
436
- }
437
- async function fetch2(url2, init) {
438
- return runWithTimer("cmd_all_timing_network_ms")(
439
- () => debugLogResponseInfo({ url: url2.toString(), request: fetch(url2, init) })
440
- );
441
- }
442
- async function shopifyFetch(url2, init) {
443
- const sanitizedUrl = sanitizeURL(url2.toString());
444
- const options = {
445
- ...init ?? {},
446
- headers: {
447
- ...await buildHeaders(),
448
- ...init?.headers ?? {}
449
- }
450
- };
451
- outputDebug(outputContent`Sending ${options.method ?? "GET"} request to URL ${sanitizedUrl}
452
- With request headers:
453
- ${sanitizedHeadersOutput(options?.headers ?? {})}
454
- `);
455
- return runWithTimer("cmd_all_timing_network_ms")(async () => {
456
- return debugLogResponseInfo({ url: url2.toString(), request: fetch(url2, { ...init, agent: await httpsAgent() }) });
457
- });
458
- }
459
-
460
- // ../cli-kit/src/public/common/ts/deep-required.ts
461
- init_cjs_shims();
462
-
463
- // ../cli-kit/src/public/node/monorail.ts
464
- var url = "https://monorail-edge.shopifysvc.com/v1/produce";
465
- var MONORAIL_COMMAND_TOPIC = "app_cli3_command/1.12";
466
- var publishedCommandNames = /* @__PURE__ */ new Set();
467
- async function publishMonorailEvent(schemaId, publicData, sensitiveData) {
468
- const commandName = publicData.command;
469
- if (commandName && typeof commandName === "string") {
470
- if (publishedCommandNames.has(commandName)) {
471
- return { type: "ok" };
472
- }
473
- publishedCommandNames.add(commandName);
474
- }
475
- try {
476
- const currentTime = (/* @__PURE__ */ new Date()).getTime();
477
- const payload = { ...publicData, ...sensitiveData };
478
- const body = JSON.stringify({ schema_id: schemaId, payload });
479
- const headers = buildHeaders2(currentTime);
480
- const response = await fetch2(url, { method: "POST", body, headers });
481
- if (response.status === 200) {
482
- outputDebug(outputContent`Analytics event sent: ${outputToken.json(sanitizePayload(payload))}`);
483
- return { type: "ok" };
484
- } else {
485
- outputDebug(`Failed to report usage analytics: ${response.statusText}`);
486
- return { type: "error", message: response.statusText };
487
- }
488
- } catch (error) {
489
- let message = "Failed to report usage analytics";
490
- if (error instanceof Error) {
491
- message = message.concat(`: ${error.message}`);
492
- }
493
- outputDebug(message);
494
- return { type: "error", message };
495
- }
496
- }
497
- function sanitizePayload(payload) {
498
- const result = { ...payload };
499
- if ("api_key" in result) {
500
- result.api_key = "****";
501
- }
502
- return result;
503
- }
504
- var buildHeaders2 = (currentTime) => {
505
- return {
506
- "Content-Type": "application/json; charset=utf-8",
507
- "X-Monorail-Edge-Event-Created-At-Ms": currentTime.toString(),
508
- "X-Monorail-Edge-Event-Sent-At-Ms": currentTime.toString()
509
- };
510
- };
511
-
512
- // ../cli-kit/src/private/node/otel-metrics.ts
513
- init_cjs_shims();
514
-
515
- // ../cli-kit/src/public/node/vendor/otel-js/service/types.ts
516
- init_cjs_shims();
517
-
518
- // ../cli-kit/src/public/node/vendor/otel-js/service/DefaultOtelService/DefaultOtelService.ts
519
- init_cjs_shims();
520
-
521
- // ../cli-kit/src/public/node/vendor/otel-js/service/DefaultOtelService/DefaultMeterProvider.ts
522
- init_cjs_shims();
523
-
524
- // ../cli-kit/src/public/node/vendor/otel-js/export/InstantaneousMetricReader.ts
525
- init_cjs_shims();
526
- var import_sdk_metrics = __toESM(require_src5(), 1);
527
- var import_core = __toESM(require_src3(), 1);
528
- var import_api2 = __toESM(require_src(), 1);
529
-
530
- // ../cli-kit/src/public/node/vendor/otel-js/utils/throttle.ts
531
- init_cjs_shims();
532
- function throttle(func, wait, { leading = true, trailing = true } = {}) {
533
- let lastArgs;
534
- let result;
535
- let context;
536
- let timeout = null;
537
- let previous = 0;
538
- function later() {
539
- previous = leading === false ? 0 : Date.now();
540
- timeout = null;
541
- if (lastArgs) {
542
- result = func.apply(context, lastArgs);
543
- }
544
- context = null;
545
- lastArgs = null;
546
- }
547
- return function(...args) {
548
- const now = Date.now();
549
- if (!previous && leading === false)
550
- previous = now;
551
- const remaining = wait - (now - previous);
552
- context = this;
553
- lastArgs = args;
554
- if (remaining <= 0 || remaining > wait) {
555
- if (timeout) {
556
- clearTimeout(timeout);
557
- timeout = null;
558
- }
559
- previous = now;
560
- if (lastArgs) {
561
- result = func.apply(context, lastArgs);
562
- }
563
- context = null;
564
- lastArgs = null;
565
- } else if (!timeout && trailing !== false) {
566
- timeout = setTimeout(later, remaining);
567
- }
568
- return result;
569
- };
570
- }
571
-
572
- // ../cli-kit/src/public/node/vendor/otel-js/export/InstantaneousMetricReader.ts
573
- var InstantaneousMetricReader = class extends import_sdk_metrics.MetricReader {
574
- constructor({ exporter, throttleLimit }) {
575
- super({
576
- aggregationSelector: exporter.selectAggregation?.bind(exporter),
577
- aggregationTemporalitySelector: exporter.selectAggregationTemporality?.bind(exporter)
578
- });
579
- this._exporter = exporter;
580
- this.onForceFlush = throttle(
581
- // eslint-disable-next-line @typescript-eslint/unbound-method
582
- this.onForceFlush,
583
- throttleLimit
584
- );
585
- }
586
- async onForceFlush() {
587
- const { resourceMetrics, errors } = await this.collect({});
588
- if (errors.length > 0) {
589
- import_api2.diag.error("PeriodicExportingMetricReader: metrics collection errors", ...errors);
590
- }
591
- return new Promise((resolve, reject) => {
592
- this._exporter.export(resourceMetrics, (result) => {
593
- if (result.code === import_core.ExportResultCode.SUCCESS) {
594
- resolve();
595
- } else {
596
- reject(result.error ?? new Error(`InstantaneousMetricReader: metrics export failed (error ${result.error})`));
597
- }
598
- });
599
- });
600
- }
601
- async onShutdown() {
602
- await this._exporter.shutdown();
603
- }
604
- };
605
-
606
- // ../cli-kit/src/public/node/vendor/otel-js/service/DefaultOtelService/DefaultMeterProvider.ts
607
- var import_exporter_metrics_otlp_http = __toESM(require_src6(), 1);
608
- var import_resources = __toESM(require_src4(), 1);
609
- var import_sdk_metrics2 = __toESM(require_src5(), 1);
610
- var import_semantic_conventions = __toESM(require_src2(), 1);
611
- var DefaultMeterProvider = class extends import_sdk_metrics2.MeterProvider {
612
- constructor({ serviceName, env, throttleLimit, useXhr, otelEndpoint }) {
613
- super({
614
- resource: new import_resources.Resource({
615
- [import_semantic_conventions.SemanticResourceAttributes.SERVICE_NAME]: serviceName
616
- })
617
- });
618
- const opts = {
619
- // url: OTEL_ENDPOINTS[env as Environment] || OTEL_ENDPOINTS.local,
620
- // CLI addition
621
- url: otelEndpoint,
622
- temporalityPreference: import_sdk_metrics2.AggregationTemporality.DELTA
623
- };
624
- if (useXhr) {
625
- opts.headers = {};
626
- }
627
- const exporter = new import_exporter_metrics_otlp_http.OTLPMetricExporter(opts);
628
- this.addMetricReader(
629
- new InstantaneousMetricReader({
630
- exporter,
631
- throttleLimit
632
- })
633
- );
634
- if (env === "dev") {
635
- this.addMetricReader(
636
- new InstantaneousMetricReader({
637
- exporter: new import_sdk_metrics2.ConsoleMetricExporter(),
638
- throttleLimit
639
- })
640
- );
641
- }
642
- }
643
- };
644
-
645
- // ../cli-kit/src/public/node/vendor/otel-js/service/BaseOtelService/BaseOtelService.ts
646
- init_cjs_shims();
647
- var import_sdk_metrics3 = __toESM(require_src5(), 1);
648
-
649
- // ../cli-kit/src/public/node/vendor/otel-js/utils/validators.ts
650
- init_cjs_shims();
651
- var import_api3 = __toESM(require_src(), 1);
652
- var validMetricRegex = new RegExp("[^a-zA-Z_][^a-zA-Z0-9_]*");
653
- function isValidMetricName(value) {
654
- if (validMetricRegex.test(value)) {
655
- import_api3.diag.warn(
656
- `Metric name ${value} contains invalid characters and will be dropped.
657
- Service Names and metric names must conform to the following regex %c[a-zA-Z_][a-zA-Z0-9_]*`,
658
- "color:red"
659
- );
660
- return false;
661
- }
662
- return true;
663
- }
664
-
665
- // ../cli-kit/src/public/node/vendor/otel-js/service/BaseOtelService/BaseOtelService.ts
666
- var instrumentationScope = "opentelemetry-js-shopify-web";
667
- var BaseOtelService = class {
668
- /**
669
- * Bootstraps an Otel exporter which can send Otel metrics to a dedicated Shopify supported collector endpoint.
670
- */
671
- constructor({ serviceName, prefixMetric = false, metrics = {}, onRecord, meterProvider }) {
672
- this.metrics = /* @__PURE__ */ new Map();
673
- this.recordListeners = /* @__PURE__ */ new Set();
674
- if (!serviceName) {
675
- throw new Error("Service name is required.");
676
- }
677
- this.serviceName = serviceName;
678
- this.prefixMetric = prefixMetric;
679
- if (onRecord)
680
- this.addOnRecord(onRecord);
681
- if (!meterProvider) {
682
- throw new Error("MeterProvider is required.");
683
- }
684
- this.meterProvider = meterProvider;
685
- this.register(metrics);
686
- }
687
- getMeterProvider() {
688
- return this.meterProvider;
689
- }
690
- addView(viewOptions) {
691
- ;
692
- this.meterProvider._sharedState?.viewRegistry?.addView?.(new import_sdk_metrics3.View(viewOptions));
693
- }
694
- record(metricName, value, labels) {
695
- const recordMetric = this.metrics.get(metricName);
696
- if (!recordMetric) {
697
- throw new Error(
698
- `Service ${this.serviceName} has no metrics registered for name: ${metricName}. Can't record value for unknown metric.`
699
- );
700
- }
701
- recordMetric(value, labels);
702
- }
703
- registerMetric(metricName, { type, ...options }) {
704
- if (this.metrics.has(metricName)) {
705
- return;
706
- }
707
- const meter = this.meterProvider.getMeter(instrumentationScope);
708
- const name = this.prefixMetric ? `${this.serviceName}_${metricName}` : metricName;
709
- if (!isValidMetricName(name)) {
710
- return;
711
- }
712
- const createInstrument = () => {
713
- switch (type) {
714
- case "Counter" /* Counter */:
715
- return meter.createCounter(name, options);
716
- case "UpDownCounter" /* UpDownCounter */:
717
- return meter.createUpDownCounter(name, options);
718
- case "Histogram" /* Histogram */: {
719
- if ("boundaries" in options) {
720
- this.addView({
721
- instrumentName: name,
722
- aggregation: new import_sdk_metrics3.ExplicitBucketHistogramAggregation(options.boundaries, true)
723
- });
724
- }
725
- return meter.createHistogram(name, options);
726
- }
727
- }
728
- };
729
- this.metrics.set(metricName, (firstValue, firstLabels) => {
730
- const instrument = createInstrument();
731
- const record = (value, labels) => {
732
- const [finalValue, finalLabels] = this.notifyRecordListeners(
733
- metricName,
734
- value,
735
- // ensures an new object is created so we don't mutate the original
736
- { ...labels }
737
- );
738
- if ("record" in instrument) {
739
- instrument.record(finalValue, finalLabels);
740
- } else {
741
- instrument.add(finalValue, finalLabels);
742
- }
743
- this.meterProvider.forceFlush({});
744
- };
745
- record(firstValue, firstLabels);
746
- this.metrics.set(metricName, record);
747
- });
748
- }
749
- register(metrics) {
750
- Object.entries(metrics).forEach(([metricName, options]) => {
751
- this.registerMetric(metricName, options);
752
- });
753
- }
754
- addOnRecord(onRecord) {
755
- this.recordListeners.add(onRecord);
756
- return () => {
757
- this.recordListeners.delete(onRecord);
758
- };
759
- }
760
- removeOnRecord(onRecord) {
761
- this.recordListeners.delete(onRecord);
762
- }
763
- shutdown() {
764
- this.metrics.clear();
765
- this.recordListeners.clear();
766
- return this.meterProvider.shutdown();
767
- }
768
- notifyRecordListeners(metricName, initialValue, initialLabels) {
769
- return Array.from(this.recordListeners).reduce(
770
- (recordArgs, listener) => {
771
- return listener(metricName, ...recordArgs) || recordArgs;
772
- },
773
- [initialValue, initialLabels]
774
- );
775
- }
776
- };
777
-
778
- // ../cli-kit/src/public/node/vendor/otel-js/service/DefaultOtelService/DefaultOtelService.ts
779
- var import_api4 = __toESM(require_src(), 1);
780
- var DefaultOtelService = class extends BaseOtelService {
781
- /**
782
- * Bootstraps an Otel exporter which can send Otel metrics to a dedicated Shopify supported collector endpoint.
783
- */
784
- constructor({
785
- throttleLimit = 5e3,
786
- env = "local",
787
- serviceName,
788
- prefixMetric = false,
789
- metrics = {},
790
- onRecord,
791
- meterProvider,
792
- useXhr = false,
793
- // CLI addition
794
- otelEndpoint
795
- }) {
796
- import_api4.diag.setLogger(
797
- new import_api4.DiagConsoleLogger(),
798
- ["production", "staging"].includes(env) ? import_api4.DiagLogLevel.ERROR : import_api4.DiagLogLevel.INFO
799
- );
800
- super({
801
- serviceName,
802
- meterProvider: meterProvider ?? new DefaultMeterProvider({
803
- serviceName,
804
- env,
805
- throttleLimit,
806
- useXhr,
807
- // CLI addition
808
- otelEndpoint
809
- }),
810
- prefixMetric,
811
- metrics,
812
- onRecord
813
- });
814
- }
815
- shutdown() {
816
- import_api4.diag.disable();
817
- return super.shutdown();
818
- }
819
- };
820
-
821
- // ../cli-kit/src/private/node/otel-metrics.ts
822
- var import_api5 = __toESM(require_src(), 1);
823
- async function recordMetrics(options, timing, recorderFactory = createMetricRecorder) {
824
- const recorder = recorderFactory({
825
- skipMetricAnalytics: options.skipMetricAnalytics,
826
- otelOptions: defaultOtelOptions()
827
- });
828
- let regularisedCliVersion = options.cliVersion;
829
- if (options.cliVersion.includes("nightly")) {
830
- regularisedCliVersion = "nightly";
831
- } else if (options.cliVersion.includes("pre")) {
832
- regularisedCliVersion = "pre";
833
- }
834
- const labels = {
835
- exit: options.exitMode,
836
- job: `${options.owningPlugin}::${options.command}`,
837
- cli_version: regularisedCliVersion
838
- };
839
- recordCommandCounter(recorder, labels);
840
- recordCommandTiming(recorder, labels, timing);
841
- }
842
- function defaultOtelOptions() {
843
- return {
844
- serviceName: "shopify-cli",
845
- throttleLimit: 1e3,
846
- prefixMetric: false,
847
- metrics: {
848
- ["cli_commands_total" /* Counter */]: {
849
- type: "Counter" /* Counter */,
850
- description: "Total number of CLI commands executed",
851
- valueType: import_api5.ValueType.INT
852
- },
853
- ["cli_commands_duration_ms" /* Duration */]: {
854
- type: "Histogram" /* Histogram */,
855
- description: "Total time spent in execution of CLI commands. Does not include time spent waiting for network, prompts, etc.",
856
- valueType: import_api5.ValueType.INT,
857
- boundaries: [0, 100, 250, 500, 1e3, 2e3, 5e3, 1e4, 2e4, 5e4]
858
- },
859
- ["cli_commands_wall_clock_elapsed_ms" /* Elapsed */]: {
860
- type: "Histogram" /* Histogram */,
861
- description: "Total time elapsed from start to finish of CLI commands. Includes time spent waiting for network, prompts, etc.",
862
- valueType: import_api5.ValueType.INT,
863
- boundaries: [0, 100, 250, 500, 1e3, 2e3, 5e3, 1e4, 2e4, 5e4]
864
- }
865
- }
866
- };
867
- }
868
- function createMetricRecorder(options) {
869
- let recorder = "console";
870
- if (!(options.skipMetricAnalytics || isUnitTest() || isSpinEnvironment())) {
871
- recorder = {
872
- type: "otel",
873
- otel: globalOtelService(options)
874
- };
875
- }
876
- return recorder;
877
- }
878
- var _otelService;
879
- function globalOtelService(options) {
880
- if (!_otelService) {
881
- _otelService = new DefaultOtelService({
882
- ...options.otelOptions,
883
- env: void 0,
884
- otelEndpoint: `${opentelemetryDomain()}/v1/metrics`
885
- });
886
- }
887
- return _otelService;
888
- }
889
- function recordCommandCounter(recorder, labels) {
890
- if (recorder === "console") {
891
- outputDebug(outputContent`[OTEL] record ${"cli_commands_total" /* Counter */} counter ${outputToken.json({ labels })}`);
892
- return;
893
- }
894
- recorder.otel.record("cli_commands_total" /* Counter */, 1, labels);
895
- }
896
- function recordCommandTiming(recorder, labels, timing) {
897
- if (recorder === "console") {
898
- outputDebug(
899
- outputContent`[OTEL] record ${"cli_commands_duration_ms" /* Duration */} histogram ${timing.active.toString()}ms ${outputToken.json({
900
- labels
901
- })}`
902
- );
903
- outputDebug(outputContent`[OTEL] record ${"cli_commands_wall_clock_elapsed_ms" /* Elapsed */} histogram stage="active" ${timing.active.toString()}ms`);
904
- outputDebug(outputContent`[OTEL] record ${"cli_commands_wall_clock_elapsed_ms" /* Elapsed */} histogram stage="network" ${timing.network.toString()}ms`);
905
- outputDebug(outputContent`[OTEL] record ${"cli_commands_wall_clock_elapsed_ms" /* Elapsed */} histogram stage="prompt" ${timing.prompt.toString()}ms`);
906
- return;
907
- }
908
- if (timing.active > 0) {
909
- recorder.otel.record("cli_commands_duration_ms" /* Duration */, timing.active, labels);
910
- recorder.otel.record("cli_commands_wall_clock_elapsed_ms" /* Elapsed */, timing.active, { ...labels, stage: "active" });
911
- }
912
- if (timing.network > 0) {
913
- recorder.otel.record("cli_commands_wall_clock_elapsed_ms" /* Elapsed */, timing.network, { ...labels, stage: "network" });
914
- }
915
- if (timing.prompt > 0) {
916
- recorder.otel.record("cli_commands_wall_clock_elapsed_ms" /* Elapsed */, timing.prompt, { ...labels, stage: "prompt" });
917
- }
918
- }
919
-
920
- // ../cli-kit/src/public/node/analytics.ts
921
- async function reportAnalyticsEvent(options) {
922
- try {
923
- const payload = await buildPayload(options);
924
- if (payload === void 0) {
925
- return;
926
- }
927
- const skipMonorailAnalytics = !alwaysLogAnalytics() && analyticsDisabled();
928
- const skipMetricAnalytics = !alwaysLogMetrics() && analyticsDisabled();
929
- if (skipMonorailAnalytics || skipMetricAnalytics) {
930
- outputDebug(outputContent`Skipping command analytics, payload: ${outputToken.json(payload)}`);
931
- }
932
- const doMonorail = async () => {
933
- if (skipMonorailAnalytics) {
934
- return;
935
- }
936
- const response = await publishMonorailEvent(MONORAIL_COMMAND_TOPIC, payload.public, payload.sensitive);
937
- if (response.type === "error") {
938
- outputDebug(response.message);
939
- }
940
- };
941
- const doOpenTelemetry = async () => {
942
- const active = payload.public.cmd_all_timing_active_ms || 0;
943
- const network = payload.public.cmd_all_timing_network_ms || 0;
944
- const prompt = payload.public.cmd_all_timing_prompts_ms || 0;
945
- return recordMetrics(
946
- {
947
- skipMetricAnalytics,
948
- cliVersion: payload.public.cli_version,
949
- owningPlugin: payload.public.cmd_all_plugin || "@shopify/cli",
950
- command: payload.public.command,
951
- exitMode: options.exitMode
952
- },
953
- {
954
- active,
955
- network,
956
- prompt
957
- }
958
- );
959
- };
960
- await Promise.all([doMonorail(), doOpenTelemetry()]);
961
- } catch (error) {
962
- let message = "Failed to report usage analytics";
963
- if (error instanceof Error) {
964
- message = message.concat(`: ${error.message}`);
965
- }
966
- outputDebug(message);
967
- }
968
- }
969
- async function buildPayload({ config, errorMessage, exitMode }) {
970
- const { commandStartOptions, environmentFlags, ...sensitiveMetadata } = getAllSensitiveMetadata();
971
- if (commandStartOptions === void 0) {
972
- outputDebug("Unable to log analytics event - no information on executed command");
973
- return;
974
- }
975
- const { startCommand, startArgs, startTime } = commandStartOptions;
976
- const currentTime = (/* @__PURE__ */ new Date()).getTime();
977
- const { "@shopify/cli": internalPluginsPublic, ...externalPluginsPublic } = await fanoutHooks(
978
- config,
979
- "public_command_metadata",
980
- {}
981
- );
982
- const { "@shopify/cli": internalPluginsSensitive, ...externalPluginsSensitive } = await fanoutHooks(
983
- config,
984
- "sensitive_command_metadata",
985
- {}
986
- );
987
- const environmentData = await getEnvironmentData(config);
988
- const sensitiveEnvironmentData = await getSensitiveEnvironmentData(config);
989
- const publicMetadata = getAllPublicMetadata();
990
- const subTimers = ["cmd_all_timing_network_ms", "cmd_all_timing_prompts_ms"];
991
- const totalTimeFromSubtimers = subTimers.reduce((total, timer) => {
992
- const value = publicMetadata[timer];
993
- if (value !== void 0) {
994
- return total + value;
995
- }
996
- return total;
997
- }, 0);
998
- const wallClockElapsed = currentTime - startTime;
999
- const totalTimeWithoutSubtimers = wallClockElapsed - totalTimeFromSubtimers;
1000
- let payload = {
1001
- public: {
1002
- command: startCommand,
1003
- time_start: startTime,
1004
- time_end: currentTime,
1005
- total_time: wallClockElapsed,
1006
- success: exitMode === "ok" && errorMessage === void 0,
1007
- cli_version: CLI_KIT_VERSION,
1008
- ruby_version: await version() || "",
1009
- node_version: process.version.replace("v", ""),
1010
- is_employee: await isShopify(),
1011
- ...environmentData,
1012
- ...internalPluginsPublic,
1013
- ...publicMetadata,
1014
- cmd_all_timing_active_ms: totalTimeWithoutSubtimers,
1015
- cmd_all_exit: exitMode
1016
- },
1017
- sensitive: {
1018
- args: startArgs.join(" "),
1019
- cmd_all_environment_flags: environmentFlags,
1020
- error_message: errorMessage,
1021
- ...internalPluginsSensitive,
1022
- ...sensitiveEnvironmentData,
1023
- metadata: JSON.stringify({
1024
- ...sensitiveMetadata,
1025
- extraPublic: {
1026
- ...externalPluginsPublic
1027
- },
1028
- extraSensitive: { ...externalPluginsSensitive }
1029
- })
1030
- }
1031
- };
1032
- const timingMetrics = ["cmd_all_timing_active_ms", "cmd_all_timing_network_ms", "cmd_all_timing_prompts_ms"];
1033
- timingMetrics.forEach((metric) => {
1034
- const current = payload.public[metric];
1035
- if (current !== void 0) {
1036
- payload.public[metric] = Math.floor(current);
1037
- }
1038
- });
1039
- payload = JSON.parse(JSON.stringify(payload));
1040
- return sanitizePayload2(payload);
1041
- }
1042
- function sanitizePayload2(payload) {
1043
- const payloadString = JSON.stringify(payload);
1044
- const sanitizedPayloadString = payloadString.replace(/shptka_\w*/g, "*****");
1045
- return JSON.parse(sanitizedPayloadString);
1046
- }
1047
-
1048
- export {
1049
- getEnvironmentVariables,
1050
- getPartnersToken,
1051
- getOrganization,
1052
- getBackendPort,
1053
- getIdentityTokenInformation,
1054
- execCLI2,
1055
- version,
1056
- RequestClientError,
1057
- GraphQLClientError,
1058
- sanitizedHeadersOutput,
1059
- buildHeaders,
1060
- httpsAgent,
1061
- allAPIs,
1062
- debugLogResponseInfo,
1063
- formData,
1064
- fetch2 as fetch,
1065
- shopifyFetch,
1066
- fanoutHooks,
1067
- getListOfTunnelPlugins,
1068
- reportAnalyticsEvent
1069
- };
1070
- //# sourceMappingURL=chunk-QCDYZY46.js.map