@domain-first/project-structure 8.11.0 → 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.
package/dist/115.js DELETED
@@ -1,616 +0,0 @@
1
- import node_path from "node:path";
2
- import node_fs from "node:fs";
3
- import { addImport, addWireDependencies, addConstructorParameters, UnknownFormatNaming, ConfigFile, Folder, relativeImport, File, ProjectRoot, addClassMember, stripJsonComments } from "./201.js";
4
- const inMemoryImplementationType = 'in-memory';
5
- const className = 'InMemoryDbInfrastructureService';
6
- const wireName = 'wireInMemoryDbInfrastructureService';
7
- const parameterName = 'inMemoryDbInfrastructureService';
8
- const legacyWithIdLookup = ` withId: (id: TId): T | null =>
9
- items().find(
10
- (x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
11
- ) ?? null,
12
- `;
13
- const legacyHasId = `const hasId = (x: unknown): x is { id: unknown } =>
14
- typeof x === 'object' && x !== null && 'id' in x;
15
-
16
- `;
17
- const withIdLookup = ` withId: (id: TId): T | null =>
18
- globalThis.___SHARED_IN_MEMORY_DB___![key].find((entry) =>
19
- idsAreEqual(entry.id as TId, id)
20
- )?.item ?? null,
21
- `;
22
- const inMemoryDbService = `type Entry = {
23
- id: unknown;
24
- item: any;
25
- };
26
-
27
- declare global {
28
- var ___SHARED_IN_MEMORY_DB___: Record<string, Array<Entry>> | undefined;
29
- }
30
-
31
- type Section<T, TId> = {
32
- all: (predicate?: (x: T) => boolean) => T[];
33
- first: (predicate: (x: T) => boolean) => T | null;
34
- withId: (id: TId) => T | null;
35
- lastAddedItem: () => T | null;
36
- save: (payload: T extends { id: TId } ? T : [TId, T]) => void;
37
- deleteById: (id: TId) => void;
38
- delete: (predicate: (x: T) => boolean) => void;
39
- };
40
-
41
- type IdsAreEqual<TId> = (a: TId, b: TId) => boolean;
42
-
43
- const comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;
44
-
45
- const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
46
- if (typeof a !== 'object' || a === null) {
47
- return Object.is(a, b);
48
- }
49
-
50
- for (const methodName of comparisonMethodNames) {
51
- const method: unknown = (a as Record<string, unknown>)[methodName];
52
- if (typeof method === 'function') {
53
- return Boolean(method.call(a, b));
54
- }
55
- }
56
-
57
- return Object.is(a, b);
58
- };
59
-
60
- export class InMemoryDbInfrastructureService {
61
- protected section<T extends { id: unknown }>(
62
- key: string,
63
- idsAreEqual?: IdsAreEqual<T['id']>
64
- ): Section<T, T['id']>;
65
- protected section<T, TId>(
66
- key: string,
67
- idsAreEqual?: IdsAreEqual<TId>
68
- ): Section<T, TId>;
69
- protected section<T, TId>(
70
- key: string,
71
- idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual
72
- ): Section<T, TId> {
73
- if (!globalThis.___SHARED_IN_MEMORY_DB___) {
74
- globalThis.___SHARED_IN_MEMORY_DB___ = {};
75
- }
76
-
77
- if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
78
- globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
79
- }
80
-
81
- const items = (): T[] =>
82
- globalThis.___SHARED_IN_MEMORY_DB___![key].map(
83
- (entry) => entry.item
84
- );
85
-
86
- return {
87
- all: (predicate: (x: T) => boolean = () => true): T[] =>
88
- items().filter(predicate),
89
- first: (predicate: (x: T) => boolean): T | null =>
90
- items().find(predicate) ?? null,
91
- ${withIdLookup} lastAddedItem: (): T | null =>
92
- globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
93
- save: (payload: T extends { id: TId } ? T : [TId, T]) => {
94
- const id = Array.isArray(payload) ? payload[0] : payload.id;
95
- const item = Array.isArray(payload) ? payload[1] : payload;
96
- const entries = globalThis.___SHARED_IN_MEMORY_DB___![key];
97
- const existing = entries.find((entry) =>
98
- idsAreEqual(entry.id as TId, id)
99
- );
100
- if (existing) {
101
- existing.item = item;
102
- return;
103
- }
104
- entries.push({ id, item });
105
- },
106
- deleteById: (id: TId) => {
107
- globalThis.___SHARED_IN_MEMORY_DB___![key] =
108
- globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
109
- (entry) => !idsAreEqual(entry.id as TId, id)
110
- );
111
- },
112
- delete: (predicate: (x: T) => boolean) => {
113
- globalThis.___SHARED_IN_MEMORY_DB___![key] =
114
- globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
115
- (entry) => !predicate(entry.item)
116
- );
117
- }
118
- };
119
- }
120
- }
121
- `;
122
- const inMemoryDbWiring = `import { wireClass } from '@domain-first/wire';
123
- import { InMemoryDbInfrastructureService } from '../../infrastructure/services/in-memory-db-infrastructure-service';
124
-
125
- export const wireInMemoryDbInfrastructureService = wireClass(
126
- InMemoryDbInfrastructureService,
127
- []
128
- );
129
- `;
130
- const withWiring = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
131
- const sharedFolder = ()=>new Folder(new ProjectRoot().path).subitem([
132
- ConfigFile.Instance.data.project.rootFolder,
133
- 'shared-kernel'
134
- ]);
135
- const serviceFile = ()=>new File(sharedFolder().path).subitem([
136
- 'infrastructure',
137
- 'services',
138
- 'in-memory-db-infrastructure-service.ts'
139
- ]);
140
- const wireFile = ()=>new File(sharedFolder().path).subitem([
141
- 'wiring',
142
- 'infrastructure-services',
143
- 'wire-in-memory-db-infrastructure-service.ts'
144
- ]);
145
- const scaffoldInMemoryDb = (shared)=>{
146
- const servicesFolder = shared.subitem([
147
- 'infrastructure',
148
- 'services'
149
- ]);
150
- servicesFolder.createFile('in-memory-db-infrastructure-service.ts', inMemoryDbService);
151
- if (withWiring()) shared.subitem([
152
- 'wiring',
153
- 'infrastructure-services'
154
- ]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
155
- };
156
- const inMemoryDbScaffolded = ()=>serviceFile().exists && (!withWiring() || wireFile().exists);
157
- const usesInMemoryDb = (implementationType)=>Boolean(ConfigFile.Instance.data.backend?.withInMemoryDb) && new UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && inMemoryDbScaffolded();
158
- const uncountableEndings = [
159
- 'data',
160
- 'info',
161
- 'usage',
162
- 'feedback',
163
- 'media',
164
- 'ware',
165
- 'equipment',
166
- 'information',
167
- 'knowledge',
168
- 'traffic',
169
- 'telemetry',
170
- 'analytics',
171
- 'series'
172
- ];
173
- const uncountable = new RegExp(`(${uncountableEndings.join('|')})$`, 'i');
174
- const plural = (word)=>{
175
- if (uncountable.test(word)) return word;
176
- if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
177
- if (/(^|[^aeiou]|qu)[aeiou]z$/i.test(word)) return `${word}zes`;
178
- if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
179
- return `${word}s`;
180
- };
181
- const addInMemoryDbSection = (typeNaming, typeImportTarget)=>{
182
- const file = serviceFile();
183
- const sectionNaming = new UnknownFormatNaming(plural(typeNaming.fileName));
184
- const field = sectionNaming.variableName;
185
- if (new RegExp(`\\b${field}\\s*=\\s*this\\.section\\b`).test(file.data)) return field;
186
- const withImport = addImport(file.data, `import type { ${typeNaming.ClassName} } from '${relativeImport(file.path, typeImportTarget)}';`);
187
- file.update(addClassMember(withImport, className, `${field} = this.section<${typeNaming.ClassName}>('${sectionNaming.fileName.toUpperCase()}');`));
188
- return field;
189
- };
190
- const inMemoryDbTypeImport = (fromFile)=>`import type { ${className} } from '${relativeImport(fromFile, serviceFile().path)}'`;
191
- const inMemoryDbSectionMembers = (field, derived)=>`
192
- private readonly data: ${className}['${field}']
193
-
194
- constructor(${parameterName}: ${className}) {
195
- ${derived ? 'super()\n ' : ''}this.data = ${parameterName}.${field}
196
- }
197
- `.trim();
198
- const keepInMemoryDbSection = (classFile, field)=>{
199
- classFile.update(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)).replace('constructor() {}', inMemoryDbSectionMembers(field, false)));
200
- };
201
- const isInMemoryDb = (module)=>module.wireName === wireName;
202
- const injectInMemoryDb = (classFile, implementationName)=>{
203
- classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
204
- `private readonly ${parameterName}: ${className}`
205
- ]));
206
- };
207
- const wireInMemoryDb = (consumerWireFile, implementationName)=>{
208
- consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${wireName} } from '${relativeImport(consumerWireFile.path, wireFile().path)}'`), implementationName, [
209
- wireName
210
- ]));
211
- };
212
- const hasDependency = (name)=>{
213
- const manifestFile = new File(node_path.join(new ProjectRoot().path, 'package.json'));
214
- if (!manifestFile.exists) return false;
215
- const manifest = JSON.parse(manifestFile.data);
216
- return [
217
- manifest.dependencies,
218
- manifest.devDependencies,
219
- manifest.optionalDependencies
220
- ].some((dependencies)=>dependencies && Object.hasOwn(dependencies, name));
221
- };
222
- const missingPackages = (packages)=>{
223
- const missing = [
224
- ...new Set(packages)
225
- ].filter((name)=>!hasDependency(name));
226
- return missing.length ? [
227
- `npm i ${missing.join(' ')}`
228
- ] : [];
229
- };
230
- const missingDomainFirstPackages = ()=>missingPackages(ConfigFile.backend.domainFirstPackages);
231
- const ignoredFolders = new Set([
232
- 'node_modules',
233
- '.git',
234
- '.next',
235
- '.svelte-kit',
236
- 'dist',
237
- 'build',
238
- 'out',
239
- 'coverage',
240
- 'storybook-static'
241
- ]);
242
- const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx|svelte)$/;
243
- const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
244
- const walk = (folder)=>{
245
- if (!node_fs.existsSync(folder)) return [];
246
- return node_fs.readdirSync(folder, {
247
- withFileTypes: true
248
- }).flatMap((entry)=>{
249
- const entryPath = node_path.join(folder, entry.name);
250
- if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : walk(entryPath);
251
- return entry.isFile() ? [
252
- entryPath
253
- ] : [];
254
- });
255
- };
256
- const toPosix = (value)=>value.split(node_path.sep).join('/');
257
- const readAliases = (projectRoot)=>{
258
- const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
259
- if (!node_fs.existsSync(tsconfig)) return [];
260
- try {
261
- const { compilerOptions = {} } = JSON.parse(stripJsonComments(node_fs.readFileSync(tsconfig, 'utf8')));
262
- const base = node_path.resolve(projectRoot, compilerOptions.baseUrl ?? '.');
263
- return Object.entries(compilerOptions.paths ?? {}).filter(([pattern, targets])=>pattern.endsWith('*') && targets[0]?.endsWith('*')).map(([pattern, [target]])=>({
264
- prefix: pattern.slice(0, -1),
265
- target: node_path.resolve(base, target.slice(0, -1))
266
- }));
267
- } catch {
268
- return [];
269
- }
270
- };
271
- const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
272
- const reExportPattern = /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\n]+)\1/g;
273
- const importPaths = (file)=>{
274
- const withoutExtension = file.replace(codeExtension, '');
275
- return 'index' === node_path.basename(withoutExtension) ? [
276
- withoutExtension,
277
- node_path.dirname(withoutExtension)
278
- ] : [
279
- withoutExtension
280
- ];
281
- };
282
- const projectImports = (projectRoot)=>{
283
- const aliases = readAliases(projectRoot);
284
- const resolve = (specifier, fromFile)=>{
285
- if (specifier.startsWith('.')) return {
286
- resolved: node_path.resolve(node_path.dirname(fromFile), specifier),
287
- alias: void 0
288
- };
289
- const alias = aliases.find(({ prefix })=>specifier.startsWith(prefix));
290
- return alias ? {
291
- resolved: node_path.resolve(alias.target, specifier.slice(alias.prefix.length)),
292
- alias
293
- } : void 0;
294
- };
295
- const specifierFor = (fromFile, toPath, alias)=>{
296
- const aliased = alias && toPosix(node_path.relative(alias.target, toPath));
297
- if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
298
- const relative = toPosix(node_path.relative(node_path.dirname(fromFile), toPath));
299
- return relative.startsWith('.') ? relative : `./${relative}`;
300
- };
301
- const codeFiles = new Map(walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
302
- file,
303
- node_fs.readFileSync(file, 'utf8')
304
- ]));
305
- const importsOf = (file)=>[
306
- ...(codeFiles.get(file) ?? '').matchAll(specifierPattern)
307
- ].map(([, , , specifier])=>resolve(specifier, file)?.resolved).filter((resolved)=>!!resolved);
308
- return {
309
- resolve,
310
- specifierFor,
311
- codeFiles,
312
- importsOf
313
- };
314
- };
315
- const stageModuleMove = ({ projectRoot, stopAt, moves, movedPath, rename, everyFile = (content)=>content, stopAtFor })=>{
316
- const stopFor = (file)=>stopAtFor?.(file) ?? stopAt;
317
- const { resolve, specifierFor, codeFiles } = projectImports(projectRoot);
318
- const barrels = new Set();
319
- const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
320
- for(let found = true; found;){
321
- found = false;
322
- for (const [file, content] of codeFiles){
323
- if (moves.has(file) || isBarrel(file)) continue;
324
- const reExportsModule = [
325
- ...content.matchAll(reExportPattern)
326
- ].some(([, , specifier])=>{
327
- const resolution = resolve(specifier, file);
328
- return !!resolution && (!!movedPath(resolution.resolved) || isBarrel(resolution.resolved));
329
- });
330
- if (reExportsModule) {
331
- for (const importPath of importPaths(file))barrels.add(importPath);
332
- found = true;
333
- }
334
- }
335
- }
336
- const rewrite = (content, oldFile, newFile)=>{
337
- let referencesModule = false;
338
- const rewritten = content.replace(specifierPattern, (match, keyword, quote, specifier)=>{
339
- const resolution = resolve(specifier, oldFile);
340
- if (!resolution) return match;
341
- const moved = movedPath(resolution.resolved);
342
- if (moved || isBarrel(resolution.resolved)) referencesModule = true;
343
- if (!moved && oldFile === newFile) return match;
344
- const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
345
- return `${keyword}${quote}${next}${quote}`;
346
- });
347
- const changed = everyFile(rewritten);
348
- if (!referencesModule && !moves.has(oldFile)) return changed;
349
- return rename(changed, {
350
- moved: moves.has(oldFile)
351
- });
352
- };
353
- for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new File(file).moveTo(newFile, stopFor(file));
354
- const updated = [];
355
- for (const [file, content] of codeFiles){
356
- const newFile = moves.get(file);
357
- const next = rewrite(content, file, newFile ?? file);
358
- if (newFile && newFile !== file) {
359
- new File(newFile).data = next;
360
- new File(file).delete(stopFor(file));
361
- } else if (next !== content) {
362
- new File(file).update(next);
363
- if (!newFile) updated.push(file);
364
- }
365
- }
366
- return {
367
- moves: [
368
- ...moves
369
- ].filter(([from, to])=>from !== to),
370
- updated
371
- };
372
- };
373
- const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
374
- const rootFolderSegments = (rootFolder, indent = 20)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n${' '.repeat(indent)}`).join('');
375
- const legacyEndpointFileLookup = (rootFolder)=>` // The controller, if any, is the first folder of the path:
376
- // context-root endpoints live right in presentation/rest.
377
- const [currentBoundedContext, ...relativePath] = routeMetadata.path;
378
-
379
- if (!currentBoundedContext) {
380
- return undefined;
381
- }
382
-
383
- const endpointFile = project.getSourceFile(
384
- path.join(
385
- ${rootFolderSegments(rootFolder)}'bounded-contexts',
386
- currentBoundedContext,
387
- 'presentation',
388
- 'rest',
389
- ...relativePath.map(pathParameterAsName),
390
- \`\${routeMetadata.method.toUpperCase()}.ts\`
391
- )
392
- );
393
- `;
394
- const rootEndpointFileLookup = (rootFolder)=>` const [currentBoundedContext, ...relativePath] = routeMetadata.path;
395
-
396
- if (!currentBoundedContext) {
397
- return undefined;
398
- }
399
-
400
- // A controller is the first folder of the path; other routes
401
- // belong to the context root in presentation/rest/(root).
402
- const restFolder = path.join(
403
- ${rootFolderSegments(rootFolder, 16)}'bounded-contexts',
404
- currentBoundedContext,
405
- 'presentation',
406
- 'rest'
407
- );
408
- const endpointPath = [
409
- ...relativePath.map(pathParameterAsName),
410
- \`\${routeMetadata.method.toUpperCase()}.ts\`
411
- ];
412
- const endpointFile =
413
- project.getSourceFile(path.join(restFolder, ...endpointPath)) ??
414
- project.getSourceFile(
415
- path.join(restFolder, '(root)', ...endpointPath)
416
- );
417
- `;
418
- const endpointFileLookup = (rootFolder)=>` // A context is the start of the route, nested ones included
419
- // (/sales/orders/...). A controller is the next folder; other
420
- // routes belong to the context root in presentation/rest/(root).
421
- const contextsFolder = path.join(
422
- ${rootFolderSegments(rootFolder, 16)}'bounded-contexts'
423
- );
424
- const endpointFile = Array.from(
425
- { length: routeMetadata.path.length },
426
- (_, index) => index + 1
427
- )
428
- .flatMap((contextLength) => {
429
- const restFolder = path.join(
430
- contextsFolder,
431
- ...routeMetadata.path.slice(0, contextLength),
432
- 'presentation',
433
- 'rest'
434
- );
435
- const endpointPath = [
436
- ...routeMetadata.path
437
- .slice(contextLength)
438
- .map(pathParameterAsName),
439
- \`\${routeMetadata.method.toUpperCase()}.ts\`
440
- ];
441
- return [
442
- path.join(restFolder, ...endpointPath),
443
- path.join(restFolder, '(root)', ...endpointPath)
444
- ];
445
- })
446
- .map((file) => project.getSourceFile(file))
447
- .find((file) => !!file);
448
- `;
449
- const openapiExtractor = (rootFolder)=>`import path from 'node:path';
450
- import {
451
- type DocNode,
452
- DocPlainText,
453
- TSDocConfiguration,
454
- TSDocParser,
455
- TSDocTagDefinition,
456
- TSDocTagSyntaxKind
457
- } from '@microsoft/tsdoc';
458
- import { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';
459
-
460
- type BlockTag = \`@\${string}\`;
461
-
462
- type OpenApiDataTags = {
463
- /** Omit to take the summary from the comment text before the first tag. */
464
- summary?: BlockTag;
465
- description?: BlockTag;
466
- };
467
-
468
- type OpenApiData = Partial<{
469
- summary: string;
470
- description: string;
471
- operationId: string;
472
- }>;
473
-
474
- const project = new Project({
475
- tsConfigFilePath: 'tsconfig.json'
476
- });
477
-
478
- const getText = (node: DocNode): string =>
479
- node
480
- .getChildNodes()
481
- .map((child) => {
482
- if (child instanceof DocPlainText) {
483
- return child.text;
484
- }
485
-
486
- return getText(child);
487
- })
488
- .join('');
489
-
490
- const getRawCommentText = (comment: string): string =>
491
- comment
492
- .replace(/^\\/\\*\\*/, '')
493
- .replace(/\\*\\/$/, '')
494
- .split(/\\r?\\n/)
495
- .map((line) => line.replace(/^\\s*\\*\\s?/, ''))
496
- .join('\\n');
497
-
498
- // TSDoc treats an unknown tag as summary content, so every block tag of the
499
- // comment has to be registered for the summary section to end before it.
500
- const parseSummary = (comment: string): string | undefined => {
501
- const configuration = new TSDocConfiguration();
502
- const tagNames = getRawCommentText(comment).matchAll(/(?:^|\\n)\\s*(@\\w+)/g);
503
-
504
- for (const [, tagName] of tagNames) {
505
- if (!configuration.tryGetTagDefinition(tagName)) {
506
- configuration.addTagDefinition(
507
- new TSDocTagDefinition({
508
- tagName,
509
- syntaxKind: TSDocTagSyntaxKind.BlockTag
510
- })
511
- );
512
- }
513
- }
514
-
515
- const { docComment } = new TSDocParser(configuration).parseString(comment);
516
-
517
- return getText(docComment.summarySection).trim() || undefined;
518
- };
519
-
520
- // Parsed by hand rather than through TSDoc, which drops the line breaks.
521
- const getTagText = (comment: string, tag: BlockTag): string | undefined => {
522
- const tagMatch = getRawCommentText(comment).match(
523
- new RegExp(
524
- \`(?:^|\\\\n)\\\\s*\${tag}(?:[ \\\\t]*\\\\n|[ \\\\t]+)([\\\\s\\\\S]*?)(?=\\\\n\\\\s*@\\\\w+|\\\\s*$)\`
525
- )
526
- );
527
-
528
- return tagMatch?.[1].trim() || undefined;
529
- };
530
-
531
- // Endpoints pass their logic as the generator's first argument
532
- // (\`this.endpointGenerator(this.handler.handle, ...)\`), while other injected
533
- // queries only serve as helpers, e.g. guest checks.
534
- const findHandlerClass = (endpointFile: SourceFile) =>
535
- endpointFile
536
- .getDescendantsOfKind(SyntaxKind.CallExpression)
537
- .map((call) => call.getArguments()[0])
538
- .filter(Node.isPropertyAccessExpression)
539
- .find((argument) => argument.getName() === 'handle')
540
- ?.getExpression()
541
- .getType()
542
- .getSymbol()
543
- ?.getDeclarations()
544
- .find(Node.isClassDeclaration);
545
-
546
- // Path parameters (\`:id\`) can't be part of file and folder names
547
- // everywhere (Windows), so endpoints name them \`_id_\` there.
548
- const pathParameterAsName = (segment: string) =>
549
- segment.startsWith(':') ? \`_\${segment.slice(1)}_\` : segment;
550
-
551
- export const createOpenApiDataFromEndpointLogicExtractor = ({
552
- summary: summaryTag,
553
- description: descriptionTag = '@description'
554
- }: OpenApiDataTags = {}) => {
555
- return (routeMetadata: {
556
- method: string;
557
- path: readonly string[];
558
- }): OpenApiData | undefined => {
559
- try {
560
- ${endpointFileLookup(rootFolder)}
561
- if (!endpointFile) {
562
- return undefined;
563
- }
564
-
565
- const declaration = findHandlerClass(endpointFile);
566
- const operationId = declaration?.getName();
567
- const comment = declaration?.getJsDocs().at(-1)?.getText();
568
-
569
- if (!comment) {
570
- return { operationId };
571
- }
572
-
573
- return {
574
- summary: summaryTag
575
- ? getTagText(comment, summaryTag)
576
- : parseSummary(comment),
577
- description: getTagText(comment, descriptionTag),
578
- operationId
579
- };
580
- } catch (e: unknown) {
581
- console.error(e);
582
- return undefined;
583
- }
584
- };
585
- };
586
- `;
587
- const rootControllerFolder = '(root)';
588
- const pathParameterAsName = (segment)=>segment.startsWith(':') ? `_${segment.slice(1)}_` : segment;
589
- const isPathParameterName = (name)=>name.startsWith(':') || /^_.+_$/.test(name);
590
- const endpointFileNames = new Set([
591
- 'get',
592
- 'post',
593
- 'put',
594
- 'patch',
595
- 'delete'
596
- ].map((method)=>`${method.toUpperCase()}.ts`));
597
- const entries = (folder)=>node_fs.existsSync(folder) ? node_fs.readdirSync(folder, {
598
- withFileTypes: true
599
- }) : [];
600
- const subfolders = (folder)=>entries(folder).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name);
601
- const restFolders = (boundedContextFolder)=>({
602
- presentation: node_path.join(boundedContextFolder, 'presentation', 'rest'),
603
- wiring: node_path.join(boundedContextFolder, 'wiring', 'presentation', 'rest')
604
- });
605
- const restControllers = (boundedContextFolder)=>subfolders(restFolders(boundedContextFolder).presentation).filter((name)=>name !== rootControllerFolder && !isPathParameterName(name));
606
- const rootStaticSegments = (boundedContextFolder)=>subfolders(node_path.join(restFolders(boundedContextFolder).presentation, rootControllerFolder)).filter((name)=>!isPathParameterName(name));
607
- const legacyRootEndpoints = (boundedContextFolder)=>{
608
- const { presentation, wiring } = restFolders(boundedContextFolder);
609
- return {
610
- endpointFiles: entries(presentation).filter((entry)=>entry.isFile() && endpointFileNames.has(entry.name)).map((entry)=>node_path.join(presentation, entry.name)),
611
- parameterFolders: subfolders(presentation).filter(isPathParameterName).map((name)=>node_path.join(presentation, name)),
612
- wireFiles: entries(wiring).filter((entry)=>entry.isFile() && 'index.ts' !== entry.name && /\.ts$/.test(entry.name)).map((entry)=>node_path.join(wiring, entry.name))
613
- };
614
- };
615
- const hasLegacyRootEndpoints = (boundedContextFolder)=>Object.values(legacyRootEndpoints(boundedContextFolder)).some((paths)=>paths.length > 0);
616
- export { addInMemoryDbSection, codeExtension, endpointFileLookup, escapeRegExp, hasDependency, hasLegacyRootEndpoints, inMemoryDbScaffolded, inMemoryDbSectionMembers, inMemoryDbTypeImport, inMemoryImplementationType, injectInMemoryDb, isInMemoryDb, isPathParameterName, keepInMemoryDbSection, legacyEndpointFileLookup, legacyHasId, legacyRootEndpoints, legacyWithIdLookup, missingDomainFirstPackages, missingPackages, openapiExtractor, openapiExtractorPath, pathParameterAsName, plural, projectImports, restControllers, restFolders, rootEndpointFileLookup, rootStaticSegments, scaffoldInMemoryDb, stageModuleMove, toPosix, usesInMemoryDb, walk, wireInMemoryDb, withIdLookup };