@domain-first/project-structure 8.9.0 → 8.9.2

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/287.js CHANGED
@@ -3,9 +3,8 @@ import { AsyncLocalStorage } from "node:async_hooks";
3
3
  import { Separator, checkbox as prompts_checkbox, confirm as prompts_confirm, input, search, select as prompts_select } from "@inquirer/prompts";
4
4
  import node_fs from "node:fs";
5
5
  import { styleText } from "node:util";
6
- import { addImport, availableDependencies, findWiredModules, UnknownFormatNaming, readWiredModule, addClassMember, hasNeighboringBoundedContext, addBranchedImplementation, addWireDependencies, boundedContextLocation, addConstructorParameters, relativeImport, wireBranches, wireDependencies, implementationType as wiring_implementationType, crossContextImportAllowed, crossContextImplementation, isSuggestedFor } from "./947.js";
7
- import { implementationLabelSchema, withoutOverwrites, domainFirstPackages as config_file_domainFirstPackages, scaffoldBackendRules, branchNameSchema, discardPendingChanges, ConfigFile, filesToOverwrite, Folder, implementationKinds, writePendingChanges, File, ProjectRoot, compilerOption } from "./780.js";
8
- import { missingDomainFirstPackages, walk, projectImports, escapeRegExp, pathParameterAsName, hasLegacyRootEndpoints, stageModuleMove, toPosix, rootStaticSegments, openapiExtractorPath, restControllers, hasDependency, openapiExtractor, missingPackages, codeExtension, isPathParameterName } from "./526.js";
6
+ import { availableDependencies, isSuggestedFor, domainFirstPackages as config_file_domainFirstPackages, scaffoldBackendRules, discardPendingChanges, UnknownFormatNaming, findWiredModules, Folder, compilerOption, implementationKinds, writePendingChanges, readWiredModule, addBranchedImplementation, hasNeighboringBoundedContext, implementationLabelSchema, withoutOverwrites, boundedContextLocation, branchNameSchema, filesToOverwrite, ConfigFile, relativeImport, wireBranches, wireDependencies, File, ProjectRoot, crossContextImportAllowed, crossContextImplementation, implementationType as wiring_implementationType } from "./201.js";
7
+ import { codeExtension, restControllers, missingDomainFirstPackages, isPathParameterName, keepInMemoryDbSection, walk, escapeRegExp, wireInMemoryDb, projectImports, pathParameterAsName, stageModuleMove, hasLegacyRootEndpoints, inMemoryImplementationType, toPosix, rootStaticSegments, inMemoryDbScaffolded, scaffoldInMemoryDb, injectInMemoryDb, isInMemoryDb, openapiExtractorPath, inMemoryDbTypeImport, addInMemoryDbSection, openapiExtractor, plural, missingPackages, inMemoryDbSectionMembers, usesInMemoryDb, hasDependency } from "./115.js";
9
8
  const moduleId = (module)=>`${boundedContextLocation(module.typeFile)?.name ?? 'shared-kernel'}:${module.typeName}`;
10
9
  const unitId = (unit)=>`${unit.kind}:${unit.aggregate ? `${unit.aggregate}/` : ''}${unit.name}`;
11
10
  const savedImplementations = (kind, purpose)=>[
@@ -371,207 +370,6 @@ const addDrizzle = async ()=>{
371
370
  })
372
371
  ];
373
372
  };
374
- const inMemoryImplementationType = 'in-memory';
375
- const in_memory_db_className = 'InMemoryDbInfrastructureService';
376
- const in_memory_db_wireName = 'wireInMemoryDbInfrastructureService';
377
- const parameterName = 'inMemoryDbInfrastructureService';
378
- const inMemoryDbService = `type Entry = {
379
- id: unknown;
380
- item: any;
381
- };
382
-
383
- declare global {
384
- var ___SHARED_IN_MEMORY_DB___: Record<string, Array<Entry>> | undefined;
385
- }
386
-
387
- type Section<T, TId> = {
388
- all: (predicate?: (x: T) => boolean) => T[];
389
- first: (predicate: (x: T) => boolean) => T | null;
390
- withId: (id: TId) => T | null;
391
- lastAddedItem: () => T | null;
392
- save: (payload: T extends { id: TId } ? T : [TId, T]) => void;
393
- deleteById: (id: TId) => void;
394
- delete: (predicate: (x: T) => boolean) => void;
395
- };
396
-
397
- type IdsAreEqual<TId> = (a: TId, b: TId) => boolean;
398
-
399
- const comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;
400
-
401
- const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
402
- if (typeof a !== 'object' || a === null) {
403
- return Object.is(a, b);
404
- }
405
-
406
- for (const methodName of comparisonMethodNames) {
407
- const method: unknown = (a as Record<string, unknown>)[methodName];
408
- if (typeof method === 'function') {
409
- return Boolean(method.call(a, b));
410
- }
411
- }
412
-
413
- return Object.is(a, b);
414
- };
415
-
416
- const hasId = (x: unknown): x is { id: unknown } =>
417
- typeof x === 'object' && x !== null && 'id' in x;
418
-
419
- export class InMemoryDbInfrastructureService {
420
- protected section<T extends { id: unknown }>(
421
- key: string,
422
- idsAreEqual?: IdsAreEqual<T['id']>
423
- ): Section<T, T['id']>;
424
- protected section<T, TId>(
425
- key: string,
426
- idsAreEqual?: IdsAreEqual<TId>
427
- ): Section<T, TId>;
428
- protected section<T, TId>(
429
- key: string,
430
- idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual
431
- ): Section<T, TId> {
432
- if (!globalThis.___SHARED_IN_MEMORY_DB___) {
433
- globalThis.___SHARED_IN_MEMORY_DB___ = {};
434
- }
435
-
436
- if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
437
- globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
438
- }
439
-
440
- const items = (): T[] =>
441
- globalThis.___SHARED_IN_MEMORY_DB___![key].map(
442
- (entry) => entry.item
443
- );
444
-
445
- return {
446
- all: (predicate: (x: T) => boolean = () => true): T[] =>
447
- items().filter(predicate),
448
- first: (predicate: (x: T) => boolean): T | null =>
449
- items().find(predicate) ?? null,
450
- withId: (id: TId): T | null =>
451
- items().find(
452
- (x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
453
- ) ?? null,
454
- lastAddedItem: (): T | null =>
455
- globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
456
- save: (payload: T extends { id: TId } ? T : [TId, T]) => {
457
- const id = Array.isArray(payload) ? payload[0] : payload.id;
458
- const item = Array.isArray(payload) ? payload[1] : payload;
459
- const entries = globalThis.___SHARED_IN_MEMORY_DB___![key];
460
- const existing = entries.find((entry) =>
461
- idsAreEqual(entry.id as TId, id)
462
- );
463
- if (existing) {
464
- existing.item = item;
465
- return;
466
- }
467
- entries.push({ id, item });
468
- },
469
- deleteById: (id: TId) => {
470
- globalThis.___SHARED_IN_MEMORY_DB___![key] =
471
- globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
472
- (entry) => !idsAreEqual(entry.id as TId, id)
473
- );
474
- },
475
- delete: (predicate: (x: T) => boolean) => {
476
- globalThis.___SHARED_IN_MEMORY_DB___![key] =
477
- globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
478
- (entry) => !predicate(entry.item)
479
- );
480
- }
481
- };
482
- }
483
- }
484
- `;
485
- const inMemoryDbWiring = `import { wireClass } from '@domain-first/wire';
486
- import { InMemoryDbInfrastructureService } from '../../infrastructure/services/in-memory-db-infrastructure-service';
487
-
488
- export const wireInMemoryDbInfrastructureService = wireClass(
489
- InMemoryDbInfrastructureService,
490
- []
491
- );
492
- `;
493
- const in_memory_db_withWiring = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
494
- const in_memory_db_sharedFolder = ()=>new Folder(new ProjectRoot().path).subitem([
495
- ConfigFile.Instance.data.project.rootFolder,
496
- 'shared-kernel'
497
- ]);
498
- const serviceFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
499
- 'infrastructure',
500
- 'services',
501
- 'in-memory-db-infrastructure-service.ts'
502
- ]);
503
- const in_memory_db_wireFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
504
- 'wiring',
505
- 'infrastructure-services',
506
- 'wire-in-memory-db-infrastructure-service.ts'
507
- ]);
508
- const scaffoldInMemoryDb = (shared)=>{
509
- const servicesFolder = shared.subitem([
510
- 'infrastructure',
511
- 'services'
512
- ]);
513
- servicesFolder.createFile('in-memory-db-infrastructure-service.ts', inMemoryDbService);
514
- if (in_memory_db_withWiring()) shared.subitem([
515
- 'wiring',
516
- 'infrastructure-services'
517
- ]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
518
- };
519
- const inMemoryDbScaffolded = ()=>serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_wireFile().exists);
520
- const usesInMemoryDb = (implementationType)=>Boolean(ConfigFile.Instance.data.backend?.withInMemoryDb) && new UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && inMemoryDbScaffolded();
521
- const uncountableEndings = [
522
- 'data',
523
- 'info',
524
- 'usage',
525
- 'feedback',
526
- 'media',
527
- 'ware',
528
- 'equipment',
529
- 'information',
530
- 'knowledge',
531
- 'traffic',
532
- 'telemetry',
533
- 'analytics',
534
- 'series'
535
- ];
536
- const uncountable = new RegExp(`(${uncountableEndings.join('|')})$`, 'i');
537
- const plural = (word)=>{
538
- if (uncountable.test(word)) return word;
539
- if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
540
- if (/(^|[^aeiou]|qu)[aeiou]z$/i.test(word)) return `${word}zes`;
541
- if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
542
- return `${word}s`;
543
- };
544
- const addInMemoryDbSection = (typeNaming, typeImportTarget)=>{
545
- const file = serviceFile();
546
- const sectionNaming = new UnknownFormatNaming(plural(typeNaming.fileName));
547
- const field = sectionNaming.variableName;
548
- if (new RegExp(`\\b${field}\\s*=\\s*this\\.section\\b`).test(file.data)) return field;
549
- const withImport = addImport(file.data, `import type { ${typeNaming.ClassName} } from '${relativeImport(file.path, typeImportTarget)}';`);
550
- file.update(addClassMember(withImport, in_memory_db_className, `${field} = this.section<${typeNaming.ClassName}>('${sectionNaming.fileName.toUpperCase()}');`));
551
- return field;
552
- };
553
- const inMemoryDbTypeImport = (fromFile)=>`import type { ${in_memory_db_className} } from '${relativeImport(fromFile, serviceFile().path)}'`;
554
- const inMemoryDbSectionMembers = (field, derived)=>`
555
- private readonly data: ${in_memory_db_className}['${field}']
556
-
557
- constructor(${parameterName}: ${in_memory_db_className}) {
558
- ${derived ? 'super()\n ' : ''}this.data = ${parameterName}.${field}
559
- }
560
- `.trim();
561
- const keepInMemoryDbSection = (classFile, field)=>{
562
- classFile.update(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)).replace('constructor() {}', inMemoryDbSectionMembers(field, false)));
563
- };
564
- const isInMemoryDb = (module)=>module.wireName === in_memory_db_wireName;
565
- const injectInMemoryDb = (classFile, implementationName)=>{
566
- classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
567
- `private readonly ${parameterName}: ${in_memory_db_className}`
568
- ]));
569
- };
570
- const wireInMemoryDb = (consumerWireFile, implementationName)=>{
571
- consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${in_memory_db_wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
572
- in_memory_db_wireName
573
- ]));
574
- };
575
373
  const addInMemoryDb = ()=>{
576
374
  const config = ConfigFile.Instance.data;
577
375
  if (!ConfigFile.backend.withInMemoryDb) ConfigFile.update({
@@ -587,11 +385,6 @@ const addInMemoryDb = ()=>{
587
385
  return [];
588
386
  };
589
387
  const inMemoryDbApplied = ()=>Boolean(ConfigFile.Instance.data.backend?.withInMemoryDb) && inMemoryDbScaffolded();
590
- const usesNext = ()=>ConfigFile.exists && ConfigFile.Instance.data.frontend?.react?.framework === 'next';
591
- const nextAppFolder = (root)=>[
592
- 'app',
593
- 'src/app'
594
- ].find((folder)=>new Folder(node_path.join(root, folder)).exists) ?? 'app';
595
388
  const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
596
389
  class NestedName {
597
390
  folders;
@@ -614,6 +407,11 @@ class NestedName {
614
407
  return true;
615
408
  };
616
409
  }
410
+ const usesNext = ()=>ConfigFile.exists && ConfigFile.Instance.data.frontend?.react?.framework === 'next';
411
+ const nextAppFolder = (root)=>[
412
+ 'app',
413
+ 'src/app'
414
+ ].find((folder)=>new Folder(node_path.join(root, folder)).exists) ?? 'app';
617
415
  const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
618
416
  ${[
619
417
  ...imports,
@@ -633,13 +431,14 @@ export default function Page() {
633
431
  return <${ClassName}Page />
634
432
  }
635
433
  `.trim();
636
- const scaffoldNextRoute = (name, pageFile)=>{
434
+ const scaffoldNextRoute = (name, pagePath)=>{
637
435
  const root = new ProjectRoot().path;
638
436
  const route = node_path.join(root, nextAppFolder(root), ...name.folders, name.folderName, 'page.tsx');
639
437
  const relativeRoute = node_path.relative(root, route).split(node_path.sep).join('/');
640
438
  const routeFile = new File(route);
641
- if (routeFile.exists) return void report(`${relativeRoute} already exists: render ${name.ClassName}Page there yourself.`);
642
- routeFile.data = nextRouteContent(name.ClassName, relativeImport(route, pageFile.path.replace(/\.tsx$/, '')));
439
+ const content = nextRouteContent(name.ClassName, relativeImport(route, pagePath.replace(/\.tsx$/, '')));
440
+ if (routeFile.exists) return routeFile.data === content ? void 0 : `${relativeRoute} already exists: render ${name.ClassName}Page there yourself.`;
441
+ routeFile.data = content;
643
442
  };
644
443
  const scaffoldReactPage = async (presentationReactFolder)=>{
645
444
  const name = await interaction_input({
@@ -653,7 +452,10 @@ const scaffoldReactPage = async (presentationReactFolder)=>{
653
452
  'pages',
654
453
  ...folders
655
454
  ]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
656
- if (usesNext()) scaffoldNextRoute(nestedName, pageFile);
455
+ if (usesNext()) {
456
+ const hint = scaffoldNextRoute(nestedName, pageFile.path);
457
+ if (hint) report(hint);
458
+ }
657
459
  };
658
460
  const openapiScriptPath = "scripts/generate-openapi.ts";
659
461
  const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
@@ -662,9 +464,9 @@ const extractorPackages = [
662
464
  '@microsoft/tsdoc'
663
465
  ];
664
466
  const swaggerPagePath = (rootFolder)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/pages/swagger-page.tsx');
665
- const swaggerPage = (rootFolder, outputPath)=>{
467
+ const swaggerPage = (rootFolder, outputPath, withNext = false)=>{
666
468
  const specImport = node_path.posix.relative(node_path.posix.dirname(swaggerPagePath(rootFolder)), outputPath);
667
- return reactPageContent('Swagger', {
469
+ const page = reactPageContent('Swagger', {
668
470
  imports: [
669
471
  "import 'swagger-ui-react/swagger-ui.css'",
670
472
  "import SwaggerUI from 'swagger-ui-react'",
@@ -672,6 +474,7 @@ const swaggerPage = (rootFolder, outputPath)=>{
672
474
  ],
673
475
  body: '<SwaggerUI displayOperationId spec={spec} />'
674
476
  });
477
+ return withNext ? `'use client'\n\n${page}` : page;
675
478
  };
676
479
  const openapiScripts = {
677
480
  openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
@@ -753,10 +556,14 @@ const addOpenapi = async ()=>{
753
556
  const generatorFile = new File(node_path.join(root, openapiScriptPath));
754
557
  const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
755
558
  if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
559
+ const withNextRoute = withSwaggerPage && usesNext();
560
+ let nextRouteHint;
756
561
  if (withSwaggerPage) {
757
- const pageFile = new File(node_path.join(root, swaggerPagePath(rootFolder)));
758
- const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'));
562
+ const pagePath = node_path.join(root, swaggerPagePath(rootFolder));
563
+ const pageFile = new File(pagePath);
564
+ const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'), withNextRoute);
759
565
  if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
566
+ if (withNextRoute) nextRouteHint = scaffoldNextRoute(new NestedName('swagger'), pagePath);
760
567
  }
761
568
  const resolveJsonModule = withSwaggerPage ? compilerOption(node_path.join(root, 'tsconfig.json'), 'resolveJsonModule') : true;
762
569
  const hasRestHandlers = new File(node_path.join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
@@ -783,9 +590,12 @@ const addOpenapi = async ()=>{
783
590
  ...describeScripts(selected, {
784
591
  openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
785
592
  }),
786
- ...withSwaggerPage ? [
593
+ ...withSwaggerPage && !withNextRoute ? [
787
594
  `SwaggerPage from ${swaggerPagePath(rootFolder)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
788
595
  ] : [],
596
+ ...withNextRoute ? [
597
+ nextRouteHint ?? `/swagger shows ${splitPath(outputPath).join('/')} once it is generated — the route is ${nextAppFolder(root)}/swagger/page.tsx`
598
+ ] : [],
789
599
  ...hasRestHandlers ? [] : [
790
600
  `restHandlers appear in ${node_path.posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
791
601
  ]
package/dist/38.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import node_fs from "node:fs";
2
2
  import node_path from "node:path";
3
- import { namedImportFiles, canDependOn, isCrossContextImplementation, findWiredModules, moduleKindOf, readWiredModule, crossContextImportAllowed, wiredDependencyNames } from "./947.js";
4
- import { defaultDependencyRules, fileModuleKind, compilerOption } from "./780.js";
3
+ import { defaultDependencyRules, fileModuleKind, namedImportFiles, canDependOn, isCrossContextImplementation, findWiredModules, moduleKindOf, readWiredModule, crossContextImportAllowed, compilerOption, wiredDependencyNames } from "./201.js";
5
4
  const readAliases = (projectRoot)=>{
6
5
  const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
7
6
  const paths = compilerOption(tsconfig, 'paths');
package/dist/561.js CHANGED
@@ -2,10 +2,9 @@ import node_fs from "node:fs";
2
2
  import node_path from "node:path";
3
3
  import { parseArgs } from "node:util";
4
4
  import zod from "zod";
5
- import { implementationLabelSchema, discardPendingChanges, filesToOverwrite, ConfigFile, Folder, implementationKinds, ProjectRoot, pendingChanges } from "./780.js";
5
+ import { implementationLabelSchema, availableDependencies, discardPendingChanges, findWiredModules, filesToOverwrite, ConfigFile, Folder, implementationKinds, ProjectRoot, pendingChanges, hasNeighboringBoundedContext } from "./201.js";
6
6
  import { scaffoldNewHandlersRestEndpoint, addIntegration, findContracts, helperImplementationTypes, scaffoldNewAggregateUseCase, scaffoldNewInfrastructureService, runWithAnswers, scaffoldNewCommand, scaffoldNewQuery, findReactModules, moveBackendUnitUseCase, scaffoldReactUIKitComponent, scaffoldReactSharedHook, moveReactModuleUseCase, reactKindTitles, deleteBackendUnitUseCase, integrationIds, scaffoldNewApplicationService, scaffoldNewImplementation, savedImplementations, RequestError, deleteReactModuleUseCase, rootControllerChoice, moduleId, assertAnswersConsumed, scaffoldNewDomainService, findRestEndpointGenerator, scaffoldNewErrorUseCase, scaffoldReactWidget, savePendingChanges, unitId, systemImplementationChoices, scaffoldReactPage, scaffoldNewPresentationService, scaffoldNewInfrastructureHelper, integrationSpecsAvailable, integrationSpecFile, findBackendUnits, scaffoldNewUseCase, integrationDescriptions, wireDependency, scaffoldNewDomainObject, scaffoldNewBoundedContextUseCase, scaffoldNewApplicationPort } from "./287.js";
7
- import { findWiredModules, availableDependencies, hasNeighboringBoundedContext } from "./947.js";
8
- import { restControllers } from "./526.js";
7
+ import { restControllers } from "./115.js";
9
8
  const agent_requests_name = implementationLabelSchema;
10
9
  const nestedName = zod.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*(?:\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*)*$/);
11
10
  const id = zod.string().min(1);
package/dist/graph.js CHANGED
@@ -4,9 +4,8 @@ import node_fs from "node:fs";
4
4
  import node_os from "node:os";
5
5
  import node_path from "node:path";
6
6
  import { parseArgs } from "node:util";
7
- import { File, ProjectRoot, outdatedConfigMessage, ConfigFile } from "./780.js";
7
+ import { namedImportFiles, wiring_layers, findWiredModules, outdatedConfigMessage, ConfigFile, File, ProjectRoot, wiredDependencyNames } from "./201.js";
8
8
  import { readAliases, resolveSpecifier } from "./38.js";
9
- import { namedImportFiles, wiring_layers, findWiredModules, wiredDependencyNames } from "./947.js";
10
9
  const sharedKernel = 'shared-kernel';
11
10
  const contextsOf = (contextsFolder)=>node_fs.existsSync(contextsFolder) ? node_fs.readdirSync(contextsFolder, {
12
11
  withFileTypes: true
@@ -5,6 +5,15 @@ import { type WiredModule } from './wiring';
5
5
  * Implementations of this type get the in-memory DB.
6
6
  */
7
7
  export declare const inMemoryImplementationType = "in-memory";
8
+ /**
9
+ * `withId` of 8.9.0 and earlier: it compared the stored items' `id`,
10
+ * so items saved as an `[id, item]` tuple were never found.
11
+ */
12
+ export declare const legacyWithIdLookup = " withId: (id: TId): T | null =>\n items().find(\n (x: T) => hasId(x) && idsAreEqual(x.id as TId, id)\n ) ?? null,\n";
13
+ export declare const legacyHasId = "const hasId = (x: unknown): x is { id: unknown } =>\n typeof x === 'object' && x !== null && 'id' in x;\n\n";
14
+ /** Looks up the id saved with the item, as `save` and `deleteById` do. */
15
+ export declare const withIdLookup = " withId: (id: TId): T | null =>\n globalThis.___SHARED_IN_MEMORY_DB___![key].find((entry) =>\n idsAreEqual(entry.id as TId, id)\n )?.item ?? null,\n";
16
+ export declare const inMemoryDbService = "type Entry = {\n id: unknown;\n item: any;\n};\n\ndeclare global {\n var ___SHARED_IN_MEMORY_DB___: Record<string, Array<Entry>> | undefined;\n}\n\ntype Section<T, TId> = {\n all: (predicate?: (x: T) => boolean) => T[];\n first: (predicate: (x: T) => boolean) => T | null;\n withId: (id: TId) => T | null;\n lastAddedItem: () => T | null;\n save: (payload: T extends { id: TId } ? T : [TId, T]) => void;\n deleteById: (id: TId) => void;\n delete: (predicate: (x: T) => boolean) => void;\n};\n\ntype IdsAreEqual<TId> = (a: TId, b: TId) => boolean;\n\nconst comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;\n\nconst defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {\n if (typeof a !== 'object' || a === null) {\n return Object.is(a, b);\n }\n\n for (const methodName of comparisonMethodNames) {\n const method: unknown = (a as Record<string, unknown>)[methodName];\n if (typeof method === 'function') {\n return Boolean(method.call(a, b));\n }\n }\n\n return Object.is(a, b);\n};\n\nexport class InMemoryDbInfrastructureService {\n protected section<T extends { id: unknown }>(\n key: string,\n idsAreEqual?: IdsAreEqual<T['id']>\n ): Section<T, T['id']>;\n protected section<T, TId>(\n key: string,\n idsAreEqual?: IdsAreEqual<TId>\n ): Section<T, TId>;\n protected section<T, TId>(\n key: string,\n idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual\n ): Section<T, TId> {\n if (!globalThis.___SHARED_IN_MEMORY_DB___) {\n globalThis.___SHARED_IN_MEMORY_DB___ = {};\n }\n\n if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {\n globalThis.___SHARED_IN_MEMORY_DB___[key] = [];\n }\n\n const items = (): T[] =>\n globalThis.___SHARED_IN_MEMORY_DB___![key].map(\n (entry) => entry.item\n );\n\n return {\n all: (predicate: (x: T) => boolean = () => true): T[] =>\n items().filter(predicate),\n first: (predicate: (x: T) => boolean): T | null =>\n items().find(predicate) ?? null,\n withId: (id: TId): T | null =>\n globalThis.___SHARED_IN_MEMORY_DB___![key].find((entry) =>\n idsAreEqual(entry.id as TId, id)\n )?.item ?? null,\n lastAddedItem: (): T | null =>\n globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,\n save: (payload: T extends { id: TId } ? T : [TId, T]) => {\n const id = Array.isArray(payload) ? payload[0] : payload.id;\n const item = Array.isArray(payload) ? payload[1] : payload;\n const entries = globalThis.___SHARED_IN_MEMORY_DB___![key];\n const existing = entries.find((entry) =>\n idsAreEqual(entry.id as TId, id)\n );\n if (existing) {\n existing.item = item;\n return;\n }\n entries.push({ id, item });\n },\n deleteById: (id: TId) => {\n globalThis.___SHARED_IN_MEMORY_DB___![key] =\n globalThis.___SHARED_IN_MEMORY_DB___![key].filter(\n (entry) => !idsAreEqual(entry.id as TId, id)\n );\n },\n delete: (predicate: (x: T) => boolean) => {\n globalThis.___SHARED_IN_MEMORY_DB___![key] =\n globalThis.___SHARED_IN_MEMORY_DB___![key].filter(\n (entry) => !predicate(entry.item)\n );\n }\n };\n }\n}\n";
8
17
  /**
9
18
  * The shared in-memory DB with its wire, as the config says.
10
19
  */
package/dist/index.cjs CHANGED
@@ -1283,6 +1283,11 @@ const inMemoryImplementationType = 'in-memory';
1283
1283
  const in_memory_db_className = 'InMemoryDbInfrastructureService';
1284
1284
  const in_memory_db_wireName = 'wireInMemoryDbInfrastructureService';
1285
1285
  const in_memory_db_parameterName = 'inMemoryDbInfrastructureService';
1286
+ const withIdLookup = ` withId: (id: TId): T | null =>
1287
+ globalThis.___SHARED_IN_MEMORY_DB___![key].find((entry) =>
1288
+ idsAreEqual(entry.id as TId, id)
1289
+ )?.item ?? null,
1290
+ `;
1286
1291
  const inMemoryDbService = `type Entry = {
1287
1292
  id: unknown;
1288
1293
  item: any;
@@ -1321,9 +1326,6 @@ const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
1321
1326
  return Object.is(a, b);
1322
1327
  };
1323
1328
 
1324
- const hasId = (x: unknown): x is { id: unknown } =>
1325
- typeof x === 'object' && x !== null && 'id' in x;
1326
-
1327
1329
  export class InMemoryDbInfrastructureService {
1328
1330
  protected section<T extends { id: unknown }>(
1329
1331
  key: string,
@@ -1355,11 +1357,7 @@ export class InMemoryDbInfrastructureService {
1355
1357
  items().filter(predicate),
1356
1358
  first: (predicate: (x: T) => boolean): T | null =>
1357
1359
  items().find(predicate) ?? null,
1358
- withId: (id: TId): T | null =>
1359
- items().find(
1360
- (x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
1361
- ) ?? null,
1362
- lastAddedItem: (): T | null =>
1360
+ ${withIdLookup} lastAddedItem: (): T | null =>
1363
1361
  globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
1364
1362
  save: (payload: T extends { id: TId } ? T : [TId, T]) => {
1365
1363
  const id = Array.isArray(payload) ? payload[0] : payload.id;
@@ -1513,6 +1511,28 @@ const missing_domain_first_packages_missingPackages = (packages)=>{
1513
1511
  `npm i ${missing.join(' ')}`
1514
1512
  ] : [];
1515
1513
  };
1514
+ const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
1515
+ class NestedName {
1516
+ folders;
1517
+ folderName;
1518
+ fileName;
1519
+ ClassName;
1520
+ classNameSegments;
1521
+ constructor(rawSource){
1522
+ const segments = splitSegments(rawSource);
1523
+ this.folders = segments.slice(0, -1);
1524
+ this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
1525
+ this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
1526
+ this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
1527
+ this.ClassName = this.classNameSegments.join('');
1528
+ }
1529
+ static validate = (rawSource)=>{
1530
+ const segments = splitSegments(rawSource);
1531
+ if (!segments.length) return 'Name is required';
1532
+ if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
1533
+ return true;
1534
+ };
1535
+ }
1516
1536
  const usesNext = ()=>config_file_ConfigFile.exists && config_file_ConfigFile.Instance.data.frontend?.react?.framework === 'next';
1517
1537
  const nextAppFolder = (root)=>[
1518
1538
  'app',
@@ -1552,28 +1572,6 @@ const compilerOption = (configFile, name, seen = new Set())=>{
1552
1572
  if (void 0 !== value) return value;
1553
1573
  }
1554
1574
  };
1555
- const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
1556
- class NestedName {
1557
- folders;
1558
- folderName;
1559
- fileName;
1560
- ClassName;
1561
- classNameSegments;
1562
- constructor(rawSource){
1563
- const segments = splitSegments(rawSource);
1564
- this.folders = segments.slice(0, -1);
1565
- this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
1566
- this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
1567
- this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
1568
- this.ClassName = this.classNameSegments.join('');
1569
- }
1570
- static validate = (rawSource)=>{
1571
- const segments = splitSegments(rawSource);
1572
- if (!segments.length) return 'Name is required';
1573
- if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
1574
- return true;
1575
- };
1576
- }
1577
1575
  const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
1578
1576
  ${[
1579
1577
  ...imports,
@@ -1593,13 +1591,14 @@ export default function Page() {
1593
1591
  return <${ClassName}Page />
1594
1592
  }
1595
1593
  `.trim();
1596
- const scaffoldNextRoute = (name, pageFile)=>{
1594
+ const scaffoldNextRoute = (name, pagePath)=>{
1597
1595
  const root = new project_root_ProjectRoot().path;
1598
1596
  const route = external_node_path_default().join(root, nextAppFolder(root), ...name.folders, name.folderName, 'page.tsx');
1599
1597
  const relativeRoute = external_node_path_default().relative(root, route).split(external_node_path_default().sep).join('/');
1600
1598
  const routeFile = new file_system_File(route);
1601
- if (routeFile.exists) return void report(`${relativeRoute} already exists: render ${name.ClassName}Page there yourself.`);
1602
- routeFile.data = nextRouteContent(name.ClassName, relativeImport(route, pageFile.path.replace(/\.tsx$/, '')));
1599
+ const content = nextRouteContent(name.ClassName, relativeImport(route, pagePath.replace(/\.tsx$/, '')));
1600
+ if (routeFile.exists) return routeFile.data === content ? void 0 : `${relativeRoute} already exists: render ${name.ClassName}Page there yourself.`;
1601
+ routeFile.data = content;
1603
1602
  };
1604
1603
  const scaffoldReactPage = async (presentationReactFolder)=>{
1605
1604
  const name = await interaction_input({
@@ -1613,7 +1612,10 @@ const scaffoldReactPage = async (presentationReactFolder)=>{
1613
1612
  'pages',
1614
1613
  ...folders
1615
1614
  ]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
1616
- if (usesNext()) scaffoldNextRoute(nestedName, pageFile);
1615
+ if (usesNext()) {
1616
+ const hint = scaffoldNextRoute(nestedName, pageFile.path);
1617
+ if (hint) report(hint);
1618
+ }
1617
1619
  };
1618
1620
  const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
1619
1621
  const rootFolderSegments = (rootFolder, indent = 20)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n${' '.repeat(indent)}`).join('');
@@ -1786,9 +1788,9 @@ const extractorPackages = [
1786
1788
  '@microsoft/tsdoc'
1787
1789
  ];
1788
1790
  const swaggerPagePath = (rootFolder)=>external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/pages/swagger-page.tsx');
1789
- const swaggerPage = (rootFolder, outputPath)=>{
1791
+ const swaggerPage = (rootFolder, outputPath, withNext = false)=>{
1790
1792
  const specImport = external_node_path_default().posix.relative(external_node_path_default().posix.dirname(swaggerPagePath(rootFolder)), outputPath);
1791
- return reactPageContent('Swagger', {
1793
+ const page = reactPageContent('Swagger', {
1792
1794
  imports: [
1793
1795
  "import 'swagger-ui-react/swagger-ui.css'",
1794
1796
  "import SwaggerUI from 'swagger-ui-react'",
@@ -1796,6 +1798,7 @@ const swaggerPage = (rootFolder, outputPath)=>{
1796
1798
  ],
1797
1799
  body: '<SwaggerUI displayOperationId spec={spec} />'
1798
1800
  });
1801
+ return withNext ? `'use client'\n\n${page}` : page;
1799
1802
  };
1800
1803
  const openapiScripts = {
1801
1804
  openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
@@ -1877,10 +1880,14 @@ const addOpenapi = async ()=>{
1877
1880
  const generatorFile = new file_system_File(external_node_path_default().join(root, openapiScriptPath));
1878
1881
  const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
1879
1882
  if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
1883
+ const withNextRoute = withSwaggerPage && usesNext();
1884
+ let nextRouteHint;
1880
1885
  if (withSwaggerPage) {
1881
- const pageFile = new file_system_File(external_node_path_default().join(root, swaggerPagePath(rootFolder)));
1882
- const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'));
1886
+ const pagePath = external_node_path_default().join(root, swaggerPagePath(rootFolder));
1887
+ const pageFile = new file_system_File(pagePath);
1888
+ const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'), withNextRoute);
1883
1889
  if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
1890
+ if (withNextRoute) nextRouteHint = scaffoldNextRoute(new NestedName('swagger'), pagePath);
1884
1891
  }
1885
1892
  const resolveJsonModule = withSwaggerPage ? compilerOption(external_node_path_default().join(root, 'tsconfig.json'), 'resolveJsonModule') : true;
1886
1893
  const hasRestHandlers = new file_system_File(external_node_path_default().join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
@@ -1907,9 +1914,12 @@ const addOpenapi = async ()=>{
1907
1914
  ...describeScripts(selected, {
1908
1915
  openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
1909
1916
  }),
1910
- ...withSwaggerPage ? [
1917
+ ...withSwaggerPage && !withNextRoute ? [
1911
1918
  `SwaggerPage from ${swaggerPagePath(rootFolder)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
1912
1919
  ] : [],
1920
+ ...withNextRoute ? [
1921
+ nextRouteHint ?? `/swagger shows ${splitPath(outputPath).join('/')} once it is generated — the route is ${nextAppFolder(root)}/swagger/page.tsx`
1922
+ ] : [],
1913
1923
  ...hasRestHandlers ? [] : [
1914
1924
  `restHandlers appear in ${external_node_path_default().posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
1915
1925
  ]
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { select as prompts_select } from "@inquirer/prompts";
3
3
  import { runCLI } from "./561.js";
4
- import { outdatedConfigMessage, ProjectRoot, ConfigFile, Folder } from "./780.js";
4
+ import { outdatedConfigMessage, ProjectRoot, ConfigFile, Folder } from "./201.js";
5
5
  import { scaffoldNewDomainService, scaffoldNewErrorUseCase, scaffoldNewAggregateUseCase, scaffoldNewQuery, scaffoldNewInfrastructureService, scaffoldNewHandlersRestEndpoint, savePendingChanges, moveBackendUnitUseCase, scaffoldNewCommand, scaffoldNewPresentationService, scaffoldNewInfrastructureHelper, deleteBackendUnitUseCase, scaffoldNewApplicationService, scaffoldNewUseCase, scaffoldNewImplementation, wireDependency, scaffoldNewBoundedContextUseCase, scaffoldNewDomainObject, scaffoldNewApplicationPort } from "./287.js";
6
6
  const main = async ()=>{
7
7
  if (!ConfigFile.exists) {
package/dist/init.cjs CHANGED
@@ -695,6 +695,11 @@ const wiring_relativeImport = (fromFile, toFile)=>{
695
695
  return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
696
696
  };
697
697
  const inMemoryImplementationType = 'in-memory';
698
+ const withIdLookup = ` withId: (id: TId): T | null =>
699
+ globalThis.___SHARED_IN_MEMORY_DB___![key].find((entry) =>
700
+ idsAreEqual(entry.id as TId, id)
701
+ )?.item ?? null,
702
+ `;
698
703
  const inMemoryDbService = `type Entry = {
699
704
  id: unknown;
700
705
  item: any;
@@ -733,9 +738,6 @@ const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
733
738
  return Object.is(a, b);
734
739
  };
735
740
 
736
- const hasId = (x: unknown): x is { id: unknown } =>
737
- typeof x === 'object' && x !== null && 'id' in x;
738
-
739
741
  export class InMemoryDbInfrastructureService {
740
742
  protected section<T extends { id: unknown }>(
741
743
  key: string,
@@ -767,11 +769,7 @@ export class InMemoryDbInfrastructureService {
767
769
  items().filter(predicate),
768
770
  first: (predicate: (x: T) => boolean): T | null =>
769
771
  items().find(predicate) ?? null,
770
- withId: (id: TId): T | null =>
771
- items().find(
772
- (x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
773
- ) ?? null,
774
- lastAddedItem: (): T | null =>
772
+ ${withIdLookup} lastAddedItem: (): T | null =>
775
773
  globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
776
774
  save: (payload: T extends { id: TId } ? T : [TId, T]) => {
777
775
  const id = Array.isArray(payload) ? payload[0] : payload.id;
package/dist/init.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { parseArgs } from "node:util";
3
- import { ConfigFile, outdatedConfigMessage } from "./780.js";
3
+ import { ConfigFile, outdatedConfigMessage } from "./201.js";
4
4
  import { printNextSteps, configurationSections, initializeUseCase, savePendingChanges } from "./287.js";
5
5
  const help = `Usage: df-init [--section project|backend|frontend]
6
6