@webiny/project 6.6.0-alpha.11 → 6.6.0-alpha.12

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.
@@ -2,9 +2,11 @@ import { z } from "zod";
2
2
  /**
3
3
  * Sets a dedicated WebSocket URL for the Admin app, baked into the admin bundle as
4
4
  * `WEBINY_ADMIN_WS_API_URL`. This is optional: when omitted, the admin derives the WebSocket URL
5
- * from the API URL (same origin, http -> ws), which is what the standalone hosting type needs by
6
- * default. Set it only when WebSockets are served from a different origin than the API. Because the
7
- * config is evaluated at build time, the value can come from any env var the user chooses, e.g.
5
+ * from the API URL (same origin, http -> ws, plus the `/ws` path the standalone server takes
6
+ * upgrades on), which is what the standalone hosting type needs by default. Set it only when that
7
+ * derivation lands in the wrong place: WebSockets on a different origin, or a proxy that rewrites
8
+ * the path. The value is the full socket URL and is used as is. Because the config is evaluated at
9
+ * build time, the value can come from any env var the user chooses, e.g.
8
10
  * `<Admin.WebsocketsUrl url={process.env.MY_WS_URL} />`.
9
11
  */
10
12
  export declare const AdminWebsocketsUrl: import("~/defineExtension/index.js").ExtensionComponent<z.ZodObject<{
@@ -10,7 +10,7 @@ const AdminWebsocketsUrl = defineExtension({
10
10
  },
11
11
  description: "Set a dedicated WebSocket URL for the Admin app.",
12
12
  paramsSchema: z.object({
13
- url: z.string().describe("The WebSocket origin, e.g. wss://ws.example.com or ws://localhost:3002")
13
+ url: z.string().describe("The full WebSocket URL, e.g. wss://ws.example.com/ws or ws://localhost:3002/ws")
14
14
  }),
15
15
  render: (props)=>/*#__PURE__*/ react.createElement(EnvVar, {
16
16
  varName: "WEBINY_ADMIN_WS_API_URL",
@@ -1 +1 @@
1
- {"version":3,"file":"extensions/AdminWebsocketsUrl.js","sources":["../../src/extensions/AdminWebsocketsUrl.tsx"],"sourcesContent":["import React from \"react\";\nimport { z } from \"zod\";\nimport { defineExtension } from \"~/defineExtension/index.js\";\nimport { EnvVar } from \"./EnvVar.js\";\n\n/**\n * Sets a dedicated WebSocket URL for the Admin app, baked into the admin bundle as\n * `WEBINY_ADMIN_WS_API_URL`. This is optional: when omitted, the admin derives the WebSocket URL\n * from the API URL (same origin, http -> ws), which is what the standalone hosting type needs by\n * default. Set it only when WebSockets are served from a different origin than the API. Because the\n * config is evaluated at build time, the value can come from any env var the user chooses, e.g.\n * `<Admin.WebsocketsUrl url={process.env.MY_WS_URL} />`.\n */\nexport const AdminWebsocketsUrl = defineExtension({\n type: \"Admin/WebsocketsUrl\",\n tags: { runtimeContext: \"project\", hosting: \"all\" },\n description: \"Set a dedicated WebSocket URL for the Admin app.\",\n paramsSchema: z.object({\n url: z\n .string()\n .describe(\"The WebSocket origin, e.g. wss://ws.example.com or ws://localhost:3002\")\n }),\n render: props => {\n return <EnvVar varName=\"WEBINY_ADMIN_WS_API_URL\" value={props.url} />;\n }\n});\n"],"names":["AdminWebsocketsUrl","defineExtension","z","props","EnvVar"],"mappings":";;;;AAaO,MAAMA,qBAAqBC,gBAAgB;IAC9C,MAAM;IACN,MAAM;QAAE,gBAAgB;QAAW,SAAS;IAAM;IAClD,aAAa;IACb,cAAcC,EAAE,MAAM,CAAC;QACnB,KAAKA,EAAAA,MACM,GACN,QAAQ,CAAC;IAClB;IACA,QAAQC,CAAAA,QACG,WAAP,GAAO,oBAACC,QAAMA;YAAC,SAAQ;YAA0B,OAAOD,MAAM,GAAG;;AAEzE"}
1
+ {"version":3,"file":"extensions/AdminWebsocketsUrl.js","sources":["../../src/extensions/AdminWebsocketsUrl.tsx"],"sourcesContent":["import React from \"react\";\nimport { z } from \"zod\";\nimport { defineExtension } from \"~/defineExtension/index.js\";\nimport { EnvVar } from \"./EnvVar.js\";\n\n/**\n * Sets a dedicated WebSocket URL for the Admin app, baked into the admin bundle as\n * `WEBINY_ADMIN_WS_API_URL`. This is optional: when omitted, the admin derives the WebSocket URL\n * from the API URL (same origin, http -> ws, plus the `/ws` path the standalone server takes\n * upgrades on), which is what the standalone hosting type needs by default. Set it only when that\n * derivation lands in the wrong place: WebSockets on a different origin, or a proxy that rewrites\n * the path. The value is the full socket URL and is used as is. Because the config is evaluated at\n * build time, the value can come from any env var the user chooses, e.g.\n * `<Admin.WebsocketsUrl url={process.env.MY_WS_URL} />`.\n */\nexport const AdminWebsocketsUrl = defineExtension({\n type: \"Admin/WebsocketsUrl\",\n tags: { runtimeContext: \"project\", hosting: \"all\" },\n description: \"Set a dedicated WebSocket URL for the Admin app.\",\n paramsSchema: z.object({\n url: z\n .string()\n .describe(\n \"The full WebSocket URL, e.g. wss://ws.example.com/ws or ws://localhost:3002/ws\"\n )\n }),\n render: props => {\n return <EnvVar varName=\"WEBINY_ADMIN_WS_API_URL\" value={props.url} />;\n }\n});\n"],"names":["AdminWebsocketsUrl","defineExtension","z","props","EnvVar"],"mappings":";;;;AAeO,MAAMA,qBAAqBC,gBAAgB;IAC9C,MAAM;IACN,MAAM;QAAE,gBAAgB;QAAW,SAAS;IAAM;IAClD,aAAa;IACb,cAAcC,EAAE,MAAM,CAAC;QACnB,KAAKA,EAAAA,MACM,GACN,QAAQ,CACL;IAEZ;IACA,QAAQC,CAAAA,QACG,WAAP,GAAO,oBAACC,QAAMA;YAAC,SAAQ;YAA0B,OAAOD,MAAM,GAAG;;AAEzE"}
@@ -4,5 +4,6 @@ export declare const DatabaseSetup: import("./index.js").ExtensionComponent<z.Zo
4
4
  ddb: "ddb";
5
5
  "ddb+es": "ddb+es";
6
6
  "ddb+os": "ddb+os";
7
+ pg: "pg";
7
8
  }>;
8
9
  }, z.core.$strip>>;
@@ -6,13 +6,14 @@ const DatabaseSetup = defineExtension({
6
6
  runtimeContext: "project",
7
7
  hosting: "all"
8
8
  },
9
- description: "Define the database setup configuration (ddb, ddb+es, or ddb+os).",
9
+ description: "Define the database setup configuration (ddb, ddb+es, ddb+os or pg).",
10
10
  paramsSchema: z.object({
11
11
  setupName: z["enum"]([
12
12
  "ddb",
13
13
  "ddb+es",
14
- "ddb+os"
15
- ]).describe("The database setup type: ddb (DynamoDB only), ddb+es (DynamoDB + ElasticSearch), or ddb+os (DynamoDB + OpenSearch)")
14
+ "ddb+os",
15
+ "pg"
16
+ ]).describe("The database setup type: ddb (DynamoDB only), ddb+es (DynamoDB + ElasticSearch), ddb+os (DynamoDB + OpenSearch), or pg (PostgreSQL)")
16
17
  })
17
18
  });
18
19
  export { DatabaseSetup };
@@ -1 +1 @@
1
- {"version":3,"file":"extensions/DatabaseSetup.js","sources":["../../src/extensions/DatabaseSetup.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { defineExtension } from \"../defineExtension/index.js\";\n\nexport const DatabaseSetup = defineExtension({\n type: \"Project/DatabaseSetup\",\n tags: { runtimeContext: \"project\", hosting: \"all\" },\n description: \"Define the database setup configuration (ddb, ddb+es, or ddb+os).\",\n paramsSchema: z.object({\n setupName: z\n .enum([\"ddb\", \"ddb+es\", \"ddb+os\"])\n .describe(\n \"The database setup type: ddb (DynamoDB only), ddb+es (DynamoDB + ElasticSearch), or ddb+os (DynamoDB + OpenSearch)\"\n )\n })\n});\n"],"names":["DatabaseSetup","defineExtension","z"],"mappings":";;AAGO,MAAMA,gBAAgBC,gBAAgB;IACzC,MAAM;IACN,MAAM;QAAE,gBAAgB;QAAW,SAAS;IAAM;IAClD,aAAa;IACb,cAAcC,EAAE,MAAM,CAAC;QACnB,WAAWA,CAAC,CAADA,OACF,CAAC;YAAC;YAAO;YAAU;SAAS,EAChC,QAAQ,CACL;IAEZ;AACJ"}
1
+ {"version":3,"file":"extensions/DatabaseSetup.js","sources":["../../src/extensions/DatabaseSetup.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { defineExtension } from \"../defineExtension/index.js\";\n\nexport const DatabaseSetup = defineExtension({\n type: \"Project/DatabaseSetup\",\n tags: { runtimeContext: \"project\", hosting: \"all\" },\n description: \"Define the database setup configuration (ddb, ddb+es, ddb+os or pg).\",\n paramsSchema: z.object({\n setupName: z\n .enum([\"ddb\", \"ddb+es\", \"ddb+os\", \"pg\"])\n .describe(\n \"The database setup type: ddb (DynamoDB only), ddb+es (DynamoDB + ElasticSearch), ddb+os (DynamoDB + OpenSearch), or pg (PostgreSQL)\"\n )\n })\n});\n"],"names":["DatabaseSetup","defineExtension","z"],"mappings":";;AAGO,MAAMA,gBAAgBC,gBAAgB;IACzC,MAAM;IACN,MAAM;QAAE,gBAAgB;QAAW,SAAS;IAAM;IAClD,aAAa;IACb,cAAcC,EAAE,MAAM,CAAC;QACnB,WAAWA,CAAC,CAADA,OACF,CAAC;YAAC;YAAO;YAAU;YAAU;SAAK,EACtC,QAAQ,CACL;IAEZ;AACJ"}
@@ -3,7 +3,8 @@
3
3
  * API Gateway wants `{orderId}`, the DI `HttpRouter` wants `:orderId`. Rather than pick a winner and
4
4
  * break whichever projects already used the other, accept both and convert per consumer. The API
5
5
  * Gateway conversion lives in `@webiny/project-aws` (`toApiGatewayPath.ts`), the only package that
6
- * creates API Gateway routes.
6
+ * creates API Gateway routes, next to the CloudFront one (`toCloudFrontPathPattern.ts`) that routes a
7
+ * path to the web function.
7
8
  *
8
9
  * Wildcards are left alone. `HttpRouter` matches a trailing `/*`, API Gateway spells the same thing
9
10
  * `{proxy+}`, and translating between them changes what the route captures — so a wildcard route
@@ -1 +1 @@
1
- {"version":3,"file":"extensions/api/Route/routePath.js","sources":["../../../../src/extensions/api/Route/routePath.ts"],"sourcesContent":["/**\n * The `path` prop on `<Api.Route>` feeds two consumers that spell path parameters differently:\n * API Gateway wants `{orderId}`, the DI `HttpRouter` wants `:orderId`. Rather than pick a winner and\n * break whichever projects already used the other, accept both and convert per consumer. The API\n * Gateway conversion lives in `@webiny/project-aws` (`toApiGatewayPath.ts`), the only package that\n * creates API Gateway routes.\n *\n * Wildcards are left alone. `HttpRouter` matches a trailing `/*`, API Gateway spells the same thing\n * `{proxy+}`, and translating between them changes what the route captures — so a wildcard route\n * has to be written for the target it's aimed at.\n */\n\n/** `/orders/{orderId}` → `/orders/:orderId`. Already-colon segments pass through. */\nexport function toRouterPath(path: string): string {\n return path.replace(/\\{([^}]+)\\}/g, (_match, name: string) => {\n return `:${name}`;\n });\n}\n\n/**\n * `/asd/{id}/xs` + POST → `asd-xs-post`. Handles either parameter syntax.\n *\n * Used for BOTH the Pulumi resource name and the route's DI name, so the name a decorator matches\n * on is the same one that shows up in infrastructure.\n */\nexport function deriveRouteName(routePath: string, method: string): string {\n // /asd/{id}/xs + POST → asd-xs-post. Strips parameters in either syntax.\n const pathPart = routePath\n .replace(/^\\//, \"\")\n .replace(/\\{[^}]*\\}/g, \"\")\n .replace(/(^|\\/):[^/]+/g, \"$1\")\n .replace(/\\/+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .toLowerCase();\n\n return `${pathPart}-${method.toLowerCase()}`;\n}\n"],"names":["toRouterPath","path","_match","name","deriveRouteName","routePath","method","pathPart"],"mappings":"AAaO,SAASA,aAAaC,IAAY;IACrC,OAAOA,KAAK,OAAO,CAAC,gBAAgB,CAACC,QAAQC,OAClC,CAAC,CAAC,EAAEA,MAAM;AAEzB;AAQO,SAASC,gBAAgBC,SAAiB,EAAEC,MAAc;IAE7D,MAAMC,WAAWF,UACZ,OAAO,CAAC,OAAO,IACf,OAAO,CAAC,cAAc,IACtB,OAAO,CAAC,iBAAiB,MACzB,OAAO,CAAC,QAAQ,KAChB,OAAO,CAAC,YAAY,IACpB,WAAW;IAEhB,OAAO,GAAGE,SAAS,CAAC,EAAED,OAAO,WAAW,IAAI;AAChD"}
1
+ {"version":3,"file":"extensions/api/Route/routePath.js","sources":["../../../../src/extensions/api/Route/routePath.ts"],"sourcesContent":["/**\n * The `path` prop on `<Api.Route>` feeds two consumers that spell path parameters differently:\n * API Gateway wants `{orderId}`, the DI `HttpRouter` wants `:orderId`. Rather than pick a winner and\n * break whichever projects already used the other, accept both and convert per consumer. The API\n * Gateway conversion lives in `@webiny/project-aws` (`toApiGatewayPath.ts`), the only package that\n * creates API Gateway routes, next to the CloudFront one (`toCloudFrontPathPattern.ts`) that routes a\n * path to the web function.\n *\n * Wildcards are left alone. `HttpRouter` matches a trailing `/*`, API Gateway spells the same thing\n * `{proxy+}`, and translating between them changes what the route captures — so a wildcard route\n * has to be written for the target it's aimed at.\n */\n\n/** `/orders/{orderId}` → `/orders/:orderId`. Already-colon segments pass through. */\nexport function toRouterPath(path: string): string {\n return path.replace(/\\{([^}]+)\\}/g, (_match, name: string) => {\n return `:${name}`;\n });\n}\n\n/**\n * `/asd/{id}/xs` + POST → `asd-xs-post`. Handles either parameter syntax.\n *\n * Used for BOTH the Pulumi resource name and the route's DI name, so the name a decorator matches\n * on is the same one that shows up in infrastructure.\n */\nexport function deriveRouteName(routePath: string, method: string): string {\n // /asd/{id}/xs + POST → asd-xs-post. Strips parameters in either syntax.\n const pathPart = routePath\n .replace(/^\\//, \"\")\n .replace(/\\{[^}]*\\}/g, \"\")\n .replace(/(^|\\/):[^/]+/g, \"$1\")\n .replace(/\\/+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .toLowerCase();\n\n return `${pathPart}-${method.toLowerCase()}`;\n}\n"],"names":["toRouterPath","path","_match","name","deriveRouteName","routePath","method","pathPart"],"mappings":"AAcO,SAASA,aAAaC,IAAY;IACrC,OAAOA,KAAK,OAAO,CAAC,gBAAgB,CAACC,QAAQC,OAClC,CAAC,CAAC,EAAEA,MAAM;AAEzB;AAQO,SAASC,gBAAgBC,SAAiB,EAAEC,MAAc;IAE7D,MAAMC,WAAWF,UACZ,OAAO,CAAC,OAAO,IACf,OAAO,CAAC,cAAc,IACtB,OAAO,CAAC,iBAAiB,MACzB,OAAO,CAAC,QAAQ,KAChB,OAAO,CAAC,YAAY,IACpB,WAAW;IAEhB,OAAO,GAAGE,SAAS,CAAC,EAAED,OAAO,WAAW,IAAI;AAChD"}
@@ -44,7 +44,7 @@ export { CoreBeforeWatch };
44
44
  export { CoreAfterBuild };
45
45
  export { ProductionEnvironments };
46
46
  export declare const definitions: (import("./index.js").ExtensionDefinitionModel<import("zod").ZodObject<{
47
- enabled: import("zod").ZodDefault<import("zod").ZodBoolean>;
47
+ environments: import("zod").ZodArray<import("zod").ZodString>;
48
48
  }, import("zod/v4/core").$strip>> | import("./index.js").ExtensionDefinitionModel<import("zod").ZodObject<{
49
49
  paramName: import("zod").ZodString;
50
50
  value: import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodRecord<import("zod").ZodString, import("zod").ZodAny>, import("zod").ZodArray<import("zod").ZodAny>, import("zod").ZodNumber, import("zod").ZodBoolean]>;
@@ -98,17 +98,18 @@ export declare const definitions: (import("./index.js").ExtensionDefinitionModel
98
98
  }, import("zod/v4/core").$strip>> | import("./index.js").ExtensionDefinitionModel<import("zod").ZodObject<{
99
99
  varName: import("zod").ZodString;
100
100
  value: import("zod").ZodString;
101
+ }, import("zod/v4/core").$strip>> | import("./index.js").ExtensionDefinitionModel<import("zod").ZodObject<{
102
+ enabled: import("zod").ZodDefault<import("zod").ZodBoolean>;
101
103
  }, import("zod/v4/core").$strip>> | import("./index.js").ExtensionDefinitionModel<import("zod").ZodObject<{
102
104
  token: import("zod").ZodOptional<import("zod").ZodString>;
103
105
  repository: import("zod").ZodOptional<import("zod").ZodString>;
104
106
  labels: import("zod").ZodOptional<import("zod").ZodString>;
105
- }, import("zod/v4/core").$strip>> | import("./index.js").ExtensionDefinitionModel<import("zod").ZodObject<{
106
- environments: import("zod").ZodArray<import("zod").ZodString>;
107
107
  }, import("zod/v4/core").$strip>> | import("./index.js").ExtensionDefinitionModel<import("zod").ZodObject<{
108
108
  setupName: import("zod").ZodEnum<{
109
109
  ddb: "ddb";
110
110
  "ddb+es": "ddb+es";
111
111
  "ddb+os": "ddb+os";
112
+ pg: "pg";
112
113
  }>;
113
114
  }, import("zod/v4/core").$strip>> | import("./index.js").ExtensionDefinitionModel<import("zod").ZodObject<{
114
115
  retentionDays: import("zod").ZodNumber;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webiny/project",
3
- "version": "6.6.0-alpha.11",
3
+ "version": "6.6.0-alpha.12",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./index.js",
@@ -13,14 +13,14 @@
13
13
  "description": "An SDK for managing Webiny projects.",
14
14
  "license": "MIT",
15
15
  "dependencies": {
16
- "@webiny/build-tools": "6.6.0-alpha.11",
16
+ "@webiny/build-tools": "6.6.0-alpha.12",
17
17
  "@webiny/di": "2.0.0",
18
- "@webiny/feature-flags": "6.6.0-alpha.11",
19
- "@webiny/global-config": "6.6.0-alpha.11",
20
- "@webiny/react-properties": "6.6.0-alpha.11",
21
- "@webiny/system-requirements": "6.6.0-alpha.11",
22
- "@webiny/telemetry": "6.6.0-alpha.11",
23
- "@webiny/wcp": "6.6.0-alpha.11",
18
+ "@webiny/feature-flags": "6.6.0-alpha.12",
19
+ "@webiny/global-config": "6.6.0-alpha.12",
20
+ "@webiny/react-properties": "6.6.0-alpha.12",
21
+ "@webiny/system-requirements": "6.6.0-alpha.12",
22
+ "@webiny/telemetry": "6.6.0-alpha.12",
23
+ "@webiny/wcp": "6.6.0-alpha.12",
24
24
  "chalk": "6.0.1",
25
25
  "chokidar": "6.0.0",
26
26
  "ci-info": "4.4.0",
@@ -1,4 +1,6 @@
1
1
  import fs from "fs";
2
+ import { Project } from "ts-morph";
3
+ import { ensureNamedImport } from "../../utils/ensureNamedImport.js";
2
4
  const serializePropsToJsx = (props)=>{
3
5
  const attributes = [];
4
6
  for (const [key, value] of Object.entries(props)){
@@ -37,29 +39,13 @@ const updateWebinyConfig = async (params)=>{
37
39
  const { projectRoot, webinyConfigTsx } = params;
38
40
  const webinyConfigPath = `${projectRoot}/webiny.config.tsx`;
39
41
  let content = fs.readFileSync(webinyConfigPath, "utf-8");
40
- if (webinyConfigTsx.imports && webinyConfigTsx.imports.length > 0) for (const importStatement of webinyConfigTsx.imports){
41
- const existingImportRegex = new RegExp(`import\\s+{([^}]+)}\\s+from\\s+["']${importStatement.path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}["'];?`, "m");
42
- const existingImportMatch = content.match(existingImportRegex);
43
- if (existingImportMatch) {
44
- const existingSpecifiers = existingImportMatch[1].split(",").map((s)=>s.trim());
45
- if (!existingSpecifiers.includes(importStatement.specifier)) {
46
- const updatedSpecifiers = [
47
- ...existingSpecifiers,
48
- importStatement.specifier
49
- ].join(", ");
50
- const updatedImportLine = `import { ${updatedSpecifiers} } from "${importStatement.path}";`;
51
- content = content.replace(existingImportRegex, updatedImportLine);
52
- }
53
- } else {
54
- const importLine = `import { ${importStatement.specifier} } from "${importStatement.path}";`;
55
- const importRegex = /^import\s+.*?from\s+["'].*?["'];?\s*$/gm;
56
- const matches = Array.from(content.matchAll(importRegex));
57
- if (matches.length > 0) {
58
- const lastImport = matches[matches.length - 1];
59
- const lastImportEnd = lastImport.index + lastImport[0].length;
60
- content = content.slice(0, lastImportEnd) + "\n" + importLine + content.slice(lastImportEnd);
61
- } else content = importLine + "\n\n" + content;
62
- }
42
+ if (webinyConfigTsx.imports && webinyConfigTsx.imports.length > 0) {
43
+ const tsMorphProject = new Project({
44
+ useInMemoryFileSystem: true
45
+ });
46
+ const sourceFile = tsMorphProject.createSourceFile("webiny.config.tsx", content);
47
+ for (const importStatement of webinyConfigTsx.imports)ensureNamedImport(sourceFile, importStatement.specifier, importStatement.path);
48
+ content = sourceFile.getFullText();
63
49
  }
64
50
  if (webinyConfigTsx.component) content = addComponentToExtensions(content, webinyConfigTsx.component.name, webinyConfigTsx.component.props);
65
51
  if (webinyConfigTsx.components && webinyConfigTsx.components.length > 0) for (const component of webinyConfigTsx.components)content = addComponentToExtensions(content, component.name, component.props);
@@ -1 +1 @@
1
- {"version":3,"file":"services/InstallExtensionService/updateWebinyConfig.js","sources":["../../../src/services/InstallExtensionService/updateWebinyConfig.ts"],"sourcesContent":["import fs from \"fs\";\nimport { ExtensionWebinyConfigTsx } from \"./types.js\";\n\ninterface UpdateWebinyConfigParams {\n projectRoot: string;\n webinyConfigTsx: ExtensionWebinyConfigTsx;\n}\n\n/**\n * Serializes a props object to JSX attribute syntax.\n * Examples:\n * - { secretKey: \"value\" } => 'secretKey={\"value\"}'\n * - { enabled: true } => 'enabled={true}'\n * - { count: 42 } => 'count={42}'\n * - { config: { key: \"value\" } } => 'config={{\"key\":\"value\"}}'\n */\nconst serializePropsToJsx = (props: Record<string, any>): string => {\n const attributes: string[] = [];\n\n for (const [key, value] of Object.entries(props)) {\n // Skip undefined values.\n if (value === undefined) {\n continue;\n }\n\n // Determine the serialization based on value type.\n let serializedValue: string;\n\n if (typeof value === \"string\") {\n // Strings: use JSON.stringify to handle escaping, then wrap in curly braces.\n serializedValue = `{${JSON.stringify(value)}}`;\n } else if (typeof value === \"number\" || typeof value === \"boolean\") {\n // Numbers and booleans: wrap in curly braces without quotes.\n serializedValue = `{${value}}`;\n } else if (value === null) {\n // Null values.\n serializedValue = `{null}`;\n } else if (Array.isArray(value) || typeof value === \"object\") {\n // Arrays and objects: use JSON.stringify, then wrap in curly braces.\n serializedValue = `{${JSON.stringify(value)}}`;\n } else {\n // Fallback for any other types.\n serializedValue = `{${JSON.stringify(value)}}`;\n }\n\n attributes.push(`${key}=${serializedValue}`);\n }\n\n return attributes.join(\" \");\n};\n\n/**\n * Adds a component to the Extensions function in the webiny.config.tsx content.\n */\nconst addComponentToExtensions = (\n content: string,\n componentName: string,\n props?: Record<string, any>\n): string => {\n // Serialize props to JSX attributes.\n const propsString = props ? serializePropsToJsx(props) : \"\";\n\n // Generate component tag with or without props.\n const componentTag = propsString\n ? `<${componentName} ${propsString} />`\n : `<${componentName} />`;\n\n // Check if component already exists.\n if (content.includes(componentTag)) {\n return content;\n }\n\n // Find the Extensions function's return statement and add component before the final </>.\n // Strategy: Find \"export const Extensions\" block, then find the last </> and insert before it.\n const extensionsFuncRegex = /export const Extensions = \\(\\) => \\{[\\s\\S]*?\\};/;\n const extensionsFuncMatch = content.match(extensionsFuncRegex);\n\n if (!extensionsFuncMatch) {\n return content;\n }\n\n const funcContent = extensionsFuncMatch[0];\n // Find all </> in the function - the last one closes the return statement.\n const closingTags = [...funcContent.matchAll(/<\\/>/g)];\n\n if (closingTags.length === 0) {\n return content;\n }\n\n const lastClosingTag = closingTags[closingTags.length - 1];\n const lastClosingTagIndex = lastClosingTag.index!;\n\n // Find the indentation of the line containing the last </>.\n const beforeClosing = funcContent.substring(0, lastClosingTagIndex);\n const lines = beforeClosing.split(\"\\n\");\n const lastLine = lines[lines.length - 1];\n const indent = lastLine.match(/^(\\s*)/)?.[1] || \" \";\n\n // Insert the component before the last </>.\n const newFuncContent =\n funcContent.substring(0, lastClosingTagIndex) +\n `${indent}${componentTag}\\n${indent}` +\n funcContent.substring(lastClosingTagIndex);\n\n return content.replace(extensionsFuncRegex, newFuncContent);\n};\n\n/**\n * Update the webiny.config.tsx file to add extension imports and component.\n */\nexport const updateWebinyConfig = async (params: UpdateWebinyConfigParams): Promise<void> => {\n const { projectRoot, webinyConfigTsx } = params;\n\n const webinyConfigPath = `${projectRoot}/webiny.config.tsx`;\n\n // Read the current webiny.config.tsx\n let content = fs.readFileSync(webinyConfigPath, \"utf-8\");\n\n // Add imports at the top (after existing imports)\n if (webinyConfigTsx.imports && webinyConfigTsx.imports.length > 0) {\n for (const importStatement of webinyConfigTsx.imports) {\n // Check if we need to add to an existing import from the same path.\n const existingImportRegex = new RegExp(\n `import\\\\s+{([^}]+)}\\\\s+from\\\\s+[\"']${importStatement.path.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}[\"'];?`,\n \"m\"\n );\n const existingImportMatch = content.match(existingImportRegex);\n\n if (existingImportMatch) {\n // Import from this path exists, check if specifier is already imported.\n const existingSpecifiers = existingImportMatch[1].split(\",\").map(s => s.trim());\n\n if (!existingSpecifiers.includes(importStatement.specifier)) {\n // Append the new specifier to the existing import.\n const updatedSpecifiers = [\n ...existingSpecifiers,\n importStatement.specifier\n ].join(\", \");\n const updatedImportLine = `import { ${updatedSpecifiers} } from \"${importStatement.path}\";`;\n content = content.replace(existingImportRegex, updatedImportLine);\n }\n } else {\n // No existing import from this path, add a new import line.\n const importLine = `import { ${importStatement.specifier} } from \"${importStatement.path}\";`;\n\n // Find the position after the last import or at the beginning.\n const importRegex = /^import\\s+.*?from\\s+[\"'].*?[\"'];?\\s*$/gm;\n const matches = Array.from(content.matchAll(importRegex));\n\n if (matches.length > 0) {\n // Add after the last import.\n const lastImport = matches[matches.length - 1];\n const lastImportEnd = lastImport.index! + lastImport[0].length;\n content =\n content.slice(0, lastImportEnd) +\n \"\\n\" +\n importLine +\n content.slice(lastImportEnd);\n } else {\n // No imports found, add at the beginning.\n content = importLine + \"\\n\\n\" + content;\n }\n }\n }\n }\n\n // Add component to the Extensions function.\n if (webinyConfigTsx.component) {\n content = addComponentToExtensions(\n content,\n webinyConfigTsx.component.name,\n webinyConfigTsx.component.props\n );\n }\n\n // Add multiple components to the Extensions function.\n if (webinyConfigTsx.components && webinyConfigTsx.components.length > 0) {\n for (const component of webinyConfigTsx.components) {\n content = addComponentToExtensions(content, component.name, component.props);\n }\n }\n\n // Write the updated content back\n fs.writeFileSync(webinyConfigPath, content, \"utf-8\");\n};\n"],"names":["serializePropsToJsx","props","attributes","key","value","Object","undefined","serializedValue","JSON","Array","addComponentToExtensions","content","componentName","propsString","componentTag","extensionsFuncRegex","extensionsFuncMatch","funcContent","closingTags","lastClosingTag","lastClosingTagIndex","beforeClosing","lines","lastLine","indent","newFuncContent","updateWebinyConfig","params","projectRoot","webinyConfigTsx","webinyConfigPath","fs","importStatement","existingImportRegex","RegExp","existingImportMatch","existingSpecifiers","s","updatedSpecifiers","updatedImportLine","importLine","importRegex","matches","lastImport","lastImportEnd","component"],"mappings":";AAgBA,MAAMA,sBAAsB,CAACC;IACzB,MAAMC,aAAuB,EAAE;IAE/B,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAO,OAAO,CAACJ,OAAQ;QAE9C,IAAIG,AAAUE,WAAVF,OACA;QAIJ,IAAIG;QAEJ,IAAI,AAAiB,YAAjB,OAAOH,OAEPG,kBAAkB,CAAC,CAAC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C8B;YAE5C,IAAIC,QAAQ,MAAM,GAAG,GAAG;gBAEpB,MAAMC,aAAaD,OAAO,CAACA,QAAQ,MAAM,GAAG,EAAE;gBAC9C,MAAME,gBAAgBD,WAAW,KAAK,GAAIA,UAAU,CAAC,EAAE,CAAC,MAAM;gBAC9DhC,UACIA,QAAQ,KAAK,CAAC,GAAGiC,iBACjB,OACAJ,aACA7B,QAAQ,KAAK,CAACiC;YACtB,OAEIjC,UAAU6B,aAAa,SAAS7B;QAExC;IACJ;IAIJ,IAAIkB,gBAAgB,SAAS,EACzBlB,UAAUD,yBACNC,SACAkB,gBAAgB,SAAS,CAAC,IAAI,EAC9BA,gBAAgB,SAAS,CAAC,KAAK;IAKvC,IAAIA,gBAAgB,UAAU,IAAIA,gBAAgB,UAAU,CAAC,MAAM,GAAG,GAClE,KAAK,MAAMgB,aAAahB,gBAAgB,UAAU,CAC9ClB,UAAUD,yBAAyBC,SAASkC,UAAU,IAAI,EAAEA,UAAU,KAAK;IAKnFd,GAAG,aAAa,CAACD,kBAAkBnB,SAAS;AAChD"}
1
+ {"version":3,"file":"services/InstallExtensionService/updateWebinyConfig.js","sources":["../../../src/services/InstallExtensionService/updateWebinyConfig.ts"],"sourcesContent":["import fs from \"fs\";\nimport { Project as TsMorphProject } from \"ts-morph\";\nimport { ensureNamedImport } from \"~/utils/ensureNamedImport.js\";\nimport { ExtensionWebinyConfigTsx } from \"./types.js\";\n\ninterface UpdateWebinyConfigParams {\n projectRoot: string;\n webinyConfigTsx: ExtensionWebinyConfigTsx;\n}\n\n/**\n * Serializes a props object to JSX attribute syntax.\n * Examples:\n * - { secretKey: \"value\" } => 'secretKey={\"value\"}'\n * - { enabled: true } => 'enabled={true}'\n * - { count: 42 } => 'count={42}'\n * - { config: { key: \"value\" } } => 'config={{\"key\":\"value\"}}'\n */\nconst serializePropsToJsx = (props: Record<string, any>): string => {\n const attributes: string[] = [];\n\n for (const [key, value] of Object.entries(props)) {\n // Skip undefined values.\n if (value === undefined) {\n continue;\n }\n\n // Determine the serialization based on value type.\n let serializedValue: string;\n\n if (typeof value === \"string\") {\n // Strings: use JSON.stringify to handle escaping, then wrap in curly braces.\n serializedValue = `{${JSON.stringify(value)}}`;\n } else if (typeof value === \"number\" || typeof value === \"boolean\") {\n // Numbers and booleans: wrap in curly braces without quotes.\n serializedValue = `{${value}}`;\n } else if (value === null) {\n // Null values.\n serializedValue = `{null}`;\n } else if (Array.isArray(value) || typeof value === \"object\") {\n // Arrays and objects: use JSON.stringify, then wrap in curly braces.\n serializedValue = `{${JSON.stringify(value)}}`;\n } else {\n // Fallback for any other types.\n serializedValue = `{${JSON.stringify(value)}}`;\n }\n\n attributes.push(`${key}=${serializedValue}`);\n }\n\n return attributes.join(\" \");\n};\n\n/**\n * Adds a component to the Extensions function in the webiny.config.tsx content.\n */\nconst addComponentToExtensions = (\n content: string,\n componentName: string,\n props?: Record<string, any>\n): string => {\n // Serialize props to JSX attributes.\n const propsString = props ? serializePropsToJsx(props) : \"\";\n\n // Generate component tag with or without props.\n const componentTag = propsString\n ? `<${componentName} ${propsString} />`\n : `<${componentName} />`;\n\n // Check if component already exists.\n if (content.includes(componentTag)) {\n return content;\n }\n\n // Find the Extensions function's return statement and add component before the final </>.\n // Strategy: Find \"export const Extensions\" block, then find the last </> and insert before it.\n const extensionsFuncRegex = /export const Extensions = \\(\\) => \\{[\\s\\S]*?\\};/;\n const extensionsFuncMatch = content.match(extensionsFuncRegex);\n\n if (!extensionsFuncMatch) {\n return content;\n }\n\n const funcContent = extensionsFuncMatch[0];\n // Find all </> in the function - the last one closes the return statement.\n const closingTags = [...funcContent.matchAll(/<\\/>/g)];\n\n if (closingTags.length === 0) {\n return content;\n }\n\n const lastClosingTag = closingTags[closingTags.length - 1];\n const lastClosingTagIndex = lastClosingTag.index!;\n\n // Find the indentation of the line containing the last </>.\n const beforeClosing = funcContent.substring(0, lastClosingTagIndex);\n const lines = beforeClosing.split(\"\\n\");\n const lastLine = lines[lines.length - 1];\n const indent = lastLine.match(/^(\\s*)/)?.[1] || \" \";\n\n // Insert the component before the last </>.\n const newFuncContent =\n funcContent.substring(0, lastClosingTagIndex) +\n `${indent}${componentTag}\\n${indent}` +\n funcContent.substring(lastClosingTagIndex);\n\n return content.replace(extensionsFuncRegex, newFuncContent);\n};\n\n/**\n * Update the webiny.config.tsx file to add extension imports and component.\n */\nexport const updateWebinyConfig = async (params: UpdateWebinyConfigParams): Promise<void> => {\n const { projectRoot, webinyConfigTsx } = params;\n\n const webinyConfigPath = `${projectRoot}/webiny.config.tsx`;\n\n // Read the current webiny.config.tsx\n let content = fs.readFileSync(webinyConfigPath, \"utf-8\");\n\n // Add imports, parsed rather than matched, so a commented-out import or an unusual import shape\n // is not mistaken for the one the extension needs.\n if (webinyConfigTsx.imports && webinyConfigTsx.imports.length > 0) {\n const tsMorphProject = new TsMorphProject({ useInMemoryFileSystem: true });\n const sourceFile = tsMorphProject.createSourceFile(\"webiny.config.tsx\", content);\n\n for (const importStatement of webinyConfigTsx.imports) {\n ensureNamedImport(sourceFile, importStatement.specifier, importStatement.path);\n }\n\n content = sourceFile.getFullText();\n }\n\n // Add component to the Extensions function.\n if (webinyConfigTsx.component) {\n content = addComponentToExtensions(\n content,\n webinyConfigTsx.component.name,\n webinyConfigTsx.component.props\n );\n }\n\n // Add multiple components to the Extensions function.\n if (webinyConfigTsx.components && webinyConfigTsx.components.length > 0) {\n for (const component of webinyConfigTsx.components) {\n content = addComponentToExtensions(content, component.name, component.props);\n }\n }\n\n // Write the updated content back\n fs.writeFileSync(webinyConfigPath, content, \"utf-8\");\n};\n"],"names":["serializePropsToJsx","props","attributes","key","value","Object","undefined","serializedValue","JSON","Array","addComponentToExtensions","content","componentName","propsString","componentTag","extensionsFuncRegex","extensionsFuncMatch","funcContent","closingTags","lastClosingTag","lastClosingTagIndex","beforeClosing","lines","lastLine","indent","newFuncContent","updateWebinyConfig","params","projectRoot","webinyConfigTsx","webinyConfigPath","fs","tsMorphProject","TsMorphProject","sourceFile","importSt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CAACD,kBAAkBnB,SAAS;AAChD"}
@@ -1,6 +1,7 @@
1
1
  import { createImplementation } from "@webiny/di";
2
2
  import { GetProjectService, SetProjectIdService } from "../../abstractions/index.js";
3
3
  import { Project, SyntaxKind } from "ts-morph";
4
+ import { ensureNamedImport } from "../../utils/ensureNamedImport.js";
4
5
  class DefaultSetProjectIdService {
5
6
  constructor(getProjectService){
6
7
  this.getProjectService = getProjectService;
@@ -10,13 +11,7 @@ class DefaultSetProjectIdService {
10
11
  const webinyConfigFileTsx = project.paths.webinyConfigFile.toString();
11
12
  const tsMorphProject = new Project();
12
13
  const sourceFile = tsMorphProject.addSourceFileAtPath(webinyConfigFileTsx);
13
- const hasProjectImport = sourceFile.getImportDeclarations().some((decl)=>"webiny/extensions" === decl.getModuleSpecifierValue() && decl.getNamedImports().some((imp)=>"Project" === imp.getName()));
14
- if (!hasProjectImport) sourceFile.insertImportDeclaration(0, {
15
- namedImports: [
16
- "Project"
17
- ],
18
- moduleSpecifier: "webiny/extensions"
19
- });
14
+ ensureNamedImport(sourceFile, "Project", "webiny/extensions");
20
15
  const jsxElements = sourceFile.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement);
21
16
  const existingProjectIdEl = jsxElements.find((el)=>"Project.Id" === el.getTagNameNode().getText());
22
17
  if (existingProjectIdEl) {
@@ -1 +1 @@
1
- {"version":3,"file":"services/SetProjectIdService/SetProjectIdService.js","sources":["../../../src/services/SetProjectIdService/SetProjectIdService.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/di\";\nimport { GetProjectService, SetProjectIdService } from \"~/abstractions/index.js\";\nimport { Project as TsMorphProject, SyntaxKind } from \"ts-morph\";\n\nclass DefaultSetProjectIdService implements SetProjectIdService.Interface {\n constructor(private getProjectService: GetProjectService.Interface) {}\n\n async execute(id: string, options: SetProjectIdService.Options = {}) {\n const project = this.getProjectService.execute();\n const webinyConfigFileTsx = project.paths.webinyConfigFile.toString();\n\n const tsMorphProject = new TsMorphProject();\n const sourceFile = tsMorphProject.addSourceFileAtPath(webinyConfigFileTsx);\n\n // Ensure import { Project } from \"webiny/extensions\".\n const hasProjectImport = sourceFile\n .getImportDeclarations()\n .some(\n decl =>\n decl.getModuleSpecifierValue() === \"webiny/extensions\" &&\n decl.getNamedImports().some(imp => imp.getName() === \"Project\")\n );\n if (!hasProjectImport) {\n sourceFile.insertImportDeclaration(0, {\n namedImports: [\"Project\"],\n moduleSpecifier: \"webiny/extensions\"\n });\n }\n\n const jsxElements = sourceFile.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement);\n\n // Check for existing <Project.Id />.\n const existingProjectIdEl = jsxElements.find(\n el => el.getTagNameNode().getText() === \"Project.Id\"\n );\n if (existingProjectIdEl) {\n if (options.force !== true) {\n throw new Error(\"Project.Id already exists in the file.\");\n }\n // Update the id attribute in-place.\n const idAttr = existingProjectIdEl\n .getAttributes()\n .find(attr => attr.getFirstChildByKind(SyntaxKind.Identifier)?.getText() === \"id\");\n if (idAttr) {\n idAttr.replaceWithText(`id={\"${id}\"}`);\n } else {\n existingProjectIdEl.replaceWithText(`<Project.Id id={\"${id}\"} />`);\n }\n await sourceFile.save();\n return;\n }\n\n /* Determine the insertion point — after the last <Project.*> element that is a\n direct child of the outermost JSX fragment (i.e. not inside a conditional expression).\n Fall back to inserting after the opening tag of the outermost JSX fragment. */\n const fragment = sourceFile.getFirstDescendantByKind(SyntaxKind.JsxFragment);\n const projectEls = jsxElements.filter(\n el =>\n el.getTagNameNode().getText().startsWith(\"Project.\") &&\n el.getParent()?.getParent() === fragment\n );\n\n if (projectEls.length > 0) {\n const lastProjectEl = projectEls[projectEls.length - 1];\n sourceFile.insertText(\n lastProjectEl.getEnd(),\n `\\n <Project.Id id={\"${id}\"} />`\n );\n } else {\n // Fallback: insert as first child of the outermost JSX fragment.\n if (!fragment) {\n throw new Error(\n `Could not find a JSX fragment or <Project.*> element to anchor <Project.Id /> in ${webinyConfigFileTsx}`\n );\n }\n const openingFragment = fragment.getOpeningFragment();\n sourceFile.insertText(\n openingFragment.getEnd(),\n `\\n <Project.Id id={\"${id}\"} />`\n );\n }\n\n await sourceFile.save();\n }\n}\n\nexport const setProjectIdService = createImplementation({\n abstraction: SetProjectIdService,\n implementation: DefaultSetProjectIdService,\n dependencies: [GetProjectService]\n});\n"],"names":["DefaultSetProjectIdService","getProjectService","id","options","project","webinyConfigFileTsx","tsMorphProject","TsMorphProject","sourceFile","hasProjectImport","decl","imp","jsxElements","SyntaxKind","existingProjectIdEl","el","Error","idAttr","attr","fragment","projectEls","lastProjectEl","openingFragment","setProjectIdService","createImplementation","SetProjectIdService","GetProjectService"],"mappings":";;;AAIA,MAAMA;IACF,YAAoBC,iBAA8C,CAAE;aAAhDA,iBAAiB,GAAjBA;IAAiD;IAErE,MAAM,QAAQC,EAAU,EAAEC,UAAuC,CAAC,CAAC,EAAE;QACjE,MAAMC,UAAU,IAAI,CAAC,iBAAiB,CAAC,OAAO;QAC9C,MAAMC,sBAAsBD,QAAQ,KAAK,CAAC,gBAAgB,CAAC,QAAQ;QAEnE,MAAME,iBAAiB,IAAIC;QAC3B,MAAMC,aAAaF,eAAe,mBAAmB,CAACD;QAGtD,MAAMI,mBAAmBD,WACpB,qBAAqB,GACrB,IAAI,CACDE,CAAAA,OACIA,AAAmC,wBAAnCA,KAAK,uBAAuB,MAC5BA,KAAK,eAAe,GAAG,IAAI,CAACC,CAAAA,MAAOA,AAAkB,cAAlBA,IAAI,OAAO;QAE1D,IAAI,CAACF,kBACDD,WAAW,uBAAuB,CAAC,GAAG;YAClC,cAAc;gBAAC;aAAU;YACzB,iBAAiB;QACrB;QAGJ,MAAMI,cAAcJ,WAAW,oBAAoB,CAACK,WAAW,qBAAqB;QAGpF,MAAMC,sBAAsBF,YAAY,IAAI,CACxCG,CAAAA,KAAMA,AAAkC,iBAAlCA,GAAG,cAAc,GAAG,OAAO;QAErC,IAAID,qBAAqB;YACrB,IAAIX,AAAkB,SAAlBA,QAAQ,KAAK,EACb,MAAM,IAAIa,MAAM;YAGpB,MAAMC,SAASH,oBACV,aAAa,GACb,IAAI,CAACI,CAAAA,OAAQA,KAAK,mBAAmB,CAACL,WAAW,UAAU,GAAG,cAAc;YACjF,IAAII,QACAA,OAAO,eAAe,CAAC,CAAC,KAAK,EAAEf,GAAG,EAAE,CAAC;iBAErCY,oBAAoB,eAAe,CAAC,CAAC,iBAAiB,EAAEZ,GAAG,KAAK,CAAC;YAErE,MAAMM,WAAW,IAAI;YACrB;QACJ;QAKA,MAAMW,WAAWX,WAAW,wBAAwB,CAACK,WAAW,WAAW;QAC3E,MAAMO,aAAaR,YAAY,MAAM,CACjCG,CAAAA,KACIA,GAAG,cAAc,GAAG,OAAO,GAAG,UAAU,CAAC,eACzCA,GAAG,SAAS,IAAI,gBAAgBI;QAGxC,IAAIC,WAAW,MAAM,GAAG,GAAG;YACvB,MAAMC,gBAAgBD,UAAU,CAACA,WAAW,MAAM,GAAG,EAAE;YACvDZ,WAAW,UAAU,CACjBa,cAAc,MAAM,IACpB,CAAC,+BAA+B,EAAEnB,GAAG,KAAK,CAAC;QAEnD,OAAO;YAEH,IAAI,CAACiB,UACD,MAAM,IAAIH,MACN,CAAC,iFAAiF,EAAEX,qBAAqB;YAGjH,MAAMiB,kBAAkBH,SAAS,kBAAkB;YACnDX,WAAW,UAAU,CACjBc,gBAAgB,MAAM,IACtB,CAAC,+BAA+B,EAAEpB,GAAG,KAAK,CAAC;QAEnD;QAEA,MAAMM,WAAW,IAAI;IACzB;AACJ;AAEO,MAAMe,sBAAsBC,qBAAqB;IACpD,aAAaC;IACb,gBAAgBzB;IAChB,cAAc;QAAC0B;KAAkB;AACrC"}
1
+ {"version":3,"file":"services/SetProjectIdService/SetProjectIdService.js","sources":["../../../src/services/SetProjectIdService/SetProjectIdService.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/di\";\nimport { GetProjectService, SetProjectIdService } from \"~/abstractions/index.js\";\nimport { Project as TsMorphProject, SyntaxKind } from \"ts-morph\";\nimport { ensureNamedImport } from \"~/utils/ensureNamedImport.js\";\n\nclass DefaultSetProjectIdService implements SetProjectIdService.Interface {\n constructor(private getProjectService: GetProjectService.Interface) {}\n\n async execute(id: string, options: SetProjectIdService.Options = {}) {\n const project = this.getProjectService.execute();\n const webinyConfigFileTsx = project.paths.webinyConfigFile.toString();\n\n const tsMorphProject = new TsMorphProject();\n const sourceFile = tsMorphProject.addSourceFileAtPath(webinyConfigFileTsx);\n\n ensureNamedImport(sourceFile, \"Project\", \"webiny/extensions\");\n\n const jsxElements = sourceFile.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement);\n\n // Check for existing <Project.Id />.\n const existingProjectIdEl = jsxElements.find(\n el => el.getTagNameNode().getText() === \"Project.Id\"\n );\n if (existingProjectIdEl) {\n if (options.force !== true) {\n throw new Error(\"Project.Id already exists in the file.\");\n }\n // Update the id attribute in-place.\n const idAttr = existingProjectIdEl\n .getAttributes()\n .find(attr => attr.getFirstChildByKind(SyntaxKind.Identifier)?.getText() === \"id\");\n if (idAttr) {\n idAttr.replaceWithText(`id={\"${id}\"}`);\n } else {\n existingProjectIdEl.replaceWithText(`<Project.Id id={\"${id}\"} />`);\n }\n await sourceFile.save();\n return;\n }\n\n /* Determine the insertion point — after the last <Project.*> element that is a\n direct child of the outermost JSX fragment (i.e. not inside a conditional expression).\n Fall back to inserting after the opening tag of the outermost JSX fragment. */\n const fragment = sourceFile.getFirstDescendantByKind(SyntaxKind.JsxFragment);\n const projectEls = jsxElements.filter(\n el =>\n el.getTagNameNode().getText().startsWith(\"Project.\") &&\n el.getParent()?.getParent() === fragment\n );\n\n if (projectEls.length > 0) {\n const lastProjectEl = projectEls[projectEls.length - 1];\n sourceFile.insertText(\n lastProjectEl.getEnd(),\n `\\n <Project.Id id={\"${id}\"} />`\n );\n } else {\n // Fallback: insert as first child of the outermost JSX fragment.\n if (!fragment) {\n throw new Error(\n `Could not find a JSX fragment or <Project.*> element to anchor <Project.Id /> in ${webinyConfigFileTsx}`\n );\n }\n const openingFragment = fragment.getOpeningFragment();\n sourceFile.insertText(\n openingFragment.getEnd(),\n `\\n <Project.Id id={\"${id}\"} />`\n );\n }\n\n await sourceFile.save();\n }\n}\n\nexport const setProjectIdService = createImplementation({\n abstraction: SetProjectIdService,\n implementation: DefaultSetProjectIdService,\n dependencies: [GetProjectService]\n});\n"],"names":["DefaultSetProjectIdService","getProjectService","id","options","project","webinyConfigFileTsx","tsMorphProject","TsMorphProject","sourceFile","ensureNamedImport","jsxElements","SyntaxKind","existingProjectIdEl","el","Error","idAttr","attr","fragment","projectEls","lastProjectEl","openingFragment","setProjectIdService","createImplementation","SetProjectIdService","GetProjectService"],"mappings":";;;;AAKA,MAAMA;IACF,YAAoBC,iBAA8C,CAAE;aAAhDA,iBAAiB,GAAjBA;IAAiD;IAErE,MAAM,QAAQC,EAAU,EAAEC,UAAuC,CAAC,CAAC,EAAE;QACjE,MAAMC,UAAU,IAAI,CAAC,iBAAiB,CAAC,OAAO;QAC9C,MAAMC,sBAAsBD,QAAQ,KAAK,CAAC,gBAAgB,CAAC,QAAQ;QAEnE,MAAME,iBAAiB,IAAIC;QAC3B,MAAMC,aAAaF,eAAe,mBAAmB,CAACD;QAEtDI,kBAAkBD,YAAY,WAAW;QAEzC,MAAME,cAAcF,WAAW,oBAAoB,CAACG,WAAW,qBAAqB;QAGpF,MAAMC,sBAAsBF,YAAY,IAAI,CACxCG,CAAAA,KAAMA,AAAkC,iBAAlCA,GAAG,cAAc,GAAG,OAAO;QAErC,IAAID,qBAAqB;YACrB,IAAIT,AAAkB,SAAlBA,QAAQ,KAAK,EACb,MAAM,IAAIW,MAAM;YAGpB,MAAMC,SAASH,oBACV,aAAa,GACb,IAAI,CAACI,CAAAA,OAAQA,KAAK,mBAAmB,CAACL,WAAW,UAAU,GAAG,cAAc;YACjF,IAAII,QACAA,OAAO,eAAe,CAAC,CAAC,KAAK,EAAEb,GAAG,EAAE,CAAC;iBAErCU,oBAAoB,eAAe,CAAC,CAAC,iBAAiB,EAAEV,GAAG,KAAK,CAAC;YAErE,MAAMM,WAAW,IAAI;YACrB;QACJ;QAKA,MAAMS,WAAWT,WAAW,wBAAwB,CAACG,WAAW,WAAW;QAC3E,MAAMO,aAAaR,YAAY,MAAM,CACjCG,CAAAA,KACIA,GAAG,cAAc,GAAG,OAAO,GAAG,UAAU,CAAC,eACzCA,GAAG,SAAS,IAAI,gBAAgBI;QAGxC,IAAIC,WAAW,MAAM,GAAG,GAAG;YACvB,MAAMC,gBAAgBD,UAAU,CAACA,WAAW,MAAM,GAAG,EAAE;YACvDV,WAAW,UAAU,CACjBW,cAAc,MAAM,IACpB,CAAC,+BAA+B,EAAEjB,GAAG,KAAK,CAAC;QAEnD,OAAO;YAEH,IAAI,CAACe,UACD,MAAM,IAAIH,MACN,CAAC,iFAAiF,EAAET,qBAAqB;YAGjH,MAAMe,kBAAkBH,SAAS,kBAAkB;YACnDT,WAAW,UAAU,CACjBY,gBAAgB,MAAM,IACtB,CAAC,+BAA+B,EAAElB,GAAG,KAAK,CAAC;QAEnD;QAEA,MAAMM,WAAW,IAAI;IACzB;AACJ;AAEO,MAAMa,sBAAsBC,qBAAqB;IACpD,aAAaC;IACb,gBAAgBvB;IAChB,cAAc;QAACwB;KAAkB;AACrC"}
@@ -0,0 +1,12 @@
1
+ import type { SourceFile } from "ts-morph";
2
+ /**
3
+ * Makes sure `name` is imported from `moduleSpecifier` in the given file, as a value under its own
4
+ * name, so it can be used in JSX.
5
+ *
6
+ * Checks every import from the module, not only the first: a file can import from one module on
7
+ * several lines, and adding the name to one line when another already has it declares it twice.
8
+ * If the name is imported only as a type, that import becomes a value import, since a second,
9
+ * value import of the same name is also a duplicate. Otherwise a missing name goes into the first
10
+ * import from the module that takes named imports, or onto a new import line after the last one.
11
+ */
12
+ export declare const ensureNamedImport: (sourceFile: SourceFile, name: string, moduleSpecifier: string) => void;
@@ -0,0 +1,27 @@
1
+ const ensureNamedImport = (sourceFile, name, moduleSpecifier)=>{
2
+ const moduleDeclarations = sourceFile.getImportDeclarations().filter((declaration)=>declaration.getModuleSpecifierValue() === moduleSpecifier);
3
+ const declarations = moduleDeclarations.filter((declaration)=>!declaration.isTypeOnly());
4
+ const isImported = declarations.some((declaration)=>declaration.getNamedImports().some((namedImport)=>namedImport.getName() === name && !namedImport.getAliasNode() && !namedImport.isTypeOnly()));
5
+ if (isImported) return;
6
+ for (const declaration of moduleDeclarations){
7
+ const typeOnlyImport = declaration.getNamedImports().find((namedImport)=>namedImport.getName() === name && !namedImport.getAliasNode());
8
+ if (!typeOnlyImport) continue;
9
+ if (typeOnlyImport.isTypeOnly()) return void typeOnlyImport.setIsTypeOnly(false);
10
+ const isOnlyName = 1 === declaration.getNamedImports().length && !declaration.getDefaultImport();
11
+ if (isOnlyName) return void declaration.setIsTypeOnly(false);
12
+ typeOnlyImport.remove();
13
+ break;
14
+ }
15
+ const target = declarations.find((declaration)=>!declaration.getNamespaceImport());
16
+ if (target) return void target.addNamedImport(name);
17
+ const index = sourceFile.getImportDeclarations().length;
18
+ sourceFile.insertImportDeclaration(index, {
19
+ namedImports: [
20
+ name
21
+ ],
22
+ moduleSpecifier
23
+ });
24
+ };
25
+ export { ensureNamedImport };
26
+
27
+ //# sourceMappingURL=ensureNamedImport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils/ensureNamedImport.js","sources":["../../src/utils/ensureNamedImport.ts"],"sourcesContent":["import type { SourceFile } from \"ts-morph\";\n\n/**\n * Makes sure `name` is imported from `moduleSpecifier` in the given file, as a value under its own\n * name, so it can be used in JSX.\n *\n * Checks every import from the module, not only the first: a file can import from one module on\n * several lines, and adding the name to one line when another already has it declares it twice.\n * If the name is imported only as a type, that import becomes a value import, since a second,\n * value import of the same name is also a duplicate. Otherwise a missing name goes into the first\n * import from the module that takes named imports, or onto a new import line after the last one.\n */\nexport const ensureNamedImport = (\n sourceFile: SourceFile,\n name: string,\n moduleSpecifier: string\n) => {\n const moduleDeclarations = sourceFile\n .getImportDeclarations()\n .filter(declaration => declaration.getModuleSpecifierValue() === moduleSpecifier);\n const declarations = moduleDeclarations.filter(declaration => !declaration.isTypeOnly());\n\n const isImported = declarations.some(declaration => {\n return declaration.getNamedImports().some(namedImport => {\n return (\n namedImport.getName() === name &&\n !namedImport.getAliasNode() &&\n !namedImport.isTypeOnly()\n );\n });\n });\n\n if (isImported) {\n return;\n }\n\n for (const declaration of moduleDeclarations) {\n const typeOnlyImport = declaration.getNamedImports().find(namedImport => {\n return namedImport.getName() === name && !namedImport.getAliasNode();\n });\n if (!typeOnlyImport) {\n continue;\n }\n\n // `import { Infra, type Api }`: drop the `type` on the name.\n if (typeOnlyImport.isTypeOnly()) {\n typeOnlyImport.setIsTypeOnly(false);\n return;\n }\n\n // `import type { Api }`: the name is all it imports, so drop the `type` on the line.\n const isOnlyName =\n declaration.getNamedImports().length === 1 && !declaration.getDefaultImport();\n if (isOnlyName) {\n declaration.setIsTypeOnly(false);\n return;\n }\n\n // `import type { Api, Admin }`: take the name out and add it as a value below.\n typeOnlyImport.remove();\n break;\n }\n\n const target = declarations.find(declaration => !declaration.getNamespaceImport());\n if (target) {\n target.addNamedImport(name);\n return;\n }\n\n const index = sourceFile.getImportDeclarations().length;\n sourceFile.insertImportDeclaration(index, {\n namedImports: [name],\n moduleSpecifier\n });\n};\n"],"names":["ensureNamedImport","sourceFile","name","moduleSpecifier","moduleDeclarations","declaration","declarations","isImported","namedImport","typeOnlyImport","isOnlyName","target","index"],"mappings":"AAYO,MAAMA,oBAAoB,CAC7BC,YACAC,MACAC;IAEA,MAAMC,qBAAqBH,WACtB,qBAAqB,GACrB,MAAM,CAACI,CAAAA,cAAeA,YAAY,uBAAuB,OAAOF;IACrE,MAAMG,eAAeF,mBAAmB,MAAM,CAACC,CAAAA,cAAe,CAACA,YAAY,UAAU;IAErF,MAAME,aAAaD,aAAa,IAAI,CAACD,CAAAA,cAC1BA,YAAY,eAAe,GAAG,IAAI,CAACG,CAAAA,cAElCA,YAAY,OAAO,OAAON,QAC1B,CAACM,YAAY,YAAY,MACzB,CAACA,YAAY,UAAU;IAKnC,IAAID,YACA;IAGJ,KAAK,MAAMF,eAAeD,mBAAoB;QAC1C,MAAMK,iBAAiBJ,YAAY,eAAe,GAAG,IAAI,CAACG,CAAAA,cAC/CA,YAAY,OAAO,OAAON,QAAQ,CAACM,YAAY,YAAY;QAEtE,IAAI,CAACC,gBACD;QAIJ,IAAIA,eAAe,UAAU,IAAI,YAC7BA,eAAe,aAAa,CAAC;QAKjC,MAAMC,aACFL,AAAyC,MAAzCA,YAAY,eAAe,GAAG,MAAM,IAAU,CAACA,YAAY,gBAAgB;QAC/E,IAAIK,YAAY,YACZL,YAAY,aAAa,CAAC;QAK9BI,eAAe,MAAM;QACrB;IACJ;IAEA,MAAME,SAASL,aAAa,IAAI,CAACD,CAAAA,cAAe,CAACA,YAAY,kBAAkB;IAC/E,IAAIM,QAAQ,YACRA,OAAO,cAAc,CAACT;IAI1B,MAAMU,QAAQX,WAAW,qBAAqB,GAAG,MAAM;IACvDA,WAAW,uBAAuB,CAACW,OAAO;QACtC,cAAc;YAACV;SAAK;QACpBC;IACJ;AACJ"}
package/utils/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from "./constants.js";
2
2
  export * from "./createPathResolver.js";
3
+ export * from "./ensureNamedImport.js";
3
4
  export * from "./getRandomColorForString.js";
4
5
  export * from "./getStackName.js";
5
6
  export * from "./ExtensionSrcResolver.js";
package/utils/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from "./constants.js";
2
2
  export * from "./createPathResolver.js";
3
+ export * from "./ensureNamedImport.js";
3
4
  export * from "./getRandomColorForString.js";
4
5
  export * from "./getStackName.js";
5
6
  export * from "./ExtensionSrcResolver.js";