@domain-first/project-structure 8.11.0 → 8.13.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/upgrade.js CHANGED
@@ -4,8 +4,8 @@ import { parseArgs } from "node:util";
4
4
  import { confirm as prompts_confirm } from "@inquirer/prompts";
5
5
  import zod from "zod";
6
6
  import node_fs from "node:fs";
7
- import { boundedContextName, implementationLabelSchema, domainFirstPackages as config_file_domainFirstPackages, discardPendingChanges, configSchema, rulesSchema, ConfigFile, boundedContextPath, isOutdatedConfig, writePendingChanges, File, ProjectRoot, configFileName, boundedContextNames } from "./201.js";
8
- import { restFolders, withIdLookup, endpointFileLookup, walk, legacyWithIdLookup, hasLegacyRootEndpoints, stageModuleMove, legacyRootEndpoints, toPosix, openapiExtractorPath, rootEndpointFileLookup, legacyEndpointFileLookup, legacyHasId, hasDependency, codeExtension } from "./115.js";
7
+ import { domainFirstPackages as config_file_domainFirstPackages, discardPendingChanges, configSchema, module_move_walk, escapeRegExp, writePendingChanges, stageModuleMove, configFileName, toPosix, boundedContextNames, implementationLabelSchema, rulesSchema, ConfigFile, boundedContextPath, isOutdatedConfig, File, ProjectRoot, codeExtension, boundedContextName } from "./878.js";
8
+ import { svelteSwaggerPage, restFolders, withIdLookup, openapiExtractorPath, rootEndpointFileLookup, legacyEndpointFileLookup, hasLegacyRootEndpoints, legacyHasId, legacyWithIdLookup, endpointFileLookup, hasDependency, svelteKitStaticUrl, legacyRootEndpoints, swaggerPagePath } from "./783.js";
9
9
  const serviceFile = ({ config })=>{
10
10
  const project = config.project;
11
11
  const rootFolder = 'object' == typeof project && null !== project ? project.rootFolder : void 0;
@@ -48,7 +48,7 @@ const rootMoves = (contextFolder)=>{
48
48
  files: [
49
49
  ...[
50
50
  ...endpointFiles,
51
- ...parameterFolders.flatMap(walk)
51
+ ...parameterFolders.flatMap(module_move_walk)
52
52
  ].map((file)=>[
53
53
  file,
54
54
  intoRoot(presentation, file)
@@ -201,6 +201,207 @@ const openapiExtractorManualStep = {
201
201
  ]
202
202
  };
203
203
  const record = (value)=>'object' != typeof value || null === value || Array.isArray(value) ? {} : value;
204
+ const svelteOf = ({ config })=>'svelte' in record(config.frontend) ? record(record(config.frontend).svelte) : void 0;
205
+ const upgrade_svelte_rootFolderOf = ({ config })=>{
206
+ const rootFolder = record(config.project).rootFolder;
207
+ return 'string' == typeof rootFolder ? rootFolder : void 0;
208
+ };
209
+ const upgrade_svelte_relative = (file)=>toPosix(node_path.relative(new ProjectRoot().path, file));
210
+ const svelteFolder = (context)=>{
211
+ const rootFolder = upgrade_svelte_rootFolderOf(context);
212
+ return svelteOf(context) && rootFolder ? node_path.join(new ProjectRoot().path, rootFolder, 'presentation', 'svelte') : void 0;
213
+ };
214
+ const legacySwaggerPage = (context)=>{
215
+ const rootFolder = upgrade_svelte_rootFolderOf(context);
216
+ if (!svelteOf(context) || !rootFolder) return;
217
+ const file = new File(node_path.join(new ProjectRoot().path, swaggerPagePath(rootFolder, 'svelte')));
218
+ return file.exists && /swagger-ui\/dist\/swagger-ui\.css|import\(\s*['"]swagger-ui['"]\s*\)/.test(file.data) ? file : void 0;
219
+ };
220
+ const importedSpecPath = (page)=>{
221
+ const specifier = page.data.match(/import\s+spec\s+from\s+['"]([^'"]+)['"]/)?.[1];
222
+ return specifier?.startsWith('.') ? upgrade_svelte_relative(node_path.resolve(node_path.dirname(page.path), specifier)) : void 0;
223
+ };
224
+ const svelteSwaggerPageStep = {
225
+ id: 'svelte-swagger-ui-dist',
226
+ kind: 'optional',
227
+ title: 'Render the Svelte Swagger UI page with swagger-ui-dist',
228
+ detect: (context)=>{
229
+ const page = legacySwaggerPage(context);
230
+ return !!page && !!importedSpecPath(page);
231
+ },
232
+ plan: (context)=>{
233
+ const page = legacySwaggerPage(context);
234
+ return [
235
+ `${upgrade_svelte_relative(page.path)}: regenerated on swagger-ui-dist/swagger-ui-bundle.js, which bundles its own React`
236
+ ];
237
+ },
238
+ apply: (context)=>{
239
+ const page = legacySwaggerPage(context);
240
+ const outputPath = importedSpecPath(page);
241
+ const sveltekit = svelteOf(context)?.framework === 'sveltekit';
242
+ page.update(svelteSwaggerPage(upgrade_svelte_rootFolderOf(context), outputPath, sveltekit ? svelteKitStaticUrl(outputPath) : void 0));
243
+ }
244
+ };
245
+ const svelteSwaggerPackagesStep = {
246
+ id: 'svelte-swagger-ui-dist-packages',
247
+ kind: 'manual',
248
+ title: 'Replace swagger-ui with swagger-ui-dist',
249
+ detect: (context)=>!!svelteOf(context) && hasDependency('swagger-ui'),
250
+ plan: ()=>[
251
+ `npm uninstall swagger-ui${hasDependency('@types/swagger-ui') ? ' @types/swagger-ui' : ''}`,
252
+ ...hasDependency('swagger-ui-dist') ? [] : [
253
+ 'npm install swagger-ui-dist'
254
+ ],
255
+ ...hasDependency('@types/swagger-ui-dist') ? [] : [
256
+ 'npm install --save-dev @types/swagger-ui-dist'
257
+ ]
258
+ ]
259
+ };
260
+ const legacyFunctionNames = (file)=>[
261
+ ...node_fs.readFileSync(file, 'utf8').matchAll(/export\s+(?:const|function)\s+use(\w+)\b/g)
262
+ ].map(([, name])=>[
263
+ `use${name}`,
264
+ `create${name}`
265
+ ]);
266
+ const legacyModels = (context)=>{
267
+ const folder = svelteFolder(context);
268
+ if (!folder) return [];
269
+ const sharedFolder = node_path.join(folder, 'hooks');
270
+ if (!node_fs.existsSync(sharedFolder)) return [];
271
+ return node_fs.readdirSync(sharedFolder).map((name)=>node_path.join(sharedFolder, name)).filter((file)=>/^use-.+\.svelte\.[jt]s$/.test(node_path.basename(file)) && !/\.(spec|test)\./.test(file)).map((file)=>({
272
+ from: file,
273
+ to: node_path.join(folder, 'shared', 'model', node_path.basename(file).replace(/^use-/, 'create-'))
274
+ })).filter(({ to })=>!node_fs.existsSync(to)).map((move)=>({
275
+ ...move,
276
+ names: legacyFunctionNames(move.from)
277
+ }));
278
+ };
279
+ const svelteModelsStep = {
280
+ id: 'svelte-models',
281
+ kind: 'optional',
282
+ title: 'Rename Svelte shared hooks to shared models: shared/model/create-*.svelte.ts',
283
+ detect: (context)=>legacyModels(context).length > 0,
284
+ plan: (context)=>legacyModels(context).flatMap(({ from, to, names })=>[
285
+ `${upgrade_svelte_relative(from)} → ${upgrade_svelte_relative(to)}`,
286
+ ...names.map(([from, to])=>` ${from} → ${to}`)
287
+ ]),
288
+ apply: (context)=>{
289
+ const models = legacyModels(context);
290
+ const moves = new Map(models.map(({ from, to })=>[
291
+ from,
292
+ to
293
+ ]));
294
+ const withoutExtension = new Map(models.map(({ from, to })=>[
295
+ from.replace(codeExtension, ''),
296
+ to.replace(codeExtension, '')
297
+ ]));
298
+ const names = models.flatMap((model)=>model.names);
299
+ const namePattern = names.length && new RegExp(`(?<![\\w$])(${names.map(([from])=>escapeRegExp(from)).join('|')})(?![\\w$])`, 'g');
300
+ const renames = new Map(names);
301
+ stageModuleMove({
302
+ projectRoot: new ProjectRoot().path,
303
+ stopAt: svelteFolder(context),
304
+ moves,
305
+ movedPath: (candidate)=>moves.get(candidate) ?? withoutExtension.get(candidate),
306
+ rename: (content)=>namePattern ? content.replace(namePattern, (name)=>renames.get(name) ?? name) : content
307
+ });
308
+ }
309
+ };
310
+ const withoutLineComments = (text)=>text.split('\n').filter((line)=>!/^\s*\/\//.test(line)).join('\n');
311
+ const closesAtEnd = (text)=>{
312
+ let depth = 0;
313
+ let quote;
314
+ for(let index = 0; index < text.length; index++){
315
+ const char = text[index];
316
+ if (quote) {
317
+ if ('\\' === char) index++;
318
+ else if (char === quote) quote = void 0;
319
+ continue;
320
+ }
321
+ if ("'" === char || '"' === char || '`' === char) quote = char;
322
+ else if ('{' === char) depth++;
323
+ else if ('}' === char && 0 === --depth) return index === text.length - 1;
324
+ }
325
+ return false;
326
+ };
327
+ const mappedObject = (content)=>{
328
+ const lines = content.replace(/\/\*[\s\S]*?\*\//g, '').split('\n');
329
+ const exportAt = lines.findIndex((line)=>/^export\s/.test(line));
330
+ if (exportAt < 0) return;
331
+ const onlyTypeImports = lines.slice(0, exportAt).filter((line)=>line.trim() && !/^\s*\/\//.test(line)).every((line)=>/^import\s+type\s*\{[^}]*\}\s*from\s*['"]\.\.\/types['"];?\s*$/.test(line));
332
+ const declaration = lines.slice(exportAt).join('\n').trim().match(/^export\s+const\s+(?:use|create)(\w+)UIModel\s*=\s*\(\s*([\w$]+)\s*(?::[^)]*)?\)\s*(?::[^=]+?)?=>\s*([\s\S]*?);?$/);
333
+ if (!onlyTypeImports || !declaration) return;
334
+ const [, ClassName, param, rawBody] = declaration;
335
+ const body = rawBody.trim();
336
+ const object = body.startsWith('(') && body.endsWith(')') ? body.slice(1, -1).trim() : body.startsWith('{') && body.endsWith('}') ? withoutLineComments(body.slice(1, -1)).trim().match(/^return\s*(\{[\s\S]*\})\s*;?$/)?.[1] : void 0;
337
+ if (!object || !closesAtEnd(object)) return;
338
+ if (/\b(?:get|set)\s+[\w$]+\s*\(|\$(?:state|derived|effect)\b/.test(object)) return;
339
+ const ownProps = new RegExp(`(?<![\\w$.])${escapeRegExp(param)}\\.`, 'g');
340
+ if (new RegExp(`(?<![\\w$])${escapeRegExp(param)}(?![\\w$])`).test(object.replace(ownProps, ''))) return;
341
+ return {
342
+ ClassName,
343
+ object: '{}' === withoutLineComments(object).replace(/\s/g, '') ? '{}' : object,
344
+ ownProps
345
+ };
346
+ };
347
+ const inlineModel = (widget, model)=>{
348
+ const mapped = mappedObject(node_fs.readFileSync(model, 'utf8'));
349
+ if (!mapped) return;
350
+ const { ClassName, object, ownProps } = mapped;
351
+ const content = node_fs.readFileSync(widget, 'utf8');
352
+ const importLine = new RegExp(`^[ \\t]*import\\s*\\{\\s*(?:use|create)${ClassName}UIModel\\s*\\}\\s*from\\s*['"]\\./(?:hooks|model)/[^'"]+['"];?[ \\t]*\\n`, 'm');
353
+ const call = new RegExp(`^(?:[ \\t]*// The (?:\\$props\\(\\) proxy|rest of \\$props\\(\\)).*\\n)?(?:[ \\t]*// svelte-ignore state_referenced_locally\\n)?([ \\t]*)const\\s+uiModel\\s*=\\s*(?:use|create)${ClassName}UIModel\\(\\s*([\\w$]+)\\s*\\);?[ \\t]*\\n`, 'm');
354
+ const typesImport = new RegExp(`import\\s+type\\s*\\{\\s*${ClassName}WidgetProps\\s*\\}\\s*from\\s*(['"])\\./types\\1`);
355
+ const callMatch = content.match(call);
356
+ if (!importLine.test(content) || !callMatch || !typesImport.test(content) || !content.includes('{...uiModel}')) return;
357
+ const [, indent, argument] = callMatch;
358
+ const objectLines = object.replace(ownProps, `${argument}.`).split('\n');
359
+ const closingIndent = objectLines.at(-1).match(/^\s*/)[0].length;
360
+ const shift = indent.length - closingIndent;
361
+ const reindented = objectLines.map((line, index)=>0 === index ? line : shift >= 0 ? `${' '.repeat(shift)}${line}` : line.replace(new RegExp(`^ {0,${-shift}}`), '')).join('\n');
362
+ const inlined = content.replace(importLine, '').replace(call, `${indent}const toUIProps = (): ${ClassName}WidgetUIProps => (${reindented})\n`).replace(typesImport, (_, quote)=>`import type { ${ClassName}WidgetProps, ${ClassName}WidgetUIProps } from ${quote}./types${quote}`).replaceAll('{...uiModel}', '{...toUIProps()}');
363
+ return /(?<![\w$])uiModel(?![\w$])/.test(inlined) ? void 0 : inlined;
364
+ };
365
+ const widgetModels = (context)=>{
366
+ const folder = svelteFolder(context);
367
+ if (!folder) return [];
368
+ return module_move_walk(node_path.join(folder, 'widgets')).filter((file)=>[
369
+ 'hooks',
370
+ 'model'
371
+ ].includes(node_path.basename(node_path.dirname(file))) && /^(?:use|create)-.+-ui-model\.svelte\.[jt]s$/.test(node_path.basename(file))).map((model)=>{
372
+ const widgetFolder = node_path.dirname(node_path.dirname(model));
373
+ const widgetName = node_fs.readdirSync(widgetFolder).find((name)=>name.endsWith('-widget.svelte'));
374
+ const widget = widgetName && node_path.join(widgetFolder, widgetName);
375
+ const specifier = node_path.basename(model).replace(codeExtension, '');
376
+ const usedElsewhere = module_move_walk(widgetFolder).some((file)=>file !== widget && file !== model && codeExtension.test(file) && node_fs.readFileSync(file, 'utf8').includes(specifier));
377
+ return {
378
+ model,
379
+ widget,
380
+ inlined: widget && !usedElsewhere ? inlineModel(widget, model) : void 0
381
+ };
382
+ });
383
+ };
384
+ const svelteToUIPropsStep = {
385
+ id: 'svelte-to-ui-props',
386
+ kind: 'optional',
387
+ title: 'Map Svelte widget props with toUIProps in the widget',
388
+ detect: (context)=>widgetModels(context).some(({ inlined })=>void 0 !== inlined),
389
+ plan: (context)=>widgetModels(context).filter(({ inlined })=>void 0 !== inlined).map(({ model, widget })=>`${upgrade_svelte_relative(model)} → toUIProps in ${upgrade_svelte_relative(widget)}; the model file is deleted`),
390
+ apply: (context)=>{
391
+ for (const { model, widget, inlined } of widgetModels(context))if (void 0 !== inlined) {
392
+ new File(widget).update(inlined);
393
+ new File(model).delete(node_path.dirname(widget));
394
+ }
395
+ }
396
+ };
397
+ const svelteToUIPropsManualStep = {
398
+ id: 'svelte-to-ui-props-manual',
399
+ kind: 'manual',
400
+ title: 'Move Svelte widget UI models into toUIProps by hand',
401
+ detect: (context)=>widgetModels(context).some(({ inlined })=>void 0 === inlined),
402
+ plan: (context)=>widgetModels(context).filter(({ inlined })=>void 0 === inlined).map(({ model, widget })=>widget ? `${upgrade_svelte_relative(model)}: move its state and methods into the <script> of ${upgrade_svelte_relative(widget)}, map props in toUIProps and render {...toUIProps()}, then delete the model` : `${upgrade_svelte_relative(model)}: no widget file next to it; map props with toUIProps in the widget`)
403
+ };
404
+ const upgrade_steps_record = (value)=>'object' != typeof value || null === value || Array.isArray(value) ? {} : value;
204
405
  const flatConfigSchema = zod.object({
205
406
  rootFolder: zod.string().min(1),
206
407
  domainFirstPackages: zod.array(zod["enum"](config_file_domainFirstPackages)),
@@ -254,17 +455,17 @@ const sectionsStep = {
254
455
  };
255
456
  }
256
457
  };
257
- const reactOf = (config)=>record(record(config.frontend).react);
458
+ const reactOf = (config)=>upgrade_steps_record(upgrade_steps_record(config.frontend).react);
258
459
  const frameworkStep = {
259
460
  id: 'react-framework',
260
461
  kind: 'required',
261
462
  title: 'Record the frontend framework explicitly',
262
- detect: ({ config })=>'react' in record(config.frontend) && !reactOf(config).framework,
463
+ detect: ({ config })=>'react' in upgrade_steps_record(config.frontend) && !reactOf(config).framework,
263
464
  plan: ()=>[
264
465
  hasDependency('next') ? 'frontend.react.framework: "next" (next is in package.json)' : 'frontend.react.framework: "react" (next is not in package.json)'
265
466
  ],
266
467
  apply: ({ config })=>{
267
- const frontend = record(config.frontend);
468
+ const frontend = upgrade_steps_record(config.frontend);
268
469
  config.frontend = {
269
470
  ...frontend,
270
471
  react: {
@@ -283,9 +484,9 @@ const persistenceStep = {
283
484
  id: 'persistence-default',
284
485
  kind: 'required',
285
486
  title: 'Move the default persistence implementation to saved implementation types',
286
- detect: ({ config })=>'defaultPersistenceLayerImplementation' in record(config.backend),
487
+ detect: ({ config })=>'defaultPersistenceLayerImplementation' in upgrade_steps_record(config.backend),
287
488
  plan: ({ config })=>{
288
- const label = record(config.backend).defaultPersistenceLayerImplementation;
489
+ const label = upgrade_steps_record(config.backend).defaultPersistenceLayerImplementation;
289
490
  if (void 0 === label) return [];
290
491
  return implementationLabelSchema.safeParse(label).success ? [
291
492
  `defaultPersistenceLayerImplementation "${label}" → first primary type of backend.implementations.${persistenceKinds.join(', ')}`
@@ -294,11 +495,11 @@ const persistenceStep = {
294
495
  ];
295
496
  },
296
497
  apply: ({ config })=>{
297
- const { defaultPersistenceLayerImplementation: label, ...backend } = record(config.backend);
298
- const implementations = record(backend.implementations);
498
+ const { defaultPersistenceLayerImplementation: label, ...backend } = upgrade_steps_record(config.backend);
499
+ const implementations = upgrade_steps_record(backend.implementations);
299
500
  if (implementationLabelSchema.safeParse(label).success) {
300
501
  for (const kind of persistenceKinds){
301
- const group = record(implementations[kind]);
502
+ const group = upgrade_steps_record(implementations[kind]);
302
503
  const primary = Array.isArray(group.primary) ? group.primary : [];
303
504
  implementations[kind] = {
304
505
  primary: [
@@ -321,12 +522,17 @@ const upgradeSteps = [
321
522
  openapiExtractorRootStep,
322
523
  openapiExtractorNestedStep,
323
524
  openapiExtractorManualStep,
324
- inMemoryDbWithIdStep
525
+ inMemoryDbWithIdStep,
526
+ svelteSwaggerPageStep,
527
+ svelteSwaggerPackagesStep,
528
+ svelteModelsStep,
529
+ svelteToUIPropsStep,
530
+ svelteToUIPropsManualStep
325
531
  ];
326
532
  const skillsNote = 'Update the agent skills to this version: npx df-skills';
327
533
  const planUpgrade = async (config, acceptOptional = ()=>true, steps = upgradeSteps)=>{
328
534
  const context = {
329
- config: structuredClone(record(config))
535
+ config: structuredClone(upgrade_steps_record(config))
330
536
  };
331
537
  const original = JSON.stringify(context.config);
332
538
  const planned = [];
@@ -17,6 +17,7 @@ export declare const scaffoldSveltePage: (presentationSvelteFolder: Folder) => P
17
17
  export declare const scaffoldSvelteWidget: (presentationSvelteFolder: Folder) => Promise<void>;
18
18
  export declare const scaffoldSvelteUIKitComponent: (presentationSvelteFolder: Folder) => Promise<void>;
19
19
  /**
20
- * A shared hook is a `.svelte.ts` module, so it may use runes.
20
+ * A shared model is a `.svelte.ts` factory, so it may use runes. Svelte
21
+ * has no hooks: in SvelteKit they are `hooks.server.ts`/`hooks.client.ts`.
21
22
  */
22
- export declare const scaffoldSvelteSharedHook: (presentationSvelteFolder: Folder) => Promise<void>;
23
+ export declare const scaffoldSvelteSharedModel: (presentationSvelteFolder: Folder) => Promise<void>;
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.11.0",
4
+ "version": "8.13.0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -11,7 +11,7 @@ Follow this order for every request:
11
11
 
12
12
  1. Read `domain-first.project-structure.config.json` beside the nearest `package.json`: `project.rootFolder`, `backend` (including `backend.implementations` and `backend.rules`), and `frontend`. `frontend.react.framework` records React (`react`) or Next.js (`next`); both use `df-react`. `frontend.svelte.framework` records Svelte (`svelte`) or SvelteKit (`sveltekit`); both use `df-svelte`. Initialization and configuration belong to the human: never run `df-init` or manually add/change these settings. If the config is missing, tell the user to run `npx df-init`; if backend work needs an absent `backend`, tell them to run `npx df-init --section backend`. Continue only with work whose required sections are configured. A config of an earlier major version (flat, without `project`) makes every command stop with `run npx df-upgrade` (`CONFIG_OUTDATED` in JSON mode): ask the user to run `npx df-upgrade`; never run it or convert the config yourself. `df-init` scaffolds explicit standard lists and enabled lint checks under `backend.rules`; read the saved values as authoritative. Older or partial configs may omit entries, which retain the defaults. Backend reconfiguration by the user fills missing entries without resetting existing rules.
13
13
  2. Feature request without named contexts/components → `df-ps-plan-feature` (it covers steps 3–5).
14
- 3. Choose a component for each piece of logic with `references/choosing-components.md`. Pieces of UI (pages, widgets, UI-kit components, shared hooks): `df-ps-react` (Svelte: `df-ps-svelte`).
14
+ 3. Choose a component for each piece of logic with `references/choosing-components.md`. Pieces of UI (pages, widgets, UI-kit components, shared hooks): `df-ps-react` (Svelte: `df-ps-svelte`, with shared models in place of shared hooks).
15
15
  4. Read `references/units/<unit>.md` for every unit in the plan ("Units" below) and prepare the run details ("Preparing runs"). Read [agent-mode.md](references/agent-mode.md) for the JSON protocol and use `--describe` to obtain the installed request schema and selectable IDs.
16
16
  5. If the task creates files, show the work plan and **stop until it's approved** (rule 1).
17
17
  6. Run the generators in plan order with `--request` JSON; check exit code, `ok` and all returned file lists.
@@ -40,7 +40,7 @@ Every new file is created by `df-scaffold` (React modules: `df-react`; Svelte mo
40
40
  | --- | --- | --- | --- |
41
41
  | 1 | Missing spec | `<component>.spec.ts` next to the component | Exactly from "Spec templates" in `references/generators.md`. |
42
42
  | 2 | Output of project tools | where the tool puts it | Migrations, codegen: run the project's script, use its output as-is; never hand-write or edit it. No approval needed for these files. |
43
- | 3 | Widget hooks / UI | `…/presentation/react/widgets/<name>/hooks/**`, `ui/**` (Svelte: `…/presentation/svelte/widgets/<name>/…`) | Widget generated by df-react or df-svelte. |
43
+ | 3 | Widget hooks / UI | `…/presentation/react/widgets/<name>/hooks/**`, `ui/**` (Svelte: `…/presentation/svelte/widgets/<name>/ui/**`; logic stays in the widget's `toUIProps`) | Widget generated by df-react or df-svelte. |
44
44
  | 4 | Widget/page/UI-kit support files | inside the widget folder or `ui-kit/<name>/`: styles, assets, `*.test.tsx`, `*.stories.tsx`; next to a page: `pages/<name>-page.module.css`, for a nested page in its folder (`pages/admin/admin-users-page.module.css`) (layout of its widgets only) | Widget/page/UI-kit component generated by df-react. Details and story templates: `df-ps-react`. |
45
45
  | 5 | App bootstrap and config | outside `<rootFolder>/{bounded-contexts,shared-kernel,presentation}/`: entry point, HTTP server setup registering `restHandlers`, tool configs | Bootstrapping only. Domain/application/infrastructure logic never goes there. |
46
46
 
@@ -131,7 +131,7 @@ All support `dryRun` and `overwrite`. Use CLI moves even for a rename or folder
131
131
 
132
132
  ## Svelte operations: df-svelte
133
133
 
134
- With `frontend.svelte` configured, `df-svelte` takes the same operations and fields as `df-react` for `<rootFolder>/presentation/svelte/`; `--describe` lists modules as `svelteModules`. Svelte and SvelteKit use the same operations. With SvelteKit, `page` also creates `src/routes/<name>/+page.svelte`, and `moveRoute` / `deleteRoute` apply to that route folder. Stories follow `frontend.svelte.storybookFramework`. Generated files: `df-ps-svelte/references/generators.md`.
134
+ With `frontend.svelte` configured, `df-svelte` takes the same operations and fields as `df-react` for `<rootFolder>/presentation/svelte/`, except that Svelte has shared models, not hooks: `shared-model`, `move-shared-model` and `delete-shared-model` (`shared/model/create-<name>.svelte.ts`, `create<Name>`; a leading `create-` is dropped) replace the `shared-hook` operations, which `df-svelte` rejects with `INVALID_REQUEST`. `--describe` lists modules as `svelteModules`, shared models with kind `model`. Svelte and SvelteKit use the same operations. With SvelteKit, `page` also creates `src/routes/<name>/+page.svelte`, and `moveRoute` / `deleteRoute` apply to that route folder. Stories follow `frontend.svelte.storybookFramework`. Generated files: `df-ps-svelte/references/generators.md`.
135
135
 
136
136
  ## Integrations: df-integration
137
137
 
@@ -148,7 +148,7 @@ Use `operation: "add"` and a nonempty `integrations` array. Select only IDs mark
148
148
  | `playwright` | No extra integration-specific fields. Adds its config, example and scripts. |
149
149
  | `testcontainers` | Backend required. With wire: optional `integrationTestTypes`, the saved primary types whose implementations get integration specs (omitted: the configured list stays); missing specs of existing primary implementations are added. Reads staged Prisma/Drizzle/Vitest setup when selected together. Database scripts are generated, not executed. |
150
150
  | `openapi` | Backend with `handlers-rest`. `routePrefix` defaults to `/api`; `openapiPath` is computed from the project unless supplied. `withExtractor` defaults to true. `swaggerPage` applies only with React or Svelte configured and defaults to true there; otherwise omit it. With Svelte it is `swagger-page.svelte` (route `src/routes/swagger/+page.svelte` with SvelteKit), and `openapiPath` defaults to `static/openapi.json` with SvelteKit. |
151
- | `orval` | Requires configured `handlers-rest`. `openapiPath` is read from the staged/existing OpenAPI generator when omitted. With React or Svelte configured, `targets` can be a nonempty list of `hooks`/`client` and defaults to `hooks` (React Query or Svelte Query hooks; with SvelteKit, a missing `src/routes/+layout.svelte` is created with `QueryProvider`). Without a frontend, omit `targets`: the typed client is generated automatically. |
151
+ | `orval` | Requires configured `handlers-rest`. `openapiPath` is read from the staged/existing OpenAPI generator when omitted. With React or Svelte configured, `targets` can be a nonempty list of `hooks`/`client` and defaults to `hooks` (React Query hooks, or Svelte Query `createQuery`/`createMutation`; with SvelteKit, a missing `src/routes/+layout.svelte` is created with `QueryProvider`). Without a frontend, omit `targets`: the typed client is generated automatically. |
152
152
 
153
153
  Fields for integrations not selected, or for conditions that do not apply, must be omitted. For example, `targets` on a non-React project and `nextAdapter` on an explicitly React project are unused parameters. If OpenAPI and Orval are selected together, a supplied `openapiPath` applies to both.
154
154
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: df-ps-svelte
3
- description: Build the Svelte part of a Domain-First project with the `df-svelte` CLI (@domain-first/project-structure) — choose between pages, widgets (separated UI, headless, monolithic), UI-kit components and shared hooks (Svelte 5 runes), generate them with Storybook stories and SvelteKit routes, move, rename or delete them, and implement them against the backend without importing bounded contexts. Use when the project has domain-first.project-structure.config.json with frontend.svelte configured and the user asks for screens, UI blocks, components, runes/hooks or stories, or to move, rename or regroup a page or widget.
3
+ description: Build the Svelte part of a Domain-First project with the `df-svelte` CLI (@domain-first/project-structure) — choose between pages, widgets (separated UI, headless, monolithic), UI-kit components and shared models (Svelte 5 runes, `create…` factories), generate them with Storybook stories and SvelteKit routes, move, rename or delete them, and implement them against the backend without importing bounded contexts. Use when the project has domain-first.project-structure.config.json with frontend.svelte configured and the user asks for screens, UI blocks, components, runes, reusable reactive logic or stories, or to move, rename or regroup a page or widget.
4
4
  ---
5
5
 
6
6
  # Svelte modules with df-svelte
@@ -11,15 +11,15 @@ Svelte modules live in `<rootFolder>/presentation/svelte/` (`…/svelte/` below)
11
11
 
12
12
  1. Read `domain-first.project-structure.config.json`: source root is `project.rootFolder`; Svelte is enabled by `frontend.svelte`; `frontend.svelte.framework` is `svelte` or `sveltekit`, and both use `df-svelte`. Stories use `frontend.svelte.storybookFramework` (`@storybook/svelte-vite` or `@storybook/sveltekit`). A config of an earlier major version (`CONFIG_OUTDATED`): ask the user to run `npx df-upgrade`; never run it yourself. Without the config, tell the user to run `npx df-init`; without Svelte configured, tell them to run `npx df-init --section frontend`. Initialization and configuration belong to the human: do not run `df-init` or edit these settings yourself.
13
13
  2. A feature that also needs backend work → plan it with `df-ps-plan-feature`; Svelte runs come last in the plan.
14
- 3. Choose a module for each piece of UI by "Choosing the module" of `df-ps-react`: page, widget, UI-kit component, shared hook. Widgets never import each other; the widget type defaults to `with separated ui`.
14
+ 3. Choose a module for each piece of UI by "Choosing the module" of `df-ps-react`: page, widget, UI-kit component, shared model (React's shared hook: Svelte has no hooks). Widgets never import each other; the widget type defaults to `with separated ui`.
15
15
  4. Show the work plan in the format of `df-ps-scaffold/references/work-plan.md` (the frontend block, `df-svelte` runs) and **stop until it's approved**. Details holds the widget type and, for a page move or delete with SvelteKit, whether the route follows.
16
- 5. Run the generators with `df-svelte --request` JSON in plan order (shared hooks → UI-kit → widgets → pages); check each output.
16
+ 5. Run the generators with `df-svelte --request` JSON in plan order (shared models → UI-kit → widgets → pages); check each output.
17
17
  6. Implement ("Implementing"), after the backend and the regenerated API client.
18
18
  7. Run `npx df-lint` and the project's svelte-check/lint/tests. Report against the plan.
19
19
 
20
20
  ## Running df-svelte
21
21
 
22
- Prefer `npx df-svelte --describe` and `npx df-svelte --request` JSON. The operations and fields are those of `df-react` (`page`, `widget`, `ui-kit-component`, `shared-hook`, `move-*`, `delete-*`); `--describe` lists current Svelte modules as `svelteModules`. For example:
22
+ Prefer `npx df-svelte --describe` and `npx df-svelte --request` JSON. The operations and fields are those of `df-react` (`page`, `widget`, `ui-kit-component`, `move-*`, `delete-*`), with `shared-model`, `move-shared-model` and `delete-shared-model` in place of the `shared-hook` ones; `--describe` lists current Svelte modules as `svelteModules` (shared models with kind `model`). For example:
23
23
 
24
24
  ```bash
25
25
  npx df-svelte --request '{"operation":"widget","name":"cart","widgetType":"separated"}'
@@ -33,7 +33,7 @@ Moving, renaming and deleting go through df-svelte, never by hand, with an appro
33
33
 
34
34
  Only these (`df-ps-scaffold`, rule 2, exceptions 3–4), for modules generated by df-svelte:
35
35
 
36
- - Widget hooks and UI parts: `…/svelte/widgets/<name>/hooks/**` (`*.svelte.ts` for runes), `ui/**`.
36
+ - Widget UI parts: `…/svelte/widgets/<name>/ui/**`. A widget's own logic stays in its `<script>` (`toUIProps`); no model files next to it.
37
37
  - Support files inside the widget folder or `ui-kit/<name>/`: styles, assets, `*.test.ts`, `*.stories.ts`. A missing UI-kit or widget UI story: exactly from "Story templates" in `references/generators.md`.
38
38
  - A page stays one `.svelte` file that composes widgets; its `<style>` block lays out its widgets only. Its own state, UI parts or types mean a widget is missing, so generate it.
39
39
  - SvelteKit route files next to a generated route (`+page.ts`, `+layout.svelte`, `+error.svelte`) for loading and layout; the route's `+page.svelte` only renders the page component.
@@ -41,9 +41,14 @@ Only these (`df-ps-scaffold`, rule 2, exceptions 3–4), for modules generated b
41
41
  ## Implementing
42
42
 
43
43
  - Svelte 5 with runes: props through `$props()`, state through `$state`, derived values through `$derived`. Each component exports its props type from `<script lang="ts" module>`.
44
- - Separated UI widget: state, effects and derived data in `hooks/use-<name>-ui-model.svelte.ts` (props → UI props). Return getters (or `$derived` values behind getters) so `{...uiModel}` stays reactive; `ui/` stays presentational. Headless: the same hook, and the consumer passes `UI` (a `Component<UIProps>`).
45
- - UI-kit components and shared hooks (`…/svelte/hooks/use-<name>.svelte.ts`): the same limits as in `df-ps-react` — driven only by props or arguments; no API client, no data loading, no imports from widgets, pages or contexts.
46
- - Stories (`frontend.svelte.storybookFramework`): fill `args` of `Default` with valid props and add one story per meaningful state. Keep `meta`, the file name and the title (`UI-kit/N` or `Widgets/N`).
47
- - Talking to the backend: as in `df-ps-react` ("Talking to the backend") — a generated API client first (Orval's Svelte Query hooks in `<rootFolder>/presentation/svelte/data-layer/orval`, or its typed client in `<rootFolder>/presentation/data-layer`; queries need `QueryProvider` from `…/svelte/data-layer/query-provider.svelte` above them, which SvelteKit's root `+layout.svelte` provides), `import type` of endpoint contracts only without one. SvelteKit `+page.ts`/`+page.server.ts` loads call the client, not bounded contexts.
48
-
49
- `npx df-lint` (check `svelte`) reports a widget importing another widget, UI-kit importing widgets, pages or contexts, shared hooks importing UI-kit, widgets, pages or contexts, and Svelte importing contexts beyond the contract types. Fix every finding.
44
+ - Separated UI widget: props → UI props in `toUIProps` of `n-widget.svelte`, rendered as `<NWidgetUI {...toUIProps()} />`; `ui/` stays presentational. Keep it reactive:
45
+ - call `toUIProps()` in the markup only; `const ui = toUIProps()` in `<script>` reads the values once (`state_referenced_locally` warns);
46
+ - local state (`$state`), methods, `$effect`, `getContext`, `createQuery` are declared in the widget's `<script>`; `toUIProps` only returns them: `({ title: props.title, open, toggle })`;
47
+ - heavy computations go to `$derived`: `toUIProps` rebuilds the whole object on any change;
48
+ - no getters, `svelte-ignore` or model files are needed.
49
+ - Headless: the same `toUIProps`, reading `rest` of `let { UI, ...rest } = $props()` (it stays reactive); the consumer passes `UI` (a `Component<UIProps>`).
50
+ - UI-kit components and shared models (`…/svelte/shared/model/create-<name>.svelte.ts`, `create<Name>`): the same limits as in `df-ps-react` — driven only by props or arguments; no API client, no data loading, no imports from widgets, pages or contexts.
51
+ - Stories (`frontend.svelte.storybookFramework`): fill `args` of `Default` with valid props (the generated `// fill required props of …` marks the place; svelte-check fails on empty `args` once a prop is required) and add one story per meaningful state. Keep `meta`, the file name and the title (`UI-kit/N` or `Widgets/N`).
52
+ - Talking to the backend: as in `df-ps-react` ("Talking to the backend") — a generated API client first (Orval's Svelte Query `createQuery`/`createMutation` in `<rootFolder>/presentation/svelte/data-layer/orval`, or its typed client in `<rootFolder>/presentation/data-layer`; queries need `QueryProvider` from `…/svelte/data-layer/query-provider.svelte` above them, which SvelteKit's root `+layout.svelte` provides), `import type` of endpoint contracts only without one. SvelteKit `+page.ts`/`+page.server.ts` loads call the client, not bounded contexts.
53
+
54
+ `npx df-lint` (check `svelte`) reports a widget importing another widget, UI-kit importing widgets, pages or contexts, shared models importing UI-kit, widgets, pages or contexts, and Svelte importing contexts beyond the contract types. Fix every finding.
@@ -12,8 +12,8 @@ Notation: `…/svelte/` = `<rootFolder>/presentation/svelte/`. `n` = the entered
12
12
 
13
13
  `…/svelte/widgets/n/`:
14
14
 
15
- - `with separated ui` (default): `n-widget.svelte`, `types.ts`, `ui/n-widget-ui.svelte`, `hooks/use-n-ui-model.svelte.ts`; with `storybookFramework`: `ui/n-widget-ui.stories.ts` (CSF3: `title: 'Widgets/N'`, `component: NWidgetUI`, story `Default`)
16
- - `headless`: `n-widget.svelte` (renders `<UI {...uiModel} />`), `types.ts` (props include `UI: Component<NWidgetUIProps>`), `hooks/use-n-ui-model.svelte.ts`
15
+ - `with separated ui` (default): `n-widget.svelte`, `types.ts`, `ui/n-widget-ui.svelte`; the widget declares `const toUIProps = (): NWidgetUIProps => ({})` and renders `<NWidgetUI {...toUIProps()} />`; with `storybookFramework`: `ui/n-widget-ui.stories.ts` (CSF3: `title: 'Widgets/N'`, `component: NWidgetUI`, story `Default` with `// fill required props of NWidgetUIProps` above `args: {}`)
16
+ - `headless`: `n-widget.svelte` (`let { UI, ...rest } = $props()`, renders `<UI {...toUIProps()} />`), `types.ts` (props include `UI: Component<NWidgetUIProps>`)
17
17
  - `monolithic`: `n-widget.svelte` (`NWidgetProps`)
18
18
  - every type: `index.ts` (`export { default as NWidget } from './n-widget.svelte'` and the props type)
19
19
 
@@ -23,13 +23,13 @@ Nested names work as in df-react: `admin/panel/users` → `…/widgets/admin/pan
23
23
 
24
24
  `…/svelte/ui-kit/n/`: `n.svelte` (`NProps`), `index.ts` (`export { default as N } from './n.svelte'` and `NProps`), with `storybookFramework`: `n.stories.ts` (`title: 'UI-kit/N'`).
25
25
 
26
- ## New shared hook
26
+ ## New shared model
27
27
 
28
- `…/svelte/hooks/use-n.svelte.ts` (`const useN = () => …`), so it may use runes. A leading `use-` in the name is dropped.
28
+ Operation `shared-model`: `…/svelte/shared/model/create-n.svelte.ts` (`const createN = () => …`), so it may use runes. A leading `create-` in the name is dropped. Svelte has no hooks: in SvelteKit they are `hooks.server.ts`/`hooks.client.ts`.
29
29
 
30
30
  ## Move, rename, delete
31
31
 
32
- As in df-react: files, `<Name>Page` / `<Name>Widget…` / `use<Name>UIModel` / `<Name>` / `use<Name>`, story titles and every import (with or without the `.svelte` extension, relative or through `tsconfig` aliases) follow a move; a delete is refused while other files import the module. With SvelteKit, the page's own route folder files move or are deleted too when confirmed.
32
+ As in df-react: files, `<Name>Page` / `<Name>Widget…` / `<Name>` / `create<Name>`, story titles and every import (with or without the `.svelte` extension, relative or through `tsconfig` aliases) follow a move; a delete is refused while other files import the module. With SvelteKit, the page's own route folder files move or are deleted too when confirmed.
33
33
 
34
34
  ## Story templates
35
35
 
@@ -51,6 +51,7 @@ export default meta;
51
51
  type Story = StoryObj<typeof meta>;
52
52
 
53
53
  export const Default: Story = {
54
+ // fill required props of NProps
54
55
  args: {},
55
56
  };
56
57
  ```