@domain-first/project-structure 8.6.0 → 8.7.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 (54) hide show
  1. package/README.md +1 -1
  2. package/bin/df-skills.mjs +55 -9
  3. package/dist/287.js +54 -2
  4. package/dist/38.js +36 -0
  5. package/dist/561.js +9 -1
  6. package/dist/780.js +2 -1
  7. package/dist/947.js +11 -1
  8. package/dist/agent-cli.d.ts +9 -2
  9. package/dist/agent-principles.cjs +116 -0
  10. package/dist/agent-principles.d.ts +9 -0
  11. package/dist/agent-principles.js +64 -0
  12. package/dist/agent-principles.spec.d.ts +1 -0
  13. package/dist/agent-requests.d.ts +16 -2
  14. package/dist/file-system.d.ts +2 -1
  15. package/dist/graph.cjs +12 -1
  16. package/dist/index.cjs +76 -2
  17. package/dist/index.js +4 -1
  18. package/dist/init.cjs +14 -3
  19. package/dist/integration.cjs +73 -2
  20. package/dist/lint.cjs +48 -1
  21. package/dist/react.cjs +73 -2
  22. package/dist/upgrade.cjs +21 -13
  23. package/dist/upgrade.js +19 -12
  24. package/dist/use-cases/add-integration.d.ts +1 -1
  25. package/dist/use-cases/index.d.ts +1 -0
  26. package/dist/use-cases/scaffold-new-infrastructure-helper.d.ts +7 -0
  27. package/dist/wiring.d.ts +2 -2
  28. package/package.json +3 -2
  29. package/principles/df-principles.md +33 -0
  30. package/skills/df-ps-implement/SKILL.md +26 -1
  31. package/skills/df-ps-plan-feature/SKILL.md +22 -18
  32. package/skills/df-ps-react/SKILL.md +2 -9
  33. package/skills/df-ps-react/references/generators.md +9 -9
  34. package/skills/df-ps-scaffold/SKILL.md +19 -125
  35. package/skills/df-ps-scaffold/references/agent-mode.md +2 -2
  36. package/skills/df-ps-scaffold/references/agent-operations.md +1 -0
  37. package/skills/df-ps-scaffold/references/choosing-components.md +65 -49
  38. package/skills/df-ps-scaffold/references/generators.md +28 -5
  39. package/skills/df-ps-scaffold/references/units/aggregate.md +1 -3
  40. package/skills/df-ps-scaffold/references/units/bounded-context.md +1 -1
  41. package/skills/df-ps-scaffold/references/units/command-query.md +4 -6
  42. package/skills/df-ps-scaffold/references/units/delete.md +0 -2
  43. package/skills/df-ps-scaffold/references/units/endpoint.md +1 -4
  44. package/skills/df-ps-scaffold/references/units/entity-value-object.md +0 -4
  45. package/skills/df-ps-scaffold/references/units/errors.md +0 -4
  46. package/skills/df-ps-scaffold/references/units/helper.md +30 -0
  47. package/skills/df-ps-scaffold/references/units/implementation.md +0 -4
  48. package/skills/df-ps-scaffold/references/units/move-or-rename.md +0 -4
  49. package/skills/df-ps-scaffold/references/units/port.md +2 -5
  50. package/skills/df-ps-scaffold/references/units/services.md +2 -4
  51. package/skills/df-ps-scaffold/references/units/use-case.md +1 -2
  52. package/skills/df-ps-scaffold/references/units/wire-dependency.md +0 -2
  53. package/skills/df-ps-scaffold/references/work-plan.md +73 -0
  54. package/skills/df-ps-scaffold/scripts/drive.mjs +0 -252
package/dist/index.cjs CHANGED
@@ -346,7 +346,8 @@ class file_system_File extends FileSystemItem {
346
346
  });
347
347
  };
348
348
  addLineIfMissing = (newLine, separator = '\n')=>{
349
- const alreadyAdded = this.exists && this.data.split('\n').some((line)=>line.trim() === newLine.trim());
349
+ const normalized = (line)=>line.trim().replace(/;$/, '');
350
+ const alreadyAdded = this.exists && this.data.split('\n').some((line)=>normalized(line) === normalized(newLine));
350
351
  if (!alreadyAdded) this.addLine(newLine, separator);
351
352
  };
352
353
  }
@@ -640,7 +641,17 @@ const findWiredModules = (contextPath)=>{
640
641
  const moduleKindOf = (module)=>wiredModuleKind(module.kind);
641
642
  const layerRule = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && ('infrastructure' !== consumer.implementationsLayer || 'application' !== candidate.layer || 'application-ports' === candidate.kind);
642
643
  const wiring_implementationType = (consumer, implementation)=>consumer.branched ? external_node_path_default().basename(external_node_path_default().dirname(implementation.file)) : void 0;
643
- const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && `-${external_node_path_default().basename(candidate.typeFile, '.ts')}-`.includes(`-${implementation}-`);
644
+ const systemInfrastructureServices = new Map([
645
+ [
646
+ 'prisma',
647
+ 'prisma-infrastructure-service'
648
+ ],
649
+ [
650
+ 'in-memory',
651
+ 'in-memory-db-infrastructure-service'
652
+ ]
653
+ ]);
654
+ const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && external_node_path_default().basename(candidate.typeFile, '.ts') === systemInfrastructureServices.get(implementation);
644
655
  const canDependOn = (consumer, candidate, rules = defaultDependencyRules, implementation = consumer.implementations[0])=>{
645
656
  const crossContext = crossContextImportAllowed(consumer.wireFile, candidate.wireFile);
646
657
  if (void 0 !== crossContext) return crossContext && 'infrastructure' === consumer.implementationsLayer && 'application' === candidate.layer && !!implementation && true === crossContextImportAllowed(implementation.file, candidate.typeFile);
@@ -3175,6 +3186,12 @@ const scaffoldRequestSchema = external_zod_default().discriminatedUnion('operati
3175
3186
  ...named,
3176
3187
  ...agent_requests_wired
3177
3188
  }),
3189
+ agent_requests_operation('helper', {
3190
+ ...common,
3191
+ ...agent_requests_owner,
3192
+ name: agent_requests_nestedName.describe('Kebab-case, folders split by "/": mappers/social-network-type.'),
3193
+ implementationType: agent_requests_name.describe('A saved or system implementation type: a helper belongs to one.')
3194
+ }),
3178
3195
  agent_requests_operation('presentation-service', {
3179
3196
  ...named,
3180
3197
  ...agent_requests_wired
@@ -5413,6 +5430,58 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
5413
5430
  for (const implementation of unused)report(`${implementation.className} is no longer used in any environment.`);
5414
5431
  await wireNewImplementationDependencies(ownerFolder, wireFile, className, inMemoryRepositoryWiring(ownerFolder, unit, wireFile));
5415
5432
  };
5433
+ const helperImplementationTypes = ()=>[
5434
+ ...new Set(implementationKinds.flatMap((kind)=>[
5435
+ ...savedImplementations(kind, 'primary'),
5436
+ ...savedImplementations(kind, 'test'),
5437
+ ...systemImplementationChoices(kind).map(({ value })=>value)
5438
+ ]))
5439
+ ].filter((label)=>label !== crossContextImplementation);
5440
+ const validateName = (value)=>{
5441
+ const valid = NestedName.validate(value);
5442
+ if (true !== valid) return valid;
5443
+ const { folders, folderName } = new NestedName(value);
5444
+ return [
5445
+ ...folders,
5446
+ folderName
5447
+ ].every((part)=>kebabName.test(part)) ? true : 'Use lowercase kebab-case split by "/", e.g. mappers/social-network-type';
5448
+ };
5449
+ const scaffoldNewInfrastructureHelper = async (ownerFolder)=>{
5450
+ const types = helperImplementationTypes();
5451
+ if (!types.length) return void report('No implementation types yet: a helper belongs to one, so add an implementation first.');
5452
+ const name = new NestedName(await interaction_input({
5453
+ key: 'name',
5454
+ message: 'Name (folders split by "/"): ',
5455
+ validate: validateName
5456
+ }));
5457
+ const label = await interaction_select({
5458
+ key: 'implementationType',
5459
+ message: 'Implementation:',
5460
+ choices: types.map((value)=>({
5461
+ name: value,
5462
+ value
5463
+ }))
5464
+ });
5465
+ const fileName = name.folderName.startsWith(`${label}-`) ? name.folderName : `${label}-${name.folderName}`;
5466
+ const naming = new UnknownFormatNaming(fileName);
5467
+ const folder = ownerFolder.subitem([
5468
+ 'infrastructure',
5469
+ 'helpers',
5470
+ label,
5471
+ ...name.folders
5472
+ ]);
5473
+ folder.createFile(`${fileName}.ts`, `export const ${naming.variableName} = () => {}`);
5474
+ if (config_file_ConfigFile.backend.testingLibrary) folder.createFile(`${fileName}.spec.ts`, `
5475
+ import { describe, test, expect } from '${config_file_ConfigFile.backend.testingLibrary}'
5476
+ import { ${naming.variableName} } from './${fileName}'
5477
+
5478
+ describe('${naming.withSpaces}', () => {
5479
+ test('is defined', () => {
5480
+ expect(${naming.variableName}).toBeDefined()
5481
+ })
5482
+ })
5483
+ `.trim());
5484
+ };
5416
5485
  const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
5417
5486
  const name = await interaction_input({
5418
5487
  key: 'name',
@@ -5985,6 +6054,7 @@ const executeScaffold = async (request, owner)=>{
5985
6054
  ]).content.fileNames.includes(request.namespace)) throw new RequestError('TARGET_NOT_FOUND', `Unknown namespace: ${request.namespace}.`);
5986
6055
  if ('implementation' === request.operation && !findContracts(owner.path).length) throw new RequestError('TARGET_NOT_FOUND', 'No contracts in this context.');
5987
6056
  if (('move' === request.operation || 'delete' === request.operation) && !findBackendUnits(owner.path).length) throw new RequestError('TARGET_NOT_FOUND', 'No modules in this context.');
6057
+ if ('helper' === request.operation && !helperImplementationTypes().length) throw new RequestError('TARGET_NOT_FOUND', 'No implementation types yet: add an implementation first.');
5988
6058
  if ('wire-dependency' === request.operation && (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') || !findWiredModules(owner.path).length)) throw new RequestError('TARGET_NOT_FOUND', 'No wired modules in this context.');
5989
6059
  if ('endpoint' === request.operation) {
5990
6060
  if (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers-rest') || !findRestEndpointGenerator(new file_system_Folder(requireProject()).subitem([
@@ -6005,6 +6075,7 @@ const executeScaffold = async (request, owner)=>{
6005
6075
  'domain-service': ()=>scaffoldNewDomainService(owner),
6006
6076
  'application-service': ()=>scaffoldNewApplicationService(owner),
6007
6077
  'infrastructure-service': ()=>scaffoldNewInfrastructureService(owner),
6078
+ helper: ()=>scaffoldNewInfrastructureHelper(owner),
6008
6079
  'presentation-service': ()=>scaffoldNewPresentationService(owner),
6009
6080
  'use-case': ()=>scaffoldNewUseCase(owner),
6010
6081
  command: ()=>scaffoldNewCommand(owner),
@@ -6274,12 +6345,15 @@ const main = async ()=>{
6274
6345
  message: 'Infrastructure layer operation:',
6275
6346
  choices: [
6276
6347
  'New Service',
6348
+ 'New Helper',
6277
6349
  'New Implementation'
6278
6350
  ]
6279
6351
  });
6280
6352
  switch(operation){
6281
6353
  case 'New Implementation':
6282
6354
  return void await scaffoldNewImplementation(boundedContextFolder);
6355
+ case 'New Helper':
6356
+ return void await scaffoldNewInfrastructureHelper(boundedContextFolder);
6283
6357
  case 'New Service':
6284
6358
  return void await scaffoldNewInfrastructureService(boundedContextFolder);
6285
6359
  }
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { select as prompts_select } from "@inquirer/prompts";
3
3
  import { runCLI } from "./561.js";
4
4
  import { outdatedConfigMessage, ProjectRoot, ConfigFile, Folder } from "./780.js";
5
- import { scaffoldNewDomainService, scaffoldNewErrorUseCase, scaffoldNewAggregateUseCase, scaffoldNewQuery, scaffoldNewInfrastructureService, scaffoldNewHandlersRestEndpoint, savePendingChanges, moveBackendUnitUseCase, scaffoldNewCommand, scaffoldNewPresentationService, deleteBackendUnitUseCase, scaffoldNewApplicationService, scaffoldNewUseCase, scaffoldNewImplementation, wireDependency, scaffoldNewBoundedContextUseCase, scaffoldNewDomainObject, scaffoldNewApplicationPort } from "./287.js";
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) {
8
8
  console.log('No domain-first.project-structure.config.json found: run df-init first to initialize the project.');
@@ -131,12 +131,15 @@ const main = async ()=>{
131
131
  message: 'Infrastructure layer operation:',
132
132
  choices: [
133
133
  'New Service',
134
+ 'New Helper',
134
135
  'New Implementation'
135
136
  ]
136
137
  });
137
138
  switch(operation){
138
139
  case 'New Implementation':
139
140
  return void await scaffoldNewImplementation(boundedContextFolder);
141
+ case 'New Helper':
142
+ return void await scaffoldNewInfrastructureHelper(boundedContextFolder);
140
143
  case 'New Service':
141
144
  return void await scaffoldNewInfrastructureService(boundedContextFolder);
142
145
  }
package/dist/init.cjs CHANGED
@@ -263,18 +263,19 @@ class file_system_File extends FileSystemItem {
263
263
  });
264
264
  };
265
265
  addLineIfMissing = (newLine, separator = '\n')=>{
266
- const alreadyAdded = this.exists && this.data.split('\n').some((line)=>line.trim() === newLine.trim());
266
+ const normalized = (line)=>line.trim().replace(/;$/, '');
267
+ const alreadyAdded = this.exists && this.data.split('\n').some((line)=>normalized(line) === normalized(newLine));
267
268
  if (!alreadyAdded) this.addLine(newLine, separator);
268
269
  };
269
270
  }
270
- const implementationKinds = [
271
+ const implementation_options_schema_implementationKinds = [
271
272
  'repositories',
272
273
  'commands',
273
274
  'queries',
274
275
  'ports'
275
276
  ];
276
277
  const implementation_options_schema_implementationLabelSchema = external_zod_default().string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/);
277
- const implementationOptionsSchema = external_zod_default().partialRecord(external_zod_default()["enum"](implementationKinds), external_zod_default().object({
278
+ const implementationOptionsSchema = external_zod_default().partialRecord(external_zod_default()["enum"](implementation_options_schema_implementationKinds), external_zod_default().object({
278
279
  primary: external_zod_default().array(implementation_options_schema_implementationLabelSchema).default([]),
279
280
  test: external_zod_default().array(implementation_options_schema_implementationLabelSchema).default([])
280
281
  }).strict());
@@ -630,6 +631,16 @@ const save_pending_changes_savePendingChanges = async ()=>{
630
631
  writePendingChanges();
631
632
  return true;
632
633
  };
634
+ new Map([
635
+ [
636
+ 'prisma',
637
+ 'prisma-infrastructure-service'
638
+ ],
639
+ [
640
+ 'in-memory',
641
+ 'in-memory-db-infrastructure-service'
642
+ ]
643
+ ]);
633
644
  const wiring_relativeImport = (fromFile, toFile)=>{
634
645
  const relativePath = external_node_path_default().relative(external_node_path_default().dirname(fromFile), toFile).replace(/\.ts$/, '').split(external_node_path_default().sep).join('/');
635
646
  return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
@@ -345,7 +345,8 @@ class file_system_File extends FileSystemItem {
345
345
  });
346
346
  };
347
347
  addLineIfMissing = (newLine, separator = '\n')=>{
348
- const alreadyAdded = this.exists && this.data.split('\n').some((line)=>line.trim() === newLine.trim());
348
+ const normalized = (line)=>line.trim().replace(/;$/, '');
349
+ const alreadyAdded = this.exists && this.data.split('\n').some((line)=>normalized(line) === normalized(newLine));
349
350
  if (!alreadyAdded) this.addLine(newLine, separator);
350
351
  };
351
352
  }
@@ -639,7 +640,17 @@ const findWiredModules = (contextPath)=>{
639
640
  const moduleKindOf = (module)=>wiredModuleKind(module.kind);
640
641
  const layerRule = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && ('infrastructure' !== consumer.implementationsLayer || 'application' !== candidate.layer || 'application-ports' === candidate.kind);
641
642
  const wiring_implementationType = (consumer, implementation)=>consumer.branched ? external_node_path_default().basename(external_node_path_default().dirname(implementation.file)) : void 0;
642
- const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && `-${external_node_path_default().basename(candidate.typeFile, '.ts')}-`.includes(`-${implementation}-`);
643
+ const systemInfrastructureServices = new Map([
644
+ [
645
+ 'prisma',
646
+ 'prisma-infrastructure-service'
647
+ ],
648
+ [
649
+ 'in-memory',
650
+ 'in-memory-db-infrastructure-service'
651
+ ]
652
+ ]);
653
+ const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && external_node_path_default().basename(candidate.typeFile, '.ts') === systemInfrastructureServices.get(implementation);
643
654
  const canDependOn = (consumer, candidate, rules = defaultDependencyRules, implementation = consumer.implementations[0])=>{
644
655
  const crossContext = crossContextImportAllowed(consumer.wireFile, candidate.wireFile);
645
656
  if (void 0 !== crossContext) return crossContext && 'infrastructure' === consumer.implementationsLayer && 'application' === candidate.layer && !!implementation && true === crossContextImportAllowed(implementation.file, candidate.typeFile);
@@ -3175,6 +3186,12 @@ const scaffoldRequestSchema = external_zod_default().discriminatedUnion('operati
3175
3186
  ...named,
3176
3187
  ...agent_requests_wired
3177
3188
  }),
3189
+ agent_requests_operation('helper', {
3190
+ ...common,
3191
+ ...agent_requests_owner,
3192
+ name: agent_requests_nestedName.describe('Kebab-case, folders split by "/": mappers/social-network-type.'),
3193
+ implementationType: agent_requests_name.describe('A saved or system implementation type: a helper belongs to one.')
3194
+ }),
3178
3195
  agent_requests_operation('presentation-service', {
3179
3196
  ...named,
3180
3197
  ...agent_requests_wired
@@ -5413,6 +5430,58 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
5413
5430
  for (const implementation of unused)report(`${implementation.className} is no longer used in any environment.`);
5414
5431
  await wireNewImplementationDependencies(ownerFolder, wireFile, className, inMemoryRepositoryWiring(ownerFolder, unit, wireFile));
5415
5432
  };
5433
+ const helperImplementationTypes = ()=>[
5434
+ ...new Set(implementationKinds.flatMap((kind)=>[
5435
+ ...savedImplementations(kind, 'primary'),
5436
+ ...savedImplementations(kind, 'test'),
5437
+ ...systemImplementationChoices(kind).map(({ value })=>value)
5438
+ ]))
5439
+ ].filter((label)=>label !== crossContextImplementation);
5440
+ const validateName = (value)=>{
5441
+ const valid = NestedName.validate(value);
5442
+ if (true !== valid) return valid;
5443
+ const { folders, folderName } = new NestedName(value);
5444
+ return [
5445
+ ...folders,
5446
+ folderName
5447
+ ].every((part)=>kebabName.test(part)) ? true : 'Use lowercase kebab-case split by "/", e.g. mappers/social-network-type';
5448
+ };
5449
+ const scaffoldNewInfrastructureHelper = async (ownerFolder)=>{
5450
+ const types = helperImplementationTypes();
5451
+ if (!types.length) return void report('No implementation types yet: a helper belongs to one, so add an implementation first.');
5452
+ const name = new NestedName(await interaction_input({
5453
+ key: 'name',
5454
+ message: 'Name (folders split by "/"): ',
5455
+ validate: validateName
5456
+ }));
5457
+ const label = await interaction_select({
5458
+ key: 'implementationType',
5459
+ message: 'Implementation:',
5460
+ choices: types.map((value)=>({
5461
+ name: value,
5462
+ value
5463
+ }))
5464
+ });
5465
+ const fileName = name.folderName.startsWith(`${label}-`) ? name.folderName : `${label}-${name.folderName}`;
5466
+ const naming = new UnknownFormatNaming(fileName);
5467
+ const folder = ownerFolder.subitem([
5468
+ 'infrastructure',
5469
+ 'helpers',
5470
+ label,
5471
+ ...name.folders
5472
+ ]);
5473
+ folder.createFile(`${fileName}.ts`, `export const ${naming.variableName} = () => {}`);
5474
+ if (config_file_ConfigFile.backend.testingLibrary) folder.createFile(`${fileName}.spec.ts`, `
5475
+ import { describe, test, expect } from '${config_file_ConfigFile.backend.testingLibrary}'
5476
+ import { ${naming.variableName} } from './${fileName}'
5477
+
5478
+ describe('${naming.withSpaces}', () => {
5479
+ test('is defined', () => {
5480
+ expect(${naming.variableName}).toBeDefined()
5481
+ })
5482
+ })
5483
+ `.trim());
5484
+ };
5416
5485
  const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
5417
5486
  const name = await interaction_input({
5418
5487
  key: 'name',
@@ -5985,6 +6054,7 @@ const executeScaffold = async (request, owner)=>{
5985
6054
  ]).content.fileNames.includes(request.namespace)) throw new RequestError('TARGET_NOT_FOUND', `Unknown namespace: ${request.namespace}.`);
5986
6055
  if ('implementation' === request.operation && !findContracts(owner.path).length) throw new RequestError('TARGET_NOT_FOUND', 'No contracts in this context.');
5987
6056
  if (('move' === request.operation || 'delete' === request.operation) && !findBackendUnits(owner.path).length) throw new RequestError('TARGET_NOT_FOUND', 'No modules in this context.');
6057
+ if ('helper' === request.operation && !helperImplementationTypes().length) throw new RequestError('TARGET_NOT_FOUND', 'No implementation types yet: add an implementation first.');
5988
6058
  if ('wire-dependency' === request.operation && (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') || !findWiredModules(owner.path).length)) throw new RequestError('TARGET_NOT_FOUND', 'No wired modules in this context.');
5989
6059
  if ('endpoint' === request.operation) {
5990
6060
  if (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers-rest') || !findRestEndpointGenerator(new file_system_Folder(requireProject()).subitem([
@@ -6005,6 +6075,7 @@ const executeScaffold = async (request, owner)=>{
6005
6075
  'domain-service': ()=>scaffoldNewDomainService(owner),
6006
6076
  'application-service': ()=>scaffoldNewApplicationService(owner),
6007
6077
  'infrastructure-service': ()=>scaffoldNewInfrastructureService(owner),
6078
+ helper: ()=>scaffoldNewInfrastructureHelper(owner),
6008
6079
  'presentation-service': ()=>scaffoldNewPresentationService(owner),
6009
6080
  'use-case': ()=>scaffoldNewUseCase(owner),
6010
6081
  command: ()=>scaffoldNewCommand(owner),
package/dist/lint.cjs CHANGED
@@ -203,7 +203,8 @@ class file_system_File extends FileSystemItem {
203
203
  });
204
204
  };
205
205
  addLineIfMissing = (newLine, separator = '\n')=>{
206
- const alreadyAdded = this.exists && this.data.split('\n').some((line)=>line.trim() === newLine.trim());
206
+ const normalized = (line)=>line.trim().replace(/;$/, '');
207
+ const alreadyAdded = this.exists && this.data.split('\n').some((line)=>normalized(line) === normalized(newLine));
207
208
  if (!alreadyAdded) this.addLine(newLine, separator);
208
209
  };
209
210
  }
@@ -578,6 +579,16 @@ const findWiredModules = (contextPath)=>{
578
579
  };
579
580
  const moduleKindOf = (module)=>wiredModuleKind(module.kind);
580
581
  const wiring_layerRule = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && ('infrastructure' !== consumer.implementationsLayer || 'application' !== candidate.layer || 'application-ports' === candidate.kind);
582
+ new Map([
583
+ [
584
+ 'prisma',
585
+ 'prisma-infrastructure-service'
586
+ ],
587
+ [
588
+ 'in-memory',
589
+ 'in-memory-db-infrastructure-service'
590
+ ]
591
+ ]);
581
592
  const canDependOn = (consumer, candidate, rules = defaultDependencyRules, implementation = consumer.implementations[0])=>{
582
593
  const crossContext = context_dependencies_crossContextImportAllowed(consumer.wireFile, candidate.wireFile);
583
594
  if (void 0 !== crossContext) return crossContext && 'infrastructure' === consumer.implementationsLayer && 'application' === candidate.layer && !!implementation && true === context_dependencies_crossContextImportAllowed(implementation.file, candidate.typeFile);
@@ -735,6 +746,32 @@ const layerImportRules = {
735
746
  };
736
747
  const baseName = (file)=>external_node_path_default().basename(file).replace(/\.[^.]+$/, '');
737
748
  const isOwnContract = (file, target)=>baseName(file).endsWith(`-${baseName(target)}`);
749
+ const helperOf = ([layer, kind, ...rest])=>'infrastructure' === layer && 'helpers' === kind && rest.length ? {
750
+ label: rest.length > 1 ? rest[0] : void 0
751
+ } : void 0;
752
+ const implementationLabelOf = ([layer, kind, label, ...rest])=>'infrastructure' === layer && [
753
+ 'repositories',
754
+ 'commands',
755
+ 'queries',
756
+ 'application-adapters'
757
+ ].includes(kind) && rest.length ? label : void 0;
758
+ const helperImportRule = (from, to, typeOnly)=>{
759
+ const fromHelper = helperOf(from);
760
+ const toHelper = helperOf(to);
761
+ if (toHelper && 'wiring' === from[0]) return 'wiring imports an infrastructure helper:';
762
+ if (fromHelper && !toHelper) {
763
+ const toKind = fileModuleKind(to);
764
+ if ('infrastructure' === to[0] || toKind && !(typeOnly && [
765
+ 'queries',
766
+ 'commands',
767
+ 'application-ports'
768
+ ].includes(toKind))) return 'an infrastructure helper imports a module (only domain models, other helpers and `import type` of query, command and port contracts):';
769
+ }
770
+ if (toHelper?.label) {
771
+ const label = fromHelper ? fromHelper.label : implementationLabelOf(from);
772
+ if ((fromHelper || label) && label !== toHelper.label) return 'imports a helper of another implementation:';
773
+ }
774
+ };
738
775
  const importViolations = (projectRoot, rootFolder, rules)=>{
739
776
  const root = external_node_path_default().resolve(projectRoot, rootFolder);
740
777
  const contextsFolder = external_node_path_default().join(root, 'bounded-contexts');
@@ -782,6 +819,14 @@ const importViolations = (projectRoot, rootFolder, rules)=>{
782
819
  for (const file of files){
783
820
  const source = external_node_fs_default().readFileSync(file, 'utf8');
784
821
  const from = locate(file);
822
+ const helper = from && helperOf(from.segments);
823
+ if (helper && !helper.label) violations.push({
824
+ check: 'layers',
825
+ rule: `[${from.owner}] a helper outside the folder of its implementation (code shared by implementations is an infrastructure service):`,
826
+ file,
827
+ line: 1,
828
+ text: external_node_path_default().basename(file)
829
+ });
785
830
  const ownContext = inside(contextsFolder, file)?.[0];
786
831
  const directWiring = ownContext && from?.segments[0] === 'wiring' && readWiredModule(file, external_node_path_default().join(contextsFolder, ownContext))?.implementations.some((implementation)=>isCrossContextImplementation(implementation.file));
787
832
  const report = (check, rule, imported)=>violations.push({
@@ -820,6 +865,8 @@ const importViolations = (projectRoot, rootFolder, rules)=>{
820
865
  if (!from || !to) continue;
821
866
  if (crossContextAllowed) continue;
822
867
  if (isSpec(file)) continue;
868
+ const helperRule = helperImportRule(from.segments, to.segments, imported.typeOnly);
869
+ if (helperRule) report('layers', `[${from.owner}] ${helperRule}`, imported);
823
870
  const fromKind = fileModuleKind(from.segments);
824
871
  const toKind = fileModuleKind(to.segments);
825
872
  if (fromKind && toKind) {
package/dist/react.cjs CHANGED
@@ -346,7 +346,8 @@ class file_system_File extends FileSystemItem {
346
346
  });
347
347
  };
348
348
  addLineIfMissing = (newLine, separator = '\n')=>{
349
- const alreadyAdded = this.exists && this.data.split('\n').some((line)=>line.trim() === newLine.trim());
349
+ const normalized = (line)=>line.trim().replace(/;$/, '');
350
+ const alreadyAdded = this.exists && this.data.split('\n').some((line)=>normalized(line) === normalized(newLine));
350
351
  if (!alreadyAdded) this.addLine(newLine, separator);
351
352
  };
352
353
  }
@@ -640,7 +641,17 @@ const findWiredModules = (contextPath)=>{
640
641
  const moduleKindOf = (module)=>wiredModuleKind(module.kind);
641
642
  const layerRule = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && ('infrastructure' !== consumer.implementationsLayer || 'application' !== candidate.layer || 'application-ports' === candidate.kind);
642
643
  const wiring_implementationType = (consumer, implementation)=>consumer.branched ? external_node_path_default().basename(external_node_path_default().dirname(implementation.file)) : void 0;
643
- const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && `-${external_node_path_default().basename(candidate.typeFile, '.ts')}-`.includes(`-${implementation}-`);
644
+ const systemInfrastructureServices = new Map([
645
+ [
646
+ 'prisma',
647
+ 'prisma-infrastructure-service'
648
+ ],
649
+ [
650
+ 'in-memory',
651
+ 'in-memory-db-infrastructure-service'
652
+ ]
653
+ ]);
654
+ const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && external_node_path_default().basename(candidate.typeFile, '.ts') === systemInfrastructureServices.get(implementation);
644
655
  const canDependOn = (consumer, candidate, rules = defaultDependencyRules, implementation = consumer.implementations[0])=>{
645
656
  const crossContext = crossContextImportAllowed(consumer.wireFile, candidate.wireFile);
646
657
  if (void 0 !== crossContext) return crossContext && 'infrastructure' === consumer.implementationsLayer && 'application' === candidate.layer && !!implementation && true === crossContextImportAllowed(implementation.file, candidate.typeFile);
@@ -3175,6 +3186,12 @@ const scaffoldRequestSchema = external_zod_default().discriminatedUnion('operati
3175
3186
  ...named,
3176
3187
  ...agent_requests_wired
3177
3188
  }),
3189
+ agent_requests_operation('helper', {
3190
+ ...common,
3191
+ ...agent_requests_owner,
3192
+ name: agent_requests_nestedName.describe('Kebab-case, folders split by "/": mappers/social-network-type.'),
3193
+ implementationType: agent_requests_name.describe('A saved or system implementation type: a helper belongs to one.')
3194
+ }),
3178
3195
  agent_requests_operation('presentation-service', {
3179
3196
  ...named,
3180
3197
  ...agent_requests_wired
@@ -5413,6 +5430,58 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
5413
5430
  for (const implementation of unused)report(`${implementation.className} is no longer used in any environment.`);
5414
5431
  await wireNewImplementationDependencies(ownerFolder, wireFile, className, inMemoryRepositoryWiring(ownerFolder, unit, wireFile));
5415
5432
  };
5433
+ const helperImplementationTypes = ()=>[
5434
+ ...new Set(implementationKinds.flatMap((kind)=>[
5435
+ ...savedImplementations(kind, 'primary'),
5436
+ ...savedImplementations(kind, 'test'),
5437
+ ...systemImplementationChoices(kind).map(({ value })=>value)
5438
+ ]))
5439
+ ].filter((label)=>label !== crossContextImplementation);
5440
+ const validateName = (value)=>{
5441
+ const valid = NestedName.validate(value);
5442
+ if (true !== valid) return valid;
5443
+ const { folders, folderName } = new NestedName(value);
5444
+ return [
5445
+ ...folders,
5446
+ folderName
5447
+ ].every((part)=>kebabName.test(part)) ? true : 'Use lowercase kebab-case split by "/", e.g. mappers/social-network-type';
5448
+ };
5449
+ const scaffoldNewInfrastructureHelper = async (ownerFolder)=>{
5450
+ const types = helperImplementationTypes();
5451
+ if (!types.length) return void report('No implementation types yet: a helper belongs to one, so add an implementation first.');
5452
+ const name = new NestedName(await interaction_input({
5453
+ key: 'name',
5454
+ message: 'Name (folders split by "/"): ',
5455
+ validate: validateName
5456
+ }));
5457
+ const label = await interaction_select({
5458
+ key: 'implementationType',
5459
+ message: 'Implementation:',
5460
+ choices: types.map((value)=>({
5461
+ name: value,
5462
+ value
5463
+ }))
5464
+ });
5465
+ const fileName = name.folderName.startsWith(`${label}-`) ? name.folderName : `${label}-${name.folderName}`;
5466
+ const naming = new UnknownFormatNaming(fileName);
5467
+ const folder = ownerFolder.subitem([
5468
+ 'infrastructure',
5469
+ 'helpers',
5470
+ label,
5471
+ ...name.folders
5472
+ ]);
5473
+ folder.createFile(`${fileName}.ts`, `export const ${naming.variableName} = () => {}`);
5474
+ if (config_file_ConfigFile.backend.testingLibrary) folder.createFile(`${fileName}.spec.ts`, `
5475
+ import { describe, test, expect } from '${config_file_ConfigFile.backend.testingLibrary}'
5476
+ import { ${naming.variableName} } from './${fileName}'
5477
+
5478
+ describe('${naming.withSpaces}', () => {
5479
+ test('is defined', () => {
5480
+ expect(${naming.variableName}).toBeDefined()
5481
+ })
5482
+ })
5483
+ `.trim());
5484
+ };
5416
5485
  const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
5417
5486
  const name = await interaction_input({
5418
5487
  key: 'name',
@@ -5985,6 +6054,7 @@ const executeScaffold = async (request, owner)=>{
5985
6054
  ]).content.fileNames.includes(request.namespace)) throw new RequestError('TARGET_NOT_FOUND', `Unknown namespace: ${request.namespace}.`);
5986
6055
  if ('implementation' === request.operation && !findContracts(owner.path).length) throw new RequestError('TARGET_NOT_FOUND', 'No contracts in this context.');
5987
6056
  if (('move' === request.operation || 'delete' === request.operation) && !findBackendUnits(owner.path).length) throw new RequestError('TARGET_NOT_FOUND', 'No modules in this context.');
6057
+ if ('helper' === request.operation && !helperImplementationTypes().length) throw new RequestError('TARGET_NOT_FOUND', 'No implementation types yet: add an implementation first.');
5988
6058
  if ('wire-dependency' === request.operation && (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') || !findWiredModules(owner.path).length)) throw new RequestError('TARGET_NOT_FOUND', 'No wired modules in this context.');
5989
6059
  if ('endpoint' === request.operation) {
5990
6060
  if (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers-rest') || !findRestEndpointGenerator(new file_system_Folder(requireProject()).subitem([
@@ -6005,6 +6075,7 @@ const executeScaffold = async (request, owner)=>{
6005
6075
  'domain-service': ()=>scaffoldNewDomainService(owner),
6006
6076
  'application-service': ()=>scaffoldNewApplicationService(owner),
6007
6077
  'infrastructure-service': ()=>scaffoldNewInfrastructureService(owner),
6078
+ helper: ()=>scaffoldNewInfrastructureHelper(owner),
6008
6079
  'presentation-service': ()=>scaffoldNewPresentationService(owner),
6009
6080
  'use-case': ()=>scaffoldNewUseCase(owner),
6010
6081
  command: ()=>scaffoldNewCommand(owner),
package/dist/upgrade.cjs CHANGED
@@ -214,7 +214,8 @@ class File extends FileSystemItem {
214
214
  });
215
215
  };
216
216
  addLineIfMissing = (newLine, separator = '\n')=>{
217
- const alreadyAdded = this.exists && this.data.split('\n').some((line)=>line.trim() === newLine.trim());
217
+ const normalized = (line)=>line.trim().replace(/;$/, '');
218
+ const alreadyAdded = this.exists && this.data.split('\n').some((line)=>normalized(line) === normalized(newLine));
218
219
  if (!alreadyAdded) this.addLine(newLine, separator);
219
220
  };
220
221
  }
@@ -612,17 +613,18 @@ const rootMoves = (contextFolder)=>{
612
613
  };
613
614
  };
614
615
  const exportPattern = /^export\s+\*\s+from\s+(['"])([^'"]+)\1;?\s*$/;
615
- const regroupExports = (file, isRootWire, groupLine)=>{
616
- if (!file.exists) return [];
617
- const lines = file.data.split('\n');
616
+ const exportedSpecifier = (line)=>line.trim().match(exportPattern)?.[2];
617
+ const regroupExports = (file, isRootWire, groupSpecifier)=>{
618
+ const lines = file.exists ? file.data.split('\n') : [];
618
619
  const rootWires = lines.filter((line)=>{
619
- const specifier = line.trim().match(exportPattern)?.[2];
620
+ const specifier = exportedSpecifier(line);
620
621
  return !!specifier && isRootWire(specifier);
621
622
  });
622
- if (!rootWires.length) return [];
623
- const first = lines.indexOf(rootWires[0]);
623
+ const first = rootWires.length ? lines.indexOf(rootWires[0]) : lines.length - [
624
+ ...lines
625
+ ].reverse().findIndex((line)=>!!line.trim());
624
626
  const kept = lines.filter((line)=>!rootWires.includes(line));
625
- if (!kept.some((line)=>line.trim() === groupLine)) kept.splice(first, 0, groupLine);
627
+ if (!kept.some((line)=>exportedSpecifier(line) === groupSpecifier)) kept.splice(first, 0, `export * from '${groupSpecifier}'`);
626
628
  file.update(kept.join('\n'));
627
629
  return rootWires;
628
630
  };
@@ -639,8 +641,8 @@ const restRootControllerStep = {
639
641
  return [
640
642
  ...files.map(([from, to])=>`${upgrade_rest_root_relative(from)} → ${upgrade_rest_root_relative(to)}`),
641
643
  ...wired ? [
642
- `${upgrade_rest_root_relative(external_node_path_default().join(wiring, 'index.ts'))}: one line for ./(root)`,
643
- `${upgrade_rest_root_relative(external_node_path_default().join(new ProjectRoot().path, rootFolderOf(context), 'presentation', 'rest', 'wires.ts'))}: the ${name} context-root lines → one line for (root)`
644
+ `${upgrade_rest_root_relative(external_node_path_default().join(wiring, 'index.ts'))}: the context-root lines → one line for ./(root)`,
645
+ `${upgrade_rest_root_relative(external_node_path_default().join(new ProjectRoot().path, rootFolderOf(context), 'presentation', 'rest', 'wires.ts'))}: the ${name} context-root lines → one line for (root), added if missing`
644
646
  ] : [],
645
647
  'Imports of the moved files are rewritten'
646
648
  ];
@@ -681,10 +683,16 @@ const restRootControllerStep = {
681
683
  for (const contextFolder of contexts){
682
684
  const name = external_node_path_default().basename(contextFolder);
683
685
  const { wiring } = restFolders(contextFolder);
684
- const rootWires = regroupExports(new File(external_node_path_default().join(wiring, 'index.ts')), (specifier)=>specifier.startsWith("./(root)/"), "export * from './(root)'");
685
- if (rootWires.length) new File(external_node_path_default().join(wiring, "(root)", 'index.ts')).data = rootWires.map((line)=>line.replace("./(root)/", './')).join('\n');
686
+ const movedWires = legacyRootEndpoints(contextFolder).wireFiles;
687
+ if (!movedWires.length) continue;
688
+ const listed = regroupExports(new File(external_node_path_default().join(wiring, 'index.ts')), (specifier)=>specifier.startsWith("./(root)/"), "./(root)").map((line)=>line.replace("./(root)/", './'));
689
+ const unlisted = movedWires.map((file)=>`./${external_node_path_default().basename(file, '.ts')}`).filter((specifier)=>!listed.some((line)=>exportedSpecifier(line) === specifier)).map((specifier)=>`export * from '${specifier}'`);
690
+ new File(external_node_path_default().join(wiring, "(root)", 'index.ts')).data = [
691
+ ...listed,
692
+ ...unlisted
693
+ ].join('\n');
686
694
  const wiringPath = `bounded-contexts/${name}/wiring/presentation/rest/(root)`;
687
- regroupExports(sharedWires, (specifier)=>specifier.includes(`${wiringPath}/`), `export * from '../../${wiringPath}'`);
695
+ regroupExports(sharedWires, (specifier)=>specifier.includes(`${wiringPath}/`), `../../${wiringPath}`);
688
696
  }
689
697
  }
690
698
  };
package/dist/upgrade.js CHANGED
@@ -46,17 +46,18 @@ const rootMoves = (contextFolder)=>{
46
46
  };
47
47
  };
48
48
  const exportPattern = /^export\s+\*\s+from\s+(['"])([^'"]+)\1;?\s*$/;
49
- const regroupExports = (file, isRootWire, groupLine)=>{
50
- if (!file.exists) return [];
51
- const lines = file.data.split('\n');
49
+ const exportedSpecifier = (line)=>line.trim().match(exportPattern)?.[2];
50
+ const regroupExports = (file, isRootWire, groupSpecifier)=>{
51
+ const lines = file.exists ? file.data.split('\n') : [];
52
52
  const rootWires = lines.filter((line)=>{
53
- const specifier = line.trim().match(exportPattern)?.[2];
53
+ const specifier = exportedSpecifier(line);
54
54
  return !!specifier && isRootWire(specifier);
55
55
  });
56
- if (!rootWires.length) return [];
57
- const first = lines.indexOf(rootWires[0]);
56
+ const first = rootWires.length ? lines.indexOf(rootWires[0]) : lines.length - [
57
+ ...lines
58
+ ].reverse().findIndex((line)=>!!line.trim());
58
59
  const kept = lines.filter((line)=>!rootWires.includes(line));
59
- if (!kept.some((line)=>line.trim() === groupLine)) kept.splice(first, 0, groupLine);
60
+ if (!kept.some((line)=>exportedSpecifier(line) === groupSpecifier)) kept.splice(first, 0, `export * from '${groupSpecifier}'`);
60
61
  file.update(kept.join('\n'));
61
62
  return rootWires;
62
63
  };
@@ -73,8 +74,8 @@ const restRootControllerStep = {
73
74
  return [
74
75
  ...files.map(([from, to])=>`${relative(from)} → ${relative(to)}`),
75
76
  ...wired ? [
76
- `${relative(node_path.join(wiring, 'index.ts'))}: one line for ./(root)`,
77
- `${relative(node_path.join(new ProjectRoot().path, rootFolderOf(context), 'presentation', 'rest', 'wires.ts'))}: the ${name} context-root lines → one line for (root)`
77
+ `${relative(node_path.join(wiring, 'index.ts'))}: the context-root lines → one line for ./(root)`,
78
+ `${relative(node_path.join(new ProjectRoot().path, rootFolderOf(context), 'presentation', 'rest', 'wires.ts'))}: the ${name} context-root lines → one line for (root), added if missing`
78
79
  ] : [],
79
80
  'Imports of the moved files are rewritten'
80
81
  ];
@@ -115,10 +116,16 @@ const restRootControllerStep = {
115
116
  for (const contextFolder of contexts){
116
117
  const name = node_path.basename(contextFolder);
117
118
  const { wiring } = restFolders(contextFolder);
118
- const rootWires = regroupExports(new File(node_path.join(wiring, 'index.ts')), (specifier)=>specifier.startsWith("./(root)/"), "export * from './(root)'");
119
- if (rootWires.length) new File(node_path.join(wiring, "(root)", 'index.ts')).data = rootWires.map((line)=>line.replace("./(root)/", './')).join('\n');
119
+ const movedWires = legacyRootEndpoints(contextFolder).wireFiles;
120
+ if (!movedWires.length) continue;
121
+ const listed = regroupExports(new File(node_path.join(wiring, 'index.ts')), (specifier)=>specifier.startsWith("./(root)/"), "./(root)").map((line)=>line.replace("./(root)/", './'));
122
+ const unlisted = movedWires.map((file)=>`./${node_path.basename(file, '.ts')}`).filter((specifier)=>!listed.some((line)=>exportedSpecifier(line) === specifier)).map((specifier)=>`export * from '${specifier}'`);
123
+ new File(node_path.join(wiring, "(root)", 'index.ts')).data = [
124
+ ...listed,
125
+ ...unlisted
126
+ ].join('\n');
120
127
  const wiringPath = `bounded-contexts/${name}/wiring/presentation/rest/(root)`;
121
- regroupExports(sharedWires, (specifier)=>specifier.includes(`${wiringPath}/`), `export * from '../../${wiringPath}'`);
128
+ regroupExports(sharedWires, (specifier)=>specifier.includes(`${wiringPath}/`), `../../${wiringPath}`);
122
129
  }
123
130
  }
124
131
  };