@warlock.js/core 5.7.0 → 5.8.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 (38) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/esm/cli/cli-commands.manager.mjs +2 -2
  3. package/esm/cli/cli-commands.manager.mjs.map +1 -1
  4. package/esm/cli/commands/doctor/checks/index.mjs +2 -0
  5. package/esm/cli/commands/doctor/checks/index.mjs.map +1 -1
  6. package/esm/cli/commands/doctor/checks/jwt-secret.check.mjs +55 -0
  7. package/esm/cli/commands/doctor/checks/jwt-secret.check.mjs.map +1 -0
  8. package/esm/cli/commands/generate/generators/controller.generator.mjs +4 -4
  9. package/esm/cli/commands/generate/generators/controller.generator.mjs.map +1 -1
  10. package/esm/cli/commands/generate/generators/migration.generator.mjs.map +1 -1
  11. package/esm/cli/commands/generate/generators/model.generator.mjs +4 -4
  12. package/esm/cli/commands/generate/generators/model.generator.mjs.map +1 -1
  13. package/esm/cli/commands/generate/generators/module.generator.mjs.map +1 -1
  14. package/esm/cli/commands/generate/generators/repository.generator.mjs +4 -4
  15. package/esm/cli/commands/generate/generators/repository.generator.mjs.map +1 -1
  16. package/esm/cli/commands/generate/generators/resource.generator.mjs +4 -4
  17. package/esm/cli/commands/generate/generators/resource.generator.mjs.map +1 -1
  18. package/esm/cli/commands/generate/generators/service.generator.mjs +4 -4
  19. package/esm/cli/commands/generate/generators/service.generator.mjs.map +1 -1
  20. package/esm/cli/commands/generate/templates/stubs.mjs +6 -3
  21. package/esm/cli/commands/generate/templates/stubs.mjs.map +1 -1
  22. package/esm/dev-server/files-orchestrator.mjs +1 -0
  23. package/esm/dev-server/files-orchestrator.mjs.map +1 -1
  24. package/esm/generations/stubs.mjs +6 -6
  25. package/esm/generations/stubs.mjs.map +1 -1
  26. package/esm/http/boot-port-preflight.d.mts +25 -1
  27. package/esm/http/boot-port-preflight.d.mts.map +1 -1
  28. package/esm/http/boot-port-preflight.mjs +51 -2
  29. package/esm/http/boot-port-preflight.mjs.map +1 -1
  30. package/esm/http/index.d.mts +1 -1
  31. package/esm/http/index.mjs +1 -1
  32. package/esm/index.d.mts +2 -2
  33. package/esm/index.mjs +2 -2
  34. package/esm/utils/load-environment.mjs +4 -1
  35. package/esm/utils/load-environment.mjs.map +1 -1
  36. package/esm/utils/recorded-environment-overrides.mjs +41 -0
  37. package/esm/utils/recorded-environment-overrides.mjs.map +1 -0
  38. package/package.json +12 -12
@@ -1 +1 @@
1
- {"version":3,"file":"repository.generator.mjs","names":[],"sources":["../../../../../../../../../../core/src/cli/commands/generate/generators/repository.generator.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport type { CommandActionData } from \"../../../../commands/types\";\r\nimport { repositoryStub } from \"../templates/stubs\";\r\nimport { putFileAsync, setDryRun } from \"../utils/writer\";\r\nimport { parseModulePath, parseName } from \"../utils/name-parser\";\r\nimport {\r\n componentExists,\r\n ensureComponentDirectory,\r\n moduleExists,\r\n resolveComponentPath,\r\n} from \"../utils/path-resolver\";\r\n\r\nexport async function generateRepository(data: CommandActionData): Promise<void> {\r\n const input = data.args[0];\r\n\r\n if (!input) {\r\n console.log(colors.red(\"Error: Repository name is required\"));\r\n console.log(colors.yellow(\"Usage: warlock create.repository <module>/<name>\"));\r\n console.log(colors.yellow(\"Example: warlock create.repository users/user\"));\r\n process.exit(1);\r\n }\r\n\r\n const { module, name: componentName } = parseModulePath(input);\r\n\r\n if (!module) {\r\n console.log(colors.red(\"Error: Module name is required\"));\r\n console.log(colors.yellow(\"Usage: warlock create.repository <module>/<name>\"));\r\n process.exit(1);\r\n }\r\n\r\n // Check if module exists\r\n if (!(await moduleExists(module))) {\r\n console.log(colors.red(`Error: Module \"${module}\" does not exist`));\r\n console.log(colors.yellow(`Run: warlock create.module ${module}`));\r\n process.exit(1);\r\n }\r\n\r\n const name = parseName(componentName);\r\n const force = data.options.force || data.options.f;\r\n setDryRun(Boolean(data.options.dryRun));\r\n\r\n // Check if repository already exists\r\n if ((await componentExists(module, \"repositories\", `${name.kebab}.repository`)) && !force) {\r\n console.log(colors.red(`Error: Repository \"${name.kebab}.repository.ts\" already exists`));\r\n console.log(colors.yellow(\"Use --force to overwrite\"));\r\n process.exit(1);\r\n }\r\n\r\n // Ensure directories exist\r\n await ensureComponentDirectory(module, \"repositories\");\r\n\r\n // Generate repository\r\n const repositoryPath = resolveComponentPath(module, \"repositories\", `${name.kebab}.repository`);\r\n const repositoryContent = repositoryStub(name);\r\n\r\n await putFileAsync(repositoryPath, repositoryContent);\r\n\r\n console.log(colors.cyan(`\\n✨ Repository \"${name.pascal}Repository\" generated successfully!`));\r\n}\r\n"],"mappings":";;;;;;;AAYA,eAAsB,mBAAmB,MAAwC;CAC/E,MAAM,QAAQ,KAAK,KAAK;CAExB,IAAI,CAAC,OAAO;EACV,QAAQ,IAAI,OAAO,IAAI,oCAAoC,CAAC;EAC5D,QAAQ,IAAI,OAAO,OAAO,kDAAkD,CAAC;EAC7E,QAAQ,IAAI,OAAO,OAAO,+CAA+C,CAAC;EAC1E,QAAQ,KAAK,CAAC;CAChB;CAEA,MAAM,EAAE,QAAQ,MAAM,kBAAkB,gBAAgB,KAAK;CAE7D,IAAI,CAAC,QAAQ;EACX,QAAQ,IAAI,OAAO,IAAI,gCAAgC,CAAC;EACxD,QAAQ,IAAI,OAAO,OAAO,kDAAkD,CAAC;EAC7E,QAAQ,KAAK,CAAC;CAChB;CAGA,IAAI,CAAE,MAAM,aAAa,MAAM,GAAI;EACjC,QAAQ,IAAI,OAAO,IAAI,kBAAkB,OAAO,iBAAiB,CAAC;EAClE,QAAQ,IAAI,OAAO,OAAO,8BAA8B,QAAQ,CAAC;EACjE,QAAQ,KAAK,CAAC;CAChB;CAEA,MAAM,OAAO,UAAU,aAAa;CACpC,MAAM,QAAQ,KAAK,QAAQ,SAAS,KAAK,QAAQ;CACjD,UAAU,QAAQ,KAAK,QAAQ,MAAM,CAAC;CAGtC,IAAK,MAAM,gBAAgB,QAAQ,gBAAgB,GAAG,KAAK,MAAM,YAAY,KAAM,CAAC,OAAO;EACzF,QAAQ,IAAI,OAAO,IAAI,sBAAsB,KAAK,MAAM,+BAA+B,CAAC;EACxF,QAAQ,IAAI,OAAO,OAAO,0BAA0B,CAAC;EACrD,QAAQ,KAAK,CAAC;CAChB;CAGA,MAAM,yBAAyB,QAAQ,cAAc;CAMrD,MAAM,aAHiB,qBAAqB,QAAQ,gBAAgB,GAAG,KAAK,MAAM,YAGlD,GAFN,eAAe,IAEU,CAAC;CAEpD,QAAQ,IAAI,OAAO,KAAK,qBAAqB,KAAK,OAAO,oCAAoC,CAAC;AAChG"}
1
+ {"version":3,"file":"repository.generator.mjs","names":[],"sources":["../../../../../../../../../../core/src/cli/commands/generate/generators/repository.generator.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport type { CommandActionData } from \"../../../../commands/types\";\nimport { repositoryStub } from \"../templates/stubs\";\nimport { putFileAsync, setDryRun } from \"../utils/writer\";\nimport { parseModulePath, parseName } from \"../utils/name-parser\";\nimport {\n componentExists,\n ensureComponentDirectory,\n moduleExists,\n resolveComponentPath,\n} from \"../utils/path-resolver\";\n\nexport async function generateRepository(data: CommandActionData): Promise<void> {\n const input = data.args[0];\n\n if (!input) {\n console.log(colors.red(\"Error: Repository name is required\"));\n console.log(colors.yellow(\"Usage: warlock generate.repository <module>/<name>\"));\n console.log(colors.yellow(\"Example: warlock generate.repository users/user\"));\n process.exit(1);\n }\n\n const { module, name: componentName } = parseModulePath(input);\n\n if (!module) {\n console.log(colors.red(\"Error: Module name is required\"));\n console.log(colors.yellow(\"Usage: warlock generate.repository <module>/<name>\"));\n process.exit(1);\n }\n\n // Check if module exists\n if (!(await moduleExists(module))) {\n console.log(colors.red(`Error: Module \"${module}\" does not exist`));\n console.log(colors.yellow(`Run: warlock generate.module ${module}`));\n process.exit(1);\n }\n\n const name = parseName(componentName);\n const force = data.options.force || data.options.f;\n setDryRun(Boolean(data.options.dryRun));\n\n // Check if repository already exists\n if ((await componentExists(module, \"repositories\", `${name.kebab}.repository`)) && !force) {\n console.log(colors.red(`Error: Repository \"${name.kebab}.repository.ts\" already exists`));\n console.log(colors.yellow(\"Use --force to overwrite\"));\n process.exit(1);\n }\n\n // Ensure directories exist\n await ensureComponentDirectory(module, \"repositories\");\n\n // Generate repository\n const repositoryPath = resolveComponentPath(module, \"repositories\", `${name.kebab}.repository`);\n const repositoryContent = repositoryStub(name);\n\n await putFileAsync(repositoryPath, repositoryContent);\n\n console.log(colors.cyan(`\\n✨ Repository \"${name.pascal}Repository\" generated successfully!`));\n}\n"],"mappings":";;;;;;;AAYA,eAAsB,mBAAmB,MAAwC;CAC/E,MAAM,QAAQ,KAAK,KAAK;CAExB,IAAI,CAAC,OAAO;EACV,QAAQ,IAAI,OAAO,IAAI,oCAAoC,CAAC;EAC5D,QAAQ,IAAI,OAAO,OAAO,oDAAoD,CAAC;EAC/E,QAAQ,IAAI,OAAO,OAAO,iDAAiD,CAAC;EAC5E,QAAQ,KAAK,CAAC;CAChB;CAEA,MAAM,EAAE,QAAQ,MAAM,kBAAkB,gBAAgB,KAAK;CAE7D,IAAI,CAAC,QAAQ;EACX,QAAQ,IAAI,OAAO,IAAI,gCAAgC,CAAC;EACxD,QAAQ,IAAI,OAAO,OAAO,oDAAoD,CAAC;EAC/E,QAAQ,KAAK,CAAC;CAChB;CAGA,IAAI,CAAE,MAAM,aAAa,MAAM,GAAI;EACjC,QAAQ,IAAI,OAAO,IAAI,kBAAkB,OAAO,iBAAiB,CAAC;EAClE,QAAQ,IAAI,OAAO,OAAO,gCAAgC,QAAQ,CAAC;EACnE,QAAQ,KAAK,CAAC;CAChB;CAEA,MAAM,OAAO,UAAU,aAAa;CACpC,MAAM,QAAQ,KAAK,QAAQ,SAAS,KAAK,QAAQ;CACjD,UAAU,QAAQ,KAAK,QAAQ,MAAM,CAAC;CAGtC,IAAK,MAAM,gBAAgB,QAAQ,gBAAgB,GAAG,KAAK,MAAM,YAAY,KAAM,CAAC,OAAO;EACzF,QAAQ,IAAI,OAAO,IAAI,sBAAsB,KAAK,MAAM,+BAA+B,CAAC;EACxF,QAAQ,IAAI,OAAO,OAAO,0BAA0B,CAAC;EACrD,QAAQ,KAAK,CAAC;CAChB;CAGA,MAAM,yBAAyB,QAAQ,cAAc;CAMrD,MAAM,aAHiB,qBAAqB,QAAQ,gBAAgB,GAAG,KAAK,MAAM,YAGlD,GAFN,eAAe,IAEU,CAAC;CAEpD,QAAQ,IAAI,OAAO,KAAK,qBAAqB,KAAK,OAAO,oCAAoC,CAAC;AAChG"}
@@ -9,19 +9,19 @@ async function generateResource(data) {
9
9
  const input = data.args[0];
10
10
  if (!input) {
11
11
  console.log(colors.red("Error: Resource name is required"));
12
- console.log(colors.yellow("Usage: warlock create.resource <module>/<name>"));
13
- console.log(colors.yellow("Example: warlock create.resource users/user"));
12
+ console.log(colors.yellow("Usage: warlock generate.resource <module>/<name>"));
13
+ console.log(colors.yellow("Example: warlock generate.resource users/user"));
14
14
  process.exit(1);
15
15
  }
16
16
  const { module, name: componentName } = parseModulePath(input);
17
17
  if (!module) {
18
18
  console.log(colors.red("Error: Module name is required"));
19
- console.log(colors.yellow("Usage: warlock create.resource <module>/<name>"));
19
+ console.log(colors.yellow("Usage: warlock generate.resource <module>/<name>"));
20
20
  process.exit(1);
21
21
  }
22
22
  if (!await moduleExists(module)) {
23
23
  console.log(colors.red(`Error: Module "${module}" does not exist`));
24
- console.log(colors.yellow(`Run: warlock create.module ${module}`));
24
+ console.log(colors.yellow(`Run: warlock generate.module ${module}`));
25
25
  process.exit(1);
26
26
  }
27
27
  const name = parseName(componentName);
@@ -1 +1 @@
1
- {"version":3,"file":"resource.generator.mjs","names":[],"sources":["../../../../../../../../../../core/src/cli/commands/generate/generators/resource.generator.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport type { CommandActionData } from \"../../../../commands/types\";\r\nimport { resourceStub } from \"../templates/stubs\";\r\nimport { putFileAsync, setDryRun } from \"../utils/writer\";\r\nimport { parseModulePath, parseName } from \"../utils/name-parser\";\r\nimport {\r\n componentExists,\r\n ensureComponentDirectory,\r\n moduleExists,\r\n resolveComponentPath,\r\n} from \"../utils/path-resolver\";\r\n\r\nexport async function generateResource(data: CommandActionData): Promise<void> {\r\n const input = data.args[0];\r\n\r\n if (!input) {\r\n console.log(colors.red(\"Error: Resource name is required\"));\r\n console.log(colors.yellow(\"Usage: warlock create.resource <module>/<name>\"));\r\n console.log(colors.yellow(\"Example: warlock create.resource users/user\"));\r\n process.exit(1);\r\n }\r\n\r\n const { module, name: componentName } = parseModulePath(input);\r\n\r\n if (!module) {\r\n console.log(colors.red(\"Error: Module name is required\"));\r\n console.log(colors.yellow(\"Usage: warlock create.resource <module>/<name>\"));\r\n process.exit(1);\r\n }\r\n\r\n // Check if module exists\r\n if (!(await moduleExists(module))) {\r\n console.log(colors.red(`Error: Module \"${module}\" does not exist`));\r\n console.log(colors.yellow(`Run: warlock create.module ${module}`));\r\n process.exit(1);\r\n }\r\n\r\n const name = parseName(componentName);\r\n const force = data.options.force || data.options.f;\r\n setDryRun(Boolean(data.options.dryRun));\r\n\r\n // Check if resource already exists\r\n if ((await componentExists(module, \"resources\", `${name.kebab}.resource`)) && !force) {\r\n console.log(colors.red(`Error: Resource \"${name.kebab}.resource.ts\" already exists`));\r\n console.log(colors.yellow(\"Use --force to overwrite\"));\r\n process.exit(1);\r\n }\r\n\r\n // Ensure directories exist\r\n await ensureComponentDirectory(module, \"resources\");\r\n\r\n // Generate resource\r\n const resourcePath = resolveComponentPath(module, \"resources\", `${name.kebab}.resource`);\r\n const resourceContent = resourceStub(name);\r\n\r\n await putFileAsync(resourcePath, resourceContent);\r\n\r\n console.log(colors.cyan(`\\n✨ Resource \"${name.pascal}Resource\" generated successfully!`));\r\n}\r\n"],"mappings":";;;;;;;AAYA,eAAsB,iBAAiB,MAAwC;CAC7E,MAAM,QAAQ,KAAK,KAAK;CAExB,IAAI,CAAC,OAAO;EACV,QAAQ,IAAI,OAAO,IAAI,kCAAkC,CAAC;EAC1D,QAAQ,IAAI,OAAO,OAAO,gDAAgD,CAAC;EAC3E,QAAQ,IAAI,OAAO,OAAO,6CAA6C,CAAC;EACxE,QAAQ,KAAK,CAAC;CAChB;CAEA,MAAM,EAAE,QAAQ,MAAM,kBAAkB,gBAAgB,KAAK;CAE7D,IAAI,CAAC,QAAQ;EACX,QAAQ,IAAI,OAAO,IAAI,gCAAgC,CAAC;EACxD,QAAQ,IAAI,OAAO,OAAO,gDAAgD,CAAC;EAC3E,QAAQ,KAAK,CAAC;CAChB;CAGA,IAAI,CAAE,MAAM,aAAa,MAAM,GAAI;EACjC,QAAQ,IAAI,OAAO,IAAI,kBAAkB,OAAO,iBAAiB,CAAC;EAClE,QAAQ,IAAI,OAAO,OAAO,8BAA8B,QAAQ,CAAC;EACjE,QAAQ,KAAK,CAAC;CAChB;CAEA,MAAM,OAAO,UAAU,aAAa;CACpC,MAAM,QAAQ,KAAK,QAAQ,SAAS,KAAK,QAAQ;CACjD,UAAU,QAAQ,KAAK,QAAQ,MAAM,CAAC;CAGtC,IAAK,MAAM,gBAAgB,QAAQ,aAAa,GAAG,KAAK,MAAM,UAAU,KAAM,CAAC,OAAO;EACpF,QAAQ,IAAI,OAAO,IAAI,oBAAoB,KAAK,MAAM,6BAA6B,CAAC;EACpF,QAAQ,IAAI,OAAO,OAAO,0BAA0B,CAAC;EACrD,QAAQ,KAAK,CAAC;CAChB;CAGA,MAAM,yBAAyB,QAAQ,WAAW;CAMlD,MAAM,aAHe,qBAAqB,QAAQ,aAAa,GAAG,KAAK,MAAM,UAG/C,GAFN,aAAa,IAEU,CAAC;CAEhD,QAAQ,IAAI,OAAO,KAAK,mBAAmB,KAAK,OAAO,kCAAkC,CAAC;AAC5F"}
1
+ {"version":3,"file":"resource.generator.mjs","names":[],"sources":["../../../../../../../../../../core/src/cli/commands/generate/generators/resource.generator.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport type { CommandActionData } from \"../../../../commands/types\";\nimport { resourceStub } from \"../templates/stubs\";\nimport { putFileAsync, setDryRun } from \"../utils/writer\";\nimport { parseModulePath, parseName } from \"../utils/name-parser\";\nimport {\n componentExists,\n ensureComponentDirectory,\n moduleExists,\n resolveComponentPath,\n} from \"../utils/path-resolver\";\n\nexport async function generateResource(data: CommandActionData): Promise<void> {\n const input = data.args[0];\n\n if (!input) {\n console.log(colors.red(\"Error: Resource name is required\"));\n console.log(colors.yellow(\"Usage: warlock generate.resource <module>/<name>\"));\n console.log(colors.yellow(\"Example: warlock generate.resource users/user\"));\n process.exit(1);\n }\n\n const { module, name: componentName } = parseModulePath(input);\n\n if (!module) {\n console.log(colors.red(\"Error: Module name is required\"));\n console.log(colors.yellow(\"Usage: warlock generate.resource <module>/<name>\"));\n process.exit(1);\n }\n\n // Check if module exists\n if (!(await moduleExists(module))) {\n console.log(colors.red(`Error: Module \"${module}\" does not exist`));\n console.log(colors.yellow(`Run: warlock generate.module ${module}`));\n process.exit(1);\n }\n\n const name = parseName(componentName);\n const force = data.options.force || data.options.f;\n setDryRun(Boolean(data.options.dryRun));\n\n // Check if resource already exists\n if ((await componentExists(module, \"resources\", `${name.kebab}.resource`)) && !force) {\n console.log(colors.red(`Error: Resource \"${name.kebab}.resource.ts\" already exists`));\n console.log(colors.yellow(\"Use --force to overwrite\"));\n process.exit(1);\n }\n\n // Ensure directories exist\n await ensureComponentDirectory(module, \"resources\");\n\n // Generate resource\n const resourcePath = resolveComponentPath(module, \"resources\", `${name.kebab}.resource`);\n const resourceContent = resourceStub(name);\n\n await putFileAsync(resourcePath, resourceContent);\n\n console.log(colors.cyan(`\\n✨ Resource \"${name.pascal}Resource\" generated successfully!`));\n}\n"],"mappings":";;;;;;;AAYA,eAAsB,iBAAiB,MAAwC;CAC7E,MAAM,QAAQ,KAAK,KAAK;CAExB,IAAI,CAAC,OAAO;EACV,QAAQ,IAAI,OAAO,IAAI,kCAAkC,CAAC;EAC1D,QAAQ,IAAI,OAAO,OAAO,kDAAkD,CAAC;EAC7E,QAAQ,IAAI,OAAO,OAAO,+CAA+C,CAAC;EAC1E,QAAQ,KAAK,CAAC;CAChB;CAEA,MAAM,EAAE,QAAQ,MAAM,kBAAkB,gBAAgB,KAAK;CAE7D,IAAI,CAAC,QAAQ;EACX,QAAQ,IAAI,OAAO,IAAI,gCAAgC,CAAC;EACxD,QAAQ,IAAI,OAAO,OAAO,kDAAkD,CAAC;EAC7E,QAAQ,KAAK,CAAC;CAChB;CAGA,IAAI,CAAE,MAAM,aAAa,MAAM,GAAI;EACjC,QAAQ,IAAI,OAAO,IAAI,kBAAkB,OAAO,iBAAiB,CAAC;EAClE,QAAQ,IAAI,OAAO,OAAO,gCAAgC,QAAQ,CAAC;EACnE,QAAQ,KAAK,CAAC;CAChB;CAEA,MAAM,OAAO,UAAU,aAAa;CACpC,MAAM,QAAQ,KAAK,QAAQ,SAAS,KAAK,QAAQ;CACjD,UAAU,QAAQ,KAAK,QAAQ,MAAM,CAAC;CAGtC,IAAK,MAAM,gBAAgB,QAAQ,aAAa,GAAG,KAAK,MAAM,UAAU,KAAM,CAAC,OAAO;EACpF,QAAQ,IAAI,OAAO,IAAI,oBAAoB,KAAK,MAAM,6BAA6B,CAAC;EACpF,QAAQ,IAAI,OAAO,OAAO,0BAA0B,CAAC;EACrD,QAAQ,KAAK,CAAC;CAChB;CAGA,MAAM,yBAAyB,QAAQ,WAAW;CAMlD,MAAM,aAHe,qBAAqB,QAAQ,aAAa,GAAG,KAAK,MAAM,UAG/C,GAFN,aAAa,IAEU,CAAC;CAEhD,QAAQ,IAAI,OAAO,KAAK,mBAAmB,KAAK,OAAO,kCAAkC,CAAC;AAC5F"}
@@ -9,19 +9,19 @@ async function generateService(data) {
9
9
  const input = data.args[0];
10
10
  if (!input) {
11
11
  console.log(colors.red("Error: Service name is required"));
12
- console.log(colors.yellow("Usage: warlock create.service <module>/<name>"));
13
- console.log(colors.yellow("Example: warlock create.service users/create-user"));
12
+ console.log(colors.yellow("Usage: warlock generate.service <module>/<name>"));
13
+ console.log(colors.yellow("Example: warlock generate.service users/create-user"));
14
14
  process.exit(1);
15
15
  }
16
16
  const { module, name: componentName } = parseModulePath(input);
17
17
  if (!module) {
18
18
  console.log(colors.red("Error: Module name is required"));
19
- console.log(colors.yellow("Usage: warlock create.service <module>/<name>"));
19
+ console.log(colors.yellow("Usage: warlock generate.service <module>/<name>"));
20
20
  process.exit(1);
21
21
  }
22
22
  if (!await moduleExists(module)) {
23
23
  console.log(colors.red(`Error: Module "${module}" does not exist`));
24
- console.log(colors.yellow(`Run: warlock create.module ${module}`));
24
+ console.log(colors.yellow(`Run: warlock generate.module ${module}`));
25
25
  process.exit(1);
26
26
  }
27
27
  const name = parseName(componentName);
@@ -1 +1 @@
1
- {"version":3,"file":"service.generator.mjs","names":[],"sources":["../../../../../../../../../../core/src/cli/commands/generate/generators/service.generator.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport type { CommandActionData } from \"../../../../commands/types\";\r\nimport { serviceStub } from \"../templates/stubs\";\r\nimport { putFileAsync, setDryRun } from \"../utils/writer\";\r\nimport { parseModulePath, parseName } from \"../utils/name-parser\";\r\nimport {\r\n componentExists,\r\n ensureComponentDirectory,\r\n moduleExists,\r\n resolveComponentPath,\r\n} from \"../utils/path-resolver\";\r\n\r\nexport async function generateService(data: CommandActionData): Promise<void> {\r\n const input = data.args[0];\r\n\r\n if (!input) {\r\n console.log(colors.red(\"Error: Service name is required\"));\r\n console.log(colors.yellow(\"Usage: warlock create.service <module>/<name>\"));\r\n console.log(colors.yellow(\"Example: warlock create.service users/create-user\"));\r\n process.exit(1);\r\n }\r\n\r\n const { module, name: componentName } = parseModulePath(input);\r\n\r\n if (!module) {\r\n console.log(colors.red(\"Error: Module name is required\"));\r\n console.log(colors.yellow(\"Usage: warlock create.service <module>/<name>\"));\r\n process.exit(1);\r\n }\r\n\r\n // Check if module exists\r\n if (!(await moduleExists(module))) {\r\n console.log(colors.red(`Error: Module \"${module}\" does not exist`));\r\n console.log(colors.yellow(`Run: warlock create.module ${module}`));\r\n process.exit(1);\r\n }\r\n\r\n const name = parseName(componentName);\r\n const force = data.options.force || data.options.f;\r\n setDryRun(Boolean(data.options.dryRun));\r\n\r\n // Check if service already exists\r\n if ((await componentExists(module, \"services\", `${name.kebab}.service`)) && !force) {\r\n console.log(colors.red(`Error: Service \"${name.kebab}.service.ts\" already exists`));\r\n console.log(colors.yellow(\"Use --force to overwrite\"));\r\n process.exit(1);\r\n }\r\n\r\n // Ensure directories exist\r\n await ensureComponentDirectory(module, \"services\");\r\n\r\n // Generate service\r\n const servicePath = resolveComponentPath(module, \"services\", `${name.kebab}.service`);\r\n const serviceContent = serviceStub(name);\r\n\r\n await putFileAsync(servicePath, serviceContent);\r\n\r\n console.log(colors.cyan(`\\n✨ Service \"${name.camel}\" generated successfully!`));\r\n}\r\n"],"mappings":";;;;;;;AAYA,eAAsB,gBAAgB,MAAwC;CAC5E,MAAM,QAAQ,KAAK,KAAK;CAExB,IAAI,CAAC,OAAO;EACV,QAAQ,IAAI,OAAO,IAAI,iCAAiC,CAAC;EACzD,QAAQ,IAAI,OAAO,OAAO,+CAA+C,CAAC;EAC1E,QAAQ,IAAI,OAAO,OAAO,mDAAmD,CAAC;EAC9E,QAAQ,KAAK,CAAC;CAChB;CAEA,MAAM,EAAE,QAAQ,MAAM,kBAAkB,gBAAgB,KAAK;CAE7D,IAAI,CAAC,QAAQ;EACX,QAAQ,IAAI,OAAO,IAAI,gCAAgC,CAAC;EACxD,QAAQ,IAAI,OAAO,OAAO,+CAA+C,CAAC;EAC1E,QAAQ,KAAK,CAAC;CAChB;CAGA,IAAI,CAAE,MAAM,aAAa,MAAM,GAAI;EACjC,QAAQ,IAAI,OAAO,IAAI,kBAAkB,OAAO,iBAAiB,CAAC;EAClE,QAAQ,IAAI,OAAO,OAAO,8BAA8B,QAAQ,CAAC;EACjE,QAAQ,KAAK,CAAC;CAChB;CAEA,MAAM,OAAO,UAAU,aAAa;CACpC,MAAM,QAAQ,KAAK,QAAQ,SAAS,KAAK,QAAQ;CACjD,UAAU,QAAQ,KAAK,QAAQ,MAAM,CAAC;CAGtC,IAAK,MAAM,gBAAgB,QAAQ,YAAY,GAAG,KAAK,MAAM,SAAS,KAAM,CAAC,OAAO;EAClF,QAAQ,IAAI,OAAO,IAAI,mBAAmB,KAAK,MAAM,4BAA4B,CAAC;EAClF,QAAQ,IAAI,OAAO,OAAO,0BAA0B,CAAC;EACrD,QAAQ,KAAK,CAAC;CAChB;CAGA,MAAM,yBAAyB,QAAQ,UAAU;CAMjD,MAAM,aAHc,qBAAqB,QAAQ,YAAY,GAAG,KAAK,MAAM,SAG9C,GAFN,YAAY,IAEU,CAAC;CAE9C,QAAQ,IAAI,OAAO,KAAK,kBAAkB,KAAK,MAAM,0BAA0B,CAAC;AAClF"}
1
+ {"version":3,"file":"service.generator.mjs","names":[],"sources":["../../../../../../../../../../core/src/cli/commands/generate/generators/service.generator.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport type { CommandActionData } from \"../../../../commands/types\";\nimport { serviceStub } from \"../templates/stubs\";\nimport { putFileAsync, setDryRun } from \"../utils/writer\";\nimport { parseModulePath, parseName } from \"../utils/name-parser\";\nimport {\n componentExists,\n ensureComponentDirectory,\n moduleExists,\n resolveComponentPath,\n} from \"../utils/path-resolver\";\n\nexport async function generateService(data: CommandActionData): Promise<void> {\n const input = data.args[0];\n\n if (!input) {\n console.log(colors.red(\"Error: Service name is required\"));\n console.log(colors.yellow(\"Usage: warlock generate.service <module>/<name>\"));\n console.log(colors.yellow(\"Example: warlock generate.service users/create-user\"));\n process.exit(1);\n }\n\n const { module, name: componentName } = parseModulePath(input);\n\n if (!module) {\n console.log(colors.red(\"Error: Module name is required\"));\n console.log(colors.yellow(\"Usage: warlock generate.service <module>/<name>\"));\n process.exit(1);\n }\n\n // Check if module exists\n if (!(await moduleExists(module))) {\n console.log(colors.red(`Error: Module \"${module}\" does not exist`));\n console.log(colors.yellow(`Run: warlock generate.module ${module}`));\n process.exit(1);\n }\n\n const name = parseName(componentName);\n const force = data.options.force || data.options.f;\n setDryRun(Boolean(data.options.dryRun));\n\n // Check if service already exists\n if ((await componentExists(module, \"services\", `${name.kebab}.service`)) && !force) {\n console.log(colors.red(`Error: Service \"${name.kebab}.service.ts\" already exists`));\n console.log(colors.yellow(\"Use --force to overwrite\"));\n process.exit(1);\n }\n\n // Ensure directories exist\n await ensureComponentDirectory(module, \"services\");\n\n // Generate service\n const servicePath = resolveComponentPath(module, \"services\", `${name.kebab}.service`);\n const serviceContent = serviceStub(name);\n\n await putFileAsync(servicePath, serviceContent);\n\n console.log(colors.cyan(`\\n✨ Service \"${name.camel}\" generated successfully!`));\n}\n"],"mappings":";;;;;;;AAYA,eAAsB,gBAAgB,MAAwC;CAC5E,MAAM,QAAQ,KAAK,KAAK;CAExB,IAAI,CAAC,OAAO;EACV,QAAQ,IAAI,OAAO,IAAI,iCAAiC,CAAC;EACzD,QAAQ,IAAI,OAAO,OAAO,iDAAiD,CAAC;EAC5E,QAAQ,IAAI,OAAO,OAAO,qDAAqD,CAAC;EAChF,QAAQ,KAAK,CAAC;CAChB;CAEA,MAAM,EAAE,QAAQ,MAAM,kBAAkB,gBAAgB,KAAK;CAE7D,IAAI,CAAC,QAAQ;EACX,QAAQ,IAAI,OAAO,IAAI,gCAAgC,CAAC;EACxD,QAAQ,IAAI,OAAO,OAAO,iDAAiD,CAAC;EAC5E,QAAQ,KAAK,CAAC;CAChB;CAGA,IAAI,CAAE,MAAM,aAAa,MAAM,GAAI;EACjC,QAAQ,IAAI,OAAO,IAAI,kBAAkB,OAAO,iBAAiB,CAAC;EAClE,QAAQ,IAAI,OAAO,OAAO,gCAAgC,QAAQ,CAAC;EACnE,QAAQ,KAAK,CAAC;CAChB;CAEA,MAAM,OAAO,UAAU,aAAa;CACpC,MAAM,QAAQ,KAAK,QAAQ,SAAS,KAAK,QAAQ;CACjD,UAAU,QAAQ,KAAK,QAAQ,MAAM,CAAC;CAGtC,IAAK,MAAM,gBAAgB,QAAQ,YAAY,GAAG,KAAK,MAAM,SAAS,KAAM,CAAC,OAAO;EAClF,QAAQ,IAAI,OAAO,IAAI,mBAAmB,KAAK,MAAM,4BAA4B,CAAC;EAClF,QAAQ,IAAI,OAAO,OAAO,0BAA0B,CAAC;EACrD,QAAQ,KAAK,CAAC;CAChB;CAGA,MAAM,yBAAyB,QAAQ,UAAU;CAMjD,MAAM,aAHc,qBAAqB,QAAQ,YAAY,GAAG,KAAK,MAAM,SAG9C,GAFN,YAAY,IAEU,CAAC;CAE9C,QAAQ,IAAI,OAAO,KAAK,kBAAkB,KAAK,MAAM,0BAA0B,CAAC;AAClF"}
@@ -214,7 +214,7 @@ export const ${moduleName.singular.pascal}Resource = defineResource({
214
214
  function crudRepositoryStub(entity) {
215
215
  const moduleSingularName = entity.singular;
216
216
  const modulePluralName = entity.plural;
217
- return `import type { FilterRules, TypedRepositoryOptions } from "@warlock.js/core";
217
+ return `import type { FilterRules, RepositoryOptions, TypedRepositoryOptions } from "@warlock.js/core";
218
218
  import { RepositoryManager } from "@warlock.js/core";
219
219
  import { ${moduleSingularName.pascal} } from "../models/${moduleSingularName.kebab}";
220
220
 
@@ -331,13 +331,16 @@ import { ${entity.singular.pascal} } from "../models/${entity.singular.kebab}";
331
331
  export default seeder({
332
332
  name: "Seed ${entity.plural.pascal}",
333
333
  once: true,
334
- enabled: true,
334
+ // Disabled until you fill in the fields below. A generated stub calls
335
+ // create({}) with no data, which fails required-field validation and would
336
+ // abort the whole \`warlock seed\` run. Add the fields, then set this to true.
337
+ enabled: false,
335
338
  run: async ({ track }) => {
336
339
  const total = 10;
337
340
  for (let i = 0; i < total; i++) {
338
341
  track(
339
342
  await ${entity.singular.pascal}.create({
340
- // TODO: Add more fields
343
+ // TODO: Add the model's required fields here, then set enabled: true above.
341
344
  }),
342
345
  );
343
346
  }
@@ -1 +1 @@
1
- {"version":3,"file":"stubs.mjs","names":[],"sources":["../../../../../../../../../../core/src/cli/commands/generate/templates/stubs.ts"],"sourcesContent":["import type { ParsedName } from \"../types\";\nimport { Name } from \"../utils/name-parser\";\n\n/**\n * Controller template stub\n *\n * Controllers default to the guarded handler type since application\n * routes run behind `guarded()`. When `withValidation` is set, the\n * schema's exported type + value are imported directly from the\n * `schema/` folder and bound to the handler — no `requests/` alias.\n */\nexport function controllerStub(\n name: ParsedName,\n options: { withValidation?: boolean } = {},\n): string {\n const { withValidation } = options;\n\n if (!withValidation) {\n return `import { type GuardedRequestHandler } from \"app/auth/requests/guarded.request\";\n\nexport const ${name.camel}Controller: GuardedRequestHandler = async ({ response }) => {\n // TODO: Implement controller logic\n return response.success({});\n};\n`;\n }\n\n return `import { type GuardedRequestHandler } from \"app/auth/requests/guarded.request\";\nimport { type ${name.pascal}Schema, ${name.camel}Schema } from \"../schema/${name.kebab}.schema\";\n\nexport const ${name.camel}Controller: GuardedRequestHandler<${name.pascal}Schema> = async ({\n response,\n}) => {\n // TODO: Implement controller logic\n return response.success({});\n};\n\n${name.camel}Controller.validation = {\n schema: ${name.camel}Schema,\n};\n`;\n}\n\n/**\n * CRUD Create Controller template\n * Note: moduleName is the module (plural), we need singular entity name\n */\nexport function crudCreateControllerStub(moduleName: Name): string {\n return `import { type GuardedRequestHandler } from \"app/auth/requests/guarded.request\";\nimport { type Create${moduleName.pascal}Schema, create${moduleName.pascal}Schema } from \"../schema/create-${moduleName.kebab}.schema\";\nimport { create${moduleName.pascal}Service } from \"../services/create-${moduleName.kebab}.service\";\n\nexport const create${moduleName.pascal}Controller: GuardedRequestHandler<Create${moduleName.pascal}Schema> = async ({\n request,\n response,\n}) => {\n const ${moduleName.camel} = await create${moduleName.pascal}Service(request.validated());\n\n return response.successCreate({\n ${moduleName.camel},\n });\n};\n\ncreate${moduleName.pascal}Controller.validation = {\n schema: create${moduleName.pascal}Schema,\n};\n`;\n}\n\n/**\n * CRUD Update Controller template\n */\nexport function crudUpdateControllerStub(moduleName: Name): string {\n return `import { type GuardedRequestHandler } from \"app/auth/requests/guarded.request\";\nimport { type Update${moduleName.pascal}Schema, update${moduleName.pascal}Schema } from \"../schema/update-${moduleName.kebab}.schema\";\nimport { update${moduleName.pascal}Service } from \"../services/update-${moduleName.kebab}.service\";\n\nexport const update${moduleName.pascal}Controller: GuardedRequestHandler<Update${moduleName.pascal}Schema> = async ({\n request,\n response,\n}) => {\n const ${moduleName.camel} = await update${moduleName.pascal}Service(request.input(\"id\"), request.validated());\n\n return response.success({\n ${moduleName.camel},\n });\n};\n\nupdate${moduleName.pascal}Controller.validation = {\n schema: update${moduleName.pascal}Schema,\n};\n`;\n}\n\n/**\n * CRUD List Controller template\n */\nexport function crudListControllerStub(moduleName: Name): string {\n const plural = moduleName.plural;\n return `import { type GuardedRequestHandler } from \"app/auth/requests/guarded.request\";\nimport { list${plural.pascal}Service } from \"../services/list-${plural.kebab}.service\";\n\nexport const list${plural.pascal}Controller: GuardedRequestHandler = async ({\n request,\n response,\n}) => {\n const { data, pagination } = await list${plural.pascal}Service(request.all());\n\n return response.success({\n data,\n pagination,\n });\n};\n`;\n}\n\n/**\n * CRUD Show/Get Controller template\n */\nexport function crudShowControllerStub(moduleName: Name): string {\n return `import { type GuardedRequestHandler } from \"app/auth/requests/guarded.request\";\nimport { get${moduleName.pascal}Service } from \"../services/get-${moduleName.kebab}.service\";\n\nexport const get${moduleName.pascal}Controller: GuardedRequestHandler = async ({\n request,\n response,\n}) => {\n const ${moduleName.camel} = await get${moduleName.pascal}Service(request.input(\"id\"));\n\n if (!${moduleName.camel}) {\n return response.notFound();\n }\n\n return response.success({\n ${moduleName.camel},\n });\n};\n`;\n}\n\n/**\n * CRUD Delete Controller template\n */\nexport function crudDeleteControllerStub(moduleName: Name): string {\n return `import { type GuardedRequestHandler } from \"app/auth/requests/guarded.request\";\nimport { delete${moduleName.pascal}Service } from \"../services/delete-${moduleName.kebab}.service\";\n\nexport const delete${moduleName.pascal}Controller: GuardedRequestHandler = async ({\n request,\n response,\n}) => {\n await delete${moduleName.pascal}Service(request.input(\"id\"));\n\n return response.noContent();\n};\n`;\n}\n\n/**\n * CRUD Routes template\n */\nexport function crudRoutesStub(moduleName: Name): string {\n const singular = moduleName.singular;\n const plural = moduleName.plural;\n\n return `import { router } from \"@warlock.js/core\";\nimport { guarded } from \"app/shared/utils/router\";\nimport { create${singular.pascal}Controller } from \"./controllers/create-${singular.kebab}.controller\";\nimport { delete${singular.pascal}Controller } from \"./controllers/delete-${singular.kebab}.controller\";\nimport { get${singular.pascal}Controller } from \"./controllers/get-${singular.kebab}.controller\";\nimport { list${plural.pascal}Controller } from \"./controllers/list-${plural.kebab}.controller\";\nimport { update${singular.pascal}Controller } from \"./controllers/update-${singular.kebab}.controller\";\n\nguarded(() => {\n router\n .route(\"/${plural.kebab}\")\n .list(list${plural.pascal}Controller)\n .show(get${singular.pascal}Controller)\n .create(create${singular.pascal}Controller)\n .update(update${singular.pascal}Controller)\n .destroy(delete${singular.pascal}Controller);\n});\n`;\n}\n\n/**\n * CRUD Model template\n */\nexport function crudModelStub(moduleName: Name): string {\n const singular = moduleName.singular;\n const plural = moduleName.plural;\n\n return `import { Model, RegisterModel } from \"@warlock.js/cascade\";\nimport { type Infer, v } from \"@warlock.js/seal\";\nimport { ${singular.pascal}Resource } from \"app/${plural.kebab}/resources/${singular.kebab}.resource\";\n\nexport const ${singular.camel}Schema = v.object({\n // TODO: Add more fields\n});\n\nexport type ${singular.pascal}Schema = Infer.Output<typeof ${singular.camel}Schema>;\n\n@RegisterModel()\nexport class ${singular.pascal} extends Model<${singular.pascal}Schema> {\n public static table = \"${plural.snake}\";\n\n public static schema = ${singular.camel}Schema;\n\n public static relations = {};\n\n public static resource = ${singular.pascal}Resource;\n}\n`;\n}\n\n/**\n * CRUD Resource template\n */\nexport function crudResourceStub(moduleName: Name): string {\n // Get singular entity name\n const entity = moduleName.singular;\n\n return `import { defineResource } from \"@warlock.js/core\";\n\nexport const ${entity.pascal}Resource = defineResource({\n schema: {\n id: \"number\",\n // TODO: Add more resource fields\n },\n});\n`;\n}\n\n/**\n * CRUD Repository template\n */\nexport function crudRepositoryStub(entity: Name): string {\n const moduleSingularName = entity.singular;\n const modulePluralName = entity.plural;\n return `import type { FilterRules, TypedRepositoryOptions } from \"@warlock.js/core\";\nimport { RepositoryManager } from \"@warlock.js/core\";\nimport { ${moduleSingularName.pascal} } from \"../models/${moduleSingularName.kebab}\";\n\ntype ${moduleSingularName.pascal}ListFilter = {\n // Repository list filters\n};\n\nexport type ${moduleSingularName.pascal}ListOptions = TypedRepositoryOptions<${moduleSingularName.pascal}ListFilter>;\n\nclass ${modulePluralName.pascal}Repository extends RepositoryManager<${moduleSingularName.pascal}, ${moduleSingularName.pascal}ListOptions> {\n public source = ${moduleSingularName.pascal};\n\n public simpleSelectColumns: string[] = [\"id\"];\n\n public filterBy: FilterRules = {\n id: \"=\",\n };\n\n public defaultOptions: RepositoryOptions = {\n orderBy: {\n id: \"desc\",\n },\n };\n}\n\nexport const ${modulePluralName.camel}Repository = new ${modulePluralName.pascal}Repository();\n`;\n}\n\n/**\n * CRUD Create Service template\n */\nexport function crudCreateServiceStub(entity: Name): string {\n const moduleSingularName = entity.singular;\n return `import { ${moduleSingularName.pascal} } from \"../models/${moduleSingularName.kebab}\";\nimport type { Create${moduleSingularName.pascal}Schema } from \"../schema/create-${moduleSingularName.kebab}.schema\";\n\nexport async function create${moduleSingularName.pascal}Service(data: Create${moduleSingularName.pascal}Schema) {\n const ${moduleSingularName.camel} = await ${moduleSingularName.pascal}.create(data);\n return ${moduleSingularName.camel};\n}\n`;\n}\n\n/**\n * CRUD Update Service template\n */\nexport function crudUpdateServiceStub(entity: Name): string {\n const moduleSingularName = entity.singular;\n return `import { ResourceNotFoundError } from \"@warlock.js/core\";\nimport { get${moduleSingularName.pascal}Service } from \"./get-${moduleSingularName.kebab}.service\";\nimport type { Update${moduleSingularName.pascal}Schema } from \"../schema/update-${moduleSingularName.kebab}.schema\";\n\nexport async function update${moduleSingularName.pascal}Service(id: number | string, data: Update${moduleSingularName.pascal}Schema) {\n const ${moduleSingularName.camel} = await get${moduleSingularName.pascal}Service(id);\n\n await ${moduleSingularName.camel}.save({ merge: data });\n return ${moduleSingularName.camel};\n}\n`;\n}\n\n/**\n * CRUD List Service template\n */\nexport function crudListServiceStub(entity: Name): string {\n const modulePluralName = entity.plural;\n return `import { ${modulePluralName.camel}Repository } from \"../repositories/${modulePluralName.kebab}.repository\";\n\nexport async function list${modulePluralName.pascal}Service(filters: any) {\n return ${modulePluralName.camel}Repository.listCached(filters);\n}\n`;\n}\n\n/**\n * CRUD Get Service template\n */\nexport function crudGetServiceStub(entity: Name): string {\n return `import { ${entity.plural.camel}Repository } from \"../repositories/${entity.plural.kebab}.repository\";\nimport { ResourceNotFoundError } from \"@warlock.js/core\";\n\nexport async function get${entity.singular.pascal}Service(id: number | string) {\n const ${entity.singular.camel} = await ${entity.plural.camel}Repository.getCached(id);\n\n if (!${entity.singular.camel}) {\n throw new ResourceNotFoundError(\"${entity.singular.pascal} resource not found!\");\n }\n\n return ${entity.singular.camel};\n}\n`;\n}\n\n/**\n * CRUD Delete Service template\n */\nexport function crudDeleteServiceStub(entity: Name): string {\n const singular = entity.singular;\n return `import { ResourceNotFoundError } from \"@warlock.js/core\";\nimport { get${singular.pascal}Service } from \"./get-${singular.kebab}.service\";\n\nexport async function delete${singular.pascal}Service(id: number | string) {\n const ${singular.camel} = await get${singular.pascal}Service(id);\n if (!${singular.camel}) {\n throw new ResourceNotFoundError(\"${singular.pascal} not found\");\n }\n await ${singular.camel}.destroy();\n}\n`;\n}\n\n/**\n * CRUD Seed template\n */\nexport function crudSeedStub(entity: Name): string {\n return `import { seeder } from \"@warlock.js/core\";\nimport { ${entity.singular.pascal} } from \"../models/${entity.singular.kebab}\";\n\nexport default seeder({\n name: \"Seed ${entity.plural.pascal}\",\n once: true,\n enabled: true,\n run: async ({ track }) => {\n const total = 10;\n for (let i = 0; i < total; i++) {\n track(\n await ${entity.singular.pascal}.create({\n // TODO: Add more fields\n }),\n );\n }\n },\n});\n`;\n}\n\n/**\n * Migration template\n */\n/**\n * Migration Create template\n */\nexport function migrationStub(\n entityName: ParsedName,\n options: {\n columns?: string;\n imports?: string[];\n timestamps?: boolean;\n tableName?: string;\n } = {},\n): string {\n const { columns = \"\", imports = [], timestamps = true } = options;\n\n const allImports = [\"Migration\", ...imports].join(\", \");\n\n let optionsString = \"\";\n if (timestamps === false) {\n optionsString = `, { timestamps: false }`;\n }\n\n return `import { ${allImports} } from \"@warlock.js/cascade\";\nimport { ${entityName.pascal} } from \"../${entityName.kebab}.model\";\n\nexport default Migration.create(${entityName.pascal}, {\n${columns ? columns : \" // add your columns here, id is auto added to the list\"}\n}${optionsString});\n`;\n}\n\n/**\n * Migration Alter template\n */\nexport function migrationAlterStub(\n entityName: ParsedName,\n options: {\n add?: string;\n drop?: string; // stringified array like `\"[\\\"col1\\\", \\\"col2\\\"]\"`\n rename?: string; // stringified object like `{ old: \"new\" }`\n imports?: string[];\n } = {},\n): string {\n const { add = \"\", drop, rename, imports = [] } = options;\n const allImports = [\"Migration\", ...imports].join(\", \");\n\n // Build the schema object dynamically\n const schemaParts: string[] = [];\n\n if (add) {\n schemaParts.push(` add: {\\n${add}\\n },`);\n }\n\n if (drop) {\n schemaParts.push(` drop: ${drop},`);\n }\n\n if (rename) {\n schemaParts.push(` rename: ${rename},`);\n }\n\n return `import { ${allImports} } from \"@warlock.js/cascade\";\nimport { ${entityName.pascal} } from \"../${entityName.kebab}.model\";\n\nexport default Migration.alter(${entityName.pascal}, {\n${schemaParts.join(\"\\n\")}\n});\n`;\n}\n\n/**\n * CRUD Create Schema template\n * Outputs to: schema/create-{entity}.schema.ts\n */\nexport function crudCreateSchemaStub(moduleName: Name): string {\n return `import { type Infer, v } from \"@warlock.js/seal\";\n\nexport const create${moduleName.pascal}Schema = v.object({\n // TODO: Add validation rules\n});\n\nexport type Create${moduleName.pascal}Schema = Infer<typeof create${moduleName.pascal}Schema>;\n`;\n}\n\n/**\n * CRUD Update Schema template\n * Outputs to: schema/update-{entity}.schema.ts\n */\nexport function crudUpdateSchemaStub(moduleName: Name): string {\n return `import { type Infer, v } from \"@warlock.js/seal\";\n\nexport const update${moduleName.pascal}Schema = v.object({\n // TODO: Add validation rules\n});\n\nexport type Update${moduleName.pascal}Schema = Infer<typeof update${moduleName.pascal}Schema>;\n`;\n}\n\n/**\n * Service template stub\n */\nexport function serviceStub(name: Name): string {\n return `export async function ${name.camel}Service(data: any): Promise<any> {\n // TODO: Implement service logic\n throw new Error(\"${name.camel}Service not implemented\");\n}\n`;\n}\n\n/**\n * Schema template stub\n * Outputs to: schema/{name}.schema.ts\n */\nexport function schemaStub(name: Name): string {\n return `import { type Infer, v } from \"@warlock.js/seal\";\n\nexport const ${name.camel}Schema = v.object({\n // TODO: Define validation schema\n});\n\nexport type ${name.pascal}Schema = Infer<typeof ${name.camel}Schema>;\n`;\n}\n\n/**\n * Model template stub\n */\nexport function modelStub(\n name: Name,\n options: { tableName?: string; withResource?: boolean } = {},\n): string {\n const { tableName = `${name.plural.snake}`, withResource } = options;\n\n return `import { Model, type StrictMode } from \"@warlock.js/cascade\";\nimport { v, type Infer } from \"@warlock.js/seal\";\n${withResource ? `import { ${name.singular.pascal}Resource } from \"../../resources/${name.singular.kebab}.resource\";` : \"\"}\n\nconst ${name.singular.camel}Schema = v.object({\n // TODO: Define model schema\n});\n\nexport type ${name.singular.pascal}Type = Infer.Output<typeof ${name.singular.camel}Schema>;\n\nexport class ${name.singular.pascal} extends Model<${name.singular.pascal}Type> {\n public static table = \"${tableName}\";\n public static strictMode: StrictMode = \"fail\";\n${withResource ? ` public static resource = ${name.singular.pascal}Resource;` : \"\"}\n\n public static schema = ${name.singular.camel}Schema;\n\n public static relations = {\n // TODO: Define relations\n };\n}\n`;\n}\n\n/**\n * Repository template stub\n */\nexport function repositoryStub(name: Name): string {\n return `import type { FilterByOptions, RepositoryOptions } from \"@warlock.js/core\";\nimport { RepositoryManager } from \"@warlock.js/core\";\nimport { ${name.singular.pascal} } from \"../models/${name.singular.kebab}\";\n\ntype ${name.singular.pascal}ListFilter = {\n // Repository list filters\n};\n\nexport type ${name.singular.pascal}ListOptions = RepositoryOptions & ${name.singular.pascal}ListFilter;\n\nexport class ${name.plural.pascal}Repository extends RepositoryManager<${name.singular.pascal}, ${name.singular.pascal}ListFilter> {\n public source = ${name.singular.pascal};\n\n protected defaultOptions: RepositoryOptions = this.withDefaultOptions({});\n\n protected filterBy: FilterByOptions = this.withDefaultFilters({\n name: \"like\",\n });\n}\n\nexport const ${name.plural.camel}Repository = new ${name.plural.pascal}Repository();\n`;\n}\n\n/**\n * Resource template stub\n */\nexport function resourceStub(name: Name): string {\n return `import { Resource } from \"@warlock.js/core\";\n\nexport class ${name.singular.pascal}Resource extends Resource {\n public schema = {\n id: \"int\",\n name: \"string\",\n // TODO: Define resource schema\n };\n}\n`;\n}\n"],"mappings":";;;;;;;;;AAWA,SAAgB,eACd,MACA,UAAwC,CAAC,GACjC;CACR,MAAM,EAAE,mBAAmB;CAE3B,IAAI,CAAC,gBACH,OAAO;;eAEI,KAAK,MAAM;;;;;CAOxB,OAAO;gBACO,KAAK,OAAO,UAAU,KAAK,MAAM,2BAA2B,KAAK,MAAM;;eAExE,KAAK,MAAM,oCAAoC,KAAK,OAAO;;;;;;;EAOxE,KAAK,MAAM;YACD,KAAK,MAAM;;;AAGvB;;;;;AAMA,SAAgB,yBAAyB,YAA0B;CACjE,OAAO;sBACa,WAAW,OAAO,gBAAgB,WAAW,OAAO,kCAAkC,WAAW,MAAM;iBAC5G,WAAW,OAAO,qCAAqC,WAAW,MAAM;;qBAEpE,WAAW,OAAO,0CAA0C,WAAW,OAAO;;;;UAIzF,WAAW,MAAM,iBAAiB,WAAW,OAAO;;;MAGxD,WAAW,MAAM;;;;QAIf,WAAW,OAAO;kBACR,WAAW,OAAO;;;AAGpC;;;;AAKA,SAAgB,yBAAyB,YAA0B;CACjE,OAAO;sBACa,WAAW,OAAO,gBAAgB,WAAW,OAAO,kC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O;2BAC/C,UAAU;;EAEnC,eAAe,8BAA8B,KAAK,SAAS,OAAO,aAAa,GAAG;;2BAEzD,KAAK,SAAS,MAAM;;;;;;;AAO/C;;;;AAKA,SAAgB,eAAe,MAAoB;CACjD,OAAO;;WAEE,KAAK,SAAS,OAAO,qBAAqB,KAAK,SAAS,MAAM;;OAElE,KAAK,SAAS,OAAO;;;;cAId,KAAK,SAAS,OAAO,oCAAoC,KAAK,SAAS,OAAO;;eAE7E,KAAK,OAAO,OAAO,uCAAuC,KAAK,SAAS,OAAO,IAAI,KAAK,SAAS,OAAO;oBACnG,KAAK,SAAS,OAAO;;;;;;;;;eAS1B,KAAK,OAAO,MAAM,mBAAmB,KAAK,OAAO,OAAO;;AAEvE;;;;AAKA,SAAgB,aAAa,MAAoB;CAC/C,OAAO;;eAEM,KAAK,SAAS,OAAO;;;;;;;;AAQpC"}
1
+ {"version":3,"file":"stubs.mjs","names":[],"sources":["../../../../../../../../../../core/src/cli/commands/generate/templates/stubs.ts"],"sourcesContent":["import type { ParsedName } from \"../types\";\nimport { Name } from \"../utils/name-parser\";\n\n/**\n * Controller template stub\n *\n * Controllers default to the guarded handler type since application\n * routes run behind `guarded()`. When `withValidation` is set, the\n * schema's exported type + value are imported directly from the\n * `schema/` folder and bound to the handler — no `requests/` alias.\n */\nexport function controllerStub(\n name: ParsedName,\n options: { withValidation?: boolean } = {},\n): string {\n const { withValidation } = options;\n\n if (!withValidation) {\n return `import { type GuardedRequestHandler } from \"app/auth/requests/guarded.request\";\n\nexport const ${name.camel}Controller: GuardedRequestHandler = async ({ response }) => {\n // TODO: Implement controller logic\n return response.success({});\n};\n`;\n }\n\n return `import { type GuardedRequestHandler } from \"app/auth/requests/guarded.request\";\nimport { type ${name.pascal}Schema, ${name.camel}Schema } from \"../schema/${name.kebab}.schema\";\n\nexport const ${name.camel}Controller: GuardedRequestHandler<${name.pascal}Schema> = async ({\n response,\n}) => {\n // TODO: Implement controller logic\n return response.success({});\n};\n\n${name.camel}Controller.validation = {\n schema: ${name.camel}Schema,\n};\n`;\n}\n\n/**\n * CRUD Create Controller template\n * Note: moduleName is the module (plural), we need singular entity name\n */\nexport function crudCreateControllerStub(moduleName: Name): string {\n return `import { type GuardedRequestHandler } from \"app/auth/requests/guarded.request\";\nimport { type Create${moduleName.pascal}Schema, create${moduleName.pascal}Schema } from \"../schema/create-${moduleName.kebab}.schema\";\nimport { create${moduleName.pascal}Service } from \"../services/create-${moduleName.kebab}.service\";\n\nexport const create${moduleName.pascal}Controller: GuardedRequestHandler<Create${moduleName.pascal}Schema> = async ({\n request,\n response,\n}) => {\n const ${moduleName.camel} = await create${moduleName.pascal}Service(request.validated());\n\n return response.successCreate({\n ${moduleName.camel},\n });\n};\n\ncreate${moduleName.pascal}Controller.validation = {\n schema: create${moduleName.pascal}Schema,\n};\n`;\n}\n\n/**\n * CRUD Update Controller template\n */\nexport function crudUpdateControllerStub(moduleName: Name): string {\n return `import { type GuardedRequestHandler } from \"app/auth/requests/guarded.request\";\nimport { type Update${moduleName.pascal}Schema, update${moduleName.pascal}Schema } from \"../schema/update-${moduleName.kebab}.schema\";\nimport { update${moduleName.pascal}Service } from \"../services/update-${moduleName.kebab}.service\";\n\nexport const update${moduleName.pascal}Controller: GuardedRequestHandler<Update${moduleName.pascal}Schema> = async ({\n request,\n response,\n}) => {\n const ${moduleName.camel} = await update${moduleName.pascal}Service(request.input(\"id\"), request.validated());\n\n return response.success({\n ${moduleName.camel},\n });\n};\n\nupdate${moduleName.pascal}Controller.validation = {\n schema: update${moduleName.pascal}Schema,\n};\n`;\n}\n\n/**\n * CRUD List Controller template\n */\nexport function crudListControllerStub(moduleName: Name): string {\n const plural = moduleName.plural;\n return `import { type GuardedRequestHandler } from \"app/auth/requests/guarded.request\";\nimport { list${plural.pascal}Service } from \"../services/list-${plural.kebab}.service\";\n\nexport const list${plural.pascal}Controller: GuardedRequestHandler = async ({\n request,\n response,\n}) => {\n const { data, pagination } = await list${plural.pascal}Service(request.all());\n\n return response.success({\n data,\n pagination,\n });\n};\n`;\n}\n\n/**\n * CRUD Show/Get Controller template\n */\nexport function crudShowControllerStub(moduleName: Name): string {\n return `import { type GuardedRequestHandler } from \"app/auth/requests/guarded.request\";\nimport { get${moduleName.pascal}Service } from \"../services/get-${moduleName.kebab}.service\";\n\nexport const get${moduleName.pascal}Controller: GuardedRequestHandler = async ({\n request,\n response,\n}) => {\n const ${moduleName.camel} = await get${moduleName.pascal}Service(request.input(\"id\"));\n\n if (!${moduleName.camel}) {\n return response.notFound();\n }\n\n return response.success({\n ${moduleName.camel},\n });\n};\n`;\n}\n\n/**\n * CRUD Delete Controller template\n */\nexport function crudDeleteControllerStub(moduleName: Name): string {\n return `import { type GuardedRequestHandler } from \"app/auth/requests/guarded.request\";\nimport { delete${moduleName.pascal}Service } from \"../services/delete-${moduleName.kebab}.service\";\n\nexport const delete${moduleName.pascal}Controller: GuardedRequestHandler = async ({\n request,\n response,\n}) => {\n await delete${moduleName.pascal}Service(request.input(\"id\"));\n\n return response.noContent();\n};\n`;\n}\n\n/**\n * CRUD Routes template\n */\nexport function crudRoutesStub(moduleName: Name): string {\n const singular = moduleName.singular;\n const plural = moduleName.plural;\n\n return `import { router } from \"@warlock.js/core\";\nimport { guarded } from \"app/shared/utils/router\";\nimport { create${singular.pascal}Controller } from \"./controllers/create-${singular.kebab}.controller\";\nimport { delete${singular.pascal}Controller } from \"./controllers/delete-${singular.kebab}.controller\";\nimport { get${singular.pascal}Controller } from \"./controllers/get-${singular.kebab}.controller\";\nimport { list${plural.pascal}Controller } from \"./controllers/list-${plural.kebab}.controller\";\nimport { update${singular.pascal}Controller } from \"./controllers/update-${singular.kebab}.controller\";\n\nguarded(() => {\n router\n .route(\"/${plural.kebab}\")\n .list(list${plural.pascal}Controller)\n .show(get${singular.pascal}Controller)\n .create(create${singular.pascal}Controller)\n .update(update${singular.pascal}Controller)\n .destroy(delete${singular.pascal}Controller);\n});\n`;\n}\n\n/**\n * CRUD Model template\n */\nexport function crudModelStub(moduleName: Name): string {\n const singular = moduleName.singular;\n const plural = moduleName.plural;\n\n return `import { Model, RegisterModel } from \"@warlock.js/cascade\";\nimport { type Infer, v } from \"@warlock.js/seal\";\nimport { ${singular.pascal}Resource } from \"app/${plural.kebab}/resources/${singular.kebab}.resource\";\n\nexport const ${singular.camel}Schema = v.object({\n // TODO: Add more fields\n});\n\nexport type ${singular.pascal}Schema = Infer.Output<typeof ${singular.camel}Schema>;\n\n@RegisterModel()\nexport class ${singular.pascal} extends Model<${singular.pascal}Schema> {\n public static table = \"${plural.snake}\";\n\n public static schema = ${singular.camel}Schema;\n\n public static relations = {};\n\n public static resource = ${singular.pascal}Resource;\n}\n`;\n}\n\n/**\n * CRUD Resource template\n */\nexport function crudResourceStub(moduleName: Name): string {\n // Get singular entity name\n const entity = moduleName.singular;\n\n return `import { defineResource } from \"@warlock.js/core\";\n\nexport const ${entity.pascal}Resource = defineResource({\n schema: {\n id: \"number\",\n // TODO: Add more resource fields\n },\n});\n`;\n}\n\n/**\n * CRUD Repository template\n */\nexport function crudRepositoryStub(entity: Name): string {\n const moduleSingularName = entity.singular;\n const modulePluralName = entity.plural;\n return `import type { FilterRules, RepositoryOptions, TypedRepositoryOptions } from \"@warlock.js/core\";\nimport { RepositoryManager } from \"@warlock.js/core\";\nimport { ${moduleSingularName.pascal} } from \"../models/${moduleSingularName.kebab}\";\n\ntype ${moduleSingularName.pascal}ListFilter = {\n // Repository list filters\n};\n\nexport type ${moduleSingularName.pascal}ListOptions = TypedRepositoryOptions<${moduleSingularName.pascal}ListFilter>;\n\nclass ${modulePluralName.pascal}Repository extends RepositoryManager<${moduleSingularName.pascal}, ${moduleSingularName.pascal}ListOptions> {\n public source = ${moduleSingularName.pascal};\n\n public simpleSelectColumns: string[] = [\"id\"];\n\n public filterBy: FilterRules = {\n id: \"=\",\n };\n\n public defaultOptions: RepositoryOptions = {\n orderBy: {\n id: \"desc\",\n },\n };\n}\n\nexport const ${modulePluralName.camel}Repository = new ${modulePluralName.pascal}Repository();\n`;\n}\n\n/**\n * CRUD Create Service template\n */\nexport function crudCreateServiceStub(entity: Name): string {\n const moduleSingularName = entity.singular;\n return `import { ${moduleSingularName.pascal} } from \"../models/${moduleSingularName.kebab}\";\nimport type { Create${moduleSingularName.pascal}Schema } from \"../schema/create-${moduleSingularName.kebab}.schema\";\n\nexport async function create${moduleSingularName.pascal}Service(data: Create${moduleSingularName.pascal}Schema) {\n const ${moduleSingularName.camel} = await ${moduleSingularName.pascal}.create(data);\n return ${moduleSingularName.camel};\n}\n`;\n}\n\n/**\n * CRUD Update Service template\n */\nexport function crudUpdateServiceStub(entity: Name): string {\n const moduleSingularName = entity.singular;\n return `import { ResourceNotFoundError } from \"@warlock.js/core\";\nimport { get${moduleSingularName.pascal}Service } from \"./get-${moduleSingularName.kebab}.service\";\nimport type { Update${moduleSingularName.pascal}Schema } from \"../schema/update-${moduleSingularName.kebab}.schema\";\n\nexport async function update${moduleSingularName.pascal}Service(id: number | string, data: Update${moduleSingularName.pascal}Schema) {\n const ${moduleSingularName.camel} = await get${moduleSingularName.pascal}Service(id);\n\n await ${moduleSingularName.camel}.save({ merge: data });\n return ${moduleSingularName.camel};\n}\n`;\n}\n\n/**\n * CRUD List Service template\n */\nexport function crudListServiceStub(entity: Name): string {\n const modulePluralName = entity.plural;\n return `import { ${modulePluralName.camel}Repository } from \"../repositories/${modulePluralName.kebab}.repository\";\n\nexport async function list${modulePluralName.pascal}Service(filters: any) {\n return ${modulePluralName.camel}Repository.listCached(filters);\n}\n`;\n}\n\n/**\n * CRUD Get Service template\n */\nexport function crudGetServiceStub(entity: Name): string {\n return `import { ${entity.plural.camel}Repository } from \"../repositories/${entity.plural.kebab}.repository\";\nimport { ResourceNotFoundError } from \"@warlock.js/core\";\n\nexport async function get${entity.singular.pascal}Service(id: number | string) {\n const ${entity.singular.camel} = await ${entity.plural.camel}Repository.getCached(id);\n\n if (!${entity.singular.camel}) {\n throw new ResourceNotFoundError(\"${entity.singular.pascal} resource not found!\");\n }\n\n return ${entity.singular.camel};\n}\n`;\n}\n\n/**\n * CRUD Delete Service template\n */\nexport function crudDeleteServiceStub(entity: Name): string {\n const singular = entity.singular;\n return `import { ResourceNotFoundError } from \"@warlock.js/core\";\nimport { get${singular.pascal}Service } from \"./get-${singular.kebab}.service\";\n\nexport async function delete${singular.pascal}Service(id: number | string) {\n const ${singular.camel} = await get${singular.pascal}Service(id);\n if (!${singular.camel}) {\n throw new ResourceNotFoundError(\"${singular.pascal} not found\");\n }\n await ${singular.camel}.destroy();\n}\n`;\n}\n\n/**\n * CRUD Seed template\n */\nexport function crudSeedStub(entity: Name): string {\n return `import { seeder } from \"@warlock.js/core\";\nimport { ${entity.singular.pascal} } from \"../models/${entity.singular.kebab}\";\n\nexport default seeder({\n name: \"Seed ${entity.plural.pascal}\",\n once: true,\n // Disabled until you fill in the fields below. A generated stub calls\n // create({}) with no data, which fails required-field validation and would\n // abort the whole \\`warlock seed\\` run. Add the fields, then set this to true.\n enabled: false,\n run: async ({ track }) => {\n const total = 10;\n for (let i = 0; i < total; i++) {\n track(\n await ${entity.singular.pascal}.create({\n // TODO: Add the model's required fields here, then set enabled: true above.\n }),\n );\n }\n },\n});\n`;\n}\n\n/**\n * Migration template\n */\n/**\n * Migration Create template\n */\nexport function migrationStub(\n entityName: ParsedName,\n options: {\n columns?: string;\n imports?: string[];\n timestamps?: boolean;\n tableName?: string;\n } = {},\n): string {\n const { columns = \"\", imports = [], timestamps = true } = options;\n\n const allImports = [\"Migration\", ...imports].join(\", \");\n\n let optionsString = \"\";\n if (timestamps === false) {\n optionsString = `, { timestamps: false }`;\n }\n\n return `import { ${allImports} } from \"@warlock.js/cascade\";\nimport { ${entityName.pascal} } from \"../${entityName.kebab}.model\";\n\nexport default Migration.create(${entityName.pascal}, {\n${columns ? columns : \" // add your columns here, id is auto added to the list\"}\n}${optionsString});\n`;\n}\n\n/**\n * Migration Alter template\n */\nexport function migrationAlterStub(\n entityName: ParsedName,\n options: {\n add?: string;\n drop?: string; // stringified array like `\"[\\\"col1\\\", \\\"col2\\\"]\"`\n rename?: string; // stringified object like `{ old: \"new\" }`\n imports?: string[];\n } = {},\n): string {\n const { add = \"\", drop, rename, imports = [] } = options;\n const allImports = [\"Migration\", ...imports].join(\", \");\n\n // Build the schema object dynamically\n const schemaParts: string[] = [];\n\n if (add) {\n schemaParts.push(` add: {\\n${add}\\n },`);\n }\n\n if (drop) {\n schemaParts.push(` drop: ${drop},`);\n }\n\n if (rename) {\n schemaParts.push(` rename: ${rename},`);\n }\n\n return `import { ${allImports} } from \"@warlock.js/cascade\";\nimport { ${entityName.pascal} } from \"../${entityName.kebab}.model\";\n\nexport default Migration.alter(${entityName.pascal}, {\n${schemaParts.join(\"\\n\")}\n});\n`;\n}\n\n/**\n * CRUD Create Schema template\n * Outputs to: schema/create-{entity}.schema.ts\n */\nexport function crudCreateSchemaStub(moduleName: Name): string {\n return `import { type Infer, v } from \"@warlock.js/seal\";\n\nexport const create${moduleName.pascal}Schema = v.object({\n // TODO: Add validation rules\n});\n\nexport type Create${moduleName.pascal}Schema = Infer<typeof create${moduleName.pascal}Schema>;\n`;\n}\n\n/**\n * CRUD Update Schema template\n * Outputs to: schema/update-{entity}.schema.ts\n */\nexport function crudUpdateSchemaStub(moduleName: Name): string {\n return `import { type Infer, v } from \"@warlock.js/seal\";\n\nexport const update${moduleName.pascal}Schema = v.object({\n // TODO: Add validation rules\n});\n\nexport type Update${moduleName.pascal}Schema = Infer<typeof update${moduleName.pascal}Schema>;\n`;\n}\n\n/**\n * Service template stub\n */\nexport function serviceStub(name: Name): string {\n return `export async function ${name.camel}Service(data: any): Promise<any> {\n // TODO: Implement service logic\n throw new Error(\"${name.camel}Service not implemented\");\n}\n`;\n}\n\n/**\n * Schema template stub\n * Outputs to: schema/{name}.schema.ts\n */\nexport function schemaStub(name: Name): string {\n return `import { type Infer, v } from \"@warlock.js/seal\";\n\nexport const ${name.camel}Schema = v.object({\n // TODO: Define validation schema\n});\n\nexport type ${name.pascal}Schema = Infer<typeof ${name.camel}Schema>;\n`;\n}\n\n/**\n * Model template stub\n */\nexport function modelStub(\n name: Name,\n options: { tableName?: string; withResource?: boolean } = {},\n): string {\n const { tableName = `${name.plural.snake}`, withResource } = options;\n\n return `import { Model, type StrictMode } from \"@warlock.js/cascade\";\nimport { v, type Infer } from \"@warlock.js/seal\";\n${withResource ? `import { ${name.singular.pascal}Resource } from \"../../resources/${name.singular.kebab}.resource\";` : \"\"}\n\nconst ${name.singular.camel}Schema = v.object({\n // TODO: Define model schema\n});\n\nexport type ${name.singular.pascal}Type = Infer.Output<typeof ${name.singular.camel}Schema>;\n\nexport class ${name.singular.pascal} extends Model<${name.singular.pascal}Type> {\n public static table = \"${tableName}\";\n public static strictMode: StrictMode = \"fail\";\n${withResource ? ` public static resource = ${name.singular.pascal}Resource;` : \"\"}\n\n public static schema = ${name.singular.camel}Schema;\n\n public static relations = {\n // TODO: Define relations\n };\n}\n`;\n}\n\n/**\n * Repository template stub\n */\nexport function repositoryStub(name: Name): string {\n return `import type { FilterByOptions, RepositoryOptions } from \"@warlock.js/core\";\nimport { RepositoryManager } from \"@warlock.js/core\";\nimport { ${name.singular.pascal} } from \"../models/${name.singular.kebab}\";\n\ntype ${name.singular.pascal}ListFilter = {\n // Repository list filters\n};\n\nexport type ${name.singular.pascal}ListOptions = RepositoryOptions & ${name.singular.pascal}ListFilter;\n\nexport class ${name.plural.pascal}Repository extends RepositoryManager<${name.singular.pascal}, ${name.singular.pascal}ListFilter> {\n public source = ${name.singular.pascal};\n\n protected defaultOptions: RepositoryOptions = this.withDefaultOptions({});\n\n protected filterBy: FilterByOptions = this.withDefaultFilters({\n name: \"like\",\n });\n}\n\nexport const ${name.plural.camel}Repository = new ${name.plural.pascal}Repository();\n`;\n}\n\n/**\n * Resource template stub\n */\nexport function resourceStub(name: Name): string {\n return `import { Resource } from \"@warlock.js/core\";\n\nexport class ${name.singular.pascal}Resource extends Resource {\n public schema = {\n id: \"int\",\n name: \"string\",\n // TODO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K,SAAS,OAAO;;;;;;;;AAQpC"}
@@ -48,6 +48,7 @@ var FilesOrchestrator = class {
48
48
  return this.fileOperations.addFile(relativePath);
49
49
  }
50
50
  async load(relativePath, type = "other") {
51
+ await this.init();
51
52
  const fileManager = await this.add(relativePath);
52
53
  return this.moduleLoader.loadModule(fileManager, fileManager.type || type);
53
54
  }
@@ -1 +1 @@
1
- {"version":3,"file":"files-orchestrator.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/files-orchestrator.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport { init } from \"es-module-lexer\";\r\nimport type { MessagePort } from \"node:worker_threads\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { DependencyGraph } from \"./dependency-graph\";\r\nimport { devLogDim, devLogSuccess } from \"./dev-logger\";\r\nimport { FileEventHandler } from \"./file-event-handler\";\r\nimport { FileManager } from \"./file-manager\";\r\nimport { FileOperations } from \"./file-operations\";\r\nimport { FilesWatcher } from \"./files-watcher\";\r\nimport { FILE_PROCESSING_BATCH_SIZE } from \"./flags\";\r\nimport { EslintHealthChecker } from \"./health-checker/checkers/eslint-health-checker\";\r\nimport { TypescriptHealthChecker } from \"./health-checker/checkers/typescript-health-checker\";\r\nimport type { FileHealthCheckerContract } from \"./health-checker/file-health-checker.contract\";\r\nimport { FilesHealthcareManager } from \"./health-checker/files-healthcare.manager\";\r\nimport { buildTranspileInit } from \"./loader/build-transpile-init.js\";\r\nimport { registerLoader } from \"./loader/register-loader.js\";\r\nimport { ManifestManager } from \"./manifest-manager\";\r\nimport { ModuleLoader } from \"./module-loader\";\r\nimport { packageJsonManager } from \"./package-json-manager\";\r\nimport { Path } from \"../utils/normalized-path\";\r\nimport { SpecialFilesCollector } from \"./special-files-collector\";\r\nimport { tsconfigManager } from \"./tsconfig-manager\";\r\nimport { ensureWarlockDirectory, getFilesFromDirectory } from \"./utils\";\r\n\r\n/**\r\n * Register a cleanup callback that fires before the current module is\r\n * unloaded by HMR. Stack-inspects the caller so user code doesn't need to\r\n * thread the FileManager through.\r\n */\r\nexport function onCleanup(callback: () => any) {\r\n if (globalThis.__currentModuleFile) {\r\n globalThis.__currentModuleFile.addCleanup(callback);\r\n return;\r\n }\r\n\r\n const stack = new Error().stack;\r\n const callerLine = stack?.split(\"\\n\")[2];\r\n const match = callerLine?.match(/\\((.+?):\\d+:\\d+\\)/) || callerLine?.match(/at (.+?):\\d+:\\d+/);\r\n const callerFile = match?.[1];\r\n\r\n if (!callerFile) return;\r\n const fileManager = filesOrchestrator.files.get(Path.toRelative(callerFile));\r\n fileManager?.addCleanup(callback);\r\n}\r\n\r\n/**\r\n * Top-level coordinator for the dev server's file system.\r\n *\r\n * Owns: file discovery, the dependency graph, the manifest, the special-files\r\n * index, the file watcher, and the lifecycle of the ESM loader hook (which\r\n * provides cache-busting via `?v=N` version tokens).\r\n */\r\nexport class FilesOrchestrator {\r\n public readonly filesWatcher = new FilesWatcher();\r\n public readonly files = new Map<string, FileManager>();\r\n private readonly manifest = new ManifestManager(this.files);\r\n private readonly dependencyGraph = new DependencyGraph();\r\n private readonly healthCheckerManager = new FilesHealthcareManager(this.files);\r\n public readonly specialFilesCollector = new SpecialFilesCollector();\r\n public readonly moduleLoader = new ModuleLoader(this.specialFilesCollector);\r\n public readonly fileOperations: FileOperations;\r\n private readonly eventHandler: FileEventHandler;\r\n\r\n /** Main-thread end of the MessageChannel to the loader hook worker. */\r\n private loaderPort: MessagePort | null = null;\r\n\r\n /** Resolve callbacks for pending `flushVersionBumps()` calls. */\r\n private readonly pendingFlushes: Array<() => void> = [];\r\n\r\n public isInitialized = false;\r\n\r\n public constructor() {\r\n this.fileOperations = new FileOperations(\r\n this.files,\r\n this.dependencyGraph,\r\n this.manifest,\r\n this.specialFilesCollector,\r\n );\r\n\r\n this.eventHandler = new FileEventHandler(\r\n this.fileOperations,\r\n this.manifest,\r\n this.dependencyGraph,\r\n this.files,\r\n );\r\n }\r\n\r\n public async add(relativePath: string): Promise<FileManager> {\r\n return this.fileOperations.addFile(relativePath);\r\n }\r\n\r\n public async load<T>(relativePath: string, type = \"other\") {\r\n const fileManager = await this.add(relativePath);\r\n return this.moduleLoader.loadModule<T>(fileManager, fileManager.type || type);\r\n }\r\n\r\n public getDependencyGraph(): DependencyGraph {\r\n return this.dependencyGraph;\r\n }\r\n\r\n public getInvalidationChain(file: string): string[] {\r\n return this.dependencyGraph.getInvalidationChain(file);\r\n }\r\n\r\n public getFiles(): Map<string, FileManager> {\r\n return this.files;\r\n }\r\n\r\n public getHealthCheckerManager(): FilesHealthcareManager {\r\n return this.healthCheckerManager;\r\n }\r\n\r\n /**\r\n * Initialise managers and register the ESM loader hook. Must be called\r\n * before any user `src/` module is dynamically imported.\r\n */\r\n public async init() {\r\n if (this.isInitialized) return;\r\n this.isInitialized = true;\r\n\r\n await init;\r\n await Promise.all([tsconfigManager.init(), packageJsonManager.init()]);\r\n\r\n // The loader hook writes itself into .warlock/, so ensure the dir exists.\r\n await ensureWarlockDirectory();\r\n\r\n const devServerConfig = await warlockConfigManager.lazyGet(\"devServer\");\r\n const transpileInit = buildTranspileInit(\r\n tsconfigManager.tsconfig?.compilerOptions,\r\n devServerConfig?.transpileCacheDebug === true,\r\n );\r\n\r\n this.loaderPort = await registerLoader(transpileInit);\r\n\r\n this.loaderPort.on(\"message\", (msg: { type: string }) => {\r\n if (msg.type === \"sync-ack\") {\r\n this.pendingFlushes.shift()?.();\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Tell the hook worker a file changed. The next `import()` of it will get\r\n * a fresh `?v=N` URL → Node cache miss → fresh content.\r\n */\r\n public bumpVersion(absolutePath: string): void {\r\n this.loaderPort?.postMessage({ type: \"bump\", absolutePath });\r\n }\r\n\r\n /**\r\n * Wait until the hook worker has processed every pending bump.\r\n *\r\n * `postMessage` is async — without this, a follow-up `import()` may\r\n * resolve before the worker increments the counter and Node will return\r\n * the cached old module.\r\n */\r\n public flushVersionBumps(): Promise<void> {\r\n if (!this.loaderPort) return Promise.resolve();\r\n\r\n return new Promise<void>((resolve) => {\r\n this.pendingFlushes.push(resolve);\r\n this.loaderPort!.postMessage({ type: \"sync\" });\r\n });\r\n }\r\n\r\n /**\r\n * Discover files on disk, reconcile against the manifest, build the dep\r\n * graph, and persist the new manifest. Idempotent.\r\n */\r\n public async initializeAll() {\r\n const [filesInFilesystem, manifestExists] = await Promise.all([\r\n this.getAllFilesFromFilesystem(),\r\n this.manifest.init(),\r\n ]);\r\n\r\n if (!manifestExists) {\r\n await this.processFiles(filesInFilesystem);\r\n } else {\r\n await this.reconcileFiles(filesInFilesystem);\r\n }\r\n\r\n this.dependencyGraph.build(this.files);\r\n this.fileOperations.updateFileDependents();\r\n this.fileOperations.syncFilesToManifest();\r\n await this.manifest.save();\r\n }\r\n\r\n public async checkHealth(files: { added: string[]; changed: string[]; deleted: string[] }) {\r\n const filesToCheck = [...files.added, ...files.changed]\r\n .map((file) => this.files.get(Path.toRelative(file)))\r\n .filter((file): file is FileManager => !!file);\r\n\r\n const filesToDelete = files.deleted\r\n .map((file) => this.files.get(Path.toRelative(file)))\r\n .filter((file): file is FileManager => !!file);\r\n\r\n await this.healthCheckerManager.onFileChanges(filesToCheck);\r\n this.healthCheckerManager.removeFiles(filesToDelete);\r\n this.healthCheckerManager.checkFiles(filesToCheck);\r\n }\r\n\r\n public async startCheckingHealth(healthCheckers?: FileHealthCheckerContract[]): Promise<void> {\r\n devLogDim(\"Started File Health Checks in the background.\");\r\n\r\n const checkers = healthCheckers ?? [new TypescriptHealthChecker(), new EslintHealthChecker()];\r\n await this.healthCheckerManager.setHealthCheckers(checkers).initialize();\r\n await this.healthCheckerManager.validateAllFiles();\r\n }\r\n\r\n /**\r\n * Glob the src directory, returning relative paths.\r\n */\r\n public async getAllFilesFromFilesystem(): Promise<string[]> {\r\n const absolutePaths = await getFilesFromDirectory();\r\n return absolutePaths.map((absPath) => Path.toRelative(absPath));\r\n }\r\n\r\n /**\r\n * Process every file from scratch — used when no manifest exists.\r\n */\r\n private async processFiles(filePaths: string[]) {\r\n devLogDim(`processing ${filePaths.length} files...`);\r\n await runInBatches(filePaths, FILE_PROCESSING_BATCH_SIZE, async (relativePath) => {\r\n const fileManager = new FileManager(\r\n Path.toAbsolute(relativePath),\r\n this.files,\r\n this.fileOperations,\r\n );\r\n this.files.set(relativePath, fileManager);\r\n await fileManager.process();\r\n });\r\n devLogSuccess(`processed ${filePaths.length} files`);\r\n }\r\n\r\n private async reconcileFiles(filesInFilesystem: string[]) {\r\n const filesInManifest = new Set(this.manifest.getAllFilePaths());\r\n const filesInFilesystemSet = new Set(filesInFilesystem);\r\n\r\n const newFiles = filesInFilesystem.filter((f) => !filesInManifest.has(f));\r\n const deletedFiles = Array.from(filesInManifest).filter((f) => !filesInFilesystemSet.has(f));\r\n const existingFiles = filesInFilesystem.filter((f) => filesInManifest.has(f));\r\n\r\n if (newFiles.length > 0 || deletedFiles.length > 0) {\r\n devLogDim(\r\n `reconciling: ${colors.green(newFiles.length)} new, ${colors.red(deletedFiles.length)} deleted, ${colors.blue(existingFiles.length)} existing`,\r\n );\r\n }\r\n\r\n await this.processFiles(newFiles);\r\n\r\n for (const relativePath of deletedFiles) {\r\n this.manifest.removeFile(relativePath);\r\n this.files.delete(relativePath);\r\n }\r\n\r\n await runInBatches(existingFiles, FILE_PROCESSING_BATCH_SIZE, async (relativePath) => {\r\n const fileManager = new FileManager(\r\n Path.toAbsolute(relativePath),\r\n this.files,\r\n this.fileOperations,\r\n );\r\n this.files.set(relativePath, fileManager);\r\n await fileManager.init(this.manifest.getFile(relativePath));\r\n });\r\n }\r\n\r\n public async watchFiles() {\n devLogSuccess(\"watching for file changes (not serving yet)\");\n\r\n this.filesWatcher.onFileChange((p) => this.eventHandler.handleFileChange(p));\r\n this.filesWatcher.onFileAdd((p) => this.eventHandler.handleFileAdd(p));\r\n this.filesWatcher.onFileDelete((p) => this.eventHandler.handleFileDelete(p));\r\n\r\n const watchConfig = warlockConfigManager.get(\"devServer\")?.watch;\r\n await this.filesWatcher.watch(watchConfig);\r\n }\r\n}\r\n\r\nasync function runInBatches<T>(\r\n items: T[],\r\n size: number,\r\n fn: (item: T) => Promise<unknown>,\r\n): Promise<void> {\r\n if (items.length === 0) return;\r\n for (let i = 0; i < items.length; i += size) {\r\n await Promise.all(items.slice(i, i + size).map(fn));\r\n }\r\n}\r\n\r\nexport const filesOrchestrator = new FilesOrchestrator();\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,IAAa,oBAAb,MAA+B;CAmB7B,AAAO,cAAc;sBAlBU,IAAI,aAAa;+BACxB,IAAI,IAAyB;kBACzB,IAAI,gBAAgB,KAAK,KAAK;yBACvB,IAAI,gBAAgB;8BACf,IAAI,uBAAuB,KAAK,KAAK;+BACrC,IAAI,sBAAsB;sBACnC,IAAI,aAAa,KAAK,qBAAqB;oBAKjC;wBAGY,CAAC;uBAE/B;EAGrB,KAAK,iBAAiB,IAAI,eACxB,KAAK,OACL,KAAK,iBACL,KAAK,UACL,KAAK,qBACP;EAEA,KAAK,eAAe,IAAI,iBACtB,KAAK,gBACL,KAAK,UACL,KAAK,iBACL,KAAK,KACP;CACF;CAEA,MAAa,IAAI,cAA4C;EAC3D,OAAO,KAAK,eAAe,QAAQ,YAAY;CACjD;CAEA,MAAa,KAAQ,cAAsB,OAAO,SAAS;EACzD,MAAM,cAAc,MAAM,KAAK,IAAI,YAAY;EAC/C,OAAO,KAAK,aAAa,WAAc,aAAa,YAAY,QAAQ,IAAI;CAC9E;CAEA,AAAO,qBAAsC;EAC3C,OAAO,KAAK;CACd;CAEA,AAAO,qBAAqB,MAAwB;EAClD,OAAO,KAAK,gBAAgB,qBAAqB,IAAI;CACvD;CAEA,AAAO,WAAqC;EAC1C,OAAO,KAAK;CACd;CAEA,AAAO,0BAAkD;EACvD,OAAO,KAAK;CACd;;;;;CAMA,MAAa,OAAO;EAClB,IAAI,KAAK,eAAe;EACxB,KAAK,gBAAgB;EAErB,MAAM;EACN,MAAM,Q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AE5E,IAAI,SAAS,SAAS,KAAK,aAAa,SAAS,GAC/C,UACE,gBAAgB,OAAO,MAAM,SAAS,MAAM,EAAE,QAAQ,OAAO,IAAI,aAAa,MAAM,EAAE,YAAY,OAAO,KAAK,cAAc,MAAM,EAAE,UACtI;EAGF,MAAM,KAAK,aAAa,QAAQ;EAEhC,KAAK,MAAM,gBAAgB,cAAc;GACvC,KAAK,SAAS,WAAW,YAAY;GACrC,KAAK,MAAM,OAAO,YAAY;EAChC;EAEA,MAAM,aAAa,oBAA2C,OAAO,iBAAiB;GACpF,MAAM,cAAc,IAAI,YACtB,KAAK,WAAW,YAAY,GAC5B,KAAK,OACL,KAAK,cACP;GACA,KAAK,MAAM,IAAI,cAAc,WAAW;GACxC,MAAM,YAAY,KAAK,KAAK,SAAS,QAAQ,YAAY,CAAC;EAC5D,CAAC;CACH;CAEA,MAAa,aAAa;EACxB,cAAc,6CAA6C;EAE3D,KAAK,aAAa,cAAc,MAAM,KAAK,aAAa,iBAAiB,CAAC,CAAC;EAC3E,KAAK,aAAa,WAAW,MAAM,KAAK,aAAa,cAAc,CAAC,CAAC;EACrE,KAAK,aAAa,cAAc,MAAM,KAAK,aAAa,iBAAiB,CAAC,CAAC;EAE3E,MAAM,cAAc,qBAAqB,IAAI,WAAW,CAAC,EAAE;EAC3D,MAAM,KAAK,aAAa,MAAM,WAAW;CAC3C;AACF;AAEA,eAAe,aACb,OACA,MACA,IACe;CACf,IAAI,MAAM,WAAW,GAAG;CACxB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,MACrC,MAAM,QAAQ,IAAI,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;AAEtD;AAEA,MAAa,oBAAoB,IAAI,kBAAkB"}
1
+ {"version":3,"file":"files-orchestrator.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/files-orchestrator.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport { init } from \"es-module-lexer\";\r\nimport type { MessagePort } from \"node:worker_threads\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { DependencyGraph } from \"./dependency-graph\";\r\nimport { devLogDim, devLogSuccess } from \"./dev-logger\";\r\nimport { FileEventHandler } from \"./file-event-handler\";\r\nimport { FileManager } from \"./file-manager\";\r\nimport { FileOperations } from \"./file-operations\";\r\nimport { FilesWatcher } from \"./files-watcher\";\r\nimport { FILE_PROCESSING_BATCH_SIZE } from \"./flags\";\r\nimport { EslintHealthChecker } from \"./health-checker/checkers/eslint-health-checker\";\r\nimport { TypescriptHealthChecker } from \"./health-checker/checkers/typescript-health-checker\";\r\nimport type { FileHealthCheckerContract } from \"./health-checker/file-health-checker.contract\";\r\nimport { FilesHealthcareManager } from \"./health-checker/files-healthcare.manager\";\r\nimport { buildTranspileInit } from \"./loader/build-transpile-init.js\";\r\nimport { registerLoader } from \"./loader/register-loader.js\";\r\nimport { ManifestManager } from \"./manifest-manager\";\r\nimport { ModuleLoader } from \"./module-loader\";\r\nimport { packageJsonManager } from \"./package-json-manager\";\r\nimport { Path } from \"../utils/normalized-path\";\r\nimport { SpecialFilesCollector } from \"./special-files-collector\";\r\nimport { tsconfigManager } from \"./tsconfig-manager\";\r\nimport { ensureWarlockDirectory, getFilesFromDirectory } from \"./utils\";\r\n\r\n/**\r\n * Register a cleanup callback that fires before the current module is\r\n * unloaded by HMR. Stack-inspects the caller so user code doesn't need to\r\n * thread the FileManager through.\r\n */\r\nexport function onCleanup(callback: () => any) {\r\n if (globalThis.__currentModuleFile) {\r\n globalThis.__currentModuleFile.addCleanup(callback);\r\n return;\r\n }\r\n\r\n const stack = new Error().stack;\r\n const callerLine = stack?.split(\"\\n\")[2];\r\n const match = callerLine?.match(/\\((.+?):\\d+:\\d+\\)/) || callerLine?.match(/at (.+?):\\d+:\\d+/);\r\n const callerFile = match?.[1];\r\n\r\n if (!callerFile) return;\r\n const fileManager = filesOrchestrator.files.get(Path.toRelative(callerFile));\r\n fileManager?.addCleanup(callback);\r\n}\r\n\r\n/**\r\n * Top-level coordinator for the dev server's file system.\r\n *\r\n * Owns: file discovery, the dependency graph, the manifest, the special-files\r\n * index, the file watcher, and the lifecycle of the ESM loader hook (which\r\n * provides cache-busting via `?v=N` version tokens).\r\n */\r\nexport class FilesOrchestrator {\r\n public readonly filesWatcher = new FilesWatcher();\r\n public readonly files = new Map<string, FileManager>();\r\n private readonly manifest = new ManifestManager(this.files);\r\n private readonly dependencyGraph = new DependencyGraph();\r\n private readonly healthCheckerManager = new FilesHealthcareManager(this.files);\r\n public readonly specialFilesCollector = new SpecialFilesCollector();\r\n public readonly moduleLoader = new ModuleLoader(this.specialFilesCollector);\r\n public readonly fileOperations: FileOperations;\r\n private readonly eventHandler: FileEventHandler;\r\n\r\n /** Main-thread end of the MessageChannel to the loader hook worker. */\r\n private loaderPort: MessagePort | null = null;\r\n\r\n /** Resolve callbacks for pending `flushVersionBumps()` calls. */\r\n private readonly pendingFlushes: Array<() => void> = [];\r\n\r\n public isInitialized = false;\r\n\r\n public constructor() {\r\n this.fileOperations = new FileOperations(\r\n this.files,\r\n this.dependencyGraph,\r\n this.manifest,\r\n this.specialFilesCollector,\r\n );\r\n\r\n this.eventHandler = new FileEventHandler(\r\n this.fileOperations,\r\n this.manifest,\r\n this.dependencyGraph,\r\n this.files,\r\n );\r\n }\r\n\r\n public async add(relativePath: string): Promise<FileManager> {\r\n return this.fileOperations.addFile(relativePath);\r\n }\r\n\r\n public async load<T>(relativePath: string, type = \"other\") {\r\n // Guarantee the ESM loader hook is registered before we import anything.\r\n // `load()` is the dynamic-import entrypoint, so it is the one place that\r\n // must satisfy `init()`'s documented precondition (\"Must be called before\r\n // any user src/ module is dynamically imported\") on its own — it cannot\r\n // assume a caller ran `init()` first.\r\n //\r\n // The CLI command-resolution path proves why: `cliCommandsLoader.load()`\r\n // imports a project command module during command *lookup* (before the\r\n // command's own `execute()` runs), whereas `loadPreloaders()` only calls\r\n // `init()` from *inside* `execute()`. So a `warlock <command>` whose\r\n // command file imports an `app/*` alias or a `.ts` sibling was imported\r\n // with no hook registered and died on `ERR_MODULE_NOT_FOUND` (f9d8f99f).\r\n //\r\n // `init()` is idempotent (guarded by `isInitialized`), so this is a no-op\r\n // on the dev-server path, which already calls it explicitly at startup.\r\n await this.init();\r\n\r\n const fileManager = await this.add(relativePath);\r\n return this.moduleLoader.loadModule<T>(fileManager, fileManager.type || type);\r\n }\r\n\r\n public getDependencyGraph(): DependencyGraph {\r\n return this.dependencyGraph;\r\n }\r\n\r\n public getInvalidationChain(file: string): string[] {\r\n return this.dependencyGraph.getInvalidationChain(file);\r\n }\r\n\r\n public getFiles(): Map<string, FileManager> {\r\n return this.files;\r\n }\r\n\r\n public getHealthCheckerManager(): FilesHealthcareManager {\r\n return this.healthCheckerManager;\r\n }\r\n\r\n /**\r\n * Initialise managers and register the ESM loader hook. Must be called\r\n * before any user `src/` module is dynamically imported.\r\n */\r\n public async init() {\r\n if (this.isInitialized) return;\r\n this.isInitialized = true;\r\n\r\n await init;\r\n await Promise.all([tsconfigManager.init(), packageJsonManager.init()]);\r\n\r\n // The loader hook writes itself into .warlock/, so ensure the dir exists.\r\n await ensureWarlockDirectory();\r\n\r\n const devServerConfig = await warlockConfigManager.lazyGet(\"devServer\");\r\n const transpileInit = buildTranspileInit(\r\n tsconfigManager.tsconfig?.compilerOptions,\r\n devServerConfig?.transpileCacheDebug === true,\r\n );\r\n\r\n this.loaderPort = await registerLoader(transpileInit);\r\n\r\n this.loaderPort.on(\"message\", (msg: { type: string }) => {\r\n if (msg.type === \"sync-ack\") {\r\n this.pendingFlushes.shift()?.();\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Tell the hook worker a file changed. The next `import()` of it will get\r\n * a fresh `?v=N` URL → Node cache miss → fresh content.\r\n */\r\n public bumpVersion(absolutePath: string): void {\r\n this.loaderPort?.postMessage({ type: \"bump\", absolutePath });\r\n }\r\n\r\n /**\r\n * Wait until the hook worker has processed every pending bump.\r\n *\r\n * `postMessage` is async — without this, a follow-up `import()` may\r\n * resolve before the worker increments the counter and Node will return\r\n * the cached old module.\r\n */\r\n public flushVersionBumps(): Promise<void> {\r\n if (!this.loaderPort) return Promise.resolve();\r\n\r\n return new Promise<void>((resolve) => {\r\n this.pendingFlushes.push(resolve);\r\n this.loaderPort!.postMessage({ type: \"sync\" });\r\n });\r\n }\r\n\r\n /**\r\n * Discover files on disk, reconcile against the manifest, build the dep\r\n * graph, and persist the new manifest. Idempotent.\r\n */\r\n public async initializeAll() {\r\n const [filesInFilesystem, manifestExists] = await Promise.all([\r\n this.getAllFilesFromFilesystem(),\r\n this.manifest.init(),\r\n ]);\r\n\r\n if (!manifestExists) {\r\n await this.processFiles(filesInFilesystem);\r\n } else {\r\n await this.reconcileFiles(filesInFilesystem);\r\n }\r\n\r\n this.dependencyGraph.build(this.files);\r\n this.fileOperations.updateFileDependents();\r\n this.fileOperations.syncFilesToManifest();\r\n await this.manifest.save();\r\n }\r\n\r\n public async checkHealth(files: { added: string[]; changed: string[]; deleted: string[] }) {\r\n const filesToCheck = [...files.added, ...files.changed]\r\n .map((file) => this.files.get(Path.toRelative(file)))\r\n .filter((file): file is FileManager => !!file);\r\n\r\n const filesToDelete = files.deleted\r\n .map((file) => this.files.get(Path.toRelative(file)))\r\n .filter((file): file is FileManager => !!file);\r\n\r\n await this.healthCheckerManager.onFileChanges(filesToCheck);\r\n this.healthCheckerManager.removeFiles(filesToDelete);\r\n this.healthCheckerManager.checkFiles(filesToCheck);\r\n }\r\n\r\n public async startCheckingHealth(healthCheckers?: FileHealthCheckerContract[]): Promise<void> {\r\n devLogDim(\"Started File Health Checks in the background.\");\r\n\r\n const checkers = healthCheckers ?? [new TypescriptHealthChecker(), new EslintHealthChecker()];\r\n await this.healthCheckerManager.setHealthCheckers(checkers).initialize();\r\n await this.healthCheckerManager.validateAllFiles();\r\n }\r\n\r\n /**\r\n * Glob the src directory, returning relative paths.\r\n */\r\n public async getAllFilesFromFilesystem(): Promise<string[]> {\r\n const absolutePaths = await getFilesFromDirectory();\r\n return absolutePaths.map((absPath) => Path.toRelative(absPath));\r\n }\r\n\r\n /**\r\n * Process every file from scratch — used when no manifest exists.\r\n */\r\n private async processFiles(filePaths: string[]) {\r\n devLogDim(`processing ${filePaths.length} files...`);\r\n await runInBatches(filePaths, FILE_PROCESSING_BATCH_SIZE, async (relativePath) => {\r\n const fileManager = new FileManager(\r\n Path.toAbsolute(relativePath),\r\n this.files,\r\n this.fileOperations,\r\n );\r\n this.files.set(relativePath, fileManager);\r\n await fileManager.process();\r\n });\r\n devLogSuccess(`processed ${filePaths.length} files`);\r\n }\r\n\r\n private async reconcileFiles(filesInFilesystem: string[]) {\r\n const filesInManifest = new Set(this.manifest.getAllFilePaths());\r\n const filesInFilesystemSet = new Set(filesInFilesystem);\r\n\r\n const newFiles = filesInFilesystem.filter((f) => !filesInManifest.has(f));\r\n const deletedFiles = Array.from(filesInManifest).filter((f) => !filesInFilesystemSet.has(f));\r\n const existingFiles = filesInFilesystem.filter((f) => filesInManifest.has(f));\r\n\r\n if (newFiles.length > 0 || deletedFiles.length > 0) {\r\n devLogDim(\r\n `reconciling: ${colors.green(newFiles.length)} new, ${colors.red(deletedFiles.length)} deleted, ${colors.blue(existingFiles.length)} existing`,\r\n );\r\n }\r\n\r\n await this.processFiles(newFiles);\r\n\r\n for (const relativePath of deletedFiles) {\r\n this.manifest.removeFile(relativePath);\r\n this.files.delete(relativePath);\r\n }\r\n\r\n await runInBatches(existingFiles, FILE_PROCESSING_BATCH_SIZE, async (relativePath) => {\r\n const fileManager = new FileManager(\r\n Path.toAbsolute(relativePath),\r\n this.files,\r\n this.fileOperations,\r\n );\r\n this.files.set(relativePath, fileManager);\r\n await fileManager.init(this.manifest.getFile(relativePath));\r\n });\r\n }\r\n\r\n public async watchFiles() {\r\n devLogSuccess(\"watching for file changes (not serving yet)\");\r\n\r\n this.filesWatcher.onFileChange((p) => this.eventHandler.handleFileChange(p));\r\n this.filesWatcher.onFileAdd((p) => this.eventHandler.handleFileAdd(p));\r\n this.filesWatcher.onFileDelete((p) => this.eventHandler.handleFileDelete(p));\r\n\r\n const watchConfig = warlockConfigManager.get(\"devServer\")?.watch;\r\n await this.filesWatcher.watch(watchConfig);\r\n }\r\n}\r\n\r\nasync function runInBatches<T>(\r\n items: T[],\r\n size: number,\r\n fn: (item: T) => Promise<unknown>,\r\n): Promise<void> {\r\n if (items.length === 0) return;\r\n for (let i = 0; i < items.length; i += size) {\r\n await Promise.all(items.slice(i, i + size).map(fn));\r\n }\r\n}\r\n\r\nexport const filesOrchestrator = new FilesOrchestrator();\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,IAAa,oBAAb,MAA+B;CAmB7B,AAAO,cAAc;sBAlBU,IAAI,aAAa;+BACxB,IAAI,IAAyB;kBACzB,IAAI,gBAAgB,KAAK,KAAK;yBACvB,IAAI,gBAAgB;8BACf,IAAI,uBAAuB,KAAK,KAAK;+BACrC,IAAI,sBAAsB;sBACnC,IAAI,aAAa,KAAK,qBAAqB;oBAKjC;wBAGY,CAAC;uBAE/B;EAGrB,KAAK,iBAAiB,IAAI,eACxB,KAAK,OACL,KAAK,iBACL,KAAK,UACL,KAAK,qBACP;EAEA,KAAK,eAAe,IAAI,iBACtB,KAAK,gBACL,KAAK,UACL,KAAK,iBACL,KAAK,KACP;CACF;CAEA,MAAa,IAAI,cAA4C;EAC3D,OAAO,KAAK,eAAe,QAAQ,YAAY;CACjD;CAEA,MAAa,KAAQ,cAAsB,OAAO,SAAS;EAgBzD,MAAM,KAAK,KAAK;EAEhB,MAAM,cAAc,MAAM,KAAK,IAAI,YAAY;EAC/C,OAAO,KAAK,aAAa,WAAc,aAAa,YAAY,QAAQ,IAAI;CAC9E;CAEA,AAAO,qBAAsC;EAC3C,OAAO,KAAK;CACd;CAEA,AAAO,qBAAqB,MAAwB;EAClD,OAAO,KAAK,gBAAgB,qBAAqB,IAAI;CACvD;CAEA,AAAO,WAAqC;E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a,oBAAoB,IAAI,kBAAkB"}
@@ -648,9 +648,9 @@ const webContactControllerStub = `import { type Request, type RequestHandler } f
648
648
  import { type Infer, v } from "@warlock.js/seal";
649
649
 
650
650
  export const contactSchema = v.object({
651
- name: v.string().min(2).required(),
652
- email: v.email().required(),
653
- message: v.string().min(10).required(),
651
+ name: v.string().min(2),
652
+ email: v.email(),
653
+ message: v.string().min(10),
654
654
  });
655
655
 
656
656
  export type ContactSchema = Infer.Output<typeof contactSchema>;
@@ -743,9 +743,9 @@ export const route = { path: "/", name: "index" } as const;
743
743
  export const metadata = { title: "Home" };
744
744
 
745
745
  const contactSchema = v.object({
746
- name: v.string().min(2).required(),
747
- email: v.email().required(),
748
- message: v.string().min(10).required(),
746
+ name: v.string().min(2),
747
+ email: v.email(),
748
+ message: v.string().min(10),
749
749
  });
750
750
 
751
751
  function TextInput({ label, ...controlProps }: FormControlProps & { label: string }) {
@@ -1 +1 @@
1
- {"version":3,"file":"stubs.mjs","names":[],"sources":["../../../../../../../core/src/generations/stubs.ts"],"sourcesContent":["export const accessConfigStub = `import { type AccessConfigurations } from \"@warlock.js/access\";\r\nimport { DatabaseAccessResolver } from \"app/access/services/access-resolver\";\r\n\r\n/**\r\n * Authorization configuration — read by @warlock.js/access on boot.\r\n *\r\n * The resolver is the one required piece: it tells the engine how to read a\r\n * user's roles + permissions. The ejected DatabaseAccessResolver reads roles\r\n * from the user_roles table and maps them through the roles catalog table (so\r\n * roles + their permissions are managed at runtime, in the DB).\r\n *\r\n * For a fixed, code-defined catalog with no tables, swap in DefaultAccessResolver:\r\n * import { DefaultAccessResolver } from \"@warlock.js/access\";\r\n * resolver: new DefaultAccessResolver({ admin: [\"*\"], editor: [\"orders.*\"] }),\r\n *\r\n * Multi-tenant? Add a \\`resolveTenant()\\` to the resolver to read the active\r\n * tenant from the request; checks then scope to it automatically.\r\n */\r\nconst access: AccessConfigurations = {\r\n resolver: new DatabaseAccessResolver(),\r\n\r\n // Cache resolved permission sets (default \"10m\").\r\n // cache: { ttl: \"10m\" },\r\n};\r\n\r\nexport default access;\r\n`;\r\n\r\nexport const aiConfigStub = `import type { AIConfig } from \"@warlock.js/ai\";\r\n\r\n// >>> warlock:ai-packages (auto-managed) >>>\r\n// Satellite packages augment the \"ai\" object on import — e.g. ai.workspace,\r\n// ai.tools / ai.mcp, and panoptic's ai.config({ panoptic }) wiring. The command\r\n// \"warlock add ai-workspace | ai-tools | ai-panoptic\" adds the matching\r\n// side-effect import below; keep them so the augmentation + runtime registration\r\n// load before the ai connector applies this config.\r\n// <<< warlock:ai-packages <<<\r\n\r\n/**\r\n * AI configuration — applied on boot by the ai connector, which calls\r\n * ai.config(...) with the object below. Cross-cutting defaults live here\r\n * (shared cache / snapshot stores, observability); per-call options always win.\r\n *\r\n * Wire a default model from a provider you installed, e.g.:\r\n * import { OpenAISDK } from \"@warlock.js/ai-openai\";\r\n * const openai = OpenAISDK({ apiKey: env(\"OPENAI_API_KEY\") });\r\n * // then pass openai.model({ name: \"gpt-4o-mini\" }) into your agents.\r\n */\r\nconst ai: Partial<AIConfig> = {\r\n // Default cache driver for cache-backed AI features (semantic cache, rag / memory vector stores).\r\n // defaultStore: cache.driver(\"redis\", { client }),\r\n\r\n // Observability — requires \"warlock add ai-panoptic\". Exporters + the local dashboard.\r\n // panoptic: { exporters: [], dashboard: false, observeAll: false },\r\n};\r\n\r\nexport default ai;\r\n`;\r\n\r\nexport const accessRoleModelStub = `import { Model, RegisterModel } from \"@warlock.js/cascade\";\r\nimport { type Infer, v } from \"@warlock.js/seal\";\r\n\r\n/**\r\n * Validation schema for the roles catalog — mirrors the migration columns\r\n * (snake_case). Each row is a role name plus the permission strings it grants;\r\n * wildcards work (\"orders.*\", \"*\"). The DatabaseAccessResolver maps a user's\r\n * assigned role names through this table to their effective permissions.\r\n */\r\nexport const roleSchema = v.object({\r\n name: v.string(),\r\n permissions: v.array(v.string()).default([]),\r\n});\r\n\r\nexport type RoleSchema = Infer<typeof roleSchema>;\r\n\r\n/**\r\n * The roles catalog — role name → the permissions it grants. Managed at runtime\r\n * (admins add roles + edit their permissions), unlike a fixed code map. Read by\r\n * DatabaseAccessResolver.resolvePermissions to expand a user's roles to permissions.\r\n */\r\n@RegisterModel()\r\nexport class Role extends Model<RoleSchema> {\r\n public static table = \"roles\";\r\n\r\n public static schema = roleSchema;\r\n\r\n /** The permission strings this role grants. */\r\n public get permissions(): string[] {\r\n return this.get<string[]>(\"permissions\", []);\r\n }\r\n}\r\n`;\r\n\r\nexport const accessRoleModelIndexStub = `export * from \"./role.model\";\r\n`;\r\n\r\nexport const accessRoleMigrationStub = `import { arrayText, Migration, text } from \"@warlock.js/cascade\";\r\nimport { Role } from \"../role.model\";\r\n\r\n/**\r\n * Roles catalog table. \\`name\\` is unique (one row per role); \\`permissions\\` is a\r\n * text array of the permission strings the role grants.\r\n */\r\nexport default Migration.create(Role, {\r\n name: text().notNullable().unique(),\r\n permissions: arrayText().nullable(),\r\n});\r\n`;\r\n\r\nexport const accessUserRoleModelStub = `import { access } from \"@warlock.js/access\";\r\nimport type { Auth } from \"@warlock.js/auth\";\r\nimport { Model, RegisterModel } from \"@warlock.js/cascade\";\r\nimport { type Infer, v } from \"@warlock.js/seal\";\r\n\r\n/**\r\n * Validation schema for a role assignment — mirrors the migration columns\r\n * (snake_case). \\`tenant\\` is nullable: a null tenant is a GLOBAL assignment.\r\n */\r\nexport const userRoleSchema = v.object({\r\n user_id: v.string(),\r\n user_type: v.string(),\r\n role: v.string(),\r\n tenant: v.string().optional(),\r\n});\r\n\r\nexport type UserRoleSchema = Infer<typeof userRoleSchema>;\r\n\r\n/**\r\n * The role-assignment table — which roles a user holds, optionally per tenant.\r\n * Read by DatabaseAccessResolver.resolveRoles; mutated via the statics below.\r\n * \\`assign\\` / \\`revoke\\` flush the cached permission set automatically, so callers\r\n * never need to call \\`access.flush(user, tenant)\\` themselves.\r\n */\r\n@RegisterModel()\r\nexport class UserRole extends Model<UserRoleSchema> {\r\n public static table = \"user_roles\";\r\n\r\n public static schema = userRoleSchema;\r\n\r\n /**\r\n * Role names assigned to the user in the given tenant.\r\n *\r\n * An unresolved tenant (\\`undefined\\`) scopes to GLOBAL roles only — the rows\r\n * stored with no tenant (\\`null\\`) — never the union across every tenant. The\r\n * union would be a privilege-escalation: a user who is \\`owner\\` in one tenant\r\n * must not be treated as \\`owner\\` everywhere just because a check didn't carry\r\n * a tenant. This mirrors how \\`assign(user, role)\\` stores a global row.\r\n */\r\n public static async rolesFor(user: Auth, tenant?: string): Promise<string[]> {\r\n const rows = await this.query()\r\n .where({\r\n user_id: user.id,\r\n user_type: user.userType,\r\n tenant: tenant ?? null,\r\n })\r\n .get();\r\n\r\n // De-dupe so a duplicate row (a concurrent assign that slipped past the\r\n // existence check) can't distort the resolved set.\r\n return [...new Set(rows.map((row) => row.get(\"role\") as string))];\r\n }\r\n\r\n /**\r\n * Assign a role to the user. No-op if the assignment already exists.\r\n * Flushes the user's cached permission set automatically.\r\n */\r\n public static async assign(user: Auth, role: string, tenant?: string): Promise<void> {\r\n const existing = await this.first({\r\n user_id: user.id,\r\n user_type: user.userType,\r\n role,\r\n tenant: tenant ?? null,\r\n });\r\n\r\n if (existing) return;\r\n\r\n await this.create({\r\n user_id: user.id,\r\n user_type: user.userType,\r\n role,\r\n tenant,\r\n });\r\n\r\n await access.flush(user, tenant);\r\n }\r\n\r\n /**\r\n * Remove a role assignment from the user.\r\n * Flushes the user's cached permission set automatically.\r\n */\r\n public static async revoke(user: Auth, role: string, tenant?: string): Promise<void> {\r\n await this.delete({\r\n user_id: user.id,\r\n user_type: user.userType,\r\n role,\r\n tenant: tenant ?? null,\r\n });\r\n\r\n await access.flush(user, tenant);\r\n }\r\n}\r\n`;\r\n\r\nexport const accessUserRoleModelIndexStub = `export * from \"./user-role.model\";\r\n`;\r\n\r\nexport const accessUserRoleMigrationStub = `import { Migration, text, uuid } from \"@warlock.js/cascade\";\r\nimport { UserRole } from \"../user-role.model\";\r\n\r\n/**\r\n * Role-assignment table. \\`user_id\\` is a UUID — override this migration if your\r\n * user ids are integers. The composite index powers the per-user (per-tenant)\r\n * lookup the resolver runs on every check.\r\n */\r\nexport default Migration.create(\r\n UserRole,\r\n {\r\n user_id: uuid().notNullable().index(),\r\n user_type: text().notNullable(),\r\n role: text().notNullable().index(),\r\n tenant: text().nullable().index(),\r\n },\r\n {\r\n index: [{ columns: [\"user_id\", \"user_type\", \"tenant\"] }],\r\n },\r\n);\r\n`;\r\n\r\nexport const accessResolverStub = `import type { AccessResolver } from \"@warlock.js/access\";\r\nimport type { Auth } from \"@warlock.js/auth\";\r\nimport { Role } from \"app/access/models/role\";\r\nimport { UserRole } from \"app/access/models/user-role\";\r\n\r\n/**\r\n * The app's access adapter — connects @warlock.js/access to the ejected role\r\n * tables. Roles come from the user_roles assignment table; permissions are\r\n * expanded by mapping those role names through the roles catalog table. Both\r\n * are managed at runtime (in the DB), so admins can add roles + edit their\r\n * permissions without a deploy.\r\n *\r\n * The engine owns the hard parts (wildcard matching, caching, fail-closed); this\r\n * resolver only fetches — keep it dumb, never cache inside it.\r\n */\r\nexport class DatabaseAccessResolver implements AccessResolver {\r\n /** The role names this user holds (powers \\`hasRole\\` / \\`hasAnyRole\\`). */\r\n public async resolveRoles(user: Auth, tenant?: string): Promise<string[]> {\r\n return UserRole.rolesFor(user, tenant);\r\n }\r\n\r\n /** The effective permission strings this user has (powers \\`can\\` / \\`authorize\\`). */\r\n public async resolvePermissions(user: Auth, tenant?: string): Promise<string[]> {\r\n const names = await this.resolveRoles(user, tenant);\r\n\r\n if (names.length === 0) return [];\r\n\r\n const roles = await Role.query().whereIn(\"name\", names).get();\r\n\r\n // Flatten + de-dupe so two roles granting the same permission yield one entry.\r\n return [...new Set(roles.flatMap((role) => role.permissions))];\r\n }\r\n\r\n /**\r\n * Optional. Resolve the ambient tenant when a check doesn't pass one\r\n * explicitly — derive it from the authenticated user (safer than reading\r\n * client request input, which a caller could spoof). Uncomment + adapt for a\r\n * multi-tenant app (single-tenant apps leave this off and return undefined).\r\n */\r\n // public resolveTenant(user: Auth): string | undefined {\r\n // return user.get(\"organization_id\");\r\n // }\r\n}\r\n`;\r\n\r\nexport const socketConfigStub = `import type { SocketOptions } from \"@warlock.js/core\";\r\n\r\n/**\r\n * Socket.IO configuration — read by the framework's socket connector\r\n * on boot. When the HTTP server is running the socket server attaches\r\n * to it; otherwise it listens on its own configured port.\r\n *\r\n * Remove this file to disable the socket server entirely.\r\n */\r\nexport default {\r\n options: {\r\n cors: {\r\n origin: \"*\",\r\n },\r\n },\r\n} as SocketOptions;\r\n`;\r\n\r\nexport const communicatorsConfigStub = `import { env } from \"@warlock.js/core\";\r\nimport type { BrokerConfigurations, RabbitMQClientOptions } from \"@warlock.js/herald\";\r\n\r\nconst heraldConfigurations: BrokerConfigurations<RabbitMQClientOptions> = {\r\n driver: \"rabbitmq\",\r\n name: \"default\",\r\n isDefault: true,\r\n\r\n // ============================================================================\r\n // Connection Settings\r\n // ============================================================================\r\n\r\n host: env(\"RABBITMQ_HOST\", \"localhost\"),\r\n port: env(\"RABBITMQ_PORT\", 5672),\r\n username: env(\"RABBITMQ_USERNAME\", \"guest\"),\r\n password: env(\"RABBITMQ_PASSWORD\", \"guest\"),\r\n vhost: env(\"RABBITMQ_VHOST\", \"/\"),\r\n\r\n // Or use connection URI (takes precedence over host/port)\r\n // uri: env(\"RABBITMQ_URL\"),\r\n\r\n // ============================================================================\r\n // Connection Options\r\n // ============================================================================\r\n\r\n /** Heartbeat interval in seconds */\r\n heartbeat: 60,\r\n\r\n /** Connection timeout in milliseconds */\r\n connectionTimeout: 10000,\r\n\r\n /** Enable automatic reconnection on disconnect */\r\n reconnect: true,\r\n\r\n /** Delay between reconnection attempts in milliseconds */\r\n reconnectDelay: 5_000,\r\n\r\n // ============================================================================\r\n // Consumer Options\r\n // ============================================================================\r\n\r\n /** Default prefetch count (number of unacknowledged messages per consumer) */\r\n prefetch: 10,\r\n\r\n // ============================================================================\r\n // Client Options (Native amqplib options)\r\n // ============================================================================\r\n // These options are passed directly to amqplib.connect()\r\n // for low-level configuration like frame size, TLS, socket options, etc.\r\n // ============================================================================\r\n clientOptions: {\r\n // Frame max size in bytes (0 = no limit)\r\n // frameMax: 0,\r\n\r\n // Channel max (0 = unlimited)\r\n // channelMax: 0,\r\n\r\n // Socket options\r\n socket: {\r\n // Enable TCP keep-alive\r\n keepAlive: true,\r\n\r\n // Disable Nagle's algorithm for lower latency\r\n noDelay: true,\r\n\r\n // Socket timeout (in addition to heartbeat)\r\n // timeout: 30000,\r\n },\r\n\r\n // TLS/SSL options (uncomment for secure connections)\r\n // socket: {\r\n // ca: fs.readFileSync('/path/to/ca.pem'),\r\n // cert: fs.readFileSync('/path/to/cert.pem'),\r\n // key: fs.readFileSync('/path/to/key.pem'),\r\n // rejectUnauthorized: true,\r\n // },\r\n },\r\n};\r\n\r\nexport default heraldConfigurations;\r\n`;\r\n\r\nexport const notificationsConfigStub = `import { type NotificationConfig, inApp, mailChannel } from \"@warlock.js/notifications\";\r\nimport { Notification } from \"app/notifications/notification.model\";\r\n\r\n/**\r\n * Notifications configuration. Auto-loaded from src/config on boot — the\r\n * framework's notifications connector reads this default export and hands it to\r\n * setNotificationConfig, so this file stays declarative (no side-effect call).\r\n *\r\n * Each channel is payload-typed, so notify.mail(...) / notify.database(...)\r\n * and defineNotification are type-checked against the registry.\r\n *\r\n * Channels enabled here:\r\n * - mail wraps @warlock.js/core sendMail; route is notifiable.email.\r\n * The \"from\" address defaults to config/mail.ts; override per\r\n * channel with mailChannel({ from: \"no-reply@yourapp.com\" }).\r\n * - database in-app store backed by the Notification model. The \"inApp\"\r\n * facade exposes the recipient-scoped read API: listUnread,\r\n * countUnread, markAsRead, dismiss, ...\r\n *\r\n * Async delivery (.queue()) is OPTIONAL: run \"npx warlock add herald\",\r\n * import { heraldQueue } from \"@warlock.js/notifications\", and uncomment the\r\n * queue line below.\r\n */\r\nconst config: NotificationConfig = {\r\n channels: {\r\n mail: mailChannel(),\r\n database: inApp.configure({ model: Notification }),\r\n },\r\n\r\n // Async queue — requires @warlock.js/herald (npx warlock add herald):\r\n // queue: heraldQueue(),\r\n};\r\n\r\nexport default config;\r\n`;\r\n\r\nexport const notificationModelStub = `import { RegisterModel } from \"@warlock.js/cascade\";\r\nimport { DatabaseNotification, type NotificationColumnMap } from \"@warlock.js/notifications\";\r\nimport { v } from \"@warlock.js/seal\";\r\n\r\n/**\r\n * Validation schema for the notifications table — mirrors the migration\r\n * columns (snake_case). Cascade validates + casts every write against it:\r\n * nullable columns use .nullish() (may be absent or null), and payload is\r\n * free-form JSON. Keep this in sync with the migration + columnMap when you\r\n * add or rename columns.\r\n */\r\nconst notificationSchema = v.object({\r\n user_id: v.string(),\r\n type: v.string(),\r\n title: v.string(),\r\n body: v.string().nullish(),\r\n payload: v.record(v.any()).nullish(),\r\n read_at: v.date().nullish(),\r\n idempotency_key: v.string().nullish(),\r\n});\r\n\r\n/**\r\n * In-app notification model.\r\n *\r\n * Extends the package's DatabaseNotification base, which provides the stable\r\n * accessors (recipientId, tenantId, isRead, readAt, markRead) — all derived\r\n * from the columnMap below. The read/write API lives on the inApp facade\r\n * (configured in config/notifications.ts); you rarely touch this class directly.\r\n */\r\n@RegisterModel()\r\nexport class Notification extends DatabaseNotification {\r\n public static table = \"notifications\";\r\n public static schema = notificationSchema;\r\n\r\n /**\r\n * Maps the in-app store's roles to your columns. This default is\r\n * single-tenant + read_at-only. Add tenant: \"organization_id\" for\r\n * multi-tenant; use isRead: \"is_read\" (instead of, or alongside, readAt) to\r\n * track a boolean read flag. The migration + accessors all follow this map.\r\n */\r\n public static columnMap: NotificationColumnMap = { readAt: \"read_at\" };\r\n}\r\n`;\r\n\r\nexport const notificationMigrationStub = `import { Migration } from \"@warlock.js/cascade\";\r\nimport { notificationColumns } from \"@warlock.js/notifications\";\r\nimport { Notification } from \"../notification.model\";\r\n\r\n/**\r\n * Notifications table.\r\n *\r\n * Columns come from notificationColumns(Notification) — the recipient / tenant\r\n * / read-state names follow the model's columnMap; type / title / body /\r\n * payload / idempotency_key are fixed. Spread it to add your own columns\r\n * (remember to mirror them in the model schema):\r\n *\r\n * import { uuid } from \"@warlock.js/cascade\";\r\n *\r\n * export default Migration.create(Notification, {\r\n * ...notificationColumns(Notification),\r\n * // category_id: uuid().index().nullable(),\r\n * });\r\n */\r\nexport default Migration.create(Notification, notificationColumns(Notification));\r\n`;\r\n\r\nexport const notificationControllersStub = `import { type RequestHandler } from \"@warlock.js/core\";\r\nimport { inApp, type Id } from \"@warlock.js/notifications\";\r\n\r\n/**\r\n * The authenticated user's notification HTTP surface — thin wrappers over the\r\n * recipient-scoped \\`inApp\\` facade (a foreign id can never touch another user's\r\n * rows). Notifications are produced by domain events, never over HTTP, so there\r\n * is no create. Trim or split these as your app grows.\r\n */\r\n\r\n/**\r\n * Read \\`id\\` off \\`request.user\\` without assuming this app's \\`RequestUser\\`\r\n * augmentation declares it — \\`RequestUser\\` is empty by default (see\r\n * \\`@warlock.js/core\\`'s \\`RequestUser\\` docs), so a narrow runtime read survives\r\n * any augmentation shape instead of assuming \\`.id\\` exists at the type level.\r\n * \\`inApp\\` only ever needs the id (it reduces a \\`Notifiable\\` to one via\r\n * \\`recipient.id\\` internally), so reading it here — rather than forwarding\r\n * \\`request.user\\` itself — also skips a needless \\`Notifiable\\` cast.\r\n */\r\nfunction recipientId(user: unknown): Id {\r\n if (user && typeof user === \"object\" && \"id\" in user) {\r\n const id = (user as { id?: unknown }).id;\r\n\r\n if (typeof id === \"string\" || typeof id === \"number\") return id;\r\n }\r\n\r\n throw new Error(\"Authenticated request is missing a usable user id\");\r\n}\r\n\r\n/** GET /notifications — list, most recent first (page / limit / type / unread via query). */\r\nexport const listNotificationsController: RequestHandler = async ({ request, response }) => {\r\n const { data, pagination } = await inApp.list(recipientId(request.user), request.all());\r\n\r\n return response.success({ notifications: data, pagination });\r\n};\r\n\r\nlistNotificationsController.description = \"List notifications\";\r\n\r\n/** GET /notifications/unread-count — drives the bell badge. */\r\nexport const unreadNotificationsCountController: RequestHandler = async ({\r\n request,\r\n response,\r\n}) => {\r\n const count = await inApp.countUnread(recipientId(request.user));\r\n\r\n return response.success({ count });\r\n};\r\n\r\nunreadNotificationsCountController.description = \"Unread notifications count\";\r\n\r\n/** PATCH /notifications/:id/read — mark one read, return the updated row. */\r\nexport const markNotificationReadController: RequestHandler = async ({ request, response }) => {\r\n const id = request.input(\"id\");\r\n const userId = recipientId(request.user);\r\n\r\n await inApp.markAsRead(userId, id);\r\n const notification = await inApp.find(userId, id);\r\n\r\n return response.success({ notification });\r\n};\r\n\r\nmarkNotificationReadController.description = \"Mark notification read\";\r\n\r\n/** PATCH /notifications/read-all — mark every unread one read. */\r\nexport const markAllNotificationsReadController: RequestHandler = async ({\r\n request,\r\n response,\r\n}) => {\r\n const count = await inApp.markAsRead(recipientId(request.user));\r\n\r\n return response.success({ count });\r\n};\r\n\r\nmarkAllNotificationsReadController.description = \"Mark all notifications read\";\r\n\r\n/** DELETE /notifications — dismiss all for the user. */\r\nexport const clearNotificationsController: RequestHandler = async ({ request, response }) => {\r\n await inApp.dismiss(recipientId(request.user));\r\n\r\n return response.noContent();\r\n};\r\n\r\nclearNotificationsController.description = \"Clear notifications\";\r\n\r\n/** DELETE /notifications/:id — dismiss one. */\r\nexport const deleteNotificationController: RequestHandler = async ({ request, response }) => {\r\n await inApp.dismiss(recipientId(request.user), request.input(\"id\"));\r\n\r\n return response.noContent();\r\n};\r\n\r\ndeleteNotificationController.description = \"Delete notification\";\r\n`;\r\n\r\nexport const notificationRoutesStub = `import { authMiddleware } from \"@warlock.js/auth\";\r\nimport { router } from \"@warlock.js/core\";\r\nimport {\r\n clearNotificationsController,\r\n deleteNotificationController,\r\n listNotificationsController,\r\n markAllNotificationsReadController,\r\n markNotificationReadController,\r\n unreadNotificationsCountController,\r\n} from \"./controllers/notifications.controller\";\r\n\r\n/**\r\n * Notification routes — the authenticated user's read + dismiss surface.\r\n *\r\n * Notifications are produced by domain events (never created over HTTP), so\r\n * there is no POST. Every route is gated by \\`authMiddleware\\` and recipient-\r\n * scoped by \\`inApp\\` (a foreign id touches zero rows). Delete any endpoint you\r\n * don't need; if your app reads notifications over sockets/GraphQL instead,\r\n * delete this file + the controllers entirely.\r\n */\r\nrouter.group({ prefix: \"/notifications\", middleware: [authMiddleware([])] }, () => {\r\n router.get(\"/\", listNotificationsController);\r\n router.get(\"/unread-count\", unreadNotificationsCountController);\r\n router.patch(\"/read-all\", markAllNotificationsReadController);\r\n router.patch(\"/:id/read\", markNotificationReadController);\r\n router.delete(\"/\", clearNotificationsController);\r\n router.delete(\"/:id\", deleteNotificationController);\r\n});\r\n`;\r\n\r\n/**\r\n * `src/web/root.tsx` — the application root for the SSR page layer.\r\n *\r\n * Deliberately minimal. The framework ships a default root, so this exists to\r\n * give you a place to start rather than because anything requires it. The\r\n * reference app (`v5/app/src/web/root.tsx`) is where to look for the fuller\r\n * shape: middleware, an app-level loader, locales, an ErrorBoundary.\r\n */\r\nexport const webRootStub = `import type { AppProps } from \"@warlock.js/web\";\r\nimport { Head, Scripts } from \"@warlock.js/web\";\r\n\r\n/**\r\n * The application root.\r\n *\r\n * NOT async, and it receives no request/response: it renders on the server and\r\n * again in the browser during hydration, where neither exists.\r\n */\r\nexport default function App({ children }: AppProps) {\r\n return (\r\n <html lang=\"en\">\r\n <head>\r\n {/*\r\n Placement only. The framework injects the page's \\`metadata\\`, the\r\n stylesheet and preload tags for this route, and the canonical links\r\n into <head> by default — <Head /> just says WHERE they land.\r\n\r\n Do not add a <title> here: the page's \\`metadata\\` owns it, and a root\r\n that emits one too produces two.\r\n */}\r\n <Head />\r\n <link rel=\"icon\" href=\"data:,\" />\r\n </head>\r\n <body>\r\n {/*\r\n REQUIRED — this is the hydration mount point, not a styling wrapper.\r\n\r\n The browser runtime looks up \\`#root\\` and hydrates that element only.\r\n Remove this div, or rename the id, and the page still renders from the\r\n server but never becomes interactive: the runtime throws in the console\r\n and nothing on screen changes.\r\n\r\n Wrap it in your own markup freely, and put anything that must live\r\n outside the hydrated tree (a static footer, a portal target) outside\r\n it — just keep an element with \\`id=\"root\"\\` around {children}.\r\n */}\r\n <div id=\"root\">{children}</div>\r\n {/*\r\n The hydration payload and module tags. Written explicitly because\r\n placement occasionally matters — a CSP nonce, or ordering against\r\n your own scripts.\r\n */}\r\n <Scripts />\r\n </body>\r\n </html>\r\n );\r\n}\r\n`;\r\n\r\n/**\r\n * `src/app/contact/controllers/contact.controller.ts` — a real API endpoint\r\n * for the Web starter's contact form. It intentionally has no persistence\r\n * dependency: replace the acknowledgement with a mail/job/database action.\r\n */\r\nexport const webContactControllerStub = `import { type Request, type RequestHandler } from \"@warlock.js/core\";\r\nimport { type Infer, v } from \"@warlock.js/seal\";\r\n\r\nexport const contactSchema = v.object({\r\n name: v.string().min(2).required(),\r\n email: v.email().required(),\r\n message: v.string().min(10).required(),\r\n});\r\n\r\nexport type ContactSchema = Infer.Output<typeof contactSchema>;\r\n\r\n/** POST /api/contact — validates the starter contact form. */\r\nexport const contactController: RequestHandler<Request<ContactSchema>> = async ({\r\n request,\r\n response,\r\n}) => {\r\n const contact = request.validated();\r\n\r\n // Replace this with delivery/persistence for your app. Keeping the accepted\r\n // payload visible makes the endpoint useful while remaining side-effect free.\r\n return response.success({\r\n message: \"Thanks, \" + contact.name + \". Your message has been received.\",\r\n });\r\n};\r\n\r\ncontactController.validation = { schema: contactSchema };\r\n`;\r\n\r\n/** `src/app/contact/routes.ts` — discovered by the standard app route loader. */\r\nexport const webContactRoutesStub = `import { router } from \"@warlock.js/core\";\r\nimport { contactController } from \"./controllers/contact.controller\";\r\n\r\nrouter.post(\"/api/contact\", contactController);\r\n`;\r\n\r\n/**\r\n * `src/web/index.register.ts` — universal static setup for the starter page.\r\n *\r\n * The page re-exports this stable binding so Warlock's `register()` lifecycle\r\n * still sees it in both realms without making React Fast Refresh treat every\r\n * JSX edit as an incompatible function-export replacement.\r\n */\r\nexport const webHomeRegisterStub = `import { extend } from \"@mongez/localization\";\r\n\r\nexport function register() {\r\n extend(\"en\", {\r\n starter: {\r\n title: \"Your Warlock app is running.\",\r\n introduction: \"This page is rendered on the server and hydrated in the browser.\",\r\n language: \"العربية\",\r\n contact: \"Send a message\",\r\n name: \"Name\",\r\n email: \"Email\",\r\n message: \"Message\",\r\n submit: \"Send message\",\r\n sent: \"Thanks — your message has been received.\",\r\n },\r\n });\r\n extend(\"ar\", {\r\n starter: {\r\n title: \"تطبيق Warlock يعمل الآن.\",\r\n introduction: \"تُعرض هذه الصفحة على الخادم ثم تُفعَّل في المتصفح.\",\r\n language: \"English\",\r\n contact: \"أرسل رسالة\",\r\n name: \"الاسم\",\r\n email: \"البريد الإلكتروني\",\r\n message: \"الرسالة\",\r\n submit: \"إرسال الرسالة\",\r\n sent: \"شكرًا — تم استلام رسالتك.\",\r\n },\r\n });\r\n}\r\n`;\r\n\r\n/**\r\n * `src/web/index.page.tsx` — one page, so \\`warlock dev\\` has something to serve\r\n * the moment this finishes.\r\n */\r\nexport const webHomePageStub = `import { http } from \"@mongez/http\";\r\nimport { setCurrentLocaleCode } from \"@mongez/localization\";\r\nimport { Form, useFormControl, type FormControlProps } from \"@mongez/react-form\";\r\nimport { transX } from \"@mongez/react-localization\";\r\nimport { v } from \"@warlock.js/seal\";\r\nimport { Link, type PageProps } from \"@warlock.js/web\";\r\nimport { useState } from \"react\";\r\n\r\nexport { register } from \"./index.register\";\r\n\r\n/**\r\n * A page route is an ordinary Warlock route whose handler renders React\r\n * instead of returning JSON.\r\n *\r\n * The URL and stable hydration name are the ones this file DECLARES below.\r\n * This page answers \\`GET \"/\"\\` because \\`route.path = \"/\"\\`, not because of\r\n * where the file lives. A page file with\r\n * no \\`route\\` export is REFUSED by both the dev server and the build.\r\n */\r\nexport const route = { path: \"/\", name: \"index\" } as const;\r\n\r\nexport const metadata = { title: \"Home\" };\r\n\r\nconst contactSchema = v.object({\r\n name: v.string().min(2).required(),\r\n email: v.email().required(),\r\n message: v.string().min(10).required(),\r\n});\r\n\r\nfunction TextInput({ label, ...controlProps }: FormControlProps & { label: string }) {\r\n const { error, getErrorProps, getInputProps } = useFormControl(controlProps);\r\n\r\n return (\r\n <div className=\"wk-field\">\r\n <label htmlFor={controlProps.name}>{label}</label>\r\n <input {...getInputProps()} />\r\n {error && <p {...getErrorProps()}>{error}</p>}\r\n </div>\r\n );\r\n}\r\n\r\n/**\r\n * Add a \\`loader\\` export to fetch data on the server, and it arrives here as\r\n * \\`data\\`, typed:\r\n *\r\n * export const loader = (async () => ({ items: await itemsRepository.all() }));\r\n * export default function HomePage({ data }: PageProps<typeof loader>) { ... }\r\n */\r\nexport default function HomePage(_props: PageProps) {\r\n // Live state. If the button below does nothing, the page rendered on the\r\n // server but never hydrated — the runtime never mounted at \\`#root\\`. This is\r\n // deliberately here so that failure is impossible to miss.\r\n const [count, setCount] = useState(0);\r\n const [locale, setLocale] = useState<\"en\" | \"ar\">(\"en\");\r\n const [submitted, setSubmitted] = useState(false);\r\n const [submitError, setSubmitError] = useState<string | null>(null);\r\n\r\n const toggleLocale = () => {\r\n const nextLocale = locale === \"en\" ? \"ar\" : \"en\";\r\n setCurrentLocaleCode(nextLocale);\r\n setLocale(nextLocale);\r\n };\r\n\r\n return (\r\n <>\r\n {/*\r\n Self-contained, dependency-free styling: plain CSS, system fonts, and\r\n CSS custom properties, scoped to this page. No CSS framework, no utility\r\n classes, no external stylesheet — this page looks the same whether or\r\n not \\`warlock add tailwind\\` has ever been run.\r\n */}\r\n <style>{\\`\r\n .wk-home {\r\n --wk-fg: #0f172a;\r\n --wk-muted: #64748b;\r\n --wk-accent: #4f46e5;\r\n --wk-border: #e2e8f0;\r\n font-family: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\r\n color: var(--wk-fg);\r\n max-width: 42rem;\r\n margin: 4rem auto;\r\n padding: 0 1.5rem;\r\n line-height: 1.6;\r\n }\r\n .wk-home h1 { font-size: 2.25rem; margin: 0 0 0.5rem; }\r\n .wk-home p { color: var(--wk-muted); margin: 0 0 1.5rem; }\r\n .wk-home code {\r\n font-family: ui-monospace, \"SFMono-Regular\", Menlo, monospace;\r\n background: #f1f5f9;\r\n padding: 0.1rem 0.35rem;\r\n border-radius: 0.25rem;\r\n }\r\n .wk-check {\r\n border: 1px solid var(--wk-border);\r\n border-radius: 0.75rem;\r\n padding: 1.25rem 1.5rem;\r\n margin: 2rem 0;\r\n }\r\n .wk-check strong { display: block; font-size: 1.5rem; }\r\n .wk-check button {\r\n font: inherit;\r\n cursor: pointer;\r\n background: var(--wk-accent);\r\n color: #fff;\r\n border: 0;\r\n border-radius: 0.5rem;\r\n padding: 0.5rem 1rem;\r\n margin-top: 0.75rem;\r\n }\r\n .wk-links { display: flex; gap: 1.25rem; font-size: 0.95rem; }\r\n .wk-links a { color: var(--wk-accent); text-decoration: none; }\r\n .wk-links a:hover { text-decoration: underline; }\r\n .wk-language { margin-left: auto; }\r\n .wk-contact { margin-top: 2rem; }\r\n .wk-field { display: grid; gap: 0.35rem; margin: 0.8rem 0; }\r\n .wk-field input, .wk-field textarea { font: inherit; padding: 0.55rem; }\r\n .wk-field p, .wk-submit-error { color: #b91c1c; margin: 0; }\r\n .wk-success { color: #047857; }\r\n \\`}</style>\r\n\r\n <main className=\"wk-home\" dir={locale === \"ar\" ? \"rtl\" : \"ltr\"}>\r\n <nav className=\"wk-links\" aria-label=\"Starter links\">\r\n <a href=\"https://warlock.js.org\" target=\"_blank\" rel=\"noreferrer\">\r\n Docs\r\n </a>\r\n <Link href=\"/\" aria-current=\"page\">\r\n Home\r\n </Link>\r\n <button\r\n className=\"wk-language\"\r\n type=\"button\"\r\n aria-pressed={locale === \"ar\"}\r\n onClick={toggleLocale}\r\n >\r\n {transX(\"starter.language\")}\r\n </button>\r\n </nav>\r\n\r\n <h1>{transX(\"starter.title\")}</h1>\r\n <p>{transX(\"starter.introduction\")}</p>\r\n\r\n <section className=\"wk-check\">\r\n <label>If this number goes up when you click, React is hydrated:</label>\r\n <strong>{count}</strong>\r\n <button type=\"button\" onClick={() => setCount((c) => c + 1)}>\r\n Count up\r\n </button>\r\n </section>\r\n\r\n <section className=\"wk-contact\" aria-labelledby=\"contact-heading\">\r\n <h2 id=\"contact-heading\">{transX(\"starter.contact\")}</h2>\r\n <Form<typeof contactSchema>\r\n id=\"contact-form\"\r\n schema={contactSchema}\r\n onSubmit={async ({ form, values }) => {\r\n setSubmitted(false);\r\n setSubmitError(null);\r\n const result = await http.post<{ message: string }>(\"/api/contact\", values);\r\n\r\n if (result.error) {\r\n if (result.error.isValidationError) {\r\n const body = result.error.body as {\r\n errors?: Array<{ input: string; error: string }>;\r\n message?: string;\r\n };\r\n form.setErrors(\r\n Object.fromEntries(\r\n (body.errors ?? []).map(({ input, error }) => [input, error]),\r\n ),\r\n );\r\n setSubmitError(body.message ?? \"Please correct the highlighted fields.\");\r\n } else {\r\n setSubmitError(\"Your message could not be sent. Please try again.\");\r\n }\r\n return;\r\n }\r\n\r\n setSubmitted(true);\r\n form.reset();\r\n }}\r\n >\r\n <TextInput name=\"name\" label={transX(\"starter.name\")} autoComplete=\"name\" />\r\n <TextInput\r\n name=\"email\"\r\n label={transX(\"starter.email\")}\r\n type=\"email\"\r\n autoComplete=\"email\"\r\n />\r\n <ContactMessage />\r\n <button type=\"submit\">{transX(\"starter.submit\")}</button>\r\n {submitError && (\r\n <p className=\"wk-submit-error\" role=\"alert\">\r\n {submitError}\r\n </p>\r\n )}\r\n {submitted && (\r\n <p className=\"wk-success\" role=\"status\">\r\n {transX(\"starter.sent\")}\r\n </p>\r\n )}\r\n </Form>\r\n </section>\r\n </main>\r\n </>\r\n );\r\n}\r\n\r\nfunction ContactMessage() {\r\n const { error, getErrorProps, getInputProps } = useFormControl({ name: \"message\" });\r\n\r\n return (\r\n <div className=\"wk-field\">\r\n <label htmlFor=\"message\">{transX(\"starter.message\")}</label>\r\n <textarea {...getInputProps()} rows={5} />\r\n {error && <p {...getErrorProps()}>{error}</p>}\r\n </div>\r\n );\r\n}\r\n`;\r\n"],"mappings":";AAAA,MAAa,mBAAmB;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;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCnC,MAAa,kBAAkB"}
1
+ {"version":3,"file":"stubs.mjs","names":[],"sources":["../../../../../../../core/src/generations/stubs.ts"],"sourcesContent":["export const accessConfigStub = `import { type AccessConfigurations } from \"@warlock.js/access\";\r\nimport { DatabaseAccessResolver } from \"app/access/services/access-resolver\";\r\n\r\n/**\r\n * Authorization configuration — read by @warlock.js/access on boot.\r\n *\r\n * The resolver is the one required piece: it tells the engine how to read a\r\n * user's roles + permissions. The ejected DatabaseAccessResolver reads roles\r\n * from the user_roles table and maps them through the roles catalog table (so\r\n * roles + their permissions are managed at runtime, in the DB).\r\n *\r\n * For a fixed, code-defined catalog with no tables, swap in DefaultAccessResolver:\r\n * import { DefaultAccessResolver } from \"@warlock.js/access\";\r\n * resolver: new DefaultAccessResolver({ admin: [\"*\"], editor: [\"orders.*\"] }),\r\n *\r\n * Multi-tenant? Add a \\`resolveTenant()\\` to the resolver to read the active\r\n * tenant from the request; checks then scope to it automatically.\r\n */\r\nconst access: AccessConfigurations = {\r\n resolver: new DatabaseAccessResolver(),\r\n\r\n // Cache resolved permission sets (default \"10m\").\r\n // cache: { ttl: \"10m\" },\r\n};\r\n\r\nexport default access;\r\n`;\r\n\r\nexport const aiConfigStub = `import type { AIConfig } from \"@warlock.js/ai\";\r\n\r\n// >>> warlock:ai-packages (auto-managed) >>>\r\n// Satellite packages augment the \"ai\" object on import — e.g. ai.workspace,\r\n// ai.tools / ai.mcp, and panoptic's ai.config({ panoptic }) wiring. The command\r\n// \"warlock add ai-workspace | ai-tools | ai-panoptic\" adds the matching\r\n// side-effect import below; keep them so the augmentation + runtime registration\r\n// load before the ai connector applies this config.\r\n// <<< warlock:ai-packages <<<\r\n\r\n/**\r\n * AI configuration — applied on boot by the ai connector, which calls\r\n * ai.config(...) with the object below. Cross-cutting defaults live here\r\n * (shared cache / snapshot stores, observability); per-call options always win.\r\n *\r\n * Wire a default model from a provider you installed, e.g.:\r\n * import { OpenAISDK } from \"@warlock.js/ai-openai\";\r\n * const openai = OpenAISDK({ apiKey: env(\"OPENAI_API_KEY\") });\r\n * // then pass openai.model({ name: \"gpt-4o-mini\" }) into your agents.\r\n */\r\nconst ai: Partial<AIConfig> = {\r\n // Default cache driver for cache-backed AI features (semantic cache, rag / memory vector stores).\r\n // defaultStore: cache.driver(\"redis\", { client }),\r\n\r\n // Observability — requires \"warlock add ai-panoptic\". Exporters + the local dashboard.\r\n // panoptic: { exporters: [], dashboard: false, observeAll: false },\r\n};\r\n\r\nexport default ai;\r\n`;\r\n\r\nexport const accessRoleModelStub = `import { Model, RegisterModel } from \"@warlock.js/cascade\";\r\nimport { type Infer, v } from \"@warlock.js/seal\";\r\n\r\n/**\r\n * Validation schema for the roles catalog — mirrors the migration columns\r\n * (snake_case). Each row is a role name plus the permission strings it grants;\r\n * wildcards work (\"orders.*\", \"*\"). The DatabaseAccessResolver maps a user's\r\n * assigned role names through this table to their effective permissions.\r\n */\r\nexport const roleSchema = v.object({\r\n name: v.string(),\r\n permissions: v.array(v.string()).default([]),\r\n});\r\n\r\nexport type RoleSchema = Infer<typeof roleSchema>;\r\n\r\n/**\r\n * The roles catalog — role name → the permissions it grants. Managed at runtime\r\n * (admins add roles + edit their permissions), unlike a fixed code map. Read by\r\n * DatabaseAccessResolver.resolvePermissions to expand a user's roles to permissions.\r\n */\r\n@RegisterModel()\r\nexport class Role extends Model<RoleSchema> {\r\n public static table = \"roles\";\r\n\r\n public static schema = roleSchema;\r\n\r\n /** The permission strings this role grants. */\r\n public get permissions(): string[] {\r\n return this.get<string[]>(\"permissions\", []);\r\n }\r\n}\r\n`;\r\n\r\nexport const accessRoleModelIndexStub = `export * from \"./role.model\";\r\n`;\r\n\r\nexport const accessRoleMigrationStub = `import { arrayText, Migration, text } from \"@warlock.js/cascade\";\r\nimport { Role } from \"../role.model\";\r\n\r\n/**\r\n * Roles catalog table. \\`name\\` is unique (one row per role); \\`permissions\\` is a\r\n * text array of the permission strings the role grants.\r\n */\r\nexport default Migration.create(Role, {\r\n name: text().notNullable().unique(),\r\n permissions: arrayText().nullable(),\r\n});\r\n`;\r\n\r\nexport const accessUserRoleModelStub = `import { access } from \"@warlock.js/access\";\r\nimport type { Auth } from \"@warlock.js/auth\";\r\nimport { Model, RegisterModel } from \"@warlock.js/cascade\";\r\nimport { type Infer, v } from \"@warlock.js/seal\";\r\n\r\n/**\r\n * Validation schema for a role assignment — mirrors the migration columns\r\n * (snake_case). \\`tenant\\` is nullable: a null tenant is a GLOBAL assignment.\r\n */\r\nexport const userRoleSchema = v.object({\r\n user_id: v.string(),\r\n user_type: v.string(),\r\n role: v.string(),\r\n tenant: v.string().optional(),\r\n});\r\n\r\nexport type UserRoleSchema = Infer<typeof userRoleSchema>;\r\n\r\n/**\r\n * The role-assignment table — which roles a user holds, optionally per tenant.\r\n * Read by DatabaseAccessResolver.resolveRoles; mutated via the statics below.\r\n * \\`assign\\` / \\`revoke\\` flush the cached permission set automatically, so callers\r\n * never need to call \\`access.flush(user, tenant)\\` themselves.\r\n */\r\n@RegisterModel()\r\nexport class UserRole extends Model<UserRoleSchema> {\r\n public static table = \"user_roles\";\r\n\r\n public static schema = userRoleSchema;\r\n\r\n /**\r\n * Role names assigned to the user in the given tenant.\r\n *\r\n * An unresolved tenant (\\`undefined\\`) scopes to GLOBAL roles only — the rows\r\n * stored with no tenant (\\`null\\`) — never the union across every tenant. The\r\n * union would be a privilege-escalation: a user who is \\`owner\\` in one tenant\r\n * must not be treated as \\`owner\\` everywhere just because a check didn't carry\r\n * a tenant. This mirrors how \\`assign(user, role)\\` stores a global row.\r\n */\r\n public static async rolesFor(user: Auth, tenant?: string): Promise<string[]> {\r\n const rows = await this.query()\r\n .where({\r\n user_id: user.id,\r\n user_type: user.userType,\r\n tenant: tenant ?? null,\r\n })\r\n .get();\r\n\r\n // De-dupe so a duplicate row (a concurrent assign that slipped past the\r\n // existence check) can't distort the resolved set.\r\n return [...new Set(rows.map((row) => row.get(\"role\") as string))];\r\n }\r\n\r\n /**\r\n * Assign a role to the user. No-op if the assignment already exists.\r\n * Flushes the user's cached permission set automatically.\r\n */\r\n public static async assign(user: Auth, role: string, tenant?: string): Promise<void> {\r\n const existing = await this.first({\r\n user_id: user.id,\r\n user_type: user.userType,\r\n role,\r\n tenant: tenant ?? null,\r\n });\r\n\r\n if (existing) return;\r\n\r\n await this.create({\r\n user_id: user.id,\r\n user_type: user.userType,\r\n role,\r\n tenant,\r\n });\r\n\r\n await access.flush(user, tenant);\r\n }\r\n\r\n /**\r\n * Remove a role assignment from the user.\r\n * Flushes the user's cached permission set automatically.\r\n */\r\n public static async revoke(user: Auth, role: string, tenant?: string): Promise<void> {\r\n await this.delete({\r\n user_id: user.id,\r\n user_type: user.userType,\r\n role,\r\n tenant: tenant ?? null,\r\n });\r\n\r\n await access.flush(user, tenant);\r\n }\r\n}\r\n`;\r\n\r\nexport const accessUserRoleModelIndexStub = `export * from \"./user-role.model\";\r\n`;\r\n\r\nexport const accessUserRoleMigrationStub = `import { Migration, text, uuid } from \"@warlock.js/cascade\";\r\nimport { UserRole } from \"../user-role.model\";\r\n\r\n/**\r\n * Role-assignment table. \\`user_id\\` is a UUID — override this migration if your\r\n * user ids are integers. The composite index powers the per-user (per-tenant)\r\n * lookup the resolver runs on every check.\r\n */\r\nexport default Migration.create(\r\n UserRole,\r\n {\r\n user_id: uuid().notNullable().index(),\r\n user_type: text().notNullable(),\r\n role: text().notNullable().index(),\r\n tenant: text().nullable().index(),\r\n },\r\n {\r\n index: [{ columns: [\"user_id\", \"user_type\", \"tenant\"] }],\r\n },\r\n);\r\n`;\r\n\r\nexport const accessResolverStub = `import type { AccessResolver } from \"@warlock.js/access\";\r\nimport type { Auth } from \"@warlock.js/auth\";\r\nimport { Role } from \"app/access/models/role\";\r\nimport { UserRole } from \"app/access/models/user-role\";\r\n\r\n/**\r\n * The app's access adapter — connects @warlock.js/access to the ejected role\r\n * tables. Roles come from the user_roles assignment table; permissions are\r\n * expanded by mapping those role names through the roles catalog table. Both\r\n * are managed at runtime (in the DB), so admins can add roles + edit their\r\n * permissions without a deploy.\r\n *\r\n * The engine owns the hard parts (wildcard matching, caching, fail-closed); this\r\n * resolver only fetches — keep it dumb, never cache inside it.\r\n */\r\nexport class DatabaseAccessResolver implements AccessResolver {\r\n /** The role names this user holds (powers \\`hasRole\\` / \\`hasAnyRole\\`). */\r\n public async resolveRoles(user: Auth, tenant?: string): Promise<string[]> {\r\n return UserRole.rolesFor(user, tenant);\r\n }\r\n\r\n /** The effective permission strings this user has (powers \\`can\\` / \\`authorize\\`). */\r\n public async resolvePermissions(user: Auth, tenant?: string): Promise<string[]> {\r\n const names = await this.resolveRoles(user, tenant);\r\n\r\n if (names.length === 0) return [];\r\n\r\n const roles = await Role.query().whereIn(\"name\", names).get();\r\n\r\n // Flatten + de-dupe so two roles granting the same permission yield one entry.\r\n return [...new Set(roles.flatMap((role) => role.permissions))];\r\n }\r\n\r\n /**\r\n * Optional. Resolve the ambient tenant when a check doesn't pass one\r\n * explicitly — derive it from the authenticated user (safer than reading\r\n * client request input, which a caller could spoof). Uncomment + adapt for a\r\n * multi-tenant app (single-tenant apps leave this off and return undefined).\r\n */\r\n // public resolveTenant(user: Auth): string | undefined {\r\n // return user.get(\"organization_id\");\r\n // }\r\n}\r\n`;\r\n\r\nexport const socketConfigStub = `import type { SocketOptions } from \"@warlock.js/core\";\r\n\r\n/**\r\n * Socket.IO configuration — read by the framework's socket connector\r\n * on boot. When the HTTP server is running the socket server attaches\r\n * to it; otherwise it listens on its own configured port.\r\n *\r\n * Remove this file to disable the socket server entirely.\r\n */\r\nexport default {\r\n options: {\r\n cors: {\r\n origin: \"*\",\r\n },\r\n },\r\n} as SocketOptions;\r\n`;\r\n\r\nexport const communicatorsConfigStub = `import { env } from \"@warlock.js/core\";\r\nimport type { BrokerConfigurations, RabbitMQClientOptions } from \"@warlock.js/herald\";\r\n\r\nconst heraldConfigurations: BrokerConfigurations<RabbitMQClientOptions> = {\r\n driver: \"rabbitmq\",\r\n name: \"default\",\r\n isDefault: true,\r\n\r\n // ============================================================================\r\n // Connection Settings\r\n // ============================================================================\r\n\r\n host: env(\"RABBITMQ_HOST\", \"localhost\"),\r\n port: env(\"RABBITMQ_PORT\", 5672),\r\n username: env(\"RABBITMQ_USERNAME\", \"guest\"),\r\n password: env(\"RABBITMQ_PASSWORD\", \"guest\"),\r\n vhost: env(\"RABBITMQ_VHOST\", \"/\"),\r\n\r\n // Or use connection URI (takes precedence over host/port)\r\n // uri: env(\"RABBITMQ_URL\"),\r\n\r\n // ============================================================================\r\n // Connection Options\r\n // ============================================================================\r\n\r\n /** Heartbeat interval in seconds */\r\n heartbeat: 60,\r\n\r\n /** Connection timeout in milliseconds */\r\n connectionTimeout: 10000,\r\n\r\n /** Enable automatic reconnection on disconnect */\r\n reconnect: true,\r\n\r\n /** Delay between reconnection attempts in milliseconds */\r\n reconnectDelay: 5_000,\r\n\r\n // ============================================================================\r\n // Consumer Options\r\n // ============================================================================\r\n\r\n /** Default prefetch count (number of unacknowledged messages per consumer) */\r\n prefetch: 10,\r\n\r\n // ============================================================================\r\n // Client Options (Native amqplib options)\r\n // ============================================================================\r\n // These options are passed directly to amqplib.connect()\r\n // for low-level configuration like frame size, TLS, socket options, etc.\r\n // ============================================================================\r\n clientOptions: {\r\n // Frame max size in bytes (0 = no limit)\r\n // frameMax: 0,\r\n\r\n // Channel max (0 = unlimited)\r\n // channelMax: 0,\r\n\r\n // Socket options\r\n socket: {\r\n // Enable TCP keep-alive\r\n keepAlive: true,\r\n\r\n // Disable Nagle's algorithm for lower latency\r\n noDelay: true,\r\n\r\n // Socket timeout (in addition to heartbeat)\r\n // timeout: 30000,\r\n },\r\n\r\n // TLS/SSL options (uncomment for secure connections)\r\n // socket: {\r\n // ca: fs.readFileSync('/path/to/ca.pem'),\r\n // cert: fs.readFileSync('/path/to/cert.pem'),\r\n // key: fs.readFileSync('/path/to/key.pem'),\r\n // rejectUnauthorized: true,\r\n // },\r\n },\r\n};\r\n\r\nexport default heraldConfigurations;\r\n`;\r\n\r\nexport const notificationsConfigStub = `import { type NotificationConfig, inApp, mailChannel } from \"@warlock.js/notifications\";\r\nimport { Notification } from \"app/notifications/notification.model\";\r\n\r\n/**\r\n * Notifications configuration. Auto-loaded from src/config on boot — the\r\n * framework's notifications connector reads this default export and hands it to\r\n * setNotificationConfig, so this file stays declarative (no side-effect call).\r\n *\r\n * Each channel is payload-typed, so notify.mail(...) / notify.database(...)\r\n * and defineNotification are type-checked against the registry.\r\n *\r\n * Channels enabled here:\r\n * - mail wraps @warlock.js/core sendMail; route is notifiable.email.\r\n * The \"from\" address defaults to config/mail.ts; override per\r\n * channel with mailChannel({ from: \"no-reply@yourapp.com\" }).\r\n * - database in-app store backed by the Notification model. The \"inApp\"\r\n * facade exposes the recipient-scoped read API: listUnread,\r\n * countUnread, markAsRead, dismiss, ...\r\n *\r\n * Async delivery (.queue()) is OPTIONAL: run \"npx warlock add herald\",\r\n * import { heraldQueue } from \"@warlock.js/notifications\", and uncomment the\r\n * queue line below.\r\n */\r\nconst config: NotificationConfig = {\r\n channels: {\r\n mail: mailChannel(),\r\n database: inApp.configure({ model: Notification }),\r\n },\r\n\r\n // Async queue — requires @warlock.js/herald (npx warlock add herald):\r\n // queue: heraldQueue(),\r\n};\r\n\r\nexport default config;\r\n`;\r\n\r\nexport const notificationModelStub = `import { RegisterModel } from \"@warlock.js/cascade\";\r\nimport { DatabaseNotification, type NotificationColumnMap } from \"@warlock.js/notifications\";\r\nimport { v } from \"@warlock.js/seal\";\r\n\r\n/**\r\n * Validation schema for the notifications table — mirrors the migration\r\n * columns (snake_case). Cascade validates + casts every write against it:\r\n * nullable columns use .nullish() (may be absent or null), and payload is\r\n * free-form JSON. Keep this in sync with the migration + columnMap when you\r\n * add or rename columns.\r\n */\r\nconst notificationSchema = v.object({\r\n user_id: v.string(),\r\n type: v.string(),\r\n title: v.string(),\r\n body: v.string().nullish(),\r\n payload: v.record(v.any()).nullish(),\r\n read_at: v.date().nullish(),\r\n idempotency_key: v.string().nullish(),\r\n});\r\n\r\n/**\r\n * In-app notification model.\r\n *\r\n * Extends the package's DatabaseNotification base, which provides the stable\r\n * accessors (recipientId, tenantId, isRead, readAt, markRead) — all derived\r\n * from the columnMap below. The read/write API lives on the inApp facade\r\n * (configured in config/notifications.ts); you rarely touch this class directly.\r\n */\r\n@RegisterModel()\r\nexport class Notification extends DatabaseNotification {\r\n public static table = \"notifications\";\r\n public static schema = notificationSchema;\r\n\r\n /**\r\n * Maps the in-app store's roles to your columns. This default is\r\n * single-tenant + read_at-only. Add tenant: \"organization_id\" for\r\n * multi-tenant; use isRead: \"is_read\" (instead of, or alongside, readAt) to\r\n * track a boolean read flag. The migration + accessors all follow this map.\r\n */\r\n public static columnMap: NotificationColumnMap = { readAt: \"read_at\" };\r\n}\r\n`;\r\n\r\nexport const notificationMigrationStub = `import { Migration } from \"@warlock.js/cascade\";\r\nimport { notificationColumns } from \"@warlock.js/notifications\";\r\nimport { Notification } from \"../notification.model\";\r\n\r\n/**\r\n * Notifications table.\r\n *\r\n * Columns come from notificationColumns(Notification) — the recipient / tenant\r\n * / read-state names follow the model's columnMap; type / title / body /\r\n * payload / idempotency_key are fixed. Spread it to add your own columns\r\n * (remember to mirror them in the model schema):\r\n *\r\n * import { uuid } from \"@warlock.js/cascade\";\r\n *\r\n * export default Migration.create(Notification, {\r\n * ...notificationColumns(Notification),\r\n * // category_id: uuid().index().nullable(),\r\n * });\r\n */\r\nexport default Migration.create(Notification, notificationColumns(Notification));\r\n`;\r\n\r\nexport const notificationControllersStub = `import { type RequestHandler } from \"@warlock.js/core\";\r\nimport { inApp, type Id } from \"@warlock.js/notifications\";\r\n\r\n/**\r\n * The authenticated user's notification HTTP surface — thin wrappers over the\r\n * recipient-scoped \\`inApp\\` facade (a foreign id can never touch another user's\r\n * rows). Notifications are produced by domain events, never over HTTP, so there\r\n * is no create. Trim or split these as your app grows.\r\n */\r\n\r\n/**\r\n * Read \\`id\\` off \\`request.user\\` without assuming this app's \\`RequestUser\\`\r\n * augmentation declares it — \\`RequestUser\\` is empty by default (see\r\n * \\`@warlock.js/core\\`'s \\`RequestUser\\` docs), so a narrow runtime read survives\r\n * any augmentation shape instead of assuming \\`.id\\` exists at the type level.\r\n * \\`inApp\\` only ever needs the id (it reduces a \\`Notifiable\\` to one via\r\n * \\`recipient.id\\` internally), so reading it here — rather than forwarding\r\n * \\`request.user\\` itself — also skips a needless \\`Notifiable\\` cast.\r\n */\r\nfunction recipientId(user: unknown): Id {\r\n if (user && typeof user === \"object\" && \"id\" in user) {\r\n const id = (user as { id?: unknown }).id;\r\n\r\n if (typeof id === \"string\" || typeof id === \"number\") return id;\r\n }\r\n\r\n throw new Error(\"Authenticated request is missing a usable user id\");\r\n}\r\n\r\n/** GET /notifications — list, most recent first (page / limit / type / unread via query). */\r\nexport const listNotificationsController: RequestHandler = async ({ request, response }) => {\r\n const { data, pagination } = await inApp.list(recipientId(request.user), request.all());\r\n\r\n return response.success({ notifications: data, pagination });\r\n};\r\n\r\nlistNotificationsController.description = \"List notifications\";\r\n\r\n/** GET /notifications/unread-count — drives the bell badge. */\r\nexport const unreadNotificationsCountController: RequestHandler = async ({\r\n request,\r\n response,\r\n}) => {\r\n const count = await inApp.countUnread(recipientId(request.user));\r\n\r\n return response.success({ count });\r\n};\r\n\r\nunreadNotificationsCountController.description = \"Unread notifications count\";\r\n\r\n/** PATCH /notifications/:id/read — mark one read, return the updated row. */\r\nexport const markNotificationReadController: RequestHandler = async ({ request, response }) => {\r\n const id = request.input(\"id\");\r\n const userId = recipientId(request.user);\r\n\r\n await inApp.markAsRead(userId, id);\r\n const notification = await inApp.find(userId, id);\r\n\r\n return response.success({ notification });\r\n};\r\n\r\nmarkNotificationReadController.description = \"Mark notification read\";\r\n\r\n/** PATCH /notifications/read-all — mark every unread one read. */\r\nexport const markAllNotificationsReadController: RequestHandler = async ({\r\n request,\r\n response,\r\n}) => {\r\n const count = await inApp.markAsRead(recipientId(request.user));\r\n\r\n return response.success({ count });\r\n};\r\n\r\nmarkAllNotificationsReadController.description = \"Mark all notifications read\";\r\n\r\n/** DELETE /notifications — dismiss all for the user. */\r\nexport const clearNotificationsController: RequestHandler = async ({ request, response }) => {\r\n await inApp.dismiss(recipientId(request.user));\r\n\r\n return response.noContent();\r\n};\r\n\r\nclearNotificationsController.description = \"Clear notifications\";\r\n\r\n/** DELETE /notifications/:id — dismiss one. */\r\nexport const deleteNotificationController: RequestHandler = async ({ request, response }) => {\r\n await inApp.dismiss(recipientId(request.user), request.input(\"id\"));\r\n\r\n return response.noContent();\r\n};\r\n\r\ndeleteNotificationController.description = \"Delete notification\";\r\n`;\r\n\r\nexport const notificationRoutesStub = `import { authMiddleware } from \"@warlock.js/auth\";\r\nimport { router } from \"@warlock.js/core\";\r\nimport {\r\n clearNotificationsController,\r\n deleteNotificationController,\r\n listNotificationsController,\r\n markAllNotificationsReadController,\r\n markNotificationReadController,\r\n unreadNotificationsCountController,\r\n} from \"./controllers/notifications.controller\";\r\n\r\n/**\r\n * Notification routes — the authenticated user's read + dismiss surface.\r\n *\r\n * Notifications are produced by domain events (never created over HTTP), so\r\n * there is no POST. Every route is gated by \\`authMiddleware\\` and recipient-\r\n * scoped by \\`inApp\\` (a foreign id touches zero rows). Delete any endpoint you\r\n * don't need; if your app reads notifications over sockets/GraphQL instead,\r\n * delete this file + the controllers entirely.\r\n */\r\nrouter.group({ prefix: \"/notifications\", middleware: [authMiddleware([])] }, () => {\r\n router.get(\"/\", listNotificationsController);\r\n router.get(\"/unread-count\", unreadNotificationsCountController);\r\n router.patch(\"/read-all\", markAllNotificationsReadController);\r\n router.patch(\"/:id/read\", markNotificationReadController);\r\n router.delete(\"/\", clearNotificationsController);\r\n router.delete(\"/:id\", deleteNotificationController);\r\n});\r\n`;\r\n\r\n/**\r\n * `src/web/root.tsx` — the application root for the SSR page layer.\r\n *\r\n * Deliberately minimal. The framework ships a default root, so this exists to\r\n * give you a place to start rather than because anything requires it. The\r\n * reference app (`v5/app/src/web/root.tsx`) is where to look for the fuller\r\n * shape: middleware, an app-level loader, locales, an ErrorBoundary.\r\n */\r\nexport const webRootStub = `import type { AppProps } from \"@warlock.js/web\";\r\nimport { Head, Scripts } from \"@warlock.js/web\";\r\n\r\n/**\r\n * The application root.\r\n *\r\n * NOT async, and it receives no request/response: it renders on the server and\r\n * again in the browser during hydration, where neither exists.\r\n */\r\nexport default function App({ children }: AppProps) {\r\n return (\r\n <html lang=\"en\">\r\n <head>\r\n {/*\r\n Placement only. The framework injects the page's \\`metadata\\`, the\r\n stylesheet and preload tags for this route, and the canonical links\r\n into <head> by default — <Head /> just says WHERE they land.\r\n\r\n Do not add a <title> here: the page's \\`metadata\\` owns it, and a root\r\n that emits one too produces two.\r\n */}\r\n <Head />\r\n <link rel=\"icon\" href=\"data:,\" />\r\n </head>\r\n <body>\r\n {/*\r\n REQUIRED — this is the hydration mount point, not a styling wrapper.\r\n\r\n The browser runtime looks up \\`#root\\` and hydrates that element only.\r\n Remove this div, or rename the id, and the page still renders from the\r\n server but never becomes interactive: the runtime throws in the console\r\n and nothing on screen changes.\r\n\r\n Wrap it in your own markup freely, and put anything that must live\r\n outside the hydrated tree (a static footer, a portal target) outside\r\n it — just keep an element with \\`id=\"root\"\\` around {children}.\r\n */}\r\n <div id=\"root\">{children}</div>\r\n {/*\r\n The hydration payload and module tags. Written explicitly because\r\n placement occasionally matters — a CSP nonce, or ordering against\r\n your own scripts.\r\n */}\r\n <Scripts />\r\n </body>\r\n </html>\r\n );\r\n}\r\n`;\r\n\r\n/**\r\n * `src/app/contact/controllers/contact.controller.ts` — a real API endpoint\r\n * for the Web starter's contact form. It intentionally has no persistence\r\n * dependency: replace the acknowledgement with a mail/job/database action.\r\n */\r\nexport const webContactControllerStub = `import { type Request, type RequestHandler } from \"@warlock.js/core\";\r\nimport { type Infer, v } from \"@warlock.js/seal\";\r\n\r\nexport const contactSchema = v.object({\r\n name: v.string().min(2),\r\n email: v.email(),\r\n message: v.string().min(10),\r\n});\r\n\r\nexport type ContactSchema = Infer.Output<typeof contactSchema>;\r\n\r\n/** POST /api/contact — validates the starter contact form. */\r\nexport const contactController: RequestHandler<Request<ContactSchema>> = async ({\r\n request,\r\n response,\r\n}) => {\r\n const contact = request.validated();\r\n\r\n // Replace this with delivery/persistence for your app. Keeping the accepted\r\n // payload visible makes the endpoint useful while remaining side-effect free.\r\n return response.success({\r\n message: \"Thanks, \" + contact.name + \". Your message has been received.\",\r\n });\r\n};\r\n\r\ncontactController.validation = { schema: contactSchema };\r\n`;\r\n\r\n/** `src/app/contact/routes.ts` — discovered by the standard app route loader. */\r\nexport const webContactRoutesStub = `import { router } from \"@warlock.js/core\";\r\nimport { contactController } from \"./controllers/contact.controller\";\r\n\r\nrouter.post(\"/api/contact\", contactController);\r\n`;\r\n\r\n/**\r\n * `src/web/index.register.ts` — universal static setup for the starter page.\r\n *\r\n * The page re-exports this stable binding so Warlock's `register()` lifecycle\r\n * still sees it in both realms without making React Fast Refresh treat every\r\n * JSX edit as an incompatible function-export replacement.\r\n */\r\nexport const webHomeRegisterStub = `import { extend } from \"@mongez/localization\";\r\n\r\nexport function register() {\r\n extend(\"en\", {\r\n starter: {\r\n title: \"Your Warlock app is running.\",\r\n introduction: \"This page is rendered on the server and hydrated in the browser.\",\r\n language: \"العربية\",\r\n contact: \"Send a message\",\r\n name: \"Name\",\r\n email: \"Email\",\r\n message: \"Message\",\r\n submit: \"Send message\",\r\n sent: \"Thanks — your message has been received.\",\r\n },\r\n });\r\n extend(\"ar\", {\r\n starter: {\r\n title: \"تطبيق Warlock يعمل الآن.\",\r\n introduction: \"تُعرض هذه الصفحة على الخادم ثم تُفعَّل في المتصفح.\",\r\n language: \"English\",\r\n contact: \"أرسل رسالة\",\r\n name: \"الاسم\",\r\n email: \"البريد الإلكتروني\",\r\n message: \"الرسالة\",\r\n submit: \"إرسال الرسالة\",\r\n sent: \"شكرًا — تم استلام رسالتك.\",\r\n },\r\n });\r\n}\r\n`;\r\n\r\n/**\r\n * `src/web/index.page.tsx` — one page, so \\`warlock dev\\` has something to serve\r\n * the moment this finishes.\r\n */\r\nexport const webHomePageStub = `import { http } from \"@mongez/http\";\r\nimport { setCurrentLocaleCode } from \"@mongez/localization\";\r\nimport { Form, useFormControl, type FormControlProps } from \"@mongez/react-form\";\r\nimport { transX } from \"@mongez/react-localization\";\r\nimport { v } from \"@warlock.js/seal\";\r\nimport { Link, type PageProps } from \"@warlock.js/web\";\r\nimport { useState } from \"react\";\r\n\r\nexport { register } from \"./index.register\";\r\n\r\n/**\r\n * A page route is an ordinary Warlock route whose handler renders React\r\n * instead of returning JSON.\r\n *\r\n * The URL and stable hydration name are the ones this file DECLARES below.\r\n * This page answers \\`GET \"/\"\\` because \\`route.path = \"/\"\\`, not because of\r\n * where the file lives. A page file with\r\n * no \\`route\\` export is REFUSED by both the dev server and the build.\r\n */\r\nexport const route = { path: \"/\", name: \"index\" } as const;\r\n\r\nexport const metadata = { title: \"Home\" };\r\n\r\nconst contactSchema = v.object({\r\n name: v.string().min(2),\r\n email: v.email(),\r\n message: v.string().min(10),\r\n});\r\n\r\nfunction TextInput({ label, ...controlProps }: FormControlProps & { label: string }) {\r\n const { error, getErrorProps, getInputProps } = useFormControl(controlProps);\r\n\r\n return (\r\n <div className=\"wk-field\">\r\n <label htmlFor={controlProps.name}>{label}</label>\r\n <input {...getInputProps()} />\r\n {error && <p {...getErrorProps()}>{error}</p>}\r\n </div>\r\n );\r\n}\r\n\r\n/**\r\n * Add a \\`loader\\` export to fetch data on the server, and it arrives here as\r\n * \\`data\\`, typed:\r\n *\r\n * export const loader = (async () => ({ items: await itemsRepository.all() }));\r\n * export default function HomePage({ data }: PageProps<typeof loader>) { ... }\r\n */\r\nexport default function HomePage(_props: PageProps) {\r\n // Live state. If the button below does nothing, the page rendered on the\r\n // server but never hydrated — the runtime never mounted at \\`#root\\`. This is\r\n // deliberately here so that failure is impossible to miss.\r\n const [count, setCount] = useState(0);\r\n const [locale, setLocale] = useState<\"en\" | \"ar\">(\"en\");\r\n const [submitted, setSubmitted] = useState(false);\r\n const [submitError, setSubmitError] = useState<string | null>(null);\r\n\r\n const toggleLocale = () => {\r\n const nextLocale = locale === \"en\" ? \"ar\" : \"en\";\r\n setCurrentLocaleCode(nextLocale);\r\n setLocale(nextLocale);\r\n };\r\n\r\n return (\r\n <>\r\n {/*\r\n Self-contained, dependency-free styling: plain CSS, system fonts, and\r\n CSS custom properties, scoped to this page. No CSS framework, no utility\r\n classes, no external stylesheet — this page looks the same whether or\r\n not \\`warlock add tailwind\\` has ever been run.\r\n */}\r\n <style>{\\`\r\n .wk-home {\r\n --wk-fg: #0f172a;\r\n --wk-muted: #64748b;\r\n --wk-accent: #4f46e5;\r\n --wk-border: #e2e8f0;\r\n font-family: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\r\n color: var(--wk-fg);\r\n max-width: 42rem;\r\n margin: 4rem auto;\r\n padding: 0 1.5rem;\r\n line-height: 1.6;\r\n }\r\n .wk-home h1 { font-size: 2.25rem; margin: 0 0 0.5rem; }\r\n .wk-home p { color: var(--wk-muted); margin: 0 0 1.5rem; }\r\n .wk-home code {\r\n font-family: ui-monospace, \"SFMono-Regular\", Menlo, monospace;\r\n background: #f1f5f9;\r\n padding: 0.1rem 0.35rem;\r\n border-radius: 0.25rem;\r\n }\r\n .wk-check {\r\n border: 1px solid var(--wk-border);\r\n border-radius: 0.75rem;\r\n padding: 1.25rem 1.5rem;\r\n margin: 2rem 0;\r\n }\r\n .wk-check strong { display: block; font-size: 1.5rem; }\r\n .wk-check button {\r\n font: inherit;\r\n cursor: pointer;\r\n background: var(--wk-accent);\r\n color: #fff;\r\n border: 0;\r\n border-radius: 0.5rem;\r\n padding: 0.5rem 1rem;\r\n margin-top: 0.75rem;\r\n }\r\n .wk-links { display: flex; gap: 1.25rem; font-size: 0.95rem; }\r\n .wk-links a { color: var(--wk-accent); text-decoration: none; }\r\n .wk-links a:hover { text-decoration: underline; }\r\n .wk-language { margin-left: auto; }\r\n .wk-contact { margin-top: 2rem; }\r\n .wk-field { display: grid; gap: 0.35rem; margin: 0.8rem 0; }\r\n .wk-field input, .wk-field textarea { font: inherit; padding: 0.55rem; }\r\n .wk-field p, .wk-submit-error { color: #b91c1c; margin: 0; }\r\n .wk-success { color: #047857; }\r\n \\`}</style>\r\n\r\n <main className=\"wk-home\" dir={locale === \"ar\" ? \"rtl\" : \"ltr\"}>\r\n <nav className=\"wk-links\" aria-label=\"Starter links\">\r\n <a href=\"https://warlock.js.org\" target=\"_blank\" rel=\"noreferrer\">\r\n Docs\r\n </a>\r\n <Link href=\"/\" aria-current=\"page\">\r\n Home\r\n </Link>\r\n <button\r\n className=\"wk-language\"\r\n type=\"button\"\r\n aria-pressed={locale === \"ar\"}\r\n onClick={toggleLocale}\r\n >\r\n {transX(\"starter.language\")}\r\n </button>\r\n </nav>\r\n\r\n <h1>{transX(\"starter.title\")}</h1>\r\n <p>{transX(\"starter.introduction\")}</p>\r\n\r\n <section className=\"wk-check\">\r\n <label>If this number goes up when you click, React is hydrated:</label>\r\n <strong>{count}</strong>\r\n <button type=\"button\" onClick={() => setCount((c) => c + 1)}>\r\n Count up\r\n </button>\r\n </section>\r\n\r\n <section className=\"wk-contact\" aria-labelledby=\"contact-heading\">\r\n <h2 id=\"contact-heading\">{transX(\"starter.contact\")}</h2>\r\n <Form<typeof contactSchema>\r\n id=\"contact-form\"\r\n schema={contactSchema}\r\n onSubmit={async ({ form, values }) => {\r\n setSubmitted(false);\r\n setSubmitError(null);\r\n const result = await http.post<{ message: string }>(\"/api/contact\", values);\r\n\r\n if (result.error) {\r\n if (result.error.isValidationError) {\r\n const body = result.error.body as {\r\n errors?: Array<{ input: string; error: string }>;\r\n message?: string;\r\n };\r\n form.setErrors(\r\n Object.fromEntries(\r\n (body.errors ?? []).map(({ input, error }) => [input, error]),\r\n ),\r\n );\r\n setSubmitError(body.message ?? \"Please correct the highlighted fields.\");\r\n } else {\r\n setSubmitError(\"Your message could not be sent. Please try again.\");\r\n }\r\n return;\r\n }\r\n\r\n setSubmitted(true);\r\n form.reset();\r\n }}\r\n >\r\n <TextInput name=\"name\" label={transX(\"starter.name\")} autoComplete=\"name\" />\r\n <TextInput\r\n name=\"email\"\r\n label={transX(\"starter.email\")}\r\n type=\"email\"\r\n autoComplete=\"email\"\r\n />\r\n <ContactMessage />\r\n <button type=\"submit\">{transX(\"starter.submit\")}</button>\r\n {submitError && (\r\n <p className=\"wk-submit-error\" role=\"alert\">\r\n {submitError}\r\n </p>\r\n )}\r\n {submitted && (\r\n <p className=\"wk-success\" role=\"status\">\r\n {transX(\"starter.sent\")}\r\n </p>\r\n )}\r\n </Form>\r\n </section>\r\n </main>\r\n </>\r\n );\r\n}\r\n\r\nfunction ContactMessage() {\r\n const { error, getErrorProps, getInputProps } = useFormControl({ name: \"message\" });\r\n\r\n return (\r\n <div className=\"wk-field\">\r\n <label htmlFor=\"message\">{transX(\"starter.message\")}</label>\r\n <textarea {...getInputProps()} rows={5} />\r\n {error && <p {...getErrorProps()}>{error}</p>}\r\n </div>\r\n );\r\n}\r\n`;\r\n"],"mappings":";AAAA,MAAa,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BhC,MAAa,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+B5B,MAAa,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCnC,MAAa,2BAA2B;;AAGxC,MAAa,0BAA0B;;;;;;;;;;;;AAavC,MAAa,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FvC,MAAa,+BAA+B;;AAG5C,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;;;;AAsB3C,MAAa,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6ClC,MAAa,mBAAmB;;;;;;;;;;;;;;;;;AAkBhC,MAAa,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