@domain-first/project-structure 8.1.1 → 8.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.cjs CHANGED
@@ -1149,6 +1149,7 @@ const missing_domain_first_packages_missingPackages = (packages)=>{
1149
1149
  ] : [];
1150
1150
  };
1151
1151
  const external_node_async_hooks_namespaceObject = require("node:async_hooks");
1152
+ const isSeparator = (choice)=>'function' == typeof prompts_namespaceObject.Separator && choice instanceof prompts_namespaceObject.Separator || 'object' == typeof choice && null !== choice && 'separator' === choice.type;
1152
1153
  class RequestError extends Error {
1153
1154
  code;
1154
1155
  details;
@@ -1224,7 +1225,7 @@ const interaction_confirm = async (config)=>{
1224
1225
  });
1225
1226
  return value;
1226
1227
  };
1227
- const choicesOf = (config)=>config.choices.filter((choice)=>!(choice instanceof prompts_namespaceObject.Separator)).map((choice)=>'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
1228
+ const choicesOf = (config)=>config.choices.filter((choice)=>!isSeparator(choice)).map((choice)=>'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
1228
1229
  value: choice
1229
1230
  });
1230
1231
  const choiceId = (choice, id)=>id?.(choice.value) ?? choice.value;
@@ -1237,9 +1238,62 @@ const resolveChoice = (value, choices, key, id)=>{
1237
1238
  });
1238
1239
  return matches[0].value;
1239
1240
  };
1241
+ const searchThreshold = 10;
1242
+ const choiceLabel = (choice)=>choice.name ?? String(choice.value);
1243
+ const filterChoices = (choices, term)=>{
1244
+ const text = (term ?? '').trim().toLowerCase();
1245
+ const words = text.split(/\s+/).filter(Boolean);
1246
+ if (!words.length) return [
1247
+ ...choices
1248
+ ];
1249
+ const groups = [
1250
+ {
1251
+ matches: []
1252
+ }
1253
+ ];
1254
+ for (const choice of choices){
1255
+ if (isSeparator(choice)) {
1256
+ groups.push({
1257
+ separator: choice,
1258
+ matches: []
1259
+ });
1260
+ continue;
1261
+ }
1262
+ const normalized = 'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
1263
+ value: choice
1264
+ };
1265
+ const label = choiceLabel(normalized).toLowerCase();
1266
+ if (words.every((word)=>label.includes(word))) groups.at(-1)?.matches.push({
1267
+ choice: normalized,
1268
+ prefix: label.startsWith(text)
1269
+ });
1270
+ }
1271
+ const byPrefix = (items, prefix)=>[
1272
+ ...items.filter(prefix),
1273
+ ...items.filter((item)=>!prefix(item))
1274
+ ];
1275
+ const [ungrouped, ...grouped] = groups;
1276
+ return [
1277
+ ungrouped,
1278
+ ...byPrefix(grouped.filter(({ matches })=>matches.length), ({ matches })=>matches.some(({ prefix })=>prefix))
1279
+ ].flatMap(({ separator, matches })=>[
1280
+ ...separator ? [
1281
+ separator
1282
+ ] : [],
1283
+ ...byPrefix(matches, ({ prefix })=>prefix).map(({ choice })=>choice)
1284
+ ]);
1285
+ };
1240
1286
  const interaction_select = async (config)=>{
1241
1287
  const { key, id, ...interactive } = config;
1242
- if (!isNonInteractive()) return (0, prompts_namespaceObject.select)(interactive);
1288
+ if (!isNonInteractive()) {
1289
+ if (choicesOf(config).length <= searchThreshold) return (0, prompts_namespaceObject.select)(interactive);
1290
+ return (0, prompts_namespaceObject.search)({
1291
+ message: `${config.message.trimEnd()} (type to filter)`,
1292
+ source: (term)=>filterChoices(config.choices, term),
1293
+ pageSize: config.pageSize,
1294
+ default: config.default
1295
+ });
1296
+ }
1243
1297
  const field = requireKey(key);
1244
1298
  const value = answerFor(field, config.default);
1245
1299
  if (void 0 === value) throw interaction_missing(field);
@@ -3162,6 +3216,11 @@ const scaffoldRequestSchema = external_zod_default().discriminatedUnion('operati
3162
3216
  module: agent_requests_id.describe('Exact wiring target ID, including implementation class, from --describe.'),
3163
3217
  dependencies: agent_requests_dependencies
3164
3218
  }),
3219
+ operation('delete', {
3220
+ ...common,
3221
+ ...agent_requests_owner,
3222
+ module: agent_requests_id.describe('Exact unit ID from --describe. Refused while other files use it.')
3223
+ }),
3165
3224
  operation('move', {
3166
3225
  ...common,
3167
3226
  ...agent_requests_owner,
@@ -3199,6 +3258,15 @@ const reactRequestSchema = external_zod_default().discriminatedUnion('operation'
3199
3258
  name: agent_requests_nestedName,
3200
3259
  moveRoute: external_zod_default().boolean().optional().describe('With Next.js and a route at the page path: move it too (default true). Omit it without such a route.')
3201
3260
  }),
3261
+ operation('delete-page', {
3262
+ ...common,
3263
+ module: agent_requests_nestedName,
3264
+ deleteRoute: external_zod_default().boolean().optional().describe("With Next.js and the page's own route: delete it too (default true). Omit it without such a route.")
3265
+ }),
3266
+ operation('delete-widget', {
3267
+ ...common,
3268
+ module: agent_requests_nestedName
3269
+ }),
3202
3270
  operation('move-widget', {
3203
3271
  ...common,
3204
3272
  module: agent_requests_nestedName,
@@ -3702,6 +3770,75 @@ const projectRelative = (fromFile, toFile)=>{
3702
3770
  const relative = toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toFile.replace(codeExtension, '')));
3703
3771
  return relative.startsWith('.') ? relative : `./${relative}`;
3704
3772
  };
3773
+ const importSpecifier = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"\n]+)\1/g;
3774
+ const backend_module_move_importLine = /^\s*(?:import|export)\b[^'"\n]*\bfrom\s*(['"])([^'"\n]+)\1;?\s*$/;
3775
+ const deleteBackendUnit = (projectRoot, rootFolderPath, unit)=>{
3776
+ const files = [
3777
+ ...unitMoves(unit, unit).keys()
3778
+ ];
3779
+ const fileSet = new Set(files);
3780
+ const stems = new Set(files.map((file)=>file.replace(codeExtension, '')));
3781
+ const aggregateFolder = 'aggregate' === unit.kind ? external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.name) : void 0;
3782
+ const parentAggregate = unit.aggregate ? external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.aggregate) : void 0;
3783
+ const isUnit = (resolved)=>stems.has(resolved) || !!aggregateFolder && (resolved === aggregateFolder || resolved.startsWith(`${aggregateFolder}${external_node_path_default().sep}`));
3784
+ const isParentBarrel = (resolved)=>!!parentAggregate && (resolved === parentAggregate || resolved === external_node_path_default().join(parentAggregate, 'index'));
3785
+ const { codeFiles, resolve } = projectImports(projectRoot);
3786
+ const resolved = (specifier, file)=>resolve(specifier, file)?.resolved;
3787
+ const withoutUnitImports = (content, file)=>content.split('\n').filter((line)=>{
3788
+ const specifier = line.match(backend_module_move_importLine)?.[2];
3789
+ const target = specifier && resolved(specifier, file);
3790
+ return !(target && isUnit(target));
3791
+ }).join('\n');
3792
+ const cleaned = new Map();
3793
+ const inMemoryDb = inMemoryDbFile(rootFolderPath);
3794
+ if ('aggregate' === unit.kind && codeFiles.has(inMemoryDb)) {
3795
+ const section = new UnknownFormatNaming(plural(unit.name));
3796
+ const original = codeFiles.get(inMemoryDb);
3797
+ const content = withoutUnitImports(original.replace(new RegExp(`^[ \\t]*${escapeRegExp(section.variableName)}\\s*=\\s*this\\.section<[^\\n]*\\n?`, 'm'), ''), inMemoryDb);
3798
+ if (content !== original) cleaned.set(inMemoryDb, content);
3799
+ }
3800
+ if (parentAggregate) {
3801
+ const index = external_node_path_default().join(parentAggregate, 'index.ts');
3802
+ const original = codeFiles.get(index);
3803
+ if (void 0 !== original) {
3804
+ const content = withoutUnitImports(original, index);
3805
+ if (content !== original) cleaned.set(index, content);
3806
+ }
3807
+ }
3808
+ const ClassName = new UnknownFormatNaming(unit.name).ClassName;
3809
+ const namedImports = /import\s+(?:type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\2/g;
3810
+ const usedBy = [];
3811
+ const relative = (file)=>toPosix(external_node_path_default().relative(projectRoot, file));
3812
+ for (const [file, original] of codeFiles){
3813
+ if (fileSet.has(file)) continue;
3814
+ const content = cleaned.get(file) ?? original;
3815
+ for (const [, , specifier] of content.matchAll(importSpecifier)){
3816
+ const target = resolved(specifier, file);
3817
+ if (target && isUnit(target)) usedBy.push([
3818
+ relative(file),
3819
+ relative(target)
3820
+ ]);
3821
+ }
3822
+ for (const [, names, , specifier] of content.matchAll(namedImports)){
3823
+ const target = resolved(specifier, file);
3824
+ if (target && isParentBarrel(target) && new RegExp(`(?<![\\w$])${ClassName}(?![\\w$])`).test(names)) usedBy.push([
3825
+ relative(file),
3826
+ `${relative(target)} (${ClassName})`
3827
+ ]);
3828
+ }
3829
+ }
3830
+ if (usedBy.length) return {
3831
+ usedBy
3832
+ };
3833
+ for (const file of files)new file_system_File(file).delete(rootFolderPath);
3834
+ for (const [file, content] of cleaned)new file_system_File(file).update(content);
3835
+ return {
3836
+ deleted: files,
3837
+ updated: [
3838
+ ...cleaned.keys()
3839
+ ]
3840
+ };
3841
+ };
3705
3842
  const contractKinds = [
3706
3843
  'aggregate',
3707
3844
  'command',
@@ -3885,7 +4022,7 @@ const validateMove = (reactFolder, module, rawName)=>{
3885
4022
  if (target.startsWith(`${module.path}${external_node_path_default().sep}`)) return 'A widget cannot be moved into itself';
3886
4023
  return true;
3887
4024
  };
3888
- const routeFolder = (appFolder, rawName)=>{
4025
+ const react_module_move_routeFolder = (appFolder, rawName)=>{
3889
4026
  const { folders, folderName } = new NestedName(rawName);
3890
4027
  return external_node_path_default().join(appFolder, ...folders, folderName);
3891
4028
  };
@@ -3947,6 +4084,51 @@ const moveReactModule = (projectRoot, reactFolder, module, rawName, route)=>{
3947
4084
  }
3948
4085
  });
3949
4086
  };
4087
+ const pageRouteFolder = (appFolder, page)=>{
4088
+ const folder = react_module_move_routeFolder(appFolder, page.name);
4089
+ const routePage = external_node_path_default().join(folder, 'page.tsx');
4090
+ return external_node_fs_default().existsSync(routePage) && new RegExp(`(?<![\\w$])${page.ClassName}Page(?![\\w$])`).test(external_node_fs_default().readFileSync(routePage, 'utf8')) ? folder : void 0;
4091
+ };
4092
+ const reactModuleFiles = (module)=>{
4093
+ if ('widget' === module.kind) return module_move_walk(module.path);
4094
+ const folder = external_node_path_default().dirname(module.path);
4095
+ const own = new RegExp(`^${escapeRegExp(module.fileBase)}-page(?:\\.|$)`);
4096
+ return external_node_fs_default().readdirSync(folder, {
4097
+ withFileTypes: true
4098
+ }).filter((entry)=>entry.isFile() && own.test(entry.name)).map((entry)=>external_node_path_default().join(folder, entry.name));
4099
+ };
4100
+ const react_module_move_importSpecifier = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"\n]+)\1/g;
4101
+ const deleteReactModule = (projectRoot, reactFolder, module, route)=>{
4102
+ const moduleFiles = reactModuleFiles(module);
4103
+ const routeFileList = route ? routeFiles(route.folder) : [];
4104
+ const own = new Set([
4105
+ ...moduleFiles,
4106
+ ...routeFileList
4107
+ ]);
4108
+ const stems = new Set(moduleFiles.map((file)=>file.replace(codeExtension, '')));
4109
+ const isModule = (resolved)=>stems.has(resolved) || 'widget' === module.kind && (resolved === module.path || resolved.startsWith(`${module.path}${external_node_path_default().sep}`));
4110
+ const { codeFiles, resolve } = projectImports(projectRoot);
4111
+ const relative = (file)=>toPosix(external_node_path_default().relative(projectRoot, file));
4112
+ const usedBy = [];
4113
+ for (const [file, content] of codeFiles)if (!own.has(file)) for (const [, , specifier] of content.matchAll(react_module_move_importSpecifier)){
4114
+ const target = resolve(specifier, file)?.resolved;
4115
+ if (target && isModule(target)) usedBy.push([
4116
+ relative(file),
4117
+ relative(target)
4118
+ ]);
4119
+ }
4120
+ if (usedBy.length) return {
4121
+ usedBy
4122
+ };
4123
+ for (const file of moduleFiles)new file_system_File(file).delete(reactFolder);
4124
+ for (const file of routeFileList)new file_system_File(file).delete(route.appFolder);
4125
+ return {
4126
+ deleted: [
4127
+ ...moduleFiles,
4128
+ ...routeFileList
4129
+ ]
4130
+ };
4131
+ };
3950
4132
  const systemImplementationChoices = (kind, crossContext = false)=>{
3951
4133
  if ('ports' === kind) return crossContext ? [
3952
4134
  {
@@ -3961,6 +4143,108 @@ const systemImplementationChoices = (kind, crossContext = false)=>{
3961
4143
  }
3962
4144
  ] : [];
3963
4145
  };
4146
+ const deleteBackendUnitUseCase = async (ownerFolder)=>{
4147
+ const root = new project_root_ProjectRoot().path;
4148
+ const rootFolderPath = external_node_path_default().join(root, config_file_ConfigFile.Instance.data.project.rootFolder);
4149
+ const units = findBackendUnits(ownerFolder.path);
4150
+ if (!units.length) return void report('No modules generated by df-scaffold were found here.');
4151
+ const unit = await interaction_select({
4152
+ key: 'module',
4153
+ id: unitId,
4154
+ message: 'Module to delete:',
4155
+ choices: Object.keys(kindLayouts).flatMap((kind)=>{
4156
+ const group = units.filter((x)=>x.kind === kind);
4157
+ return group.length ? [
4158
+ new prompts_namespaceObject.Separator(`── ${kindLayouts[group[0].kind].title}`),
4159
+ ...group.map((value)=>({
4160
+ name: value.aggregate ? `${value.name} (${value.aggregate})` : value.name,
4161
+ value
4162
+ }))
4163
+ ] : [];
4164
+ }),
4165
+ pageSize: 20
4166
+ });
4167
+ const result = deleteBackendUnit(root, rootFolderPath, unit);
4168
+ if (result.usedBy) {
4169
+ if (isNonInteractive()) throw new RequestError('DELETE_NOT_ALLOWED', 'Other files still use the module.', {
4170
+ usedBy: result.usedBy
4171
+ });
4172
+ report([
4173
+ 'Nothing was deleted: these files still use it.',
4174
+ ...result.usedBy.map(([file, used])=>` ${file} → ${used}`),
4175
+ 'Remove those uses first (Wire dependency edits wiring; imports and constructor parameters are yours).'
4176
+ ].join('\n'));
4177
+ return;
4178
+ }
4179
+ const relative = (file)=>external_node_path_default().relative(root, file);
4180
+ report([
4181
+ 'Files to delete:',
4182
+ ...result.deleted.map((file)=>` ${relative(file)}`),
4183
+ ...result.updated.length ? [
4184
+ 'Files to update:',
4185
+ ...result.updated.map((file)=>` ${relative(file)}`)
4186
+ ] : []
4187
+ ].join('\n'));
4188
+ if (!await interaction_confirm({
4189
+ key: 'apply',
4190
+ message: 'Delete?',
4191
+ default: false
4192
+ })) {
4193
+ discardPendingChanges();
4194
+ report('Cancelled: nothing was deleted.');
4195
+ }
4196
+ };
4197
+ const deleteReactModuleUseCase = async (presentationReactFolder, kind)=>{
4198
+ const reactFolder = presentationReactFolder.path;
4199
+ const modules = findReactModules(reactFolder, kind);
4200
+ if (!modules.length) return void report(`No ${kind}s generated by df-react were found.`);
4201
+ const module = await interaction_select({
4202
+ key: 'module',
4203
+ id: (value)=>value.name,
4204
+ message: 'page' === kind ? 'Page to delete:' : 'Widget to delete:',
4205
+ choices: modules.map((value)=>({
4206
+ name: value.name,
4207
+ value,
4208
+ description: external_node_path_default().relative(reactFolder, value.path)
4209
+ }))
4210
+ });
4211
+ const root = new project_root_ProjectRoot().path;
4212
+ const relative = (file)=>external_node_path_default().relative(root, file).split(external_node_path_default().sep).join('/');
4213
+ const appFolder = external_node_path_default().join(root, nextAppFolder(root));
4214
+ const routeFolder = 'page' === kind && usesNext() ? pageRouteFolder(appFolder, module) : void 0;
4215
+ const withRoute = !!routeFolder && await interaction_confirm({
4216
+ key: 'deleteRoute',
4217
+ message: `Delete its Next.js route too: ${relative(routeFolder)}? Its URL stops working.`,
4218
+ default: true
4219
+ });
4220
+ const result = deleteReactModule(root, reactFolder, module, withRoute && routeFolder ? {
4221
+ appFolder,
4222
+ folder: routeFolder
4223
+ } : void 0);
4224
+ if (result.usedBy) {
4225
+ if (isNonInteractive()) throw new RequestError('DELETE_NOT_ALLOWED', `Other files still use the ${kind}.`, {
4226
+ usedBy: result.usedBy
4227
+ });
4228
+ report([
4229
+ 'Nothing was deleted: these files still use it.',
4230
+ ...result.usedBy.map(([file, used])=>` ${file} → ${used}`),
4231
+ 'Remove those uses first.'
4232
+ ].join('\n'));
4233
+ return;
4234
+ }
4235
+ report([
4236
+ 'Files to delete:',
4237
+ ...result.deleted.map((file)=>` ${relative(file)}`)
4238
+ ].join('\n'));
4239
+ if (!await interaction_confirm({
4240
+ key: 'apply',
4241
+ message: 'Delete?',
4242
+ default: false
4243
+ })) {
4244
+ discardPendingChanges();
4245
+ report('Cancelled: nothing was deleted.');
4246
+ }
4247
+ };
3964
4248
  Symbol('create-test-branch');
3965
4249
  Symbol('no-test-branch');
3966
4250
  const noAggregate = 'No aggregate';
@@ -4064,11 +4348,10 @@ const moveBackendUnitUseCase = async (ownerFolder)=>{
4064
4348
  const promptRouteMove = async (root, page, newName)=>{
4065
4349
  if (!usesNext()) return;
4066
4350
  const appFolder = external_node_path_default().join(root, nextAppFolder(root));
4067
- const from = routeFolder(appFolder, page.name);
4068
- const to = routeFolder(appFolder, newName);
4351
+ const from = pageRouteFolder(appFolder, page);
4352
+ const to = react_module_move_routeFolder(appFolder, newName);
4069
4353
  const relative = (file)=>external_node_path_default().relative(root, file).split(external_node_path_default().sep).join('/');
4070
- const routePage = external_node_path_default().join(from, 'page.tsx');
4071
- if (from === to || !external_node_fs_default().existsSync(routePage) || !new RegExp(`\\b${page.ClassName}Page\\b`).test(external_node_fs_default().readFileSync(routePage, 'utf8'))) return;
4354
+ if (!from || from === to) return;
4072
4355
  if (external_node_fs_default().existsSync(external_node_path_default().join(to, 'page.tsx'))) return void report(`${relative(to)}/page.tsx already exists: the route ${relative(from)} stays.`);
4073
4356
  const move = await interaction_confirm({
4074
4357
  key: 'moveRoute',
@@ -5524,7 +5807,7 @@ const executeScaffold = async (request, owner)=>{
5524
5807
  'errors'
5525
5808
  ]).content.fileNames.includes(request.namespace)) throw new RequestError('TARGET_NOT_FOUND', `Unknown namespace: ${request.namespace}.`);
5526
5809
  if ('implementation' === request.operation && !findContracts(owner.path).length) throw new RequestError('TARGET_NOT_FOUND', 'No contracts in this context.');
5527
- if ('move' === request.operation && !findBackendUnits(owner.path).length) throw new RequestError('TARGET_NOT_FOUND', 'No modules in this context.');
5810
+ if (('move' === request.operation || 'delete' === request.operation) && !findBackendUnits(owner.path).length) throw new RequestError('TARGET_NOT_FOUND', 'No modules in this context.');
5528
5811
  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.');
5529
5812
  if ('endpoint' === request.operation) {
5530
5813
  if (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers-rest') || !findRestEndpointGenerator(new file_system_Folder(requireProject()).subitem([
@@ -5553,7 +5836,8 @@ const executeScaffold = async (request, owner)=>{
5553
5836
  implementation: ()=>scaffoldNewImplementation(owner),
5554
5837
  endpoint: ()=>scaffoldNewHandlersRestEndpoint(owner),
5555
5838
  'wire-dependency': ()=>wireDependency(owner),
5556
- move: ()=>moveBackendUnitUseCase(owner)
5839
+ move: ()=>moveBackendUnitUseCase(owner),
5840
+ delete: ()=>deleteBackendUnitUseCase(owner)
5557
5841
  };
5558
5842
  return actions[request.operation]();
5559
5843
  };
@@ -5562,14 +5846,16 @@ const executeReact = async (request)=>{
5562
5846
  config_file_ConfigFile.Instance.data.project.rootFolder,
5563
5847
  'presentation/react'
5564
5848
  ]);
5565
- if (request.operation.startsWith('move-') && !findReactModules(folder.path, 'move-page' === request.operation ? 'page' : 'widget').length) throw new RequestError('TARGET_NOT_FOUND', 'No React modules to move.');
5849
+ if (/^(move|delete)-/.test(request.operation) && !findReactModules(folder.path, request.operation.endsWith('-page') ? 'page' : 'widget').length) throw new RequestError('TARGET_NOT_FOUND', `No React ${request.operation.endsWith('-page') ? 'pages' : 'widgets'} here.`);
5566
5850
  const actions = {
5567
5851
  page: ()=>scaffoldReactPage(folder),
5568
5852
  widget: ()=>scaffoldReactWidget(folder),
5569
5853
  'ui-kit-component': ()=>scaffoldReactUIKitComponent(folder),
5570
5854
  'shared-hook': ()=>scaffoldReactSharedHook(folder),
5571
5855
  'move-page': ()=>moveReactModuleUseCase(folder, 'page'),
5572
- 'move-widget': ()=>moveReactModuleUseCase(folder, 'widget')
5856
+ 'move-widget': ()=>moveReactModuleUseCase(folder, 'widget'),
5857
+ 'delete-page': ()=>deleteReactModuleUseCase(folder, 'page'),
5858
+ 'delete-widget': ()=>deleteReactModuleUseCase(folder, 'widget')
5573
5859
  };
5574
5860
  return actions[request.operation]();
5575
5861
  };
@@ -5727,7 +6013,9 @@ Options:
5727
6013
  'New UI-kit component',
5728
6014
  'New shared hook',
5729
6015
  'Move or rename widget',
5730
- 'Move or rename page'
6016
+ 'Move or rename page',
6017
+ 'Delete widget',
6018
+ 'Delete page'
5731
6019
  ]
5732
6020
  });
5733
6021
  switch(action){
@@ -5743,6 +6031,10 @@ Options:
5743
6031
  return void await moveReactModuleUseCase(reactFolder, 'widget');
5744
6032
  case 'Move or rename page':
5745
6033
  return void await moveReactModuleUseCase(reactFolder, 'page');
6034
+ case 'Delete widget':
6035
+ return void await deleteReactModuleUseCase(reactFolder, 'widget');
6036
+ case 'Delete page':
6037
+ return void await deleteReactModuleUseCase(reactFolder, 'page');
5746
6038
  default:
5747
6039
  return;
5748
6040
  }
package/dist/react.js CHANGED
@@ -3,7 +3,7 @@ import { parseArgs } from "node:util";
3
3
  import { select as prompts_select } from "@inquirer/prompts";
4
4
  import { runCLI } from "./561.js";
5
5
  import { outdatedConfigMessage, ProjectRoot, ConfigFile, Folder } from "./870.js";
6
- import { scaffoldReactWidget, moveReactModuleUseCase, scaffoldReactPage, scaffoldReactUIKitComponent, scaffoldReactSharedHook, savePendingChanges } from "./287.js";
6
+ import { scaffoldReactWidget, moveReactModuleUseCase, deleteReactModuleUseCase, scaffoldReactPage, scaffoldReactUIKitComponent, scaffoldReactSharedHook, savePendingChanges } from "./287.js";
7
7
  runCLI('df-react', async ()=>{
8
8
  const help = `Usage: df-react
9
9
 
@@ -54,7 +54,9 @@ Options:
54
54
  'New UI-kit component',
55
55
  'New shared hook',
56
56
  'Move or rename widget',
57
- 'Move or rename page'
57
+ 'Move or rename page',
58
+ 'Delete widget',
59
+ 'Delete page'
58
60
  ]
59
61
  });
60
62
  switch(action){
@@ -70,6 +72,10 @@ Options:
70
72
  return void await moveReactModuleUseCase(reactFolder, 'widget');
71
73
  case 'Move or rename page':
72
74
  return void await moveReactModuleUseCase(reactFolder, 'page');
75
+ case 'Delete widget':
76
+ return void await deleteReactModuleUseCase(reactFolder, 'widget');
77
+ case 'Delete page':
78
+ return void await deleteReactModuleUseCase(reactFolder, 'page');
73
79
  default:
74
80
  return;
75
81
  }
@@ -0,0 +1,6 @@
1
+ import type { Folder } from '../file-system';
2
+ /**
3
+ * Deletes a unit of a bounded context or the Shared Kernel with every file
4
+ * of it, once nothing else in the project imports it.
5
+ */
6
+ export declare const deleteBackendUnitUseCase: (ownerFolder: Folder) => Promise<void>;
@@ -0,0 +1,8 @@
1
+ import { type Folder } from '../file-system';
2
+ import { type ReactModuleKind } from '../react-module-move';
3
+ /**
4
+ * Deletes a page or widget with its files once nothing else imports it.
5
+ * With Next.js, a page's own route can go with it: its URL stops working,
6
+ * so it is asked.
7
+ */
8
+ export declare const deleteReactModuleUseCase: (presentationReactFolder: Folder, kind: ReactModuleKind) => Promise<void>;
@@ -1,4 +1,6 @@
1
1
  export * from './add-integration';
2
+ export * from './delete-backend-unit';
3
+ export * from './delete-react-module';
2
4
  export * from './initialize';
3
5
  export * from './move-backend-unit';
4
6
  export * from './move-react-module';
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.1.1",
4
+ "version": "8.3.0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -22,7 +22,8 @@
22
22
  "df-integration": "./dist/integration.js",
23
23
  "df-skills": "./bin/df-skills.mjs",
24
24
  "df-lint": "./dist/lint.js",
25
- "df-upgrade": "./dist/upgrade.js"
25
+ "df-upgrade": "./dist/upgrade.js",
26
+ "df-graph": "./dist/graph.js"
26
27
  },
27
28
  "main": "./dist/index.cjs",
28
29
  "homepage": "https://domain-first-landing.vercel.app/scaffolder/",
@@ -15,6 +15,8 @@ Read the config, then build an overview of the contexts and `shared-kernel/` fro
15
15
  rg --files <rootFolder>/bounded-contexts <rootFolder>/shared-kernel
16
16
  ```
17
17
 
18
+ With `@domain-first/wire`, `npx df-graph --json` lists the wired modules of every owner and what each implementation injects, including cross-context ports and the neighbor handlers they reach; `--context <name>` narrows it to one context. Use it to see existing dependencies before reading code.
19
+
18
20
  Use the overview to identify likely owners and related contexts. Search for the feature's domain terms and synonyms; don't infer ownership from folder names alone.
19
21
 
20
22
  Read the relevant code in the affected contexts: aggregates and their rules, use cases, commands/queries, ports, and behavior tests. Follow their dependencies into adapters, wiring, relevant `shared-kernel/` components, and the REST endpoints of any providing context. Note how contexts can reach each other: which database each one uses, and any message queue, RPC, or event setup. Expand the search when ownership or a dependency remains unclear; unrelated implementations do not need a full read.
@@ -41,7 +41,7 @@ A business element goes to UI-kit only when several widgets contain the same ele
41
41
 
42
42
  ## Running df-react
43
43
 
44
- Prefer `npx df-react --describe` and `npx df-react --request` JSON. The installed schema lists operations (`page`, `widget`, `ui-kit-component`, `shared-hook`, `move-page`, `move-widget`), fields and current React modules. For example:
44
+ Prefer `npx df-react --describe` and `npx df-react --request` JSON. The installed schema lists operations (`page`, `widget`, `ui-kit-component`, `shared-hook`, `move-page`, `move-widget`, `delete-page`, `delete-widget`), fields and current React modules. For example:
45
45
 
46
46
  ```bash
47
47
  npx df-react --request '{"operation":"widget","name":"cart","widgetType":"separated"}'
@@ -54,13 +54,15 @@ node <df-ps-scaffold-skill-dir>/scripts/drive.mjs --bin df-react [--cwd <dir>] [
54
54
  node <df-ps-scaffold-skill-dir>/scripts/drive.mjs --bin df-react "pick:New widget" text:cart "pick:with separated ui"
55
55
  ```
56
56
 
57
- Steps and checks are the same as for `df-scaffold` ("Legacy interactive driver" in `df-ps-scaffold`). Its menu: `New widget`, `New page`, `New UI-kit component`, `New shared hook`, `Move or rename widget`, `Move or rename page`. Prompts and output of each: `references/generators.md`.
57
+ Steps and checks are the same as for `df-scaffold` ("Legacy interactive driver" in `df-ps-scaffold`). Its menu: `New widget`, `New page`, `New UI-kit component`, `New shared hook`, `Move or rename widget`, `Move or rename page`, `Delete widget`, `Delete page`. Prompts and output of each: `references/generators.md`.
58
58
 
59
59
  If the CLI cannot run, report the failure and give the user the prepared JSON command (a menu path only for a legacy CLI). Never hand-write its output.
60
60
 
61
61
  ### Moving and renaming
62
62
 
63
- Moving or renaming a page or widget is a df-react run (`Move or rename page` / `Move or rename widget`): it creates the files at the new paths, so it needs an approved plan. With Next.js, moving a page can also move its App Router route and so change its URL: state in the plan whether the route moves (`moveRoute`), and ask the user when the request doesn't say. Don't move, rename, or copy their files by hand, and don't rename their `<Name>Page…`, `<Name>Widget…`, or `use<Name>UIModel` by hand: df-react keeps file names, code names, story titles, and imports in sync. List each move as a run: old → new name, the files to move (`→`), and the files whose imports change (`~`).
63
+ Moving or renaming a page or widget is a df-react run (`Move or rename page` / `Move or rename widget`): it creates the files at the new paths, so it needs an approved plan. With Next.js, moving a page can also move its App Router route and so change its URL: state in the plan whether the route moves (`moveRoute`), and ask the user when the request doesn't say. Don't move, rename, or copy their files by hand, and don't rename their `<Name>Page…`, `<Name>Widget…`, or `use<Name>UIModel` by hand: df-react keeps file names, code names, story titles, and imports in sync. List each move as a plan row (Type `page move` / `widget move`, Name `old → new`).
64
+
65
+ Deleting a page or widget is a df-react run too (`Delete page` / `Delete widget`, JSON `delete-page` / `delete-widget`) and needs an approved plan (Type `page delete` / `widget delete`). It is refused while other files import the module (`DELETE_NOT_ALLOWED` with `details.usedBy`): remove those uses first, or delete the importing module first. With Next.js, deleting a page can also delete its own route and so its URL: state it in the plan (`deleteRoute`), and ask the user when the request doesn't say. Never delete their files by hand.
64
66
 
65
67
  ### Files you may create by hand
66
68
 
@@ -25,6 +25,10 @@ Page and widget names may have folders before them: `text:admin/panel/users` →
25
25
 
26
26
  Move or rename a page or a widget only with df-react, never by hand: `"pick:Move or rename widget" "pick:admin/users" text:team/users "yes"` (`Move or rename page` for pages; the list shows nested names, the default new name is the current one). It moves the widget folder (or the page with its `<name>-page.*` files), renames files and `<Name>Widget…` / `use<Name>UIModel` / `<Name>Page…` to the new name, updates a generated story title and every import of the module (relative and `tsconfig` aliases; importers of barrels re-exporting it get the renamed classes), and fixes relative imports inside it. Before `Apply?` it prints the files to move and to update; check them. An existing target or a move into itself is rejected.
27
27
 
28
+ ## Delete page / widget
29
+
30
+ Delete a page or a widget only with df-react: `"pick:Delete widget" "pick:orders/filters" yes` (`Delete page` for pages; with Next.js and the page's own route, a `yes`/`no` for deleting the route comes before `Delete?`). It deletes the widget folder (or the page with its `<name>-page.*` files) and, if confirmed, the route folder's own files. It refuses while other files import the module and lists them; nothing changes then.
31
+
28
32
  ## New UI-kit component
29
33
 
30
34
  `"pick:New UI-kit" text:date-picker` → `…/react/ui-kit/n/`:
@@ -88,7 +88,7 @@ Reply "ok" to start.
88
88
  - **Scaffolding** has one block per owner, in run order: new contexts first, marked `(new)` (and `(provisional)` with the reason when ownership is a reversible default), then existing contexts, `shared-kernel`, React last.
89
89
  - **Why here**: one short sentence on why this owner, not another: the data or rule the context owns; for `shared-kernel`, why several contexts share it; for React, why the UI changes.
90
90
  - **What will be scaffolded**: one table per owner, one row per `df-scaffold`/`df-react` run. Layers in order domain → application → infrastructure → presentation, the layer in bold only on its first row. Repositories go with their aggregate in domain; commands, queries and ports in application (their implementations are Details); endpoints and React modules in presentation.
91
- - **Type**: the unit: aggregate, entity, value object, error, error namespace, service, port, command, query, use case, implementation, endpoint, wire dependency, move; for React: page, widget, ui-kit component, hook, page move, widget move.
91
+ - **Type**: the unit: aggregate, entity, value object, error, error namespace, service, port, command, query, use case, implementation, endpoint, wire dependency, move, delete; for React: page, widget, ui-kit component, hook, page move, widget move, page delete, widget delete.
92
92
  - **Name**: the entered name; for a move `old → new`; for an implementation the contract; for wire dependency the module.
93
93
  - **Details**: only what changes behavior: implementation types (`(saved)` when saved for future runs), the test implementation, dependencies (`deps: OrderRepository`), environments, widget type, the endpoint's handler, whether a Next.js route moves (`route moves: /a → /b`). No file paths, no CLI menu paths.
94
94
  - **Why**: at most six words: why this kind of module (`choosing-components.md`).
@@ -117,11 +117,11 @@ Anything else (helpers, types, constants, mappers, wiring, barrels): put it in a
117
117
 
118
118
  If the CLI cannot run, report the failure and give the user the prepared JSON command to run themselves (the menu path and answers only for a legacy CLI). Never hand-write its output. Missing generated files are only recreated by re-running the generator, as an approved overwrite.
119
119
 
120
- Moving or renaming a module (aggregate, entity, value object, service, port, query, command, use case) is a df-scaffold run, `Move or rename` (`references/units/move-or-rename.md`); a page or widget, a df-react run (`df-ps-react`). Never by hand: it creates files at the new paths, so it needs an approved plan.
120
+ Moving or renaming a module (aggregate, entity, value object, service, port, query, command, use case) is a df-scaffold run, `Move or rename` (`references/units/move-or-rename.md`); a page or widget, a df-react run (`df-ps-react`). Never by hand: it creates files at the new paths, so it needs an approved plan. Deleting a module is a df-scaffold run too, `Delete` (`references/units/delete.md`): it removes files, so it needs an approved plan as well.
121
121
 
122
122
  ### 3. New dependencies only through df-scaffold
123
123
 
124
- With `@domain-first/wire`, every new dependency of a wired class (a constructor parameter plus its wire) is added by `df-scaffold`: the generator's `Dependencies:` step for a new module, `Wire dependency` for an existing one, and the `Handler:` pick for an endpoint (its generator is added automatically). Don't add constructor parameters or wire entries by hand, and don't reorder or remove the ones `df-scaffold` added.
124
+ With `@domain-first/wire`, every new dependency of a wired class (a constructor parameter plus its wire) is added by `df-scaffold`: the generator's `Dependencies:` step for a new module, `Wire dependency` for an existing one, and the `Handler:` pick for an endpoint (its generator is added automatically). Don't add constructor parameters or wire entries by hand, and don't reorder or remove the ones `df-scaffold` added. The one exception: an approved plan removes a dependency (from the wire and the constructor together), e.g. before deleting the module it points to.
125
125
 
126
126
  - List each module's dependencies in its plan row's Details (`deps: OrderRepository`); for an existing module, add a `wire dependency` row.
127
127
  - A dependency the CLI doesn't offer is forbidden by the project's dependency rules (the defaults, changed by `backend.rules.dependencies` in the config) or by context isolation: change the design (a port, a query or command, an infrastructure service) instead of adding it by hand.
@@ -150,6 +150,7 @@ One file per unit in `references/units/`: when to choose it, how to generate it
150
150
  | REST endpoint | `endpoint.md` | Presentation → New Handlers-REST Endpoint |
151
151
  | Dependency of an existing module | `wire-dependency.md` | Wire dependency |
152
152
  | Moving or renaming a module | `move-or-rename.md` | Move or rename |
153
+ | Deleting a module | `delete.md` | Delete |
153
154
  | React modules | `df-ps-react` skill | `df-react` |
154
155
 
155
156
  ## Preparing runs
@@ -198,7 +199,7 @@ Check every run: exit code 0, no `WARNING`/`ABORTED`, and exactly the files its
198
199
  | Infrastructure | New Service, New Implementation | New Service, New Implementation |
199
200
  | Presentation | New Handlers-REST Endpoint (needs handlers-rest), New Service | New Service |
200
201
 
201
- With `@domain-first/wire`, the layer menu of a context and of the Shared Kernel also has `Wire dependency`: it adds dependencies to an existing wired module. Every layer menu has `Move or rename`.
202
+ With `@domain-first/wire`, the layer menu of a context and of the Shared Kernel also has `Wire dependency`: it adds dependencies to an existing wired module. Every layer menu has `Move or rename` and `Delete`.
202
203
 
203
204
  The main menu also has `Scaffold new bounded context`. React modules come from a separate CLI, `df-react`: see `df-ps-react`.
204
205
 
@@ -67,6 +67,7 @@ Compare the reported changes with the approved plan, then implement the generate
67
67
  | `CONTEXT_NOT_FOUND`, `TARGET_NOT_FOUND`, `REST_NOT_CONFIGURED` | Create the required context, aggregate, namespace, contract, handler or integration first if that work is authorized; otherwise report the missing prerequisite. A dry run of a prerequisite does not create it. |
68
68
  | `OVERWRITE_REQUIRED` | Preview and inspect the listed paths. Use `overwrite: true` only for replacements already within the approved plan; obtain any required plan change first. |
69
69
  | `MOVE_NOT_ALLOWED` | Review the boundary violations and change the design or move prerequisites first. Do not perform the move by hand. |
70
+ | `DELETE_NOT_ALLOWED` | `details.usedBy` lists `[file, import]` pairs still using the module. Remove those uses first if the plan covers it, or report them; never delete the files by hand. |
70
71
  | `CANCELLED`, `OPERATION_FAILED`, `UNSUPPORTED_PROMPT` | Inspect the message and report the failed operation or unsupported CLI path. Do not treat this as permission to switch to interactive execution or write output by hand. |
71
72
 
72
73
  Failures discard the operation's staged changes. Success can still have follow-up notes: inspect `messages`/`nextSteps` for manual adapter connection, integration installation, custom wiring or an implementation no longer selected by any environment. Check the actual generated files before implementing business logic.
@@ -28,6 +28,7 @@ All operations support `dryRun` and `overwrite`. Except `bounded-context`, they
28
28
  | `endpoint` | `controller`, `method`, `path` | REST package and generator must exist. With wiring and selectable handlers, provide `handler`. Without selectable handlers, omit it; the generated handler remains `never` and needs a later approved generator rerun. |
29
29
  | `wire-dependency` | `module`, `dependencies` | `module` is a wiring target ID, not a contract/unit ID. Adds only eligible dependencies not already wired to that implementation. |
30
30
  | `move` | `module` | `module` is a unit ID. Optional `name`, `targetContext`, `aggregate`; omitted name/context keep the existing ones. A same-owner entity/value-object keeps its aggregate by default. The target aggregate must exist; the target context must be a discovered, allowed destination for that unit kind. Illegal cross-context imports reject the move. |
31
+ | `delete` | `module` | `module` is a unit ID. Deletes every file of the unit and its generated references (aggregate barrel re-export, in-memory DB section). Refused with `DELETE_NOT_ALLOWED` and `details.usedBy` while other files import it; nothing changes. |
31
32
 
32
33
  `implementation` and `testImplementation` contain `type` and optional `save` (default false). Explicit types can be new ordinary names; they need not already be saved. Saving is independent for primary and test roles. The test type must differ from the primary type. Adding a new implementation remembers a saved type according to the selected environments: `test` or primary for other environments. Branches are `backend.envBranches.names` from the config (`test`, `development`, `production` when absent), with `backend.envBranches.test` as the test one; additional names must be offered by the existing branched wire. Custom branches without `test` take no test implementations: omit `testImplementation`. Without usable branching, omit `environments` and follow the returned wiring note.
33
34
 
@@ -118,6 +119,8 @@ The owner configures frontend first. React and Next.js use the same operations.
118
119
  | `shared-hook` | `name` | Single kebab-case name, preferably without `use-`; a leading `use-` is stripped. |
119
120
  | `move-page` | `module`, `name` | `module` is the existing nested page name from discovery; `name` is the target nested name. With Next.js and a route at the page path that renders the page, `moveRoute` (default true) moves that route folder's own files to the new path, changing the URL; `false` keeps the route with its import updated. Omit `moveRoute` when there is no such route. |
120
121
  | `move-widget` | `module`, `name` | Same for widgets. Files, imports, code names and generated story titles follow the move. |
122
+ | `delete-page` | `module` | Deletes the page and its `<name>-page.*` files. With Next.js and the page's own route, `deleteRoute` (default true) deletes that route folder's own files too; `false` keeps the route, which still imports the page, so the delete is refused. Omit `deleteRoute` without such a route. |
123
+ | `delete-widget` | `module` | Deletes the widget folder. Refused with `DELETE_NOT_ALLOWED` and `details.usedBy` while other files import it. |
121
124
 
122
125
  All support `dryRun` and `overwrite`. Use CLI moves even for a rename or folder regrouping; an existing target or a move into itself is rejected.
123
126