@shopify/cli-kit 3.50.2 → 3.51.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/assets/cli-ruby/lib/shopify_cli/constants.rb +3 -2
- package/assets/cli-ruby/lib/shopify_cli/theme/extension/dev_server/local_assets.rb +2 -2
- package/assets/cli-ruby/lib/shopify_cli/theme/repl/remote_evaluator.rb +7 -2
- package/dist/private/node/session.d.ts +4 -1
- package/dist/private/node/session.js +6 -1
- package/dist/private/node/session.js.map +1 -1
- package/dist/public/common/string.d.ts +8 -0
- package/dist/public/common/string.js +11 -1
- package/dist/public/common/string.js.map +1 -1
- package/dist/public/common/version.d.ts +1 -1
- package/dist/public/common/version.js +1 -1
- package/dist/public/common/version.js.map +1 -1
- package/dist/public/node/analytics.js +11 -3
- package/dist/public/node/analytics.js.map +1 -1
- package/dist/public/node/base-command.js +1 -1
- package/dist/public/node/base-command.js.map +1 -1
- package/dist/public/node/cli.js +9 -6
- package/dist/public/node/cli.js.map +1 -1
- package/dist/public/node/error-handler.d.ts +0 -4
- package/dist/public/node/error-handler.js +1 -1
- package/dist/public/node/error-handler.js.map +1 -1
- package/dist/public/node/error.d.ts +1 -0
- package/dist/public/node/error.js +1 -0
- package/dist/public/node/error.js.map +1 -1
- package/dist/public/node/git.js +46 -43
- package/dist/public/node/git.js.map +1 -1
- package/dist/public/node/metadata.js +32 -28
- package/dist/public/node/metadata.js.map +1 -1
- package/dist/public/node/node-package-manager.d.ts +4 -2
- package/dist/public/node/node-package-manager.js +44 -8
- package/dist/public/node/node-package-manager.js.map +1 -1
- package/dist/public/node/output.js +1 -0
- package/dist/public/node/output.js.map +1 -1
- package/dist/public/node/ruby.d.ts +0 -1
- package/dist/public/node/ruby.js +12 -9
- package/dist/public/node/ruby.js.map +1 -1
- package/dist/public/node/session.d.ts +7 -2
- package/dist/public/node/session.js +6 -5
- package/dist/public/node/session.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -27,6 +27,7 @@ Initialize your project using one of the following commands:
|
|
|
27
27
|
- `npm init @shopify/app@latest` (installed by default with Node)
|
|
28
28
|
- `pnpm create @shopify/create-app@latest`
|
|
29
29
|
- `yarn create @shopify/app`
|
|
30
|
+
- `bun create @shopify/app@latest` (experimental)
|
|
30
31
|
|
|
31
32
|
Learn more in the docs: [Create an app](https://shopify.dev/apps/getting-started/create)
|
|
32
33
|
|
|
@@ -58,7 +58,8 @@ module ShopifyCLI
|
|
|
58
58
|
# Authentication
|
|
59
59
|
AUTH_TOKEN = "SHOPIFY_CLI_AUTH_TOKEN"
|
|
60
60
|
ADMIN_AUTH_TOKEN = "SHOPIFY_CLI_ADMIN_AUTH_TOKEN"
|
|
61
|
-
STOREFRONT_RENDERER_AUTH_TOKEN =
|
|
61
|
+
STOREFRONT_RENDERER_AUTH_TOKEN =
|
|
62
|
+
"SHOPIFY_CLI_STOREFRONT_RENDERER_AUTH_TOKEN"
|
|
62
63
|
|
|
63
64
|
# Monorail
|
|
64
65
|
MONORAIL_REAL_EVENTS = "MONORAIL_REAL_EVENTS"
|
|
@@ -88,7 +89,7 @@ module ShopifyCLI
|
|
|
88
89
|
end
|
|
89
90
|
|
|
90
91
|
module Extension
|
|
91
|
-
DEFAULT_PORT =
|
|
92
|
+
DEFAULT_PORT = 39_351
|
|
92
93
|
end
|
|
93
94
|
end
|
|
94
95
|
end
|
|
@@ -8,13 +8,13 @@ module ShopifyCLI
|
|
|
8
8
|
class DevServer < ShopifyCLI::Theme::DevServer
|
|
9
9
|
class LocalAssets < ShopifyCLI::Theme::DevServer::LocalAssets
|
|
10
10
|
SUPPORTED_EXTENSIONS = [:js, :css].join("|")
|
|
11
|
-
TAE_ASSET_REGEX = %r{(http:|https:)?//cdn
|
|
11
|
+
TAE_ASSET_REGEX = %r{(http:|https:)?//cdn\..*?(shopify\.com|spin\.dev)(/[^/]+)*?/extensions/.+?/(assets/.+?\.(?:#{SUPPORTED_EXTENSIONS}))}
|
|
12
12
|
|
|
13
13
|
private
|
|
14
14
|
|
|
15
15
|
def replace_asset_urls(body)
|
|
16
16
|
replaced_body = body.join.gsub(TAE_ASSET_REGEX) do |match|
|
|
17
|
-
path = Regexp.last_match[
|
|
17
|
+
path = Regexp.last_match[4]
|
|
18
18
|
if @target.static_asset_paths.include?(path)
|
|
19
19
|
"/#{path}"
|
|
20
20
|
else
|
|
@@ -72,9 +72,14 @@ module ShopifyCLI
|
|
|
72
72
|
|
|
73
73
|
error = body.gsub(/ \(snippets\/eval line \d+\)/, "")
|
|
74
74
|
|
|
75
|
-
|
|
75
|
+
print_syntax_error(error)
|
|
76
|
+
end
|
|
76
77
|
|
|
77
|
-
|
|
78
|
+
def print_syntax_error(error)
|
|
79
|
+
error_message = "Unknown object, property, tag, or filter: '#{input}'"
|
|
80
|
+
error_message = error unless error.include?("Unknown tag")
|
|
81
|
+
|
|
82
|
+
ctx.puts("{{red:#{error_message}}}")
|
|
78
83
|
end
|
|
79
84
|
|
|
80
85
|
def json_from_response(response)
|
|
@@ -59,5 +59,8 @@ export interface OAuthSession {
|
|
|
59
59
|
* @param forceRefresh - Optional flag to force a refresh of the token.
|
|
60
60
|
* @returns An instance with the access tokens organized by application.
|
|
61
61
|
*/
|
|
62
|
-
export declare function ensureAuthenticated(applications: OAuthApplications, _env?: NodeJS.ProcessEnv, forceRefresh?:
|
|
62
|
+
export declare function ensureAuthenticated(applications: OAuthApplications, _env?: NodeJS.ProcessEnv, { forceRefresh, noPrompt }?: {
|
|
63
|
+
forceRefresh?: boolean;
|
|
64
|
+
noPrompt?: boolean;
|
|
65
|
+
}): Promise<OAuthSession>;
|
|
63
66
|
export {};
|
|
@@ -24,7 +24,7 @@ import { outputCompleted, outputInfo, outputWarn } from '@shopify/cli-kit/node/o
|
|
|
24
24
|
* @param forceRefresh - Optional flag to force a refresh of the token.
|
|
25
25
|
* @returns An instance with the access tokens organized by application.
|
|
26
26
|
*/
|
|
27
|
-
export async function ensureAuthenticated(applications, _env, forceRefresh = false) {
|
|
27
|
+
export async function ensureAuthenticated(applications, _env, { forceRefresh = false, noPrompt = false } = {}) {
|
|
28
28
|
const fqdn = await identityFqdn();
|
|
29
29
|
const previousStoreFqdn = applications.adminApi?.storeFqdn;
|
|
30
30
|
if (previousStoreFqdn) {
|
|
@@ -44,6 +44,11 @@ ${outputToken.json(applications)}
|
|
|
44
44
|
const validationResult = await validateSession(scopes, applications, fqdnSession);
|
|
45
45
|
let newSession = {};
|
|
46
46
|
if (validationResult === 'needs_full_auth') {
|
|
47
|
+
if (noPrompt) {
|
|
48
|
+
throw new AbortError(`The currently available CLI credentials are invalid.
|
|
49
|
+
|
|
50
|
+
The CLI is currently unable to prompt for reauthentication.`, 'Restart the CLI process you were running. If in an interactive terminal, you will be prompted to reauthenticate. If in a non-interactive terminal, ensure the correct credentials are available in the program environment.');
|
|
51
|
+
}
|
|
47
52
|
outputDebug(outputContent `Initiating the full authentication flow...`);
|
|
48
53
|
newSession = await executeCompleteFlow(applications, fqdn);
|
|
49
54
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/private/node/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,aAAa,EAAC,MAAM,uBAAuB,CAAA;AACnD,OAAO,EAAC,eAAe,EAAC,MAAM,uBAAuB,CAAA;AACrD,OAAO,EAAC,gBAAgB,EAAE,SAAS,EAAC,MAAM,qBAAqB,CAAA;AAC/D,OAAO,EACL,kCAAkC,EAClC,0BAA0B,EAC1B,0BAA0B,EAE1B,kBAAkB,EAClB,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAC,SAAS,EAAC,MAAM,wBAAwB,CAAA;AAEhD,OAAO,KAAK,WAAW,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAAC,0BAA0B,EAAE,0BAA0B,EAAC,MAAM,mCAAmC,CAAA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H,CAAC","sourcesContent":["import {applicationId} from './session/identity.js'\nimport {validateSession} from './session/validate.js'\nimport {allDefaultScopes, apiScopes} from './session/scopes.js'\nimport {\n exchangeAccessForApplicationTokens,\n exchangeCodeForAccessToken,\n exchangeCustomPartnerToken,\n ExchangeScopes,\n refreshAccessToken,\n InvalidGrantError,\n InvalidRequestError,\n} from './session/exchange.js'\nimport {authorize} from './session/authorize.js'\nimport {IdentityToken, Session} from './session/schema.js'\nimport * as secureStore from './session/store.js'\nimport {pollForDeviceAuthorization, requestDeviceAuthorization} from './session/device-authorization.js'\nimport {RequestClientError} from './api/headers.js'\nimport {outputContent, outputToken, outputDebug} from '../../public/node/output.js'\nimport {firstPartyDev, useDeviceAuth} from '../../public/node/context/local.js'\nimport {AbortError, BugError} from '../../public/node/error.js'\nimport {partnersRequest} from '../../public/node/api/partners.js'\nimport {normalizeStoreFqdn, partnersFqdn, identityFqdn} from '../../public/node/context/fqdn.js'\nimport {openURL} from '../../public/node/system.js'\nimport {keypress} from '../../public/node/ui.js'\nimport {getIdentityTokenInformation, getPartnersToken} from '../../public/node/environment.js'\nimport {gql} from 'graphql-request'\nimport {AdminSession} from '@shopify/cli-kit/node/session'\nimport {outputCompleted, outputInfo, outputWarn} from '@shopify/cli-kit/node/output'\n\n/**\n * A scope supported by the Shopify Admin API.\n */\ntype AdminAPIScope = 'graphql' | 'themes' | 'collaborator' | string\n\n/**\n * It represents the options to authenticate against the Shopify Admin API.\n */\n\ninterface AdminAPIOAuthOptions {\n /** Store to request permissions for. */\n storeFqdn: string\n /** List of scopes to request permissions for. */\n scopes: AdminAPIScope[]\n}\n\n/**\n * A scope supported by the Partners API.\n */\ntype PartnersAPIScope = 'cli' | string\ninterface PartnersAPIOAuthOptions {\n /** List of scopes to request permissions for. */\n scopes: PartnersAPIScope[]\n}\n\n/**\n * A scope supported by the Storefront Renderer API.\n */\ntype StorefrontRendererScope = 'devtools' | string\ninterface StorefrontRendererAPIOAuthOptions {\n /** List of scopes to request permissions for. */\n scopes: StorefrontRendererScope[]\n}\n\ntype BusinessPlatformScope = 'destinations' | string\ninterface BusinessPlatformAPIOAuthOptions {\n /** List of scopes to request permissions for. */\n scopes: BusinessPlatformScope[]\n}\n\n/**\n * It represents the authentication requirements and\n * is the input necessary to trigger the authentication\n * flow.\n */\nexport interface OAuthApplications {\n adminApi?: AdminAPIOAuthOptions\n storefrontRendererApi?: StorefrontRendererAPIOAuthOptions\n partnersApi?: PartnersAPIOAuthOptions\n businessPlatformApi?: BusinessPlatformAPIOAuthOptions\n}\n\nexport interface OAuthSession {\n admin?: AdminSession\n partners?: string\n storefront?: string\n businessPlatform?: string\n}\n\n/**\n * This method ensures that we have a valid session to authenticate against the given applications using the provided scopes.\n *\n * @param applications - An object containing the applications we need to be authenticated with.\n * @param _env - Optional environment variables to use.\n * @param forceRefresh - Optional flag to force a refresh of the token.\n * @returns An instance with the access tokens organized by application.\n */\nexport async function ensureAuthenticated(\n applications: OAuthApplications,\n _env?: NodeJS.ProcessEnv,\n forceRefresh = false,\n): Promise<OAuthSession> {\n const fqdn = await identityFqdn()\n\n const previousStoreFqdn = applications.adminApi?.storeFqdn\n if (previousStoreFqdn) {\n const normalizedStoreName = await normalizeStoreFqdn(previousStoreFqdn)\n if (previousStoreFqdn === applications.adminApi?.storeFqdn) {\n applications.adminApi.storeFqdn = normalizedStoreName\n }\n }\n\n const currentSession = (await secureStore.fetch()) || {}\n const fqdnSession = currentSession[fqdn]!\n const scopes = getFlattenScopes(applications)\n\n outputDebug(outputContent`Validating existing session against the scopes:\n${outputToken.json(scopes)}\nFor applications:\n${outputToken.json(applications)}\n`)\n const validationResult = await validateSession(scopes, applications, fqdnSession)\n\n let newSession = {}\n\n if (validationResult === 'needs_full_auth') {\n outputDebug(outputContent`Initiating the full authentication flow...`)\n newSession = await executeCompleteFlow(applications, fqdn)\n } else if (validationResult === 'needs_refresh' || forceRefresh) {\n outputDebug(outputContent`The current session is valid but needs refresh. Refreshing...`)\n try {\n newSession = await refreshTokens(fqdnSession.identity, applications, fqdn)\n } catch (error) {\n if (error instanceof InvalidGrantError) {\n newSession = await executeCompleteFlow(applications, fqdn)\n } else if (error instanceof InvalidRequestError) {\n await secureStore.remove()\n throw new AbortError('\\nError validating auth session', \"We've cleared the current session, please try again\")\n } else {\n throw error\n }\n }\n }\n\n const completeSession: Session = {...currentSession, ...newSession}\n // Save the new session info if it has changed\n if (Object.keys(newSession).length > 0) await secureStore.store(completeSession)\n const tokens = await tokensFor(applications, completeSession, fqdn)\n\n // Overwrite partners token if using a custom CLI Token\n const envToken = getPartnersToken()\n if (envToken && applications.partnersApi) {\n tokens.partners = (await exchangeCustomPartnerToken(envToken)).accessToken\n }\n if (!envToken && tokens.partners) {\n await ensureUserHasPartnerAccount(tokens.partners)\n }\n\n return tokens\n}\n\n/**\n * Execute the full authentication flow.\n *\n * @param applications - An object containing the applications we need to be authenticated with.\n * @param identityFqdn - The identity FQDN.\n */\nasync function executeCompleteFlow(applications: OAuthApplications, identityFqdn: string): Promise<Session> {\n const scopes = getFlattenScopes(applications)\n const exchangeScopes = getExchangeScopes(applications)\n const store = applications.adminApi?.storeFqdn\n if (firstPartyDev()) {\n outputDebug(outputContent`Authenticating as Shopify Employee...`)\n scopes.push('employee')\n }\n\n let identityToken: IdentityToken\n const identityTokenInformation = getIdentityTokenInformation()\n if (identityTokenInformation) {\n identityToken = buildIdentityTokenFromEnv(scopes, identityTokenInformation)\n } else if (useDeviceAuth()) {\n // Request a device code to authorize without a browser redirect.\n outputDebug(outputContent`Requesting device authorization code...`)\n const deviceAuth = await requestDeviceAuthorization(scopes)\n\n // Poll for the identity token\n outputDebug(outputContent`Starting polling for the identity token...`)\n identityToken = await pollForDeviceAuthorization(deviceAuth.deviceCode, deviceAuth.interval)\n } else {\n // Authorize user via browser\n outputDebug(outputContent`Authorizing through Identity's website...`)\n const code = await authorize(scopes)\n\n // Exchange code for identity token\n outputDebug(outputContent`Authorization code received. Exchanging it for a CLI token...`)\n identityToken = await exchangeCodeForAccessToken(code)\n }\n\n // Exchange identity token for application tokens\n outputDebug(outputContent`CLI token received. Exchanging it for application tokens...`)\n const result = await exchangeAccessForApplicationTokens(identityToken, exchangeScopes, store)\n\n const session: Session = {\n [identityFqdn]: {\n identity: identityToken,\n applications: result,\n },\n }\n\n outputCompleted('Logged in.')\n\n return session\n}\n\n/**\n * If the user creates an account from the Identity website, the created\n * account won't get a Partner organization created. We need to detect that\n * and take the user to create a partner organization.\n *\n * @param partnersToken - Partners token.\n */\nasync function ensureUserHasPartnerAccount(partnersToken: string) {\n outputDebug(outputContent`Verifying that the user has a Partner organization`)\n if (!(await hasPartnerAccount(partnersToken))) {\n outputInfo(`\\nA Shopify Partners organization is needed to proceed.`)\n outputInfo(`👉 Press any key to create one`)\n await keypress()\n await openURL(`https://${await partnersFqdn()}/signup`)\n outputInfo(outputContent`👉 Press any key when you have ${outputToken.cyan('created the organization')}`)\n outputWarn(outputContent`Make sure you've confirmed your Shopify and the Partner organization from the email`)\n await keypress()\n if (!(await hasPartnerAccount(partnersToken))) {\n throw new AbortError(\n `Couldn't find your Shopify Partners organization`,\n `Have you confirmed your accounts from the emails you received?`,\n )\n }\n }\n}\n\nconst getFirstOrganization = gql`\n {\n organizations(first: 1) {\n nodes {\n id\n }\n }\n }\n`\n\n/**\n * Validate if the current token is valid for partners API.\n *\n * @param partnersToken - Partners token.\n * @returns A promise that resolves to true if the token is valid for partners API.\n */\nasync function hasPartnerAccount(partnersToken: string): Promise<boolean> {\n try {\n await partnersRequest(getFirstOrganization, partnersToken)\n return true\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n if (error instanceof RequestClientError && error.statusCode === 404) {\n return false\n } else {\n return true\n }\n }\n}\n\n/**\n * Refresh the tokens for a given session.\n *\n * @param token - Identity token.\n * @param applications - An object containing the applications we need to be authenticated with.\n * @param fqdn - The identity FQDN.\n */\nasync function refreshTokens(token: IdentityToken, applications: OAuthApplications, fqdn: string): Promise<Session> {\n // Refresh Identity Token\n const identityToken = await refreshAccessToken(token)\n // Exchange new identity token for application tokens\n const exchangeScopes = getExchangeScopes(applications)\n const applicationTokens = await exchangeAccessForApplicationTokens(\n identityToken,\n exchangeScopes,\n applications.adminApi?.storeFqdn,\n )\n\n return {\n [fqdn]: {\n identity: identityToken,\n applications: applicationTokens,\n },\n }\n}\n\n/**\n * Get the application tokens for a given session.\n *\n * @param applications - An object containing the applications we need the tokens for.\n * @param session - The current session.\n * @param fqdn - The identity FQDN.\n */\nasync function tokensFor(applications: OAuthApplications, session: Session, fqdn: string): Promise<OAuthSession> {\n const fqdnSession = session[fqdn]\n if (!fqdnSession) {\n throw new BugError('No session found after ensuring authenticated')\n }\n const tokens: OAuthSession = {}\n if (applications.adminApi) {\n const appId = applicationId('admin')\n const realAppId = `${applications.adminApi.storeFqdn}-${appId}`\n const token = fqdnSession.applications[realAppId]?.accessToken\n if (token) {\n tokens.admin = {token, storeFqdn: applications.adminApi.storeFqdn}\n }\n }\n\n if (applications.partnersApi) {\n const appId = applicationId('partners')\n tokens.partners = fqdnSession.applications[appId]?.accessToken\n }\n\n if (applications.storefrontRendererApi) {\n const appId = applicationId('storefront-renderer')\n tokens.storefront = fqdnSession.applications[appId]?.accessToken\n }\n\n if (applications.businessPlatformApi) {\n const appId = applicationId('business-platform')\n tokens.businessPlatform = fqdnSession.applications[appId]?.accessToken\n }\n\n return tokens\n}\n\n// Scope Helpers\n/**\n * Get a flattened array of scopes for the given applications.\n *\n * @param apps - An object containing the applications we need the scopes for.\n * @returns A flattened array of scopes.\n */\nfunction getFlattenScopes(apps: OAuthApplications): string[] {\n const admin = apps.adminApi?.scopes || []\n const partner = apps.partnersApi?.scopes || []\n const storefront = apps.storefrontRendererApi?.scopes || []\n const businessPlatform = apps.businessPlatformApi?.scopes || []\n const requestedScopes = [...admin, ...partner, ...storefront, ...businessPlatform]\n return allDefaultScopes(requestedScopes)\n}\n\n/**\n * Get the scopes for the given applications.\n *\n * @param apps - An object containing the applications we need the scopes for.\n * @returns An object containing the scopes for each application.\n */\nfunction getExchangeScopes(apps: OAuthApplications): ExchangeScopes {\n const adminScope = apps.adminApi?.scopes || []\n const partnerScope = apps.partnersApi?.scopes || []\n const storefrontScopes = apps.storefrontRendererApi?.scopes || []\n const businessPlatformScopes = apps.businessPlatformApi?.scopes || []\n return {\n admin: apiScopes('admin', adminScope),\n partners: apiScopes('partners', partnerScope),\n storefront: apiScopes('storefront-renderer', storefrontScopes),\n businessPlatform: apiScopes('business-platform', businessPlatformScopes),\n }\n}\n\nfunction buildIdentityTokenFromEnv(\n scopes: string[],\n identityTokenInformation: {accessToken: string; refreshToken: string},\n) {\n return {\n ...identityTokenInformation,\n expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),\n scopes,\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/private/node/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,aAAa,EAAC,MAAM,uBAAuB,CAAA;AACnD,OAAO,EAAC,eAAe,EAAC,MAAM,uBAAuB,CAAA;AACrD,OAAO,EAAC,gBAAgB,EAAE,SAAS,EAAC,MAAM,qBAAqB,CAAA;AAC/D,OAAO,EACL,kCAAkC,EAClC,0BAA0B,EAC1B,0BAA0B,EAE1B,kBAAkB,EAClB,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAC,SAAS,EAAC,MAAM,wBAAwB,CAAA;AAEhD,OAAO,KAAK,WAAW,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAAC,0BAA0B,EAAE,0BAA0B,EAAC,MAAM,mCAAmC,CAAA;AACxG,OAAO,EAAC,kBAAkB,EAAC,MAAM,kBAAkB,CAAA;AACnD,OAAO,EAAC,aAAa,EAAE,WAAW,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AACnF,OAAO,EAAC,aAAa,EAAE,aAAa,EAAC,MAAM,oCAAoC,CAAA;AAC/E,OAAO,EAAC,UAAU,EAAE,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AAG,IAAI,CAAC,qBAAqB,EAAE,MAAM,IAAI,EAAE,CAAA;IAC3D,MAAM,gBAAgB,GAAG,IAAI,CAAC,mBAAmB,EAAE,MAAM,IAAI,EAAE,CAAA;IAC/D,MAAM,eAAe,GAAG,CAAC,GAAG,KAAK,EAAE,GAAG,OAAO,EAAE,GAAG,UAAU,EAAE,GAAG,gBAAgB,CAAC,CAAA;IAClF,OAAO,gBAAgB,CAAC,eAAe,CAAC,CAAA;AAC1C,CAAC;AAED;;;;;GAKG;AACH,SAAS,iBAAiB,CAAC,IAAuB;IAChD,MAAM,UAAU,GAAG,IAAI,CAAC,QAAQ,EAAE,MAAM,IAAI,EAAE,CAAA;IAC9C,MAAM,YAAY,GAAG,IAAI,CAAC,WAAW,EAAE,MAAM,IAAI,EAAE,CAAA;IACnD,MAAM,gBAAgB,GAAG,IAAI,CAAC,qBAAqB,EAAE,MAAM,IAAI,EAAE,CAAA;IACjE,MAAM,sBAAsB,GAAG,IAAI,CAAC,mBAAmB,EAAE,MAAM,IAAI,EAAE,CAAA;IACrE,OAAO;QACL,KAAK,EAAE,SAAS,CAAC,OAAO,EAAE,UAAU,CAAC;QACrC,QAAQ,EAAE,SAAS,CAAC,UAAU,EAAE,YAAY,CAAC;QAC7C,UAAU,EAAE,SAAS,CAAC,qBAAqB,EAAE,gBAAgB,CAAC;QAC9D,gBAAgB,EAAE,SAAS,CAAC,mBAAmB,EAAE,sBAAsB,CAAC;KACzE,CAAA;AACH,CAAC;AAED,SAAS,yBAAyB,CAChC,MAAgB,EAChB,wBAAqE;IAErE,OAAO;QACL,GAAG,wBAAwB;QAC3B,SAAS,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QAC1D,MAAM;KACP,CAAA;AACH,CAAC","sourcesContent":["import {applicationId} from './session/identity.js'\nimport {validateSession} from './session/validate.js'\nimport {allDefaultScopes, apiScopes} from './session/scopes.js'\nimport {\n exchangeAccessForApplicationTokens,\n exchangeCodeForAccessToken,\n exchangeCustomPartnerToken,\n ExchangeScopes,\n refreshAccessToken,\n InvalidGrantError,\n InvalidRequestError,\n} from './session/exchange.js'\nimport {authorize} from './session/authorize.js'\nimport {IdentityToken, Session} from './session/schema.js'\nimport * as secureStore from './session/store.js'\nimport {pollForDeviceAuthorization, requestDeviceAuthorization} from './session/device-authorization.js'\nimport {RequestClientError} from './api/headers.js'\nimport {outputContent, outputToken, outputDebug} from '../../public/node/output.js'\nimport {firstPartyDev, useDeviceAuth} from '../../public/node/context/local.js'\nimport {AbortError, BugError} from '../../public/node/error.js'\nimport {partnersRequest} from '../../public/node/api/partners.js'\nimport {normalizeStoreFqdn, partnersFqdn, identityFqdn} from '../../public/node/context/fqdn.js'\nimport {openURL} from '../../public/node/system.js'\nimport {keypress} from '../../public/node/ui.js'\nimport {getIdentityTokenInformation, getPartnersToken} from '../../public/node/environment.js'\nimport {gql} from 'graphql-request'\nimport {AdminSession} from '@shopify/cli-kit/node/session'\nimport {outputCompleted, outputInfo, outputWarn} from '@shopify/cli-kit/node/output'\n\n/**\n * A scope supported by the Shopify Admin API.\n */\ntype AdminAPIScope = 'graphql' | 'themes' | 'collaborator' | string\n\n/**\n * It represents the options to authenticate against the Shopify Admin API.\n */\n\ninterface AdminAPIOAuthOptions {\n /** Store to request permissions for. */\n storeFqdn: string\n /** List of scopes to request permissions for. */\n scopes: AdminAPIScope[]\n}\n\n/**\n * A scope supported by the Partners API.\n */\ntype PartnersAPIScope = 'cli' | string\ninterface PartnersAPIOAuthOptions {\n /** List of scopes to request permissions for. */\n scopes: PartnersAPIScope[]\n}\n\n/**\n * A scope supported by the Storefront Renderer API.\n */\ntype StorefrontRendererScope = 'devtools' | string\ninterface StorefrontRendererAPIOAuthOptions {\n /** List of scopes to request permissions for. */\n scopes: StorefrontRendererScope[]\n}\n\ntype BusinessPlatformScope = 'destinations' | string\ninterface BusinessPlatformAPIOAuthOptions {\n /** List of scopes to request permissions for. */\n scopes: BusinessPlatformScope[]\n}\n\n/**\n * It represents the authentication requirements and\n * is the input necessary to trigger the authentication\n * flow.\n */\nexport interface OAuthApplications {\n adminApi?: AdminAPIOAuthOptions\n storefrontRendererApi?: StorefrontRendererAPIOAuthOptions\n partnersApi?: PartnersAPIOAuthOptions\n businessPlatformApi?: BusinessPlatformAPIOAuthOptions\n}\n\nexport interface OAuthSession {\n admin?: AdminSession\n partners?: string\n storefront?: string\n businessPlatform?: string\n}\n\n/**\n * This method ensures that we have a valid session to authenticate against the given applications using the provided scopes.\n *\n * @param applications - An object containing the applications we need to be authenticated with.\n * @param _env - Optional environment variables to use.\n * @param forceRefresh - Optional flag to force a refresh of the token.\n * @returns An instance with the access tokens organized by application.\n */\nexport async function ensureAuthenticated(\n applications: OAuthApplications,\n _env?: NodeJS.ProcessEnv,\n {forceRefresh = false, noPrompt = false}: {forceRefresh?: boolean; noPrompt?: boolean} = {},\n): Promise<OAuthSession> {\n const fqdn = await identityFqdn()\n\n const previousStoreFqdn = applications.adminApi?.storeFqdn\n if (previousStoreFqdn) {\n const normalizedStoreName = await normalizeStoreFqdn(previousStoreFqdn)\n if (previousStoreFqdn === applications.adminApi?.storeFqdn) {\n applications.adminApi.storeFqdn = normalizedStoreName\n }\n }\n\n const currentSession = (await secureStore.fetch()) || {}\n const fqdnSession = currentSession[fqdn]!\n const scopes = getFlattenScopes(applications)\n\n outputDebug(outputContent`Validating existing session against the scopes:\n${outputToken.json(scopes)}\nFor applications:\n${outputToken.json(applications)}\n`)\n const validationResult = await validateSession(scopes, applications, fqdnSession)\n\n let newSession = {}\n\n if (validationResult === 'needs_full_auth') {\n if (noPrompt) {\n throw new AbortError(\n `The currently available CLI credentials are invalid.\n\nThe CLI is currently unable to prompt for reauthentication.`,\n 'Restart the CLI process you were running. If in an interactive terminal, you will be prompted to reauthenticate. If in a non-interactive terminal, ensure the correct credentials are available in the program environment.',\n )\n }\n outputDebug(outputContent`Initiating the full authentication flow...`)\n newSession = await executeCompleteFlow(applications, fqdn)\n } else if (validationResult === 'needs_refresh' || forceRefresh) {\n outputDebug(outputContent`The current session is valid but needs refresh. Refreshing...`)\n try {\n newSession = await refreshTokens(fqdnSession.identity, applications, fqdn)\n } catch (error) {\n if (error instanceof InvalidGrantError) {\n newSession = await executeCompleteFlow(applications, fqdn)\n } else if (error instanceof InvalidRequestError) {\n await secureStore.remove()\n throw new AbortError('\\nError validating auth session', \"We've cleared the current session, please try again\")\n } else {\n throw error\n }\n }\n }\n\n const completeSession: Session = {...currentSession, ...newSession}\n // Save the new session info if it has changed\n if (Object.keys(newSession).length > 0) await secureStore.store(completeSession)\n const tokens = await tokensFor(applications, completeSession, fqdn)\n\n // Overwrite partners token if using a custom CLI Token\n const envToken = getPartnersToken()\n if (envToken && applications.partnersApi) {\n tokens.partners = (await exchangeCustomPartnerToken(envToken)).accessToken\n }\n if (!envToken && tokens.partners) {\n await ensureUserHasPartnerAccount(tokens.partners)\n }\n\n return tokens\n}\n\n/**\n * Execute the full authentication flow.\n *\n * @param applications - An object containing the applications we need to be authenticated with.\n * @param identityFqdn - The identity FQDN.\n */\nasync function executeCompleteFlow(applications: OAuthApplications, identityFqdn: string): Promise<Session> {\n const scopes = getFlattenScopes(applications)\n const exchangeScopes = getExchangeScopes(applications)\n const store = applications.adminApi?.storeFqdn\n if (firstPartyDev()) {\n outputDebug(outputContent`Authenticating as Shopify Employee...`)\n scopes.push('employee')\n }\n\n let identityToken: IdentityToken\n const identityTokenInformation = getIdentityTokenInformation()\n if (identityTokenInformation) {\n identityToken = buildIdentityTokenFromEnv(scopes, identityTokenInformation)\n } else if (useDeviceAuth()) {\n // Request a device code to authorize without a browser redirect.\n outputDebug(outputContent`Requesting device authorization code...`)\n const deviceAuth = await requestDeviceAuthorization(scopes)\n\n // Poll for the identity token\n outputDebug(outputContent`Starting polling for the identity token...`)\n identityToken = await pollForDeviceAuthorization(deviceAuth.deviceCode, deviceAuth.interval)\n } else {\n // Authorize user via browser\n outputDebug(outputContent`Authorizing through Identity's website...`)\n const code = await authorize(scopes)\n\n // Exchange code for identity token\n outputDebug(outputContent`Authorization code received. Exchanging it for a CLI token...`)\n identityToken = await exchangeCodeForAccessToken(code)\n }\n\n // Exchange identity token for application tokens\n outputDebug(outputContent`CLI token received. Exchanging it for application tokens...`)\n const result = await exchangeAccessForApplicationTokens(identityToken, exchangeScopes, store)\n\n const session: Session = {\n [identityFqdn]: {\n identity: identityToken,\n applications: result,\n },\n }\n\n outputCompleted('Logged in.')\n\n return session\n}\n\n/**\n * If the user creates an account from the Identity website, the created\n * account won't get a Partner organization created. We need to detect that\n * and take the user to create a partner organization.\n *\n * @param partnersToken - Partners token.\n */\nasync function ensureUserHasPartnerAccount(partnersToken: string) {\n outputDebug(outputContent`Verifying that the user has a Partner organization`)\n if (!(await hasPartnerAccount(partnersToken))) {\n outputInfo(`\\nA Shopify Partners organization is needed to proceed.`)\n outputInfo(`👉 Press any key to create one`)\n await keypress()\n await openURL(`https://${await partnersFqdn()}/signup`)\n outputInfo(outputContent`👉 Press any key when you have ${outputToken.cyan('created the organization')}`)\n outputWarn(outputContent`Make sure you've confirmed your Shopify and the Partner organization from the email`)\n await keypress()\n if (!(await hasPartnerAccount(partnersToken))) {\n throw new AbortError(\n `Couldn't find your Shopify Partners organization`,\n `Have you confirmed your accounts from the emails you received?`,\n )\n }\n }\n}\n\nconst getFirstOrganization = gql`\n {\n organizations(first: 1) {\n nodes {\n id\n }\n }\n }\n`\n\n/**\n * Validate if the current token is valid for partners API.\n *\n * @param partnersToken - Partners token.\n * @returns A promise that resolves to true if the token is valid for partners API.\n */\nasync function hasPartnerAccount(partnersToken: string): Promise<boolean> {\n try {\n await partnersRequest(getFirstOrganization, partnersToken)\n return true\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n if (error instanceof RequestClientError && error.statusCode === 404) {\n return false\n } else {\n return true\n }\n }\n}\n\n/**\n * Refresh the tokens for a given session.\n *\n * @param token - Identity token.\n * @param applications - An object containing the applications we need to be authenticated with.\n * @param fqdn - The identity FQDN.\n */\nasync function refreshTokens(token: IdentityToken, applications: OAuthApplications, fqdn: string): Promise<Session> {\n // Refresh Identity Token\n const identityToken = await refreshAccessToken(token)\n // Exchange new identity token for application tokens\n const exchangeScopes = getExchangeScopes(applications)\n const applicationTokens = await exchangeAccessForApplicationTokens(\n identityToken,\n exchangeScopes,\n applications.adminApi?.storeFqdn,\n )\n\n return {\n [fqdn]: {\n identity: identityToken,\n applications: applicationTokens,\n },\n }\n}\n\n/**\n * Get the application tokens for a given session.\n *\n * @param applications - An object containing the applications we need the tokens for.\n * @param session - The current session.\n * @param fqdn - The identity FQDN.\n */\nasync function tokensFor(applications: OAuthApplications, session: Session, fqdn: string): Promise<OAuthSession> {\n const fqdnSession = session[fqdn]\n if (!fqdnSession) {\n throw new BugError('No session found after ensuring authenticated')\n }\n const tokens: OAuthSession = {}\n if (applications.adminApi) {\n const appId = applicationId('admin')\n const realAppId = `${applications.adminApi.storeFqdn}-${appId}`\n const token = fqdnSession.applications[realAppId]?.accessToken\n if (token) {\n tokens.admin = {token, storeFqdn: applications.adminApi.storeFqdn}\n }\n }\n\n if (applications.partnersApi) {\n const appId = applicationId('partners')\n tokens.partners = fqdnSession.applications[appId]?.accessToken\n }\n\n if (applications.storefrontRendererApi) {\n const appId = applicationId('storefront-renderer')\n tokens.storefront = fqdnSession.applications[appId]?.accessToken\n }\n\n if (applications.businessPlatformApi) {\n const appId = applicationId('business-platform')\n tokens.businessPlatform = fqdnSession.applications[appId]?.accessToken\n }\n\n return tokens\n}\n\n// Scope Helpers\n/**\n * Get a flattened array of scopes for the given applications.\n *\n * @param apps - An object containing the applications we need the scopes for.\n * @returns A flattened array of scopes.\n */\nfunction getFlattenScopes(apps: OAuthApplications): string[] {\n const admin = apps.adminApi?.scopes || []\n const partner = apps.partnersApi?.scopes || []\n const storefront = apps.storefrontRendererApi?.scopes || []\n const businessPlatform = apps.businessPlatformApi?.scopes || []\n const requestedScopes = [...admin, ...partner, ...storefront, ...businessPlatform]\n return allDefaultScopes(requestedScopes)\n}\n\n/**\n * Get the scopes for the given applications.\n *\n * @param apps - An object containing the applications we need the scopes for.\n * @returns An object containing the scopes for each application.\n */\nfunction getExchangeScopes(apps: OAuthApplications): ExchangeScopes {\n const adminScope = apps.adminApi?.scopes || []\n const partnerScope = apps.partnersApi?.scopes || []\n const storefrontScopes = apps.storefrontRendererApi?.scopes || []\n const businessPlatformScopes = apps.businessPlatformApi?.scopes || []\n return {\n admin: apiScopes('admin', adminScope),\n partners: apiScopes('partners', partnerScope),\n storefront: apiScopes('storefront-renderer', storefrontScopes),\n businessPlatform: apiScopes('business-platform', businessPlatformScopes),\n }\n}\n\nfunction buildIdentityTokenFromEnv(\n scopes: string[],\n identityTokenInformation: {accessToken: string; refreshToken: string},\n) {\n return {\n ...identityTokenInformation,\n expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),\n scopes,\n }\n}\n"]}
|
|
@@ -97,3 +97,11 @@ export declare function formatDate(date: Date): string;
|
|
|
97
97
|
* @returns The joined string.
|
|
98
98
|
*/
|
|
99
99
|
export declare function joinWithAnd(items: string[]): string;
|
|
100
|
+
/**
|
|
101
|
+
* Given a string, it returns the PascalCase form of it.
|
|
102
|
+
* Eg: "pascal_case" returns "PascalCase".
|
|
103
|
+
*
|
|
104
|
+
* @param str - String to PascalCase.
|
|
105
|
+
* @returns String with all the first letter capitalized with no spaces.
|
|
106
|
+
*/
|
|
107
|
+
export declare function pascalize(str: string): string;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { takeRandomFromArray } from './array.js';
|
|
2
2
|
import { unstyled } from '../../public/node/output.js';
|
|
3
|
-
import { camelCase, constantCase, paramCase, snakeCase } from 'change-case';
|
|
3
|
+
import { camelCase, constantCase, paramCase, snakeCase, pascalCase } from 'change-case';
|
|
4
4
|
const SAFE_RANDOM_BUSINESS_ADJECTIVES = [
|
|
5
5
|
'commercial',
|
|
6
6
|
'profitable',
|
|
@@ -332,4 +332,14 @@ export function joinWithAnd(items) {
|
|
|
332
332
|
.map((item) => `"${item}"`)
|
|
333
333
|
.join(', ')} and "${items[items.length - 1]}"`;
|
|
334
334
|
}
|
|
335
|
+
/**
|
|
336
|
+
* Given a string, it returns the PascalCase form of it.
|
|
337
|
+
* Eg: "pascal_case" returns "PascalCase".
|
|
338
|
+
*
|
|
339
|
+
* @param str - String to PascalCase.
|
|
340
|
+
* @returns String with all the first letter capitalized with no spaces.
|
|
341
|
+
*/
|
|
342
|
+
export function pascalize(str) {
|
|
343
|
+
return pascalCase(str);
|
|
344
|
+
}
|
|
335
345
|
//# sourceMappingURL=string.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"string.js","sourceRoot":"","sources":["../../../src/public/common/string.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,mBAAmB,EAAC,MAAM,YAAY,CAAA;AAC9C,OAAO,EAAC,QAAQ,EAAC,MAAM,6BAA6B,CAAA;AAEpD,OAAO,EAAC,SAAS,EAAE,YAAY,EAAE,SAAS,EAAE,SAAS,EAAC,MAAM,aAAa,CAAA;AAEzE,MAAM,+BAA+B,GAAG;IACtC,YAAY;IACZ,YAAY;IACZ,aAAa;IACb,SAAS;IACT,YAAY;IACZ,aAAa;IACb,cAAc;IACd,aAAa;IACb,MAAM;IACN,OAAO;IACP,SAAS;IACT,QAAQ;IACR,UAAU;IACV,WAAW;IACX,WAAW;IACX,eAAe;IACf,YAAY;IACZ,UAAU;IACV,WAAW;IACX,WAAW;IACX,QAAQ;IACR,QAAQ;IACR,WAAW;IACX,UAAU;IACV,WAAW;IACX,SAAS;IACT,aAAa;IACb,YAAY;IACZ,UAAU;IACV,aAAa;IACb,SAAS;IACT,WAAW;IACX,SAAS;IACT,UAAU;IACV,aAAa;CACd,CAAA;AAED,MAAM,+BAA+B,GAAG;IACtC,QAAQ;IACR,WAAW;IACX,SAAS;IACT,UAAU;IACV,QAAQ;IACR,SAAS;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C,OAAO,GAAG,KAAK;SACZ,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;SACZ,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,GAAG,CAAC;SAC1B,IAAI,CAAC,IAAI,CAAC,SAAS,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAA;AAClD,CAAC","sourcesContent":["import {takeRandomFromArray} from './array.js'\nimport {unstyled} from '../../public/node/output.js'\nimport {Token, TokenItem} from '../../private/node/ui/components/TokenizedText.js'\nimport {camelCase, constantCase, paramCase, snakeCase} from 'change-case'\n\nconst SAFE_RANDOM_BUSINESS_ADJECTIVES = [\n 'commercial',\n 'profitable',\n 'amortizable',\n 'branded',\n 'integrated',\n 'synergistic',\n 'consolidated',\n 'diversified',\n 'lean',\n 'niche',\n 'premium',\n 'luxury',\n 'scalable',\n 'optimized',\n 'empowered',\n 'international',\n 'beneficial',\n 'fruitful',\n 'extensive',\n 'lucrative',\n 'modern',\n 'stable',\n 'strategic',\n 'adaptive',\n 'efficient',\n 'growing',\n 'sustainable',\n 'innovative',\n 'regional',\n 'specialized',\n 'focused',\n 'pragmatic',\n 'ethical',\n 'flexible',\n 'competitive',\n]\n\nconst SAFE_RANDOM_CREATIVE_ADJECTIVES = [\n 'bright',\n 'impactful',\n 'stylish',\n 'colorful',\n 'modern',\n 'minimal',\n 'trendy',\n 'creative',\n 'artistic',\n 'spectacular',\n 'glamorous',\n 'luxury',\n 'retro',\n 'nostalgic',\n 'comfy',\n 'polished',\n 'fabulous',\n 'balanced',\n 'monochrome',\n 'glitched',\n 'contrasted',\n 'elegant',\n 'textured',\n 'vibrant',\n 'harmonious',\n 'versatile',\n 'eclectic',\n 'futuristic',\n 'idealistic',\n 'intricate',\n 'bohemian',\n 'abstract',\n 'meticulous',\n 'refined',\n 'flamboyant',\n]\n\nconst SAFE_RANDOM_BUSINESS_NOUNS = [\n 'account',\n 'consumer',\n 'customer',\n 'enterprise',\n 'business',\n 'venture',\n 'marketplace',\n 'revenue',\n 'vertical',\n 'portfolio',\n 'negotiation',\n 'shipping',\n 'demand',\n 'supply',\n 'growth',\n 'merchant',\n 'investment',\n 'shareholder',\n 'conversion',\n 'capital',\n 'projection',\n 'upside',\n 'trade',\n 'deal',\n 'merchandise',\n 'transaction',\n 'sale',\n 'franchise',\n 'subsidiary',\n 'logistics',\n 'infrastructure',\n 'sponsorship',\n 'partnership',\n 'tax',\n 'policy',\n 'outsource',\n 'equity',\n 'strategy',\n 'valuation',\n 'benchmark',\n 'metrics',\n 'duplication',\n]\n\nconst SAFE_RANDOM_CREATIVE_NOUNS = [\n 'vibe',\n 'style',\n 'moment',\n 'mood',\n 'flavor',\n 'look',\n 'appearance',\n 'perspective',\n 'aspect',\n 'ambience',\n 'quality',\n 'backdrop',\n 'focus',\n 'tone',\n 'inspiration',\n 'imagery',\n 'aesthetics',\n 'palette',\n 'ornamentation',\n 'contrast',\n 'colorway',\n 'visuals',\n 'typography',\n 'composition',\n 'scale',\n 'symmetry',\n 'gradients',\n 'proportions',\n 'textures',\n 'harmony',\n 'shapes',\n 'patterns',\n]\n\nexport type RandomNameFamily = 'business' | 'creative'\n\n/**\n * Generates a random name by combining an adjective and noun.\n *\n * @param family - Theme to use for the random name (business or creative).\n * @returns A random name generated by combining an adjective and noun.\n */\nexport function getRandomName(family: RandomNameFamily = 'business'): string {\n const mapping = {\n business: {\n adjectives: SAFE_RANDOM_BUSINESS_ADJECTIVES,\n nouns: SAFE_RANDOM_BUSINESS_NOUNS,\n },\n creative: {\n adjectives: SAFE_RANDOM_CREATIVE_ADJECTIVES,\n nouns: SAFE_RANDOM_CREATIVE_NOUNS,\n },\n }\n return `${takeRandomFromArray(mapping[family].adjectives)}-${takeRandomFromArray(mapping[family].nouns)}`\n}\n\n/**\n * Given a string, it returns it with the first letter capitalized.\n *\n * @param str - String to capitalize.\n * @returns String with the first letter capitalized.\n */\nexport function capitalize(str: string): string {\n return str.substring(0, 1).toUpperCase() + str.substring(1)\n}\n\n/**\n * Given a list of items, it returns a pluralized string based on the amount of items.\n *\n * @param items - List of items.\n * @param plural - Supplier used when the list of items has more than one item.\n * @param singular - Supplier used when the list of items has a single item.\n * @param none - Supplier used when the list has no items.\n * @returns The {@link TokenItem} supplied by the {@link plural}, {@link singular}, or {@link none} functions.\n */\nexport function pluralize<\n T,\n TToken extends Token = Token,\n TPluralToken extends TToken = TToken,\n TSingularToken extends TToken = TToken,\n TNoneToken extends TToken = TToken,\n>(\n items: T[],\n plural: (items: T[]) => TokenItem<TPluralToken>,\n singular: (item: T) => TokenItem<TSingularToken>,\n none?: () => TokenItem<TNoneToken>,\n): TokenItem<TPluralToken | TSingularToken | TNoneToken> | string {\n if (items.length === 1) {\n return singular(items[0]!)\n }\n\n if (items.length > 1) {\n return plural(items)\n }\n\n if (none) {\n return none()\n }\n\n return ''\n}\n\n/**\n * Try to convert a string to an int, falling back to undefined if unable to.\n *\n * @param maybeInt - String to convert to an int.\n * @returns The int if it was able to convert, otherwise undefined.\n */\nexport function tryParseInt(maybeInt: string | undefined): number | undefined {\n let asInt: number | undefined\n if (maybeInt !== undefined) {\n asInt = parseInt(maybeInt, 10)\n if (isNaN(asInt)) {\n asInt = undefined\n }\n }\n return asInt\n}\n\n/**\n * Transforms a matrix of strings into a single string with the columns aligned.\n *\n * @param lines - Array of rows, where each row is an array of strings (representing columns).\n * @returns A string with the columns aligned.\n */\nexport function linesToColumns(lines: string[][]): string {\n const widths: number[] = []\n for (let i = 0; lines[0] && i < lines[0].length; i++) {\n const columnRows = lines.map((line) => line[i]!)\n widths.push(Math.max(...columnRows.map((row) => unstyled(row).length)))\n }\n const paddedLines = lines\n .map((line) => {\n return line\n .map((col, index) => {\n return `${col}${' '.repeat(widths[index]! - unstyled(col).length)}`\n })\n .join(' ')\n .trimEnd()\n })\n .join('\\n')\n return paddedLines\n}\n\n/**\n * Given a string, it transforms it to a slug (lowercase, hyphenated, no special chars, trimmed...).\n *\n * @param str - String to slugify.\n * @returns The slugified string.\n */\nexport function slugify(str: string): string {\n return str\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, '')\n .replace(/[\\s_-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n}\n\n/**\n * Given a string, it returns it with the special regex characters escaped.\n * More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping.\n *\n * @param str - String to escape.\n * @returns The escaped string.\n */\nexport function escapeRegExp(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Transform a string to camelCase.\n *\n * @param input - String to escape.\n * @returns The escaped string.\n */\nexport function camelize(input: string): string {\n return camelCase(input)\n}\n\n/**\n * Transform a string to param-case.\n *\n * @param input - String to transform.\n * @returns The transformed string.\n */\nexport function hyphenate(input: string): string {\n return paramCase(input)\n}\n\n/**\n * Transform a string to snake_case.\n *\n * @param input - String to transform.\n * @returns The transformed string.\n */\nexport function underscore(input: string): string {\n return snakeCase(input)\n}\n\n/**\n * Transform a string to CONSTANT_CASE.\n *\n * @param input - String to transform.\n * @returns The transformed string.\n */\nexport function constantize(input: string): string {\n return constantCase(input)\n}\n\n/**\n * Given a date, return a formatted string like \"2021-01-01 12:00:00\".\n *\n * @param date - Date to format.\n * @returns The transformed string.\n */\nexport function formatDate(date: Date): string {\n const components = date.toISOString().split('T')\n const dateString = components[0] ?? date.toDateString()\n const timeString = components[1]?.split('.')[0] ?? date.toTimeString()\n return `${dateString} ${timeString}`\n}\n\n/**\n * Given a list of items, it returns a string with the items joined by commas and the last item joined by \"and\".\n * All items are wrapped in double quotes.\n * For example: [\"a\", \"b\", \"c\"] returns \"a\", \"b\" and \"c\".\n *\n * @param items - List of items.\n * @returns The joined string.\n */\nexport function joinWithAnd(items: string[]): string {\n if (items.length === 0) return ''\n if (items.length === 1) return `\"${items[0]}\"`\n\n return `${items\n .slice(0, -1)\n .map((item) => `\"${item}\"`)\n .join(', ')} and \"${items[items.length - 1]}\"`\n}\n"]}
|
|
1
|
+
{"version":3,"file":"string.js","sourceRoot":"","sources":["../../../src/public/common/string.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,mBAAmB,EAAC,MAAM,YAAY,CAAA;AAC9C,OAAO,EAAC,QAAQ,EAAC,MAAM,6BAA6B,CAAA;AAEpD,OAAO,EAAC,SAAS,EAAE,YAAY,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAC,MAAM,aAAa,CAAA;AAErF,MAAM,+BAA+B,GAAG;IACtC,YAAY;IACZ,YAAY;IACZ,aAAa;IACb,SAAS;IACT,YAAY;IACZ,aAAa;IACb,cAAc;IACd,aAAa;IACb,MAAM;IACN,OAAO;IACP,SAAS;IACT,QAAQ;IACR,UAAU;IACV,WAAW;IACX,WAAW;IACX,eAAe;IACf,YAAY;IACZ,UAAU;IACV,WAAW;IACX,WAAW;IACX,QAAQ;IACR,QAAQ;IACR,WAAW;IACX,UAAU;IACV,WAAW;IACX,SAAS;IACT,aAAa;IACb,YAAY;IACZ,UAAU;IACV,aAAa;IACb,SAAS;IACT,WAAW;IACX,SAAS;IACT,UAAU;IACV,aAAa;CACd,CAAA;AAED,MAAM,+BAA+B,GAAG;IACtC,QAAQ;IACR,WAAW;IACX,SAAS;IACT,UAAU;IACV,QAAQ;IACR,SAAS;IACT,QAAQ;IACR,UAAU;IACV,UAAU;IACV,aAAa;IACb,WAAW;IACX,QAAQ;IACR,OAAO;IACP,WAAW;IACX,OAAO;IACP,UAAU;IACV,UAAU;IACV,UAAU;IACV,YAAY;IACZ,UAAU;IACV,YAAY;IACZ,SAAS;IACT,UAAU;IACV,SAAS;IACT,YAAY;IACZ,WAAW;IACX,UAAU;IACV,YAAY;IACZ,YAAY;IACZ,WAAW;IACX,UAAU;IACV,UAAU;IACV,YAAY;IACZ,SAAS;IACT,YAAY;CACb,CAAA;AAED,MAAM,0BAA0B,GAAG;IACjC,SAAS;IACT,UAAU;IACV,UAAU;IACV,YAAY;IACZ,UAAU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nimport {Token, TokenItem} from '../../private/node/ui/components/TokenizedText.js'\nimport {camelCase, constantCase, paramCase, snakeCase, pascalCase} from 'change-case'\n\nconst SAFE_RANDOM_BUSINESS_ADJECTIVES = [\n 'commercial',\n 'profitable',\n 'amortizable',\n 'branded',\n 'integrated',\n 'synergistic',\n 'consolidated',\n 'diversified',\n 'lean',\n 'niche',\n 'premium',\n 'luxury',\n 'scalable',\n 'optimized',\n 'empowered',\n 'international',\n 'beneficial',\n 'fruitful',\n 'extensive',\n 'lucrative',\n 'modern',\n 'stable',\n 'strategic',\n 'adaptive',\n 'efficient',\n 'growing',\n 'sustainable',\n 'innovative',\n 'regional',\n 'specialized',\n 'focused',\n 'pragmatic',\n 'ethical',\n 'flexible',\n 'competitive',\n]\n\nconst SAFE_RANDOM_CREATIVE_ADJECTIVES = [\n 'bright',\n 'impactful',\n 'stylish',\n 'colorful',\n 'modern',\n 'minimal',\n 'trendy',\n 'creative',\n 'artistic',\n 'spectacular',\n 'glamorous',\n 'luxury',\n 'retro',\n 'nostalgic',\n 'comfy',\n 'polished',\n 'fabulous',\n 'balanced',\n 'monochrome',\n 'glitched',\n 'contrasted',\n 'elegant',\n 'textured',\n 'vibrant',\n 'harmonious',\n 'versatile',\n 'eclectic',\n 'futuristic',\n 'idealistic',\n 'intricate',\n 'bohemian',\n 'abstract',\n 'meticulous',\n 'refined',\n 'flamboyant',\n]\n\nconst SAFE_RANDOM_BUSINESS_NOUNS = [\n 'account',\n 'consumer',\n 'customer',\n 'enterprise',\n 'business',\n 'venture',\n 'marketplace',\n 'revenue',\n 'vertical',\n 'portfolio',\n 'negotiation',\n 'shipping',\n 'demand',\n 'supply',\n 'growth',\n 'merchant',\n 'investment',\n 'shareholder',\n 'conversion',\n 'capital',\n 'projection',\n 'upside',\n 'trade',\n 'deal',\n 'merchandise',\n 'transaction',\n 'sale',\n 'franchise',\n 'subsidiary',\n 'logistics',\n 'infrastructure',\n 'sponsorship',\n 'partnership',\n 'tax',\n 'policy',\n 'outsource',\n 'equity',\n 'strategy',\n 'valuation',\n 'benchmark',\n 'metrics',\n 'duplication',\n]\n\nconst SAFE_RANDOM_CREATIVE_NOUNS = [\n 'vibe',\n 'style',\n 'moment',\n 'mood',\n 'flavor',\n 'look',\n 'appearance',\n 'perspective',\n 'aspect',\n 'ambience',\n 'quality',\n 'backdrop',\n 'focus',\n 'tone',\n 'inspiration',\n 'imagery',\n 'aesthetics',\n 'palette',\n 'ornamentation',\n 'contrast',\n 'colorway',\n 'visuals',\n 'typography',\n 'composition',\n 'scale',\n 'symmetry',\n 'gradients',\n 'proportions',\n 'textures',\n 'harmony',\n 'shapes',\n 'patterns',\n]\n\nexport type RandomNameFamily = 'business' | 'creative'\n\n/**\n * Generates a random name by combining an adjective and noun.\n *\n * @param family - Theme to use for the random name (business or creative).\n * @returns A random name generated by combining an adjective and noun.\n */\nexport function getRandomName(family: RandomNameFamily = 'business'): string {\n const mapping = {\n business: {\n adjectives: SAFE_RANDOM_BUSINESS_ADJECTIVES,\n nouns: SAFE_RANDOM_BUSINESS_NOUNS,\n },\n creative: {\n adjectives: SAFE_RANDOM_CREATIVE_ADJECTIVES,\n nouns: SAFE_RANDOM_CREATIVE_NOUNS,\n },\n }\n return `${takeRandomFromArray(mapping[family].adjectives)}-${takeRandomFromArray(mapping[family].nouns)}`\n}\n\n/**\n * Given a string, it returns it with the first letter capitalized.\n *\n * @param str - String to capitalize.\n * @returns String with the first letter capitalized.\n */\nexport function capitalize(str: string): string {\n return str.substring(0, 1).toUpperCase() + str.substring(1)\n}\n\n/**\n * Given a list of items, it returns a pluralized string based on the amount of items.\n *\n * @param items - List of items.\n * @param plural - Supplier used when the list of items has more than one item.\n * @param singular - Supplier used when the list of items has a single item.\n * @param none - Supplier used when the list has no items.\n * @returns The {@link TokenItem} supplied by the {@link plural}, {@link singular}, or {@link none} functions.\n */\nexport function pluralize<\n T,\n TToken extends Token = Token,\n TPluralToken extends TToken = TToken,\n TSingularToken extends TToken = TToken,\n TNoneToken extends TToken = TToken,\n>(\n items: T[],\n plural: (items: T[]) => TokenItem<TPluralToken>,\n singular: (item: T) => TokenItem<TSingularToken>,\n none?: () => TokenItem<TNoneToken>,\n): TokenItem<TPluralToken | TSingularToken | TNoneToken> | string {\n if (items.length === 1) {\n return singular(items[0]!)\n }\n\n if (items.length > 1) {\n return plural(items)\n }\n\n if (none) {\n return none()\n }\n\n return ''\n}\n\n/**\n * Try to convert a string to an int, falling back to undefined if unable to.\n *\n * @param maybeInt - String to convert to an int.\n * @returns The int if it was able to convert, otherwise undefined.\n */\nexport function tryParseInt(maybeInt: string | undefined): number | undefined {\n let asInt: number | undefined\n if (maybeInt !== undefined) {\n asInt = parseInt(maybeInt, 10)\n if (isNaN(asInt)) {\n asInt = undefined\n }\n }\n return asInt\n}\n\n/**\n * Transforms a matrix of strings into a single string with the columns aligned.\n *\n * @param lines - Array of rows, where each row is an array of strings (representing columns).\n * @returns A string with the columns aligned.\n */\nexport function linesToColumns(lines: string[][]): string {\n const widths: number[] = []\n for (let i = 0; lines[0] && i < lines[0].length; i++) {\n const columnRows = lines.map((line) => line[i]!)\n widths.push(Math.max(...columnRows.map((row) => unstyled(row).length)))\n }\n const paddedLines = lines\n .map((line) => {\n return line\n .map((col, index) => {\n return `${col}${' '.repeat(widths[index]! - unstyled(col).length)}`\n })\n .join(' ')\n .trimEnd()\n })\n .join('\\n')\n return paddedLines\n}\n\n/**\n * Given a string, it transforms it to a slug (lowercase, hyphenated, no special chars, trimmed...).\n *\n * @param str - String to slugify.\n * @returns The slugified string.\n */\nexport function slugify(str: string): string {\n return str\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, '')\n .replace(/[\\s_-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n}\n\n/**\n * Given a string, it returns it with the special regex characters escaped.\n * More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping.\n *\n * @param str - String to escape.\n * @returns The escaped string.\n */\nexport function escapeRegExp(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Transform a string to camelCase.\n *\n * @param input - String to escape.\n * @returns The escaped string.\n */\nexport function camelize(input: string): string {\n return camelCase(input)\n}\n\n/**\n * Transform a string to param-case.\n *\n * @param input - String to transform.\n * @returns The transformed string.\n */\nexport function hyphenate(input: string): string {\n return paramCase(input)\n}\n\n/**\n * Transform a string to snake_case.\n *\n * @param input - String to transform.\n * @returns The transformed string.\n */\nexport function underscore(input: string): string {\n return snakeCase(input)\n}\n\n/**\n * Transform a string to CONSTANT_CASE.\n *\n * @param input - String to transform.\n * @returns The transformed string.\n */\nexport function constantize(input: string): string {\n return constantCase(input)\n}\n\n/**\n * Given a date, return a formatted string like \"2021-01-01 12:00:00\".\n *\n * @param date - Date to format.\n * @returns The transformed string.\n */\nexport function formatDate(date: Date): string {\n const components = date.toISOString().split('T')\n const dateString = components[0] ?? date.toDateString()\n const timeString = components[1]?.split('.')[0] ?? date.toTimeString()\n return `${dateString} ${timeString}`\n}\n\n/**\n * Given a list of items, it returns a string with the items joined by commas and the last item joined by \"and\".\n * All items are wrapped in double quotes.\n * For example: [\"a\", \"b\", \"c\"] returns \"a\", \"b\" and \"c\".\n *\n * @param items - List of items.\n * @returns The joined string.\n */\nexport function joinWithAnd(items: string[]): string {\n if (items.length === 0) return ''\n if (items.length === 1) return `\"${items[0]}\"`\n\n return `${items\n .slice(0, -1)\n .map((item) => `\"${item}\"`)\n .join(', ')} and \"${items[items.length - 1]}\"`\n}\n\n/**\n * Given a string, it returns the PascalCase form of it.\n * Eg: \"pascal_case\" returns \"PascalCase\".\n *\n * @param str - String to PascalCase.\n * @returns String with all the first letter capitalized with no spaces.\n */\nexport function pascalize(str: string): string {\n return pascalCase(str)\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const CLI_KIT_VERSION = "3.
|
|
1
|
+
export declare const CLI_KIT_VERSION = "3.51.1";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export const CLI_KIT_VERSION = '3.
|
|
1
|
+
export const CLI_KIT_VERSION = '3.51.1';
|
|
2
2
|
//# sourceMappingURL=version.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/public/common/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,eAAe,GAAG,QAAQ,CAAA","sourcesContent":["export const CLI_KIT_VERSION = '3.
|
|
1
|
+
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/public/common/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,eAAe,GAAG,QAAQ,CAAA","sourcesContent":["export const CLI_KIT_VERSION = '3.51.1'\n"]}
|
|
@@ -35,9 +35,9 @@ export async function reportAnalyticsEvent(options) {
|
|
|
35
35
|
}
|
|
36
36
|
};
|
|
37
37
|
const doOpenTelemetry = async () => {
|
|
38
|
-
const active =
|
|
39
|
-
const network =
|
|
40
|
-
const prompt =
|
|
38
|
+
const active = payload.public.cmd_all_timing_active_ms || 0;
|
|
39
|
+
const network = payload.public.cmd_all_timing_network_ms || 0;
|
|
40
|
+
const prompt = payload.public.cmd_all_timing_prompts_ms || 0;
|
|
41
41
|
return recordMetrics({
|
|
42
42
|
skipMetricAnalytics,
|
|
43
43
|
cliVersion: payload.public.cli_version,
|
|
@@ -117,6 +117,14 @@ async function buildPayload({ config, errorMessage, exitMode }) {
|
|
|
117
117
|
}),
|
|
118
118
|
},
|
|
119
119
|
};
|
|
120
|
+
// round down timing metrics
|
|
121
|
+
const timingMetrics = ['cmd_all_timing_active_ms', 'cmd_all_timing_network_ms', 'cmd_all_timing_prompts_ms'];
|
|
122
|
+
timingMetrics.forEach((metric) => {
|
|
123
|
+
const current = payload.public[metric];
|
|
124
|
+
if (current !== undefined) {
|
|
125
|
+
payload.public[metric] = Math.floor(current);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
120
128
|
// strip undefined fields -- they make up the majority of payloads due to wide metadata structure.
|
|
121
129
|
payload = JSON.parse(JSON.stringify(payload));
|
|
122
130
|
return sanitizePayload(payload);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analytics.js","sourceRoot":"","sources":["../../../src/public/node/analytics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,OAAO,IAAI,WAAW,EAAC,MAAM,WAAW,CAAA;AAChD,OAAO,EAAC,kBAAkB,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,SAAS,EAAC,MAAM,oBAAoB,CAAA;AACrG,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,EAAC,oBAAoB,EAAE,sBAAsB,EAAC,MAAM,eAAe,CAAA;AAC1E,OAAO,EAAC,WAAW,EAAC,MAAM,cAAc,CAAA;AAExC,OAAO,EAAC,aAAa,EAAE,WAAW,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AACnF,OAAO,EAAC,kBAAkB,EAAE,2BAA2B,EAAC,MAAM,iCAAiC,CAAA;AAC/F,OAAO,EAAC,eAAe,EAAC,MAAM,sBAAsB,CAAA;AACpD,OAAO,EAAC,aAAa,EAAC,MAAM,oCAAoC,CAAA;AAiBhE;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CAAC,OAAoC;IAC7E,IAAI;QACF,MAAM,OAAO,GAAG,MAAM,YAAY,CAAC,OAAO,CAAC,CAAA;QAC3C,IAAI,OAAO,KAAK,SAAS,EAAE;YACzB,iBAAiB;YACjB,OAAM;SACP;QAED,MAAM,qBAAqB,GAAG,CAAC,kBAAkB,EAAE,IAAI,iBAAiB,EAAE,CAAA;QAC1E,MAAM,mBAAmB,GAAG,CAAC,gBAAgB,EAAE,IAAI,iBAAiB,EAAE,CAAA;QACtE,IAAI,qBAAqB,IAAI,mBAAmB,EAAE;YAChD,WAAW,CAAC,aAAa,CAAA,wCAAwC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;SAC9F;QAED,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I,OAAU;IACpC,MAAM,aAAa,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAA;IAC7C,iDAAiD;IACjD,MAAM,sBAAsB,GAAG,aAAa,CAAC,OAAO,CAAC,aAAa,EAAE,OAAO,CAAC,CAAA;IAC5E,OAAO,IAAI,CAAC,KAAK,CAAC,sBAAsB,CAAC,CAAA;AAC3C,CAAC","sourcesContent":["import {version as rubyVersion} from './ruby.js'\nimport {alwaysLogAnalytics, alwaysLogMetrics, analyticsDisabled, isShopify} from './context/local.js'\nimport * as metadata from './metadata.js'\nimport {publishMonorailEvent, MONORAIL_COMMAND_TOPIC} from './monorail.js'\nimport {fanoutHooks} from './plugins.js'\n\nimport {outputContent, outputDebug, outputToken} from '../../public/node/output.js'\nimport {getEnvironmentData, getSensitiveEnvironmentData} from '../../private/node/analytics.js'\nimport {CLI_KIT_VERSION} from '../common/version.js'\nimport {recordMetrics} from '../../private/node/otel-metrics.js'\nimport {Interfaces} from '@oclif/core'\n\nexport type CommandExitMode =\n // The command completed successfully\n | 'ok'\n // The command exited for some unexpected reason -- i.e. a bug\n | 'unexpected_error'\n // The command exited with an error, but its one we expect and doesn't point to a bug -- i.e. malformed config files\n | 'expected_error'\n\ninterface ReportAnalyticsEventOptions {\n config: Interfaces.Config\n errorMessage?: string\n exitMode: CommandExitMode\n}\n\n/**\n * Report an analytics event, sending it off to Monorail -- Shopify's internal analytics service.\n *\n * The payload for an event includes both generic data, and data gathered from installed plug-ins.\n *\n */\nexport async function reportAnalyticsEvent(options: ReportAnalyticsEventOptions): Promise<void> {\n try {\n const payload = await buildPayload(options)\n if (payload === undefined) {\n // Nothing to log\n return\n }\n\n const skipMonorailAnalytics = !alwaysLogAnalytics() && analyticsDisabled()\n const skipMetricAnalytics = !alwaysLogMetrics() && analyticsDisabled()\n if (skipMonorailAnalytics || skipMetricAnalytics) {\n outputDebug(outputContent`Skipping command analytics, payload: ${outputToken.json(payload)}`)\n }\n\n const doMonorail = async () => {\n if (skipMonorailAnalytics) {\n return\n }\n const response = await publishMonorailEvent(MONORAIL_COMMAND_TOPIC, payload.public, payload.sensitive)\n if (response.type === 'error') {\n outputDebug(response.message)\n }\n }\n const doOpenTelemetry = async () => {\n const active = Math.floor(payload.public.cmd_all_timing_active_ms || 0)\n const network = Math.floor(payload.public.cmd_all_timing_network_ms || 0)\n const prompt = Math.floor(payload.public.cmd_all_timing_prompts_ms || 0)\n\n return recordMetrics(\n {\n skipMetricAnalytics,\n cliVersion: payload.public.cli_version,\n owningPlugin: payload.public.cmd_all_plugin || '@shopify/cli',\n command: payload.public.command,\n exitMode: options.exitMode,\n },\n {\n active,\n network,\n prompt,\n },\n )\n }\n await Promise.all([doMonorail(), doOpenTelemetry()])\n\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n let message = 'Failed to report usage analytics'\n if (error instanceof Error) {\n message = message.concat(`: ${error.message}`)\n }\n outputDebug(message)\n }\n}\n\nasync function buildPayload({config, errorMessage, exitMode}: ReportAnalyticsEventOptions) {\n const {commandStartOptions, environmentFlags, ...sensitiveMetadata} = metadata.getAllSensitiveMetadata()\n if (commandStartOptions === undefined) {\n outputDebug('Unable to log analytics event - no information on executed command')\n return\n }\n const {startCommand, startArgs, startTime} = commandStartOptions\n const currentTime = new Date().getTime()\n\n const {'@shopify/app': appPublic, ...otherPluginsPublic} = await fanoutHooks(config, 'public_command_metadata', {})\n const {'@shopify/app': appSensitive, ...otherPluginsSensitive} = await fanoutHooks(\n config,\n 'sensitive_command_metadata',\n {},\n )\n\n const environmentData = await getEnvironmentData(config)\n const sensitiveEnvironmentData = await getSensitiveEnvironmentData(config)\n const publicMetadata = metadata.getAllPublicMetadata()\n\n // Automatically calculate the total time spent in the command, excluding time spent in subtimers.\n const subTimers = ['cmd_all_timing_network_ms', 'cmd_all_timing_prompts_ms'] as const\n const totalTimeFromSubtimers = subTimers.reduce((total, timer) => {\n const value = publicMetadata[timer]\n if (value !== undefined) {\n return total + value\n }\n return total\n }, 0)\n const wallClockElapsed = currentTime - startTime\n const totalTimeWithoutSubtimers = wallClockElapsed - totalTimeFromSubtimers\n\n let payload = {\n public: {\n command: startCommand,\n time_start: startTime,\n time_end: currentTime,\n total_time: wallClockElapsed,\n success: errorMessage === undefined,\n cli_version: CLI_KIT_VERSION,\n ruby_version: (await rubyVersion()) || '',\n node_version: process.version.replace('v', ''),\n is_employee: await isShopify(),\n ...environmentData,\n ...appPublic,\n ...publicMetadata,\n cmd_all_timing_active_ms: totalTimeWithoutSubtimers,\n cmd_all_exit: exitMode,\n },\n sensitive: {\n args: startArgs.join(' '),\n cmd_all_environment_flags: environmentFlags,\n error_message: errorMessage,\n ...appSensitive,\n ...sensitiveEnvironmentData,\n metadata: JSON.stringify({\n ...sensitiveMetadata,\n extraPublic: {\n ...otherPluginsPublic,\n },\n extraSensitive: {...otherPluginsSensitive},\n }),\n },\n }\n\n // strip undefined fields -- they make up the majority of payloads due to wide metadata structure.\n payload = JSON.parse(JSON.stringify(payload))\n\n return sanitizePayload(payload)\n}\n\nfunction sanitizePayload<T>(payload: T): T {\n const payloadString = JSON.stringify(payload)\n // Remove Theme Access passwords from the payload\n const sanitizedPayloadString = payloadString.replace(/shptka_\\w*/g, '*****')\n return JSON.parse(sanitizedPayloadString)\n}\n"]}
|
|
1
|
+
{"version":3,"file":"analytics.js","sourceRoot":"","sources":["../../../src/public/node/analytics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,OAAO,IAAI,WAAW,EAAC,MAAM,WAAW,CAAA;AAChD,OAAO,EAAC,kBAAkB,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,SAAS,EAAC,MAAM,oBAAoB,CAAA;AACrG,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,EAAC,oBAAoB,EAAE,sBAAsB,EAAC,MAAM,eAAe,CAAA;AAC1E,OAAO,EAAC,WAAW,EAAC,MAAM,cAAc,CAAA;AAExC,OAAO,EAAC,aAAa,EAAE,WAAW,EAAE,WAAW,E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ent":["import {version as rubyVersion} from './ruby.js'\nimport {alwaysLogAnalytics, alwaysLogMetrics, analyticsDisabled, isShopify} from './context/local.js'\nimport * as metadata from './metadata.js'\nimport {publishMonorailEvent, MONORAIL_COMMAND_TOPIC} from './monorail.js'\nimport {fanoutHooks} from './plugins.js'\n\nimport {outputContent, outputDebug, outputToken} from '../../public/node/output.js'\nimport {getEnvironmentData, getSensitiveEnvironmentData} from '../../private/node/analytics.js'\nimport {CLI_KIT_VERSION} from '../common/version.js'\nimport {recordMetrics} from '../../private/node/otel-metrics.js'\nimport {Interfaces} from '@oclif/core'\n\nexport type CommandExitMode =\n // The command completed successfully\n | 'ok'\n // The command exited for some unexpected reason -- i.e. a bug\n | 'unexpected_error'\n // The command exited with an error, but its one we expect and doesn't point to a bug -- i.e. malformed config files\n | 'expected_error'\n\ninterface ReportAnalyticsEventOptions {\n config: Interfaces.Config\n errorMessage?: string\n exitMode: CommandExitMode\n}\n\n/**\n * Report an analytics event, sending it off to Monorail -- Shopify's internal analytics service.\n *\n * The payload for an event includes both generic data, and data gathered from installed plug-ins.\n *\n */\nexport async function reportAnalyticsEvent(options: ReportAnalyticsEventOptions): Promise<void> {\n try {\n const payload = await buildPayload(options)\n if (payload === undefined) {\n // Nothing to log\n return\n }\n\n const skipMonorailAnalytics = !alwaysLogAnalytics() && analyticsDisabled()\n const skipMetricAnalytics = !alwaysLogMetrics() && analyticsDisabled()\n if (skipMonorailAnalytics || skipMetricAnalytics) {\n outputDebug(outputContent`Skipping command analytics, payload: ${outputToken.json(payload)}`)\n }\n\n const doMonorail = async () => {\n if (skipMonorailAnalytics) {\n return\n }\n const response = await publishMonorailEvent(MONORAIL_COMMAND_TOPIC, payload.public, payload.sensitive)\n if (response.type === 'error') {\n outputDebug(response.message)\n }\n }\n const doOpenTelemetry = async () => {\n const active = payload.public.cmd_all_timing_active_ms || 0\n const network = payload.public.cmd_all_timing_network_ms || 0\n const prompt = payload.public.cmd_all_timing_prompts_ms || 0\n\n return recordMetrics(\n {\n skipMetricAnalytics,\n cliVersion: payload.public.cli_version,\n owningPlugin: payload.public.cmd_all_plugin || '@shopify/cli',\n command: payload.public.command,\n exitMode: options.exitMode,\n },\n {\n active,\n network,\n prompt,\n },\n )\n }\n await Promise.all([doMonorail(), doOpenTelemetry()])\n\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n let message = 'Failed to report usage analytics'\n if (error instanceof Error) {\n message = message.concat(`: ${error.message}`)\n }\n outputDebug(message)\n }\n}\n\nasync function buildPayload({config, errorMessage, exitMode}: ReportAnalyticsEventOptions) {\n const {commandStartOptions, environmentFlags, ...sensitiveMetadata} = metadata.getAllSensitiveMetadata()\n if (commandStartOptions === undefined) {\n outputDebug('Unable to log analytics event - no information on executed command')\n return\n }\n const {startCommand, startArgs, startTime} = commandStartOptions\n const currentTime = new Date().getTime()\n\n const {'@shopify/app': appPublic, ...otherPluginsPublic} = await fanoutHooks(config, 'public_command_metadata', {})\n const {'@shopify/app': appSensitive, ...otherPluginsSensitive} = await fanoutHooks(\n config,\n 'sensitive_command_metadata',\n {},\n )\n\n const environmentData = await getEnvironmentData(config)\n const sensitiveEnvironmentData = await getSensitiveEnvironmentData(config)\n const publicMetadata = metadata.getAllPublicMetadata()\n\n // Automatically calculate the total time spent in the command, excluding time spent in subtimers.\n const subTimers = ['cmd_all_timing_network_ms', 'cmd_all_timing_prompts_ms'] as const\n const totalTimeFromSubtimers = subTimers.reduce((total, timer) => {\n const value = publicMetadata[timer]\n if (value !== undefined) {\n return total + value\n }\n return total\n }, 0)\n const wallClockElapsed = currentTime - startTime\n const totalTimeWithoutSubtimers = wallClockElapsed - totalTimeFromSubtimers\n\n let payload = {\n public: {\n command: startCommand,\n time_start: startTime,\n time_end: currentTime,\n total_time: wallClockElapsed,\n success: errorMessage === undefined,\n cli_version: CLI_KIT_VERSION,\n ruby_version: (await rubyVersion()) || '',\n node_version: process.version.replace('v', ''),\n is_employee: await isShopify(),\n ...environmentData,\n ...appPublic,\n ...publicMetadata,\n cmd_all_timing_active_ms: totalTimeWithoutSubtimers,\n cmd_all_exit: exitMode,\n },\n sensitive: {\n args: startArgs.join(' '),\n cmd_all_environment_flags: environmentFlags,\n error_message: errorMessage,\n ...appSensitive,\n ...sensitiveEnvironmentData,\n metadata: JSON.stringify({\n ...sensitiveMetadata,\n extraPublic: {\n ...otherPluginsPublic,\n },\n extraSensitive: {...otherPluginsSensitive},\n }),\n },\n }\n\n // round down timing metrics\n const timingMetrics = ['cmd_all_timing_active_ms', 'cmd_all_timing_network_ms', 'cmd_all_timing_prompts_ms'] as const\n timingMetrics.forEach((metric) => {\n const current = payload.public[metric]\n if (current !== undefined) {\n payload.public[metric] = Math.floor(current)\n }\n })\n\n // strip undefined fields -- they make up the majority of payloads due to wide metadata structure.\n payload = JSON.parse(JSON.stringify(payload))\n\n return sanitizePayload(payload)\n}\n\nfunction sanitizePayload<T>(payload: T): T {\n const payloadString = JSON.stringify(payload)\n // Remove Theme Access passwords from the payload\n const sanitizedPayloadString = payloadString.replace(/shptka_\\w*/g, '*****')\n return JSON.parse(sanitizedPayloadString)\n}\n"]}
|
|
@@ -18,7 +18,7 @@ class BaseCommand extends Command {
|
|
|
18
18
|
return undefined;
|
|
19
19
|
}
|
|
20
20
|
async catch(error) {
|
|
21
|
-
errorHandler(error, this.config);
|
|
21
|
+
await errorHandler(error, this.config);
|
|
22
22
|
return Errors.handle(error);
|
|
23
23
|
}
|
|
24
24
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-command.js","sourceRoot":"","sources":["../../../src/public/node/base-command.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAE,2CAA2C,EAAC,MAAM,oBAAoB,CAAA;AAC5F,OAAO,EAAC,eAAe,EAAC,MAAM,mBAAmB,CAAA;AACjD,OAAO,EAAC,aAAa,EAAC,MAAM,oBAAoB,CAAA;AAChD,OAAO,EAAC,iBAAiB,EAAC,M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,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;QAC5G,MAAM,qBAAqB,GACzB,gBAAgB,CAAC,KAAK,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,gBAAgB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;QAC/F,IAAI,uBAAuB,IAAI,CAAC,qBAAqB,EAAE;YACrD,IAAI,OAAO,KAAK,KAAK,SAAS,EAAE;gBAC9B,IAAI,KAAK,KAAK,IAAI,EAAE;oBAClB,IAAI,CAAC,IAAI,CAAC,KAAK,KAAK,EAAE,CAAC,CAAA;iBACxB;qBAAM;oBACL,MAAM,IAAI,UAAU,CAClB,aAAa,CAAA,0EAA0E,WAAW,CAAC,MAAM,CACvG,KAAK,CACN,YAAY,CACd,CAAA;iBACF;aACF;iBAAM,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;gBAC/B,KAAK,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,KAAK,EAAE,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC,CAAA;aAClE;iBAAM;gBACL,IAAI,CAAC,IAAI,CAAC,KAAK,KAAK,EAAE,EAAE,GAAG,KAAK,EAAE,CAAC,CAAA;aACpC;SACF;KACF;IACD,OAAO,IAAI,CAAA;AACb,CAAC;AAED,eAAe,WAAW,CAAA","sourcesContent":["import {errorHandler, registerCleanBugsnagErrorsFromWithinPlugins} from './error-handler.js'\nimport {loadEnvironment} from './environments.js'\nimport {isDevelopment} from './context/local.js'\nimport {addPublicMetadata} from './metadata.js'\nimport {AbortError} from './error.js'\nimport {renderInfo, renderWarning} from './ui.js'\nimport {outputContent, outputInfo, outputToken} from './output.js'\nimport {terminalSupportsRawMode} from './system.js'\nimport {hashString} from './crypto.js'\nimport {isTruthy} from './context/utilities.js'\nimport {JsonMap} from '../../private/common/json.js'\nimport {underscore} from '../common/string.js'\nimport {Command, Errors} from '@oclif/core'\nimport {FlagOutput, Input, ParserOutput, FlagInput, ArgOutput} from '@oclif/core/lib/interfaces/parser.js'\n\ninterface EnvironmentFlags {\n environment?: string\n path?: string\n}\n\nabstract class BaseCommand extends Command {\n public static analyticsNameOverride(): string | undefined {\n return undefined\n }\n\n public static analyticsStopCommand(): string | undefined {\n return undefined\n }\n\n async catch(error: Error & {exitCode?: number | undefined}): Promise<void> {\n errorHandler(error, this.config)\n return Errors.handle(error)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async init(): Promise<any> {\n this.exitWithTimestampWhenEnvVariablePresent()\n if (!isDevelopment()) {\n // This function runs just prior to `run`\n await registerCleanBugsnagErrorsFromWithinPlugins(this.config)\n }\n this.showNpmFlagWarning()\n return super.init()\n }\n\n // NPM creates an environment variable for every flag passed to a script.\n // This function checks for the presence of any of the available CLI flags\n // and warns the user to use the `--` separator.\n protected showNpmFlagWarning(): void {\n const commandVariables = this.constructor as unknown as {_flags: JsonMap}\n const commandFlags = Object.keys(commandVariables._flags || {})\n const possibleNpmEnvVars = commandFlags.map((key) => `npm_config_${underscore(key).replace(/^no_/, '')}`)\n\n if (possibleNpmEnvVars.some((flag) => process.env[flag] !== undefined)) {\n renderWarning({\n body: [\n 'NPM scripts require an extra',\n {command: '--'},\n 'separator to pass the flags. Example:',\n {command: 'npm run dev -- --reset'},\n ],\n })\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n protected exitWithTimestampWhenEnvVariablePresent() {\n if (isTruthy(process.env.SHOPIFY_CLI_ENV_STARTUP_PERFORMANCE_RUN)) {\n outputInfo(`\n SHOPIFY_CLI_TIMESTAMP_START\n { \"timestamp\": ${Date.now()} }\n SHOPIFY_CLI_TIMESTAMP_END\n `)\n process.exit(0)\n }\n }\n\n protected async parse<\n TFlags extends FlagOutput & {path?: string; verbose?: boolean},\n TGlobalFlags extends FlagOutput,\n TArgs extends ArgOutput,\n >(\n options?: Input<TFlags, TGlobalFlags, TArgs>,\n argv?: string[],\n ): Promise<ParserOutput<TFlags, TGlobalFlags, TArgs> & {argv: string[]}> {\n let result = await super.parse<TFlags, TGlobalFlags, TArgs>(options, argv)\n result = await this.resultWithEnvironment<TFlags, TGlobalFlags, TArgs>(result, options, argv)\n await addFromParsedFlags(result.flags)\n return {...result, ...{argv: result.argv as string[]}}\n }\n\n protected environmentsFilename(): string | undefined {\n // To be re-implemented if needed\n return undefined\n }\n\n protected failMissingNonTTYFlags(flags: FlagOutput, requiredFlags: string[]): void {\n if (terminalSupportsRawMode()) return\n\n requiredFlags.forEach((name: string) => {\n if (!(name in flags)) {\n throw new AbortError(\n outputContent`Flag not specified:\n\n${outputToken.cyan(name)}\n\nThis flag is required in non-interactive terminal environments, such as a CI environment, or when piping input from another process.`,\n 'To resolve this, specify the option in the command, or run the command in an interactive environment such as your local terminal.',\n )\n }\n })\n }\n\n private async resultWithEnvironment<\n TFlags extends FlagOutput & {path?: string; verbose?: boolean},\n TGlobalFlags extends FlagOutput,\n TArgs extends ArgOutput,\n >(\n originalResult: ParserOutput<TFlags, TGlobalFlags, TArgs>,\n options?: Input<TFlags, TGlobalFlags, TArgs>,\n argv?: string[],\n ): Promise<ParserOutput<TFlags, TGlobalFlags, TArgs>> {\n // If no environment is specified, don't modify the results\n const flags = originalResult.flags as EnvironmentFlags\n const environmentsFileName = this.environmentsFilename()\n if (!flags.environment || !environmentsFileName) return originalResult\n\n // If the specified environment isn't found, don't modify the results\n const environment = await loadEnvironment(flags.environment, environmentsFileName, {from: flags.path})\n if (!environment) return originalResult\n\n // Parse using noDefaultsOptions to derive a list of flags specified as\n // command-line arguments.\n const noDefaultsResult = await super.parse<TFlags, TGlobalFlags, TArgs>(noDefaultsOptions(options), argv)\n\n // Add the environment's settings to argv and pass them to `super.parse`. This\n // invokes oclif's validation system without breaking the oclif black box.\n // Replace the original result with this one.\n const result = await super.parse<TFlags, TGlobalFlags, TArgs>(options, [\n // Need to specify argv default because we're merging with argsFromEnvironment.\n ...(argv || this.argv),\n ...argsFromEnvironment<TFlags, TGlobalFlags, TArgs>(environment, options, noDefaultsResult),\n ])\n\n // Report successful application of the environment.\n reportEnvironmentApplication<TFlags, TGlobalFlags, TArgs>(\n noDefaultsResult.flags,\n result.flags,\n flags.environment,\n environment,\n )\n\n return result\n }\n}\n\nexport async function addFromParsedFlags(flags: {path?: string; verbose?: boolean}): Promise<void> {\n await addPublicMetadata(() => ({\n cmd_all_verbose: flags.verbose,\n cmd_all_path_override: flags.path !== undefined,\n cmd_all_path_override_hash: flags.path === undefined ? undefined : hashString(flags.path),\n }))\n}\n\n/**\n * Any flag which is:\n *\n * 1. Present in the final set of flags\n * 2. Specified in the environment\n * 3. Not specified by the user as a command line argument\n *\n * should be reported.\n *\n * It doesn't matter if the environment flag's value was the same as the default; from\n * the user's perspective, they want to know their environment was applied.\n */\nfunction reportEnvironmentApplication<\n TFlags extends FlagOutput,\n TGlobalFlags extends FlagOutput,\n TArgs extends ArgOutput,\n>(\n noDefaultsFlags: ParserOutput<TFlags, TGlobalFlags, TArgs>['flags'],\n flagsWithEnvironments: ParserOutput<TFlags, TGlobalFlags, TArgs>['flags'],\n environmentName: string,\n environment: JsonMap,\n): void {\n const changes: JsonMap = {}\n for (const [name, value] of Object.entries(flagsWithEnvironments)) {\n const userSpecifiedThisFlag = Object.prototype.hasOwnProperty.call(noDefaultsFlags, name)\n const environmentContainsFlag = Object.prototype.hasOwnProperty.call(environment, name)\n if (!userSpecifiedThisFlag && environmentContainsFlag) {\n const valueToReport = name === 'password' ? `********${value.substr(-4)}` : value\n changes[name] = valueToReport\n }\n }\n if (Object.keys(changes).length === 0) return\n\n const items = Object.entries(changes).map(([name, value]) => `${name}: ${value}`)\n renderInfo({\n headline: ['Using applicable flags from', {userInput: environmentName}, 'environment:'],\n body: [{list: {items}}],\n })\n}\n\n/**\n * Strips the defaults from configured flags. For example, if flags contains:\n *\n * ```\n * someFlag: Flags.boolean({\n * description: 'some flag',\n * default: false\n * })\n * ```\n *\n * it becomes:\n *\n * ```\n * someFlag: Flags.boolean({\n * description: 'some flag'\n * })\n * ```\n *\n * If we parse using this configuration, the only specified flags will be those\n * the user actually passed on the command line.\n */\nfunction noDefaultsOptions<TFlags extends FlagOutput, TGlobalFlags extends FlagOutput, TArgs extends ArgOutput>(\n options: Input<TFlags, TGlobalFlags, TArgs> | undefined,\n): Input<TFlags, TGlobalFlags, TArgs> | undefined {\n if (!options?.flags) return options\n return {\n ...options,\n flags: Object.fromEntries(\n Object.entries(options.flags).map(([label, settings]) => {\n const copiedSettings = {...(settings as {default?: unknown})}\n delete copiedSettings.default\n return [label, copiedSettings]\n }),\n ) as FlagInput<TFlags>,\n }\n}\n\n/**\n * Converts the environment's settings to arguments as though passed on the command\n * line, skipping any arguments the user specified on the command line.\n */\nfunction argsFromEnvironment<TFlags extends FlagOutput, TGlobalFlags extends FlagOutput, TArgs extends ArgOutput>(\n environment: JsonMap,\n options: Input<TFlags, TGlobalFlags, TArgs> | undefined,\n noDefaultsResult: ParserOutput<TFlags, TArgs>,\n): string[] {\n const args: string[] = []\n for (const [label, value] of Object.entries(environment)) {\n const flagIsRelevantToCommand = options?.flags && Object.prototype.hasOwnProperty.call(options.flags, label)\n const userSpecifiedThisFlag =\n noDefaultsResult.flags && Object.prototype.hasOwnProperty.call(noDefaultsResult.flags, label)\n if (flagIsRelevantToCommand && !userSpecifiedThisFlag) {\n if (typeof value === 'boolean') {\n if (value === true) {\n args.push(`--${label}`)\n } else {\n throw new AbortError(\n outputContent`Environments can only specify true for boolean flags. Attempted to set ${outputToken.yellow(\n label,\n )} to false.`,\n )\n }\n } else if (Array.isArray(value)) {\n value.forEach((element) => args.push(`--${label}`, `${element}`))\n } else {\n args.push(`--${label}`, `${value}`)\n }\n }\n }\n return args\n}\n\nexport default BaseCommand\n"]}
|
|
1
|
+
{"version":3,"file":"base-command.js","sourceRoot":"","sources":["../../../src/public/node/base-command.ts"],"names":[],"mappings":"AAAA,OAAO,EAA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Aa,EAAE,CAAA;IACzB,KAAK,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,EAAE;QACxD,MAAM,uBAAuB,GAAG,OAAO,EAAE,KAAK,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;QAC5G,MAAM,qBAAqB,GACzB,gBAAgB,CAAC,KAAK,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,gBAAgB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;QAC/F,IAAI,uBAAuB,IAAI,CAAC,qBAAqB,EAAE;YACrD,IAAI,OAAO,KAAK,KAAK,SAAS,EAAE;gBAC9B,IAAI,KAAK,KAAK,IAAI,EAAE;oBAClB,IAAI,CAAC,IAAI,CAAC,KAAK,KAAK,EAAE,CAAC,CAAA;iBACxB;qBAAM;oBACL,MAAM,IAAI,UAAU,CAClB,aAAa,CAAA,0EAA0E,WAAW,CAAC,MAAM,CACvG,KAAK,CACN,YAAY,CACd,CAAA;iBACF;aACF;iBAAM,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;gBAC/B,KAAK,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,KAAK,EAAE,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC,CAAA;aAClE;iBAAM;gBACL,IAAI,CAAC,IAAI,CAAC,KAAK,KAAK,EAAE,EAAE,GAAG,KAAK,EAAE,CAAC,CAAA;aACpC;SACF;KACF;IACD,OAAO,IAAI,CAAA;AACb,CAAC;AAED,eAAe,WAAW,CAAA","sourcesContent":["import {errorHandler, registerCleanBugsnagErrorsFromWithinPlugins} from './error-handler.js'\nimport {loadEnvironment} from './environments.js'\nimport {isDevelopment} from './context/local.js'\nimport {addPublicMetadata} from './metadata.js'\nimport {AbortError} from './error.js'\nimport {renderInfo, renderWarning} from './ui.js'\nimport {outputContent, outputInfo, outputToken} from './output.js'\nimport {terminalSupportsRawMode} from './system.js'\nimport {hashString} from './crypto.js'\nimport {isTruthy} from './context/utilities.js'\nimport {JsonMap} from '../../private/common/json.js'\nimport {underscore} from '../common/string.js'\nimport {Command, Errors} from '@oclif/core'\nimport {FlagOutput, Input, ParserOutput, FlagInput, ArgOutput} from '@oclif/core/lib/interfaces/parser.js'\n\ninterface EnvironmentFlags {\n environment?: string\n path?: string\n}\n\nabstract class BaseCommand extends Command {\n public static analyticsNameOverride(): string | undefined {\n return undefined\n }\n\n public static analyticsStopCommand(): string | undefined {\n return undefined\n }\n\n async catch(error: Error & {exitCode?: number | undefined}): Promise<void> {\n await errorHandler(error, this.config)\n return Errors.handle(error)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async init(): Promise<any> {\n this.exitWithTimestampWhenEnvVariablePresent()\n if (!isDevelopment()) {\n // This function runs just prior to `run`\n await registerCleanBugsnagErrorsFromWithinPlugins(this.config)\n }\n this.showNpmFlagWarning()\n return super.init()\n }\n\n // NPM creates an environment variable for every flag passed to a script.\n // This function checks for the presence of any of the available CLI flags\n // and warns the user to use the `--` separator.\n protected showNpmFlagWarning(): void {\n const commandVariables = this.constructor as unknown as {_flags: JsonMap}\n const commandFlags = Object.keys(commandVariables._flags || {})\n const possibleNpmEnvVars = commandFlags.map((key) => `npm_config_${underscore(key).replace(/^no_/, '')}`)\n\n if (possibleNpmEnvVars.some((flag) => process.env[flag] !== undefined)) {\n renderWarning({\n body: [\n 'NPM scripts require an extra',\n {command: '--'},\n 'separator to pass the flags. Example:',\n {command: 'npm run dev -- --reset'},\n ],\n })\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n protected exitWithTimestampWhenEnvVariablePresent() {\n if (isTruthy(process.env.SHOPIFY_CLI_ENV_STARTUP_PERFORMANCE_RUN)) {\n outputInfo(`\n SHOPIFY_CLI_TIMESTAMP_START\n { \"timestamp\": ${Date.now()} }\n SHOPIFY_CLI_TIMESTAMP_END\n `)\n process.exit(0)\n }\n }\n\n protected async parse<\n TFlags extends FlagOutput & {path?: string; verbose?: boolean},\n TGlobalFlags extends FlagOutput,\n TArgs extends ArgOutput,\n >(\n options?: Input<TFlags, TGlobalFlags, TArgs>,\n argv?: string[],\n ): Promise<ParserOutput<TFlags, TGlobalFlags, TArgs> & {argv: string[]}> {\n let result = await super.parse<TFlags, TGlobalFlags, TArgs>(options, argv)\n result = await this.resultWithEnvironment<TFlags, TGlobalFlags, TArgs>(result, options, argv)\n await addFromParsedFlags(result.flags)\n return {...result, ...{argv: result.argv as string[]}}\n }\n\n protected environmentsFilename(): string | undefined {\n // To be re-implemented if needed\n return undefined\n }\n\n protected failMissingNonTTYFlags(flags: FlagOutput, requiredFlags: string[]): void {\n if (terminalSupportsRawMode()) return\n\n requiredFlags.forEach((name: string) => {\n if (!(name in flags)) {\n throw new AbortError(\n outputContent`Flag not specified:\n\n${outputToken.cyan(name)}\n\nThis flag is required in non-interactive terminal environments, such as a CI environment, or when piping input from another process.`,\n 'To resolve this, specify the option in the command, or run the command in an interactive environment such as your local terminal.',\n )\n }\n })\n }\n\n private async resultWithEnvironment<\n TFlags extends FlagOutput & {path?: string; verbose?: boolean},\n TGlobalFlags extends FlagOutput,\n TArgs extends ArgOutput,\n >(\n originalResult: ParserOutput<TFlags, TGlobalFlags, TArgs>,\n options?: Input<TFlags, TGlobalFlags, TArgs>,\n argv?: string[],\n ): Promise<ParserOutput<TFlags, TGlobalFlags, TArgs>> {\n // If no environment is specified, don't modify the results\n const flags = originalResult.flags as EnvironmentFlags\n const environmentsFileName = this.environmentsFilename()\n if (!flags.environment || !environmentsFileName) return originalResult\n\n // If the specified environment isn't found, don't modify the results\n const environment = await loadEnvironment(flags.environment, environmentsFileName, {from: flags.path})\n if (!environment) return originalResult\n\n // Parse using noDefaultsOptions to derive a list of flags specified as\n // command-line arguments.\n const noDefaultsResult = await super.parse<TFlags, TGlobalFlags, TArgs>(noDefaultsOptions(options), argv)\n\n // Add the environment's settings to argv and pass them to `super.parse`. This\n // invokes oclif's validation system without breaking the oclif black box.\n // Replace the original result with this one.\n const result = await super.parse<TFlags, TGlobalFlags, TArgs>(options, [\n // Need to specify argv default because we're merging with argsFromEnvironment.\n ...(argv || this.argv),\n ...argsFromEnvironment<TFlags, TGlobalFlags, TArgs>(environment, options, noDefaultsResult),\n ])\n\n // Report successful application of the environment.\n reportEnvironmentApplication<TFlags, TGlobalFlags, TArgs>(\n noDefaultsResult.flags,\n result.flags,\n flags.environment,\n environment,\n )\n\n return result\n }\n}\n\nexport async function addFromParsedFlags(flags: {path?: string; verbose?: boolean}): Promise<void> {\n await addPublicMetadata(() => ({\n cmd_all_verbose: flags.verbose,\n cmd_all_path_override: flags.path !== undefined,\n cmd_all_path_override_hash: flags.path === undefined ? undefined : hashString(flags.path),\n }))\n}\n\n/**\n * Any flag which is:\n *\n * 1. Present in the final set of flags\n * 2. Specified in the environment\n * 3. Not specified by the user as a command line argument\n *\n * should be reported.\n *\n * It doesn't matter if the environment flag's value was the same as the default; from\n * the user's perspective, they want to know their environment was applied.\n */\nfunction reportEnvironmentApplication<\n TFlags extends FlagOutput,\n TGlobalFlags extends FlagOutput,\n TArgs extends ArgOutput,\n>(\n noDefaultsFlags: ParserOutput<TFlags, TGlobalFlags, TArgs>['flags'],\n flagsWithEnvironments: ParserOutput<TFlags, TGlobalFlags, TArgs>['flags'],\n environmentName: string,\n environment: JsonMap,\n): void {\n const changes: JsonMap = {}\n for (const [name, value] of Object.entries(flagsWithEnvironments)) {\n const userSpecifiedThisFlag = Object.prototype.hasOwnProperty.call(noDefaultsFlags, name)\n const environmentContainsFlag = Object.prototype.hasOwnProperty.call(environment, name)\n if (!userSpecifiedThisFlag && environmentContainsFlag) {\n const valueToReport = name === 'password' ? `********${value.substr(-4)}` : value\n changes[name] = valueToReport\n }\n }\n if (Object.keys(changes).length === 0) return\n\n const items = Object.entries(changes).map(([name, value]) => `${name}: ${value}`)\n renderInfo({\n headline: ['Using applicable flags from', {userInput: environmentName}, 'environment:'],\n body: [{list: {items}}],\n })\n}\n\n/**\n * Strips the defaults from configured flags. For example, if flags contains:\n *\n * ```\n * someFlag: Flags.boolean({\n * description: 'some flag',\n * default: false\n * })\n * ```\n *\n * it becomes:\n *\n * ```\n * someFlag: Flags.boolean({\n * description: 'some flag'\n * })\n * ```\n *\n * If we parse using this configuration, the only specified flags will be those\n * the user actually passed on the command line.\n */\nfunction noDefaultsOptions<TFlags extends FlagOutput, TGlobalFlags extends FlagOutput, TArgs extends ArgOutput>(\n options: Input<TFlags, TGlobalFlags, TArgs> | undefined,\n): Input<TFlags, TGlobalFlags, TArgs> | undefined {\n if (!options?.flags) return options\n return {\n ...options,\n flags: Object.fromEntries(\n Object.entries(options.flags).map(([label, settings]) => {\n const copiedSettings = {...(settings as {default?: unknown})}\n delete copiedSettings.default\n return [label, copiedSettings]\n }),\n ) as FlagInput<TFlags>,\n }\n}\n\n/**\n * Converts the environment's settings to arguments as though passed on the command\n * line, skipping any arguments the user specified on the command line.\n */\nfunction argsFromEnvironment<TFlags extends FlagOutput, TGlobalFlags extends FlagOutput, TArgs extends ArgOutput>(\n environment: JsonMap,\n options: Input<TFlags, TGlobalFlags, TArgs> | undefined,\n noDefaultsResult: ParserOutput<TFlags, TArgs>,\n): string[] {\n const args: string[] = []\n for (const [label, value] of Object.entries(environment)) {\n const flagIsRelevantToCommand = options?.flags && Object.prototype.hasOwnProperty.call(options.flags, label)\n const userSpecifiedThisFlag =\n noDefaultsResult.flags && Object.prototype.hasOwnProperty.call(noDefaultsResult.flags, label)\n if (flagIsRelevantToCommand && !userSpecifiedThisFlag) {\n if (typeof value === 'boolean') {\n if (value === true) {\n args.push(`--${label}`)\n } else {\n throw new AbortError(\n outputContent`Environments can only specify true for boolean flags. Attempted to set ${outputToken.yellow(\n label,\n )} to false.`,\n )\n }\n } else if (Array.isArray(value)) {\n value.forEach((element) => args.push(`--${label}`, `${element}`))\n } else {\n args.push(`--${label}`, `${value}`)\n }\n }\n }\n return args\n}\n\nexport default BaseCommand\n"]}
|
package/dist/public/node/cli.js
CHANGED
|
@@ -64,13 +64,16 @@ export async function runCLI(options) {
|
|
|
64
64
|
if (isDevelopment()) {
|
|
65
65
|
settings.debug = true;
|
|
66
66
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
67
|
+
try {
|
|
68
|
+
await run(undefined, options.moduleURL);
|
|
69
|
+
await flush();
|
|
70
|
+
printEventsJson();
|
|
71
|
+
// eslint-disable-next-line no-catch-all/no-catch-all
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
await errorHandler(error);
|
|
72
75
|
return Errors.handle(error);
|
|
73
|
-
}
|
|
76
|
+
}
|
|
74
77
|
}
|
|
75
78
|
/**
|
|
76
79
|
* A function for create-x CLIs that automatically runs the "init" command.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../../../src/public/node/cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAC,MAAM,wBAAwB,CAAA;AAC/C,OAAO,EAAC,eAAe,EAAC,MAAM,qCAAqC,CAAA;AACnE,OAAO,EAAC,KAAK,EAAC,MAAM,aAAa,CAAA;AAajC,KAAK,UAAU,oBAAoB;IACjC,MAAM,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAA;IACzC,MAAM,gBAAgB,GAAG,MAAM,CAAC,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAE1D,MAAM,2BAA2B,GAAG,EAAE,CAAA;IACtC,IAAI,gBAAgB,GAAG,2BAA2B,EAAE;QAClD,MAAM,EAAC,aAAa,EAAC,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,CAAA;QAC/C,aAAa,CAAC;YACZ,QAAQ,EAAE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qC;QAClD,GAAG,EAAE,sBAAsB;KAC5B,CAAC;CACH,CAAA;AAED,eAAe,MAAM,CAAA","sourcesContent":["import {isTruthy} from './context/utilities.js'\nimport {printEventsJson} from '../../private/node/demo-recorder.js'\nimport {Flags} from '@oclif/core'\n\n/**\n * IMPORTANT NOTE: Imports in this module are dynamic to ensure that \"setupEnvironmentVariables\" can dynamically\n * set the DEBUG environment variable before the 'debug' package sets up its configuration when modules\n * are loaded statically.\n */\ninterface RunCLIOptions {\n /** The value of import.meta.url of the CLI executable module */\n moduleURL: string\n development: boolean\n}\n\nasync function warnIfOldNodeVersion() {\n const nodeVersion = process.versions.node\n const nodeMajorVersion = Number(nodeVersion.split('.')[0])\n\n const currentSupportedNodeVersion = 18\n if (nodeMajorVersion < currentSupportedNodeVersion) {\n const {renderWarning} = await import('./ui.js')\n renderWarning({\n headline: 'Upgrade to a supported Node version now.',\n body: [\n `Node ${nodeMajorVersion} has reached end-of-life and poses security risks. When you upgrade to a`,\n {\n link: {\n url: 'https://nodejs.dev/en/about/previous-releases',\n label: 'supported version',\n },\n },\n {char: ','},\n \"you'll be able to use Shopify CLI without interruption.\",\n ],\n })\n }\n}\n\nfunction setupEnvironmentVariables(options: Pick<RunCLIOptions, 'development'>) {\n /**\n * By setting DEBUG=* when --verbose is passed we are increasing the\n * verbosity of oclif. Oclif uses debug (https://www.npmjs.com/package/debug)\n * for logging, and it's configured through the DEBUG= environment variable.\n */\n if (process.argv.includes('--verbose')) {\n process.env.DEBUG = process.env.DEBUG ?? '*'\n }\n if (options.development) {\n process.env.SHOPIFY_CLI_ENV = process.env.SHOPIFY_CLI_ENV ?? 'development'\n }\n}\n\nfunction forceNoColor() {\n if (\n process.argv.includes('--no-color') ||\n isTruthy(process.env.NO_COLOR) ||\n isTruthy(process.env.SHOPIFY_FLAG_NO_COLOR) ||\n process.env.TERM === 'dumb'\n ) {\n process.env.FORCE_COLOR = '0'\n }\n}\n\n/**\n * A function that abstracts away setting up the environment and running\n * a CLI\n * @param options - Options.\n */\nexport async function runCLI(options: RunCLIOptions): Promise<void> {\n setupEnvironmentVariables(options)\n forceNoColor()\n await warnIfOldNodeVersion()\n /**\n * These imports need to be dynamic because if they are static\n * they are loaded before we set the DEBUG=* environment variable\n * and therefore it has no effect.\n */\n const {errorHandler} = await import('./error-handler.js')\n const {isDevelopment} = await import('./context/local.js')\n const {run, settings, flush, Errors} = await import('@oclif/core')\n\n if (isDevelopment()) {\n settings.debug = true\n }\n\n run(undefined, options.moduleURL)\n .then(() => flush())\n .then(printEventsJson)\n .catch((error) => {\n errorHandler(error)\n return Errors.handle(error)\n })\n}\n\n/**\n * A function for create-x CLIs that automatically runs the \"init\" command.\n */\nexport async function runCreateCLI(options: RunCLIOptions): Promise<void> {\n setupEnvironmentVariables(options)\n\n const {findUpAndReadPackageJson} = await import('./node-package-manager.js')\n const {moduleDirectory} = await import('./path.js')\n\n const packageJson = await findUpAndReadPackageJson(moduleDirectory(options.moduleURL))\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const packageName = (packageJson.content as any).name as string\n const name = packageName.replace('@shopify/create-', '')\n const initIndex = process.argv.findIndex((arg) => arg.includes('init'))\n if (initIndex === -1) {\n const initIndex =\n process.argv.findIndex((arg) => arg.match(new RegExp(`bin(\\\\/|\\\\\\\\)+(create-${name}|dev|run)`))) + 1\n process.argv.splice(initIndex, 0, 'init')\n }\n await runCLI(options)\n}\n\nexport async function useLocalCLIIfDetected(filepath: string): Promise<boolean> {\n const {environmentVariables} = await import('../../private/node/constants.js')\n const {joinPath: join} = await import('./path.js')\n const {exec} = await import('./system.js')\n\n // Temporary flag while we test out this feature and ensure it won't break anything!\n if (!isTruthy(process.env[environmentVariables.enableCliRedirect])) return false\n\n // Setting an env variable in the child process prevents accidental recursion.\n if (isTruthy(process.env[environmentVariables.skipCliRedirect])) return false\n\n // If already running via package manager, we can assume it's running correctly already.\n if (process.env.npm_config_user_agent) return false\n\n const cliPackage = await localCliPackage()\n if (!cliPackage) return false\n\n const correctExecutablePath = join(cliPackage.path, cliPackage.bin.shopify)\n if (correctExecutablePath === filepath) return false\n try {\n await exec(correctExecutablePath, process.argv.slice(2, process.argv.length), {\n stdio: 'inherit',\n env: {[environmentVariables.skipCliRedirect]: '1'},\n })\n // eslint-disable-next-line no-catch-all/no-catch-all, @typescript-eslint/no-explicit-any\n } catch (processError: any) {\n process.exit(processError.exitCode)\n }\n return true\n}\n\ninterface CliPackageInfo {\n path: string\n bin: {shopify: string}\n}\n\ninterface PackageJSON {\n dependencies?: {[packageName: string]: CliPackageInfo}\n devDependencies?: {[packageName: string]: CliPackageInfo}\n peerDependencies?: {[packageName: string]: CliPackageInfo}\n}\n\nexport async function localCliPackage(): Promise<CliPackageInfo | undefined> {\n const {captureOutput} = await import('./system.js')\n\n let npmListOutput = ''\n let localShopifyCLI: PackageJSON = {}\n try {\n npmListOutput = await captureOutput('npm', ['list', '@shopify/cli', '--json', '-l'])\n localShopifyCLI = JSON.parse(npmListOutput)\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (err) {\n return\n }\n const dependenciesList = {\n ...localShopifyCLI.peerDependencies,\n ...localShopifyCLI.devDependencies,\n ...localShopifyCLI.dependencies,\n }\n return dependenciesList['@shopify/cli']\n}\n\n/**\n * An object that contains the flags that\n * are shared across all the commands.\n */\nexport const globalFlags = {\n 'no-color': Flags.boolean({\n hidden: false,\n description: 'Disable color output.',\n env: 'SHOPIFY_FLAG_NO_COLOR',\n }),\n verbose: Flags.boolean({\n hidden: false,\n description: 'Increase the verbosity of the logs.',\n env: 'SHOPIFY_FLAG_VERBOSE',\n }),\n}\n\nexport default runCLI\n"]}
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../../../src/public/node/cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAC,MAAM,wBAAwB,CAAA;AAC/C,OAAO,EAAC,eAAe,EAAC,MAAM,qCAAqC,CAAA;AACnE,OAAO,EAAC,KAAK,EAAC,MAAM,aAA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,eAAe;QAClC,GAAG,eAAe,CAAC,YAAY;KAChC,CAAA;IACD,OAAO,gBAAgB,CAAC,cAAc,CAAC,CAAA;AACzC,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,UAAU,EAAE,KAAK,CAAC,OAAO,CAAC;QACxB,MAAM,EAAE,KAAK;QACb,WAAW,EAAE,uBAAuB;QACpC,GAAG,EAAE,uBAAuB;KAC7B,CAAC;IACF,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC;QACrB,MAAM,EAAE,KAAK;QACb,WAAW,EAAE,qCAAqC;QAClD,GAAG,EAAE,sBAAsB;KAC5B,CAAC;CACH,CAAA;AAED,eAAe,MAAM,CAAA","sourcesContent":["import {isTruthy} from './context/utilities.js'\nimport {printEventsJson} from '../../private/node/demo-recorder.js'\nimport {Flags} from '@oclif/core'\n\n/**\n * IMPORTANT NOTE: Imports in this module are dynamic to ensure that \"setupEnvironmentVariables\" can dynamically\n * set the DEBUG environment variable before the 'debug' package sets up its configuration when modules\n * are loaded statically.\n */\ninterface RunCLIOptions {\n /** The value of import.meta.url of the CLI executable module */\n moduleURL: string\n development: boolean\n}\n\nasync function warnIfOldNodeVersion() {\n const nodeVersion = process.versions.node\n const nodeMajorVersion = Number(nodeVersion.split('.')[0])\n\n const currentSupportedNodeVersion = 18\n if (nodeMajorVersion < currentSupportedNodeVersion) {\n const {renderWarning} = await import('./ui.js')\n renderWarning({\n headline: 'Upgrade to a supported Node version now.',\n body: [\n `Node ${nodeMajorVersion} has reached end-of-life and poses security risks. When you upgrade to a`,\n {\n link: {\n url: 'https://nodejs.dev/en/about/previous-releases',\n label: 'supported version',\n },\n },\n {char: ','},\n \"you'll be able to use Shopify CLI without interruption.\",\n ],\n })\n }\n}\n\nfunction setupEnvironmentVariables(options: Pick<RunCLIOptions, 'development'>) {\n /**\n * By setting DEBUG=* when --verbose is passed we are increasing the\n * verbosity of oclif. Oclif uses debug (https://www.npmjs.com/package/debug)\n * for logging, and it's configured through the DEBUG= environment variable.\n */\n if (process.argv.includes('--verbose')) {\n process.env.DEBUG = process.env.DEBUG ?? '*'\n }\n if (options.development) {\n process.env.SHOPIFY_CLI_ENV = process.env.SHOPIFY_CLI_ENV ?? 'development'\n }\n}\n\nfunction forceNoColor() {\n if (\n process.argv.includes('--no-color') ||\n isTruthy(process.env.NO_COLOR) ||\n isTruthy(process.env.SHOPIFY_FLAG_NO_COLOR) ||\n process.env.TERM === 'dumb'\n ) {\n process.env.FORCE_COLOR = '0'\n }\n}\n\n/**\n * A function that abstracts away setting up the environment and running\n * a CLI\n * @param options - Options.\n */\nexport async function runCLI(options: RunCLIOptions): Promise<void> {\n setupEnvironmentVariables(options)\n forceNoColor()\n await warnIfOldNodeVersion()\n /**\n * These imports need to be dynamic because if they are static\n * they are loaded before we set the DEBUG=* environment variable\n * and therefore it has no effect.\n */\n const {errorHandler} = await import('./error-handler.js')\n const {isDevelopment} = await import('./context/local.js')\n const {run, settings, flush, Errors} = await import('@oclif/core')\n\n if (isDevelopment()) {\n settings.debug = true\n }\n\n try {\n await run(undefined, options.moduleURL)\n await flush()\n printEventsJson()\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n await errorHandler(error as Error)\n return Errors.handle(error as Error)\n }\n}\n\n/**\n * A function for create-x CLIs that automatically runs the \"init\" command.\n */\nexport async function runCreateCLI(options: RunCLIOptions): Promise<void> {\n setupEnvironmentVariables(options)\n\n const {findUpAndReadPackageJson} = await import('./node-package-manager.js')\n const {moduleDirectory} = await import('./path.js')\n\n const packageJson = await findUpAndReadPackageJson(moduleDirectory(options.moduleURL))\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const packageName = (packageJson.content as any).name as string\n const name = packageName.replace('@shopify/create-', '')\n const initIndex = process.argv.findIndex((arg) => arg.includes('init'))\n if (initIndex === -1) {\n const initIndex =\n process.argv.findIndex((arg) => arg.match(new RegExp(`bin(\\\\/|\\\\\\\\)+(create-${name}|dev|run)`))) + 1\n process.argv.splice(initIndex, 0, 'init')\n }\n await runCLI(options)\n}\n\nexport async function useLocalCLIIfDetected(filepath: string): Promise<boolean> {\n const {environmentVariables} = await import('../../private/node/constants.js')\n const {joinPath: join} = await import('./path.js')\n const {exec} = await import('./system.js')\n\n // Temporary flag while we test out this feature and ensure it won't break anything!\n if (!isTruthy(process.env[environmentVariables.enableCliRedirect])) return false\n\n // Setting an env variable in the child process prevents accidental recursion.\n if (isTruthy(process.env[environmentVariables.skipCliRedirect])) return false\n\n // If already running via package manager, we can assume it's running correctly already.\n if (process.env.npm_config_user_agent) return false\n\n const cliPackage = await localCliPackage()\n if (!cliPackage) return false\n\n const correctExecutablePath = join(cliPackage.path, cliPackage.bin.shopify)\n if (correctExecutablePath === filepath) return false\n try {\n await exec(correctExecutablePath, process.argv.slice(2, process.argv.length), {\n stdio: 'inherit',\n env: {[environmentVariables.skipCliRedirect]: '1'},\n })\n // eslint-disable-next-line no-catch-all/no-catch-all, @typescript-eslint/no-explicit-any\n } catch (processError: any) {\n process.exit(processError.exitCode)\n }\n return true\n}\n\ninterface CliPackageInfo {\n path: string\n bin: {shopify: string}\n}\n\ninterface PackageJSON {\n dependencies?: {[packageName: string]: CliPackageInfo}\n devDependencies?: {[packageName: string]: CliPackageInfo}\n peerDependencies?: {[packageName: string]: CliPackageInfo}\n}\n\nexport async function localCliPackage(): Promise<CliPackageInfo | undefined> {\n const {captureOutput} = await import('./system.js')\n\n let npmListOutput = ''\n let localShopifyCLI: PackageJSON = {}\n try {\n npmListOutput = await captureOutput('npm', ['list', '@shopify/cli', '--json', '-l'])\n localShopifyCLI = JSON.parse(npmListOutput)\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (err) {\n return\n }\n const dependenciesList = {\n ...localShopifyCLI.peerDependencies,\n ...localShopifyCLI.devDependencies,\n ...localShopifyCLI.dependencies,\n }\n return dependenciesList['@shopify/cli']\n}\n\n/**\n * An object that contains the flags that\n * are shared across all the commands.\n */\nexport const globalFlags = {\n 'no-color': Flags.boolean({\n hidden: false,\n description: 'Disable color output.',\n env: 'SHOPIFY_FLAG_NO_COLOR',\n }),\n verbose: Flags.boolean({\n hidden: false,\n description: 'Increase the verbosity of the logs.',\n env: 'SHOPIFY_FLAG_VERBOSE',\n }),\n}\n\nexport default runCLI\n"]}
|