@shopify/cli-kit 3.10.1 → 3.11.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/CHANGELOG.md +12 -0
- package/dist/api/admin.js +2 -6
- package/dist/api/admin.js.map +1 -1
- package/dist/api/identity.js +2 -2
- package/dist/api/identity.js.map +1 -1
- package/dist/api/partners.js +2 -10
- package/dist/api/partners.js.map +1 -1
- package/dist/common/result.d.ts +17 -0
- package/dist/common/result.js +31 -0
- package/dist/common/result.js.map +1 -0
- package/dist/constants.d.ts +5 -4
- package/dist/constants.js +6 -4
- package/dist/constants.js.map +1 -1
- package/dist/environment/fqdn.js +4 -4
- package/dist/environment/fqdn.js.map +1 -1
- package/dist/environment/local.d.ts +2 -0
- package/dist/environment/local.js +9 -0
- package/dist/environment/local.js.map +1 -1
- package/dist/environment/service.d.ts +2 -17
- package/dist/environment/service.js +5 -46
- package/dist/environment/service.js.map +1 -1
- package/dist/environment/spin-cache.d.ts +2 -0
- package/dist/environment/spin-cache.js +8 -0
- package/dist/environment/spin-cache.js.map +1 -0
- package/dist/environment/spin.d.ts +3 -0
- package/dist/environment/spin.js +19 -3
- package/dist/environment/spin.js.map +0 -1
- package/dist/error.d.ts +0 -1
- package/dist/error.js +0 -1
- package/dist/error.js.map +1 -1
- package/dist/http/fetch.d.ts +1 -2
- package/dist/http/fetch.js +2 -2
- package/dist/http/fetch.js.map +1 -1
- package/dist/http/graphql.d.ts +0 -2
- package/dist/http/graphql.js +1 -1
- package/dist/http/graphql.js.map +1 -1
- package/dist/http.d.ts +2 -3
- package/dist/http.js +5 -5
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/log.d.ts +21 -0
- package/dist/log.js +155 -0
- package/dist/log.js.map +1 -0
- package/dist/node/hooks/init.js +2 -2
- package/dist/node/hooks/init.js.map +1 -1
- package/dist/node/node-package-manager.d.ts +2 -2
- package/dist/node/node-package-manager.js +9 -16
- package/dist/node/node-package-manager.js.map +1 -1
- package/dist/output.d.ts +1 -8
- package/dist/output.js +2 -99
- package/dist/output.js.map +1 -1
- package/dist/port.js +1 -1
- package/dist/port.js.map +1 -1
- package/dist/session/device-authorization.d.ts +32 -0
- package/dist/session/device-authorization.js +86 -0
- package/dist/session/device-authorization.js.map +1 -0
- package/dist/session/exchange.d.ts +11 -0
- package/dist/session/exchange.js +22 -2
- package/dist/session/exchange.js.map +1 -1
- package/dist/session/identity.js +5 -5
- package/dist/session/identity.js.map +1 -1
- package/dist/session.js +21 -7
- package/dist/session.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/ui.js +2 -1
- package/dist/ui.js.map +1 -1
- package/package.json +1 -1
package/dist/error.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.js","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,gBAAgB,EAAE,KAAK,IAAI,WAAW,EAAC,MAAM,aAAa,CAAA;AAC3E,OAAO,EAAC,SAAS,EAAC,MAAM,WAAW,CAAA;AACnC,OAAO,EAAC,MAAM,EAAC,MAAM,aAAa,CAAA;AAElC,OAAO,EAAC,eAAe,EAAC,MAAM,UAAU,CAAA;
|
|
1
|
+
{"version":3,"file":"error.js","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,gBAAgB,EAAE,KAAK,IAAI,WAAW,EAAC,MAAM,aAAa,CAAA;AAC3E,OAAO,EAAC,SAAS,EAAC,MAAM,WAAW,CAAA;AACnC,OAAO,EAAC,MAAM,EAAC,MAAM,aAAa,CAAA;AAElC,OAAO,EAAC,eAAe,EAAC,MAAM,UAAU,CAAA;AAExC,IAAK,cAIJ;AAJD,WAAK,cAAc;IACjB,qDAAK,CAAA;IACL,iEAAW,CAAA;IACX,iDAAG,CAAA;AACL,CAAC,EAJI,cAAc,KAAd,cAAc,QAIlB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AAU,yBAAyB,CAAC,QAAgB;IACxD,OAAO,SAAS,CAAC,QAAQ,CAAC;SACvB,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC;SACtB,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAA;AAC9B,CAAC","sourcesContent":["import {Message, stringifyMessage, error as outputError} from './output.js'\nimport {normalize} from './path.js'\nimport {Errors} from '@oclif/core'\n\nexport {ExtendableError} from 'ts-error'\n\nenum FatalErrorType {\n Abort,\n AbortSilent,\n Bug,\n}\n\nexport class CancelExecution extends Error {}\n\n/**\n * A fatal error represents an error shouldn't be rescued and that causes the execution to terminate.\n * There shouldn't be code that catches fatal errors.\n */\nexport abstract class Fatal extends Error {\n tryMessage: string | null\n type: FatalErrorType\n constructor(message: Message, type: FatalErrorType, tryMessage: Message | null = null) {\n super(stringifyMessage(message))\n this.tryMessage = tryMessage ? stringifyMessage(tryMessage) : null\n this.type = type\n }\n}\n\n/**\n * An abort error is a fatal error that shouldn't be reported as a bug.\n * Those usually represent unexpected scenarios that we can't handle and that usually require some action from the developer\n */\nexport class Abort extends Fatal {\n constructor(message: Message, tryMessage: Message | null = null) {\n super(message, FatalErrorType.Abort, tryMessage)\n }\n}\n\nexport class AbortSilent extends Fatal {\n constructor() {\n super('', FatalErrorType.AbortSilent)\n }\n}\n\n/**\n * A bug error is an error that represents a bug and therefore should be reported.\n */\nexport class Bug extends Fatal {\n constructor(message: Message, tryMessage: string | null = null) {\n super(message, FatalErrorType.Bug, tryMessage)\n }\n}\n\n/**\n * A function that handles errors that blow up in the CLI.\n * @param error Error to be handled.\n * @returns A promise that resolves with the error passed.\n */\nexport async function handler(error: unknown): Promise<unknown> {\n let fatal: Fatal\n if (isFatal(error)) {\n fatal = error\n } else if (typeof error === 'string') {\n fatal = new Bug(error)\n } else if (error instanceof Error) {\n fatal = new Bug(error.message)\n fatal.stack = error.stack\n } else {\n // errors can come in all shapes and sizes...\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const maybeError = error as any\n fatal = new Bug(maybeError?.message ?? 'Unknown error')\n if (maybeError?.stack) {\n fatal.stack = maybeError?.stack\n }\n }\n\n await outputError(fatal)\n return Promise.resolve(error)\n}\n\nexport function mapper(error: unknown): Promise<unknown> {\n if (error instanceof Errors.CLIError) {\n const mappedError = new Abort(error.message)\n mappedError.stack = error.stack\n return Promise.resolve(mappedError)\n } else {\n return Promise.resolve(error)\n }\n}\n\nexport function isFatal(error: unknown): error is Fatal {\n try {\n return Object.prototype.hasOwnProperty.call(error, 'type')\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch {\n return false\n }\n}\n\nexport function shouldReport(error: unknown): boolean {\n if (!isFatal(error)) {\n return true\n }\n if (error.type === FatalErrorType.Bug) {\n return true\n }\n return false\n}\n\n/**\n * Stack traces usually have file:// - we strip that and also remove the Windows drive designation\n *\n */\nexport function cleanSingleStackTracePath(filePath: string): string {\n return normalize(filePath)\n .replace('file:/', '/')\n .replace(/^\\/?[A-Z]:/, '')\n}\n"]}
|
package/dist/http/fetch.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { Service } from '../network/service.js';
|
|
2
1
|
import nodeFetch from 'node-fetch';
|
|
3
2
|
import type { RequestInfo, RequestInit } from 'node-fetch';
|
|
4
3
|
declare type Response = ReturnType<typeof nodeFetch>;
|
|
@@ -19,5 +18,5 @@ export default function fetch(url: RequestInfo, init?: RequestInit): Response;
|
|
|
19
18
|
* TLS configuragion is used based on the environment in which the service is running
|
|
20
19
|
* (e.g. spin)
|
|
21
20
|
*/
|
|
22
|
-
export declare function shopifyFetch(
|
|
21
|
+
export declare function shopifyFetch(url: RequestInfo, init?: RequestInit): Response;
|
|
23
22
|
export {};
|
package/dist/http/fetch.js
CHANGED
|
@@ -20,8 +20,8 @@ export default async function fetch(url, init) {
|
|
|
20
20
|
* TLS configuragion is used based on the environment in which the service is running
|
|
21
21
|
* (e.g. spin)
|
|
22
22
|
*/
|
|
23
|
-
export async function shopifyFetch(
|
|
24
|
-
const response = await nodeFetch(url, { ...init, agent: await httpsAgent(
|
|
23
|
+
export async function shopifyFetch(url, init) {
|
|
24
|
+
const response = await nodeFetch(url, { ...init, agent: await httpsAgent() });
|
|
25
25
|
return response;
|
|
26
26
|
}
|
|
27
27
|
//# sourceMappingURL=fetch.js.map
|
package/dist/http/fetch.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../src/http/fetch.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../src/http/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,MAAM,YAAY,CAAA;AACrC,OAAO,SAAS,MAAM,YAAY,CAAA;AAIlC;;;;;;;;;;GAUG;AACH,MAAM,CAAC,OAAO,CAAC,KAAK,UAAU,KAAK,CAAC,GAAgB,EAAE,IAAkB;IACtE,MAAM,QAAQ,GAAG,MAAM,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC,CAAA;IAC3C,OAAO,QAAQ,CAAA;AACjB,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,GAAgB,EAAE,IAAkB;IACrE,MAAM,QAAQ,GAAG,MAAM,SAAS,CAAC,GAAG,EAAE,EAAC,GAAG,IAAI,EAAE,KAAK,EAAE,MAAM,UAAU,EAAE,EAAC,CAAC,CAAA;IAC3E,OAAO,QAAQ,CAAA;AACjB,CAAC","sourcesContent":["import {httpsAgent} from '../http.js'\nimport nodeFetch from 'node-fetch'\nimport type {RequestInfo, RequestInit} from 'node-fetch'\n\ntype Response = ReturnType<typeof nodeFetch>\n/**\n * An interface that abstracts way node-fetch. When Node has built-in\n * support for \"fetch\" in the standard library, we can drop the node-fetch\n * dependency from here.\n * Note that we are exposing types from \"node-fetch\". The reason being is that\n * they are consistent with the Web API so if we drop node-fetch in the future\n * it won't require changes from the callers.\n * @param url {RequestInfo} This defines the resource that you wish to fetch.\n * @param init {RequestInit} An object containing any custom settings that you want to apply to the request\n * @returns A promise that resolves with the response.\n */\nexport default async function fetch(url: RequestInfo, init?: RequestInit): Response {\n const response = await nodeFetch(url, init)\n return response\n}\n\n/**\n * A fetch function to use with Shopify services. The function ensures the right\n * TLS configuragion is used based on the environment in which the service is running\n * (e.g. spin)\n */\nexport async function shopifyFetch(url: RequestInfo, init?: RequestInit): Response {\n const response = await nodeFetch(url, {...init, agent: await httpsAgent()})\n return response\n}\n"]}
|
package/dist/http/graphql.d.ts
CHANGED
package/dist/http/graphql.js
CHANGED
|
@@ -5,7 +5,7 @@ import { GraphQLClient } from 'graphql-request';
|
|
|
5
5
|
* the client will interact with.
|
|
6
6
|
*/
|
|
7
7
|
export async function graphqlClient(options) {
|
|
8
|
-
const clientOptions = { agent: await httpsAgent(
|
|
8
|
+
const clientOptions = { agent: await httpsAgent(), headers: options.headers };
|
|
9
9
|
const client = new GraphQLClient(options.url, clientOptions);
|
|
10
10
|
return client;
|
|
11
11
|
}
|
package/dist/http/graphql.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graphql.js","sourceRoot":"","sources":["../../src/http/graphql.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"graphql.js","sourceRoot":"","sources":["../../src/http/graphql.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,MAAM,YAAY,CAAA;AACrC,OAAO,EAAC,aAAa,EAAC,MAAM,iBAAiB,CAAA;AAO7C;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,OAA6B;IAC/D,MAAM,aAAa,GAAG,EAAC,KAAK,EAAE,MAAM,UAAU,EAAE,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAC,CAAA;IAC3E,MAAM,MAAM,GAAG,IAAI,aAAa,CAAC,OAAO,CAAC,GAAG,EAAE,aAAa,CAAC,CAAA;IAC5D,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import {httpsAgent} from '../http.js'\nimport {GraphQLClient} from 'graphql-request'\n\ninterface GraphqlClientOptions {\n url: string\n headers: {[key: string]: string}\n}\n\n/**\n * Creates a GraphQLClient instance with the right HTTPs agent baed on the service\n * the client will interact with.\n */\nexport async function graphqlClient(options: GraphqlClientOptions) {\n const clientOptions = {agent: await httpsAgent(), headers: options.headers}\n const client = new GraphQLClient(options.url, clientOptions)\n return client\n}\n"]}
|
package/dist/http.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
|
-
import { Service } from './network/service.js';
|
|
3
2
|
import https from 'https';
|
|
4
3
|
export { default as fetch } from './http/fetch.js';
|
|
5
4
|
export { shopifyFetch } from './http/fetch.js';
|
|
@@ -10,7 +9,7 @@ export { default as formData } from './http/formdata.js';
|
|
|
10
9
|
* if the service is running in a Spin environment, the attribute "rejectUnauthorized" is
|
|
11
10
|
* set to false
|
|
12
11
|
*/
|
|
13
|
-
export declare function httpsAgent(
|
|
12
|
+
export declare function httpsAgent(): Promise<https.Agent>;
|
|
14
13
|
/**
|
|
15
14
|
* Spin stores the CA certificate in the keychain and it should be used when sending HTTP
|
|
16
15
|
* requests to Spin instances. However, Node doesn't read certificates from the Keychain
|
|
@@ -23,4 +22,4 @@ export declare function httpsAgent(service: Service): Promise<https.Agent>;
|
|
|
23
22
|
* @returns {Promise<boolean>} A promise that resolves with a boolean indicating whether
|
|
24
23
|
* unauthorized requests should be rejected or not.
|
|
25
24
|
*/
|
|
26
|
-
export declare function shouldRejectUnauthorizedRequests(
|
|
25
|
+
export declare function shouldRejectUnauthorizedRequests(): Promise<boolean>;
|
package/dist/http.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { serviceEnvironment } from './environment/service.js';
|
|
2
2
|
import https from 'https';
|
|
3
3
|
export { default as fetch } from './http/fetch.js';
|
|
4
4
|
export { shopifyFetch } from './http/fetch.js';
|
|
@@ -9,8 +9,8 @@ export { default as formData } from './http/formdata.js';
|
|
|
9
9
|
* if the service is running in a Spin environment, the attribute "rejectUnauthorized" is
|
|
10
10
|
* set to false
|
|
11
11
|
*/
|
|
12
|
-
export async function httpsAgent(
|
|
13
|
-
return new https.Agent({ rejectUnauthorized: await shouldRejectUnauthorizedRequests(
|
|
12
|
+
export async function httpsAgent() {
|
|
13
|
+
return new https.Agent({ rejectUnauthorized: await shouldRejectUnauthorizedRequests() });
|
|
14
14
|
}
|
|
15
15
|
/**
|
|
16
16
|
* Spin stores the CA certificate in the keychain and it should be used when sending HTTP
|
|
@@ -24,7 +24,7 @@ export async function httpsAgent(service) {
|
|
|
24
24
|
* @returns {Promise<boolean>} A promise that resolves with a boolean indicating whether
|
|
25
25
|
* unauthorized requests should be rejected or not.
|
|
26
26
|
*/
|
|
27
|
-
export async function shouldRejectUnauthorizedRequests(
|
|
28
|
-
return (await
|
|
27
|
+
export async function shouldRejectUnauthorizedRequests() {
|
|
28
|
+
return (await serviceEnvironment()) !== 'spin';
|
|
29
29
|
}
|
|
30
30
|
//# sourceMappingURL=http.js.map
|
package/dist/http.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.js","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"http.js","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,kBAAkB,EAAC,MAAM,0BAA0B,CAAA;AAC3D,OAAO,KAAK,MAAM,OAAO,CAAA;AAEzB,OAAO,EAAC,OAAO,IAAI,KAAK,EAAC,MAAM,iBAAiB,CAAA;AAChD,OAAO,EAAC,YAAY,EAAC,MAAM,iBAAiB,CAAA;AAC5C,OAAO,EAAC,OAAO,IAAI,QAAQ,EAAC,MAAM,oBAAoB,CAAA;AAEtD;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU;IAC9B,OAAO,IAAI,KAAK,CAAC,KAAK,CAAC,EAAC,kBAAkB,EAAE,MAAM,gCAAgC,EAAE,EAAC,CAAC,CAAA;AACxF,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,gCAAgC;IACpD,OAAO,CAAC,MAAM,kBAAkB,EAAE,CAAC,KAAK,MAAM,CAAA;AAChD,CAAC","sourcesContent":["import {serviceEnvironment} from './environment/service.js'\nimport https from 'https'\n\nexport {default as fetch} from './http/fetch.js'\nexport {shopifyFetch} from './http/fetch.js'\nexport {default as formData} from './http/formdata.js'\n\n/**\n * This utility function returns the https.Agent to use for a given service. The agent\n * includes the right configuration based on the service's environment. For example,\n * if the service is running in a Spin environment, the attribute \"rejectUnauthorized\" is\n * set to false\n */\nexport async function httpsAgent() {\n return new https.Agent({rejectUnauthorized: await shouldRejectUnauthorizedRequests()})\n}\n\n/**\n * Spin stores the CA certificate in the keychain and it should be used when sending HTTP\n * requests to Spin instances. However, Node doesn't read certificates from the Keychain\n * by default, which leads to Shopifolks running into issues that they workaround by setting the\n * NODE_TLS_REJECT_UNAUTHORIZED=0 environment variable, which applies to all the HTTP\n * requests sent from the CLI (context: https://github.com/nodejs/node/issues/39657)\n * This utility function allows controlling the behavior in a per-service level by returning\n * the value of for the \"rejectUnauthorized\" attribute that's used in the https agent.\n *\n * @returns {Promise<boolean>} A promise that resolves with a boolean indicating whether\n * unauthorized requests should be rejected or not.\n */\nexport async function shouldRejectUnauthorizedRequests(): Promise<boolean> {\n return (await serviceEnvironment()) !== 'spin'\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -13,6 +13,7 @@ export * as github from './github.js';
|
|
|
13
13
|
export * as haiku from './haiku.js';
|
|
14
14
|
export * as http from './http.js';
|
|
15
15
|
export * as id from './id.js';
|
|
16
|
+
export * as log from './log.js';
|
|
16
17
|
export * as npm from './npm.js';
|
|
17
18
|
export * as os from './os.js';
|
|
18
19
|
export * as output from './output.js';
|
package/dist/index.js
CHANGED
|
@@ -13,6 +13,7 @@ export * as github from './github.js';
|
|
|
13
13
|
export * as haiku from './haiku.js';
|
|
14
14
|
export * as http from './http.js';
|
|
15
15
|
export * as id from './id.js';
|
|
16
|
+
export * as log from './log.js';
|
|
16
17
|
export * as npm from './npm.js';
|
|
17
18
|
export * as os from './os.js';
|
|
18
19
|
export * as output from './output.js';
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,OAAO,IAAI,SAAS,EAAC,MAAM,gBAAgB,CAAA;AACnD,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,OAAO,KAAK,SAAS,MAAM,gBAAgB,CAAA;AAC3C,OAAO,KAAK,GAAG,MAAM,UAAU,CAAA;AAC/B,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,OAAO,KAAK,GAAG,MAAM,UAAU,CAAA;AAC/B,OAAO,KAAK,WAAW,MAAM,kBAAkB,CAAA;AAC/C,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,OAAO,KAAK,OAAO,MAAM,SAAS,CAAA;AAClC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,GAAG,MAAM,UAAU,CAAA;AAC/B,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,EAAE,MAAM,SAAS,CAAA;AAC7B,OAAO,KAAK,GAAG,MAAM,UAAU,CAAA;AAC/B,OAAO,KAAK,EAAE,MAAM,SAAS,CAAA;AAC7B,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,OAAO,MAAM,cAAc,CAAA;AACvC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,OAAO,MAAM,cAAc,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,EAAE,MAAM,SAAS,CAAA;AAC7B,OAAO,KAAK,OAAO,MAAM,cAAc,CAAA;AACvC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,YAAY,MAAM,qBAAqB,CAAA;AACnD,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA","sourcesContent":["export {default as constants} from './constants.js'\nexport * as abort from './abort.js'\nexport * as analytics from './analytics.js'\nexport * as api from './api.js'\nexport * as array from './array.js'\nexport * as cli from './cli.js'\nexport * as environment from './environment.js'\nexport * as error from './error.js'\nexport * as fastify from 'fastify'\nexport * as file from './file.js'\nexport * as git from './git.js'\nexport * as github from './github.js'\nexport * as haiku from './haiku.js'\nexport * as http from './http.js'\nexport * as id from './id.js'\nexport * as npm from './npm.js'\nexport * as os from './os.js'\nexport * as output from './output.js'\nexport * as path from './path.js'\nexport * as plugins from './plugins.js'\nexport * as port from './port.js'\nexport * as schema from './schema.js'\nexport * as semver from './semver.js'\nexport * as session from './session.js'\nexport * as store from './store.js'\nexport * as string from './string.js'\nexport * as system from './system.js'\nexport * as template from './template.js'\nexport * as toml from './toml.js'\nexport * as ui from './ui.js'\nexport * as version from './version.js'\nexport * as vscode from './vscode.js'\nexport * as yaml from './yaml.js'\nexport * as outputMocker from './testing/output.js'\nexport * as metadata from './metadata.js'\nexport * as monorail from './monorail.js'\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,OAAO,IAAI,SAAS,EAAC,MAAM,gBAAgB,CAAA;AACnD,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,OAAO,KAAK,SAAS,MAAM,gBAAgB,CAAA;AAC3C,OAAO,KAAK,GAAG,MAAM,UAAU,CAAA;AAC/B,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,OAAO,KAAK,GAAG,MAAM,UAAU,CAAA;AAC/B,OAAO,KAAK,WAAW,MAAM,kBAAkB,CAAA;AAC/C,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,OAAO,KAAK,OAAO,MAAM,SAAS,CAAA;AAClC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,GAAG,MAAM,UAAU,CAAA;AAC/B,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,EAAE,MAAM,SAAS,CAAA;AAC7B,OAAO,KAAK,GAAG,MAAM,UAAU,CAAA;AAC/B,OAAO,KAAK,GAAG,MAAM,UAAU,CAAA;AAC/B,OAAO,KAAK,EAAE,MAAM,SAAS,CAAA;AAC7B,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,OAAO,MAAM,cAAc,CAAA;AACvC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,OAAO,MAAM,cAAc,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,EAAE,MAAM,SAAS,CAAA;AAC7B,OAAO,KAAK,OAAO,MAAM,cAAc,CAAA;AACvC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,YAAY,MAAM,qBAAqB,CAAA;AACnD,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA","sourcesContent":["export {default as constants} from './constants.js'\nexport * as abort from './abort.js'\nexport * as analytics from './analytics.js'\nexport * as api from './api.js'\nexport * as array from './array.js'\nexport * as cli from './cli.js'\nexport * as environment from './environment.js'\nexport * as error from './error.js'\nexport * as fastify from 'fastify'\nexport * as file from './file.js'\nexport * as git from './git.js'\nexport * as github from './github.js'\nexport * as haiku from './haiku.js'\nexport * as http from './http.js'\nexport * as id from './id.js'\nexport * as log from './log.js'\nexport * as npm from './npm.js'\nexport * as os from './os.js'\nexport * as output from './output.js'\nexport * as path from './path.js'\nexport * as plugins from './plugins.js'\nexport * as port from './port.js'\nexport * as schema from './schema.js'\nexport * as semver from './semver.js'\nexport * as session from './session.js'\nexport * as store from './store.js'\nexport * as string from './string.js'\nexport * as system from './system.js'\nexport * as template from './template.js'\nexport * as toml from './toml.js'\nexport * as ui from './ui.js'\nexport * as version from './version.js'\nexport * as vscode from './vscode.js'\nexport * as yaml from './yaml.js'\nexport * as outputMocker from './testing/output.js'\nexport * as metadata from './metadata.js'\nexport * as monorail from './monorail.js'\n"]}
|
package/dist/log.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
import { Transform, TransformCallback, TransformOptions } from 'node:stream';
|
|
3
|
+
export declare class LinesTruncatorTransformer extends Transform {
|
|
4
|
+
readonly maxFileSize: number;
|
|
5
|
+
linesToRetain: string[];
|
|
6
|
+
lastLineCompleted: boolean;
|
|
7
|
+
constructor(maxFileSize: number, opts?: TransformOptions);
|
|
8
|
+
_transform(chunk: unknown, encoding: BufferEncoding, callback: TransformCallback): void;
|
|
9
|
+
_flush(callback: TransformCallback): void;
|
|
10
|
+
calculateNumLinesToRetain(): number;
|
|
11
|
+
completeLastLine(tokens: string[]): void;
|
|
12
|
+
}
|
|
13
|
+
export declare function initiateLogging(options?: {
|
|
14
|
+
logDir?: string;
|
|
15
|
+
override?: boolean;
|
|
16
|
+
}): Promise<void>;
|
|
17
|
+
export declare function closeLogging(): void;
|
|
18
|
+
export declare function logToFile(message: string, logLevel: string): void;
|
|
19
|
+
export declare function pageLogs({ lastCommand }: {
|
|
20
|
+
lastCommand: boolean;
|
|
21
|
+
}): Promise<void>;
|
package/dist/log.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { isUnitTest } from './environment/local.js';
|
|
2
|
+
import constants from './constants.js';
|
|
3
|
+
import { generateRandomUUID } from './id.js';
|
|
4
|
+
import { mkdirSync as fileMkdirSync, sizeSync as fileSizeSync, touchSync as fileTouchSync, readSync as fileReadSync, } from './file.js';
|
|
5
|
+
import { join as pathJoin } from './path.js';
|
|
6
|
+
import { consoleLog } from './output.js';
|
|
7
|
+
import { page } from './system.js';
|
|
8
|
+
import { promisify } from 'node:util';
|
|
9
|
+
import { Stream, Transform } from 'node:stream';
|
|
10
|
+
import { createWriteStream, createReadStream, unlinkSync } from 'node:fs';
|
|
11
|
+
import { EOL } from 'node:os';
|
|
12
|
+
const logFileName = 'shopify.cli.log';
|
|
13
|
+
const maxLogFileSize = 5 * 1024 * 1024;
|
|
14
|
+
let logFileStream;
|
|
15
|
+
let commandUuid;
|
|
16
|
+
let logFilePath;
|
|
17
|
+
export class LinesTruncatorTransformer extends Transform {
|
|
18
|
+
constructor(maxFileSize, opts) {
|
|
19
|
+
super(opts);
|
|
20
|
+
this.maxFileSize = maxFileSize;
|
|
21
|
+
this.linesToRetain = [];
|
|
22
|
+
this.lastLineCompleted = true;
|
|
23
|
+
}
|
|
24
|
+
_transform(chunk, encoding, callback) {
|
|
25
|
+
const tokens = chunk.toString().split(EOL);
|
|
26
|
+
this.completeLastLine(tokens);
|
|
27
|
+
// last splitted token will be an empty string when last character is a breakline
|
|
28
|
+
this.lastLineCompleted = tokens[tokens.length - 1] === '';
|
|
29
|
+
if (this.lastLineCompleted) {
|
|
30
|
+
tokens.pop();
|
|
31
|
+
}
|
|
32
|
+
this.linesToRetain = this.linesToRetain.concat(tokens);
|
|
33
|
+
const numLinesToRetain = this.calculateNumLinesToRetain();
|
|
34
|
+
if (this.linesToRetain.length > numLinesToRetain) {
|
|
35
|
+
this.linesToRetain = this.linesToRetain.splice(this.linesToRetain.length - numLinesToRetain);
|
|
36
|
+
}
|
|
37
|
+
callback();
|
|
38
|
+
}
|
|
39
|
+
_flush(callback) {
|
|
40
|
+
this.push(this.linesToRetain.join(EOL));
|
|
41
|
+
callback();
|
|
42
|
+
}
|
|
43
|
+
// Lines retained length average is used so the number of lines depends on the length of them
|
|
44
|
+
calculateNumLinesToRetain() {
|
|
45
|
+
return Math.floor(this.maxFileSize /
|
|
46
|
+
(this.linesToRetain.map((line) => line.length).reduce((l1, l2) => l1 + l2, 0) / this.linesToRetain.length));
|
|
47
|
+
}
|
|
48
|
+
completeLastLine(tokens) {
|
|
49
|
+
if (this.lastLineCompleted) {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
const remainingToken = tokens.shift() ?? '';
|
|
53
|
+
const incompleteToken = this.linesToRetain[this.linesToRetain.length - 1] ?? '';
|
|
54
|
+
this.linesToRetain[this.linesToRetain.length - 1] = incompleteToken.concat(remainingToken);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
export async function initiateLogging(options = {}) {
|
|
58
|
+
if (isUnitTest())
|
|
59
|
+
return;
|
|
60
|
+
commandUuid = generateRandomUUID();
|
|
61
|
+
logFilePath = getLogFilePath(options);
|
|
62
|
+
await truncateLogs(logFilePath);
|
|
63
|
+
logFileStream = createWriteStream(logFilePath, { flags: 'a' });
|
|
64
|
+
}
|
|
65
|
+
export function closeLogging() {
|
|
66
|
+
if (logFileExists()) {
|
|
67
|
+
logFileStream.end();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
// DO NOT USE THIS FUNCTION DIRECTLY under normal circumstances.
|
|
71
|
+
// It is exported purely for use in cases where output is already being logged
|
|
72
|
+
// to the terminal but is not reflected in the logfile, e.g. Listr output.
|
|
73
|
+
export function logToFile(message, logLevel) {
|
|
74
|
+
// If file logging hasn't been initiated, skip it
|
|
75
|
+
if (!logFileExists())
|
|
76
|
+
return;
|
|
77
|
+
const timestamp = new Date().toISOString();
|
|
78
|
+
const logContents = `[${timestamp} ${commandUuid} ${logLevel}]: ${message}\n`;
|
|
79
|
+
logFileStream.write(logContents);
|
|
80
|
+
}
|
|
81
|
+
export async function pageLogs({ lastCommand }) {
|
|
82
|
+
const logDir = constants.paths.directories.cache.path();
|
|
83
|
+
const logFile = pathJoin(logDir, logFileName);
|
|
84
|
+
// Ensure file exists in case they deleted it or something
|
|
85
|
+
fileTouchSync(logFile);
|
|
86
|
+
if (lastCommand) {
|
|
87
|
+
printLastCommand(logFile);
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
await page(logFile);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function getLogFilePath(options = {}) {
|
|
94
|
+
if (!logFilePath || options.override) {
|
|
95
|
+
const logDir = options.logDir || constants.paths.directories.cache.path();
|
|
96
|
+
fileMkdirSync(logDir);
|
|
97
|
+
logFilePath = pathJoin(logDir, logFileName);
|
|
98
|
+
fileTouchSync(logFilePath);
|
|
99
|
+
}
|
|
100
|
+
return logFilePath;
|
|
101
|
+
}
|
|
102
|
+
// Shaves off older log lines if logs are over maxLogFileSize long.
|
|
103
|
+
async function truncateLogs(logFile) {
|
|
104
|
+
if (fileSizeSync(logFile) < maxLogFileSize) {
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
const tmpLogFile = logFile.concat('.tmp');
|
|
108
|
+
const truncateLines = new LinesTruncatorTransformer(maxLogFileSize);
|
|
109
|
+
const pipeline = promisify(Stream.pipeline);
|
|
110
|
+
await pipeline(createReadStream(logFile), truncateLines, createWriteStream(tmpLogFile));
|
|
111
|
+
await pipeline(createReadStream(tmpLogFile), createWriteStream(logFile));
|
|
112
|
+
unlinkSync(tmpLogFile);
|
|
113
|
+
}
|
|
114
|
+
function logFileExists() {
|
|
115
|
+
return Boolean(logFileStream);
|
|
116
|
+
}
|
|
117
|
+
function printLastCommand(logFile) {
|
|
118
|
+
const contents = fileReadSync(logFile).split('\n');
|
|
119
|
+
const uuids = contents
|
|
120
|
+
.map(logfileLineUUID)
|
|
121
|
+
.filter((uuid) => uuid)
|
|
122
|
+
.reverse();
|
|
123
|
+
// 2nd unique UUID, because the currently running command will be the 1st
|
|
124
|
+
const relevantUuid = Array.from(new Set(uuids))[1];
|
|
125
|
+
if (relevantUuid) {
|
|
126
|
+
consoleLog(relevantLines(contents, relevantUuid).join('\n'));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
function relevantLines(contents, relevantUuid) {
|
|
130
|
+
// We run through the file line by line, keeping track of the most recently
|
|
131
|
+
// encountered UUID.
|
|
132
|
+
//
|
|
133
|
+
// If the current line has a UUID, it's a new logged unit and should be
|
|
134
|
+
// considered. Otherwise, the line is related to the most recent UUID.
|
|
135
|
+
let mostRecentUuid = '';
|
|
136
|
+
return contents.filter((line) => {
|
|
137
|
+
const currentUuid = logfileLineUUID(line) || mostRecentUuid;
|
|
138
|
+
mostRecentUuid = currentUuid;
|
|
139
|
+
return currentUuid === relevantUuid;
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
function logfileLineUUID(line) {
|
|
143
|
+
// Log lines look like:
|
|
144
|
+
//
|
|
145
|
+
// timestamp UUID contents
|
|
146
|
+
// ===========================================================================================
|
|
147
|
+
// [2022-07-20T08:51:40.296Z 5288e1da-a06a-4f96-b1a6-e34fcdd7b416 DEBUG]: Running command logs
|
|
148
|
+
// ===========================================================================================
|
|
149
|
+
//
|
|
150
|
+
// There may be subsequent lines if the contents section is multi-line.
|
|
151
|
+
//
|
|
152
|
+
const match = line.match(/^\[\S+ ([0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}) [A-Z]+\]/);
|
|
153
|
+
return match && match[1];
|
|
154
|
+
}
|
|
155
|
+
//# sourceMappingURL=log.js.map
|
package/dist/log.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"log.js","sourceRoot":"","sources":["../src/log.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,MAAM,wBAAwB,CAAA;AACjD,OAAO,SAAS,MAAM,gBAAgB,CAAA;AACtC,OAAO,EAAC,kBAAkB,EAAC,MAAM,SAAS,CAAA;AAC1C,OAAO,EACL,SAAS,IAAI,aAAa,EAC1B,QAAQ,IAAI,YAAY,EACxB,SAAS,IAAI,aAAa,EAC1B,QAAQ,IAAI,YAAY,GACzB,MAAM,WAAW,CAAA;AAClB,OAAO,EAAC,IAAI,IAAI,QAAQ,EAAC,MAAM,WAAW,CAAA;AAC1C,OAAO,EAAC,UAAU,EAAC,MAAM,aAAa,CAAA;AACtC,OAAO,EAAC,IAAI,EAAC,MAAM,aAAa,CAAA;AAChC,OAAO,EAAC,SAAS,EAAC,MAAM,WAAW,CAAA;AACnC,OAAO,EAAC,MAAM,EAAE,SAAS,EAAsC,MAAM,aAAa,CAAA;AAClF,OAAO,EAAc,iBAAiB,EAAE,gBAAgB,EAAE,UAAU,EAAC,MAAM,SAAS,CAAA;AACpF,OAAO,EAAC,GAAG,EAAC,MAAM,SAAS,CAAA;AAE3B,MAAM,WAA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AG,EAAE,CAAA;IACvB,OAAO,QAAQ,CAAC,MAAM,CAAC,CAAC,IAAY,EAAE,EAAE;QACtC,MAAM,WAAW,GAAG,eAAe,CAAC,IAAI,CAAC,IAAI,cAAc,CAAA;QAC3D,cAAc,GAAG,WAAW,CAAA;QAC5B,OAAO,WAAW,KAAK,YAAY,CAAA;IACrC,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,SAAS,eAAe,CAAC,IAAY;IACnC,uBAAuB;IACvB,EAAE;IACF,uFAAuF;IACvF,8FAA8F;IAC9F,8FAA8F;IAC9F,8FAA8F;IAC9F,EAAE;IACF,uEAAuE;IACvE,EAAE;IACF,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,6DAA6D,CAAC,CAAA;IACvF,OAAO,KAAK,IAAI,KAAK,CAAC,CAAC,CAAE,CAAA;AAC3B,CAAC","sourcesContent":["import {isUnitTest} from './environment/local.js'\nimport constants from './constants.js'\nimport {generateRandomUUID} from './id.js'\nimport {\n mkdirSync as fileMkdirSync,\n sizeSync as fileSizeSync,\n touchSync as fileTouchSync,\n readSync as fileReadSync,\n} from './file.js'\nimport {join as pathJoin} from './path.js'\nimport {consoleLog} from './output.js'\nimport {page} from './system.js'\nimport {promisify} from 'node:util'\nimport {Stream, Transform, TransformCallback, TransformOptions} from 'node:stream'\nimport {WriteStream, createWriteStream, createReadStream, unlinkSync} from 'node:fs'\nimport {EOL} from 'node:os'\n\nconst logFileName = 'shopify.cli.log'\nconst maxLogFileSize = 5 * 1024 * 1024\nlet logFileStream: WriteStream\nlet commandUuid: string\nlet logFilePath: string\nexport class LinesTruncatorTransformer extends Transform {\n linesToRetain: string[] = []\n lastLineCompleted = true\n\n constructor(readonly maxFileSize: number, opts?: TransformOptions) {\n super(opts)\n }\n\n _transform(chunk: unknown, encoding: BufferEncoding, callback: TransformCallback): void {\n const tokens = (chunk as string).toString().split(EOL)\n\n this.completeLastLine(tokens)\n // last splitted token will be an empty string when last character is a breakline\n this.lastLineCompleted = tokens[tokens.length - 1] === ''\n if (this.lastLineCompleted) {\n tokens.pop()\n }\n this.linesToRetain = this.linesToRetain.concat(tokens)\n\n const numLinesToRetain = this.calculateNumLinesToRetain()\n if (this.linesToRetain.length > numLinesToRetain) {\n this.linesToRetain = this.linesToRetain.splice(this.linesToRetain.length - numLinesToRetain)\n }\n callback()\n }\n\n _flush(callback: TransformCallback): void {\n this.push(this.linesToRetain.join(EOL))\n callback()\n }\n\n // Lines retained length average is used so the number of lines depends on the length of them\n calculateNumLinesToRetain() {\n return Math.floor(\n this.maxFileSize /\n (this.linesToRetain.map((line) => line.length).reduce((l1, l2) => l1 + l2, 0) / this.linesToRetain.length),\n )\n }\n\n completeLastLine(tokens: string[]) {\n if (this.lastLineCompleted) {\n return\n }\n\n const remainingToken = tokens.shift() ?? ''\n const incompleteToken = this.linesToRetain[this.linesToRetain.length - 1] ?? ''\n this.linesToRetain[this.linesToRetain.length - 1] = incompleteToken.concat(remainingToken)\n }\n}\n\nexport async function initiateLogging(options: {logDir?: string; override?: boolean} = {}) {\n if (isUnitTest()) return\n commandUuid = generateRandomUUID()\n logFilePath = getLogFilePath(options)\n await truncateLogs(logFilePath)\n logFileStream = createWriteStream(logFilePath, {flags: 'a'})\n}\n\nexport function closeLogging() {\n if (logFileExists()) {\n logFileStream.end()\n }\n}\n\n// DO NOT USE THIS FUNCTION DIRECTLY under normal circumstances.\n// It is exported purely for use in cases where output is already being logged\n// to the terminal but is not reflected in the logfile, e.g. Listr output.\nexport function logToFile(message: string, logLevel: string): void {\n // If file logging hasn't been initiated, skip it\n if (!logFileExists()) return\n const timestamp = new Date().toISOString()\n const logContents = `[${timestamp} ${commandUuid} ${logLevel}]: ${message}\\n`\n logFileStream.write(logContents)\n}\n\nexport async function pageLogs({lastCommand}: {lastCommand: boolean}) {\n const logDir = constants.paths.directories.cache.path()\n const logFile = pathJoin(logDir, logFileName)\n // Ensure file exists in case they deleted it or something\n fileTouchSync(logFile)\n if (lastCommand) {\n printLastCommand(logFile)\n } else {\n await page(logFile)\n }\n}\n\nfunction getLogFilePath(options: {logDir?: string; override?: boolean} = {}) {\n if (!logFilePath || options.override) {\n const logDir = options.logDir || constants.paths.directories.cache.path()\n fileMkdirSync(logDir)\n logFilePath = pathJoin(logDir, logFileName)\n fileTouchSync(logFilePath)\n }\n\n return logFilePath\n}\n\n// Shaves off older log lines if logs are over maxLogFileSize long.\nasync function truncateLogs(logFile: string) {\n if (fileSizeSync(logFile) < maxLogFileSize) {\n return\n }\n const tmpLogFile = logFile.concat('.tmp')\n const truncateLines = new LinesTruncatorTransformer(maxLogFileSize)\n const pipeline = promisify(Stream.pipeline)\n await pipeline(createReadStream(logFile), truncateLines, createWriteStream(tmpLogFile))\n await pipeline(createReadStream(tmpLogFile), createWriteStream(logFile))\n unlinkSync(tmpLogFile)\n}\n\nfunction logFileExists(): boolean {\n return Boolean(logFileStream)\n}\n\nfunction printLastCommand(logFile: string): void {\n const contents = fileReadSync(logFile).split('\\n')\n const uuids = contents\n .map(logfileLineUUID)\n .filter((uuid) => uuid)\n .reverse()\n // 2nd unique UUID, because the currently running command will be the 1st\n const relevantUuid = Array.from(new Set(uuids))[1]\n if (relevantUuid) {\n consoleLog(relevantLines(contents, relevantUuid).join('\\n'))\n }\n}\n\nfunction relevantLines(contents: string[], relevantUuid: string): string[] {\n // We run through the file line by line, keeping track of the most recently\n // encountered UUID.\n //\n // If the current line has a UUID, it's a new logged unit and should be\n // considered. Otherwise, the line is related to the most recent UUID.\n let mostRecentUuid = ''\n return contents.filter((line: string) => {\n const currentUuid = logfileLineUUID(line) || mostRecentUuid\n mostRecentUuid = currentUuid\n return currentUuid === relevantUuid\n })\n}\n\nfunction logfileLineUUID(line: string): string | null {\n // Log lines look like:\n //\n // timestamp UUID contents\n // ===========================================================================================\n // [2022-07-20T08:51:40.296Z 5288e1da-a06a-4f96-b1a6-e34fcdd7b416 DEBUG]: Running command logs\n // ===========================================================================================\n //\n // There may be subsequent lines if the contents section is multi-line.\n //\n const match = line.match(/^\\[\\S+ ([0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}) [A-Z]+\\]/)\n return match && match[1]!\n}\n"]}
|
package/dist/node/hooks/init.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.js","sourceRoot":"","sources":["../../../src/node/hooks/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,eAAe,EAAC,MAAM,
|
|
1
|
+
{"version":3,"file":"init.js","sourceRoot":"","sources":["../../../src/node/hooks/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,eAAe,EAAC,MAAM,cAAc,CAAA;AAG5C,MAAM,CAAC,MAAM,IAAI,GAAc,KAAK,EAAE,OAAO,EAAE,EAAE;IAC/C,MAAM,eAAe,EAAE,CAAA;AACzB,CAAC,CAAA","sourcesContent":["import {initiateLogging} from '../../log.js'\nimport {Hook} from '@oclif/core'\n\nexport const hook: Hook.Init = async (options) => {\n await initiateLogging()\n}\n"]}
|
|
@@ -174,9 +174,9 @@ export interface DependencyVersion {
|
|
|
174
174
|
* @param dependencies {string[]} List of dependencies to be added.
|
|
175
175
|
* @param options {AddNPMDependenciesIfNeededOptions} Options for adding dependencies.
|
|
176
176
|
*/
|
|
177
|
-
export declare function addNPMDependenciesIfNeeded(dependencies: DependencyVersion[], options: AddNPMDependenciesIfNeededOptions
|
|
177
|
+
export declare function addNPMDependenciesIfNeeded(dependencies: DependencyVersion[], options: AddNPMDependenciesIfNeededOptions): Promise<void>;
|
|
178
|
+
export declare function addNPMDependencies(dependencies: DependencyVersion[], options: AddNPMDependenciesIfNeededOptions): Promise<void>;
|
|
178
179
|
export declare function addNPMDependenciesWithoutVersionIfNeeded(dependencies: string[], options: AddNPMDependenciesIfNeededOptions): Promise<void>;
|
|
179
|
-
export declare function addLatestNPMDependencies(dependencies: string[], options: AddNPMDependenciesIfNeededOptions): Promise<void>;
|
|
180
180
|
/**
|
|
181
181
|
* Given a directory it traverses the directory up looking for a package.json and if found, it reads it
|
|
182
182
|
* decodes the JSON, and returns its content as a Javascript object.
|
|
@@ -176,7 +176,7 @@ export async function readAndParsePackageJson(packageJsonPath) {
|
|
|
176
176
|
* @param dependencies {string[]} List of dependencies to be added.
|
|
177
177
|
* @param options {AddNPMDependenciesIfNeededOptions} Options for adding dependencies.
|
|
178
178
|
*/
|
|
179
|
-
export async function addNPMDependenciesIfNeeded(dependencies, options
|
|
179
|
+
export async function addNPMDependenciesIfNeeded(dependencies, options) {
|
|
180
180
|
debug(content `Adding the following dependencies if needed:
|
|
181
181
|
${token.json(dependencies)}
|
|
182
182
|
With options:
|
|
@@ -188,16 +188,17 @@ ${token.json(options)}
|
|
|
188
188
|
}
|
|
189
189
|
const existingDependencies = Object.keys(await getDependencies(packageJsonPath));
|
|
190
190
|
let dependenciesToAdd = dependencies;
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
});
|
|
195
|
-
}
|
|
191
|
+
dependenciesToAdd = dependencies.filter((dep) => {
|
|
192
|
+
return !existingDependencies.includes(dep.name);
|
|
193
|
+
});
|
|
196
194
|
if (dependenciesToAdd.length === 0) {
|
|
197
195
|
return;
|
|
198
196
|
}
|
|
197
|
+
await addNPMDependencies(dependenciesToAdd, options);
|
|
198
|
+
}
|
|
199
|
+
export async function addNPMDependencies(dependencies, options) {
|
|
199
200
|
let args;
|
|
200
|
-
const depedenciesWithVersion =
|
|
201
|
+
const depedenciesWithVersion = dependencies.map((dep) => {
|
|
201
202
|
return dep.version ? `${dep.name}@${dep.version}` : dep.name;
|
|
202
203
|
});
|
|
203
204
|
switch (options.packageManager) {
|
|
@@ -211,7 +212,7 @@ ${token.json(options)}
|
|
|
211
212
|
args = argumentsToAddDependenciesWithPNPM(depedenciesWithVersion, options.type);
|
|
212
213
|
break;
|
|
213
214
|
}
|
|
214
|
-
options.stdout?.write(`Executing
|
|
215
|
+
options.stdout?.write(`Executing... ${[options.packageManager, ...args].join(' ')}`);
|
|
215
216
|
await exec(options.packageManager, args, {
|
|
216
217
|
cwd: options.directory,
|
|
217
218
|
stdout: options.stdout,
|
|
@@ -224,14 +225,6 @@ export async function addNPMDependenciesWithoutVersionIfNeeded(dependencies, opt
|
|
|
224
225
|
return { name: dependency, version: undefined };
|
|
225
226
|
}), options);
|
|
226
227
|
}
|
|
227
|
-
// eslint-disable-next-line no-warning-comments
|
|
228
|
-
// TODO: Switch it around so add-if-needed depends on this, rather than calling
|
|
229
|
-
// if-needed with force: true which is counterintuitive.
|
|
230
|
-
export async function addLatestNPMDependencies(dependencies, options) {
|
|
231
|
-
await addNPMDependenciesIfNeeded(dependencies.map((dependency) => {
|
|
232
|
-
return { name: dependency, version: 'latest' };
|
|
233
|
-
}), options, true);
|
|
234
|
-
}
|
|
235
228
|
/**
|
|
236
229
|
* Returns the arguments to add dependencies using NPM.
|
|
237
230
|
* @param dependencies {string[]} The list of dependencies to add
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-package-manager.js","sourceRoot":"","sources":["../../src/node/node-package-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,IAAI,EAAC,MAAM,cAAc,CAAA;AACjC,OAAO,EAAC,MAAM,IAAI,UAAU,EAAE,IAAI,IAAI,QAAQ,EAAC,MAAM,YAAY,CAAA;AACjE,OAAO,EAAC,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,QAAQ,EAAE,MAAM,EAAC,MAAM,YAAY,CAAA;AAClE,OAAO,EAAC,KAAK,EAAE,GAAG,EAAC,MAAM,aAAa,CAAA;AACtC,OAAO,EAAC,uBAAuB,EAAC,MAAM,eAAe,CAAA;AACrD,OAAO,EAAC,OAAO,EAAC,MAAM,cAAc,CAAA;AACpC,OAAO,EAAC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAC,MAAM,cAAc,CAAA;AAClD,OAAO,EAAC,eAAe,EAAc,MAAM,kBAAkB,CAAA;AAI7D,qCAAqC;AACrC,MAAM,CAAC,MAAM,YAAY,GAAG,WAAW,CAAA;AAE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C,IAAI,CAAC,QAAQ,CAAC,CAAA;YACtB,MAAK;QACP,KAAK,MAAM;YACT,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;YACtB,MAAK;KACR;IACD,OAAO,OAAO,CAAA;AAChB,CAAC;AAED;;;;;GAKG;AACH,SAAS,kCAAkC,CAAC,YAAsB,EAAE,IAAoB;IACtF,IAAI,OAAO,GAAG,CAAC,KAAK,CAAC,CAAA;IACrB,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,YAAY,CAAC,CAAA;IACtC,QAAQ,IAAI,EAAE;QACZ,KAAK,KAAK;YACR,OAAO,CAAC,IAAI,CAAC,YAAY,CAAC,CAAA;YAC1B,MAAK;QACP,KAAK,MAAM;YACT,OAAO,CAAC,IAAI,CAAC,aAAa,CAAC,CAAA;YAC3B,MAAK;QACP,KAAK,MAAM;YACT,OAAO,CAAC,IAAI,CAAC,aAAa,CAAC,CAAA;YAC3B,MAAK;KACR;IACD,OAAO,OAAO,CAAA;AAChB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,aAAqB;IAClE,MAAM,eAAe,GAAG,MAAM,MAAM,CAAC,cAAc,EAAE,EAAC,GAAG,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,EAAC,CAAC,CAAA;IACxF,IAAI,eAAe,EAAE;QACnB,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,QAAQ,CAAC,eAAe,CAAC,CAAC,CAAA;QAC/D,OAAO,EAAC,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,WAAW,EAAC,CAAA;KACrD;SAAM;QACL,MAAM,qCAAqC,CAAC,aAAa,CAAC,CAAA;KAC3D;AACH,CAAC","sourcesContent":["import {exec} from '../system.js'\nimport {exists as fileExists, read as readFile} from '../file.js'\nimport {glob, dirname, join as pathJoin, findUp} from '../path.js'\nimport {Abort, Bug} from '../error.js'\nimport {latestNpmPackageVersion} from '../version.js'\nimport {Version} from '../semver.js'\nimport {content, token, debug} from '../output.js'\nimport {AbortController, AbortSignal} from 'abort-controller'\nimport type {Writable} from 'node:stream'\nimport type {ExecOptions} from '../system.js'\n\n/** The name of the Yarn lock file */\nexport const yarnLockfile = 'yarn.lock'\n\n/** The name of the pnpm lock file */\nexport const pnpmLockfile = 'pnpm-lock.yaml'\n\n/** An array containing the lockfiles from all the package managers */\nexport const lockfiles = [yarnLockfile, pnpmLockfile]\n\n/**\n * A union type that represents the type of dependencies in the package.json\n * - dev: devDependencies\n * - prod: dependencies\n * - peer: peerDependencies\n */\nexport type DependencyType = 'dev' | 'prod' | 'peer'\n\n/**\n * A union that represents the package managers available.\n */\nexport const packageManager = ['yarn', 'npm', 'pnpm'] as const\nexport type PackageManager = typeof packageManager[number]\n\n/**\n * Returns an abort error that's thrown when a directory that's expected to have\n * a package.json doesn't have it.\n * @param directory {string} The path to the directory that should contain a package.json\n * @returns {Abort} An abort error.\n */\nexport const PackageJsonNotFoundError = (directory: string) => {\n return new Abort(`The directory ${directory} doesn't have a package.json.`)\n}\n\n/**\n * Returns a bug error that's thrown when the lookup of the package.json traversing the directory\n * hierarchy up can't find a package.json\n * @param directory {string} The directory from which the traverse has been done\n * @returns {Abort} An abort error.\n */\nexport const FindUpAndReadPackageJsonNotFoundError = (directory: string) => {\n return new Bug(content`Couldn't find a a package.json traversing directories from ${token.path(directory)}`)\n}\n\n/**\n * Returns the dependency manager used to run the create workflow.\n * @param env {Object} The environment variables of the process in which the CLI runs.\n * @returns The dependency manager\n */\nexport function packageManagerUsedForCreating(env = process.env): PackageManager | 'unknown' {\n if (env.npm_config_user_agent?.includes('yarn')) {\n return 'yarn'\n } else if (env.npm_config_user_agent?.includes('pnpm')) {\n return 'pnpm'\n } else if (env.npm_config_user_agent?.includes('npm')) {\n return 'npm'\n }\n return 'unknown'\n}\n\n/**\n * Returns the dependency manager used by an existing project.\n * @param directory {string} The root directory of the project.\n * @returns The dependency manager\n */\nexport async function getPackageManager(directory: string): Promise<PackageManager> {\n debug(content`Obtaining the dependency manager in directory ${token.path(directory)}...`)\n const yarnLockPath = pathJoin(directory, yarnLockfile)\n const pnpmLockPath = pathJoin(directory, pnpmLockfile)\n if (await fileExists(yarnLockPath)) {\n return 'yarn'\n } else if (await fileExists(pnpmLockPath)) {\n return 'pnpm'\n } else {\n return 'npm'\n }\n}\n\ninterface InstallNPMDependenciesRecursivelyOptions {\n /**\n * The dependency manager to use to install the dependencies.\n */\n packageManager: PackageManager\n /**\n * The directory from where we'll find package.json's recursively\n */\n directory: string\n\n /**\n * Specifies the maximum depth of the glob search.\n */\n deep?: number\n}\n\n/**\n * This function traverses down a directory tree to find directories containing a package.json\n * and installs the dependencies if needed. To know if it's needed, it uses the \"check\" command\n * provided by dependency managers.\n * @param options {InstallNPMDependenciesRecursivelyOptions} Options to install dependencies recursively.\n */\nexport async function installNPMDependenciesRecursively(options: InstallNPMDependenciesRecursivelyOptions) {\n const packageJsons = await glob(pathJoin(options.directory, '**/package.json'), {\n ignore: [pathJoin(options.directory, 'node_modules/**/package.json')],\n cwd: options.directory,\n onlyFiles: true,\n deep: options.deep,\n })\n const abortController = new AbortController()\n try {\n await Promise.all(\n packageJsons.map(async (packageJsonPath) => {\n const directory = dirname(packageJsonPath)\n await installNodeModules({\n directory,\n packageManager: options.packageManager,\n stdout: undefined,\n stderr: undefined,\n signal: abortController.signal,\n args: [],\n })\n }),\n )\n } catch (error) {\n abortController.abort()\n throw error\n }\n}\n\ninterface InstallNodeModulesOptions {\n directory: string\n args: string[]\n packageManager: PackageManager\n stdout?: Writable\n stderr?: Writable\n signal?: AbortSignal\n}\n\nexport async function installNodeModules(options: InstallNodeModulesOptions) {\n const execOptions: ExecOptions = {\n cwd: options.directory,\n stdin: undefined,\n stdout: options.stdout,\n stderr: options.stderr,\n signal: options.signal,\n }\n let args = ['install']\n if (options.args) {\n args = args.concat(options.args)\n }\n await exec(options.packageManager, args, execOptions)\n}\n\n/**\n * Returns the name of the package configured in its package.json\n * @param packageJsonPath {string} Path to the package.json file\n * @returns A promise that resolves with the name.\n */\nexport async function getPackageName(packageJsonPath: string): Promise<string | undefined> {\n const packageJsonContent = await readAndParsePackageJson(packageJsonPath)\n return packageJsonContent.name\n}\n\n/**\n * Returns the list of production and dev dependencies of a package.json\n * @param packageJsonPath {string} Path to the package.json file\n * @returns A promise that resolves with the list of dependencies.\n */\nexport async function getDependencies(packageJsonPath: string): Promise<{[key: string]: string}> {\n const packageJsonContent = await readAndParsePackageJson(packageJsonPath)\n const dependencies: {[key: string]: string} = packageJsonContent.dependencies ?? {}\n const devDependencies: {[key: string]: string} = packageJsonContent.devDependencies ?? {}\n\n return {...dependencies, ...devDependencies}\n}\n\n/**\n * Given an NPM dependency, it checks if there's a more recent version, and if there is, it returns its value.\n * @param dependency {string} The dependency name (e.g. react)\n * @param currentVersion {string} The current version.\n * @returns {Promise<string>} A promise that resolves with a more recent version or undefined if there's no more recent version.\n */\nexport async function checkForNewVersion(dependency: string, currentVersion: string): Promise<string | undefined> {\n debug(content`Checking if there's a version of ${dependency} newer than ${currentVersion}`)\n try {\n const lastVersion = await latestNpmPackageVersion(dependency)\n if (lastVersion && new Version(currentVersion).compare(lastVersion) < 0) {\n return lastVersion\n } else {\n return undefined\n }\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n return undefined\n }\n}\n\n/**\n * An interface that represents a package.json\n */\ninterface PackageJson {\n /**\n * The name attribute of the package.json\n */\n name?: string\n\n /**\n * The version attribute of the package.json\n */\n version?: string\n\n /**\n * The dependencies attribute of the package.json\n */\n dependencies?: {[key: string]: string}\n\n /**\n * The devDependencies attribute of the package.json\n */\n devDependencies?: {[key: string]: string}\n}\n\n/**\n * Reads and parses a package.json\n * @param packageJsonPath {string} Path to the package.json\n * @returns {Promise<PackageJson>} An promise that resolves with an in-memory representation\n * of the package.json or rejects with an error if the file is not found or the content is\n * not decodable.\n */\nexport async function readAndParsePackageJson(packageJsonPath: string): Promise<PackageJson> {\n if (!(await fileExists(packageJsonPath))) {\n throw PackageJsonNotFoundError(dirname(packageJsonPath))\n }\n return JSON.parse(await readFile(packageJsonPath))\n}\n\ninterface AddNPMDependenciesIfNeededOptions {\n /** How dependencies should be added */\n type: DependencyType\n\n /** The dependency manager to use to add dependencies */\n packageManager: PackageManager\n\n /** The directory that contains the package.json where dependencies will be added */\n directory: string\n\n /** Standard output coming from the underlying installation process */\n stdout?: Writable\n\n /** Standard error coming from the underlying installation process */\n stderr?: Writable\n\n /** Abort signal to stop the process */\n signal?: AbortSignal\n}\n\n/**\n * An interface that represents a dependency name with its version\n */\nexport interface DependencyVersion {\n /**\n * The name of the NPM dependency as it's reflected in the package.json:\n *\n * @example\n * In the example below name would be \"react\"\n * {\n * \"react\": \"1.2.3\"\n * }\n */\n name: string\n\n /**\n * The version of the NPM dependency as it's reflected in the package.json:\n *\n * @example\n * In the example below version would be \"1.2.3\"\n * {\n * \"react\": \"1.2.3\"\n * }\n */\n version: string | undefined\n}\n\n/**\n * Adds dependencies to a Node project (i.e. a project that has a package.json)\n * @param dependencies {string[]} List of dependencies to be added.\n * @param options {AddNPMDependenciesIfNeededOptions} Options for adding dependencies.\n */\nexport async function addNPMDependenciesIfNeeded(\n dependencies: DependencyVersion[],\n options: AddNPMDependenciesIfNeededOptions,\n force = false,\n) {\n debug(content`Adding the following dependencies if needed:\n${token.json(dependencies)}\nWith options:\n${token.json(options)}\n `)\n const packageJsonPath = pathJoin(options.directory, 'package.json')\n if (!(await fileExists(packageJsonPath))) {\n throw PackageJsonNotFoundError(options.directory)\n }\n const existingDependencies = Object.keys(await getDependencies(packageJsonPath))\n let dependenciesToAdd = dependencies\n if (!force) {\n dependenciesToAdd = dependencies.filter((dep) => {\n return !existingDependencies.includes(dep.name)\n })\n }\n if (dependenciesToAdd.length === 0) {\n return\n }\n let args: string[]\n const depedenciesWithVersion = dependenciesToAdd.map((dep) => {\n return dep.version ? `${dep.name}@${dep.version}` : dep.name\n })\n switch (options.packageManager) {\n case 'npm':\n args = argumentsToAddDependenciesWithNPM(depedenciesWithVersion, options.type)\n break\n case 'yarn':\n args = argumentsToAddDependenciesWithYarn(depedenciesWithVersion, options.type)\n break\n case 'pnpm':\n args = argumentsToAddDependenciesWithPNPM(depedenciesWithVersion, options.type)\n break\n }\n options.stdout?.write(`Executing...${args.join(' ')}`)\n await exec(options.packageManager, args, {\n cwd: options.directory,\n stdout: options.stdout,\n stderr: options.stderr,\n signal: options.signal,\n })\n}\n\nexport async function addNPMDependenciesWithoutVersionIfNeeded(\n dependencies: string[],\n options: AddNPMDependenciesIfNeededOptions,\n) {\n await addNPMDependenciesIfNeeded(\n dependencies.map((dependency) => {\n return {name: dependency, version: undefined}\n }),\n options,\n )\n}\n\n// eslint-disable-next-line no-warning-comments\n// TODO: Switch it around so add-if-needed depends on this, rather than calling\n// if-needed with force: true which is counterintuitive.\nexport async function addLatestNPMDependencies(dependencies: string[], options: AddNPMDependenciesIfNeededOptions) {\n await addNPMDependenciesIfNeeded(\n dependencies.map((dependency) => {\n return {name: dependency, version: 'latest'}\n }),\n options,\n true,\n )\n}\n\n/**\n * Returns the arguments to add dependencies using NPM.\n * @param dependencies {string[]} The list of dependencies to add\n * @param type {DependencyType} The dependency type.\n * @returns {string[]} An array with the arguments.\n */\nfunction argumentsToAddDependenciesWithNPM(dependencies: string[], type: DependencyType): string[] {\n let command = ['install']\n command = command.concat(dependencies)\n switch (type) {\n case 'dev':\n command.push('--save-dev')\n break\n case 'peer':\n command.push('--save-peer')\n break\n case 'prod':\n command.push('--save-prod')\n break\n }\n return command\n}\n\n/**\n * Returns the arguments to add dependencies using Yarn.\n * @param dependencies {string[]} The list of dependencies to add\n * @param type {DependencyType} The dependency type.\n * @returns {string[]} An array with the arguments.\n */\nfunction argumentsToAddDependenciesWithYarn(dependencies: string[], type: DependencyType): string[] {\n let command = ['add']\n command = command.concat(dependencies)\n switch (type) {\n case 'dev':\n command.push('--dev')\n break\n case 'peer':\n command.push('--peer')\n break\n case 'prod':\n command.push('--prod')\n break\n }\n return command\n}\n\n/**\n * Returns the arguments to add dependencies using PNPM.\n * @param dependencies {string[]} The list of dependencies to add\n * @param type {DependencyType} The dependency type.\n * @returns {string[]} An array with the arguments.\n */\nfunction argumentsToAddDependenciesWithPNPM(dependencies: string[], type: DependencyType): string[] {\n let command = ['add']\n command = command.concat(dependencies)\n switch (type) {\n case 'dev':\n command.push('--save-dev')\n break\n case 'peer':\n command.push('--save-peer')\n break\n case 'prod':\n command.push('--save-prod')\n break\n }\n return command\n}\n\n/**\n * Given a directory it traverses the directory up looking for a package.json and if found, it reads it\n * decodes the JSON, and returns its content as a Javascript object.\n * @param options {string} The directory from which traverse up.\n * @returns {Promise<{path: string; content: unknown}>} If found, the promise resolves with the path to the\n * package.json and its content. If not found, it throws a FindUpAndReadPackageJsonNotFoundError error.\n */\nexport async function findUpAndReadPackageJson(fromDirectory: string): Promise<{path: string; content: unknown}> {\n const packageJsonPath = await findUp('package.json', {cwd: fromDirectory, type: 'file'})\n if (packageJsonPath) {\n const packageJson = JSON.parse(await readFile(packageJsonPath))\n return {path: packageJsonPath, content: packageJson}\n } else {\n throw FindUpAndReadPackageJsonNotFoundError(fromDirectory)\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"node-package-manager.js","sourceRoot":"","sources":["../../src/node/node-package-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,IAAI,EAAC,MAAM,cAAc,CAAA;AACjC,OAAO,EAAC,MAAM,IAAI,UAAU,EAAE,IAAI,IAAI,QAAQ,EAAC,MAAM,YAAY,CAAA;AACjE,OAAO,EAAC,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,QAAQ,EAAE,MAAM,EAAC,MAAM,YAAY,CAAA;AAClE,OAAO,EAAC,KAAK,EAAE,GAAG,EAAC,MAAM,aAAa,CAAA;AACtC,OAAO,EAAC,uBAAuB,EAAC,MAAM,eAAe,CAAA;AACrD,OAAO,EAAC,OAAO,EAAC,MAAM,cAAc,CAAA;AACpC,OAAO,EAAC,OA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ACtB,MAAK;QACP,KAAK,MAAM;YACT,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;YACtB,MAAK;KACR;IACD,OAAO,OAAO,CAAA;AAChB,CAAC;AAED;;;;;GAKG;AACH,SAAS,kCAAkC,CAAC,YAAsB,EAAE,IAAoB;IACtF,IAAI,OAAO,GAAG,CAAC,KAAK,CAAC,CAAA;IACrB,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,YAAY,CAAC,CAAA;IACtC,QAAQ,IAAI,EAAE;QACZ,KAAK,KAAK;YACR,OAAO,CAAC,IAAI,CAAC,YAAY,CAAC,CAAA;YAC1B,MAAK;QACP,KAAK,MAAM;YACT,OAAO,CAAC,IAAI,CAAC,aAAa,CAAC,CAAA;YAC3B,MAAK;QACP,KAAK,MAAM;YACT,OAAO,CAAC,IAAI,CAAC,aAAa,CAAC,CAAA;YAC3B,MAAK;KACR;IACD,OAAO,OAAO,CAAA;AAChB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,aAAqB;IAClE,MAAM,eAAe,GAAG,MAAM,MAAM,CAAC,cAAc,EAAE,EAAC,GAAG,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,EAAC,CAAC,CAAA;IACxF,IAAI,eAAe,EAAE;QACnB,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,QAAQ,CAAC,eAAe,CAAC,CAAC,CAAA;QAC/D,OAAO,EAAC,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,WAAW,EAAC,CAAA;KACrD;SAAM;QACL,MAAM,qCAAqC,CAAC,aAAa,CAAC,CAAA;KAC3D;AACH,CAAC","sourcesContent":["import {exec} from '../system.js'\nimport {exists as fileExists, read as readFile} from '../file.js'\nimport {glob, dirname, join as pathJoin, findUp} from '../path.js'\nimport {Abort, Bug} from '../error.js'\nimport {latestNpmPackageVersion} from '../version.js'\nimport {Version} from '../semver.js'\nimport {content, token, debug} from '../output.js'\nimport {AbortController, AbortSignal} from 'abort-controller'\nimport type {Writable} from 'node:stream'\nimport type {ExecOptions} from '../system.js'\n\n/** The name of the Yarn lock file */\nexport const yarnLockfile = 'yarn.lock'\n\n/** The name of the pnpm lock file */\nexport const pnpmLockfile = 'pnpm-lock.yaml'\n\n/** An array containing the lockfiles from all the package managers */\nexport const lockfiles = [yarnLockfile, pnpmLockfile]\n\n/**\n * A union type that represents the type of dependencies in the package.json\n * - dev: devDependencies\n * - prod: dependencies\n * - peer: peerDependencies\n */\nexport type DependencyType = 'dev' | 'prod' | 'peer'\n\n/**\n * A union that represents the package managers available.\n */\nexport const packageManager = ['yarn', 'npm', 'pnpm'] as const\nexport type PackageManager = typeof packageManager[number]\n\n/**\n * Returns an abort error that's thrown when a directory that's expected to have\n * a package.json doesn't have it.\n * @param directory {string} The path to the directory that should contain a package.json\n * @returns {Abort} An abort error.\n */\nexport const PackageJsonNotFoundError = (directory: string) => {\n return new Abort(`The directory ${directory} doesn't have a package.json.`)\n}\n\n/**\n * Returns a bug error that's thrown when the lookup of the package.json traversing the directory\n * hierarchy up can't find a package.json\n * @param directory {string} The directory from which the traverse has been done\n * @returns {Abort} An abort error.\n */\nexport const FindUpAndReadPackageJsonNotFoundError = (directory: string) => {\n return new Bug(content`Couldn't find a a package.json traversing directories from ${token.path(directory)}`)\n}\n\n/**\n * Returns the dependency manager used to run the create workflow.\n * @param env {Object} The environment variables of the process in which the CLI runs.\n * @returns The dependency manager\n */\nexport function packageManagerUsedForCreating(env = process.env): PackageManager | 'unknown' {\n if (env.npm_config_user_agent?.includes('yarn')) {\n return 'yarn'\n } else if (env.npm_config_user_agent?.includes('pnpm')) {\n return 'pnpm'\n } else if (env.npm_config_user_agent?.includes('npm')) {\n return 'npm'\n }\n return 'unknown'\n}\n\n/**\n * Returns the dependency manager used by an existing project.\n * @param directory {string} The root directory of the project.\n * @returns The dependency manager\n */\nexport async function getPackageManager(directory: string): Promise<PackageManager> {\n debug(content`Obtaining the dependency manager in directory ${token.path(directory)}...`)\n const yarnLockPath = pathJoin(directory, yarnLockfile)\n const pnpmLockPath = pathJoin(directory, pnpmLockfile)\n if (await fileExists(yarnLockPath)) {\n return 'yarn'\n } else if (await fileExists(pnpmLockPath)) {\n return 'pnpm'\n } else {\n return 'npm'\n }\n}\n\ninterface InstallNPMDependenciesRecursivelyOptions {\n /**\n * The dependency manager to use to install the dependencies.\n */\n packageManager: PackageManager\n /**\n * The directory from where we'll find package.json's recursively\n */\n directory: string\n\n /**\n * Specifies the maximum depth of the glob search.\n */\n deep?: number\n}\n\n/**\n * This function traverses down a directory tree to find directories containing a package.json\n * and installs the dependencies if needed. To know if it's needed, it uses the \"check\" command\n * provided by dependency managers.\n * @param options {InstallNPMDependenciesRecursivelyOptions} Options to install dependencies recursively.\n */\nexport async function installNPMDependenciesRecursively(options: InstallNPMDependenciesRecursivelyOptions) {\n const packageJsons = await glob(pathJoin(options.directory, '**/package.json'), {\n ignore: [pathJoin(options.directory, 'node_modules/**/package.json')],\n cwd: options.directory,\n onlyFiles: true,\n deep: options.deep,\n })\n const abortController = new AbortController()\n try {\n await Promise.all(\n packageJsons.map(async (packageJsonPath) => {\n const directory = dirname(packageJsonPath)\n await installNodeModules({\n directory,\n packageManager: options.packageManager,\n stdout: undefined,\n stderr: undefined,\n signal: abortController.signal,\n args: [],\n })\n }),\n )\n } catch (error) {\n abortController.abort()\n throw error\n }\n}\n\ninterface InstallNodeModulesOptions {\n directory: string\n args: string[]\n packageManager: PackageManager\n stdout?: Writable\n stderr?: Writable\n signal?: AbortSignal\n}\n\nexport async function installNodeModules(options: InstallNodeModulesOptions) {\n const execOptions: ExecOptions = {\n cwd: options.directory,\n stdin: undefined,\n stdout: options.stdout,\n stderr: options.stderr,\n signal: options.signal,\n }\n let args = ['install']\n if (options.args) {\n args = args.concat(options.args)\n }\n await exec(options.packageManager, args, execOptions)\n}\n\n/**\n * Returns the name of the package configured in its package.json\n * @param packageJsonPath {string} Path to the package.json file\n * @returns A promise that resolves with the name.\n */\nexport async function getPackageName(packageJsonPath: string): Promise<string | undefined> {\n const packageJsonContent = await readAndParsePackageJson(packageJsonPath)\n return packageJsonContent.name\n}\n\n/**\n * Returns the list of production and dev dependencies of a package.json\n * @param packageJsonPath {string} Path to the package.json file\n * @returns A promise that resolves with the list of dependencies.\n */\nexport async function getDependencies(packageJsonPath: string): Promise<{[key: string]: string}> {\n const packageJsonContent = await readAndParsePackageJson(packageJsonPath)\n const dependencies: {[key: string]: string} = packageJsonContent.dependencies ?? {}\n const devDependencies: {[key: string]: string} = packageJsonContent.devDependencies ?? {}\n\n return {...dependencies, ...devDependencies}\n}\n\n/**\n * Given an NPM dependency, it checks if there's a more recent version, and if there is, it returns its value.\n * @param dependency {string} The dependency name (e.g. react)\n * @param currentVersion {string} The current version.\n * @returns {Promise<string>} A promise that resolves with a more recent version or undefined if there's no more recent version.\n */\nexport async function checkForNewVersion(dependency: string, currentVersion: string): Promise<string | undefined> {\n debug(content`Checking if there's a version of ${dependency} newer than ${currentVersion}`)\n try {\n const lastVersion = await latestNpmPackageVersion(dependency)\n if (lastVersion && new Version(currentVersion).compare(lastVersion) < 0) {\n return lastVersion\n } else {\n return undefined\n }\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n return undefined\n }\n}\n\n/**\n * An interface that represents a package.json\n */\ninterface PackageJson {\n /**\n * The name attribute of the package.json\n */\n name?: string\n\n /**\n * The version attribute of the package.json\n */\n version?: string\n\n /**\n * The dependencies attribute of the package.json\n */\n dependencies?: {[key: string]: string}\n\n /**\n * The devDependencies attribute of the package.json\n */\n devDependencies?: {[key: string]: string}\n}\n\n/**\n * Reads and parses a package.json\n * @param packageJsonPath {string} Path to the package.json\n * @returns {Promise<PackageJson>} An promise that resolves with an in-memory representation\n * of the package.json or rejects with an error if the file is not found or the content is\n * not decodable.\n */\nexport async function readAndParsePackageJson(packageJsonPath: string): Promise<PackageJson> {\n if (!(await fileExists(packageJsonPath))) {\n throw PackageJsonNotFoundError(dirname(packageJsonPath))\n }\n return JSON.parse(await readFile(packageJsonPath))\n}\n\ninterface AddNPMDependenciesIfNeededOptions {\n /** How dependencies should be added */\n type: DependencyType\n\n /** The dependency manager to use to add dependencies */\n packageManager: PackageManager\n\n /** The directory that contains the package.json where dependencies will be added */\n directory: string\n\n /** Standard output coming from the underlying installation process */\n stdout?: Writable\n\n /** Standard error coming from the underlying installation process */\n stderr?: Writable\n\n /** Abort signal to stop the process */\n signal?: AbortSignal\n}\n\n/**\n * An interface that represents a dependency name with its version\n */\nexport interface DependencyVersion {\n /**\n * The name of the NPM dependency as it's reflected in the package.json:\n *\n * @example\n * In the example below name would be \"react\"\n * {\n * \"react\": \"1.2.3\"\n * }\n */\n name: string\n\n /**\n * The version of the NPM dependency as it's reflected in the package.json:\n *\n * @example\n * In the example below version would be \"1.2.3\"\n * {\n * \"react\": \"1.2.3\"\n * }\n */\n version: string | undefined\n}\n\n/**\n * Adds dependencies to a Node project (i.e. a project that has a package.json)\n * @param dependencies {string[]} List of dependencies to be added.\n * @param options {AddNPMDependenciesIfNeededOptions} Options for adding dependencies.\n */\nexport async function addNPMDependenciesIfNeeded(\n dependencies: DependencyVersion[],\n options: AddNPMDependenciesIfNeededOptions,\n) {\n debug(content`Adding the following dependencies if needed:\n${token.json(dependencies)}\nWith options:\n${token.json(options)}\n `)\n const packageJsonPath = pathJoin(options.directory, 'package.json')\n if (!(await fileExists(packageJsonPath))) {\n throw PackageJsonNotFoundError(options.directory)\n }\n const existingDependencies = Object.keys(await getDependencies(packageJsonPath))\n let dependenciesToAdd = dependencies\n dependenciesToAdd = dependencies.filter((dep) => {\n return !existingDependencies.includes(dep.name)\n })\n if (dependenciesToAdd.length === 0) {\n return\n }\n await addNPMDependencies(dependenciesToAdd, options)\n}\n\nexport async function addNPMDependencies(\n dependencies: DependencyVersion[],\n options: AddNPMDependenciesIfNeededOptions,\n) {\n let args: string[]\n const depedenciesWithVersion = dependencies.map((dep) => {\n return dep.version ? `${dep.name}@${dep.version}` : dep.name\n })\n switch (options.packageManager) {\n case 'npm':\n args = argumentsToAddDependenciesWithNPM(depedenciesWithVersion, options.type)\n break\n case 'yarn':\n args = argumentsToAddDependenciesWithYarn(depedenciesWithVersion, options.type)\n break\n case 'pnpm':\n args = argumentsToAddDependenciesWithPNPM(depedenciesWithVersion, options.type)\n break\n }\n options.stdout?.write(`Executing... ${[options.packageManager, ...args].join(' ')}`)\n await exec(options.packageManager, args, {\n cwd: options.directory,\n stdout: options.stdout,\n stderr: options.stderr,\n signal: options.signal,\n })\n}\n\nexport async function addNPMDependenciesWithoutVersionIfNeeded(\n dependencies: string[],\n options: AddNPMDependenciesIfNeededOptions,\n) {\n await addNPMDependenciesIfNeeded(\n dependencies.map((dependency) => {\n return {name: dependency, version: undefined}\n }),\n options,\n )\n}\n\n/**\n * Returns the arguments to add dependencies using NPM.\n * @param dependencies {string[]} The list of dependencies to add\n * @param type {DependencyType} The dependency type.\n * @returns {string[]} An array with the arguments.\n */\nfunction argumentsToAddDependenciesWithNPM(dependencies: string[], type: DependencyType): string[] {\n let command = ['install']\n command = command.concat(dependencies)\n switch (type) {\n case 'dev':\n command.push('--save-dev')\n break\n case 'peer':\n command.push('--save-peer')\n break\n case 'prod':\n command.push('--save-prod')\n break\n }\n return command\n}\n\n/**\n * Returns the arguments to add dependencies using Yarn.\n * @param dependencies {string[]} The list of dependencies to add\n * @param type {DependencyType} The dependency type.\n * @returns {string[]} An array with the arguments.\n */\nfunction argumentsToAddDependenciesWithYarn(dependencies: string[], type: DependencyType): string[] {\n let command = ['add']\n command = command.concat(dependencies)\n switch (type) {\n case 'dev':\n command.push('--dev')\n break\n case 'peer':\n command.push('--peer')\n break\n case 'prod':\n command.push('--prod')\n break\n }\n return command\n}\n\n/**\n * Returns the arguments to add dependencies using PNPM.\n * @param dependencies {string[]} The list of dependencies to add\n * @param type {DependencyType} The dependency type.\n * @returns {string[]} An array with the arguments.\n */\nfunction argumentsToAddDependenciesWithPNPM(dependencies: string[], type: DependencyType): string[] {\n let command = ['add']\n command = command.concat(dependencies)\n switch (type) {\n case 'dev':\n command.push('--save-dev')\n break\n case 'peer':\n command.push('--save-peer')\n break\n case 'prod':\n command.push('--save-prod')\n break\n }\n return command\n}\n\n/**\n * Given a directory it traverses the directory up looking for a package.json and if found, it reads it\n * decodes the JSON, and returns its content as a Javascript object.\n * @param options {string} The directory from which traverse up.\n * @returns {Promise<{path: string; content: unknown}>} If found, the promise resolves with the path to the\n * package.json and its content. If not found, it throws a FindUpAndReadPackageJsonNotFoundError error.\n */\nexport async function findUpAndReadPackageJson(fromDirectory: string): Promise<{path: string; content: unknown}> {\n const packageJsonPath = await findUp('package.json', {cwd: fromDirectory, type: 'file'})\n if (packageJsonPath) {\n const packageJson = JSON.parse(await readFile(packageJsonPath))\n return {path: packageJsonPath, content: packageJson}\n } else {\n throw FindUpAndReadPackageJsonNotFoundError(fromDirectory)\n }\n}\n"]}
|