@fougere/core 0.3.0-alpha.0 → 0.5.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (243) hide show
  1. package/README.md +1 -1
  2. package/dist/boot/Emissions.js +1 -1
  3. package/dist/boot/Emissions.js.map +1 -1
  4. package/dist/boot/HandlerFacade.js +2 -2
  5. package/dist/boot/HandlerFacade.js.map +1 -1
  6. package/dist/boot/apply.d.ts.map +1 -1
  7. package/dist/boot/apply.js +2 -12
  8. package/dist/boot/apply.js.map +1 -1
  9. package/dist/boot/binding.d.ts +1 -1
  10. package/dist/boot/binding.d.ts.map +1 -1
  11. package/dist/boot/binding.js +4 -4
  12. package/dist/boot/binding.js.map +1 -1
  13. package/dist/boot/boot.d.ts +1 -1
  14. package/dist/boot/boot.d.ts.map +1 -1
  15. package/dist/boot/bootstrap.d.ts.map +1 -1
  16. package/dist/boot/bootstrap.js +26 -17
  17. package/dist/boot/bootstrap.js.map +1 -1
  18. package/dist/boot/frame.d.ts +1 -1
  19. package/dist/boot/frame.d.ts.map +1 -1
  20. package/dist/boot/frame.js +5 -14
  21. package/dist/boot/frame.js.map +1 -1
  22. package/dist/boot/hosted.d.ts +29 -0
  23. package/dist/boot/hosted.d.ts.map +1 -0
  24. package/dist/boot/hosted.js +38 -0
  25. package/dist/boot/hosted.js.map +1 -0
  26. package/dist/boot/ownership.d.ts +0 -3
  27. package/dist/boot/ownership.d.ts.map +1 -1
  28. package/dist/boot/ownership.js +5 -5
  29. package/dist/boot/ownership.js.map +1 -1
  30. package/dist/boot/remote.d.ts +1 -1
  31. package/dist/boot/remote.d.ts.map +1 -1
  32. package/dist/boot/remote.js +3 -3
  33. package/dist/boot/remote.js.map +1 -1
  34. package/dist/boot/statement-drift.d.ts +24 -0
  35. package/dist/boot/statement-drift.d.ts.map +1 -0
  36. package/dist/boot/statement-drift.js +38 -0
  37. package/dist/boot/statement-drift.js.map +1 -0
  38. package/dist/boot/together.d.ts.map +1 -1
  39. package/dist/boot/together.js +6 -6
  40. package/dist/boot/together.js.map +1 -1
  41. package/dist/boot/types.d.ts +17 -4
  42. package/dist/boot/types.d.ts.map +1 -1
  43. package/dist/contract/CallLog.d.ts +57 -0
  44. package/dist/contract/CallLog.d.ts.map +1 -0
  45. package/dist/contract/CallLog.js +2 -0
  46. package/dist/contract/CallLog.js.map +1 -0
  47. package/dist/contract.d.ts +9 -4
  48. package/dist/contract.d.ts.map +1 -1
  49. package/dist/contract.js +12 -5
  50. package/dist/contract.js.map +1 -1
  51. package/dist/dispatch/DispatchLifecycle.d.ts +9 -1
  52. package/dist/dispatch/DispatchLifecycle.d.ts.map +1 -1
  53. package/dist/dispatch/DispatchLifecycle.js +17 -2
  54. package/dist/dispatch/DispatchLifecycle.js.map +1 -1
  55. package/dist/dispatch/InFlight.d.ts +0 -1
  56. package/dist/dispatch/InFlight.d.ts.map +1 -1
  57. package/dist/dispatch/InFlight.js +0 -3
  58. package/dist/dispatch/InFlight.js.map +1 -1
  59. package/dist/dispatch/InputValidator.d.ts.map +1 -1
  60. package/dist/dispatch/InputValidator.js +3 -2
  61. package/dist/dispatch/InputValidator.js.map +1 -1
  62. package/dist/dispatch/OutputProjector.js +2 -2
  63. package/dist/dispatch/OutputProjector.js.map +1 -1
  64. package/dist/dispatch/StorageGuard.d.ts.map +1 -1
  65. package/dist/dispatch/StorageGuard.js +2 -2
  66. package/dist/dispatch/StorageGuard.js.map +1 -1
  67. package/dist/effective-operation.d.ts.map +1 -1
  68. package/dist/effective-operation.js +8 -5
  69. package/dist/effective-operation.js.map +1 -1
  70. package/dist/emit.d.ts +2 -2
  71. package/dist/emit.d.ts.map +1 -1
  72. package/dist/emit.js +2 -2
  73. package/dist/emit.js.map +1 -1
  74. package/dist/identity.js +1 -1
  75. package/dist/identity.js.map +1 -1
  76. package/dist/imports.d.ts +1 -1
  77. package/dist/imports.d.ts.map +1 -1
  78. package/dist/imports.js.map +1 -1
  79. package/dist/index.d.ts +8 -2
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +12 -1
  82. package/dist/index.js.map +1 -1
  83. package/dist/node.d.ts +2 -0
  84. package/dist/node.d.ts.map +1 -1
  85. package/dist/node.js +2 -0
  86. package/dist/node.js.map +1 -1
  87. package/dist/orm.d.ts.map +1 -1
  88. package/dist/orm.js +4 -4
  89. package/dist/orm.js.map +1 -1
  90. package/dist/prefab/collector.js +2 -2
  91. package/dist/prefab/collector.js.map +1 -1
  92. package/dist/prefab/mirror.d.ts.map +1 -1
  93. package/dist/prefab/mirror.js +2 -2
  94. package/dist/prefab/mirror.js.map +1 -1
  95. package/dist/prefab/presenter.d.ts.map +1 -1
  96. package/dist/prefab/presenter.js +2 -2
  97. package/dist/prefab/presenter.js.map +1 -1
  98. package/dist/prefab/repository.d.ts.map +1 -1
  99. package/dist/prefab/repository.js +2 -2
  100. package/dist/prefab/repository.js.map +1 -1
  101. package/dist/scan/bundling.d.ts +14 -0
  102. package/dist/scan/bundling.d.ts.map +1 -0
  103. package/dist/scan/bundling.js +26 -0
  104. package/dist/scan/bundling.js.map +1 -0
  105. package/dist/scan/declare.d.ts +71 -0
  106. package/dist/scan/declare.d.ts.map +1 -0
  107. package/dist/scan/declare.js +125 -0
  108. package/dist/scan/declare.js.map +1 -0
  109. package/dist/scan/emit.d.ts.map +1 -1
  110. package/dist/scan/emit.js +3 -2
  111. package/dist/scan/emit.js.map +1 -1
  112. package/dist/scan/handler-parser.d.ts +2 -0
  113. package/dist/scan/handler-parser.d.ts.map +1 -1
  114. package/dist/scan/handler-parser.js +52 -13
  115. package/dist/scan/handler-parser.js.map +1 -1
  116. package/dist/scan/scanner.d.ts.map +1 -1
  117. package/dist/scan/scanner.js +37 -11
  118. package/dist/scan/scanner.js.map +1 -1
  119. package/dist/scan/statement.d.ts +4 -0
  120. package/dist/scan/statement.d.ts.map +1 -0
  121. package/dist/scan/statement.js +112 -0
  122. package/dist/scan/statement.js.map +1 -0
  123. package/dist/verify.js +2 -2
  124. package/dist/verify.js.map +1 -1
  125. package/dist/wire/call.d.ts +19 -8
  126. package/dist/wire/call.d.ts.map +1 -1
  127. package/dist/wire/call.js +17 -6
  128. package/dist/wire/call.js.map +1 -1
  129. package/dist/wire/drift.d.ts +55 -0
  130. package/dist/wire/drift.d.ts.map +1 -0
  131. package/dist/wire/drift.js +121 -0
  132. package/dist/wire/drift.js.map +1 -0
  133. package/dist/wire/middleware.d.ts +1 -1
  134. package/dist/wire/middleware.d.ts.map +1 -1
  135. package/package.json +6 -4
  136. package/src/boot/AppLifecycle.ts +50 -0
  137. package/src/boot/Emissions.ts +263 -0
  138. package/src/boot/HandlerFacade.ts +242 -0
  139. package/src/boot/ambient-port.ts +41 -0
  140. package/src/boot/ambient.als.ts +43 -0
  141. package/src/boot/ambient.queue.ts +75 -0
  142. package/src/boot/apply.ts +47 -0
  143. package/src/boot/auth.ts +55 -0
  144. package/src/boot/binding.ts +182 -0
  145. package/src/boot/boot.ts +125 -0
  146. package/src/boot/bootstrap.ts +847 -0
  147. package/src/boot/frame.ts +210 -0
  148. package/src/boot/hosted.ts +77 -0
  149. package/src/boot/ownership.ts +137 -0
  150. package/src/boot/ports.ts +66 -0
  151. package/src/boot/remote.ts +179 -0
  152. package/src/boot/seed.ts +158 -0
  153. package/src/boot/statement-drift.ts +60 -0
  154. package/src/boot/together.ts +215 -0
  155. package/src/boot/types.ts +274 -0
  156. package/src/builtins/config.ts +19 -0
  157. package/src/builtins/logger.ts +175 -0
  158. package/src/config-loader.ts +146 -0
  159. package/src/contract/Call.ts +18 -0
  160. package/src/contract/CallLog.ts +55 -0
  161. package/src/contract/Invocation.ts +72 -0
  162. package/src/contract/RouteAddress.ts +49 -0
  163. package/src/contract.ts +83 -0
  164. package/src/crypto/encoding.ts +59 -0
  165. package/src/crypto/node.ts +30 -0
  166. package/src/crypto/port.ts +45 -0
  167. package/src/crypto/webcrypto.ts +55 -0
  168. package/src/define.ts +10 -0
  169. package/src/dispatch/ArgumentResolver.ts +17 -0
  170. package/src/dispatch/ArrayResult.ts +10 -0
  171. package/src/dispatch/DispatchEvent.ts +38 -0
  172. package/src/dispatch/DispatchLifecycle.ts +43 -0
  173. package/src/dispatch/DispatchPort.ts +6 -0
  174. package/src/dispatch/Dispatcher.ts +48 -0
  175. package/src/dispatch/InFlight.ts +45 -0
  176. package/src/dispatch/InputValidator.ts +28 -0
  177. package/src/dispatch/LocalRoutePolicy.ts +34 -0
  178. package/src/dispatch/OperationExecutor.ts +60 -0
  179. package/src/dispatch/OperationRoute.ts +18 -0
  180. package/src/dispatch/OutputProjector.ts +32 -0
  181. package/src/dispatch/OutputView.ts +9 -0
  182. package/src/dispatch/PresenterArgumentResolver.ts +25 -0
  183. package/src/dispatch/PresenterExecutor.ts +55 -0
  184. package/src/dispatch/RemoteRouteResolver.ts +21 -0
  185. package/src/dispatch/Route.ts +11 -0
  186. package/src/dispatch/RouteNotFoundError.ts +29 -0
  187. package/src/dispatch/RoutePolicy.ts +8 -0
  188. package/src/dispatch/RouteRegistry.ts +73 -0
  189. package/src/dispatch/RouteResolver.ts +7 -0
  190. package/src/dispatch/StorageGuard.ts +71 -0
  191. package/src/effective-operation.ts +601 -0
  192. package/src/emit.ts +90 -0
  193. package/src/entry/DynamicFacade.ts +28 -0
  194. package/src/entry/FacadeEntry.ts +32 -0
  195. package/src/entry/TransportEntry.ts +30 -0
  196. package/src/frond-config.ts +138 -0
  197. package/src/graph.ts +180 -0
  198. package/src/identity-keys.ts +43 -0
  199. package/src/identity.ts +235 -0
  200. package/src/imports.ts +123 -0
  201. package/src/index.ts +120 -0
  202. package/src/loader.ts +41 -0
  203. package/src/node.ts +30 -0
  204. package/src/orm.ts +252 -0
  205. package/src/prefab/collector.ts +36 -0
  206. package/src/prefab/crud.ts +188 -0
  207. package/src/prefab/mirror.ts +122 -0
  208. package/src/prefab/prefab.ts +46 -0
  209. package/src/prefab/presenter.ts +63 -0
  210. package/src/prefab/repository.ts +170 -0
  211. package/src/scan/Fronds.ts +73 -0
  212. package/src/scan/bundling.ts +25 -0
  213. package/src/scan/conventions.ts +122 -0
  214. package/src/scan/declare.ts +188 -0
  215. package/src/scan/emit.ts +231 -0
  216. package/src/scan/frond.ts +235 -0
  217. package/src/scan/handler-parser.ts +817 -0
  218. package/src/scan/scanner.ts +757 -0
  219. package/src/scan/statement.ts +126 -0
  220. package/src/verify.ts +193 -0
  221. package/src/wire/call.ts +381 -0
  222. package/src/wire/drift.ts +131 -0
  223. package/src/wire/errors.ts +124 -0
  224. package/src/wire/http-error.ts +77 -0
  225. package/src/wire/loggerMiddleware.ts +29 -0
  226. package/src/wire/middleware.ts +47 -0
  227. package/src/wire/operation.ts +258 -0
  228. package/dist/boot/Lifecycle.d.ts +0 -4
  229. package/dist/boot/Lifecycle.d.ts.map +0 -1
  230. package/dist/boot/Lifecycle.js +0 -3
  231. package/dist/boot/Lifecycle.js.map +0 -1
  232. package/dist/boot/egress.d.ts +0 -8
  233. package/dist/boot/egress.d.ts.map +0 -1
  234. package/dist/boot/egress.js +0 -11
  235. package/dist/boot/egress.js.map +0 -1
  236. package/dist/scan/scan-cache.d.ts +0 -16
  237. package/dist/scan/scan-cache.d.ts.map +0 -1
  238. package/dist/scan/scan-cache.js +0 -99
  239. package/dist/scan/scan-cache.js.map +0 -1
  240. package/dist/wire/invocation.d.ts +0 -4
  241. package/dist/wire/invocation.d.ts.map +0 -1
  242. package/dist/wire/invocation.js +0 -3
  243. package/dist/wire/invocation.js.map +0 -1
@@ -0,0 +1,158 @@
1
+ import { Role } from '@fougere/schema';
2
+ import { facadeKeyOf } from '../wire/call.js';
3
+ import type { FrondDescriptor, SeedEntry, SeedFactory } from '../scan/frond.js';
4
+ import type { App } from './types.js';
5
+ import type { Extension } from './AppLifecycle.js';
6
+
7
+ /**
8
+ * Seeds in dependency order — a `ref()` target is planted before its referrer.
9
+ *
10
+ * The order is a fact about the entity graph, not about the surface running the seeds,
11
+ * so it is stated once here. The Nuxt module read it off a pairwise comparator (which
12
+ * `Array.sort` cannot make transitive: `a` before `b` and `b` before `c` never implies
13
+ * `a` before `c`), and `boot()` had no order at all — the same fact, told twice and
14
+ * wrong both times. A list seeded before its owner failed on the foreign key, and the
15
+ * driver's error named neither the entity nor the file.
16
+ *
17
+ * Kahn, like `orderTables` in `@fougere/adapter-sql` — the same shape one level up: there
18
+ * the nodes are tables and the edges FK columns, here they are seeds and the edges the
19
+ * `one` relations of the entities they target. A cycle cannot be satisfied by ordering,
20
+ * so its remaining seeds keep their scan order and land last: the driver refuses what is
21
+ * genuinely impossible, and everything acyclic around it still gets planted.
22
+ */
23
+ export function orderSeeds(fronds: FrondDescriptor[]): SeedEntry[] {
24
+ const refs = new Map<string, Set<string>>();
25
+ for (const frond of fronds) {
26
+ for (const entity of frond.entities) {
27
+ const targets = new Set<string>();
28
+ for (const field of Object.values(entity.entityClass.getFields())) {
29
+ if (!Role.of(field).isReference) continue;
30
+ const target = (Role.of(field).target as { name?: string }).name?.toLowerCase();
31
+ if (target && target !== entity.name.toLowerCase()) targets.add(target);
32
+ }
33
+ refs.set(entity.name.toLowerCase(), targets);
34
+ }
35
+ }
36
+
37
+ const seeds = fronds.flatMap((frond) => frond.seeds);
38
+ const seeded = new Set(seeds.map((seed) => seed.entityName.toLowerCase()));
39
+
40
+ // Only what is actually seeded can be waited for: a relation to an entity with no seed
41
+ // is already satisfied by whatever put its rows there.
42
+ const waiting = new Map(
43
+ seeds.map((seed) => {
44
+ const own = seed.entityName.toLowerCase();
45
+ const targets = [...(refs.get(own) ?? [])].filter((target) => seeded.has(target) && target !== own);
46
+
47
+ return [seed, new Set(targets)] as const;
48
+ }),
49
+ );
50
+
51
+ const ordered: SeedEntry[] = [];
52
+ const planted = new Set<string>();
53
+
54
+ while (waiting.size > 0) {
55
+ const ready = [...waiting.keys()].find((seed) => [...waiting.get(seed)!].every((dep) => planted.has(dep)));
56
+ if (!ready) break;
57
+
58
+ ordered.push(ready);
59
+ planted.add(ready.entityName.toLowerCase());
60
+ waiting.delete(ready);
61
+ }
62
+
63
+ return [...ordered, ...waiting.keys()];
64
+ }
65
+
66
+ /** Where a seed writes, and what it may skip — resolved per entity. */
67
+ interface SeedDoor {
68
+ list(): Promise<unknown[]>;
69
+ write(item: unknown): Promise<unknown>;
70
+ }
71
+
72
+ /**
73
+ * Plant a set of seeds, in the order given. Reports what it did, one line per entity.
74
+ *
75
+ * The one seeding loop. `boot()` had one and the Nuxt module generated a second into its
76
+ * Nitro plugin, which had drifted: no ORM fallback, so an entity with no façade was
77
+ * skipped there and planted here. Two answers to "how does a row get in at boot" is one
78
+ * too many, and the second was the one running in the browser.
79
+ */
80
+ export async function runSeeds(
81
+ app: App,
82
+ seeds: SeedEntry[],
83
+ report: (message: string) => void = () => {},
84
+ ): Promise<void> {
85
+ for (const seed of seeds) {
86
+ const resolve = <T>(name: string) => app.resolve<T>(name + 'Handler');
87
+ const data = typeof seed.data === 'function' ? await (seed.data as SeedFactory)(resolve) : seed.data;
88
+
89
+ const door = doorFor(app, seed.entityName);
90
+ if (!door) {
91
+ report(` ${seed.entityName}: no handler façade nor ORM — skipping seed`);
92
+ continue;
93
+ }
94
+
95
+ const existing = await door.list();
96
+ if (existing.length > 0) {
97
+ report(` ${seed.entityName}: skipped (${existing.length} exist)`);
98
+ continue;
99
+ }
100
+
101
+ // The driver's error alone names neither the entity nor the row — and a foreign
102
+ // key is exactly what a seed gets wrong.
103
+ for (const item of data) {
104
+ try {
105
+ await door.write(item);
106
+ } catch (cause) {
107
+ throw new Error(
108
+ `Seed '${seed.entityName}' failed on ${JSON.stringify(item)}: ${(cause as Error)?.message ?? cause}`,
109
+ { cause },
110
+ );
111
+ }
112
+ }
113
+ report(` ${seed.entityName}: ${data.length} records`);
114
+ }
115
+ }
116
+
117
+ /**
118
+ * A seed is not a client: it writes at boot, from inside. The façade is used when the
119
+ * entity declares one (its judge catches a bad seed early), the storage when it does
120
+ * not — an entity that exposes nothing is still an entity whose reference rows must land.
121
+ */
122
+ function doorFor(app: App, entityName: string): SeedDoor | undefined {
123
+ let handler: Record<string, Function> | undefined;
124
+ try { handler = app.resolve<Record<string, Function>>(facadeKeyOf(entityName)); } catch {}
125
+
126
+ if (typeof handler?.list === 'function' && typeof handler.create === 'function') {
127
+ return {
128
+ list: () => handler!.list() as Promise<unknown[]>,
129
+ write: (item) => handler!.create({ params: {}, query: {}, body: item, state: {} }),
130
+ };
131
+ }
132
+
133
+ const orm = app.ormFor(entityName) as
134
+ | { list: () => Promise<unknown[]>; create: (input: unknown) => Promise<unknown> }
135
+ | undefined;
136
+ if (!orm) return undefined;
137
+
138
+ return { list: () => orm.list(), write: (item) => orm.create(item) };
139
+ }
140
+
141
+ /**
142
+ * The framework's own ascent for rows, named — so a host can REPLACE it rather than take
143
+ * over the whole post-boot to get its own.
144
+ *
145
+ * That is what Nuxt's Nitro plugin had to do: a bundler needs its seed modules spelled out
146
+ * as static imports, so the plugin claimed everything after the boot and its copy of the
147
+ * loop drifted. It now declares an extension under this same name instead, and the delta
148
+ * is one member of a list.
149
+ */
150
+ export function seeding(report?: (message: string) => void): Extension {
151
+ return {
152
+ name: 'seeds',
153
+ up: async (app: App) => {
154
+ const seeds = orderSeeds(app.fronds);
155
+ if (seeds.length > 0) await runSeeds(app, seeds, report);
156
+ },
157
+ };
158
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Where a STATED contract and the signature it is about have stopped agreeing.
3
+ *
4
+ * `frond.config.ts` states an operation's contract and wins over the scan — that order is
5
+ * deliberate, and it is the only answer for a method inherited from an installed base class
6
+ * the workspace scan cannot see. But winning silently is how a statement made about
7
+ * `publish(id: string)` keeps applying after the parameter was renamed to `postId`: the
8
+ * façade binds what the config said, the method receives `undefined`, and nothing anywhere
9
+ * says the two disagree.
10
+ *
11
+ * So this compares, and only where BOTH exist — a statement about a signature the scan
12
+ * never read is not drift, it is the case config was built for. It is a `warning` and not
13
+ * a refusal: the statement is still the author's word, and a boot that ran yesterday must
14
+ * not stop running because a parameter moved. What it must not do is stay quiet.
15
+ */
16
+ import type { FrondDescriptor, HandlerEntry, ScanDiagnostic } from '../scan/frond.js';
17
+ import type { BindingPlan } from './binding.js';
18
+ import type { ParsedMethod } from '../scan/handler-parser.js';
19
+
20
+ /** The parameters a stated binding names, against the ones the method declares. */
21
+ function namesDisagreeing(stated: BindingPlan, signature: ParsedMethod): string[] {
22
+ const declared = new Set(signature.params.map((p: { name: string }) => p.name));
23
+
24
+ return stated.map((b) => b.name).filter((name) => !declared.has(name));
25
+ }
26
+
27
+ /**
28
+ * What a frond's stated contracts no longer match.
29
+ *
30
+ * Read by `resolveEffectiveOperations`, so the same answer reaches `fougere check` and a
31
+ * boot — one comparison, two readers, no second opinion to drift on its own.
32
+ */
33
+ export function statementDrift(frond: FrondDescriptor, handler: HandlerEntry): ScanDiagnostic[] {
34
+ const found: ScanDiagnostic[] = [];
35
+
36
+ for (const [name, override] of Object.entries(frond.operationsOverrides ?? {})) {
37
+ if (!override.binding) continue;
38
+
39
+ // The scan's own reading of this method. Absent means config is stating what nothing
40
+ // read — an installed base class, a handler outside the workspace — which is legal.
41
+ const signature = handler.operations.get(name)?.signature;
42
+ if (!signature) continue;
43
+
44
+ const orphans = namesDisagreeing(override.binding, signature);
45
+ if (orphans.length === 0) continue;
46
+
47
+ found.push({
48
+ severity: 'warning',
49
+ code: 'stated-binding-drifted',
50
+ filePath: handler.filePath,
51
+ frond: frond.name,
52
+ subject: `${handler.ctor.name}.${name}`,
53
+ message: `frond.config.ts binds ${orphans.map((o) => `\`${o}\``).join(', ')} on `
54
+ + `${handler.ctor.name}.${name}, which declares (${signature.params.map((p: { name: string }) => p.name).join(', ')}). `
55
+ + `The statement wins, so those parameters receive nothing.`,
56
+ });
57
+ }
58
+
59
+ return found;
60
+ }
@@ -0,0 +1,215 @@
1
+ /**
2
+ * Building a frame — what a handler asking for `Together<[…]>` receives.
3
+ *
4
+ * The declaration names its members and nothing else; where they live, and therefore
5
+ * which of the two realizations they get, is read HERE and stated at boot. A frame whose
6
+ * members share an engine is a transaction; one whose members are split replays its own
7
+ * inverses (`frame.ts`). Same user code, two guarantees, and the boot says which — the
8
+ * one thing a gradient must never leave to assumption.
9
+ */
10
+ import { ambient } from '#ambient';
11
+ import { upperFirst, lowerFirst, type SchemaView } from '@fougere/schema';
12
+ import type { Container } from '@fougere/container';
13
+ import { membersOfTogetherKey, ormKeyOf, type EntityOrm, type OrmFactory } from '../orm.js';
14
+ import type { Logger } from '../builtins/logger.js';
15
+ import type { ProviderEntry } from '../scan/frond.js';
16
+ import { StorageGuard } from '../dispatch/StorageGuard.js';
17
+ import { recording, unwind, type Undo } from './frame.js';
18
+
19
+ /** Everything the boot knows that a frame needs, gathered once for every frond. */
20
+ export interface FrameWorld {
21
+ /** Every entity of every frond, by registration key. A frame crosses fronds by design. */
22
+ entityByName: Map<string, SchemaView>;
23
+ /** Which frond holds an entity — the question `remotes:` turns into a refusal. */
24
+ frondOf: Map<string, string>;
25
+ hostedHere: (frond: string) => boolean;
26
+ ormFactory?: OrmFactory;
27
+ sourceOf?: (entityName: string) => string;
28
+ transacted?: <R>(source: string, fn: (ormFactory: OrmFactory) => Promise<R>) => Promise<R>;
29
+ log: Logger;
30
+ }
31
+
32
+ /** An entity the block writes through, and a provider rebuilt so that its writes count too. */
33
+ interface Members {
34
+ entities: { name: string; schema: SchemaView }[];
35
+ providers: ProviderEntry[];
36
+ }
37
+
38
+ /**
39
+ * Each declared name, resolved to what it designates.
40
+ *
41
+ * A name that resolves to nothing is refused rather than skipped: `Together<[Account,
42
+ * Ledgre]>` is a typo whose only other symptom is a frame quietly one member short. The
43
+ * two lists are checked against different registries, which is exactly why the declaration
44
+ * separates them — nothing here has to guess what kind a name is.
45
+ */
46
+ function resolve(names: { entities: string[]; providers: string[] }, declared: readonly ProviderEntry[], world: FrameWorld): Members {
47
+ const entities = names.entities.map((member) => {
48
+ const name = lowerFirst(member);
49
+ const schema = world.entityByName.get(name);
50
+ if (!schema) {
51
+ throw new Error(
52
+ `Together<[…${member}…]>: no entity named '${member}' is scanned in this app. ` +
53
+ `The first list names entities; a class of this frond goes in the second.`,
54
+ );
55
+ }
56
+ return { name, schema };
57
+ });
58
+
59
+ const providers = names.providers.map((member) => {
60
+ const entry = declared.find((provider) => provider.ctor.name === member);
61
+ if (!entry) {
62
+ throw new Error(
63
+ `Together<[…], [… ${member} …]>: this frond declares no class named '${member}'. ` +
64
+ `The second list names providers to rebuild inside the frame — a service, a mirror, ` +
65
+ `a repository — so that what they write is covered by the unwind.`,
66
+ );
67
+ }
68
+ return entry;
69
+ });
70
+
71
+ return { entities, providers };
72
+ }
73
+
74
+ /**
75
+ * A member that cannot write here at all — its frond is hosted elsewhere.
76
+ *
77
+ * Refused rather than compensated: a compensated frame still writes through a local ORM,
78
+ * and a remote frond registers none. There is nothing to record and nothing to undo.
79
+ */
80
+ function refuseRemote(members: Members, world: FrameWorld, key: string): void {
81
+ for (const member of members.entities) {
82
+ const frond = world.frondOf.get(member.name);
83
+ if (frond && !world.hostedHere(frond)) {
84
+ throw new Error(
85
+ `Together<[…]> (${key}): '${member.name}' belongs to frond '${frond}', which this ` +
86
+ `process declares in remotes: — it registers no storage here, so its writes cannot be ` +
87
+ `part of a frame. Host the frond here, or split the work and join the halves with a fact.`,
88
+ );
89
+ }
90
+ }
91
+ }
92
+
93
+ /**
94
+ * A provider member writing an entity the frame does not name.
95
+ *
96
+ * The frame does not widen itself to cover it: doing so would pull an entity from another
97
+ * source into the group without anyone writing it down. Named instead, with the one-word fix.
98
+ */
99
+ function refuseUncoveredWrites(members: Members, key: string): void {
100
+ const covered = new Set(members.entities.map((member) => member.name));
101
+ for (const provider of members.providers) {
102
+ for (const dep of provider.deps) {
103
+ if (!dep.endsWith('Orm')) continue;
104
+ const entity = lowerFirst(dep.slice(0, -'Orm'.length));
105
+ if (covered.has(entity)) continue;
106
+ throw new Error(
107
+ `Together<[…]> (${key}): ${provider.ctor.name} writes ${entity}, which is not in the ` +
108
+ `frame's entity list — its writes would escape the unwind. Add it: ` +
109
+ `Together<[…, ${upperFirst(entity)}], [… ${provider.ctor.name} …]>.`,
110
+ );
111
+ }
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Open the block: build every member over `factory`, in a scope of their own.
117
+ *
118
+ * The scope is what makes a provider member work without a locator — its ORM keys are
119
+ * registered here, so the container hands it the framed ones through the ordinary
120
+ * constructor. It is disposed when the block ends, whichever way it ended.
121
+ */
122
+ async function inScope<R>(
123
+ parent: Container,
124
+ members: Members,
125
+ factory: OrmFactory,
126
+ wrap: (orm: EntityOrm, name: string, schema: SchemaView) => EntityOrm,
127
+ fn: (entities: unknown[], providers: unknown[]) => Promise<R>,
128
+ ): Promise<R> {
129
+ const scope = parent.createScope();
130
+ try {
131
+ const orms = members.entities.map((member) => {
132
+ const orm = wrap(factory(member.schema, member.name), member.name, member.schema);
133
+ scope.registerValue(ormKeyOf(member.name), orm);
134
+ return orm;
135
+ });
136
+ // Providers after every ORM is in place: one may depend on another member's.
137
+ const built = members.providers.map((provider) => {
138
+ scope.register(provider.ctor.name, provider.ctor, { deps: provider.deps });
139
+ return scope.resolve(provider.ctor.name);
140
+ });
141
+ return await fn(orms, built);
142
+ } finally {
143
+ await scope.dispose();
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Register one frame per key a handler or provider of this frond asked for.
149
+ *
150
+ * Called with the frond's scope, because that is where the asking constructor resolves —
151
+ * while the MEMBERS are looked up app-wide, a frame crossing fronds being the ordinary case
152
+ * rather than the exception (the frond is not the storage boundary; `sources:` is).
153
+ */
154
+ export function registerFrames(
155
+ scope: Container,
156
+ keys: Iterable<string>,
157
+ providers: readonly ProviderEntry[],
158
+ world: FrameWorld,
159
+ ): void {
160
+ let registered = 0;
161
+ for (const key of new Set(keys)) {
162
+ const names = membersOfTogetherKey(key);
163
+ if (!names) continue;
164
+ registered += 1;
165
+ if (!world.ormFactory) {
166
+ throw new Error(`Together<[${names.entities.join(', ')}]> needs storage, and this boot declares none.`);
167
+ }
168
+
169
+ const members = resolve(names, providers, world);
170
+ refuseRemote(members, world, key);
171
+ refuseUncoveredWrites(members, key);
172
+
173
+ const sources = new Set(members.entities.map((member) => world.sourceOf?.(member.name) ?? 'db'));
174
+ const judge = (orm: EntityOrm, name: string, schema: SchemaView) =>
175
+ new StorageGuard(schema.getFields(), name).guard(orm);
176
+
177
+ // One engine and a way into it: the engine gives the unwind AND the isolation.
178
+ if (world.transacted && sources.size === 1) {
179
+ const source = [...sources][0];
180
+ world.log.info(`${key} — transaction, source '${source}'`);
181
+ scope.registerValue(key, {
182
+ run: <R>(fn: (entities: never, providers: never) => Promise<R>) =>
183
+ ambient.enterFrame(key, () =>
184
+ world.transacted!(source, (factory) => inScope(scope, members, factory, judge, fn as never))),
185
+ });
186
+ continue;
187
+ }
188
+
189
+ // Split, or an engine that hands out no transaction: the frame keeps the before-image
190
+ // of every write and replays the inverses itself. `judge` stays OUTSIDE `recording`, so
191
+ // a write the entity refuses never enters the journal.
192
+ const why = sources.size > 1
193
+ ? members.entities.map((m) => `${m.name} in '${world.sourceOf?.(m.name) ?? 'db'}'`).join(', ')
194
+ : 'this storage hands out no transaction';
195
+ world.log.info(`${key} — compensated: ${why} — no isolation`);
196
+ scope.registerValue(key, {
197
+ run: <R>(fn: (entities: never, providers: never) => Promise<R>): Promise<R> => ambient.enterFrame(key, async () => {
198
+ const journal: Undo[] = [];
199
+ const record = (orm: EntityOrm, name: string, schema: SchemaView) =>
200
+ judge(recording(orm, name, schema.getFields(), journal), name, schema);
201
+ try {
202
+ return await inScope(scope, members, world.ormFactory!, record, fn as never);
203
+ } catch (cause) {
204
+ return unwind(journal, cause, world.log);
205
+ }
206
+ }),
207
+ });
208
+ }
209
+ if (registered > 0 && ambient.degraded) {
210
+ world.log.warn(
211
+ 'no async context on this runtime — frames run one at a time, and a frame opened '
212
+ + 'inside another times out instead of being refused',
213
+ );
214
+ }
215
+ }