@domain-first/project-structure 8.6.1 → 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 (50) 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/947.js +11 -1
  7. package/dist/agent-cli.d.ts +9 -2
  8. package/dist/agent-principles.cjs +116 -0
  9. package/dist/agent-principles.d.ts +9 -0
  10. package/dist/agent-principles.js +64 -0
  11. package/dist/agent-principles.spec.d.ts +1 -0
  12. package/dist/agent-requests.d.ts +16 -2
  13. package/dist/graph.cjs +10 -0
  14. package/dist/index.cjs +74 -1
  15. package/dist/index.js +4 -1
  16. package/dist/init.cjs +12 -2
  17. package/dist/integration.cjs +71 -1
  18. package/dist/lint.cjs +46 -0
  19. package/dist/react.cjs +71 -1
  20. package/dist/use-cases/add-integration.d.ts +1 -1
  21. package/dist/use-cases/index.d.ts +1 -0
  22. package/dist/use-cases/scaffold-new-infrastructure-helper.d.ts +7 -0
  23. package/dist/wiring.d.ts +2 -2
  24. package/package.json +3 -2
  25. package/principles/df-principles.md +33 -0
  26. package/skills/df-ps-implement/SKILL.md +26 -1
  27. package/skills/df-ps-plan-feature/SKILL.md +22 -18
  28. package/skills/df-ps-react/SKILL.md +2 -9
  29. package/skills/df-ps-react/references/generators.md +9 -9
  30. package/skills/df-ps-scaffold/SKILL.md +19 -125
  31. package/skills/df-ps-scaffold/references/agent-mode.md +2 -2
  32. package/skills/df-ps-scaffold/references/agent-operations.md +1 -0
  33. package/skills/df-ps-scaffold/references/choosing-components.md +65 -49
  34. package/skills/df-ps-scaffold/references/generators.md +28 -5
  35. package/skills/df-ps-scaffold/references/units/aggregate.md +1 -3
  36. package/skills/df-ps-scaffold/references/units/bounded-context.md +1 -1
  37. package/skills/df-ps-scaffold/references/units/command-query.md +4 -6
  38. package/skills/df-ps-scaffold/references/units/delete.md +0 -2
  39. package/skills/df-ps-scaffold/references/units/endpoint.md +1 -4
  40. package/skills/df-ps-scaffold/references/units/entity-value-object.md +0 -4
  41. package/skills/df-ps-scaffold/references/units/errors.md +0 -4
  42. package/skills/df-ps-scaffold/references/units/helper.md +30 -0
  43. package/skills/df-ps-scaffold/references/units/implementation.md +0 -4
  44. package/skills/df-ps-scaffold/references/units/move-or-rename.md +0 -4
  45. package/skills/df-ps-scaffold/references/units/port.md +2 -5
  46. package/skills/df-ps-scaffold/references/units/services.md +2 -4
  47. package/skills/df-ps-scaffold/references/units/use-case.md +1 -2
  48. package/skills/df-ps-scaffold/references/units/wire-dependency.md +0 -2
  49. package/skills/df-ps-scaffold/references/work-plan.md +73 -0
  50. package/skills/df-ps-scaffold/scripts/drive.mjs +0 -252
package/dist/index.cjs CHANGED
@@ -641,7 +641,17 @@ const findWiredModules = (contextPath)=>{
641
641
  const moduleKindOf = (module)=>wiredModuleKind(module.kind);
642
642
  const layerRule = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && ('infrastructure' !== consumer.implementationsLayer || 'application' !== candidate.layer || 'application-ports' === candidate.kind);
643
643
  const wiring_implementationType = (consumer, implementation)=>consumer.branched ? external_node_path_default().basename(external_node_path_default().dirname(implementation.file)) : void 0;
644
- 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);
645
655
  const canDependOn = (consumer, candidate, rules = defaultDependencyRules, implementation = consumer.implementations[0])=>{
646
656
  const crossContext = crossContextImportAllowed(consumer.wireFile, candidate.wireFile);
647
657
  if (void 0 !== crossContext) return crossContext && 'infrastructure' === consumer.implementationsLayer && 'application' === candidate.layer && !!implementation && true === crossContextImportAllowed(implementation.file, candidate.typeFile);
@@ -3176,6 +3186,12 @@ const scaffoldRequestSchema = external_zod_default().discriminatedUnion('operati
3176
3186
  ...named,
3177
3187
  ...agent_requests_wired
3178
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
+ }),
3179
3195
  agent_requests_operation('presentation-service', {
3180
3196
  ...named,
3181
3197
  ...agent_requests_wired
@@ -5414,6 +5430,58 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
5414
5430
  for (const implementation of unused)report(`${implementation.className} is no longer used in any environment.`);
5415
5431
  await wireNewImplementationDependencies(ownerFolder, wireFile, className, inMemoryRepositoryWiring(ownerFolder, unit, wireFile));
5416
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
+ };
5417
5485
  const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
5418
5486
  const name = await interaction_input({
5419
5487
  key: 'name',
@@ -5986,6 +6054,7 @@ const executeScaffold = async (request, owner)=>{
5986
6054
  ]).content.fileNames.includes(request.namespace)) throw new RequestError('TARGET_NOT_FOUND', `Unknown namespace: ${request.namespace}.`);
5987
6055
  if ('implementation' === request.operation && !findContracts(owner.path).length) throw new RequestError('TARGET_NOT_FOUND', 'No contracts in this context.');
5988
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.');
5989
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.');
5990
6059
  if ('endpoint' === request.operation) {
5991
6060
  if (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers-rest') || !findRestEndpointGenerator(new file_system_Folder(requireProject()).subitem([
@@ -6006,6 +6075,7 @@ const executeScaffold = async (request, owner)=>{
6006
6075
  'domain-service': ()=>scaffoldNewDomainService(owner),
6007
6076
  'application-service': ()=>scaffoldNewApplicationService(owner),
6008
6077
  'infrastructure-service': ()=>scaffoldNewInfrastructureService(owner),
6078
+ helper: ()=>scaffoldNewInfrastructureHelper(owner),
6009
6079
  'presentation-service': ()=>scaffoldNewPresentationService(owner),
6010
6080
  'use-case': ()=>scaffoldNewUseCase(owner),
6011
6081
  command: ()=>scaffoldNewCommand(owner),
@@ -6275,12 +6345,15 @@ const main = async ()=>{
6275
6345
  message: 'Infrastructure layer operation:',
6276
6346
  choices: [
6277
6347
  'New Service',
6348
+ 'New Helper',
6278
6349
  'New Implementation'
6279
6350
  ]
6280
6351
  });
6281
6352
  switch(operation){
6282
6353
  case 'New Implementation':
6283
6354
  return void await scaffoldNewImplementation(boundedContextFolder);
6355
+ case 'New Helper':
6356
+ return void await scaffoldNewInfrastructureHelper(boundedContextFolder);
6284
6357
  case 'New Service':
6285
6358
  return void await scaffoldNewInfrastructureService(boundedContextFolder);
6286
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
@@ -268,14 +268,14 @@ class file_system_File extends FileSystemItem {
268
268
  if (!alreadyAdded) this.addLine(newLine, separator);
269
269
  };
270
270
  }
271
- const implementationKinds = [
271
+ const implementation_options_schema_implementationKinds = [
272
272
  'repositories',
273
273
  'commands',
274
274
  'queries',
275
275
  'ports'
276
276
  ];
277
277
  const implementation_options_schema_implementationLabelSchema = external_zod_default().string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/);
278
- 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({
279
279
  primary: external_zod_default().array(implementation_options_schema_implementationLabelSchema).default([]),
280
280
  test: external_zod_default().array(implementation_options_schema_implementationLabelSchema).default([])
281
281
  }).strict());
@@ -631,6 +631,16 @@ const save_pending_changes_savePendingChanges = async ()=>{
631
631
  writePendingChanges();
632
632
  return true;
633
633
  };
634
+ new Map([
635
+ [
636
+ 'prisma',
637
+ 'prisma-infrastructure-service'
638
+ ],
639
+ [
640
+ 'in-memory',
641
+ 'in-memory-db-infrastructure-service'
642
+ ]
643
+ ]);
634
644
  const wiring_relativeImport = (fromFile, toFile)=>{
635
645
  const relativePath = external_node_path_default().relative(external_node_path_default().dirname(fromFile), toFile).replace(/\.ts$/, '').split(external_node_path_default().sep).join('/');
636
646
  return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
@@ -640,7 +640,17 @@ const findWiredModules = (contextPath)=>{
640
640
  const moduleKindOf = (module)=>wiredModuleKind(module.kind);
641
641
  const layerRule = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && ('infrastructure' !== consumer.implementationsLayer || 'application' !== candidate.layer || 'application-ports' === candidate.kind);
642
642
  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}-`);
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);
644
654
  const canDependOn = (consumer, candidate, rules = defaultDependencyRules, implementation = consumer.implementations[0])=>{
645
655
  const crossContext = crossContextImportAllowed(consumer.wireFile, candidate.wireFile);
646
656
  if (void 0 !== crossContext) return crossContext && 'infrastructure' === consumer.implementationsLayer && 'application' === candidate.layer && !!implementation && true === crossContextImportAllowed(implementation.file, candidate.typeFile);
@@ -3176,6 +3186,12 @@ const scaffoldRequestSchema = external_zod_default().discriminatedUnion('operati
3176
3186
  ...named,
3177
3187
  ...agent_requests_wired
3178
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
+ }),
3179
3195
  agent_requests_operation('presentation-service', {
3180
3196
  ...named,
3181
3197
  ...agent_requests_wired
@@ -5414,6 +5430,58 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
5414
5430
  for (const implementation of unused)report(`${implementation.className} is no longer used in any environment.`);
5415
5431
  await wireNewImplementationDependencies(ownerFolder, wireFile, className, inMemoryRepositoryWiring(ownerFolder, unit, wireFile));
5416
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
+ };
5417
5485
  const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
5418
5486
  const name = await interaction_input({
5419
5487
  key: 'name',
@@ -5986,6 +6054,7 @@ const executeScaffold = async (request, owner)=>{
5986
6054
  ]).content.fileNames.includes(request.namespace)) throw new RequestError('TARGET_NOT_FOUND', `Unknown namespace: ${request.namespace}.`);
5987
6055
  if ('implementation' === request.operation && !findContracts(owner.path).length) throw new RequestError('TARGET_NOT_FOUND', 'No contracts in this context.');
5988
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.');
5989
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.');
5990
6059
  if ('endpoint' === request.operation) {
5991
6060
  if (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers-rest') || !findRestEndpointGenerator(new file_system_Folder(requireProject()).subitem([
@@ -6006,6 +6075,7 @@ const executeScaffold = async (request, owner)=>{
6006
6075
  'domain-service': ()=>scaffoldNewDomainService(owner),
6007
6076
  'application-service': ()=>scaffoldNewApplicationService(owner),
6008
6077
  'infrastructure-service': ()=>scaffoldNewInfrastructureService(owner),
6078
+ helper: ()=>scaffoldNewInfrastructureHelper(owner),
6009
6079
  'presentation-service': ()=>scaffoldNewPresentationService(owner),
6010
6080
  'use-case': ()=>scaffoldNewUseCase(owner),
6011
6081
  command: ()=>scaffoldNewCommand(owner),
package/dist/lint.cjs CHANGED
@@ -579,6 +579,16 @@ const findWiredModules = (contextPath)=>{
579
579
  };
580
580
  const moduleKindOf = (module)=>wiredModuleKind(module.kind);
581
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
+ ]);
582
592
  const canDependOn = (consumer, candidate, rules = defaultDependencyRules, implementation = consumer.implementations[0])=>{
583
593
  const crossContext = context_dependencies_crossContextImportAllowed(consumer.wireFile, candidate.wireFile);
584
594
  if (void 0 !== crossContext) return crossContext && 'infrastructure' === consumer.implementationsLayer && 'application' === candidate.layer && !!implementation && true === context_dependencies_crossContextImportAllowed(implementation.file, candidate.typeFile);
@@ -736,6 +746,32 @@ const layerImportRules = {
736
746
  };
737
747
  const baseName = (file)=>external_node_path_default().basename(file).replace(/\.[^.]+$/, '');
738
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
+ };
739
775
  const importViolations = (projectRoot, rootFolder, rules)=>{
740
776
  const root = external_node_path_default().resolve(projectRoot, rootFolder);
741
777
  const contextsFolder = external_node_path_default().join(root, 'bounded-contexts');
@@ -783,6 +819,14 @@ const importViolations = (projectRoot, rootFolder, rules)=>{
783
819
  for (const file of files){
784
820
  const source = external_node_fs_default().readFileSync(file, 'utf8');
785
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
+ });
786
830
  const ownContext = inside(contextsFolder, file)?.[0];
787
831
  const directWiring = ownContext && from?.segments[0] === 'wiring' && readWiredModule(file, external_node_path_default().join(contextsFolder, ownContext))?.implementations.some((implementation)=>isCrossContextImplementation(implementation.file));
788
832
  const report = (check, rule, imported)=>violations.push({
@@ -821,6 +865,8 @@ const importViolations = (projectRoot, rootFolder, rules)=>{
821
865
  if (!from || !to) continue;
822
866
  if (crossContextAllowed) continue;
823
867
  if (isSpec(file)) continue;
868
+ const helperRule = helperImportRule(from.segments, to.segments, imported.typeOnly);
869
+ if (helperRule) report('layers', `[${from.owner}] ${helperRule}`, imported);
824
870
  const fromKind = fileModuleKind(from.segments);
825
871
  const toKind = fileModuleKind(to.segments);
826
872
  if (fromKind && toKind) {
package/dist/react.cjs CHANGED
@@ -641,7 +641,17 @@ const findWiredModules = (contextPath)=>{
641
641
  const moduleKindOf = (module)=>wiredModuleKind(module.kind);
642
642
  const layerRule = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && ('infrastructure' !== consumer.implementationsLayer || 'application' !== candidate.layer || 'application-ports' === candidate.kind);
643
643
  const wiring_implementationType = (consumer, implementation)=>consumer.branched ? external_node_path_default().basename(external_node_path_default().dirname(implementation.file)) : void 0;
644
- 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);
645
655
  const canDependOn = (consumer, candidate, rules = defaultDependencyRules, implementation = consumer.implementations[0])=>{
646
656
  const crossContext = crossContextImportAllowed(consumer.wireFile, candidate.wireFile);
647
657
  if (void 0 !== crossContext) return crossContext && 'infrastructure' === consumer.implementationsLayer && 'application' === candidate.layer && !!implementation && true === crossContextImportAllowed(implementation.file, candidate.typeFile);
@@ -3176,6 +3186,12 @@ const scaffoldRequestSchema = external_zod_default().discriminatedUnion('operati
3176
3186
  ...named,
3177
3187
  ...agent_requests_wired
3178
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
+ }),
3179
3195
  agent_requests_operation('presentation-service', {
3180
3196
  ...named,
3181
3197
  ...agent_requests_wired
@@ -5414,6 +5430,58 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
5414
5430
  for (const implementation of unused)report(`${implementation.className} is no longer used in any environment.`);
5415
5431
  await wireNewImplementationDependencies(ownerFolder, wireFile, className, inMemoryRepositoryWiring(ownerFolder, unit, wireFile));
5416
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
+ };
5417
5485
  const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
5418
5486
  const name = await interaction_input({
5419
5487
  key: 'name',
@@ -5986,6 +6054,7 @@ const executeScaffold = async (request, owner)=>{
5986
6054
  ]).content.fileNames.includes(request.namespace)) throw new RequestError('TARGET_NOT_FOUND', `Unknown namespace: ${request.namespace}.`);
5987
6055
  if ('implementation' === request.operation && !findContracts(owner.path).length) throw new RequestError('TARGET_NOT_FOUND', 'No contracts in this context.');
5988
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.');
5989
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.');
5990
6059
  if ('endpoint' === request.operation) {
5991
6060
  if (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers-rest') || !findRestEndpointGenerator(new file_system_Folder(requireProject()).subitem([
@@ -6006,6 +6075,7 @@ const executeScaffold = async (request, owner)=>{
6006
6075
  'domain-service': ()=>scaffoldNewDomainService(owner),
6007
6076
  'application-service': ()=>scaffoldNewApplicationService(owner),
6008
6077
  'infrastructure-service': ()=>scaffoldNewInfrastructureService(owner),
6078
+ helper: ()=>scaffoldNewInfrastructureHelper(owner),
6009
6079
  'presentation-service': ()=>scaffoldNewPresentationService(owner),
6010
6080
  'use-case': ()=>scaffoldNewUseCase(owner),
6011
6081
  command: ()=>scaffoldNewCommand(owner),
@@ -9,7 +9,7 @@ export declare const addIntegration: ({ save }?: {
9
9
  save?: boolean;
10
10
  }) => Promise<string[]>;
11
11
  export declare const integrationDescriptions: () => {
12
- id: "openapi" | "orval" | "prisma" | "rest-endpoint-generator" | "storybook" | "vitest" | "testcontainers" | "in-memory-db" | "playwright";
12
+ id: "prisma" | "openapi" | "orval" | "rest-endpoint-generator" | "storybook" | "vitest" | "testcontainers" | "in-memory-db" | "playwright";
13
13
  name: string;
14
14
  group: "backend" | "frontend";
15
15
  available: boolean;
@@ -14,6 +14,7 @@ export * from './scaffold-new-domain-service';
14
14
  export * from './scaffold-new-error';
15
15
  export * from './scaffold-new-handlers-rest-endpoint';
16
16
  export * from './scaffold-new-implementation';
17
+ export * from './scaffold-new-infrastructure-helper';
17
18
  export * from './scaffold-new-infrastructure-service';
18
19
  export * from './scaffold-new-presentation-service';
19
20
  export * from './scaffold-new-query';
@@ -0,0 +1,7 @@
1
+ import type { Folder } from '../file-system';
2
+ /**
3
+ * Every implementation type the project knows, of any kind: a helper is
4
+ * shared between the repositories, commands, queries and ports of a type.
5
+ */
6
+ export declare const helperImplementationTypes: () => string[];
7
+ export declare const scaffoldNewInfrastructureHelper: (ownerFolder: Folder) => Promise<void>;
package/dist/wiring.d.ts CHANGED
@@ -55,8 +55,8 @@ export declare const moduleKindOf: (module: WiredModule) => "queries" | "command
55
55
  */
56
56
  export declare const implementationType: (consumer: WiredModule, implementation: WiredClass) => string | undefined;
57
57
  /**
58
- * An infrastructure module whose file name has the implementation label
59
- * as whole words: `in-memory-db-infrastructure-service` for `in-memory`.
58
+ * Only the system service of the implementation is suggested: any other
59
+ * service is chosen by hand, whatever its name says.
60
60
  */
61
61
  export declare const isSuggestedFor: (candidate: WiredModule, implementation: string) => boolean;
62
62
  export declare const canDependOn: (consumer: WiredModule, candidate: WiredModule, rules?: DependencyRules, implementation?: WiredClass) => boolean;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@domain-first/project-structure",
3
3
  "description": "Build and manage your Domain-First project structure with CLI",
4
- "version": "8.6.1",
4
+ "version": "8.7.0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -31,7 +31,8 @@
31
31
  "files": [
32
32
  "dist",
33
33
  "bin",
34
- "skills"
34
+ "skills",
35
+ "principles"
35
36
  ],
36
37
  "publishConfig": {
37
38
  "access": "public"
@@ -0,0 +1,33 @@
1
+ # Programming principles
2
+
3
+ ## Naming instead of comments
4
+
5
+ Code documents itself through names. If something is unclear without a comment, rename or restructure the code first.
6
+
7
+ Keep a comment only for non-standard behavior the code can't show: a non-obvious decision, a workaround for a library quirk, a security requirement.
8
+
9
+ ```ts
10
+ // Bad: the comment restates the name
11
+ /** Domain social network → database enum value */
12
+ socialNetworkIdToPrisma(x: SocialNetworkId) { … }
13
+
14
+ // Good: explains a decision the code doesn't show
15
+ // Another author's post is reported as missing so we don't reveal that it exists
16
+ if (!post || !post.isAuthoredBy(requesterId)) { … }
17
+ ```
18
+
19
+ A `TODO(...)` is a task, not an explanation: keep it.
20
+
21
+ The one exception: modules of the application layer have a required JSDoc block on the class, in the format of the `df-ps-implement` skill.
22
+
23
+ ## Code reads like plain English
24
+
25
+ Read a line aloud: it should sound like a sentence about the domain, not a puzzle. Spell words out (`requesterId`, not `reqId`; `id` and `url` are fine), name a boolean state with a plain adjective (`enabled`, `published`) and use `has` or `can` where the meaning needs a verb (`hasPosts`, `canEdit`), name functions with verbs, and give a complex condition a name of its own. Prefer a getter for a synchronous check without side effects: `order.hasItems`, not `order.hasItems()`. A check that takes an argument stays a method: `post.hasAuthor(requesterId)`.
26
+
27
+ ```ts
28
+ // Bad
29
+ if (p.uid === rid && !p.del && p.pubAt) { … }
30
+
31
+ // Good
32
+ if (post.hasAuthor(requesterId) && post.published) { … }
33
+ ```
@@ -43,7 +43,7 @@ Run it from the project root; `rootFolder` defaults to the config's. It resolves
43
43
  - module files importing kinds the project's dependency rules don't allow (a use case importing a use case, a query importing a command, …), and wired dependencies they don't allow ("Wiring" below, `df-ps-scaffold` rule 3); an implementation importing its own contract is fine;
44
44
  - a widget importing another widget (a widget = the nearest folder under `presentation/react/widgets/` with a `*-widget.tsx`, nested widgets included), UI-kit importing widgets, pages or contexts, shared hooks importing UI-kit, widgets, pages or contexts;
45
45
  - `new Date()` / `Date.now()` in domain or application (use the `clock` port);
46
- - `process.env` / `import.meta.env` in domain or application (use the `config` port).
46
+ - `process.env` / `import.meta.env` in domain or application (use the `application-config` port).
47
47
 
48
48
  It exits with 1 when anything is found. Checks turned off in the config (`backend.rules.lint`) aren't reported; don't turn checks off yourself.
49
49
 
@@ -51,6 +51,31 @@ It exits with 1 when anything is found. Checks turned off in the config (`backen
51
51
 
52
52
  How to fill in each unit (aggregate, entity, value object, errors, services, use case, command, query, port, endpoint) is in the "Implement" and "Test" sections of `df-ps-scaffold/references/units/<unit>.md`. Read the files of the units you implement; the rules below apply to all of them.
53
53
 
54
+ ## Application modules get a summary and a description
55
+
56
+ Every scaffolded module of the application layer gets a JSDoc block on its class: application services, ports, commands, queries and use cases. For commands, queries and ports it goes on the abstract contract. The block is required even when the summary stays close to the name.
57
+
58
+ Other layers don't need one. Domain modules, repository contracts included, document themselves through their names and schemas; infrastructure and presentation modules follow the contracts documented in the application layer. Anything non-standard there gets a regular comment.
59
+
60
+ The block:
61
+
62
+ - Summary: the first line, without a tag. Says **what** the module is for, not how it works. One sentence.
63
+ - `@description`: its own section after the summary, only when there are extra details: edge cases, non-obvious decisions, errors with a special meaning. The tag stands on its own line, the text starts on the next one.
64
+
65
+ ```ts
66
+ /**
67
+ * Obtains a whole post of the requesting author.
68
+ *
69
+ * @description
70
+ * Throws `ItemNotFoundSharedKernelError` both when the post doesn't exist and
71
+ * when its author isn't the requester: for security, posts of other users must
72
+ * not be revealed.
73
+ */
74
+ export abstract class OwnPostQuery { … }
75
+ ```
76
+
77
+ What the description says doesn't need to be repeated in a comment inside the class.
78
+
54
79
  ## Wiring ({wire})
55
80
 
56
81
  Dependencies (constructor parameters and their wires) are added only by `df-scaffold` (`df-ps-scaffold`, rule 3): the generator's `Dependencies:` step or `Wire dependency`. It keeps each `wireClass(X, [...])` in the order of the constructor, which TypeScript checks: