@ingenyus/swarm-wasp 0.1.0 → 0.2.1

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 (126) 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.d.ts +0 -1
  7. package/dist/common/index.d.ts.map +1 -1
  8. package/dist/common/index.js +366 -0
  9. package/dist/common/prisma.js +140 -0
  10. package/dist/common/schemas.d.ts +8 -42
  11. package/dist/common/schemas.d.ts.map +1 -1
  12. package/dist/common/schemas.js +54 -0
  13. package/dist/common/templates.js +52 -0
  14. package/dist/generators/action/action-generator.d.ts +16 -29
  15. package/dist/generators/action/action-generator.d.ts.map +1 -1
  16. package/dist/generators/action/action-generator.js +1425 -0
  17. package/dist/generators/action/index.js +1425 -0
  18. package/dist/generators/action/schema.d.ts +11 -23
  19. package/dist/generators/action/schema.d.ts.map +1 -1
  20. package/dist/generators/action/schema.js +115 -0
  21. package/dist/generators/api/api-generator.d.ts +19 -26
  22. package/dist/generators/api/api-generator.d.ts.map +1 -1
  23. package/dist/generators/api/api-generator.js +1104 -0
  24. package/dist/generators/api/index.js +1104 -0
  25. package/dist/generators/api/schema.d.ts +13 -21
  26. package/dist/generators/api/schema.d.ts.map +1 -1
  27. package/dist/generators/api/schema.js +117 -0
  28. package/dist/generators/api-namespace/api-namespace-generator.d.ts +10 -17
  29. package/dist/generators/api-namespace/api-namespace-generator.d.ts.map +1 -1
  30. package/dist/generators/api-namespace/api-namespace-generator.js +1028 -0
  31. package/dist/generators/api-namespace/index.js +1028 -0
  32. package/dist/generators/api-namespace/schema.d.ts +4 -12
  33. package/dist/generators/api-namespace/schema.d.ts.map +1 -1
  34. package/dist/generators/api-namespace/schema.js +89 -0
  35. package/dist/generators/base/{entity-generator.base.d.ts → component-generator.base.d.ts} +9 -9
  36. package/dist/generators/base/component-generator.base.d.ts.map +1 -0
  37. package/dist/generators/base/component-generator.base.js +931 -0
  38. package/dist/generators/base/index.d.ts +1 -1
  39. package/dist/generators/base/index.d.ts.map +1 -1
  40. package/dist/generators/base/index.js +1330 -0
  41. package/dist/generators/base/operation-generator.base.d.ts +12 -3
  42. package/dist/generators/base/operation-generator.base.d.ts.map +1 -1
  43. package/dist/generators/base/operation-generator.base.js +1331 -0
  44. package/dist/generators/base/wasp-generator.base.d.ts +2 -1
  45. package/dist/generators/base/wasp-generator.base.d.ts.map +1 -1
  46. package/dist/generators/base/wasp-generator.base.js +706 -0
  47. package/dist/generators/config/config-generator.d.ts +7 -4
  48. package/dist/generators/config/config-generator.d.ts.map +1 -1
  49. package/dist/generators/config/config-generator.js +0 -0
  50. package/dist/generators/config/index.js +596 -0
  51. package/dist/generators/config/wasp-config-generator.d.ts +1 -1
  52. package/dist/generators/config/wasp-config-generator.d.ts.map +1 -1
  53. package/dist/generators/config/wasp-config-generator.js +596 -0
  54. package/dist/generators/crud/crud-generator.d.ts +34 -22
  55. package/dist/generators/crud/crud-generator.d.ts.map +1 -1
  56. package/dist/generators/crud/crud-generator.js +1550 -0
  57. package/dist/generators/crud/index.js +1550 -0
  58. package/dist/generators/crud/schema.d.ts +25 -18
  59. package/dist/generators/crud/schema.d.ts.map +1 -1
  60. package/dist/generators/crud/schema.js +133 -0
  61. package/dist/generators/feature/feature-generator.d.ts +20 -0
  62. package/dist/generators/feature/feature-generator.d.ts.map +1 -0
  63. package/dist/generators/feature/feature-generator.js +765 -0
  64. package/dist/generators/feature/index.d.ts +2 -0
  65. package/dist/generators/feature/index.d.ts.map +1 -0
  66. package/dist/generators/feature/index.js +765 -0
  67. package/dist/generators/feature/schema.d.ts +5 -0
  68. package/dist/generators/feature/schema.d.ts.map +1 -0
  69. package/dist/generators/feature/schema.js +86 -0
  70. package/dist/generators/index.d.ts +1 -1
  71. package/dist/generators/index.d.ts.map +1 -1
  72. package/dist/generators/index.js +2211 -0
  73. package/dist/generators/job/index.js +1099 -0
  74. package/dist/generators/job/job-generator.d.ts +12 -23
  75. package/dist/generators/job/job-generator.d.ts.map +1 -1
  76. package/dist/generators/job/job-generator.js +1099 -0
  77. package/dist/generators/job/schema.d.ts +6 -18
  78. package/dist/generators/job/schema.d.ts.map +1 -1
  79. package/dist/generators/job/schema.js +152 -0
  80. package/dist/generators/query/index.js +1425 -0
  81. package/dist/generators/query/query-generator.d.ts +16 -29
  82. package/dist/generators/query/query-generator.d.ts.map +1 -1
  83. package/dist/generators/query/query-generator.js +1425 -0
  84. package/dist/generators/query/schema.d.ts +11 -23
  85. package/dist/generators/query/schema.d.ts.map +1 -1
  86. package/dist/generators/query/schema.js +115 -0
  87. package/dist/generators/route/index.js +1038 -0
  88. package/dist/generators/route/route-generator.d.ts +11 -20
  89. package/dist/generators/route/route-generator.d.ts.map +1 -1
  90. package/dist/generators/route/route-generator.js +1038 -0
  91. package/dist/generators/route/schema.d.ts +5 -15
  92. package/dist/generators/route/schema.d.ts.map +1 -1
  93. package/dist/generators/route/schema.js +90 -0
  94. package/dist/index.d.ts +2 -10
  95. package/dist/index.d.ts.map +1 -1
  96. package/dist/index.js +1980 -2115
  97. package/dist/plugins/index.d.ts +2 -0
  98. package/dist/plugins/index.d.ts.map +1 -0
  99. package/dist/plugins/wasp.d.ts +3 -0
  100. package/dist/plugins/wasp.d.ts.map +1 -0
  101. package/dist/types/constants.d.ts +4 -22
  102. package/dist/types/constants.d.ts.map +1 -1
  103. package/dist/types/constants.js +8 -2
  104. package/dist/types/index.d.ts +2 -2
  105. package/dist/types/index.d.ts.map +1 -1
  106. package/dist/types/index.js +8 -2
  107. package/dist/wasp-config/app.d.ts +2 -1
  108. package/dist/wasp-config/app.d.ts.map +1 -1
  109. package/dist/wasp-config/app.js +357 -0
  110. package/dist/wasp-config/index.js +357 -0
  111. package/dist/wasp-config/stubs/index.js +48 -0
  112. package/package.json +5 -14
  113. package/dist/common/plugin.d.ts +0 -2
  114. package/dist/common/plugin.d.ts.map +0 -1
  115. package/dist/generators/args.types.d.ts +0 -85
  116. package/dist/generators/args.types.d.ts.map +0 -1
  117. package/dist/generators/base/entity-generator.base.d.ts.map +0 -1
  118. package/dist/generators/feature-directory/feature-directory-generator.d.ts +0 -18
  119. package/dist/generators/feature-directory/feature-directory-generator.d.ts.map +0 -1
  120. package/dist/generators/feature-directory/index.d.ts +0 -2
  121. package/dist/generators/feature-directory/index.d.ts.map +0 -1
  122. package/dist/generators/feature-directory/schema.d.ts +0 -8
  123. package/dist/generators/feature-directory/schema.d.ts.map +0 -1
  124. package/dist/plugin.d.ts +0 -6
  125. package/dist/plugin.d.ts.map +0 -1
  126. /package/dist/generators/{feature-directory → feature}/templates/feature.wasp.eta +0 -0
@@ -0,0 +1,1331 @@
1
+ // src/generators/base/operation-generator.base.ts
2
+ import {
3
+ capitalise,
4
+ getPlural,
5
+ handleFatalError as handleFatalError3,
6
+ toPascalCase as toPascalCase2
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
+ var OPERATION_TYPES = ["query", "action"];
17
+ var OPERATIONS = {
18
+ CREATE: "create",
19
+ UPDATE: "update",
20
+ DELETE: "delete",
21
+ GET: "get",
22
+ GETALL: "getAll",
23
+ GETFILTERED: "getFiltered"
24
+ };
25
+ var TYPE_DIRECTORIES = {
26
+ component: "client/components",
27
+ hook: "client/hooks",
28
+ layout: "client/layouts",
29
+ page: "client/pages",
30
+ util: "client/utils",
31
+ action: "server/actions",
32
+ query: "server/queries",
33
+ middleware: "server/middleware",
34
+ job: "server/jobs",
35
+ api: "server/apis",
36
+ crud: "server/cruds",
37
+ type: "types"
38
+ };
39
+
40
+ // src/common/filesystem.ts
41
+ var realFileSystem = {
42
+ readFileSync: fs.readFileSync,
43
+ writeFileSync: fs.writeFileSync,
44
+ existsSync: fs.existsSync,
45
+ copyFileSync: fs.copyFileSync,
46
+ mkdirSync: fs.mkdirSync,
47
+ readdirSync: fs.readdirSync,
48
+ statSync: fs.statSync
49
+ };
50
+ function findWaspRoot(fileSystem, startDir = process.cwd()) {
51
+ const startDirPath = path.resolve(startDir);
52
+ let currentDirPath = startDirPath;
53
+ const root = path.parse(currentDirPath).root;
54
+ while (currentDirPath !== root) {
55
+ const waspRootPath = path.join(currentDirPath, ".wasproot");
56
+ if (fileSystem.existsSync(waspRootPath)) {
57
+ return currentDirPath;
58
+ }
59
+ currentDirPath = path.dirname(currentDirPath);
60
+ }
61
+ throw new Error(
62
+ `Couldn't find Wasp application root from ${startDirPath}. Make sure you are running this command from within a Wasp project directory.`
63
+ );
64
+ }
65
+ function copyDirectory(fileSystem, src, dest) {
66
+ if (!fileSystem.existsSync(dest)) {
67
+ fileSystem.mkdirSync(dest, { recursive: true });
68
+ }
69
+ const entries = fileSystem.readdirSync(src, { withFileTypes: true });
70
+ for (const entry of entries) {
71
+ const srcPath = path.join(src, entry.name);
72
+ const destPath = path.join(dest, entry.name);
73
+ if (entry.isDirectory()) {
74
+ copyDirectory(fileSystem, srcPath, destPath);
75
+ } else {
76
+ fileSystem.copyFileSync(srcPath, destPath);
77
+ }
78
+ }
79
+ }
80
+ function ensureDirectoryExists(fileSystem, dir) {
81
+ if (!fileSystem.existsSync(dir)) {
82
+ fileSystem.mkdirSync(dir, { recursive: true });
83
+ }
84
+ }
85
+ function normaliseFeaturePath(featurePath) {
86
+ const segments = validateFeaturePath(featurePath);
87
+ const normalisedSegments = [];
88
+ for (let i = 0; i < segments.length; i++) {
89
+ const segment = segments[i];
90
+ const previousSegment = normalisedSegments[normalisedSegments.length - 1];
91
+ if (previousSegment !== "features" && segment !== "features") {
92
+ normalisedSegments.push("features");
93
+ }
94
+ normalisedSegments.push(segment);
95
+ }
96
+ return normalisedSegments.join("/");
97
+ }
98
+ function getFeatureDir(fileSystem, featureName) {
99
+ const waspRoot = findWaspRoot(fileSystem);
100
+ const normalisedPath = normaliseFeaturePath(featureName);
101
+ return path.join(waspRoot, "src", normalisedPath);
102
+ }
103
+ function getFeatureImportPath(featurePath) {
104
+ const segments = validateFeaturePath(featurePath);
105
+ return segments.join("/");
106
+ }
107
+
108
+ // src/common/prisma.ts
109
+ import {
110
+ getSchema
111
+ } from "@mrleebo/prisma-ast";
112
+ import fs2 from "fs";
113
+ import path2 from "path";
114
+ async function getEntityMetadata(modelName) {
115
+ try {
116
+ const schemaPath = path2.join(process.cwd(), "schema.prisma");
117
+ const schemaContent = fs2.readFileSync(schemaPath, "utf8");
118
+ const schema2 = getSchema(schemaContent);
119
+ const model = schema2.list?.find(
120
+ (m) => m.type === "model" && m.name === modelName
121
+ );
122
+ if (!model || model.type !== "model") {
123
+ throw new Error(`Model ${modelName} not found in schema`);
124
+ }
125
+ const compositeIdAttr = (model.properties || []).find(
126
+ (item) => item.type === "attribute" && item.kind === "object" && item.name === "id"
127
+ );
128
+ let compositeIdFields = [];
129
+ if (compositeIdAttr?.args?.[0]) {
130
+ const arg = compositeIdAttr.args[0];
131
+ if (typeof arg.value === "object" && arg.value !== null && "type" in arg.value && arg.value.type === "array" && "args" in arg.value) {
132
+ compositeIdFields = arg.value.args;
133
+ }
134
+ }
135
+ const fields = (model.properties || []).filter(
136
+ (item) => item.type === "field" && !item.array && !item.attributes?.some((attr) => attr.name === "relation")
137
+ ).map((field) => {
138
+ const fieldType = typeof field.fieldType === "string" ? field.fieldType : field.fieldType.name;
139
+ const tsType = getPrismaToTsType(fieldType);
140
+ const isRequired = !field.optional;
141
+ const isId = field.attributes?.some((attr) => attr.name === "id") || compositeIdFields.includes(field.name);
142
+ const isUnique = field.attributes?.some((attr) => attr.name === "unique") || false;
143
+ const hasDefaultValue = field.attributes?.some((attr) => attr.name === "default") || false;
144
+ const isUpdatedAt = field.attributes?.some((attr) => attr.name === "updatedAt") || false;
145
+ const isGenerated = field.attributes?.some((attr) => attr.name === "map") || false;
146
+ return {
147
+ name: field.name,
148
+ type: fieldType,
149
+ tsType,
150
+ isRequired,
151
+ isId,
152
+ isUnique,
153
+ hasDefaultValue,
154
+ isGenerated,
155
+ isUpdatedAt
156
+ };
157
+ });
158
+ return {
159
+ name: modelName,
160
+ fields
161
+ };
162
+ } catch (error) {
163
+ throw new Error(
164
+ `Failed to get entity metadata for ${modelName}: ${error instanceof Error ? error.message : String(error)}`
165
+ );
166
+ }
167
+ }
168
+ function getIdFields(model) {
169
+ const idFields = model.fields.filter((f) => f.isId).map((f) => f.name);
170
+ if (idFields.length === 0) {
171
+ throw new Error(`No ID field found for model ${model.name}`);
172
+ }
173
+ return idFields;
174
+ }
175
+ function getRequiredFields(model) {
176
+ return model.fields.filter(
177
+ (f) => f.isRequired && !f.hasDefaultValue && !f.isGenerated && !f.isUpdatedAt
178
+ ).map((f) => f.name);
179
+ }
180
+ function getOptionalFields(model) {
181
+ return model.fields.filter(
182
+ (field) => (field.hasDefaultValue && field.type !== "DateTime" || !field.isRequired) && !field.isId && !field.isGenerated && !field.isUpdatedAt
183
+ ).map((field) => field.name);
184
+ }
185
+ function getJsonFields(model) {
186
+ return model.fields.filter((f) => f.type === "Json").map((f) => f.name);
187
+ }
188
+ function generateJsonTypeHandling(jsonFields) {
189
+ if (jsonFields.length === 0) return "";
190
+ const assignments = jsonFields.map(
191
+ (field) => ` ${field}: (data.${field} as Prisma.JsonValue) || Prisma.JsonNull`
192
+ ).join(",\n");
193
+ return `,
194
+ ${assignments}`;
195
+ }
196
+ function needsPrismaImport(model) {
197
+ return model.fields.some((f) => f.type === "Json" || f.type === "Decimal");
198
+ }
199
+ function generatePickType(modelName, fields, allFields) {
200
+ if (fields.length === 0) return "";
201
+ if (fields.length === allFields.length) return modelName;
202
+ const fieldUnion = fields.map((f) => `"${f}"`).join(" | ");
203
+ return `Pick<${modelName}, ${fieldUnion}>`;
204
+ }
205
+ function generateOmitType(modelName, fields, allFields) {
206
+ if (fields.length === 0) return modelName;
207
+ if (fields.length === allFields.length) return "";
208
+ const fieldUnion = fields.map((f) => `"${f}"`).join(" | ");
209
+ return `Omit<${modelName}, ${fieldUnion}>`;
210
+ }
211
+ function generatePartialType(typeString) {
212
+ if (!typeString) return "";
213
+ return `Partial<${typeString}>`;
214
+ }
215
+ function generateIntersectionType(type1, type2) {
216
+ if (!type1 && !type2) return "";
217
+ if (!type1) return type2;
218
+ if (!type2) return type1;
219
+ return `${type1} & ${type2}`;
220
+ }
221
+ function getPrismaToTsType(type) {
222
+ const typeMap = {
223
+ String: "string",
224
+ Int: "number",
225
+ Float: "number",
226
+ Boolean: "boolean",
227
+ DateTime: "Date",
228
+ Json: "Prisma.JsonValue",
229
+ BigInt: "bigint",
230
+ Decimal: "Prisma.Decimal",
231
+ Bytes: "Buffer"
232
+ };
233
+ return typeMap[type] || type;
234
+ }
235
+
236
+ // src/common/schemas.ts
237
+ import { commandRegistry } from "@ingenyus/swarm";
238
+ import { z } from "zod";
239
+ var commonSchemas = {
240
+ feature: z.string().min(1, "Feature is required").meta({
241
+ description: "The feature directory this component will be generated in"
242
+ }).register(commandRegistry, {
243
+ shortName: "f",
244
+ examples: ["root", "auth", "dashboard/users"],
245
+ helpText: "Can be nested as a logical or relative path, e.g. 'dashboard/users' or 'features/dashboard/features/users'"
246
+ }),
247
+ name: z.string().min(1, "Name is required").meta({ description: "The name of the generated component" }).register(commandRegistry, {
248
+ shortName: "n",
249
+ examples: ["users", "task"],
250
+ helpText: "Will be used for generated files and configuration entries"
251
+ }),
252
+ target: z.string().min(1, "Target directory is required").meta({ description: "The target path of the generated directory" }).register(commandRegistry, {
253
+ shortName: "t",
254
+ examples: ["dashboard/users", "features/dashboard/features/users"],
255
+ helpText: "A logical or relative path, e.g. 'dashboard/users' or 'features/dashboard/features/users'"
256
+ }),
257
+ path: z.string().min(1, "Path is required").meta({ description: "The path that this component will be accessible at" }).register(commandRegistry, {
258
+ shortName: "p",
259
+ examples: ["/api/users/:id", "/api/products"],
260
+ helpText: "Supports Express-style placeholders, e.g. '/api/users/:id'"
261
+ }),
262
+ dataType: z.string().min(1, "Data type is required").meta({ description: "The data type/model name for this operation" }).register(commandRegistry, {
263
+ shortName: "d",
264
+ examples: ["User", "Product", "Task"],
265
+ helpText: "The Wasp entity or model name this operation will interact with"
266
+ }),
267
+ entities: z.array(z.string()).optional().meta({
268
+ description: "The Wasp entities that will be available to this component (optional)"
269
+ }).register(commandRegistry, {
270
+ shortName: "e",
271
+ examples: ["User", "User Task"],
272
+ helpText: "An array of Wasp entity names"
273
+ }),
274
+ force: z.boolean().optional().meta({
275
+ description: "Force overwrite of existing files and configuration entries (optional)"
276
+ }).register(commandRegistry, {
277
+ shortName: "F",
278
+ helpText: "CAUTION: Will overwrite existing files and configuration entries with current parameters"
279
+ }),
280
+ auth: z.boolean().optional().meta({
281
+ description: "Require authentication for this component (optional)"
282
+ }).register(commandRegistry, {
283
+ shortName: "a",
284
+ helpText: "Will generate authentication checks"
285
+ })
286
+ };
287
+
288
+ // src/common/templates.ts
289
+ import { toKebabCase } from "@ingenyus/swarm";
290
+ import { Eta } from "eta";
291
+ import path3 from "path";
292
+ var TemplateUtility = class {
293
+ constructor(fileSystem) {
294
+ this.fileSystem = fileSystem;
295
+ }
296
+ processTemplate(templatePath, replacements) {
297
+ const declarations = Object.keys(replacements).map((key) => `${key}=it.${key}`).join(", ");
298
+ const functionHeader = declarations ? `const ${declarations};` : void 0;
299
+ const templateDir = path3.dirname(templatePath);
300
+ const eta = new Eta({
301
+ autoTrim: false,
302
+ autoEscape: false,
303
+ views: templateDir,
304
+ functionHeader
305
+ });
306
+ const templateName = path3.basename(templatePath).replace(/\.eta$/, "");
307
+ if (this.fileSystem.existsSync(templatePath)) {
308
+ return eta.render(templateName, replacements);
309
+ } else {
310
+ const template = this.fileSystem.readFileSync(templatePath, "utf8");
311
+ return eta.renderString(template, replacements);
312
+ }
313
+ }
314
+ /**
315
+ * Helper method to resolve template paths for concrete generators
316
+ * @param relativePath - The relative path to the template file
317
+ * @param generatorName - The name of the generator (e.g., 'api', 'job')
318
+ * @param currentFileUrl - The import.meta.url from the concrete generator class
319
+ * @returns The full path to the template file
320
+ */
321
+ resolveTemplatePath(relativePath, generatorName, currentFileUrl) {
322
+ const generatorDirName = toKebabCase(generatorName);
323
+ const currentFilePath = new URL(currentFileUrl).pathname;
324
+ const currentFileDir = path3.dirname(currentFilePath);
325
+ const currentFileName = path3.basename(currentFilePath);
326
+ const isInstalledPackage = currentFileDir.includes("node_modules") && currentFileDir.endsWith("/dist") && currentFileName === "index.js";
327
+ const startDir = isInstalledPackage ? currentFileDir : path3.dirname(path3.dirname(currentFileDir));
328
+ return path3.join(
329
+ startDir,
330
+ "generators",
331
+ generatorDirName,
332
+ "templates",
333
+ relativePath
334
+ );
335
+ }
336
+ };
337
+
338
+ // src/generators/base/component-generator.base.ts
339
+ import {
340
+ hasHelperMethodCall,
341
+ logger as singletonLogger4,
342
+ toCamelCase,
343
+ toKebabCase as toKebabCase2,
344
+ validateFeaturePath as validateFeaturePath3
345
+ } from "@ingenyus/swarm";
346
+ import path6 from "path";
347
+
348
+ // src/generators/feature/feature-generator.ts
349
+ import {
350
+ handleFatalError as handleFatalError2,
351
+ logger as singletonLogger3,
352
+ validateFeaturePath as validateFeaturePath2
353
+ } from "@ingenyus/swarm";
354
+ import path5 from "path";
355
+
356
+ // src/generators/base/wasp-generator.base.ts
357
+ import {
358
+ GeneratorBase,
359
+ logger as singletonLogger2,
360
+ SwarmConfigManager,
361
+ TemplateResolver
362
+ } from "@ingenyus/swarm";
363
+
364
+ // src/generators/config/wasp-config-generator.ts
365
+ import {
366
+ handleFatalError,
367
+ parseHelperMethodDefinition,
368
+ logger as singletonLogger
369
+ } from "@ingenyus/swarm";
370
+ import path4 from "path";
371
+ var WaspConfigGenerator = class {
372
+ constructor(logger = singletonLogger, fileSystem = realFileSystem) {
373
+ this.logger = logger;
374
+ this.fileSystem = fileSystem;
375
+ this.templateUtility = new TemplateUtility(fileSystem);
376
+ }
377
+ path = path4;
378
+ templateUtility;
379
+ /**
380
+ * Gets the template path for feature config templates.
381
+ * Feature config templates are located in the feature generator's templates directory.
382
+ * @param templateName - The name of the template file (e.g., 'feature.wasp.eta')
383
+ * @returns The full path to the template file
384
+ */
385
+ getTemplatePath(templateName) {
386
+ return this.templateUtility.resolveTemplatePath(
387
+ templateName,
388
+ "feature",
389
+ import.meta.url
390
+ );
391
+ }
392
+ /**
393
+ * Generate a TypeScript Wasp config file in a feature directory
394
+ * @param featurePath - The feature directory path
395
+ */
396
+ generate(featurePath) {
397
+ const featureDir = getFeatureDir(this.fileSystem, featurePath);
398
+ if (!this.fileSystem.existsSync(featureDir)) {
399
+ this.fileSystem.mkdirSync(featureDir, { recursive: true });
400
+ }
401
+ const templatePath = this.getTemplatePath("feature.wasp.eta");
402
+ if (!this.fileSystem.existsSync(templatePath)) {
403
+ this.logger.error(`Template not found: ${templatePath}`);
404
+ return;
405
+ }
406
+ const configFilePath = path4.join(featureDir, `feature.wasp.ts`);
407
+ if (this.fileSystem.existsSync(configFilePath)) {
408
+ this.logger.warn(`Feature config already exists: ${configFilePath}`);
409
+ return;
410
+ }
411
+ this.fileSystem.copyFileSync(templatePath, configFilePath);
412
+ this.logger.success(`Generated feature config: ${configFilePath}`);
413
+ }
414
+ /**
415
+ * Updates or creates a feature configuration file with a pre-built declaration.
416
+ * @param featurePath - The path to the feature
417
+ * @param declaration - The pre-built declaration string to add or update
418
+ * @returns The updated feature configuration file
419
+ */
420
+ update(featurePath, declaration) {
421
+ const configDir = getFeatureDir(this.fileSystem, featurePath);
422
+ const configFilePath = path4.join(configDir, `feature.wasp.ts`);
423
+ if (!this.fileSystem.existsSync(configFilePath)) {
424
+ const templatePath = this.getTemplatePath("feature.wasp.eta");
425
+ if (!this.fileSystem.existsSync(templatePath)) {
426
+ handleFatalError(`Feature config template not found: ${templatePath}`);
427
+ }
428
+ this.fileSystem.copyFileSync(templatePath, configFilePath);
429
+ }
430
+ let content = this.fileSystem.readFileSync(configFilePath, "utf8");
431
+ content = this.normaliseSemicolons(content);
432
+ const parsed = parseHelperMethodDefinition(declaration);
433
+ if (!parsed) {
434
+ handleFatalError(`Could not parse definition: ${declaration}`);
435
+ return content;
436
+ }
437
+ const { methodName } = parsed;
438
+ const hadExistingDefinitions = this.hasExistingDefinitions(
439
+ content,
440
+ methodName
441
+ );
442
+ content = this.removeExistingDefinition(content, declaration);
443
+ const hasExistingDefinitions = this.hasExistingDefinitions(
444
+ content,
445
+ methodName
446
+ );
447
+ const lines = content.split("\n");
448
+ const configureFunctionStart = lines.findIndex(
449
+ (line) => line.trim().startsWith("export default function")
450
+ );
451
+ if (configureFunctionStart === -1) {
452
+ handleFatalError("Could not find configure function in feature config");
453
+ }
454
+ const appLineIndex = lines.findIndex(
455
+ (line, index) => index > configureFunctionStart && line.trim() === "app"
456
+ );
457
+ if (appLineIndex === -1) {
458
+ const insertIndex = configureFunctionStart + 1;
459
+ const itemsToInsert = [" app"];
460
+ const comment = this.getMethodComment(methodName);
461
+ itemsToInsert.push(` ${comment}`);
462
+ itemsToInsert.push(declaration.trimEnd());
463
+ lines.splice(insertIndex, 0, ...itemsToInsert);
464
+ } else {
465
+ const { insertIndex, addComment } = this.findGroupInsertionPoint(
466
+ lines,
467
+ methodName,
468
+ declaration,
469
+ hadExistingDefinitions || hasExistingDefinitions
470
+ );
471
+ const newLines = this.insertWithSpacing(
472
+ lines,
473
+ declaration,
474
+ insertIndex,
475
+ methodName,
476
+ addComment
477
+ );
478
+ const normalisedContent2 = this.normaliseSemicolons(newLines.join("\n"));
479
+ this.fileSystem.writeFileSync(configFilePath, normalisedContent2);
480
+ return configFilePath;
481
+ }
482
+ const normalisedContent = this.normaliseSemicolons(lines.join("\n"));
483
+ this.fileSystem.writeFileSync(configFilePath, normalisedContent);
484
+ return configFilePath;
485
+ }
486
+ /**
487
+ * Determines the insertion index for a method name based on alphabetical ordering
488
+ * of existing groups in the configuration file.
489
+ * @param groups - Object containing existing method groups
490
+ * @param methodName - The method name to find insertion index for
491
+ * @returns The insertion index for the method name
492
+ */
493
+ getInsertionIndexForMethod(groups, methodName) {
494
+ const existingMethods = Object.keys(groups).filter(
495
+ (method) => groups[method].length > 0
496
+ );
497
+ const allMethods = [...existingMethods, methodName].sort();
498
+ return allMethods.indexOf(methodName);
499
+ }
500
+ /**
501
+ * Gets the comment text for a method type.
502
+ * @param methodName The method name (e.g., 'addApi')
503
+ * @returns The comment text for the method type
504
+ */
505
+ getMethodComment(methodName) {
506
+ const entityName = methodName.startsWith("add") ? methodName.slice(3) : methodName;
507
+ return `// ${entityName} definitions`;
508
+ }
509
+ /**
510
+ * Finds the correct insertion point for a new configuration item.
511
+ * @param lines - Array of file lines
512
+ * @param methodName - The method name (e.g., 'addApi')
513
+ * @param definition - The definition string to parse for item name
514
+ * @returns Object with insertion index and whether to add a comment
515
+ */
516
+ findGroupInsertionPoint(lines, methodName, definition, hasExistingDefinitionsOfType) {
517
+ const appLineIndex = lines.findIndex((line) => line.trim() === "app");
518
+ if (appLineIndex === -1) {
519
+ return { insertIndex: appLineIndex + 1, addComment: false };
520
+ }
521
+ const methodCalls = [];
522
+ for (let i = appLineIndex + 1; i < lines.length; i++) {
523
+ const line = lines[i].trim();
524
+ if (line.startsWith(".") && line.includes("(")) {
525
+ let methodCallContent = line;
526
+ let j = i;
527
+ let closingParenCount = 0;
528
+ let foundClosingParen = false;
529
+ for (let k = 0; k < methodCallContent.length; k++) {
530
+ if (methodCallContent[k] === "(") closingParenCount++;
531
+ if (methodCallContent[k] === ")") closingParenCount--;
532
+ if (closingParenCount === 0 && methodCallContent[k] === ")") {
533
+ foundClosingParen = true;
534
+ break;
535
+ }
536
+ }
537
+ while (!foundClosingParen && j < lines.length - 1) {
538
+ j++;
539
+ methodCallContent += " " + lines[j].trim();
540
+ for (let k = 0; k < lines[j].length; k++) {
541
+ if (lines[j][k] === "(") closingParenCount++;
542
+ if (lines[j][k] === ")") closingParenCount--;
543
+ if (closingParenCount === 0 && lines[j][k] === ")") {
544
+ foundClosingParen = true;
545
+ break;
546
+ }
547
+ }
548
+ }
549
+ const match = methodCallContent.match(
550
+ /\.(\w+)\([^,]+,\s*['"`]([^'"`]+)['"`]/
551
+ );
552
+ if (match) {
553
+ methodCalls.push({
554
+ lineIndex: i,
555
+ endLineIndex: j,
556
+ methodName: match[1],
557
+ itemName: match[2]
558
+ });
559
+ }
560
+ }
561
+ }
562
+ const groups = {};
563
+ methodCalls.forEach((call) => {
564
+ if (!groups[call.methodName]) {
565
+ groups[call.methodName] = [];
566
+ }
567
+ groups[call.methodName].push({
568
+ lineIndex: call.lineIndex,
569
+ endLineIndex: call.endLineIndex,
570
+ itemName: call.itemName
571
+ });
572
+ });
573
+ const targetGroup = groups[methodName] || [];
574
+ if (targetGroup.length === 0) {
575
+ const targetGroupIndex = this.getInsertionIndexForMethod(
576
+ groups,
577
+ methodName
578
+ );
579
+ const existingMethods = Object.keys(groups).filter((method) => groups[method].length > 0).sort();
580
+ for (let i = targetGroupIndex; i < existingMethods.length; i++) {
581
+ const groupMethod = existingMethods[i];
582
+ if (groups[groupMethod] && groups[groupMethod].length > 0) {
583
+ const firstItem = groups[groupMethod][0];
584
+ let insertIndex = firstItem.lineIndex;
585
+ for (let j = firstItem.lineIndex - 1; j > appLineIndex; j--) {
586
+ const line = lines[j].trim();
587
+ if (line.startsWith("//") && line.includes("definitions")) {
588
+ insertIndex = j;
589
+ break;
590
+ } else if (line.startsWith(".") || line === "") {
591
+ continue;
592
+ } else {
593
+ break;
594
+ }
595
+ }
596
+ return { insertIndex, addComment: !hasExistingDefinitionsOfType };
597
+ }
598
+ }
599
+ for (let i = targetGroupIndex - 1; i >= 0; i--) {
600
+ const groupMethod = existingMethods[i];
601
+ if (groups[groupMethod] && groups[groupMethod].length > 0) {
602
+ const lastItem2 = groups[groupMethod][groups[groupMethod].length - 1];
603
+ return {
604
+ insertIndex: lastItem2.endLineIndex + 1,
605
+ addComment: !hasExistingDefinitionsOfType
606
+ };
607
+ }
608
+ }
609
+ return {
610
+ insertIndex: appLineIndex + 1,
611
+ addComment: !hasExistingDefinitionsOfType
612
+ };
613
+ }
614
+ const parsed = parseHelperMethodDefinition(definition);
615
+ if (!parsed) {
616
+ return { insertIndex: appLineIndex + 1, addComment: false };
617
+ }
618
+ const { firstParam: itemName } = parsed;
619
+ for (let i = 0; i < targetGroup.length; i++) {
620
+ if (itemName.localeCompare(targetGroup[i].itemName) < 0) {
621
+ return { insertIndex: targetGroup[i].lineIndex, addComment: false };
622
+ }
623
+ }
624
+ const lastItem = targetGroup[targetGroup.length - 1];
625
+ return { insertIndex: lastItem.endLineIndex + 1, addComment: false };
626
+ }
627
+ /**
628
+ * Inserts a definition with optional comment header.
629
+ * @param lines - Array of file lines
630
+ * @param declaration - The declaration to insert
631
+ * @param insertIndex - The index where to insert
632
+ * @param methodName - The method name for comment generation
633
+ * @param addComment - Whether to add a comment before the declaration
634
+ * @returns The modified lines array
635
+ */
636
+ insertWithSpacing(lines, declaration, insertIndex, methodName, addComment = false) {
637
+ const newLines = [...lines];
638
+ if (addComment) {
639
+ const comment = this.getMethodComment(methodName);
640
+ newLines.splice(insertIndex, 0, ` ${comment}`);
641
+ insertIndex += 1;
642
+ }
643
+ newLines.splice(insertIndex, 0, declaration.trimEnd());
644
+ return newLines;
645
+ }
646
+ /**
647
+ * Checks if there are any existing definitions of a specific type in the content.
648
+ * @param content - The file content to search
649
+ * @param methodName - The method name to check for (e.g., 'addJob', 'addApi')
650
+ * @returns true if there are existing definitions of this type, false otherwise
651
+ */
652
+ hasExistingDefinitions(content, methodName) {
653
+ const lines = content.split("\n");
654
+ for (const line of lines) {
655
+ if (line.trim().startsWith(`.${methodName}(`)) {
656
+ return true;
657
+ }
658
+ }
659
+ return false;
660
+ }
661
+ /**
662
+ * Removes an existing definition from the content by finding the helper method call
663
+ * and removing the entire method call block.
664
+ * @param content - The file content
665
+ * @param definition - The new definition to find the existing one from
666
+ * @returns The content with the existing definition removed
667
+ */
668
+ removeExistingDefinition(content, definition) {
669
+ const parsed = parseHelperMethodDefinition(definition);
670
+ if (!parsed) {
671
+ return content;
672
+ }
673
+ const { methodName, firstParam } = parsed;
674
+ let contentLines = content.split("\n");
675
+ let openingLineIndex = -1;
676
+ for (let i = 0; i < contentLines.length; i++) {
677
+ const line = contentLines[i];
678
+ if (line.trim().startsWith(`.${methodName}(`)) {
679
+ if (firstParam && line.includes(firstParam)) {
680
+ openingLineIndex = i;
681
+ break;
682
+ }
683
+ }
684
+ }
685
+ if (openingLineIndex === -1) {
686
+ return content;
687
+ }
688
+ let closingLineIndex = -1;
689
+ let parenCount = 0;
690
+ let braceCount = 0;
691
+ let foundOpening = false;
692
+ for (let i = openingLineIndex; i < contentLines.length; i++) {
693
+ const line = contentLines[i];
694
+ for (const char of line) {
695
+ if (char === "(") {
696
+ parenCount++;
697
+ foundOpening = true;
698
+ } else if (char === ")") {
699
+ parenCount--;
700
+ if (foundOpening && parenCount === 0 && braceCount === 0) {
701
+ closingLineIndex = i;
702
+ break;
703
+ }
704
+ } else if (char === "{") {
705
+ braceCount++;
706
+ } else if (char === "}") {
707
+ braceCount--;
708
+ }
709
+ }
710
+ if (closingLineIndex !== -1) {
711
+ break;
712
+ }
713
+ }
714
+ if (closingLineIndex === -1) {
715
+ this.logger.warn(
716
+ "Could not find closing parenthesis for existing definition"
717
+ );
718
+ return content;
719
+ }
720
+ contentLines.splice(
721
+ openingLineIndex,
722
+ closingLineIndex - openingLineIndex + 1
723
+ );
724
+ return contentLines.join("\n");
725
+ }
726
+ /**
727
+ * Adds a definition to the content by finding the appropriate place to insert it.
728
+ * @param content - The current file content
729
+ * @param definition - The definition to add
730
+ * @returns The updated content with the new definition
731
+ */
732
+ addDefinitionToContent(content, definition) {
733
+ const lines = content.split("\n");
734
+ const lastLineIndex = lines.length - 1;
735
+ let insertIndex = lastLineIndex;
736
+ for (let i = lastLineIndex; i >= 0; i--) {
737
+ const line = lines[i].trim();
738
+ if (line && !line.startsWith("}")) {
739
+ insertIndex = i;
740
+ break;
741
+ }
742
+ }
743
+ lines.splice(insertIndex + 1, 0, ` ${definition}`);
744
+ return lines.join("\n");
745
+ }
746
+ /**
747
+ * Normalises semicolons in the config file by removing them from method chain calls
748
+ * while preserving them in other contexts (imports, declarations, etc.).
749
+ * @param content - The file content to normalise
750
+ * @returns The normalised content
751
+ */
752
+ normaliseSemicolons(content) {
753
+ const lines = content.split("\n");
754
+ const configureFunctionStart = lines.findIndex(
755
+ (line) => line.trim().startsWith("export default function")
756
+ );
757
+ if (configureFunctionStart === -1) {
758
+ return content;
759
+ }
760
+ const appLineIndex = lines.findIndex(
761
+ (line, index) => index > configureFunctionStart && line.trim().startsWith("app")
762
+ );
763
+ if (appLineIndex === -1) {
764
+ return content;
765
+ }
766
+ let braceCount = 0;
767
+ let functionEndIndex = lines.length - 1;
768
+ for (let i = configureFunctionStart; i < lines.length; i++) {
769
+ const line = lines[i];
770
+ for (const char of line) {
771
+ if (char === "{") braceCount++;
772
+ if (char === "}") {
773
+ braceCount--;
774
+ if (braceCount === 0) {
775
+ functionEndIndex = i;
776
+ break;
777
+ }
778
+ }
779
+ }
780
+ if (braceCount === 0 && i > configureFunctionStart) {
781
+ break;
782
+ }
783
+ }
784
+ let lastMethodCallIndex = -1;
785
+ for (let i = appLineIndex + 1; i < functionEndIndex; i++) {
786
+ const line = lines[i];
787
+ const trimmed = line.trim();
788
+ if ((trimmed.endsWith(")") || trimmed.endsWith(");")) && !trimmed.startsWith("//")) {
789
+ lines[i] = line.replace(/;\s*$/, "");
790
+ lastMethodCallIndex = i;
791
+ }
792
+ }
793
+ if (lastMethodCallIndex !== -1 && !lines[lastMethodCallIndex].trim().endsWith(";")) {
794
+ lines[lastMethodCallIndex] = lines[lastMethodCallIndex] + ";";
795
+ }
796
+ return lines.join("\n");
797
+ }
798
+ };
799
+
800
+ // src/generators/base/wasp-generator.base.ts
801
+ var WaspGeneratorBase = class extends GeneratorBase {
802
+ constructor(fileSystem = realFileSystem, logger = singletonLogger2) {
803
+ super(fileSystem, logger);
804
+ this.fileSystem = fileSystem;
805
+ this.logger = logger;
806
+ this.configGenerator = new WaspConfigGenerator(logger, fileSystem);
807
+ this.templateUtility = new TemplateUtility(fileSystem);
808
+ this.templateResolver = new TemplateResolver(fileSystem);
809
+ }
810
+ configGenerator;
811
+ templateUtility;
812
+ templateResolver;
813
+ swarmConfig;
814
+ configLoaded = false;
815
+ // Plugin name from swarm.config.json
816
+ pluginName = PLUGIN_NAME;
817
+ async loadSwarmConfig() {
818
+ if (this.configLoaded) return;
819
+ const configManager = new SwarmConfigManager();
820
+ this.swarmConfig = await configManager.loadConfig();
821
+ this.configLoaded = true;
822
+ }
823
+ async getCustomTemplateDir() {
824
+ await this.loadSwarmConfig();
825
+ return this.swarmConfig?.templateDirectory;
826
+ }
827
+ /**
828
+ * Resolves template path with override support
829
+ */
830
+ async getTemplatePath(templateName) {
831
+ const defaultPath = this.getDefaultTemplatePath(templateName);
832
+ const customPath = await this.getCustomTemplateDir();
833
+ if (!customPath) {
834
+ return defaultPath;
835
+ }
836
+ const { path: resolvedPath, isCustom } = this.templateResolver.resolveTemplatePath(
837
+ this.pluginName,
838
+ this.name,
839
+ templateName,
840
+ defaultPath,
841
+ customPath
842
+ );
843
+ if (isCustom) {
844
+ this.logger.info(`Using custom template: ${resolvedPath}`);
845
+ }
846
+ return resolvedPath;
847
+ }
848
+ /**
849
+ * Processes a template and writes the result to a file
850
+ */
851
+ async renderTemplateToFile(templateName, replacements, outputPath, readableFileType, force) {
852
+ const templatePath = await this.getTemplatePath(templateName);
853
+ const fileExists = this.checkFileExists(
854
+ outputPath,
855
+ force,
856
+ readableFileType
857
+ );
858
+ const content = this.templateUtility.processTemplate(
859
+ templatePath,
860
+ replacements
861
+ );
862
+ this.writeFile(outputPath, content, readableFileType, fileExists);
863
+ return fileExists;
864
+ }
865
+ /**
866
+ * Generic existence check with force flag handling
867
+ * Consolidates the pattern used in both file and config checks
868
+ */
869
+ checkExistence(exists, itemDescription, force, errorMessage) {
870
+ if (exists && !force) {
871
+ this.logger.error(`${itemDescription}. Use --force to overwrite`);
872
+ throw new Error(errorMessage || itemDescription);
873
+ }
874
+ return exists;
875
+ }
876
+ /**
877
+ * Checks if a file exists and handles force flag logic
878
+ */
879
+ checkFileExists(filePath, force, fileType) {
880
+ const fileExists = this.fileSystem.existsSync(filePath);
881
+ return this.checkExistence(
882
+ fileExists,
883
+ `${fileType} already exists: ${filePath}`,
884
+ force,
885
+ `${fileType} already exists`
886
+ );
887
+ }
888
+ /**
889
+ * Safely writes a file with proper error handling and logging
890
+ */
891
+ writeFile(filePath, content, fileType, fileExists) {
892
+ this.fileSystem.writeFileSync(filePath, content);
893
+ this.logger.success(
894
+ `${fileExists ? "Overwrote" : "Generated"} ${fileType}: ${filePath}`
895
+ );
896
+ }
897
+ };
898
+
899
+ // src/generators/feature/schema.ts
900
+ import { z as z2 } from "zod";
901
+ var schema = z2.object({
902
+ target: commonSchemas.target
903
+ });
904
+
905
+ // src/generators/feature/feature-generator.ts
906
+ var FeatureGenerator = class extends WaspGeneratorBase {
907
+ constructor(logger = singletonLogger3, fileSystem = realFileSystem) {
908
+ super(fileSystem, logger);
909
+ this.logger = logger;
910
+ this.fileSystem = fileSystem;
911
+ this.name = "feature";
912
+ this.description = "Generates a feature directory containing a Wasp configuration file";
913
+ }
914
+ name;
915
+ description;
916
+ schema = schema;
917
+ getDefaultTemplatePath(templateName) {
918
+ return this.templateUtility.resolveTemplatePath(
919
+ templateName,
920
+ this.name,
921
+ import.meta.url
922
+ );
923
+ }
924
+ /**
925
+ * Generates a feature directory containing a Wasp configuration file
926
+ * @param target - The target path of the generated directory
927
+ */
928
+ async generate(args) {
929
+ const { target } = args;
930
+ const segments = validateFeaturePath2(target);
931
+ const normalisedPath = normaliseFeaturePath(target);
932
+ const sourceRoot = path5.join(findWaspRoot(this.fileSystem), "src");
933
+ if (segments.length > 1) {
934
+ const parentPath = segments.slice(0, -1).join("/");
935
+ const parentNormalisedPath = normaliseFeaturePath(parentPath);
936
+ const parentFeatureDir = path5.join(sourceRoot, parentNormalisedPath);
937
+ if (!this.fileSystem.existsSync(parentFeatureDir)) {
938
+ handleFatalError2(
939
+ `Parent feature '${parentPath}' does not exist. Please create it first.`
940
+ );
941
+ }
942
+ }
943
+ const featureDir = path5.join(sourceRoot, normalisedPath);
944
+ this.fileSystem.mkdirSync(featureDir, { recursive: true });
945
+ this.configGenerator.generate(normalisedPath);
946
+ this.logger.success(`Generated feature: ${normalisedPath}`);
947
+ }
948
+ };
949
+
950
+ // src/generators/base/component-generator.base.ts
951
+ var ComponentGeneratorBase = class extends WaspGeneratorBase {
952
+ constructor(logger = singletonLogger4, fileSystem = realFileSystem, featureDirectoryGenerator = new FeatureGenerator(logger, fileSystem)) {
953
+ super(fileSystem, logger);
954
+ this.logger = logger;
955
+ this.fileSystem = fileSystem;
956
+ this.featureDirectoryGenerator = featureDirectoryGenerator;
957
+ this.featureDirectoryGenerator = featureDirectoryGenerator;
958
+ }
959
+ getDefaultTemplatePath(templateName) {
960
+ return this.templateUtility.resolveTemplatePath(
961
+ templateName,
962
+ this.name,
963
+ import.meta.url
964
+ );
965
+ }
966
+ get name() {
967
+ return toKebabCase2(this.componentType);
968
+ }
969
+ /**
970
+ * Validates that the feature config file exists in the target or ancestor directories
971
+ */
972
+ validateFeatureConfig(featurePath) {
973
+ const normalisedPath = normaliseFeaturePath(featurePath);
974
+ const segments = normalisedPath.split("/");
975
+ for (let i = segments.length; i > 0; i--) {
976
+ const pathSegments = segments.slice(0, i);
977
+ const currentPath = pathSegments.join("/");
978
+ const featureName = pathSegments[pathSegments.length - 1];
979
+ const featureDir = getFeatureDir(this.fileSystem, currentPath);
980
+ const configPath = path6.join(featureDir, `feature.wasp.ts`);
981
+ if (this.fileSystem.existsSync(configPath)) {
982
+ return configPath;
983
+ }
984
+ }
985
+ this.logger.error(
986
+ `Feature config file not found in '${normalisedPath}' or any ancestor directories`
987
+ );
988
+ this.logger.error(
989
+ `Expected to find a feature.wasp.ts config file in one of the feature directories`
990
+ );
991
+ throw new Error("Feature config file not found");
992
+ }
993
+ /**
994
+ * Checks if a config item already exists in the feature config
995
+ */
996
+ checkConfigExists(configPath, methodName, itemName, force) {
997
+ const configContent = this.fileSystem.readFileSync(configPath, "utf8");
998
+ const configExists = hasHelperMethodCall(
999
+ configContent,
1000
+ methodName,
1001
+ itemName
1002
+ );
1003
+ return this.checkExistence(
1004
+ configExists,
1005
+ `${methodName} config already exists in ${configPath}`,
1006
+ force,
1007
+ `${methodName} config already exists`
1008
+ );
1009
+ }
1010
+ /**
1011
+ * Updates the feature config with a new definition
1012
+ */
1013
+ updateFeatureConfig(featurePath, definition, configPath, configExists, methodName) {
1014
+ this.configGenerator.update(featurePath, definition);
1015
+ this.logger.success(
1016
+ `${configExists ? "Updated" : "Added"} ${methodName} config in: ${configPath}`
1017
+ );
1018
+ }
1019
+ /**
1020
+ * Consolidated helper for updating config files with existence check
1021
+ * This replaces the duplicated updateConfigFile pattern in concrete generators
1022
+ */
1023
+ updateConfigWithCheck(configPath, methodName, entityName, definition, featurePath, force) {
1024
+ const configExists = this.checkConfigExists(
1025
+ configPath,
1026
+ methodName,
1027
+ entityName,
1028
+ force
1029
+ );
1030
+ if (!configExists || force) {
1031
+ this.updateFeatureConfig(
1032
+ featurePath,
1033
+ definition,
1034
+ configPath,
1035
+ configExists,
1036
+ methodName
1037
+ );
1038
+ }
1039
+ }
1040
+ /**
1041
+ * Gets the appropriate directory for a feature based on its path.
1042
+ * @param fileSystem - The filesystem abstraction
1043
+ * @param featurePath - The full feature path
1044
+ * @param type - The type of file being generated
1045
+ * @returns The target directory and import path
1046
+ */
1047
+ getFeatureTargetDir(fileSystem, featurePath, type) {
1048
+ validateFeaturePath3(featurePath);
1049
+ const normalisedPath = normaliseFeaturePath(featurePath);
1050
+ const featureDir = getFeatureDir(fileSystem, normalisedPath);
1051
+ const typeKey = type.toLowerCase();
1052
+ const typeDirectory = TYPE_DIRECTORIES[typeKey];
1053
+ const targetDirectory = path6.join(featureDir, typeDirectory);
1054
+ const importDirectory = `@src/${normalisedPath}/${typeDirectory}`;
1055
+ return { targetDirectory, importDirectory };
1056
+ }
1057
+ /**
1058
+ * Ensures a target directory exists and returns its path
1059
+ */
1060
+ ensureTargetDirectory(featurePath, type) {
1061
+ const { targetDirectory, importDirectory } = this.getFeatureTargetDir(
1062
+ this.fileSystem,
1063
+ featurePath,
1064
+ type
1065
+ );
1066
+ ensureDirectoryExists(this.fileSystem, targetDirectory);
1067
+ return { targetDirectory, importDirectory };
1068
+ }
1069
+ /**
1070
+ * Generate middleware file for API or API namespace
1071
+ */
1072
+ async generateMiddlewareFile(targetFile, name, force) {
1073
+ const replacements = {
1074
+ name,
1075
+ middlewareType: toCamelCase(this.componentType || "")
1076
+ };
1077
+ await this.renderTemplateToFile(
1078
+ "middleware.eta",
1079
+ replacements,
1080
+ targetFile,
1081
+ "Middleware file",
1082
+ force
1083
+ );
1084
+ }
1085
+ };
1086
+
1087
+ // src/generators/base/operation-generator.base.ts
1088
+ var OperationGeneratorBase = class extends ComponentGeneratorBase {
1089
+ /**
1090
+ * Gets the operation name based on operation type and model name.
1091
+ */
1092
+ getOperationName(operation, modelName, customName) {
1093
+ if (customName) {
1094
+ return customName;
1095
+ }
1096
+ switch (operation) {
1097
+ case OPERATIONS.GETALL:
1098
+ return `getAll${getPlural(modelName)}`;
1099
+ case OPERATIONS.GETFILTERED:
1100
+ return `getFiltered${getPlural(modelName)}`;
1101
+ default:
1102
+ return `${operation}${modelName}`;
1103
+ }
1104
+ }
1105
+ /**
1106
+ * Gets the template path for operation templates.
1107
+ * This method resolves operation templates to the operation generator's directory
1108
+ * instead of the current generator's directory.
1109
+ */
1110
+ getOperationTemplatePath(templateName) {
1111
+ return this.templateUtility.resolveTemplatePath(
1112
+ templateName,
1113
+ "operation",
1114
+ import.meta.url
1115
+ );
1116
+ }
1117
+ /**
1118
+ * Gets the TypeScript type name for an operation.
1119
+ */
1120
+ getOperationTypeName(operation, modelName) {
1121
+ return toPascalCase2(this.getOperationName(operation, modelName));
1122
+ }
1123
+ /**
1124
+ * Generates import statements for an operation.
1125
+ */
1126
+ generateImports(model, modelName, operation) {
1127
+ const imports = [];
1128
+ if (operation !== OPERATIONS.GETALL) {
1129
+ if (needsPrismaImport(model)) {
1130
+ imports.push('import { Prisma } from "@prisma/client";');
1131
+ }
1132
+ imports.push(`import { ${modelName} } from "wasp/entities";`);
1133
+ }
1134
+ imports.push('import { HttpError } from "wasp/server";');
1135
+ imports.push(
1136
+ `import type { ${this.getOperationTypeName(
1137
+ operation,
1138
+ modelName
1139
+ )} } from "wasp/server/operations";`
1140
+ );
1141
+ return imports.join("\n");
1142
+ }
1143
+ /**
1144
+ * Gets the operation type ("query" or "action") for a given operation.
1145
+ */
1146
+ getOperationType(operation) {
1147
+ return operation === OPERATIONS.GETALL || operation === OPERATIONS.GET || operation === OPERATIONS.GETFILTERED ? "query" : "action";
1148
+ }
1149
+ /**
1150
+ * Generates the operation components needed for file and config generation.
1151
+ */
1152
+ async generateOperationComponents(modelName, operation, auth = false, entities = [modelName], isCrudOverride = false, crudName = null, customName) {
1153
+ const model = await getEntityMetadata(modelName);
1154
+ const operationType = this.getOperationType(operation);
1155
+ const operationName = this.getOperationName(
1156
+ operation,
1157
+ modelName,
1158
+ customName
1159
+ );
1160
+ const operationCode = await this.generateOperationCode(
1161
+ model,
1162
+ operation,
1163
+ auth,
1164
+ isCrudOverride,
1165
+ crudName
1166
+ );
1167
+ const configEntry = {
1168
+ operationName,
1169
+ entities,
1170
+ authRequired: auth
1171
+ };
1172
+ return {
1173
+ operationCode,
1174
+ configEntry,
1175
+ operationType,
1176
+ operationName
1177
+ };
1178
+ }
1179
+ /**
1180
+ * Generates the code for an operation.
1181
+ */
1182
+ async generateOperationCode(model, operation, auth = false, isCrudOverride = false, crudName = null) {
1183
+ const operationType = this.getOperationType(operation);
1184
+ const templatePath = this.getOperationTemplatePath(`${operation}.eta`);
1185
+ const allFieldNames = model.fields.map((f) => f.name);
1186
+ const idFields = getIdFields(model);
1187
+ const requiredFields = getRequiredFields(model);
1188
+ const optionalFields = getOptionalFields(model);
1189
+ const jsonFields = getJsonFields(model);
1190
+ const pluralModelName = getPlural(model.name);
1191
+ const pluralModelNameLower = pluralModelName.toLowerCase();
1192
+ const modelNameLower = model.name.toLowerCase();
1193
+ const operationName = this.getOperationName(operation, model.name);
1194
+ const imports = isCrudOverride ? "" : this.generateImports(model, model.name, operation);
1195
+ const jsonTypeHandling = generateJsonTypeHandling(jsonFields);
1196
+ let typeParams = "";
1197
+ switch (operation) {
1198
+ case "create": {
1199
+ const pickRequired = generatePickType(
1200
+ model.name,
1201
+ requiredFields,
1202
+ allFieldNames
1203
+ );
1204
+ const partialOptional = generatePartialType(
1205
+ generatePickType(model.name, optionalFields, allFieldNames)
1206
+ );
1207
+ typeParams = `<${generateIntersectionType(pickRequired, partialOptional)}>`;
1208
+ break;
1209
+ }
1210
+ case "update": {
1211
+ const pickId = generatePickType(model.name, idFields, allFieldNames);
1212
+ const omitId = generateOmitType(model.name, idFields, allFieldNames);
1213
+ const partialRest = generatePartialType(omitId);
1214
+ typeParams = `<${generateIntersectionType(pickId, partialRest)}>`;
1215
+ break;
1216
+ }
1217
+ case "delete":
1218
+ case "get":
1219
+ typeParams = `<${generatePickType(model.name, idFields, allFieldNames)}>`;
1220
+ break;
1221
+ case "getAll":
1222
+ typeParams = `<void>`;
1223
+ break;
1224
+ case "getFiltered":
1225
+ typeParams = `<${generatePartialType(model.name)}>`;
1226
+ break;
1227
+ }
1228
+ const authCheck = auth ? ` if (!context.user) {
1229
+ throw new HttpError(401);
1230
+ }
1231
+
1232
+ ` : "";
1233
+ let typeAnnotation = "";
1234
+ let satisfiesType = "";
1235
+ if (isCrudOverride && crudName) {
1236
+ const opCap = capitalise(operation);
1237
+ if (operationType === "action") {
1238
+ typeAnnotation = `: ${crudName}.${opCap}Action${typeParams}`;
1239
+ } else {
1240
+ typeAnnotation = "";
1241
+ }
1242
+ if (operationType === "query") {
1243
+ satisfiesType = `satisfies ${crudName}.${opCap}Query${typeParams}`;
1244
+ } else {
1245
+ satisfiesType = "";
1246
+ }
1247
+ } else {
1248
+ if (operationType === "action") {
1249
+ typeAnnotation = `: ${this.getOperationTypeName(operation, model.name)}${typeParams}`;
1250
+ } else {
1251
+ typeAnnotation = "";
1252
+ }
1253
+ if (operationType === "query") {
1254
+ satisfiesType = `satisfies ${this.getOperationTypeName(operation, model.name)}${typeParams}`;
1255
+ } else {
1256
+ satisfiesType = "";
1257
+ }
1258
+ }
1259
+ const isCompositeKey = idFields.length > 1;
1260
+ const compositeKeyName = isCompositeKey ? idFields.join("_") : "";
1261
+ const idFieldParams = isCompositeKey ? idFields.join(", ") : idFields[0];
1262
+ const whereClause = isCompositeKey ? `${compositeKeyName}: { ${idFields.map((f) => `${f}`).join(", ")} }` : idFields[0];
1263
+ const replacements = {
1264
+ operationName,
1265
+ modelName: model.name,
1266
+ authCheck,
1267
+ imports,
1268
+ idField: idFields[0],
1269
+ idFieldParams,
1270
+ whereClause,
1271
+ isCompositeKey: String(isCompositeKey),
1272
+ compositeKeyName,
1273
+ jsonTypeHandling,
1274
+ typeAnnotation,
1275
+ satisfiesType,
1276
+ modelNameLower,
1277
+ pluralModelNameLower
1278
+ };
1279
+ return this.templateUtility.processTemplate(templatePath, replacements);
1280
+ }
1281
+ /**
1282
+ * Generates an operation file for a given operation.
1283
+ */
1284
+ generateOperationFile(operationsDir, operationName, operationCode, force = false) {
1285
+ const operationFile = `${operationsDir}/${operationName}.ts`;
1286
+ const fileExists = this.checkFileExists(
1287
+ operationFile,
1288
+ force,
1289
+ "Operation file"
1290
+ );
1291
+ this.writeFile(operationFile, operationCode, "operation file", fileExists);
1292
+ }
1293
+ /**
1294
+ * Copies a directory of operation templates to the target feature directory.
1295
+ * @param templateDir - The source template directory
1296
+ * @param targetDir - The target feature directory
1297
+ */
1298
+ copyOperationTemplates(templateDir, targetDir) {
1299
+ copyDirectory(this.fileSystem, templateDir, targetDir);
1300
+ this.logger.debug(
1301
+ `Copied operation templates from ${templateDir} to ${targetDir}`
1302
+ );
1303
+ }
1304
+ /**
1305
+ * Generates an operation definition for the feature configuration.
1306
+ */
1307
+ getDefinition(operationName, featurePath, entities, operationType, importPath, auth = false) {
1308
+ if (!OPERATION_TYPES.includes(operationType)) {
1309
+ handleFatalError3(`Unknown operation type: ${operationType}`);
1310
+ }
1311
+ const directory = TYPE_DIRECTORIES[operationType];
1312
+ const featureDir = getFeatureImportPath(featurePath);
1313
+ const templatePath = this.templateUtility.resolveTemplatePath(
1314
+ "operation.eta",
1315
+ "config",
1316
+ import.meta.url
1317
+ );
1318
+ return this.templateUtility.processTemplate(templatePath, {
1319
+ operationType: capitalise(operationType),
1320
+ operationName,
1321
+ featureDir,
1322
+ directory,
1323
+ entities: entities.map((e) => `"${e}"`).join(", "),
1324
+ importPath,
1325
+ auth: String(auth)
1326
+ });
1327
+ }
1328
+ };
1329
+ export {
1330
+ OperationGeneratorBase
1331
+ };