@webiny/project 6.6.0-alpha.4 → 6.6.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/components/FeatureFlag.js +1 -1
  2. package/components/FeatureFlag.js.map +1 -1
  3. package/createProjectSdkContainer.js +22 -9
  4. package/createProjectSdkContainer.js.map +1 -1
  5. package/extensions/AdminExtension.js +2 -2
  6. package/extensions/AdminExtension.js.map +1 -1
  7. package/extensions/ApiExtension.js +2 -2
  8. package/extensions/ApiExtension.js.map +1 -1
  9. package/extensions/BugReporter.d.ts +6 -0
  10. package/extensions/BugReporter.js +33 -0
  11. package/extensions/BugReporter.js.map +1 -0
  12. package/extensions/FeatureFlags.d.ts +6 -1
  13. package/extensions/FeatureFlags.js +9 -1
  14. package/extensions/FeatureFlags.js.map +1 -1
  15. package/extensions/hasDefaultExport.d.ts +2 -0
  16. package/extensions/hasDefaultExport.js +17 -0
  17. package/extensions/hasDefaultExport.js.map +1 -0
  18. package/extensions/index.d.ts +14 -3
  19. package/extensions/index.js +3 -1
  20. package/extensions/index.js.map +1 -1
  21. package/features/Watch/watchers/worker.js +3 -0
  22. package/features/Watch/watchers/worker.js.map +1 -1
  23. package/package.json +14 -14
  24. package/services/GetProjectConfigService/ConfigRenderErrorBoundary.d.ts +15 -0
  25. package/services/GetProjectConfigService/ConfigRenderErrorBoundary.js +23 -0
  26. package/services/GetProjectConfigService/ConfigRenderErrorBoundary.js.map +1 -0
  27. package/services/GetProjectConfigService/EnvContext.d.ts +3 -2
  28. package/services/GetProjectConfigService/EnvContext.js +4 -6
  29. package/services/GetProjectConfigService/EnvContext.js.map +1 -1
  30. package/services/GetProjectConfigService/GetProjectConfigService.js +14 -11
  31. package/services/GetProjectConfigService/GetProjectConfigService.js.map +1 -1
  32. package/services/GetProjectConfigService/getRenderCacheKey.d.ts +1 -0
  33. package/services/GetProjectConfigService/getRenderCacheKey.js +13 -0
  34. package/services/GetProjectConfigService/getRenderCacheKey.js.map +1 -0
  35. package/services/GetProjectConfigService/nullRenderer.d.ts +4 -0
  36. package/services/GetProjectConfigService/nullRenderer.js +51 -0
  37. package/services/GetProjectConfigService/nullRenderer.js.map +1 -0
  38. package/services/GetProjectConfigService/renderConfig.d.ts +3 -12
  39. package/services/GetProjectConfigService/renderConfig.js +10 -35
  40. package/services/GetProjectConfigService/renderConfig.js.map +1 -1
  41. package/services/GetProjectConfigService/renderExtensions.d.ts +8 -0
  42. package/services/GetProjectConfigService/renderExtensions.js +52 -0
  43. package/services/GetProjectConfigService/renderExtensions.js.map +1 -0
  44. package/services/InitProjectSdkService/InitProjectSdkService.js +5 -8
  45. package/services/InitProjectSdkService/InitProjectSdkService.js.map +1 -1
  46. package/services/InitProjectSdkService/applyWcpEnvVars.js +27 -9
  47. package/services/InitProjectSdkService/applyWcpEnvVars.js.map +1 -1
  48. package/services/ValidateProjectConfigService/ValidateProjectConfigService.js +10 -7
  49. package/services/ValidateProjectConfigService/ValidateProjectConfigService.js.map +1 -1
  50. package/services/WcpService/GetProjectEnvironment.js +16 -5
  51. package/services/WcpService/GetProjectEnvironment.js.map +1 -1
  52. package/services/WcpService/fetchProjectEnvironmentByApiKey.d.ts +8 -0
  53. package/services/WcpService/fetchProjectEnvironmentByApiKey.js +21 -0
  54. package/services/WcpService/fetchProjectEnvironmentByApiKey.js.map +1 -0
  55. package/utils/index.d.ts +1 -0
  56. package/utils/index.js +1 -0
  57. package/utils/trace/TraceRecorder.d.ts +17 -0
  58. package/utils/trace/TraceRecorder.js +51 -0
  59. package/utils/trace/TraceRecorder.js.map +1 -0
  60. package/utils/trace/formatTraceReport.d.ts +2 -0
  61. package/utils/trace/formatTraceReport.js +53 -0
  62. package/utils/trace/formatTraceReport.js.map +1 -0
  63. package/utils/trace/index.d.ts +6 -0
  64. package/utils/trace/index.js +6 -0
  65. package/utils/trace/isTraceRequested.d.ts +1 -0
  66. package/utils/trace/isTraceRequested.js +12 -0
  67. package/utils/trace/isTraceRequested.js.map +1 -0
  68. package/utils/trace/startTrace.d.ts +1 -0
  69. package/utils/trace/startTrace.js +19 -0
  70. package/utils/trace/startTrace.js.map +1 -0
  71. package/utils/trace/trace.d.ts +1 -0
  72. package/utils/trace/trace.js +13 -0
  73. package/utils/trace/trace.js.map +1 -0
  74. package/utils/trace/traceAsync.d.ts +1 -0
  75. package/utils/trace/traceAsync.js +13 -0
  76. package/utils/trace/traceAsync.js.map +1 -0
  77. package/rslib-runtime.js +0 -14
  78. package/rslib-runtime.js.map +0 -1
  79. package/services/GetProjectConfigService/renderConfigWorker.d.ts +0 -1
  80. package/services/GetProjectConfigService/renderConfigWorker.js +0 -64
  81. package/services/GetProjectConfigService/renderConfigWorker.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"services/InitProjectSdkService/InitProjectSdkService.js","sources":["../../../src/services/InitProjectSdkService/InitProjectSdkService.ts"],"sourcesContent":["import { createImplementation, Container } from \"@webiny/di\";\nimport {\n GetProjectService,\n GetProjectConfig,\n InitProjectSdkService\n} from \"~/abstractions/index.js\";\nimport {\n buildAppWithHooks,\n deployAppClearWatchedLambdaFunctions,\n deployAppRefreshStackOutputCache,\n deployAppWithHooks,\n deployAppWithWatchedLambdaReplacement,\n destroyAppClearStackOutputCache,\n watchWithHooks,\n getPulumiServiceWithDownloadInfo\n} from \"~/decorators/index.js\";\nimport { applyEnvVars } from \"./applyEnvVars.js\";\nimport { applyWcpEnvVars } from \"./applyWcpEnvVars.js\";\nimport { registerHooks } from \"./registerHooks.js\";\nimport { registerPulumiExtensions } from \"./registerPulumiExtensions.js\";\nimport { registerImplementations } from \"./registerImplementations.js\";\nimport { registerDecorators } from \"./registerDecorators.js\";\n\nexport class DefaultInitProjectSdkService implements InitProjectSdkService.Interface {\n constructor(\n private getProjectService: GetProjectService.Interface,\n private getProjectConfig: GetProjectConfig.Interface\n ) {}\n\n async execute(container: Container) {\n const project = this.getProjectService.execute();\n const projectExtensions = await this.getProjectConfig.execute({\n tags: { runtimeContext: \"project\" }\n });\n\n // Apply environment variables from extensions.\n applyEnvVars(projectExtensions);\n\n // Set WCP environment variables if project ID exists.\n await applyWcpEnvVars(container);\n\n // Register hooks from extensions.\n await registerHooks(container, projectExtensions, project);\n\n // Register Pulumi extensions.\n await registerPulumiExtensions(container, projectExtensions, project);\n\n // Decorators that must be applied last on top of potentially custom ones.\n container.registerDecorator(buildAppWithHooks);\n container.registerDecorator(deployAppWithWatchedLambdaReplacement);\n container.registerDecorator(deployAppClearWatchedLambdaFunctions);\n container.registerDecorator(deployAppRefreshStackOutputCache);\n container.registerDecorator(destroyAppClearStackOutputCache);\n container.registerDecorator(deployAppWithHooks);\n container.registerDecorator(watchWithHooks);\n container.registerDecorator(getPulumiServiceWithDownloadInfo);\n\n // Register custom implementations first (they replace existing implementations).\n await registerImplementations(container, projectExtensions, project);\n\n // Register decorators after implementations (they enhance existing implementations).\n await registerDecorators(container, projectExtensions, project);\n }\n}\n\nexport const initProjectSdkService = createImplementation({\n abstraction: InitProjectSdkService,\n implementation: DefaultInitProjectSdkService,\n dependencies: [GetProjectService, GetProjectConfig]\n});\n"],"names":["DefaultInitProjectSdkService","getProjectService","getProjectConfig","container","project","projectExtensions","applyEnvVars","applyWcpEnvVars","registerHooks","registerPulumiExtensions","buildAppWithHooks","deployAppWithWatchedLambdaReplacement","deployAppClearWatchedLambdaFunctions","deployAppRefreshStackOutputCache","destroyAppClearStackOutputCache","deployAppWithHooks","watchWithHooks","getPulumiServiceWithDownloadInfo","registerImplementations","registerDecorators","initProjectSdkService","createImplementation","InitProjectSdkService","GetProjectService","GetProjectConfig"],"mappings":";;;;;;;;;AAuBO,MAAMA;IACT,YACYC,iBAA8C,EAC9CC,gBAA4C,CACtD;aAFUD,iBAAiB,GAAjBA;aACAC,gBAAgB,GAAhBA;IACT;IAEH,MAAM,QAAQC,SAAoB,EAAE;QAChC,MAAMC,UAAU,IAAI,CAAC,iBAAiB,CAAC,OAAO;QAC9C,MAAMC,oBAAoB,MAAM,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC;YAC1D,MAAM;gBAAE,gBAAgB;YAAU;QACtC;QAGAC,aAAaD;QAGb,MAAME,gBAAgBJ;QAGtB,MAAMK,cAAcL,WAAWE,mBAAmBD;QAGlD,MAAMK,yBAAyBN,WAAWE,mBAAmBD;QAG7DD,UAAU,iBAAiB,CAACO;QAC5BP,UAAU,iBAAiB,CAACQ;QAC5BR,UAAU,iBAAiB,CAACS;QAC5BT,UAAU,iBAAiB,CAACU;QAC5BV,UAAU,iBAAiB,CAACW;QAC5BX,UAAU,iBAAiB,CAACY;QAC5BZ,UAAU,iBAAiB,CAACa;QAC5Bb,UAAU,iBAAiB,CAACc;QAG5B,MAAMC,wBAAwBf,WAAWE,mBAAmBD;QAG5D,MAAMe,mBAAmBhB,WAAWE,mBAAmBD;IAC3D;AACJ;AAEO,MAAMgB,wBAAwBC,qBAAqB;IACtD,aAAaC;IACb,gBAAgBtB;IAChB,cAAc;QAACuB;QAAmBC;KAAiB;AACvD"}
1
+ {"version":3,"file":"services/InitProjectSdkService/InitProjectSdkService.js","sources":["../../../src/services/InitProjectSdkService/InitProjectSdkService.ts"],"sourcesContent":["import { createImplementation, Container } from \"@webiny/di\";\nimport {\n GetProjectService,\n GetProjectConfig,\n InitProjectSdkService\n} from \"~/abstractions/index.js\";\nimport {\n buildAppWithHooks,\n deployAppClearWatchedLambdaFunctions,\n deployAppRefreshStackOutputCache,\n deployAppWithHooks,\n deployAppWithWatchedLambdaReplacement,\n destroyAppClearStackOutputCache,\n watchWithHooks,\n getPulumiServiceWithDownloadInfo\n} from \"~/decorators/index.js\";\nimport { registerHooks } from \"./registerHooks.js\";\nimport { registerPulumiExtensions } from \"./registerPulumiExtensions.js\";\nimport { registerImplementations } from \"./registerImplementations.js\";\nimport { registerDecorators } from \"./registerDecorators.js\";\nimport { traceAsync } from \"~/utils/trace/index.js\";\n\nexport class DefaultInitProjectSdkService implements InitProjectSdkService.Interface {\n constructor(\n private getProjectService: GetProjectService.Interface,\n private getProjectConfig: GetProjectConfig.Interface\n ) {}\n\n async execute(container: Container) {\n const project = this.getProjectService.execute();\n const projectExtensions = await this.getProjectConfig.execute({\n tags: { runtimeContext: \"project\" }\n });\n\n // Environment variables, WCP ones included, are applied by `createProjectSdkContainer` before\n // this runs, because the WCP license has to be known before the config is rendered.\n\n // Register hooks from extensions.\n await traceAsync(\"register hooks\", () => {\n return registerHooks(container, projectExtensions, project);\n });\n\n // Register Pulumi extensions.\n await traceAsync(\"register Pulumi extensions\", () => {\n return registerPulumiExtensions(container, projectExtensions, project);\n });\n\n // Decorators that must be applied last on top of potentially custom ones.\n container.registerDecorator(buildAppWithHooks);\n container.registerDecorator(deployAppWithWatchedLambdaReplacement);\n container.registerDecorator(deployAppClearWatchedLambdaFunctions);\n container.registerDecorator(deployAppRefreshStackOutputCache);\n container.registerDecorator(destroyAppClearStackOutputCache);\n container.registerDecorator(deployAppWithHooks);\n container.registerDecorator(watchWithHooks);\n container.registerDecorator(getPulumiServiceWithDownloadInfo);\n\n // Register custom implementations first (they replace existing implementations).\n await traceAsync(\"register implementations\", () => {\n return registerImplementations(container, projectExtensions, project);\n });\n\n // Register decorators after implementations (they enhance existing implementations).\n await traceAsync(\"register decorators\", () => {\n return registerDecorators(container, projectExtensions, project);\n });\n }\n}\n\nexport const initProjectSdkService = createImplementation({\n abstraction: InitProjectSdkService,\n implementation: DefaultInitProjectSdkService,\n dependencies: [GetProjectService, GetProjectConfig]\n});\n"],"names":["DefaultInitProjectSdkService","getProjectService","getProjectConfig","container","project","projectExtensions","traceAsync","registerHooks","registerPulumiExtensions","buildAppWithHooks","deployAppWithWatchedLambdaReplacement","deployAppClearWatchedLambdaFunctions","deployAppRefreshStackOutputCache","destroyAppClearStackOutputCache","deployAppWithHooks","watchWithHooks","getPulumiServiceWithDownloadInfo","registerImplementations","registerDecorators","initProjectSdkService","createImplementation","InitProjectSdkService","GetProjectService","GetProjectConfig"],"mappings":";;;;;;;;AAsBO,MAAMA;IACT,YACYC,iBAA8C,EAC9CC,gBAA4C,CACtD;aAFUD,iBAAiB,GAAjBA;aACAC,gBAAgB,GAAhBA;IACT;IAEH,MAAM,QAAQC,SAAoB,EAAE;QAChC,MAAMC,UAAU,IAAI,CAAC,iBAAiB,CAAC,OAAO;QAC9C,MAAMC,oBAAoB,MAAM,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC;YAC1D,MAAM;gBAAE,gBAAgB;YAAU;QACtC;QAMA,MAAMC,WAAW,kBAAkB,IACxBC,cAAcJ,WAAWE,mBAAmBD;QAIvD,MAAME,WAAW,8BAA8B,IACpCE,yBAAyBL,WAAWE,mBAAmBD;QAIlED,UAAU,iBAAiB,CAACM;QAC5BN,UAAU,iBAAiB,CAACO;QAC5BP,UAAU,iBAAiB,CAACQ;QAC5BR,UAAU,iBAAiB,CAACS;QAC5BT,UAAU,iBAAiB,CAACU;QAC5BV,UAAU,iBAAiB,CAACW;QAC5BX,UAAU,iBAAiB,CAACY;QAC5BZ,UAAU,iBAAiB,CAACa;QAG5B,MAAMV,WAAW,4BAA4B,IAClCW,wBAAwBd,WAAWE,mBAAmBD;QAIjE,MAAME,WAAW,uBAAuB,IAC7BY,mBAAmBf,WAAWE,mBAAmBD;IAEhE;AACJ;AAEO,MAAMe,wBAAwBC,qBAAqB;IACtD,aAAaC;IACb,gBAAgBrB;IAChB,cAAc;QAACsB;QAAmBC;KAAiB;AACvD"}
@@ -1,5 +1,13 @@
1
1
  import { decrypt, encrypt } from "@webiny/wcp";
2
2
  import { GetProjectIdService, LoggerService, ProjectSdkParamsService, WcpService } from "../../abstractions/index.js";
3
+ const applyProjectLicense = async (wcpService, params)=>{
4
+ if (!params.apiKey) return null;
5
+ const license = await wcpService.getProjectLicense(params);
6
+ if (!license) return null;
7
+ const licenseDto = license.toDto();
8
+ if (licenseDto) process.env.WCP_PROJECT_LICENSE = JSON.stringify(licenseDto);
9
+ return license;
10
+ };
3
11
  const applyWcpEnvVars = async (container)=>{
4
12
  const getProjectIdService = container.resolve(GetProjectIdService);
5
13
  const wcpService = container.resolve(WcpService);
@@ -7,20 +15,35 @@ const applyWcpEnvVars = async (container)=>{
7
15
  const projectSdkParamsService = container.resolve(ProjectSdkParamsService);
8
16
  const wcpProjectId = await getProjectIdService.execute();
9
17
  if (!wcpProjectId) return void loggerService.debug('Was not able to determine the WCP project ID. Skipping the setting of "WCP_PROJECT_ENVIRONMENT" and "WCP_PROJECT_ENVIRONMENT_API_KEY" env vars.');
18
+ const [orgId, projectId] = wcpProjectId.split("/");
10
19
  if (process.env.WCP_PROJECT_ENVIRONMENT) {
11
- loggerService.info('The "WCP_PROJECT_ENVIRONMENT" env var is already set. Using that value and skipping the rest of the process.');
20
+ loggerService.info('The "WCP_PROJECT_ENVIRONMENT" env var is already set. Using that value instead of looking the environment up.');
12
21
  const decryptedProjectEnvironment = decrypt(process.env.WCP_PROJECT_ENVIRONMENT);
13
22
  process.env.WEBINY_PROJECT_API_KEY = decryptedProjectEnvironment.apiKey;
14
23
  process.env.WCP_PROJECT_ENVIRONMENT_API_KEY = decryptedProjectEnvironment.apiKey;
24
+ const suppliedOrgId = decryptedProjectEnvironment.org?.id;
25
+ const suppliedProjectId = decryptedProjectEnvironment.project?.id;
26
+ const belongsToThisProject = suppliedOrgId === orgId && suppliedProjectId === projectId;
27
+ if (!process.env.WCP_PROJECT_LICENSE && !belongsToThisProject) loggerService.warn({
28
+ suppliedOrgId,
29
+ suppliedProjectId,
30
+ wcpProjectId
31
+ }, `"WCP_PROJECT_ENVIRONMENT" belongs to "${suppliedOrgId}/${suppliedProjectId}", not to "${wcpProjectId}". Not fetching its license.`);
32
+ if (!process.env.WCP_PROJECT_LICENSE && belongsToThisProject) await applyProjectLicense(wcpService, {
33
+ apiKey: decryptedProjectEnvironment.apiKey,
34
+ orgId,
35
+ projectId
36
+ });
15
37
  return;
16
38
  }
17
- const [orgId, projectId] = wcpProjectId.split("/");
18
39
  const apiKey = process.env.WEBINY_PROJECT_API_KEY || process.env.WCP_PROJECT_ENVIRONMENT_API_KEY;
19
40
  const sdkParams = projectSdkParamsService.get();
20
41
  const env = sdkParams.env;
21
42
  let projectEnvironment;
22
43
  if (apiKey) projectEnvironment = await wcpService.getProjectEnvironment({
23
- apiKey
44
+ apiKey,
45
+ orgId,
46
+ projectId
24
47
  });
25
48
  else {
26
49
  const isValidId = orgId && projectId;
@@ -61,8 +84,7 @@ const applyWcpEnvVars = async (container)=>{
61
84
  loggerService.error(`The "${projectEnvironment.name}" project environment has been disabled.`);
62
85
  throw new Error(`Cannot retrieve project environment because the "${projectEnvironment.name}" project environment has been disabled.`);
63
86
  }
64
- let license = null;
65
- if (projectEnvironment.apiKey) license = await wcpService.getProjectLicense({
87
+ const license = await applyProjectLicense(wcpService, {
66
88
  apiKey: projectEnvironment.apiKey,
67
89
  orgId,
68
90
  projectId
@@ -80,10 +102,6 @@ const applyWcpEnvVars = async (container)=>{
80
102
  process.env.WCP_PROJECT_ENVIRONMENT = encrypt(wcpProjectEnvironment);
81
103
  process.env.WEBINY_PROJECT_API_KEY = projectEnvironment.apiKey;
82
104
  process.env.WCP_PROJECT_ENVIRONMENT_API_KEY = projectEnvironment.apiKey;
83
- if (license) {
84
- const licenseDto = license.toDto();
85
- if (licenseDto) process.env.WCP_PROJECT_LICENSE = JSON.stringify(licenseDto);
86
- }
87
105
  loggerService.debug({
88
106
  id: projectEnvironment.id,
89
107
  apiKey: projectEnvironment.apiKey.replace(/./g, "#"),
@@ -1 +1 @@
1
- {"version":3,"file":"services/InitProjectSdkService/applyWcpEnvVars.js","sources":["../../../src/services/InitProjectSdkService/applyWcpEnvVars.ts"],"sourcesContent":["import { encrypt, decrypt } from \"@webiny/wcp\";\nimport type { ILicense } from \"@webiny/wcp/types\";\nimport { Container } from \"@webiny/di\";\nimport {\n GetProjectIdService,\n LoggerService,\n ProjectSdkParamsService,\n WcpService\n} from \"~/abstractions/index.js\";\n\nexport const applyWcpEnvVars = async (container: Container) => {\n /**\n * The environment variables we set via these hooks are the following:\n * - WCP_PROJECT_ENVIRONMENT - contains encrypted data about the deployed project environment\n * - WEBINY_PROJECT_API_KEY / WCP_PROJECT_ENVIRONMENT_API_KEY - for easier access, we also set the API key\n * - WCP_PROJECT_LICENSE - contains encrypted license data\n */\n\n /**\n * There are multiple ways the hooks below prepare the WCP-enabled project for deployment.\n * 1. If `WCP_PROJECT_ENVIRONMENT` metadata env var is defined, we decrypt it, retrieve the\n * API key from it, and assign it as the `WEBINY_PROJECT_API_KEY` and `WCP_PROJECT_ENVIRONMENT_API_KEY` env vars.\n * 2. If `WEBINY_PROJECT_API_KEY` or `WCP_PROJECT_ENVIRONMENT_API_KEY` env var is defined, then we use that as the\n * project environment API key. We use that to load the project environment data\n * and to also assign the `WCP_PROJECT_ENVIRONMENT` metadata env var.\n * 3. If none of the above is defined, we retrieve (or create) the project environment,\n * retrieve its API key and again assign it as `WEBINY_PROJECT_API_KEY` and `WCP_PROJECT_ENVIRONMENT_API_KEY` env vars.\n * As in 2), we also assign the `WCP_PROJECT_ENVIRONMENT` metadata env var.\n */\n\n const getProjectIdService = container.resolve(GetProjectIdService);\n const wcpService = container.resolve(WcpService);\n const loggerService = container.resolve(LoggerService);\n const projectSdkParamsService = container.resolve(ProjectSdkParamsService);\n\n const wcpProjectId = await getProjectIdService.execute();\n\n // If the project isn't linked with WCP, do nothing.\n if (!wcpProjectId) {\n loggerService.debug(\n 'Was not able to determine the WCP project ID. Skipping the setting of \"WCP_PROJECT_ENVIRONMENT\" and \"WCP_PROJECT_ENVIRONMENT_API_KEY\" env vars.'\n );\n return;\n }\n\n // Case 1: For development purposes, we allow setting the WCP_PROJECT_ENVIRONMENT env var directly.\n if (process.env.WCP_PROJECT_ENVIRONMENT) {\n loggerService.info(\n 'The \"WCP_PROJECT_ENVIRONMENT\" env var is already set. Using that value and skipping the rest of the process.'\n );\n // If we have WCP_PROJECT_ENVIRONMENT env var, we set the WEBINY_PROJECT_API_KEY and WCP_PROJECT_ENVIRONMENT_API_KEY too.\n const decryptedProjectEnvironment = decrypt(process.env.WCP_PROJECT_ENVIRONMENT);\n process.env.WEBINY_PROJECT_API_KEY = decryptedProjectEnvironment.apiKey;\n process.env.WCP_PROJECT_ENVIRONMENT_API_KEY = decryptedProjectEnvironment.apiKey;\n return;\n }\n\n // The `id` has the orgId/projectId structure, for example `my-org-x/my-project-y`.\n const [orgId, projectId] = wcpProjectId.split(\"/\");\n\n // Check if API key is already set (prefer WEBINY_PROJECT_API_KEY over WCP_PROJECT_ENVIRONMENT_API_KEY).\n const apiKey =\n process.env.WEBINY_PROJECT_API_KEY || process.env.WCP_PROJECT_ENVIRONMENT_API_KEY;\n\n const sdkParams = projectSdkParamsService.get();\n const env = sdkParams.env;\n\n let projectEnvironment;\n if (apiKey) {\n projectEnvironment = await wcpService.getProjectEnvironment({ apiKey });\n } else {\n const isValidId = orgId && projectId;\n if (!isValidId) {\n loggerService.error(\n { orgId, projectId, wcpProjectId },\n `The project ID, specified in \"webiny.config.tsx\" file, seems to be invalid.`\n );\n throw new Error(\n `It seems the project ID, specified in \"webiny.config.tsx\" file, is invalid.`\n );\n }\n\n // If there is no API key, that means we need to retrieve the currently logged-in user.\n const user = await wcpService.getUser();\n if (!user) {\n throw new Error(\n `It seems you are not logged into your WCP project. Please log in using the \"yarn webiny login\" command.`\n );\n }\n\n const project = user.projects.find(item => item.id === projectId);\n if (!project) {\n loggerService.error(\n { projects: user.projects },\n `The \"${projectId}\" project doesn't exist or you don't belong to it.`\n );\n throw new Error(\n `It seems you don't belong to the current project or the current project has been deleted.`\n );\n }\n\n loggerService.debug(\n `Retrieving the \"${env}\" project environment for the \"${project.name}\" project.`\n );\n\n projectEnvironment = await wcpService.getProjectEnvironment({\n orgId,\n projectId,\n userId: user.id,\n environmentId: env\n });\n }\n\n // Validate the project environment belongs to the correct org and project\n if (projectEnvironment.org.id !== orgId) {\n loggerService.error(\n `The \"${projectEnvironment.name}\" project environment doesn't belong to the \"${orgId}\" organization.`\n );\n throw new Error(\n `Cannot retrieve project environment because the \"${projectEnvironment.name}\" project environment doesn't belong to the \"${orgId}\" organization. Please check your WCP project ID (currently set to \"${wcpProjectId}\").`\n );\n }\n\n if (projectEnvironment.project.id !== projectId) {\n loggerService.error(\n `The \"${projectEnvironment.name}\" project environment doesn't belong to the \"${projectId}\" project.`\n );\n throw new Error(\n `Cannot retrieve project environment because the \"${projectEnvironment.name}\" project environment doesn't belong to the \"${wcpProjectId}\" project. Please check your WCP project ID (currently set to \"${wcpProjectId}\").`\n );\n }\n\n if (projectEnvironment && projectEnvironment.status !== \"enabled\") {\n loggerService.error(\n `The \"${projectEnvironment.name}\" project environment has been disabled.`\n );\n throw new Error(\n `Cannot retrieve project environment because the \"${projectEnvironment.name}\" project environment has been disabled.`\n );\n }\n\n // Fetch license\n let license: ILicense | null = null;\n if (projectEnvironment.apiKey) {\n license = await wcpService.getProjectLicense({\n apiKey: projectEnvironment.apiKey,\n orgId,\n projectId\n });\n }\n\n // Assign `WCP_PROJECT_ENVIRONMENT`, `WEBINY_PROJECT_API_KEY`, `WCP_PROJECT_ENVIRONMENT_API_KEY`, and `WCP_PROJECT_LICENSE`.\n const wcpProjectEnvironment = {\n id: projectEnvironment.id,\n apiKey: projectEnvironment.apiKey,\n org: { id: projectEnvironment.org.id },\n project: { id: projectEnvironment.project.id }\n };\n\n process.env.WCP_PROJECT_ENVIRONMENT = encrypt(wcpProjectEnvironment);\n process.env.WEBINY_PROJECT_API_KEY = projectEnvironment.apiKey;\n process.env.WCP_PROJECT_ENVIRONMENT_API_KEY = projectEnvironment.apiKey;\n if (license) {\n const licenseDto = license.toDto();\n if (licenseDto) {\n process.env.WCP_PROJECT_LICENSE = JSON.stringify(licenseDto);\n }\n }\n\n loggerService.debug(\n {\n id: projectEnvironment.id,\n apiKey: projectEnvironment.apiKey.replace(/./g, \"#\"),\n org: { id: projectEnvironment.org.id },\n project: { id: projectEnvironment.project.id },\n license: license ? \"present\" : \"not fetched\"\n },\n `WCP project environment \"${projectEnvironment.name}\" (ID: ${projectEnvironment.id}) has been set.`\n );\n};\n"],"names":["applyWcpEnvVars","container","getProjectIdService","GetProjectIdService","wcpService","WcpService","loggerService","LoggerService","projectSdkParamsService","ProjectSdkParamsService","wcpProjectId","process","decryptedProjectEnvironment","decrypt","orgId","projectId","apiKey","sdkParams","env","projectEnvironment","isValidId","Error","user","project","item","license","wcpProjectEnvironment","encrypt","licenseDto","JSON"],"mappings":"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"}
1
+ {"version":3,"file":"services/InitProjectSdkService/applyWcpEnvVars.js","sources":["../../../src/services/InitProjectSdkService/applyWcpEnvVars.ts"],"sourcesContent":["import { encrypt, decrypt } from \"@webiny/wcp\";\nimport type { ILicense } from \"@webiny/wcp/types\";\nimport { Container } from \"@webiny/di\";\nimport {\n GetProjectIdService,\n LoggerService,\n ProjectSdkParamsService,\n WcpService\n} from \"~/abstractions/index.js\";\n\n/*\n * Fetches the project license and puts it in `WCP_PROJECT_LICENSE`, which is where the config render\n * reads it from. License-gated feature flags decide which extensions the rendered config contains,\n * so a missing license silently produces a config without them.\n */\nconst applyProjectLicense = async (\n wcpService: WcpService.Interface,\n params: { apiKey: string; orgId: string; projectId: string }\n): Promise<ILicense | null> => {\n if (!params.apiKey) {\n return null;\n }\n\n const license = await wcpService.getProjectLicense(params);\n if (!license) {\n return null;\n }\n\n const licenseDto = license.toDto();\n if (licenseDto) {\n process.env.WCP_PROJECT_LICENSE = JSON.stringify(licenseDto);\n }\n\n return license;\n};\n\nexport const applyWcpEnvVars = async (container: Container) => {\n /**\n * The environment variables we set via these hooks are the following:\n * - WCP_PROJECT_ENVIRONMENT - contains encrypted data about the deployed project environment\n * - WEBINY_PROJECT_API_KEY / WCP_PROJECT_ENVIRONMENT_API_KEY - for easier access, we also set the API key\n * - WCP_PROJECT_LICENSE - contains encrypted license data\n */\n\n /**\n * There are multiple ways the hooks below prepare the WCP-enabled project for deployment.\n * 1. If `WCP_PROJECT_ENVIRONMENT` metadata env var is defined, we decrypt it, retrieve the\n * API key from it, and assign it as the `WEBINY_PROJECT_API_KEY` and `WCP_PROJECT_ENVIRONMENT_API_KEY` env vars.\n * 2. If `WEBINY_PROJECT_API_KEY` or `WCP_PROJECT_ENVIRONMENT_API_KEY` env var is defined, then we use that as the\n * project environment API key. We use that to load the project environment data\n * and to also assign the `WCP_PROJECT_ENVIRONMENT` metadata env var.\n * 3. If none of the above is defined, we retrieve (or create) the project environment,\n * retrieve its API key and again assign it as `WEBINY_PROJECT_API_KEY` and `WCP_PROJECT_ENVIRONMENT_API_KEY` env vars.\n * As in 2), we also assign the `WCP_PROJECT_ENVIRONMENT` metadata env var.\n */\n\n const getProjectIdService = container.resolve(GetProjectIdService);\n const wcpService = container.resolve(WcpService);\n const loggerService = container.resolve(LoggerService);\n const projectSdkParamsService = container.resolve(ProjectSdkParamsService);\n\n const wcpProjectId = await getProjectIdService.execute();\n\n // If the project isn't linked with WCP, do nothing.\n if (!wcpProjectId) {\n loggerService.debug(\n 'Was not able to determine the WCP project ID. Skipping the setting of \"WCP_PROJECT_ENVIRONMENT\" and \"WCP_PROJECT_ENVIRONMENT_API_KEY\" env vars.'\n );\n return;\n }\n\n // The `id` has the orgId/projectId structure, for example `my-org-x/my-project-y`.\n const [orgId, projectId] = wcpProjectId.split(\"/\");\n\n // Case 1: For development purposes, we allow setting the WCP_PROJECT_ENVIRONMENT env var directly.\n if (process.env.WCP_PROJECT_ENVIRONMENT) {\n loggerService.info(\n 'The \"WCP_PROJECT_ENVIRONMENT\" env var is already set. Using that value instead of looking the environment up.'\n );\n // If we have WCP_PROJECT_ENVIRONMENT env var, we set the WEBINY_PROJECT_API_KEY and WCP_PROJECT_ENVIRONMENT_API_KEY too.\n const decryptedProjectEnvironment = decrypt(process.env.WCP_PROJECT_ENVIRONMENT);\n process.env.WEBINY_PROJECT_API_KEY = decryptedProjectEnvironment.apiKey;\n process.env.WCP_PROJECT_ENVIRONMENT_API_KEY = decryptedProjectEnvironment.apiKey;\n\n // Build and watch processes inherit `WCP_PROJECT_LICENSE` along with this variable, so they\n // already have one. Someone who sets `WCP_PROJECT_ENVIRONMENT` by hand, in CI for instance,\n // usually doesn't, and without it the config renders as though the project had no license.\n //\n // Only if the environment belongs to the project this config names, though. Otherwise the\n // config would render with another project's entitlements. This path has never checked\n // that, and failing here would break setups that work today, so a mismatch skips the\n // license with a warning instead, the same as if it had never been fetched.\n const suppliedOrgId = decryptedProjectEnvironment.org?.id;\n const suppliedProjectId = decryptedProjectEnvironment.project?.id;\n const belongsToThisProject = suppliedOrgId === orgId && suppliedProjectId === projectId;\n\n if (!process.env.WCP_PROJECT_LICENSE && !belongsToThisProject) {\n loggerService.warn(\n { suppliedOrgId, suppliedProjectId, wcpProjectId },\n `\"WCP_PROJECT_ENVIRONMENT\" belongs to \"${suppliedOrgId}/${suppliedProjectId}\", not to \"${wcpProjectId}\". Not fetching its license.`\n );\n }\n\n if (!process.env.WCP_PROJECT_LICENSE && belongsToThisProject) {\n await applyProjectLicense(wcpService, {\n apiKey: decryptedProjectEnvironment.apiKey,\n orgId,\n projectId\n });\n }\n\n return;\n }\n\n // Check if API key is already set (prefer WEBINY_PROJECT_API_KEY over WCP_PROJECT_ENVIRONMENT_API_KEY).\n const apiKey =\n process.env.WEBINY_PROJECT_API_KEY || process.env.WCP_PROJECT_ENVIRONMENT_API_KEY;\n\n const sdkParams = projectSdkParamsService.get();\n const env = sdkParams.env;\n\n let projectEnvironment;\n if (apiKey) {\n // The org and project let the lookup use WCP's cacheable REST endpoint.\n projectEnvironment = await wcpService.getProjectEnvironment({ apiKey, orgId, projectId });\n } else {\n const isValidId = orgId && projectId;\n if (!isValidId) {\n loggerService.error(\n { orgId, projectId, wcpProjectId },\n `The project ID, specified in \"webiny.config.tsx\" file, seems to be invalid.`\n );\n throw new Error(\n `It seems the project ID, specified in \"webiny.config.tsx\" file, is invalid.`\n );\n }\n\n // If there is no API key, that means we need to retrieve the currently logged-in user.\n const user = await wcpService.getUser();\n if (!user) {\n throw new Error(\n `It seems you are not logged into your WCP project. Please log in using the \"yarn webiny login\" command.`\n );\n }\n\n const project = user.projects.find(item => item.id === projectId);\n if (!project) {\n loggerService.error(\n { projects: user.projects },\n `The \"${projectId}\" project doesn't exist or you don't belong to it.`\n );\n throw new Error(\n `It seems you don't belong to the current project or the current project has been deleted.`\n );\n }\n\n loggerService.debug(\n `Retrieving the \"${env}\" project environment for the \"${project.name}\" project.`\n );\n\n projectEnvironment = await wcpService.getProjectEnvironment({\n orgId,\n projectId,\n userId: user.id,\n environmentId: env\n });\n }\n\n // Validate the project environment belongs to the correct org and project\n if (projectEnvironment.org.id !== orgId) {\n loggerService.error(\n `The \"${projectEnvironment.name}\" project environment doesn't belong to the \"${orgId}\" organization.`\n );\n throw new Error(\n `Cannot retrieve project environment because the \"${projectEnvironment.name}\" project environment doesn't belong to the \"${orgId}\" organization. Please check your WCP project ID (currently set to \"${wcpProjectId}\").`\n );\n }\n\n if (projectEnvironment.project.id !== projectId) {\n loggerService.error(\n `The \"${projectEnvironment.name}\" project environment doesn't belong to the \"${projectId}\" project.`\n );\n throw new Error(\n `Cannot retrieve project environment because the \"${projectEnvironment.name}\" project environment doesn't belong to the \"${wcpProjectId}\" project. Please check your WCP project ID (currently set to \"${wcpProjectId}\").`\n );\n }\n\n if (projectEnvironment && projectEnvironment.status !== \"enabled\") {\n loggerService.error(\n `The \"${projectEnvironment.name}\" project environment has been disabled.`\n );\n throw new Error(\n `Cannot retrieve project environment because the \"${projectEnvironment.name}\" project environment has been disabled.`\n );\n }\n\n const license = await applyProjectLicense(wcpService, {\n apiKey: projectEnvironment.apiKey,\n orgId,\n projectId\n });\n\n // Assign `WCP_PROJECT_ENVIRONMENT`, `WEBINY_PROJECT_API_KEY` and `WCP_PROJECT_ENVIRONMENT_API_KEY`. The license was assigned above.\n const wcpProjectEnvironment = {\n id: projectEnvironment.id,\n apiKey: projectEnvironment.apiKey,\n org: { id: projectEnvironment.org.id },\n project: { id: projectEnvironment.project.id }\n };\n\n process.env.WCP_PROJECT_ENVIRONMENT = encrypt(wcpProjectEnvironment);\n process.env.WEBINY_PROJECT_API_KEY = projectEnvironment.apiKey;\n process.env.WCP_PROJECT_ENVIRONMENT_API_KEY = projectEnvironment.apiKey;\n\n loggerService.debug(\n {\n id: projectEnvironment.id,\n apiKey: projectEnvironment.apiKey.replace(/./g, \"#\"),\n org: { id: projectEnvironment.org.id },\n project: { id: projectEnvironment.project.id },\n license: license ? \"present\" : \"not fetched\"\n },\n `WCP project environment \"${projectEnvironment.name}\" (ID: ${projectEnvironment.id}) has been set.`\n );\n};\n"],"names":["applyProjectLicense","wcpService","params","license","licenseDto","process","JSON","applyWcpEnvVars","container","getProjectIdService","GetProjectIdService","WcpService","loggerService","LoggerService","projectSdkParamsService","ProjectSdkParamsService","wcpProjectId","orgId","projectId","decryptedProjectEnvironment","decrypt","suppliedOrgId","suppliedProjectId","belongsToThisProject","apiKey","sdkParams","env","projectEnvironment","isValidId","Error","user","project","item","wcpProjectEnvironment","encrypt"],"mappings":"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"}
@@ -1,19 +1,22 @@
1
1
  import { createImplementation } from "@webiny/di";
2
2
  import { ValidateProjectConfigService } from "../../abstractions/index.js";
3
3
  import { ProjectError } from "../../ProjectError.js";
4
+ import { traceAsync } from "../../utils/trace/index.js";
4
5
  class DefaultValidateProjectConfigService {
5
6
  async execute(projectConfig) {
6
7
  const extensionTypes = Object.keys(projectConfig.config);
7
8
  for (const extensionType of extensionTypes){
8
9
  const extensionsCollection = projectConfig.extensionsByType(extensionType);
9
- for (const extension of extensionsCollection){
10
- await extension.validateParams();
11
- if (extension.validate) try {
12
- await extension.validate();
13
- } catch (error) {
14
- throw ProjectError.from(`Validation failed for extension of type %s: ${error.message}`, extensionType);
10
+ await traceAsync(`validate "${extensionType}"`, async ()=>{
11
+ for (const extension of extensionsCollection){
12
+ await extension.validateParams();
13
+ if (extension.validate) try {
14
+ await extension.validate();
15
+ } catch (error) {
16
+ throw ProjectError.from(`Validation failed for extension of type %s: ${error.message}`, extensionType);
17
+ }
15
18
  }
16
- }
19
+ });
17
20
  }
18
21
  }
19
22
  }
@@ -1 +1 @@
1
- {"version":3,"file":"services/ValidateProjectConfigService/ValidateProjectConfigService.js","sources":["../../../src/services/ValidateProjectConfigService/ValidateProjectConfigService.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/di\";\nimport { ValidateProjectConfigService } from \"~/abstractions/index.js\";\nimport { ProjectError } from \"~/ProjectError.js\";\n\nexport class DefaultValidateProjectConfigService implements ValidateProjectConfigService.Interface {\n async execute(projectConfig: ValidateProjectConfigService.Params): Promise<void> {\n const extensionTypes = Object.keys(projectConfig.config);\n for (const extensionType of extensionTypes) {\n const extensionsCollection = projectConfig.extensionsByType(extensionType);\n for (const extension of extensionsCollection) {\n await extension.validateParams();\n\n if (extension.validate) {\n try {\n await extension.validate();\n } catch (error) {\n throw ProjectError.from(\n `Validation failed for extension of type %s: ${error.message}`,\n extensionType\n );\n }\n }\n }\n }\n }\n}\n\nexport const validateProjectConfigService = createImplementation({\n abstraction: ValidateProjectConfigService,\n implementation: DefaultValidateProjectConfigService,\n dependencies: []\n});\n"],"names":["DefaultValidateProjectConfigService","projectConfig","extensionTypes","Object","extensionType","extensionsCollection","extension","error","ProjectError","validateProjectConfigService","createImplementation","ValidateProjectConfigService"],"mappings":";;;AAIO,MAAMA;IACT,MAAM,QAAQC,aAAkD,EAAiB;QAC7E,MAAMC,iBAAiBC,OAAO,IAAI,CAACF,cAAc,MAAM;QACvD,KAAK,MAAMG,iBAAiBF,eAAgB;YACxC,MAAMG,uBAAuBJ,cAAc,gBAAgB,CAACG;YAC5D,KAAK,MAAME,aAAaD,qBAAsB;gBAC1C,MAAMC,UAAU,cAAc;gBAE9B,IAAIA,UAAU,QAAQ,EAClB,IAAI;oBACA,MAAMA,UAAU,QAAQ;gBAC5B,EAAE,OAAOC,OAAO;oBACZ,MAAMC,aAAa,IAAI,CACnB,CAAC,4CAA4C,EAAED,MAAM,OAAO,EAAE,EAC9DH;gBAER;YAER;QACJ;IACJ;AACJ;AAEO,MAAMK,+BAA+BC,qBAAqB;IAC7D,aAAaC;IACb,gBAAgBX;IAChB,cAAc,EAAE;AACpB"}
1
+ {"version":3,"file":"services/ValidateProjectConfigService/ValidateProjectConfigService.js","sources":["../../../src/services/ValidateProjectConfigService/ValidateProjectConfigService.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/di\";\nimport { ValidateProjectConfigService } from \"~/abstractions/index.js\";\nimport { ProjectError } from \"~/ProjectError.js\";\nimport { traceAsync } from \"~/utils/trace/index.js\";\n\nexport class DefaultValidateProjectConfigService implements ValidateProjectConfigService.Interface {\n async execute(projectConfig: ValidateProjectConfigService.Params): Promise<void> {\n const extensionTypes = Object.keys(projectConfig.config);\n for (const extensionType of extensionTypes) {\n const extensionsCollection = projectConfig.extensionsByType(extensionType);\n\n // Validation is serial, and an extension is free to hit the network or the filesystem in\n // its `validate`, so each type is timed separately.\n await traceAsync(`validate \"${extensionType}\"`, async () => {\n for (const extension of extensionsCollection) {\n await extension.validateParams();\n\n if (extension.validate) {\n try {\n await extension.validate();\n } catch (error) {\n throw ProjectError.from(\n `Validation failed for extension of type %s: ${error.message}`,\n extensionType\n );\n }\n }\n }\n });\n }\n }\n}\n\nexport const validateProjectConfigService = createImplementation({\n abstraction: ValidateProjectConfigService,\n implementation: DefaultValidateProjectConfigService,\n dependencies: []\n});\n"],"names":["DefaultValidateProjectConfigService","projectConfig","extensionTypes","Object","extensionType","extensionsCollection","traceAsync","extension","error","ProjectError","validateProjectConfigService","createImplementation","ValidateProjectConfigService"],"mappings":";;;;AAKO,MAAMA;IACT,MAAM,QAAQC,aAAkD,EAAiB;QAC7E,MAAMC,iBAAiBC,OAAO,IAAI,CAACF,cAAc,MAAM;QACvD,KAAK,MAAMG,iBAAiBF,eAAgB;YACxC,MAAMG,uBAAuBJ,cAAc,gBAAgB,CAACG;YAI5D,MAAME,WAAW,CAAC,UAAU,EAAEF,cAAc,CAAC,CAAC,EAAE;gBAC5C,KAAK,MAAMG,aAAaF,qBAAsB;oBAC1C,MAAME,UAAU,cAAc;oBAE9B,IAAIA,UAAU,QAAQ,EAClB,IAAI;wBACA,MAAMA,UAAU,QAAQ;oBAC5B,EAAE,OAAOC,OAAO;wBACZ,MAAMC,aAAa,IAAI,CACnB,CAAC,4CAA4C,EAAED,MAAM,OAAO,EAAE,EAC9DJ;oBAER;gBAER;YACJ;QACJ;IACJ;AACJ;AAEO,MAAMM,+BAA+BC,qBAAqB;IAC7D,aAAaC;IACb,gBAAgBZ;IAChB,cAAc,EAAE;AACpB"}
@@ -1,4 +1,5 @@
1
1
  import { WcpGqlClient } from "./WcpGqlClient.js";
2
+ import { fetchProjectEnvironmentByApiKey } from "./fetchProjectEnvironmentByApiKey.js";
2
3
  import { WcpEnvironmentModel } from "../../models/index.js";
3
4
  const ENVIRONMENT_FIELDS = `
4
5
  fragment EnvironmentFields on Environment {
@@ -64,11 +65,21 @@ class GetProjectEnvironment {
64
65
  async execute(params) {
65
66
  const { localStorageService } = this.di;
66
67
  const { orgId, projectId, userId, environmentId, apiKey } = params;
67
- if (apiKey) return WcpGqlClient.execute(GET_ENVIRONMENT, {
68
- apiKey
69
- }).then((response)=>WcpEnvironmentModel.fromDto(response.projects.getEnvironment)).catch(()=>{
70
- throw new Error("It seems the API key you provided is incorrect or disabled. Please double check the API key and try again.");
71
- });
68
+ if (apiKey) {
69
+ if (orgId && projectId) try {
70
+ const environment = await fetchProjectEnvironmentByApiKey({
71
+ apiKey,
72
+ orgId,
73
+ projectId
74
+ });
75
+ return WcpEnvironmentModel.fromDto(environment);
76
+ } catch {}
77
+ return WcpGqlClient.execute(GET_ENVIRONMENT, {
78
+ apiKey
79
+ }).then((response)=>WcpEnvironmentModel.fromDto(response.projects.getEnvironment)).catch(()=>{
80
+ throw new Error("It seems the API key you provided is incorrect or disabled. Please double check the API key and try again.");
81
+ });
82
+ }
72
83
  const pat = localStorageService.get("wcpPat");
73
84
  if (!pat) throw new Error('It seems you are not logged in. Please login using the "webiny login" command.');
74
85
  const headers = {
@@ -1 +1 @@
1
- {"version":3,"file":"services/WcpService/GetProjectEnvironment.js","sources":["../../../src/services/WcpService/GetProjectEnvironment.ts"],"sourcesContent":["import { LocalStorageService } from \"~/abstractions/index.js\";\nimport { WcpGqlClient } from \"./WcpGqlClient.js\";\nimport { IGetProjectEnvironmentParams } from \"~/abstractions/services/WcpService.js\";\nimport { IWcpEnvironmentDto } from \"~/abstractions/models/index.js\";\nimport { WcpEnvironmentModel } from \"~/models/index.js\";\n\nconst ENVIRONMENT_FIELDS = /* GraphQL */ `\n fragment EnvironmentFields on Environment {\n id\n status\n name\n apiKey\n org {\n id\n name\n }\n project {\n id\n name\n }\n user {\n id\n email\n }\n }\n`;\n\nconst CREATE_ENVIRONMENT = /* GraphQL */ `\n ${ENVIRONMENT_FIELDS}\n mutation CreateEnvironment(\n $orgId: ID!\n $projectId: ID!\n $userId: ID\n $data: CreateEnvironmentDataInput!\n ) {\n projects {\n createEnvironment(orgId: $orgId, projectId: $projectId, userId: $userId, data: $data) {\n ...EnvironmentFields\n }\n }\n }\n`;\n\nexport interface ICreateEnvironmentParams {\n projects: {\n createEnvironment: IWcpEnvironmentDto;\n };\n}\n\nconst GET_ENVIRONMENT = /* GraphQL */ `\n ${ENVIRONMENT_FIELDS}\n query GetEnvironment(\n $environmentId: ID\n $orgId: ID\n $projectId: ID\n $userId: ID\n $apiKey: String\n ) {\n projects {\n getEnvironment(\n environmentId: $environmentId\n orgId: $orgId\n projectId: $projectId\n userId: $userId\n apiKey: $apiKey\n ) {\n ...EnvironmentFields\n }\n }\n }\n`;\n\nexport interface IGetEnvironmentResponse {\n projects: {\n getEnvironment: IWcpEnvironmentDto;\n };\n}\n\nexport interface IGetProjectEnvironmentDi {\n localStorageService: LocalStorageService.Interface;\n}\n\nexport class GetProjectEnvironment {\n di: IGetProjectEnvironmentDi;\n\n constructor(di: IGetProjectEnvironmentDi) {\n this.di = di;\n }\n\n async execute(params: IGetProjectEnvironmentParams): Promise<WcpEnvironmentModel> {\n const { localStorageService } = this.di;\n const { orgId, projectId, userId, environmentId, apiKey } = params;\n\n if (apiKey) {\n return WcpGqlClient.execute<IGetEnvironmentResponse>(GET_ENVIRONMENT, { apiKey })\n .then(response => WcpEnvironmentModel.fromDto(response.projects.getEnvironment))\n .catch(() => {\n throw new Error(\n `It seems the API key you provided is incorrect or disabled. Please double check the API key and try again.`\n );\n });\n }\n\n const pat = localStorageService.get(\"wcpPat\");\n if (!pat) {\n throw new Error(\n `It seems you are not logged in. Please login using the \"webiny login\" command.`\n );\n }\n\n const headers = { authorization: pat };\n return WcpGqlClient.execute<IGetEnvironmentResponse>(\n GET_ENVIRONMENT,\n {\n orgId,\n projectId,\n userId,\n environmentId,\n apiKey\n },\n headers\n )\n .then(async response => WcpEnvironmentModel.fromDto(response.projects.getEnvironment))\n .catch(() => {\n return WcpGqlClient.execute<ICreateEnvironmentParams>(\n CREATE_ENVIRONMENT,\n {\n orgId,\n projectId,\n userId,\n data: {\n name: environmentId\n }\n },\n headers\n ).then(response => response.projects.createEnvironment);\n });\n }\n}\n"],"names":["ENVIRONMENT_FIELDS","CREATE_ENVIRONMENT","GET_ENVIRONMENT","GetProjectEnvironment","di","params","localStorageService","orgId","projectId","userId","environmentId","apiKey","WcpGqlClient","response","WcpEnvironmentModel","Error","pat","headers"],"mappings":";;AAMA,MAAMA,qBAAmC,CAAC;;;;;;;;;;;;;;;;;;;AAmB1C,CAAC;AAED,MAAMC,qBAAmC,CAAC;IACtC,EAAED,mBAAmB;;;;;;;;;;;;;AAazB,CAAC;AAQD,MAAME,kBAAgC,CAAC;IACnC,EAAEF,mBAAmB;;;;;;;;;;;;;;;;;;;;AAoBzB,CAAC;AAYM,MAAMG;IAGT,YAAYC,EAA4B,CAAE;QACtC,IAAI,CAAC,EAAE,GAAGA;IACd;IAEA,MAAM,QAAQC,MAAoC,EAAgC;QAC9E,MAAM,EAAEC,mBAAmB,EAAE,GAAG,IAAI,CAAC,EAAE;QACvC,MAAM,EAAEC,KAAK,EAAEC,SAAS,EAAEC,MAAM,EAAEC,aAAa,EAAEC,MAAM,EAAE,GAAGN;QAE5D,IAAIM,QACA,OAAOC,aAAa,OAAO,CAA0BV,iBAAiB;YAAES;QAAO,GAC1E,IAAI,CAACE,CAAAA,WAAYC,oBAAoB,OAAO,CAACD,SAAS,QAAQ,CAAC,cAAc,GAC7E,KAAK,CAAC;YACH,MAAM,IAAIE,MACN;QAER;QAGR,MAAMC,MAAMV,oBAAoB,GAAG,CAAC;QACpC,IAAI,CAACU,KACD,MAAM,IAAID,MACN;QAIR,MAAME,UAAU;YAAE,eAAeD;QAAI;QACrC,OAAOJ,aAAa,OAAO,CACvBV,iBACA;YACIK;YACAC;YACAC;YACAC;YACAC;QACJ,GACAM,SAEC,IAAI,CAAC,OAAMJ,WAAYC,oBAAoB,OAAO,CAACD,SAAS,QAAQ,CAAC,cAAc,GACnF,KAAK,CAAC,IACID,aAAa,OAAO,CACvBX,oBACA;gBACIM;gBACAC;gBACAC;gBACA,MAAM;oBACF,MAAMC;gBACV;YACJ,GACAO,SACF,IAAI,CAACJ,CAAAA,WAAYA,SAAS,QAAQ,CAAC,iBAAiB;IAElE;AACJ"}
1
+ {"version":3,"file":"services/WcpService/GetProjectEnvironment.js","sources":["../../../src/services/WcpService/GetProjectEnvironment.ts"],"sourcesContent":["import { LocalStorageService } from \"~/abstractions/index.js\";\nimport { WcpGqlClient } from \"./WcpGqlClient.js\";\nimport { fetchProjectEnvironmentByApiKey } from \"./fetchProjectEnvironmentByApiKey.js\";\nimport { IGetProjectEnvironmentParams } from \"~/abstractions/services/WcpService.js\";\nimport { IWcpEnvironmentDto } from \"~/abstractions/models/index.js\";\nimport { WcpEnvironmentModel } from \"~/models/index.js\";\n\nconst ENVIRONMENT_FIELDS = /* GraphQL */ `\n fragment EnvironmentFields on Environment {\n id\n status\n name\n apiKey\n org {\n id\n name\n }\n project {\n id\n name\n }\n user {\n id\n email\n }\n }\n`;\n\nconst CREATE_ENVIRONMENT = /* GraphQL */ `\n ${ENVIRONMENT_FIELDS}\n mutation CreateEnvironment(\n $orgId: ID!\n $projectId: ID!\n $userId: ID\n $data: CreateEnvironmentDataInput!\n ) {\n projects {\n createEnvironment(orgId: $orgId, projectId: $projectId, userId: $userId, data: $data) {\n ...EnvironmentFields\n }\n }\n }\n`;\n\nexport interface ICreateEnvironmentParams {\n projects: {\n createEnvironment: IWcpEnvironmentDto;\n };\n}\n\nconst GET_ENVIRONMENT = /* GraphQL */ `\n ${ENVIRONMENT_FIELDS}\n query GetEnvironment(\n $environmentId: ID\n $orgId: ID\n $projectId: ID\n $userId: ID\n $apiKey: String\n ) {\n projects {\n getEnvironment(\n environmentId: $environmentId\n orgId: $orgId\n projectId: $projectId\n userId: $userId\n apiKey: $apiKey\n ) {\n ...EnvironmentFields\n }\n }\n }\n`;\n\nexport interface IGetEnvironmentResponse {\n projects: {\n getEnvironment: IWcpEnvironmentDto;\n };\n}\n\nexport interface IGetProjectEnvironmentDi {\n localStorageService: LocalStorageService.Interface;\n}\n\nexport class GetProjectEnvironment {\n di: IGetProjectEnvironmentDi;\n\n constructor(di: IGetProjectEnvironmentDi) {\n this.di = di;\n }\n\n async execute(params: IGetProjectEnvironmentParams): Promise<WcpEnvironmentModel> {\n const { localStorageService } = this.di;\n const { orgId, projectId, userId, environmentId, apiKey } = params;\n\n if (apiKey) {\n // The cacheable REST endpoint needs the org and project in its URL. When a caller has\n // them, try it first. Anything but a clean answer falls through to the GraphQL query\n // below, which keeps every failure reported exactly as it was before the endpoint\n // existed, and keeps working against a WCP that doesn't have the endpoint.\n if (orgId && projectId) {\n try {\n const environment = await fetchProjectEnvironmentByApiKey({\n apiKey,\n orgId,\n projectId\n });\n\n return WcpEnvironmentModel.fromDto(environment);\n } catch {\n // Fall through to GraphQL.\n }\n }\n\n return WcpGqlClient.execute<IGetEnvironmentResponse>(GET_ENVIRONMENT, { apiKey })\n .then(response => WcpEnvironmentModel.fromDto(response.projects.getEnvironment))\n .catch(() => {\n throw new Error(\n `It seems the API key you provided is incorrect or disabled. Please double check the API key and try again.`\n );\n });\n }\n\n const pat = localStorageService.get(\"wcpPat\");\n if (!pat) {\n throw new Error(\n `It seems you are not logged in. Please login using the \"webiny login\" command.`\n );\n }\n\n const headers = { authorization: pat };\n return WcpGqlClient.execute<IGetEnvironmentResponse>(\n GET_ENVIRONMENT,\n {\n orgId,\n projectId,\n userId,\n environmentId,\n apiKey\n },\n headers\n )\n .then(async response => WcpEnvironmentModel.fromDto(response.projects.getEnvironment))\n .catch(() => {\n return WcpGqlClient.execute<ICreateEnvironmentParams>(\n CREATE_ENVIRONMENT,\n {\n orgId,\n projectId,\n userId,\n data: {\n name: environmentId\n }\n },\n headers\n ).then(response => response.projects.createEnvironment);\n });\n }\n}\n"],"names":["ENVIRONMENT_FIELDS","CREATE_ENVIRONMENT","GET_ENVIRONMENT","GetProjectEnvironment","di","params","localStorageService","orgId","projectId","userId","environmentId","apiKey","environment","fetchProjectEnvironmentByApiKey","WcpEnvironmentModel","WcpGqlClient","response","Error","pat","headers"],"mappings":";;;AAOA,MAAMA,qBAAmC,CAAC;;;;;;;;;;;;;;;;;;;AAmB1C,CAAC;AAED,MAAMC,qBAAmC,CAAC;IACtC,EAAED,mBAAmB;;;;;;;;;;;;;AAazB,CAAC;AAQD,MAAME,kBAAgC,CAAC;IACnC,EAAEF,mBAAmB;;;;;;;;;;;;;;;;;;;;AAoBzB,CAAC;AAYM,MAAMG;IAGT,YAAYC,EAA4B,CAAE;QACtC,IAAI,CAAC,EAAE,GAAGA;IACd;IAEA,MAAM,QAAQC,MAAoC,EAAgC;QAC9E,MAAM,EAAEC,mBAAmB,EAAE,GAAG,IAAI,CAAC,EAAE;QACvC,MAAM,EAAEC,KAAK,EAAEC,SAAS,EAAEC,MAAM,EAAEC,aAAa,EAAEC,MAAM,EAAE,GAAGN;QAE5D,IAAIM,QAAQ;YAKR,IAAIJ,SAASC,WACT,IAAI;gBACA,MAAMI,cAAc,MAAMC,gCAAgC;oBACtDF;oBACAJ;oBACAC;gBACJ;gBAEA,OAAOM,oBAAoB,OAAO,CAACF;YACvC,EAAE,OAAM,CAER;YAGJ,OAAOG,aAAa,OAAO,CAA0Bb,iBAAiB;gBAAES;YAAO,GAC1E,IAAI,CAACK,CAAAA,WAAYF,oBAAoB,OAAO,CAACE,SAAS,QAAQ,CAAC,cAAc,GAC7E,KAAK,CAAC;gBACH,MAAM,IAAIC,MACN;YAER;QACR;QAEA,MAAMC,MAAMZ,oBAAoB,GAAG,CAAC;QACpC,IAAI,CAACY,KACD,MAAM,IAAID,MACN;QAIR,MAAME,UAAU;YAAE,eAAeD;QAAI;QACrC,OAAOH,aAAa,OAAO,CACvBb,iBACA;YACIK;YACAC;YACAC;YACAC;YACAC;QACJ,GACAQ,SAEC,IAAI,CAAC,OAAMH,WAAYF,oBAAoB,OAAO,CAACE,SAAS,QAAQ,CAAC,cAAc,GACnF,KAAK,CAAC,IACID,aAAa,OAAO,CACvBd,oBACA;gBACIM;gBACAC;gBACAC;gBACA,MAAM;oBACF,MAAMC;gBACV;YACJ,GACAS,SACF,IAAI,CAACH,CAAAA,WAAYA,SAAS,QAAQ,CAAC,iBAAiB;IAElE;AACJ"}
@@ -0,0 +1,8 @@
1
+ import { type IWcpEnvironmentDto } from "../../abstractions/models/index.js";
2
+ interface FetchProjectEnvironmentByApiKeyParams {
3
+ apiKey: string;
4
+ orgId: string;
5
+ projectId: string;
6
+ }
7
+ export declare const fetchProjectEnvironmentByApiKey: (params: FetchProjectEnvironmentByApiKeyParams) => Promise<IWcpEnvironmentDto>;
8
+ export {};
@@ -0,0 +1,21 @@
1
+ import { getWcpApiUrl } from "@webiny/wcp";
2
+ const TIMEOUT_MS = 10000;
3
+ const fetchProjectEnvironmentByApiKey = async (params)=>{
4
+ const { apiKey, orgId, projectId } = params;
5
+ const orgPath = encodeURIComponent(orgId);
6
+ const projectPath = encodeURIComponent(projectId);
7
+ const url = getWcpApiUrl(`/orgs/${orgPath}/projects/${projectPath}/environment`);
8
+ const response = await fetch(url, {
9
+ headers: {
10
+ authorization: apiKey
11
+ },
12
+ signal: AbortSignal.timeout(TIMEOUT_MS)
13
+ });
14
+ if (!response.ok) throw new Error(`WCP returned ${response.status} for the project environment.`);
15
+ const body = await response.json();
16
+ if (!body.environment) throw new Error("WCP returned no project environment.");
17
+ return body.environment;
18
+ };
19
+ export { fetchProjectEnvironmentByApiKey };
20
+
21
+ //# sourceMappingURL=fetchProjectEnvironmentByApiKey.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"services/WcpService/fetchProjectEnvironmentByApiKey.js","sources":["../../../src/services/WcpService/fetchProjectEnvironmentByApiKey.ts"],"sourcesContent":["import { getWcpApiUrl } from \"@webiny/wcp\";\nimport { type IWcpEnvironmentDto } from \"~/abstractions/models/index.js\";\n\n// Long enough for a cold start behind a cache miss (about 2s), short enough that a stuck request\n// still leaves time to fall back to the GraphQL query.\nconst TIMEOUT_MS = 10_000;\n\ninterface FetchProjectEnvironmentByApiKeyParams {\n apiKey: string;\n orgId: string;\n projectId: string;\n}\n\n/*\n * Looks up a project environment through WCP's REST endpoint rather than its GraphQL API.\n *\n * The CLI does this on every command, and a GraphQL POST can never be cached, so it was a full round\n * trip to WCP every time: about 500ms. This endpoint is a GET that CloudFront caches per API key,\n * so a repeat lookup comes back from the edge in tens of milliseconds. It returns the same fields as\n * the GraphQL query.\n *\n * Throws on anything other than a successful response, including a disabled environment, a key\n * from another project, or a WCP without this route. Callers fall back to the GraphQL query, which\n * reports those cases the way it always has.\n */\nexport const fetchProjectEnvironmentByApiKey = async (\n params: FetchProjectEnvironmentByApiKeyParams\n): Promise<IWcpEnvironmentDto> => {\n const { apiKey, orgId, projectId } = params;\n\n const orgPath = encodeURIComponent(orgId);\n const projectPath = encodeURIComponent(projectId);\n const url = getWcpApiUrl(`/orgs/${orgPath}/projects/${projectPath}/environment`);\n\n const response = await fetch(url, {\n headers: { authorization: apiKey },\n signal: AbortSignal.timeout(TIMEOUT_MS)\n });\n\n if (!response.ok) {\n throw new Error(`WCP returned ${response.status} for the project environment.`);\n }\n\n const body: { environment?: IWcpEnvironmentDto } = await response.json();\n if (!body.environment) {\n throw new Error(\"WCP returned no project environment.\");\n }\n\n return body.environment;\n};\n"],"names":["TIMEOUT_MS","fetchProjectEnvironmentByApiKey","params","apiKey","orgId","projectId","orgPath","encodeURIComponent","projectPath","url","getWcpApiUrl","response","fetch","AbortSignal","Error","body"],"mappings":";AAKA,MAAMA,aAAa;AAoBZ,MAAMC,kCAAkC,OAC3CC;IAEA,MAAM,EAAEC,MAAM,EAAEC,KAAK,EAAEC,SAAS,EAAE,GAAGH;IAErC,MAAMI,UAAUC,mBAAmBH;IACnC,MAAMI,cAAcD,mBAAmBF;IACvC,MAAMI,MAAMC,aAAa,CAAC,MAAM,EAAEJ,QAAQ,UAAU,EAAEE,YAAY,YAAY,CAAC;IAE/E,MAAMG,WAAW,MAAMC,MAAMH,KAAK;QAC9B,SAAS;YAAE,eAAeN;QAAO;QACjC,QAAQU,YAAY,OAAO,CAACb;IAChC;IAEA,IAAI,CAACW,SAAS,EAAE,EACZ,MAAM,IAAIG,MAAM,CAAC,aAAa,EAAEH,SAAS,MAAM,CAAC,6BAA6B,CAAC;IAGlF,MAAMI,OAA6C,MAAMJ,SAAS,IAAI;IACtE,IAAI,CAACI,KAAK,WAAW,EACjB,MAAM,IAAID,MAAM;IAGpB,OAAOC,KAAK,WAAW;AAC3B"}
package/utils/index.d.ts CHANGED
@@ -9,5 +9,6 @@ export * from "./isValidVariantName.js";
9
9
  export * from "./measureDuration.js";
10
10
  export * from "./requireConfig.js";
11
11
  export * from "./toImportSpecifier.js";
12
+ export * from "./trace/index.js";
12
13
  export * from "./projectSdkContext.js";
13
14
  export * from "./registerExtension.js";
package/utils/index.js CHANGED
@@ -9,5 +9,6 @@ export * from "./isValidVariantName.js";
9
9
  export * from "./measureDuration.js";
10
10
  export * from "./requireConfig.js";
11
11
  export * from "./toImportSpecifier.js";
12
+ export * from "./trace/index.js";
12
13
  export * from "./projectSdkContext.js";
13
14
  export * from "./registerExtension.js";
@@ -0,0 +1,17 @@
1
+ export interface ITraceEntry {
2
+ label: string;
3
+ start: number;
4
+ end: number;
5
+ unfinished?: boolean;
6
+ }
7
+ export declare class TraceRecorder {
8
+ private readonly entries;
9
+ private isEnabled;
10
+ processLabel: string;
11
+ get enabled(): boolean;
12
+ enable(): void;
13
+ start(label: string): () => void;
14
+ record(label: string, start: number, end: number): void;
15
+ getEntries(): ITraceEntry[];
16
+ }
17
+ export declare const traceRecorder: TraceRecorder;
@@ -0,0 +1,51 @@
1
+ class TraceRecorder {
2
+ get enabled() {
3
+ return this.isEnabled;
4
+ }
5
+ enable() {
6
+ this.isEnabled = true;
7
+ process.env.WEBINY_CLI_TRACE = "1";
8
+ }
9
+ start(label) {
10
+ if (!this.isEnabled) return ()=>{};
11
+ const entry = {
12
+ label,
13
+ start: performance.now(),
14
+ end: 0 / 0
15
+ };
16
+ this.entries.push(entry);
17
+ return ()=>{
18
+ entry.end = performance.now();
19
+ };
20
+ }
21
+ record(label, start, end) {
22
+ if (!this.isEnabled) return;
23
+ this.entries.push({
24
+ label,
25
+ start,
26
+ end
27
+ });
28
+ }
29
+ getEntries() {
30
+ const now = performance.now();
31
+ const entries = this.entries.map((entry)=>{
32
+ if (!Number.isNaN(entry.end)) return entry;
33
+ return {
34
+ ...entry,
35
+ end: now,
36
+ unfinished: true
37
+ };
38
+ });
39
+ entries.sort((a, b)=>a.start - b.start);
40
+ return entries;
41
+ }
42
+ constructor(){
43
+ this.entries = [];
44
+ this.isEnabled = "1" === process.env.WEBINY_CLI_TRACE;
45
+ this.processLabel = "Webiny CLI";
46
+ }
47
+ }
48
+ const traceRecorder = new TraceRecorder();
49
+ export { TraceRecorder, traceRecorder };
50
+
51
+ //# sourceMappingURL=TraceRecorder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils/trace/TraceRecorder.js","sources":["../../../src/utils/trace/TraceRecorder.ts"],"sourcesContent":["export interface ITraceEntry {\n label: string;\n /* Milliseconds since this process started. */\n start: number;\n end: number;\n /* True when the process exited before the phase closed. `webiny --version` does this. */\n unfinished?: boolean;\n}\n\n/*\n * Collects the durations of named phases within a single process, so the CLI can print a timeline of\n * where a run spent its time. Timestamps are relative to process start, which means the report can\n * also account for the time spent before the first line of code ran (loading the module graph).\n *\n * Recording is off unless `WEBINY_CLI_TRACE` is set, and the `trace` helpers short-circuit when it is\n * off, so leaving the instrumentation in place costs a boolean check per phase.\n */\nexport class TraceRecorder {\n private readonly entries: ITraceEntry[] = [];\n\n private isEnabled: boolean = process.env.WEBINY_CLI_TRACE === \"1\";\n\n /* Distinguishes the reports of the main process and of the forked config render worker. */\n public processLabel = \"Webiny CLI\";\n\n public get enabled() {\n return this.isEnabled;\n }\n\n /*\n * Turns tracing on for the rest of the run. The environment variable is set as well, so that the\n * forked config render worker inherits it and reports its own timings.\n */\n public enable() {\n this.isEnabled = true;\n process.env.WEBINY_CLI_TRACE = \"1\";\n }\n\n /* Starts a phase and returns the function that closes it. */\n public start(label: string) {\n if (!this.isEnabled) {\n return () => {\n return;\n };\n }\n\n const entry: ITraceEntry = { label, start: performance.now(), end: NaN };\n this.entries.push(entry);\n\n return () => {\n entry.end = performance.now();\n };\n }\n\n /*\n * Records a phase that already finished. Used for time spent before tracing was installed, and\n * for phases whose label is only known once they are done.\n */\n public record(label: string, start: number, end: number) {\n if (!this.isEnabled) {\n return;\n }\n\n this.entries.push({ label, start, end });\n }\n\n /*\n * Phases still open when the report is built are closed at `now` and flagged. This happens on any\n * command that exits the process from inside its handler, `webiny --version` being the obvious one.\n */\n public getEntries(): ITraceEntry[] {\n const now = performance.now();\n\n const entries = this.entries.map(entry => {\n if (!Number.isNaN(entry.end)) {\n return entry;\n }\n\n return { ...entry, end: now, unfinished: true };\n });\n\n entries.sort((a, b) => a.start - b.start);\n\n return entries;\n }\n}\n\n/*\n * One recorder per process. The config render runs in a forked child process, which gets a recorder\n * and a report of its own. Kept next to the class because macOS filesystems are case-insensitive, so\n * a `traceRecorder.ts` module would collide with this file.\n */\nexport const traceRecorder = new TraceRecorder();\n"],"names":["TraceRecorder","process","label","entry","performance","NaN","start","end","now","entries","Number","a","b","traceRecorder"],"mappings":"AAiBO,MAAMA;IAQT,IAAW,UAAU;QACjB,OAAO,IAAI,CAAC,SAAS;IACzB;IAMO,SAAS;QACZ,IAAI,CAAC,SAAS,GAAG;QACjBC,QAAQ,GAAG,CAAC,gBAAgB,GAAG;IACnC;IAGO,MAAMC,KAAa,EAAE;QACxB,IAAI,CAAC,IAAI,CAAC,SAAS,EACf,OAAO,KAEP;QAGJ,MAAMC,QAAqB;YAAED;YAAO,OAAOE,YAAY,GAAG;YAAI,KAAKC,KAAG;QAAC;QACvE,IAAI,CAAC,OAAO,CAAC,IAAI,CAACF;QAElB,OAAO;YACHA,MAAM,GAAG,GAAGC,YAAY,GAAG;QAC/B;IACJ;IAMO,OAAOF,KAAa,EAAEI,KAAa,EAAEC,GAAW,EAAE;QACrD,IAAI,CAAC,IAAI,CAAC,SAAS,EACf;QAGJ,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;YAAEL;YAAOI;YAAOC;QAAI;IAC1C;IAMO,aAA4B;QAC/B,MAAMC,MAAMJ,YAAY,GAAG;QAE3B,MAAMK,UAAU,IAAI,CAAC,OAAO,CAAC,GAAG,CAACN,CAAAA;YAC7B,IAAI,CAACO,OAAO,KAAK,CAACP,MAAM,GAAG,GACvB,OAAOA;YAGX,OAAO;gBAAE,GAAGA,KAAK;gBAAE,KAAKK;gBAAK,YAAY;YAAK;QAClD;QAEAC,QAAQ,IAAI,CAAC,CAACE,GAAGC,IAAMD,EAAE,KAAK,GAAGC,EAAE,KAAK;QAExC,OAAOH;IACX;;aAlEiB,OAAO,GAAkB,EAAE;aAEpC,SAAS,GAAYR,AAAiC,QAAjCA,QAAQ,GAAG,CAAC,gBAAgB;QAEgC,KAClF,YAAY,GAAG;;AA8D1B;AAOO,MAAMY,gBAAgB,IAAIb"}
@@ -0,0 +1,2 @@
1
+ import { type ITraceEntry } from "./TraceRecorder.js";
2
+ export declare const formatTraceReport: (processLabel: string, entries: ITraceEntry[], total: number) => string;
@@ -0,0 +1,53 @@
1
+ const toNestedNodes = (entries)=>{
2
+ const nodes = [];
3
+ const open = [];
4
+ for (const entry of entries){
5
+ while(open.length > 0 && open[open.length - 1].end < entry.end)open.pop();
6
+ nodes.push({
7
+ entry,
8
+ depth: open.length
9
+ });
10
+ open.push(entry);
11
+ }
12
+ return nodes;
13
+ };
14
+ const isWorthPrinting = (node, index, nodes)=>{
15
+ const duration = node.entry.end - node.entry.start;
16
+ if (Math.round(duration) > 0) return true;
17
+ const next = nodes[index + 1];
18
+ return void 0 !== next && next.depth > node.depth;
19
+ };
20
+ const formatRow = (label, duration, total, depth)=>{
21
+ const ms = `${Math.round(duration)} ms`.padStart(9);
22
+ const share = `${(duration / total * 100).toFixed(1)}%`.padStart(7);
23
+ const indent = " ".repeat(depth);
24
+ return `${ms} ${share} ${indent}${label}`;
25
+ };
26
+ const formatTraceReport = (processLabel, entries, total)=>{
27
+ if (0 === entries.length) return `${processLabel} trace: nothing was recorded.`;
28
+ const nodes = toNestedNodes(entries);
29
+ const printableNodes = nodes.filter(isWorthPrinting);
30
+ const hiddenCount = nodes.length - printableNodes.length;
31
+ const lines = [
32
+ `${processLabel} trace: ${Math.round(total)} ms total`,
33
+ ""
34
+ ];
35
+ for (const { entry, depth } of printableNodes){
36
+ const duration = entry.end - entry.start;
37
+ let label = entry.label;
38
+ if (entry.unfinished) label = `${label} (still running at exit)`;
39
+ lines.push(formatRow(label, duration, total, depth));
40
+ }
41
+ const topLevelNodes = nodes.filter((node)=>0 === node.depth);
42
+ const tracedTotal = topLevelNodes.reduce((sum, node)=>sum + (node.entry.end - node.entry.start), 0);
43
+ const untraced = total - tracedTotal;
44
+ if (untraced > 1) lines.push(formatRow("(untraced)", untraced, total, 0));
45
+ if (hiddenCount > 0) {
46
+ lines.push("");
47
+ lines.push(`${hiddenCount} phase(s) took under a millisecond and are not listed.`);
48
+ }
49
+ return lines.join("\n");
50
+ };
51
+ export { formatTraceReport };
52
+
53
+ //# sourceMappingURL=formatTraceReport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils/trace/formatTraceReport.js","sources":["../../../src/utils/trace/formatTraceReport.ts"],"sourcesContent":["import { type ITraceEntry } from \"./TraceRecorder.js\";\n\ninterface ITraceNode {\n entry: ITraceEntry;\n depth: number;\n}\n\n/*\n * Phases are recorded flat, but they nest in practice (initializing the CLI contains rendering the\n * project config, which contains the child process fork). Rebuild the nesting from the timestamps: a\n * phase is a child of the closest still-open phase that fully contains it.\n */\nconst toNestedNodes = (entries: ITraceEntry[]): ITraceNode[] => {\n const nodes: ITraceNode[] = [];\n const open: ITraceEntry[] = [];\n\n for (const entry of entries) {\n while (open.length > 0 && open[open.length - 1].end < entry.end) {\n open.pop();\n }\n\n nodes.push({ entry, depth: open.length });\n open.push(entry);\n }\n\n return nodes;\n};\n\n/*\n * A run records a lot of phases that turn out to be instant: every command definition, every\n * extension type. Dropping the ones that round to zero and contain nothing keeps the report to the\n * handful of rows worth reading; a hidden phase is by definition not the bottleneck.\n *\n * The test is deliberately `Math.round`, matching how `formatRow` prints the duration, so that the\n * rows kept are exactly the rows that would show a non-zero figure. Comparing the raw duration\n * against 1 instead would hide a 0.6 ms phase that the report would have rendered as \"1 ms\".\n */\nconst isWorthPrinting = (node: ITraceNode, index: number, nodes: ITraceNode[]) => {\n const duration = node.entry.end - node.entry.start;\n if (Math.round(duration) > 0) {\n return true;\n }\n\n const next = nodes[index + 1];\n\n return next !== undefined && next.depth > node.depth;\n};\n\nconst formatRow = (label: string, duration: number, total: number, depth: number) => {\n const ms = `${Math.round(duration)} ms`.padStart(9);\n const share = `${((duration / total) * 100).toFixed(1)}%`.padStart(7);\n const indent = \" \".repeat(depth);\n\n return `${ms} ${share} ${indent}${label}`;\n};\n\nexport const formatTraceReport = (\n processLabel: string,\n entries: ITraceEntry[],\n total: number\n): string => {\n if (entries.length === 0) {\n return `${processLabel} trace: nothing was recorded.`;\n }\n\n const nodes = toNestedNodes(entries);\n const printableNodes = nodes.filter(isWorthPrinting);\n const hiddenCount = nodes.length - printableNodes.length;\n\n const lines = [`${processLabel} trace: ${Math.round(total)} ms total`, \"\"];\n\n for (const { entry, depth } of printableNodes) {\n const duration = entry.end - entry.start;\n let label = entry.label;\n if (entry.unfinished) {\n label = `${label} (still running at exit)`;\n }\n\n lines.push(formatRow(label, duration, total, depth));\n }\n\n const topLevelNodes = nodes.filter(node => node.depth === 0);\n const tracedTotal = topLevelNodes.reduce((sum, node) => {\n return sum + (node.entry.end - node.entry.start);\n }, 0);\n\n const untraced = total - tracedTotal;\n if (untraced > 1) {\n lines.push(formatRow(\"(untraced)\", untraced, total, 0));\n }\n\n if (hiddenCount > 0) {\n lines.push(\"\");\n lines.push(`${hiddenCount} phase(s) took under a millisecond and are not listed.`);\n }\n\n return lines.join(\"\\n\");\n};\n"],"names":["toNestedNodes","entries","nodes","open","entry","isWorthPrinting","node","index","duration","Math","next","undefined","formatRow","label","total","depth","ms","share","indent","formatTraceReport","processLabel","printableNodes","hiddenCount","lines","topLevelNodes","tracedTotal","sum","untraced"],"mappings":"AAYA,MAAMA,gBAAgB,CAACC;IACnB,MAAMC,QAAsB,EAAE;IAC9B,MAAMC,OAAsB,EAAE;IAE9B,KAAK,MAAMC,SAASH,QAAS;QACzB,MAAOE,KAAK,MAAM,GAAG,KAAKA,IAAI,CAACA,KAAK,MAAM,GAAG,EAAE,CAAC,GAAG,GAAGC,MAAM,GAAG,CAC3DD,KAAK,GAAG;QAGZD,MAAM,IAAI,CAAC;YAAEE;YAAO,OAAOD,KAAK,MAAM;QAAC;QACvCA,KAAK,IAAI,CAACC;IACd;IAEA,OAAOF;AACX;AAWA,MAAMG,kBAAkB,CAACC,MAAkBC,OAAeL;IACtD,MAAMM,WAAWF,KAAK,KAAK,CAAC,GAAG,GAAGA,KAAK,KAAK,CAAC,KAAK;IAClD,IAAIG,KAAK,KAAK,CAACD,YAAY,GACvB,OAAO;IAGX,MAAME,OAAOR,KAAK,CAACK,QAAQ,EAAE;IAE7B,OAAOG,AAASC,WAATD,QAAsBA,KAAK,KAAK,GAAGJ,KAAK,KAAK;AACxD;AAEA,MAAMM,YAAY,CAACC,OAAeL,UAAkBM,OAAeC;IAC/D,MAAMC,KAAK,GAAGP,KAAK,KAAK,CAACD,UAAU,GAAG,CAAC,CAAC,QAAQ,CAAC;IACjD,MAAMS,QAAQ,GAAI,AAACT,CAAAA,WAAWM,QAAS,GAAE,EAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC;IACnE,MAAMI,SAAS,KAAK,MAAM,CAACH;IAE3B,OAAO,GAAGC,GAAG,EAAE,EAAEC,MAAM,GAAG,EAAEC,SAASL,OAAO;AAChD;AAEO,MAAMM,oBAAoB,CAC7BC,cACAnB,SACAa;IAEA,IAAIb,AAAmB,MAAnBA,QAAQ,MAAM,EACd,OAAO,GAAGmB,aAAa,6BAA6B,CAAC;IAGzD,MAAMlB,QAAQF,cAAcC;IAC5B,MAAMoB,iBAAiBnB,MAAM,MAAM,CAACG;IACpC,MAAMiB,cAAcpB,MAAM,MAAM,GAAGmB,eAAe,MAAM;IAExD,MAAME,QAAQ;QAAC,GAAGH,aAAa,QAAQ,EAAEX,KAAK,KAAK,CAACK,OAAO,SAAS,CAAC;QAAE;KAAG;IAE1E,KAAK,MAAM,EAAEV,KAAK,EAAEW,KAAK,EAAE,IAAIM,eAAgB;QAC3C,MAAMb,WAAWJ,MAAM,GAAG,GAAGA,MAAM,KAAK;QACxC,IAAIS,QAAQT,MAAM,KAAK;QACvB,IAAIA,MAAM,UAAU,EAChBS,QAAQ,GAAGA,MAAM,wBAAwB,CAAC;QAG9CU,MAAM,IAAI,CAACX,UAAUC,OAAOL,UAAUM,OAAOC;IACjD;IAEA,MAAMS,gBAAgBtB,MAAM,MAAM,CAACI,CAAAA,OAAQA,AAAe,MAAfA,KAAK,KAAK;IACrD,MAAMmB,cAAcD,cAAc,MAAM,CAAC,CAACE,KAAKpB,OACpCoB,MAAOpB,CAAAA,KAAK,KAAK,CAAC,GAAG,GAAGA,KAAK,KAAK,CAAC,KAAI,GAC/C;IAEH,MAAMqB,WAAWb,QAAQW;IACzB,IAAIE,WAAW,GACXJ,MAAM,IAAI,CAACX,UAAU,cAAce,UAAUb,OAAO;IAGxD,IAAIQ,cAAc,GAAG;QACjBC,MAAM,IAAI,CAAC;QACXA,MAAM,IAAI,CAAC,GAAGD,YAAY,sDAAsD,CAAC;IACrF;IAEA,OAAOC,MAAM,IAAI,CAAC;AACtB"}
@@ -0,0 +1,6 @@
1
+ export * from "./TraceRecorder.js";
2
+ export * from "./formatTraceReport.js";
3
+ export * from "./isTraceRequested.js";
4
+ export * from "./startTrace.js";
5
+ export * from "./trace.js";
6
+ export * from "./traceAsync.js";
@@ -0,0 +1,6 @@
1
+ export * from "./TraceRecorder.js";
2
+ export * from "./formatTraceReport.js";
3
+ export * from "./isTraceRequested.js";
4
+ export * from "./startTrace.js";
5
+ export * from "./trace.js";
6
+ export * from "./traceAsync.js";
@@ -0,0 +1 @@
1
+ export declare const isTraceRequested: (argv: string[]) => boolean;
@@ -0,0 +1,12 @@
1
+ const TRACE_FLAG = "--trace";
2
+ const TRACE_FLAG_ASSIGNMENT = `${TRACE_FLAG}=`;
3
+ const isTraceRequested = (argv)=>{
4
+ const index = argv.findIndex((arg)=>arg === TRACE_FLAG || arg.startsWith(TRACE_FLAG_ASSIGNMENT));
5
+ if (-1 === index) return false;
6
+ const flag = argv[index];
7
+ if (flag.startsWith(TRACE_FLAG_ASSIGNMENT)) return flag !== `${TRACE_FLAG_ASSIGNMENT}false`;
8
+ return "false" !== argv[index + 1];
9
+ };
10
+ export { isTraceRequested };
11
+
12
+ //# sourceMappingURL=isTraceRequested.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils/trace/isTraceRequested.js","sources":["../../../src/utils/trace/isTraceRequested.ts"],"sourcesContent":["const TRACE_FLAG = \"--trace\";\nconst TRACE_FLAG_ASSIGNMENT = `${TRACE_FLAG}=`;\n\n/*\n * Reads the `--trace` flag straight out of `process.argv`, because tracing has to be decided before\n * yargs exists: the phase it is most needed for is the module load that already happened by the time\n * the CLI entrypoint runs its first statement.\n *\n * That means matching what yargs would have concluded for a boolean option. It accepts a bare\n * `--trace`, the assignment form `--trace=true`, and a separated value `--trace false`, so all three\n * have to mean the same thing here as they do in `webiny --help`.\n */\nexport const isTraceRequested = (argv: string[]): boolean => {\n const index = argv.findIndex(arg => {\n return arg === TRACE_FLAG || arg.startsWith(TRACE_FLAG_ASSIGNMENT);\n });\n\n if (index === -1) {\n return false;\n }\n\n const flag = argv[index];\n if (flag.startsWith(TRACE_FLAG_ASSIGNMENT)) {\n return flag !== `${TRACE_FLAG_ASSIGNMENT}false`;\n }\n\n return argv[index + 1] !== \"false\";\n};\n"],"names":["TRACE_FLAG","TRACE_FLAG_ASSIGNMENT","isTraceRequested","argv","index","arg","flag"],"mappings":"AAAA,MAAMA,aAAa;AACnB,MAAMC,wBAAwB,GAAGD,WAAW,CAAC,CAAC;AAWvC,MAAME,mBAAmB,CAACC;IAC7B,MAAMC,QAAQD,KAAK,SAAS,CAACE,CAAAA,MAClBA,QAAQL,cAAcK,IAAI,UAAU,CAACJ;IAGhD,IAAIG,AAAU,OAAVA,OACA,OAAO;IAGX,MAAME,OAAOH,IAAI,CAACC,MAAM;IACxB,IAAIE,KAAK,UAAU,CAACL,wBAChB,OAAOK,SAAS,GAAGL,sBAAsB,KAAK,CAAC;IAGnD,OAAOE,AAAoB,YAApBA,IAAI,CAACC,QAAQ,EAAE;AAC1B"}
@@ -0,0 +1 @@
1
+ export declare const startTrace: (processLabel: string) => void;
@@ -0,0 +1,19 @@
1
+ import fs from "fs";
2
+ import { traceRecorder } from "./TraceRecorder.js";
3
+ import { formatTraceReport } from "./formatTraceReport.js";
4
+ import { isTraceRequested } from "./isTraceRequested.js";
5
+ const startTrace = (processLabel)=>{
6
+ const requestedViaArgv = isTraceRequested(process.argv);
7
+ if (requestedViaArgv) traceRecorder.enable();
8
+ if (!traceRecorder.enabled) return;
9
+ traceRecorder.processLabel = processLabel;
10
+ traceRecorder.record("load modules", 0, performance.now());
11
+ process.on("exit", ()=>{
12
+ const entries = traceRecorder.getEntries();
13
+ const report = formatTraceReport(processLabel, entries, performance.now());
14
+ fs.writeSync(2, `\n${report}\n\n`);
15
+ });
16
+ };
17
+ export { startTrace };
18
+
19
+ //# sourceMappingURL=startTrace.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils/trace/startTrace.js","sources":["../../../src/utils/trace/startTrace.ts"],"sourcesContent":["import fs from \"fs\";\nimport { traceRecorder } from \"./TraceRecorder.js\";\nimport { formatTraceReport } from \"./formatTraceReport.js\";\nimport { isTraceRequested } from \"./isTraceRequested.js\";\n\n/*\n * Call this as the very first statement of a CLI entrypoint. Everything that ran before it is\n * recorded as a single \"load modules\" phase: Node booting, then evaluating the entrypoint's import\n * graph. That phase is usually the largest one.\n *\n * None of this goes through `LoggerService`, and it is worth saying why, because that is the obvious\n * question. The logger needs `GetProjectService` and `ProjectSdkParamsService`, so it only exists\n * once the project SDK container has been built, and building that container is roughly two thirds\n * of what we are trying to measure. The phases before it (loading modules, the preflight checks) run\n * in `bin.ts` where there is no container at all, and the config render worker is a separate process\n * with no container either. Writing straight to stderr is also what lets the report survive an `exit`\n * handler, and keeping it off stdout means it can never corrupt the output of a piped command.\n */\nexport const startTrace = (processLabel: string) => {\n const requestedViaArgv = isTraceRequested(process.argv);\n if (requestedViaArgv) {\n traceRecorder.enable();\n }\n\n if (!traceRecorder.enabled) {\n return;\n }\n\n traceRecorder.processLabel = processLabel;\n traceRecorder.record(\"load modules\", 0, performance.now());\n\n process.on(\"exit\", () => {\n const entries = traceRecorder.getEntries();\n const report = formatTraceReport(processLabel, entries, performance.now());\n\n // `fs.writeSync` rather than `process.stderr.write`: when stderr is a pipe, which it is for\n // the forked render worker, a buffered write is dropped if the process exits first.\n fs.writeSync(2, `\\n${report}\\n\\n`);\n });\n};\n"],"names":["startTrace","processLabel","requestedViaArgv","isTraceRequested","process","traceRecorder","performance","entries","report","formatTraceReport","fs"],"mappings":";;;;AAkBO,MAAMA,aAAa,CAACC;IACvB,MAAMC,mBAAmBC,iBAAiBC,QAAQ,IAAI;IACtD,IAAIF,kBACAG,cAAc,MAAM;IAGxB,IAAI,CAACA,cAAc,OAAO,EACtB;IAGJA,cAAc,YAAY,GAAGJ;IAC7BI,cAAc,MAAM,CAAC,gBAAgB,GAAGC,YAAY,GAAG;IAEvDF,QAAQ,EAAE,CAAC,QAAQ;QACf,MAAMG,UAAUF,cAAc,UAAU;QACxC,MAAMG,SAASC,kBAAkBR,cAAcM,SAASD,YAAY,GAAG;QAIvEI,GAAG,SAAS,CAAC,GAAG,CAAC,EAAE,EAAEF,OAAO,IAAI,CAAC;IACrC;AACJ"}
@@ -0,0 +1 @@
1
+ export declare function trace<T>(label: string, fn: () => T): T;
@@ -0,0 +1,13 @@
1
+ import { traceRecorder } from "./TraceRecorder.js";
2
+ function trace(label, fn) {
3
+ if (!traceRecorder.enabled) return fn();
4
+ const stop = traceRecorder.start(label);
5
+ try {
6
+ return fn();
7
+ } finally{
8
+ stop();
9
+ }
10
+ }
11
+ export { trace };
12
+
13
+ //# sourceMappingURL=trace.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils/trace/trace.js","sources":["../../../src/utils/trace/trace.ts"],"sourcesContent":["import { traceRecorder } from \"./TraceRecorder.js\";\n\n/* Times a synchronous phase of a CLI run. A no-op unless `WEBINY_CLI_TRACE` is set. */\nexport function trace<T>(label: string, fn: () => T): T {\n if (!traceRecorder.enabled) {\n return fn();\n }\n\n const stop = traceRecorder.start(label);\n\n try {\n return fn();\n } finally {\n stop();\n }\n}\n"],"names":["trace","label","fn","traceRecorder","stop"],"mappings":";AAGO,SAASA,MAASC,KAAa,EAAEC,EAAW;IAC/C,IAAI,CAACC,cAAc,OAAO,EACtB,OAAOD;IAGX,MAAME,OAAOD,cAAc,KAAK,CAACF;IAEjC,IAAI;QACA,OAAOC;IACX,SAAU;QACNE;IACJ;AACJ"}
@@ -0,0 +1 @@
1
+ export declare function traceAsync<T>(label: string, fn: () => Promise<T>): Promise<T>;
@@ -0,0 +1,13 @@
1
+ import { traceRecorder } from "./TraceRecorder.js";
2
+ async function traceAsync(label, fn) {
3
+ if (!traceRecorder.enabled) return fn();
4
+ const stop = traceRecorder.start(label);
5
+ try {
6
+ return await fn();
7
+ } finally{
8
+ stop();
9
+ }
10
+ }
11
+ export { traceAsync };
12
+
13
+ //# sourceMappingURL=traceAsync.js.map