@fougere/core 0.11.0-alpha.0 → 0.12.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 (146) hide show
  1. package/dist/FougereConfig.d.ts +10 -6
  2. package/dist/FougereConfig.d.ts.map +1 -1
  3. package/dist/FougereConfig.js +19 -4
  4. package/dist/FougereConfig.js.map +1 -1
  5. package/dist/FrondConfig.d.ts +0 -6
  6. package/dist/FrondConfig.d.ts.map +1 -1
  7. package/dist/FrondConfig.js.map +1 -1
  8. package/dist/FrondDeclaration.d.ts +2 -9
  9. package/dist/FrondDeclaration.d.ts.map +1 -1
  10. package/dist/FrondDeclaration.js +0 -1
  11. package/dist/FrondDeclaration.js.map +1 -1
  12. package/dist/FrondsStated.d.ts +54 -0
  13. package/dist/FrondsStated.d.ts.map +1 -0
  14. package/dist/FrondsStated.js +26 -0
  15. package/dist/FrondsStated.js.map +1 -0
  16. package/dist/StatedFrond.d.ts +21 -0
  17. package/dist/StatedFrond.d.ts.map +1 -0
  18. package/dist/StatedFrond.js +34 -0
  19. package/dist/StatedFrond.js.map +1 -0
  20. package/dist/StatedModules.d.ts +19 -0
  21. package/dist/StatedModules.d.ts.map +1 -0
  22. package/dist/StatedModules.js +37 -0
  23. package/dist/StatedModules.js.map +1 -0
  24. package/dist/boot/CreateAppOptions.d.ts +19 -2
  25. package/dist/boot/CreateAppOptions.d.ts.map +1 -1
  26. package/dist/boot/Emissions.d.ts +9 -0
  27. package/dist/boot/Emissions.d.ts.map +1 -1
  28. package/dist/boot/Emissions.js +11 -5
  29. package/dist/boot/Emissions.js.map +1 -1
  30. package/dist/boot/bootstrap.d.ts.map +1 -1
  31. package/dist/boot/bootstrap.js +342 -307
  32. package/dist/boot/bootstrap.js.map +1 -1
  33. package/dist/boot/declared.d.ts.map +1 -1
  34. package/dist/boot/declared.js +3 -0
  35. package/dist/boot/declared.js.map +1 -1
  36. package/dist/boot/frame.d.ts +0 -4
  37. package/dist/boot/frame.d.ts.map +1 -1
  38. package/dist/boot/frame.js +31 -14
  39. package/dist/boot/frame.js.map +1 -1
  40. package/dist/boot/hosted.d.ts.map +1 -1
  41. package/dist/boot/hosted.js +4 -3
  42. package/dist/boot/hosted.js.map +1 -1
  43. package/dist/boot/install.d.ts +9 -0
  44. package/dist/boot/install.d.ts.map +1 -1
  45. package/dist/boot/install.js +271 -185
  46. package/dist/boot/install.js.map +1 -1
  47. package/dist/boot/nesting.d.ts +33 -0
  48. package/dist/boot/nesting.d.ts.map +1 -0
  49. package/dist/boot/nesting.js +164 -0
  50. package/dist/boot/nesting.js.map +1 -0
  51. package/dist/boot/ownership.d.ts +0 -1
  52. package/dist/boot/ownership.d.ts.map +1 -1
  53. package/dist/boot/ownership.js +66 -51
  54. package/dist/boot/ownership.js.map +1 -1
  55. package/dist/boot/ports.js +30 -25
  56. package/dist/boot/ports.js.map +1 -1
  57. package/dist/boot/remote.d.ts.map +1 -1
  58. package/dist/boot/remote.js +31 -28
  59. package/dist/boot/remote.js.map +1 -1
  60. package/dist/boot/seed.d.ts.map +1 -1
  61. package/dist/boot/seed.js +27 -20
  62. package/dist/boot/seed.js.map +1 -1
  63. package/dist/boot/together.d.ts.map +1 -1
  64. package/dist/boot/together.js +71 -56
  65. package/dist/boot/together.js.map +1 -1
  66. package/dist/descriptor/FrondDescriptor.d.ts +7 -0
  67. package/dist/descriptor/FrondDescriptor.d.ts.map +1 -1
  68. package/dist/descriptor/MiddlewareEntry.d.ts +6 -5
  69. package/dist/descriptor/MiddlewareEntry.d.ts.map +1 -1
  70. package/dist/descriptor/ProviderEntry.d.ts +7 -0
  71. package/dist/descriptor/ProviderEntry.d.ts.map +1 -1
  72. package/dist/dispatch/HandlerFacade.d.ts +6 -1
  73. package/dist/dispatch/HandlerFacade.d.ts.map +1 -1
  74. package/dist/dispatch/HandlerFacade.js +23 -20
  75. package/dist/dispatch/HandlerFacade.js.map +1 -1
  76. package/dist/dispatch/PresenterExecutor.d.ts +6 -0
  77. package/dist/dispatch/PresenterExecutor.d.ts.map +1 -1
  78. package/dist/dispatch/PresenterExecutor.js +30 -22
  79. package/dist/dispatch/PresenterExecutor.js.map +1 -1
  80. package/dist/dispatch/Release.js +53 -47
  81. package/dist/dispatch/Release.js.map +1 -1
  82. package/dist/dispatch/StorageGuard.d.ts +21 -0
  83. package/dist/dispatch/StorageGuard.d.ts.map +1 -1
  84. package/dist/dispatch/StorageGuard.js +84 -66
  85. package/dist/dispatch/StorageGuard.js.map +1 -1
  86. package/dist/index.d.ts +3 -0
  87. package/dist/index.d.ts.map +1 -1
  88. package/dist/index.js +3 -0
  89. package/dist/index.js.map +1 -1
  90. package/dist/node.d.ts +2 -1
  91. package/dist/node.d.ts.map +1 -1
  92. package/dist/node.js +2 -1
  93. package/dist/node.js.map +1 -1
  94. package/dist/storage/Storage.js +1 -1
  95. package/dist/storage/Storage.js.map +1 -1
  96. package/dist/storage/Store.d.ts.map +1 -1
  97. package/dist/storage/Store.js +29 -21
  98. package/dist/storage/Store.js.map +1 -1
  99. package/dist/verify.d.ts.map +1 -1
  100. package/dist/verify.js +14 -0
  101. package/dist/verify.js.map +1 -1
  102. package/dist/wire/Invocation.d.ts +1 -1
  103. package/dist/wire/Invocation.d.ts.map +1 -1
  104. package/dist/wire/Invocation.js +1 -1
  105. package/dist/wire/Invocation.js.map +1 -1
  106. package/dist/wire/binding.d.ts.map +1 -1
  107. package/dist/wire/binding.js +29 -57
  108. package/dist/wire/binding.js.map +1 -1
  109. package/dist/wire/drift.d.ts.map +1 -1
  110. package/dist/wire/drift.js +22 -19
  111. package/dist/wire/drift.js.map +1 -1
  112. package/package.json +4 -4
  113. package/src/FougereConfig.ts +24 -10
  114. package/src/FrondConfig.ts +0 -6
  115. package/src/FrondDeclaration.ts +2 -7
  116. package/src/FrondsStated.ts +72 -0
  117. package/src/StatedFrond.ts +51 -0
  118. package/src/StatedModules.ts +58 -0
  119. package/src/boot/CreateAppOptions.ts +19 -2
  120. package/src/boot/Emissions.ts +16 -5
  121. package/src/boot/bootstrap.ts +478 -359
  122. package/src/boot/declared.ts +3 -0
  123. package/src/boot/frame.ts +42 -11
  124. package/src/boot/hosted.ts +4 -3
  125. package/src/boot/install.ts +388 -212
  126. package/src/boot/nesting.ts +196 -0
  127. package/src/boot/ownership.ts +79 -51
  128. package/src/boot/ports.ts +45 -31
  129. package/src/boot/remote.ts +47 -29
  130. package/src/boot/seed.ts +36 -27
  131. package/src/boot/together.ts +98 -63
  132. package/src/descriptor/FrondDescriptor.ts +7 -0
  133. package/src/descriptor/MiddlewareEntry.ts +6 -5
  134. package/src/descriptor/ProviderEntry.ts +7 -0
  135. package/src/dispatch/HandlerFacade.ts +27 -17
  136. package/src/dispatch/PresenterExecutor.ts +33 -22
  137. package/src/dispatch/Release.ts +68 -44
  138. package/src/dispatch/StorageGuard.ts +90 -69
  139. package/src/index.ts +3 -0
  140. package/src/node.ts +2 -1
  141. package/src/storage/Storage.ts +2 -2
  142. package/src/storage/Store.ts +39 -18
  143. package/src/verify.ts +15 -0
  144. package/src/wire/Invocation.ts +2 -1
  145. package/src/wire/binding.ts +26 -58
  146. package/src/wire/drift.ts +48 -21
@@ -1,5 +1,7 @@
1
+ import { createContainer } from '@fougere/container';
1
2
  import { lowerFirst } from '@fougere/schema';
2
3
  import { hostedBy } from './hosted.js';
4
+ import { nestingOf, parentsFirst } from './nesting.js';
3
5
  import { installFrond } from './install.js';
4
6
  import { dependentsOf, releasing, unfinishable, unheldAmong } from './relations.js';
5
7
  import { release as releaseRow } from '../dispatch/Release.js';
@@ -70,9 +72,334 @@ function keyClaims(fronds, remotes, refused) {
70
72
  claim(presenterKeyOf(presenter.entityName), frond.name, 'presenter', presenter.filePath);
71
73
  }
72
74
  }
75
+ /**
76
+ * What this app hosts, and what its operations effectively are.
77
+ *
78
+ * Producing it may read a disk; consuming it never does, which is the whole reason this file
79
+ * names no builtin and a Worker can run what it builds.
80
+ */
81
+ async function readFronds(options, log) {
82
+ const scanStart = performance.now();
83
+ // An extension's fronds sit beside the app's own: it is installed like any other, and
84
+ // its handlers resolve at call time — by which point the extension's `up` has put what
85
+ // they ask for in the container.
86
+ const brought = (options.extensions ?? [])
87
+ .flatMap((extension) => extension?.fronds ?? [])
88
+ .map((frond) => ({ ...frond, brought: true }));
89
+ const { fronds, diagnostics } = await hostedBy(brought.length > 0 ? { ...options, fronds: [...(options.fronds ?? []), ...brought] } : options);
90
+ // An app that states nothing AND scans nothing is a mistake — unless something else it
91
+ // declares brings its own entities, which an auth provider does. Refused here and not in
92
+ // `hostedBy`, which is handed the frond sources and cannot see the rest of the app. The
93
+ // condition is the KEYS, not the count: a scan that found nothing is an ordinary answer.
94
+ if (!options.fronds && !options.scan && !options.auth && brought.length === 0) {
95
+ throw new Error('createApp needs `fronds:` (what this app states) or `scan:` (what a scanner found). '
96
+ + 'Neither was given, and nothing else declares entities of its own.\n'
97
+ + ' createApp({ fronds: [blog] })\n'
98
+ + ' createApp({ scan: await scanProject(root) })');
99
+ }
100
+ const { under, refused } = nestingOf(options.under, fronds, options.remotes, options.narrowed);
101
+ const refusal = refusalOf(refused, 'thing(s) the frond tree does not allow');
102
+ if (refusal)
103
+ throw refusal;
104
+ for (const frond of fronds) {
105
+ const parent = under.get(frond.name);
106
+ if (parent !== undefined)
107
+ frond.extends = parent;
108
+ }
109
+ const ordered = parentsFirst(fronds, under);
110
+ const operationModel = resolveEffectiveOperations(ordered, {
111
+ diagnostics,
112
+ remotes: options.remotes,
113
+ adapters: options.adapters,
114
+ });
115
+ const scanMs = (performance.now() - scanStart).toFixed(0);
116
+ log.info(`read ${ordered.length} frond(s) in ${scanMs}ms`
117
+ + (diagnostics.length ? ` — ${diagnostics.length} thing(s) the scan could not do` : ''));
118
+ /** Say what could not be read, at the one line everyone already watches. */
119
+ for (const d of diagnostics.filter((one) => one.severity === 'blocking'))
120
+ log.error(`[${d.code}] ${d.message}`, d.cause);
121
+ for (const d of diagnostics)
122
+ if (d.severity === 'warning')
123
+ log.warn(`[${d.code}] ${d.message}`);
124
+ /** An ambiguous convention is not a partial scan. */
125
+ const unresolved = refusalOf(operationModel.resolutionDiagnostics, 'unresolved operation contract(s)');
126
+ if (unresolved)
127
+ throw unresolved;
128
+ return { fronds: ordered, operationModel };
129
+ }
130
+ /**
131
+ * What core answers under `rpc`, in every process, whatever fronds it carries.
132
+ *
133
+ * All four read the STORAGE and never a facade: a facade answers what its handler chose to show,
134
+ * so `PostHandler.list` hiding drafts would hide exactly the row the question exists to find.
135
+ */
136
+ function serveCoreRpc(app, hosting, storageFor) {
137
+ app.serveRpc('discover', (_invocation, surface) => identityCardOf(app, surface));
138
+ app.serveRpc('holds', async (invocation) => {
139
+ const named = String(invocation.params.entity);
140
+ const keys = (invocation.params.keys ?? []);
141
+ const rows = storageFor(named);
142
+ if (!rows)
143
+ return { missing: [] };
144
+ const found = await rows.findByKeys(keys.map(String));
145
+ return { missing: keys.filter((key) => !found.has(String(key))) };
146
+ });
147
+ app.serveRpc('dependents', (invocation) => dependentsOf(String(invocation.params.entity), hosting));
148
+ app.serveRpc('release', async (invocation) => {
149
+ await releaseRow(String(invocation.params.entity), invocation.params.key, releasing(hosting), (invocation.params.visited ?? []));
150
+ return { released: true };
151
+ });
152
+ }
153
+ /**
154
+ * What no single frond can see about a `ref()`, so it is said once every frond is installed.
155
+ *
156
+ * A target belongs to another frond, and a journal arrives with an extension, which rises last.
157
+ */
158
+ function warnAboutRelations(relations, hosting, log) {
159
+ const unfinished = unfinishable(hosting);
160
+ if (unfinished.length > 0) {
161
+ log.warn(`[relations] ${unfinished.join(', ')} — declared, and this process keeps nothing on `
162
+ + 'restart: a release interrupted here is not resumed. Install @fougere/workflow, or '
163
+ + 'expect to finish one by hand.');
164
+ }
165
+ const unheld = unheldAmong(relations, hosting);
166
+ if (unheld.length > 0) {
167
+ log.warn(`[relations] ${unheld.join(', ')} — declared, and nothing in this process holds them: `
168
+ + 'no foreign key, and the target answers elsewhere. A row may name one that is gone.');
169
+ }
170
+ }
171
+ /** The process that serves an entity, asked the three questions a release travels on. */
172
+ function peerBehind(entity, router) {
173
+ const ask = async (op, params) => (await router.route(entity)).transport({ entity: RPC_ENTITY, op }, { ...Invocation.empty, params: params });
174
+ return {
175
+ dependents: async (named) => await ask('dependents', { entity: named }),
176
+ missing: async (named, keys) => (await ask('holds', { entity: named, keys })).missing,
177
+ release: async (named, key) => { await ask('release', { entity: named, key }); },
178
+ };
179
+ }
180
+ /** Close the door, and answer once the calls already running are done. */
181
+ async function drainCalls(inflight, timeoutMs) {
182
+ inflight.close();
183
+ if (timeoutMs === undefined)
184
+ return inflight.whenIdle();
185
+ let timer;
186
+ await Promise.race([
187
+ inflight.whenIdle().then(() => clearTimeout(timer)),
188
+ new Promise((_, reject) => {
189
+ timer = setTimeout(() => reject(new Error(`[drain] ${inflight.count} call(s) still running after ${timeoutMs}ms`)), timeoutMs);
190
+ }),
191
+ ]);
192
+ }
193
+ function dispatching(options, log, fronds, journalOf) {
194
+ const inflight = new InFlight();
195
+ const globalMiddlewares = [];
196
+ const scopedMiddlewares = new Map();
197
+ const routeRegistry = new RouteRegistry();
198
+ const dispatchLifecycle = new DispatchLifecycle(options.dispatchObservers, (error, event) => log.error(`[dispatch-observer] ${event.stage} ${event.call.address.toString()}`, error));
199
+ return {
200
+ inflight,
201
+ routeRegistry,
202
+ dispatchLifecycle,
203
+ // Resolved at the call and never here: a journal is a provider of a brought frond, and the
204
+ // extension that registers it rises long after this line.
205
+ dispatcher: new Dispatcher(routeRegistry, inflight, dispatchLifecycle, undefined, journalOf),
206
+ localDispatcher: new Dispatcher(routeRegistry, inflight, dispatchLifecycle, new LocalRoutePolicy((surface) => fronds.servedNames(surface)), journalOf),
207
+ getMiddlewares: (entity) => [...globalMiddlewares, ...(scopedMiddlewares.get(entity) ?? [])],
208
+ use(middleware, entity) {
209
+ if (entity === undefined) {
210
+ globalMiddlewares.push(middleware);
211
+ return;
212
+ }
213
+ scopedMiddlewares.set(entity, [...(scopedMiddlewares.get(entity) ?? []), middleware]);
214
+ },
215
+ };
216
+ }
217
+ /** Every entity of every frond, who holds it, and the door a fact goes through. */
218
+ function whatTheAppKnows(fronds, container, options, refused) {
219
+ // By name, so a fact can be validated where it LANDS and a `reads:` clause can name a
220
+ // neighbour's entity.
221
+ const entityByName = fronds.schemas();
222
+ // The line is core's, so its SHAPE is too: a destination that declares only a handler would
223
+ // otherwise be handed a line with no `at` — the announcement stamps `created()` off the shape,
224
+ // and the strict judge refuses what it did not stamp. Measured on `demos/observability`, where
225
+ // the ring held 11 calls and 0 lines.
226
+ if (!entityByName.has(LOG_LINE))
227
+ entityByName.set(LOG_LINE, LogLine);
228
+ return {
229
+ entityByName,
230
+ // What turns "a member is remote" into a refusal that names the FROND rather than the
231
+ // entity, since `remotes:` is declared per frond.
232
+ frondOf: new Map(fronds.flatMap((one) => one.entities.map((entity) => [entity.name, one.name]))),
233
+ emissions: new Emissions(fronds, entityByName, container,
234
+ // No carry: this is what CARRIES a fact, and a line about carrying one comes back here.
235
+ new Logger('boot:app'), refused, options.onEmit),
236
+ };
237
+ }
238
+ function hostingFor({ fronds, container, options, declaredRemotes, remoteRouter, entityByName, frondOf, storageOf }) {
239
+ // What carries a release writes none: an instrumentation frond's own rows are kept while a
240
+ // release happens, and journalling them would begin one inside the one being written down.
241
+ const carriesRelease = new Set(fronds.filter((one) => one.brought).flatMap((one) => one.entities.map((entity) => entity.name)));
242
+ /**
243
+ * The journal a package registered, found where its own frond put it — a provider lands in its
244
+ * frond's scope, and the app container sees none of them. Resolved per call and never at boot:
245
+ * the package that registers it rises in the ascent, long after this answer is built.
246
+ */
247
+ const journalOf = () => {
248
+ for (const frond of fronds) {
249
+ if (!frond.brought)
250
+ continue;
251
+ const scope = container.resolve(`frond:${frond.name}`);
252
+ if (scope.has(JOURNAL))
253
+ return scope.resolve(JOURNAL);
254
+ }
255
+ return undefined;
256
+ };
257
+ const hosting = {
258
+ hostedHere: (entity) => !(options.remotes && (frondOf.get(entity) ?? '') in options.remotes),
259
+ sourceOf: (name) => options.sourceOf?.(name) ?? 'db',
260
+ enforces: (source, constraint) => options.enforces?.(source, constraint) ?? false,
261
+ storageOf,
262
+ entities: () => entityByName,
263
+ journal: (entity) => (carriesRelease.has(entity) ? undefined : journalOf()),
264
+ // Built from `remotes:` itself and not from the router: the router indexes by ENTITY, read
265
+ // off a card, while the question here is asked of a PROCESS about rows it may be alone in
266
+ // knowing about. Nothing is cached — a peer that was down at boot answers the next call.
267
+ peers: () => (options.remoteTransport
268
+ ? declaredRemotes.map(([, url]) => peerOver(options.remoteTransport(url)))
269
+ : []),
270
+ peerOf: (entity) => (remoteRouter ? peerBehind(entity, remoteRouter) : undefined),
271
+ };
272
+ return { hosting, journalOf };
273
+ }
274
+ /**
275
+ * What an app answers about what it serves — the membership rule and its neighbours.
276
+ *
277
+ * `facadeFor` is THE rule, stated once: every projection reads it and nothing else.
278
+ */
279
+ function readings({ container, fronds, remoteRouter, localDispatcher, routeRegistry, effectiveByKey, log }) {
280
+ /** Stop taking calls, and resolve once the ones already running are done. */
281
+ const resolve = (name) => {
282
+ try {
283
+ return container.resolve(name);
284
+ }
285
+ catch (err) {
286
+ if (name.endsWith('Handler') && !name.includes(':') && !remoteRouter) {
287
+ throw new Error(notLoaded(name.replace(/Handler$/, '')));
288
+ }
289
+ throw err;
290
+ }
291
+ };
292
+ const schemaFor = async (entity) => {
293
+ const found = fronds.entity(entity);
294
+ if (found)
295
+ return found.entityClass;
296
+ if (remoteRouter) {
297
+ const route = await remoteRouter.route(entity);
298
+ // A remote facade that stores nothing publishes ops and no shape. Saying so beats
299
+ // handing back an empty schema, which would validate every input it was given.
300
+ if (!route.schema) {
301
+ throw new Error(`'${entity}' is served by frond '${route.frond}' but stores no rows, so it has no schema. `
302
+ + `Call its operations through the façade instead.`);
303
+ }
304
+ return route.schema;
305
+ }
306
+ throw new Error(notLoaded(entity));
307
+ };
308
+ const facadeAt = (key, topology) => {
309
+ try {
310
+ return topology
311
+ ? resolve(key)
312
+ : container.resolve(key);
313
+ }
314
+ catch {
315
+ return undefined;
316
+ }
317
+ };
318
+ /** Said once per pair, so a facade that registers in a loop says it once. */
319
+ const saidAbsent = new Set();
320
+ /**
321
+ * A surface is declared in the frond that serves it. When that frond runs in another
322
+ * process, this one never asked for its facades, and answering 'no' is the only thing a
323
+ * synchronous rule can do — so it says so rather than registering nothing in silence.
324
+ */
325
+ const sayNoSurfaceAcross = (entity, surface) => {
326
+ if (!remoteRouter || saidAbsent.has(`${surface}:${entity}`))
327
+ return;
328
+ saidAbsent.add(`${surface}:${entity}`);
329
+ log.warn(`surface '${surface}' serves nothing for '${entity}' — the frond that declares it runs `
330
+ + 'elsewhere, and a remote is asked for its facades at the first call, not at boot. '
331
+ + 'The default facade answers.');
332
+ };
333
+ /** THE membership rule, stated once — every projection reads this and nothing else. */
334
+ const facadeFor = (entity, surface) => {
335
+ if (!surface)
336
+ return facadeAt(facadeKeyOf(entity), true);
337
+ const own = facadeAt(facadeKeyOf(entity, surface), false);
338
+ const owner = fronds.owner(entity);
339
+ if (!owner) {
340
+ sayNoSurfaceAcross(entity, surface);
341
+ return own;
342
+ }
343
+ const declared = owner.surfaces?.[surface];
344
+ if (!declared)
345
+ return own;
346
+ if (!declared.some((n) => n.toLowerCase() === entity.toLowerCase()))
347
+ return undefined;
348
+ if (own)
349
+ return own;
350
+ const fallback = facadeAt(facadeKeyOf(entity), false);
351
+ return fallback
352
+ ? facadeOperations(localDispatcher, entity, routeRegistry.operationNames(entity, surface), surface)
353
+ : undefined;
354
+ };
355
+ /** The terms beside a facade, with the exact same named-surface fallback rule. */
356
+ const operationsFor = (entity, surface) => {
357
+ if (!surface)
358
+ return effectiveByKey.get(facadeKeyOf(entity));
359
+ const own = effectiveByKey.get(facadeKeyOf(entity, surface));
360
+ const declared = fronds.owner(entity)?.surfaces?.[surface];
361
+ if (!declared)
362
+ return own;
363
+ return declared.some((name) => name.toLowerCase() === entity.toLowerCase())
364
+ ? (own ?? effectiveByKey.get(facadeKeyOf(entity)))
365
+ : undefined;
366
+ };
367
+ /** The presenter of an entity, resolved through its owning frond's scope. */
368
+ const presenterFor = (entity) => {
369
+ const owner = fronds.owner(entity);
370
+ if (!owner)
371
+ return undefined;
372
+ try {
373
+ return container.resolve(`frond:${owner.name}`).resolve(presenterKeyOf(entity));
374
+ }
375
+ catch {
376
+ return undefined;
377
+ }
378
+ };
379
+ return { resolve, schemaFor, facadeFor, operationsFor, presenterFor };
380
+ }
381
+ /**
382
+ * Built once from the lazy `AuthConfig` a provider factory produced (`betterAuth({…})` in
383
+ * fougere.config.ts). The provider receives our db and storage factory, so every auth write
384
+ * flows through `Storage` like any other.
385
+ */
386
+ async function authFor(options, log) {
387
+ if (!options.auth)
388
+ return undefined;
389
+ if (!options.storageFactory) {
390
+ throw new Error('createApp: `auth` is set but `storageFactory` is missing — auth providers need it to back their adapter. Pass one through CreateAppOptions.storageFactory.');
391
+ }
392
+ if (options.db === undefined) {
393
+ throw new Error('createApp: `auth` is set but `db` is missing — pass the storage handle through CreateAppOptions.db.');
394
+ }
395
+ log.info('initializing auth runtime');
396
+ const runtime = await options.auth.create({ db: options.db, storageFactory: options.storageFactory });
397
+ log.info(`auth ready — mounted at ${runtime.basePath}`);
398
+ return runtime;
399
+ }
73
400
  /** Bootstrap a fougere application. */
74
401
  export async function createApp(options) {
75
- const container = options.createContainer();
402
+ const container = (options.createContainer ?? createContainer)();
76
403
  // Held out here, and not where the ascent reads it, because releasing needs it and
77
404
  // releasing has to work from the first line the boot takes something.
78
405
  // The conventional ascent, ordered here: tables, then rows, then whatever the host took
@@ -131,64 +458,8 @@ export async function createApp(options) {
131
458
  container.registerValue('Logger', new Logger('app', { carry }));
132
459
  container.register('Config', Config, { lifetime: 'singleton' });
133
460
  log.debug('builtins registered (Logger, Config)');
134
- // What this app hosts is HANDED IN — stated, scanned, or both (`hostedBy`). Producing
135
- // it may read a disk; consuming it never does, which is the whole reason this file names
136
- // no builtin and a Worker can run what it builds.
137
- const scanStart = performance.now();
138
- // An extension's fronds sit beside the app's own: it is installed like any other, and
139
- // its handlers resolve at call time — by which point the extension's `up` has put what
140
- // they ask for in the container.
141
- const brought = (options.extensions ?? [])
142
- .flatMap((extension) => extension?.fronds ?? [])
143
- .map((frond) => ({ ...frond, brought: true }));
144
- const { fronds, diagnostics } = await hostedBy(brought.length > 0 ? { ...options, fronds: [...(options.fronds ?? []), ...brought] } : options);
145
- // An app that states nothing AND scans nothing is a mistake — unless something else it
146
- // declares brings its own entities, which an auth provider does. Refused here and not in
147
- // `hostedBy`, which is handed the frond sources and cannot see the rest of the app. The
148
- // condition is the KEYS, not the count: a scan that found nothing is an ordinary answer.
149
- if (!options.fronds && !options.scan && !options.auth && brought.length === 0) {
150
- throw new Error('createApp needs `fronds:` (what this app states) or `scan:` (what a scanner found). '
151
- + 'Neither was given, and nothing else declares entities of its own.\n'
152
- + ' createApp({ fronds: [blog] })\n'
153
- + ' createApp({ scan: await scanProject(root) })');
154
- }
155
- const operationModel = resolveEffectiveOperations(fronds, {
156
- diagnostics,
157
- remotes: options.remotes,
158
- adapters: options.adapters,
159
- });
160
- const scanMs = (performance.now() - scanStart).toFixed(0);
161
- const blocking = diagnostics.filter((d) => d.severity === 'blocking');
162
- log.info(`read ${fronds.length} frond(s) in ${scanMs}ms`
163
- + (diagnostics.length ? ` — ${diagnostics.length} thing(s) the scan could not do` : ''));
164
- /** Say what could not be read, at the one line everyone already watches. */
165
- for (const d of blocking)
166
- log.error(`[${d.code}] ${d.message}`, d.cause);
167
- for (const d of diagnostics)
168
- if (d.severity === 'warning')
169
- log.warn(`[${d.code}] ${d.message}`);
170
- /** An ambiguous convention is not a partial scan. */
171
- const unresolved = refusalOf(operationModel.resolutionDiagnostics, 'unresolved operation contract(s)');
172
- if (unresolved)
173
- throw unresolved;
174
- // Auth runtime — built once from the lazy AuthConfig produced by a provider factory
175
- // (e.g. betterAuth({...})) in fougere.config.ts. The provider receives our db +
176
- // storageFactory so all auth writes flow through Storage.
177
- let authRuntime;
178
- if (options.auth) {
179
- if (!options.storageFactory) {
180
- throw new Error('createApp: `auth` is set but `storageFactory` is missing — auth providers need it to back their adapter. Pass one through CreateAppOptions.storageFactory.');
181
- }
182
- if (options.db === undefined) {
183
- throw new Error('createApp: `auth` is set but `db` is missing — pass the storage handle through CreateAppOptions.db.');
184
- }
185
- log.info('initializing auth runtime');
186
- authRuntime = await options.auth.create({
187
- db: options.db,
188
- storageFactory: options.storageFactory,
189
- });
190
- log.info(`auth ready — mounted at ${authRuntime.basePath}`);
191
- }
461
+ const { fronds, operationModel } = await readFronds(options, log);
462
+ const authRuntime = await authFor(options, log);
192
463
  // Remote routing — validated at boot: declaring remotes without a transport is a config error.
193
464
  // A remote declaration wins over local presence: `remotes: { blog: url }` IS
194
465
  // the topology statement — the frond's code may sit in fronds/**, it runs elsewhere.
@@ -199,37 +470,7 @@ export async function createApp(options) {
199
470
  const remoteRouter = declaredRemotes.length > 0 && options.remoteTransport
200
471
  ? createRemoteRouter(Object.fromEntries(declaredRemotes), options.remoteTransport)
201
472
  : undefined;
202
- // What is running on this app counted at the one facade every caller goes through,
203
- // so releasing it can wait for the work instead of pulling the floor out.
204
- const inflight = new InFlight();
205
- // Middleware storage — read at call time, not at boot time
206
- const globalMiddlewares = [];
207
- const scopedMiddlewares = new Map();
208
- /** What this app took on beyond its fronds. Its `up` is the last thing the boot does. */
209
- const routeRegistry = new RouteRegistry();
210
- const dispatchLifecycle = new DispatchLifecycle(options.dispatchObservers, (error, event) => log.error(`[dispatch-observer] ${event.stage} ${event.call.address.toString()}`, error));
211
- // Resolved at the call and never here: a journal is a provider of a brought frond, and
212
- // the extension that registers it rises long after this line.
213
- const keeping = () => journalOf();
214
- const dispatcher = new Dispatcher(routeRegistry, inflight, dispatchLifecycle, undefined, keeping);
215
- const localDispatcher = new Dispatcher(routeRegistry, inflight, dispatchLifecycle, new LocalRoutePolicy((surface) => fronds.servedNames(surface)), keeping);
216
- function getMiddlewares(entity) {
217
- const scoped = scopedMiddlewares.get(entity) ?? [];
218
- return [...globalMiddlewares, ...scoped];
219
- }
220
- /**
221
- * The one place a middleware is taken on. `App.use` is its late form, and a frond's
222
- * `middlewares/` its early one — the app does not exist yet while fronds install.
223
- */
224
- function use(middleware, entity) {
225
- if (entity === undefined) {
226
- globalMiddlewares.push(middleware);
227
- return;
228
- }
229
- const scoped = scopedMiddlewares.get(entity) ?? [];
230
- scoped.push(middleware);
231
- scopedMiddlewares.set(entity, scoped);
232
- }
473
+ const { inflight, routeRegistry, dispatchLifecycle, dispatcher, localDispatcher, getMiddlewares, use } = dispatching(options, log, fronds, () => journalOf());
233
474
  /** What every check of this boot writes into — refused together, once they have all run. */
234
475
  const refused = [];
235
476
  const relations = [];
@@ -239,23 +480,7 @@ export async function createApp(options) {
239
480
  const claimed = refusalOf(refused, 'declaration(s) that do not hold');
240
481
  if (claimed)
241
482
  throw claimed;
242
- // Every entity of every frond, by name so a fact can be validated where it LANDS, and
243
- // so a `reads:` clause can name a neighbour's.
244
- const entityByName = fronds.schemas();
245
- // The line is core's, so its SHAPE is too: a destination that declares only a handler
246
- // would otherwise be handed a line with no `at` — the announcement stamps `created()`
247
- // off the shape, and the strict judge refuses what it did not stamp. Measured on
248
- // `demos/observability`, where the ring held 11 calls and 0 lines.
249
- if (!entityByName.has(LOG_LINE))
250
- entityByName.set(LOG_LINE, LogLine);
251
- // Which frond holds an entity — what turns "a member is remote" into a refusal that
252
- // names the frond rather than the entity, since `remotes:` is declared per frond.
253
- const frondOf = new Map(fronds.flatMap((f) => f.entities.map((e) => [e.name, f.name])));
254
- // Its own writer, which does NOT announce: this is what carries a fact, and a line
255
- // about carrying one would come back here. See `LoggerOptions.carries`.
256
- const emissions = new Emissions(fronds, entityByName, container,
257
- // No carry: this is what CARRIES a fact, and a line about carrying one comes back.
258
- new Logger('boot:app'), refused, options.onEmit);
483
+ const { entityByName, frondOf, emissions } = whatTheAppKnows(fronds, container, options, refused);
259
484
  /** Canonical operation tables, indexed by the same audience key as their facades. */
260
485
  const effectiveByKey = new Map();
261
486
  const contractsOf = (operations) => new Map([...operations].map(([name, operation]) => [name, operation]));
@@ -277,52 +502,9 @@ export async function createApp(options) {
277
502
  };
278
503
  // What carries a release writes none: an instrumentation frond's own rows are kept while a
279
504
  // release happens, and journalling them would begin one inside the one being written down.
280
- const carriesRelease = new Set(fronds.filter((one) => one.brought).flatMap((one) => one.entities.map((e) => e.name)));
281
- /**
282
- * The journal a package registered, found where its own frond put it — a provider lands in
283
- * its frond's scope, and the app container sees none of them.
284
- */
285
- const journalOf = () => {
286
- for (const frond of fronds) {
287
- if (!frond.brought)
288
- continue;
289
- const scope = container.resolve(`frond:${frond.name}`);
290
- if (scope.has(JOURNAL))
291
- return scope.resolve(JOURNAL);
292
- }
293
- return undefined;
294
- };
295
- const hosting = {
296
- hostedHere: (entity) => !(options.remotes && (frondOf.get(entity) ?? '') in options.remotes),
297
- sourceOf: (name) => options.sourceOf?.(name) ?? 'db',
298
- enforces: (source, constraint) => options.enforces?.(source, constraint) ?? false,
299
- storageOf: storageFor,
300
- entities: () => entityByName,
301
- // The two readings core serves in EVERY process, asked of the one that holds the rows.
302
- // Nothing is cached: a peer that was down at boot answers the next call.
303
- // Built from `remotes:` itself, not from the router: the router indexes by ENTITY, read
304
- // off a card, and the question here is asked of a PROCESS about rows it may be alone
305
- // in knowing about.
306
- // Resolved per call and never at boot: the package that registers it rises in the
307
- // ascent, long after this answer is built.
308
- journal: (entity) => (carriesRelease.has(entity) ? undefined : journalOf()),
309
- peers: () => (options.remoteTransport
310
- ? declaredRemotes.map(([, url]) => peerOver(options.remoteTransport(url)))
311
- : []),
312
- peerOf: (entity) => (remoteRouter ? {
313
- dependents: async (named) => (await remoteRouter.route(entity))
314
- .transport({ entity: RPC_ENTITY, op: 'dependents' }, { ...Invocation.empty, params: { entity: named } }),
315
- missing: async (named, keys) => {
316
- const answer = await (await remoteRouter.route(entity))
317
- .transport({ entity: RPC_ENTITY, op: 'holds' }, { ...Invocation.empty, params: { entity: named, keys } });
318
- return answer.missing;
319
- },
320
- release: async (named, key) => {
321
- const route = await remoteRouter.route(entity);
322
- await route.transport({ entity: RPC_ENTITY, op: 'release' }, { ...Invocation.empty, params: { entity: named, key } });
323
- },
324
- } : undefined),
325
- };
505
+ const { hosting, journalOf } = hostingFor({
506
+ fronds, container, options, declaredRemotes, remoteRouter, entityByName, frondOf, storageOf: storageFor,
507
+ });
326
508
  // Every port an implementation was bound to, so a `ports:` entry that named none
327
509
  // can say so rather than look obeyed.
328
510
  const boundPorts = new Set();
@@ -332,27 +514,11 @@ export async function createApp(options) {
332
514
  const assembly = {
333
515
  container, routeRegistry, emissions, dispatcher, localDispatcher, effectiveByKey,
334
516
  boundPorts, refused, relations, hosting, operationModel, entityByName, frondOf, contractsOf,
335
- getMiddlewares, use, log, options,
517
+ getMiddlewares, use, middlewaresOf: new Map(), seamsOf: new Map(), log, options,
336
518
  };
337
519
  for (const frond of fronds)
338
520
  await installFrond(frond, assembly);
339
- // A reference no key holds and no storage answers: said at the END, for the reason the
340
- // `ports:` warning below is — a target is another frond's, so no single frond can tell
341
- // an absence from a neighbour that had not been installed yet.
342
- const unheld = unheldAmong(relations, hosting);
343
- // Declared here, and this process cannot finish what it starts — both halves are local,
344
- // so nothing is asked of anyone. Said once, after every frond installed, because a journal
345
- // arrives with an extension and an extension rises last.
346
- const unfinished = unfinishable(hosting);
347
- if (unfinished.length > 0) {
348
- log.warn(`[relations] ${unfinished.join(', ')} — declared, and this process keeps nothing on `
349
- + 'restart: a release interrupted here is not resumed. Install @fougere/workflow, or '
350
- + 'expect to finish one by hand.');
351
- }
352
- if (unheld.length > 0) {
353
- log.warn(`[relations] ${unheld.join(', ')} — declared, and nothing in this process holds them: `
354
- + 'no foreign key, and the target answers elsewhere. A row may name one that is gone.');
355
- }
521
+ warnAboutRelations(relations, hosting, log);
356
522
  // Every check of the install, said at once — a boot that stops at the first makes the
357
523
  // next one visible only after a fix and a restart.
358
524
  const bootRefusal = refusalOf(refused, 'declaration(s) that do not hold');
@@ -391,93 +557,6 @@ export async function createApp(options) {
391
557
  // 'Product' and every by-type dependency on a remote handler answered NOT_FOUND.
392
558
  return facadeOperations(dispatcher, lowerFirst(name.replace(/Handler$/, '')));
393
559
  });
394
- /** Stop taking calls, and resolve once the ones already running are done. */
395
- const drain = async (timeoutMs) => {
396
- inflight.close();
397
- if (timeoutMs === undefined)
398
- return inflight.whenIdle();
399
- let timer;
400
- await Promise.race([
401
- inflight.whenIdle().then(() => clearTimeout(timer)),
402
- new Promise((_, reject) => {
403
- timer = setTimeout(() => reject(new Error(`[drain] ${inflight.count} call(s) still running after ${timeoutMs}ms`)), timeoutMs);
404
- }),
405
- ]);
406
- };
407
- const resolve = (name) => {
408
- try {
409
- return container.resolve(name);
410
- }
411
- catch (err) {
412
- if (name.endsWith('Handler') && !name.includes(':') && !remoteRouter) {
413
- throw new Error(notLoaded(name.replace(/Handler$/, '')));
414
- }
415
- throw err;
416
- }
417
- };
418
- const schemaFor = async (entity) => {
419
- const found = fronds.entity(entity);
420
- if (found)
421
- return found.entityClass;
422
- if (remoteRouter) {
423
- const route = await remoteRouter.route(entity);
424
- // A remote facade that stores nothing publishes ops and no shape. Saying so beats
425
- // handing back an empty schema, which would validate every input it was given.
426
- if (!route.schema) {
427
- throw new Error(`'${entity}' is served by frond '${route.frond}' but stores no rows, so it has no schema. `
428
- + `Call its operations through the façade instead.`);
429
- }
430
- return route.schema;
431
- }
432
- throw new Error(notLoaded(entity));
433
- };
434
- const facadeAt = (key, topology) => {
435
- try {
436
- return topology
437
- ? resolve(key)
438
- : container.resolve(key);
439
- }
440
- catch {
441
- return undefined;
442
- }
443
- };
444
- /** Said once per pair, so a facade that registers in a loop says it once. */
445
- const saidAbsent = new Set();
446
- /**
447
- * A surface is declared in the frond that serves it. When that frond runs in another
448
- * process, this one never asked for its facades, and answering 'no' is the only thing a
449
- * synchronous rule can do — so it says so rather than registering nothing in silence.
450
- */
451
- const sayNoSurfaceAcross = (entity, surface) => {
452
- if (!remoteRouter || saidAbsent.has(`${surface}:${entity}`))
453
- return;
454
- saidAbsent.add(`${surface}:${entity}`);
455
- log.warn(`surface '${surface}' serves nothing for '${entity}' — the frond that declares it runs `
456
- + 'elsewhere, and a remote is asked for its facades at the first call, not at boot. '
457
- + 'The default facade answers.');
458
- };
459
- /** THE membership rule, stated once — every projection reads this and nothing else. */
460
- const facadeFor = (entity, surface) => {
461
- if (!surface)
462
- return facadeAt(facadeKeyOf(entity), true);
463
- const own = facadeAt(facadeKeyOf(entity, surface), false);
464
- const owner = fronds.owner(entity);
465
- if (!owner) {
466
- sayNoSurfaceAcross(entity, surface);
467
- return own;
468
- }
469
- const declared = owner.surfaces?.[surface];
470
- if (!declared)
471
- return own;
472
- if (!declared.some((n) => n.toLowerCase() === entity.toLowerCase()))
473
- return undefined;
474
- if (own)
475
- return own;
476
- const fallback = facadeAt(facadeKeyOf(entity), false);
477
- return fallback
478
- ? facadeOperations(localDispatcher, entity, routeRegistry.operationNames(entity, surface), surface)
479
- : undefined;
480
- };
481
560
  if (remoteRouter) {
482
561
  const remoteFacades = new Map();
483
562
  routeRegistry.addResolver(remoteRoutes((entity) => {
@@ -489,30 +568,9 @@ export async function createApp(options) {
489
568
  return facade;
490
569
  }));
491
570
  }
492
- /** The terms beside a facade, with the exact same named-surface fallback rule. */
493
- const operationsFor = (entity, surface) => {
494
- if (!surface)
495
- return effectiveByKey.get(facadeKeyOf(entity));
496
- const own = effectiveByKey.get(facadeKeyOf(entity, surface));
497
- const declared = fronds.owner(entity)?.surfaces?.[surface];
498
- if (!declared)
499
- return own;
500
- return declared.some((name) => name.toLowerCase() === entity.toLowerCase())
501
- ? (own ?? effectiveByKey.get(facadeKeyOf(entity)))
502
- : undefined;
503
- };
504
- /** The presenter of an entity, resolved through its owning frond's scope. */
505
- const presenterFor = (entity) => {
506
- const owner = fronds.owner(entity);
507
- if (!owner)
508
- return undefined;
509
- try {
510
- return container.resolve(`frond:${owner.name}`).resolve(presenterKeyOf(entity));
511
- }
512
- catch {
513
- return undefined;
514
- }
515
- };
571
+ const { resolve, schemaFor, facadeFor, operationsFor, presenterFor } = readings({
572
+ container, fronds, remoteRouter, localDispatcher, routeRegistry, effectiveByKey, log,
573
+ });
516
574
  const app = {
517
575
  container,
518
576
  fronds,
@@ -534,7 +592,7 @@ export async function createApp(options) {
534
592
  storageFor,
535
593
  presenterFor,
536
594
  dispose: release,
537
- drain,
595
+ drain: (timeoutMs) => drainCalls(inflight, timeoutMs),
538
596
  inFlight: () => inflight.count,
539
597
  [Symbol.asyncDispose]: release,
540
598
  serveRpc(op, answer) {
@@ -563,30 +621,7 @@ export async function createApp(options) {
563
621
  // What a release is, resolved once and registered: a package that drives one asks for it
564
622
  // by type, the way every other dependency is asked for.
565
623
  container.registerValue('Releasing', releasing(hosting));
566
- app.serveRpc('discover', (_invocation, surface) => identityCardOf(app, surface));
567
- // What a release asks another process, and what it tells it to do. Served by EVERY process
568
- // the way `discover` is: a frond that hosts rows is the only one that can answer for them.
569
- //
570
- // Read off the STORAGE and never off a facade: a facade answers what its handler chose to
571
- // show — `PostHandler.list` hands back published posts — so a draft naming a deleted user
572
- // would be invisible to the very question that exists to find it.
573
- // The dual of `release`, and the same reason it is served by every process: only the one
574
- // that holds the rows can say a key is missing, and only from the STORAGE — a facade
575
- // answers what its handler chose to show.
576
- app.serveRpc('holds', async (invocation) => {
577
- const named = String(invocation.params.entity);
578
- const keys = (invocation.params.keys ?? []);
579
- const rows = storageFor(named);
580
- if (!rows)
581
- return { missing: [] };
582
- const found = await rows.findByKeys(keys.map(String));
583
- return { missing: keys.filter((key) => !found.has(String(key))) };
584
- });
585
- app.serveRpc('dependents', (invocation) => dependentsOf(String(invocation.params.entity), hosting));
586
- app.serveRpc('release', async (invocation) => {
587
- await releaseRow(String(invocation.params.entity), invocation.params.key, releasing(hosting), (invocation.params.visited ?? []));
588
- return { released: true };
589
- });
624
+ serveCoreRpc(app, hosting, storageFor);
590
625
  // The last thing the boot does, and the first thing a release undoes. An extension may
591
626
  // await here — which is what a provider needing to OPEN something could never do.
592
627
  built = app;