@warlock.js/core 5.7.0 → 5.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/esm/cli/cli-commands.manager.mjs +2 -2
- package/esm/cli/cli-commands.manager.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/index.mjs +2 -0
- package/esm/cli/commands/doctor/checks/index.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/jwt-secret.check.mjs +55 -0
- package/esm/cli/commands/doctor/checks/jwt-secret.check.mjs.map +1 -0
- package/esm/cli/commands/generate/generators/controller.generator.mjs +4 -4
- package/esm/cli/commands/generate/generators/controller.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/migration.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/model.generator.mjs +4 -4
- package/esm/cli/commands/generate/generators/model.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/module.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/repository.generator.mjs +4 -4
- package/esm/cli/commands/generate/generators/repository.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/resource.generator.mjs +4 -4
- package/esm/cli/commands/generate/generators/resource.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/service.generator.mjs +4 -4
- package/esm/cli/commands/generate/generators/service.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/templates/stubs.mjs +6 -3
- package/esm/cli/commands/generate/templates/stubs.mjs.map +1 -1
- package/esm/dev-server/files-orchestrator.mjs +1 -0
- package/esm/dev-server/files-orchestrator.mjs.map +1 -1
- package/esm/dev-server/parse-imports.mjs +1 -1
- package/esm/dev-server/parse-imports.mjs.map +1 -1
- package/esm/generations/features/shadcn.feature.mjs +1 -0
- package/esm/generations/features/shadcn.feature.mjs.map +1 -1
- package/esm/generations/stubs.mjs +6 -6
- package/esm/generations/stubs.mjs.map +1 -1
- package/esm/http/boot-port-preflight.d.mts +25 -1
- package/esm/http/boot-port-preflight.d.mts.map +1 -1
- package/esm/http/boot-port-preflight.mjs +51 -2
- package/esm/http/boot-port-preflight.mjs.map +1 -1
- package/esm/http/index.d.mts +1 -1
- package/esm/http/index.mjs +1 -1
- package/esm/index.d.mts +2 -2
- package/esm/index.mjs +2 -2
- package/esm/utils/load-environment.mjs +4 -1
- package/esm/utils/load-environment.mjs.map +1 -1
- package/esm/utils/recorded-environment-overrides.mjs +41 -0
- package/esm/utils/recorded-environment-overrides.mjs.map +1 -0
- package/llms-full.txt +3 -0
- package/package.json +12 -12
- package/skills/warlock-doctor/SKILL.md +3 -0
|
@@ -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\";\
|
|
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
|
|
13
|
-
console.log(colors.yellow("Example: warlock
|
|
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
|
|
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
|
|
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\";\
|
|
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
|
|
13
|
-
console.log(colors.yellow("Example: warlock
|
|
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
|
|
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
|
|
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\";\
|
|
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
|
-
|
|
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
|
|
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":";;;;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
{"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: 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,iBAA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S,OAAO,mCAAmC,KAAK,SAAS,MAAM,eAAe,GAAG;;QAEnH,KAAK,SAAS,MAAM;;;;cAId,KAAK,SAAS,OAAO,6BAA6B,KAAK,SAAS,MAAM;;eAErE,KAAK,SAAS,OAAO,iBAAiB,KAAK,SAAS,OAAO;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"}
|
|
@@ -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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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,cAA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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"}
|
|
@@ -281,7 +281,7 @@ function clearFileExistsCache() {
|
|
|
281
281
|
async function cachedFileExists(filePath) {
|
|
282
282
|
if (fileExistsCache.has(filePath)) return fileExistsCache.get(filePath);
|
|
283
283
|
const exists = await fileExistsAsync(filePath);
|
|
284
|
-
fileExistsCache.set(filePath, exists);
|
|
284
|
+
if (exists) fileExistsCache.set(filePath, exists);
|
|
285
285
|
return exists;
|
|
286
286
|
}
|
|
287
287
|
async function tryResolveWithExtensions(basePath) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parse-imports.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/parse-imports.ts"],"sourcesContent":["import { fileExistsAsync, directoryExistsAsync } from \"@warlock.js/fs\";\nimport { type ImportSpecifier, parse } from \"es-module-lexer\";\nimport path from \"node:path\";\nimport { Path } from \"../utils/normalized-path\";\nimport { tsconfigManager } from \"./tsconfig-manager\";\n\n/**\n * Detect if a file contains only type definitions (no runtime code)\n *\n * A file is considered type-only if ALL its exports are:\n * - interface declarations\n * - type alias declarations\n * - export type { ... } statements\n * - export type { ... } from \"...\" statements\n *\n * Files with any of these are NOT type-only:\n * - export const/let/var\n * - export function\n * - export class\n * - export default (non-type)\n * - export { ... } (without type keyword)\n * - export * from (without type keyword)\n *\n * @param source - The source code to analyze\n * @returns true if the file exports only types\n */\nexport function isTypeOnlyFile(source: string): boolean {\n // Remove comments to avoid false positives\n const withoutComments = source\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\") // block comments\n .replace(/\\/\\/.*$/gm, \"\"); // line comments\n\n // Remove string literals to avoid false positives\n const withoutStrings = withoutComments\n .replace(/'(?:[^'\\\\]|\\\\.)*'/g, \"''\")\n .replace(/\"(?:[^\"\\\\]|\\\\.)*\"/g, '\"\"')\n .replace(/`(?:[^`\\\\]|\\\\.)*`/g, \"``\");\n\n // Patterns for type-only exports (these are safe)\n const typeOnlyPatterns = [\n /export\\s+type\\s+\\{[^}]*\\}/g, // export type { Foo, Bar }\n /export\\s+type\\s+\\{[^}]*\\}\\s+from\\s+['\"]/g, // export type { Foo } from \"...\"\n /export\\s+interface\\s+\\w+/g, // export interface Foo\n /export\\s+type\\s+\\w+\\s*=/g, // export type Foo =\n ];\n\n // Remove all type-only exports from consideration\n let remaining = withoutStrings;\n for (const pattern of typeOnlyPatterns) {\n remaining = remaining.replace(pattern, \"\");\n }\n\n // Patterns for runtime exports (these make the file NOT type-only)\n const runtimeExportPatterns = [\n /export\\s+(?:const|let|var)\\s+\\w+/g, // export const/let/var foo\n /export\\s+function\\s+\\w+/g, // export function foo\n /export\\s+async\\s+function\\s+\\w+/g, // export async function foo\n /export\\s+class\\s+\\w+/g, // export class Foo\n /export\\s+enum\\s+\\w+/g, // export enum Foo (enums have runtime value)\n /export\\s+default\\s+(?!type\\s)/g, // export default (not type)\n /export\\s+\\{[^}]*\\}(?!\\s+from)/g, // export { foo } (local re-export without type)\n /export\\s+\\{[^}]*\\}\\s+from\\s+['\"][^'\"]+['\"]/g, // export { foo } from (without type)\n /export\\s+\\*\\s+from\\s+['\"][^'\"]+['\"]/g, // export * from (re-exports everything)\n /export\\s+\\*\\s+as\\s+\\w+/g, // export * as namespace\n ];\n\n for (const pattern of runtimeExportPatterns) {\n if (pattern.test(remaining)) {\n // Reset regex lastIndex for subsequent tests\n pattern.lastIndex = 0;\n\n // Special case: check if export { } contains only type exports\n if (pattern.source.includes(\"export\\\\s+\\\\{\")) {\n const matches = remaining.match(/export\\s+\\{([^}]*)\\}(?:\\s+from\\s+['\"][^'\"]+['\"])?/g);\n if (matches) {\n for (const match of matches) {\n // Skip if it's already a type export\n if (/^export\\s+type\\s+/.test(match)) continue;\n\n // Extract the specifiers\n const specifiersMatch = match.match(/export\\s+\\{([^}]*)\\}/);\n if (specifiersMatch) {\n // Capture group 1 exists whenever the pattern matched. `?? \"\"`\n // yields an empty specifier list, which `some()` below reads as\n // \"no runtime specifier\" — the same answer an empty `{}` gives.\n const specifiers = specifiersMatch[1] ?? \"\";\n const items = specifiers\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n // If any specifier is NOT prefixed with \"type \", this is a runtime export\n const hasRuntimeSpecifier = items.some((item) => !item.startsWith(\"type \"));\n if (hasRuntimeSpecifier) {\n return false;\n }\n }\n }\n }\n continue;\n }\n\n return false;\n }\n }\n\n // If we get here, no runtime exports were found\n // But we should also verify the file has at least some type exports\n // (an empty file or file with only imports is not really \"type-only\")\n const hasTypeExports = typeOnlyPatterns.some((pattern) => {\n pattern.lastIndex = 0;\n return pattern.test(withoutStrings);\n });\n\n return hasTypeExports;\n}\n\n/**\n * Check if an import statement is a pure `import type` (the keyword sits\n * immediately after `import`, covering `import type { X }`, `import type Foo`,\n * and `import type * as Ns`).\n */\nfunction isTypeOnlyImport(line: string): boolean {\n const trimmed = line.trim();\n\n return trimmed.startsWith(\"import type \") || !!trimmed.match(/^import\\s+type\\s+[\\{\\*]/);\n}\n\n/**\n * Decide whether an `import ... from \"m\"` statement contributes any runtime\n * binding. Returns false for pure `import type` and for destructured imports\n * where every specifier is prefixed with the `type` keyword.\n */\nfunction hasRuntimeImports(line: string): boolean {\n const trimmed = line.trim();\n\n if (isTypeOnlyImport(trimmed)) {\n return false;\n }\n\n const specifiersMatch = trimmed.match(/import\\s+(?:type\\s+)?\\{([^}]+)\\}/);\n\n if (!specifiersMatch) {\n return true;\n }\n\n const items = (specifiersMatch[1] ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n return !items.every((item) => /^type\\s+\\w+/.test(item));\n}\n\n/**\n * Decide whether an `export ... from \"m\"` statement re-exports only types.\n * Covers `export type { X } from`, `export type * from`, and\n * `export { type X, type Y } from`.\n */\nfunction isExportTypeOnlyStatement(line: string): boolean {\n const trimmed = line.trim();\n\n if (/^export\\s+type\\s+/.test(trimmed)) {\n return true;\n }\n\n const specifiersMatch = trimmed.match(/export\\s+\\{([^}]+)\\}/);\n\n if (!specifiersMatch) {\n return false;\n }\n\n const items = (specifiersMatch[1] ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n return items.every((item) => /^type\\s+\\w+/.test(item));\n}\n\n/**\n * Extract import paths using regex (more reliable for TypeScript).\n * Each entry carries an `isTypeOnly` flag: true when every occurrence of the\n * path in the source is a type-only statement (no runtime binding).\n * A single runtime occurrence makes the path runtime.\n */\nfunction extractImportPathsWithRegex(\n source: string,\n): Array<{ path: string; originalLine: string; isTypeOnly: boolean }> {\n const imports: Array<{ path: string; originalLine: string; isTypeOnly: boolean }> = [];\n const seenPaths = new Map<string, number>();\n\n /**\n * Record an import path with its type-only flag.\n * If the same path appears in multiple statements, the edge is type-only\n * iff every occurrence is type-only — a single runtime statement makes it runtime.\n */\n const record = (importPath: string, originalLine: string, isTypeOnly: boolean): void => {\n if (!importPath) {\n return;\n }\n\n const existingIndex = seenPaths.get(importPath);\n\n if (existingIndex === undefined) {\n seenPaths.set(importPath, imports.length);\n imports.push({ path: importPath, originalLine, isTypeOnly });\n\n return;\n }\n\n if (!isTypeOnly) {\n const existing = imports[existingIndex];\n\n // `existingIndex` came from findIndex on this same array, so it is in\n // range; the compiler does not carry that here.\n if (existing) existing.isTypeOnly = false;\n }\n };\n\n // Pattern 1: Standard ES module imports (handles multiline)\n // Matches: import { ... } from \"path\", import Foo from \"path\", import Foo, { ... } from \"path\"\n const importRegex =\n /import\\s+(?:type\\s+)?(\\{[\\s\\S]*?\\}|\\*\\s+as\\s+\\w+|\\w+(?:\\s*,\\s*\\{[\\s\\S]*?\\})?)\\s+from\\s+['\"]([^'\"]+)['\"]/g;\n\n let match;\n\n while ((match = importRegex.exec(source)) !== null) {\n const fullMatch = match[0];\n const importPath = match[2];\n\n // Each pattern here captures its path in a group, so a match always carries\n // one. Skipping rather than recording keeps a malformed match out of the\n // dependency graph entirely — recording `undefined` would add an import\n // edge to a module named \"undefined\", which the dev server would then\n // watch, fail to resolve, and report against the wrong file.\n if (importPath === undefined) continue;\n\n const isTypeOnly = !hasRuntimeImports(fullMatch);\n\n record(importPath, fullMatch, isTypeOnly);\n }\n\n // Pattern 1b: Side-effect imports - import \"path\" — always runtime\n const sideEffectRegex = /import\\s+['\"]([^'\"]+)['\"]/g;\n\n while ((match = sideEffectRegex.exec(source)) !== null) {\n const sideEffectPath = match[1];\n\n if (sideEffectPath === undefined) continue;\n\n record(sideEffectPath, match[0], false);\n }\n\n // Pattern 2: Dynamic imports - import(\"path\") — always runtime\n const dynamicImportPattern = /import\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n\n while ((match = dynamicImportPattern.exec(source)) !== null) {\n const dynamicPath = match[1];\n\n if (dynamicPath === undefined) continue;\n\n record(dynamicPath, match[0], false);\n }\n\n // Pattern 3: Export from - export ... from \"path\"\n const exportFromPattern = /export\\s+(?:\\{[^}]*\\}|\\*|\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/g;\n\n while ((match = exportFromPattern.exec(source)) !== null) {\n const fullMatch = match[0];\n const exportPath = match[1];\n\n if (exportPath === undefined) continue;\n\n record(exportPath, fullMatch, isExportTypeOnlyStatement(fullMatch));\n }\n\n return imports;\n}\n\n/**\n * Metadata for a single resolved import edge.\n * `isTypeOnly` is true iff every import/export statement that references this\n * path is type-only (pure `import type`, `export type`, or destructured lists\n * where every specifier carries the `type` keyword). A single runtime\n * occurrence flips the flag to false — that's what matters for cycle detection.\n */\nexport type ResolvedImport = {\n absolutePath: string;\n isTypeOnly: boolean;\n};\n\n/**\n * Parse import/export statements in a TS/JS source file and return the\n * resolved dependency edges keyed by the original import path. Includes\n * type-only edges (flagged) so downstream consumers can distinguish runtime\n * cycles from type-only ones.\n *\n * @example\n * const importMap = await parseImports(source, \"/abs/path/to/file.ts\");\n * for (const [importPath, { absolutePath, isTypeOnly }] of importMap) {\n * // ...\n * }\n */\nexport async function parseImports(\n source: string,\n filePath: string,\n): Promise<Map<string, ResolvedImport>> {\n try {\n // Skip .d.ts files - they're type declarations, not runtime code\n if (filePath.endsWith(\".d.ts\")) {\n return new Map();\n }\n\n // Try es-module-lexer first (faster and more accurate for simple cases)\n try {\n const [imports] = await parse(source);\n\n if (imports && imports.length > 0) {\n return await resolveImports(imports as ImportSpecifier[], source, filePath);\n }\n } catch (lexerError) {\n // es-module-lexer failed, fall back to regex-based extraction\n // This is common with TypeScript files that have complex syntax\n }\n\n // Fallback: Use regex-based extraction (more forgiving with TypeScript)\n const regexImports = extractImportPathsWithRegex(source);\n const resolvedImports = new Map<string, ResolvedImport>();\n\n for (const { path: importPath, isTypeOnly } of regexImports) {\n if (isNodeBuiltin(importPath)) {\n continue;\n }\n\n if (!importPath.startsWith(\".\") && !tsconfigManager.isAlias(importPath)) {\n continue;\n }\n\n let resolvedPath: string | null = null;\n\n if (tsconfigManager.isAlias(importPath)) {\n resolvedPath = await resolveAliasImport(importPath);\n } else if (importPath.startsWith(\".\")) {\n resolvedPath = await resolveRelativeImport(importPath, filePath);\n }\n\n if (resolvedPath) {\n mergeResolvedImport(resolvedImports, importPath, resolvedPath, isTypeOnly);\n }\n }\n\n return resolvedImports;\n } catch (error) {\n console.error(`Error parsing imports for ${filePath}:`, error);\n\n return new Map();\n }\n}\n\n/**\n * Merge a resolved import into the output map, preserving the type-only rule:\n * a path is type-only iff every statement that references it is type-only.\n */\nfunction mergeResolvedImport(\n target: Map<string, ResolvedImport>,\n importPath: string,\n absolutePath: string,\n isTypeOnly: boolean,\n): void {\n const existing = target.get(importPath);\n\n if (!existing) {\n target.set(importPath, { absolutePath, isTypeOnly });\n\n return;\n }\n\n if (!isTypeOnly) {\n existing.isTypeOnly = false;\n }\n}\n\n/**\n * Resolve imports from `es-module-lexer` output. For each specifier, slice the\n * raw statement (`ss..se`) and re-run the type-only heuristic so we can flag\n * the edge correctly — the lexer itself does not distinguish `import type`.\n */\nasync function resolveImports(\n imports: ImportSpecifier[],\n source: string,\n filePath: string,\n): Promise<Map<string, ResolvedImport>> {\n const resolvedImports = new Map<string, ResolvedImport>();\n\n for (const imp of imports) {\n const importPath = imp.n;\n\n if (!importPath) {\n continue;\n }\n\n if (isNodeBuiltin(importPath)) {\n continue;\n }\n\n if (!importPath.startsWith(\".\") && !tsconfigManager.isAlias(importPath)) {\n continue;\n }\n\n let resolvedPath: string | null = null;\n\n if (tsconfigManager.isAlias(importPath)) {\n resolvedPath = await resolveAliasImport(importPath);\n } else if (importPath.startsWith(\".\")) {\n resolvedPath = await resolveRelativeImport(importPath, filePath);\n }\n\n if (!resolvedPath) {\n continue;\n }\n\n const isTypeOnly = isLexerStatementTypeOnly(imp, source);\n\n mergeResolvedImport(resolvedImports, importPath, resolvedPath, isTypeOnly);\n }\n\n return resolvedImports;\n}\n\n/**\n * Classify a single lexer-reported statement as type-only or runtime.\n * Dynamic imports (`import(...)`) are always runtime. For static\n * imports/export-from we slice the raw source and apply the same heuristic\n * the regex fallback uses.\n */\nfunction isLexerStatementTypeOnly(imp: ImportSpecifier, source: string): boolean {\n // Dynamic imports always execute — they cannot be type-only.\n // es-module-lexer reports dynamic with a.n === undefined typically, but\n // we guard by checking the statement prefix too.\n const statementStart = imp.ss;\n const statementEnd = imp.se;\n\n if (\n typeof statementStart !== \"number\" ||\n typeof statementEnd !== \"number\" ||\n statementEnd <= statementStart\n ) {\n return false;\n }\n\n const statement = source.slice(statementStart, statementEnd);\n const trimmed = statement.trim();\n\n if (trimmed.startsWith(\"import(\") || /^\\bimport\\s*\\(/.test(trimmed)) {\n return false;\n }\n\n if (trimmed.startsWith(\"export\")) {\n return isExportTypeOnlyStatement(statement);\n }\n\n return !hasRuntimeImports(statement);\n}\n\n/**\n * Resolve alias imports to actual file paths with extensions\n * Example: app/users/services/get-users.service -> /absolute/path/to/src/app/users/services/get-users.service.ts\n */\nasync function resolveAliasImport(importPath: string): Promise<string | null> {\n // Use tsconfig manager to resolve the alias to an absolute path\n const resolvedBase = tsconfigManager.resolveAliasToAbsolute(importPath);\n\n if (!resolvedBase) return null;\n\n // Try to resolve with extensions\n const resolvedPath = await tryResolveWithExtensions(resolvedBase);\n\n return resolvedPath;\n}\n\n/**\n * Resolve relative imports to actual file paths\n * Example: ./../services/get-user.service -> /absolute/path/to/services/get-user.service.ts\n */\nasync function resolveRelativeImport(\n importPath: string,\n currentFilePath: string,\n): Promise<string | null> {\n const dir = path.dirname(currentFilePath);\n // Use path.resolve to handle .. and . properly, then normalize to forward slashes\n const resolvedBase = Path.normalize(path.resolve(dir, importPath));\n\n // Try to resolve with extensions\n const resolvedPath = await tryResolveWithExtensions(resolvedBase);\n\n return resolvedPath;\n}\n\n/**\n * Try to resolve a file path by checking different extensions\n * TypeScript/JavaScript files can be imported without extensions\n *\n * @TODO: For better performance, we need to check the files in files orchestrator\n * instead of using the file system as we will be fetching all project files anyway.\n */\n// Cache for file existence checks to avoid redundant filesystem calls\nconst fileExistsCache = new Map<string, boolean>();\n\n/**\n * Clear the file exists cache\n * Should be called when new files are created to ensure fresh lookups\n */\nexport function clearFileExistsCache(): void {\n fileExistsCache.clear();\n}\n\nasync function cachedFileExists(filePath: string): Promise<boolean> {\n if (fileExistsCache.has(filePath)) {\n return fileExistsCache.get(filePath)!;\n }\n const exists = (await fileExistsAsync(filePath)) as boolean;\n fileExistsCache.set(filePath, exists);\n return exists;\n}\n\nasync function tryResolveWithExtensions(basePath: string): Promise<string | null> {\n // Normalize the base path first (handle Windows paths)\n const normalizedBase = Path.normalize(basePath);\n\n // List of extensions to try, in order of preference\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\"];\n const validExtensions = new Set(extensions);\n\n // If the path already has a VALID code file extension, check if it exists\n const ext = path.extname(normalizedBase);\n if (ext && validExtensions.has(ext)) {\n if (await cachedFileExists(normalizedBase)) {\n return normalizedBase;\n }\n // If explicit extension doesn't exist, return null\n return null;\n }\n\n // Try all extensions in parallel for better performance\n const pathsToCheck = extensions.map((extension) => normalizedBase + extension);\n const results = await Promise.all(\n pathsToCheck.map(async (p) => ({ path: p, exists: await cachedFileExists(p) })),\n );\n\n // Return the first one that exists (in order of preference)\n for (const result of results) {\n if (result.exists) {\n return result.path;\n }\n }\n\n // Try index files in directory\n if (await directoryExistsAsync(normalizedBase)) {\n const indexPaths = extensions.map((extension) =>\n Path.join(normalizedBase, `index${extension}`),\n );\n const indexResults = await Promise.all(\n indexPaths.map(async (p) => ({ path: p, exists: await cachedFileExists(p) })),\n );\n\n for (const result of indexResults) {\n if (result.exists) {\n return result.path;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Check if import is a Node.js built-in module\n */\nfunction isNodeBuiltin(importPath: string): boolean {\n const builtins = [\n \"fs\",\n \"path\",\n \"http\",\n \"https\",\n \"crypto\",\n \"stream\",\n \"util\",\n \"events\",\n \"buffer\",\n \"child_process\",\n \"os\",\n \"url\",\n \"querystring\",\n \"zlib\",\n \"net\",\n \"tls\",\n \"dns\",\n \"dgram\",\n \"cluster\",\n \"worker_threads\",\n \"perf_hooks\",\n \"async_hooks\",\n \"timers\",\n \"readline\",\n \"repl\",\n \"vm\",\n \"assert\",\n \"console\",\n \"process\",\n \"v8\",\n ];\n\n // Check for node: prefix or direct builtin name\n if (importPath.startsWith(\"node:\")) return true;\n\n // `split` always yields a first element. Falling back to the whole path\n // keeps the builtin check answering about a real name rather than undefined.\n const moduleName = importPath.split(\"/\")[0] ?? importPath;\n\n return builtins.includes(moduleName);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,eAAe,QAAyB;CAOtD,MAAM,iBALkB,OACrB,QAAQ,qBAAqB,EAAE,CAAC,CAChC,QAAQ,aAAa,EAGa,CAAC,CACnC,QAAQ,sBAAsB,IAAI,CAAC,CACnC,QAAQ,sBAAsB,MAAI,CAAC,CACnC,QAAQ,sBAAsB,IAAI;CAGrC,MAAM,mBAAmB;EACvB;EACA;EACA;EACA;CACF;CAGA,IAAI,YAAY;CAChB,KAAK,MAAM,WAAW,kBACpB,YAAY,UAAU,QAAQ,SAAS,EAAE;CAiB3C,KAAK,MAAM,WAAW;EAZpB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CAGwC,GACxC,IAAI,QAAQ,KAAK,SAAS,GAAG;EAE3B,QAAQ,YAAY;EAGpB,IAAI,QAAQ,OAAO,SAAS,eAAe,GAAG;GAC5C,MAAM,UAAU,UAAU,MAAM,oDAAoD;GACpF,IAAI,SACF,KAAK,MAAM,SAAS,SAAS;IAE3B,IAAI,oBAAoB,KAAK,KAAK,GAAG;IAGrC,MAAM,kBAAkB,MAAM,MAAM,sBAAsB;IAC1D,IAAI,iBAYF;UARmB,gBAAgB,MAAM,GACjB,CACrB,MAAM,GAAG,CAAC,CACV,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,CACpB,OAAO,OAGsB,CAAC,CAAC,MAAM,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Q;EAAQ;CAAM;CAChE,MAAM,kBAAkB,IAAI,IAAI,UAAU;CAG1C,MAAM,MAAM,KAAK,QAAQ,cAAc;CACvC,IAAI,OAAO,gBAAgB,IAAI,GAAG,GAAG;EACnC,IAAI,MAAM,iBAAiB,cAAc,GACvC,OAAO;EAGT,OAAO;CACT;CAGA,MAAM,eAAe,WAAW,KAAK,cAAc,iBAAiB,SAAS;CAC7E,MAAM,UAAU,MAAM,QAAQ,IAC5B,aAAa,IAAI,OAAO,OAAO;EAAE,MAAM;EAAG,QAAQ,MAAM,iBAAiB,CAAC;CAAE,EAAE,CAChF;CAGA,KAAK,MAAM,UAAU,SACnB,IAAI,OAAO,QACT,OAAO,OAAO;CAKlB,IAAI,MAAM,qBAAqB,cAAc,GAAG;EAC9C,MAAM,aAAa,WAAW,KAAK,cACjC,KAAK,KAAK,gBAAgB,QAAQ,WAAW,CAC/C;EACA,MAAM,eAAe,MAAM,QAAQ,IACjC,WAAW,IAAI,OAAO,OAAO;GAAE,MAAM;GAAG,QAAQ,MAAM,iBAAiB,CAAC;EAAE,EAAE,CAC9E;EAEA,KAAK,MAAM,UAAU,cACnB,IAAI,OAAO,QACT,OAAO,OAAO;CAGpB;CAEA,OAAO;AACT;;;;AAKA,SAAS,cAAc,YAA6B;CAClD,MAAM,WAAW;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;CAGA,IAAI,WAAW,WAAW,OAAO,GAAG,OAAO;CAI3C,MAAM,aAAa,WAAW,MAAM,GAAG,CAAC,CAAC,MAAM;CAE/C,OAAO,SAAS,SAAS,UAAU;AACrC"}
|
|
1
|
+
{"version":3,"file":"parse-imports.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/parse-imports.ts"],"sourcesContent":["import { fileExistsAsync, directoryExistsAsync } from \"@warlock.js/fs\";\nimport { type ImportSpecifier, parse } from \"es-module-lexer\";\nimport path from \"node:path\";\nimport { Path } from \"../utils/normalized-path\";\nimport { tsconfigManager } from \"./tsconfig-manager\";\n\n/**\n * Detect if a file contains only type definitions (no runtime code)\n *\n * A file is considered type-only if ALL its exports are:\n * - interface declarations\n * - type alias declarations\n * - export type { ... } statements\n * - export type { ... } from \"...\" statements\n *\n * Files with any of these are NOT type-only:\n * - export const/let/var\n * - export function\n * - export class\n * - export default (non-type)\n * - export { ... } (without type keyword)\n * - export * from (without type keyword)\n *\n * @param source - The source code to analyze\n * @returns true if the file exports only types\n */\nexport function isTypeOnlyFile(source: string): boolean {\n // Remove comments to avoid false positives\n const withoutComments = source\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\") // block comments\n .replace(/\\/\\/.*$/gm, \"\"); // line comments\n\n // Remove string literals to avoid false positives\n const withoutStrings = withoutComments\n .replace(/'(?:[^'\\\\]|\\\\.)*'/g, \"''\")\n .replace(/\"(?:[^\"\\\\]|\\\\.)*\"/g, '\"\"')\n .replace(/`(?:[^`\\\\]|\\\\.)*`/g, \"``\");\n\n // Patterns for type-only exports (these are safe)\n const typeOnlyPatterns = [\n /export\\s+type\\s+\\{[^}]*\\}/g, // export type { Foo, Bar }\n /export\\s+type\\s+\\{[^}]*\\}\\s+from\\s+['\"]/g, // export type { Foo } from \"...\"\n /export\\s+interface\\s+\\w+/g, // export interface Foo\n /export\\s+type\\s+\\w+\\s*=/g, // export type Foo =\n ];\n\n // Remove all type-only exports from consideration\n let remaining = withoutStrings;\n for (const pattern of typeOnlyPatterns) {\n remaining = remaining.replace(pattern, \"\");\n }\n\n // Patterns for runtime exports (these make the file NOT type-only)\n const runtimeExportPatterns = [\n /export\\s+(?:const|let|var)\\s+\\w+/g, // export const/let/var foo\n /export\\s+function\\s+\\w+/g, // export function foo\n /export\\s+async\\s+function\\s+\\w+/g, // export async function foo\n /export\\s+class\\s+\\w+/g, // export class Foo\n /export\\s+enum\\s+\\w+/g, // export enum Foo (enums have runtime value)\n /export\\s+default\\s+(?!type\\s)/g, // export default (not type)\n /export\\s+\\{[^}]*\\}(?!\\s+from)/g, // export { foo } (local re-export without type)\n /export\\s+\\{[^}]*\\}\\s+from\\s+['\"][^'\"]+['\"]/g, // export { foo } from (without type)\n /export\\s+\\*\\s+from\\s+['\"][^'\"]+['\"]/g, // export * from (re-exports everything)\n /export\\s+\\*\\s+as\\s+\\w+/g, // export * as namespace\n ];\n\n for (const pattern of runtimeExportPatterns) {\n if (pattern.test(remaining)) {\n // Reset regex lastIndex for subsequent tests\n pattern.lastIndex = 0;\n\n // Special case: check if export { } contains only type exports\n if (pattern.source.includes(\"export\\\\s+\\\\{\")) {\n const matches = remaining.match(/export\\s+\\{([^}]*)\\}(?:\\s+from\\s+['\"][^'\"]+['\"])?/g);\n if (matches) {\n for (const match of matches) {\n // Skip if it's already a type export\n if (/^export\\s+type\\s+/.test(match)) continue;\n\n // Extract the specifiers\n const specifiersMatch = match.match(/export\\s+\\{([^}]*)\\}/);\n if (specifiersMatch) {\n // Capture group 1 exists whenever the pattern matched. `?? \"\"`\n // yields an empty specifier list, which `some()` below reads as\n // \"no runtime specifier\" — the same answer an empty `{}` gives.\n const specifiers = specifiersMatch[1] ?? \"\";\n const items = specifiers\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n // If any specifier is NOT prefixed with \"type \", this is a runtime export\n const hasRuntimeSpecifier = items.some((item) => !item.startsWith(\"type \"));\n if (hasRuntimeSpecifier) {\n return false;\n }\n }\n }\n }\n continue;\n }\n\n return false;\n }\n }\n\n // If we get here, no runtime exports were found\n // But we should also verify the file has at least some type exports\n // (an empty file or file with only imports is not really \"type-only\")\n const hasTypeExports = typeOnlyPatterns.some((pattern) => {\n pattern.lastIndex = 0;\n return pattern.test(withoutStrings);\n });\n\n return hasTypeExports;\n}\n\n/**\n * Check if an import statement is a pure `import type` (the keyword sits\n * immediately after `import`, covering `import type { X }`, `import type Foo`,\n * and `import type * as Ns`).\n */\nfunction isTypeOnlyImport(line: string): boolean {\n const trimmed = line.trim();\n\n return trimmed.startsWith(\"import type \") || !!trimmed.match(/^import\\s+type\\s+[\\{\\*]/);\n}\n\n/**\n * Decide whether an `import ... from \"m\"` statement contributes any runtime\n * binding. Returns false for pure `import type` and for destructured imports\n * where every specifier is prefixed with the `type` keyword.\n */\nfunction hasRuntimeImports(line: string): boolean {\n const trimmed = line.trim();\n\n if (isTypeOnlyImport(trimmed)) {\n return false;\n }\n\n const specifiersMatch = trimmed.match(/import\\s+(?:type\\s+)?\\{([^}]+)\\}/);\n\n if (!specifiersMatch) {\n return true;\n }\n\n const items = (specifiersMatch[1] ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n return !items.every((item) => /^type\\s+\\w+/.test(item));\n}\n\n/**\n * Decide whether an `export ... from \"m\"` statement re-exports only types.\n * Covers `export type { X } from`, `export type * from`, and\n * `export { type X, type Y } from`.\n */\nfunction isExportTypeOnlyStatement(line: string): boolean {\n const trimmed = line.trim();\n\n if (/^export\\s+type\\s+/.test(trimmed)) {\n return true;\n }\n\n const specifiersMatch = trimmed.match(/export\\s+\\{([^}]+)\\}/);\n\n if (!specifiersMatch) {\n return false;\n }\n\n const items = (specifiersMatch[1] ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n return items.every((item) => /^type\\s+\\w+/.test(item));\n}\n\n/**\n * Extract import paths using regex (more reliable for TypeScript).\n * Each entry carries an `isTypeOnly` flag: true when every occurrence of the\n * path in the source is a type-only statement (no runtime binding).\n * A single runtime occurrence makes the path runtime.\n */\nfunction extractImportPathsWithRegex(\n source: string,\n): Array<{ path: string; originalLine: string; isTypeOnly: boolean }> {\n const imports: Array<{ path: string; originalLine: string; isTypeOnly: boolean }> = [];\n const seenPaths = new Map<string, number>();\n\n /**\n * Record an import path with its type-only flag.\n * If the same path appears in multiple statements, the edge is type-only\n * iff every occurrence is type-only — a single runtime statement makes it runtime.\n */\n const record = (importPath: string, originalLine: string, isTypeOnly: boolean): void => {\n if (!importPath) {\n return;\n }\n\n const existingIndex = seenPaths.get(importPath);\n\n if (existingIndex === undefined) {\n seenPaths.set(importPath, imports.length);\n imports.push({ path: importPath, originalLine, isTypeOnly });\n\n return;\n }\n\n if (!isTypeOnly) {\n const existing = imports[existingIndex];\n\n // `existingIndex` came from findIndex on this same array, so it is in\n // range; the compiler does not carry that here.\n if (existing) existing.isTypeOnly = false;\n }\n };\n\n // Pattern 1: Standard ES module imports (handles multiline)\n // Matches: import { ... } from \"path\", import Foo from \"path\", import Foo, { ... } from \"path\"\n const importRegex =\n /import\\s+(?:type\\s+)?(\\{[\\s\\S]*?\\}|\\*\\s+as\\s+\\w+|\\w+(?:\\s*,\\s*\\{[\\s\\S]*?\\})?)\\s+from\\s+['\"]([^'\"]+)['\"]/g;\n\n let match;\n\n while ((match = importRegex.exec(source)) !== null) {\n const fullMatch = match[0];\n const importPath = match[2];\n\n // Each pattern here captures its path in a group, so a match always carries\n // one. Skipping rather than recording keeps a malformed match out of the\n // dependency graph entirely — recording `undefined` would add an import\n // edge to a module named \"undefined\", which the dev server would then\n // watch, fail to resolve, and report against the wrong file.\n if (importPath === undefined) continue;\n\n const isTypeOnly = !hasRuntimeImports(fullMatch);\n\n record(importPath, fullMatch, isTypeOnly);\n }\n\n // Pattern 1b: Side-effect imports - import \"path\" — always runtime\n const sideEffectRegex = /import\\s+['\"]([^'\"]+)['\"]/g;\n\n while ((match = sideEffectRegex.exec(source)) !== null) {\n const sideEffectPath = match[1];\n\n if (sideEffectPath === undefined) continue;\n\n record(sideEffectPath, match[0], false);\n }\n\n // Pattern 2: Dynamic imports - import(\"path\") — always runtime\n const dynamicImportPattern = /import\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n\n while ((match = dynamicImportPattern.exec(source)) !== null) {\n const dynamicPath = match[1];\n\n if (dynamicPath === undefined) continue;\n\n record(dynamicPath, match[0], false);\n }\n\n // Pattern 3: Export from - export ... from \"path\"\n const exportFromPattern = /export\\s+(?:\\{[^}]*\\}|\\*|\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/g;\n\n while ((match = exportFromPattern.exec(source)) !== null) {\n const fullMatch = match[0];\n const exportPath = match[1];\n\n if (exportPath === undefined) continue;\n\n record(exportPath, fullMatch, isExportTypeOnlyStatement(fullMatch));\n }\n\n return imports;\n}\n\n/**\n * Metadata for a single resolved import edge.\n * `isTypeOnly` is true iff every import/export statement that references this\n * path is type-only (pure `import type`, `export type`, or destructured lists\n * where every specifier carries the `type` keyword). A single runtime\n * occurrence flips the flag to false — that's what matters for cycle detection.\n */\nexport type ResolvedImport = {\n absolutePath: string;\n isTypeOnly: boolean;\n};\n\n/**\n * Parse import/export statements in a TS/JS source file and return the\n * resolved dependency edges keyed by the original import path. Includes\n * type-only edges (flagged) so downstream consumers can distinguish runtime\n * cycles from type-only ones.\n *\n * @example\n * const importMap = await parseImports(source, \"/abs/path/to/file.ts\");\n * for (const [importPath, { absolutePath, isTypeOnly }] of importMap) {\n * // ...\n * }\n */\nexport async function parseImports(\n source: string,\n filePath: string,\n): Promise<Map<string, ResolvedImport>> {\n try {\n // Skip .d.ts files - they're type declarations, not runtime code\n if (filePath.endsWith(\".d.ts\")) {\n return new Map();\n }\n\n // Try es-module-lexer first (faster and more accurate for simple cases)\n try {\n const [imports] = await parse(source);\n\n if (imports && imports.length > 0) {\n return await resolveImports(imports as ImportSpecifier[], source, filePath);\n }\n } catch (lexerError) {\n // es-module-lexer failed, fall back to regex-based extraction\n // This is common with TypeScript files that have complex syntax\n }\n\n // Fallback: Use regex-based extraction (more forgiving with TypeScript)\n const regexImports = extractImportPathsWithRegex(source);\n const resolvedImports = new Map<string, ResolvedImport>();\n\n for (const { path: importPath, isTypeOnly } of regexImports) {\n if (isNodeBuiltin(importPath)) {\n continue;\n }\n\n if (!importPath.startsWith(\".\") && !tsconfigManager.isAlias(importPath)) {\n continue;\n }\n\n let resolvedPath: string | null = null;\n\n if (tsconfigManager.isAlias(importPath)) {\n resolvedPath = await resolveAliasImport(importPath);\n } else if (importPath.startsWith(\".\")) {\n resolvedPath = await resolveRelativeImport(importPath, filePath);\n }\n\n if (resolvedPath) {\n mergeResolvedImport(resolvedImports, importPath, resolvedPath, isTypeOnly);\n }\n }\n\n return resolvedImports;\n } catch (error) {\n console.error(`Error parsing imports for ${filePath}:`, error);\n\n return new Map();\n }\n}\n\n/**\n * Merge a resolved import into the output map, preserving the type-only rule:\n * a path is type-only iff every statement that references it is type-only.\n */\nfunction mergeResolvedImport(\n target: Map<string, ResolvedImport>,\n importPath: string,\n absolutePath: string,\n isTypeOnly: boolean,\n): void {\n const existing = target.get(importPath);\n\n if (!existing) {\n target.set(importPath, { absolutePath, isTypeOnly });\n\n return;\n }\n\n if (!isTypeOnly) {\n existing.isTypeOnly = false;\n }\n}\n\n/**\n * Resolve imports from `es-module-lexer` output. For each specifier, slice the\n * raw statement (`ss..se`) and re-run the type-only heuristic so we can flag\n * the edge correctly — the lexer itself does not distinguish `import type`.\n */\nasync function resolveImports(\n imports: ImportSpecifier[],\n source: string,\n filePath: string,\n): Promise<Map<string, ResolvedImport>> {\n const resolvedImports = new Map<string, ResolvedImport>();\n\n for (const imp of imports) {\n const importPath = imp.n;\n\n if (!importPath) {\n continue;\n }\n\n if (isNodeBuiltin(importPath)) {\n continue;\n }\n\n if (!importPath.startsWith(\".\") && !tsconfigManager.isAlias(importPath)) {\n continue;\n }\n\n let resolvedPath: string | null = null;\n\n if (tsconfigManager.isAlias(importPath)) {\n resolvedPath = await resolveAliasImport(importPath);\n } else if (importPath.startsWith(\".\")) {\n resolvedPath = await resolveRelativeImport(importPath, filePath);\n }\n\n if (!resolvedPath) {\n continue;\n }\n\n const isTypeOnly = isLexerStatementTypeOnly(imp, source);\n\n mergeResolvedImport(resolvedImports, importPath, resolvedPath, isTypeOnly);\n }\n\n return resolvedImports;\n}\n\n/**\n * Classify a single lexer-reported statement as type-only or runtime.\n * Dynamic imports (`import(...)`) are always runtime. For static\n * imports/export-from we slice the raw source and apply the same heuristic\n * the regex fallback uses.\n */\nfunction isLexerStatementTypeOnly(imp: ImportSpecifier, source: string): boolean {\n // Dynamic imports always execute — they cannot be type-only.\n // es-module-lexer reports dynamic with a.n === undefined typically, but\n // we guard by checking the statement prefix too.\n const statementStart = imp.ss;\n const statementEnd = imp.se;\n\n if (\n typeof statementStart !== \"number\" ||\n typeof statementEnd !== \"number\" ||\n statementEnd <= statementStart\n ) {\n return false;\n }\n\n const statement = source.slice(statementStart, statementEnd);\n const trimmed = statement.trim();\n\n if (trimmed.startsWith(\"import(\") || /^\\bimport\\s*\\(/.test(trimmed)) {\n return false;\n }\n\n if (trimmed.startsWith(\"export\")) {\n return isExportTypeOnlyStatement(statement);\n }\n\n return !hasRuntimeImports(statement);\n}\n\n/**\n * Resolve alias imports to actual file paths with extensions\n * Example: app/users/services/get-users.service -> /absolute/path/to/src/app/users/services/get-users.service.ts\n */\nasync function resolveAliasImport(importPath: string): Promise<string | null> {\n // Use tsconfig manager to resolve the alias to an absolute path\n const resolvedBase = tsconfigManager.resolveAliasToAbsolute(importPath);\n\n if (!resolvedBase) return null;\n\n // Try to resolve with extensions\n const resolvedPath = await tryResolveWithExtensions(resolvedBase);\n\n return resolvedPath;\n}\n\n/**\n * Resolve relative imports to actual file paths\n * Example: ./../services/get-user.service -> /absolute/path/to/services/get-user.service.ts\n */\nasync function resolveRelativeImport(\n importPath: string,\n currentFilePath: string,\n): Promise<string | null> {\n const dir = path.dirname(currentFilePath);\n // Use path.resolve to handle .. and . properly, then normalize to forward slashes\n const resolvedBase = Path.normalize(path.resolve(dir, importPath));\n\n // Try to resolve with extensions\n const resolvedPath = await tryResolveWithExtensions(resolvedBase);\n\n return resolvedPath;\n}\n\n/**\n * Try to resolve a file path by checking different extensions\n * TypeScript/JavaScript files can be imported without extensions\n *\n * @TODO: For better performance, we need to check the files in files orchestrator\n * instead of using the file system as we will be fetching all project files anyway.\n */\n// Cache for file existence checks to avoid redundant filesystem calls\nconst fileExistsCache = new Map<string, boolean>();\n\n/**\n * Clear the file exists cache\n * Should be called when new files are created to ensure fresh lookups\n */\nexport function clearFileExistsCache(): void {\n fileExistsCache.clear();\n}\n\nasync function cachedFileExists(filePath: string): Promise<boolean> {\n if (fileExistsCache.has(filePath)) {\n return fileExistsCache.get(filePath)!;\n }\n const exists = (await fileExistsAsync(filePath)) as boolean;\n\n // Cache ONLY positive results. A negative (\"does not exist\") answer is the\n // exact case that flips moments later: the \"add a new controller/route\" flow\n // references a file, then creates it. Caching that negative for the whole\n // process lifetime (it was cleared only on a multi-file watcher batch) left\n // a routes.ts import unresolvable after its target was created — the dep\n // edge never formed and the route module import failed, so the new API route\n // 404'd until an unrelated multi-file batch cleared the cache. That is\n // finding 60721e35 (\"backend route HMR needs a second edit\"). A file that\n // exists does not stop existing mid-resolve, so caching the hit is safe;\n // re-probing a still-missing path costs only a handful of stat calls.\n if (exists) {\n fileExistsCache.set(filePath, exists);\n }\n\n return exists;\n}\n\nasync function tryResolveWithExtensions(basePath: string): Promise<string | null> {\n // Normalize the base path first (handle Windows paths)\n const normalizedBase = Path.normalize(basePath);\n\n // List of extensions to try, in order of preference\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\"];\n const validExtensions = new Set(extensions);\n\n // If the path already has a VALID code file extension, check if it exists\n const ext = path.extname(normalizedBase);\n if (ext && validExtensions.has(ext)) {\n if (await cachedFileExists(normalizedBase)) {\n return normalizedBase;\n }\n // If explicit extension doesn't exist, return null\n return null;\n }\n\n // Try all extensions in parallel for better performance\n const pathsToCheck = extensions.map((extension) => normalizedBase + extension);\n const results = await Promise.all(\n pathsToCheck.map(async (p) => ({ path: p, exists: await cachedFileExists(p) })),\n );\n\n // Return the first one that exists (in order of preference)\n for (const result of results) {\n if (result.exists) {\n return result.path;\n }\n }\n\n // Try index files in directory\n if (await directoryExistsAsync(normalizedBase)) {\n const indexPaths = extensions.map((extension) =>\n Path.join(normalizedBase, `index${extension}`),\n );\n const indexResults = await Promise.all(\n indexPaths.map(async (p) => ({ path: p, exists: await cachedFileExists(p) })),\n );\n\n for (const result of indexResults) {\n if (result.exists) {\n return result.path;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Check if import is a Node.js built-in module\n */\nfunction isNodeBuiltin(importPath: string): boolean {\n const builtins = [\n \"fs\",\n \"path\",\n \"http\",\n \"https\",\n \"crypto\",\n \"stream\",\n \"util\",\n \"events\",\n \"buffer\",\n \"child_process\",\n \"os\",\n \"url\",\n \"querystring\",\n \"zlib\",\n \"net\",\n \"tls\",\n \"dns\",\n \"dgram\",\n \"cluster\",\n \"worker_threads\",\n \"perf_hooks\",\n \"async_hooks\",\n \"timers\",\n \"readline\",\n \"repl\",\n \"vm\",\n \"assert\",\n \"console\",\n \"process\",\n \"v8\",\n ];\n\n // Check for node: prefix or direct builtin name\n if (importPath.startsWith(\"node:\")) return true;\n\n // `split` always yields a first element. Falling back to the whole path\n // keeps the builtin check answering about a real name rather than undefined.\n const moduleName = importPath.split(\"/\")[0] ?? importPath;\n\n return builtins.includes(moduleName);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,eAAe,QAAyB;CAOtD,MAAM,iBALkB,OACrB,QAAQ,qBAAqB,EAAE,CAAC,CAChC,QAAQ,aAAa,EAGa,CAAC,CACnC,QAAQ,sBAAsB,IAAI,CAAC,CACnC,QAAQ,sBAAsB,MAAI,CAAC,CACnC,QAAQ,sBAAsB,IAAI;CAGrC,MAAM,mBAAmB;EACvB;EACA;EACA;EACA;CACF;CAGA,IAAI,YAAY;CAChB,KAAK,MAAM,WAAW,kBACpB,YAAY,UAAU,QAAQ,SAAS,EAAE;CAiB3C,KAAK,MAAM,WAAW;EAZpB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CAGwC,GACxC,IAAI,QAAQ,KAAK,SAAS,GAAG;EAE3B,QAAQ,YAAY;EAGpB,IAAI,QAAQ,OAAO,SAAS,e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ACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;CAGA,IAAI,WAAW,WAAW,OAAO,GAAG,OAAO;CAI3C,MAAM,aAAa,WAAW,MAAM,GAAG,CAAC,CAAC,MAAM;CAE/C,OAAO,SAAS,SAAS,UAAU;AACrC"}
|
|
@@ -360,6 +360,7 @@ async function addWebPathAlias() {
|
|
|
360
360
|
function printNextStep() {
|
|
361
361
|
console.log(`\n${colors.green("✓")} shadcn/ui prerequisites are in place. Add components with shadcn's own CLI:\n ${colors.yellowBright("npx shadcn@latest add button card")}\n Skip \`shadcn init\` — this feature did its job, and running it would rewrite components.json
|
|
362
362
|
and replace the theme tokens with an \`@theme inline\` block that resolves to nothing here.
|
|
363
|
+
Since shadcn's September 2026 change, ${colors.yellowBright("shadcn add")} installs the ${colors.yellowBright("cn")} package and its generated\n components import ${colors.yellowBright("cn")} from ${colors.yellowBright("\"cn\"")}, not from the src/web/lib/utils.ts written here.\n That file stays as a working local \`cn\` for your own imports; new shadcn components no longer route through it.
|
|
363
364
|
${colors.yellowBright("class-variance-authority")} and ${colors.yellowBright("lucide-react")} are already installed: shadcn declares\n them on the style index that only \`init\` reads, so \`add\` would never install them for you.
|
|
364
365
|
${colors.yellowBright("radix-ui")} (the unified package, not @radix-ui/react-*) IS declared per component,\n so shadcn's CLI installs that one itself as each component needs it.
|
|
365
366
|
For overlay animations, add ${colors.yellowBright("tw-animate-css")} and put ${colors.yellowBright("@import \"tw-animate-css\";")}\n at the TOP of src/web/app.css, under the Tailwind import. Without it dialogs and dropdowns
|