@shopify/cli-kit 3.66.1 → 3.67.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 (65) hide show
  1. package/assets/cli-ruby/lib/shopify_cli/theme/dev_server/proxy.rb +3 -7
  2. package/dist/private/node/conf-store.d.ts +45 -3
  3. package/dist/private/node/conf-store.js +60 -2
  4. package/dist/private/node/conf-store.js.map +1 -1
  5. package/dist/private/node/constants.d.ts +6 -0
  6. package/dist/private/node/constants.js +1 -0
  7. package/dist/private/node/constants.js.map +1 -1
  8. package/dist/private/node/session/exchange.js +24 -3
  9. package/dist/private/node/session/exchange.js.map +1 -1
  10. package/dist/private/node/session/schema.d.ts +24 -0
  11. package/dist/private/node/session/schema.js +10 -0
  12. package/dist/private/node/session/schema.js.map +1 -1
  13. package/dist/private/node/session/validate.js +4 -0
  14. package/dist/private/node/session/validate.js.map +1 -1
  15. package/dist/private/node/session.d.ts +1 -0
  16. package/dist/private/node/session.js +17 -6
  17. package/dist/private/node/session.js.map +1 -1
  18. package/dist/public/common/retry.d.ts +2 -1
  19. package/dist/public/common/retry.js +8 -5
  20. package/dist/public/common/retry.js.map +1 -1
  21. package/dist/public/common/ts/json-narrowing.d.ts +9 -0
  22. package/dist/public/common/ts/json-narrowing.js +13 -0
  23. package/dist/public/common/ts/json-narrowing.js.map +1 -0
  24. package/dist/public/common/version.d.ts +1 -1
  25. package/dist/public/common/version.js +1 -1
  26. package/dist/public/common/version.js.map +1 -1
  27. package/dist/public/node/analytics.js +14 -0
  28. package/dist/public/node/analytics.js.map +1 -1
  29. package/dist/public/node/api/partners.d.ts +0 -21
  30. package/dist/public/node/api/partners.js +0 -24
  31. package/dist/public/node/api/partners.js.map +1 -1
  32. package/dist/public/node/base-command.js +2 -2
  33. package/dist/public/node/base-command.js.map +1 -1
  34. package/dist/public/node/context/fqdn.js +12 -3
  35. package/dist/public/node/context/fqdn.js.map +1 -1
  36. package/dist/public/node/crypto.d.ts +9 -0
  37. package/dist/public/node/crypto.js +19 -0
  38. package/dist/public/node/crypto.js.map +1 -1
  39. package/dist/public/node/environment.d.ts +1 -0
  40. package/dist/public/node/environment.js +2 -0
  41. package/dist/public/node/environment.js.map +1 -1
  42. package/dist/public/node/error-handler.js +15 -1
  43. package/dist/public/node/error-handler.js.map +1 -1
  44. package/dist/public/node/http.d.ts +2 -3
  45. package/dist/public/node/http.js +1 -1
  46. package/dist/public/node/http.js.map +1 -1
  47. package/dist/public/node/is-global.js +2 -2
  48. package/dist/public/node/is-global.js.map +1 -1
  49. package/dist/public/node/session.d.ts +8 -2
  50. package/dist/public/node/session.js +4 -3
  51. package/dist/public/node/session.js.map +1 -1
  52. package/dist/public/node/system.d.ts +3 -9
  53. package/dist/public/node/system.js +19 -12
  54. package/dist/public/node/system.js.map +1 -1
  55. package/dist/public/node/themes/api.js +6 -0
  56. package/dist/public/node/themes/api.js.map +1 -1
  57. package/dist/public/node/themes/factories.d.ts +2 -1
  58. package/dist/public/node/themes/factories.js +3 -1
  59. package/dist/public/node/themes/factories.js.map +1 -1
  60. package/dist/public/node/themes/types.d.ts +95 -14
  61. package/dist/public/node/themes/types.js.map +1 -1
  62. package/dist/public/node/ui.js +3 -3
  63. package/dist/public/node/ui.js.map +1 -1
  64. package/dist/tsconfig.tsbuildinfo +1 -1
  65. package/package.json +5 -2
@@ -1 +1 @@
1
- {"version":3,"file":"fqdn.js","sourceRoot":"","sources":["../../../../src/public/node/context/fqdn.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,iBAAiB,EAAE,QAAQ,EAAC,MAAM,WAAW,CAAA;AACrD,OAAO,EAAC,UAAU,EAAC,MAAM,aAAa,CAAA;AACtC,OAAO,EAAC,kBAAkB,EAAC,MAAM,0CAA0C,CAAA;AAE3E,MAAM,CAAC,MAAM,kCAAkC,GAAG,IAAI,UAAU,CAC9D,iGAAiG,CAClG,CAAA;AACD,MAAM,CAAC,MAAM,kCAAkC,GAAG,IAAI,UAAU,CAC9D,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ironment} from '../../../private/node/context/service.js'\n\nexport const CouldntObtainPartnersSpinFQDNError = new AbortError(\n \"Couldn't obtain the Spin FQDN for Partners when the CLI is not running from a Spin environment.\",\n)\nexport const CouldntObtainIdentitySpinFQDNError = new AbortError(\n \"Couldn't obtain the Spin FQDN for Identity when the CLI is not running from a Spin environment.\",\n)\nexport const CouldntObtainShopifySpinFQDNError = new AbortError(\n \"Couldn't obtain the Spin FQDN for Shopify when the CLI is not running from a Spin environment.\",\n)\nexport const NotProvidedStoreFQDNError = new AbortError(\n \"Couldn't obtain the Shopify FQDN because the store FQDN was not provided.\",\n)\n\n/**\n * It returns the Partners' API service we should interact with.\n *\n * @returns Fully-qualified domain of the partners service we should interact with.\n */\nexport async function partnersFqdn(): Promise<string> {\n const environment = serviceEnvironment()\n const productionFqdn = 'partners.shopify.com'\n switch (environment) {\n case 'local':\n return 'partners.myshopify.io'\n case 'spin':\n return `partners.${await spinFqdn()}`\n default:\n return productionFqdn\n }\n}\n\n/**\n * It returns the App Management API service we should interact with.\n *\n * @returns Fully-qualified domain of the App Management service we should interact with.\n */\nexport async function appManagementFqdn(): Promise<string> {\n const environment = serviceEnvironment()\n const productionFqdn = 'app.shopify.com'\n switch (environment) {\n case 'local':\n return 'app.shopify.myshopify.io'\n case 'spin':\n return `app.shopify.${await spinFqdn()}`\n default:\n return productionFqdn\n }\n}\n\n/**\n * It returns the Developer Dashboard domain we should interact with.\n *\n * @returns Fully-qualified domain of the Developer Dashboard we should interact with.\n */\nexport async function developerDashboardFqdn(): Promise<string> {\n const environment = serviceEnvironment()\n const productionFqdn = 'dev.shopify.com'\n switch (environment) {\n case 'local':\n return 'dev.shopify.myshopify.io'\n case 'spin':\n return `dev.shopify.${await spinFqdn()}`\n default:\n return productionFqdn\n }\n}\n\n/**\n * It returns the BusinessPlatform' API service we should interact with.\n *\n * @returns Fully-qualified domain of the partners service we should interact with.\n */\nexport async function businessPlatformFqdn(): Promise<string> {\n const environment = serviceEnvironment()\n const productionFqdn = 'destinations.shopifysvc.com'\n switch (environment) {\n case 'local':\n return 'business-platform.myshopify.io'\n case 'spin':\n return `business-platform.${await spinFqdn()}`\n default:\n return productionFqdn\n }\n}\n\n/**\n * It returns the Identity service we should interact with.\n *\n * @returns Fully-qualified domain of the Identity service we should interact with.\n */\nexport async function identityFqdn(): Promise<string> {\n const environment = serviceEnvironment()\n const productionFqdn = 'accounts.shopify.com'\n switch (environment) {\n case 'local':\n return 'identity.myshopify.io'\n case 'spin':\n return `identity.${await spinFqdn()}`\n default:\n return productionFqdn\n }\n}\n\n/**\n * Normalize the store name to be used in the CLI.\n * It will add the .myshopify.com domain if it's not present.\n * It will add the spin domain if it's not present and we're in a Spin environment.\n *\n * @param store - Store name.\n * @returns Normalized store name.\n */\nexport async function normalizeStoreFqdn(store: string): Promise<string> {\n const storeFqdn = store.replace(/^https?:\\/\\//, '').replace(/\\/$/, '')\n const addDomain = async (storeFqdn: string) =>\n isSpinEnvironment() ? `${storeFqdn}.shopify.${await spinFqdn()}` : `${storeFqdn}.myshopify.com`\n const containDomain = (storeFqdn: string) => storeFqdn.includes('.myshopify.com') || storeFqdn.includes('spin.dev')\n return containDomain(storeFqdn) ? storeFqdn : addDomain(storeFqdn)\n}\n"]}
1
+ {"version":3,"file":"fqdn.js","sourceRoot":"","sources":["../../../../src/public/node/context/fqdn.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAC,MAAM,WAAW,CAAA;AAClC,OAAO,EAAC,UAAU,EAAC,MAAM,aAAa,CAAA;AACtC,OAAO,EAAC,kBAAkB,EAAC,MAAM,0CAA0C,CAAA;AAE3E,MAAM,CAAC,MAAM,kCAAkC,GAAG,IAAI,UAAU,CAC9D,iGAAiG,CAClG,CAAA;AACD,MAAM,CAAC,MAAM,kCAAkC,GAAG,IAAI,UAAU,CAC9D,iGAAiG,CAClG,CAAA;AACD,MAAM,CAAC,MAAM,iCAAiC,GAAG,IAAI,UAAU,CAC7D,gGAAgG,CACjG,CAAA;AACD,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spin.js'\nimport {AbortError} from '../error.js'\nimport {serviceEnvironment} from '../../../private/node/context/service.js'\n\nexport const CouldntObtainPartnersSpinFQDNError = new AbortError(\n \"Couldn't obtain the Spin FQDN for Partners when the CLI is not running from a Spin environment.\",\n)\nexport const CouldntObtainIdentitySpinFQDNError = new AbortError(\n \"Couldn't obtain the Spin FQDN for Identity when the CLI is not running from a Spin environment.\",\n)\nexport const CouldntObtainShopifySpinFQDNError = new AbortError(\n \"Couldn't obtain the Spin FQDN for Shopify when the CLI is not running from a Spin environment.\",\n)\nexport const NotProvidedStoreFQDNError = new AbortError(\n \"Couldn't obtain the Shopify FQDN because the store FQDN was not provided.\",\n)\n\n/**\n * It returns the Partners' API service we should interact with.\n *\n * @returns Fully-qualified domain of the partners service we should interact with.\n */\nexport async function partnersFqdn(): Promise<string> {\n const environment = serviceEnvironment()\n const productionFqdn = 'partners.shopify.com'\n switch (environment) {\n case 'local':\n return 'partners.myshopify.io'\n case 'spin':\n return `partners.${await spinFqdn()}`\n default:\n return productionFqdn\n }\n}\n\n/**\n * It returns the App Management API service we should interact with.\n *\n * @returns Fully-qualified domain of the App Management service we should interact with.\n */\nexport async function appManagementFqdn(): Promise<string> {\n const environment = serviceEnvironment()\n const productionFqdn = 'app.shopify.com'\n switch (environment) {\n case 'local':\n return 'app.shopify.myshopify.io'\n case 'spin':\n return `app.shopify.${await spinFqdn()}`\n default:\n return productionFqdn\n }\n}\n\n/**\n * It returns the Developer Dashboard domain we should interact with.\n *\n * @returns Fully-qualified domain of the Developer Dashboard we should interact with.\n */\nexport async function developerDashboardFqdn(): Promise<string> {\n const environment = serviceEnvironment()\n const productionFqdn = 'dev.shopify.com'\n switch (environment) {\n case 'local':\n return 'dev.shopify.myshopify.io'\n case 'spin':\n return `dev.shopify.${await spinFqdn()}`\n default:\n return productionFqdn\n }\n}\n\n/**\n * It returns the BusinessPlatform' API service we should interact with.\n *\n * @returns Fully-qualified domain of the partners service we should interact with.\n */\nexport async function businessPlatformFqdn(): Promise<string> {\n const environment = serviceEnvironment()\n const productionFqdn = 'destinations.shopifysvc.com'\n switch (environment) {\n case 'local':\n return 'business-platform.myshopify.io'\n case 'spin':\n return `business-platform.${await spinFqdn()}`\n default:\n return productionFqdn\n }\n}\n\n/**\n * It returns the Identity service we should interact with.\n *\n * @returns Fully-qualified domain of the Identity service we should interact with.\n */\nexport async function identityFqdn(): Promise<string> {\n const environment = serviceEnvironment()\n const productionFqdn = 'accounts.shopify.com'\n switch (environment) {\n case 'local':\n return 'identity.myshopify.io'\n case 'spin':\n return `identity.${await spinFqdn()}`\n default:\n return productionFqdn\n }\n}\n\n/**\n * Normalize the store name to be used in the CLI.\n * It will add the .myshopify.com domain if it's not present.\n * It will add the spin domain if it's not present and we're in a Spin environment.\n *\n * @param store - Store name.\n * @returns Normalized store name.\n */\nexport async function normalizeStoreFqdn(store: string): Promise<string> {\n const storeFqdn = store.replace(/^https?:\\/\\//, '').replace(/\\/$/, '')\n const addDomain = async (storeFqdn: string) => {\n switch (serviceEnvironment()) {\n case 'local':\n return `${storeFqdn}.myshopify.io`\n case 'spin':\n return `${storeFqdn}.shopify.${await spinFqdn()}`\n default:\n return `${storeFqdn}.myshopify.com`\n }\n }\n const containDomain = (storeFqdn: string) =>\n storeFqdn.includes('.myshopify.com') || storeFqdn.includes('spin.dev') || storeFqdn.includes('shopify.io')\n return containDomain(storeFqdn) ? storeFqdn : addDomain(storeFqdn)\n}\n"]}
@@ -47,3 +47,12 @@ export declare function randomBytes(size: number): Buffer;
47
47
  * @returns A random UUID string.
48
48
  */
49
49
  export declare function randomUUID(): string;
50
+ /**
51
+ * Generate a non-random UUID string.
52
+ * Useful for generating an identifier from a string that is consistent
53
+ * across different runs of the CLI.
54
+ *
55
+ * @param subject - The subject to generate the UUID from.
56
+ * @returns A non-random UUID string.
57
+ */
58
+ export declare function nonRandomUUID(subject: string): string;
@@ -61,4 +61,23 @@ export function randomBytes(size) {
61
61
  export function randomUUID() {
62
62
  return crypto.randomUUID();
63
63
  }
64
+ /**
65
+ * Generate a non-random UUID string.
66
+ * Useful for generating an identifier from a string that is consistent
67
+ * across different runs of the CLI.
68
+ *
69
+ * @param subject - The subject to generate the UUID from.
70
+ * @returns A non-random UUID string.
71
+ */
72
+ export function nonRandomUUID(subject) {
73
+ // A fixed namespace UUID
74
+ const namespace = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
75
+ return crypto
76
+ .createHash('sha1')
77
+ .update(Buffer.from(namespace.replace(/-/g, ''), 'hex'))
78
+ .update(subject)
79
+ .digest()
80
+ .toString('hex')
81
+ .replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5');
82
+ }
64
83
  //# sourceMappingURL=crypto.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"crypto.js","sourceRoot":"","sources":["../../../src/public/node/crypto.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAA;AAE3B;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,OAAO,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;AACjD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAAC,GAAW;IACzC,OAAO,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAA;AAC3F,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,MAAM,CAAC,GAAW;IAChC,OAAO,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAA;AACzD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,GAAW;IACpC,OAAO,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AAC5D,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,QAAQ,CAAC,IAAY;IACnC,OAAO,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AAC5D,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,OAAO,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,CAAA;AACjC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,UAAU;IACxB,OAAO,MAAM,CAAC,UAAU,EAAE,CAAA;AAC5B,CAAC","sourcesContent":["import crypto from 'crypto'\n\n/**\n * Generate a random string in Hex format of the provided size.\n *\n * @param size - Number of bytes to be generated.\n * @returns A random string in Hex format.\n */\nexport function randomHex(size: number): string {\n return crypto.randomBytes(size).toString('hex')\n}\n\n/**\n * Encode a string in Base64 valid for URLs.\n *\n * @param str - The string to encode.\n * @returns The encoded string.\n */\nexport function base64URLEncode(str: Buffer): string {\n return str.toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/[=]/g, '')\n}\n\n/**\n * Generate the SHA256 hash of a string.\n *\n * @param str - The string to hash.\n * @returns The SHA256 hash of the string.\n */\nexport function sha256(str: string): Buffer {\n return crypto.createHash('sha256').update(str).digest()\n}\n\n/**\n * Generate the SHA1 hash of a string.\n *\n * @param str - The string to hash.\n * @returns The SHA1 hash of the string.\n */\nexport function hashString(str: string): string {\n return crypto.createHash('sha1').update(str).digest('hex')\n}\n\n/**\n * Generate an MD5 hash of a buffer.\n *\n * @param buff - The file buffer to hash.\n * @returns A string containing the MD5 hash.\n */\nexport function fileHash(buff: Buffer): string {\n return crypto.createHash('md5').update(buff).digest('hex')\n}\n\n/**\n * Generate random data of the provided size.\n *\n * @param size - Number of bytes to be generated.\n * @returns A buffer of random data.\n */\nexport function randomBytes(size: number): Buffer {\n return crypto.randomBytes(size)\n}\n\n/**\n * Generate a random UUID string.\n *\n * @returns A random UUID string.\n */\nexport function randomUUID(): string {\n return crypto.randomUUID()\n}\n"]}
1
+ {"version":3,"file":"crypto.js","sourceRoot":"","sources":["../../../src/public/node/crypto.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAA;AAE3B;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,OAAO,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;AACjD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAAC,GAAW;IACzC,OAAO,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAA;AAC3F,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,MAAM,CAAC,GAAW;IAChC,OAAO,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAA;AACzD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,GAAW;IACpC,OAAO,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AAC5D,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,QAAQ,CAAC,IAAY;IACnC,OAAO,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AAC5D,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,OAAO,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,CAAA;AACjC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,UAAU;IACxB,OAAO,MAAM,CAAC,UAAU,EAAE,CAAA;AAC5B,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,aAAa,CAAC,OAAe;IAC3C,yBAAyB;IACzB,MAAM,SAAS,GAAG,sCAAsC,CAAA;IACxD,OAAO,MAAM;SACV,UAAU,CAAC,MAAM,CAAC;SAClB,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC;SACvD,MAAM,CAAC,OAAO,CAAC;SACf,MAAM,EAAE;SACR,QAAQ,CAAC,KAAK,CAAC;SACf,OAAO,CAAC,iCAAiC,EAAE,gBAAgB,CAAC,CAAA;AACjE,CAAC","sourcesContent":["import crypto from 'crypto'\n\n/**\n * Generate a random string in Hex format of the provided size.\n *\n * @param size - Number of bytes to be generated.\n * @returns A random string in Hex format.\n */\nexport function randomHex(size: number): string {\n return crypto.randomBytes(size).toString('hex')\n}\n\n/**\n * Encode a string in Base64 valid for URLs.\n *\n * @param str - The string to encode.\n * @returns The encoded string.\n */\nexport function base64URLEncode(str: Buffer): string {\n return str.toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/[=]/g, '')\n}\n\n/**\n * Generate the SHA256 hash of a string.\n *\n * @param str - The string to hash.\n * @returns The SHA256 hash of the string.\n */\nexport function sha256(str: string): Buffer {\n return crypto.createHash('sha256').update(str).digest()\n}\n\n/**\n * Generate the SHA1 hash of a string.\n *\n * @param str - The string to hash.\n * @returns The SHA1 hash of the string.\n */\nexport function hashString(str: string): string {\n return crypto.createHash('sha1').update(str).digest('hex')\n}\n\n/**\n * Generate an MD5 hash of a buffer.\n *\n * @param buff - The file buffer to hash.\n * @returns A string containing the MD5 hash.\n */\nexport function fileHash(buff: Buffer): string {\n return crypto.createHash('md5').update(buff).digest('hex')\n}\n\n/**\n * Generate random data of the provided size.\n *\n * @param size - Number of bytes to be generated.\n * @returns A buffer of random data.\n */\nexport function randomBytes(size: number): Buffer {\n return crypto.randomBytes(size)\n}\n\n/**\n * Generate a random UUID string.\n *\n * @returns A random UUID string.\n */\nexport function randomUUID(): string {\n return crypto.randomUUID()\n}\n\n/**\n * Generate a non-random UUID string.\n * Useful for generating an identifier from a string that is consistent\n * across different runs of the CLI.\n *\n * @param subject - The subject to generate the UUID from.\n * @returns A non-random UUID string.\n */\nexport function nonRandomUUID(subject: string): string {\n // A fixed namespace UUID\n const namespace = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'\n return crypto\n .createHash('sha1')\n .update(Buffer.from(namespace.replace(/-/g, ''), 'hex'))\n .update(subject)\n .digest()\n .toString('hex')\n .replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5')\n}\n"]}
@@ -42,4 +42,5 @@ export declare function getBackendPort(): number | undefined;
42
42
  export declare function getIdentityTokenInformation(): {
43
43
  accessToken: string;
44
44
  refreshToken: string;
45
+ userId: string;
45
46
  } | undefined;
@@ -1,3 +1,4 @@
1
+ import { nonRandomUUID } from './crypto.js';
1
2
  import { environmentVariables, systemEnvironmentVariables } from '../../private/node/constants.js';
2
3
  /**
3
4
  * It returns the environment variables of the environment
@@ -61,6 +62,7 @@ export function getIdentityTokenInformation() {
61
62
  return {
62
63
  accessToken: identityToken,
63
64
  refreshToken,
65
+ userId: nonRandomUUID(identityToken),
64
66
  };
65
67
  }
66
68
  //# sourceMappingURL=environment.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"environment.js","sourceRoot":"","sources":["../../../src/public/node/environment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,oBAAoB,EAAE,0BAA0B,EAAC,MAAM,iCAAiC,CAAA;AAEhG;;;;;;;;;GASG;AACH,MAAM,UAAU,uBAAuB;IACrC,OAAO,OAAO,CAAC,GAAG,CAAA;AACpB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,gBAAgB;IAC9B,OAAO,uBAAuB,EAAE,CAAC,oBAAoB,CAAC,aAAa,CAAC,CAAA;AACtE,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,gBAAgB;IAC9B,OAAO,gBAAgB,EAAE,KAAK,SAAS,CAAA;AACzC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,eAAe;IAC7B,OAAO,uBAAuB,EAAE,CAAC,oBAAoB,CAAC,YAAY,CAAC,CAAA;AACrE,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,cAAc;IAC5B,MAAM,WAAW,GAAG,uBAAuB,EAAE,CAAC,0BAA0B,CAAC,WAAW,CAAC,CAAA;IACrF,IAAI,WAAW,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,EAAE;QAC9C,OAAO,MAAM,CAAC,WAAW,CAAC,CAAA;KAC3B;IACD,OAAO,SAAS,CAAA;AAClB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,2BAA2B;IACzC,MAAM,aAAa,GAAG,uBAAuB,EAAE,CAAC,oBAAoB,CAAC,aAAa,CAAC,CAAA;IACnF,MAAM,YAAY,GAAG,uBAAuB,EAAE,CAAC,oBAAoB,CAAC,YAAY,CAAC,CAAA;IACjF,IAAI,CAAC,aAAa,IAAI,CAAC,YAAY;QAAE,OAAO,SAAS,CAAA;IACrD,OAAO;QACL,WAAW,EAAE,aAAa;QAC1B,YAAY;KACb,CAAA;AACH,CAAC","sourcesContent":["import {environmentVariables, systemEnvironmentVariables} from '../../private/node/constants.js'\n\n/**\n * It returns the environment variables of the environment\n * where the Node process is running.\n *\n * This function exists to prevent the access of the process\n * global variable which is discouraged via the no-process-env\n * ESLint rule.\n *\n * @returns Current process environment variables.\n */\nexport function getEnvironmentVariables(): NodeJS.ProcessEnv {\n return process.env\n}\n\n/**\n * Returns the value of the SHOPIFY_CLI_PARTNERS_TOKEN environment variable.\n *\n * @returns Current process environment variables.\n */\nexport function getPartnersToken(): string | undefined {\n return getEnvironmentVariables()[environmentVariables.partnersToken]\n}\n\n/**\n * Check if the current proccess is running using the partners token.\n *\n * @returns True if the current proccess is running using the partners token.\n */\nexport function usePartnersToken(): boolean {\n return getPartnersToken() !== undefined\n}\n\n/**\n * Returns the value of the organization id from the environment variables.\n *\n * @returns True if the current proccess is running using the partners token.\n */\nexport function getOrganization(): string | undefined {\n return getEnvironmentVariables()[environmentVariables.organization]\n}\n\n/**\n * Return the backend port value.\n *\n * @returns The port as a number. Undefined otherwise.\n */\nexport function getBackendPort(): number | undefined {\n const backendPort = getEnvironmentVariables()[systemEnvironmentVariables.backendPort]\n if (backendPort && !isNaN(Number(backendPort))) {\n return Number(backendPort)\n }\n return undefined\n}\n\n/**\n * Returns the information of the identity & refresh tokens, provided by environment variables.\n *\n * @returns The identity token information in case it exists.\n */\nexport function getIdentityTokenInformation(): {accessToken: string; refreshToken: string} | undefined {\n const identityToken = getEnvironmentVariables()[environmentVariables.identityToken]\n const refreshToken = getEnvironmentVariables()[environmentVariables.refreshToken]\n if (!identityToken || !refreshToken) return undefined\n return {\n accessToken: identityToken,\n refreshToken,\n }\n}\n"]}
1
+ {"version":3,"file":"environment.js","sourceRoot":"","sources":["../../../src/public/node/environment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,aAAa,EAAC,MAAM,aAAa,CAAA;AACzC,OAAO,EAAC,oBAAoB,EAAE,0BAA0B,EAAC,MAAM,iCAAiC,CAAA;AAEhG;;;;;;;;;GASG;AACH,MAAM,UAAU,uBAAuB;IACrC,OAAO,OAAO,CAAC,GAAG,CAAA;AACpB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,gBAAgB;IAC9B,OAAO,uBAAuB,EAAE,CAAC,oBAAoB,CAAC,aAAa,CAAC,CAAA;AACtE,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,gBAAgB;IAC9B,OAAO,gBAAgB,EAAE,KAAK,SAAS,CAAA;AACzC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,eAAe;IAC7B,OAAO,uBAAuB,EAAE,CAAC,oBAAoB,CAAC,YAAY,CAAC,CAAA;AACrE,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,cAAc;IAC5B,MAAM,WAAW,GAAG,uBAAuB,EAAE,CAAC,0BAA0B,CAAC,WAAW,CAAC,CAAA;IACrF,IAAI,WAAW,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,EAAE;QAC9C,OAAO,MAAM,CAAC,WAAW,CAAC,CAAA;KAC3B;IACD,OAAO,SAAS,CAAA;AAClB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,2BAA2B;IACzC,MAAM,aAAa,GAAG,uBAAuB,EAAE,CAAC,oBAAoB,CAAC,aAAa,CAAC,CAAA;IACnF,MAAM,YAAY,GAAG,uBAAuB,EAAE,CAAC,oBAAoB,CAAC,YAAY,CAAC,CAAA;IACjF,IAAI,CAAC,aAAa,IAAI,CAAC,YAAY;QAAE,OAAO,SAAS,CAAA;IACrD,OAAO;QACL,WAAW,EAAE,aAAa;QAC1B,YAAY;QACZ,MAAM,EAAE,aAAa,CAAC,aAAa,CAAC;KACrC,CAAA;AACH,CAAC","sourcesContent":["import {nonRandomUUID} from './crypto.js'\nimport {environmentVariables, systemEnvironmentVariables} from '../../private/node/constants.js'\n\n/**\n * It returns the environment variables of the environment\n * where the Node process is running.\n *\n * This function exists to prevent the access of the process\n * global variable which is discouraged via the no-process-env\n * ESLint rule.\n *\n * @returns Current process environment variables.\n */\nexport function getEnvironmentVariables(): NodeJS.ProcessEnv {\n return process.env\n}\n\n/**\n * Returns the value of the SHOPIFY_CLI_PARTNERS_TOKEN environment variable.\n *\n * @returns Current process environment variables.\n */\nexport function getPartnersToken(): string | undefined {\n return getEnvironmentVariables()[environmentVariables.partnersToken]\n}\n\n/**\n * Check if the current proccess is running using the partners token.\n *\n * @returns True if the current proccess is running using the partners token.\n */\nexport function usePartnersToken(): boolean {\n return getPartnersToken() !== undefined\n}\n\n/**\n * Returns the value of the organization id from the environment variables.\n *\n * @returns True if the current proccess is running using the partners token.\n */\nexport function getOrganization(): string | undefined {\n return getEnvironmentVariables()[environmentVariables.organization]\n}\n\n/**\n * Return the backend port value.\n *\n * @returns The port as a number. Undefined otherwise.\n */\nexport function getBackendPort(): number | undefined {\n const backendPort = getEnvironmentVariables()[systemEnvironmentVariables.backendPort]\n if (backendPort && !isNaN(Number(backendPort))) {\n return Number(backendPort)\n }\n return undefined\n}\n\n/**\n * Returns the information of the identity & refresh tokens, provided by environment variables.\n *\n * @returns The identity token information in case it exists.\n */\nexport function getIdentityTokenInformation(): {accessToken: string; refreshToken: string; userId: string} | undefined {\n const identityToken = getEnvironmentVariables()[environmentVariables.identityToken]\n const refreshToken = getEnvironmentVariables()[environmentVariables.refreshToken]\n if (!identityToken || !refreshToken) return undefined\n return {\n accessToken: identityToken,\n refreshToken,\n userId: nonRandomUUID(identityToken),\n }\n}\n"]}
@@ -5,9 +5,10 @@ import * as metadata from './metadata.js';
5
5
  import { AbortSilentError, CancelExecution, errorMapper, shouldReportError, handler, cleanSingleStackTracePath, } from './error.js';
6
6
  import { getEnvironmentData } from '../../private/node/analytics.js';
7
7
  import { outputDebug, outputInfo } from '../../public/node/output.js';
8
- import { bugsnagApiKey } from '../../private/node/constants.js';
8
+ import { bugsnagApiKey, reportingRateLimit } from '../../private/node/constants.js';
9
9
  import { printEventsJson } from '../../private/node/demo-recorder.js';
10
10
  import { CLI_KIT_VERSION } from '../common/version.js';
11
+ import { runWithRateLimit } from '../../private/node/conf-store.js';
11
12
  import { settings } from '@oclif/core';
12
13
  import StackTracey from 'stacktracey';
13
14
  import Bugsnag from '@bugsnag/js';
@@ -87,6 +88,18 @@ export async function sendErrorToBugsnag(error, exitMode) {
87
88
  })
88
89
  .join('\n');
89
90
  reportableError.stack = `Error: ${reportableError.message}\n${formattedStacktrace}`;
91
+ let withinRateLimit = false;
92
+ await runWithRateLimit({
93
+ key: 'send-error-to-bugsnag',
94
+ ...reportingRateLimit,
95
+ task: async () => {
96
+ withinRateLimit = true;
97
+ },
98
+ });
99
+ if (!withinRateLimit) {
100
+ outputDebug(`Skipping Bugsnag report due to rate limiting`);
101
+ report = false;
102
+ }
90
103
  if (report) {
91
104
  initializeBugsnag();
92
105
  await new Promise((resolve, reject) => {
@@ -222,6 +235,7 @@ function initializeBugsnag() {
222
235
  appVersion: CLI_KIT_VERSION,
223
236
  autoTrackSessions: false,
224
237
  autoDetectErrors: false,
238
+ enabledReleaseStages: ['production'],
225
239
  });
226
240
  }
227
241
  //# sourceMappingURL=error-handler.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-handler.js","sourceRoot":"","sources":["../../../src/public/node/error-handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,oBAAoB,EAAC,MAAM,gBAAgB,CAAA;AACpE,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,EAAC,WAAW,EAAC,MAAM,cAAc,CAAA;AACxC,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,WAAW,EACX,iBAAiB,EACjB,OAAO,EACP,yBAAyB,GAC1B,MAAM,YAAY,CAAA;AACnB,OAAO,EAAC,kBAAkB,EAAC,MAAM,iCAAiC,CAAA;AAClE,OAAO,EAAC,WAAW,EAAE,UAAU,EAAC,MAAM,6BAA6B,CAAA;AACnE,OAAO,EAAC,aAAa,EAAC,MAAM,iCAAiC,CAAA;AAC7D,OAAO,EAAC,eAAe,EAAC,MAAM,qCAAqC,CAAA;AACnE,OAAO,EAAC,eAAe,EAAC,MAAM,sBAAsB,CAAA;AACpD,OAAO,EAAC,QAAQ,EAAa,MAAM,aAAa,CAAA;AAChD,OAAO,WAAW,MAAM,aAAa,CAAA;AACrC,OAAO,OAAgB,MAAM,aAAa,CAAA;AAC1C,OAAO,EAAC,QAAQ,EAAC,MAAM,aAAa,CAAA;AAEpC,MAA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,OAAO,EAAE,MAAM;QACf,MAAM,EAAE,aAAa;QACrB,MAAM,EAAE,IAAI;QACZ,UAAU,EAAE,eAAe;QAC3B,iBAAiB,EAAE,KAAK;QACxB,gBAAgB,EAAE,KAAK;KACxB,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import {CommandExitMode, reportAnalyticsEvent} from './analytics.js'\nimport * as path from './path.js'\nimport {fanoutHooks} from './plugins.js'\nimport * as metadata from './metadata.js'\nimport {\n AbortSilentError,\n CancelExecution,\n errorMapper,\n shouldReportError,\n handler,\n cleanSingleStackTracePath,\n} from './error.js'\nimport {getEnvironmentData} from '../../private/node/analytics.js'\nimport {outputDebug, outputInfo} from '../../public/node/output.js'\nimport {bugsnagApiKey} from '../../private/node/constants.js'\nimport {printEventsJson} from '../../private/node/demo-recorder.js'\nimport {CLI_KIT_VERSION} from '../common/version.js'\nimport {settings, Interfaces} from '@oclif/core'\nimport StackTracey from 'stacktracey'\nimport Bugsnag, {Event} from '@bugsnag/js'\nimport {realpath} from 'fs/promises'\n\nexport async function errorHandler(\n error: Error & {exitCode?: number | undefined},\n config?: Interfaces.Config,\n): Promise<void> {\n if (error instanceof CancelExecution) {\n if (error.message && error.message !== '') {\n outputInfo(`✨ ${error.message}`)\n }\n } else if (error instanceof AbortSilentError) {\n printEventsJson()\n } else {\n return errorMapper(error)\n .then((error) => {\n return handler(error)\n })\n .then((mappedError) => {\n printEventsJson()\n return reportError(mappedError, config)\n })\n }\n}\n\nconst reportError = async (error: unknown, config?: Interfaces.Config): Promise<void> => {\n // categorise the error first\n let exitMode: CommandExitMode = 'expected_error'\n if (shouldReportError(error)) exitMode = 'unexpected_error'\n\n if (config !== undefined) {\n // Log an analytics event when there's an error\n await reportAnalyticsEvent({config, errorMessage: error instanceof Error ? error.message : undefined, exitMode})\n }\n await sendErrorToBugsnag(error, exitMode)\n}\n\n/**\n * Sends an error to Bugsnag. This is configured automatically for uncaught errors from CLI commands, but can also be used to manually record an error.\n *\n * @returns the reported error (this may have been tweaked for better reporting), and a bool to indicate if the error was actually submitted or not\n */\nexport async function sendErrorToBugsnag(\n error: unknown,\n exitMode: Omit<CommandExitMode, 'ok'>,\n): Promise<{reported: false; error: unknown; unhandled: unknown} | {error: Error; reported: true; unhandled: boolean}> {\n if (settings.debug) {\n outputDebug(`Skipping Bugsnag report`)\n return {reported: false, error, unhandled: undefined}\n }\n\n // If the error was unexpected, we flag it as \"unhandled\" in Bugsnag. This is a helpful distinction.\n const unhandled = exitMode === 'unexpected_error'\n\n let reportableError: Error\n let stacktrace: string | undefined\n let report = false\n\n if (error instanceof Error) {\n report = true\n reportableError = new Error(error.message)\n stacktrace = error.stack\n\n /**\n * Some errors that reach this point have an empty string. For example:\n * https://app.bugsnag.com/shopify/cli/errors/62cd5d31fd5040000814086c?filters[event.since]=30d&filters[error.status]=new&filters[release.seen_in]=3.1.0\n *\n * Because at this point we have neither the error message nor a stack trace reporting them\n * to Bugsnag is pointless and adds noise.\n */\n } else if (typeof error === 'string' && error.trim().length !== 0) {\n report = true\n reportableError = new Error(error)\n stacktrace = reportableError.stack\n } else {\n report = false\n reportableError = new Error('Unknown error')\n }\n\n const formattedStacktrace = new StackTracey(stacktrace ?? '')\n .clean()\n .items.map((item) => {\n const filePath = cleanSingleStackTracePath(item.file)\n return ` at ${item.callee} (${filePath}:${item.line}:${item.column})`\n })\n .join('\\n')\n reportableError.stack = `Error: ${reportableError.message}\\n${formattedStacktrace}`\n\n if (report) {\n initializeBugsnag()\n await new Promise((resolve, reject) => {\n outputDebug(`Reporting ${unhandled ? 'unhandled' : 'handled'} error to Bugsnag: ${reportableError.message}`)\n const eventHandler = (event: Event) => {\n event.severity = 'error'\n event.unhandled = unhandled\n }\n const errorHandler = (error: unknown) => {\n if (error) {\n reject(error)\n } else {\n resolve(reportableError)\n }\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n Bugsnag.notify(reportableError, eventHandler, errorHandler)\n })\n }\n return {error: reportableError, reported: report, unhandled}\n}\n\n/**\n * If the given file path is within a node_modules folder, remove prefix up\n * to and including the node_modules folder.\n *\n * This gives us very consistent paths for errors generated by the CLI.\n */\nexport function cleanStackFrameFilePath({\n currentFilePath,\n projectRoot,\n pluginLocations,\n}: {\n currentFilePath: string\n projectRoot: string\n pluginLocations: {name: string; pluginPath: string}[]\n}): string {\n const fullLocation = path.isAbsolutePath(currentFilePath)\n ? currentFilePath\n : path.joinPath(projectRoot, currentFilePath)\n\n const matchingPluginPath = pluginLocations.filter(({pluginPath}) => fullLocation.indexOf(pluginPath) === 0)[0]\n\n if (matchingPluginPath !== undefined) {\n // the plugin name (e.g. @shopify/cli-kit), plus the relative path of the error line from within the plugin's code (e.g. dist/something.js )\n return path.joinPath(matchingPluginPath.name, path.relativePath(matchingPluginPath.pluginPath, fullLocation))\n }\n\n // strip prefix up to node_modules folder, so we can normalize error reporting\n return currentFilePath.replace(/.*node_modules\\//, '')\n}\n\n/**\n * Register a Bugsnag error listener to clean up stack traces for errors within plugin code.\n *\n */\nexport async function registerCleanBugsnagErrorsFromWithinPlugins(config: Interfaces.Config): Promise<void> {\n // Bugsnag have their own plug-ins that use this private field\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const bugsnagConfigProjectRoot: string = (Bugsnag as any)?._client?._config?.projectRoot ?? path.cwd()\n const projectRoot = path.normalizePath(bugsnagConfigProjectRoot)\n const pluginLocations = await Promise.all(\n [...config.plugins].map(async ([_, plugin]) => {\n const followSymlinks = await realpath(plugin.root)\n return {name: plugin.name, pluginPath: path.normalizePath(followSymlinks)}\n }),\n )\n initializeBugsnag()\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n Bugsnag.addOnError(async (event) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n event.errors.forEach((error: any) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n error.stacktrace.forEach((stackFrame: any) => {\n stackFrame.file = cleanStackFrameFilePath({currentFilePath: stackFrame.file, projectRoot, pluginLocations})\n })\n })\n try {\n await addBugsnagMetadata(event, config)\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (metadataError) {\n outputDebug(`There was an error adding metadata to the Bugsnag report; Ignoring and carrying on ${metadataError}`)\n }\n })\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any\nexport async function addBugsnagMetadata(event: any, config: Interfaces.Config): Promise<void> {\n const publicData = metadata.getAllPublicMetadata()\n const {commandStartOptions} = metadata.getAllSensitiveMetadata()\n const {startCommand} = commandStartOptions ?? {}\n\n const {'@shopify/app': appPublic, ...otherPluginsPublic} = await fanoutHooks(config, 'public_command_metadata', {})\n\n const environment = await getEnvironmentData(config)\n\n const allMetadata = {\n command: startCommand,\n ...appPublic,\n ...publicData,\n ...environment,\n pluginData: otherPluginsPublic,\n }\n\n const appData = {} as {[key: string]: unknown}\n const commandData = {} as {[key: string]: unknown}\n const environmentData = {} as {[key: string]: unknown}\n const miscData = {} as {[key: string]: unknown}\n const appKeys = ['api_key', 'partner_id', 'project_type']\n const commandKeys = ['command']\n const environmentKeys = ['cli_version', 'node_version', 'ruby_version', 'uname']\n\n Object.entries(allMetadata).forEach(([key, value]) => {\n if (key.startsWith('app_') || appKeys.includes(key)) {\n appData[key] = value\n } else if (key.startsWith('cmd_') || commandKeys.includes(key)) {\n commandData[key] = value\n } else if (key.startsWith('env_') || environmentKeys) {\n environmentData[key] = value\n } else {\n miscData[key] = value\n }\n })\n\n // app, command, environment, misc\n const bugsnagMetadata = {\n 'Shopify App': appData,\n Command: commandData,\n Environment: environmentData,\n Misc: miscData,\n }\n Object.entries(bugsnagMetadata).forEach(([section, values]) => {\n event.addMetadata(section, values)\n })\n}\n\nfunction initializeBugsnag() {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n if (Bugsnag.isStarted()) {\n return\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n Bugsnag.start({\n appType: 'node',\n apiKey: bugsnagApiKey,\n logger: null,\n appVersion: CLI_KIT_VERSION,\n autoTrackSessions: false,\n autoDetectErrors: false,\n })\n}\n"]}
1
+ {"version":3,"file":"error-handler.js","sourceRoot":"","sources":["../../../src/public/node/error-handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,oBAAoB,EAAC,MAAM,gBAAgB,CAAA;AACpE,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,EAAC,WAAW,EAAC,MAAM,cAAc,CAAA;AACxC,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,WAAW,EACX,iBAAiB,EACjB,OAAO,EACP,yBAAyB,GAC1B,MAAM,YAAY,CAAA;AACnB,OAAO,EAAC,kBAAkB,EAAC,MAAM,iCAAiC,CAAA;AAClE,OAAO,EAAC,WAAW,EAAE,UAAU,EAAC,MAAM,6BAA6B,CAAA;AACnE,OAAO,EAAC,aAAa,EAAE,kBAAkB,EAAC,MAAM,iCAAiC,CAAA;AACjF,OAAO,EAAC,eAAe,EAAC,MAAM,qCAAqC,CAAA;AACnE,OAAO,EAAC,eAAe,EAAC,MAAM,sBAAsB,CAAA;AACpD,OAAO,EAAC,gBAAgB,EAAC,MAAM,kCAAkC,CAAA;AACjE,OAAO,EAAC,QAAQ,EAAa,MAAM,aAAa,CAAA;AAChD,OAAO,WAAW,MAAM,aAAa,CAAA;AACrC,OAAO,OAAgB,MAAM,aAAa,CAAA;AAC1C,OAAO,EAAC,QAAQ,EAAC,MAAM,aAAa,CAAA;AAEpC,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,KAA8C,EAC9C,MAA0B;IAE1B,IAAI,KAAK,YAAY,eAAe,EAAE;QACpC,IAAI,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,OAAO,KAAK,EAAE,EAAE;YACzC,UAAU,CAAC,MAAM,KAAK,CAAC,OAAO,EAAE,CAAC,CAAA;SAClC;KACF;SAAM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AM;KACP;IACD,6DAA6D;IAC7D,aAAa;IACb,OAAO,CAAC,KAAK,CAAC;QACZ,OAAO,EAAE,MAAM;QACf,MAAM,EAAE,aAAa;QACrB,MAAM,EAAE,IAAI;QACZ,UAAU,EAAE,eAAe;QAC3B,iBAAiB,EAAE,KAAK;QACxB,gBAAgB,EAAE,KAAK;QACvB,oBAAoB,EAAE,CAAC,YAAY,CAAC;KACrC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import {CommandExitMode, reportAnalyticsEvent} from './analytics.js'\nimport * as path from './path.js'\nimport {fanoutHooks} from './plugins.js'\nimport * as metadata from './metadata.js'\nimport {\n AbortSilentError,\n CancelExecution,\n errorMapper,\n shouldReportError,\n handler,\n cleanSingleStackTracePath,\n} from './error.js'\nimport {getEnvironmentData} from '../../private/node/analytics.js'\nimport {outputDebug, outputInfo} from '../../public/node/output.js'\nimport {bugsnagApiKey, reportingRateLimit} from '../../private/node/constants.js'\nimport {printEventsJson} from '../../private/node/demo-recorder.js'\nimport {CLI_KIT_VERSION} from '../common/version.js'\nimport {runWithRateLimit} from '../../private/node/conf-store.js'\nimport {settings, Interfaces} from '@oclif/core'\nimport StackTracey from 'stacktracey'\nimport Bugsnag, {Event} from '@bugsnag/js'\nimport {realpath} from 'fs/promises'\n\nexport async function errorHandler(\n error: Error & {exitCode?: number | undefined},\n config?: Interfaces.Config,\n): Promise<void> {\n if (error instanceof CancelExecution) {\n if (error.message && error.message !== '') {\n outputInfo(`✨ ${error.message}`)\n }\n } else if (error instanceof AbortSilentError) {\n printEventsJson()\n } else {\n return errorMapper(error)\n .then((error) => {\n return handler(error)\n })\n .then((mappedError) => {\n printEventsJson()\n return reportError(mappedError, config)\n })\n }\n}\n\nconst reportError = async (error: unknown, config?: Interfaces.Config): Promise<void> => {\n // categorise the error first\n let exitMode: CommandExitMode = 'expected_error'\n if (shouldReportError(error)) exitMode = 'unexpected_error'\n\n if (config !== undefined) {\n // Log an analytics event when there's an error\n await reportAnalyticsEvent({config, errorMessage: error instanceof Error ? error.message : undefined, exitMode})\n }\n await sendErrorToBugsnag(error, exitMode)\n}\n\n/**\n * Sends an error to Bugsnag. This is configured automatically for uncaught errors from CLI commands, but can also be used to manually record an error.\n *\n * @returns the reported error (this may have been tweaked for better reporting), and a bool to indicate if the error was actually submitted or not\n */\nexport async function sendErrorToBugsnag(\n error: unknown,\n exitMode: Omit<CommandExitMode, 'ok'>,\n): Promise<{reported: false; error: unknown; unhandled: unknown} | {error: Error; reported: true; unhandled: boolean}> {\n if (settings.debug) {\n outputDebug(`Skipping Bugsnag report`)\n return {reported: false, error, unhandled: undefined}\n }\n\n // If the error was unexpected, we flag it as \"unhandled\" in Bugsnag. This is a helpful distinction.\n const unhandled = exitMode === 'unexpected_error'\n\n let reportableError: Error\n let stacktrace: string | undefined\n let report = false\n\n if (error instanceof Error) {\n report = true\n reportableError = new Error(error.message)\n stacktrace = error.stack\n\n /**\n * Some errors that reach this point have an empty string. For example:\n * https://app.bugsnag.com/shopify/cli/errors/62cd5d31fd5040000814086c?filters[event.since]=30d&filters[error.status]=new&filters[release.seen_in]=3.1.0\n *\n * Because at this point we have neither the error message nor a stack trace reporting them\n * to Bugsnag is pointless and adds noise.\n */\n } else if (typeof error === 'string' && error.trim().length !== 0) {\n report = true\n reportableError = new Error(error)\n stacktrace = reportableError.stack\n } else {\n report = false\n reportableError = new Error('Unknown error')\n }\n\n const formattedStacktrace = new StackTracey(stacktrace ?? '')\n .clean()\n .items.map((item) => {\n const filePath = cleanSingleStackTracePath(item.file)\n return ` at ${item.callee} (${filePath}:${item.line}:${item.column})`\n })\n .join('\\n')\n reportableError.stack = `Error: ${reportableError.message}\\n${formattedStacktrace}`\n\n let withinRateLimit = false\n await runWithRateLimit({\n key: 'send-error-to-bugsnag',\n ...reportingRateLimit,\n task: async () => {\n withinRateLimit = true\n },\n })\n if (!withinRateLimit) {\n outputDebug(`Skipping Bugsnag report due to rate limiting`)\n report = false\n }\n\n if (report) {\n initializeBugsnag()\n await new Promise((resolve, reject) => {\n outputDebug(`Reporting ${unhandled ? 'unhandled' : 'handled'} error to Bugsnag: ${reportableError.message}`)\n const eventHandler = (event: Event) => {\n event.severity = 'error'\n event.unhandled = unhandled\n }\n const errorHandler = (error: unknown) => {\n if (error) {\n reject(error)\n } else {\n resolve(reportableError)\n }\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n Bugsnag.notify(reportableError, eventHandler, errorHandler)\n })\n }\n return {error: reportableError, reported: report, unhandled}\n}\n\n/**\n * If the given file path is within a node_modules folder, remove prefix up\n * to and including the node_modules folder.\n *\n * This gives us very consistent paths for errors generated by the CLI.\n */\nexport function cleanStackFrameFilePath({\n currentFilePath,\n projectRoot,\n pluginLocations,\n}: {\n currentFilePath: string\n projectRoot: string\n pluginLocations: {name: string; pluginPath: string}[]\n}): string {\n const fullLocation = path.isAbsolutePath(currentFilePath)\n ? currentFilePath\n : path.joinPath(projectRoot, currentFilePath)\n\n const matchingPluginPath = pluginLocations.filter(({pluginPath}) => fullLocation.indexOf(pluginPath) === 0)[0]\n\n if (matchingPluginPath !== undefined) {\n // the plugin name (e.g. @shopify/cli-kit), plus the relative path of the error line from within the plugin's code (e.g. dist/something.js )\n return path.joinPath(matchingPluginPath.name, path.relativePath(matchingPluginPath.pluginPath, fullLocation))\n }\n\n // strip prefix up to node_modules folder, so we can normalize error reporting\n return currentFilePath.replace(/.*node_modules\\//, '')\n}\n\n/**\n * Register a Bugsnag error listener to clean up stack traces for errors within plugin code.\n *\n */\nexport async function registerCleanBugsnagErrorsFromWithinPlugins(config: Interfaces.Config): Promise<void> {\n // Bugsnag have their own plug-ins that use this private field\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const bugsnagConfigProjectRoot: string = (Bugsnag as any)?._client?._config?.projectRoot ?? path.cwd()\n const projectRoot = path.normalizePath(bugsnagConfigProjectRoot)\n const pluginLocations = await Promise.all(\n [...config.plugins].map(async ([_, plugin]) => {\n const followSymlinks = await realpath(plugin.root)\n return {name: plugin.name, pluginPath: path.normalizePath(followSymlinks)}\n }),\n )\n initializeBugsnag()\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n Bugsnag.addOnError(async (event) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n event.errors.forEach((error: any) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n error.stacktrace.forEach((stackFrame: any) => {\n stackFrame.file = cleanStackFrameFilePath({currentFilePath: stackFrame.file, projectRoot, pluginLocations})\n })\n })\n try {\n await addBugsnagMetadata(event, config)\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (metadataError) {\n outputDebug(`There was an error adding metadata to the Bugsnag report; Ignoring and carrying on ${metadataError}`)\n }\n })\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any\nexport async function addBugsnagMetadata(event: any, config: Interfaces.Config): Promise<void> {\n const publicData = metadata.getAllPublicMetadata()\n const {commandStartOptions} = metadata.getAllSensitiveMetadata()\n const {startCommand} = commandStartOptions ?? {}\n\n const {'@shopify/app': appPublic, ...otherPluginsPublic} = await fanoutHooks(config, 'public_command_metadata', {})\n\n const environment = await getEnvironmentData(config)\n\n const allMetadata = {\n command: startCommand,\n ...appPublic,\n ...publicData,\n ...environment,\n pluginData: otherPluginsPublic,\n }\n\n const appData = {} as {[key: string]: unknown}\n const commandData = {} as {[key: string]: unknown}\n const environmentData = {} as {[key: string]: unknown}\n const miscData = {} as {[key: string]: unknown}\n const appKeys = ['api_key', 'partner_id', 'project_type']\n const commandKeys = ['command']\n const environmentKeys = ['cli_version', 'node_version', 'ruby_version', 'uname']\n\n Object.entries(allMetadata).forEach(([key, value]) => {\n if (key.startsWith('app_') || appKeys.includes(key)) {\n appData[key] = value\n } else if (key.startsWith('cmd_') || commandKeys.includes(key)) {\n commandData[key] = value\n } else if (key.startsWith('env_') || environmentKeys) {\n environmentData[key] = value\n } else {\n miscData[key] = value\n }\n })\n\n // app, command, environment, misc\n const bugsnagMetadata = {\n 'Shopify App': appData,\n Command: commandData,\n Environment: environmentData,\n Misc: miscData,\n }\n Object.entries(bugsnagMetadata).forEach(([section, values]) => {\n event.addMetadata(section, values)\n })\n}\n\nfunction initializeBugsnag() {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n if (Bugsnag.isStarted()) {\n return\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n Bugsnag.start({\n appType: 'node',\n apiKey: bugsnagApiKey,\n logger: null,\n appVersion: CLI_KIT_VERSION,\n autoTrackSessions: false,\n autoDetectErrors: false,\n enabledReleaseStages: ['production'],\n })\n}\n"]}
@@ -1,13 +1,12 @@
1
1
  import FormData from 'form-data';
2
- import nodeFetch, { RequestInfo, RequestInit } from 'node-fetch';
3
- export { FetchError, Request } from 'node-fetch';
2
+ import { RequestInfo, RequestInit, Response } from 'node-fetch';
3
+ export { FetchError, Request, Response } from 'node-fetch';
4
4
  /**
5
5
  * Create a new FormData object.
6
6
  *
7
7
  * @returns A FormData object.
8
8
  */
9
9
  export declare function formData(): FormData;
10
- export type Response = Awaited<ReturnType<typeof nodeFetch>>;
11
10
  /**
12
11
  * An interface that abstracts way node-fetch. When Node has built-in
13
12
  * support for "fetch" in the standard library, we can drop the node-fetch
@@ -7,7 +7,7 @@ import { outputContent, outputDebug } from '../../public/node/output.js';
7
7
  import { simpleRequestWithDebugLog } from '../../private/node/api.js';
8
8
  import FormData from 'form-data';
9
9
  import nodeFetch from 'node-fetch';
10
- export { FetchError, Request } from 'node-fetch';
10
+ export { FetchError, Request, Response } from 'node-fetch';
11
11
  /**
12
12
  * Create a new FormData object.
13
13
  *
@@ -1 +1 @@
1
- {"version":3,"file":"http.js","sourceRoot":"","sources":["../../../src/public/node/http.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,OAAO,EAAC,MAAM,WAAW,CAAA;AACjC,OAAO,EAAC,qBAAqB,EAAE,cAAc,EAAE,SAA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,MAAM,CAAC,GAAG,CAAC,CAAA;YACb,CAAC,CAAC,CAAA;YAEF,SAAS,CAAC,GAAG,EAAE,EAAC,QAAQ,EAAE,QAAQ,EAAC,CAAC;iBACjC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE;gBACZ,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CAAA;YACtB,CAAC,CAAC;iBACD,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;gBACb,cAAc,CAAC,EAAE,CAAC,CAAA;gBAClB,MAAM,CAAC,GAAG,CAAC,CAAA;YACb,CAAC,CAAC,CAAA;QACN,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import {dirname} from './path.js'\nimport {createFileWriteStream, fileExistsSync, mkdirSync, unlinkFileSync} from './fs.js'\nimport {runWithTimer} from './metadata.js'\nimport {buildHeaders, httpsAgent, sanitizedHeadersOutput} from '../../private/node/api/headers.js'\nimport {sanitizeURL} from '../../private/node/api/urls.js'\nimport {outputContent, outputDebug} from '../../public/node/output.js'\nimport {simpleRequestWithDebugLog} from '../../private/node/api.js'\nimport FormData from 'form-data'\nimport nodeFetch, {RequestInfo, RequestInit} from 'node-fetch'\n\nexport {FetchError, Request} from 'node-fetch'\n\n/**\n * Create a new FormData object.\n *\n * @returns A FormData object.\n */\nexport function formData(): FormData {\n return new FormData()\n}\n\nexport type Response = Awaited<ReturnType<typeof nodeFetch>>\n\n/**\n * An interface that abstracts way node-fetch. When Node has built-in\n * support for \"fetch\" in the standard library, we can drop the node-fetch\n * dependency from here.\n * Note that we are exposing types from \"node-fetch\". The reason being is that\n * they are consistent with the Web API so if we drop node-fetch in the future\n * it won't require changes from the callers.\n *\n * @param url - This defines the resource that you wish to fetch.\n * @param init - An object containing any custom settings that you want to apply to the request.\n * @returns A promise that resolves with the response.\n */\nexport async function fetch(url: RequestInfo, init?: RequestInit): Promise<Response> {\n return runWithTimer('cmd_all_timing_network_ms')(() =>\n simpleRequestWithDebugLog({url: url.toString(), request: () => nodeFetch(url, init)}),\n )\n}\n\n/**\n * A fetch function to use with Shopify services. The function ensures the right\n * TLS configuragion is used based on the environment in which the service is running\n * (e.g. Spin).\n *\n * @param url - This defines the resource that you wish to fetch.\n * @param init - An object containing any custom settings that you want to apply to the request.\n * @returns A promise that resolves with the response.\n */\nexport async function shopifyFetch(url: RequestInfo, init?: RequestInit): Promise<Response> {\n const sanitizedUrl = sanitizeURL(url.toString())\n const options: RequestInit = {\n ...(init ?? {}),\n headers: {\n ...(await buildHeaders()),\n ...(init?.headers ?? {}),\n },\n }\n\n outputDebug(outputContent`Sending ${options.method ?? 'GET'} request to URL ${sanitizedUrl}\nWith request headers:\n${sanitizedHeadersOutput((options?.headers ?? {}) as {[header: string]: string})}\n`)\n return runWithTimer('cmd_all_timing_network_ms')(async () => {\n return simpleRequestWithDebugLog({\n url: url.toString(),\n request: async () => nodeFetch(url, {...init, agent: await httpsAgent()}),\n })\n })\n}\n\n/**\n * Download a file from a URL to a local path.\n *\n * @param url - The URL to download from.\n * @param to - The local path to download to.\n * @returns - A promise that resolves with the local path.\n */\nexport function downloadFile(url: string, to: string): Promise<string> {\n const sanitizedUrl = sanitizeURL(url)\n outputDebug(`Downloading ${sanitizedUrl} to ${to}`)\n\n return runWithTimer('cmd_all_timing_network_ms')(() => {\n return new Promise<string>((resolve, reject) => {\n if (!fileExistsSync(dirname(to))) {\n mkdirSync(dirname(to))\n }\n\n const file = createFileWriteStream(to)\n\n file.on('finish', () => {\n file.close()\n resolve(to)\n })\n\n file.on('error', (err) => {\n unlinkFileSync(to)\n reject(err)\n })\n\n nodeFetch(url, {redirect: 'follow'})\n .then((res) => {\n res.body?.pipe(file)\n })\n .catch((err) => {\n unlinkFileSync(to)\n reject(err)\n })\n })\n })\n}\n"]}
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../../../src/public/node/http.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,OAAO,EAAC,MAAM,WAA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CAAC,GAAG,EAAE,EAAE;gBACvB,cAAc,CAAC,EAAE,CAAC,CAAA;gBAClB,MAAM,CAAC,GAAG,CAAC,CAAA;YACb,CAAC,CAAC,CAAA;YAEF,SAAS,CAAC,GAAG,EAAE,EAAC,QAAQ,EAAE,QAAQ,EAAC,CAAC;iBACjC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE;gBACZ,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CAAA;YACtB,CAAC,CAAC;iBACD,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;gBACb,cAAc,CAAC,EAAE,CAAC,CAAA;gBAClB,MAAM,CAAC,GAAG,CAAC,CAAA;YACb,CAAC,CAAC,CAAA;QACN,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import {dirname} from './path.js'\nimport {createFileWriteStream, fileExistsSync, mkdirSync, unlinkFileSync} from './fs.js'\nimport {runWithTimer} from './metadata.js'\nimport {buildHeaders, httpsAgent, sanitizedHeadersOutput} from '../../private/node/api/headers.js'\nimport {sanitizeURL} from '../../private/node/api/urls.js'\nimport {outputContent, outputDebug} from '../../public/node/output.js'\nimport {simpleRequestWithDebugLog} from '../../private/node/api.js'\nimport FormData from 'form-data'\nimport nodeFetch, {RequestInfo, RequestInit, Response} from 'node-fetch'\n\nexport {FetchError, Request, Response} from 'node-fetch'\n\n/**\n * Create a new FormData object.\n *\n * @returns A FormData object.\n */\nexport function formData(): FormData {\n return new FormData()\n}\n\n/**\n * An interface that abstracts way node-fetch. When Node has built-in\n * support for \"fetch\" in the standard library, we can drop the node-fetch\n * dependency from here.\n * Note that we are exposing types from \"node-fetch\". The reason being is that\n * they are consistent with the Web API so if we drop node-fetch in the future\n * it won't require changes from the callers.\n *\n * @param url - This defines the resource that you wish to fetch.\n * @param init - An object containing any custom settings that you want to apply to the request.\n * @returns A promise that resolves with the response.\n */\nexport async function fetch(url: RequestInfo, init?: RequestInit): Promise<Response> {\n return runWithTimer('cmd_all_timing_network_ms')(() =>\n simpleRequestWithDebugLog({url: url.toString(), request: () => nodeFetch(url, init)}),\n )\n}\n\n/**\n * A fetch function to use with Shopify services. The function ensures the right\n * TLS configuragion is used based on the environment in which the service is running\n * (e.g. Spin).\n *\n * @param url - This defines the resource that you wish to fetch.\n * @param init - An object containing any custom settings that you want to apply to the request.\n * @returns A promise that resolves with the response.\n */\nexport async function shopifyFetch(url: RequestInfo, init?: RequestInit): Promise<Response> {\n const sanitizedUrl = sanitizeURL(url.toString())\n const options: RequestInit = {\n ...(init ?? {}),\n headers: {\n ...(await buildHeaders()),\n ...(init?.headers ?? {}),\n },\n }\n\n outputDebug(outputContent`Sending ${options.method ?? 'GET'} request to URL ${sanitizedUrl}\nWith request headers:\n${sanitizedHeadersOutput((options?.headers ?? {}) as {[header: string]: string})}\n`)\n return runWithTimer('cmd_all_timing_network_ms')(async () => {\n return simpleRequestWithDebugLog({\n url: url.toString(),\n request: async () => nodeFetch(url, {...init, agent: await httpsAgent()}),\n })\n })\n}\n\n/**\n * Download a file from a URL to a local path.\n *\n * @param url - The URL to download from.\n * @param to - The local path to download to.\n * @returns - A promise that resolves with the local path.\n */\nexport function downloadFile(url: string, to: string): Promise<string> {\n const sanitizedUrl = sanitizeURL(url)\n outputDebug(`Downloading ${sanitizedUrl} to ${to}`)\n\n return runWithTimer('cmd_all_timing_network_ms')(() => {\n return new Promise<string>((resolve, reject) => {\n if (!fileExistsSync(dirname(to))) {\n mkdirSync(dirname(to))\n }\n\n const file = createFileWriteStream(to)\n\n file.on('finish', () => {\n file.close()\n resolve(to)\n })\n\n file.on('error', (err) => {\n unlinkFileSync(to)\n reject(err)\n })\n\n nodeFetch(url, {redirect: 'follow'})\n .then((res) => {\n res.body?.pipe(file)\n })\n .catch((err) => {\n unlinkFileSync(to)\n reject(err)\n })\n })\n })\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { isUnitTest } from './context/local.js';
2
2
  import { outputInfo } from './output.js';
3
3
  import { cwd, sniffForPath } from './path.js';
4
- import { captureOutput, exec, terminalSupportsRawMode } from './system.js';
4
+ import { captureOutput, exec, terminalSupportsPrompting } from './system.js';
5
5
  import { renderSelectPrompt } from './ui.js';
6
6
  import { execaSync } from 'execa';
7
7
  let _isGlobal;
@@ -59,7 +59,7 @@ export async function installGlobalShopifyCLI(packageManager) {
59
59
  * @returns `true` if the user has installed the global CLI.
60
60
  */
61
61
  export async function installGlobalCLIPrompt() {
62
- if (!terminalSupportsRawMode())
62
+ if (!terminalSupportsPrompting())
63
63
  return { install: false, alreadyInstalled: false };
64
64
  if (await isGlobalCLIInstalled()) {
65
65
  return { install: false, alreadyInstalled: true };
@@ -1 +1 @@
1
- {"version":3,"file":"is-global.js","sourceRoot":"","sources":["../../../src/public/node/is-global.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,MAAM,oBAAoB,CAAA;AAE7C,OAAO,EAAC,UAAU,EAAC,MAAM,aAAa,CAAA;AACtC,OAAO,EAAC,GAAG,EAAE,YAAY,EAAC,MAAM,WAAW,CAAA;AAC3C,OAAO,EAAC,aAAa,EAAE,IAAI,EAAE,uBAAuB,EAAC,MAAM,aAAa,CAAA;AACxE,OAAO,EAAC,kBAAkB,EAAC,MAAM,SAAS,CAAA;AAC1C,OAAO,EAAC,SAAS,EAAC,MAAM,OAAO,CAAA;AAE/B,IAAI,SAA8B,CAAA;AAElC;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI;IACxD,wDAAwD;IACxD,IAAI,SAAS,KAAK,SAAS,IAAI,CAAC,UAAU,EAAE;QAAE,OAAO,SAAS,CAAA;IAE9D,mDAAmD;IACnD,MAAM,IAAI,GAAG,YAAY,EAAE,IAAI,GAAG,EAAE,CAAA;IAEpC,oFAAoF;IACpF,gEAAgE;IAChE,MAAM,SAAS,GAAG,SAAS,CAAC,KAAK,EAAE,CAAC,QAAQ,CAAC,EAAE,EAAC,GAA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E,EAAE;QAChC,OAAO,EAAC,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAE,IAAI,EAAC,CAAA;KAChD;IACD,MAAM,MAAM,GAAG,MAAM,kBAAkB,CAAC;QACtC,OAAO,EAAE,gGAAgG;QACzG,OAAO,EAAE;YACP,EAAC,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAC;YAC5B,EAAC,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,2BAA2B,EAAC;SAClD;KACF,CAAC,CAAA;IAEF,OAAO,EAAC,OAAO,EAAE,MAAM,KAAK,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAC,CAAA;AAC7D,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,+BAA+B,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI;IACjE,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC;QAAE,OAAO,SAAS,CAAA;IAEnD,mDAAmD;IACnD,MAAM,WAAW,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;IACjC,IAAI,WAAW,CAAC,QAAQ,CAAC,MAAM,CAAC;QAAE,OAAO,MAAM,CAAA;IAC/C,IAAI,WAAW,CAAC,QAAQ,CAAC,MAAM,CAAC;QAAE,OAAO,MAAM,CAAA;IAC/C,IAAI,WAAW,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAA;IAC7C,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["import {isUnitTest} from './context/local.js'\nimport {PackageManager} from './node-package-manager.js'\nimport {outputInfo} from './output.js'\nimport {cwd, sniffForPath} from './path.js'\nimport {captureOutput, exec, terminalSupportsRawMode} from './system.js'\nimport {renderSelectPrompt} from './ui.js'\nimport {execaSync} from 'execa'\n\nlet _isGlobal: boolean | undefined\n\n/**\n * Returns true if the current process is running in a global context.\n *\n * @param argv - The arguments passed to the process.\n * @returns `true` if the current process is running in a global context.\n */\nexport function currentProcessIsGlobal(argv = process.argv): boolean {\n // If we are running tests, we need to disable the cache\n if (_isGlobal !== undefined && !isUnitTest()) return _isGlobal\n\n // Path where the current project is (app/hydrogen)\n const path = sniffForPath() ?? cwd()\n\n // Closest parent directory to contain a package.json file or node_modules directory\n // https://docs.npmjs.com/cli/v8/commands/npm-prefix#description\n const npmPrefix = execaSync('npm', ['prefix'], {cwd: path}).stdout.trim()\n\n // From node docs: \"The second element [of the array] will be the path to the JavaScript file being executed\"\n const binDir = argv[1] ?? ''\n\n // If binDir starts with npmPrefix, then we are running a local CLI\n const isLocal = binDir.startsWith(npmPrefix.trim())\n\n _isGlobal = !isLocal\n return _isGlobal\n}\n\n/**\n * Returns true if the global CLI is installed.\n *\n * @returns `true` if the global CLI is installed.\n */\nexport async function isGlobalCLIInstalled(): Promise<boolean> {\n try {\n const output = await captureOutput('shopify', ['app'])\n // Installed if `app dev` is available globally\n return output.includes('app dev')\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch {\n return false\n }\n}\n\n/**\n * Installs the global Shopify CLI, using the provided package manager.\n *\n * @param packageManager - The package manager to use.\n */\nexport async function installGlobalShopifyCLI(packageManager: PackageManager): Promise<void> {\n const args =\n packageManager === 'yarn' ? ['global', 'add', '@shopify/cli@latest'] : ['install', '-g', '@shopify/cli@latest']\n outputInfo(`Running ${packageManager} ${args.join(' ')}...`)\n await exec(packageManager, args, {stdio: 'inherit'})\n}\n\nexport interface InstallGlobalCLIPromptResult {\n install: boolean\n alreadyInstalled: boolean\n}\n/**\n * Prompts the user to install the global CLI.\n *\n * @returns `true` if the user has installed the global CLI.\n */\nexport async function installGlobalCLIPrompt(): Promise<InstallGlobalCLIPromptResult> {\n if (!terminalSupportsRawMode()) return {install: false, alreadyInstalled: false}\n if (await isGlobalCLIInstalled()) {\n return {install: false, alreadyInstalled: true}\n }\n const result = await renderSelectPrompt({\n message: 'We recommend installing Shopify CLI globally in your system. Would you like to install it now?',\n choices: [\n {value: 'yes', label: 'Yes'},\n {value: 'no', label: 'No, just for this project'},\n ],\n })\n\n return {install: result === 'yes', alreadyInstalled: false}\n}\n\n/**\n * Infers the package manager used by the global CLI.\n *\n * @param argv - The arguments passed to the process.\n * @returns The package manager used by the global CLI.\n */\nexport function inferPackageManagerForGlobalCLI(argv = process.argv): PackageManager {\n if (!currentProcessIsGlobal(argv)) return 'unknown'\n\n // argv[1] contains the path of the executed binary\n const processArgv = argv[1] ?? ''\n if (processArgv.includes('yarn')) return 'yarn'\n if (processArgv.includes('pnpm')) return 'pnpm'\n if (processArgv.includes('bun')) return 'bun'\n return 'npm'\n}\n"]}
1
+ {"version":3,"file":"is-global.js","sourceRoot":"","sources":["../../../src/public/node/is-global.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,MAAM,oBAAoB,CAAA;AAE7C,OAAO,EAAC,UAAU,EAAC,MAAM,aAAa,CAAA;AACtC,OAAO,EAAC,GAAG,EAAE,YAAY,EAAC,MAAM,WAAW,CAAA;AAC3C,OAAO,EAAC,aAAa,EAAE,IAAI,EAAE,yBAAyB,EAAC,MAAM,aAAa,CAAA;AAC1E,OAAO,EAAC,kBAAkB,EAAC,MAAM,SAAS,CAAA;AAC1C,OAAO,EAAC,SAAS,EAAC,MAAM,OAAO,CAAA;AAE/B,IAAI,SAA8B,CAAA;AAElC;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI;IACxD,wDAAwD;IACxD,IAAI,SAAS,KAAK,SAAS,IAAI,CAAC,UAAU,EAAE;QAAE,OAAO,SAAS,CAAA;IAE9D,mDAAmD;IACnD,MAAM,IAAI,GAAG,YAAY,EAAE,IAAI,GAAG,EAAE,CAAA;IAEpC,oFAAoF;IACpF,gEAAgE;IAChE,MAAM,SAAS,GAAG,SAAS,CAAC,KAAK,EAAE,CAAC,QAAQ,CAAC,EAAE,EAAC,GAAG,EAAE,IAAI,EAAC,CAAC,CAAC,MAAM,CAAC,IAAI,EAAE,CAAA;IAEzE,6GAA6G;IAC7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KAChD;IACD,MAAM,MAAM,GAAG,MAAM,kBAAkB,CAAC;QACtC,OAAO,EAAE,gGAAgG;QACzG,OAAO,EAAE;YACP,EAAC,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAC;YAC5B,EAAC,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,2BAA2B,EAAC;SAClD;KACF,CAAC,CAAA;IAEF,OAAO,EAAC,OAAO,EAAE,MAAM,KAAK,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAC,CAAA;AAC7D,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,+BAA+B,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI;IACjE,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC;QAAE,OAAO,SAAS,CAAA;IAEnD,mDAAmD;IACnD,MAAM,WAAW,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;IACjC,IAAI,WAAW,CAAC,QAAQ,CAAC,MAAM,CAAC;QAAE,OAAO,MAAM,CAAA;IAC/C,IAAI,WAAW,CAAC,QAAQ,CAAC,MAAM,CAAC;QAAE,OAAO,MAAM,CAAA;IAC/C,IAAI,WAAW,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAA;IAC7C,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["import {isUnitTest} from './context/local.js'\nimport {PackageManager} from './node-package-manager.js'\nimport {outputInfo} from './output.js'\nimport {cwd, sniffForPath} from './path.js'\nimport {captureOutput, exec, terminalSupportsPrompting} from './system.js'\nimport {renderSelectPrompt} from './ui.js'\nimport {execaSync} from 'execa'\n\nlet _isGlobal: boolean | undefined\n\n/**\n * Returns true if the current process is running in a global context.\n *\n * @param argv - The arguments passed to the process.\n * @returns `true` if the current process is running in a global context.\n */\nexport function currentProcessIsGlobal(argv = process.argv): boolean {\n // If we are running tests, we need to disable the cache\n if (_isGlobal !== undefined && !isUnitTest()) return _isGlobal\n\n // Path where the current project is (app/hydrogen)\n const path = sniffForPath() ?? cwd()\n\n // Closest parent directory to contain a package.json file or node_modules directory\n // https://docs.npmjs.com/cli/v8/commands/npm-prefix#description\n const npmPrefix = execaSync('npm', ['prefix'], {cwd: path}).stdout.trim()\n\n // From node docs: \"The second element [of the array] will be the path to the JavaScript file being executed\"\n const binDir = argv[1] ?? ''\n\n // If binDir starts with npmPrefix, then we are running a local CLI\n const isLocal = binDir.startsWith(npmPrefix.trim())\n\n _isGlobal = !isLocal\n return _isGlobal\n}\n\n/**\n * Returns true if the global CLI is installed.\n *\n * @returns `true` if the global CLI is installed.\n */\nexport async function isGlobalCLIInstalled(): Promise<boolean> {\n try {\n const output = await captureOutput('shopify', ['app'])\n // Installed if `app dev` is available globally\n return output.includes('app dev')\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch {\n return false\n }\n}\n\n/**\n * Installs the global Shopify CLI, using the provided package manager.\n *\n * @param packageManager - The package manager to use.\n */\nexport async function installGlobalShopifyCLI(packageManager: PackageManager): Promise<void> {\n const args =\n packageManager === 'yarn' ? ['global', 'add', '@shopify/cli@latest'] : ['install', '-g', '@shopify/cli@latest']\n outputInfo(`Running ${packageManager} ${args.join(' ')}...`)\n await exec(packageManager, args, {stdio: 'inherit'})\n}\n\nexport interface InstallGlobalCLIPromptResult {\n install: boolean\n alreadyInstalled: boolean\n}\n/**\n * Prompts the user to install the global CLI.\n *\n * @returns `true` if the user has installed the global CLI.\n */\nexport async function installGlobalCLIPrompt(): Promise<InstallGlobalCLIPromptResult> {\n if (!terminalSupportsPrompting()) return {install: false, alreadyInstalled: false}\n if (await isGlobalCLIInstalled()) {\n return {install: false, alreadyInstalled: true}\n }\n const result = await renderSelectPrompt({\n message: 'We recommend installing Shopify CLI globally in your system. Would you like to install it now?',\n choices: [\n {value: 'yes', label: 'Yes'},\n {value: 'no', label: 'No, just for this project'},\n ],\n })\n\n return {install: result === 'yes', alreadyInstalled: false}\n}\n\n/**\n * Infers the package manager used by the global CLI.\n *\n * @param argv - The arguments passed to the process.\n * @returns The package manager used by the global CLI.\n */\nexport function inferPackageManagerForGlobalCLI(argv = process.argv): PackageManager {\n if (!currentProcessIsGlobal(argv)) return 'unknown'\n\n // argv[1] contains the path of the executed binary\n const processArgv = argv[1] ?? ''\n if (processArgv.includes('yarn')) return 'yarn'\n if (processArgv.includes('pnpm')) return 'pnpm'\n if (processArgv.includes('bun')) return 'bun'\n return 'npm'\n}\n"]}
@@ -19,7 +19,10 @@ interface EnsureAuthenticatedAdditionalOptions {
19
19
  * @param options - Optional extra options to use.
20
20
  * @returns The access token for the Partners API.
21
21
  */
22
- export declare function ensureAuthenticatedPartners(scopes?: string[], env?: NodeJS.ProcessEnv, options?: EnsureAuthenticatedAdditionalOptions): Promise<string>;
22
+ export declare function ensureAuthenticatedPartners(scopes?: string[], env?: NodeJS.ProcessEnv, options?: EnsureAuthenticatedAdditionalOptions): Promise<{
23
+ token: string;
24
+ userId: string;
25
+ }>;
23
26
  /**
24
27
  * Ensure that we have a valid session to access the App Management API.
25
28
  *
@@ -28,7 +31,10 @@ export declare function ensureAuthenticatedPartners(scopes?: string[], env?: Nod
28
31
  * @param options - Optional extra options to use.
29
32
  * @returns The access token for the App Management API.
30
33
  */
31
- export declare function ensureAuthenticatedAppManagement(scopes?: string[], env?: NodeJS.ProcessEnv, options?: EnsureAuthenticatedAdditionalOptions): Promise<string>;
34
+ export declare function ensureAuthenticatedAppManagement(scopes?: string[], env?: NodeJS.ProcessEnv, options?: EnsureAuthenticatedAdditionalOptions): Promise<{
35
+ token: string;
36
+ userId: string;
37
+ }>;
32
38
  /**
33
39
  * Ensure that we have a valid session to access the Storefront API.
34
40
  *
@@ -1,6 +1,7 @@
1
1
  import { normalizeStoreFqdn } from './context/fqdn.js';
2
2
  import { BugError } from './error.js';
3
3
  import { getPartnersToken } from './environment.js';
4
+ import { nonRandomUUID } from './crypto.js';
4
5
  import * as secureStore from '../../private/node/session/store.js';
5
6
  import { exchangeCustomPartnerToken } from '../../private/node/session/exchange.js';
6
7
  import { outputContent, outputToken, outputDebug } from '../../public/node/output.js';
@@ -21,13 +22,13 @@ ${outputToken.json(scopes)}
21
22
  `);
22
23
  const envToken = getPartnersToken();
23
24
  if (envToken) {
24
- return (await exchangeCustomPartnerToken(envToken)).accessToken;
25
+ return { token: (await exchangeCustomPartnerToken(envToken)).accessToken, userId: nonRandomUUID(envToken) };
25
26
  }
26
27
  const tokens = await ensureAuthenticated({ partnersApi: { scopes } }, env, options);
27
28
  if (!tokens.partners) {
28
29
  throw new BugError('No partners token found after ensuring authenticated');
29
30
  }
30
- return tokens.partners;
31
+ return { token: tokens.partners, userId: tokens.userId };
31
32
  }
32
33
  /**
33
34
  * Ensure that we have a valid session to access the App Management API.
@@ -45,7 +46,7 @@ ${outputToken.json(scopes)}
45
46
  if (!tokens) {
46
47
  throw new BugError('No App Management token found after ensuring authenticated');
47
48
  }
48
- return tokens.appManagement;
49
+ return { token: tokens.appManagement, userId: tokens.userId };
49
50
  }
50
51
  /**
51
52
  * Ensure that we have a valid session to access the Storefront API.
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/public/node/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,kBAAkB,EAAC,MAAM,mBAAmB,CAAA;AACpD,OAAO,EAAC,QAAQ,EAAC,MAAM,YAAY,CAAA;AACnC,OAAO,EAAC,gBAAgB,EAAC,MAAM,kBAAkB,CAAA;AACjD,OAAO,KAAK,WAAW,MAAM,qCAAqC,CAAA;AAClE,OAAO,EAAC,0BAA0B,EAAC,MAAM,wCAAwC,CAAA;AACjF,OAAO,EAAC,aAAa,EAAE,WAAW,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AACnF,OAAO,EAAC,mBAAmB,EAAC,MAAM,+BAA+B,CAAA;AAcjE;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,SAAmB,EAAE,EACrB,GAAG,GAAG,OAAO,CAAC,GAAG,EACjB,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B,CAAC,KAAK,CAAC,EAAC,CAAA;IAClF,OAAO,wBAAwB,CAAC,KAAK,EAAE,MAAM,EAAE,YAAY,CAAC,CAAA;AAC9D,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,SAAmB,EAAE;IAC7E,WAAW,CAAC,aAAa,CAAA;EACzB,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC;CACzB,CAAC,CAAA;IACA,MAAM,MAAM,GAAG,MAAM,mBAAmB,CAAC,EAAC,mBAAmB,EAAE,EAAC,MAAM,EAAC,EAAC,EAAE,OAAO,CAAC,GAAG,CAAC,CAAA;IACtF,IAAI,CAAC,MAAM,CAAC,gBAAgB,EAAE;QAC5B,MAAM,IAAI,QAAQ,CAAC,+DAA+D,CAAC,CAAA;KACpF;IACD,OAAO,MAAM,CAAC,gBAAgB,CAAA;AAChC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,MAAM;IACpB,OAAO,WAAW,CAAC,MAAM,EAAE,CAAA;AAC7B,CAAC","sourcesContent":["import {normalizeStoreFqdn} from './context/fqdn.js'\nimport {BugError} from './error.js'\nimport {getPartnersToken} from './environment.js'\nimport * as secureStore from '../../private/node/session/store.js'\nimport {exchangeCustomPartnerToken} from '../../private/node/session/exchange.js'\nimport {outputContent, outputToken, outputDebug} from '../../public/node/output.js'\nimport {ensureAuthenticated} from '../../private/node/session.js'\n\n/**\n * Session Object to access the Admin API, includes the token and the store FQDN.\n */\nexport interface AdminSession {\n token: string\n storeFqdn: string\n}\n\ninterface EnsureAuthenticatedAdditionalOptions {\n noPrompt?: boolean\n}\n\n/**\n * Ensure that we have a valid session to access the Partners API.\n * If SHOPIFY_CLI_PARTNERS_TOKEN exists, that token will be used to obtain a valid Partners Token\n * If SHOPIFY_CLI_PARTNERS_TOKEN exists, scopes will be ignored.\n *\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param env - Optional environment variables to use.\n * @param options - Optional extra options to use.\n * @returns The access token for the Partners API.\n */\nexport async function ensureAuthenticatedPartners(\n scopes: string[] = [],\n env = process.env,\n options: EnsureAuthenticatedAdditionalOptions = {},\n): Promise<string> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the Partners API with the following scopes:\n${outputToken.json(scopes)}\n`)\n const envToken = getPartnersToken()\n if (envToken) {\n return (await exchangeCustomPartnerToken(envToken)).accessToken\n }\n const tokens = await ensureAuthenticated({partnersApi: {scopes}}, env, options)\n if (!tokens.partners) {\n throw new BugError('No partners token found after ensuring authenticated')\n }\n return tokens.partners\n}\n\n/**\n * Ensure that we have a valid session to access the App Management API.\n *\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param env - Optional environment variables to use.\n * @param options - Optional extra options to use.\n * @returns The access token for the App Management API.\n */\nexport async function ensureAuthenticatedAppManagement(\n scopes: string[] = [],\n env = process.env,\n options: EnsureAuthenticatedAdditionalOptions = {},\n): Promise<string> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the App Management API with the following scopes:\n${outputToken.json(scopes)}\n`)\n const tokens = await ensureAuthenticated({appManagementApi: {scopes}}, env, options)\n if (!tokens) {\n throw new BugError('No App Management token found after ensuring authenticated')\n }\n return tokens.appManagement!\n}\n\n/**\n * Ensure that we have a valid session to access the Storefront API.\n *\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param password - Optional password to use.\n * @param forceRefresh - Optional flag to force a refresh of the token.\n * @returns The access token for the Storefront API.\n */\nexport async function ensureAuthenticatedStorefront(\n scopes: string[] = [],\n password: string | undefined = undefined,\n forceRefresh = false,\n): Promise<string> {\n if (password) return password\n\n outputDebug(outputContent`Ensuring that the user is authenticated with the Storefront API with the following scopes:\n${outputToken.json(scopes)}\n`)\n const tokens = await ensureAuthenticated({storefrontRendererApi: {scopes}}, process.env, {forceRefresh})\n if (!tokens.storefront) {\n throw new BugError('No storefront token found after ensuring authenticated')\n }\n return tokens.storefront\n}\n\n/**\n * Ensure that we have a valid Admin session for the given store.\n *\n * @param store - Store fqdn to request auth for.\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param forceRefresh - Optional flag to force a refresh of the token.\n * @param options - Optional extra options to use.\n * @returns The access token for the Admin API.\n */\nexport async function ensureAuthenticatedAdmin(\n store: string,\n scopes: string[] = [],\n forceRefresh = false,\n options: EnsureAuthenticatedAdditionalOptions = {},\n): Promise<AdminSession> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the Admin API with the following scopes for the store ${outputToken.raw(\n store,\n )}:\n${outputToken.json(scopes)}\n`)\n const tokens = await ensureAuthenticated({adminApi: {scopes, storeFqdn: store}}, process.env, {\n forceRefresh,\n ...options,\n })\n if (!tokens.admin) {\n throw new BugError('No admin token found after ensuring authenticated')\n }\n return tokens.admin\n}\n\n/**\n * Ensure that we have a valid session to access the Theme API.\n * If a password is provided, that token will be used against Theme Access API.\n * Otherwise, it will ensure that the user is authenticated with the Admin API.\n *\n * @param store - Store fqdn to request auth for.\n * @param password - Password generated from Theme Access app.\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param forceRefresh - Optional flag to force a refresh of the token.\n * @returns The access token and store.\n */\nexport async function ensureAuthenticatedThemes(\n store: string,\n password: string | undefined,\n scopes: string[] = [],\n forceRefresh = false,\n): Promise<AdminSession> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the Theme API with the following scopes:\n${outputToken.json(scopes)}\n`)\n if (password) return {token: password, storeFqdn: await normalizeStoreFqdn(store)}\n return ensureAuthenticatedAdmin(store, scopes, forceRefresh)\n}\n\n/**\n * Ensure that we have a valid session to access the Business Platform API.\n *\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @returns The access token for the Business Platform API.\n */\nexport async function ensureAuthenticatedBusinessPlatform(scopes: string[] = []): Promise<string> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the Business Platform API with the following scopes:\n${outputToken.json(scopes)}\n`)\n const tokens = await ensureAuthenticated({businessPlatformApi: {scopes}}, process.env)\n if (!tokens.businessPlatform) {\n throw new BugError('No business-platform token found after ensuring authenticated')\n }\n return tokens.businessPlatform\n}\n\n/**\n * Logout from Shopify.\n *\n * @returns A promise that resolves when the logout is complete.\n */\nexport function logout(): Promise<void> {\n return secureStore.remove()\n}\n"]}
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/public/node/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,kBAAkB,EAAC,MAAM,mBAAmB,CAAA;AACpD,OAAO,EAAC,QAAQ,EAAC,MAAM,YAAY,CAAA;AACnC,OAAO,EAAC,gBAAgB,EAAC,MAAM,kBAAkB,CAAA;AACjD,OAAO,EAAC,aAAa,EAAC,MAAM,aAAa,CAAA;AACzC,OAAO,KAAK,WAAW,MAAM,qCAAqC,CAAA;AAClE,OAAO,EAAC,0BAA0B,EAAC,MAAM,wCAAwC,CAAA;AACjF,OAAO,EAAC,aAAa,EAAE,WAAW,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AACnF,OAAO,EAAC,mBAAmB,EAAC,MAAM,+BAA+B,CAAA;AAcjE;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,SAAmB,EAAE,EACrB,GAAG,GAAG,OAAO,CAAC,GAAG,EACjB,UAAgD,EAAE;IAElD,WAAW,CAAC,aAAa,CAAA;EACzB,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC;CACzB,CAAC,CAAA;IACA,MAAM,QAAQ,GAAG,gBAAgB,EAAE,CAAA;IACnC,IAAI,QAAQ,EAAE;QACZ,OAAO,EAAC,KAAK,EAAE,CAAC,MAAM,0BAA0B,CAAC,QAAQ,CAAC,CAAC,CAAC,WAAW,EAAE,MAAM,EAAE,aAAa,CAAC,QAAQ,CAAC,EAAC,CAAA;KAC1G;IACD,MAAM,MAAM,GAAG,MAAM,mBAAmB,CAAC,EAAC,WAAW,EAAE,EAAC,MAAM,EAAC,EAAC,EAAE,GAAG,EAAE,OAAO,CAAC,CAAA;IAC/E,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE;QACpB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,mBAAmB,CAAC,EAAC,mBAAmB,EAAE,EAAC,MAAM,EAAC,EAAC,EAAE,OAAO,CAAC,GAAG,CAAC,CAAA;IACtF,IAAI,CAAC,MAAM,CAAC,gBAAgB,EAAE;QAC5B,MAAM,IAAI,QAAQ,CAAC,+DAA+D,CAAC,CAAA;KACpF;IACD,OAAO,MAAM,CAAC,gBAAgB,CAAA;AAChC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,MAAM;IACpB,OAAO,WAAW,CAAC,MAAM,EAAE,CAAA;AAC7B,CAAC","sourcesContent":["import {normalizeStoreFqdn} from './context/fqdn.js'\nimport {BugError} from './error.js'\nimport {getPartnersToken} from './environment.js'\nimport {nonRandomUUID} from './crypto.js'\nimport * as secureStore from '../../private/node/session/store.js'\nimport {exchangeCustomPartnerToken} from '../../private/node/session/exchange.js'\nimport {outputContent, outputToken, outputDebug} from '../../public/node/output.js'\nimport {ensureAuthenticated} from '../../private/node/session.js'\n\n/**\n * Session Object to access the Admin API, includes the token and the store FQDN.\n */\nexport interface AdminSession {\n token: string\n storeFqdn: string\n}\n\ninterface EnsureAuthenticatedAdditionalOptions {\n noPrompt?: boolean\n}\n\n/**\n * Ensure that we have a valid session to access the Partners API.\n * If SHOPIFY_CLI_PARTNERS_TOKEN exists, that token will be used to obtain a valid Partners Token\n * If SHOPIFY_CLI_PARTNERS_TOKEN exists, scopes will be ignored.\n *\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param env - Optional environment variables to use.\n * @param options - Optional extra options to use.\n * @returns The access token for the Partners API.\n */\nexport async function ensureAuthenticatedPartners(\n scopes: string[] = [],\n env = process.env,\n options: EnsureAuthenticatedAdditionalOptions = {},\n): Promise<{token: string; userId: string}> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the Partners API with the following scopes:\n${outputToken.json(scopes)}\n`)\n const envToken = getPartnersToken()\n if (envToken) {\n return {token: (await exchangeCustomPartnerToken(envToken)).accessToken, userId: nonRandomUUID(envToken)}\n }\n const tokens = await ensureAuthenticated({partnersApi: {scopes}}, env, options)\n if (!tokens.partners) {\n throw new BugError('No partners token found after ensuring authenticated')\n }\n return {token: tokens.partners, userId: tokens.userId}\n}\n\n/**\n * Ensure that we have a valid session to access the App Management API.\n *\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param env - Optional environment variables to use.\n * @param options - Optional extra options to use.\n * @returns The access token for the App Management API.\n */\nexport async function ensureAuthenticatedAppManagement(\n scopes: string[] = [],\n env = process.env,\n options: EnsureAuthenticatedAdditionalOptions = {},\n): Promise<{token: string; userId: string}> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the App Management API with the following scopes:\n${outputToken.json(scopes)}\n`)\n const tokens = await ensureAuthenticated({appManagementApi: {scopes}}, env, options)\n if (!tokens) {\n throw new BugError('No App Management token found after ensuring authenticated')\n }\n return {token: tokens.appManagement!, userId: tokens.userId}\n}\n\n/**\n * Ensure that we have a valid session to access the Storefront API.\n *\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param password - Optional password to use.\n * @param forceRefresh - Optional flag to force a refresh of the token.\n * @returns The access token for the Storefront API.\n */\nexport async function ensureAuthenticatedStorefront(\n scopes: string[] = [],\n password: string | undefined = undefined,\n forceRefresh = false,\n): Promise<string> {\n if (password) return password\n\n outputDebug(outputContent`Ensuring that the user is authenticated with the Storefront API with the following scopes:\n${outputToken.json(scopes)}\n`)\n const tokens = await ensureAuthenticated({storefrontRendererApi: {scopes}}, process.env, {forceRefresh})\n if (!tokens.storefront) {\n throw new BugError('No storefront token found after ensuring authenticated')\n }\n return tokens.storefront\n}\n\n/**\n * Ensure that we have a valid Admin session for the given store.\n *\n * @param store - Store fqdn to request auth for.\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param forceRefresh - Optional flag to force a refresh of the token.\n * @param options - Optional extra options to use.\n * @returns The access token for the Admin API.\n */\nexport async function ensureAuthenticatedAdmin(\n store: string,\n scopes: string[] = [],\n forceRefresh = false,\n options: EnsureAuthenticatedAdditionalOptions = {},\n): Promise<AdminSession> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the Admin API with the following scopes for the store ${outputToken.raw(\n store,\n )}:\n${outputToken.json(scopes)}\n`)\n const tokens = await ensureAuthenticated({adminApi: {scopes, storeFqdn: store}}, process.env, {\n forceRefresh,\n ...options,\n })\n if (!tokens.admin) {\n throw new BugError('No admin token found after ensuring authenticated')\n }\n return tokens.admin\n}\n\n/**\n * Ensure that we have a valid session to access the Theme API.\n * If a password is provided, that token will be used against Theme Access API.\n * Otherwise, it will ensure that the user is authenticated with the Admin API.\n *\n * @param store - Store fqdn to request auth for.\n * @param password - Password generated from Theme Access app.\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param forceRefresh - Optional flag to force a refresh of the token.\n * @returns The access token and store.\n */\nexport async function ensureAuthenticatedThemes(\n store: string,\n password: string | undefined,\n scopes: string[] = [],\n forceRefresh = false,\n): Promise<AdminSession> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the Theme API with the following scopes:\n${outputToken.json(scopes)}\n`)\n if (password) return {token: password, storeFqdn: await normalizeStoreFqdn(store)}\n return ensureAuthenticatedAdmin(store, scopes, forceRefresh)\n}\n\n/**\n * Ensure that we have a valid session to access the Business Platform API.\n *\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @returns The access token for the Business Platform API.\n */\nexport async function ensureAuthenticatedBusinessPlatform(scopes: string[] = []): Promise<string> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the Business Platform API with the following scopes:\n${outputToken.json(scopes)}\n`)\n const tokens = await ensureAuthenticated({businessPlatformApi: {scopes}}, process.env)\n if (!tokens.businessPlatform) {\n throw new BugError('No business-platform token found after ensuring authenticated')\n }\n return tokens.businessPlatform\n}\n\n/**\n * Logout from Shopify.\n *\n * @returns A promise that resolves when the logout is complete.\n */\nexport function logout(): Promise<void> {\n return secureStore.remove()\n}\n"]}
@@ -1,8 +1,5 @@
1
1
  /// <reference types="node" resolution-mode="require"/>
2
- /// <reference types="node" resolution-mode="require"/>
3
- /// <reference types="node" resolution-mode="require"/>
4
2
  import { AbortSignal } from './abort.js';
5
- import { ReadStream } from 'tty';
6
3
  import type { Writable, Readable } from 'stream';
7
4
  export interface ExecOptions {
8
5
  cwd?: string;
@@ -48,11 +45,8 @@ export declare function exec(command: string, args: string[], options?: ExecOpti
48
45
  */
49
46
  export declare function sleep(seconds: number): Promise<void>;
50
47
  /**
51
- * In case an standard input stream is passed check if it supports raw mode. Otherwise default standard input stream
52
- * will be used.
48
+ * Check if the standard input and output streams support prompting.
53
49
  *
54
- * @param stdin - The standard input stream to check.
55
- * @param env - Environmemnt variables.
56
- * @returns True in the selected input stream support raw mode.
50
+ * @returns True if the standard input and output streams support prompting.
57
51
  */
58
- export declare function terminalSupportsRawMode(stdin?: ReadStream, env?: NodeJS.ProcessEnv): boolean;
52
+ export declare function terminalSupportsPrompting(): boolean;
@@ -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
  *
@@ -112,19 +124,14 @@ export async function sleep(seconds) {
112
124
  });
113
125
  }
114
126
  /**
115
- * In case an standard input stream is passed check if it supports raw mode. Otherwise default standard input stream
116
- * will be used.
127
+ * Check if the standard input and output streams support prompting.
117
128
  *
118
- * @param stdin - The standard input stream to check.
119
- * @param env - Environmemnt variables.
120
- * @returns True in the selected input stream support raw mode.
129
+ * @returns True if the standard input and output streams support prompting.
121
130
  */
122
- export function terminalSupportsRawMode(stdin, env = process.env) {
123
- if (isTruthy(env.CI)) {
131
+ export function terminalSupportsPrompting() {
132
+ if (isTruthy(process.env.CI)) {
124
133
  return false;
125
134
  }
126
- if (stdin)
127
- return Boolean(stdin.isTTY);
128
- return process.stdin.isTTY;
135
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
129
136
  }
130
137
  //# sourceMappingURL=system.js.map