@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,69 @@
1
+ // Boots the framework runtimes that sit behind ctx (D-107, D-135, docs/JOBS.md §8).
2
+ //
3
+ // Split out of bootstrap.ts to keep that file under the 300-line gate. Each boot is
4
+ // degradation-safe: a broken queue/task/workflow runtime is a manifest warning and a null
5
+ // service, never a failed process (contracts §8).
6
+ import {
7
+ DEFAULT_JOBS_CONFIG,
8
+ DEFAULT_WORKFLOWS_CONFIG,
9
+ type FacilisConfig,
10
+ type ManifestWarning,
11
+ } from "@facilis.dev/core";
12
+ import type { FacilisDb } from "@facilis.dev/db";
13
+
14
+ import { bootJobs } from "./jobs/boot.ts";
15
+ import type { JobModule } from "./jobs/contracts.ts";
16
+ import type { JobsRuntime } from "./jobs/runtime.ts";
17
+ import { bootTasks } from "./tasks/boot.ts";
18
+ import type { TasksRuntime } from "./tasks/boot.ts";
19
+ import { bootWorkflows } from "./workflows/boot.ts";
20
+ import type { WorkflowModule } from "./workflows/contracts.ts";
21
+ import type { WorkflowsRuntime } from "./workflows/runner.ts";
22
+
23
+ /** The per-request services the context middleware attaches, all nullable on failure. */
24
+ export interface BootedRuntimes {
25
+ readonly jobs: JobsRuntime | null;
26
+ readonly tasks: TasksRuntime | null;
27
+ readonly workflows: WorkflowsRuntime | null;
28
+ }
29
+
30
+ export async function bootRuntimes(options: {
31
+ readonly db: FacilisDb;
32
+ readonly tenantId: string;
33
+ readonly projectConfig: FacilisConfig;
34
+ readonly jobModules: readonly JobModule[];
35
+ readonly workflowModules: readonly WorkflowModule[];
36
+ readonly warnings: ManifestWarning[];
37
+ }): Promise<BootedRuntimes> {
38
+ const { db, tenantId, projectConfig, jobModules, workflowModules, warnings } = options;
39
+
40
+ // The queue starts after the roles/views exist: its own writes run as facilis_app, while
41
+ // a job body escalates to facilis_system (D-107). A failure there is a warning, not a 500.
42
+ const jobs = await bootJobs({
43
+ db,
44
+ // isFacilisConfig deliberately does not require `jobs`, so an older virtual config can
45
+ // still hand an undefined section to a newer runtime: fall back to documented defaults.
46
+ jobsConfig: projectConfig.jobs ?? DEFAULT_JOBS_CONFIG,
47
+ modules: jobModules,
48
+ tenantId,
49
+ warnings,
50
+ });
51
+
52
+ // Manual tasks are durable rows, not a process queue (D-135): booting them is just the
53
+ // store and its table probe; the workflow runner (below) is the only tick.
54
+ const tasks = await bootTasks({ db, tenantId, warnings });
55
+
56
+ // Workflows chain step jobs and approval tasks (D-135, WORKFLOWS.md §8): the runner needs
57
+ // both runtimes, and a missing one disables the API with a warning instead of failing boot.
58
+ const workflows = await bootWorkflows({
59
+ db,
60
+ tenantId,
61
+ modules: workflowModules,
62
+ jobs,
63
+ jobsConfig: projectConfig.jobs ?? DEFAULT_JOBS_CONFIG,
64
+ workflowsConfig: projectConfig.workflows ?? DEFAULT_WORKFLOWS_CONFIG,
65
+ warnings,
66
+ });
67
+
68
+ return { jobs, tasks, workflows };
69
+ }
@@ -0,0 +1,300 @@
1
+ import { createDb, type FacilisDb } from "@facilis.dev/db";
2
+ import { sessionMiddleware, type SessionEvent } from "@facilis.dev/auth";
3
+ import {
4
+ type FacilisConfig,
5
+ type FacilisLoggingApi,
6
+ type FacilisLoggingConfig,
7
+ type ManifestWarning,
8
+ type StorageApi,
9
+ } from "@facilis.dev/core";
10
+ import { projectRoot } from "#facilis/config";
11
+ import dbSchema from "#facilis/db-schema";
12
+ import dbViewModules from "#facilis/db-views";
13
+ import jobModules from "#facilis/jobs";
14
+ import workflowModules from "#facilis/workflows";
15
+
16
+ import { toAuthConfig } from "./config.ts";
17
+ import { bootstrapDevelopmentDatabase, describe } from "./db-bootstrap.ts";
18
+ import { resolveDbTarget } from "./db-target.ts";
19
+ import {
20
+ devDbSnapshotPath,
21
+ installDevDbSnapshotter,
22
+ readDevDbSnapshot,
23
+ } from "./dev-db-persistence.ts";
24
+ import { bootRuntimes } from "./boot-runtimes.ts";
25
+ import { isProductionEnvironment } from "./env.ts";
26
+ import type { JobsRuntime } from "./jobs/runtime.ts";
27
+ import type { TasksRuntime } from "./tasks/boot.ts";
28
+ import type { WorkflowsRuntime } from "./workflows/runner.ts";
29
+ import { readProjectConfig } from "./project-config.ts";
30
+ import { createBootstrapLogging } from "./logging/bootstrap-logging.ts";
31
+ import { installSudoAuditBridge } from "./logging/sudo-bridge.ts";
32
+ import { readDefaultTenantId } from "./tenant.ts";
33
+ import { resolveStorage } from "./storage-target.ts";
34
+
35
+ export interface BootstrapState {
36
+ readonly db: FacilisDb | null;
37
+ readonly config: FacilisConfig | null;
38
+ readonly warnings: readonly ManifestWarning[];
39
+ readonly startedAt: string;
40
+ /**
41
+ * Background-job runtime (D-107); null when the db or the job boot failed. The context
42
+ * middleware carries `jobs.api` on `event.context.facilis`.
43
+ */
44
+ readonly jobs: JobsRuntime | null;
45
+ /**
46
+ * Manual-task runtime (D-135); null when facilis_tasks is missing or the task boot failed.
47
+ * The context middleware carries tasks.api on event.context.facilis.
48
+ */
49
+ readonly tasks: TasksRuntime | null;
50
+ /**
51
+ * Workflow runtime (D-135); null when the tables or the job queue are unavailable. The
52
+ * context middleware carries workflows.api on event.context.facilis.
53
+ */
54
+ readonly workflows: WorkflowsRuntime | null;
55
+ /** Binary-storage runtime (D-053); null when the boot refused its configuration. */
56
+ readonly storage: StorageApi | null;
57
+ /**
58
+ * Operator logging runtime (D-119). Always present: built from the documented defaults when
59
+ * the project config failed, so the request context never lacks a logger.
60
+ */
61
+ readonly logging: FacilisLoggingApi;
62
+ /** Effective logging config (project defaults + env level override) for the middleware. */
63
+ readonly loggingConfig: FacilisLoggingConfig;
64
+ /** Cached session handler; rebuilt lazily because it closes over the db client. */
65
+ sessionHandler?: (event: SessionEvent) => Promise<void>;
66
+ }
67
+
68
+ let bootstrapPromise: Promise<BootstrapState> | undefined;
69
+
70
+ /**
71
+ * Boot the framework runtime once per process (lazily, on the first request).
72
+ *
73
+ * Contract (docs/archive/PHASE1-CONTRACTS.md §8): never crash the request. Each failure is
74
+ * recorded as a manifest warning and the remaining steps still run, so a broken
75
+ * migration yields a 200 partial manifest instead of a 500.
76
+ */
77
+ export function getBootstrap(): Promise<BootstrapState> {
78
+ bootstrapPromise ??= bootstrap();
79
+ return bootstrapPromise;
80
+ }
81
+
82
+ export function getSessionHandler(
83
+ state: BootstrapState,
84
+ ): ((event: SessionEvent) => Promise<void>) | null {
85
+ if (state.db === null || state.config === null) return null;
86
+ state.sessionHandler ??= sessionMiddleware({
87
+ db: state.db,
88
+ config: toAuthConfig(state.config.auth),
89
+ tenantId: readDefaultTenantId(),
90
+ });
91
+ return state.sessionHandler;
92
+ }
93
+
94
+ async function bootstrap(): Promise<BootstrapState> {
95
+ const warnings: ManifestWarning[] = [];
96
+ const startedAt = new Date().toISOString();
97
+ const projectConfig = readProjectConfig(warnings);
98
+
99
+ // Operator logging is built BEFORE the database (D-119): a database boot failure must not
100
+ // take the access/error streams down with it, and logging never prevents a boot.
101
+ const loggingState = createBootstrapLogging({
102
+ loggingConfig: projectConfig?.logging ?? null,
103
+ env: process.env,
104
+ projectRoot,
105
+ });
106
+ warnings.push(...loggingState.warnings);
107
+ const loggingFields = {
108
+ logging: loggingState.logging,
109
+ loggingConfig: loggingState.config,
110
+ } satisfies Pick<BootstrapState, "logging" | "loggingConfig">;
111
+ // The sudo trail is one of the audit stream's events, not a parallel protocol (D-099):
112
+ // install the bridge once per process, before the db can run an elevation.
113
+ installSudoAuditBridge(loggingState.logging);
114
+
115
+ if (projectConfig === null) {
116
+ return {
117
+ db: null,
118
+ config: null,
119
+ warnings,
120
+ startedAt,
121
+ jobs: null,
122
+ tasks: null,
123
+ workflows: null,
124
+ storage: null,
125
+ ...loggingFields,
126
+ };
127
+ }
128
+
129
+ // Binary storage is independent of the database: a refused storage configuration is a
130
+ // warning and a null API, so the rest of the app keeps working (D-053).
131
+ const resolvedStorage = resolveStorage(projectConfig, process.env, projectRoot);
132
+ warnings.push(...resolvedStorage.warnings);
133
+ const storage = resolvedStorage.storage;
134
+
135
+ // The environment, not the config alone, decides where data lives (D-068): a deployment
136
+ // sets a Postgres URL and the same build runs there. Every refusal is a warning, so a
137
+ // misconfigured production boot degrades to "no database" instead of crashing.
138
+ const resolved = resolveDbTarget(projectConfig, process.env);
139
+ warnings.push(...resolved.warnings);
140
+ if (resolved.target === null) {
141
+ return {
142
+ db: null,
143
+ config: projectConfig,
144
+ warnings,
145
+ startedAt,
146
+ jobs: null,
147
+ tasks: null,
148
+ workflows: null,
149
+ storage,
150
+ ...loggingFields,
151
+ };
152
+ }
153
+ const target = resolved.target;
154
+ const usesPglite = target.driver === "pglite";
155
+
156
+ // Dev-only persistence (D-052): an in-memory PGlite cluster is restored from one snapshot
157
+ // file in the project. A postgres target has no snapshot to read, and must not restore one.
158
+ const devPersistenceEnabled = usesPglite && !isProductionEnvironment();
159
+ const snapshotPath = devDbSnapshotPath(projectRoot);
160
+ let snapshot: Uint8Array | null = null;
161
+ if (devPersistenceEnabled) {
162
+ try {
163
+ snapshot = await readDevDbSnapshot(snapshotPath);
164
+ } catch (error) {
165
+ warnings.push(
166
+ warning(
167
+ "db_snapshot_unreadable",
168
+ `Could not read the dev database snapshot: ${describe(error)}`,
169
+ ),
170
+ );
171
+ }
172
+ }
173
+
174
+ let db: FacilisDb;
175
+ try {
176
+ db = await createDb({
177
+ driver: target.driver,
178
+ url: target.url,
179
+ loadSnapshot: snapshot ?? undefined,
180
+ schema: dbSchema,
181
+ });
182
+ } catch (error) {
183
+ if (snapshot === null) {
184
+ warnings.push(warning("db_unavailable", `Could not open the database: ${describe(error)}`));
185
+ return {
186
+ db: null,
187
+ config: projectConfig,
188
+ warnings,
189
+ startedAt,
190
+ jobs: null,
191
+ tasks: null,
192
+ workflows: null,
193
+ storage,
194
+ ...loggingFields,
195
+ };
196
+ }
197
+ // A corrupt or incompatible snapshot must not make the project unbootable: warn and
198
+ // start from an empty cluster instead (the old file is replaced by the next dump).
199
+ // Only pglite ever reads a snapshot (see devPersistenceEnabled), so the retry keeps the
200
+ // resolved driver instead of hard-coding one.
201
+ warnings.push(
202
+ warning(
203
+ "db_snapshot_failed",
204
+ `Could not restore the dev database snapshot, starting empty: ${describe(error)}`,
205
+ ),
206
+ );
207
+ try {
208
+ db = await createDb({
209
+ driver: target.driver,
210
+ url: target.url,
211
+ schema: dbSchema,
212
+ });
213
+ } catch (retryError) {
214
+ warnings.push(
215
+ warning("db_unavailable", `Could not open the database: ${describe(retryError)}`),
216
+ );
217
+ return {
218
+ db: null,
219
+ config: projectConfig,
220
+ warnings,
221
+ startedAt,
222
+ jobs: null,
223
+ tasks: null,
224
+ workflows: null,
225
+ storage,
226
+ ...loggingFields,
227
+ };
228
+ }
229
+ }
230
+
231
+ // The dev bootstrap keeps a PGlite project self-contained: migrations -> seed -> app role
232
+ // (D-052). A real Postgres is provisioned out of band by the deploy step; the runtime may
233
+ // even connect as facilis_app, which can neither create roles nor run schema changes.
234
+ if (usesPglite) {
235
+ await bootstrapDevelopmentDatabase(db, projectConfig, warnings);
236
+ } else {
237
+ warnings.push(
238
+ warning(
239
+ "db_migrations_skipped",
240
+ "Postgres target: migrations, roles and views are provisioned by the deploy step, not at boot.",
241
+ ),
242
+ );
243
+ // Views are DDL like migrations: a restricted runtime role cannot create them, so the
244
+ // deploy step owns them and the boot only reports that it skipped the step.
245
+ if (dbViewModules.length > 0) {
246
+ warnings.push(
247
+ warning(
248
+ "view_ddl_skipped",
249
+ "Postgres target: SQL views are provisioned by the deploy step, not at boot.",
250
+ ),
251
+ );
252
+ }
253
+ }
254
+
255
+ if (devPersistenceEnabled) {
256
+ installDevDbSnapshotter({
257
+ db,
258
+ projectRoot,
259
+ snapshotPath,
260
+ onError: (error) => {
261
+ // One warning per process is enough: a full disk would otherwise flood the manifest.
262
+ if (!warnings.some((entry) => entry.code === "db_snapshot_write_failed")) {
263
+ warnings.push(
264
+ warning(
265
+ "db_snapshot_write_failed",
266
+ `Could not write the dev database snapshot: ${describe(error)}`,
267
+ ),
268
+ );
269
+ }
270
+ },
271
+ });
272
+ }
273
+
274
+ // The queue, manual tasks and workflows all run as facilis_app after the roles/views exist
275
+ // (D-107, D-135); a failure in any of them is a warning and a null service, not a 500.
276
+ const { jobs, tasks, workflows } = await bootRuntimes({
277
+ db,
278
+ tenantId: readDefaultTenantId(),
279
+ projectConfig,
280
+ jobModules,
281
+ workflowModules,
282
+ warnings,
283
+ });
284
+
285
+ return {
286
+ db,
287
+ config: projectConfig,
288
+ warnings,
289
+ startedAt,
290
+ jobs,
291
+ tasks,
292
+ workflows,
293
+ storage,
294
+ ...loggingFields,
295
+ };
296
+ }
297
+
298
+ function warning(code: string, message: string): ManifestWarning {
299
+ return { code, message };
300
+ }
@@ -0,0 +1,60 @@
1
+ import type { AuthConfig } from "@facilis.dev/auth";
2
+ import type { FacilisConfig } from "@facilis.dev/core";
3
+
4
+ export const DEFAULT_SESSION_DURATION_MS = 7 * 24 * 60 * 60 * 1000;
5
+ export const DEFAULT_MIGRATIONS_DIR = "db/migrations";
6
+ export const DEFAULT_LOCALE = "en";
7
+
8
+ /** Subset of FacilisConfig.auth that may be missing when the virtual module fell back. */
9
+ export interface AuthConfigLike {
10
+ permissions?: readonly string[];
11
+ roles?: Readonly<Record<string, readonly string[]>>;
12
+ defaultRole?: string;
13
+ sessionDurationMs?: number;
14
+ }
15
+
16
+ /**
17
+ * Normalise the project auth config into @facilis.dev/auth's AuthConfig. The config is
18
+ * validated by @facilis.dev/core at definition time; defaults here only cover the
19
+ * "config module missing/corrupt" bootstrap path so it degrades to a warning.
20
+ */
21
+ export function toAuthConfig(auth: AuthConfigLike | undefined): AuthConfig {
22
+ return {
23
+ permissions: auth?.permissions ?? [],
24
+ roles: auth?.roles ?? {},
25
+ defaultRole: auth?.defaultRole ?? "user",
26
+ sessionDurationMs: auth?.sessionDurationMs ?? DEFAULT_SESSION_DURATION_MS,
27
+ };
28
+ }
29
+
30
+ export function readMigrationsDir(config: FacilisConfig | null | undefined): string {
31
+ return config?.db?.migrationsDir ?? DEFAULT_MIGRATIONS_DIR;
32
+ }
33
+
34
+ export function readDefaultLocale(config: FacilisConfig | null | undefined): string {
35
+ return config?.i18n?.defaultLocale ?? DEFAULT_LOCALE;
36
+ }
37
+
38
+ /**
39
+ * Runtime guard for the virtual `#facilis/config` default export.
40
+ *
41
+ * The virtual module falls back to `{}` when the project has no config file, so the
42
+ * bootstrap must not trust the static type at the module boundary.
43
+ */
44
+ export function isFacilisConfig(value: unknown): value is FacilisConfig {
45
+ if (typeof value !== "object" || value === null) return false;
46
+ const candidate = value as Partial<FacilisConfig>;
47
+ const { auth, db, i18n } = candidate;
48
+ return (
49
+ typeof auth === "object" &&
50
+ auth !== null &&
51
+ Array.isArray(auth.permissions) &&
52
+ typeof auth.defaultRole === "string" &&
53
+ typeof auth.roles === "object" &&
54
+ auth.roles !== null &&
55
+ typeof db === "object" &&
56
+ db !== null &&
57
+ typeof i18n === "object" &&
58
+ i18n !== null
59
+ );
60
+ }
@@ -0,0 +1,107 @@
1
+ import type { RouteMetadata, RouteMetadataMap } from "../types.ts";
2
+
3
+ /**
4
+ * CORS policy for the runtime middleware (SPEC §8).
5
+ *
6
+ * Pure on purpose: it owns the OpenAPI-path matcher and the header/preflight decisions, so
7
+ * the middleware is only wiring and the rules stay unit-testable without virtual modules.
8
+ */
9
+
10
+ /** Compiled path templates, cached: every request would otherwise recompile the route table. */
11
+ const PATH_PATTERNS = new Map<string, RegExp>();
12
+
13
+ const PARAM_SEGMENT = /^\{[^}]+\}$/;
14
+ const CATCH_ALL_SEGMENT = /^\{\*[^}]+\}$/;
15
+ const ALLOW_METHODS = "GET,POST,PUT,PATCH,DELETE,OPTIONS";
16
+ // A browser preflight for a Bearer token asks for authorization: without it in the default
17
+ // allow-list a cross-site token request (v3a) would be blocked before reaching the route.
18
+ const DEFAULT_ALLOW_HEADERS = "content-type,authorization";
19
+ const PREFLIGHT_MAX_AGE = "600";
20
+
21
+ function escapeSegment(segment: string): string {
22
+ return segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
23
+ }
24
+
25
+ /** A {name} segment matches one segment, a {*rest} segment matches the remainder. */
26
+ function compilePattern(template: string): RegExp {
27
+ const cached = PATH_PATTERNS.get(template);
28
+ if (cached !== undefined) return cached;
29
+ const pattern = template
30
+ .split("/")
31
+ .map((segment) => {
32
+ if (CATCH_ALL_SEGMENT.test(segment)) return ".*";
33
+ if (PARAM_SEGMENT.test(segment)) return "[^/]+";
34
+ return escapeSegment(segment);
35
+ })
36
+ .join("/");
37
+ const compiled = new RegExp("^" + pattern + "$");
38
+ PATH_PATTERNS.set(template, compiled);
39
+ return compiled;
40
+ }
41
+
42
+ /** The route whose OpenAPI path template matches the request path and method, if any. */
43
+ export function matchRoute(
44
+ metadata: RouteMetadataMap,
45
+ pathname: string,
46
+ method: string,
47
+ ): RouteMetadata | undefined {
48
+ const normalizedMethod = method.toLowerCase();
49
+ for (const [template, operations] of Object.entries(metadata)) {
50
+ if (!compilePattern(template).test(pathname)) continue;
51
+ const route = operations[normalizedMethod];
52
+ if (route !== undefined) return route;
53
+ }
54
+ return undefined;
55
+ }
56
+
57
+ /**
58
+ * Headers for a non-preflight response. A crossSite route answers every origin with "*"
59
+ * and no credentials; a trusted origin gets an exact echo plus credentials. Nothing else
60
+ * may be exposed, so an untrusted origin receives no CORS header at all.
61
+ */
62
+ export function corsHeadersFor(
63
+ origin: string | null,
64
+ trusted: boolean,
65
+ route: RouteMetadata | undefined,
66
+ ): Headers {
67
+ const headers = new Headers();
68
+ if (route?.crossSite === true) {
69
+ headers.set("access-control-allow-origin", "*");
70
+ return headers;
71
+ }
72
+ if (!trusted || origin === null) return headers;
73
+ headers.set("access-control-allow-origin", origin);
74
+ headers.set("access-control-allow-credentials", "true");
75
+ headers.set("vary", "origin");
76
+ return headers;
77
+ }
78
+
79
+ /**
80
+ * Preflight answer, or null when the request is not a CORS preflight the policy allows.
81
+ *
82
+ * The caller gates on the OPTIONS method; this function only needs the headers, because a
83
+ * missing access-control-request-method is what distinguishes a plain OPTIONS request.
84
+ */
85
+ export function preflightResponse(
86
+ metadata: RouteMetadataMap,
87
+ pathname: string,
88
+ requestHeaders: Headers,
89
+ trustedOrigins: readonly string[],
90
+ ): Response | null {
91
+ const requestedMethod = requestHeaders.get("access-control-request-method");
92
+ if (requestedMethod === null) return null;
93
+
94
+ const origin = requestHeaders.get("origin");
95
+ const trusted = origin !== null && trustedOrigins.includes(origin);
96
+ const route = matchRoute(metadata, pathname, requestedMethod);
97
+ const headers = corsHeadersFor(origin, trusted, route);
98
+ if (!headers.has("access-control-allow-origin")) return null;
99
+
100
+ headers.set("access-control-allow-methods", ALLOW_METHODS);
101
+ headers.set(
102
+ "access-control-allow-headers",
103
+ requestHeaders.get("access-control-request-headers") ?? DEFAULT_ALLOW_HEADERS,
104
+ );
105
+ headers.set("access-control-max-age", PREFLIGHT_MAX_AGE);
106
+ return new Response(null, { status: 204, headers });
107
+ }
@@ -0,0 +1,99 @@
1
+ import { readdir } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+
4
+ import { applyStatements, applyViews, ensureAppRole, type FacilisDb } from "@facilis.dev/db";
5
+ import { seedStatements } from "@facilis.dev/auth";
6
+ import type { FacilisConfig, ManifestWarning } from "@facilis.dev/core";
7
+ import { projectRoot } from "#facilis/config";
8
+ import dbViewModules from "#facilis/db-views";
9
+
10
+ import { readMigrationsDir, toAuthConfig } from "./config.ts";
11
+ import { readTextFile } from "./project-files.ts";
12
+ import { splitSqlStatements } from "./sql.ts";
13
+ import { provisionSystemRole } from "./system-role.ts";
14
+
15
+ /**
16
+ * Dev-only database bootstrap: migrations -> seed -> app role -> system role -> views
17
+ * (D-052/D-097/D-099). Split from `bootstrap.ts` to keep both modules under the file-length
18
+ * limit; a Postgres target skips this module entirely, because the deploy step owns DDL.
19
+ */
20
+ export async function bootstrapDevelopmentDatabase(
21
+ db: FacilisDb,
22
+ projectConfig: FacilisConfig,
23
+ warnings: ManifestWarning[],
24
+ ): Promise<void> {
25
+ // Order mandated by the Lead: migrations -> seed (roles/role_permissions) -> app role.
26
+ try {
27
+ const statements = await readMigrationStatements(projectConfig);
28
+ if (statements.length > 0) await applyStatements(db, statements);
29
+ } catch (error) {
30
+ warnings.push(warning("migration_failed", `Migrations failed: ${describe(error)}`));
31
+ }
32
+
33
+ try {
34
+ await applyStatements(db, seedStatements(toAuthConfig(projectConfig.auth)));
35
+ } catch (error) {
36
+ warnings.push(warning("seed_failed", `Seeding roles/permissions failed: ${describe(error)}`));
37
+ }
38
+
39
+ try {
40
+ await ensureAppRole(db);
41
+ } catch (error) {
42
+ warnings.push(
43
+ warning("app_role_failed", `Could not provision the app role: ${describe(error)}`),
44
+ );
45
+ }
46
+
47
+ // D-099: the system role is the sudo identity; provision it after the app role so the
48
+ // membership grant can reference it.
49
+ await provisionSystemRole(db, warnings);
50
+
51
+ // Views are code (D-097): create/replace them after the app role exists, because the
52
+ // security_invoker view must be granted to that role. A broken view is a warning, never a
53
+ // failed boot, and the endpoint returns the same failures on demand.
54
+ if (dbViewModules.length === 0) return;
55
+ try {
56
+ const applied = await applyViews(db, dbViewModules, {
57
+ permissions: projectConfig.auth.permissions,
58
+ });
59
+ for (const failure of applied.failed) {
60
+ warnings.push(
61
+ warning("view_failed", `View "${failure.name}" could not be created: ${failure.error}`),
62
+ );
63
+ }
64
+ } catch (error) {
65
+ warnings.push(warning("view_failed", `Views could not be applied: ${describe(error)}`));
66
+ }
67
+ }
68
+
69
+ async function readMigrationStatements(projectConfig: FacilisConfig): Promise<string[]> {
70
+ const dir = join(projectRoot, readMigrationsDir(projectConfig));
71
+ let entries: string[];
72
+ try {
73
+ entries = await readdir(dir);
74
+ } catch (error) {
75
+ // No migrations directory is a valid early-project state.
76
+ if (isMissingFileError(error)) return [];
77
+ throw error;
78
+ }
79
+
80
+ const names = entries.filter((name) => name.endsWith(".sql")).toSorted();
81
+ const contents = await Promise.all(names.map((name) => readTextFile(join(dir, name))));
82
+ const statements: string[] = [];
83
+ for (const source of contents) {
84
+ if (source !== null) statements.push(...splitSqlStatements(source));
85
+ }
86
+ return statements;
87
+ }
88
+
89
+ function warning(code: string, message: string): ManifestWarning {
90
+ return { code, message };
91
+ }
92
+
93
+ function isMissingFileError(error: unknown): boolean {
94
+ return (error as NodeJS.ErrnoException | null)?.code === "ENOENT";
95
+ }
96
+
97
+ export function describe(error: unknown): string {
98
+ return error instanceof Error ? error.message : String(error);
99
+ }