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