@domain-first/project-structure 8.10.1 → 8.12.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 (58) hide show
  1. package/README.md +17 -7
  2. package/dist/287.js +406 -788
  3. package/dist/364.js +79 -0
  4. package/dist/38.js +31 -14
  5. package/dist/561.js +179 -96
  6. package/dist/783.js +1147 -0
  7. package/dist/{201.js → 878.js} +465 -2
  8. package/dist/agent-cli.d.ts +17 -6
  9. package/dist/agent-requests.d.ts +82 -8
  10. package/dist/config-file.d.ts +25 -1
  11. package/dist/frontend-cli.d.ts +3 -0
  12. package/dist/frontend-modules.d.ts +14 -0
  13. package/dist/graph.cjs +125 -5
  14. package/dist/graph.js +1 -1
  15. package/dist/index.cjs +3545 -2930
  16. package/dist/index.js +1 -1
  17. package/dist/init.cjs +368 -83
  18. package/dist/init.js +1 -1
  19. package/dist/integration.cjs +3545 -2930
  20. package/dist/integration.js +1 -1
  21. package/dist/integrations/openapi.d.ts +19 -2
  22. package/dist/integrations/orval.d.ts +31 -4
  23. package/dist/integrations/rest-endpoint-generator.d.ts +11 -7
  24. package/dist/integrations/storybook.d.ts +19 -1
  25. package/dist/lint.cjs +159 -22
  26. package/dist/lint.js +2 -2
  27. package/dist/page-router.d.ts +18 -0
  28. package/dist/react-module-move.d.ts +47 -14
  29. package/dist/react.cjs +1645 -999
  30. package/dist/react.js +2 -102
  31. package/dist/rest-adapters.d.ts +13 -0
  32. package/dist/svelte-agent-cli.spec.d.ts +1 -0
  33. package/dist/svelte.cjs +7373 -0
  34. package/dist/svelte.d.ts +2 -0
  35. package/dist/svelte.js +3 -0
  36. package/dist/sveltekit-app.d.ts +7 -0
  37. package/dist/upgrade-steps.d.ts +6 -1
  38. package/dist/upgrade-svelte.d.ts +15 -0
  39. package/dist/upgrade-svelte.spec.d.ts +1 -0
  40. package/dist/upgrade.cjs +307 -42
  41. package/dist/upgrade.js +132 -13
  42. package/dist/use-cases/add-integration.d.ts +1 -1
  43. package/dist/use-cases/delete-react-module.d.ts +4 -4
  44. package/dist/use-cases/index.d.ts +1 -0
  45. package/dist/use-cases/move-react-module.d.ts +2 -2
  46. package/dist/use-cases/rest-endpoint-generator.d.ts +6 -4
  47. package/dist/use-cases/scaffold-svelte-modules.d.ts +27 -0
  48. package/package.json +2 -1
  49. package/skills/df-ps-implement/SKILL.md +3 -3
  50. package/skills/df-ps-plan-feature/SKILL.md +1 -1
  51. package/skills/df-ps-scaffold/SKILL.md +9 -8
  52. package/skills/df-ps-scaffold/references/agent-mode.md +1 -1
  53. package/skills/df-ps-scaffold/references/agent-operations.md +8 -4
  54. package/skills/df-ps-scaffold/references/generators.md +1 -1
  55. package/skills/df-ps-scaffold/references/work-plan.md +1 -1
  56. package/skills/df-ps-svelte/SKILL.md +54 -0
  57. package/skills/df-ps-svelte/references/generators.md +56 -0
  58. package/dist/115.js +0 -615
package/dist/783.js ADDED
@@ -0,0 +1,1147 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { Separator, checkbox as prompts_checkbox, confirm as prompts_confirm, input, search, select as prompts_select } from "@inquirer/prompts";
3
+ import node_path from "node:path";
4
+ import node_fs from "node:fs";
5
+ import { addImport, addWireDependencies, routePageFile, addConstructorParameters, UnknownFormatNaming, ConfigFile, Folder, relativeImport as wiring_relativeImport, NestedName, File, ProjectRoot, addClassMember, compilerOption } from "./878.js";
6
+ const isSeparator = (choice)=>'function' == typeof Separator && choice instanceof Separator || 'object' == typeof choice && null !== choice && 'separator' === choice.type;
7
+ class RequestError extends Error {
8
+ code;
9
+ details;
10
+ constructor(code, message, details){
11
+ super(message), this.code = code, this.details = details;
12
+ }
13
+ }
14
+ const storage = new AsyncLocalStorage();
15
+ const isNonInteractive = ()=>Boolean(storage.getStore());
16
+ const runWithAnswers = async (answers, defaults, run)=>storage.run({
17
+ answers,
18
+ defaults,
19
+ used: new Set(),
20
+ messages: []
21
+ }, async ()=>{
22
+ const result = await run();
23
+ const state = storage.getStore();
24
+ assertAnswersConsumed();
25
+ return {
26
+ result,
27
+ messages: state.messages
28
+ };
29
+ });
30
+ const assertAnswersConsumed = ()=>{
31
+ const state = storage.getStore();
32
+ if (!state) return;
33
+ const unused = Object.keys(state.answers).filter((key)=>!state.used.has(key));
34
+ if (unused.length) throw new RequestError('UNUSED_PARAMETERS', 'Some parameters do not apply to this operation.', {
35
+ fields: unused
36
+ });
37
+ };
38
+ const answerFor = (key, fallback)=>{
39
+ const state = storage.getStore();
40
+ if (!state) return;
41
+ if (Object.hasOwn(state.answers, key)) {
42
+ state.used.add(key);
43
+ return state.answers[key];
44
+ }
45
+ return Object.hasOwn(state.defaults, key) ? state.defaults[key] : fallback;
46
+ };
47
+ const report = (...values)=>{
48
+ const state = storage.getStore();
49
+ if (state) state.messages.push(values.map(String).join(' '));
50
+ else console.log(...values);
51
+ };
52
+ const requireKey = (key)=>{
53
+ if (!key) throw new RequestError('UNSUPPORTED_PROMPT', 'This operation needs an answer that is not supported in non-interactive mode.');
54
+ return key;
55
+ };
56
+ const interaction_missing = (key)=>new RequestError('MISSING_PARAMETER', `Provide ${key}.`, {
57
+ field: key
58
+ });
59
+ const interaction_input = async (config)=>{
60
+ const { key, ...interactive } = config;
61
+ if (!isNonInteractive()) return input(interactive);
62
+ const field = requireKey(key);
63
+ const value = answerFor(field, config.default);
64
+ if ('string' != typeof value) throw interaction_missing(field);
65
+ const valid = await config.validate?.(value);
66
+ if (void 0 !== valid && true !== valid) throw new RequestError('INVALID_PARAMETER', 'string' == typeof valid ? valid : `Invalid ${field}.`, {
67
+ field
68
+ });
69
+ return value;
70
+ };
71
+ const interaction_confirm = async (config)=>{
72
+ const { key, requestRequired, ...interactive } = config;
73
+ if (!isNonInteractive()) return prompts_confirm(interactive);
74
+ const field = requireKey(key);
75
+ const value = answerFor(field, requestRequired ? void 0 : config.default ?? false);
76
+ if (void 0 === value) throw interaction_missing(field);
77
+ if ('boolean' != typeof value) throw new RequestError('INVALID_PARAMETER', `${field} must be a boolean.`, {
78
+ field
79
+ });
80
+ return value;
81
+ };
82
+ const choicesOf = (config)=>config.choices.filter((choice)=>!isSeparator(choice)).map((choice)=>'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
83
+ value: choice
84
+ });
85
+ const choiceId = (choice, id)=>id?.(choice.value) ?? choice.value;
86
+ const resolveChoice = (value, choices, key, id)=>{
87
+ const matches = choices.filter((choice)=>Object.is(choice.value, value) || choiceId(choice, id) === value);
88
+ if (1 !== matches.length || matches[0].disabled) throw new RequestError('INVALID_CHOICE', `Invalid or unavailable choice for ${key}.`, {
89
+ field: key,
90
+ value,
91
+ choices: choices.filter((choice)=>!choice.disabled).map((choice)=>choiceId(choice, id))
92
+ });
93
+ return matches[0].value;
94
+ };
95
+ const searchThreshold = 10;
96
+ const choiceLabel = (choice)=>choice.name ?? String(choice.value);
97
+ const filterChoices = (choices, term)=>{
98
+ const text = (term ?? '').trim().toLowerCase();
99
+ const words = text.split(/\s+/).filter(Boolean);
100
+ if (!words.length) return [
101
+ ...choices
102
+ ];
103
+ const groups = [
104
+ {
105
+ matches: []
106
+ }
107
+ ];
108
+ for (const choice of choices){
109
+ if (isSeparator(choice)) {
110
+ groups.push({
111
+ separator: choice,
112
+ matches: []
113
+ });
114
+ continue;
115
+ }
116
+ const normalized = 'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
117
+ value: choice
118
+ };
119
+ const label = choiceLabel(normalized).toLowerCase();
120
+ if (words.every((word)=>label.includes(word))) groups.at(-1)?.matches.push({
121
+ choice: normalized,
122
+ prefix: label.startsWith(text)
123
+ });
124
+ }
125
+ const byPrefix = (items, prefix)=>[
126
+ ...items.filter(prefix),
127
+ ...items.filter((item)=>!prefix(item))
128
+ ];
129
+ const [ungrouped, ...grouped] = groups;
130
+ return [
131
+ ungrouped,
132
+ ...byPrefix(grouped.filter(({ matches })=>matches.length), ({ matches })=>matches.some(({ prefix })=>prefix))
133
+ ].flatMap(({ separator, matches })=>[
134
+ ...separator ? [
135
+ separator
136
+ ] : [],
137
+ ...byPrefix(matches, ({ prefix })=>prefix).map(({ choice })=>choice)
138
+ ]);
139
+ };
140
+ const interaction_select = async (config)=>{
141
+ const { key, id, ...interactive } = config;
142
+ if (!isNonInteractive()) {
143
+ if (choicesOf(config).length <= searchThreshold) return prompts_select(interactive);
144
+ return search({
145
+ message: `${config.message.trimEnd()} (type to filter)`,
146
+ source: (term)=>filterChoices(config.choices, term),
147
+ pageSize: config.pageSize,
148
+ default: config.default
149
+ });
150
+ }
151
+ const field = requireKey(key);
152
+ const value = answerFor(field, config.default);
153
+ if (void 0 === value) throw interaction_missing(field);
154
+ return resolveChoice(value, choicesOf(config), field, id);
155
+ };
156
+ const interaction_checkbox = async (config)=>{
157
+ const { key, id, ...interactive } = config;
158
+ if (!isNonInteractive()) return prompts_checkbox(interactive);
159
+ const field = requireKey(key);
160
+ const choices = choicesOf(config);
161
+ const values = answerFor(field, choices.filter((choice)=>choice.checked && !choice.disabled).map((choice)=>choice.value));
162
+ if (!Array.isArray(values)) throw new RequestError('INVALID_PARAMETER', `${field} must be an array.`, {
163
+ field
164
+ });
165
+ const selected = values.map((value)=>resolveChoice(value, choices, field, id));
166
+ if (new Set(selected).size !== selected.length) throw new RequestError('INVALID_PARAMETER', `Duplicate choices for ${field}.`, {
167
+ field
168
+ });
169
+ if (config.required && !selected.length) throw interaction_missing(field);
170
+ return selected;
171
+ };
172
+ const addPackageScripts = async (file, additions)=>{
173
+ const original = file.data;
174
+ const manifest = JSON.parse(original);
175
+ const scripts = {
176
+ ...manifest.scripts
177
+ };
178
+ const selected = {};
179
+ for (const [name, command] of Object.entries(additions)){
180
+ let target = name;
181
+ if (Object.hasOwn(scripts, name) && scripts[name] !== command) {
182
+ const action = await interaction_select({
183
+ key: `scriptConflicts.${name}`,
184
+ message: `Script "${name}" already exists: ${scripts[name]}`,
185
+ choices: [
186
+ 'Keep existing',
187
+ 'Replace',
188
+ 'Use another name'
189
+ ]
190
+ });
191
+ if ('Keep existing' === action) continue;
192
+ if ('Use another name' === action) target = await interaction_input({
193
+ key: `scriptNames.${name}`,
194
+ message: "New script name:",
195
+ validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
196
+ });
197
+ }
198
+ scripts[target] = command;
199
+ selected[name] = target;
200
+ }
201
+ if (JSON.stringify(manifest.scripts) !== JSON.stringify(scripts)) {
202
+ manifest.scripts = scripts;
203
+ const indent = original.match(/\n([\t ]+)"/)?.[1] ?? ' ';
204
+ file.update(`${JSON.stringify(manifest, null, indent)}\n`);
205
+ }
206
+ return selected;
207
+ };
208
+ const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
209
+ const inMemoryImplementationType = 'in-memory';
210
+ const className = 'InMemoryDbInfrastructureService';
211
+ const wireName = 'wireInMemoryDbInfrastructureService';
212
+ const parameterName = 'inMemoryDbInfrastructureService';
213
+ const legacyWithIdLookup = ` withId: (id: TId): T | null =>
214
+ items().find(
215
+ (x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
216
+ ) ?? null,
217
+ `;
218
+ const legacyHasId = `const hasId = (x: unknown): x is { id: unknown } =>
219
+ typeof x === 'object' && x !== null && 'id' in x;
220
+
221
+ `;
222
+ const withIdLookup = ` withId: (id: TId): T | null =>
223
+ globalThis.___SHARED_IN_MEMORY_DB___![key].find((entry) =>
224
+ idsAreEqual(entry.id as TId, id)
225
+ )?.item ?? null,
226
+ `;
227
+ const inMemoryDbService = `type Entry = {
228
+ id: unknown;
229
+ item: any;
230
+ };
231
+
232
+ declare global {
233
+ var ___SHARED_IN_MEMORY_DB___: Record<string, Array<Entry>> | undefined;
234
+ }
235
+
236
+ type Section<T, TId> = {
237
+ all: (predicate?: (x: T) => boolean) => T[];
238
+ first: (predicate: (x: T) => boolean) => T | null;
239
+ withId: (id: TId) => T | null;
240
+ lastAddedItem: () => T | null;
241
+ save: (payload: T extends { id: TId } ? T : [TId, T]) => void;
242
+ deleteById: (id: TId) => void;
243
+ delete: (predicate: (x: T) => boolean) => void;
244
+ };
245
+
246
+ type IdsAreEqual<TId> = (a: TId, b: TId) => boolean;
247
+
248
+ const comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;
249
+
250
+ const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
251
+ if (typeof a !== 'object' || a === null) {
252
+ return Object.is(a, b);
253
+ }
254
+
255
+ for (const methodName of comparisonMethodNames) {
256
+ const method: unknown = (a as Record<string, unknown>)[methodName];
257
+ if (typeof method === 'function') {
258
+ return Boolean(method.call(a, b));
259
+ }
260
+ }
261
+
262
+ return Object.is(a, b);
263
+ };
264
+
265
+ export class InMemoryDbInfrastructureService {
266
+ protected section<T extends { id: unknown }>(
267
+ key: string,
268
+ idsAreEqual?: IdsAreEqual<T['id']>
269
+ ): Section<T, T['id']>;
270
+ protected section<T, TId>(
271
+ key: string,
272
+ idsAreEqual?: IdsAreEqual<TId>
273
+ ): Section<T, TId>;
274
+ protected section<T, TId>(
275
+ key: string,
276
+ idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual
277
+ ): Section<T, TId> {
278
+ if (!globalThis.___SHARED_IN_MEMORY_DB___) {
279
+ globalThis.___SHARED_IN_MEMORY_DB___ = {};
280
+ }
281
+
282
+ if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
283
+ globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
284
+ }
285
+
286
+ const items = (): T[] =>
287
+ globalThis.___SHARED_IN_MEMORY_DB___![key].map(
288
+ (entry) => entry.item
289
+ );
290
+
291
+ return {
292
+ all: (predicate: (x: T) => boolean = () => true): T[] =>
293
+ items().filter(predicate),
294
+ first: (predicate: (x: T) => boolean): T | null =>
295
+ items().find(predicate) ?? null,
296
+ ${withIdLookup} lastAddedItem: (): T | null =>
297
+ globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
298
+ save: (payload: T extends { id: TId } ? T : [TId, T]) => {
299
+ const id = Array.isArray(payload) ? payload[0] : payload.id;
300
+ const item = Array.isArray(payload) ? payload[1] : payload;
301
+ const entries = globalThis.___SHARED_IN_MEMORY_DB___![key];
302
+ const existing = entries.find((entry) =>
303
+ idsAreEqual(entry.id as TId, id)
304
+ );
305
+ if (existing) {
306
+ existing.item = item;
307
+ return;
308
+ }
309
+ entries.push({ id, item });
310
+ },
311
+ deleteById: (id: TId) => {
312
+ globalThis.___SHARED_IN_MEMORY_DB___![key] =
313
+ globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
314
+ (entry) => !idsAreEqual(entry.id as TId, id)
315
+ );
316
+ },
317
+ delete: (predicate: (x: T) => boolean) => {
318
+ globalThis.___SHARED_IN_MEMORY_DB___![key] =
319
+ globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
320
+ (entry) => !predicate(entry.item)
321
+ );
322
+ }
323
+ };
324
+ }
325
+ }
326
+ `;
327
+ const inMemoryDbWiring = `import { wireClass } from '@domain-first/wire';
328
+ import { InMemoryDbInfrastructureService } from '../../infrastructure/services/in-memory-db-infrastructure-service';
329
+
330
+ export const wireInMemoryDbInfrastructureService = wireClass(
331
+ InMemoryDbInfrastructureService,
332
+ []
333
+ );
334
+ `;
335
+ const withWiring = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
336
+ const sharedFolder = ()=>new Folder(new ProjectRoot().path).subitem([
337
+ ConfigFile.Instance.data.project.rootFolder,
338
+ 'shared-kernel'
339
+ ]);
340
+ const serviceFile = ()=>new File(sharedFolder().path).subitem([
341
+ 'infrastructure',
342
+ 'services',
343
+ 'in-memory-db-infrastructure-service.ts'
344
+ ]);
345
+ const wireFile = ()=>new File(sharedFolder().path).subitem([
346
+ 'wiring',
347
+ 'infrastructure-services',
348
+ 'wire-in-memory-db-infrastructure-service.ts'
349
+ ]);
350
+ const scaffoldInMemoryDb = (shared)=>{
351
+ const servicesFolder = shared.subitem([
352
+ 'infrastructure',
353
+ 'services'
354
+ ]);
355
+ servicesFolder.createFile('in-memory-db-infrastructure-service.ts', inMemoryDbService);
356
+ if (withWiring()) shared.subitem([
357
+ 'wiring',
358
+ 'infrastructure-services'
359
+ ]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
360
+ };
361
+ const inMemoryDbScaffolded = ()=>serviceFile().exists && (!withWiring() || wireFile().exists);
362
+ const usesInMemoryDb = (implementationType)=>Boolean(ConfigFile.Instance.data.backend?.withInMemoryDb) && new UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && inMemoryDbScaffolded();
363
+ const uncountableEndings = [
364
+ 'data',
365
+ 'info',
366
+ 'usage',
367
+ 'feedback',
368
+ 'media',
369
+ 'ware',
370
+ 'equipment',
371
+ 'information',
372
+ 'knowledge',
373
+ 'traffic',
374
+ 'telemetry',
375
+ 'analytics',
376
+ 'series'
377
+ ];
378
+ const uncountable = new RegExp(`(${uncountableEndings.join('|')})$`, 'i');
379
+ const plural = (word)=>{
380
+ if (uncountable.test(word)) return word;
381
+ if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
382
+ if (/(^|[^aeiou]|qu)[aeiou]z$/i.test(word)) return `${word}zes`;
383
+ if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
384
+ return `${word}s`;
385
+ };
386
+ const addInMemoryDbSection = (typeNaming, typeImportTarget)=>{
387
+ const file = serviceFile();
388
+ const sectionNaming = new UnknownFormatNaming(plural(typeNaming.fileName));
389
+ const field = sectionNaming.variableName;
390
+ if (new RegExp(`\\b${field}\\s*=\\s*this\\.section\\b`).test(file.data)) return field;
391
+ const withImport = addImport(file.data, `import type { ${typeNaming.ClassName} } from '${wiring_relativeImport(file.path, typeImportTarget)}';`);
392
+ file.update(addClassMember(withImport, className, `${field} = this.section<${typeNaming.ClassName}>('${sectionNaming.fileName.toUpperCase()}');`));
393
+ return field;
394
+ };
395
+ const inMemoryDbTypeImport = (fromFile)=>`import type { ${className} } from '${wiring_relativeImport(fromFile, serviceFile().path)}'`;
396
+ const inMemoryDbSectionMembers = (field, derived)=>`
397
+ private readonly data: ${className}['${field}']
398
+
399
+ constructor(${parameterName}: ${className}) {
400
+ ${derived ? 'super()\n ' : ''}this.data = ${parameterName}.${field}
401
+ }
402
+ `.trim();
403
+ const keepInMemoryDbSection = (classFile, field)=>{
404
+ classFile.update(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)).replace('constructor() {}', inMemoryDbSectionMembers(field, false)));
405
+ };
406
+ const isInMemoryDb = (module)=>module.wireName === wireName;
407
+ const injectInMemoryDb = (classFile, implementationName)=>{
408
+ classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
409
+ `private readonly ${parameterName}: ${className}`
410
+ ]));
411
+ };
412
+ const wireInMemoryDb = (consumerWireFile, implementationName)=>{
413
+ consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${wireName} } from '${wiring_relativeImport(consumerWireFile.path, wireFile().path)}'`), implementationName, [
414
+ wireName
415
+ ]));
416
+ };
417
+ const hasDependency = (name)=>{
418
+ const manifestFile = new File(node_path.join(new ProjectRoot().path, 'package.json'));
419
+ if (!manifestFile.exists) return false;
420
+ const manifest = JSON.parse(manifestFile.data);
421
+ return [
422
+ manifest.dependencies,
423
+ manifest.devDependencies,
424
+ manifest.optionalDependencies
425
+ ].some((dependencies)=>dependencies && Object.hasOwn(dependencies, name));
426
+ };
427
+ const missingPackages = (packages)=>{
428
+ const missing = [
429
+ ...new Set(packages)
430
+ ].filter((name)=>!hasDependency(name));
431
+ return missing.length ? [
432
+ `npm i ${missing.join(' ')}`
433
+ ] : [];
434
+ };
435
+ const missingDomainFirstPackages = ()=>missingPackages(ConfigFile.backend.domainFirstPackages);
436
+ const usesNext = ()=>ConfigFile.exists && ConfigFile.Instance.data.frontend?.react?.framework === 'next';
437
+ const nextAppFolder = (root)=>[
438
+ 'app',
439
+ 'src/app'
440
+ ].find((folder)=>new Folder(node_path.join(root, folder)).exists) ?? 'app';
441
+ const usesSvelteKit = ()=>ConfigFile.exists && ConfigFile.Instance.data.frontend?.svelte?.framework === 'sveltekit';
442
+ const svelteKitRoutesFolder = (root)=>[
443
+ 'src/routes',
444
+ 'routes'
445
+ ].find((folder)=>new Folder(node_path.join(root, folder)).exists) ?? 'src/routes';
446
+ const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
447
+ ${[
448
+ ...imports,
449
+ "import { type FC } from 'react'"
450
+ ].join('\n')}
451
+
452
+ export type ${ClassName}PageProps = {}
453
+
454
+ export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
455
+ return ${body}
456
+ }
457
+ `.trim();
458
+ const nextRouteContent = (ClassName, pageImport)=>`
459
+ import { ${ClassName}Page } from '${pageImport}'
460
+
461
+ export default function Page() {
462
+ return <${ClassName}Page />
463
+ }
464
+ `.trim();
465
+ const scaffoldNextRoute = (name, pagePath)=>{
466
+ const root = new ProjectRoot().path;
467
+ const route = node_path.join(root, nextAppFolder(root), ...name.folders, name.folderName, 'page.tsx');
468
+ const relativeRoute = node_path.relative(root, route).split(node_path.sep).join('/');
469
+ const routeFile = new File(route);
470
+ const content = nextRouteContent(name.ClassName, wiring_relativeImport(route, pagePath.replace(/\.tsx$/, '')));
471
+ if (routeFile.exists) return routeFile.data === content ? void 0 : `${relativeRoute} already exists: render ${name.ClassName}Page there yourself.`;
472
+ routeFile.data = content;
473
+ };
474
+ const scaffoldReactPage = async (presentationReactFolder)=>{
475
+ const name = await interaction_input({
476
+ key: 'name',
477
+ message: 'Provide name (folders split by "/"):',
478
+ validate: NestedName.validate
479
+ });
480
+ const nestedName = new NestedName(name);
481
+ const { folders, ClassName, fileName } = nestedName;
482
+ const pageFile = presentationReactFolder.subitem([
483
+ 'pages',
484
+ ...folders
485
+ ]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
486
+ if (usesNext()) {
487
+ const hint = scaffoldNextRoute(nestedName, pageFile.path);
488
+ if (hint) report(hint);
489
+ }
490
+ };
491
+ const svelteComponentContent = (propsType)=>`
492
+ <script lang="ts" module>
493
+ export type ${propsType} = {}
494
+ </script>
495
+
496
+ <script lang="ts">
497
+ let props: ${propsType} = $props()
498
+ </script>
499
+ `.trim();
500
+ const svelteStory = (storybookFramework, componentName, componentFile, title)=>`
501
+ import type { Meta, StoryObj } from '${storybookFramework}'
502
+ import ${componentName} from './${componentFile}'
503
+
504
+ const meta = {
505
+ title: '${title}',
506
+ component: ${componentName}
507
+ } satisfies Meta<typeof ${componentName}>
508
+
509
+ export default meta
510
+
511
+ type Story = StoryObj<typeof meta>
512
+
513
+ export const Default: Story = {
514
+ args: {}
515
+ }
516
+ `.trim();
517
+ const svelteUIModelContent = (ClassName, propsType)=>`
518
+ import type { ${ClassName}WidgetProps, ${ClassName}WidgetUIProps } from '../types'
519
+
520
+ /**
521
+ * - widgetProps is the $props() proxy as a whole: destructuring it in the
522
+ * signature (({ a }) =>) or copying it ({ ...props }) loses reactivity
523
+ * - values depending on props: $derived, exposed through getters only
524
+ * - local state: $state; methods: plain functions of the returned object
525
+ * - getters satisfy ${ClassName}WidgetUIProps
526
+ */
527
+ export const create${ClassName}UIModel = (
528
+ widgetProps: ${propsType},
529
+ ): ${ClassName}WidgetUIProps => {
530
+ // derived values go here
531
+ // const value = $derived(widgetProps.value)
532
+
533
+ return {
534
+ // expose values via getters to keep reactivity:
535
+ // get value() { return value },
536
+ }
537
+ }
538
+ `.trim();
539
+ const scaffold_svelte_modules_storybookFramework = ()=>ConfigFile.Instance.data.frontend?.svelte?.storybookFramework;
540
+ const svelteKitRouteContent = (ClassName, pageImport)=>`
541
+ <script lang="ts">
542
+ import ${ClassName}Page from '${pageImport}'
543
+ </script>
544
+
545
+ <${ClassName}Page />
546
+ `.trim();
547
+ const relativeImport = (fromFile, toFile)=>{
548
+ const relative = node_path.relative(node_path.dirname(fromFile), toFile).split(node_path.sep).join('/');
549
+ return relative.startsWith('.') ? relative : `./${relative}`;
550
+ };
551
+ const scaffoldSvelteKitRoute = (name, pagePath)=>{
552
+ const root = new ProjectRoot().path;
553
+ const route = node_path.join(root, svelteKitRoutesFolder(root), ...name.folders, name.folderName, routePageFile.svelte);
554
+ const relativeRoute = node_path.relative(root, route).split(node_path.sep).join('/');
555
+ const routeFile = new File(route);
556
+ const content = svelteKitRouteContent(name.ClassName, relativeImport(route, pagePath));
557
+ if (routeFile.exists) return routeFile.data === content ? void 0 : `${relativeRoute} already exists: render ${name.ClassName}Page there yourself.`;
558
+ routeFile.data = content;
559
+ };
560
+ const scaffoldSveltePage = async (presentationSvelteFolder)=>{
561
+ const name = await interaction_input({
562
+ key: 'name',
563
+ message: 'Provide name (folders split by "/"):',
564
+ validate: NestedName.validate
565
+ });
566
+ const nestedName = new NestedName(name);
567
+ const { folders, ClassName, fileName } = nestedName;
568
+ const pageFile = presentationSvelteFolder.subitem([
569
+ 'pages',
570
+ ...folders
571
+ ]).createFile(`${fileName}-page.svelte`, svelteComponentContent(`${ClassName}PageProps`));
572
+ if (usesSvelteKit()) {
573
+ const hint = scaffoldSvelteKitRoute(nestedName, pageFile.path);
574
+ if (hint) report(hint);
575
+ }
576
+ };
577
+ const scaffoldSvelteWidget = async (presentationSvelteFolder)=>{
578
+ const widgetName = await interaction_input({
579
+ key: 'name',
580
+ message: 'Name (folders split by "/"): ',
581
+ validate: NestedName.validate
582
+ });
583
+ const widgetType = await interaction_select({
584
+ choices: [
585
+ 'monolithic',
586
+ 'with separated ui',
587
+ 'headless'
588
+ ],
589
+ key: 'widgetType',
590
+ message: 'Type: '
591
+ });
592
+ const { folders, folderName, ClassName, fileName, classNameSegments } = new NestedName(widgetName);
593
+ const folder = presentationSvelteFolder.subitem([
594
+ 'widgets',
595
+ ...folders,
596
+ folderName
597
+ ]);
598
+ const storyTitle = [
599
+ 'Widgets',
600
+ ...classNameSegments
601
+ ].join('/');
602
+ const widgetFileName = `${fileName}-widget`;
603
+ const uiFileName = `${fileName}-widget-ui`;
604
+ const uiModelFileName = `create-${fileName}-ui-model`;
605
+ if ('monolithic' === widgetType) {
606
+ folder.createFile('index.ts', `
607
+ export { default as ${ClassName}Widget } from './${widgetFileName}.svelte'
608
+ export type { ${ClassName}WidgetProps } from './${widgetFileName}.svelte'
609
+ `.trim());
610
+ folder.createFile(`${widgetFileName}.svelte`, svelteComponentContent(`${ClassName}WidgetProps`));
611
+ return;
612
+ }
613
+ folder.createFile('index.ts', `
614
+ export { default as ${ClassName}Widget } from './${widgetFileName}.svelte'
615
+ export type { ${ClassName}WidgetProps } from './types'
616
+ `.trim());
617
+ if ('with separated ui' === widgetType) {
618
+ folder.createFile('types.ts', `
619
+ export type ${ClassName}WidgetProps = { }
620
+
621
+ export type ${ClassName}WidgetUIProps = { }
622
+ `.trim());
623
+ folder.createFile(`${widgetFileName}.svelte`, `
624
+ <script lang="ts">
625
+ import type { ${ClassName}WidgetProps } from './types'
626
+ import ${ClassName}WidgetUI from './ui/${uiFileName}.svelte'
627
+ import { create${ClassName}UIModel } from './model/${uiModelFileName}.svelte'
628
+
629
+ let props: ${ClassName}WidgetProps = $props()
630
+ // The $props() proxy stays reactive: the model reads it in $derived and getters
631
+ // svelte-ignore state_referenced_locally
632
+ const uiModel = create${ClassName}UIModel(props)
633
+ </script>
634
+
635
+ <${ClassName}WidgetUI {...uiModel} />
636
+ `.trim());
637
+ folder.subitem([
638
+ 'ui'
639
+ ]).createFile(`${uiFileName}.svelte`, `
640
+ <script lang="ts">
641
+ import type { ${ClassName}WidgetUIProps } from '../types'
642
+
643
+ let props: ${ClassName}WidgetUIProps = $props()
644
+ </script>
645
+ `.trim());
646
+ const framework = scaffold_svelte_modules_storybookFramework();
647
+ if (framework) folder.subitem([
648
+ 'ui'
649
+ ]).createFile(`${uiFileName}.stories.ts`, svelteStory(framework, `${ClassName}WidgetUI`, `${uiFileName}.svelte`, storyTitle));
650
+ folder.subitem([
651
+ 'model'
652
+ ]).createFile(`${uiModelFileName}.svelte.ts`, svelteUIModelContent(ClassName, `${ClassName}WidgetProps`));
653
+ return;
654
+ }
655
+ folder.createFile('types.ts', `
656
+ import type { Component } from 'svelte'
657
+
658
+ export type ${ClassName}WidgetUIProps = { }
659
+
660
+ export type ${ClassName}WidgetProps = {
661
+ UI: Component<${ClassName}WidgetUIProps>
662
+ }
663
+ `.trim());
664
+ folder.createFile(`${widgetFileName}.svelte`, `
665
+ <script lang="ts">
666
+ import type { ${ClassName}WidgetProps } from './types'
667
+ import { create${ClassName}UIModel } from './model/${uiModelFileName}.svelte'
668
+
669
+ let { UI, ...widgetProps }: ${ClassName}WidgetProps = $props()
670
+ // The rest of $props() stays reactive, a copy made by hand would not
671
+ // svelte-ignore state_referenced_locally
672
+ const uiModel = create${ClassName}UIModel(widgetProps)
673
+ </script>
674
+
675
+ <UI {...uiModel} />
676
+ `.trim());
677
+ folder.subitem([
678
+ 'model'
679
+ ]).createFile(`${uiModelFileName}.svelte.ts`, svelteUIModelContent(ClassName, `Omit<${ClassName}WidgetProps, 'UI'>`));
680
+ };
681
+ const scaffoldSvelteUIKitComponent = async (presentationSvelteFolder)=>{
682
+ const name = await interaction_input({
683
+ key: 'name',
684
+ message: 'Name: '
685
+ });
686
+ const { ClassName, fileName } = new UnknownFormatNaming(name);
687
+ const componentFolder = presentationSvelteFolder.subitem([
688
+ 'ui-kit',
689
+ fileName
690
+ ]);
691
+ componentFolder.createFile('index.ts', `
692
+ export { default as ${ClassName} } from './${fileName}.svelte'
693
+ export type { ${ClassName}Props } from './${fileName}.svelte'
694
+ `.trim());
695
+ componentFolder.createFile(`${fileName}.svelte`, svelteComponentContent(`${ClassName}Props`));
696
+ const framework = scaffold_svelte_modules_storybookFramework();
697
+ if (framework) componentFolder.createFile(`${fileName}.stories.ts`, svelteStory(framework, ClassName, `${fileName}.svelte`, `UI-kit/${ClassName}`));
698
+ };
699
+ const scaffoldSvelteSharedModel = async (presentationSvelteFolder)=>{
700
+ const name = await interaction_input({
701
+ key: 'name',
702
+ message: 'Name without "create" (e.g. debounce): '
703
+ });
704
+ const { ClassName, fileName } = new UnknownFormatNaming(name.trim().replace(/^create-/, ''));
705
+ presentationSvelteFolder.subitem([
706
+ 'shared',
707
+ 'model'
708
+ ]).createFile(`create-${fileName}.svelte.ts`, `
709
+ export const create${ClassName} = () => {
710
+ return {}
711
+ }
712
+ `.trim());
713
+ };
714
+ const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
715
+ const rootFolderSegments = (rootFolder, indent = 20)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n${' '.repeat(indent)}`).join('');
716
+ const legacyEndpointFileLookup = (rootFolder)=>` // The controller, if any, is the first folder of the path:
717
+ // context-root endpoints live right in presentation/rest.
718
+ const [currentBoundedContext, ...relativePath] = routeMetadata.path;
719
+
720
+ if (!currentBoundedContext) {
721
+ return undefined;
722
+ }
723
+
724
+ const endpointFile = project.getSourceFile(
725
+ path.join(
726
+ ${rootFolderSegments(rootFolder)}'bounded-contexts',
727
+ currentBoundedContext,
728
+ 'presentation',
729
+ 'rest',
730
+ ...relativePath.map(pathParameterAsName),
731
+ \`\${routeMetadata.method.toUpperCase()}.ts\`
732
+ )
733
+ );
734
+ `;
735
+ const rootEndpointFileLookup = (rootFolder)=>` const [currentBoundedContext, ...relativePath] = routeMetadata.path;
736
+
737
+ if (!currentBoundedContext) {
738
+ return undefined;
739
+ }
740
+
741
+ // A controller is the first folder of the path; other routes
742
+ // belong to the context root in presentation/rest/(root).
743
+ const restFolder = path.join(
744
+ ${rootFolderSegments(rootFolder, 16)}'bounded-contexts',
745
+ currentBoundedContext,
746
+ 'presentation',
747
+ 'rest'
748
+ );
749
+ const endpointPath = [
750
+ ...relativePath.map(pathParameterAsName),
751
+ \`\${routeMetadata.method.toUpperCase()}.ts\`
752
+ ];
753
+ const endpointFile =
754
+ project.getSourceFile(path.join(restFolder, ...endpointPath)) ??
755
+ project.getSourceFile(
756
+ path.join(restFolder, '(root)', ...endpointPath)
757
+ );
758
+ `;
759
+ const endpointFileLookup = (rootFolder)=>` // A context is the start of the route, nested ones included
760
+ // (/sales/orders/...). A controller is the next folder; other
761
+ // routes belong to the context root in presentation/rest/(root).
762
+ const contextsFolder = path.join(
763
+ ${rootFolderSegments(rootFolder, 16)}'bounded-contexts'
764
+ );
765
+ const endpointFile = Array.from(
766
+ { length: routeMetadata.path.length },
767
+ (_, index) => index + 1
768
+ )
769
+ .flatMap((contextLength) => {
770
+ const restFolder = path.join(
771
+ contextsFolder,
772
+ ...routeMetadata.path.slice(0, contextLength),
773
+ 'presentation',
774
+ 'rest'
775
+ );
776
+ const endpointPath = [
777
+ ...routeMetadata.path
778
+ .slice(contextLength)
779
+ .map(pathParameterAsName),
780
+ \`\${routeMetadata.method.toUpperCase()}.ts\`
781
+ ];
782
+ return [
783
+ path.join(restFolder, ...endpointPath),
784
+ path.join(restFolder, '(root)', ...endpointPath)
785
+ ];
786
+ })
787
+ .map((file) => project.getSourceFile(file))
788
+ .find((file) => !!file);
789
+ `;
790
+ const openapiExtractor = (rootFolder)=>`import path from 'node:path';
791
+ import {
792
+ type DocNode,
793
+ DocPlainText,
794
+ TSDocConfiguration,
795
+ TSDocParser,
796
+ TSDocTagDefinition,
797
+ TSDocTagSyntaxKind
798
+ } from '@microsoft/tsdoc';
799
+ import { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';
800
+
801
+ type BlockTag = \`@\${string}\`;
802
+
803
+ type OpenApiDataTags = {
804
+ /** Omit to take the summary from the comment text before the first tag. */
805
+ summary?: BlockTag;
806
+ description?: BlockTag;
807
+ };
808
+
809
+ type OpenApiData = Partial<{
810
+ summary: string;
811
+ description: string;
812
+ operationId: string;
813
+ }>;
814
+
815
+ const project = new Project({
816
+ tsConfigFilePath: 'tsconfig.json'
817
+ });
818
+
819
+ const getText = (node: DocNode): string =>
820
+ node
821
+ .getChildNodes()
822
+ .map((child) => {
823
+ if (child instanceof DocPlainText) {
824
+ return child.text;
825
+ }
826
+
827
+ return getText(child);
828
+ })
829
+ .join('');
830
+
831
+ const getRawCommentText = (comment: string): string =>
832
+ comment
833
+ .replace(/^\\/\\*\\*/, '')
834
+ .replace(/\\*\\/$/, '')
835
+ .split(/\\r?\\n/)
836
+ .map((line) => line.replace(/^\\s*\\*\\s?/, ''))
837
+ .join('\\n');
838
+
839
+ // TSDoc treats an unknown tag as summary content, so every block tag of the
840
+ // comment has to be registered for the summary section to end before it.
841
+ const parseSummary = (comment: string): string | undefined => {
842
+ const configuration = new TSDocConfiguration();
843
+ const tagNames = getRawCommentText(comment).matchAll(/(?:^|\\n)\\s*(@\\w+)/g);
844
+
845
+ for (const [, tagName] of tagNames) {
846
+ if (!configuration.tryGetTagDefinition(tagName)) {
847
+ configuration.addTagDefinition(
848
+ new TSDocTagDefinition({
849
+ tagName,
850
+ syntaxKind: TSDocTagSyntaxKind.BlockTag
851
+ })
852
+ );
853
+ }
854
+ }
855
+
856
+ const { docComment } = new TSDocParser(configuration).parseString(comment);
857
+
858
+ return getText(docComment.summarySection).trim() || undefined;
859
+ };
860
+
861
+ // Parsed by hand rather than through TSDoc, which drops the line breaks.
862
+ const getTagText = (comment: string, tag: BlockTag): string | undefined => {
863
+ const tagMatch = getRawCommentText(comment).match(
864
+ new RegExp(
865
+ \`(?:^|\\\\n)\\\\s*\${tag}(?:[ \\\\t]*\\\\n|[ \\\\t]+)([\\\\s\\\\S]*?)(?=\\\\n\\\\s*@\\\\w+|\\\\s*$)\`
866
+ )
867
+ );
868
+
869
+ return tagMatch?.[1].trim() || undefined;
870
+ };
871
+
872
+ // Endpoints pass their logic as the generator's first argument
873
+ // (\`this.endpointGenerator(this.handler.handle, ...)\`), while other injected
874
+ // queries only serve as helpers, e.g. guest checks.
875
+ const findHandlerClass = (endpointFile: SourceFile) =>
876
+ endpointFile
877
+ .getDescendantsOfKind(SyntaxKind.CallExpression)
878
+ .map((call) => call.getArguments()[0])
879
+ .filter(Node.isPropertyAccessExpression)
880
+ .find((argument) => argument.getName() === 'handle')
881
+ ?.getExpression()
882
+ .getType()
883
+ .getSymbol()
884
+ ?.getDeclarations()
885
+ .find(Node.isClassDeclaration);
886
+
887
+ // Path parameters (\`:id\`) can't be part of file and folder names
888
+ // everywhere (Windows), so endpoints name them \`_id_\` there.
889
+ const pathParameterAsName = (segment: string) =>
890
+ segment.startsWith(':') ? \`_\${segment.slice(1)}_\` : segment;
891
+
892
+ export const createOpenApiDataFromEndpointLogicExtractor = ({
893
+ summary: summaryTag,
894
+ description: descriptionTag = '@description'
895
+ }: OpenApiDataTags = {}) => {
896
+ return (routeMetadata: {
897
+ method: string;
898
+ path: readonly string[];
899
+ }): OpenApiData | undefined => {
900
+ try {
901
+ ${endpointFileLookup(rootFolder)}
902
+ if (!endpointFile) {
903
+ return undefined;
904
+ }
905
+
906
+ const declaration = findHandlerClass(endpointFile);
907
+ const operationId = declaration?.getName();
908
+ const comment = declaration?.getJsDocs().at(-1)?.getText();
909
+
910
+ if (!comment) {
911
+ return { operationId };
912
+ }
913
+
914
+ return {
915
+ summary: summaryTag
916
+ ? getTagText(comment, summaryTag)
917
+ : parseSummary(comment),
918
+ description: getTagText(comment, descriptionTag),
919
+ operationId
920
+ };
921
+ } catch (e: unknown) {
922
+ console.error(e);
923
+ return undefined;
924
+ }
925
+ };
926
+ };
927
+ `;
928
+ const openapiScriptPath = "scripts/generate-openapi.ts";
929
+ const defaultOpenapiPath = ()=>usesNext() ? 'public/openapi.json' : usesSvelteKit() ? 'static/openapi.json' : 'openapi.json';
930
+ const extractorPackages = [
931
+ 'ts-morph',
932
+ '@microsoft/tsdoc'
933
+ ];
934
+ const swaggerPagePath = (rootFolder, framework = 'react')=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'svelte' === framework ? 'presentation/svelte/pages/swagger-page.svelte' : 'presentation/react/pages/swagger-page.tsx');
935
+ const specImportOf = (pagePath, outputPath)=>{
936
+ const specImport = node_path.posix.relative(node_path.posix.dirname(pagePath), outputPath);
937
+ return specImport.startsWith('.') ? specImport : `./${specImport}`;
938
+ };
939
+ const swaggerPage = (rootFolder, outputPath, withNext = false)=>{
940
+ const page = reactPageContent('Swagger', {
941
+ imports: [
942
+ "import 'swagger-ui-react/swagger-ui.css'",
943
+ "import SwaggerUI from 'swagger-ui-react'",
944
+ `import spec from '${specImportOf(swaggerPagePath(rootFolder), outputPath)}' with { type: 'json' }`
945
+ ],
946
+ body: '<SwaggerUI displayOperationId spec={spec} />'
947
+ });
948
+ return withNext ? `'use client'\n\n${page}` : page;
949
+ };
950
+ const svelteKitStaticFolder = 'static/';
951
+ const svelteKitStaticUrl = (outputPath)=>outputPath.startsWith(svelteKitStaticFolder) ? `/${outputPath.slice(svelteKitStaticFolder.length)}` : void 0;
952
+ const svelteSwaggerPage = (rootFolder, outputPath, url)=>`
953
+ <script lang="ts" module>
954
+ export type SwaggerPageProps = {}
955
+ </script>
956
+
957
+ <script lang="ts">
958
+ import 'swagger-ui-dist/swagger-ui.css'
959
+ import type { SwaggerUIBundle as SwaggerUIBundleType } from 'swagger-ui-dist'
960
+ import { onMount } from 'svelte'${url ? '' : `
961
+ import spec from '${specImportOf(swaggerPagePath(rootFolder, 'svelte'), outputPath)}'`}
962
+
963
+ let props: SwaggerPageProps = $props()
964
+ let container: HTMLDivElement
965
+
966
+ onMount(async () => {
967
+ // Self-contained bundle: React is bundled inside, no react deps in the project
968
+ const { default: SwaggerUIBundle } = (await import(
969
+ // @ts-expect-error -- swagger-ui-dist ships no types for this entry point
970
+ 'swagger-ui-dist/swagger-ui-bundle.js'
971
+ )) as { default: SwaggerUIBundleType }
972
+
973
+ SwaggerUIBundle({ domNode: container, ${url ? `url: '${url}'` : 'spec'}, displayOperationId: true })
974
+ })
975
+ </script>
976
+
977
+ <div bind:this={container}></div>
978
+ `.trim();
979
+ const swaggerPackages = {
980
+ react: {
981
+ dependency: 'swagger-ui-react',
982
+ types: '@types/swagger-ui-react'
983
+ },
984
+ svelte: {
985
+ dependency: 'swagger-ui-dist',
986
+ types: '@types/swagger-ui-dist'
987
+ }
988
+ };
989
+ const openapiScripts = {
990
+ openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
991
+ };
992
+ const splitPath = (value)=>value.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
993
+ const apiTitle = (packageName)=>{
994
+ const words = String(packageName ?? '').replace(/^@[^/]*\//, '').split(/[^a-zA-Z0-9]+/).filter((word)=>!!word).map((word)=>word[0].toUpperCase() + word.slice(1));
995
+ return [
996
+ ...words,
997
+ 'API'
998
+ ].join(' ');
999
+ };
1000
+ const openapiGenerator = (rootFolder, title, routePrefix, outputPath, withExtractor = false)=>{
1001
+ const restFolder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest');
1002
+ const restImport = node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), restFolder);
1003
+ const prefixSegments = splitPath(routePrefix);
1004
+ const apiRoutePrefix = prefixSegments.length ? `\n apiRoutePrefix: [${prefixSegments.map((segment)=>`'${segment}'`).join(', ')}],` : '';
1005
+ const extractorImport = `./${node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), openapiExtractorPath.replace(/\.ts$/, ''))}`;
1006
+ const handlers = withExtractor ? `
1007
+ const extractOpenApiDataFromEndpointLogic =
1008
+ createOpenApiDataFromEndpointLogicExtractor();
1009
+
1010
+ const handlers = restHandlers.map((x) => ({
1011
+ ...x,
1012
+ metadata: {
1013
+ ...x.metadata,
1014
+ openApiMetadata: {
1015
+ ...extractOpenApiDataFromEndpointLogic(x.metadata.route),
1016
+ ...(x.metadata.openApiMetadata ?? {})
1017
+ }
1018
+ }
1019
+ }));
1020
+ ` : '';
1021
+ return `import { generateOpenAPI } from '@domain-first/handlers-rest';
1022
+ import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';${withExtractor ? `\nimport { createOpenApiDataFromEndpointLogicExtractor } from '${extractorImport}';` : ''}
1023
+ ${handlers}
1024
+ generateOpenAPI(${withExtractor ? 'handlers' : 'restHandlers'}, {
1025
+ document: { info: { title: '${title}', version: '1.0.0' } },${apiRoutePrefix}
1026
+ outputFile: { path: '${outputPath}' }
1027
+ });
1028
+ `;
1029
+ };
1030
+ const addOpenapi = async ()=>{
1031
+ const { rootFolder } = ConfigFile.Instance.data.project;
1032
+ const root = new ProjectRoot().path;
1033
+ const manifestFile = new File(node_path.join(root, 'package.json'));
1034
+ const manifest = JSON.parse(manifestFile.data);
1035
+ const dependencies = {
1036
+ ...manifest.dependencies,
1037
+ ...manifest.devDependencies
1038
+ };
1039
+ const routePrefix = await interaction_input({
1040
+ key: 'routePrefix',
1041
+ message: 'Route prefix the REST handlers are served under:',
1042
+ default: '/api'
1043
+ });
1044
+ const outputPath = await interaction_input({
1045
+ key: 'openapiPath',
1046
+ message: 'OpenAPI document path:',
1047
+ default: defaultOpenapiPath(),
1048
+ validate: (value)=>splitPath(value).length ? true : 'Path is required'
1049
+ });
1050
+ const withExtractor = await interaction_confirm({
1051
+ key: 'withExtractor',
1052
+ message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
1053
+ default: true
1054
+ });
1055
+ const { frontend } = ConfigFile.Instance.data;
1056
+ const framework = frontend?.svelte ? 'svelte' : frontend?.react ? 'react' : void 0;
1057
+ const withSwaggerPage = !!framework && await interaction_confirm({
1058
+ key: 'swaggerPage',
1059
+ message: 'Add a Swagger UI page?',
1060
+ default: true
1061
+ });
1062
+ const selected = await addPackageScripts(manifestFile, openapiScripts);
1063
+ if (withExtractor) {
1064
+ const extractorFile = new File(node_path.join(root, openapiExtractorPath));
1065
+ const extractor = openapiExtractor(rootFolder);
1066
+ if (!extractorFile.exists || extractorFile.data !== extractor) extractorFile.data = extractor;
1067
+ }
1068
+ const generatorFile = new File(node_path.join(root, openapiScriptPath));
1069
+ const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
1070
+ if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
1071
+ const routeFile = withSwaggerPage && 'react' === framework && usesNext() ? `${nextAppFolder(root)}/swagger/page.tsx` : withSwaggerPage && 'svelte' === framework && usesSvelteKit() ? `${svelteKitRoutesFolder(root)}/swagger/+page.svelte` : void 0;
1072
+ let routeHint;
1073
+ const specUrl = 'svelte' === framework && usesSvelteKit() ? svelteKitStaticUrl(splitPath(outputPath).join('/')) : void 0;
1074
+ if (withSwaggerPage) {
1075
+ const pagePath = node_path.join(root, swaggerPagePath(rootFolder, framework));
1076
+ const pageFile = new File(pagePath);
1077
+ const page = 'svelte' === framework ? svelteSwaggerPage(rootFolder, splitPath(outputPath).join('/'), specUrl) : swaggerPage(rootFolder, splitPath(outputPath).join('/'), !!routeFile);
1078
+ if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
1079
+ if (routeFile) routeHint = ('svelte' === framework ? scaffoldSvelteKitRoute : scaffoldNextRoute)(new NestedName('swagger'), pagePath);
1080
+ }
1081
+ const packages = swaggerPackages[framework ?? 'react'];
1082
+ const resolveJsonModule = withSwaggerPage && !specUrl ? compilerOption(node_path.join(root, 'tsconfig.json'), 'resolveJsonModule') : true;
1083
+ const hasRestHandlers = new File(node_path.join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
1084
+ const missingExtractorPackages = withExtractor ? extractorPackages.filter((name)=>!dependencies[name]) : [];
1085
+ return [
1086
+ ...dependencies['@domain-first/handlers-rest'] ? [] : [
1087
+ 'npm install @domain-first/handlers-rest'
1088
+ ],
1089
+ ...dependencies.tsx ? [] : [
1090
+ 'npm install --save-dev tsx'
1091
+ ],
1092
+ ...missingExtractorPackages.length ? [
1093
+ `npm install --save-dev ${missingExtractorPackages.join(' ')}`
1094
+ ] : [],
1095
+ ...withSwaggerPage && !dependencies[packages.dependency] ? [
1096
+ `npm install ${packages.dependency}`
1097
+ ] : [],
1098
+ ...withSwaggerPage && !dependencies[packages.types] ? [
1099
+ `npm install --save-dev ${packages.types}`
1100
+ ] : [],
1101
+ ...true === resolveJsonModule || null === resolveJsonModule ? [] : [
1102
+ 'set "resolveJsonModule": true in compilerOptions of tsconfig.json — the Swagger UI page imports the OpenAPI document as JSON'
1103
+ ],
1104
+ ...describeScripts(selected, {
1105
+ openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
1106
+ }),
1107
+ ...withSwaggerPage && !routeFile ? [
1108
+ `SwaggerPage from ${swaggerPagePath(rootFolder, framework)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
1109
+ ] : [],
1110
+ ...routeFile ? [
1111
+ routeHint ?? `/swagger shows ${splitPath(outputPath).join('/')} once it is generated — the route is ${routeFile}`
1112
+ ] : [],
1113
+ ...hasRestHandlers ? [] : [
1114
+ `restHandlers appear in ${node_path.posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
1115
+ ]
1116
+ ];
1117
+ };
1118
+ const rootControllerFolder = '(root)';
1119
+ const pathParameterAsName = (segment)=>segment.startsWith(':') ? `_${segment.slice(1)}_` : segment;
1120
+ const isPathParameterName = (name)=>name.startsWith(':') || /^_.+_$/.test(name);
1121
+ const endpointFileNames = new Set([
1122
+ 'get',
1123
+ 'post',
1124
+ 'put',
1125
+ 'patch',
1126
+ 'delete'
1127
+ ].map((method)=>`${method.toUpperCase()}.ts`));
1128
+ const entries = (folder)=>node_fs.existsSync(folder) ? node_fs.readdirSync(folder, {
1129
+ withFileTypes: true
1130
+ }) : [];
1131
+ const subfolders = (folder)=>entries(folder).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name);
1132
+ const restFolders = (boundedContextFolder)=>({
1133
+ presentation: node_path.join(boundedContextFolder, 'presentation', 'rest'),
1134
+ wiring: node_path.join(boundedContextFolder, 'wiring', 'presentation', 'rest')
1135
+ });
1136
+ const restControllers = (boundedContextFolder)=>subfolders(restFolders(boundedContextFolder).presentation).filter((name)=>name !== rootControllerFolder && !isPathParameterName(name));
1137
+ const rootStaticSegments = (boundedContextFolder)=>subfolders(node_path.join(restFolders(boundedContextFolder).presentation, rootControllerFolder)).filter((name)=>!isPathParameterName(name));
1138
+ const legacyRootEndpoints = (boundedContextFolder)=>{
1139
+ const { presentation, wiring } = restFolders(boundedContextFolder);
1140
+ return {
1141
+ endpointFiles: entries(presentation).filter((entry)=>entry.isFile() && endpointFileNames.has(entry.name)).map((entry)=>node_path.join(presentation, entry.name)),
1142
+ parameterFolders: subfolders(presentation).filter(isPathParameterName).map((name)=>node_path.join(presentation, name)),
1143
+ wireFiles: entries(wiring).filter((entry)=>entry.isFile() && 'index.ts' !== entry.name && /\.ts$/.test(entry.name)).map((entry)=>node_path.join(wiring, entry.name))
1144
+ };
1145
+ };
1146
+ const hasLegacyRootEndpoints = (boundedContextFolder)=>Object.values(legacyRootEndpoints(boundedContextFolder)).some((paths)=>paths.length > 0);
1147
+ export { RequestError, Separator, addInMemoryDbSection, addOpenapi, addPackageScripts, answerFor, assertAnswersConsumed, defaultOpenapiPath, describeScripts, endpointFileLookup, hasDependency, hasLegacyRootEndpoints, inMemoryDbScaffolded, inMemoryDbSectionMembers, inMemoryDbTypeImport, inMemoryImplementationType, injectInMemoryDb, interaction_checkbox, interaction_confirm, interaction_input, interaction_select, isInMemoryDb, isNonInteractive, isPathParameterName, keepInMemoryDbSection, legacyEndpointFileLookup, legacyHasId, legacyRootEndpoints, legacyWithIdLookup, missingDomainFirstPackages, missingPackages, nextAppFolder, openapiExtractorPath, openapiScriptPath, pathParameterAsName, plural, report, restControllers, restFolders, rootEndpointFileLookup, rootStaticSegments, runWithAnswers, scaffoldInMemoryDb, scaffoldReactPage, scaffoldSveltePage, scaffoldSvelteSharedModel, scaffoldSvelteUIKitComponent, scaffoldSvelteWidget, svelteKitRoutesFolder, svelteKitStaticUrl, svelteSwaggerPage, swaggerPagePath, usesInMemoryDb, usesNext, usesSvelteKit, wireInMemoryDb, withIdLookup };