@getstrata/cli 3.0.5 → 3.0.7

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 CHANGED
@@ -1,5 +1,20 @@
1
1
  # @getstrata/cli changelog
2
2
 
3
+ ## 3.0.7
4
+
5
+ Carry forward the 3.0.6 application-authoring and correctness changes after its release stopped before publication. Correct SAML release acceptance to require browser-bound state while preserving assertion validation, successful login and MFA. See docs/releases/3.0.7.md for upgrade notes.
6
+
7
+ ## 3.0.6
8
+
9
+ - Package built-in application commands and load application adapters lazily, so custom CLI apps do not require bootstrap dependencies unless configured.
10
+ - Simplify module scaffolds to models, controllers, requests and policies without forwarding service/repository/provider layers. Honor the configured modules directory.
11
+ - Generate factories in `src/db/factories`, resolve existing standalone or module record types, support nested model names and reject missing models before writing files.
12
+ - Validate scaffold names/paths before filesystem changes and keep per-command help free of file-writing side effects. Generate migrations through `defineMigration`.
13
+ - Share captured configuration across migration, seeding and reset commands, including the production reset guard.
14
+ - Align CLI peer dependencies and generated application pins with core/bootstrap 3.0.6.
15
+
16
+ **Upgrade:** Review generated module/factory layouts and adopt the packaged application command configuration. Applications using removed test helpers should use the dedicated testing entrypoints. See [the release notes](../../docs/releases/3.0.6.md) and [application authoring changes](../../docs/architecture/application-dx-convergence.md).
17
+
3
18
  ## 3.0.5
4
19
 
5
20
  - Fixed SQLite queries returning no rows when SQL begins with comments, including VALUES, PRAGMA, EXPLAIN, and compact RETURNING statements.
package/README.md CHANGED
@@ -19,7 +19,7 @@ strata help
19
19
 
20
20
  `strata start` does not migrate when `APP_ENV=production`. Run `strata migrate` as an explicit deploy step.
21
21
 
22
- App commands from `src/cli/register.ts` merge with this list. Generated apps add `queue:work`, failed-job commands, `make:*`, `openapi:*`, and `schedule:run`. User-auth starters also add explicit `auth:provision-admin`; its `initialAdmin` subpath reads bounded password input from a pipe and redacts provisioning errors. The app owns its transactional one-time claim and user schema. See [initial-admin provisioning](https://github.com/EyK-26/strata/blob/main/docs/INITIAL-ADMIN.md) before adoption.
22
+ Package-owned commands also provide `queue:work`, failed-job operations, `make:*`, `openapi:*` and `schedule:run`. Custom commands from `src/cli/register.ts` merge with the command set; user-auth starters add explicit `auth:provision-admin`.
23
23
 
24
24
  ## Running it
25
25
 
@@ -48,18 +48,35 @@ From the current working directory, `strata` loads `strata.config.ts` if present
48
48
  | `server` | `src/bootstrap/server.ts` |
49
49
  | `modulesDirectory` | `src/modules` |
50
50
  | `commands` | `src/cli/register.ts` |
51
+ | `application` | Generated application entrypoint |
52
+ | `schedule` | `src/bootstrap/schedule.ts` |
51
53
  | `migrate` | `src/db/migrate.ts` |
52
54
  | `fresh` | `src/db/fresh.ts` |
53
55
 
54
- `src/cli/register.ts` can export `commands` or `registerCommands()` to add your own commands. Generated apps ship `queue:work`, which boots the app (`bootstrapApp` / `createApp`) rather than the monorepo provider stack, plus `make:*`, failed-job commands, `openapi:*`, and `schedule:run`. User-auth starters also add explicit `auth:provision-admin`; its `initialAdmin` subpath reads bounded password input from a pipe and redacts provisioning errors. The app owns its transactional one-time claim and user schema. See [initial-admin provisioning](https://github.com/EyK-26/strata/blob/main/docs/INITIAL-ADMIN.md) before adoption.
56
+ Configure `application` and `schedule` in `strata.config.ts` to select the
57
+ application entrypoint and schedule. Package-owned commands supply `queue:work`,
58
+ failed-job operations, `make:*`, `openapi:*` and `schedule:run`; commands that need
59
+ runtime services boot the selected application and close their owner afterward.
60
+ `src/cli/register.ts` exports `commands` or `registerCommands()` for custom commands.
61
+ User-auth starters also provide explicit `auth:provision-admin`; its `initialAdmin`
62
+ subpath reads bounded password input from a pipe and redacts provisioning errors.
63
+ See [initial-admin provisioning](https://github.com/EyK-26/strata/blob/main/docs/INITIAL-ADMIN.md).
55
64
 
56
- Helpers live on package subpaths: `@getstrata/cli/queueWorker`, `@getstrata/cli/queueFailed`, `@getstrata/cli/scaffold`, `@getstrata/cli/openapi`, and `@getstrata/cli/schedule`. `queue:work` takes `{ boot, close }` and does not call `assertProductionSecrets()` (that belongs in app boot). Scaffold commands resolve paths from the app working directory (`src/modules`, `src/db/migrations`, `src/jobs`, `views/` or `resources/views`). See [docs/BUILDING-APPS.md](https://github.com/EyK-26/strata/blob/main/docs/BUILDING-APPS.md#extending-the-cli).
65
+ Advanced command adapters remain available on `@getstrata/cli/queueWorker`,
66
+ `queueFailed`, `scaffold`, `openapi` and `schedule`. Scaffold paths resolve from the
67
+ app working directory. Prefer the package-owned commands for ordinary apps.
57
68
 
58
- `make:model <Name|Group/Name>` generates an id-only declarative model under `src/models`; its repository comes from `defineModel(table)` and normal startup discovery. Use `--table=existing_table`, `--primary-key=id`, and `--key-type=number|string` for explicit metadata. UUID keys use `string`. Add domain fields to the record, table columns and allowlist before writing them. Migration generation is always separate: `make:migration <name>`. No route or custom repository is generated, and existing files/symlinked parents are refused.
69
+ `make:model <Name|Group/Name>` generates an id-only declarative model under `src/models`; its repository comes from `createModel` and normal startup discovery. Use `--table=existing_table`, `--primary-key=id`, and `--key-type=number|string` for explicit metadata. UUID keys use `string`. Add domain fields to the record, table columns and allowlist before writing them. Migration generation is always separate: `make:migration <name>`. No route or custom repository is generated, and existing files/symlinked parents are refused.
59
70
 
60
- Existing apps must register `makeModelCommand` from `@getstrata/cli/scaffold` (or merge its `scaffoldCommands` map). A dependency upgrade does not rewrite the app-owned command registry. Use `make:model --help` for options.
71
+ Existing apps with copied command registries should adopt the package-owned commands or register `makeModelCommand` from `@getstrata/cli/scaffold` (or merge its `scaffoldCommands` map). A dependency upgrade does not rewrite those files. Use `make:model --help` for options.
61
72
 
62
- `make:view reports/summary[.eta]` creates an Eta HTML template under an existing `views/`, or `resources/views/` otherwise. It supports nested names, leading-underscore partials and numeric error pages, and refuses unsafe paths, symlinks and overwrites. It does not create routes/controllers, enable views or change the app's layout/directory configuration. Register `makeViewCommand` from the same scaffold subpath in existing apps; fresh generated registries include it.
73
+ `make:view reports/summary[.eta]` creates an Eta HTML template under an existing `views/`, or `resources/views/` otherwise. It supports nested names, leading-underscore partials and numeric error pages, and refuses unsafe paths, symlinks and overwrites. It does not create routes/controllers, enable views or change the app's layout/directory configuration. Register `makeViewCommand` from the same scaffold subpath in existing apps; package-owned scaffold commands include it.
74
+
75
+ Migration entry callbacks (`migrate`, `seed`, `fresh`) may accept an optional
76
+ frozen environment snapshot. The CLI supplies it per invocation; zero-argument
77
+ callbacks remain supported. Application bootstrap and CLI migrations use their
78
+ selected snapshot rather than mutating process defaults. `modulesDirectory` is
79
+ shared by module discovery, scaffolding and OpenAPI.
63
80
 
64
81
  A migrate entry may export `close()`. The CLI calls it after `migrate()` and `fresh()` so pooled drivers such as `mysql2` release the event loop instead of hanging the command.
65
82
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getstrata/cli",
3
- "version": "3.0.5",
3
+ "version": "3.0.7",
4
4
  "description": "Strata CLI: framework commands for Bun apps (dev, start, migrate, run)",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -54,8 +54,8 @@
54
54
  ],
55
55
  "scripts": {},
56
56
  "peerDependencies": {
57
- "@getstrata/bootstrap": "^3.0.5",
58
- "@getstrata/core": "^3.0.5"
57
+ "@getstrata/bootstrap": "^3.0.7",
58
+ "@getstrata/core": "^3.0.7"
59
59
  },
60
60
  "publishConfig": {
61
61
  "access": "public"
@@ -0,0 +1,87 @@
1
+ import { pathToFileURL } from "node:url";
2
+ import type { QueueCommandApplication } from "./queueFailed";
3
+
4
+ interface CommandApp extends QueueCommandApplication {
5
+ readonly outboxWorker: import("@getstrata/core/events/outbox").OutboxWorkerTransport;
6
+ readonly routes: Record<string, unknown>;
7
+ readonly context: { dispose(): Promise<void> };
8
+ }
9
+ type AppFactory = (options: {
10
+ migrate: false;
11
+ mode: "command" | "worker" | "outbox-worker";
12
+ }) => Promise<CommandApp>;
13
+
14
+ import { createScheduleRunOptions } from "@getstrata/bootstrap/schedule";
15
+ import {
16
+ createOpenApiCheckCommand,
17
+ createOpenApiGenerateCommand,
18
+ createOpenApiValidateCommand,
19
+ } from "./openapi";
20
+ import { runOutboxWorkerCommand } from "./outboxWorker";
21
+ import { createQueueFailedCommands } from "./queueFailed";
22
+ import { runQueueWorkerCommand } from "./queueWorker";
23
+ import { createScheduleRunCommand } from "./schedule";
24
+ import type { StrataAppConfig, StrataCommandMap } from "./types";
25
+
26
+ function applicationCommands(config: StrataAppConfig): StrataCommandMap {
27
+ const applicationPath = config.application;
28
+ if (!applicationPath) return {};
29
+ const load = async () =>
30
+ (await import(pathToFileURL(applicationPath).href)) as {
31
+ bootstrapApp: AppFactory;
32
+ createApp: AppFactory;
33
+ };
34
+ const boot = async () => (await load()).bootstrapApp({ migrate: false, mode: "command" });
35
+ const failed = createQueueFailedCommands(boot);
36
+ const commands: StrataCommandMap = {
37
+ "queue:work": async () => () =>
38
+ runQueueWorkerCommand({
39
+ boot: async () => (await load()).bootstrapApp({ migrate: false, mode: "worker" }),
40
+ }),
41
+ "outbox:work": async () => () =>
42
+ runOutboxWorkerCommand({
43
+ boot: async () => (await load()).bootstrapApp({ migrate: false, mode: "outbox-worker" }),
44
+ }),
45
+ "queue:failed": async () => failed.queueFailedCommand,
46
+ "queue:retry": async () => failed.queueRetryCommand,
47
+ "queue:flush-failed": async () => failed.queueFlushFailedCommand,
48
+ };
49
+ for (const [name, factory] of Object.entries({
50
+ generate: createOpenApiGenerateCommand,
51
+ validate: createOpenApiValidateCommand,
52
+ check: createOpenApiCheckCommand,
53
+ })) {
54
+ commands[`openapi:${name}`] = async () => async () => {
55
+ let app: Awaited<ReturnType<AppFactory>> | undefined;
56
+ await factory(
57
+ async () => {
58
+ app = await (await load()).createApp({ migrate: false, mode: "command" });
59
+ return app;
60
+ },
61
+ async () => {
62
+ await app?.context.dispose();
63
+ },
64
+ )();
65
+ };
66
+ }
67
+ const schedulePath = config.schedule;
68
+ if (schedulePath)
69
+ commands["schedule:run"] = async () => async () => {
70
+ const environment = Object.freeze({ ...process.env });
71
+ let app: Awaited<ReturnType<AppFactory>> | undefined;
72
+ await createScheduleRunCommand(
73
+ async () => {
74
+ app = await boot();
75
+ const { createSchedule } = await import(pathToFileURL(schedulePath).href);
76
+ return createSchedule(app, environment);
77
+ },
78
+ async () => {
79
+ await app?.context.dispose();
80
+ },
81
+ { scheduler: createScheduleRunOptions(environment) },
82
+ )();
83
+ };
84
+ return commands;
85
+ }
86
+
87
+ export { applicationCommands };
@@ -3,9 +3,9 @@ import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
3
3
  import type { StrataAppConfig } from "../types.ts";
4
4
 
5
5
  type MigrateModule = {
6
- migrate?: (...args: string[]) => Promise<void> | void;
7
- seed?: (...args: string[]) => Promise<void> | void;
8
- fresh?: (...args: string[]) => Promise<void> | void;
6
+ migrate?: (environment?: Readonly<Record<string, string | undefined>>) => Promise<void> | void;
7
+ seed?: (environment?: Readonly<Record<string, string | undefined>>) => Promise<void> | void;
8
+ fresh?: (environment?: Readonly<Record<string, string | undefined>>) => Promise<void> | void;
9
9
  close?: () => Promise<void> | void;
10
10
  };
11
11
 
@@ -24,6 +24,7 @@ async function closeEntry(entry: MigrateModule): Promise<void> {
24
24
  }
25
25
 
26
26
  async function migrateCommand(app: StrataAppConfig, args: string[]): Promise<void> {
27
+ const environment = Object.freeze({ ...process.env });
27
28
  if (!app.migrate) {
28
29
  throw new Error(
29
30
  "No migrate entry found. Add src/db/migrate.ts or set migrate in strata.config.ts.",
@@ -39,10 +40,10 @@ async function migrateCommand(app: StrataAppConfig, args: string[]): Promise<voi
39
40
  }
40
41
 
41
42
  try {
42
- await entry.migrate(...args);
43
+ await entry.migrate(environment);
43
44
 
44
45
  if (args.includes("--seed") && typeof entry.seed === "function") {
45
- await entry.seed(...args);
46
+ await entry.seed(environment);
46
47
  }
47
48
  } finally {
48
49
  await closeEntry(entry);
@@ -51,8 +52,9 @@ async function migrateCommand(app: StrataAppConfig, args: string[]): Promise<voi
51
52
  }
52
53
 
53
54
  async function migrateFreshCommand(app: StrataAppConfig, args: string[]): Promise<void> {
55
+ const environment = Object.freeze({ ...process.env });
54
56
  if (args.some((arg) => arg !== "--seed")) throw new Error("migrate:fresh supports only --seed.");
55
- if (isProductionEnv())
57
+ if (isProductionEnv(environment))
56
58
  throw new Error("migrate:fresh is only available in development/test environments.");
57
59
  if (app.fresh) {
58
60
  const entry = await importEntry(app.fresh);
@@ -70,9 +72,9 @@ async function migrateFreshCommand(app: StrataAppConfig, args: string[]): Promis
70
72
  throw new Error("--seed requires a seed() export on the migration or fresh entry.");
71
73
  }
72
74
  try {
73
- await entry.fresh(...args);
75
+ await entry.fresh(environment);
74
76
  if (seedEntry?.seed) {
75
- await seedEntry.seed(...args);
77
+ await seedEntry.seed(environment);
76
78
  }
77
79
  } finally {
78
80
  await closeEntry(entry);
package/src/resolveApp.ts CHANGED
@@ -45,6 +45,8 @@ async function resolveApp(cwd = process.cwd()): Promise<StrataAppConfig> {
45
45
 
46
46
  return {
47
47
  root,
48
+ application: resolvePath(root, file.application, []),
49
+ schedule: resolvePath(root, file.schedule, []),
48
50
  preload: resolvePath(root, file.preload, [
49
51
  "src/bootstrap/preload.ts",
50
52
  "src/bootstrap/preloadModules.ts",
@@ -52,6 +54,8 @@ async function resolveApp(cwd = process.cwd()): Promise<StrataAppConfig> {
52
54
  server: resolvePath(root, file.server, ["src/bootstrap/server.ts"]),
53
55
  modulesDirectory: resolvePath(root, file.modulesDirectory, ["src/modules"]),
54
56
  commandsModule: resolvePath(root, file.commands, ["src/cli/register.ts"]),
57
+ migrateStatus: resolvePath(root, file.migrateStatus, ["src/db/status.ts"]),
58
+ rollback: resolvePath(root, file.rollback, ["src/db/rollback.ts"]),
55
59
  migrate: resolvePath(root, file.migrate, ["src/db/migrate.ts"]),
56
60
  fresh: resolvePath(root, file.fresh, ["src/db/fresh.ts"]),
57
61
  };
package/src/runCli.ts CHANGED
@@ -5,6 +5,7 @@ import { migrateCommand, migrateFreshCommand } from "./commands/migrate.ts";
5
5
  import { runCommand } from "./commands/run.ts";
6
6
  import { startCommand } from "./commands/start.ts";
7
7
  import { loadAppCommands, resolveApp } from "./resolveApp.ts";
8
+ import { scaffoldCommands } from "./scaffold/index.ts";
8
9
  import type { RunCliOptions, StrataAppConfig, StrataCommandMap } from "./types.ts";
9
10
 
10
11
  const HELP_FLAGS = new Set(["--help", "-h", "help"]);
@@ -40,10 +41,30 @@ function builtinCommands(app: StrataAppConfig): StrataCommandMap {
40
41
  };
41
42
  }
42
43
 
44
+ for (const [name, path, exported] of [
45
+ ["migrate:status", app.migrateStatus, "status"],
46
+ ["migrate:rollback", app.rollback, "rollback"],
47
+ ] as const) {
48
+ if (path)
49
+ commands[name] =
50
+ async () =>
51
+ async (...args: string[]) => {
52
+ if (args.length) throw new Error(`${name} takes no arguments.`);
53
+ const entry = await import(pathToFileURL(path).href);
54
+ if (typeof entry[exported] !== "function")
55
+ throw new Error(`${path} must export ${exported}().`);
56
+ try {
57
+ await entry[exported]();
58
+ } finally {
59
+ if (typeof entry.close === "function") await entry.close();
60
+ }
61
+ };
62
+ }
63
+
43
64
  return commands;
44
65
  }
45
66
 
46
- async function runCli(options: RunCliOptions = {}): Promise<number> {
67
+ async function executeCli(options: RunCliOptions = {}): Promise<number> {
47
68
  const exitProcess = options.exitProcess ?? true;
48
69
  const app = await resolveApp(options.cwd ?? process.cwd());
49
70
 
@@ -54,6 +75,8 @@ async function runCli(options: RunCliOptions = {}): Promise<number> {
54
75
  const appCommands = options.commands ?? (await loadAppCommands(app));
55
76
  const registry: StrataCommandMap = {
56
77
  ...builtinCommands(app),
78
+ ...(app.application ? (await import("./applicationCommands")).applicationCommands(app) : {}),
79
+ ...scaffoldCommands,
57
80
  ...appCommands,
58
81
  };
59
82
 
@@ -62,7 +85,9 @@ async function runCli(options: RunCliOptions = {}): Promise<number> {
62
85
  printHelp(commandNames);
63
86
  };
64
87
 
65
- const [requested = "help", ...args] = options.argv ?? process.argv.slice(2);
88
+ const argv = options.argv ?? process.argv.slice(2);
89
+ const verbose = argv.includes("--verbose");
90
+ const [requested = "help", ...args] = argv.filter((arg) => arg !== "--verbose");
66
91
  const command = HELP_FLAGS.has(requested) ? "help" : requested;
67
92
  const loadHandler = registry[command];
68
93
 
@@ -84,9 +109,20 @@ async function runCli(options: RunCliOptions = {}): Promise<number> {
84
109
  await handler(...args);
85
110
  return typeof process.exitCode === "number" ? process.exitCode : 0;
86
111
  } catch (error) {
87
- console.error(error);
112
+ console.error(verbose ? error : error instanceof Error ? error.message : String(error));
88
113
  return fail(1);
89
114
  }
90
115
  }
91
116
 
117
+ async function runCli(options: RunCliOptions = {}): Promise<number> {
118
+ try {
119
+ return await executeCli(options);
120
+ } catch (error) {
121
+ const verbose = (options.argv ?? process.argv.slice(2)).includes("--verbose");
122
+ console.error(verbose ? error : error instanceof Error ? error.message : String(error));
123
+ if (options.exitProcess ?? true) process.exit(1);
124
+ return 1;
125
+ }
126
+ }
127
+
92
128
  export { runCli };
@@ -1,49 +1,54 @@
1
- import { join } from "node:path";
2
- import { ensureDirectory, moduleDirectory, toKebabCase, toPascalCase } from "./utils";
3
-
4
- async function makeFactoryCommand(name?: string): Promise<void> {
1
+ import { dirname, join, relative, sep } from "node:path";
2
+ import { scaffoldArguments, writeScaffoldFile } from "./scaffoldFile";
3
+ import { moduleDirectory, toKebabCase, toPascalCase } from "./utils";
4
+
5
+ async function makeFactoryCommand(...args: string[]): Promise<void> {
6
+ const parsed = scaffoldArguments("make:factory", args);
7
+ if (!parsed) return;
8
+ const [name] = parsed;
5
9
  if (!name) {
6
10
  throw new Error("make:factory requires a model name.");
7
11
  }
8
12
 
9
- const moduleSlug = toKebabCase(name);
10
- const modelName = toPascalCase(name);
11
- const directory = moduleDirectory(moduleSlug);
12
- const filePath = join(directory, "factory.ts");
13
-
14
- await ensureDirectory(directory);
15
-
16
- const exists = await Bun.file(filePath).exists();
17
- if (exists) {
18
- throw new Error(`Factory already exists: ${filePath}`);
13
+ const classParts = name.split("/").map(toPascalCase);
14
+ const modelName = classParts.join("");
15
+ const filePath = join(
16
+ process.cwd(),
17
+ "src",
18
+ "db",
19
+ "factories",
20
+ ...classParts.slice(0, -1),
21
+ `${classParts.at(-1)}Factory.ts`,
22
+ );
23
+ if (await Bun.file(filePath).exists()) throw new Error(`Factory already exists: ${filePath}`);
24
+ const standalone = join(process.cwd(), "src", "models", ...classParts) + ".ts";
25
+ const module = await moduleDirectory(toKebabCase(name));
26
+ const candidates = [standalone, join(module, "types.ts"), join(module, "model.ts")];
27
+ let recordPath: string | undefined;
28
+ for (const candidate of candidates) {
29
+ if (await Bun.file(candidate).exists()) {
30
+ recordPath = candidate;
31
+ break;
32
+ }
19
33
  }
20
-
21
- const content = `import { defineFactory, Factory, type FactoryPersist } from "@getstrata/core/database/factory";
22
- import type { ${modelName}Record } from "./types";
23
-
24
- export interface ${modelName}FactoryDependencies {
25
- definition: () => ${modelName}Record;
26
- persist?: FactoryPersist<${modelName}Record>;
27
- }
28
-
29
- const ${modelName}Factory = defineFactory<${modelName}Record, ${modelName}FactoryDependencies>({
30
- construct: dependencies => ({
31
- definition: () => dependencies.definition(),
32
- persist: values => {
33
- if (!dependencies.persist) throw new Error("${modelName}Factory persistence must be supplied to use create().");
34
- return dependencies.persist(values);
35
- },
36
- }),
37
- });
38
-
39
- function create${modelName}Factory(dependencies: ${modelName}FactoryDependencies) {
40
- return Factory.from(${modelName}Factory, dependencies);
34
+ if (!recordPath)
35
+ throw new Error(
36
+ `Model ${modelName} was not found. Create it with make:model or make:module before make:factory.`,
37
+ );
38
+ let recordImport = relative(dirname(filePath), recordPath).split(sep).join("/");
39
+ if (!recordImport.startsWith(".")) recordImport = `./${recordImport}`;
40
+ const content = `import { createFactory, type FactoryPersist } from "@getstrata/core/database/factory";
41
+ import type { ${modelName}Record } from "${recordImport}";
42
+
43
+ function create${modelName}Factory(definition: () => ${modelName}Record, persist?: FactoryPersist<${modelName}Record>) {
44
+ return createFactory({ definition, persist });
41
45
  }
42
46
 
43
- export { ${modelName}Factory, create${modelName}Factory };
47
+ // Supply persistence from the current invocation, e.g. async values => (await session.model(${modelName}Definition).create(values)).toObject().
48
+ export { create${modelName}Factory };
44
49
  `;
45
50
 
46
- await Bun.write(filePath, content);
51
+ await writeScaffoldFile(relative(process.cwd(), filePath).split(sep), content, "Factory");
47
52
  console.log(`Created factory: ${filePath}`);
48
53
  }
49
54
 
@@ -1,8 +1,12 @@
1
- import { access, mkdir } from "node:fs/promises";
2
- import { join } from "node:path";
1
+ import { access } from "node:fs/promises";
2
+ import { join, relative, sep } from "node:path";
3
+ import { scaffoldArguments, writeScaffoldFile } from "./scaffoldFile";
3
4
  import { toKebabCase, toPascalCase } from "./utils";
4
5
 
5
- async function makeJobCommand(name?: string): Promise<void> {
6
+ async function makeJobCommand(...args: string[]): Promise<void> {
7
+ const parsed = scaffoldArguments("make:job", args);
8
+ if (!parsed) return;
9
+ const [name] = parsed;
6
10
  if (!name) {
7
11
  throw new Error("make:job requires a job name.");
8
12
  }
@@ -13,8 +17,6 @@ async function makeJobCommand(name?: string): Promise<void> {
13
17
  const directory = join(process.cwd(), "src", "jobs");
14
18
  const jobPath = join(directory, `${jobSlug}Job.ts`);
15
19
 
16
- await mkdir(directory, { recursive: true });
17
-
18
20
  try {
19
21
  await access(jobPath);
20
22
  throw new Error(`Job already exists: ${jobPath}`);
@@ -41,7 +43,7 @@ export default ${jobClass};
41
43
  export type { ${payloadType} };
42
44
  `;
43
45
 
44
- await Bun.write(jobPath, content);
46
+ await writeScaffoldFile(relative(process.cwd(), jobPath).split(sep), content, "Job");
45
47
 
46
48
  console.log(`Created job in: ${jobPath}`);
47
49
  console.log(
@@ -1,20 +1,21 @@
1
- import { access, mkdir } from "node:fs/promises";
2
- import { join } from "node:path";
1
+ import { access } from "node:fs/promises";
2
+ import { join, relative, sep } from "node:path";
3
+ import { scaffoldArguments, writeScaffoldFile } from "./scaffoldFile";
3
4
  import { toCamelCase, toKebabCase, toPascalCase } from "./utils";
4
5
 
5
- async function makeListenerCommand(name?: string, eventName?: string): Promise<void> {
6
+ async function makeListenerCommand(...args: string[]): Promise<void> {
7
+ const parsed = scaffoldArguments("make:listener", args);
8
+ if (!parsed) return;
9
+ const [name, eventName] = parsed;
6
10
  if (!name) {
7
11
  throw new Error("make:listener requires a listener name.");
8
12
  }
9
13
 
10
14
  const listenerSlug = toKebabCase(name);
11
- const listenerToken = `${toPascalCase(name)}Listener`;
12
15
  const directory = join(process.cwd(), "src", "listeners");
13
16
  const listenerPath = join(directory, `${listenerSlug}.ts`);
14
17
  const resolvedEventName = eventName ?? `${toCamelCase(name)}.created`;
15
18
 
16
- await mkdir(directory, { recursive: true });
17
-
18
19
  try {
19
20
  await access(listenerPath);
20
21
  throw new Error(`Listener already exists: ${listenerPath}`);
@@ -30,34 +31,21 @@ async function makeListenerCommand(name?: string, eventName?: string): Promise<v
30
31
  ["created", "updated", "deleted", "restored", "force-deleted"].includes(action ?? "");
31
32
  const modelName = toPascalCase((table ?? name).replace(/s$/, ""));
32
33
  const content = modelEvent
33
- ? `import { service } from "@getstrata/core/contracts/services";
34
- import { createServiceToken } from "@getstrata/core/contracts/token";
35
- import { repositoryEffects, type AfterCommitRepositoryListener } from "@getstrata/core/database/definitions";
36
- import { ${modelName}Repository, type ${modelName}Record } from "../models/${modelName}.ts";
37
- import type { ListenerDeclarations } from "@getstrata/bootstrap/discoverListeners";
34
+ ? `import { defineModelListener } from "@getstrata/bootstrap/discoverListeners";
35
+ import { ${modelName}Repository } from "../models/${modelName}.ts";
38
36
 
39
- const ${listenerToken}=createServiceToken<AfterCommitRepositoryListener<${modelName}Record>>(${JSON.stringify(resolvedEventName)});
40
- const declarations:ListenerDeclarations=Object.freeze({
41
- services:Object.freeze([service(${listenerToken},{lifetime:"application",dependencies:[] as const,create:()=>async(row)=>{void row;}})]),
42
- repositoryEffects:Object.freeze([repositoryEffects(${modelName}Repository,[{action:${JSON.stringify(action)},afterCommit:${listenerToken}}])]),
37
+ export default defineModelListener(${modelName}Repository, ${JSON.stringify(action)}, async row => {
38
+ void row;
43
39
  });
44
- export default declarations;
45
40
  `
46
- : `import { resourceService } from "@getstrata/core/contracts/services";
47
- import { createServiceToken } from "@getstrata/core/contracts/token";
48
- import { APPLICATION_EVENT_BUS_TOKEN } from "@getstrata/bootstrap/providers/events";
49
- import type { ListenerDeclarations } from "@getstrata/bootstrap/discoverListeners";
41
+ : `import { defineEventListener } from "@getstrata/bootstrap/discoverListeners";
50
42
 
51
- const ${listenerToken}=createServiceToken<()=>void>(${JSON.stringify(resolvedEventName)});
52
- const declarations:ListenerDeclarations=Object.freeze({repositoryEffects:Object.freeze([]),services:Object.freeze([
53
- resourceService(${listenerToken},{lifetime:"application",dependencies:[APPLICATION_EVENT_BUS_TOKEN] as const,create:bus=>({
54
- name:${JSON.stringify(resolvedEventName)},open:()=>({ok:true,value:bus.listen(${JSON.stringify(resolvedEventName)},async payload=>{void payload;})}),close:unsubscribe=>unsubscribe(),
55
- })}),
56
- ])});
57
- export default declarations;
43
+ export default defineEventListener(${JSON.stringify(resolvedEventName)}, async payload => {
44
+ void payload;
45
+ });
58
46
  `;
59
47
 
60
- await Bun.write(listenerPath, content);
48
+ await writeScaffoldFile(relative(process.cwd(), listenerPath).split(sep), content, "Listener");
61
49
 
62
50
  console.log(`Created listener in: ${listenerPath}`);
63
51
  console.log(`Listening for event: ${resolvedEventName}`);
@@ -1,8 +1,12 @@
1
1
  import { access } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import { ensureDirectory, migrationDirectory, timestampForFilename, toKebabCase } from "./utils";
4
-
5
- async function makeMigrationCommand(name?: string): Promise<void> {
2
+ import { join, relative, sep } from "node:path";
3
+ import { scaffoldArguments, writeScaffoldFile } from "./scaffoldFile";
4
+ import { migrationDirectory, timestampForFilename, toKebabCase } from "./utils";
5
+
6
+ async function makeMigrationCommand(...args: string[]): Promise<void> {
7
+ const parsed = scaffoldArguments("make:migration", args);
8
+ if (!parsed) return;
9
+ const [name] = parsed;
6
10
  if (!name) {
7
11
  throw new Error("make:migration requires a name.");
8
12
  }
@@ -16,8 +20,6 @@ async function makeMigrationCommand(name?: string): Promise<void> {
16
20
  const directory = migrationDirectory();
17
21
  const filePath = join(directory, `${fileBaseName}.ts`);
18
22
 
19
- await ensureDirectory(directory);
20
-
21
23
  try {
22
24
  await access(filePath);
23
25
  throw new Error(`Migration already exists: ${filePath}`);
@@ -30,31 +32,25 @@ async function makeMigrationCommand(name?: string): Promise<void> {
30
32
  }
31
33
  }
32
34
 
33
- const content = `import type { Migration } from "@getstrata/core/database/migrations/types";
34
- import { currentSqlDialect } from "@getstrata/core/database/dialect";
35
- import { Schema } from "@getstrata/core/database/schema";
35
+ const content = `import { defineMigration } from "@getstrata/core/database/migrations";
36
36
 
37
- const migration: Migration = {
37
+ export default defineMigration({
38
38
  name: "${fileBaseName}",
39
- async up(db) {
40
- await Schema.run(db, currentSqlDialect().driver, (schema) => {
41
- // Define schema.create(...) or schema.table(...) here.
42
- // Keep data transformations and unsupported engine features in db.unsafe(...).
43
- void schema;
44
- });
39
+ up(schema, db) {
40
+ // Define schema.create(...) or schema.table(...) here.
41
+ // Use db.unsafe(...) for explicit data transformations.
42
+ void schema;
43
+ void db;
45
44
  },
46
- async down(db) {
47
- await Schema.run(db, currentSqlDialect().driver, (schema) => {
48
- // Reverse the schema changes; guard against losing business history.
49
- void schema;
50
- });
45
+ down(schema, db) {
46
+ // Reverse the schema changes; preserve business history.
47
+ void schema;
48
+ void db;
51
49
  },
52
- };
53
-
54
- export default migration;
50
+ });
55
51
  `;
56
52
 
57
- await Bun.write(filePath, content);
53
+ await writeScaffoldFile(relative(process.cwd(), filePath).split(sep), content, "Migration");
58
54
  console.log(`Created migration: ${filePath}`);
59
55
  }
60
56
 
@@ -44,29 +44,23 @@ async function makeModelCommand(...args: string[]): Promise<void> {
44
44
  if (keyType !== "number" && keyType !== "string")
45
45
  throw new Error("--key-type must be number or string; UUID model keys use string.");
46
46
  const fillable = keyType === "string" ? JSON.stringify(key) : "";
47
- const content = `import { Model } from "@getstrata/core/database/model";
48
- import { BaseRepository } from "@getstrata/core/database/baseRepository";
49
- import { defineModel, defineRepository } from "@getstrata/core/database/definitions";
47
+ const content = `import { createModel, type Model } from "@getstrata/core/database/model";
50
48
  import { defineTable } from "@getstrata/core/database/table";
51
49
 
52
50
  interface ${className}Record { ${key}: ${keyType}; }
53
51
  const table = defineTable<${className}Record, "${key}">({
54
52
  name: "${table}", primaryKey: "${key}", columns: ["${key}"],
55
53
  });
56
- const repository = defineRepository({
57
- name: "${className}.repository", table, dependencies: [] as const,
58
- create: binding => new BaseRepository(binding),
59
- });
60
- class ${className} extends Model<${className}Record, "${key}"> {}
61
- const ${className}Definition = defineModel({
62
- name: "${className}", repository, dependencies: [] as const,
54
+ type ${className} = Model<${className}Record, "${key}">;
55
+ const ${className}Definition = createModel({
56
+ name: "${className}", table,
63
57
  attributes: { fillable: [${fillable}], timestamps: false },
64
- construct: (state, binding) => new ${className}(state, binding),
65
58
  });
59
+ const ${className}Repository = ${className}Definition.repository;
66
60
  // Register this definition in createDatabaseBindings({ models: [...] }).
67
61
  // Use selectedSession.model(${className}Definition) inside an application invocation.
68
- export type { ${className}Record };
69
- export { ${className}, ${className}Definition, repository as ${className}Repository };
62
+ export type { ${className}Record, ${className} };
63
+ export { ${className}Definition, ${className}Repository };
70
64
  `;
71
65
  const path = await writeScaffoldFile(
72
66
  ["src", "models", ...classParts.slice(0, -1), `${classParts.at(-1)}.ts`],
@@ -1,8 +1,8 @@
1
1
  import { access } from "node:fs/promises";
2
- import { join } from "node:path";
2
+ import { join, relative, sep } from "node:path";
3
3
  import { renderModuleScaffold } from "./renderModule";
4
+ import { scaffoldArguments, writeScaffoldFile } from "./scaffoldFile";
4
5
  import {
5
- ensureDirectory,
6
6
  moduleDirectory,
7
7
  toCamelCase,
8
8
  toKebabCase,
@@ -11,8 +11,10 @@ import {
11
11
  } from "./utils";
12
12
 
13
13
  async function makeModuleCommand(...args: string[]): Promise<void> {
14
+ const parsed = scaffoldArguments("make:module", args, ["--with-web"]);
15
+ if (!parsed) return;
14
16
  const withWeb = args.includes("--with-web");
15
- const name = args.find((arg) => !arg.startsWith("--"));
17
+ const [name] = parsed;
16
18
 
17
19
  if (!name) {
18
20
  throw new Error("make:module requires a name.");
@@ -26,7 +28,7 @@ async function makeModuleCommand(...args: string[]): Promise<void> {
26
28
  throw new Error("make:module requires a valid module name.");
27
29
  }
28
30
 
29
- const directory = moduleDirectory(moduleSlug);
31
+ const directory = await moduleDirectory(moduleSlug);
30
32
 
31
33
  try {
32
34
  await access(directory);
@@ -40,8 +42,6 @@ async function makeModuleCommand(...args: string[]): Promise<void> {
40
42
  }
41
43
  }
42
44
 
43
- await ensureDirectory(directory);
44
-
45
45
  const { files, webFiles, viewFiles, pluralSlug } = renderModuleScaffold({
46
46
  moduleSlug,
47
47
  moduleName,
@@ -50,7 +50,11 @@ async function makeModuleCommand(...args: string[]): Promise<void> {
50
50
  });
51
51
 
52
52
  for (const [fileName, content] of files) {
53
- await Bun.write(join(directory, fileName), content);
53
+ await writeScaffoldFile(
54
+ relative(process.cwd(), join(directory, fileName)).split(sep),
55
+ content,
56
+ "Module file",
57
+ );
54
58
  }
55
59
 
56
60
  let createdViewsDirectory: string | undefined;
@@ -58,12 +62,19 @@ async function makeModuleCommand(...args: string[]): Promise<void> {
58
62
  if (withWeb) {
59
63
  const viewsDirectory = webViewsDirectory(pluralSlug);
60
64
  createdViewsDirectory = viewsDirectory;
61
- await ensureDirectory(viewsDirectory);
62
65
  for (const [fileName, content] of viewFiles) {
63
- await Bun.write(join(viewsDirectory, fileName), content);
66
+ await writeScaffoldFile(
67
+ relative(process.cwd(), join(viewsDirectory, fileName)).split(sep),
68
+ content,
69
+ "Module view",
70
+ );
64
71
  }
65
72
  for (const [fileName, content] of webFiles) {
66
- await Bun.write(join(directory, fileName), content);
73
+ await writeScaffoldFile(
74
+ relative(process.cwd(), join(directory, fileName)).split(sep),
75
+ content,
76
+ "Module file",
77
+ );
67
78
  }
68
79
  }
69
80
 
@@ -78,7 +89,7 @@ async function makeModuleCommand(...args: string[]): Promise<void> {
78
89
  console.log(`Module will be auto-discovered from the app modules directory (${moduleSlug}/)`);
79
90
  console.log(`Next: strata make:migration create_${moduleSlug} && strata migrate`);
80
91
 
81
- console.log("Register the generated repository definition in application database bindings.");
92
+ console.log("Register the generated model and its repository in src/models/register.ts.");
82
93
  }
83
94
 
84
95
  export { makeModuleCommand };
@@ -1,15 +1,19 @@
1
1
  import { access } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import { moduleDirectory, toCamelCase, toKebabCase, toPascalCase } from "./utils";
2
+ import { join, relative, sep } from "node:path";
3
+ import { scaffoldArguments, writeScaffoldFile } from "./scaffoldFile";
4
+ import { moduleDirectory, toKebabCase, toPascalCase } from "./utils";
4
5
 
5
- async function makePolicyCommand(moduleName?: string): Promise<void> {
6
+ async function makePolicyCommand(...args: string[]): Promise<void> {
7
+ const parsed = scaffoldArguments("make:policy", args);
8
+ if (!parsed) return;
9
+ const [moduleName] = parsed;
6
10
  if (!moduleName) {
7
11
  throw new Error("make:policy requires a module name.");
8
12
  }
9
13
 
10
14
  const moduleSlug = toKebabCase(moduleName);
11
15
  const resourceName = toPascalCase(moduleName);
12
- const directory = moduleDirectory(moduleSlug);
16
+ const directory = await moduleDirectory(moduleSlug);
13
17
  const policyPath = join(directory, "policy.ts");
14
18
 
15
19
  try {
@@ -29,7 +33,6 @@ async function makePolicyCommand(moduleName?: string): Promise<void> {
29
33
 
30
34
  const recordType = `${resourceName}Record`;
31
35
  const policyClass = `${resourceName}Policy`;
32
- const policyVariable = `${toCamelCase(moduleName)}Policy`;
33
36
 
34
37
  const content = `import { Policy } from "@getstrata/core/auth/policy";
35
38
  import type { ${recordType} } from "./types";
@@ -55,11 +58,11 @@ class ${policyClass} extends Policy {
55
58
  export default ${policyClass};
56
59
  `;
57
60
 
58
- await Bun.write(policyPath, content);
61
+ await writeScaffoldFile(relative(process.cwd(), policyPath).split(sep), content, "Policy");
59
62
 
60
63
  console.log(`Created policy in: ${policyPath}`);
61
64
  console.log(
62
- `Register it in src/modules/${moduleSlug}/provider.ts boot() via gate.register("${moduleSlug}", container.resolve(${policyVariable})).`,
65
+ `Register it in your module index: policies: { "${moduleSlug}": new ${policyClass}() }.`,
63
66
  );
64
67
  }
65
68
 
@@ -1,16 +1,18 @@
1
- import { join } from "node:path";
2
- import { ensureDirectory, moduleDirectory, toKebabCase, toPascalCase } from "./utils";
1
+ import { join, relative, sep } from "node:path";
2
+ import { scaffoldArguments, writeScaffoldFile } from "./scaffoldFile";
3
+ import { moduleDirectory, toKebabCase, toPascalCase } from "./utils";
3
4
 
4
- async function makeRequestCommand(moduleName?: string): Promise<void> {
5
+ async function makeRequestCommand(...args: string[]): Promise<void> {
6
+ const parsed = scaffoldArguments("make:request", args);
7
+ if (!parsed) return;
8
+ const [moduleName] = parsed;
5
9
  if (!moduleName) {
6
10
  throw new Error("make:request requires a module name.");
7
11
  }
8
12
 
9
13
  const moduleSlug = toKebabCase(moduleName);
10
14
  const moduleNamePascal = toPascalCase(moduleName);
11
- const filePath = join(moduleDirectory(moduleSlug), "requests.ts");
12
-
13
- await ensureDirectory(moduleDirectory(moduleSlug));
15
+ const filePath = join(await moduleDirectory(moduleSlug), "requests.ts");
14
16
 
15
17
  const exists = await Bun.file(filePath).exists();
16
18
  if (exists) {
@@ -63,7 +65,7 @@ export { parseCreate${moduleNamePascal}Body, parse${moduleNamePascal}IdParams };
63
65
  export type { Create${moduleNamePascal}BodyDto, ${moduleNamePascal}IdParams };
64
66
  `;
65
67
 
66
- await Bun.write(filePath, content);
68
+ await writeScaffoldFile(relative(process.cwd(), filePath).split(sep), content, "Request");
67
69
  console.log(`Created request helpers: ${filePath}`);
68
70
  }
69
71
 
@@ -42,58 +42,15 @@ export { ${moduleIdentifier}Table };
42
42
  `,
43
43
  ],
44
44
  [
45
- "repository.ts",
46
- `import { BaseRepository } from "@getstrata/core/database/baseRepository";
47
- import { defineRepository } from "@getstrata/core/database/definitions";
45
+ "model.ts",
46
+ `import { createModel } from "@getstrata/core/database/model";
48
47
  import { ${moduleIdentifier}Table } from "./table";
49
- import type { ${moduleName}Record } from "./types";
50
-
51
- class ${moduleName}Repository extends BaseRepository<${moduleName}Record, "id"> {}
52
- const ${moduleIdentifier}Repository = defineRepository({
53
- name: "${moduleSlug}.repository", table: ${moduleIdentifier}Table, dependencies: [] as const,
54
- create: binding => new ${moduleName}Repository(binding),
48
+ const ${moduleName}Definition = createModel({
49
+ name: "${moduleName}", table: ${moduleIdentifier}Table,
50
+ attributes: { fillable: ["name"], timestamps: false },
55
51
  });
56
- export { ${moduleIdentifier}Repository };
57
- export default ${moduleName}Repository;
58
- `,
59
- ],
60
- [
61
- "service.ts",
62
- `import { NotFoundError } from "@getstrata/core/errors/http";
63
- import ${moduleName}Repository from "./repository";
64
- import type { ${moduleName}Record } from "./types";
65
- import type { PaginatedResult } from "@getstrata/core/pagination";
66
-
67
- class ${moduleName}Service {
68
- constructor(private readonly repository: ${moduleName}Repository) {}
69
-
70
- paginate(options: {
71
- page: number;
72
- perPage: number;
73
- }): Promise<PaginatedResult<${moduleName}Record>> {
74
- return this.repository.paginate(options);
75
- }
76
-
77
- findByIdOrThrow(id: number): Promise<${moduleName}Record> {
78
- return this.repository.findByIdOrThrow(id, () => new NotFoundError("${moduleName} not found."));
79
- }
80
-
81
- create(input: { name: string }): Promise<${moduleName}Record> {
82
- return this.repository.create(input);
83
- }
84
-
85
- update(id: number, input: { name?: string }): Promise<${moduleName}Record> {
86
- return this.repository.updateByIdOrThrow(id, input, () => new NotFoundError("${moduleName} not found."));
87
- }
88
-
89
- async delete(id: number): Promise<void> {
90
- if (!(await this.repository.deleteById(id))) {
91
- throw new NotFoundError("${moduleName} not found.");
92
- }
93
- }
94
- }
95
-
96
- export default ${moduleName}Service;
52
+ const ${moduleIdentifier}Repository = ${moduleName}Definition.repository;
53
+ export { ${moduleName}Definition, ${moduleIdentifier}Repository };
97
54
  `,
98
55
  ],
99
56
  [
@@ -117,32 +74,6 @@ class ${moduleName}Policy extends Policy {
117
74
  }
118
75
 
119
76
  export default ${moduleName}Policy;
120
- `,
121
- ],
122
- [
123
- "provider.ts",
124
- `import { createServiceToken } from "@getstrata/core/contracts/token";
125
- import type { ServiceProvider } from "@getstrata/core/contracts/di";
126
- import { CORE_POLICY_GATE_TOKEN } from "@getstrata/bootstrap/config";
127
- import ${moduleName}Policy from "./policy";
128
-
129
- const ${moduleIdentifier}PolicyToken = createServiceToken<${moduleName}Policy>("${moduleSlug}.policy");
130
-
131
- const ${moduleIdentifier}Provider: ServiceProvider = {
132
- name: "${moduleSlug}.provider",
133
- register({ container }) {
134
- container.singleton(${moduleIdentifier}PolicyToken, () => new ${moduleName}Policy());
135
- },
136
- boot({ container }) {
137
- const gate = container.resolve(CORE_POLICY_GATE_TOKEN);
138
- gate.register("${moduleSlug}", container.resolve(${moduleIdentifier}PolicyToken));
139
- },
140
- };
141
-
142
- export default ${moduleIdentifier}Provider;
143
- export {
144
- ${moduleIdentifier}PolicyToken,
145
- };
146
77
  `,
147
78
  ],
148
79
  [
@@ -272,8 +203,8 @@ import { buildRequestCacheKey } from "@getstrata/core/http/validation";
272
203
  import {type RouteModelBindingPorts, securedBindRouteModel } from "@getstrata/core/http/securedRouteModelBinding";
273
204
  import type { RouteRequest } from "@getstrata/core/http/route";
274
205
  import { createdResponse, jsonResponse, noContentResponse } from "@getstrata/core/http/response";
275
- import ${moduleName}Service from "./service";
276
- import { ${moduleIdentifier}Repository } from "./repository";
206
+ import { NotFoundError } from "@getstrata/core/errors/http";
207
+ import { ${moduleIdentifier}Repository } from "./model";
277
208
  import {
278
209
  parseCreate${moduleName}Body,
279
210
  parse${moduleName}ListQuery,
@@ -299,8 +230,12 @@ class ${moduleName}Controller {
299
230
  readonly update:(request:RouteRequest<${moduleName}IdParams>)=>Promise<Response>;
300
231
  readonly destroy:(request:RouteRequest<${moduleName}IdParams>)=>Promise<Response>;
301
232
 
302
- private get service(): ${moduleName}Service {
303
- return new ${moduleName}Service(this.database.repository(${moduleIdentifier}Repository));
233
+ private get records() {
234
+ return this.database.repository(${moduleIdentifier}Repository);
235
+ }
236
+
237
+ private find(id: number) {
238
+ return this.records.findByIdOrThrow(id, () => new NotFoundError("${moduleName} not found."));
304
239
  }
305
240
 
306
241
  readonly index = (async (request?: Request) => {
@@ -310,7 +245,7 @@ class ${moduleName}Controller {
310
245
  return await this.cachedJson(
311
246
  cacheKey,
312
247
  async () => {
313
- const result = await this.service.paginate(query);
248
+ const result = await this.records.paginate(query);
314
249
  return to${moduleName}PaginatedResourceCollection(result.data, result.meta);
315
250
  },
316
251
  [${moduleIdentifier.toUpperCase()}_CACHE_TAG],
@@ -321,7 +256,7 @@ class ${moduleName}Controller {
321
256
  readonly show = (
322
257
  bindRouteModel(
323
258
  "id",
324
- (id) => this.service.findByIdOrThrow(id),
259
+ (id) => this.find(id),
325
260
  async (_request: RouteRequest<${moduleName}IdParams>, record) => {
326
261
  return jsonResponse(to${moduleName}Resource(record));
327
262
  },
@@ -330,17 +265,17 @@ class ${moduleName}Controller {
330
265
 
331
266
  readonly store = (async (request: Request) => {
332
267
  const body = await parseCreate${moduleName}Body(request);
333
- const record = await this.service.create(body);
268
+ const record = await this.records.create(body);
334
269
  return createdResponse(to${moduleName}Resource(record));
335
270
  });
336
271
 
337
272
  private bindUpdate(binding:RouteModelBindingPorts) {return securedBindRouteModel(
338
273
  "id",
339
- (id) => this.service.findByIdOrThrow(id),
274
+ (id) => this.find(id),
340
275
  { resource: "${moduleSlug}", action: "update" },
341
276
  async (req: RouteRequest<${moduleName}IdParams>, record) => {
342
277
  const body = await parseUpdate${moduleName}Body(req);
343
- const updated = await this.service.update(record.id, body);
278
+ const updated = await this.records.updateByIdOrThrow(record.id, body, () => new NotFoundError("${moduleName} not found."));
344
279
  return jsonResponse(to${moduleName}Resource(updated));
345
280
  },
346
281
  binding,
@@ -349,10 +284,10 @@ class ${moduleName}Controller {
349
284
 
350
285
  private bindDestroy(binding:RouteModelBindingPorts) {return securedBindRouteModel(
351
286
  "id",
352
- (id) => this.service.findByIdOrThrow(id),
287
+ (id) => this.find(id),
353
288
  { resource: "${moduleSlug}", action: "delete" },
354
289
  async (_request: RouteRequest<${moduleName}IdParams>, record) => {
355
- await this.service.delete(record.id);
290
+ await this.records.deleteById(record.id);
356
291
  return noContentResponse();
357
292
  },
358
293
  binding,
@@ -369,15 +304,13 @@ export default ${moduleName}Controller;
369
304
  import type { BusinessRequestPorts } from "@getstrata/bootstrap/contracts";
370
305
  import type { RouteRequest } from "@getstrata/core/http/route";
371
306
  import type { ${moduleName}IdParams } from "./requests";
372
- import type { AppDependencies, CachedJson } from "@getstrata/core/contracts/di";
307
+ import type { CachedJson } from "@getstrata/core/contracts/di";
373
308
  ${withWeb ? 'import { apiPrefix } from "@getstrata/core/runtime/appKeyPrefix";\n' : ""}import ${moduleName}Controller from "./controller";
374
309
 
375
310
  function create${moduleName}Routes(
376
- dependencies: AppDependencies,
377
311
  cachedJson: CachedJson,
378
312
  kernel: HttpKernel,
379
313
  ) {
380
- void dependencies;
381
314
  const controller = (ports: BusinessRequestPorts) => new ${moduleName}Controller(ports.database, cachedJson, kernel.routeModelBindingPorts(ports.auth));
382
315
  ${withWeb ? ` const apiBase = \`\${apiPrefix()}/${pluralSlug}\`;\n` : ""}
383
316
 
@@ -410,8 +343,7 @@ export { create${moduleName}Routes };
410
343
  "index.ts",
411
344
  `import { type AppModule } from "@getstrata/bootstrap/contracts";
412
345
  import ${moduleName}Controller from "./controller";
413
- import ${moduleIdentifier}Provider, {
414
- } from "./provider";
346
+ import ${moduleName}Policy from "./policy";
415
347
  import { create${moduleName}Routes } from "./routes";${
416
348
  withWeb
417
349
  ? `
@@ -425,9 +357,9 @@ const ${moduleVariable}: AppModule = {
425
357
  order: 100,
426
358
  tableName: ${moduleIdentifier}Table.name,
427
359
  cacheTags: ["${pluralSlug}"],
428
- providers: [${moduleIdentifier}Provider],
429
- routes({ dependencies, cachedJson, kernel }) {
430
- return create${moduleName}Routes(dependencies, cachedJson, kernel);
360
+ policies: { "${moduleSlug}": new ${moduleName}Policy() },
361
+ routes({ cachedJson, kernel }) {
362
+ return create${moduleName}Routes(cachedJson, kernel);
431
363
  },${
432
364
  withWeb
433
365
  ? `
@@ -439,9 +371,6 @@ const ${moduleVariable}: AppModule = {
439
371
  };
440
372
 
441
373
  export default ${moduleVariable};
442
- export {
443
- ${moduleIdentifier}Provider,
444
- };
445
374
  export { ${moduleName}Controller };
446
375
  export { parse${moduleName}IdParams, parse${moduleName}ListQuery } from "./requests";
447
376
  export {
@@ -455,8 +384,7 @@ export { create${moduleName}Routes } from "./routes";${
455
384
  export { create${moduleName}WebRoutes } from "./webRoutes";`
456
385
  : ""
457
386
  }
458
- export { default as ${moduleName}Repository, ${moduleIdentifier}Repository } from "./repository";
459
- export { default as ${moduleName}Service } from "./service";
387
+ export { ${moduleName}Definition, ${moduleIdentifier}Repository } from "./model";
460
388
  export { ${moduleIdentifier}Table } from "./table";
461
389
  export type { ${moduleName}Record } from "./types";
462
390
  `,
@@ -480,27 +408,20 @@ export type { ${moduleName}Record } from "./types";
480
408
  webFiles.set(
481
409
  "webController.ts",
482
410
  `import type { BusinessRequestPorts } from "@getstrata/bootstrap/contracts";
483
- import type { AppDependencies } from "@getstrata/core/contracts/di";
484
- import { resolveService } from "@getstrata/core/contracts/di";
485
- import { CORE_VIEW_RENDERER_TOKEN, type NamespacedViewRenderer } from "@getstrata/core/view";
486
- import { ${moduleIdentifier}Repository } from "./repository";
411
+ import type { NamespacedViewRenderer } from "@getstrata/core/view";
412
+ import { ${moduleIdentifier}Repository } from "./model";
487
413
  import { parse${moduleName}ListQuery } from "./requests";
488
- import ${moduleName}Service from "./service";
489
414
 
490
415
  class ${moduleName}WebController {
491
- constructor(private readonly dependencies: AppDependencies, private readonly database: BusinessRequestPorts["database"]) {}
492
-
493
- private get service(): ${moduleName}Service {
494
- return new ${moduleName}Service(this.database.repository(${moduleIdentifier}Repository));
495
- }
416
+ constructor(private readonly views: NamespacedViewRenderer, private readonly database: BusinessRequestPorts["database"]) {}
496
417
 
497
- private get views(): NamespacedViewRenderer {
498
- return resolveService(this.dependencies, CORE_VIEW_RENDERER_TOKEN).namespace("${pluralSlug}");
418
+ private get records() {
419
+ return this.database.repository(${moduleIdentifier}Repository);
499
420
  }
500
421
 
501
422
  readonly index = (async (request?: Request) => {
502
423
  const query = parse${moduleName}ListQuery(request);
503
- const result = await this.service.paginate(query);
424
+ const result = await this.records.paginate(query);
504
425
 
505
426
  return this.views.renderHtmx("index.eta", {
506
427
  layout: { title: "${moduleName}s" },
@@ -517,15 +438,17 @@ export default ${moduleName}WebController;
517
438
 
518
439
  webFiles.set(
519
440
  "webRoutes.ts",
520
- `import type { AppDependencies } from "@getstrata/core/contracts/di";
441
+ `import { resolveService, type AppDependencies } from "@getstrata/core/contracts/di";
442
+ import { CORE_VIEW_RENDERER_TOKEN } from "@getstrata/core/view";
521
443
  import type { HttpKernel } from "@getstrata/bootstrap/httpKernel";
522
444
  import type { BusinessRequestPorts } from "@getstrata/bootstrap/contracts";
523
445
  import ${moduleName}WebController from "./webController";
524
446
 
525
447
  function create${moduleName}WebRoutes(dependencies: AppDependencies, kernel: HttpKernel) {
448
+ const views = resolveService(dependencies, CORE_VIEW_RENDERER_TOKEN).namespace("${pluralSlug}");
526
449
  return {
527
450
  "/${pluralSlug}": {
528
- GET: kernel.wrapWebPublicRead((request: Request, ports: BusinessRequestPorts) => new ${moduleName}WebController(dependencies, ports.database).index(request)),
451
+ GET: kernel.wrapWebPublicRead((request: Request, ports: BusinessRequestPorts) => new ${moduleName}WebController(views, ports.database).index(request)),
529
452
  },
530
453
  };
531
454
  }
@@ -1,6 +1,6 @@
1
1
  import type { Stats } from "node:fs";
2
2
  import { lstat, mkdir, writeFile } from "node:fs/promises";
3
- import { join } from "node:path";
3
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
4
4
 
5
5
  /** Validate before normalization so traversal and punctuation cannot become a different name. */
6
6
  function scaffoldNameParts(
@@ -24,6 +24,11 @@ async function writeScaffoldFile(
24
24
  content: string,
25
25
  label: string,
26
26
  ): Promise<string> {
27
+ const target = resolve(process.cwd(), ...segments);
28
+ const local = relative(process.cwd(), target);
29
+ if (!local || local.startsWith(`..${sep}`) || local === ".." || isAbsolute(local))
30
+ throw new Error("Scaffold output must stay inside the application directory.");
31
+ segments = local.split(sep);
27
32
  let directory = process.cwd();
28
33
  for (const segment of segments.slice(0, -1)) {
29
34
  directory = join(directory, segment);
@@ -51,3 +56,36 @@ async function writeScaffoldFile(
51
56
  }
52
57
 
53
58
  export { scaffoldNameParts, writeScaffoldFile };
59
+
60
+ function scaffoldArguments(
61
+ command: string,
62
+ args: string[],
63
+ flags: string[] = [],
64
+ ): string[] | undefined {
65
+ if (args.includes("--help") || args.includes("-h")) {
66
+ console.log(
67
+ `Usage: strata ${command} <Name>${command === "make:listener" ? " [event]" : ""}${flags.map((flag) => ` [${flag}]`).join("")}`,
68
+ );
69
+ return;
70
+ }
71
+ const names = args.filter((arg) => !flags.includes(arg));
72
+ if (names.some((arg) => arg.startsWith("-")))
73
+ throw new Error(`Unsupported ${command} option; use --help.`);
74
+ if (names.length > (command === "make:listener" ? 2 : 1))
75
+ throw new Error(`${command} received too many arguments; use --help.`);
76
+ const noun =
77
+ (
78
+ {
79
+ "make:factory": "model name",
80
+ "make:job": "job name",
81
+ "make:listener": "listener name",
82
+ "make:policy": "module name",
83
+ "make:request": "module name",
84
+ } as Record<string, string>
85
+ )[command] ?? "name";
86
+ if (!names[0]) throw new Error(`${command} requires a ${noun}.`);
87
+ scaffoldNameParts(names[0], command);
88
+ return names;
89
+ }
90
+
91
+ export { scaffoldArguments };
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { mkdir } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
+ import { resolveApp } from "../resolveApp";
4
5
 
5
6
  function toKebabCase(value: string): string {
6
7
  return value
@@ -43,8 +44,12 @@ async function ensureDirectory(path: string): Promise<void> {
43
44
  await mkdir(path, { recursive: true });
44
45
  }
45
46
 
46
- function moduleDirectory(name: string): string {
47
- return join(process.cwd(), "src", "modules", toKebabCase(name));
47
+ async function moduleDirectory(name: string): Promise<string> {
48
+ const app = await resolveApp();
49
+ return join(
50
+ app.modulesDirectory ?? join(app.root, "src", "modules"),
51
+ ...name.split("/").map(toKebabCase),
52
+ );
48
53
  }
49
54
 
50
55
  function migrationDirectory(): string {
package/src/types.ts CHANGED
@@ -3,20 +3,28 @@ type StrataCommandLoader = () => Promise<StrataCommand>;
3
3
  type StrataCommandMap = Record<string, StrataCommandLoader>;
4
4
 
5
5
  type StrataFileConfig = {
6
+ application?: string;
7
+ schedule?: string;
6
8
  preload?: string;
7
9
  server?: string;
8
10
  modulesDirectory?: string;
9
11
  commands?: string;
12
+ migrateStatus?: string;
13
+ rollback?: string;
10
14
  migrate?: string;
11
15
  fresh?: string;
12
16
  };
13
17
 
14
18
  type StrataAppConfig = {
15
19
  root: string;
20
+ application?: string;
21
+ schedule?: string;
16
22
  preload?: string;
17
23
  server?: string;
18
24
  modulesDirectory?: string;
19
25
  commandsModule?: string;
26
+ migrateStatus?: string;
27
+ rollback?: string;
20
28
  migrate?: string;
21
29
  fresh?: string;
22
30
  };