@ingenyus/swarm-wasp 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/README.md +229 -21
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/common/filesystem.d.ts +0 -14
  4. package/dist/common/filesystem.d.ts.map +1 -1
  5. package/dist/common/filesystem.js +123 -0
  6. package/dist/common/index.js +391 -0
  7. package/dist/common/plugin.js +41 -0
  8. package/dist/common/prisma.js +140 -0
  9. package/dist/common/schemas.d.ts +8 -42
  10. package/dist/common/schemas.d.ts.map +1 -1
  11. package/dist/common/schemas.js +54 -0
  12. package/dist/common/templates.js +52 -0
  13. package/dist/generators/action/action-generator.d.ts +16 -29
  14. package/dist/generators/action/action-generator.d.ts.map +1 -1
  15. package/dist/generators/action/action-generator.js +1429 -0
  16. package/dist/generators/action/index.js +1429 -0
  17. package/dist/generators/action/schema.d.ts +11 -23
  18. package/dist/generators/action/schema.d.ts.map +1 -1
  19. package/dist/generators/action/schema.js +119 -0
  20. package/dist/generators/api/api-generator.d.ts +19 -26
  21. package/dist/generators/api/api-generator.d.ts.map +1 -1
  22. package/dist/generators/api/api-generator.js +1108 -0
  23. package/dist/generators/api/index.js +1108 -0
  24. package/dist/generators/api/schema.d.ts +13 -21
  25. package/dist/generators/api/schema.d.ts.map +1 -1
  26. package/dist/generators/api/schema.js +121 -0
  27. package/dist/generators/api-namespace/api-namespace-generator.d.ts +10 -17
  28. package/dist/generators/api-namespace/api-namespace-generator.d.ts.map +1 -1
  29. package/dist/generators/api-namespace/api-namespace-generator.js +1032 -0
  30. package/dist/generators/api-namespace/index.js +1032 -0
  31. package/dist/generators/api-namespace/schema.d.ts +4 -12
  32. package/dist/generators/api-namespace/schema.d.ts.map +1 -1
  33. package/dist/generators/api-namespace/schema.js +93 -0
  34. package/dist/generators/base/{entity-generator.base.d.ts → component-generator.base.d.ts} +9 -9
  35. package/dist/generators/base/component-generator.base.d.ts.map +1 -0
  36. package/dist/generators/base/component-generator.base.js +935 -0
  37. package/dist/generators/base/index.d.ts +1 -1
  38. package/dist/generators/base/index.d.ts.map +1 -1
  39. package/dist/generators/base/index.js +1334 -0
  40. package/dist/generators/base/operation-generator.base.d.ts +12 -3
  41. package/dist/generators/base/operation-generator.base.d.ts.map +1 -1
  42. package/dist/generators/base/operation-generator.base.js +1335 -0
  43. package/dist/generators/base/wasp-generator.base.d.ts +2 -1
  44. package/dist/generators/base/wasp-generator.base.d.ts.map +1 -1
  45. package/dist/generators/base/wasp-generator.base.js +710 -0
  46. package/dist/generators/config/config-generator.d.ts +7 -4
  47. package/dist/generators/config/config-generator.d.ts.map +1 -1
  48. package/dist/generators/config/config-generator.js +0 -0
  49. package/dist/generators/config/index.js +600 -0
  50. package/dist/generators/config/wasp-config-generator.d.ts +1 -1
  51. package/dist/generators/config/wasp-config-generator.d.ts.map +1 -1
  52. package/dist/generators/config/wasp-config-generator.js +600 -0
  53. package/dist/generators/crud/crud-generator.d.ts +34 -22
  54. package/dist/generators/crud/crud-generator.d.ts.map +1 -1
  55. package/dist/generators/crud/crud-generator.js +1554 -0
  56. package/dist/generators/crud/index.js +1554 -0
  57. package/dist/generators/crud/schema.d.ts +25 -18
  58. package/dist/generators/crud/schema.d.ts.map +1 -1
  59. package/dist/generators/crud/schema.js +137 -0
  60. package/dist/generators/feature/feature-generator.d.ts +20 -0
  61. package/dist/generators/feature/feature-generator.d.ts.map +1 -0
  62. package/dist/generators/feature/feature-generator.js +769 -0
  63. package/dist/generators/feature/index.d.ts +2 -0
  64. package/dist/generators/feature/index.d.ts.map +1 -0
  65. package/dist/generators/feature/index.js +769 -0
  66. package/dist/generators/feature/schema.d.ts +5 -0
  67. package/dist/generators/feature/schema.d.ts.map +1 -0
  68. package/dist/generators/feature/schema.js +90 -0
  69. package/dist/generators/index.d.ts +1 -1
  70. package/dist/generators/index.d.ts.map +1 -1
  71. package/dist/generators/index.js +2215 -0
  72. package/dist/generators/job/index.js +1103 -0
  73. package/dist/generators/job/job-generator.d.ts +12 -23
  74. package/dist/generators/job/job-generator.d.ts.map +1 -1
  75. package/dist/generators/job/job-generator.js +1103 -0
  76. package/dist/generators/job/schema.d.ts +6 -18
  77. package/dist/generators/job/schema.d.ts.map +1 -1
  78. package/dist/generators/job/schema.js +156 -0
  79. package/dist/generators/query/index.js +1429 -0
  80. package/dist/generators/query/query-generator.d.ts +16 -29
  81. package/dist/generators/query/query-generator.d.ts.map +1 -1
  82. package/dist/generators/query/query-generator.js +1429 -0
  83. package/dist/generators/query/schema.d.ts +11 -23
  84. package/dist/generators/query/schema.d.ts.map +1 -1
  85. package/dist/generators/query/schema.js +119 -0
  86. package/dist/generators/route/index.js +1042 -0
  87. package/dist/generators/route/route-generator.d.ts +11 -20
  88. package/dist/generators/route/route-generator.d.ts.map +1 -1
  89. package/dist/generators/route/route-generator.js +1042 -0
  90. package/dist/generators/route/schema.d.ts +5 -15
  91. package/dist/generators/route/schema.d.ts.map +1 -1
  92. package/dist/generators/route/schema.js +94 -0
  93. package/dist/index.d.ts +2 -10
  94. package/dist/index.d.ts.map +1 -1
  95. package/dist/index.js +1730 -1839
  96. package/dist/plugins/index.d.ts +2 -0
  97. package/dist/plugins/index.d.ts.map +1 -0
  98. package/dist/plugins/wasp.d.ts +3 -0
  99. package/dist/plugins/wasp.d.ts.map +1 -0
  100. package/dist/types/constants.d.ts +4 -22
  101. package/dist/types/constants.d.ts.map +1 -1
  102. package/dist/types/constants.js +8 -2
  103. package/dist/types/index.d.ts +2 -2
  104. package/dist/types/index.d.ts.map +1 -1
  105. package/dist/types/index.js +8 -2
  106. package/dist/wasp-config/app.d.ts +2 -1
  107. package/dist/wasp-config/app.d.ts.map +1 -1
  108. package/dist/wasp-config/app.js +357 -0
  109. package/dist/wasp-config/index.js +357 -0
  110. package/dist/wasp-config/stubs/index.js +48 -0
  111. package/package.json +5 -14
  112. package/dist/generators/args.types.d.ts +0 -85
  113. package/dist/generators/args.types.d.ts.map +0 -1
  114. package/dist/generators/base/entity-generator.base.d.ts.map +0 -1
  115. package/dist/generators/feature-directory/feature-directory-generator.d.ts +0 -18
  116. package/dist/generators/feature-directory/feature-directory-generator.d.ts.map +0 -1
  117. package/dist/generators/feature-directory/index.d.ts +0 -2
  118. package/dist/generators/feature-directory/index.d.ts.map +0 -1
  119. package/dist/generators/feature-directory/schema.d.ts +0 -8
  120. package/dist/generators/feature-directory/schema.d.ts.map +0 -1
  121. package/dist/plugin.d.ts +0 -6
  122. package/dist/plugin.d.ts.map +0 -1
  123. /package/dist/generators/{feature-directory → feature}/templates/feature.wasp.eta +0 -0
@@ -0,0 +1,710 @@
1
+ // src/generators/base/wasp-generator.base.ts
2
+ import {
3
+ GeneratorBase,
4
+ logger as singletonLogger2,
5
+ SwarmConfigManager,
6
+ TemplateResolver
7
+ } from "@ingenyus/swarm";
8
+
9
+ // src/common/filesystem.ts
10
+ import { toPascalCase, validateFeaturePath } from "@ingenyus/swarm";
11
+ import fs from "fs";
12
+ import path from "path";
13
+
14
+ // src/types/constants.ts
15
+ var PLUGIN_NAME = "wasp";
16
+
17
+ // src/common/filesystem.ts
18
+ var realFileSystem = {
19
+ readFileSync: fs.readFileSync,
20
+ writeFileSync: fs.writeFileSync,
21
+ existsSync: fs.existsSync,
22
+ copyFileSync: fs.copyFileSync,
23
+ mkdirSync: fs.mkdirSync,
24
+ readdirSync: fs.readdirSync,
25
+ statSync: fs.statSync
26
+ };
27
+ function findWaspRoot(fileSystem, startDir = process.cwd()) {
28
+ const startDirPath = path.resolve(startDir);
29
+ let currentDirPath = startDirPath;
30
+ const root = path.parse(currentDirPath).root;
31
+ while (currentDirPath !== root) {
32
+ const waspRootPath = path.join(currentDirPath, ".wasproot");
33
+ if (fileSystem.existsSync(waspRootPath)) {
34
+ return currentDirPath;
35
+ }
36
+ currentDirPath = path.dirname(currentDirPath);
37
+ }
38
+ throw new Error(
39
+ `Couldn't find Wasp application root from ${startDirPath}. Make sure you are running this command from within a Wasp project directory.`
40
+ );
41
+ }
42
+ function normaliseFeaturePath(featurePath) {
43
+ const segments = validateFeaturePath(featurePath);
44
+ const normalisedSegments = [];
45
+ for (let i = 0; i < segments.length; i++) {
46
+ const segment = segments[i];
47
+ const previousSegment = normalisedSegments[normalisedSegments.length - 1];
48
+ if (previousSegment !== "features" && segment !== "features") {
49
+ normalisedSegments.push("features");
50
+ }
51
+ normalisedSegments.push(segment);
52
+ }
53
+ return normalisedSegments.join("/");
54
+ }
55
+ function getFeatureDir(fileSystem, featureName) {
56
+ const waspRoot = findWaspRoot(fileSystem);
57
+ const normalisedPath = normaliseFeaturePath(featureName);
58
+ return path.join(waspRoot, "src", normalisedPath);
59
+ }
60
+
61
+ // src/common/plugin.ts
62
+ import path2 from "path";
63
+ import { fileURLToPath } from "url";
64
+
65
+ // src/common/prisma.ts
66
+ import {
67
+ getSchema
68
+ } from "@mrleebo/prisma-ast";
69
+ import fs2 from "fs";
70
+ import path3 from "path";
71
+
72
+ // src/common/schemas.ts
73
+ import { commandRegistry } from "@ingenyus/swarm";
74
+ import { z } from "zod";
75
+ var commonSchemas = {
76
+ feature: z.string().min(1, "Feature is required").meta({
77
+ description: "The feature directory this component will be generated in"
78
+ }).register(commandRegistry, {
79
+ shortName: "f",
80
+ examples: ["root", "auth", "dashboard/users"],
81
+ helpText: "Can be nested as a logical or relative path, e.g. 'dashboard/users' or 'features/dashboard/features/users'"
82
+ }),
83
+ name: z.string().min(1, "Name is required").meta({ description: "The name of the generated component" }).register(commandRegistry, {
84
+ shortName: "n",
85
+ examples: ["users", "task"],
86
+ helpText: "Will be used for generated files and configuration entries"
87
+ }),
88
+ target: z.string().min(1, "Target directory is required").meta({ description: "The target path of the generated directory" }).register(commandRegistry, {
89
+ shortName: "t",
90
+ examples: ["dashboard/users", "features/dashboard/features/users"],
91
+ helpText: "A logical or relative path, e.g. 'dashboard/users' or 'features/dashboard/features/users'"
92
+ }),
93
+ path: z.string().min(1, "Path is required").meta({ description: "The path that this component will be accessible at" }).register(commandRegistry, {
94
+ shortName: "p",
95
+ examples: ["/api/users/:id", "/api/products"],
96
+ helpText: "Supports Express-style placeholders, e.g. '/api/users/:id'"
97
+ }),
98
+ dataType: z.string().min(1, "Data type is required").meta({ description: "The data type/model name for this operation" }).register(commandRegistry, {
99
+ shortName: "d",
100
+ examples: ["User", "Product", "Task"],
101
+ helpText: "The Wasp entity or model name this operation will interact with"
102
+ }),
103
+ entities: z.array(z.string()).optional().meta({
104
+ description: "The Wasp entities that will be available to this component (optional)"
105
+ }).register(commandRegistry, {
106
+ shortName: "e",
107
+ examples: ["User", "User Task"],
108
+ helpText: "An array of Wasp entity names"
109
+ }),
110
+ force: z.boolean().optional().meta({
111
+ description: "Force overwrite of existing files and configuration entries (optional)"
112
+ }).register(commandRegistry, {
113
+ shortName: "F",
114
+ helpText: "CAUTION: Will overwrite existing files and configuration entries with current parameters"
115
+ }),
116
+ auth: z.boolean().optional().meta({
117
+ description: "Require authentication for this component (optional)"
118
+ }).register(commandRegistry, {
119
+ shortName: "a",
120
+ helpText: "Will generate authentication checks"
121
+ })
122
+ };
123
+
124
+ // src/common/templates.ts
125
+ import { toKebabCase } from "@ingenyus/swarm";
126
+ import { Eta } from "eta";
127
+ import path4 from "path";
128
+ var TemplateUtility = class {
129
+ constructor(fileSystem) {
130
+ this.fileSystem = fileSystem;
131
+ }
132
+ processTemplate(templatePath, replacements) {
133
+ const declarations = Object.keys(replacements).map((key) => `${key}=it.${key}`).join(", ");
134
+ const functionHeader = declarations ? `const ${declarations};` : void 0;
135
+ const templateDir = path4.dirname(templatePath);
136
+ const eta = new Eta({
137
+ autoTrim: false,
138
+ autoEscape: false,
139
+ views: templateDir,
140
+ functionHeader
141
+ });
142
+ const templateName = path4.basename(templatePath).replace(/\.eta$/, "");
143
+ if (this.fileSystem.existsSync(templatePath)) {
144
+ return eta.render(templateName, replacements);
145
+ } else {
146
+ const template = this.fileSystem.readFileSync(templatePath, "utf8");
147
+ return eta.renderString(template, replacements);
148
+ }
149
+ }
150
+ /**
151
+ * Helper method to resolve template paths for concrete generators
152
+ * @param relativePath - The relative path to the template file
153
+ * @param generatorName - The name of the generator (e.g., 'api', 'job')
154
+ * @param currentFileUrl - The import.meta.url from the concrete generator class
155
+ * @returns The full path to the template file
156
+ */
157
+ resolveTemplatePath(relativePath, generatorName, currentFileUrl) {
158
+ const generatorDirName = toKebabCase(generatorName);
159
+ const currentFilePath = new URL(currentFileUrl).pathname;
160
+ const currentFileDir = path4.dirname(currentFilePath);
161
+ const currentFileName = path4.basename(currentFilePath);
162
+ const isInstalledPackage = currentFileDir.includes("node_modules") && currentFileDir.endsWith("/dist") && currentFileName === "index.js";
163
+ const startDir = isInstalledPackage ? currentFileDir : path4.dirname(path4.dirname(currentFileDir));
164
+ return path4.join(
165
+ startDir,
166
+ "generators",
167
+ generatorDirName,
168
+ "templates",
169
+ relativePath
170
+ );
171
+ }
172
+ };
173
+
174
+ // src/generators/config/wasp-config-generator.ts
175
+ import {
176
+ handleFatalError,
177
+ parseHelperMethodDefinition,
178
+ logger as singletonLogger
179
+ } from "@ingenyus/swarm";
180
+ import path5 from "path";
181
+ var WaspConfigGenerator = class {
182
+ constructor(logger = singletonLogger, fileSystem = realFileSystem) {
183
+ this.logger = logger;
184
+ this.fileSystem = fileSystem;
185
+ this.templateUtility = new TemplateUtility(fileSystem);
186
+ }
187
+ path = path5;
188
+ templateUtility;
189
+ /**
190
+ * Gets the template path for feature config templates.
191
+ * Feature config templates are located in the feature generator's templates directory.
192
+ * @param templateName - The name of the template file (e.g., 'feature.wasp.eta')
193
+ * @returns The full path to the template file
194
+ */
195
+ getTemplatePath(templateName) {
196
+ return this.templateUtility.resolveTemplatePath(
197
+ templateName,
198
+ "feature",
199
+ import.meta.url
200
+ );
201
+ }
202
+ /**
203
+ * Generate a TypeScript Wasp config file in a feature directory
204
+ * @param featurePath - The feature directory path
205
+ */
206
+ generate(featurePath) {
207
+ const featureDir = getFeatureDir(this.fileSystem, featurePath);
208
+ if (!this.fileSystem.existsSync(featureDir)) {
209
+ this.fileSystem.mkdirSync(featureDir, { recursive: true });
210
+ }
211
+ const templatePath = this.getTemplatePath("feature.wasp.eta");
212
+ if (!this.fileSystem.existsSync(templatePath)) {
213
+ this.logger.error(`Template not found: ${templatePath}`);
214
+ return;
215
+ }
216
+ const configFilePath = path5.join(featureDir, `feature.wasp.ts`);
217
+ if (this.fileSystem.existsSync(configFilePath)) {
218
+ this.logger.warn(`Feature config already exists: ${configFilePath}`);
219
+ return;
220
+ }
221
+ this.fileSystem.copyFileSync(templatePath, configFilePath);
222
+ this.logger.success(`Generated feature config: ${configFilePath}`);
223
+ }
224
+ /**
225
+ * Updates or creates a feature configuration file with a pre-built declaration.
226
+ * @param featurePath - The path to the feature
227
+ * @param declaration - The pre-built declaration string to add or update
228
+ * @returns The updated feature configuration file
229
+ */
230
+ update(featurePath, declaration) {
231
+ const configDir = getFeatureDir(this.fileSystem, featurePath);
232
+ const configFilePath = path5.join(configDir, `feature.wasp.ts`);
233
+ if (!this.fileSystem.existsSync(configFilePath)) {
234
+ const templatePath = this.getTemplatePath("feature.wasp.eta");
235
+ if (!this.fileSystem.existsSync(templatePath)) {
236
+ handleFatalError(`Feature config template not found: ${templatePath}`);
237
+ }
238
+ this.fileSystem.copyFileSync(templatePath, configFilePath);
239
+ }
240
+ let content = this.fileSystem.readFileSync(configFilePath, "utf8");
241
+ content = this.normaliseSemicolons(content);
242
+ const parsed = parseHelperMethodDefinition(declaration);
243
+ if (!parsed) {
244
+ handleFatalError(`Could not parse definition: ${declaration}`);
245
+ return content;
246
+ }
247
+ const { methodName } = parsed;
248
+ const hadExistingDefinitions = this.hasExistingDefinitions(
249
+ content,
250
+ methodName
251
+ );
252
+ content = this.removeExistingDefinition(content, declaration);
253
+ const hasExistingDefinitions = this.hasExistingDefinitions(
254
+ content,
255
+ methodName
256
+ );
257
+ const lines = content.split("\n");
258
+ const configureFunctionStart = lines.findIndex(
259
+ (line) => line.trim().startsWith("export default function")
260
+ );
261
+ if (configureFunctionStart === -1) {
262
+ handleFatalError("Could not find configure function in feature config");
263
+ }
264
+ const appLineIndex = lines.findIndex(
265
+ (line, index) => index > configureFunctionStart && line.trim() === "app"
266
+ );
267
+ if (appLineIndex === -1) {
268
+ const insertIndex = configureFunctionStart + 1;
269
+ const itemsToInsert = [" app"];
270
+ const comment = this.getMethodComment(methodName);
271
+ itemsToInsert.push(` ${comment}`);
272
+ itemsToInsert.push(declaration.trimEnd());
273
+ lines.splice(insertIndex, 0, ...itemsToInsert);
274
+ } else {
275
+ const { insertIndex, addComment } = this.findGroupInsertionPoint(
276
+ lines,
277
+ methodName,
278
+ declaration,
279
+ hadExistingDefinitions || hasExistingDefinitions
280
+ );
281
+ const newLines = this.insertWithSpacing(
282
+ lines,
283
+ declaration,
284
+ insertIndex,
285
+ methodName,
286
+ addComment
287
+ );
288
+ const normalisedContent2 = this.normaliseSemicolons(newLines.join("\n"));
289
+ this.fileSystem.writeFileSync(configFilePath, normalisedContent2);
290
+ return configFilePath;
291
+ }
292
+ const normalisedContent = this.normaliseSemicolons(lines.join("\n"));
293
+ this.fileSystem.writeFileSync(configFilePath, normalisedContent);
294
+ return configFilePath;
295
+ }
296
+ /**
297
+ * Determines the insertion index for a method name based on alphabetical ordering
298
+ * of existing groups in the configuration file.
299
+ * @param groups - Object containing existing method groups
300
+ * @param methodName - The method name to find insertion index for
301
+ * @returns The insertion index for the method name
302
+ */
303
+ getInsertionIndexForMethod(groups, methodName) {
304
+ const existingMethods = Object.keys(groups).filter(
305
+ (method) => groups[method].length > 0
306
+ );
307
+ const allMethods = [...existingMethods, methodName].sort();
308
+ return allMethods.indexOf(methodName);
309
+ }
310
+ /**
311
+ * Gets the comment text for a method type.
312
+ * @param methodName The method name (e.g., 'addApi')
313
+ * @returns The comment text for the method type
314
+ */
315
+ getMethodComment(methodName) {
316
+ const entityName = methodName.startsWith("add") ? methodName.slice(3) : methodName;
317
+ return `// ${entityName} definitions`;
318
+ }
319
+ /**
320
+ * Finds the correct insertion point for a new configuration item.
321
+ * @param lines - Array of file lines
322
+ * @param methodName - The method name (e.g., 'addApi')
323
+ * @param definition - The definition string to parse for item name
324
+ * @returns Object with insertion index and whether to add a comment
325
+ */
326
+ findGroupInsertionPoint(lines, methodName, definition, hasExistingDefinitionsOfType) {
327
+ const appLineIndex = lines.findIndex((line) => line.trim() === "app");
328
+ if (appLineIndex === -1) {
329
+ return { insertIndex: appLineIndex + 1, addComment: false };
330
+ }
331
+ const methodCalls = [];
332
+ for (let i = appLineIndex + 1; i < lines.length; i++) {
333
+ const line = lines[i].trim();
334
+ if (line.startsWith(".") && line.includes("(")) {
335
+ let methodCallContent = line;
336
+ let j = i;
337
+ let closingParenCount = 0;
338
+ let foundClosingParen = false;
339
+ for (let k = 0; k < methodCallContent.length; k++) {
340
+ if (methodCallContent[k] === "(") closingParenCount++;
341
+ if (methodCallContent[k] === ")") closingParenCount--;
342
+ if (closingParenCount === 0 && methodCallContent[k] === ")") {
343
+ foundClosingParen = true;
344
+ break;
345
+ }
346
+ }
347
+ while (!foundClosingParen && j < lines.length - 1) {
348
+ j++;
349
+ methodCallContent += " " + lines[j].trim();
350
+ for (let k = 0; k < lines[j].length; k++) {
351
+ if (lines[j][k] === "(") closingParenCount++;
352
+ if (lines[j][k] === ")") closingParenCount--;
353
+ if (closingParenCount === 0 && lines[j][k] === ")") {
354
+ foundClosingParen = true;
355
+ break;
356
+ }
357
+ }
358
+ }
359
+ const match = methodCallContent.match(
360
+ /\.(\w+)\([^,]+,\s*['"`]([^'"`]+)['"`]/
361
+ );
362
+ if (match) {
363
+ methodCalls.push({
364
+ lineIndex: i,
365
+ endLineIndex: j,
366
+ methodName: match[1],
367
+ itemName: match[2]
368
+ });
369
+ }
370
+ }
371
+ }
372
+ const groups = {};
373
+ methodCalls.forEach((call) => {
374
+ if (!groups[call.methodName]) {
375
+ groups[call.methodName] = [];
376
+ }
377
+ groups[call.methodName].push({
378
+ lineIndex: call.lineIndex,
379
+ endLineIndex: call.endLineIndex,
380
+ itemName: call.itemName
381
+ });
382
+ });
383
+ const targetGroup = groups[methodName] || [];
384
+ if (targetGroup.length === 0) {
385
+ const targetGroupIndex = this.getInsertionIndexForMethod(
386
+ groups,
387
+ methodName
388
+ );
389
+ const existingMethods = Object.keys(groups).filter((method) => groups[method].length > 0).sort();
390
+ for (let i = targetGroupIndex; i < existingMethods.length; i++) {
391
+ const groupMethod = existingMethods[i];
392
+ if (groups[groupMethod] && groups[groupMethod].length > 0) {
393
+ const firstItem = groups[groupMethod][0];
394
+ let insertIndex = firstItem.lineIndex;
395
+ for (let j = firstItem.lineIndex - 1; j > appLineIndex; j--) {
396
+ const line = lines[j].trim();
397
+ if (line.startsWith("//") && line.includes("definitions")) {
398
+ insertIndex = j;
399
+ break;
400
+ } else if (line.startsWith(".") || line === "") {
401
+ continue;
402
+ } else {
403
+ break;
404
+ }
405
+ }
406
+ return { insertIndex, addComment: !hasExistingDefinitionsOfType };
407
+ }
408
+ }
409
+ for (let i = targetGroupIndex - 1; i >= 0; i--) {
410
+ const groupMethod = existingMethods[i];
411
+ if (groups[groupMethod] && groups[groupMethod].length > 0) {
412
+ const lastItem2 = groups[groupMethod][groups[groupMethod].length - 1];
413
+ return {
414
+ insertIndex: lastItem2.endLineIndex + 1,
415
+ addComment: !hasExistingDefinitionsOfType
416
+ };
417
+ }
418
+ }
419
+ return {
420
+ insertIndex: appLineIndex + 1,
421
+ addComment: !hasExistingDefinitionsOfType
422
+ };
423
+ }
424
+ const parsed = parseHelperMethodDefinition(definition);
425
+ if (!parsed) {
426
+ return { insertIndex: appLineIndex + 1, addComment: false };
427
+ }
428
+ const { firstParam: itemName } = parsed;
429
+ for (let i = 0; i < targetGroup.length; i++) {
430
+ if (itemName.localeCompare(targetGroup[i].itemName) < 0) {
431
+ return { insertIndex: targetGroup[i].lineIndex, addComment: false };
432
+ }
433
+ }
434
+ const lastItem = targetGroup[targetGroup.length - 1];
435
+ return { insertIndex: lastItem.endLineIndex + 1, addComment: false };
436
+ }
437
+ /**
438
+ * Inserts a definition with optional comment header.
439
+ * @param lines - Array of file lines
440
+ * @param declaration - The declaration to insert
441
+ * @param insertIndex - The index where to insert
442
+ * @param methodName - The method name for comment generation
443
+ * @param addComment - Whether to add a comment before the declaration
444
+ * @returns The modified lines array
445
+ */
446
+ insertWithSpacing(lines, declaration, insertIndex, methodName, addComment = false) {
447
+ const newLines = [...lines];
448
+ if (addComment) {
449
+ const comment = this.getMethodComment(methodName);
450
+ newLines.splice(insertIndex, 0, ` ${comment}`);
451
+ insertIndex += 1;
452
+ }
453
+ newLines.splice(insertIndex, 0, declaration.trimEnd());
454
+ return newLines;
455
+ }
456
+ /**
457
+ * Checks if there are any existing definitions of a specific type in the content.
458
+ * @param content - The file content to search
459
+ * @param methodName - The method name to check for (e.g., 'addJob', 'addApi')
460
+ * @returns true if there are existing definitions of this type, false otherwise
461
+ */
462
+ hasExistingDefinitions(content, methodName) {
463
+ const lines = content.split("\n");
464
+ for (const line of lines) {
465
+ if (line.trim().startsWith(`.${methodName}(`)) {
466
+ return true;
467
+ }
468
+ }
469
+ return false;
470
+ }
471
+ /**
472
+ * Removes an existing definition from the content by finding the helper method call
473
+ * and removing the entire method call block.
474
+ * @param content - The file content
475
+ * @param definition - The new definition to find the existing one from
476
+ * @returns The content with the existing definition removed
477
+ */
478
+ removeExistingDefinition(content, definition) {
479
+ const parsed = parseHelperMethodDefinition(definition);
480
+ if (!parsed) {
481
+ return content;
482
+ }
483
+ const { methodName, firstParam } = parsed;
484
+ let contentLines = content.split("\n");
485
+ let openingLineIndex = -1;
486
+ for (let i = 0; i < contentLines.length; i++) {
487
+ const line = contentLines[i];
488
+ if (line.trim().startsWith(`.${methodName}(`)) {
489
+ if (firstParam && line.includes(firstParam)) {
490
+ openingLineIndex = i;
491
+ break;
492
+ }
493
+ }
494
+ }
495
+ if (openingLineIndex === -1) {
496
+ return content;
497
+ }
498
+ let closingLineIndex = -1;
499
+ let parenCount = 0;
500
+ let braceCount = 0;
501
+ let foundOpening = false;
502
+ for (let i = openingLineIndex; i < contentLines.length; i++) {
503
+ const line = contentLines[i];
504
+ for (const char of line) {
505
+ if (char === "(") {
506
+ parenCount++;
507
+ foundOpening = true;
508
+ } else if (char === ")") {
509
+ parenCount--;
510
+ if (foundOpening && parenCount === 0 && braceCount === 0) {
511
+ closingLineIndex = i;
512
+ break;
513
+ }
514
+ } else if (char === "{") {
515
+ braceCount++;
516
+ } else if (char === "}") {
517
+ braceCount--;
518
+ }
519
+ }
520
+ if (closingLineIndex !== -1) {
521
+ break;
522
+ }
523
+ }
524
+ if (closingLineIndex === -1) {
525
+ this.logger.warn(
526
+ "Could not find closing parenthesis for existing definition"
527
+ );
528
+ return content;
529
+ }
530
+ contentLines.splice(
531
+ openingLineIndex,
532
+ closingLineIndex - openingLineIndex + 1
533
+ );
534
+ return contentLines.join("\n");
535
+ }
536
+ /**
537
+ * Adds a definition to the content by finding the appropriate place to insert it.
538
+ * @param content - The current file content
539
+ * @param definition - The definition to add
540
+ * @returns The updated content with the new definition
541
+ */
542
+ addDefinitionToContent(content, definition) {
543
+ const lines = content.split("\n");
544
+ const lastLineIndex = lines.length - 1;
545
+ let insertIndex = lastLineIndex;
546
+ for (let i = lastLineIndex; i >= 0; i--) {
547
+ const line = lines[i].trim();
548
+ if (line && !line.startsWith("}")) {
549
+ insertIndex = i;
550
+ break;
551
+ }
552
+ }
553
+ lines.splice(insertIndex + 1, 0, ` ${definition}`);
554
+ return lines.join("\n");
555
+ }
556
+ /**
557
+ * Normalises semicolons in the config file by removing them from method chain calls
558
+ * while preserving them in other contexts (imports, declarations, etc.).
559
+ * @param content - The file content to normalise
560
+ * @returns The normalised content
561
+ */
562
+ normaliseSemicolons(content) {
563
+ const lines = content.split("\n");
564
+ const configureFunctionStart = lines.findIndex(
565
+ (line) => line.trim().startsWith("export default function")
566
+ );
567
+ if (configureFunctionStart === -1) {
568
+ return content;
569
+ }
570
+ const appLineIndex = lines.findIndex(
571
+ (line, index) => index > configureFunctionStart && line.trim().startsWith("app")
572
+ );
573
+ if (appLineIndex === -1) {
574
+ return content;
575
+ }
576
+ let braceCount = 0;
577
+ let functionEndIndex = lines.length - 1;
578
+ for (let i = configureFunctionStart; i < lines.length; i++) {
579
+ const line = lines[i];
580
+ for (const char of line) {
581
+ if (char === "{") braceCount++;
582
+ if (char === "}") {
583
+ braceCount--;
584
+ if (braceCount === 0) {
585
+ functionEndIndex = i;
586
+ break;
587
+ }
588
+ }
589
+ }
590
+ if (braceCount === 0 && i > configureFunctionStart) {
591
+ break;
592
+ }
593
+ }
594
+ let lastMethodCallIndex = -1;
595
+ for (let i = appLineIndex + 1; i < functionEndIndex; i++) {
596
+ const line = lines[i];
597
+ const trimmed = line.trim();
598
+ if ((trimmed.endsWith(")") || trimmed.endsWith(");")) && !trimmed.startsWith("//")) {
599
+ lines[i] = line.replace(/;\s*$/, "");
600
+ lastMethodCallIndex = i;
601
+ }
602
+ }
603
+ if (lastMethodCallIndex !== -1 && !lines[lastMethodCallIndex].trim().endsWith(";")) {
604
+ lines[lastMethodCallIndex] = lines[lastMethodCallIndex] + ";";
605
+ }
606
+ return lines.join("\n");
607
+ }
608
+ };
609
+
610
+ // src/generators/base/wasp-generator.base.ts
611
+ var WaspGeneratorBase = class extends GeneratorBase {
612
+ constructor(fileSystem = realFileSystem, logger = singletonLogger2) {
613
+ super(fileSystem, logger);
614
+ this.fileSystem = fileSystem;
615
+ this.logger = logger;
616
+ this.configGenerator = new WaspConfigGenerator(logger, fileSystem);
617
+ this.templateUtility = new TemplateUtility(fileSystem);
618
+ this.templateResolver = new TemplateResolver(fileSystem);
619
+ }
620
+ configGenerator;
621
+ templateUtility;
622
+ templateResolver;
623
+ swarmConfig;
624
+ configLoaded = false;
625
+ // Plugin name from swarm.config.json
626
+ pluginName = PLUGIN_NAME;
627
+ async loadSwarmConfig() {
628
+ if (this.configLoaded) return;
629
+ const configManager = new SwarmConfigManager();
630
+ this.swarmConfig = await configManager.loadConfig();
631
+ this.configLoaded = true;
632
+ }
633
+ async getCustomTemplateDir() {
634
+ await this.loadSwarmConfig();
635
+ return this.swarmConfig?.templateDirectory;
636
+ }
637
+ /**
638
+ * Resolves template path with override support
639
+ */
640
+ async getTemplatePath(templateName) {
641
+ const defaultPath = this.getDefaultTemplatePath(templateName);
642
+ const customPath = await this.getCustomTemplateDir();
643
+ if (!customPath) {
644
+ return defaultPath;
645
+ }
646
+ const { path: resolvedPath, isCustom } = this.templateResolver.resolveTemplatePath(
647
+ this.pluginName,
648
+ this.name,
649
+ templateName,
650
+ defaultPath,
651
+ customPath
652
+ );
653
+ if (isCustom) {
654
+ this.logger.info(`Using custom template: ${resolvedPath}`);
655
+ }
656
+ return resolvedPath;
657
+ }
658
+ /**
659
+ * Processes a template and writes the result to a file
660
+ */
661
+ async renderTemplateToFile(templateName, replacements, outputPath, readableFileType, force) {
662
+ const templatePath = await this.getTemplatePath(templateName);
663
+ const fileExists = this.checkFileExists(
664
+ outputPath,
665
+ force,
666
+ readableFileType
667
+ );
668
+ const content = this.templateUtility.processTemplate(
669
+ templatePath,
670
+ replacements
671
+ );
672
+ this.writeFile(outputPath, content, readableFileType, fileExists);
673
+ return fileExists;
674
+ }
675
+ /**
676
+ * Generic existence check with force flag handling
677
+ * Consolidates the pattern used in both file and config checks
678
+ */
679
+ checkExistence(exists, itemDescription, force, errorMessage) {
680
+ if (exists && !force) {
681
+ this.logger.error(`${itemDescription}. Use --force to overwrite`);
682
+ throw new Error(errorMessage || itemDescription);
683
+ }
684
+ return exists;
685
+ }
686
+ /**
687
+ * Checks if a file exists and handles force flag logic
688
+ */
689
+ checkFileExists(filePath, force, fileType) {
690
+ const fileExists = this.fileSystem.existsSync(filePath);
691
+ return this.checkExistence(
692
+ fileExists,
693
+ `${fileType} already exists: ${filePath}`,
694
+ force,
695
+ `${fileType} already exists`
696
+ );
697
+ }
698
+ /**
699
+ * Safely writes a file with proper error handling and logging
700
+ */
701
+ writeFile(filePath, content, fileType, fileExists) {
702
+ this.fileSystem.writeFileSync(filePath, content);
703
+ this.logger.success(
704
+ `${fileExists ? "Overwrote" : "Generated"} ${fileType}: ${filePath}`
705
+ );
706
+ }
707
+ };
708
+ export {
709
+ WaspGeneratorBase
710
+ };