@facilis.dev/nitro 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (267) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +18 -2
  3. package/dist/config.d.ts +30 -0
  4. package/dist/config.js +112 -0
  5. package/dist/constants.d.ts +24 -0
  6. package/dist/constants.js +24 -0
  7. package/dist/facade.d.ts +37 -0
  8. package/dist/facade.js +121 -0
  9. package/dist/index.d.ts +17 -0
  10. package/dist/index.js +14 -0
  11. package/dist/middleware/context.d.ts +5 -0
  12. package/dist/middleware/context.js +86 -0
  13. package/dist/middleware/cors.d.ts +10 -0
  14. package/dist/middleware/cors.js +34 -0
  15. package/dist/middleware/session.d.ts +9 -0
  16. package/dist/middleware/session.js +18 -0
  17. package/dist/module.d.ts +7 -0
  18. package/dist/module.js +234 -0
  19. package/dist/rolldown-parser.d.ts +3 -0
  20. package/dist/rolldown-parser.js +66 -0
  21. package/dist/route-metadata.d.ts +22 -0
  22. package/dist/route-metadata.js +161 -0
  23. package/dist/routes/dev-query.post.d.ts +10 -0
  24. package/dist/routes/dev-query.post.js +49 -0
  25. package/dist/routes/dev-schema.get.d.ts +9 -0
  26. package/dist/routes/dev-schema.get.js +34 -0
  27. package/dist/routes/dev-view.post.d.ts +11 -0
  28. package/dist/routes/dev-view.post.js +61 -0
  29. package/dist/routes/health.get.d.ts +8 -0
  30. package/dist/routes/health.get.js +18 -0
  31. package/dist/routes/manifest-revision.get.d.ts +8 -0
  32. package/dist/routes/manifest-revision.get.js +26 -0
  33. package/dist/routes/manifest.get.d.ts +8 -0
  34. package/dist/routes/manifest.get.js +68 -0
  35. package/dist/routes/openapi.get.d.ts +8 -0
  36. package/dist/routes/openapi.get.js +29 -0
  37. package/dist/routes/sso.d.ts +2 -0
  38. package/dist/routes/sso.js +216 -0
  39. package/dist/routes/token.post.d.ts +10 -0
  40. package/dist/routes/token.post.js +75 -0
  41. package/dist/runtime/boot-runtimes.d.ts +21 -0
  42. package/dist/runtime/boot-runtimes.js +38 -0
  43. package/dist/runtime/bootstrap.d.ts +47 -0
  44. package/dist/runtime/bootstrap.js +214 -0
  45. package/dist/runtime/config.d.ts +27 -0
  46. package/dist/runtime/config.js +44 -0
  47. package/dist/runtime/cors-policy.d.ts +16 -0
  48. package/dist/runtime/cors-policy.js +88 -0
  49. package/dist/runtime/db-bootstrap.d.ts +9 -0
  50. package/dist/runtime/db-bootstrap.js +87 -0
  51. package/dist/runtime/db-target.d.ts +21 -0
  52. package/dist/runtime/db-target.js +52 -0
  53. package/dist/runtime/dev-db-persistence.d.ts +39 -0
  54. package/dist/runtime/dev-db-persistence.js +124 -0
  55. package/dist/runtime/dev-query.d.ts +38 -0
  56. package/dist/runtime/dev-query.js +87 -0
  57. package/dist/runtime/env.d.ts +9 -0
  58. package/dist/runtime/env.js +14 -0
  59. package/dist/runtime/http-guard.d.ts +16 -0
  60. package/dist/runtime/http-guard.js +42 -0
  61. package/dist/runtime/http.d.ts +11 -0
  62. package/dist/runtime/http.js +18 -0
  63. package/dist/runtime/jobs/boot.d.ts +20 -0
  64. package/dist/runtime/jobs/boot.js +77 -0
  65. package/dist/runtime/jobs/contracts.d.ts +161 -0
  66. package/dist/runtime/jobs/contracts.js +1 -0
  67. package/dist/runtime/jobs/db-store.d.ts +21 -0
  68. package/dist/runtime/jobs/db-store.js +210 -0
  69. package/dist/runtime/jobs/definitions.d.ts +14 -0
  70. package/dist/runtime/jobs/definitions.js +31 -0
  71. package/dist/runtime/jobs/engine-support.d.ts +22 -0
  72. package/dist/runtime/jobs/engine-support.js +32 -0
  73. package/dist/runtime/jobs/engine.d.ts +6 -0
  74. package/dist/runtime/jobs/engine.js +261 -0
  75. package/dist/runtime/jobs/executor.d.ts +11 -0
  76. package/dist/runtime/jobs/executor.js +27 -0
  77. package/dist/runtime/jobs/memory-store.d.ts +7 -0
  78. package/dist/runtime/jobs/memory-store.js +183 -0
  79. package/dist/runtime/jobs/row-mapping.d.ts +28 -0
  80. package/dist/runtime/jobs/row-mapping.js +61 -0
  81. package/dist/runtime/jobs/runtime.d.ts +24 -0
  82. package/dist/runtime/jobs/runtime.js +86 -0
  83. package/dist/runtime/logging/audit-chain.d.ts +54 -0
  84. package/dist/runtime/logging/audit-chain.js +102 -0
  85. package/dist/runtime/logging/bootstrap-logging.d.ts +28 -0
  86. package/dist/runtime/logging/bootstrap-logging.js +26 -0
  87. package/dist/runtime/logging/entry.d.ts +14 -0
  88. package/dist/runtime/logging/entry.js +85 -0
  89. package/dist/runtime/logging/file-sink.d.ts +24 -0
  90. package/dist/runtime/logging/file-sink.js +128 -0
  91. package/dist/runtime/logging/log-settings.d.ts +52 -0
  92. package/dist/runtime/logging/log-settings.js +93 -0
  93. package/dist/runtime/logging/log-sink.d.ts +18 -0
  94. package/dist/runtime/logging/log-sink.js +22 -0
  95. package/dist/runtime/logging/redact.d.ts +31 -0
  96. package/dist/runtime/logging/redact.js +106 -0
  97. package/dist/runtime/logging/runtime.d.ts +25 -0
  98. package/dist/runtime/logging/runtime.js +114 -0
  99. package/dist/runtime/logging/sudo-bridge.d.ts +13 -0
  100. package/dist/runtime/logging/sudo-bridge.js +38 -0
  101. package/dist/runtime/manifest-data.d.ts +28 -0
  102. package/dist/runtime/manifest-data.js +70 -0
  103. package/dist/runtime/manifest-response.d.ts +45 -0
  104. package/dist/runtime/manifest-response.js +50 -0
  105. package/dist/runtime/manifest-sections.d.ts +20 -0
  106. package/dist/runtime/manifest-sections.js +59 -0
  107. package/dist/runtime/manifest-service.d.ts +16 -0
  108. package/dist/runtime/manifest-service.js +66 -0
  109. package/dist/runtime/project-config.d.ts +8 -0
  110. package/dist/runtime/project-config.js +22 -0
  111. package/dist/runtime/project-files.d.ts +12 -0
  112. package/dist/runtime/project-files.js +99 -0
  113. package/dist/runtime/rate-limit.d.ts +6 -0
  114. package/dist/runtime/rate-limit.js +6 -0
  115. package/dist/runtime/revision-service.d.ts +15 -0
  116. package/dist/runtime/revision-service.js +26 -0
  117. package/dist/runtime/sql.d.ts +8 -0
  118. package/dist/runtime/sql.js +23 -0
  119. package/dist/runtime/sso.d.ts +40 -0
  120. package/dist/runtime/sso.js +98 -0
  121. package/dist/runtime/state.d.ts +7 -0
  122. package/dist/runtime/state.js +7 -0
  123. package/dist/runtime/storage-keys.d.ts +9 -0
  124. package/dist/runtime/storage-keys.js +82 -0
  125. package/dist/runtime/storage-target.d.ts +25 -0
  126. package/dist/runtime/storage-target.js +155 -0
  127. package/dist/runtime/system-role.d.ts +9 -0
  128. package/dist/runtime/system-role.js +21 -0
  129. package/dist/runtime/tasks/boot.d.ts +20 -0
  130. package/dist/runtime/tasks/boot.js +32 -0
  131. package/dist/runtime/tasks/contracts.d.ts +70 -0
  132. package/dist/runtime/tasks/contracts.js +1 -0
  133. package/dist/runtime/tasks/db-store.d.ts +18 -0
  134. package/dist/runtime/tasks/db-store.js +139 -0
  135. package/dist/runtime/tasks/row-mapping.d.ts +11 -0
  136. package/dist/runtime/tasks/row-mapping.js +69 -0
  137. package/dist/runtime/tasks/runtime.d.ts +7 -0
  138. package/dist/runtime/tasks/runtime.js +162 -0
  139. package/dist/runtime/tasks/tasks-test-harness.d.ts +16 -0
  140. package/dist/runtime/tasks/tasks-test-harness.js +70 -0
  141. package/dist/runtime/tenant.d.ts +10 -0
  142. package/dist/runtime/tenant.js +13 -0
  143. package/dist/runtime/workflows/boot.d.ts +25 -0
  144. package/dist/runtime/workflows/boot.js +75 -0
  145. package/dist/runtime/workflows/contracts.d.ts +96 -0
  146. package/dist/runtime/workflows/contracts.js +1 -0
  147. package/dist/runtime/workflows/db-store.d.ts +18 -0
  148. package/dist/runtime/workflows/db-store.js +128 -0
  149. package/dist/runtime/workflows/definitions.d.ts +14 -0
  150. package/dist/runtime/workflows/definitions.js +50 -0
  151. package/dist/runtime/workflows/dispatch.d.ts +4 -0
  152. package/dist/runtime/workflows/dispatch.js +119 -0
  153. package/dist/runtime/workflows/row-mapping.d.ts +5 -0
  154. package/dist/runtime/workflows/row-mapping.js +38 -0
  155. package/dist/runtime/workflows/runner.d.ts +15 -0
  156. package/dist/runtime/workflows/runner.js +89 -0
  157. package/dist/runtime/workflows/runtime.d.ts +14 -0
  158. package/dist/runtime/workflows/runtime.js +129 -0
  159. package/dist/runtime/workflows/steps.d.ts +14 -0
  160. package/dist/runtime/workflows/steps.js +49 -0
  161. package/dist/runtime/workflows/support.d.ts +20 -0
  162. package/dist/runtime/workflows/support.js +36 -0
  163. package/dist/runtime/workflows/transitions.d.ts +8 -0
  164. package/dist/runtime/workflows/transitions.js +184 -0
  165. package/dist/runtime/workflows/workflows-test-harness.d.ts +62 -0
  166. package/dist/runtime/workflows/workflows-test-harness.js +178 -0
  167. package/dist/session-cookie.d.ts +13 -0
  168. package/dist/session-cookie.js +48 -0
  169. package/dist/storage.d.ts +50 -0
  170. package/dist/storage.js +118 -0
  171. package/dist/types.d.ts +44 -0
  172. package/dist/types.js +1 -0
  173. package/dist/virtual-ids.d.ts +17 -0
  174. package/dist/virtual-ids.js +17 -0
  175. package/dist/vite.d.ts +22 -0
  176. package/dist/vite.js +135 -0
  177. package/package.json +61 -4
  178. package/src/config.ts +120 -0
  179. package/src/constants.ts +24 -0
  180. package/src/facade.ts +153 -0
  181. package/src/index.ts +44 -0
  182. package/src/middleware/context.ts +106 -0
  183. package/src/middleware/cors.ts +42 -0
  184. package/src/middleware/session.ts +23 -0
  185. package/src/module.ts +278 -0
  186. package/src/rolldown-parser.ts +79 -0
  187. package/src/route-metadata-test-harness.ts +62 -0
  188. package/src/route-metadata.ts +194 -0
  189. package/src/routes/dev-query.post.ts +53 -0
  190. package/src/routes/dev-schema.get.ts +43 -0
  191. package/src/routes/dev-view.post.ts +66 -0
  192. package/src/routes/health.get.ts +26 -0
  193. package/src/routes/manifest-revision.get.ts +38 -0
  194. package/src/routes/manifest.get.ts +111 -0
  195. package/src/routes/openapi.get.ts +34 -0
  196. package/src/routes/sso.ts +247 -0
  197. package/src/routes/token.post.ts +89 -0
  198. package/src/runtime/boot-runtimes.ts +69 -0
  199. package/src/runtime/bootstrap.ts +300 -0
  200. package/src/runtime/config.ts +60 -0
  201. package/src/runtime/cors-policy.ts +107 -0
  202. package/src/runtime/db-bootstrap.ts +99 -0
  203. package/src/runtime/db-target.ts +87 -0
  204. package/src/runtime/dev-db-persistence.ts +146 -0
  205. package/src/runtime/dev-query.ts +124 -0
  206. package/src/runtime/env.ts +18 -0
  207. package/src/runtime/http-guard.ts +50 -0
  208. package/src/runtime/http.ts +30 -0
  209. package/src/runtime/jobs/boot.ts +97 -0
  210. package/src/runtime/jobs/contracts.ts +165 -0
  211. package/src/runtime/jobs/db-store-test-harness.ts +98 -0
  212. package/src/runtime/jobs/db-store.ts +273 -0
  213. package/src/runtime/jobs/definitions.ts +42 -0
  214. package/src/runtime/jobs/engine-support.ts +44 -0
  215. package/src/runtime/jobs/engine.ts +296 -0
  216. package/src/runtime/jobs/executor.ts +37 -0
  217. package/src/runtime/jobs/memory-store.ts +222 -0
  218. package/src/runtime/jobs/row-mapping.ts +67 -0
  219. package/src/runtime/jobs/runtime.ts +110 -0
  220. package/src/runtime/logging/audit-chain.ts +135 -0
  221. package/src/runtime/logging/bootstrap-logging.ts +62 -0
  222. package/src/runtime/logging/entry.ts +99 -0
  223. package/src/runtime/logging/file-sink.ts +157 -0
  224. package/src/runtime/logging/log-settings.ts +166 -0
  225. package/src/runtime/logging/log-sink.ts +31 -0
  226. package/src/runtime/logging/redact.ts +108 -0
  227. package/src/runtime/logging/runtime.ts +163 -0
  228. package/src/runtime/logging/sudo-bridge.ts +41 -0
  229. package/src/runtime/manifest-data.ts +103 -0
  230. package/src/runtime/manifest-response.ts +95 -0
  231. package/src/runtime/manifest-sections.ts +79 -0
  232. package/src/runtime/manifest-service.ts +83 -0
  233. package/src/runtime/project-config.ts +25 -0
  234. package/src/runtime/project-files.ts +103 -0
  235. package/src/runtime/rate-limit.ts +12 -0
  236. package/src/runtime/revision-service.ts +38 -0
  237. package/src/runtime/sql.ts +24 -0
  238. package/src/runtime/sso.ts +153 -0
  239. package/src/runtime/state.ts +7 -0
  240. package/src/runtime/storage-keys.ts +95 -0
  241. package/src/runtime/storage-target.ts +238 -0
  242. package/src/runtime/system-role.ts +26 -0
  243. package/src/runtime/tasks/boot.ts +49 -0
  244. package/src/runtime/tasks/contracts.ts +77 -0
  245. package/src/runtime/tasks/db-store.ts +191 -0
  246. package/src/runtime/tasks/row-mapping.ts +75 -0
  247. package/src/runtime/tasks/runtime.ts +192 -0
  248. package/src/runtime/tasks/tasks-test-harness.ts +92 -0
  249. package/src/runtime/tenant.ts +15 -0
  250. package/src/runtime/workflows/boot.ts +97 -0
  251. package/src/runtime/workflows/contracts.ts +114 -0
  252. package/src/runtime/workflows/db-store.ts +156 -0
  253. package/src/runtime/workflows/definitions.ts +75 -0
  254. package/src/runtime/workflows/dispatch.ts +148 -0
  255. package/src/runtime/workflows/row-mapping.ts +54 -0
  256. package/src/runtime/workflows/runner.ts +105 -0
  257. package/src/runtime/workflows/runtime.ts +161 -0
  258. package/src/runtime/workflows/steps.ts +74 -0
  259. package/src/runtime/workflows/support.ts +60 -0
  260. package/src/runtime/workflows/transitions.ts +259 -0
  261. package/src/runtime/workflows/workflows-test-harness.ts +238 -0
  262. package/src/session-cookie.ts +69 -0
  263. package/src/storage.ts +173 -0
  264. package/src/types.ts +51 -0
  265. package/src/virtual-ids.ts +18 -0
  266. package/src/virtual-modules.d.ts +53 -0
  267. package/src/vite.ts +175 -0
@@ -0,0 +1,156 @@
1
+ // The Drizzle-backed workflow store (D-135, docs/WORKFLOWS.md §5-§8).
2
+ //
3
+ // Every operation runs through runWithPolicyScope, i.e. as facilis_app with app.tenant_id set:
4
+ // a new row's tenant_id comes from the tenantColumn default (the same GUC the restrictive
5
+ // policy reads), and a query cannot reach another tenant's chains. The runner's transitions
6
+ // are compare-and-set UPDATEs, so a transition that lost a race changes nothing.
7
+ import { and, asc, eq, inArray, isNull, sql, type SQL } from "drizzle-orm";
8
+
9
+ import { facilisWorkflows, runWithPolicyScope } from "@facilis.dev/db";
10
+ import type { FacilisDb, PolicyScopedDatabase } from "@facilis.dev/db";
11
+
12
+ import type {
13
+ NewStoredWorkflow,
14
+ StoredWorkflow,
15
+ WorkflowGuard,
16
+ WorkflowListFilters,
17
+ WorkflowPatch,
18
+ WorkflowStore,
19
+ } from "./contracts.ts";
20
+ import { toStoredWorkflow } from "./row-mapping.ts";
21
+
22
+ /**
23
+ * The persistent WorkflowStore over facilis_workflows. A missing table is not handled here:
24
+ * boot probes it with isWorkflowsTableAvailable and disables the API instead (D-135: no
25
+ * in-memory mode), so these methods may throw when the project is not migrated.
26
+ */
27
+ export function createDbWorkflowStore(options: {
28
+ readonly db: FacilisDb;
29
+ readonly tenantId: string;
30
+ /** Request transaction to join (from WorkflowStore.scoped); absent for runner-owned work. */
31
+ readonly scope?: PolicyScopedDatabase;
32
+ }): WorkflowStore {
33
+ const { db, tenantId, scope } = options;
34
+
35
+ function run<T>(fn: (tx: PolicyScopedDatabase) => Promise<T>): Promise<T> {
36
+ return scope === undefined ? runWithPolicyScope(db, { tenantId }, fn) : fn(scope);
37
+ }
38
+
39
+ return {
40
+ async insert(workflow: NewStoredWorkflow): Promise<void> {
41
+ await run((tx) =>
42
+ tx.insert(facilisWorkflows).values({
43
+ id: workflow.id,
44
+ name: workflow.name,
45
+ status: "running",
46
+ input: workflow.input,
47
+ progress: [],
48
+ plan: workflow.plan,
49
+ currentStep: 0,
50
+ attempts: 0,
51
+ startedAt: workflow.startedAt,
52
+ createdAt: workflow.createdAt,
53
+ }),
54
+ );
55
+ },
56
+
57
+ async get(id: string): Promise<StoredWorkflow | null> {
58
+ return run(async (tx) => {
59
+ const rows = await tx
60
+ .select()
61
+ .from(facilisWorkflows)
62
+ .where(eq(facilisWorkflows.id, id))
63
+ .limit(1);
64
+ const row = rows[0];
65
+ return row === undefined ? null : toStoredWorkflow(row);
66
+ });
67
+ },
68
+
69
+ async list(filters: WorkflowListFilters): Promise<StoredWorkflow[]> {
70
+ return run(async (tx) => {
71
+ const conditions: SQL[] = [];
72
+ if (filters.status !== undefined) {
73
+ conditions.push(
74
+ typeof filters.status === "string"
75
+ ? eq(facilisWorkflows.status, filters.status)
76
+ : inArray(facilisWorkflows.status, [...filters.status]),
77
+ );
78
+ }
79
+ if (filters.name !== undefined) conditions.push(eq(facilisWorkflows.name, filters.name));
80
+ const rows = await tx
81
+ .select()
82
+ .from(facilisWorkflows)
83
+ .where(conditions.length === 0 ? undefined : and(...conditions))
84
+ // Chain order: the tick advances the oldest active run first.
85
+ .orderBy(asc(facilisWorkflows.createdAt))
86
+ .limit(filters.limit);
87
+ return rows.map(toStoredWorkflow);
88
+ });
89
+ },
90
+
91
+ async update(
92
+ id: string,
93
+ guard: WorkflowGuard,
94
+ patch: WorkflowPatch,
95
+ ): Promise<StoredWorkflow | null> {
96
+ const values: Partial<typeof facilisWorkflows.$inferInsert> = {};
97
+ if (patch.status !== undefined) values.status = patch.status;
98
+ if (patch.progress !== undefined) values.progress = [...patch.progress];
99
+ if (patch.currentStep !== undefined) values.currentStep = patch.currentStep;
100
+ if (patch.currentJobId !== undefined) values.currentJobId = patch.currentJobId;
101
+ if (patch.waitingTaskId !== undefined) values.waitingTaskId = patch.waitingTaskId;
102
+ if (patch.attempts !== undefined) values.attempts = patch.attempts;
103
+ if (patch.output !== undefined) values.output = patch.output;
104
+ if (patch.error !== undefined) values.error = patch.error;
105
+ if (patch.finishedAt !== undefined) values.finishedAt = patch.finishedAt;
106
+ if (Object.keys(values).length === 0) throw new Error("workflow update has no fields");
107
+
108
+ return run(async (tx) => {
109
+ const conditions: SQL[] = [
110
+ eq(facilisWorkflows.id, id),
111
+ eq(facilisWorkflows.status, guard.status),
112
+ ];
113
+ if (guard.currentStep !== undefined) {
114
+ conditions.push(eq(facilisWorkflows.currentStep, guard.currentStep));
115
+ }
116
+ if (guard.currentJobId !== undefined) {
117
+ conditions.push(
118
+ guard.currentJobId === null
119
+ ? isNull(facilisWorkflows.currentJobId)
120
+ : eq(facilisWorkflows.currentJobId, guard.currentJobId),
121
+ );
122
+ }
123
+ if (guard.waitingTaskId !== undefined) {
124
+ conditions.push(
125
+ guard.waitingTaskId === null
126
+ ? isNull(facilisWorkflows.waitingTaskId)
127
+ : eq(facilisWorkflows.waitingTaskId, guard.waitingTaskId),
128
+ );
129
+ }
130
+ const rows = await tx
131
+ .update(facilisWorkflows)
132
+ .set(values)
133
+ .where(and(...conditions))
134
+ .returning();
135
+ const row = rows[0];
136
+ return row === undefined ? null : toStoredWorkflow(row);
137
+ });
138
+ },
139
+
140
+ /** Joins workflow operations to an existing transaction (see run above). */
141
+ scoped(next: PolicyScopedDatabase): WorkflowStore {
142
+ return createDbWorkflowStore({ db, tenantId, scope: next });
143
+ },
144
+ };
145
+ }
146
+
147
+ /**
148
+ * Probe used by boot: to_regclass answers null for a missing table instead of raising, which
149
+ * is exactly the "project not migrated yet" case (D-135).
150
+ */
151
+ export async function isWorkflowsTableAvailable(db: FacilisDb): Promise<boolean> {
152
+ const result = await db.db.execute(
153
+ sql`select to_regclass('public.facilis_workflows') is not null as available`,
154
+ );
155
+ return result.rows[0]?.["available"] === true;
156
+ }
@@ -0,0 +1,75 @@
1
+ import {
2
+ isWorkflowDefinition,
3
+ type JobDefinition,
4
+ type ManifestWarning,
5
+ type WorkflowDefinition,
6
+ } from "@facilis.dev/core";
7
+
8
+ import type { WorkflowModule } from "./contracts.ts";
9
+
10
+ /** The project's workflow definitions plus the manifest warnings raised while indexing them. */
11
+ export interface WorkflowRegistry {
12
+ readonly definitions: ReadonlyMap<string, WorkflowDefinition<unknown, unknown>>;
13
+ readonly warnings: ManifestWarning[];
14
+ }
15
+
16
+ /**
17
+ * Indexes the modules behind `#facilis/workflows` (docs/WORKFLOWS.md §6).
18
+ *
19
+ * An invalid, duplicate or dangling definition must never break boot: it becomes a manifest
20
+ * warning and the module is skipped (jobs behaviour, docs/JOBS.md §5).
21
+ */
22
+ export function buildWorkflowRegistry(
23
+ modules: readonly WorkflowModule[],
24
+ jobs: ReadonlyMap<string, JobDefinition<unknown, unknown>>,
25
+ ): WorkflowRegistry {
26
+ const definitions = new Map<string, WorkflowDefinition<unknown, unknown>>();
27
+ const warnings: ManifestWarning[] = [];
28
+
29
+ for (const module of modules) {
30
+ if (!isWorkflowDefinition(module.definition)) {
31
+ warnings.push({
32
+ code: "workflow_definition_invalid",
33
+ message: `${module.file} must default-export defineWorkflow({...}); the module was skipped.`,
34
+ sourceFile: module.file,
35
+ });
36
+ continue;
37
+ }
38
+ if (definitions.has(module.definition.name)) {
39
+ warnings.push({
40
+ code: "workflow_definition_invalid",
41
+ message: `Duplicate workflow "${module.definition.name}" in ${module.file}; the first definition wins.`,
42
+ sourceFile: module.file,
43
+ });
44
+ continue;
45
+ }
46
+ const dangling = danglingJob(module.definition, jobs);
47
+ if (dangling !== null) {
48
+ warnings.push({
49
+ code: "workflow_definition_invalid",
50
+ message: `${module.file}: step references unknown job "${dangling}"; the workflow was skipped.`,
51
+ sourceFile: module.file,
52
+ });
53
+ continue;
54
+ }
55
+ // The registry is deliberately input-erased (a project mixes definitions with different
56
+ // inputs); the resolver context is reconstructed from the row at dispatch time (§6).
57
+ definitions.set(
58
+ module.definition.name,
59
+ module.definition as WorkflowDefinition<unknown, unknown>,
60
+ );
61
+ }
62
+
63
+ return { definitions, warnings };
64
+ }
65
+
66
+ /** First job step whose name is not in the job registry; null when every step resolves. */
67
+ function danglingJob(
68
+ definition: WorkflowDefinition,
69
+ jobs: ReadonlyMap<string, JobDefinition<unknown, unknown>>,
70
+ ): string | null {
71
+ for (const step of definition.steps) {
72
+ if ("job" in step && !jobs.has(step.job)) return step.job;
73
+ }
74
+ return null;
75
+ }
@@ -0,0 +1,148 @@
1
+ // Step dispatch: the two side effects a chain can hand off (D-135, WORKFLOWS.md §8.4).
2
+ //
3
+ // A job step enqueues its job in the same transaction as the workflow update, and an approval
4
+ // step inserts its task in the same transaction as the waiting transition: either both sides
5
+ // of the hand-off exist or neither does.
6
+ import { randomUUID } from "node:crypto";
7
+
8
+ import type { WorkflowApprovalStep, WorkflowJobStep, WorkflowResolveContext } from "@facilis.dev/core";
9
+ import { runWithPolicyScope } from "@facilis.dev/db";
10
+
11
+ import type { StoredWorkflow, WorkflowRuntimeDeps } from "./contracts.ts";
12
+ import { normalizeTitleParams, planMatches, resolveContext } from "./steps.ts";
13
+ import { CasLost, describe, fail, guard, lastOutput, type Now } from "./support.ts";
14
+
15
+ /** Dispatches the current step: enqueue its job or request its approval (§8.4). */
16
+ export async function dispatch(
17
+ deps: WorkflowRuntimeDeps,
18
+ now: Now,
19
+ workflow: StoredWorkflow,
20
+ attempts: number,
21
+ ): Promise<void> {
22
+ const definition = deps.definitions.get(workflow.name);
23
+ if (definition === undefined) {
24
+ return fail(
25
+ deps,
26
+ now,
27
+ workflow,
28
+ "workflow_definition_changed",
29
+ 'Workflow "' + workflow.name + '" is no longer defined.',
30
+ );
31
+ }
32
+ const index = workflow.currentStep;
33
+ if (index >= definition.steps.length) {
34
+ await deps.store.update(workflow.id, guard(workflow), {
35
+ status: "succeeded",
36
+ currentStep: index,
37
+ currentJobId: null,
38
+ attempts: 0,
39
+ output: lastOutput(workflow.progress, index - 1),
40
+ error: null,
41
+ finishedAt: now(),
42
+ });
43
+ return;
44
+ }
45
+ if (!planMatches(workflow.plan, definition, index)) {
46
+ return fail(
47
+ deps,
48
+ now,
49
+ workflow,
50
+ "workflow_definition_changed",
51
+ "Step " + index + " changed since the run started.",
52
+ );
53
+ }
54
+ const step = definition.steps[index];
55
+ if (step === undefined) return;
56
+ const context = resolveContext(workflow.input, workflow.progress, index);
57
+ if ("job" in step) {
58
+ return dispatchJob(deps, now, workflow, step, context, attempts);
59
+ }
60
+ return dispatchApproval(deps, now, workflow, step, index, context);
61
+ }
62
+
63
+ /** Resolves, enqueues and records one job step inside a single transaction. */
64
+ async function dispatchJob(
65
+ deps: WorkflowRuntimeDeps,
66
+ now: Now,
67
+ workflow: StoredWorkflow,
68
+ step: WorkflowJobStep,
69
+ context: WorkflowResolveContext,
70
+ attempts: number,
71
+ ): Promise<void> {
72
+ let data: unknown;
73
+ try {
74
+ // No resolver means "the chain input is this job's input": the common first-step case.
75
+ data = step.input === undefined ? workflow.input : step.input(context);
76
+ } catch (error) {
77
+ await fail(deps, now, workflow, "workflow_step_failed", describe(error));
78
+ return;
79
+ }
80
+ try {
81
+ await runWithPolicyScope(deps.db, { tenantId: deps.tenantId }, async (tx) => {
82
+ const store = deps.store.scoped?.(tx) ?? deps.store;
83
+ const jobs = deps.jobs.scoped?.(tx) ?? deps.jobs;
84
+ const { id: jobId } = await jobs.enqueue(step.job, data);
85
+ const updated = await store.update(workflow.id, guard(workflow), {
86
+ status: "running",
87
+ currentJobId: jobId,
88
+ attempts,
89
+ });
90
+ if (updated === null) throw new CasLost();
91
+ });
92
+ } catch (error) {
93
+ if (error instanceof CasLost) return;
94
+ await fail(deps, now, workflow, "workflow_step_failed", describe(error));
95
+ }
96
+ }
97
+
98
+ /** Inserts the approval task and suspends the chain on it inside a single transaction. */
99
+ async function dispatchApproval(
100
+ deps: WorkflowRuntimeDeps,
101
+ now: Now,
102
+ workflow: StoredWorkflow,
103
+ step: WorkflowApprovalStep,
104
+ index: number,
105
+ context: WorkflowResolveContext,
106
+ ): Promise<void> {
107
+ const approval = step.approval;
108
+ let params: Record<string, string | number>;
109
+ try {
110
+ params = normalizeTitleParams(approval.params === undefined ? {} : approval.params(context));
111
+ } catch (error) {
112
+ await fail(deps, now, workflow, "workflow_step_failed", describe(error));
113
+ return;
114
+ }
115
+ const ttl = approval.ttlMs ?? deps.config.defaultTaskTtlMs;
116
+ const taskId = randomUUID();
117
+ const createdAt = now();
118
+ const expiresAt = ttl === null ? null : new Date(createdAt.getTime() + ttl);
119
+ try {
120
+ await runWithPolicyScope(deps.db, { tenantId: deps.tenantId }, async (tx) => {
121
+ const store = deps.store.scoped?.(tx) ?? deps.store;
122
+ const tasks = deps.tasks.scoped?.(tx) ?? deps.tasks;
123
+ await tasks.insert({
124
+ id: taskId,
125
+ workflowId: workflow.id,
126
+ stepIndex: index,
127
+ kind: "approval",
128
+ titleKey: approval.titleKey,
129
+ titleParams: params,
130
+ // The decider sees the chain input; the params are only the rendered title.
131
+ payload: workflow.input,
132
+ requestedBy: "system:workflow:" + workflow.name,
133
+ assignedPermission: approval.permission ?? null,
134
+ expiresAt,
135
+ createdAt,
136
+ });
137
+ const updated = await store.update(workflow.id, guard(workflow), {
138
+ status: "waiting",
139
+ waitingTaskId: taskId,
140
+ attempts: 0,
141
+ });
142
+ if (updated === null) throw new CasLost();
143
+ });
144
+ } catch (error) {
145
+ if (error instanceof CasLost) return;
146
+ await fail(deps, now, workflow, "workflow_step_failed", describe(error));
147
+ }
148
+ }
@@ -0,0 +1,54 @@
1
+ // Row <-> record mapping for the workflow runtime (D-135, docs/WORKFLOWS.md §5).
2
+ //
3
+ // StoredWorkflow keeps real Dates and JSON values; WorkflowRecord is the public shape and
4
+ // carries ISO-8601 instants, exactly like JobRecord (docs/JOBS.md §6).
5
+ import type {
6
+ JobJson,
7
+ WorkflowProgressEntry,
8
+ WorkflowRecord,
9
+ WorkflowStatus,
10
+ WorkflowStepIdentity,
11
+ } from "@facilis.dev/core";
12
+ import type { FacilisWorkflowRow } from "@facilis.dev/db";
13
+
14
+ import type { StoredWorkflow } from "./contracts.ts";
15
+
16
+ export function toStoredWorkflow(row: FacilisWorkflowRow): StoredWorkflow {
17
+ return {
18
+ id: row.id,
19
+ name: row.name,
20
+ status: row.status as WorkflowStatus,
21
+ input: row.input as JobJson,
22
+ // JSONB comes back as parsed JSON; the plan/progress contracts are enforced on write.
23
+ progress: Array.isArray(row.progress) ? (row.progress as WorkflowProgressEntry[]) : [],
24
+ plan: Array.isArray(row.plan) ? (row.plan as WorkflowStepIdentity[]) : [],
25
+ currentStep: row.currentStep,
26
+ currentJobId: row.currentJobId,
27
+ waitingTaskId: row.waitingTaskId,
28
+ attempts: row.attempts,
29
+ output: (row.output as JobJson | null) ?? null,
30
+ error: row.error,
31
+ startedAt: row.startedAt,
32
+ finishedAt: row.finishedAt,
33
+ createdAt: row.createdAt,
34
+ };
35
+ }
36
+
37
+ export function toWorkflowRecord(workflow: StoredWorkflow): WorkflowRecord {
38
+ return {
39
+ id: workflow.id,
40
+ name: workflow.name,
41
+ status: workflow.status,
42
+ input: workflow.input,
43
+ progress: workflow.progress,
44
+ currentStep: workflow.currentStep,
45
+ currentJobId: workflow.currentJobId,
46
+ waitingTaskId: workflow.waitingTaskId,
47
+ attempts: workflow.attempts,
48
+ output: workflow.output,
49
+ error: workflow.error,
50
+ startedAt: workflow.startedAt.toISOString(),
51
+ finishedAt: workflow.finishedAt === null ? null : workflow.finishedAt.toISOString(),
52
+ createdAt: workflow.createdAt.toISOString(),
53
+ };
54
+ }
@@ -0,0 +1,105 @@
1
+ // The workflow runner (D-135, docs/WORKFLOWS.md §8): a tick, not a job.
2
+ //
3
+ // The tick scans active rows and applies one transition each; a start or a decision only
4
+ // wakes it. Nothing here waits for a human or keeps a transaction open across steps, which is
5
+ // what makes an approval survive the dev-server worker reload (WORKFLOWS.md §2).
6
+ import type { WorkflowsApi } from "@facilis.dev/core";
7
+
8
+ import type { JobTimers } from "../jobs/contracts.ts";
9
+ import { SYSTEM_TIMERS } from "../jobs/engine-support.ts";
10
+ import type { WorkflowRuntimeDeps } from "./contracts.ts";
11
+ import { createWorkflowsApi } from "./runtime.ts";
12
+ import { expireDueTasks, stepWorkflow, TICK_BATCH } from "./transitions.ts";
13
+
14
+ /** The booted workflow runtime carried by BootstrapState (D-135). */
15
+ export interface WorkflowsRuntime {
16
+ readonly api: WorkflowsApi;
17
+ start(): Promise<void>;
18
+ stop(): Promise<void>;
19
+ /** One tick; exposed for boot recovery and deterministic tests. */
20
+ tick(): Promise<void>;
21
+ }
22
+
23
+ /**
24
+ * Builds the runner around the shared deps: the API reads/writes rows, the tick advances
25
+ * chains, and the job engine is only used for step dispatch, status and cancellation.
26
+ */
27
+ export function createWorkflowRunner(deps: WorkflowRuntimeDeps): WorkflowsRuntime {
28
+ const timers: JobTimers = deps.timers ?? SYSTEM_TIMERS;
29
+ const now = (): Date => new Date(timers.now());
30
+ const report = (error: unknown, context: string): void => deps.onError?.(error, context);
31
+
32
+ let started = false;
33
+ let stopping = false;
34
+ let tickRunning = false;
35
+ let wakeRequested = false;
36
+ let timer: unknown = null;
37
+
38
+ function scheduleTick(delayMs: number): void {
39
+ if (!started || stopping) return;
40
+ if (timer !== null) timers.clearTimeout(timer);
41
+ timer = timers.setTimeout(() => {
42
+ timer = null;
43
+ void tick().catch(() => undefined);
44
+ }, delayMs);
45
+ }
46
+
47
+ /** A start/decision asks for an immediate tick; a running tick defers to it. */
48
+ function requestTick(): void {
49
+ if (!started || stopping) return;
50
+ if (tickRunning) {
51
+ wakeRequested = true;
52
+ return;
53
+ }
54
+ scheduleTick(0);
55
+ }
56
+
57
+ async function tick(): Promise<void> {
58
+ if (stopping || tickRunning) return;
59
+ tickRunning = true;
60
+ try {
61
+ await expireDueTasks(deps, now);
62
+ const active = await deps.store.list({ status: ["running", "waiting"], limit: TICK_BATCH });
63
+ for (const workflow of active) {
64
+ try {
65
+ await stepWorkflow(deps, now, workflow);
66
+ } catch (error) {
67
+ // One broken row must not stall the others; the next tick retries it.
68
+ report(error, "runner:" + workflow.id);
69
+ }
70
+ }
71
+ } catch (error) {
72
+ report(error, "runner.tick");
73
+ } finally {
74
+ tickRunning = false;
75
+ if (started && !stopping) {
76
+ const immediate = wakeRequested;
77
+ wakeRequested = false;
78
+ scheduleTick(immediate ? 0 : deps.config.tickIntervalMs);
79
+ }
80
+ }
81
+ }
82
+
83
+ const api = createWorkflowsApi(deps, requestTick);
84
+
85
+ return {
86
+ api,
87
+ async start(): Promise<void> {
88
+ if (started || stopping) return;
89
+ started = true;
90
+ // The first tick is the boot recovery: it reconciles rows a reload left behind.
91
+ scheduleTick(0);
92
+ },
93
+ async stop(): Promise<void> {
94
+ if (!started && timer === null) return;
95
+ stopping = true;
96
+ started = false;
97
+ if (timer !== null) {
98
+ timers.clearTimeout(timer);
99
+ timer = null;
100
+ }
101
+ wakeRequested = false;
102
+ },
103
+ tick,
104
+ };
105
+ }
@@ -0,0 +1,161 @@
1
+ // The server-only workflow API (D-135, docs/WORKFLOWS.md §7).
2
+ //
3
+ // Validation and JSON serialization live here; the store only knows rows and the runner owns
4
+ // every state transition. `start` writes the row and wakes the tick - it never executes a
5
+ // step inline, so a route's latency is independent of the chain (WORKFLOWS.md §4).
6
+ import { randomUUID } from "node:crypto";
7
+
8
+ import { serializeWorkflowData, WORKFLOW_STATUSES, WorkflowError } from "@facilis.dev/core";
9
+ import type {
10
+ WorkflowDefinition,
11
+ WorkflowListOptions,
12
+ WorkflowRecord,
13
+ WorkflowsApi,
14
+ WorkflowStatus,
15
+ } from "@facilis.dev/core";
16
+ import type { PolicyScopedDatabase } from "@facilis.dev/db";
17
+
18
+ import { formatIssues } from "../jobs/engine-support.ts";
19
+ import type { WorkflowListFilters, WorkflowRuntimeDeps } from "./contracts.ts";
20
+ import { toWorkflowRecord } from "./row-mapping.ts";
21
+ import { stepIdentity } from "./steps.ts";
22
+
23
+ const DEFAULT_LIMIT = 50;
24
+ const MAX_LIMIT = 200;
25
+
26
+ /** Terminal statuses: cancel is a no-op and the tick never reads them. */
27
+ export const TERMINAL_WORKFLOW_STATUSES: ReadonlySet<WorkflowStatus> = new Set([
28
+ "succeeded",
29
+ "failed",
30
+ "cancelled",
31
+ ]);
32
+
33
+ /**
34
+ * Adapts the workflow store and the job engine to the handler-facing API.
35
+ *
36
+ * `wake` asks the runner for an immediate tick; a bound view (`bindScope`) joins the
37
+ * request transaction for every read/write it performs.
38
+ */
39
+ export function createWorkflowsApi(deps: WorkflowRuntimeDeps, wake: () => void): WorkflowsApi {
40
+ const now = (): Date => (deps.now ?? (() => new Date()))();
41
+
42
+ const api: WorkflowsApi = {
43
+ async start(name: string, input: unknown): Promise<{ id: string }> {
44
+ const definition = deps.definitions.get(name);
45
+ if (definition === undefined) {
46
+ throw new WorkflowError(
47
+ "workflow_unknown",
48
+ `Workflow "${name}" is not defined by this project.`,
49
+ );
50
+ }
51
+ const data = parseStartInput(definition, input);
52
+ const id = randomUUID();
53
+ const createdAt = now();
54
+ await deps.store.insert({
55
+ id,
56
+ name,
57
+ input: data,
58
+ plan: definition.steps.map(stepIdentity),
59
+ startedAt: createdAt,
60
+ createdAt,
61
+ });
62
+ wake();
63
+ return { id };
64
+ },
65
+
66
+ async get(id: string): Promise<WorkflowRecord | null> {
67
+ const workflow = await deps.store.get(id);
68
+ return workflow === null ? null : toWorkflowRecord(workflow);
69
+ },
70
+
71
+ async list(options: WorkflowListOptions = {}): Promise<WorkflowRecord[]> {
72
+ return (await deps.store.list(normalizeFilters(options))).map(toWorkflowRecord);
73
+ },
74
+
75
+ async cancel(id: string): Promise<boolean> {
76
+ const workflow = await deps.store.get(id);
77
+ if (workflow === null || TERMINAL_WORKFLOW_STATUSES.has(workflow.status)) return false;
78
+ const finishedAt = now();
79
+ // Stop the side effect first, then settle the row: a crash in between leaves the job/
80
+ // task terminal, so the next tick observes cancellation instead of stalling (JOBS §8).
81
+ if (workflow.currentJobId !== null) await deps.jobs.cancel(workflow.currentJobId);
82
+ if (workflow.waitingTaskId !== null) {
83
+ await deps.tasks.cancel(workflow.waitingTaskId, finishedAt);
84
+ }
85
+ const updated = await deps.store.update(
86
+ id,
87
+ {
88
+ status: workflow.status,
89
+ currentStep: workflow.currentStep,
90
+ currentJobId: workflow.currentJobId,
91
+ waitingTaskId: workflow.waitingTaskId,
92
+ },
93
+ {
94
+ status: "cancelled",
95
+ currentJobId: null,
96
+ waitingTaskId: null,
97
+ error: null,
98
+ finishedAt,
99
+ },
100
+ );
101
+ return updated !== null;
102
+ },
103
+
104
+ /**
105
+ * A handler's ctx.workflows joins the request's policy transaction, so starting or
106
+ * cancelling inside a route does not open a second transaction on the one connection
107
+ * (D-107, docs/JOBS.md §8).
108
+ */
109
+ bindScope(scope: PolicyScopedDatabase): WorkflowsApi {
110
+ return createWorkflowsApi(
111
+ {
112
+ ...deps,
113
+ store: deps.store.scoped?.(scope) ?? deps.store,
114
+ tasks: deps.tasks.scoped?.(scope) ?? deps.tasks,
115
+ jobs: deps.jobs.scoped?.(scope) ?? deps.jobs,
116
+ },
117
+ wake,
118
+ );
119
+ },
120
+ };
121
+ return api;
122
+ }
123
+
124
+ /** Zod-validates the start input and serializes it for the row (what the runner reads). */
125
+ export function parseStartInput(
126
+ definition: WorkflowDefinition<unknown, unknown>,
127
+ input: unknown,
128
+ ): ReturnType<typeof serializeWorkflowData> {
129
+ const parsed = definition.input.safeParse(input);
130
+ if (!parsed.success) {
131
+ throw new WorkflowError("workflow_invalid_input", formatIssues(parsed.error.issues));
132
+ }
133
+ return serializeWorkflowData(parsed.data);
134
+ }
135
+
136
+ function normalizeFilters(options: WorkflowListOptions): WorkflowListFilters {
137
+ const status = options.status;
138
+ if (status !== undefined) {
139
+ const values = typeof status === "string" ? [status] : [...status];
140
+ for (const value of values) {
141
+ if (!WORKFLOW_STATUSES.includes(value as WorkflowStatus)) {
142
+ throw invalid(`Unknown workflow status "${String(value)}".`);
143
+ }
144
+ }
145
+ }
146
+ return {
147
+ ...(status === undefined ? {} : { status }),
148
+ ...(options.name === undefined ? {} : { name: options.name }),
149
+ limit: normalizeLimit(options.limit),
150
+ };
151
+ }
152
+
153
+ function normalizeLimit(value: number | undefined): number {
154
+ if (value === undefined) return DEFAULT_LIMIT;
155
+ if (!Number.isInteger(value) || value < 1) throw invalid("limit must be a positive integer.");
156
+ return Math.min(value, MAX_LIMIT);
157
+ }
158
+
159
+ function invalid(message: string): WorkflowError {
160
+ return new WorkflowError("workflow_invalid_input", message);
161
+ }