@getstrata/cli 2.2.59 → 3.0.4

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.
@@ -1,85 +1,86 @@
1
- import {
2
- createAppQueue,
3
- createFailedJobService,
4
- resolveQueueConfig,
5
- } from "@getstrata/core/queue/createAppQueue";
6
- import { jobRegistry } from "@getstrata/core/queue/jobRegistry";
7
- import { resolveApplicationQueue } from "@getstrata/core/runtime/applicationRegistry";
8
- import { withCommandCleanup } from "./commandCleanup.ts";
1
+ import type { Application } from "@getstrata/core/contracts/application";
2
+ import type { Queue } from "@getstrata/core/queue";
3
+ import type { QueueInvocation, QueueServices } from "@getstrata/core/queue/createAppQueue";
4
+ import type { JobRegistry } from "@getstrata/core/queue/jobRegistry";
9
5
  import type { StrataCommand } from "./types.ts";
10
6
 
11
- type QueueFailedBoot = () => unknown | Promise<unknown>;
12
-
13
- async function queueFailedCommand(boot?: QueueFailedBoot): Promise<void> {
14
- await boot?.();
15
- const failedJobs = createFailedJobService();
16
- const jobs = await failedJobs.listRecent();
17
-
18
- if (jobs.length === 0) {
19
- console.log("No failed jobs.");
20
- return;
7
+ interface QueueCommandApplication {
8
+ readonly application: Application;
9
+ readonly invoke: QueueInvocation;
10
+ readonly queueServices: QueueServices;
11
+ readonly queue: Queue;
12
+ readonly registry: JobRegistry;
13
+ readonly worker?: { start(): Promise<void> };
14
+ }
15
+ type QueueFailedBoot = () => QueueCommandApplication | Promise<QueueCommandApplication>;
16
+ async function withQueueApplication<T>(
17
+ boot: QueueFailedBoot,
18
+ work: (app: QueueCommandApplication) => Promise<T>,
19
+ ): Promise<T> {
20
+ const app = await boot();
21
+ let value: T | undefined;
22
+ const errors: unknown[] = [];
23
+ try {
24
+ value = await work(app);
25
+ } catch (error) {
26
+ errors.push(error);
21
27
  }
22
-
23
- for (const job of jobs) {
24
- console.log(`#${job.id} ${job.job_name} failed at ${job.failed_at.toISOString()}`);
28
+ try {
29
+ const result = await app.application.stop();
30
+ if (!result.successful)
31
+ errors.push(new Error("Queue application shutdown did not complete cleanly."));
32
+ } catch (error) {
33
+ errors.push(error);
25
34
  }
35
+ if (errors.length === 1) throw errors[0];
36
+ if (errors.length) throw new AggregateError(errors, "Queue command or shutdown failed.");
37
+ return value as T;
26
38
  }
27
-
28
- async function queueRetryCommand(id?: string, boot?: QueueFailedBoot): Promise<void> {
29
- if (!id) {
30
- throw new Error("queue:retry requires a failed job id.");
31
- }
32
-
39
+ async function queueFailedCommand(boot: QueueFailedBoot): Promise<void> {
40
+ await withQueueApplication(boot, async ({ queueServices }) => {
41
+ const jobs = await queueServices.listRecent();
42
+ if (!jobs.length) console.log("No failed jobs.");
43
+ for (const job of jobs)
44
+ console.log(`#${job.id} ${job.job_name} failed at ${job.failed_at.toISOString()}`);
45
+ });
46
+ }
47
+ async function queueRetryCommand(id: string | undefined, boot: QueueFailedBoot): Promise<void> {
33
48
  const jobId = Number(id);
34
- if (!Number.isSafeInteger(jobId) || jobId <= 0)
49
+ if (!id || !Number.isSafeInteger(jobId) || jobId <= 0)
35
50
  throw new Error("queue:retry requires a positive integer failed job id.");
36
- await boot?.();
37
- const failedJobs = createFailedJobService();
38
- // App boot owns its configured queue; standalone CLI dispatch owns and closes its queue.
39
- const queue = boot
40
- ? resolveApplicationQueue()
41
- : createAppQueue(resolveQueueConfig().driver, process.env.REDIS_URL, failedJobs);
42
- try {
43
- await failedJobs.retry(jobId, async (failedJob) => {
44
- const job = jobRegistry.create(failedJob.job_name);
51
+ await withQueueApplication(boot, async ({ queueServices, queue, registry }) => {
52
+ await queueServices.retry(jobId, async (failedJob) => {
53
+ const job = registry.create(failedJob.job_name);
45
54
  if (!job) throw new Error(`Unknown job "${failedJob.job_name}".`);
46
- jobRegistry.track(failedJob.job_name, job);
55
+ registry.track(failedJob.job_name, job);
56
+ const options = failedJob.handoff == null ? undefined : { handoff: failedJob.handoff };
47
57
  if (failedJob.job_id !== null && failedJob.job_id !== undefined) {
48
58
  if (!queue.replay)
49
59
  throw new Error("Configured queue cannot preserve the failed-job identity");
50
- await queue.replay(job, failedJob.payload, failedJob.job_id);
51
- } else await queue.dispatch(job, failedJob.payload);
60
+ await queue.replay(job, failedJob.payload, failedJob.job_id, options);
61
+ } else await queue.dispatch(job, failedJob.payload, options);
52
62
  });
53
63
  console.log(`Enqueued failed job #${jobId}.`);
54
- } finally {
55
- if (!boot) await queue.close?.();
56
- }
64
+ });
57
65
  }
58
-
59
- async function queueFlushFailedCommand(boot?: QueueFailedBoot): Promise<void> {
60
- await boot?.();
61
- const deleted = await createFailedJobService().flush();
62
- console.log(`Removed ${deleted} failed job(s).`);
66
+ async function queueFlushFailedCommand(boot: QueueFailedBoot): Promise<void> {
67
+ await withQueueApplication(boot, async ({ queueServices }) => {
68
+ console.log(`Removed ${await queueServices.flush()} failed job(s).`);
69
+ });
63
70
  }
64
-
65
- function createQueueFailedCommands(
66
- boot?: QueueFailedBoot,
67
- close?: () => void | Promise<void>,
68
- ): {
71
+ function createQueueFailedCommands(boot: QueueFailedBoot): {
69
72
  queueFailedCommand: StrataCommand;
70
73
  queueRetryCommand: StrataCommand;
71
74
  queueFlushFailedCommand: StrataCommand;
72
75
  } {
73
76
  return {
74
- queueFailedCommand: async () => withCommandCleanup(() => queueFailedCommand(boot), close),
75
- queueRetryCommand: async (id?: string) =>
76
- withCommandCleanup(() => queueRetryCommand(id, boot), close),
77
- queueFlushFailedCommand: async () =>
78
- withCommandCleanup(() => queueFlushFailedCommand(boot), close),
77
+ queueFailedCommand: () => queueFailedCommand(boot),
78
+ queueRetryCommand: (id?: string) => queueRetryCommand(id, boot),
79
+ queueFlushFailedCommand: () => queueFlushFailedCommand(boot),
79
80
  };
80
81
  }
81
82
 
82
- export type { QueueFailedBoot };
83
+ export type { QueueCommandApplication, QueueFailedBoot };
83
84
  export {
84
85
  createQueueFailedCommands,
85
86
  queueFailedCommand,
@@ -2,25 +2,18 @@ import {
2
2
  installGracefulShutdownSignals,
3
3
  LifecycleCoordinator,
4
4
  } from "@getstrata/core/lifecycle/gracefulShutdown";
5
- import { createFailedJobService, createQueueWorker } from "@getstrata/core/queue/createAppQueue";
6
5
 
7
- type QueueWorkerBoot = () => unknown | Promise<unknown>;
8
- type QueueWorkerClose = () => unknown | Promise<unknown>;
6
+ import type { QueueCommandApplication } from "./queueFailed";
7
+
8
+ type QueueWorkerBoot = () => QueueCommandApplication | Promise<QueueCommandApplication>;
9
9
 
10
10
  async function runQueueWorkerCommand(options: {
11
11
  boot: QueueWorkerBoot;
12
- close?: QueueWorkerClose;
13
- flush?: QueueWorkerClose;
14
- drain?: QueueWorkerClose;
15
12
  lifecycle?: LifecycleCoordinator;
16
- failedJobs?: ReturnType<typeof createFailedJobService>;
17
13
  }): Promise<void> {
18
- const redisUrl = process.env.REDIS_URL;
19
- if (!redisUrl) throw new Error("queue:work requires REDIS_URL to be set.");
20
14
  const lifecycle = options.lifecycle ?? new LifecycleCoordinator();
21
15
  if (lifecycle.isShuttingDown) throw new Error("Cannot start a worker during shutdown.");
22
- let worker: ReturnType<typeof createQueueWorker> | undefined;
23
- let running: Promise<void> | undefined;
16
+ let application: QueueCommandApplication | undefined;
24
17
  let booting: Promise<unknown> | undefined;
25
18
  let stopping = false;
26
19
  const name = `queue:${crypto.randomUUID()}`;
@@ -28,7 +21,10 @@ async function runQueueWorkerCommand(options: {
28
21
  `${name}:stop`,
29
22
  () => {
30
23
  stopping = true;
31
- worker?.requestStop();
24
+ return application?.application.stop().then((result) => {
25
+ if (!result.successful)
26
+ throw new Error("Queue application shutdown did not complete cleanly.");
27
+ });
32
28
  },
33
29
  "stop",
34
30
  );
@@ -37,51 +33,39 @@ async function runQueueWorkerCommand(options: {
37
33
  async () => {
38
34
  // Completion, including failed startup/run, means no admitted worker remains.
39
35
  await booting?.catch(() => {});
40
- await running?.catch(() => {});
41
- if (running) console.log("[queue:work] Polling stopped.");
42
- await options.drain?.();
43
36
  },
44
37
  "drain",
45
38
  );
46
39
  lifecycle.register(
47
40
  `${name}:flush`,
48
41
  async () => {
49
- await options.flush?.();
42
+ // Canonical application owns provider flushing.
50
43
  },
51
44
  "flush",
52
45
  );
53
46
  lifecycle.register(
54
47
  `${name}:close`,
55
48
  async () => {
56
- try {
57
- await worker?.close?.();
58
- } finally {
59
- await options.close?.();
60
- }
49
+ const result = await application?.application.stop();
50
+ if (result && !result.successful)
51
+ throw new Error("Queue application shutdown did not complete cleanly.");
61
52
  },
62
53
  "close",
63
54
  );
64
- lifecycle.register(
65
- `${name}:force`,
66
- () => {
67
- worker?.requestStop();
68
- worker?.close?.();
69
- },
70
- "force",
71
- );
72
55
  const uninstall = installGracefulShutdownSignals(undefined, lifecycle);
73
56
  let failure: unknown;
74
57
  let failed = false;
75
58
  try {
76
59
  booting = (async () => {
77
- await options.boot();
60
+ application = await options.boot();
78
61
  })();
79
62
  await booting;
80
63
  if (!stopping && !lifecycle.isShuttingDown) {
81
- worker = createQueueWorker(redisUrl, options.failedJobs ?? createFailedJobService());
64
+ if (!application) throw new Error("Queue boot did not return its application.");
65
+ if (!application.worker)
66
+ throw new Error("Queue boot must configure an application-owned worker transport.");
82
67
  console.log("[queue:work] Starting Redis queue polling; idle until jobs are available.");
83
- running = worker.run();
84
- await running;
68
+ await application.worker.start();
85
69
  }
86
70
  } catch (error) {
87
71
  failed = true;
@@ -97,5 +81,5 @@ async function runQueueWorkerCommand(options: {
97
81
  if (failed) throw failure;
98
82
  }
99
83
 
100
- export type { QueueWorkerBoot, QueueWorkerClose };
84
+ export type { QueueWorkerBoot };
101
85
  export { runQueueWorkerCommand };
@@ -1,5 +1,5 @@
1
1
  import { join } from "node:path";
2
- import { ensureDirectory, moduleDirectory, toCamelCase, toKebabCase, toPascalCase } from "./utils";
2
+ import { ensureDirectory, moduleDirectory, toKebabCase, toPascalCase } from "./utils";
3
3
 
4
4
  async function makeFactoryCommand(name?: string): Promise<void> {
5
5
  if (!name) {
@@ -8,7 +8,6 @@ async function makeFactoryCommand(name?: string): Promise<void> {
8
8
 
9
9
  const moduleSlug = toKebabCase(name);
10
10
  const modelName = toPascalCase(name);
11
- const moduleIdentifier = toCamelCase(name);
12
11
  const directory = moduleDirectory(moduleSlug);
13
12
  const filePath = join(directory, "factory.ts");
14
13
 
@@ -19,26 +18,29 @@ async function makeFactoryCommand(name?: string): Promise<void> {
19
18
  throw new Error(`Factory already exists: ${filePath}`);
20
19
  }
21
20
 
22
- const content = `import { Factory } from "@getstrata/core/database/factory";
21
+ const content = `import { defineFactory, Factory, type FactoryPersist } from "@getstrata/core/database/factory";
23
22
  import type { ${modelName}Record } from "./types";
24
23
 
25
- class ${modelName}Factory extends Factory<${modelName}Record> {
26
- protected definition(): ${modelName}Record {
27
- const now = new Date();
28
-
29
- return {
30
- id: 0,
31
- } satisfies Partial<${modelName}Record> as ${modelName}Record;
32
- }
33
-
34
- protected persist(values: Partial<${modelName}Record>): Promise<${modelName}Record> {
35
- throw new Error("${modelName}Factory.persist() is not implemented.");
36
- }
24
+ export interface ${modelName}FactoryDependencies {
25
+ definition: () => ${modelName}Record;
26
+ persist?: FactoryPersist<${modelName}Record>;
37
27
  }
38
28
 
39
- const ${moduleIdentifier}Factory = new ${modelName}Factory();
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);
41
+ }
40
42
 
41
- export { ${modelName}Factory, ${moduleIdentifier}Factory };
43
+ export { ${modelName}Factory, create${modelName}Factory };
42
44
  `;
43
45
 
44
46
  await Bun.write(filePath, content);
@@ -8,7 +8,7 @@ async function makeListenerCommand(name?: string, eventName?: string): Promise<v
8
8
  }
9
9
 
10
10
  const listenerSlug = toKebabCase(name);
11
- const registerFunction = `register${toPascalCase(name)}Listener`;
11
+ const listenerToken = `${toPascalCase(name)}Listener`;
12
12
  const directory = join(process.cwd(), "src", "listeners");
13
13
  const listenerPath = join(directory, `${listenerSlug}.ts`);
14
14
  const resolvedEventName = eventName ?? `${toCamelCase(name)}.created`;
@@ -24,15 +24,37 @@ async function makeListenerCommand(name?: string, eventName?: string): Promise<v
24
24
  }
25
25
  }
26
26
 
27
- const content = `import { eventBus } from "@getstrata/core/events";
27
+ const [table, action, ...extra] = resolvedEventName.split(".");
28
+ const modelEvent =
29
+ extra.length === 0 &&
30
+ ["created", "updated", "deleted", "restored", "force-deleted"].includes(action ?? "");
31
+ const modelName = toPascalCase((table ?? name).replace(/s$/, ""));
32
+ 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";
28
38
 
29
- function ${registerFunction}(): void {
30
- eventBus.listen("${resolvedEventName}", async (payload) => {
31
- void payload;
32
- });
33
- }
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}}])]),
43
+ });
44
+ export default declarations;
45
+ `
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";
34
50
 
35
- export default ${registerFunction};
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;
36
58
  `;
37
59
 
38
60
  await Bun.write(listenerPath, content);
@@ -31,19 +31,20 @@ async function makeMigrationCommand(name?: string): Promise<void> {
31
31
  }
32
32
 
33
33
  const content = `import type { Migration } from "@getstrata/core/database/migrations/types";
34
- import { Schema, resolveDatabaseDriver } from "@getstrata/core/database/schema";
34
+ import { currentSqlDialect } from "@getstrata/core/database/dialect";
35
+ import { Schema } from "@getstrata/core/database/schema";
35
36
 
36
37
  const migration: Migration = {
37
38
  name: "${fileBaseName}",
38
39
  async up(db) {
39
- await Schema.run(db, resolveDatabaseDriver(), (schema) => {
40
+ await Schema.run(db, currentSqlDialect().driver, (schema) => {
40
41
  // Define schema.create(...) or schema.table(...) here.
41
42
  // Keep data transformations and unsupported engine features in db.unsafe(...).
42
43
  void schema;
43
44
  });
44
45
  },
45
46
  async down(db) {
46
- await Schema.run(db, resolveDatabaseDriver(), (schema) => {
47
+ await Schema.run(db, currentSqlDialect().driver, (schema) => {
47
48
  // Reverse the schema changes; guard against losing business history.
48
49
  void schema;
49
50
  });
@@ -44,28 +44,29 @@ 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 { defineModel } from "@getstrata/core/database/model";
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";
48
50
  import { defineTable } from "@getstrata/core/database/table";
49
51
 
50
- interface ${className}Record {
51
- ${key}: ${keyType};
52
- }
53
-
52
+ interface ${className}Record { ${key}: ${keyType}; }
54
53
  const table = defineTable<${className}Record, "${key}">({
55
- name: "${table}",
56
- primaryKey: "${key}",
57
- columns: ["${key}"],
54
+ name: "${table}", primaryKey: "${key}", columns: ["${key}"],
58
55
  });
59
-
60
- class ${className} extends defineModel(table) {
61
- // Add writable fields to the record, table columns and this explicit allowlist.
62
- static override $fillable = [${fillable}] as const;
63
- // Enable only after adding the corresponding timestamp columns to your schema.
64
- static override $timestamps = false;
65
- }
66
-
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,
63
+ attributes: { fillable: [${fillable}], timestamps: false },
64
+ construct: (state, binding) => new ${className}(state, binding),
65
+ });
66
+ // Register this definition in createDatabaseBindings({ models: [...] }).
67
+ // Use selectedSession.model(${className}Definition) inside an application invocation.
67
68
  export type { ${className}Record };
68
- export { ${className} };
69
+ export { ${className}, ${className}Definition, repository as ${className}Repository };
69
70
  `;
70
71
  const path = await writeScaffoldFile(
71
72
  ["src", "models", ...classParts.slice(0, -1), `${classParts.at(-1)}.ts`],
@@ -73,9 +74,7 @@ export { ${className} };
73
74
  "Model",
74
75
  );
75
76
  console.log(`Created model: ${path}`);
76
- console.log(
77
- "src/models discovery supplies its default repository; no custom repository is required.",
78
- );
77
+ console.log("Register the exported definition in the application database bindings.");
79
78
  console.log(
80
79
  `Next: strata make:migration create_${table}; define schema explicitly before strata migrate.`,
81
80
  );
@@ -78,22 +78,7 @@ async function makeModuleCommand(...args: string[]): Promise<void> {
78
78
  console.log(`Module will be auto-discovered from the app modules directory (${moduleSlug}/)`);
79
79
  console.log(`Next: strata make:migration create_${moduleSlug} && strata migrate`);
80
80
 
81
- const registerPath = join(process.cwd(), "src", "models", "register.ts");
82
- try {
83
- await access(registerPath);
84
- const existing = await Bun.file(registerPath).text();
85
- if (!existing.includes(`registerModelClass("${moduleName}"`)) {
86
- const snippet = `
87
- // ${moduleName}: after you add a Model class, register string aliases here:
88
- // import { ${moduleName} } from "../modules/${moduleSlug}/model.ts";
89
- // registerModelClass("${moduleName}", ${moduleName});
90
- `;
91
- await Bun.write(registerPath, `${existing.trimEnd()}\n${snippet}`);
92
- console.log(`Appended a registerModelClass hint to src/models/register.ts`);
93
- }
94
- } catch {
95
- // Generated apps ship register.ts. Older apps can add it from DATABASE.md.
96
- }
81
+ console.log("Register the generated repository definition in application database bindings.");
97
82
  }
98
83
 
99
84
  export { makeModuleCommand };