@shopify/cli-kit 4.0.0 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/private/node/api/headers.js +1 -1
- package/dist/private/node/api/headers.js.map +1 -1
- package/dist/private/node/constants.d.ts +0 -1
- package/dist/private/node/constants.js +0 -1
- package/dist/private/node/constants.js.map +1 -1
- package/dist/public/common/string.js +7 -6
- 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/context/local.d.ts +0 -7
- package/dist/public/node/context/local.js +18 -9
- package/dist/public/node/context/local.js.map +1 -1
- package/dist/public/node/git.js +8 -1
- package/dist/public/node/git.js.map +1 -1
- package/dist/public/node/import-extractor.js +4 -3
- package/dist/public/node/import-extractor.js.map +1 -1
- package/dist/public/node/output.js +2 -0
- package/dist/public/node/output.js.map +1 -1
- package/dist/public/node/system.js +2 -42
- package/dist/public/node/system.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<img src="https://img.shields.io/badge/License-MIT-green.svg" alt="License">
|
|
6
6
|
<a href="https://github.com/Shopify/cli/actions/workflows/shopify-cli.yml"></a>
|
|
7
7
|
|
|
8
|
-
With the Shopify command line interface (Shopify CLI
|
|
8
|
+
With the Shopify command line interface (Shopify CLI), you can:
|
|
9
9
|
- initialize, build, dev, and deploy Shopify apps, extensions, functions and themes
|
|
10
10
|
- build custom storefronts and manage their hosting
|
|
11
11
|
|
|
@@ -39,7 +39,7 @@ To work with themes, the CLI needs to be installed globally with:
|
|
|
39
39
|
|
|
40
40
|
- `npm install -g @shopify/cli`
|
|
41
41
|
|
|
42
|
-
You can also
|
|
42
|
+
You can also install it through Homebrew on macOS: `brew tap shopify/shopify && brew install shopify-cli`
|
|
43
43
|
|
|
44
44
|
Learn more in the docs: [Shopify CLI for themes](https://shopify.dev/docs/storefronts/themes/tools/cli)
|
|
45
45
|
|
|
@@ -28,7 +28,7 @@ export function sanitizedHeadersOutput(headers) {
|
|
|
28
28
|
const sanitized = {};
|
|
29
29
|
const keywords = ['token', 'authorization', 'subject_token', 'cookie'];
|
|
30
30
|
Object.keys(headers).forEach((header) => {
|
|
31
|
-
if (keywords.find((keyword) => header.
|
|
31
|
+
if (keywords.find((keyword) => header.toLowerCase().includes(keyword)) === undefined) {
|
|
32
32
|
sanitized[header] = headers[header];
|
|
33
33
|
}
|
|
34
34
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"headers.js","sourceRoot":"","sources":["../../../../src/private/node/api/headers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,eAAe,EAAC,MAAM,mCAAmC,CAAA;AACjE,OAAO,EAAC,aAAa,EAAC,MAAM,uCAAuC,CAAA;AACnE,OAAO,EAAC,UAAU,EAAC,MAAM,+BAA+B,CAAA;AACxD,OAAO,KAAK,MAAM,OAAO,CAAA;AAEzB,MAAM,kBAAmB,SAAQ,UAAU;IAEzC,YAAmB,OAAe,EAAE,UAAkB;QACpD,MAAM,UAAU,GACd,UAAU,KAAK,GAAG;YAChB,CAAC,CAAC,oFAAoF;YACtF,CAAC,CAAC,SAAS,CAAA;QACf,KAAK,CAAC,OAAO,EAAE,UAAU,CAAC,CAAA;QAC1B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;IAC9B,CAAC;CACF;AACD,MAAM,OAAO,kBAAmB,SAAQ,kBAAkB;IAIxD,8DAA8D;IAC9D,YAAmB,OAAe,EAAE,UAAkB,EAAE,MAAc;QACpE,KAAK,CAAC,OAAO,EAAE,UAAU,CAAC,CAAA;QAC1B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,KAAK,GAAG,SAAS,CAAA;IACxB,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,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AAChB,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU;IAC9B,OAAO,IAAI,KAAK,CAAC,KAAK,CAAC;QACrB,kBAAkB,EAAE,IAAI;QACxB,SAAS,EAAE,IAAI;KAChB,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import {CLI_KIT_VERSION} from '../../../public/common/version.js'\nimport {firstPartyDev} from '../../../public/node/context/local.js'\nimport {AbortError} from '../../../public/node/error.js'\nimport https from 'https'\n\nclass RequestClientError extends AbortError {\n statusCode: number\n public constructor(message: string, statusCode: number) {\n const tryMessage =\n statusCode === 403\n ? 'Ensure you are using the correct account. You can switch with `shopify auth login`'\n : undefined\n super(message, tryMessage)\n this.statusCode = statusCode\n }\n}\nexport class GraphQLClientError extends RequestClientError {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n errors?: any[]\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public constructor(message: string, statusCode: number, errors?: any[]) {\n super(message, statusCode)\n this.errors = errors\n this.stack = undefined\n }\n}\n\n/**\n * Removes the sensitive data from the headers and outputs them as a string.\n * @param headers - HTTP headers.\n * @returns A sanitized version of the headers as a string.\n */\nexport function sanitizedHeadersOutput(headers: Record<string, string>): string {\n const sanitized: Record<string, string> = {}\n const keywords = ['token', 'authorization', 'subject_token', 'cookie']\n Object.keys(headers).forEach((header) => {\n if (keywords.find((keyword) => header.toLowerCase().includes(keyword)) === undefined) {\n sanitized[header] = headers[header]!\n }\n })\n return Object.keys(sanitized)\n .map((header) => {\n return ` - ${header}: ${sanitized[header]}`\n })\n .join('\\n')\n}\n\nexport function buildHeaders(token?: string): Record<string, string> {\n const userAgent = `Shopify CLI; v=${CLI_KIT_VERSION}`\n\n const headers: Record<string, string> = {\n 'User-Agent': userAgent,\n 'Keep-Alive': 'timeout=30',\n // 'Sec-CH-UA': secCHUA, This header requires the Git sha.\n 'Sec-CH-UA-PLATFORM': process.platform,\n 'Content-Type': 'application/json',\n ...(firstPartyDev() && {'X-Shopify-Cli-Employee': '1'}),\n }\n if (token) {\n const authString = token.match(/^shp(at|ua|ca|tka)/) ? token : `Bearer ${token}`\n\n headers.authorization = authString\n headers['X-Shopify-Access-Token'] = authString\n }\n\n return headers\n}\n\n/**\n * This utility function returns the https.Agent to use for a given service.\n */\nexport async function httpsAgent(): Promise<https.Agent> {\n return new https.Agent({\n rejectUnauthorized: true,\n keepAlive: true,\n })\n}\n"]}
|
|
@@ -17,7 +17,6 @@ export const environmentVariables = {
|
|
|
17
17
|
enableCliRedirect: 'SHOPIFY_CLI_ENABLE_CLI_REDIRECT',
|
|
18
18
|
env: 'SHOPIFY_CLI_ENV',
|
|
19
19
|
firstPartyDev: 'SHOPIFY_CLI_1P_DEV',
|
|
20
|
-
hostedApps: 'HOSTED_APPS',
|
|
21
20
|
noAnalytics: 'SHOPIFY_CLI_NO_ANALYTICS',
|
|
22
21
|
optOutInstrumentation: 'OPT_OUT_INSTRUMENTATION',
|
|
23
22
|
appAutomationToken: 'SHOPIFY_APP_AUTOMATION_TOKEN',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/private/node/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAC,MAAM,2BAA2B,CAAA;AAClD,OAAO,QAAQ,MAAM,WAAW,CAAA;AAEhC,MAAM,UAAU,GAAG,aAAa,CAAA;AAEhC,MAAM,WAAW,GAAG,GAAG,EAAE;IACvB,IAAI,OAAO,CAAC,GAAG,CAAC,cAAc;QAAE,OAAO,OAAO,CAAC,GAAG,CAAC,cAAc,CAAA;IACjE,OAAO,QAAQ,CAAC,UAAU,CAAC,CAAC,KAAK,CAAA;AACnC,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,EAAE;IAC7B,OAAO,QAAQ,CAAC,UAAU,CAAC,CAAC,GAAG,CAAA;AACjC,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,oBAAoB,GAAG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;AAE/D,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAC,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,EAAC,IAAI,EAAE,CAAC,EAAC,EAAC,CAAA;AAElE,MAAM,CAAC,MAAM,oBAAoB,GAC/B,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,oBAAoB,CAAC,IAAI,2BAA2B,CAAA","sourcesContent":["import {joinPath} from '../../public/node/path.js'\nimport envPaths from 'env-paths'\n\nconst identifier = 'shopify-cli'\n\nconst cacheFolder = () => {\n if (process.env.XDG_CACHE_HOME) return process.env.XDG_CACHE_HOME\n return envPaths(identifier).cache\n}\n\nexport const logsFolder = () => {\n return envPaths(identifier).log\n}\n\nexport const environmentVariables = {\n alwaysLogAnalytics: 'SHOPIFY_CLI_ALWAYS_LOG_ANALYTICS',\n alwaysLogMetrics: 'SHOPIFY_CLI_ALWAYS_LOG_METRICS',\n deviceAuth: 'SHOPIFY_CLI_DEVICE_AUTH',\n doctor: 'SHOPIFY_CLI_DOCTOR',\n enableCliRedirect: 'SHOPIFY_CLI_ENABLE_CLI_REDIRECT',\n env: 'SHOPIFY_CLI_ENV',\n firstPartyDev: 'SHOPIFY_CLI_1P_DEV',\n noAnalytics: 'SHOPIFY_CLI_NO_ANALYTICS',\n optOutInstrumentation: 'OPT_OUT_INSTRUMENTATION',\n appAutomationToken: 'SHOPIFY_APP_AUTOMATION_TOKEN',\n partnersToken: 'SHOPIFY_CLI_PARTNERS_TOKEN',\n runAsUser: 'SHOPIFY_RUN_AS_USER',\n serviceEnv: 'SHOPIFY_SERVICE_ENV',\n skipCliRedirect: 'SHOPIFY_CLI_SKIP_CLI_REDIRECT',\n spinInstance: 'SPIN_INSTANCE',\n themeToken: 'SHOPIFY_CLI_THEME_TOKEN',\n unitTest: 'SHOPIFY_UNIT_TEST',\n verbose: 'SHOPIFY_FLAG_VERBOSE',\n // Variables to detect if the CLI is running in a cloud environment\n codespaces: 'CODESPACES',\n codespaceName: 'CODESPACE_NAME',\n codespacePortForwardingDomain: 'GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN',\n gitpod: 'GITPOD_WORKSPACE_URL',\n cloudShell: 'CLOUD_SHELL',\n spinAppPort: 'SERVER_PORT',\n spinAppHost: 'SPIN_APP_HOST',\n organization: 'SHOPIFY_CLI_ORGANIZATION',\n identityToken: 'SHOPIFY_CLI_IDENTITY_TOKEN',\n refreshToken: 'SHOPIFY_CLI_REFRESH_TOKEN',\n otelURL: 'SHOPIFY_CLI_OTEL_EXPORTER_OTLP_ENDPOINT',\n themeKitAccessDomain: 'SHOPIFY_CLI_THEME_KIT_ACCESS_DOMAIN',\n json: 'SHOPIFY_FLAG_JSON',\n neverUsePartnersApi: 'SHOPIFY_CLI_NEVER_USE_PARTNERS_API',\n skipNetworkLevelRetry: 'SHOPIFY_CLI_SKIP_NETWORK_LEVEL_RETRY',\n maxRequestTimeForNetworkCalls: 'SHOPIFY_CLI_MAX_REQUEST_TIME_FOR_NETWORK_CALLS',\n disableImportScanning: 'SHOPIFY_CLI_DISABLE_IMPORT_SCANNING',\n}\n\nexport const defaultThemeKitAccessDomain = 'theme-kit-access.shopifyapps.com'\n\nexport const systemEnvironmentVariables = {\n backendPort: 'BACKEND_PORT',\n}\n\nexport const pathConstants = {\n executables: {\n dev: '/opt/dev/bin/dev',\n },\n directories: {\n cache: {\n path: () => {\n return cacheFolder()\n },\n vendor: {\n path: () => {\n return joinPath(cacheFolder(), 'vendor')\n },\n binaries: () => {\n return joinPath(cacheFolder(), 'vendor', 'binaries')\n },\n },\n },\n },\n}\n\nexport const sessionConstants = {\n expirationTimeMarginInMinutes: 4,\n}\n\nexport const bugsnagApiKey = '9e1e6889176fd0c795d5c659225e0fae'\n\nexport const reportingRateLimit = {limit: 300, timeout: {days: 1}}\n\nexport const themeKitAccessDomain =\n process.env[environmentVariables.themeKitAccessDomain] ?? defaultThemeKitAccessDomain\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { takeRandomFromArray } from './array.js';
|
|
1
|
+
import { takeRandomFromArray, uniq } from './array.js';
|
|
2
2
|
import { unstyled } from '../node/output.js';
|
|
3
3
|
import { camelCase, capitalCase, constantCase, paramCase, snakeCase, pascalCase } from 'change-case';
|
|
4
4
|
const SAFE_RANDOM_BUSINESS_ADJECTIVES = [
|
|
@@ -368,11 +368,12 @@ export function pascalize(str) {
|
|
|
368
368
|
export function normalizeDelimitedString(delimitedString, delimiter = ',') {
|
|
369
369
|
if (!delimitedString)
|
|
370
370
|
return;
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
371
|
+
return uniq(delimitedString
|
|
372
|
+
.split(delimiter)
|
|
373
|
+
.map((item) => item.trim())
|
|
374
|
+
.filter((item) => item !== ''))
|
|
375
|
+
.sort()
|
|
376
|
+
.join(delimiter);
|
|
376
377
|
}
|
|
377
378
|
/**
|
|
378
379
|
* Given two dates, it returns a human-readable string representing the time elapsed between them.
|
|
@@ -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,mBAAmB,CAAA;AAG1C,OAAO,EAAC,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAC,MAAM,aAAa,CAAA;AAElG,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;IAC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Ac,CAAC,IAAI,EAAE,KAAK,CAAC,MAAM,CAAA;AAC7C,CAAC;AAED,SAAS,cAAc,CAAC,KAAa,EAAE,IAAY;IACjD,OAAO,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,EAAE,CAAA;AACpD,CAAC","sourcesContent":["import {takeRandomFromArray} from './array.js'\nimport {unstyled} from '../node/output.js'\nimport {Token, TokenItem} from '../../private/node/ui/components/TokenizedText.js'\n\nimport {camelCase, capitalCase, 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 '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\nconst NAME_FAMILIES: Record<RandomNameFamily, {adjectives: string[]; nouns: string[]}> = {\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\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 return `${takeRandomFromArray(NAME_FAMILIES[family].adjectives)}-${takeRandomFromArray(NAME_FAMILIES[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 if (maybeInt === undefined) return undefined\n const asInt = Number.parseInt(maybeInt, 10)\n return Number.isNaN(asInt) ? undefined : 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 capitalCase.\n *\n * @param input - String to transform.\n * @returns The transformed string.\n */\nexport function capitalizeWords(input: string): string {\n return capitalCase(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 date in UTC ISO String format, return a formatted string in local time like \"2021-01-01 12:00:00\".\n *\n * @param dateString - UTC ISO Date String.\n * @returns The transformed string in local system time.\n */\nexport function formatLocalDate(dateString: string): string {\n const dateObj = new Date(dateString)\n const localDate = new Date(\n Date.UTC(\n dateObj.getFullYear(),\n dateObj.getMonth(),\n dateObj.getDate(),\n dateObj.getHours(),\n dateObj.getMinutes(),\n dateObj.getSeconds(),\n ),\n )\n return formatDate(localDate)\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\n/**\n * Given a string that represents a list of delimited tokens, it returns the normalized string representing the same\n * list, without empty elements, sorted, and with no duplicates.\n *\n * @param delimitedString - String to normalize.\n * @param delimiter - Delimiter used to split the string into tokens.\n * @returns String with the normalized list of tokens.\n */\nexport function normalizeDelimitedString(delimitedString?: string, delimiter = ','): string | undefined {\n if (!delimitedString) return\n\n const items = delimitedString.split(delimiter).map((value) => value.trim())\n const nonEmptyItems = items.filter((value) => value !== '')\n const sortedItems = nonEmptyItems.sort()\n const uniqueSortedItems = [...new Set(sortedItems)]\n\n return uniqueSortedItems.join(delimiter)\n}\n\n/**\n * Given two dates, it returns a human-readable string representing the time elapsed between them.\n *\n * @param from - Start date.\n * @param to - End date.\n * @returns A string like \"5 minutes ago\" or \"2 days ago\".\n */\nexport function timeAgo(from: Date, to: Date): string {\n const seconds = Math.floor((to.getTime() - from.getTime()) / 1000)\n if (seconds < 60) return `${formatTimeUnit(seconds, 'second')} ago`\n\n const minutes = Math.floor(seconds / 60)\n if (minutes < 60) return `${formatTimeUnit(minutes, 'minute')} ago`\n\n const hours = Math.floor(minutes / 60)\n if (hours < 24) return `${formatTimeUnit(hours, 'hour')} ago`\n\n const days = Math.floor(hours / 24)\n return `${formatTimeUnit(days, 'day')} ago`\n}\n\nfunction formatTimeUnit(count: number, unit: string): string {\n return `${count} ${unit}${count === 1 ? '' : 's'}`\n}\n"]}
|
|
1
|
+
{"version":3,"file":"string.js","sourceRoot":"","sources":["../../../src/public/common/string.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,mBAAmB,EAAE,IAAI,EAAC,MAAM,YAAY,CAAA;AACpD,OAAO,EAAC,QAAQ,EAAC,MAAM,mBAAmB,CAAA;AAG1C,OAAO,EAAC,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAC,MAAM,aAAa,CAAA;AAElG,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,S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AC,KAAK,CAAC,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC,GAAG,IAAI,CAAC,CAAA;IAClE,IAAI,OAAO,GAAG,EAAE;QAAE,OAAO,GAAG,cAAc,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAA;IAEnE,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC,CAAA;IACxC,IAAI,OAAO,GAAG,EAAE;QAAE,OAAO,GAAG,cAAc,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAA;IAEnE,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC,CAAA;IACtC,IAAI,KAAK,GAAG,EAAE;QAAE,OAAO,GAAG,cAAc,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,CAAA;IAE7D,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,EAAE,CAAC,CAAA;IACnC,OAAO,GAAG,cAAc,CAAC,IAAI,EAAE,KAAK,CAAC,MAAM,CAAA;AAC7C,CAAC;AAED,SAAS,cAAc,CAAC,KAAa,EAAE,IAAY;IACjD,OAAO,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,EAAE,CAAA;AACpD,CAAC","sourcesContent":["import {takeRandomFromArray, uniq} from './array.js'\nimport {unstyled} from '../node/output.js'\nimport {Token, TokenItem} from '../../private/node/ui/components/TokenizedText.js'\n\nimport {camelCase, capitalCase, 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 '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\nconst NAME_FAMILIES: Record<RandomNameFamily, {adjectives: string[]; nouns: string[]}> = {\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\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 return `${takeRandomFromArray(NAME_FAMILIES[family].adjectives)}-${takeRandomFromArray(NAME_FAMILIES[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 if (maybeInt === undefined) return undefined\n const asInt = Number.parseInt(maybeInt, 10)\n return Number.isNaN(asInt) ? undefined : 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 capitalCase.\n *\n * @param input - String to transform.\n * @returns The transformed string.\n */\nexport function capitalizeWords(input: string): string {\n return capitalCase(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 date in UTC ISO String format, return a formatted string in local time like \"2021-01-01 12:00:00\".\n *\n * @param dateString - UTC ISO Date String.\n * @returns The transformed string in local system time.\n */\nexport function formatLocalDate(dateString: string): string {\n const dateObj = new Date(dateString)\n const localDate = new Date(\n Date.UTC(\n dateObj.getFullYear(),\n dateObj.getMonth(),\n dateObj.getDate(),\n dateObj.getHours(),\n dateObj.getMinutes(),\n dateObj.getSeconds(),\n ),\n )\n return formatDate(localDate)\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\n/**\n * Given a string that represents a list of delimited tokens, it returns the normalized string representing the same\n * list, without empty elements, sorted, and with no duplicates.\n *\n * @param delimitedString - String to normalize.\n * @param delimiter - Delimiter used to split the string into tokens.\n * @returns String with the normalized list of tokens.\n */\nexport function normalizeDelimitedString(delimitedString?: string, delimiter = ','): string | undefined {\n if (!delimitedString) return\n\n return uniq(\n delimitedString\n .split(delimiter)\n .map((item) => item.trim())\n .filter((item) => item !== ''),\n )\n .sort()\n .join(delimiter)\n}\n\n/**\n * Given two dates, it returns a human-readable string representing the time elapsed between them.\n *\n * @param from - Start date.\n * @param to - End date.\n * @returns A string like \"5 minutes ago\" or \"2 days ago\".\n */\nexport function timeAgo(from: Date, to: Date): string {\n const seconds = Math.floor((to.getTime() - from.getTime()) / 1000)\n if (seconds < 60) return `${formatTimeUnit(seconds, 'second')} ago`\n\n const minutes = Math.floor(seconds / 60)\n if (minutes < 60) return `${formatTimeUnit(minutes, 'minute')} ago`\n\n const hours = Math.floor(minutes / 60)\n if (hours < 24) return `${formatTimeUnit(hours, 'hour')} ago`\n\n const days = Math.floor(hours / 24)\n return `${formatTimeUnit(days, 'day')} ago`\n}\n\nfunction formatTimeUnit(count: number, unit: string): string {\n return `${count} ${unit}${count === 1 ? '' : 's'}`\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const CLI_KIT_VERSION = "4.
|
|
1
|
+
export declare const CLI_KIT_VERSION = "4.1.0";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export const CLI_KIT_VERSION = '4.
|
|
1
|
+
export const CLI_KIT_VERSION = '4.1.0';
|
|
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,OAAO,CAAA","sourcesContent":["export const CLI_KIT_VERSION = '4.
|
|
1
|
+
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/public/common/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,eAAe,GAAG,OAAO,CAAA","sourcesContent":["export const CLI_KIT_VERSION = '4.1.0'\n"]}
|
|
@@ -42,13 +42,6 @@ export declare function isShopify(env?: NodeJS.ProcessEnv): Promise<boolean>;
|
|
|
42
42
|
* @returns True if the SHOPIFY_UNIT_TEST environment variable is truthy.
|
|
43
43
|
*/
|
|
44
44
|
export declare function isUnitTest(env?: NodeJS.ProcessEnv): boolean;
|
|
45
|
-
/**
|
|
46
|
-
* Returns true if the CLI is running in hosted apps mode.
|
|
47
|
-
*
|
|
48
|
-
* @param env - The environment variables from the environment of the current process.
|
|
49
|
-
* @returns True if the HOSTED_APPS environment variable is truthy.
|
|
50
|
-
*/
|
|
51
|
-
export declare function isHostedAppsMode(env?: NodeJS.ProcessEnv): boolean;
|
|
52
45
|
/**
|
|
53
46
|
* Returns true if reporting analytics is enabled.
|
|
54
47
|
*
|
|
@@ -29,6 +29,14 @@ export function isTerminalInteractive() {
|
|
|
29
29
|
export function homeDirectory() {
|
|
30
30
|
return homedir();
|
|
31
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* Memoized value for the verbose check.
|
|
34
|
+
*/
|
|
35
|
+
let memoizedIsVerbose;
|
|
36
|
+
/**
|
|
37
|
+
* Memoized value for the unit test check.
|
|
38
|
+
*/
|
|
39
|
+
let memoizedIsUnitTest;
|
|
32
40
|
/**
|
|
33
41
|
* Returns true if the CLI is running in debug mode.
|
|
34
42
|
*
|
|
@@ -45,6 +53,11 @@ export function isDevelopment(env = process.env) {
|
|
|
45
53
|
* @returns True if SHOPIFY_FLAG_VERBOSE is truthy or the flag --verbose has been passed.
|
|
46
54
|
*/
|
|
47
55
|
export function isVerbose(env = process.env) {
|
|
56
|
+
if (env === process.env) {
|
|
57
|
+
// Memoize the result to avoid repeated scans of process.argv and env lookups
|
|
58
|
+
// in high-frequency paths like outputDebug.
|
|
59
|
+
return (memoizedIsVerbose ?? (memoizedIsVerbose = isTruthy(env[environmentVariables.verbose]) || process.argv.includes('--verbose')));
|
|
60
|
+
}
|
|
48
61
|
return isTruthy(env[environmentVariables.verbose]) || process.argv.includes('--verbose');
|
|
49
62
|
}
|
|
50
63
|
/**
|
|
@@ -70,17 +83,13 @@ export async function isShopify(env = process.env) {
|
|
|
70
83
|
* @returns True if the SHOPIFY_UNIT_TEST environment variable is truthy.
|
|
71
84
|
*/
|
|
72
85
|
export function isUnitTest(env = process.env) {
|
|
86
|
+
if (env === process.env) {
|
|
87
|
+
// Memoize the result as SHOPIFY_UNIT_TEST is static during execution
|
|
88
|
+
// and checked frequently to suppress output.
|
|
89
|
+
return (memoizedIsUnitTest ?? (memoizedIsUnitTest = isTruthy(env[environmentVariables.unitTest])));
|
|
90
|
+
}
|
|
73
91
|
return isTruthy(env[environmentVariables.unitTest]);
|
|
74
92
|
}
|
|
75
|
-
/**
|
|
76
|
-
* Returns true if the CLI is running in hosted apps mode.
|
|
77
|
-
*
|
|
78
|
-
* @param env - The environment variables from the environment of the current process.
|
|
79
|
-
* @returns True if the HOSTED_APPS environment variable is truthy.
|
|
80
|
-
*/
|
|
81
|
-
export function isHostedAppsMode(env = process.env) {
|
|
82
|
-
return isTruthy(env[environmentVariables.hostedApps]);
|
|
83
|
-
}
|
|
84
93
|
/**
|
|
85
94
|
* Returns true if reporting analytics is enabled.
|
|
86
95
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local.js","sourceRoot":"","sources":["../../../../src/public/node/context/local.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAC,MAAM,gBAAgB,CAAA;AACvC,OAAO,EAAC,aAAa,EAAE,KAAK,EAAW,MAAM,4CAA4C,CAAA;AACzF,OAAO,EAAC,2BAA2B,EAAE,oBAAoB,EAAE,aAAa,EAAC,MAAM,oCAAoC,CAAA;AACnH,OAAO,UAAU,MAAM,YAAY,CAAA;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Set, Metadata} from '../../../private/node/context/utilities.js'\nimport {defaultThemeKitAccessDomain, environmentVariables, pathConstants} from '../../../private/node/constants.js'\nimport macaddress from 'macaddress'\nimport {homedir} from 'os'\n\n// Dynamic imports to avoid circular dependency: context/local → fs → output → context/local\n// fileExists and exec are only used in specific async functions, not at module init.\nasync function lazyFileExists(path: string): Promise<boolean> {\n const {fileExists} = await import('../fs.js')\n return fileExists(path)\n}\n\nasync function lazyExec(command: string, args: string[]): Promise<void> {\n const {exec} = await import('../system.js')\n await exec(command, args)\n}\n\n/**\n * It returns true if the terminal is interactive.\n *\n * @returns True if the terminal is interactive.\n */\nexport function isTerminalInteractive(): boolean {\n return Boolean(process.stdout.isTTY && process.env.TERM !== 'dumb' && !('CI' in process.env))\n}\n\n/**\n * Returns the path to the user's home directory.\n *\n * @returns The path to the user's home directory.\n */\nexport function homeDirectory(): string {\n return homedir()\n}\n\n/**\n * Returns true if the CLI is running in debug mode.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True if SHOPIFY_ENV is development.\n */\nexport function isDevelopment(env = process.env): boolean {\n return env[environmentVariables.env] === 'development'\n}\n\n/**\n * Returns true if the CLI is running in verbose mode.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True if SHOPIFY_FLAG_VERBOSE is truthy or the flag --verbose has been passed.\n */\nexport function isVerbose(env = process.env): boolean {\n return isTruthy(env[environmentVariables.verbose]) || process.argv.includes('--verbose')\n}\n\n/**\n * Returns true if the environment in which the CLI is running is either\n * a local environment (where dev is present).\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True if the CLI is used in a Shopify environment.\n */\nexport async function isShopify(env = process.env): Promise<boolean> {\n if (Object.prototype.hasOwnProperty.call(env, environmentVariables.runAsUser)) {\n return !isTruthy(env[environmentVariables.runAsUser])\n }\n const devInstalled = await lazyFileExists(pathConstants.executables.dev)\n return devInstalled\n}\n\n/**\n * This variable is used when running unit tests to indicate that the CLI's business logic\n * is run as a subject of a unit test. We can use this variable to disable output through\n * the standard streams.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True if the SHOPIFY_UNIT_TEST environment variable is truthy.\n */\nexport function isUnitTest(env = process.env): boolean {\n return isTruthy(env[environmentVariables.unitTest])\n}\n\n/**\n * Returns true if the CLI is running in hosted apps mode.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True if the HOSTED_APPS environment variable is truthy.\n */\nexport function isHostedAppsMode(env = process.env): boolean {\n return isTruthy(env[environmentVariables.hostedApps])\n}\n\n/**\n * Returns true if reporting analytics is enabled.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True unless SHOPIFY_CLI_NO_ANALYTICS or OPT_OUT_INSTRUMENTATION is truthy, or debug mode is enabled.\n */\nexport function analyticsDisabled(env = process.env): boolean {\n return (\n isTruthy(env[environmentVariables.noAnalytics]) ||\n isTruthy(env[environmentVariables.optOutInstrumentation]) ||\n isDevelopment(env)\n )\n}\n\n/**\n * Returns true if reporting analytics should always happen, regardless of DEBUG mode etc.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True if SHOPIFY_CLI_ALWAYS_LOG_ANALYTICS is truthy.\n */\nexport function alwaysLogAnalytics(env = process.env): boolean {\n return isTruthy(env[environmentVariables.alwaysLogAnalytics])\n}\n\n/**\n * Returns true if reporting metrics should always happen, regardless of DEBUG mode etc.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True if SHOPIFY_CLI_ALWAYS_LOG_METRICS is truthy.\n */\nexport function alwaysLogMetrics(env = process.env): boolean {\n return isTruthy(env[environmentVariables.alwaysLogMetrics])\n}\n\n/**\n * Returns true if the CLI User is 1P.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True if SHOPIFY_CLI_1P is truthy.\n */\nexport function firstPartyDev(env = process.env): boolean {\n return isTruthy(env[environmentVariables.firstPartyDev])\n}\n\n/**\n * Returns true if the CLI can run the \"doctor-release\" command.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True if the CLI can run the \"doctor-release\" command.\n */\nexport function canRunDoctorRelease(env = process.env): boolean {\n return isTruthy(env[environmentVariables.doctor])\n}\n\n/**\n * Return gitpodURL if we are running in gitpod.\n * Https://www.gitpod.io/docs/environment-variables#default-environment-variables.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns The gitpod URL.\n */\nexport function gitpodURL(env = process.env): string | undefined {\n return env[environmentVariables.gitpod]\n}\n\n/**\n * Return codespaceURL if we are running in codespaces.\n * Https://docs.github.com/en/codespaces/developing-in-codespaces/default-environment-variables-for-your-codespace#list-of-default-environment-variables.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns The codespace URL.\n */\nexport function codespaceURL(env = process.env): string | undefined {\n return env[environmentVariables.codespaceName]\n}\n\n/**\n * Return codespacePortForwardingDomain if we are running in codespaces.\n * Https://docs.github.com/en/codespaces/developing-in-codespaces/default-environment-variables-for-your-codespace#list-of-default-environment-variables.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns The codespace port forwarding domain.\n */\nexport function codespacePortForwardingDomain(env = process.env): string | undefined {\n return env[environmentVariables.codespacePortForwardingDomain]\n}\n\n/**\n * Checks if the CLI is run from a cloud environment.\n *\n * @param env - Environment variables used when the cli is launched.\n * @returns True in case the CLI is run from a cloud environment.\n */\nexport function isCloudEnvironment(env: NodeJS.ProcessEnv = process.env): boolean {\n return cloudEnvironment(env).platform !== 'localhost'\n}\n\n/**\n * The token used to run a theme command with a custom password.\n *\n * @param env - Environment variables used when the cli is launched.\n * @returns A string with the token.\n */\nexport function themeToken(env = process.env): string | undefined {\n return env[environmentVariables.themeToken]\n}\n\n/**\n * Returns the cloud environment platform name and if the platform support online IDE in case the CLI is run from one of\n * them. Platform name 'localhost' is returned otherwise.\n *\n * @param env - Environment variables used when the cli is launched.\n * @returns Cloud platform information.\n */\nexport function cloudEnvironment(env: NodeJS.ProcessEnv = process.env): {\n platform: 'codespaces' | 'gitpod' | 'cloudShell' | 'localhost'\n editor: boolean\n} {\n if (isSet(env[environmentVariables.codespaces])) {\n return {platform: 'codespaces', editor: true}\n }\n if (isSet(env[environmentVariables.gitpod])) {\n return {platform: 'gitpod', editor: true}\n }\n if (isSet(env[environmentVariables.cloudShell])) {\n return {platform: 'cloudShell', editor: true}\n }\n return {platform: 'localhost', editor: false}\n}\n\n/**\n * Returns whether the environment has Git available.\n *\n * @returns A promise that resolves with the value.\n */\nexport async function hasGit(): Promise<boolean> {\n try {\n await lazyExec('git', ['--version'])\n return true\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch {\n return false\n }\n}\n\n/**\n * Gets info on the CI platform the CLI is running on, if applicable.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns The CI platform info.\n */\nexport function ciPlatform(\n env = process.env,\n): {isCI: true; name: string; metadata: Metadata} | {isCI: false; name?: undefined; metadata?: undefined} {\n if (isTruthy(env.CI)) {\n let name = 'unknown'\n if (isSet(env.BITBUCKET_BUILD_NUMBER)) {\n name = 'bitbucket'\n } else if (isTruthy(env.CIRCLECI)) {\n name = 'circleci'\n } else if (isSet(env.GITHUB_ACTION)) {\n name = 'github'\n } else if (isTruthy(env.GITLAB_CI)) {\n name = 'gitlab'\n } else if (isSet(env.BUILDKITE)) {\n name = 'buildkite'\n }\n\n return {\n isCI: true,\n name,\n metadata: getCIMetadata(name, env),\n }\n } else if (isTruthy(env.TF_BUILD)) {\n return {\n isCI: true,\n name: 'azure',\n metadata: getCIMetadata('azure', env),\n }\n }\n return {\n isCI: false,\n }\n}\n\n/**\n * Returns the first mac address found.\n *\n * @returns Mac address.\n */\nexport function macAddress(): Promise<string> {\n return macaddress.one()\n}\n\n/**\n * Get the domain for theme kit access.\n *\n * It can be overridden via the SHOPIFY_CLI_THEME_KIT_ACCESS_DOMAIN environment\n * variable.\n *\n * @param env - The environment variables from the environment of the process.\n *\n * @returns The domain for theme kit access.\n */\nexport function getThemeKitAccessDomain(env = process.env): string {\n const domain = env[environmentVariables.themeKitAccessDomain]\n\n return isSet(domain) ? domain : defaultThemeKitAccessDomain\n}\n\n/**\n * Get the domain to send OTEL metrics to.\n *\n * It can be overridden via the SHOPIFY_CLI_OTEL_EXPORTER_OTLP_ENDPOINT environment variable.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns The domain to send OTEL metrics to.\n */\nexport function opentelemetryDomain(env = process.env): string {\n const domain = env[environmentVariables.otelURL]\n\n return isSet(domain) ? domain : 'https://otlp-http-production-cli.shopifysvc.com'\n}\n\nexport type CIMetadata = Metadata\n"]}
|
|
1
|
+
{"version":3,"file":"local.js","sourceRoot":"","sources":["../../../../src/public/node/context/local.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAC,MAAM,gBAAgB,CAAA;AACvC,OAAO,EAAC,aAAa,EAAE,KAAK,EAAW,MAAM,4CAA4C,CAAA;AACzF,OAAO,EAAC,2BAA2B,EAAE,oBAAoB,EAAE,aAAa,EAAC,MAAM,oCAAoC,CAAA;AACnH,OAAO,UAAU,MAAM,YAAY,CAAA;AACnC,OAAO,EAAC,OAAO,EAAC,MAAM,IAAI,CAAA;AAE1B,4FAA4F;AAC5F,qFAAqF;AACrF,KAAK,UAAU,cAAc,CAAC,IAAY;IACxC,MAAM,EAAC,UAAU,EAAC,GAAG,MAAM,MAAM,CAAC,UAAU,CAAC,CAAA;IAC7C,OAAO,UAAU,CAAC,IAAI,CAAC,CAAA;AACzB,CAAC;AAED,KAAK,UAAU,QAAQ,CAAC,OAAe,EAAE,IAAc;IACrD,MAAM,EAAC,IAAI,EAAC,GAAG,MAAM,MAAM,CAAC,cAAc,CAAC,CAAA;IAC3C,MAAM,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;AAC3B,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,qBAAqB;IACnC,OAAO,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,KAAK,MAAM,IAAI,CAAC,CAAC,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC,CAAC,CAAA;AAC/F,CAAC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J,QAAQ,EAAE,aAAa,CAAC,IAAI,EAAE,GAAG,CAAC;SACnC,CAAA;IACH,CAAC;SAAM,IAAI,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;QAClC,OAAO;YACL,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,OAAO;YACb,QAAQ,EAAE,aAAa,CAAC,OAAO,EAAE,GAAG,CAAC;SACtC,CAAA;IACH,CAAC;IACD,OAAO;QACL,IAAI,EAAE,KAAK;KACZ,CAAA;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,UAAU;IACxB,OAAO,UAAU,CAAC,GAAG,EAAE,CAAA;AACzB,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,uBAAuB,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG;IACvD,MAAM,MAAM,GAAG,GAAG,CAAC,oBAAoB,CAAC,oBAAoB,CAAC,CAAA;IAE7D,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,2BAA2B,CAAA;AAC7D,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,mBAAmB,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG;IACnD,MAAM,MAAM,GAAG,GAAG,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAA;IAEhD,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,iDAAiD,CAAA;AACnF,CAAC","sourcesContent":["import {isTruthy} from './utilities.js'\nimport {getCIMetadata, isSet, Metadata} from '../../../private/node/context/utilities.js'\nimport {defaultThemeKitAccessDomain, environmentVariables, pathConstants} from '../../../private/node/constants.js'\nimport macaddress from 'macaddress'\nimport {homedir} from 'os'\n\n// Dynamic imports to avoid circular dependency: context/local → fs → output → context/local\n// fileExists and exec are only used in specific async functions, not at module init.\nasync function lazyFileExists(path: string): Promise<boolean> {\n const {fileExists} = await import('../fs.js')\n return fileExists(path)\n}\n\nasync function lazyExec(command: string, args: string[]): Promise<void> {\n const {exec} = await import('../system.js')\n await exec(command, args)\n}\n\n/**\n * It returns true if the terminal is interactive.\n *\n * @returns True if the terminal is interactive.\n */\nexport function isTerminalInteractive(): boolean {\n return Boolean(process.stdout.isTTY && process.env.TERM !== 'dumb' && !('CI' in process.env))\n}\n\n/**\n * Returns the path to the user's home directory.\n *\n * @returns The path to the user's home directory.\n */\nexport function homeDirectory(): string {\n return homedir()\n}\n\n/**\n * Memoized value for the verbose check.\n */\nlet memoizedIsVerbose: boolean | undefined\n\n/**\n * Memoized value for the unit test check.\n */\nlet memoizedIsUnitTest: boolean | undefined\n\n/**\n * Returns true if the CLI is running in debug mode.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True if SHOPIFY_ENV is development.\n */\nexport function isDevelopment(env = process.env): boolean {\n return env[environmentVariables.env] === 'development'\n}\n\n/**\n * Returns true if the CLI is running in verbose mode.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True if SHOPIFY_FLAG_VERBOSE is truthy or the flag --verbose has been passed.\n */\nexport function isVerbose(env = process.env): boolean {\n if (env === process.env) {\n // Memoize the result to avoid repeated scans of process.argv and env lookups\n // in high-frequency paths like outputDebug.\n return (memoizedIsVerbose ??= isTruthy(env[environmentVariables.verbose]) || process.argv.includes('--verbose'))\n }\n return isTruthy(env[environmentVariables.verbose]) || process.argv.includes('--verbose')\n}\n\n/**\n * Returns true if the environment in which the CLI is running is either\n * a local environment (where dev is present).\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True if the CLI is used in a Shopify environment.\n */\nexport async function isShopify(env = process.env): Promise<boolean> {\n if (Object.prototype.hasOwnProperty.call(env, environmentVariables.runAsUser)) {\n return !isTruthy(env[environmentVariables.runAsUser])\n }\n const devInstalled = await lazyFileExists(pathConstants.executables.dev)\n return devInstalled\n}\n\n/**\n * This variable is used when running unit tests to indicate that the CLI's business logic\n * is run as a subject of a unit test. We can use this variable to disable output through\n * the standard streams.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True if the SHOPIFY_UNIT_TEST environment variable is truthy.\n */\nexport function isUnitTest(env = process.env): boolean {\n if (env === process.env) {\n // Memoize the result as SHOPIFY_UNIT_TEST is static during execution\n // and checked frequently to suppress output.\n return (memoizedIsUnitTest ??= isTruthy(env[environmentVariables.unitTest]))\n }\n return isTruthy(env[environmentVariables.unitTest])\n}\n\n/**\n * Returns true if reporting analytics is enabled.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True unless SHOPIFY_CLI_NO_ANALYTICS or OPT_OUT_INSTRUMENTATION is truthy, or debug mode is enabled.\n */\nexport function analyticsDisabled(env = process.env): boolean {\n return (\n isTruthy(env[environmentVariables.noAnalytics]) ||\n isTruthy(env[environmentVariables.optOutInstrumentation]) ||\n isDevelopment(env)\n )\n}\n\n/**\n * Returns true if reporting analytics should always happen, regardless of DEBUG mode etc.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True if SHOPIFY_CLI_ALWAYS_LOG_ANALYTICS is truthy.\n */\nexport function alwaysLogAnalytics(env = process.env): boolean {\n return isTruthy(env[environmentVariables.alwaysLogAnalytics])\n}\n\n/**\n * Returns true if reporting metrics should always happen, regardless of DEBUG mode etc.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True if SHOPIFY_CLI_ALWAYS_LOG_METRICS is truthy.\n */\nexport function alwaysLogMetrics(env = process.env): boolean {\n return isTruthy(env[environmentVariables.alwaysLogMetrics])\n}\n\n/**\n * Returns true if the CLI User is 1P.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True if SHOPIFY_CLI_1P is truthy.\n */\nexport function firstPartyDev(env = process.env): boolean {\n return isTruthy(env[environmentVariables.firstPartyDev])\n}\n\n/**\n * Returns true if the CLI can run the \"doctor-release\" command.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns True if the CLI can run the \"doctor-release\" command.\n */\nexport function canRunDoctorRelease(env = process.env): boolean {\n return isTruthy(env[environmentVariables.doctor])\n}\n\n/**\n * Return gitpodURL if we are running in gitpod.\n * Https://www.gitpod.io/docs/environment-variables#default-environment-variables.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns The gitpod URL.\n */\nexport function gitpodURL(env = process.env): string | undefined {\n return env[environmentVariables.gitpod]\n}\n\n/**\n * Return codespaceURL if we are running in codespaces.\n * Https://docs.github.com/en/codespaces/developing-in-codespaces/default-environment-variables-for-your-codespace#list-of-default-environment-variables.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns The codespace URL.\n */\nexport function codespaceURL(env = process.env): string | undefined {\n return env[environmentVariables.codespaceName]\n}\n\n/**\n * Return codespacePortForwardingDomain if we are running in codespaces.\n * Https://docs.github.com/en/codespaces/developing-in-codespaces/default-environment-variables-for-your-codespace#list-of-default-environment-variables.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns The codespace port forwarding domain.\n */\nexport function codespacePortForwardingDomain(env = process.env): string | undefined {\n return env[environmentVariables.codespacePortForwardingDomain]\n}\n\n/**\n * Checks if the CLI is run from a cloud environment.\n *\n * @param env - Environment variables used when the cli is launched.\n * @returns True in case the CLI is run from a cloud environment.\n */\nexport function isCloudEnvironment(env: NodeJS.ProcessEnv = process.env): boolean {\n return cloudEnvironment(env).platform !== 'localhost'\n}\n\n/**\n * The token used to run a theme command with a custom password.\n *\n * @param env - Environment variables used when the cli is launched.\n * @returns A string with the token.\n */\nexport function themeToken(env = process.env): string | undefined {\n return env[environmentVariables.themeToken]\n}\n\n/**\n * Returns the cloud environment platform name and if the platform support online IDE in case the CLI is run from one of\n * them. Platform name 'localhost' is returned otherwise.\n *\n * @param env - Environment variables used when the cli is launched.\n * @returns Cloud platform information.\n */\nexport function cloudEnvironment(env: NodeJS.ProcessEnv = process.env): {\n platform: 'codespaces' | 'gitpod' | 'cloudShell' | 'localhost'\n editor: boolean\n} {\n if (isSet(env[environmentVariables.codespaces])) {\n return {platform: 'codespaces', editor: true}\n }\n if (isSet(env[environmentVariables.gitpod])) {\n return {platform: 'gitpod', editor: true}\n }\n if (isSet(env[environmentVariables.cloudShell])) {\n return {platform: 'cloudShell', editor: true}\n }\n return {platform: 'localhost', editor: false}\n}\n\n/**\n * Returns whether the environment has Git available.\n *\n * @returns A promise that resolves with the value.\n */\nexport async function hasGit(): Promise<boolean> {\n try {\n await lazyExec('git', ['--version'])\n return true\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch {\n return false\n }\n}\n\n/**\n * Gets info on the CI platform the CLI is running on, if applicable.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns The CI platform info.\n */\nexport function ciPlatform(\n env = process.env,\n): {isCI: true; name: string; metadata: Metadata} | {isCI: false; name?: undefined; metadata?: undefined} {\n if (isTruthy(env.CI)) {\n let name = 'unknown'\n if (isSet(env.BITBUCKET_BUILD_NUMBER)) {\n name = 'bitbucket'\n } else if (isTruthy(env.CIRCLECI)) {\n name = 'circleci'\n } else if (isSet(env.GITHUB_ACTION)) {\n name = 'github'\n } else if (isTruthy(env.GITLAB_CI)) {\n name = 'gitlab'\n } else if (isSet(env.BUILDKITE)) {\n name = 'buildkite'\n }\n\n return {\n isCI: true,\n name,\n metadata: getCIMetadata(name, env),\n }\n } else if (isTruthy(env.TF_BUILD)) {\n return {\n isCI: true,\n name: 'azure',\n metadata: getCIMetadata('azure', env),\n }\n }\n return {\n isCI: false,\n }\n}\n\n/**\n * Returns the first mac address found.\n *\n * @returns Mac address.\n */\nexport function macAddress(): Promise<string> {\n return macaddress.one()\n}\n\n/**\n * Get the domain for theme kit access.\n *\n * It can be overridden via the SHOPIFY_CLI_THEME_KIT_ACCESS_DOMAIN environment\n * variable.\n *\n * @param env - The environment variables from the environment of the process.\n *\n * @returns The domain for theme kit access.\n */\nexport function getThemeKitAccessDomain(env = process.env): string {\n const domain = env[environmentVariables.themeKitAccessDomain]\n\n return isSet(domain) ? domain : defaultThemeKitAccessDomain\n}\n\n/**\n * Get the domain to send OTEL metrics to.\n *\n * It can be overridden via the SHOPIFY_CLI_OTEL_EXPORTER_OTLP_ENDPOINT environment variable.\n *\n * @param env - The environment variables from the environment of the current process.\n * @returns The domain to send OTEL metrics to.\n */\nexport function opentelemetryDomain(env = process.env): string {\n const domain = env[environmentVariables.otelURL]\n\n return isSet(domain) ? domain : 'https://otlp-http-production-cli.shopifysvc.com'\n}\n\nexport type CIMetadata = Metadata\n"]}
|
package/dist/public/node/git.js
CHANGED
|
@@ -257,7 +257,8 @@ export class OutsideGitDirectoryError extends AbortError {
|
|
|
257
257
|
* @param directory - The directory to check.
|
|
258
258
|
*/
|
|
259
259
|
export async function ensureInsideGitDirectory(directory) {
|
|
260
|
-
|
|
260
|
+
await ensureGitIsPresentOrAbort();
|
|
261
|
+
if (!(await checkIfInsideGitDirectory(directory))) {
|
|
261
262
|
throw new OutsideGitDirectoryError(`${outputToken.path(directory ?? cwd())} is not a Git directory`);
|
|
262
263
|
}
|
|
263
264
|
}
|
|
@@ -268,6 +269,12 @@ export async function ensureInsideGitDirectory(directory) {
|
|
|
268
269
|
* @returns True if the directory is inside a .git directory tree.
|
|
269
270
|
*/
|
|
270
271
|
export async function insideGitDirectory(directory) {
|
|
272
|
+
if (!(await hasGit())) {
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
return checkIfInsideGitDirectory(directory);
|
|
276
|
+
}
|
|
277
|
+
async function checkIfInsideGitDirectory(directory) {
|
|
271
278
|
try {
|
|
272
279
|
await execa('git', ['rev-parse', '--git-dir'], { cwd: directory });
|
|
273
280
|
return true;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"git.js","sourceRoot":"","sources":["../../../src/public/node/git.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,aAAa,EAAE,WAAW,EAAE,WAAW,EAAC,MAAM,aAAa,CAAA;AACnE,OAAO,EAAC,MAAM,EAAE,qBAAqB,EAAC,MAAM,oBAAoB,CAAA;AAChE,OAAO,EACL,cAAc,EACd,SAAS,EACT,UAAU,EACV,cAAc,EACd,IAAI,EACJ,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AM,CAAC,KAAK,UAAU,YAAY,CAAC,SAAkB;IACnD,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,CAAC,UAAU,EAAE,QAAQ,EAAE,YAAY,CAAC,EAAE,SAAS,CAAC,CAAA;QAChF,OAAO,MAAM,CAAC,IAAI,EAAE,IAAI,SAAS,CAAA;IACnC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,UAAU,IAAI,UAAU,IAAI,KAAK,IAAI,KAAK,CAAC,QAAQ,KAAK,GAAG;YAAE,OAAO,SAAS,CAAA;QAClG,MAAM,KAAK,CAAA;IACb,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,SAAiB,EAAE,UAAU,GAAG,QAAQ;IAC5E,WAAW,CAAC,aAAa,CAAA,uBAAuB,UAAU,SAAS,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;IACpG,MAAM,yBAAyB,EAAE,CAAA;IAEjC,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC,CAAA;IACtD,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;IAElD,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC;QAClC,WAAW,CAAC,aAAa,CAAA,UAAU,UAAU,mCAAmC,CAAC,CAAA;QACjF,OAAM;IACR,CAAC;IAED,MAAM,UAAU,CAAC,CAAC,QAAQ,EAAE,QAAQ,EAAE,UAAU,CAAC,EAAE,SAAS,CAAC,CAAA;AAC/D,CAAC","sourcesContent":["import {outputContent, outputToken, outputDebug} from './output.js'\nimport {hasGit, isTerminalInteractive} from './context/local.js'\nimport {\n appendFileSync,\n detectEOL,\n fileExists,\n fileExistsSync,\n glob,\n isDirectory,\n readFileSync,\n writeFileSync,\n} from './fs.js'\nimport {AbortError} from './error.js'\nimport {cwd, joinPath} from './path.js'\nimport {runWithTimer} from './metadata.js'\nimport {execa} from 'execa'\n\nimport ignore from 'ignore'\n\nexport interface GitLogEntry {\n hash: string\n date: string\n message: string\n refs: string\n body: string\n author_name: string\n author_email: string\n}\n\nasync function gitCommand(args: string[], directory?: string): Promise<string> {\n try {\n const result = await execa('git', args, {cwd: directory})\n return result.stdout\n } catch (err) {\n if (err instanceof Error) {\n const abortError = new AbortError(err.message)\n abortError.stack = err.stack\n if ('exitCode' in err) {\n Object.assign(abortError, {exitCode: err.exitCode})\n }\n throw abortError\n }\n throw err\n }\n}\n\n/**\n * Initialize a git repository at the given directory.\n *\n * @param directory - The directory where the git repository will be initialized.\n * @param initialBranch - The name of the initial branch.\n */\nexport async function initializeGitRepository(directory: string, initialBranch = 'main'): Promise<void> {\n outputDebug(outputContent`Initializing git repository at ${outputToken.path(directory)}...`)\n await ensureGitIsPresentOrAbort()\n // We use init and checkout instead of `init --initial-branch` because the latter is only supported in git 2.28+\n await gitCommand(['init'], directory)\n await gitCommand(['checkout', '-b', initialBranch], directory)\n}\n\n/**\n * Given a Git repository and a list of absolute paths to files contained\n * in the repository, it filters and returns the files that are ignored\n * by the .gitignore.\n *\n * @param directory - The absolute path to the directory containing the files.\n * @param files - The list of files to check against.\n * @returns Files ignored by the lockfile.\n */\nexport async function checkIfIgnoredInGitRepository(directory: string, files: string[]): Promise<string[]> {\n try {\n const stdout = await gitCommand(['check-ignore', ...files], directory)\n return stdout.split('\\n').filter(Boolean)\n } catch (error) {\n // git check-ignore exits with code 1 when no files are ignored\n if (error instanceof AbortError && 'exitCode' in error && error.exitCode === 1) return []\n throw error\n }\n}\n\nexport type GitIgnoreTemplate = Record<string, string[]>\n/**\n * Create a .gitignore file in the given directory.\n *\n * @param directory - The directory where the .gitignore file will be created.\n * @param template - The template to use to create the .gitignore file.\n */\nexport function createGitIgnore(directory: string, template: GitIgnoreTemplate): void {\n outputDebug(outputContent`Creating .gitignore at ${outputToken.path(directory)}...`)\n const filePath = `${directory}/.gitignore`\n\n let fileContent = ''\n for (const [section, lines] of Object.entries(template)) {\n fileContent += `# ${section}\\n`\n fileContent += `${lines.join('\\n')}\\n\\n`\n }\n\n appendFileSync(filePath, fileContent)\n}\n\n/**\n * Add an entry to an existing .gitignore file.\n *\n * If the .gitignore file doesn't exist, or if the entry is already present,\n * no changes will be made.\n *\n * @param root - The directory containing the .gitignore file.\n * @param entry - The entry to add to the .gitignore file.\n */\nexport function addToGitIgnore(root: string, entry: string): void {\n const gitIgnorePath = joinPath(root, '.gitignore')\n\n if (!fileExistsSync(gitIgnorePath)) {\n // When the .gitignore file does not exist, the CLI should not be opinionated about creating it\n return\n }\n\n const gitIgnoreContent = readFileSync(gitIgnorePath).toString()\n const eol = detectEOL(gitIgnoreContent)\n\n const lines = gitIgnoreContent.split(eol).map((line) => line.trim())\n const ignoreManager = ignore.default({allowRelativePaths: true}).add(lines)\n\n const isIgnoredEntry = ignoreManager.ignores(joinPath(entry))\n const isIgnoredEntryAsDir = ignoreManager.ignores(joinPath(entry, 'ignored.txt'))\n const isAlreadyIgnored = isIgnoredEntry || isIgnoredEntryAsDir\n if (isAlreadyIgnored) {\n // The file is already ignored by an existing pattern\n return\n }\n\n if (gitIgnoreContent.endsWith(eol)) {\n writeFileSync(gitIgnorePath, `${gitIgnoreContent}${entry}${eol}`)\n } else {\n writeFileSync(gitIgnorePath, `${gitIgnoreContent}${eol}${entry}${eol}`)\n }\n}\n\n/**\n * Options to use when cloning a git repository.\n *\n * @param repoUrl - The URL of the repository to clone.\n * @param destination - The directory where the repository will be cloned.\n * @param shallow - Whether to clone the repository shallowly.\n * @param latestTag - Whether to clone the latest tag instead of the default branch.\n */\nexport interface GitCloneOptions {\n repoUrl: string\n destination: string\n shallow?: boolean\n latestTag?: boolean\n}\n/**\n * Clone a git repository.\n *\n * @param cloneOptions - The options to use to clone the repository.\n * @returns A promise that resolves when the clone is complete.\n */\nexport async function downloadGitRepository(cloneOptions: GitCloneOptions): Promise<void> {\n return runWithTimer('cmd_all_timing_network_ms')(async () => {\n const {repoUrl, destination, shallow, latestTag} = cloneOptions\n outputDebug(outputContent`Git-cloning repository ${repoUrl} into ${outputToken.path(destination)}...`)\n await ensureGitIsPresentOrAbort()\n\n // Validate destination directory before attempting to clone\n if (await fileExists(destination)) {\n // Check if it's a directory\n if (!(await isDirectory(destination))) {\n throw new AbortError(\n outputContent`Can't clone to ${outputToken.path(destination)}`,\n \"The path exists but isn't a directory.\",\n )\n }\n\n // Check if directory is empty\n const entries = await glob(['*', '.*'], {\n cwd: destination,\n deep: 1,\n onlyFiles: false,\n })\n\n if (entries.length > 0) {\n throw new AbortError(\n outputContent`Directory ${outputToken.path(destination)} already exists and is not empty`,\n outputContent`Choose a different name or remove the existing directory first.`,\n )\n }\n }\n\n const [repository, branch] = repoUrl.split('#')\n\n if (branch && latestTag) {\n throw new AbortError(\"Error cloning the repository. Git can't clone the latest release with a 'branch'.\")\n }\n\n if (shallow && latestTag) {\n throw new AbortError(\n \"Error cloning the repository. Git can't clone the latest release with the 'shallow' property.\",\n )\n }\n\n const args = ['clone', '--recurse-submodules']\n if (branch) {\n args.push('--branch', branch)\n }\n if (shallow) {\n args.push('--depth', '1')\n }\n if (!isTerminalInteractive()) {\n args.push('-c', 'core.askpass=true')\n }\n args.push(repository!, destination)\n\n try {\n await execa('git', args)\n\n if (latestTag) {\n const tag = await getLatestTagFromDirectory(destination, repoUrl)\n await gitCommand(['checkout', tag], destination)\n }\n } catch (err) {\n if (err instanceof AbortError) {\n throw err\n }\n if (err instanceof Error) {\n const abortError = new AbortError(err.message)\n abortError.stack = err.stack\n throw abortError\n }\n throw err\n }\n })\n}\n\nasync function getLatestTagFromDirectory(directory: string, repoUrl: string): Promise<string> {\n const tag = await getLatestTag(directory)\n\n if (!tag) {\n throw new AbortError(`Couldn't obtain the most recent tag of the repository ${repoUrl}`)\n }\n\n return tag\n}\n\n/**\n * Get the latest commit of a git repository.\n *\n * @param directory - The directory of the git repository.\n * @returns The latest commit of the repository.\n */\nexport async function getLatestGitCommit(directory?: string): Promise<GitLogEntry> {\n const format = '%H%x00%ai%x00%s%x00%D%x00%b%x00%an%x00%ae'\n const stdout = await gitCommand(['log', '-1', `--format=${format}`], directory)\n if (!stdout.trim()) {\n throw new AbortError(\n 'Must have at least one commit to run command',\n outputContent`Run ${outputToken.genericShellCommand(\n \"git commit -m 'Initial commit'\",\n )} to create your first commit.`,\n )\n }\n const parts = stdout.split('\\x00')\n return {\n hash: parts[0]!,\n date: parts[1]!,\n message: parts[2]!,\n refs: parts[3]!,\n body: parts[4]!,\n author_name: parts[5]!,\n author_email: parts[6]!,\n }\n}\n\n/**\n * Add all files to the git index from the given directory.\n *\n * @param directory - The directory where the git repository is located.\n * @returns A promise that resolves when the files are added to the index.\n */\nexport async function addAllToGitFromDirectory(directory?: string): Promise<void> {\n await gitCommand(['add', '--all'], directory)\n}\n\nexport interface CreateGitCommitOptions {\n directory?: string\n author?: string\n}\n\n/**\n * Create a git commit.\n *\n * @param message - The message of the commit.\n * @param options - The options to use to create the commit.\n * @returns The hash of the created commit.\n */\nexport async function createGitCommit(message: string, options?: CreateGitCommitOptions): Promise<string> {\n const args = ['commit', '-m', message]\n if (options?.author) {\n args.push('--author', options.author)\n }\n await gitCommand(args, options?.directory)\n const stdout = await gitCommand(['rev-parse', 'HEAD'], options?.directory)\n return stdout.trim()\n}\n\n/**\n * Get the HEAD symbolic reference of a git repository.\n *\n * @param directory - The directory of the git repository.\n * @returns The HEAD symbolic reference of the repository.\n */\nexport async function getHeadSymbolicRef(directory?: string): Promise<string> {\n const ref = await gitCommand(['symbolic-ref', '-q', 'HEAD'], directory)\n if (!ref) {\n throw new AbortError(\n \"Git HEAD can't be detached to run command\",\n outputContent`Run ${outputToken.genericShellCommand(\n 'git checkout [branchName]',\n )} to reattach HEAD or see git ${outputToken.link(\n 'documentation',\n 'https://git-scm.com/book/en/v2/Git-Internals-Git-References',\n )} for more details`,\n )\n }\n return ref.trim()\n}\n\n/**\n * If \"git\" is not present in the environment it throws\n * an abort error.\n */\nexport async function ensureGitIsPresentOrAbort(): Promise<void> {\n if (!(await hasGit())) {\n throw new AbortError(\n `Git is necessary in the environment to continue`,\n outputContent`Install ${outputToken.link(\n 'git',\n 'https://git-scm.com/book/en/v2/Getting-Started-Installing-Git',\n )}`,\n )\n }\n}\n\nexport class OutsideGitDirectoryError extends AbortError {}\n/**\n * If command run from outside a .git directory tree\n * it throws an abort error.\n *\n * @param directory - The directory to check.\n */\nexport async function ensureInsideGitDirectory(directory?: string): Promise<void> {\n if (!(await insideGitDirectory(directory))) {\n throw new OutsideGitDirectoryError(`${outputToken.path(directory ?? cwd())} is not a Git directory`)\n }\n}\n\n/**\n * Returns true if the given directory is inside a .git directory tree.\n *\n * @param directory - The directory to check.\n * @returns True if the directory is inside a .git directory tree.\n */\nexport async function insideGitDirectory(directory?: string): Promise<boolean> {\n try {\n await execa('git', ['rev-parse', '--git-dir'], {cwd: directory})\n return true\n } catch (error) {\n if (error instanceof Error && 'exitCode' in error && error.exitCode === 128) return false\n throw error\n }\n}\n\nexport class GitDirectoryNotCleanError extends AbortError {}\n/**\n * If the .git directory tree is not clean (has uncommitted changes)\n * it throws an abort error.\n *\n * @param directory - The directory to check.\n */\nexport async function ensureIsClean(directory?: string): Promise<void> {\n if (!(await isClean(directory))) {\n throw new GitDirectoryNotCleanError(`${outputToken.path(directory ?? cwd())} is not a clean Git directory`)\n }\n}\n\n/**\n * Returns true if the .git directory tree is clean (no uncommitted changes).\n *\n * @param directory - The directory to check.\n * @returns True is the .git directory is clean.\n */\nexport async function isClean(directory?: string): Promise<boolean> {\n const stdout = await gitCommand(['status', '--porcelain'], directory)\n return stdout.trim() === ''\n}\n\n/**\n * Returns the latest tag of a git repository.\n *\n * @param directory - The directory to check.\n * @returns String with the latest tag or undefined if no tags are found.\n */\nexport async function getLatestTag(directory?: string): Promise<string | undefined> {\n try {\n const stdout = await gitCommand(['describe', '--tags', '--abbrev=0'], directory)\n return stdout.trim() || undefined\n } catch (error) {\n if (error instanceof AbortError && 'exitCode' in error && error.exitCode === 128) return undefined\n throw error\n }\n}\n\n/**\n * Remove a git remote from the given directory.\n *\n * @param directory - The directory where the git repository is located.\n * @param remoteName - The name of the remote to remove (defaults to 'origin').\n * @returns A promise that resolves when the remote is removed.\n */\nexport async function removeGitRemote(directory: string, remoteName = 'origin'): Promise<void> {\n outputDebug(outputContent`Removing git remote ${remoteName} from ${outputToken.path(directory)}...`)\n await ensureGitIsPresentOrAbort()\n\n const stdout = await gitCommand(['remote'], directory)\n const remotes = stdout.split('\\n').filter(Boolean)\n\n if (!remotes.includes(remoteName)) {\n outputDebug(outputContent`Remote ${remoteName} does not exist, no action needed`)\n return\n }\n\n await gitCommand(['remote', 'remove', remoteName], directory)\n}\n"]}
|
|
1
|
+
{"version":3,"file":"git.js","sourceRoot":"","sources":["../../../src/public/node/git.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,aAAa,EAAE,WAAW,EAAE,WAAW,EAAC,MAAM,aAAa,CAAA;AACnE,OAAO,EAAC,MAAM,EAAE,qBAAqB,EAAC,MAAM,oBAAoB,CAAA;AAChE,OAAO,EACL,cAAc,EACd,SAAS,EACT,UAAU,EACV,cAAc,EACd,IAAI,EACJ,WAAW,EACX,YAAY,EACZ,aAAa,GACd,MAAM,SAAS,CAAA;AAChB,OAAO,EAAC,UAAU,EAAC,MAAM,YAAY,CAAA;AACrC,OAAO,EAAC,GAAG,EAAE,QAAQ,EAAC,MAAM,WAAW,CAAA;AACvC,OAAO,EAAC,YAAY,EAAC,MAAM,eAAe,CAAA;AAC1C,OAAO,EAAC,KAAK,EAAC,MAAM,OAAO,CAAA;AAE3B,OAAO,MAAM,MAAM,QAAQ,CAAA;AAY3B,KAAK,UAAU,UAAU,CAAC,IAAc,EAAE,SAAkB;IAC1D,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,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CAAC,IAAI,EAAE,IAAI,SAAS,CAAA;IACnC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,UAAU,IAAI,UAAU,IAAI,KAAK,IAAI,KAAK,CAAC,QAAQ,KAAK,GAAG;YAAE,OAAO,SAAS,CAAA;QAClG,MAAM,KAAK,CAAA;IACb,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,SAAiB,EAAE,UAAU,GAAG,QAAQ;IAC5E,WAAW,CAAC,aAAa,CAAA,uBAAuB,UAAU,SAAS,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;IACpG,MAAM,yBAAyB,EAAE,CAAA;IAEjC,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC,CAAA;IACtD,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;IAElD,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC;QAClC,WAAW,CAAC,aAAa,CAAA,UAAU,UAAU,mCAAmC,CAAC,CAAA;QACjF,OAAM;IACR,CAAC;IAED,MAAM,UAAU,CAAC,CAAC,QAAQ,EAAE,QAAQ,EAAE,UAAU,CAAC,EAAE,SAAS,CAAC,CAAA;AAC/D,CAAC","sourcesContent":["import {outputContent, outputToken, outputDebug} from './output.js'\nimport {hasGit, isTerminalInteractive} from './context/local.js'\nimport {\n appendFileSync,\n detectEOL,\n fileExists,\n fileExistsSync,\n glob,\n isDirectory,\n readFileSync,\n writeFileSync,\n} from './fs.js'\nimport {AbortError} from './error.js'\nimport {cwd, joinPath} from './path.js'\nimport {runWithTimer} from './metadata.js'\nimport {execa} from 'execa'\n\nimport ignore from 'ignore'\n\nexport interface GitLogEntry {\n hash: string\n date: string\n message: string\n refs: string\n body: string\n author_name: string\n author_email: string\n}\n\nasync function gitCommand(args: string[], directory?: string): Promise<string> {\n try {\n const result = await execa('git', args, {cwd: directory})\n return result.stdout\n } catch (err) {\n if (err instanceof Error) {\n const abortError = new AbortError(err.message)\n abortError.stack = err.stack\n if ('exitCode' in err) {\n Object.assign(abortError, {exitCode: err.exitCode})\n }\n throw abortError\n }\n throw err\n }\n}\n\n/**\n * Initialize a git repository at the given directory.\n *\n * @param directory - The directory where the git repository will be initialized.\n * @param initialBranch - The name of the initial branch.\n */\nexport async function initializeGitRepository(directory: string, initialBranch = 'main'): Promise<void> {\n outputDebug(outputContent`Initializing git repository at ${outputToken.path(directory)}...`)\n await ensureGitIsPresentOrAbort()\n // We use init and checkout instead of `init --initial-branch` because the latter is only supported in git 2.28+\n await gitCommand(['init'], directory)\n await gitCommand(['checkout', '-b', initialBranch], directory)\n}\n\n/**\n * Given a Git repository and a list of absolute paths to files contained\n * in the repository, it filters and returns the files that are ignored\n * by the .gitignore.\n *\n * @param directory - The absolute path to the directory containing the files.\n * @param files - The list of files to check against.\n * @returns Files ignored by the lockfile.\n */\nexport async function checkIfIgnoredInGitRepository(directory: string, files: string[]): Promise<string[]> {\n try {\n const stdout = await gitCommand(['check-ignore', ...files], directory)\n return stdout.split('\\n').filter(Boolean)\n } catch (error) {\n // git check-ignore exits with code 1 when no files are ignored\n if (error instanceof AbortError && 'exitCode' in error && error.exitCode === 1) return []\n throw error\n }\n}\n\nexport type GitIgnoreTemplate = Record<string, string[]>\n/**\n * Create a .gitignore file in the given directory.\n *\n * @param directory - The directory where the .gitignore file will be created.\n * @param template - The template to use to create the .gitignore file.\n */\nexport function createGitIgnore(directory: string, template: GitIgnoreTemplate): void {\n outputDebug(outputContent`Creating .gitignore at ${outputToken.path(directory)}...`)\n const filePath = `${directory}/.gitignore`\n\n let fileContent = ''\n for (const [section, lines] of Object.entries(template)) {\n fileContent += `# ${section}\\n`\n fileContent += `${lines.join('\\n')}\\n\\n`\n }\n\n appendFileSync(filePath, fileContent)\n}\n\n/**\n * Add an entry to an existing .gitignore file.\n *\n * If the .gitignore file doesn't exist, or if the entry is already present,\n * no changes will be made.\n *\n * @param root - The directory containing the .gitignore file.\n * @param entry - The entry to add to the .gitignore file.\n */\nexport function addToGitIgnore(root: string, entry: string): void {\n const gitIgnorePath = joinPath(root, '.gitignore')\n\n if (!fileExistsSync(gitIgnorePath)) {\n // When the .gitignore file does not exist, the CLI should not be opinionated about creating it\n return\n }\n\n const gitIgnoreContent = readFileSync(gitIgnorePath).toString()\n const eol = detectEOL(gitIgnoreContent)\n\n const lines = gitIgnoreContent.split(eol).map((line) => line.trim())\n const ignoreManager = ignore.default({allowRelativePaths: true}).add(lines)\n\n const isIgnoredEntry = ignoreManager.ignores(joinPath(entry))\n const isIgnoredEntryAsDir = ignoreManager.ignores(joinPath(entry, 'ignored.txt'))\n const isAlreadyIgnored = isIgnoredEntry || isIgnoredEntryAsDir\n if (isAlreadyIgnored) {\n // The file is already ignored by an existing pattern\n return\n }\n\n if (gitIgnoreContent.endsWith(eol)) {\n writeFileSync(gitIgnorePath, `${gitIgnoreContent}${entry}${eol}`)\n } else {\n writeFileSync(gitIgnorePath, `${gitIgnoreContent}${eol}${entry}${eol}`)\n }\n}\n\n/**\n * Options to use when cloning a git repository.\n *\n * @param repoUrl - The URL of the repository to clone.\n * @param destination - The directory where the repository will be cloned.\n * @param shallow - Whether to clone the repository shallowly.\n * @param latestTag - Whether to clone the latest tag instead of the default branch.\n */\nexport interface GitCloneOptions {\n repoUrl: string\n destination: string\n shallow?: boolean\n latestTag?: boolean\n}\n/**\n * Clone a git repository.\n *\n * @param cloneOptions - The options to use to clone the repository.\n * @returns A promise that resolves when the clone is complete.\n */\nexport async function downloadGitRepository(cloneOptions: GitCloneOptions): Promise<void> {\n return runWithTimer('cmd_all_timing_network_ms')(async () => {\n const {repoUrl, destination, shallow, latestTag} = cloneOptions\n outputDebug(outputContent`Git-cloning repository ${repoUrl} into ${outputToken.path(destination)}...`)\n await ensureGitIsPresentOrAbort()\n\n // Validate destination directory before attempting to clone\n if (await fileExists(destination)) {\n // Check if it's a directory\n if (!(await isDirectory(destination))) {\n throw new AbortError(\n outputContent`Can't clone to ${outputToken.path(destination)}`,\n \"The path exists but isn't a directory.\",\n )\n }\n\n // Check if directory is empty\n const entries = await glob(['*', '.*'], {\n cwd: destination,\n deep: 1,\n onlyFiles: false,\n })\n\n if (entries.length > 0) {\n throw new AbortError(\n outputContent`Directory ${outputToken.path(destination)} already exists and is not empty`,\n outputContent`Choose a different name or remove the existing directory first.`,\n )\n }\n }\n\n const [repository, branch] = repoUrl.split('#')\n\n if (branch && latestTag) {\n throw new AbortError(\"Error cloning the repository. Git can't clone the latest release with a 'branch'.\")\n }\n\n if (shallow && latestTag) {\n throw new AbortError(\n \"Error cloning the repository. Git can't clone the latest release with the 'shallow' property.\",\n )\n }\n\n const args = ['clone', '--recurse-submodules']\n if (branch) {\n args.push('--branch', branch)\n }\n if (shallow) {\n args.push('--depth', '1')\n }\n if (!isTerminalInteractive()) {\n args.push('-c', 'core.askpass=true')\n }\n args.push(repository!, destination)\n\n try {\n await execa('git', args)\n\n if (latestTag) {\n const tag = await getLatestTagFromDirectory(destination, repoUrl)\n await gitCommand(['checkout', tag], destination)\n }\n } catch (err) {\n if (err instanceof AbortError) {\n throw err\n }\n if (err instanceof Error) {\n const abortError = new AbortError(err.message)\n abortError.stack = err.stack\n throw abortError\n }\n throw err\n }\n })\n}\n\nasync function getLatestTagFromDirectory(directory: string, repoUrl: string): Promise<string> {\n const tag = await getLatestTag(directory)\n\n if (!tag) {\n throw new AbortError(`Couldn't obtain the most recent tag of the repository ${repoUrl}`)\n }\n\n return tag\n}\n\n/**\n * Get the latest commit of a git repository.\n *\n * @param directory - The directory of the git repository.\n * @returns The latest commit of the repository.\n */\nexport async function getLatestGitCommit(directory?: string): Promise<GitLogEntry> {\n const format = '%H%x00%ai%x00%s%x00%D%x00%b%x00%an%x00%ae'\n const stdout = await gitCommand(['log', '-1', `--format=${format}`], directory)\n if (!stdout.trim()) {\n throw new AbortError(\n 'Must have at least one commit to run command',\n outputContent`Run ${outputToken.genericShellCommand(\n \"git commit -m 'Initial commit'\",\n )} to create your first commit.`,\n )\n }\n const parts = stdout.split('\\x00')\n return {\n hash: parts[0]!,\n date: parts[1]!,\n message: parts[2]!,\n refs: parts[3]!,\n body: parts[4]!,\n author_name: parts[5]!,\n author_email: parts[6]!,\n }\n}\n\n/**\n * Add all files to the git index from the given directory.\n *\n * @param directory - The directory where the git repository is located.\n * @returns A promise that resolves when the files are added to the index.\n */\nexport async function addAllToGitFromDirectory(directory?: string): Promise<void> {\n await gitCommand(['add', '--all'], directory)\n}\n\nexport interface CreateGitCommitOptions {\n directory?: string\n author?: string\n}\n\n/**\n * Create a git commit.\n *\n * @param message - The message of the commit.\n * @param options - The options to use to create the commit.\n * @returns The hash of the created commit.\n */\nexport async function createGitCommit(message: string, options?: CreateGitCommitOptions): Promise<string> {\n const args = ['commit', '-m', message]\n if (options?.author) {\n args.push('--author', options.author)\n }\n await gitCommand(args, options?.directory)\n const stdout = await gitCommand(['rev-parse', 'HEAD'], options?.directory)\n return stdout.trim()\n}\n\n/**\n * Get the HEAD symbolic reference of a git repository.\n *\n * @param directory - The directory of the git repository.\n * @returns The HEAD symbolic reference of the repository.\n */\nexport async function getHeadSymbolicRef(directory?: string): Promise<string> {\n const ref = await gitCommand(['symbolic-ref', '-q', 'HEAD'], directory)\n if (!ref) {\n throw new AbortError(\n \"Git HEAD can't be detached to run command\",\n outputContent`Run ${outputToken.genericShellCommand(\n 'git checkout [branchName]',\n )} to reattach HEAD or see git ${outputToken.link(\n 'documentation',\n 'https://git-scm.com/book/en/v2/Git-Internals-Git-References',\n )} for more details`,\n )\n }\n return ref.trim()\n}\n\n/**\n * If \"git\" is not present in the environment it throws\n * an abort error.\n */\nexport async function ensureGitIsPresentOrAbort(): Promise<void> {\n if (!(await hasGit())) {\n throw new AbortError(\n `Git is necessary in the environment to continue`,\n outputContent`Install ${outputToken.link(\n 'git',\n 'https://git-scm.com/book/en/v2/Getting-Started-Installing-Git',\n )}`,\n )\n }\n}\n\nexport class OutsideGitDirectoryError extends AbortError {}\n/**\n * If command run from outside a .git directory tree\n * it throws an abort error.\n *\n * @param directory - The directory to check.\n */\nexport async function ensureInsideGitDirectory(directory?: string): Promise<void> {\n await ensureGitIsPresentOrAbort()\n\n if (!(await checkIfInsideGitDirectory(directory))) {\n throw new OutsideGitDirectoryError(`${outputToken.path(directory ?? cwd())} is not a Git directory`)\n }\n}\n\n/**\n * Returns true if the given directory is inside a .git directory tree.\n *\n * @param directory - The directory to check.\n * @returns True if the directory is inside a .git directory tree.\n */\nexport async function insideGitDirectory(directory?: string): Promise<boolean> {\n if (!(await hasGit())) {\n return false\n }\n\n return checkIfInsideGitDirectory(directory)\n}\n\nasync function checkIfInsideGitDirectory(directory?: string): Promise<boolean> {\n try {\n await execa('git', ['rev-parse', '--git-dir'], {cwd: directory})\n return true\n } catch (error) {\n if (error instanceof Error && 'exitCode' in error && error.exitCode === 128) return false\n throw error\n }\n}\n\nexport class GitDirectoryNotCleanError extends AbortError {}\n/**\n * If the .git directory tree is not clean (has uncommitted changes)\n * it throws an abort error.\n *\n * @param directory - The directory to check.\n */\nexport async function ensureIsClean(directory?: string): Promise<void> {\n if (!(await isClean(directory))) {\n throw new GitDirectoryNotCleanError(`${outputToken.path(directory ?? cwd())} is not a clean Git directory`)\n }\n}\n\n/**\n * Returns true if the .git directory tree is clean (no uncommitted changes).\n *\n * @param directory - The directory to check.\n * @returns True is the .git directory is clean.\n */\nexport async function isClean(directory?: string): Promise<boolean> {\n const stdout = await gitCommand(['status', '--porcelain'], directory)\n return stdout.trim() === ''\n}\n\n/**\n * Returns the latest tag of a git repository.\n *\n * @param directory - The directory to check.\n * @returns String with the latest tag or undefined if no tags are found.\n */\nexport async function getLatestTag(directory?: string): Promise<string | undefined> {\n try {\n const stdout = await gitCommand(['describe', '--tags', '--abbrev=0'], directory)\n return stdout.trim() || undefined\n } catch (error) {\n if (error instanceof AbortError && 'exitCode' in error && error.exitCode === 128) return undefined\n throw error\n }\n}\n\n/**\n * Remove a git remote from the given directory.\n *\n * @param directory - The directory where the git repository is located.\n * @param remoteName - The name of the remote to remove (defaults to 'origin').\n * @returns A promise that resolves when the remote is removed.\n */\nexport async function removeGitRemote(directory: string, remoteName = 'origin'): Promise<void> {\n outputDebug(outputContent`Removing git remote ${remoteName} from ${outputToken.path(directory)}...`)\n await ensureGitIsPresentOrAbort()\n\n const stdout = await gitCommand(['remote'], directory)\n const remotes = stdout.split('\\n').filter(Boolean)\n\n if (!remotes.includes(remoteName)) {\n outputDebug(outputContent`Remote ${remoteName} does not exist, no action needed`)\n return\n }\n\n await gitCommand(['remote', 'remove', remoteName], directory)\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { fileExistsSync, isDirectorySync } from './fs.js';
|
|
2
2
|
import { dirname, joinPath } from './path.js';
|
|
3
|
+
import { uniq } from '../common/array.js';
|
|
3
4
|
import { openSync, readSync, closeSync } from 'fs';
|
|
4
5
|
// Only read the first 128KB of each file for import scanning. This covers
|
|
5
6
|
// ~3,000+ lines which is more than enough to capture all static imports.
|
|
@@ -114,7 +115,7 @@ export function extractImportPathsRecursively(filePath, visited = new Set()) {
|
|
|
114
115
|
throw error;
|
|
115
116
|
}
|
|
116
117
|
}
|
|
117
|
-
return
|
|
118
|
+
return uniq(allImports);
|
|
118
119
|
}
|
|
119
120
|
/**
|
|
120
121
|
* Returns diagnostic information about the import scanning caches.
|
|
@@ -166,7 +167,7 @@ function extractJSLikeImports(content, filePath) {
|
|
|
166
167
|
}
|
|
167
168
|
}
|
|
168
169
|
}
|
|
169
|
-
return
|
|
170
|
+
return uniq(imports);
|
|
170
171
|
}
|
|
171
172
|
function extractRustImports(content, filePath) {
|
|
172
173
|
const imports = [];
|
|
@@ -193,7 +194,7 @@ function extractRustImports(content, filePath) {
|
|
|
193
194
|
}
|
|
194
195
|
}
|
|
195
196
|
}
|
|
196
|
-
return
|
|
197
|
+
return uniq(imports);
|
|
197
198
|
}
|
|
198
199
|
function resolveJSImport(importPath, fromFile) {
|
|
199
200
|
const basePath = cachedFileExists(fromFile) && cachedIsDir(fromFile) ? fromFile : dirname(fromFile);
|