@fougere/core 0.12.2-alpha.0 → 0.12.4-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 (126) hide show
  1. package/dist/EffectiveOperationModel.d.ts +1 -4
  2. package/dist/EffectiveOperationModel.d.ts.map +1 -1
  3. package/dist/EffectiveOperationModel.js +181 -173
  4. package/dist/EffectiveOperationModel.js.map +1 -1
  5. package/dist/FougereConfig.d.ts +5 -3
  6. package/dist/FougereConfig.d.ts.map +1 -1
  7. package/dist/FougereConfig.js +11 -13
  8. package/dist/FougereConfig.js.map +1 -1
  9. package/dist/FrondDeclaration.d.ts.map +1 -1
  10. package/dist/FrondDeclaration.js +1 -5
  11. package/dist/FrondDeclaration.js.map +1 -1
  12. package/dist/Source.js +1 -1
  13. package/dist/Source.js.map +1 -1
  14. package/dist/SourceView.d.ts +0 -2
  15. package/dist/SourceView.d.ts.map +1 -1
  16. package/dist/boot/App.d.ts +2 -4
  17. package/dist/boot/App.d.ts.map +1 -1
  18. package/dist/boot/AppLifecycle.d.ts +5 -0
  19. package/dist/boot/AppLifecycle.d.ts.map +1 -1
  20. package/dist/boot/AppLifecycle.js +19 -10
  21. package/dist/boot/AppLifecycle.js.map +1 -1
  22. package/dist/boot/AuthRuntime.d.ts +5 -12
  23. package/dist/boot/AuthRuntime.d.ts.map +1 -1
  24. package/dist/boot/AuthRuntime.js +2 -1
  25. package/dist/boot/AuthRuntime.js.map +1 -1
  26. package/dist/boot/CreateAppOptions.d.ts +0 -11
  27. package/dist/boot/CreateAppOptions.d.ts.map +1 -1
  28. package/dist/boot/Emissions.d.ts.map +1 -1
  29. package/dist/boot/Emissions.js +3 -6
  30. package/dist/boot/Emissions.js.map +1 -1
  31. package/dist/boot/Hosting.d.ts +2 -1
  32. package/dist/boot/Hosting.d.ts.map +1 -1
  33. package/dist/boot/bootstrap.d.ts.map +1 -1
  34. package/dist/boot/bootstrap.js +140 -263
  35. package/dist/boot/bootstrap.js.map +1 -1
  36. package/dist/boot/install.d.ts.map +1 -1
  37. package/dist/boot/install.js +102 -114
  38. package/dist/boot/install.js.map +1 -1
  39. package/dist/boot/relations.d.ts.map +1 -1
  40. package/dist/boot/relations.js.map +1 -1
  41. package/dist/boot/seed.d.ts.map +1 -1
  42. package/dist/boot/seed.js.map +1 -1
  43. package/dist/descriptor/Fronds.d.ts +5 -0
  44. package/dist/descriptor/Fronds.d.ts.map +1 -1
  45. package/dist/descriptor/Fronds.js +8 -0
  46. package/dist/descriptor/Fronds.js.map +1 -1
  47. package/dist/descriptor/index.d.ts +1 -0
  48. package/dist/descriptor/index.d.ts.map +1 -1
  49. package/dist/descriptor/index.js +1 -0
  50. package/dist/descriptor/index.js.map +1 -1
  51. package/dist/dispatch/InFlight.d.ts +3 -2
  52. package/dist/dispatch/InFlight.d.ts.map +1 -1
  53. package/dist/dispatch/InFlight.js +11 -1
  54. package/dist/dispatch/InFlight.js.map +1 -1
  55. package/dist/index.d.ts +2 -4
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +2 -0
  58. package/dist/index.js.map +1 -1
  59. package/dist/node.d.ts +1 -1
  60. package/dist/node.d.ts.map +1 -1
  61. package/dist/node.js +1 -1
  62. package/dist/node.js.map +1 -1
  63. package/dist/prefab/CrudConstructor.d.ts.map +1 -1
  64. package/dist/prefab/CrudConstructor.js.map +1 -1
  65. package/dist/storage/Comparison.d.ts +2 -2
  66. package/dist/storage/Comparison.d.ts.map +1 -1
  67. package/dist/storage/Comparison.js +3 -1
  68. package/dist/storage/Comparison.js.map +1 -1
  69. package/dist/wire/Emit.d.ts +0 -2
  70. package/dist/wire/Emit.d.ts.map +1 -1
  71. package/dist/wire/Emit.js +1 -1
  72. package/dist/wire/Emit.js.map +1 -1
  73. package/dist/wire/Facade.d.ts +7 -0
  74. package/dist/wire/Facade.d.ts.map +1 -1
  75. package/dist/wire/Facade.js +13 -0
  76. package/dist/wire/Facade.js.map +1 -1
  77. package/dist/wire/OperationContract.d.ts +0 -4
  78. package/dist/wire/OperationContract.d.ts.map +1 -1
  79. package/dist/wire/OperationContract.js +1 -1
  80. package/dist/wire/OperationContract.js.map +1 -1
  81. package/dist/wire/OperationsMap.d.ts +0 -3
  82. package/dist/wire/OperationsMap.d.ts.map +1 -1
  83. package/dist/wire/OperationsMap.js +0 -5
  84. package/dist/wire/OperationsMap.js.map +1 -1
  85. package/package.json +4 -4
  86. package/src/EffectiveOperationModel.ts +221 -201
  87. package/src/FougereConfig.ts +14 -16
  88. package/src/FrondDeclaration.ts +1 -7
  89. package/src/Source.ts +1 -1
  90. package/src/SourceView.ts +0 -2
  91. package/src/boot/App.ts +2 -4
  92. package/src/boot/AppLifecycle.ts +21 -10
  93. package/src/boot/AuthRuntime.ts +6 -13
  94. package/src/boot/CreateAppOptions.ts +0 -11
  95. package/src/boot/Emissions.ts +3 -7
  96. package/src/boot/Hosting.ts +2 -1
  97. package/src/boot/bootstrap.ts +168 -300
  98. package/src/boot/install.ts +120 -146
  99. package/src/boot/relations.ts +3 -8
  100. package/src/boot/seed.ts +2 -4
  101. package/src/descriptor/Fronds.ts +10 -0
  102. package/src/descriptor/index.ts +1 -0
  103. package/src/dispatch/InFlight.ts +16 -2
  104. package/src/index.ts +2 -4
  105. package/src/node.ts +1 -1
  106. package/src/prefab/CrudConstructor.ts +0 -11
  107. package/src/storage/Comparison.ts +7 -4
  108. package/src/wire/Emit.ts +1 -1
  109. package/src/wire/Facade.ts +17 -10
  110. package/src/wire/OperationContract.ts +1 -1
  111. package/src/wire/OperationsMap.ts +0 -10
  112. package/dist/boot/AuthConfig.d.ts +0 -14
  113. package/dist/boot/AuthConfig.d.ts.map +0 -1
  114. package/dist/boot/AuthConfig.js +0 -2
  115. package/dist/boot/AuthConfig.js.map +0 -1
  116. package/dist/boot/AuthContext.d.ts +0 -12
  117. package/dist/boot/AuthContext.d.ts.map +0 -1
  118. package/dist/boot/AuthContext.js +0 -2
  119. package/dist/boot/AuthContext.js.map +0 -1
  120. package/dist/storage/ComparisonName.d.ts +0 -3
  121. package/dist/storage/ComparisonName.d.ts.map +0 -1
  122. package/dist/storage/ComparisonName.js +0 -2
  123. package/dist/storage/ComparisonName.js.map +0 -1
  124. package/src/boot/AuthConfig.ts +0 -14
  125. package/src/boot/AuthContext.ts +0 -12
  126. package/src/storage/ComparisonName.ts +0 -3
@@ -12,19 +12,16 @@ import { Carry } from '../builtin/Carry.js';
12
12
  import { Logger } from '../builtin/Logger.js';
13
13
  import LogLine, { CARRIES_LINE } from '../builtin/LogLine.js';
14
14
  import { emitKeyOf } from '../wire/Emit.js';
15
- /** The fact the boot announces, spelled once. */
16
- const LOG_LINE = lowerFirst(LogLine.name);
17
15
  import { Config } from '../builtin/config.js';
18
16
  import { createRemoteRouter, createRemoteFacade } from './remote.js';
19
17
  import { Emissions } from './Emissions.js';
20
18
  import { resolveEffectiveOperations } from '../EffectiveOperationModel.js';
21
19
  import { InFlight } from '../dispatch/InFlight.js';
22
- // The keys, each read from where its concept is declared — never respelled here.
23
20
  import { RPC_ENTITY } from '../wire/RpcAnswer.js';
24
21
  import { Invocation } from '../wire/Invocation.js';
25
- import { facadeKeyOf } from '../wire/Facade.js';
22
+ import { addressOf, facadeKeyOf, isFacadeKey } from '../wire/Facade.js';
26
23
  import { identityCardOf } from './card.js';
27
- import { AppLifecycle, migrating } from './AppLifecycle.js';
24
+ import { AppLifecycle, closeAll, migrating } from './AppLifecycle.js';
28
25
  import { seeding } from './seed.js';
29
26
  import { storageKeyOf } from '../storage/Storage.js';
30
27
  import { presenterKeyOf } from '../prefab/presenter.js';
@@ -36,6 +33,7 @@ import { OperationRoute } from '../dispatch/OperationRoute.js';
36
33
  import { remoteRoutes } from '../dispatch/remoteRoutes.js';
37
34
  import { RouteRegistry } from '../dispatch/RouteRegistry.js';
38
35
  import { facadeOperations } from '../entry/facade.js';
36
+ const LOG_LINE = lowerFirst(LogLine.name);
39
37
  /** The one wording for "nobody hosts this here", with both ways out. */
40
38
  const notLoaded = (entity) => `Frond for '${entity}' is not loaded.\n` +
41
39
  ` - Add '${entity}' to --fronds flag\n` +
@@ -87,11 +85,11 @@ async function readFronds(options, log) {
87
85
  .flatMap((extension) => extension?.fronds ?? [])
88
86
  .map((frond) => ({ ...frond, brought: true }));
89
87
  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) {
88
+ // An app that states nothing AND scans nothing is a mistake — unless an extension brings
89
+ // fronds of its own. Refused here and not in `hostedBy`, which is handed the frond sources
90
+ // and cannot see the rest of the app. The condition is the KEYS, not the count: a scan that
91
+ // found nothing is an ordinary answer.
92
+ if (!options.fronds && !options.scan && brought.length === 0) {
95
93
  throw new Error('createApp needs `fronds:` (what this app states) or `scan:` (what a scanner found). '
96
94
  + 'Neither was given, and nothing else declares entities of its own.\n'
97
95
  + ' createApp({ fronds: [blog] })\n'
@@ -177,25 +175,20 @@ function peerBehind(entity, router) {
177
175
  release: async (named, key) => { await ask('release', { entity: named, key }); },
178
176
  };
179
177
  }
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
- ]);
178
+ function ownedBy(fronds, container, entity, key) {
179
+ const owner = fronds.owner(entity);
180
+ const scopeKey = `frond:${owner?.name}`;
181
+ if (!owner || !container.has(scopeKey))
182
+ return undefined;
183
+ const scope = container.resolve(scopeKey);
184
+ return scope.has(key) ? scope.resolve(key) : undefined;
192
185
  }
193
186
  function dispatching(options, log, fronds, journalOf) {
194
187
  const inflight = new InFlight();
195
188
  const globalMiddlewares = [];
196
189
  const scopedMiddlewares = new Map();
197
190
  const routeRegistry = new RouteRegistry();
198
- const dispatchLifecycle = new DispatchLifecycle(options.dispatchObservers, (error, event) => log.error(`[dispatch-observer] ${event.stage} ${event.call.address.toString()}`, error));
191
+ const dispatchLifecycle = new DispatchLifecycle([], (error, event) => log.error(`[dispatch-observer] ${event.stage} ${event.call.address.toString()}`, error));
199
192
  return {
200
193
  inflight,
201
194
  routeRegistry,
@@ -235,7 +228,7 @@ function whatTheAppKnows(fronds, container, options, refused) {
235
228
  new Logger('boot:app'), refused, options.onEmit),
236
229
  };
237
230
  }
238
- function hostingFor({ fronds, container, options, declaredRemotes, remoteRouter, entityByName, frondOf, storageOf }) {
231
+ function hostingFor({ fronds, container, options, remoteRouter, entityByName, frondOf, storageOf }) {
239
232
  // What carries a release writes none: an instrumentation frond's own rows are kept while a
240
233
  // release happens, and journalling them would begin one inside the one being written down.
241
234
  const carriesRelease = new Set(fronds.filter((one) => one.brought).flatMap((one) => one.entities.map((entity) => entity.name)));
@@ -265,7 +258,7 @@ function hostingFor({ fronds, container, options, declaredRemotes, remoteRouter,
265
258
  // off a card, while the question here is asked of a PROCESS about rows it may be alone in
266
259
  // knowing about. Nothing is cached — a peer that was down at boot answers the next call.
267
260
  peers: () => (options.remoteTransport
268
- ? declaredRemotes.map(([, url]) => peerOver(options.remoteTransport(url)))
261
+ ? Object.values(options.remotes ?? {}).map((url) => peerOver(options.remoteTransport(url)))
269
262
  : []),
270
263
  peerOf: (entity) => (remoteRouter ? peerBehind(entity, remoteRouter) : undefined),
271
264
  };
@@ -277,15 +270,13 @@ function hostingFor({ fronds, container, options, declaredRemotes, remoteRouter,
277
270
  * `facadeFor` is THE rule, stated once: every projection reads it and nothing else.
278
271
  */
279
272
  function readings({ container, fronds, remoteRouter, localDispatcher, routeRegistry, effectiveByKey, log }) {
280
- /** Stop taking calls, and resolve once the ones already running are done. */
281
273
  const resolve = (name) => {
282
274
  try {
283
275
  return container.resolve(name);
284
276
  }
285
277
  catch (err) {
286
- if (name.endsWith('Handler') && !name.includes(':') && !remoteRouter) {
287
- throw new Error(notLoaded(name.replace(/Handler$/, '')));
288
- }
278
+ if (isFacadeKey(name) && !remoteRouter)
279
+ throw new Error(notLoaded(addressOf(name)));
289
280
  throw err;
290
281
  }
291
282
  };
@@ -335,182 +326,157 @@ function readings({ container, fronds, remoteRouter, localDispatcher, routeRegis
335
326
  if (!surface)
336
327
  return facadeAt(facadeKeyOf(entity), true);
337
328
  const own = facadeAt(facadeKeyOf(entity, surface), false);
338
- const owner = fronds.owner(entity);
339
- if (!owner) {
329
+ if (!fronds.owner(entity)) {
340
330
  sayNoSurfaceAcross(entity, surface);
341
331
  return own;
342
332
  }
343
- const declared = owner.surfaces?.[surface];
344
- if (!declared)
345
- return own;
346
- if (!declared.some((n) => n.toLowerCase() === entity.toLowerCase()))
333
+ const admitted = fronds.admits(surface, entity);
334
+ if (admitted === false)
347
335
  return undefined;
348
- if (own)
336
+ if (own || admitted === undefined)
349
337
  return own;
350
338
  const fallback = facadeAt(facadeKeyOf(entity), false);
351
339
  return fallback
352
340
  ? facadeOperations(localDispatcher, entity, routeRegistry.operationNames(entity, surface), surface)
353
341
  : undefined;
354
342
  };
355
- /** The terms beside a facade, with the exact same named-surface fallback rule. */
356
343
  const operationsFor = (entity, surface) => {
357
344
  if (!surface)
358
345
  return effectiveByKey.get(facadeKeyOf(entity));
359
346
  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)
347
+ const admitted = fronds.admits(surface, entity);
348
+ if (admitted === false)
371
349
  return undefined;
372
- try {
373
- return container.resolve(`frond:${owner.name}`).resolve(presenterKeyOf(entity));
374
- }
375
- catch {
376
- return undefined;
377
- }
350
+ return admitted ? (own ?? effectiveByKey.get(facadeKeyOf(entity))) : own;
378
351
  };
352
+ const presenterFor = (entity) => ownedBy(fronds, container, entity, presenterKeyOf(entity));
379
353
  return { resolve, schemaFor, facadeFor, operationsFor, presenterFor };
380
354
  }
381
355
  /**
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.
356
+ * Registered under the class name, for type-based DI. A logger holds no level — it reads
357
+ * `setLogLevel`'s at each line — and a frond declaring `class X extends Logger` takes the key.
385
358
  */
386
- async function authFor(options, log) {
387
- if (!options.auth)
359
+ function registerBuiltins(container, carry) {
360
+ container.registerValue('Logger', new Logger('app', { carry }));
361
+ container.register('Config', Config, { lifetime: 'singleton' });
362
+ }
363
+ /** `remotes:` IS the topology statement: the frond's code may sit here, it runs elsewhere. */
364
+ function remoteRouterOf(options) {
365
+ const declared = Object.entries(options.remotes ?? {});
366
+ if (declared.length === 0)
388
367
  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.');
368
+ if (!options.remoteTransport) {
369
+ throw new Error('createApp: `remotes` is declared but `remoteTransport` is missing — pass one (e.g. from @fougere/transport-http).');
370
+ }
371
+ return createRemoteRouter(Object.fromEntries(declared), options.remoteTransport);
372
+ }
373
+ /** Every check of a phase, said at once — a boot that stops at the first shows the next after a restart. */
374
+ function refuseWhatDoesNotHold(refused) {
375
+ const refusal = refusalOf(refused, 'declaration(s) that do not hold');
376
+ if (refusal)
377
+ throw refusal;
378
+ }
379
+ /**
380
+ * A `ports:` key no port matched reads as a choice that was made. Said once every frond is
381
+ * installed: the entry is app-wide, and no single frond can tell a typo from a neighbour's port.
382
+ */
383
+ function warnAboutUnboundPorts(options, boundPorts, log) {
384
+ const unbound = Object.keys(options.ports ?? {}).filter((port) => !boundPorts.has(port));
385
+ if (unbound.length === 0)
386
+ return;
387
+ log.warn(`[ports] ${unbound.join(', ')} — named in fougere.config.ts, but no scanned class extends `
388
+ + 'them, so nothing was chosen. Check the spelling, or drop the entry.');
389
+ }
390
+ /** Read from who SUBSCRIBED, so a third party's destination is left alone by the two middlewares that observe every operation. */
391
+ function markLineCarriers(emissions) {
392
+ for (const facade of emissions.facadesFor(LOG_LINE)) {
393
+ CARRIES_LINE.add(addressOf(facade));
394
+ CARRIES_LINE.add(facade);
391
395
  }
392
- if (options.db === undefined) {
393
- throw new Error('createApp: `auth` is set but `db` is missing — pass the storage handle through CreateAppOptions.db.');
396
+ }
397
+ /**
398
+ * A handler another process serves: a stand-in for whoever asks for it by type, and a route for
399
+ * whoever calls it. A dependency names the type as written — `ProductHandler` — while a card
400
+ * declares `product`.
401
+ */
402
+ function answerRemotes({ container, routeRegistry, dispatcher, getMiddlewares }, remoteRouter) {
403
+ container.setFallback((name) => (isFacadeKey(name) ? facadeOperations(dispatcher, addressOf(name)) : undefined));
404
+ const remoteFacades = new Map();
405
+ routeRegistry.addResolver(remoteRoutes((entity) => {
406
+ const known = remoteFacades.get(entity);
407
+ if (known)
408
+ return known;
409
+ const facade = createRemoteFacade(entity, remoteRouter, getMiddlewares);
410
+ remoteFacades.set(entity, facade);
411
+ return facade;
412
+ }));
413
+ }
414
+ /** Refused rather than replaced: two declarations of one name would make the answer depend on wiring order. */
415
+ function serveRpcOn(routeRegistry) {
416
+ return (op, answer) => {
417
+ const address = new RouteAddress({ entity: 'rpc', operation: op });
418
+ if (routeRegistry.find(address)) {
419
+ throw new Error(`[claim] rpc operation '${op}' is already served; a second declaration would depend on wiring order.\n`
420
+ + ' Two extensions declare it — keep one out of `extensions:`.');
421
+ }
422
+ routeRegistry.register(new OperationRoute('system', address, (call) => answer(call.invocation, call.address.surface)));
423
+ };
424
+ }
425
+ /** A frond's extension travels with its code, so it mounts on whichever process serves that frond. */
426
+ function frondExtensions(fronds) {
427
+ return fronds.flatMap((frond) => (frond.extensions ?? []).map((one) => ({ name: one.name, ...one.extension })));
428
+ }
429
+ /**
430
+ * The boot's held lines, and every line after them, handed to the app's destinations — or let go
431
+ * when it has none. After the ascent, because handing them over resolves the destination, and what
432
+ * an extension's destination depends on is registered by that extension's `up`: resolved before,
433
+ * every held line died on `'LogRing' is not registered` (`demos/observability`). A line keeps
434
+ * `at`, when it was WRITTEN, which for a held boot line is not when it is handed over.
435
+ */
436
+ function announceLines(emissions, container, carry) {
437
+ if (!emissions.listensTo().includes(LOG_LINE)) {
438
+ carry.forget();
439
+ return undefined;
394
440
  }
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;
441
+ const emit = container.resolve(emitKeyOf(LogLine.name));
442
+ return carry.to(({ at, ...line }) => void emit({ ...line, at: new Date(at) }));
399
443
  }
400
444
  /** Bootstrap a fougere application. */
401
445
  export async function createApp(options) {
402
446
  const container = (options.createContainer ?? createContainer)();
403
- // Held out here, and not where the ascent reads it, because releasing needs it and
404
- // releasing has to work from the first line the boot takes something.
405
- // The conventional ascent, ordered here: tables, then rows, then whatever the host took
406
- // on. Four hosts assembled these two members themselves — the order is not theirs to
407
- // choose, and a host that forgot lost its migration in silence.
447
+ // Tables, then rows, then whatever the host took on — the order is not a host's to choose.
408
448
  const appLifecycle = new AppLifecycle().add(migrating(options.migrate), seeding(), ...(options.extensions ?? []));
409
- /** The app once it exists — a refusal before that releases the two levels that do. */
410
- let built;
411
- /** Where THIS boot's lines wait — never a process-wide slot, see `Carry`. */
412
449
  const carry = new Carry();
413
- /** Given back by `carry.to`, so a released app stops writing into a dead container. */
450
+ let built;
414
451
  let stopAnnouncing;
415
- /**
416
- * Everything this app holds, let go in reverse of how it was taken: what an extension took on
417
- * last, then the container's own, then whoever handed a resource in.
418
- */
452
+ /** What an extension took on last, then the container's own, then whoever handed a resource in. */
419
453
  const release = async () => {
420
- // Every level is told to close even when one refuses, and the refusals leave together —
421
- // the rule `Lifecycle.down` applies INSIDE its list, applied ACROSS the three. Stated
422
- // there and broken here, a refusing extension took the container and the connection
423
- // down with it, which is the leak this gesture exists to prevent.
424
- const refused = [];
425
- // Whatever is still held will never reach a destination — the console had it.
426
454
  stopAnnouncing?.();
427
455
  carry.forget();
428
- const levels = [
456
+ await closeAll([
429
457
  ...(built ? [() => appLifecycle.down(built)] : []),
430
458
  () => container.dispose(),
431
459
  () => options.onDispose?.(),
432
- ];
433
- for (const level of levels) {
434
- try {
435
- await level();
436
- }
437
- catch (error) {
438
- // Flattened one level: an extension's refusals are already an AggregateError, and
439
- // nesting them would make the caller unwrap twice to read one list.
440
- if (error instanceof AggregateError)
441
- refused.push(...error.errors);
442
- else
443
- refused.push(error);
444
- }
445
- }
446
- if (refused.length > 0) {
447
- throw new AggregateError(refused, `${refused.length} refusal(s) while releasing the app`);
448
- }
460
+ ], 'refusal(s) while releasing the app');
449
461
  };
450
462
  try {
451
- // Boot chatter is debug by default; a host (e.g. the CLI) can quiet it.
452
463
  const log = new Logger('boot:app', { carry });
453
- // Builtins — registered under class name (PascalCase) for type-based DI.
454
- // No level here and none anywhere: a logger consults `setLogLevel`'s value at each
455
- // emission, so this instance survives a level change and so does every handler that
456
- // was handed it. A frond declaring `class X extends Logger` takes this key over,
457
- // like any other port.
458
- container.registerValue('Logger', new Logger('app', { carry }));
459
- container.register('Config', Config, { lifetime: 'singleton' });
464
+ registerBuiltins(container, carry);
460
465
  log.debug('builtins registered (Logger, Config)');
461
466
  const { fronds, operationModel } = await readFronds(options, log);
462
- const authRuntime = await authFor(options, log);
463
- // Remote routing — validated at boot: declaring remotes without a transport is a config error.
464
- // A remote declaration wins over local presence: `remotes: { blog: url }` IS
465
- // the topology statement — the frond's code may sit in fronds/**, it runs elsewhere.
466
- const declaredRemotes = Object.entries(options.remotes ?? {});
467
- if (declaredRemotes.length > 0 && !options.remoteTransport) {
468
- throw new Error('createApp: `remotes` is declared but `remoteTransport` is missing — pass one (e.g. from @fougere/transport-http).');
469
- }
470
- const remoteRouter = declaredRemotes.length > 0 && options.remoteTransport
471
- ? createRemoteRouter(Object.fromEntries(declaredRemotes), options.remoteTransport)
472
- : undefined;
467
+ const remoteRouter = remoteRouterOf(options);
473
468
  const { inflight, routeRegistry, dispatchLifecycle, dispatcher, localDispatcher, getMiddlewares, use } = dispatching(options, log, fronds, () => journalOf());
474
- /** What every check of this boot writes into — refused together, once they have all run. */
475
469
  const refused = [];
476
- const relations = [];
477
470
  keyClaims(fronds, options.remotes, refused);
478
- // Said before anything is installed: a key claimed twice makes every later error worse —
479
- // the route registry collides first, and names a route instead of the two fronds.
480
- const claimed = refusalOf(refused, 'declaration(s) that do not hold');
481
- if (claimed)
482
- throw claimed;
471
+ refuseWhatDoesNotHold(refused);
483
472
  const { entityByName, frondOf, emissions } = whatTheAppKnows(fronds, container, options, refused);
484
- /** Canonical operation tables, indexed by the same audience key as their facades. */
485
473
  const effectiveByKey = new Map();
486
- const contractsOf = (operations) => new Map([...operations].map(([name, operation]) => [name, operation]));
487
- /**
488
- * The storage an entity is backed by — the dual of `facadeFor`, which serves its client-facing
489
- * facade.
490
- */
491
- const storageFor = (entity) => {
492
- const owner = fronds.owner(entity);
493
- if (!owner)
494
- return undefined;
495
- const key = storageKeyOf(entity);
496
- try {
497
- return container.resolve(`frond:${owner.name}`).resolve(key);
498
- }
499
- catch {
500
- return undefined;
501
- }
502
- };
503
- // What carries a release writes none: an instrumentation frond's own rows are kept while a
504
- // release happens, and journalling them would begin one inside the one being written down.
474
+ const storageFor = (entity) => ownedBy(fronds, container, entity, storageKeyOf(entity));
505
475
  const { hosting, journalOf } = hostingFor({
506
- fronds, container, options, declaredRemotes, remoteRouter, entityByName, frondOf, storageOf: storageFor,
476
+ fronds, container, options, remoteRouter, entityByName, frondOf, storageOf: storageFor,
507
477
  });
508
- // Every port an implementation was bound to, so a `ports:` entry that named none
509
- // can say so rather than look obeyed.
478
+ const relations = [];
510
479
  const boundPorts = new Set();
511
- // Register frond scopes
512
- // What every frond is installed into, and reads while it is: one container, one route
513
- // table, one emission list — so what a frond serves is there for the next one to find.
514
480
  const assembly = {
515
481
  container, routeRegistry, emissions, dispatcher, localDispatcher, effectiveByKey,
516
482
  boundPorts, refused, relations, hosting, operationModel, entityByName, frondOf, contractsOf,
@@ -520,67 +486,22 @@ export async function createApp(options) {
520
486
  await installFrond(frond, assembly);
521
487
  warnAboutRelations(relations, hosting, log);
522
488
  refused.push(...unpaired(fronds.flatMap((frond) => frond.entities), hosting));
523
- // Every check of the install, said at once — a boot that stops at the first makes the
524
- // next one visible only after a fix and a restart.
525
- const bootRefusal = refusalOf(refused, 'declaration(s) that do not hold');
526
- if (bootRefusal)
527
- throw bootRefusal;
528
- // A `ports:` key that matched no port anywhere reads as a choice that was made, and
529
- // was not. Said once, at the end, because the entry is app-wide while a port is a
530
- // frond's — no single frond can tell whether a key is a typo or a neighbour's.
531
- const unused = Object.keys(options.ports ?? {}).filter((port) => !boundPorts.has(port));
532
- if (unused.length > 0) {
533
- log.warn(`[ports] ${unused.join(', ')} — named in fougere.config.ts, but no scanned class extends `
534
- + 'them, so nothing was chosen. Check the spelling, or drop the entry.');
535
- }
536
- // Once every facade exists: what is announced here and what is listened to are both known.
489
+ refuseWhatDoesNotHold(refused);
490
+ warnAboutUnboundPorts(options, boundPorts, log);
491
+ // A pipe order and an `Emit<T, A>` are read here, once every facade exists.
537
492
  emissions.register();
538
- // The third phase: what a fact's links and its answer type state. Said after `register`,
539
- // which is where a pipe order and an `Emit<T, A>` are read.
540
- const announced = refusalOf(refused, 'declaration(s) that do not hold');
541
- if (announced)
542
- throw announced;
543
- // Which facades carry a line, read from who SUBSCRIBED — so a third party's destination
544
- // is left alone by the two middlewares that observe every operation.
545
- for (const facade of emissions.facadesFor(LOG_LINE)) {
546
- CARRIES_LINE.add(facade.replace(/Handler$/, '').replace(/^./, (c) => c.toLowerCase()));
547
- CARRIES_LINE.add(facade);
548
- }
549
- /** The last resort, held by the container so every resolution path shares it. */
550
- container.setFallback?.((name) => {
551
- if (!remoteRouter)
552
- return undefined;
553
- if (!name.endsWith('Handler') || name.includes(':'))
554
- return undefined;
555
- // Façade-shaped stand-in; routing happens lazily at the first call. Through
556
- // `lowerFirst` because a DEPENDENCY names the type as written — `ProductHandler`,
557
- // PascalCase — while a card declares `product`, so the raw strip asked the router for
558
- // 'Product' and every by-type dependency on a remote handler answered NOT_FOUND.
559
- return facadeOperations(dispatcher, lowerFirst(name.replace(/Handler$/, '')));
560
- });
561
- if (remoteRouter) {
562
- const remoteFacades = new Map();
563
- routeRegistry.addResolver(remoteRoutes((entity) => {
564
- const known = remoteFacades.get(entity);
565
- if (known)
566
- return known;
567
- const facade = createRemoteFacade(entity, remoteRouter, getMiddlewares);
568
- remoteFacades.set(entity, facade);
569
- return facade;
570
- }));
571
- }
493
+ refuseWhatDoesNotHold(refused);
494
+ markLineCarriers(emissions);
495
+ if (remoteRouter)
496
+ answerRemotes(assembly, remoteRouter);
572
497
  const { resolve, schemaFor, facadeFor, operationsFor, presenterFor } = readings({
573
498
  container, fronds, remoteRouter, localDispatcher, routeRegistry, effectiveByKey, log,
574
499
  });
575
500
  const app = {
576
501
  container,
577
502
  fronds,
578
- // What this app publishes, straight from fougere.config.ts — the facades read it,
579
- // so an undeclared adapter serves nothing whatever a host mounted.
580
503
  adapters: options.adapters ?? {},
581
- // Where a call goes, as DECLARED. Kept because a reader needs it beside what the
582
- // runtime OBSERVED — `rpc.topology` calls a frond remote because it answered, never
583
- // because a key said so, and the two disagree exactly when something is misconfigured.
504
+ // As DECLARED, beside what the runtime observes — the two disagree exactly when something is misconfigured.
584
505
  remotes: Object.freeze({ ...options.remotes }),
585
506
  dispatch: (call) => dispatcher.dispatch(call),
586
507
  local: localDispatcher,
@@ -593,76 +514,29 @@ export async function createApp(options) {
593
514
  storageFor,
594
515
  presenterFor,
595
516
  dispose: release,
596
- drain: (timeoutMs) => drainCalls(inflight, timeoutMs),
517
+ drain: (timeoutMs) => inflight.drain(timeoutMs),
597
518
  inFlight: () => inflight.count,
598
519
  [Symbol.asyncDispose]: release,
599
- serveRpc(op, answer) {
600
- // Refused rather than replaced: two declarations of one name would make the answer
601
- // depend on wiring order, and `discover` is in here precisely so it cannot be taken.
602
- const address = new RouteAddress({ entity: 'rpc', operation: op });
603
- if (routeRegistry.find(address)) {
604
- throw new Error(`[claim] rpc operation '${op}' is already served; a second declaration would depend on wiring order.\n`
605
- + ' Two extensions declare it — keep one out of `extensions:`.');
606
- }
607
- routeRegistry.register(new OperationRoute('system', address, (call) => answer(call.invocation, call.address.surface)));
608
- },
520
+ serveRpc: serveRpcOn(routeRegistry),
609
521
  extensions: () => appLifecycle.names(),
610
- observe(observer) {
611
- return dispatchLifecycle.add(observer);
612
- },
522
+ observe: (observer) => dispatchLifecycle.add(observer),
613
523
  use(...args) {
614
524
  return typeof args[0] === 'string'
615
525
  ? use(args[1], args[0])
616
526
  : use(args[0]);
617
527
  },
618
- auth: authRuntime,
619
528
  };
620
- // The card is an rpc op like any other, so one registry answers and one refusal names
621
- // what is served. A package's op is declared the same way, from outside.
622
- // What a release is, resolved once and registered: a package that drives one asks for it
623
- // by type, the way every other dependency is asked for.
624
529
  container.registerValue('Releasing', releasing(hosting));
625
530
  serveCoreRpc(app, hosting, storageFor);
626
- // The last thing the boot does, and the first thing a release undoes. An extension may
627
- // await here — which is what a provider needing to OPEN something could never do.
628
531
  built = app;
629
- // What the FRONDS declared, folded in after what the host handed over — a frond's
630
- // extension is written beside the code it instruments and travels with it, so it mounts
631
- // on whichever process ends up serving that frond. Added here rather than at the top
632
- // because the fronds are read below that line, and `up` has not run yet.
633
- appLifecycle.add(...fronds.flatMap((frond) => (frond.extensions ?? []).map((one) => ({
634
- name: one.name,
635
- ...one.extension,
636
- }))));
532
+ appLifecycle.add(...frondExtensions(fronds));
637
533
  await appLifecycle.up(app);
638
- // The boot's own lines, and every line after them. Held until here because a boot
639
- // writes most of what a process logs and writes it before any facade exists — so the
640
- // lines that say what this app is made of are the ones a destination would miss.
641
- // `LogLine` is core's for this reason: naming it costs no optional package.
642
- //
643
- // AFTER the ascent, because handing them over RESOLVES the destination, and what a
644
- // destination an extension brought depends on is registered by that same extension's
645
- // `up`: `calls()` registers `LogRing` and `ErrorRing` there, and `KeepHandler` asks for
646
- // both. Resolved before the ascent, every held line died on `'LogRing' is not
647
- // registered` — measured on `demos/observability`.
648
- if (emissions.listensTo().includes(LOG_LINE)) {
649
- const emit = container.resolve(emitKeyOf(LogLine.name));
650
- // `at` is the record's own epoch, and the entity says `created()` — so the line
651
- // keeps WHEN IT WAS WRITTEN rather than when it was handed over, which for a held
652
- // boot line is a different moment.
653
- stopAnnouncing = carry.to(({ at, ...line }) => void emit({ ...line, at: new Date(at) }));
654
- }
655
- else {
656
- // No destination in this app: the console had them, and holding more would grow.
657
- carry.forget();
658
- }
534
+ stopAnnouncing = announceLines(emissions, container, carry);
659
535
  return app;
660
536
  }
661
537
  catch (cause) {
662
- // The caller cannot release what a failed boot took: it handed `onDispose` over before
663
- // this call and never receives the app that would carry it back. Whoever opened a
664
- // connection to give us would otherwise leak it on every refusal — a source, a scan
665
- // that threw, a port bound twice, and not only an extension that refused to rise.
538
+ // The caller never receives the app that would carry `onDispose` back, so a refused boot
539
+ // releases what it took itself — a source, a scan that threw, a port bound twice.
666
540
  try {
667
541
  await release();
668
542
  }
@@ -672,4 +546,7 @@ export async function createApp(options) {
672
546
  throw cause;
673
547
  }
674
548
  }
549
+ function contractsOf(operations) {
550
+ return new Map([...operations].map(([name, operation]) => [name, operation]));
551
+ }
675
552
  //# sourceMappingURL=bootstrap.js.map