@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,1104 @@
1
+ // src/generators/api/api-generator.ts
2
+ import { toCamelCase as toCamelCase2, toPascalCase as toPascalCase3 } from "@ingenyus/swarm";
3
+
4
+ // src/common/filesystem.ts
5
+ import { toPascalCase, validateFeaturePath } from "@ingenyus/swarm";
6
+ import fs from "fs";
7
+ import path from "path";
8
+
9
+ // src/types/constants.ts
10
+ var PLUGIN_NAME = "wasp";
11
+ var API_HTTP_METHODS = [
12
+ "ALL",
13
+ "GET",
14
+ "POST",
15
+ "PUT",
16
+ "DELETE"
17
+ ];
18
+ var TYPE_DIRECTORIES = {
19
+ component: "client/components",
20
+ hook: "client/hooks",
21
+ layout: "client/layouts",
22
+ page: "client/pages",
23
+ util: "client/utils",
24
+ action: "server/actions",
25
+ query: "server/queries",
26
+ middleware: "server/middleware",
27
+ job: "server/jobs",
28
+ api: "server/apis",
29
+ crud: "server/cruds",
30
+ type: "types"
31
+ };
32
+ var CONFIG_TYPES = {
33
+ ROUTE: "Route",
34
+ QUERY: "Query",
35
+ ACTION: "Action",
36
+ JOB: "Job",
37
+ API: "Api",
38
+ API_NAMESPACE: "ApiNamespace",
39
+ CRUD: "Crud"
40
+ };
41
+
42
+ // src/common/filesystem.ts
43
+ var realFileSystem = {
44
+ readFileSync: fs.readFileSync,
45
+ writeFileSync: fs.writeFileSync,
46
+ existsSync: fs.existsSync,
47
+ copyFileSync: fs.copyFileSync,
48
+ mkdirSync: fs.mkdirSync,
49
+ readdirSync: fs.readdirSync,
50
+ statSync: fs.statSync
51
+ };
52
+ function findWaspRoot(fileSystem, startDir = process.cwd()) {
53
+ const startDirPath = path.resolve(startDir);
54
+ let currentDirPath = startDirPath;
55
+ const root = path.parse(currentDirPath).root;
56
+ while (currentDirPath !== root) {
57
+ const waspRootPath = path.join(currentDirPath, ".wasproot");
58
+ if (fileSystem.existsSync(waspRootPath)) {
59
+ return currentDirPath;
60
+ }
61
+ currentDirPath = path.dirname(currentDirPath);
62
+ }
63
+ throw new Error(
64
+ `Couldn't find Wasp application root from ${startDirPath}. Make sure you are running this command from within a Wasp project directory.`
65
+ );
66
+ }
67
+ function ensureDirectoryExists(fileSystem, dir) {
68
+ if (!fileSystem.existsSync(dir)) {
69
+ fileSystem.mkdirSync(dir, { recursive: true });
70
+ }
71
+ }
72
+ function normaliseFeaturePath(featurePath) {
73
+ const segments = validateFeaturePath(featurePath);
74
+ const normalisedSegments = [];
75
+ for (let i = 0; i < segments.length; i++) {
76
+ const segment = segments[i];
77
+ const previousSegment = normalisedSegments[normalisedSegments.length - 1];
78
+ if (previousSegment !== "features" && segment !== "features") {
79
+ normalisedSegments.push("features");
80
+ }
81
+ normalisedSegments.push(segment);
82
+ }
83
+ return normalisedSegments.join("/");
84
+ }
85
+ function getFeatureDir(fileSystem, featureName) {
86
+ const waspRoot = findWaspRoot(fileSystem);
87
+ const normalisedPath = normaliseFeaturePath(featureName);
88
+ return path.join(waspRoot, "src", normalisedPath);
89
+ }
90
+ function getFeatureImportPath(featurePath) {
91
+ const segments = validateFeaturePath(featurePath);
92
+ return segments.join("/");
93
+ }
94
+
95
+ // src/common/prisma.ts
96
+ import {
97
+ getSchema
98
+ } from "@mrleebo/prisma-ast";
99
+ import fs2 from "fs";
100
+ import path2 from "path";
101
+
102
+ // src/common/schemas.ts
103
+ import { commandRegistry } from "@ingenyus/swarm";
104
+ import { z } from "zod";
105
+ var commonSchemas = {
106
+ feature: z.string().min(1, "Feature is required").meta({
107
+ description: "The feature directory this component will be generated in"
108
+ }).register(commandRegistry, {
109
+ shortName: "f",
110
+ examples: ["root", "auth", "dashboard/users"],
111
+ helpText: "Can be nested as a logical or relative path, e.g. 'dashboard/users' or 'features/dashboard/features/users'"
112
+ }),
113
+ name: z.string().min(1, "Name is required").meta({ description: "The name of the generated component" }).register(commandRegistry, {
114
+ shortName: "n",
115
+ examples: ["users", "task"],
116
+ helpText: "Will be used for generated files and configuration entries"
117
+ }),
118
+ target: z.string().min(1, "Target directory is required").meta({ description: "The target path of the generated directory" }).register(commandRegistry, {
119
+ shortName: "t",
120
+ examples: ["dashboard/users", "features/dashboard/features/users"],
121
+ helpText: "A logical or relative path, e.g. 'dashboard/users' or 'features/dashboard/features/users'"
122
+ }),
123
+ path: z.string().min(1, "Path is required").meta({ description: "The path that this component will be accessible at" }).register(commandRegistry, {
124
+ shortName: "p",
125
+ examples: ["/api/users/:id", "/api/products"],
126
+ helpText: "Supports Express-style placeholders, e.g. '/api/users/:id'"
127
+ }),
128
+ dataType: z.string().min(1, "Data type is required").meta({ description: "The data type/model name for this operation" }).register(commandRegistry, {
129
+ shortName: "d",
130
+ examples: ["User", "Product", "Task"],
131
+ helpText: "The Wasp entity or model name this operation will interact with"
132
+ }),
133
+ entities: z.array(z.string()).optional().meta({
134
+ description: "The Wasp entities that will be available to this component (optional)"
135
+ }).register(commandRegistry, {
136
+ shortName: "e",
137
+ examples: ["User", "User Task"],
138
+ helpText: "An array of Wasp entity names"
139
+ }),
140
+ force: z.boolean().optional().meta({
141
+ description: "Force overwrite of existing files and configuration entries (optional)"
142
+ }).register(commandRegistry, {
143
+ shortName: "F",
144
+ helpText: "CAUTION: Will overwrite existing files and configuration entries with current parameters"
145
+ }),
146
+ auth: z.boolean().optional().meta({
147
+ description: "Require authentication for this component (optional)"
148
+ }).register(commandRegistry, {
149
+ shortName: "a",
150
+ helpText: "Will generate authentication checks"
151
+ })
152
+ };
153
+
154
+ // src/common/templates.ts
155
+ import { toKebabCase } from "@ingenyus/swarm";
156
+ import { Eta } from "eta";
157
+ import path3 from "path";
158
+ var TemplateUtility = class {
159
+ constructor(fileSystem) {
160
+ this.fileSystem = fileSystem;
161
+ }
162
+ processTemplate(templatePath, replacements) {
163
+ const declarations = Object.keys(replacements).map((key) => `${key}=it.${key}`).join(", ");
164
+ const functionHeader = declarations ? `const ${declarations};` : void 0;
165
+ const templateDir = path3.dirname(templatePath);
166
+ const eta = new Eta({
167
+ autoTrim: false,
168
+ autoEscape: false,
169
+ views: templateDir,
170
+ functionHeader
171
+ });
172
+ const templateName = path3.basename(templatePath).replace(/\.eta$/, "");
173
+ if (this.fileSystem.existsSync(templatePath)) {
174
+ return eta.render(templateName, replacements);
175
+ } else {
176
+ const template = this.fileSystem.readFileSync(templatePath, "utf8");
177
+ return eta.renderString(template, replacements);
178
+ }
179
+ }
180
+ /**
181
+ * Helper method to resolve template paths for concrete generators
182
+ * @param relativePath - The relative path to the template file
183
+ * @param generatorName - The name of the generator (e.g., 'api', 'job')
184
+ * @param currentFileUrl - The import.meta.url from the concrete generator class
185
+ * @returns The full path to the template file
186
+ */
187
+ resolveTemplatePath(relativePath, generatorName, currentFileUrl) {
188
+ const generatorDirName = toKebabCase(generatorName);
189
+ const currentFilePath = new URL(currentFileUrl).pathname;
190
+ const currentFileDir = path3.dirname(currentFilePath);
191
+ const currentFileName = path3.basename(currentFilePath);
192
+ const isInstalledPackage = currentFileDir.includes("node_modules") && currentFileDir.endsWith("/dist") && currentFileName === "index.js";
193
+ const startDir = isInstalledPackage ? currentFileDir : path3.dirname(path3.dirname(currentFileDir));
194
+ return path3.join(
195
+ startDir,
196
+ "generators",
197
+ generatorDirName,
198
+ "templates",
199
+ relativePath
200
+ );
201
+ }
202
+ };
203
+
204
+ // src/generators/base/component-generator.base.ts
205
+ import {
206
+ hasHelperMethodCall,
207
+ logger as singletonLogger4,
208
+ toCamelCase,
209
+ toKebabCase as toKebabCase2,
210
+ validateFeaturePath as validateFeaturePath3
211
+ } from "@ingenyus/swarm";
212
+ import path6 from "path";
213
+
214
+ // src/generators/feature/feature-generator.ts
215
+ import {
216
+ handleFatalError as handleFatalError2,
217
+ logger as singletonLogger3,
218
+ validateFeaturePath as validateFeaturePath2
219
+ } from "@ingenyus/swarm";
220
+ import path5 from "path";
221
+
222
+ // src/generators/base/wasp-generator.base.ts
223
+ import {
224
+ GeneratorBase,
225
+ logger as singletonLogger2,
226
+ SwarmConfigManager,
227
+ TemplateResolver
228
+ } from "@ingenyus/swarm";
229
+
230
+ // src/generators/config/wasp-config-generator.ts
231
+ import {
232
+ handleFatalError,
233
+ parseHelperMethodDefinition,
234
+ logger as singletonLogger
235
+ } from "@ingenyus/swarm";
236
+ import path4 from "path";
237
+ var WaspConfigGenerator = class {
238
+ constructor(logger = singletonLogger, fileSystem = realFileSystem) {
239
+ this.logger = logger;
240
+ this.fileSystem = fileSystem;
241
+ this.templateUtility = new TemplateUtility(fileSystem);
242
+ }
243
+ path = path4;
244
+ templateUtility;
245
+ /**
246
+ * Gets the template path for feature config templates.
247
+ * Feature config templates are located in the feature generator's templates directory.
248
+ * @param templateName - The name of the template file (e.g., 'feature.wasp.eta')
249
+ * @returns The full path to the template file
250
+ */
251
+ getTemplatePath(templateName) {
252
+ return this.templateUtility.resolveTemplatePath(
253
+ templateName,
254
+ "feature",
255
+ import.meta.url
256
+ );
257
+ }
258
+ /**
259
+ * Generate a TypeScript Wasp config file in a feature directory
260
+ * @param featurePath - The feature directory path
261
+ */
262
+ generate(featurePath) {
263
+ const featureDir = getFeatureDir(this.fileSystem, featurePath);
264
+ if (!this.fileSystem.existsSync(featureDir)) {
265
+ this.fileSystem.mkdirSync(featureDir, { recursive: true });
266
+ }
267
+ const templatePath = this.getTemplatePath("feature.wasp.eta");
268
+ if (!this.fileSystem.existsSync(templatePath)) {
269
+ this.logger.error(`Template not found: ${templatePath}`);
270
+ return;
271
+ }
272
+ const configFilePath = path4.join(featureDir, `feature.wasp.ts`);
273
+ if (this.fileSystem.existsSync(configFilePath)) {
274
+ this.logger.warn(`Feature config already exists: ${configFilePath}`);
275
+ return;
276
+ }
277
+ this.fileSystem.copyFileSync(templatePath, configFilePath);
278
+ this.logger.success(`Generated feature config: ${configFilePath}`);
279
+ }
280
+ /**
281
+ * Updates or creates a feature configuration file with a pre-built declaration.
282
+ * @param featurePath - The path to the feature
283
+ * @param declaration - The pre-built declaration string to add or update
284
+ * @returns The updated feature configuration file
285
+ */
286
+ update(featurePath, declaration) {
287
+ const configDir = getFeatureDir(this.fileSystem, featurePath);
288
+ const configFilePath = path4.join(configDir, `feature.wasp.ts`);
289
+ if (!this.fileSystem.existsSync(configFilePath)) {
290
+ const templatePath = this.getTemplatePath("feature.wasp.eta");
291
+ if (!this.fileSystem.existsSync(templatePath)) {
292
+ handleFatalError(`Feature config template not found: ${templatePath}`);
293
+ }
294
+ this.fileSystem.copyFileSync(templatePath, configFilePath);
295
+ }
296
+ let content = this.fileSystem.readFileSync(configFilePath, "utf8");
297
+ content = this.normaliseSemicolons(content);
298
+ const parsed = parseHelperMethodDefinition(declaration);
299
+ if (!parsed) {
300
+ handleFatalError(`Could not parse definition: ${declaration}`);
301
+ return content;
302
+ }
303
+ const { methodName } = parsed;
304
+ const hadExistingDefinitions = this.hasExistingDefinitions(
305
+ content,
306
+ methodName
307
+ );
308
+ content = this.removeExistingDefinition(content, declaration);
309
+ const hasExistingDefinitions = this.hasExistingDefinitions(
310
+ content,
311
+ methodName
312
+ );
313
+ const lines = content.split("\n");
314
+ const configureFunctionStart = lines.findIndex(
315
+ (line) => line.trim().startsWith("export default function")
316
+ );
317
+ if (configureFunctionStart === -1) {
318
+ handleFatalError("Could not find configure function in feature config");
319
+ }
320
+ const appLineIndex = lines.findIndex(
321
+ (line, index) => index > configureFunctionStart && line.trim() === "app"
322
+ );
323
+ if (appLineIndex === -1) {
324
+ const insertIndex = configureFunctionStart + 1;
325
+ const itemsToInsert = [" app"];
326
+ const comment = this.getMethodComment(methodName);
327
+ itemsToInsert.push(` ${comment}`);
328
+ itemsToInsert.push(declaration.trimEnd());
329
+ lines.splice(insertIndex, 0, ...itemsToInsert);
330
+ } else {
331
+ const { insertIndex, addComment } = this.findGroupInsertionPoint(
332
+ lines,
333
+ methodName,
334
+ declaration,
335
+ hadExistingDefinitions || hasExistingDefinitions
336
+ );
337
+ const newLines = this.insertWithSpacing(
338
+ lines,
339
+ declaration,
340
+ insertIndex,
341
+ methodName,
342
+ addComment
343
+ );
344
+ const normalisedContent2 = this.normaliseSemicolons(newLines.join("\n"));
345
+ this.fileSystem.writeFileSync(configFilePath, normalisedContent2);
346
+ return configFilePath;
347
+ }
348
+ const normalisedContent = this.normaliseSemicolons(lines.join("\n"));
349
+ this.fileSystem.writeFileSync(configFilePath, normalisedContent);
350
+ return configFilePath;
351
+ }
352
+ /**
353
+ * Determines the insertion index for a method name based on alphabetical ordering
354
+ * of existing groups in the configuration file.
355
+ * @param groups - Object containing existing method groups
356
+ * @param methodName - The method name to find insertion index for
357
+ * @returns The insertion index for the method name
358
+ */
359
+ getInsertionIndexForMethod(groups, methodName) {
360
+ const existingMethods = Object.keys(groups).filter(
361
+ (method) => groups[method].length > 0
362
+ );
363
+ const allMethods = [...existingMethods, methodName].sort();
364
+ return allMethods.indexOf(methodName);
365
+ }
366
+ /**
367
+ * Gets the comment text for a method type.
368
+ * @param methodName The method name (e.g., 'addApi')
369
+ * @returns The comment text for the method type
370
+ */
371
+ getMethodComment(methodName) {
372
+ const entityName = methodName.startsWith("add") ? methodName.slice(3) : methodName;
373
+ return `// ${entityName} definitions`;
374
+ }
375
+ /**
376
+ * Finds the correct insertion point for a new configuration item.
377
+ * @param lines - Array of file lines
378
+ * @param methodName - The method name (e.g., 'addApi')
379
+ * @param definition - The definition string to parse for item name
380
+ * @returns Object with insertion index and whether to add a comment
381
+ */
382
+ findGroupInsertionPoint(lines, methodName, definition, hasExistingDefinitionsOfType) {
383
+ const appLineIndex = lines.findIndex((line) => line.trim() === "app");
384
+ if (appLineIndex === -1) {
385
+ return { insertIndex: appLineIndex + 1, addComment: false };
386
+ }
387
+ const methodCalls = [];
388
+ for (let i = appLineIndex + 1; i < lines.length; i++) {
389
+ const line = lines[i].trim();
390
+ if (line.startsWith(".") && line.includes("(")) {
391
+ let methodCallContent = line;
392
+ let j = i;
393
+ let closingParenCount = 0;
394
+ let foundClosingParen = false;
395
+ for (let k = 0; k < methodCallContent.length; k++) {
396
+ if (methodCallContent[k] === "(") closingParenCount++;
397
+ if (methodCallContent[k] === ")") closingParenCount--;
398
+ if (closingParenCount === 0 && methodCallContent[k] === ")") {
399
+ foundClosingParen = true;
400
+ break;
401
+ }
402
+ }
403
+ while (!foundClosingParen && j < lines.length - 1) {
404
+ j++;
405
+ methodCallContent += " " + lines[j].trim();
406
+ for (let k = 0; k < lines[j].length; k++) {
407
+ if (lines[j][k] === "(") closingParenCount++;
408
+ if (lines[j][k] === ")") closingParenCount--;
409
+ if (closingParenCount === 0 && lines[j][k] === ")") {
410
+ foundClosingParen = true;
411
+ break;
412
+ }
413
+ }
414
+ }
415
+ const match = methodCallContent.match(
416
+ /\.(\w+)\([^,]+,\s*['"`]([^'"`]+)['"`]/
417
+ );
418
+ if (match) {
419
+ methodCalls.push({
420
+ lineIndex: i,
421
+ endLineIndex: j,
422
+ methodName: match[1],
423
+ itemName: match[2]
424
+ });
425
+ }
426
+ }
427
+ }
428
+ const groups = {};
429
+ methodCalls.forEach((call) => {
430
+ if (!groups[call.methodName]) {
431
+ groups[call.methodName] = [];
432
+ }
433
+ groups[call.methodName].push({
434
+ lineIndex: call.lineIndex,
435
+ endLineIndex: call.endLineIndex,
436
+ itemName: call.itemName
437
+ });
438
+ });
439
+ const targetGroup = groups[methodName] || [];
440
+ if (targetGroup.length === 0) {
441
+ const targetGroupIndex = this.getInsertionIndexForMethod(
442
+ groups,
443
+ methodName
444
+ );
445
+ const existingMethods = Object.keys(groups).filter((method) => groups[method].length > 0).sort();
446
+ for (let i = targetGroupIndex; i < existingMethods.length; i++) {
447
+ const groupMethod = existingMethods[i];
448
+ if (groups[groupMethod] && groups[groupMethod].length > 0) {
449
+ const firstItem = groups[groupMethod][0];
450
+ let insertIndex = firstItem.lineIndex;
451
+ for (let j = firstItem.lineIndex - 1; j > appLineIndex; j--) {
452
+ const line = lines[j].trim();
453
+ if (line.startsWith("//") && line.includes("definitions")) {
454
+ insertIndex = j;
455
+ break;
456
+ } else if (line.startsWith(".") || line === "") {
457
+ continue;
458
+ } else {
459
+ break;
460
+ }
461
+ }
462
+ return { insertIndex, addComment: !hasExistingDefinitionsOfType };
463
+ }
464
+ }
465
+ for (let i = targetGroupIndex - 1; i >= 0; i--) {
466
+ const groupMethod = existingMethods[i];
467
+ if (groups[groupMethod] && groups[groupMethod].length > 0) {
468
+ const lastItem2 = groups[groupMethod][groups[groupMethod].length - 1];
469
+ return {
470
+ insertIndex: lastItem2.endLineIndex + 1,
471
+ addComment: !hasExistingDefinitionsOfType
472
+ };
473
+ }
474
+ }
475
+ return {
476
+ insertIndex: appLineIndex + 1,
477
+ addComment: !hasExistingDefinitionsOfType
478
+ };
479
+ }
480
+ const parsed = parseHelperMethodDefinition(definition);
481
+ if (!parsed) {
482
+ return { insertIndex: appLineIndex + 1, addComment: false };
483
+ }
484
+ const { firstParam: itemName } = parsed;
485
+ for (let i = 0; i < targetGroup.length; i++) {
486
+ if (itemName.localeCompare(targetGroup[i].itemName) < 0) {
487
+ return { insertIndex: targetGroup[i].lineIndex, addComment: false };
488
+ }
489
+ }
490
+ const lastItem = targetGroup[targetGroup.length - 1];
491
+ return { insertIndex: lastItem.endLineIndex + 1, addComment: false };
492
+ }
493
+ /**
494
+ * Inserts a definition with optional comment header.
495
+ * @param lines - Array of file lines
496
+ * @param declaration - The declaration to insert
497
+ * @param insertIndex - The index where to insert
498
+ * @param methodName - The method name for comment generation
499
+ * @param addComment - Whether to add a comment before the declaration
500
+ * @returns The modified lines array
501
+ */
502
+ insertWithSpacing(lines, declaration, insertIndex, methodName, addComment = false) {
503
+ const newLines = [...lines];
504
+ if (addComment) {
505
+ const comment = this.getMethodComment(methodName);
506
+ newLines.splice(insertIndex, 0, ` ${comment}`);
507
+ insertIndex += 1;
508
+ }
509
+ newLines.splice(insertIndex, 0, declaration.trimEnd());
510
+ return newLines;
511
+ }
512
+ /**
513
+ * Checks if there are any existing definitions of a specific type in the content.
514
+ * @param content - The file content to search
515
+ * @param methodName - The method name to check for (e.g., 'addJob', 'addApi')
516
+ * @returns true if there are existing definitions of this type, false otherwise
517
+ */
518
+ hasExistingDefinitions(content, methodName) {
519
+ const lines = content.split("\n");
520
+ for (const line of lines) {
521
+ if (line.trim().startsWith(`.${methodName}(`)) {
522
+ return true;
523
+ }
524
+ }
525
+ return false;
526
+ }
527
+ /**
528
+ * Removes an existing definition from the content by finding the helper method call
529
+ * and removing the entire method call block.
530
+ * @param content - The file content
531
+ * @param definition - The new definition to find the existing one from
532
+ * @returns The content with the existing definition removed
533
+ */
534
+ removeExistingDefinition(content, definition) {
535
+ const parsed = parseHelperMethodDefinition(definition);
536
+ if (!parsed) {
537
+ return content;
538
+ }
539
+ const { methodName, firstParam } = parsed;
540
+ let contentLines = content.split("\n");
541
+ let openingLineIndex = -1;
542
+ for (let i = 0; i < contentLines.length; i++) {
543
+ const line = contentLines[i];
544
+ if (line.trim().startsWith(`.${methodName}(`)) {
545
+ if (firstParam && line.includes(firstParam)) {
546
+ openingLineIndex = i;
547
+ break;
548
+ }
549
+ }
550
+ }
551
+ if (openingLineIndex === -1) {
552
+ return content;
553
+ }
554
+ let closingLineIndex = -1;
555
+ let parenCount = 0;
556
+ let braceCount = 0;
557
+ let foundOpening = false;
558
+ for (let i = openingLineIndex; i < contentLines.length; i++) {
559
+ const line = contentLines[i];
560
+ for (const char of line) {
561
+ if (char === "(") {
562
+ parenCount++;
563
+ foundOpening = true;
564
+ } else if (char === ")") {
565
+ parenCount--;
566
+ if (foundOpening && parenCount === 0 && braceCount === 0) {
567
+ closingLineIndex = i;
568
+ break;
569
+ }
570
+ } else if (char === "{") {
571
+ braceCount++;
572
+ } else if (char === "}") {
573
+ braceCount--;
574
+ }
575
+ }
576
+ if (closingLineIndex !== -1) {
577
+ break;
578
+ }
579
+ }
580
+ if (closingLineIndex === -1) {
581
+ this.logger.warn(
582
+ "Could not find closing parenthesis for existing definition"
583
+ );
584
+ return content;
585
+ }
586
+ contentLines.splice(
587
+ openingLineIndex,
588
+ closingLineIndex - openingLineIndex + 1
589
+ );
590
+ return contentLines.join("\n");
591
+ }
592
+ /**
593
+ * Adds a definition to the content by finding the appropriate place to insert it.
594
+ * @param content - The current file content
595
+ * @param definition - The definition to add
596
+ * @returns The updated content with the new definition
597
+ */
598
+ addDefinitionToContent(content, definition) {
599
+ const lines = content.split("\n");
600
+ const lastLineIndex = lines.length - 1;
601
+ let insertIndex = lastLineIndex;
602
+ for (let i = lastLineIndex; i >= 0; i--) {
603
+ const line = lines[i].trim();
604
+ if (line && !line.startsWith("}")) {
605
+ insertIndex = i;
606
+ break;
607
+ }
608
+ }
609
+ lines.splice(insertIndex + 1, 0, ` ${definition}`);
610
+ return lines.join("\n");
611
+ }
612
+ /**
613
+ * Normalises semicolons in the config file by removing them from method chain calls
614
+ * while preserving them in other contexts (imports, declarations, etc.).
615
+ * @param content - The file content to normalise
616
+ * @returns The normalised content
617
+ */
618
+ normaliseSemicolons(content) {
619
+ const lines = content.split("\n");
620
+ const configureFunctionStart = lines.findIndex(
621
+ (line) => line.trim().startsWith("export default function")
622
+ );
623
+ if (configureFunctionStart === -1) {
624
+ return content;
625
+ }
626
+ const appLineIndex = lines.findIndex(
627
+ (line, index) => index > configureFunctionStart && line.trim().startsWith("app")
628
+ );
629
+ if (appLineIndex === -1) {
630
+ return content;
631
+ }
632
+ let braceCount = 0;
633
+ let functionEndIndex = lines.length - 1;
634
+ for (let i = configureFunctionStart; i < lines.length; i++) {
635
+ const line = lines[i];
636
+ for (const char of line) {
637
+ if (char === "{") braceCount++;
638
+ if (char === "}") {
639
+ braceCount--;
640
+ if (braceCount === 0) {
641
+ functionEndIndex = i;
642
+ break;
643
+ }
644
+ }
645
+ }
646
+ if (braceCount === 0 && i > configureFunctionStart) {
647
+ break;
648
+ }
649
+ }
650
+ let lastMethodCallIndex = -1;
651
+ for (let i = appLineIndex + 1; i < functionEndIndex; i++) {
652
+ const line = lines[i];
653
+ const trimmed = line.trim();
654
+ if ((trimmed.endsWith(")") || trimmed.endsWith(");")) && !trimmed.startsWith("//")) {
655
+ lines[i] = line.replace(/;\s*$/, "");
656
+ lastMethodCallIndex = i;
657
+ }
658
+ }
659
+ if (lastMethodCallIndex !== -1 && !lines[lastMethodCallIndex].trim().endsWith(";")) {
660
+ lines[lastMethodCallIndex] = lines[lastMethodCallIndex] + ";";
661
+ }
662
+ return lines.join("\n");
663
+ }
664
+ };
665
+
666
+ // src/generators/base/wasp-generator.base.ts
667
+ var WaspGeneratorBase = class extends GeneratorBase {
668
+ constructor(fileSystem = realFileSystem, logger = singletonLogger2) {
669
+ super(fileSystem, logger);
670
+ this.fileSystem = fileSystem;
671
+ this.logger = logger;
672
+ this.configGenerator = new WaspConfigGenerator(logger, fileSystem);
673
+ this.templateUtility = new TemplateUtility(fileSystem);
674
+ this.templateResolver = new TemplateResolver(fileSystem);
675
+ }
676
+ configGenerator;
677
+ templateUtility;
678
+ templateResolver;
679
+ swarmConfig;
680
+ configLoaded = false;
681
+ // Plugin name from swarm.config.json
682
+ pluginName = PLUGIN_NAME;
683
+ async loadSwarmConfig() {
684
+ if (this.configLoaded) return;
685
+ const configManager = new SwarmConfigManager();
686
+ this.swarmConfig = await configManager.loadConfig();
687
+ this.configLoaded = true;
688
+ }
689
+ async getCustomTemplateDir() {
690
+ await this.loadSwarmConfig();
691
+ return this.swarmConfig?.templateDirectory;
692
+ }
693
+ /**
694
+ * Resolves template path with override support
695
+ */
696
+ async getTemplatePath(templateName) {
697
+ const defaultPath = this.getDefaultTemplatePath(templateName);
698
+ const customPath = await this.getCustomTemplateDir();
699
+ if (!customPath) {
700
+ return defaultPath;
701
+ }
702
+ const { path: resolvedPath, isCustom } = this.templateResolver.resolveTemplatePath(
703
+ this.pluginName,
704
+ this.name,
705
+ templateName,
706
+ defaultPath,
707
+ customPath
708
+ );
709
+ if (isCustom) {
710
+ this.logger.info(`Using custom template: ${resolvedPath}`);
711
+ }
712
+ return resolvedPath;
713
+ }
714
+ /**
715
+ * Processes a template and writes the result to a file
716
+ */
717
+ async renderTemplateToFile(templateName, replacements, outputPath, readableFileType, force) {
718
+ const templatePath = await this.getTemplatePath(templateName);
719
+ const fileExists = this.checkFileExists(
720
+ outputPath,
721
+ force,
722
+ readableFileType
723
+ );
724
+ const content = this.templateUtility.processTemplate(
725
+ templatePath,
726
+ replacements
727
+ );
728
+ this.writeFile(outputPath, content, readableFileType, fileExists);
729
+ return fileExists;
730
+ }
731
+ /**
732
+ * Generic existence check with force flag handling
733
+ * Consolidates the pattern used in both file and config checks
734
+ */
735
+ checkExistence(exists, itemDescription, force, errorMessage) {
736
+ if (exists && !force) {
737
+ this.logger.error(`${itemDescription}. Use --force to overwrite`);
738
+ throw new Error(errorMessage || itemDescription);
739
+ }
740
+ return exists;
741
+ }
742
+ /**
743
+ * Checks if a file exists and handles force flag logic
744
+ */
745
+ checkFileExists(filePath, force, fileType) {
746
+ const fileExists = this.fileSystem.existsSync(filePath);
747
+ return this.checkExistence(
748
+ fileExists,
749
+ `${fileType} already exists: ${filePath}`,
750
+ force,
751
+ `${fileType} already exists`
752
+ );
753
+ }
754
+ /**
755
+ * Safely writes a file with proper error handling and logging
756
+ */
757
+ writeFile(filePath, content, fileType, fileExists) {
758
+ this.fileSystem.writeFileSync(filePath, content);
759
+ this.logger.success(
760
+ `${fileExists ? "Overwrote" : "Generated"} ${fileType}: ${filePath}`
761
+ );
762
+ }
763
+ };
764
+
765
+ // src/generators/feature/schema.ts
766
+ import { z as z2 } from "zod";
767
+ var schema = z2.object({
768
+ target: commonSchemas.target
769
+ });
770
+
771
+ // src/generators/feature/feature-generator.ts
772
+ var FeatureGenerator = class extends WaspGeneratorBase {
773
+ constructor(logger = singletonLogger3, fileSystem = realFileSystem) {
774
+ super(fileSystem, logger);
775
+ this.logger = logger;
776
+ this.fileSystem = fileSystem;
777
+ this.name = "feature";
778
+ this.description = "Generates a feature directory containing a Wasp configuration file";
779
+ }
780
+ name;
781
+ description;
782
+ schema = schema;
783
+ getDefaultTemplatePath(templateName) {
784
+ return this.templateUtility.resolveTemplatePath(
785
+ templateName,
786
+ this.name,
787
+ import.meta.url
788
+ );
789
+ }
790
+ /**
791
+ * Generates a feature directory containing a Wasp configuration file
792
+ * @param target - The target path of the generated directory
793
+ */
794
+ async generate(args) {
795
+ const { target } = args;
796
+ const segments = validateFeaturePath2(target);
797
+ const normalisedPath = normaliseFeaturePath(target);
798
+ const sourceRoot = path5.join(findWaspRoot(this.fileSystem), "src");
799
+ if (segments.length > 1) {
800
+ const parentPath = segments.slice(0, -1).join("/");
801
+ const parentNormalisedPath = normaliseFeaturePath(parentPath);
802
+ const parentFeatureDir = path5.join(sourceRoot, parentNormalisedPath);
803
+ if (!this.fileSystem.existsSync(parentFeatureDir)) {
804
+ handleFatalError2(
805
+ `Parent feature '${parentPath}' does not exist. Please create it first.`
806
+ );
807
+ }
808
+ }
809
+ const featureDir = path5.join(sourceRoot, normalisedPath);
810
+ this.fileSystem.mkdirSync(featureDir, { recursive: true });
811
+ this.configGenerator.generate(normalisedPath);
812
+ this.logger.success(`Generated feature: ${normalisedPath}`);
813
+ }
814
+ };
815
+
816
+ // src/generators/base/component-generator.base.ts
817
+ var ComponentGeneratorBase = class extends WaspGeneratorBase {
818
+ constructor(logger = singletonLogger4, fileSystem = realFileSystem, featureDirectoryGenerator = new FeatureGenerator(logger, fileSystem)) {
819
+ super(fileSystem, logger);
820
+ this.logger = logger;
821
+ this.fileSystem = fileSystem;
822
+ this.featureDirectoryGenerator = featureDirectoryGenerator;
823
+ this.featureDirectoryGenerator = featureDirectoryGenerator;
824
+ }
825
+ getDefaultTemplatePath(templateName) {
826
+ return this.templateUtility.resolveTemplatePath(
827
+ templateName,
828
+ this.name,
829
+ import.meta.url
830
+ );
831
+ }
832
+ get name() {
833
+ return toKebabCase2(this.componentType);
834
+ }
835
+ /**
836
+ * Validates that the feature config file exists in the target or ancestor directories
837
+ */
838
+ validateFeatureConfig(featurePath) {
839
+ const normalisedPath = normaliseFeaturePath(featurePath);
840
+ const segments = normalisedPath.split("/");
841
+ for (let i = segments.length; i > 0; i--) {
842
+ const pathSegments = segments.slice(0, i);
843
+ const currentPath = pathSegments.join("/");
844
+ const featureName = pathSegments[pathSegments.length - 1];
845
+ const featureDir = getFeatureDir(this.fileSystem, currentPath);
846
+ const configPath = path6.join(featureDir, `feature.wasp.ts`);
847
+ if (this.fileSystem.existsSync(configPath)) {
848
+ return configPath;
849
+ }
850
+ }
851
+ this.logger.error(
852
+ `Feature config file not found in '${normalisedPath}' or any ancestor directories`
853
+ );
854
+ this.logger.error(
855
+ `Expected to find a feature.wasp.ts config file in one of the feature directories`
856
+ );
857
+ throw new Error("Feature config file not found");
858
+ }
859
+ /**
860
+ * Checks if a config item already exists in the feature config
861
+ */
862
+ checkConfigExists(configPath, methodName, itemName, force) {
863
+ const configContent = this.fileSystem.readFileSync(configPath, "utf8");
864
+ const configExists = hasHelperMethodCall(
865
+ configContent,
866
+ methodName,
867
+ itemName
868
+ );
869
+ return this.checkExistence(
870
+ configExists,
871
+ `${methodName} config already exists in ${configPath}`,
872
+ force,
873
+ `${methodName} config already exists`
874
+ );
875
+ }
876
+ /**
877
+ * Updates the feature config with a new definition
878
+ */
879
+ updateFeatureConfig(featurePath, definition, configPath, configExists, methodName) {
880
+ this.configGenerator.update(featurePath, definition);
881
+ this.logger.success(
882
+ `${configExists ? "Updated" : "Added"} ${methodName} config in: ${configPath}`
883
+ );
884
+ }
885
+ /**
886
+ * Consolidated helper for updating config files with existence check
887
+ * This replaces the duplicated updateConfigFile pattern in concrete generators
888
+ */
889
+ updateConfigWithCheck(configPath, methodName, entityName, definition, featurePath, force) {
890
+ const configExists = this.checkConfigExists(
891
+ configPath,
892
+ methodName,
893
+ entityName,
894
+ force
895
+ );
896
+ if (!configExists || force) {
897
+ this.updateFeatureConfig(
898
+ featurePath,
899
+ definition,
900
+ configPath,
901
+ configExists,
902
+ methodName
903
+ );
904
+ }
905
+ }
906
+ /**
907
+ * Gets the appropriate directory for a feature based on its path.
908
+ * @param fileSystem - The filesystem abstraction
909
+ * @param featurePath - The full feature path
910
+ * @param type - The type of file being generated
911
+ * @returns The target directory and import path
912
+ */
913
+ getFeatureTargetDir(fileSystem, featurePath, type) {
914
+ validateFeaturePath3(featurePath);
915
+ const normalisedPath = normaliseFeaturePath(featurePath);
916
+ const featureDir = getFeatureDir(fileSystem, normalisedPath);
917
+ const typeKey = type.toLowerCase();
918
+ const typeDirectory = TYPE_DIRECTORIES[typeKey];
919
+ const targetDirectory = path6.join(featureDir, typeDirectory);
920
+ const importDirectory = `@src/${normalisedPath}/${typeDirectory}`;
921
+ return { targetDirectory, importDirectory };
922
+ }
923
+ /**
924
+ * Ensures a target directory exists and returns its path
925
+ */
926
+ ensureTargetDirectory(featurePath, type) {
927
+ const { targetDirectory, importDirectory } = this.getFeatureTargetDir(
928
+ this.fileSystem,
929
+ featurePath,
930
+ type
931
+ );
932
+ ensureDirectoryExists(this.fileSystem, targetDirectory);
933
+ return { targetDirectory, importDirectory };
934
+ }
935
+ /**
936
+ * Generate middleware file for API or API namespace
937
+ */
938
+ async generateMiddlewareFile(targetFile, name, force) {
939
+ const replacements = {
940
+ name,
941
+ middlewareType: toCamelCase(this.componentType || "")
942
+ };
943
+ await this.renderTemplateToFile(
944
+ "middleware.eta",
945
+ replacements,
946
+ targetFile,
947
+ "Middleware file",
948
+ force
949
+ );
950
+ }
951
+ };
952
+
953
+ // src/generators/base/operation-generator.base.ts
954
+ import {
955
+ capitalise,
956
+ getPlural,
957
+ handleFatalError as handleFatalError3,
958
+ toPascalCase as toPascalCase2
959
+ } from "@ingenyus/swarm";
960
+
961
+ // src/generators/api/schema.ts
962
+ import { commandRegistry as commandRegistry2 } from "@ingenyus/swarm";
963
+ import { z as z3 } from "zod";
964
+ var validHttpMethods = API_HTTP_METHODS.map((method) => `${method}`);
965
+ var schema2 = z3.object({
966
+ method: z3.string().min(1, "HTTP method is required").transform((val) => val.toUpperCase()).pipe(
967
+ z3.enum(API_HTTP_METHODS, {
968
+ message: `Invalid HTTP method. Must be one of: ${validHttpMethods.join(", ")}`
969
+ })
970
+ ).meta({ description: "The HTTP method used for this API Endpoint" }).register(commandRegistry2, {
971
+ shortName: "m",
972
+ examples: validHttpMethods,
973
+ helpText: `Must be one of: ${validHttpMethods.join(", ")}`
974
+ }),
975
+ feature: commonSchemas.feature,
976
+ name: commonSchemas.name,
977
+ path: commonSchemas.path,
978
+ entities: commonSchemas.entities,
979
+ auth: commonSchemas.auth,
980
+ force: commonSchemas.force,
981
+ customMiddleware: z3.boolean().meta({ description: "Enable custom middleware for this API Endpoint" }).optional().register(commandRegistry2, {
982
+ shortName: "c",
983
+ helpText: "Will generate custom middleware file"
984
+ })
985
+ });
986
+
987
+ // src/generators/api/api-generator.ts
988
+ var ApiGenerator = class extends ComponentGeneratorBase {
989
+ get componentType() {
990
+ return CONFIG_TYPES.API;
991
+ }
992
+ description = "Generates a Wasp API Endpoint";
993
+ schema = schema2;
994
+ async generate(args) {
995
+ const apiName = toCamelCase2(args.name);
996
+ return this.handleGeneratorError(this.componentType, apiName, async () => {
997
+ const configPath = this.validateFeatureConfig(args.feature);
998
+ const {
999
+ targetDirectory: apiTargetDirectory,
1000
+ importDirectory: apiImportDirectory
1001
+ } = this.ensureTargetDirectory(args.feature, this.name);
1002
+ const fileName = `${apiName}.ts`;
1003
+ const targetFile = `${apiTargetDirectory}/${fileName}`;
1004
+ await this.generateApiFile(targetFile, apiName, args);
1005
+ if (args.customMiddleware) {
1006
+ const { targetDirectory: middlewareTargetDirectory } = this.ensureTargetDirectory(args.feature, "middleware");
1007
+ const middlewareFile = `${middlewareTargetDirectory}/${apiName}.ts`;
1008
+ this.generateMiddlewareFile(
1009
+ middlewareFile,
1010
+ apiName,
1011
+ args.force || false
1012
+ );
1013
+ }
1014
+ await this.updateConfigFile(
1015
+ apiName,
1016
+ fileName,
1017
+ apiImportDirectory,
1018
+ args,
1019
+ configPath
1020
+ );
1021
+ });
1022
+ }
1023
+ async generateApiFile(targetFile, apiName, { method, auth = false, force = false }) {
1024
+ const replacements = this.buildTemplateData(apiName, method, auth);
1025
+ await this.renderTemplateToFile(
1026
+ "api.eta",
1027
+ replacements,
1028
+ targetFile,
1029
+ "API Endpoint file",
1030
+ force
1031
+ );
1032
+ }
1033
+ async updateConfigFile(apiName, apiFile, importDirectory, args, configFilePath) {
1034
+ const {
1035
+ feature,
1036
+ force = false,
1037
+ entities,
1038
+ method,
1039
+ path: path7,
1040
+ auth,
1041
+ customMiddleware
1042
+ } = args;
1043
+ const importPath = this.path.join(importDirectory, apiFile);
1044
+ const definition = await this.getConfigDefinition(
1045
+ apiName,
1046
+ feature,
1047
+ Array.isArray(entities) ? entities : entities ? [entities] : [],
1048
+ method,
1049
+ path7,
1050
+ apiFile,
1051
+ auth,
1052
+ importPath,
1053
+ customMiddleware || false
1054
+ );
1055
+ this.updateConfigWithCheck(
1056
+ configFilePath,
1057
+ "addApi",
1058
+ apiName,
1059
+ definition,
1060
+ feature,
1061
+ force
1062
+ );
1063
+ }
1064
+ async getConfigDefinition(apiName, featurePath, entities, method, route, apiFile, auth = false, importPath, customMiddleware = false) {
1065
+ const featureDir = getFeatureImportPath(featurePath);
1066
+ const configTemplatePath = await this.getTemplatePath("config/api.eta");
1067
+ return this.templateUtility.processTemplate(configTemplatePath, {
1068
+ apiName,
1069
+ featureDir,
1070
+ entities: entities.map((e) => `"${e}"`).join(", "),
1071
+ method,
1072
+ route,
1073
+ apiFile,
1074
+ auth: String(auth),
1075
+ importPath,
1076
+ customMiddleware: String(customMiddleware)
1077
+ });
1078
+ }
1079
+ buildTemplateData(apiName, method, auth) {
1080
+ const apiType = toPascalCase3(apiName);
1081
+ const authCheck = auth ? ` if (!context.user) {
1082
+ throw new HttpError(401);
1083
+ }
1084
+
1085
+ ` : "";
1086
+ const methodCheck = method !== "ALL" ? ` if (req.method !== '${method}') {
1087
+ throw new HttpError(405);
1088
+ }
1089
+
1090
+ ` : "";
1091
+ const errorImport = auth || method !== "ALL" ? 'import { HttpError } from "wasp/server";\n' : "";
1092
+ const imports = `${errorImport}import type { ${apiType} } from "wasp/server/api";`;
1093
+ return {
1094
+ imports,
1095
+ apiType,
1096
+ apiName,
1097
+ methodCheck,
1098
+ authCheck
1099
+ };
1100
+ }
1101
+ };
1102
+ export {
1103
+ ApiGenerator
1104
+ };