@getstrata/cli 3.0.8 → 3.1.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getstrata/cli",
3
- "version": "3.0.8",
3
+ "version": "3.1.0",
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.8",
58
- "@getstrata/core": "^3.0.8"
57
+ "@getstrata/bootstrap": "^3.1.0",
58
+ "@getstrata/core": "^3.1.0"
59
59
  },
60
60
  "publishConfig": {
61
61
  "access": "public"
@@ -1,6 +1,11 @@
1
1
  function printHelp(commandNames: string[]): void {
2
2
  const unique = [...new Set(commandNames)].sort();
3
3
  const descriptions: Record<string, string> = {
4
+ "make:model": "Model class in src/models; migrations are separate",
5
+ "make:controller": "Controller class in src/http/controllers",
6
+ "make:request": "FormRequest class in src/http/requests",
7
+ "make:policy": "Policy class in src/policies",
8
+ "make:module": "Optional domain grouping with model, controller and routes",
4
9
  dev: "HTTP development server; workers run separately",
5
10
  start: "HTTP server; workers run separately",
6
11
  "queue:work": "Poll Redis for queued jobs; requires REDIS_URL",
@@ -1,4 +1,5 @@
1
1
  import type { StrataCommandMap } from "../types.ts";
2
+ import { makeControllerCommand } from "./makeController.ts";
2
3
  import { makeFactoryCommand } from "./makeFactory.ts";
3
4
  import { makeJobCommand } from "./makeJob.ts";
4
5
  import { makeListenerCommand } from "./makeListener.ts";
@@ -20,6 +21,7 @@ import {
20
21
  } from "./utils.ts";
21
22
 
22
23
  const scaffoldCommands: StrataCommandMap = {
24
+ "make:controller": async () => makeControllerCommand,
23
25
  "make:model": async () => makeModelCommand,
24
26
  "make:view": async () => makeViewCommand,
25
27
  "make:module": async () => makeModuleCommand,
@@ -33,6 +35,7 @@ const scaffoldCommands: StrataCommandMap = {
33
35
 
34
36
  export {
35
37
  ensureDirectory,
38
+ makeControllerCommand,
36
39
  makeFactoryCommand,
37
40
  makeJobCommand,
38
41
  makeListenerCommand,
@@ -0,0 +1,32 @@
1
+ import { scaffoldArguments, writeScaffoldFile } from "./scaffoldFile";
2
+ import { toPascalCase } from "./utils";
3
+
4
+ async function makeControllerCommand(...args: string[]): Promise<void> {
5
+ const parsed = scaffoldArguments("make:controller", args);
6
+ if (!parsed) return;
7
+ const [input] = parsed;
8
+ if (!input) throw new Error("make:controller requires a controller name.");
9
+ const parts = input.split("/").map(toPascalCase);
10
+ const name = parts.at(-1) ?? "";
11
+ const className = name.endsWith("Controller") ? name : `${name}Controller`;
12
+ const content = `import { jsonResponse } from "@getstrata/core/http/response";
13
+
14
+ class ${className} {
15
+ index(_request: Request): Response {
16
+ return jsonResponse({ message: "${className}" });
17
+ }
18
+ }
19
+
20
+ export { ${className} };
21
+ `;
22
+ const path = await writeScaffoldFile(
23
+ ["src", "http", "controllers", ...parts.slice(0, -1), `${className}.ts`],
24
+ content,
25
+ "Controller",
26
+ );
27
+ console.log(`Created controller: ${path}`);
28
+ console.log("Register its methods in src/routes/web.ts or src/routes/api.ts.");
29
+ console.log("Resolve request-scoped dependencies inside the route callback.");
30
+ }
31
+
32
+ export { makeControllerCommand };
@@ -21,9 +21,14 @@ async function makeFactoryCommand(...args: string[]): Promise<void> {
21
21
  `${classParts.at(-1)}Factory.ts`,
22
22
  );
23
23
  if (await Bun.file(filePath).exists()) throw new Error(`Factory already exists: ${filePath}`);
24
- const standalone = join(process.cwd(), "src", "models", ...classParts) + ".ts";
24
+ const standalone = `${join(process.cwd(), "src", "models", ...classParts)}.ts`;
25
25
  const module = await moduleDirectory(toKebabCase(name));
26
- const candidates = [standalone, join(module, "types.ts"), join(module, "model.ts")];
26
+ const candidates = [
27
+ standalone,
28
+ join(module, "models", `${modelName}.ts`),
29
+ join(module, "types.ts"),
30
+ join(module, "model.ts"),
31
+ ];
27
32
  let recordPath: string | undefined;
28
33
  for (const candidate of candidates) {
29
34
  if (await Bun.file(candidate).exists()) {
@@ -38,13 +43,20 @@ async function makeFactoryCommand(...args: string[]): Promise<void> {
38
43
  let recordImport = relative(dirname(filePath), recordPath).split(sep).join("/");
39
44
  if (!recordImport.startsWith(".")) recordImport = `./${recordImport}`;
40
45
  const content = `import { createFactory, type FactoryPersist } from "@getstrata/core/database/factory";
41
- import type { ${modelName}Record } from "${recordImport}";
46
+ ${
47
+ candidates.indexOf(recordPath) < 2
48
+ ? `import type { ModelAttributes } from "@getstrata/core/database/model";
49
+ import type { ${modelName} } from "${recordImport}";
50
+
51
+ type ${modelName}Record = ModelAttributes<${modelName}>;`
52
+ : `import type { ${modelName}Record } from "${recordImport}";`
53
+ }
42
54
 
43
55
  function create${modelName}Factory(definition: () => ${modelName}Record, persist?: FactoryPersist<${modelName}Record>) {
44
56
  return createFactory({ definition, persist });
45
57
  }
46
58
 
47
- // Supply persistence from the current invocation, e.g. async values => (await session.model(${modelName}Definition).create(values)).toObject().
59
+ // Supply persistence from the current invocation, e.g. async values => (await session.model(${modelName}).create(values)).toObject().
48
60
  export { create${modelName}Factory };
49
61
  `;
50
62
 
@@ -15,7 +15,7 @@ async function makeModelCommand(...args: string[]): Promise<void> {
15
15
  console.log(
16
16
  "Usage: strata make:model <Name|Group/Name> [--table=name] [--primary-key=id] [--key-type=number|string]",
17
17
  );
18
- console.log("Creates an id-only declarative model in src/models with an automatic repository.");
18
+ console.log("Creates a model class in src/models; add fields and $fillable values as needed.");
19
19
  console.log("No schema changes: run strata make:migration <name> separately.");
20
20
  return;
21
21
  }
@@ -44,23 +44,20 @@ 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 { createModel, type Model } from "@getstrata/core/database/model";
48
- import { defineTable } from "@getstrata/core/database/table";
47
+ const content = `import { defineModel, field } from "@getstrata/core/database/model";
49
48
 
50
- interface ${className}Record { ${key}: ${keyType}; }
51
- const table = defineTable<${className}Record, "${key}">({
52
- name: "${table}", primaryKey: "${key}", columns: ["${key}"],
53
- });
54
- type ${className} = Model<${className}Record, "${key}">;
55
- const ${className}Definition = createModel({
56
- name: "${className}", table,
57
- attributes: { fillable: [${fillable}], timestamps: false },
58
- });
59
- const ${className}Repository = ${className}Definition.repository;
60
- // Register this definition in createDatabaseBindings({ models: [...] }).
61
- // Use selectedSession.model(${className}Definition) inside an application invocation.
62
- export type { ${className}Record, ${className} };
63
- export { ${className}Definition, ${className}Repository };
49
+ class ${className} extends defineModel({
50
+ table: "${table}",
51
+ primaryKey: "${key}",
52
+ fields: {
53
+ ${key}: field.${keyType}(),
54
+ },
55
+ }) {
56
+ static $fillable = [${fillable}] as const;
57
+ static $timestamps = false;
58
+ }
59
+
60
+ export { ${className} };
64
61
  `;
65
62
  const path = await writeScaffoldFile(
66
63
  ["src", "models", ...classParts.slice(0, -1), `${classParts.at(-1)}.ts`],
@@ -68,7 +65,7 @@ export { ${className}Definition, ${className}Repository };
68
65
  "Model",
69
66
  );
70
67
  console.log(`Created model: ${path}`);
71
- console.log("Register the exported definition in the application database bindings.");
68
+ console.log("Register the exported class in createDatabaseBindings({ models: [...] }).");
72
69
  console.log(
73
70
  `Next: strata make:migration create_${table}; define schema explicitly before strata migrate.`,
74
71
  );
@@ -89,7 +89,7 @@ async function makeModuleCommand(...args: string[]): Promise<void> {
89
89
  console.log(`Module will be auto-discovered from the app modules directory (${moduleSlug}/)`);
90
90
  console.log(`Next: strata make:migration create_${moduleSlug} && strata migrate`);
91
91
 
92
- console.log("Register the generated model and its repository in src/models/register.ts.");
92
+ console.log("Register the generated model class in createDatabaseBindings({ models: [...] }).");
93
93
  }
94
94
 
95
95
  export { makeModuleCommand };
@@ -1,68 +1,48 @@
1
- import { access } from "node:fs/promises";
2
- import { join, relative, sep } from "node:path";
3
1
  import { scaffoldArguments, writeScaffoldFile } from "./scaffoldFile";
4
- import { moduleDirectory, toKebabCase, toPascalCase } from "./utils";
2
+ import { toKebabCase, toPascalCase } from "./utils";
5
3
 
6
4
  async function makePolicyCommand(...args: string[]): Promise<void> {
7
5
  const parsed = scaffoldArguments("make:policy", args);
8
6
  if (!parsed) return;
9
- const [moduleName] = parsed;
10
- if (!moduleName) {
11
- throw new Error("make:policy requires a module name.");
12
- }
13
-
14
- const moduleSlug = toKebabCase(moduleName);
15
- const resourceName = toPascalCase(moduleName);
16
- const directory = await moduleDirectory(moduleSlug);
17
- const policyPath = join(directory, "policy.ts");
18
-
19
- try {
20
- await access(directory);
21
- } catch {
22
- throw new Error(`Module not found: ${directory}`);
23
- }
24
-
25
- try {
26
- await access(policyPath);
27
- throw new Error(`Policy already exists: ${policyPath}`);
28
- } catch (error) {
29
- if (error instanceof Error && error.message.startsWith("Policy already exists:")) {
30
- throw error;
31
- }
32
- }
33
-
34
- const recordType = `${resourceName}Record`;
35
- const policyClass = `${resourceName}Policy`;
36
-
37
- const content = `import { Policy } from "@getstrata/core/auth/policy";
38
- import type { ${recordType} } from "./types";
39
-
40
- class ${policyClass} extends Policy {
41
- override view(_user: unknown, _resource: ${recordType}): boolean {
7
+ const [input] = parsed;
8
+ if (!input) throw new Error("make:policy requires a policy name.");
9
+ const parts = input.split("/").map(toPascalCase);
10
+ const name = parts.at(-1) ?? "";
11
+ const className = name.endsWith("Policy") ? name : `${name}Policy`;
12
+ if (className === "Policy")
13
+ throw new Error("make:policy requires a resource policy name, such as NotePolicy.");
14
+ const resource = toKebabCase(name.replace(/Policy$/, ""));
15
+ const content = `import type { AuthUser } from "@getstrata/core/auth/authContext";
16
+ import { Policy } from "@getstrata/core/auth/policy";
17
+
18
+ class ${className} extends Policy {
19
+ override view(_user: AuthUser | null, _resource: unknown): boolean {
42
20
  return true;
43
21
  }
44
22
 
45
- override create(_user: unknown): boolean {
46
- return true;
23
+ override create(_user: AuthUser | null): boolean {
24
+ return false;
47
25
  }
48
26
 
49
- override update(_user: unknown, _resource: ${recordType}): boolean {
50
- return true;
27
+ override update(_user: AuthUser | null, _resource: unknown): boolean {
28
+ return false;
51
29
  }
52
30
 
53
- override delete(_user: unknown, _resource: ${recordType}): boolean {
54
- return true;
31
+ override delete(_user: AuthUser | null, _resource: unknown): boolean {
32
+ return false;
55
33
  }
56
34
  }
57
35
 
58
- export default ${policyClass};
36
+ export default ${className};
59
37
  `;
60
-
61
- await writeScaffoldFile(relative(process.cwd(), policyPath).split(sep), content, "Policy");
62
-
63
- console.log(`Created policy in: ${policyPath}`);
38
+ const path = await writeScaffoldFile(
39
+ ["src", "policies", ...parts.slice(0, -1), `${className}.ts`],
40
+ content,
41
+ "Policy",
42
+ );
43
+ console.log(`Created policy: ${path}`);
64
44
  console.log(
65
- `Register it in your module index: policies: { "${moduleSlug}": new ${policyClass}() }.`,
45
+ `Register the policy in your application policy map: "${resource}": new ${className}().`,
66
46
  );
67
47
  }
68
48
 
@@ -1,72 +1,42 @@
1
- import { join, relative, sep } from "node:path";
2
1
  import { scaffoldArguments, writeScaffoldFile } from "./scaffoldFile";
3
- import { moduleDirectory, toKebabCase, toPascalCase } from "./utils";
2
+ import { toPascalCase } from "./utils";
4
3
 
5
4
  async function makeRequestCommand(...args: string[]): Promise<void> {
6
5
  const parsed = scaffoldArguments("make:request", args);
7
6
  if (!parsed) return;
8
- const [moduleName] = parsed;
9
- if (!moduleName) {
10
- throw new Error("make:request requires a module name.");
11
- }
12
-
13
- const moduleSlug = toKebabCase(moduleName);
14
- const moduleNamePascal = toPascalCase(moduleName);
15
- const filePath = join(await moduleDirectory(moduleSlug), "requests.ts");
16
-
17
- const exists = await Bun.file(filePath).exists();
18
- if (exists) {
19
- throw new Error(`Request file already exists: ${filePath}`);
20
- }
21
-
22
- const content = `import { FormRequest } from "@getstrata/core/http";
23
- import { parsePositiveIntParam } from "@getstrata/core/http/validation";
24
- import {
25
- maxLength,
26
- minLength,
27
- required,
28
- stringRule,
29
- validateObject,
30
- } from "@getstrata/core/validation/rules";
31
-
32
- type ${moduleNamePascal}IdParams = { id: string };
33
-
34
- interface Create${moduleNamePascal}BodyDto {
7
+ const [input] = parsed;
8
+ if (!input) throw new Error("make:request requires a request name.");
9
+ const parts = input.split("/").map(toPascalCase);
10
+ const name = parts.at(-1) ?? "";
11
+ const className = name.endsWith("Request") ? name : `${name}Request`;
12
+ if (className === "FormRequest")
13
+ throw new Error("make:request requires a specific request name, such as StoreNoteRequest.");
14
+ const content = `import { FormRequest } from "@getstrata/core/http/formRequest";
15
+ import { maxLength, minLength, required, stringRule, validateObject } from "@getstrata/core/validation/rules";
16
+
17
+ interface ${className}Data {
35
18
  name: string;
36
19
  }
37
20
 
38
- class Create${moduleNamePascal}Request extends FormRequest<Create${moduleNamePascal}BodyDto> {
39
- protected parse(payload: unknown): Create${moduleNamePascal}BodyDto {
40
- const validated = validateObject(payload, {
21
+ class ${className} extends FormRequest<${className}Data> {
22
+ protected parse(payload: unknown): ${className}Data {
23
+ const data = validateObject(payload, {
41
24
  name: [required(), stringRule(), minLength(1), maxLength(120)],
42
25
  });
43
-
44
- return {
45
- name: validated.name as string,
46
- };
26
+ return { name: data.name as string };
47
27
  }
48
28
  }
49
29
 
50
- const create${moduleNamePascal}Request = new Create${moduleNamePascal}Request();
51
-
52
- function parse${moduleNamePascal}IdParams(params: ${moduleNamePascal}IdParams): { id: number } {
53
- return {
54
- id: parsePositiveIntParam(params.id, "${moduleSlug} id"),
55
- };
56
- }
57
-
58
- async function parseCreate${moduleNamePascal}Body(
59
- request: Request,
60
- ): Promise<Create${moduleNamePascal}BodyDto> {
61
- return await create${moduleNamePascal}Request.validate(request);
62
- }
63
-
64
- export { parseCreate${moduleNamePascal}Body, parse${moduleNamePascal}IdParams };
65
- export type { Create${moduleNamePascal}BodyDto, ${moduleNamePascal}IdParams };
30
+ export default ${className};
31
+ export type { ${className}Data };
66
32
  `;
67
-
68
- await writeScaffoldFile(relative(process.cwd(), filePath).split(sep), content, "Request");
69
- console.log(`Created request helpers: ${filePath}`);
33
+ const path = await writeScaffoldFile(
34
+ ["src", "http", "requests", ...parts.slice(0, -1), `${className}.ts`],
35
+ content,
36
+ "Request",
37
+ );
38
+ console.log(`Created request: ${path}`);
39
+ console.log(`Validate in a controller with await new ${className}().validate(request).`);
70
40
  }
71
41
 
72
42
  export { makeRequestCommand };