@bitakit/core 0.1.1 → 0.2.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 (158) hide show
  1. package/README.md +47 -161
  2. package/assets/bitakit-logo-dark.svg +11 -0
  3. package/assets/bitakit-logo.svg +11 -0
  4. package/discovery/index.d.ts +1 -41
  5. package/discovery/index.mjs +1 -4
  6. package/dist/actions/action-list.d.ts +4 -0
  7. package/dist/actions/action-list.js +58 -16
  8. package/dist/actions/action.d.ts +2 -0
  9. package/dist/actions/action.js +4 -0
  10. package/dist/actions/brand.d.ts +21 -0
  11. package/dist/actions/brand.js +36 -0
  12. package/dist/actions/core.d.ts +4 -3
  13. package/dist/actions/core.js +4 -2
  14. package/dist/actions/execution.d.ts +2 -2
  15. package/dist/actions/execution.js +61 -9
  16. package/dist/actions/feedback.d.ts +2 -0
  17. package/dist/actions/feedback.js +8 -0
  18. package/dist/actions/groups.js +5 -1
  19. package/dist/actions/instance-bindings.js +3 -2
  20. package/dist/actions/interceptors.d.ts +9 -3
  21. package/dist/actions/interceptors.js +31 -3
  22. package/dist/actions/navigation.d.ts +2 -1
  23. package/dist/actions/navigation.js +10 -5
  24. package/dist/actions/reference.js +10 -5
  25. package/dist/actions/types.d.ts +9 -1
  26. package/dist/app/access.d.ts +4 -4
  27. package/dist/app/access.js +33 -71
  28. package/dist/app/action-access.d.ts +2 -2
  29. package/dist/app/action-access.js +6 -4
  30. package/dist/app/service-error.d.ts +2 -2
  31. package/dist/app/service-error.js +10 -6
  32. package/dist/app/types.d.ts +76 -33
  33. package/dist/config-service.d.ts +30 -6
  34. package/dist/config-service.js +25 -9
  35. package/dist/configuration.d.ts +6 -3
  36. package/dist/configuration.js +8 -6
  37. package/dist/contracts.d.ts +4 -2
  38. package/dist/contracts.js +3 -3
  39. package/dist/contribution-origin.d.ts +4 -1
  40. package/dist/contribution-origin.js +14 -1
  41. package/dist/contributions/action.d.ts +26 -0
  42. package/dist/contributions/action.js +171 -0
  43. package/dist/contributions/host.d.ts +14 -11
  44. package/dist/contributions/index.d.ts +1 -26
  45. package/dist/contributions/index.js +1 -18
  46. package/dist/conventions.d.ts +8 -4
  47. package/dist/conventions.js +12 -31
  48. package/dist/core.d.ts +41 -18
  49. package/dist/core.js +25 -13
  50. package/dist/definitions.d.ts +272 -306
  51. package/dist/definitions.js +28 -56
  52. package/dist/destinations.d.ts +25 -0
  53. package/dist/destinations.js +21 -0
  54. package/dist/discovered.d.ts +52 -21
  55. package/dist/discovered.js +89 -35
  56. package/dist/events/define.d.ts +43 -0
  57. package/dist/events/define.js +17 -0
  58. package/dist/events/service.d.ts +35 -8
  59. package/dist/events/service.js +184 -42
  60. package/dist/events/types.d.ts +29 -9
  61. package/dist/inspection/inventory.d.ts +86 -0
  62. package/dist/inspection/inventory.js +132 -0
  63. package/dist/interceptors/define.d.ts +76 -0
  64. package/dist/interceptors/define.js +23 -0
  65. package/dist/interceptors/service-observers.d.ts +6 -3
  66. package/dist/interceptors/service-observers.js +13 -10
  67. package/dist/lifecycle/cleanup.d.ts +5 -0
  68. package/dist/lifecycle/cleanup.js +41 -0
  69. package/dist/lifecycle/controller.d.ts +82 -0
  70. package/dist/lifecycle/controller.js +276 -0
  71. package/dist/lifecycle/reconcile.d.ts +19 -0
  72. package/dist/lifecycle/reconcile.js +68 -0
  73. package/dist/lifecycle/state.d.ts +53 -0
  74. package/dist/lifecycle/state.js +86 -0
  75. package/dist/names.d.ts +10 -0
  76. package/dist/names.js +1 -0
  77. package/dist/pages.d.ts +39 -6
  78. package/dist/pages.js +93 -11
  79. package/dist/presentation.d.ts +9 -0
  80. package/dist/runtime.d.ts +166 -28
  81. package/dist/runtime.js +1485 -248
  82. package/dist/schema.d.ts +13 -0
  83. package/dist/schema.js +38 -0
  84. package/dist/scope.d.ts +59 -4
  85. package/dist/scope.js +133 -11
  86. package/dist/service-key.d.ts +33 -14
  87. package/dist/service-key.js +21 -5
  88. package/dist/service-names.d.ts +39 -0
  89. package/dist/service-names.js +175 -0
  90. package/dist/services.d.ts +24 -5
  91. package/dist/services.js +230 -37
  92. package/dist/settings/access.d.ts +19 -0
  93. package/dist/settings/access.js +78 -0
  94. package/dist/settings/define.d.ts +97 -0
  95. package/dist/settings/define.js +83 -0
  96. package/dist/settings/storage.d.ts +45 -0
  97. package/dist/settings/storage.js +102 -0
  98. package/dist/settings/store.d.ts +74 -0
  99. package/dist/settings/store.js +345 -0
  100. package/dist/slots/action-placement.d.ts +47 -0
  101. package/dist/slots/action-placement.js +1 -0
  102. package/dist/slots/define.d.ts +52 -0
  103. package/dist/slots/define.js +12 -0
  104. package/dist/slots/normalize.d.ts +7 -0
  105. package/dist/slots/normalize.js +36 -0
  106. package/dist/slots/runtime.d.ts +43 -0
  107. package/dist/slots/runtime.js +348 -0
  108. package/dist/slots/types.d.ts +113 -0
  109. package/dist/slots/types.js +1 -0
  110. package/dist/startup-error.d.ts +21 -0
  111. package/dist/startup-error.js +29 -0
  112. package/dist/store.d.ts +24 -0
  113. package/dist/store.js +40 -0
  114. package/dist/translation.d.ts +9 -4
  115. package/dist/translation.js +2 -3
  116. package/examples/todos/actions/create.mjs +1 -3
  117. package/examples/todos/actions/delete.mjs +3 -10
  118. package/examples/todos/actions/list.mjs +1 -3
  119. package/examples/todos/events.mjs +5 -0
  120. package/examples/todos/plugin.mjs +4 -2
  121. package/examples/todos/services/tasks.mjs +14 -20
  122. package/examples/todos.mjs +8 -7
  123. package/package.json +37 -9
  124. package/testing/index.d.ts +59 -0
  125. package/testing/index.mjs +150 -0
  126. package/discovery/entries.mjs +0 -124
  127. package/discovery/generate.mjs +0 -321
  128. package/discovery/host.mjs +0 -12
  129. package/discovery/modules.mjs +0 -13
  130. package/discovery/packages.mjs +0 -57
  131. package/discovery/watch.mjs +0 -23
  132. package/dist/app/service-aliases.d.ts +0 -4
  133. package/dist/app/service-aliases.js +0 -14
  134. package/dist/contributions/command.d.ts +0 -8
  135. package/dist/contributions/command.js +0 -59
  136. package/dist/contributions/dialog.d.ts +0 -8
  137. package/dist/contributions/dialog.js +0 -18
  138. package/dist/contributions/form.d.ts +0 -10
  139. package/dist/contributions/form.js +0 -67
  140. package/dist/contributions/native.d.ts +0 -11
  141. package/dist/contributions/native.js +0 -87
  142. package/dist/contributions/shared.d.ts +0 -19
  143. package/dist/contributions/shared.js +0 -48
  144. package/dist/contributions/stateful-action.d.ts +0 -29
  145. package/dist/contributions/stateful-action.js +0 -33
  146. package/dist/events/action-setup.d.ts +0 -19
  147. package/dist/events/action-setup.js +0 -24
  148. package/dist/interceptors/service.d.ts +0 -37
  149. package/dist/interceptors/service.js +0 -7
  150. package/dist/replacements.d.ts +0 -22
  151. package/dist/replacements.js +0 -54
  152. package/dist/validation.d.ts +0 -2
  153. package/dist/validation.js +0 -16
  154. package/docs/auth.md +0 -106
  155. package/docs/events.md +0 -157
  156. package/docs/file-contributions.md +0 -174
  157. package/docs/reference.md +0 -404
  158. package/docs/todo-tutorial.md +0 -88
package/dist/runtime.js CHANGED
@@ -1,59 +1,252 @@
1
1
  import { EventService, createEventScope } from './events/service.js';
2
- import { setupAction } from './events/action-setup.js';
3
- import { serviceObserver } from './interceptors/service-observers.js';
4
- import { isServiceInterceptor } from './interceptors/service.js';
2
+ import { normalizeSlots, validateSlotDeclarations } from './slots/normalize.js';
3
+ import { SlotRuntime } from './slots/runtime.js';
5
4
  import { ConfigService } from './config-service.js';
6
- import { contributionPath } from './contribution-origin.js';
7
- import { applyActionReplacements } from './replacements.js';
8
- import { validatePluginPages } from './pages.js';
5
+ import { contributionPath, contributionSource, preserveContributionPath, setContributionPath, } from './contribution-origin.js';
6
+ import { ServiceNames } from './service-names.js';
7
+ import { BitaKitStartupError, isBitaKitStartupError, moduleLabel } from './startup-error.js';
8
+ import { findPluginPage, validatePluginPages } from './pages.js';
9
+ import { projectedDestination } from './destinations.js';
9
10
  import { resolveText } from './translation.js';
10
- import { ActionGroup, } from '@bitakit/core/actions';
11
- import { PluginScope, assignScopeModule } from './scope.js';
11
+ import { ActionGroup, createActionList, } from '@bitakit/core/actions';
12
+ import { PluginScope, assignScopeModule, scopeModule, readsComposition } from './scope.js';
13
+ import { SettingsStore } from './settings/store.js';
14
+ import { createSettingsAccess } from './settings/access.js';
15
+ import { createLocalSettingsStorage } from './settings/storage.js';
16
+ import { isSettingsDefinition } from './settings/define.js';
17
+ import { translationService } from './contracts.js';
18
+ import { getService } from './service-key.js';
12
19
  import { createServices } from './services.js';
13
- import { createFoundationApp } from './app/access.js';
14
- import { serviceAliases } from './app/service-aliases.js';
15
- import { fallbackTitle } from './conventions.js';
16
- import { ActionFailure, evaluateFeedback, } from './actions/feedback.js';
17
- import { adaptContribution, } from './contributions/index.js';
18
- function orderPlugins(plugins) {
19
- const remaining = new Map(plugins.map((plugin) => [plugin.id, plugin]));
20
- if (remaining.size !== plugins.length)
21
- throw new Error('Duplicate plugin ID.');
20
+ import { createBitaKitApp } from './app/access.js';
21
+ import { fallbackTitle, resolveContribution } from './conventions.js';
22
+ import { isActionFailure, evaluateFeedback, } from './actions/feedback.js';
23
+ import { adaptAction, } from './contributions/index.js';
24
+ import { isServiceInterceptor, matchesTarget, } from './interceptors/define.js';
25
+ import { serviceObserver } from './interceptors/service-observers.js';
26
+ import { cleanupSequence, cleanupFailure } from './lifecycle/cleanup.js';
27
+ import { createLifecycleState, } from './lifecycle/state.js';
28
+ import { updateClosure, updateRestrictions, } from './lifecycle/reconcile.js';
29
+ function attributed(error, plugin, what, appId) {
30
+ if (isBitaKitStartupError(error))
31
+ return error;
32
+ const message = error instanceof Error ? error.message : String(error);
33
+ return new BitaKitStartupError(`${what} in ${moduleLabel(plugin, appId)}: ${message}`, plugin, {
34
+ cause: error,
35
+ app: plugin === appId,
36
+ });
37
+ }
38
+ function normalize(module, appId) {
39
+ const id = module.id;
40
+ const isApp = id === appId;
41
+ try {
42
+ const services = Array.isArray(module.services)
43
+ ? module.services.map((service) => {
44
+ // A contract key doubles as the ID of an array entry, as provideService did before.
45
+ const serviceId = service.id ?? service.provides;
46
+ if (!serviceId)
47
+ throw new Error('A service in an array needs an id. Prefer a record: services: { items: service }.');
48
+ return preserveContributionPath(service, {
49
+ ...service,
50
+ id: serviceId,
51
+ });
52
+ })
53
+ : Object.entries((module.services ?? {})).map(([key, service]) => preserveContributionPath(service, {
54
+ ...service,
55
+ id: service.id ?? (isApp ? key : `${id}.${key}`),
56
+ }));
57
+ const actions = Array.isArray(module.actions)
58
+ ? module.actions.map((action) => {
59
+ const resolved = resolveContribution(action);
60
+ if (!contributionPath(resolved))
61
+ setContributionPath(resolved, resolved.id.startsWith(`${id}.`)
62
+ ? resolved.id.slice(id.length + 1).split('.')
63
+ : resolved.id.split('.'), contributionSource(resolved));
64
+ return resolved;
65
+ })
66
+ : Object.entries((module.actions ?? {})).map(([key, action]) => {
67
+ const resolved = resolveContribution(action, isApp ? key : `${id}.${key}`);
68
+ if (!contributionPath(resolved))
69
+ setContributionPath(resolved, key.split('.'), contributionSource(resolved));
70
+ return resolved;
71
+ });
72
+ if (module.settings !== undefined && !isSettingsDefinition(module.settings))
73
+ throw new Error('settings must be declared with defineSettings({ ... }) in settings.ts.');
74
+ if (module.parent === id)
75
+ throw new Error('A plugin cannot be its own parent.');
76
+ return {
77
+ ...module,
78
+ id,
79
+ // The owner is a dependency: it starts first and stops last.
80
+ ...(module.parent && !module.dependencies?.includes(module.parent)
81
+ ? { dependencies: [...(module.dependencies ?? []), module.parent] }
82
+ : {}),
83
+ services,
84
+ actions,
85
+ slots: normalizeSlots(module, appId),
86
+ pages: module.ui?.pages ?? [],
87
+ views: module.ui?.slots ?? [],
88
+ providers: module.ui?.providers ?? [],
89
+ };
90
+ }
91
+ catch (error) {
92
+ throw attributed(error, id, 'Plugin definition', appId);
93
+ }
94
+ }
95
+ /** Installed plugins owned, directly or through other children, by any of `ids`. */
96
+ function descendantsOf(installed, ids) {
97
+ const found = [];
98
+ for (let frontier = [...ids]; frontier.length;) {
99
+ const children = installed
100
+ .filter((plugin) => plugin.parent && frontier.includes(plugin.parent))
101
+ .map((plugin) => plugin.id)
102
+ .filter((id) => !found.includes(id) && !ids.includes(id));
103
+ found.push(...children);
104
+ frontier = children;
105
+ }
106
+ return found;
107
+ }
108
+ function orderPlugins(plugins, appId) {
109
+ const remaining = new Map();
110
+ for (const plugin of plugins) {
111
+ if (remaining.has(plugin.id))
112
+ throw new BitaKitStartupError(`Plugin ID "${plugin.id}" is used twice. Rename one plugin folder or set a different id in plugin.config.ts.`, plugin.id, { app: plugin.id === appId });
113
+ remaining.set(plugin.id, plugin);
114
+ }
22
115
  const ordered = [];
23
116
  while (remaining.size) {
24
- const plugin = [...remaining.values()].find((item) => item.dependencies?.every((id) => ordered.some((done) => done.id === id)) ?? true);
25
- if (!plugin)
26
- throw new Error('Missing or cyclic plugin dependency.');
27
- ordered.push(plugin);
28
- remaining.delete(plugin.id);
117
+ const plugin = [...remaining.values()].find((item) => (item.dependencies ?? []).every((id) => ordered.some((done) => done.id === id)));
118
+ if (plugin) {
119
+ ordered.push(plugin);
120
+ remaining.delete(plugin.id);
121
+ continue;
122
+ }
123
+ for (const item of remaining.values()) {
124
+ const missing = (item.dependencies ?? []).find((id) => !plugins.some((candidate) => candidate.id === id));
125
+ if (missing)
126
+ throw new BitaKitStartupError(missing === item.parent
127
+ ? `Plugin "${item.id}" belongs to "${missing}", which is not installed or is disabled. Install or enable "${missing}" first.`
128
+ : `Plugin "${item.id}" depends on "${missing}", which is not installed or is disabled. Known plugins: ${plugins.map((candidate) => candidate.id).join(', ')}.`, item.id, { app: item.id === appId });
129
+ }
130
+ const path = [];
131
+ let current = remaining.keys().next().value;
132
+ while (!path.includes(current)) {
133
+ path.push(current);
134
+ current = (remaining.get(current).dependencies ?? []).find((id) => remaining.has(id));
135
+ }
136
+ const cycle = [...path.slice(path.indexOf(current)), current];
137
+ throw new BitaKitStartupError(`Plugin dependency cycle: ${cycle.join(' → ')}. Break it with an event or a shared service that both can require.`, cycle[0], { app: cycle[0] === appId });
29
138
  }
30
139
  return ordered;
31
140
  }
141
+ function deferred() {
142
+ let resolve;
143
+ let reject;
144
+ const promise = new Promise((done, fail) => {
145
+ resolve = done;
146
+ reject = fail;
147
+ });
148
+ promise.catch(() => { });
149
+ return { promise, resolve, reject };
150
+ }
32
151
  /**
33
- * Mounts plugins into the host's ActionList. Each contribution kind is normalized by an adapter
34
- * in `./contributions`; the runtime owns services, translation, dialogs, ordering and cleanup.
152
+ * Mounts plugins into the host's ActionList. The runtime owns services, events, translation,
153
+ * dialogs, confirmation, ordering and cleanup; every contribution goes through one adapter.
35
154
  */
36
- export class FoundationRuntime {
155
+ export class BitaKitRuntime {
37
156
  actions;
38
- config;
39
157
  providedServices;
40
158
  app;
41
159
  events;
42
160
  configuration;
43
- modules;
161
+ currentModules;
162
+ get modules() {
163
+ return this.currentModules;
164
+ }
165
+ currentConfig;
166
+ get config() {
167
+ return this.currentConfig;
168
+ }
169
+ groups;
170
+ /** The owner of setting values; `useSetting` and the `settings` contexts read from it. */
171
+ settings;
172
+ /** Typed handles under plugin namespaces, the `settings` every context receives. */
173
+ settingsAccess;
174
+ defaultStorage;
175
+ appId;
176
+ order;
177
+ names;
44
178
  actionConfigs = new Map();
45
- ready = false;
179
+ mounted = false;
180
+ mounting = false;
181
+ tearingDown = false;
182
+ lifecycle;
183
+ slots;
184
+ slotRuntime;
185
+ lifecycleState;
186
+ generation = 0;
187
+ stopCompletion;
188
+ mountStop;
189
+ startWork;
190
+ startPending = false;
191
+ setupComplete = false;
192
+ activeRuns = new Map();
193
+ updating;
194
+ updateController;
195
+ disabledPlugins = new Set();
196
+ /** Descendants a parent's disable switched off, so enabling the parent restores exactly them. */
197
+ disabledWithParent = new Map();
198
+ /** Host-only structural changes; no package loading or persistence is performed by Core. */
199
+ plugins = Object.freeze({
200
+ add: (plugins) => this.changePlugins('add', [...plugins]),
201
+ remove: (ids, options) => this.changePlugins('remove', [...ids], options),
202
+ enable: (id) => this.changePlugins('enable', [id]),
203
+ disable: (id, options) => this.changePlugins('disable', [id], options),
204
+ });
205
+ revision = 0;
206
+ getRevision = () => this.revision;
207
+ observations = new Map();
208
+ pluginEvents = new Map();
209
+ /** Settles after the current shutdown; a rejection means cleanup did not complete successfully. */
210
+ get stopped() {
211
+ return this.stopCompletion?.promise ?? Promise.resolve();
212
+ }
213
+ stop = () => this.mountStop?.() ?? Promise.resolve();
46
214
  readinessListeners = new Set();
47
- isReady = () => this.ready;
215
+ readyDeferred = deferred();
216
+ startController;
217
+ /** Initial startup has completed and shutdown has not begun. Updates use owner readiness. */
218
+ isReady = (plugin) => this.mounted &&
219
+ (plugin === undefined ||
220
+ this.lifecycle.get().plugins.some((entry) => entry.id === plugin && entry.phase === 'ready'));
48
221
  subscribeReady = (listener) => {
49
222
  this.readinessListeners.add(listener);
50
223
  return () => {
51
224
  this.readinessListeners.delete(listener);
52
225
  };
53
226
  };
227
+ /** Resolves when every service's `onStart` has completed; rejects with the attributed startup error. */
228
+ get ready() {
229
+ return this.readyDeferred.promise;
230
+ }
54
231
  setReady(ready) {
55
- this.ready = ready;
56
- this.readinessListeners.forEach((listener) => listener());
232
+ this.mounted = ready;
233
+ for (const listener of this.readinessListeners) {
234
+ try {
235
+ listener();
236
+ }
237
+ catch (error) {
238
+ this.reportLifecycleError(error);
239
+ }
240
+ }
241
+ // Presentation may read app.ready.
242
+ if (this.container) {
243
+ try {
244
+ this.actions.refresh();
245
+ }
246
+ catch (error) {
247
+ this.reportLifecycleError(error);
248
+ }
249
+ }
57
250
  }
58
251
  listeners = new Set();
59
252
  state = null;
@@ -61,75 +254,199 @@ export class FoundationRuntime {
61
254
  scopes = [];
62
255
  extensionCleanups = [];
63
256
  container;
257
+ view;
64
258
  translate = (key) => key;
65
259
  translationRevision = 0;
66
260
  translationListeners = new Set();
67
261
  getTranslationRevision = () => this.translationRevision;
68
262
  subscribeTranslations = (listener) => {
69
263
  this.translationListeners.add(listener);
70
- return () => { this.translationListeners.delete(listener); };
264
+ return () => {
265
+ this.translationListeners.delete(listener);
266
+ };
71
267
  };
72
268
  notifier;
73
- formFeedback = new WeakMap();
74
- groups;
269
+ confirmHandler;
270
+ confirmWarned = false;
75
271
  constructor(actions, config, providedServices = {}) {
76
272
  this.actions = actions;
77
- this.config = config;
78
273
  this.providedServices = providedServices;
79
- this.modules = [
80
- { ...config, id: config.appId ?? '@foundation/app' },
81
- ...(config.plugins ?? []),
82
- ].map((module) => ({ ...module, publicServices: serviceAliases(module) }));
274
+ this.currentConfig = config;
275
+ this.appId = config.appId ?? 'app';
276
+ const { plugins = [], appId: _appId, ...appModule } = config;
277
+ this.currentModules = [
278
+ normalize({ ...appModule, id: this.appId }, this.appId),
279
+ ...plugins.map((plugin) => normalize(plugin, this.appId)),
280
+ ];
281
+ this.order = orderPlugins(this.modules, this.appId);
282
+ validateSlotDeclarations(this.modules, this.appId);
83
283
  this.events = new EventService(config.onEventError);
84
- this.app = createFoundationApp(this);
85
- this.configuration = new ConfigService([{ id: config.appId ?? '@foundation/app', config: config.config }, ...(config.plugins ?? [])], config.configOverrides);
86
- validatePluginPages(this.modules);
87
- if (new Set(config.groups ?? []).size !== (config.groups ?? []).length)
88
- throw new Error('Duplicate action group.');
89
- this.groups = new Map((config.groups ?? []).map((id) => [id, new ActionGroup(id)]));
284
+ const publishLifecycle = this.events.reserve('runtime');
285
+ this.lifecycleState = createLifecycleState(this.modules.map((module) => module.id), this.serviceEntries().filter((entry) => !Object.hasOwn(this.providedServices, entry.id)), (snapshot) => publishLifecycle('runtime.lifecycle', snapshot), (error) => this.reportLifecycleError(error));
286
+ this.lifecycle = this.lifecycleState.state;
287
+ this.slotRuntime = new SlotRuntime(this.modules.flatMap((module) => module.slots), this.lifecycle, this.actions, (snapshot) => publishLifecycle('runtime.slot', snapshot), (error) => this.reportLifecycleError(error), this.appId);
288
+ this.slots = this.slotRuntime.reader;
289
+ for (const module of this.modules)
290
+ if (module.events) {
291
+ try {
292
+ this.events.declare(module.id, module.events);
293
+ }
294
+ catch (error) {
295
+ throw attributed(error, module.id, 'Event declaration', this.appId);
296
+ }
297
+ }
298
+ this.names = new ServiceNames(this.serviceEntries(), this.appId);
299
+ try {
300
+ this.settings = new SettingsStore(this.settingEntries(), () => this.storage());
301
+ this.settingsAccess = createSettingsAccess(this.settings);
302
+ }
303
+ catch (error) {
304
+ throw attributed(error, this.appId, 'Settings', this.appId);
305
+ }
306
+ this.app = createBitaKitApp(this);
307
+ try {
308
+ this.configuration = new ConfigService(this.modules.map((module) => ({ id: module.id, config: module.config })), config.configOverrides);
309
+ }
310
+ catch (error) {
311
+ throw attributed(error, this.appId, 'Configuration', this.appId);
312
+ }
313
+ validatePluginPages(this.modules, new Set(Object.keys(this.modules.find((module) => module.id === this.appId)?.ui?.layouts ?? {})));
314
+ const groups = config.groups ?? [];
315
+ const duplicate = groups.find((id, index) => groups.indexOf(id) !== index);
316
+ if (duplicate)
317
+ throw new Error(`Action group "${duplicate}" is listed twice in groups.`);
318
+ this.groups = new Map(groups.map((id) => [id, new ActionGroup(id)]));
90
319
  }
91
- get appId() {
92
- return this.config.appId ?? '@foundation/app';
320
+ serviceEntries(modules = this.modules) {
321
+ const entries = Object.keys(this.providedServices).map((id) => ({
322
+ id,
323
+ aliases: [],
324
+ plugin: this.appId,
325
+ }));
326
+ for (const module of modules) {
327
+ for (const service of module.services)
328
+ entries.push({
329
+ id: service.id,
330
+ aliases: [service.exposeAs, service.provides].filter((alias) => typeof alias === 'string'),
331
+ plugin: module.id,
332
+ });
333
+ }
334
+ return entries;
93
335
  }
94
- order;
95
- /** Modules in install order: dependencies first, the application module included. */
96
- moduleOrder() {
97
- this.order ??= orderPlugins([
98
- {
99
- id: this.appId,
100
- dependencies: this.config.dependencies,
101
- contributions: this.config.contributions,
102
- installs: this.config.installs,
103
- },
104
- ...(this.config.plugins ?? []),
105
- ]);
106
- return this.order;
336
+ settingEntries(modules = this.modules) {
337
+ const entries = [];
338
+ for (const module of modules)
339
+ for (const [name, spec] of Object.entries((module.settings?.settings ?? {})))
340
+ entries.push({
341
+ key: module.id === this.appId ? name : `${module.id}.${name}`,
342
+ plugin: module.id,
343
+ name,
344
+ spec,
345
+ });
346
+ return entries;
347
+ }
348
+ /** The `settings.storage` contract when a service provides it, otherwise browser storage. */
349
+ storage() {
350
+ const name = 'settings.storage';
351
+ if (this.hasService(name))
352
+ return this.container.services[this.names.key(name)];
353
+ return (this.defaultStorage ??= createLocalSettingsStorage());
107
354
  }
108
355
  /**
109
- * Declarative contributions of one kind in install order. Pure and available before mount, so
110
- * UI integrations can derive an initial render snapshot equivalent to the mounted state.
356
+ * Loads settings for the identity the `auth` contract reports. Runs after setup and whenever
357
+ * an observed service changes, so no extra subscription is needed; without authentication the
358
+ * anonymous device identity applies. Never blocks readiness.
111
359
  */
360
+ syncIdentity() {
361
+ if (!this.container)
362
+ return;
363
+ const auth = this.hasService('auth')
364
+ ? this.container.services[this.names.key('auth')]
365
+ : undefined;
366
+ const snapshot = typeof auth?.getSnapshot === 'function' ? auth.getSnapshot() : undefined;
367
+ if (snapshot?.pending)
368
+ return;
369
+ const next = {
370
+ userId: snapshot?.user?.id,
371
+ organizationId: snapshot?.organizationId ?? undefined,
372
+ };
373
+ const current = this.settings.currentIdentity;
374
+ if (this.settings.isActive &&
375
+ next.userId === current.userId &&
376
+ next.organizationId === current.organizationId)
377
+ return;
378
+ void this.settings.activate(next);
379
+ }
380
+ /** Every name (ID and aliases) that resolves to a container key. */
381
+ aliasesOf(id) {
382
+ return this.names.names().filter((name) => name !== id && this.names.key(name) === id);
383
+ }
384
+ /** Declarative contributions of one kind in install order; available before mount. */
112
385
  contributionsOf(kind) {
113
- return this.moduleOrder().flatMap((module) => {
386
+ return this.order.flatMap((module) => {
114
387
  const values = module.contributions?.[kind];
115
388
  return values?.length
116
389
  ? [{ module: module.id, app: module.id === this.appId, values: values }]
117
390
  : [];
118
391
  });
119
392
  }
393
+ /** What a URL Action leads to and which plugin owns it, from existing registrations. */
394
+ destinationOf(action) {
395
+ const owner = (plugin) => (plugin && plugin !== this.appId ? { plugin } : {});
396
+ const projected = projectedDestination(action.metadata);
397
+ if (projected)
398
+ return { kind: projected.kind, ...owner(projected.plugin) };
399
+ const href = action.href;
400
+ if (!href?.startsWith('/') || href.startsWith('//'))
401
+ return undefined;
402
+ const page = findPluginPage(this.modules, href.split(/[?#]/)[0]);
403
+ return { kind: 'page', ...owner(page ? page.plugin : this.ownerOf(action.id)) };
404
+ }
405
+ actionOwner(id) {
406
+ const registered = this.actionConfigs.get(id)?.module;
407
+ if (registered)
408
+ return registered;
409
+ const scope = this.scopes.find((scope) => scope.ownsAction(id));
410
+ return scope ? scopeModule(scope).id : undefined;
411
+ }
412
+ ownerOf(id) {
413
+ const module = this.actionConfigs.get(id)?.module;
414
+ return module && module !== this.appId ? module : undefined;
415
+ }
416
+ /** One group per ID; the first title given for an ID is kept. */
120
417
  getGroup = (entry) => {
121
418
  const id = typeof entry === 'string' ? entry : entry.id;
122
- let group = this.groups.get(id);
123
- if (!group) {
124
- group = typeof entry === 'string' ? new ActionGroup(id) : entry;
125
- this.groups.set(id, group);
126
- }
127
- return group;
419
+ const group = this.groups.get(id);
420
+ if (group &&
421
+ (typeof entry === 'string' || group.title !== undefined || entry.title === undefined))
422
+ return group;
423
+ const next = typeof entry === 'string' ? new ActionGroup(id) : entry;
424
+ this.groups.set(id, next);
425
+ return next;
128
426
  };
427
+ /** The live service tree every contribution sees. */
129
428
  get services() {
130
- if (!this.container)
131
- throw new Error('Foundation is not mounted.');
132
- return this.container.services;
429
+ if (!this.view)
430
+ throw new Error('The BitaKit runtime is not mounted.');
431
+ return this.view;
432
+ }
433
+ servicesIfMounted() {
434
+ return this.mounted ? this.view : undefined;
435
+ }
436
+ hasService(name) {
437
+ return (!!this.container &&
438
+ this.names.known(name) &&
439
+ Object.hasOwn(this.container.services, this.names.key(name)));
440
+ }
441
+ /** UI availability; raw service access remains available to dependent cleanup hooks. */
442
+ isServiceReady(name) {
443
+ if (!this.isReady() || !this.hasService(name))
444
+ return false;
445
+ const id = this.names.key(name);
446
+ if (Object.hasOwn(this.providedServices, id))
447
+ return true;
448
+ const entry = this.lifecycle.get().services.find((service) => service.id === id);
449
+ return entry?.phase === 'ready' && this.isReady(entry.plugin);
133
450
  }
134
451
  getSnapshot = () => this.state;
135
452
  getServerSnapshot = () => null;
@@ -141,26 +458,37 @@ export class FoundationRuntime {
141
458
  };
142
459
  publish(state) {
143
460
  this.state = state;
144
- this.listeners.forEach((listener) => listener());
461
+ for (const listener of this.listeners) {
462
+ try {
463
+ listener();
464
+ }
465
+ catch (error) {
466
+ this.reportLifecycleError(error);
467
+ }
468
+ }
145
469
  }
146
470
  t = (key) => this.translate(key);
147
471
  text(key, fallback, values) {
148
472
  return resolveText(this.translate, key, fallback, values);
149
473
  }
150
474
  title(definition) {
475
+ if (typeof definition.title === 'function')
476
+ return fallbackTitle(definition);
151
477
  return definition.title !== undefined
152
478
  ? this.text(definition.title, this.text(`${definition.id}.title`, definition.title))
153
- : this.text(definition.conventions !== false ? `${definition.id}.title` : undefined, fallbackTitle(definition));
479
+ : this.text(`${definition.id}.title`, fallbackTitle(definition));
154
480
  }
155
481
  description(definition) {
482
+ if (typeof definition.description === 'function')
483
+ return undefined;
156
484
  return definition.description === undefined
157
- ? undefined
485
+ ? this.text(`${definition.id}.description`, '') || undefined
158
486
  : this.text(definition.description, this.text(`${definition.id}.description`, definition.description));
159
487
  }
160
- fieldLabel(definition, name, field) {
161
- const key = field.label ??
162
- (definition.conventions !== false ? `${definition.id}.fields.${name}` : undefined);
163
- return this.text(key, field.label ?? name.charAt(0).toUpperCase() + name.slice(1));
488
+ tooltip(definition) {
489
+ if (typeof definition.tooltip === 'function' || definition.tooltip === undefined)
490
+ return undefined;
491
+ return this.text(definition.tooltip, this.text(`${definition.id}.tooltip`, definition.tooltip));
164
492
  }
165
493
  /** Installs one presentation sink; disposing an older owner cannot clear its replacement. */
166
494
  setNotifier(notify) {
@@ -170,7 +498,6 @@ export class FoundationRuntime {
170
498
  this.notifier = undefined;
171
499
  };
172
500
  }
173
- /** Presentation failures, including rejected promises, never change the Action outcome. */
174
501
  notify(message, kind = 'success') {
175
502
  if (!message)
176
503
  return;
@@ -181,6 +508,23 @@ export class FoundationRuntime {
181
508
  /* presentation only */
182
509
  }
183
510
  }
511
+ /** Installs the host's confirmation dialog for actions with `confirm`. */
512
+ setConfirm(handler) {
513
+ this.confirmHandler = handler;
514
+ return () => {
515
+ if (this.confirmHandler === handler)
516
+ this.confirmHandler = undefined;
517
+ };
518
+ }
519
+ async confirm(request) {
520
+ if (this.confirmHandler)
521
+ return this.confirmHandler(request);
522
+ if (!this.confirmWarned) {
523
+ this.confirmWarned = true;
524
+ console.warn('[bitakit] An action asks for confirmation, but no confirmation handler is installed. Proceeding without asking.');
525
+ }
526
+ return true;
527
+ }
184
528
  translator() {
185
529
  const translate = (key, values) => this.translate(key, values);
186
530
  translate.has = (key) => this.translate.has?.(key) ?? true;
@@ -195,113 +539,325 @@ export class FoundationRuntime {
195
539
  openDialog(definition, input) {
196
540
  this.publish({ definition, input, token: Symbol() });
197
541
  }
198
- rememberFormFeedback(state, outcome) {
199
- this.formFeedback.set(state, outcome);
200
- }
542
+ /**
543
+ * Resolves a feedback option. Without one, the `<id>.success` / `<id>.failure` catalog keys
544
+ * apply; a failure without any message shows the error in development and a generic text
545
+ * in production. Feedback callbacks can never turn a success into a failure.
546
+ */
201
547
  feedback(definition, kind, option, context) {
548
+ if (option === false)
549
+ return { message: false, closeDialog: true };
550
+ const key = `${definition.id}.${kind}`;
551
+ if (option === undefined) {
552
+ if (this.translate.has?.(key))
553
+ return { message: this.text(key, key), closeDialog: true };
554
+ if (kind === 'failure')
555
+ return { message: defaultFailure(context.error), closeDialog: false };
556
+ return { message: false, closeDialog: true };
557
+ }
202
558
  const value = evaluateFeedback(option, context);
203
559
  if (value === false)
204
560
  return { message: false, closeDialog: true };
205
561
  try {
206
- return {
207
- message: (value.message ? this.text(value.message, this.text(`${definition.id}.${kind}`, value.message, value.values), value.values) : value.message) ??
208
- (value.messageKey ? this.text(value.messageKey, value.messageKey, value.values) : false),
209
- closeDialog: value.closeDialog ?? true,
210
- };
562
+ const message = (value.message
563
+ ? this.text(value.message, this.text(key, value.message, value.values), value.values)
564
+ : value.message) ??
565
+ (value.messageKey
566
+ ? this.text(value.messageKey, value.messageKey, value.values)
567
+ : undefined);
568
+ if (message === undefined) {
569
+ if (this.translate.has?.(key))
570
+ return { message: this.text(key, key), closeDialog: value.closeDialog ?? true };
571
+ return {
572
+ message: kind === 'failure' ? defaultFailure(context.error) : false,
573
+ closeDialog: value.closeDialog ?? kind !== 'failure',
574
+ };
575
+ }
576
+ return { message, closeDialog: value.closeDialog ?? true };
211
577
  }
212
578
  catch {
213
579
  return { message: false, closeDialog: true };
214
580
  }
215
581
  }
216
- /** Public submission path; the internal submit registration owns validation and pending guards. */
217
- async submitForm(definition, values) {
218
- const state = this.state;
219
- if (state?.definition !== definition)
220
- return;
221
- const outcome = await this.actions.execute(`${definition.id}.submit`, values);
222
- if (outcome.status !== 'completed' || this.state !== state)
223
- return;
224
- const feedback = this.formFeedback.get(state);
225
- this.formFeedback.delete(state);
226
- if (!feedback)
227
- return;
228
- this.notify(feedback.message);
229
- if (feedback.closeDialog)
230
- this.close();
231
- }
232
582
  setTranslations(translate) {
233
583
  this.translate = translate;
234
584
  this.translationRevision += 1;
235
585
  this.translationListeners.forEach((listener) => listener());
236
- for (const { definition, handle } of this.registrations) {
586
+ for (const { definition, handle } of this.registrations)
237
587
  handle.update({
238
588
  title: this.title(definition),
239
589
  description: this.description(definition),
240
- tooltip: definition.tooltip === undefined
241
- ? undefined
242
- : this.text(definition.tooltip, this.text(`${definition.id}.tooltip`, definition.tooltip)),
590
+ tooltip: this.tooltip(definition),
243
591
  });
244
- }
245
592
  }
246
593
  close = () => {
247
- if (this.state?.definition.kind === 'form' &&
248
- this.actions.get(`${this.state.definition.id}.submit`)?.pending)
249
- return;
250
594
  this.publish(null);
251
595
  };
596
+ reportLifecycleError(error) {
597
+ try {
598
+ console.error('[bitakit] Lifecycle failed.', error);
599
+ }
600
+ catch {
601
+ /* reporting only */
602
+ }
603
+ }
604
+ servicePhase(id, phase, error) {
605
+ const failure = error === undefined
606
+ ? undefined
607
+ : { message: error instanceof Error ? error.message : String(error) };
608
+ this.lifecycleState.service(id, phase, failure);
609
+ const owner = this.lifecycle.get().services.find((entry) => entry.id === id)?.plugin;
610
+ if (owner && phase === 'failed')
611
+ this.lifecycleState.plugin(owner, 'failed', failure);
612
+ if (this.setupComplete && phase === 'ready')
613
+ this.refreshPluginReadiness();
614
+ }
615
+ refreshPluginReadiness() {
616
+ // Ready means the owner's initialization and declared dependencies are ready.
617
+ // Iterate to cover implicit service edges that are not explicit plugin ordering edges.
618
+ for (let changed = true; changed && !this.stopCompletion;) {
619
+ changed = false;
620
+ for (const plugin of this.order) {
621
+ const state = this.lifecycle.get();
622
+ if (state.plugins.find((entry) => entry.id === plugin.id)?.phase !== 'starting')
623
+ continue;
624
+ const required = [
625
+ ...plugin.services,
626
+ ...plugin.actions,
627
+ ...(plugin.interceptors ?? []),
628
+ ].flatMap((definition) => definition.requires ?? []);
629
+ const ownReady = state.services
630
+ .filter((entry) => entry.plugin === plugin.id)
631
+ .every((entry) => entry.phase === 'ready');
632
+ const dependenciesReady = (plugin.dependencies ?? []).every((id) => state.plugins.find((entry) => entry.id === id)?.phase === 'ready');
633
+ const servicesReady = required.every((name) => {
634
+ const id = this.names.key(name);
635
+ return (Object.hasOwn(this.providedServices, id) ||
636
+ state.services.find((entry) => entry.id === id)?.phase === 'ready');
637
+ });
638
+ if (ownReady && dependenciesReady && servicesReady) {
639
+ changed = true;
640
+ this.lifecycleState.plugin(plugin.id, 'ready');
641
+ }
642
+ }
643
+ }
644
+ }
252
645
  mount() {
253
- if (this.container)
254
- throw new Error('Foundation is already mounted.');
255
- const selected = applyActionReplacements(this.config.plugins ?? [], this.config.actions ?? []);
256
- const plugins = orderPlugins([
257
- {
258
- id: this.config.appId ?? '@foundation/app',
259
- dependencies: this.config.dependencies,
260
- setup: this.config.setup,
261
- actions: selected.actions,
262
- services: this.config.services,
263
- config: this.config.config,
264
- contributions: this.config.contributions,
265
- installs: this.config.installs,
266
- },
267
- ...selected.plugins,
268
- ]);
269
- const serviceModules = new Map(plugins.flatMap((plugin) => (plugin.services ?? []).map((service) => [service, plugin.id])));
270
- this.container = createServices(plugins.flatMap((plugin) => plugin.services ?? []), this.providedServices, (definition) => this.configuration.context(serviceModules.get(definition)), serviceObserver(this.modules), this.events);
646
+ if (this.mounting || this.tearingDown || this.lifecycle.get().cleanup === 'failed')
647
+ throw new Error('The BitaKit runtime cannot mount during a lifecycle transition or after failed cleanup.');
648
+ this.mounting = true;
271
649
  try {
650
+ return this.start();
651
+ }
652
+ finally {
653
+ this.mounting = false;
654
+ }
655
+ }
656
+ start() {
657
+ if (this.container || this.lifecycle.get().phase === 'stopping')
658
+ throw new Error('The BitaKit runtime is already mounted or still stopping. Await its stop before mounting.');
659
+ this.stopCompletion = undefined;
660
+ if (this.generation)
661
+ this.readyDeferred = deferred();
662
+ const generation = ++this.generation;
663
+ let completion;
664
+ this.mountStop = () => (completion ??= generation === this.generation ? this.unmount() : Promise.resolve());
665
+ const stop = this.mountStop;
666
+ this.setupComplete = false;
667
+ this.lifecycleState.update({
668
+ generation,
669
+ operation: Object.freeze({ kind: 'start', startedAt: Date.now() }),
670
+ phase: 'starting',
671
+ cleanup: 'none',
672
+ plugins: Object.freeze(this.lifecycle
673
+ .get()
674
+ .plugins.map((entry) => Object.freeze({ ...entry, phase: 'starting', failure: undefined }))),
675
+ services: Object.freeze(this.lifecycle
676
+ .get()
677
+ .services.map((entry) => Object.freeze({ ...entry, phase: 'idle', failure: undefined }))),
678
+ });
679
+ const plugins = this.order;
680
+ const owners = new Map();
681
+ for (const plugin of plugins)
682
+ for (const service of plugin.services)
683
+ owners.set(service, plugin.id);
684
+ const interceptors = plugins.flatMap((plugin) => plugin.interceptors ?? []);
685
+ this.container = createServices(plugins.flatMap((plugin) => plugin.services), this.providedServices, (definition) => this.configuration.context(owners.get(definition) ??
686
+ this.modules.find((module) => module.services.includes(definition))?.id ??
687
+ this.appId), serviceObserver(interceptors, (id) => this.aliasesOf(id)), this.events, {
688
+ names: this.names,
689
+ appId: this.appId,
690
+ moduleOf: (definition) => owners.get(definition) ??
691
+ this.modules.find((module) => module.services.includes(definition))?.id ??
692
+ this.appId,
693
+ sourceOf: (definition) => contributionSource(definition),
694
+ }, (definition) => definition.id, this.settingsAccess, (id, phase, error) => this.servicePhase(id, phase, error));
695
+ // Contexts exist only after the container does; readiness is the public facade's concern.
696
+ this.view = this.names.tree(this.container.services);
697
+ const moduleEvents = new Map();
698
+ try {
699
+ this.container.initialize();
272
700
  this.extensionCleanups.push(this.actions.subscribeExecution((event) => {
273
- if (event.phase === 'failed' &&
274
- event.context.get() &&
275
- event.error instanceof ActionFailure)
701
+ if (event.phase === 'started' &&
702
+ (this.registrations.some((entry) => entry.definition.id === event.id) ||
703
+ this.scopes.some((scope) => scope.ownsAction(event.id)))) {
704
+ const pending = deferred();
705
+ this.activeRuns.set(event.context, {
706
+ ...pending,
707
+ plugin: this.actionConfigs.get(event.id)?.module ??
708
+ (this.scopes.find((scope) => scope.ownsAction(event.id))
709
+ ? scopeModule(this.scopes.find((scope) => scope.ownsAction(event.id))).id
710
+ : undefined),
711
+ });
712
+ }
713
+ else if (event.phase !== 'started') {
714
+ this.activeRuns.get(event.context)?.resolve();
715
+ this.activeRuns.delete(event.context);
716
+ }
717
+ }), this.actions.use({
718
+ before: ({ id }) => {
719
+ const phase = this.lifecycle.get().phase;
720
+ const scope = this.scopes.find((entry) => entry.ownsAction(id));
721
+ const owner = this.actionConfigs.get(id)?.module ?? (scope && scopeModule(scope).id);
722
+ if (owner &&
723
+ (this.stopCompletion ||
724
+ phase === 'stopping' ||
725
+ phase === 'stopped' ||
726
+ (phase === 'failed' && !this.isReady()) ||
727
+ (this.isReady() && !this.isReady(owner))))
728
+ return false;
729
+ },
730
+ }), this.actions.subscribeExecution((event) => {
731
+ if (event.phase === 'failed' && event.context.get() && isActionFailure(event.error))
276
732
  this.notify(event.error.feedback, 'failure');
277
733
  }));
734
+ for (const plugin of plugins) {
735
+ const scope = createEventScope(this.events, plugin.id);
736
+ this.pluginEvents.set(plugin.id, scope);
737
+ moduleEvents.set(plugin.id, scope.events);
738
+ }
278
739
  this.connectTranslation();
279
740
  this.installInterceptors(plugins);
741
+ const composed = Object.freeze(plugins
742
+ .filter((plugin) => plugin.id !== this.appId)
743
+ .map((plugin) => Object.freeze({ id: plugin.id, metadata: plugin.metadata })));
744
+ const composedModules = Object.freeze(plugins.map((plugin) => Object.freeze({
745
+ id: plugin.id,
746
+ app: plugin.id === this.appId,
747
+ metadata: plugin.metadata,
748
+ settings: plugin.settings,
749
+ ui: plugin.ui,
750
+ })));
751
+ const translation = Object.freeze({
752
+ translate: this.translator(),
753
+ text: (key, fallback, values) => this.text(key, fallback, values),
754
+ subscribe: this.subscribeTranslations,
755
+ });
280
756
  for (const plugin of plugins) {
281
757
  const scope = new PluginScope(this.actions, this.groups);
282
- assignScopeModule(scope, { id: plugin.id, app: plugin.id === this.appId });
758
+ assignScopeModule(scope, { id: plugin.id, app: plugin.id === this.appId }, composed, composedModules, translation, this.lifecycle);
283
759
  this.scopes.push(scope);
760
+ scope.bindSlots(this.slotRuntime.bind(scope, plugin.id));
761
+ scope.onClose(this.pluginEvents.get(plugin.id).dispose);
284
762
  }
285
763
  this.installContributions(plugins);
286
- const observed = new Set();
287
764
  plugins.forEach((plugin, index) => {
288
- for (const contribution of plugin.actions ?? [])
289
- this.install(this.scopes[index], contribution, observed, plugin.id);
765
+ for (const contribution of plugin.actions)
766
+ this.install(this.scopes[index], contribution, plugin.id, moduleEvents.get(plugin.id));
290
767
  });
291
- this.observe(observed);
768
+ // Declared targets and programmatic contributions share the same owned attachment path.
769
+ // Undeclared UI slots retain their existing rendering until the placement migration.
770
+ plugins.forEach((plugin, index) => {
771
+ for (const [viewIndex, view] of plugin.views.entries()) {
772
+ if (!this.slots.has(view.slot))
773
+ continue;
774
+ const contribution = {
775
+ slot: view.slot,
776
+ id: view.id ?? `view:${viewIndex}`,
777
+ component: view.component,
778
+ key: view.key,
779
+ order: view.order,
780
+ when: view.when,
781
+ };
782
+ preserveContributionPath(view, contribution);
783
+ try {
784
+ this.scopes[index].slots.attach(contribution, {
785
+ availability: view.availability ?? 'wait',
786
+ });
787
+ }
788
+ catch (error) {
789
+ throw this.attribute(error, plugin.id, `Slot "${view.slot}"`, contributionSource(view));
790
+ }
791
+ }
792
+ });
793
+ this.observe(new Set([...this.container.observed, this.settings]));
292
794
  plugins.forEach((plugin, index) => {
293
795
  const scope = this.scopes[index];
294
- const cleanup = plugin.setup?.({ app: scope, services: this.services });
295
- if (cleanup)
296
- scope.own(cleanup);
796
+ try {
797
+ const cleanup = plugin.setup?.({ scope, services: this.services });
798
+ if (cleanup)
799
+ scope.own(cleanup);
800
+ }
801
+ catch (error) {
802
+ throw this.attribute(error, plugin.id, 'Setup');
803
+ }
297
804
  });
805
+ this.syncIdentity();
806
+ this.setupComplete = true;
807
+ this.refreshPluginReadiness();
298
808
  }
299
809
  catch (error) {
300
- this.unmount();
810
+ this.startFailed(error);
811
+ void stop();
301
812
  throw error;
302
813
  }
303
- this.setReady(true);
304
- return () => this.unmount();
814
+ if (this.stopCompletion)
815
+ return stop;
816
+ const controller = new AbortController();
817
+ this.startController = controller;
818
+ const pending = this.readyDeferred;
819
+ const finish = () => {
820
+ if (this.startController !== controller || this.stopCompletion)
821
+ return;
822
+ this.startPending = false;
823
+ for (const plugin of plugins)
824
+ this.lifecycleState.plugin(plugin.id, 'ready');
825
+ if (this.stopCompletion)
826
+ return;
827
+ this.lifecycleState.update({ phase: 'ready' });
828
+ if (this.stopCompletion)
829
+ return;
830
+ this.setReady(true);
831
+ if (!this.stopCompletion)
832
+ pending.resolve();
833
+ };
834
+ if (!this.container.hasStartHooks) {
835
+ for (const entry of this.lifecycle.get().services)
836
+ this.servicePhase(entry.id, 'ready');
837
+ finish();
838
+ }
839
+ else {
840
+ this.startPending = true;
841
+ this.startWork = this.container.start(controller.signal);
842
+ void this.startWork.then(finish, (error) => {
843
+ this.startPending = false;
844
+ if (this.startController !== controller || this.stopCompletion)
845
+ return;
846
+ this.startFailed(error);
847
+ pending.reject(error);
848
+ });
849
+ }
850
+ return stop;
851
+ }
852
+ startFailed(error) {
853
+ const failure = {
854
+ message: error instanceof Error ? error.message : String(error),
855
+ ...(isBitaKitStartupError(error) ? { plugin: error.plugin, source: error.source } : {}),
856
+ };
857
+ if (isBitaKitStartupError(error))
858
+ this.lifecycleState.plugin(error.plugin, 'failed', failure);
859
+ this.lifecycleState.update({ phase: 'failed' });
860
+ this.readyDeferred.reject(error);
305
861
  }
306
862
  /** Routes each contribution kind to the one module that installs it; cleanup stays with the contributor. */
307
863
  installContributions(plugins) {
@@ -312,150 +868,831 @@ export class FoundationRuntime {
312
868
  continue;
313
869
  const existing = installers.get(kind);
314
870
  if (existing)
315
- throw new Error(`Contribution kind "${kind}" is installed by both "${existing.module}" and "${plugin.id}".`);
871
+ throw new BitaKitStartupError(`Contribution kind "${kind}" is installed by both "${existing.module}" and "${plugin.id}".`, plugin.id);
316
872
  installers.set(kind, { module: plugin.id, install });
317
873
  }
318
874
  for (const plugin of plugins)
319
875
  for (const [kind, values] of Object.entries(plugin.contributions ?? {}))
320
876
  if (values?.length && !installers.has(kind))
321
- throw new Error(`"${plugin.id}" contributes "${kind}", but no enabled plugin installs that kind.`);
877
+ throw new BitaKitStartupError(`"${plugin.id}" contributes "${kind}", but no enabled plugin installs that kind.`, plugin.id, { app: plugin.id === this.appId });
322
878
  for (const [kind, { install }] of installers)
323
879
  plugins.forEach((plugin, index) => {
324
880
  const values = plugin.contributions?.[kind];
325
881
  if (!values?.length)
326
882
  return;
327
- const cleanup = install(values, {
328
- module: plugin.id,
329
- app: plugin.id === this.appId,
330
- services: this.services,
331
- });
332
- if (cleanup)
333
- this.scopes[index].own(cleanup);
883
+ try {
884
+ const cleanup = install(values, {
885
+ module: plugin.id,
886
+ app: plugin.id === this.appId,
887
+ services: this.services,
888
+ });
889
+ if (cleanup)
890
+ this.scopes[index].own(cleanup);
891
+ }
892
+ catch (error) {
893
+ throw this.attribute(error, plugin.id, `Contribution "${kind}"`);
894
+ }
334
895
  });
335
896
  }
336
897
  connectTranslation() {
337
- const i18n = this.services.i18n;
898
+ const i18n = this.hasService('i18n') ? getService(this.services, translationService) : undefined;
338
899
  if (!i18n)
339
900
  return;
340
901
  this.setTranslations(i18n.translate);
341
902
  this.extensionCleanups.push(i18n.subscribe(() => this.setTranslations(i18n.translate)));
342
903
  }
343
904
  installInterceptors(plugins) {
344
- const entries = [
345
- ...(this.config.interceptors ?? []).map((definition) => ({
346
- definition,
347
- module: this.config.appId ?? '@foundation/app',
348
- global: !isServiceInterceptor(definition) && definition.scope !== 'plugin',
349
- })),
350
- ...plugins.flatMap((plugin) => (plugin.interceptors ?? []).map((definition) => ({
351
- definition,
352
- module: plugin.id,
353
- global: !isServiceInterceptor(definition) && definition.scope === 'global',
354
- }))),
355
- ].sort((a, b) => (a.definition.order ?? 0) - (b.definition.order ?? 0));
356
- for (const { definition, module, global } of entries) {
357
- if (isServiceInterceptor(definition))
358
- continue;
359
- if ('create' in definition)
360
- this.requireServices(definition.requires);
361
- const interceptor = 'create' in definition
362
- ? definition.create({
363
- services: this.services,
364
- translate: this.translator(),
365
- config: this.configuration.context(module),
366
- })
367
- : definition;
368
- this.extensionCleanups.push(this.actions.use({
369
- before: (context) => {
370
- const target = this.actionConfigs.get(context.id);
371
- if (!global && target?.module !== module)
905
+ const entries = plugins
906
+ .flatMap((plugin) => (plugin.interceptors ?? []).map((spec) => ({ spec, module: plugin.id })))
907
+ .filter(({ spec }) => !isServiceInterceptor(spec))
908
+ .sort((a, b) => (a.spec.order ?? 0) - (b.spec.order ?? 0));
909
+ for (const { spec, module } of entries) {
910
+ const definition = spec;
911
+ const global = definition.scope === 'global' || (module === this.appId && definition.scope !== 'plugin');
912
+ const requester = {
913
+ label: `An interceptor in ${moduleLabel(module, this.appId)}`,
914
+ source: contributionSource(spec),
915
+ };
916
+ try {
917
+ this.requireServices(module, definition.requires, requester);
918
+ }
919
+ catch (error) {
920
+ throw this.attribute(error, module, 'Interceptor', requester.source);
921
+ }
922
+ const applies = (id) => matchesTarget(definition.action ?? '*', id) &&
923
+ (global || this.actionConfigs.get(id)?.module === module);
924
+ const context = (base) => ({
925
+ ...base,
926
+ services: this.services,
927
+ config: this.actionConfigs.get(base.id)?.config ?? this.configuration.context(module),
928
+ app: this.app,
929
+ translate: this.translator(),
930
+ });
931
+ const report = (error) => console.error(`[bitakit] Interceptor in ${moduleLabel(module, this.appId)} failed.`, error);
932
+ if (definition.before)
933
+ this.extensionCleanups.push(this.actions.use({
934
+ before: (base) => applies(base.id) ? definition.before(context(base)) : undefined,
935
+ }));
936
+ if (definition.after || definition.onError)
937
+ this.extensionCleanups.push(this.actions.subscribeExecution((event) => {
938
+ if (!applies(event.id))
372
939
  return;
373
- return interceptor.before({
374
- ...context,
375
- config: target?.config ?? this.configuration.context(module),
376
- });
377
- },
940
+ try {
941
+ if (event.phase === 'completed' && definition.after)
942
+ void Promise.resolve(definition.after({
943
+ ...context(event.context),
944
+ result: event.result?.status === 'completed' ? event.result.value : undefined,
945
+ })).catch(report);
946
+ if (event.phase === 'failed' && definition.onError)
947
+ void Promise.resolve(definition.onError({
948
+ ...context(event.context),
949
+ error: isActionFailure(event.error) ? event.error.cause : event.error,
950
+ })).catch(report);
951
+ }
952
+ catch (error) {
953
+ report(error);
954
+ }
955
+ }));
956
+ }
957
+ }
958
+ /** Resolves required names to container keys; a missing one is attributed to `module`. */
959
+ requireServices(module, ids = [], requester) {
960
+ const instances = this.container.services;
961
+ const exists = (key) => Object.hasOwn(instances, key);
962
+ return ids.map((id) => {
963
+ const key = this.names.key(id);
964
+ if (!exists(key))
965
+ throw this.names.missing(module, id, requester, exists);
966
+ return key;
967
+ });
968
+ }
969
+ attribute(error, module, what, source) {
970
+ if (isBitaKitStartupError(error))
971
+ return error;
972
+ const message = error instanceof Error ? error.message : String(error);
973
+ return new BitaKitStartupError(`${what} in ${moduleLabel(module, this.appId)} failed to start: ${message}${source ? `\nSource: ${source}` : ''}`, module, { cause: error, source, app: module === this.appId });
974
+ }
975
+ /** One path for every action: adapt, check dependencies, register, remember for re-translation. */
976
+ install(scope, contribution, module, events) {
977
+ const path = contributionPath(contribution) ?? contribution.id.split('.');
978
+ const source = contributionSource(contribution);
979
+ let adapted;
980
+ try {
981
+ const config = this.configuration.context(module, path);
982
+ adapted = adaptAction(contribution, this, config, events, () => this.isReady(module));
983
+ this.requireServices(module, adapted.requires, {
984
+ label: `Action "${adapted.definition.id}"`,
985
+ source,
986
+ });
987
+ for (const registration of adapted.registrations) {
988
+ this.actionConfigs.set(registration.id, { module, config });
989
+ const handle = this.actions.register(registration.definition, registration.placement);
990
+ scope.own(handle.unregister);
991
+ // Placement is a reference to this registration, not another Action or execution path.
992
+ if (!registration.definition.internal) {
993
+ for (const placement of (adapted.definition.slots ??
994
+ [])) {
995
+ const target = typeof placement === 'string' ? { slot: placement } : placement;
996
+ if (typeof target.slot !== 'string')
997
+ throw new TypeError('Action slot placements name their target with { slot } (formerly { name }); run "bitakit migrate".');
998
+ const reference = {
999
+ slot: target.slot,
1000
+ id: `action:${registration.id}:${target.key ?? ''}`,
1001
+ actionId: registration.id,
1002
+ input: target.input,
1003
+ key: target.key,
1004
+ order: target.order ?? contribution.order,
1005
+ };
1006
+ preserveContributionPath(contribution, reference);
1007
+ const attached = scope.slots.attach(reference, {
1008
+ availability: target.availability ?? 'wait',
1009
+ });
1010
+ handle.onDispose(attached.dispose);
1011
+ }
1012
+ }
1013
+ if (adapted.confirm) {
1014
+ const confirm = adapted.confirm;
1015
+ handle.onDispose(this.actions.use({
1016
+ before: (context) => (context.id === registration.id ? confirm(context) : undefined),
1017
+ }));
1018
+ }
1019
+ this.registrations.push({ definition: adapted.definition, handle });
1020
+ }
1021
+ }
1022
+ catch (error) {
1023
+ throw this.attribute(error, module, `Action "${contribution.id}"`, source);
1024
+ }
1025
+ }
1026
+ /** Reconcile subscriptions over the existing container; never mirror service state. */
1027
+ observe(observed, refresh = true) {
1028
+ for (const [source, off] of this.observations)
1029
+ if (!observed.has(source)) {
1030
+ off();
1031
+ this.observations.delete(source);
1032
+ }
1033
+ for (const source of observed)
1034
+ if (!this.observations.has(source))
1035
+ this.observations.set(source, source.subscribe(() => {
1036
+ if (!this.container)
1037
+ return;
1038
+ this.actions.refresh();
1039
+ this.syncIdentity();
1040
+ }));
1041
+ if (refresh && observed.size)
1042
+ this.actions.refresh();
1043
+ }
1044
+ /** Plan structural changes before touching scopes; use the existing update exclusion and executor. */
1045
+ changePlugins(operation, values, options) {
1046
+ const result = (status, reasons, changed = []) => Promise.resolve(Object.freeze({
1047
+ status,
1048
+ reasons: Object.freeze(reasons),
1049
+ changed: Object.freeze(changed),
1050
+ affected: Object.freeze([]),
1051
+ revision: this.revision,
1052
+ }));
1053
+ if (this.updating ||
1054
+ this.mounting ||
1055
+ this.tearingDown ||
1056
+ this.stopCompletion ||
1057
+ !this.container ||
1058
+ this.startPending)
1059
+ return result('blocked', ['A lifecycle operation is active or the runtime is not mounted.']);
1060
+ if (this.lifecycle.get().cleanup === 'failed')
1061
+ return result('blocked', ['Failed cleanup requires resource recovery and a new runtime.']);
1062
+ try {
1063
+ const installed = [...(this.config.plugins ?? [])];
1064
+ const disabled = new Set(this.disabledPlugins);
1065
+ const ids = operation === 'add'
1066
+ ? values.map((plugin) => plugin.id)
1067
+ : values;
1068
+ if (new Set(ids).size !== ids.length)
1069
+ return result('blocked', ['Plugin IDs must be unique.']);
1070
+ if (ids.includes(this.appId))
1071
+ return result('blocked', ['The app module cannot be changed through plugins.']);
1072
+ if ((operation === 'remove' || operation === 'disable') &&
1073
+ !['stop', 'refuse'].includes(options?.dependents ?? ''))
1074
+ return result('blocked', ['Choose dependents: stop or refuse.']);
1075
+ for (const id of ids) {
1076
+ const exists = installed.some((plugin) => plugin.id === id);
1077
+ if (operation === 'add' ? exists : !exists)
1078
+ return result('blocked', [
1079
+ `Plugin "${id}" ${exists ? 'is already installed' : 'is not installed'}.`,
1080
+ ]);
1081
+ }
1082
+ // Ownership: a parent's descendants follow it, whatever the dependents policy says.
1083
+ const owned = descendantsOf(installed, ids);
1084
+ const cascaded = new Map(this.disabledWithParent);
1085
+ if (operation === 'remove')
1086
+ ids.push(...owned);
1087
+ if (operation === 'disable')
1088
+ for (const [parent, children] of cascaded)
1089
+ cascaded.set(parent, children.filter((child) => !ids.includes(child)));
1090
+ if (operation === 'enable')
1091
+ for (const id of [...ids]) {
1092
+ const parent = installed.find((plugin) => plugin.id === id)?.parent;
1093
+ if (parent && disabled.has(parent) && !ids.includes(parent))
1094
+ return result('blocked', [
1095
+ `Plugin "${id}" belongs to "${parent}", which is disabled. Enable "${parent}" first.`,
1096
+ ]);
1097
+ ids.push(...(cascaded.get(id) ?? []).filter((child) => !ids.includes(child)));
1098
+ cascaded.delete(id);
1099
+ }
1100
+ const activeIds = new Set(this.modules.map((module) => module.id));
1101
+ let changed = [...ids];
1102
+ if (operation === 'disable' || operation === 'remove') {
1103
+ const seeds = [...ids, ...owned].filter((id) => activeIds.has(id));
1104
+ if (operation === 'remove')
1105
+ seeds.push(...this.slotRuntime.contributorsTo(new Set(ids)));
1106
+ const closure = updateClosure(this.modules, seeds);
1107
+ const dependents = closure.filter((id) => !ids.includes(id) && !owned.includes(id));
1108
+ if (dependents.length && options?.dependents === 'refuse')
1109
+ return result('blocked', [`Enabled dependents: ${dependents.join(', ')}.`]);
1110
+ changed = [...new Set([...ids, ...owned, ...dependents])];
1111
+ if (operation === 'disable') {
1112
+ const switchedOff = owned.filter((id) => !disabled.has(id));
1113
+ for (const id of ids)
1114
+ cascaded.set(id, switchedOff);
1115
+ }
1116
+ for (const id of changed)
1117
+ disabled.add(id);
1118
+ }
1119
+ else if (operation === 'enable') {
1120
+ changed = ids.filter((id) => disabled.has(id) || !this.isReady(id));
1121
+ for (const id of ids)
1122
+ disabled.delete(id);
1123
+ }
1124
+ else
1125
+ installed.push(...values);
1126
+ if (operation === 'remove')
1127
+ for (const id of ids)
1128
+ cascaded.delete(id);
1129
+ const nextInstalled = operation === 'remove' ? installed.filter((plugin) => !ids.includes(plugin.id)) : installed;
1130
+ for (const id of ids)
1131
+ if (operation === 'remove')
1132
+ disabled.delete(id);
1133
+ if (operation === 'disable')
1134
+ changed = changed.filter((id) => !this.disabledPlugins.has(id));
1135
+ if (!changed.length) {
1136
+ // An explicit disable of a child its parent already switched off: remember the intent.
1137
+ this.disabledWithParent = cascaded;
1138
+ return result('applied', []);
1139
+ }
1140
+ const normalized = nextInstalled
1141
+ .filter((plugin) => !disabled.has(plugin.id))
1142
+ .map((plugin) => normalize(plugin, this.appId));
1143
+ const app = this.modules.find((module) => module.id === this.appId);
1144
+ const all = [app, ...normalized];
1145
+ const declarations = [app, ...nextInstalled.map((plugin) => normalize(plugin, this.appId))];
1146
+ orderPlugins(all, this.appId);
1147
+ validateSlotDeclarations(declarations, this.appId);
1148
+ validatePluginPages(all, new Set(Object.keys(app.ui?.layouts ?? {})));
1149
+ // Failed updates may have already disposed a projection's scope. Recover its recorded
1150
+ // failure cohort when the host retries one of those owners, without restarting other failures.
1151
+ const lifecycle = this.lifecycle.get();
1152
+ const failures = new Set(changed.flatMap((id) => {
1153
+ const owner = lifecycle.plugins.find((entry) => entry.id === id);
1154
+ return owner?.failure?.plugin ? [owner.failure.plugin] : [];
378
1155
  }));
1156
+ const readers = [
1157
+ ...new Set([
1158
+ ...this.scopes.filter(readsComposition).map((scope) => scopeModule(scope).id),
1159
+ ...lifecycle.plugins
1160
+ .filter((entry) => entry.failure?.plugin &&
1161
+ failures.has(entry.failure.plugin) &&
1162
+ activeIds.has(entry.id) &&
1163
+ !disabled.has(entry.id))
1164
+ .map((entry) => entry.id),
1165
+ ]),
1166
+ ];
1167
+ const before = updateClosure(this.modules, [
1168
+ ...changed.filter((id) => activeIds.has(id)),
1169
+ ...readers,
1170
+ ]);
1171
+ const after = updateClosure(all, [...changed, ...readers].filter((id) => all.some((module) => module.id === id)));
1172
+ const affected = [...new Set([...before, ...after])];
1173
+ const reasons = [];
1174
+ for (const module of [...this.modules, ...all].filter((module) => affected.includes(module.id))) {
1175
+ if (module.id === this.appId ||
1176
+ module.providers.length ||
1177
+ Object.keys(module.ui?.layouts ?? {}).length ||
1178
+ module.interceptors?.length ||
1179
+ Object.keys(module.installs ?? {}).length ||
1180
+ Object.keys(module.contributions ?? {}).length)
1181
+ reasons.push(`${module.id}: host, provider or cross-plugin installer/interceptor requires composition replacement.`);
1182
+ if (module.services.some((service) => [service.id, service.provides, service.exposeAs].some((name) => ['auth', 'i18n', 'settings.storage'].includes(name))))
1183
+ reasons.push(`${module.id}: host identity, translation or storage service requires composition replacement.`);
1184
+ }
1185
+ if (reasons.length)
1186
+ return result('restart-required', [...new Set(reasons)], changed);
1187
+ const entries = this.serviceEntries(all);
1188
+ const names = new ServiceNames(entries, this.appId);
1189
+ for (const module of all)
1190
+ for (const definition of [
1191
+ ...module.services,
1192
+ ...module.actions,
1193
+ ...(module.interceptors ?? []),
1194
+ ])
1195
+ for (const requirement of definition.requires ?? [])
1196
+ if (!names.known(requirement))
1197
+ throw new Error(`${module.id}: missing required service "${requirement}".`);
1198
+ updateClosure(all, all.map((module) => module.id));
1199
+ const actionIds = all.flatMap((module) => module.actions.map((action) => action.id));
1200
+ if (new Set(actionIds).size !== actionIds.length)
1201
+ throw new Error('Duplicate Action ID in proposed composition.');
1202
+ const settings = this.settingEntries(declarations);
1203
+ for (const entry of this.settings.entries())
1204
+ if (!settings.some((next) => next.key === entry.key) &&
1205
+ this.settings.state(entry.key).pending)
1206
+ return result('blocked', [`Setting "${entry.key}" has a pending write.`]);
1207
+ createSettingsAccess(new SettingsStore(settings, () => this.storage()));
1208
+ const overrides = Object.fromEntries(Object.entries(this.config.configOverrides ?? {}).filter(([id]) => declarations.some((module) => module.id === id)));
1209
+ const configuration = new ConfigService(declarations, overrides);
1210
+ const eventCheck = new EventService();
1211
+ eventCheck.reserve('runtime');
1212
+ for (const module of declarations)
1213
+ if (module.events)
1214
+ eventCheck.declare(module.id, module.events);
1215
+ const controller = new AbortController();
1216
+ this.updateController = controller;
1217
+ this.updating = Promise.resolve().then(() => this.applyPluginUpdate(nextInstalled, normalized, changed, affected, controller, () => {
1218
+ // Writes may begin while awaited Action/scope cleanup is in progress.
1219
+ for (const entry of this.settings.entries())
1220
+ if (!settings.some((next) => next.key === entry.key) &&
1221
+ this.settings.state(entry.key).pending)
1222
+ return `Setting "${entry.key}" began writing during cleanup; await it before retrying.`;
1223
+ this.disabledPlugins = disabled;
1224
+ this.disabledWithParent = cascaded;
1225
+ this.names.replace(entries);
1226
+ this.configuration.replace(configuration);
1227
+ for (const plugin of this.config.plugins ?? [])
1228
+ this.events.undeclare(plugin.id);
1229
+ this.events.undeclare(this.appId);
1230
+ for (const module of declarations)
1231
+ if (module.events)
1232
+ this.events.declare(module.id, module.events);
1233
+ this.slotRuntime.replace(declarations.flatMap((module) => module.slots));
1234
+ this.settings.replace(settings);
1235
+ }, before, after));
1236
+ void this.updating
1237
+ .finally(() => {
1238
+ this.updating = undefined;
1239
+ this.updateController = undefined;
1240
+ })
1241
+ .catch(() => { });
1242
+ return this.updating;
1243
+ }
1244
+ catch (error) {
1245
+ return result('blocked', [error instanceof Error ? error.message : String(error)]);
1246
+ }
1247
+ }
1248
+ /** Explicit host update of already-loaded immutable plugin definitions; never installs code. */
1249
+ reconcilePlugins(next) {
1250
+ next = [...next];
1251
+ const result = (status, reasons, changed = [], affected = []) => Object.freeze({
1252
+ status,
1253
+ revision: this.revision,
1254
+ reasons: Object.freeze(reasons),
1255
+ changed: Object.freeze(changed),
1256
+ affected: Object.freeze(affected),
1257
+ });
1258
+ if (this.updating ||
1259
+ this.mounting ||
1260
+ this.tearingDown ||
1261
+ this.stopCompletion ||
1262
+ !this.container ||
1263
+ this.startPending)
1264
+ return Promise.resolve(result('blocked', ['A lifecycle operation is active or the runtime is not mounted.']));
1265
+ if (this.lifecycle.get().cleanup === 'failed')
1266
+ return Promise.resolve(result('blocked', ['Failed cleanup requires resource recovery and a new runtime.']));
1267
+ const current = this.config.plugins ?? [];
1268
+ if (this.disabledPlugins.size)
1269
+ return Promise.resolve(result('restart-required', ['Enable installed plugins before compatible updates.']));
1270
+ if (JSON.stringify(current.map((plugin) => plugin.id)) !==
1271
+ JSON.stringify(next.map((plugin) => plugin.id)))
1272
+ return Promise.resolve(result('restart-required', [
1273
+ 'Changing plugin membership or order requires composition replacement.',
1274
+ ]));
1275
+ let normalized;
1276
+ let affected;
1277
+ const failed = this.lifecycle
1278
+ .get()
1279
+ .plugins.filter((plugin) => plugin.phase === 'failed' || plugin.phase === 'blocked')
1280
+ .map((plugin) => plugin.id);
1281
+ const changed = next
1282
+ .filter((plugin, index) => plugin !== current[index] || failed.includes(plugin.id))
1283
+ .map((plugin) => plugin.id);
1284
+ if (!changed.length)
1285
+ return Promise.resolve(result('applied', []));
1286
+ try {
1287
+ normalized = next.map((plugin) => normalize(plugin, this.appId));
1288
+ const all = [this.modules.find((plugin) => plugin.id === this.appId), ...normalized];
1289
+ orderPlugins(all, this.appId);
1290
+ validateSlotDeclarations(all, this.appId);
1291
+ validatePluginPages(all, new Set(Object.keys(all[0].ui?.layouts ?? {})));
1292
+ // A projection that captured the composition is an explicit consumer of every revision.
1293
+ affected = updateClosure(all, [
1294
+ ...changed,
1295
+ ...this.scopes.filter(readsComposition).map((scope) => scopeModule(scope).id),
1296
+ ]);
1297
+ const reasons = next.flatMap((plugin, index) => updateRestrictions(current[index], plugin, this.modules.find((module) => module.id === plugin.id), normalized[index]));
1298
+ for (const id of affected) {
1299
+ const module = all.find((module) => module.id === id);
1300
+ if (id === this.appId ||
1301
+ module.interceptors?.length ||
1302
+ Object.keys(module.installs ?? {}).length ||
1303
+ Object.keys(module.contributions ?? {}).length ||
1304
+ module.providers.length)
1305
+ reasons.push(`${id}: host, provider or cross-plugin installer/interceptor requires composition replacement.`);
1306
+ if (module.services.some((service) => [service.id, service.provides, service.exposeAs].some((name) => ['auth', 'i18n', 'settings.storage'].includes(name))))
1307
+ reasons.push(`${id}: replacing a host identity, translation or storage service requires composition replacement.`);
1308
+ }
1309
+ if (reasons.length)
1310
+ return Promise.resolve(result('restart-required', reasons, changed, affected));
379
1311
  }
1312
+ catch (error) {
1313
+ return Promise.resolve(result('blocked', [error instanceof Error ? error.message : String(error)], changed));
1314
+ }
1315
+ const controller = new AbortController();
1316
+ this.updateController = controller;
1317
+ // Establish exclusion before any synchronous status observer or cleanup callback runs.
1318
+ this.updating = Promise.resolve().then(() => this.applyPluginUpdate(next, normalized, changed, affected, controller));
1319
+ void this.updating
1320
+ .finally(() => {
1321
+ this.updating = undefined;
1322
+ this.updateController = undefined;
1323
+ })
1324
+ .catch(() => { });
1325
+ return this.updating;
380
1326
  }
381
- requireServices(ids = []) {
1327
+ async stopPlugins(ids) {
1328
+ const selected = new Set(ids);
1329
+ const scopes = this.scopes.filter((scope) => selected.has(scopeModule(scope).id));
1330
+ const registrations = this.registrations.filter((entry) => selected.has(this.actionConfigs.get(entry.definition.id)?.module ?? ''));
1331
+ const runs = [...this.activeRuns.values()].filter((run) => run.plugin && selected.has(run.plugin));
1332
+ const early = [];
382
1333
  for (const id of ids)
383
- if (!Object.hasOwn(this.services, id))
384
- throw new Error(`Missing service "${id}".`);
385
- }
386
- /** One path for every kind: adapt, check dependencies, register, remember for re-translation. */
387
- install(scope, contribution, observed, module) {
388
- const path = (typeof contribution === 'object' ? contribution.configPath : undefined) ??
389
- contributionPath(contribution) ??
390
- (typeof contribution === 'object' && contribution.id ? contribution.id.split('.') : []);
391
- const config = this.configuration.context(module, path);
392
- const adapted = adaptContribution(contribution, this, config);
393
- this.requireServices(adapted.requires);
394
- for (const id of adapted.watch) {
395
- const service = this.services[id];
396
- if (!service || typeof service.subscribe !== 'function')
397
- throw new Error(`Observed service "${id}" must provide subscribe(listener).`);
398
- observed.add(id);
399
- }
400
- for (const registration of adapted.registrations) {
401
- this.actionConfigs.set(registration.id, { module, config });
402
- const handle = registration.instance
403
- ? this.actions.add(registration.id, registration.instance, registration.placement)
404
- : this.actions.register(registration.definition, registration.placement);
405
- scope.own(handle.unregister);
406
- if (adapted.setup) {
407
- const eventScope = createEventScope(this.events);
408
- handle.onDispose(eventScope.dispose);
409
- const cleanup = adapted.setup({
410
- events: eventScope.events, services: this.services,
411
- action: setupAction(handle), app: this.app, config,
1334
+ this.lifecycleState.plugin(id, 'stopping');
1335
+ if (this.state &&
1336
+ (selected.has(this.actionConfigs.get(this.state.definition.id)?.module ?? '') ||
1337
+ scopes.some((scope) => scope.ownsAction(this.state.definition.id))))
1338
+ this.close();
1339
+ for (const { handle } of registrations)
1340
+ try {
1341
+ handle.unregister();
1342
+ }
1343
+ catch (error) {
1344
+ early.push(error);
1345
+ }
1346
+ for (const scope of scopes)
1347
+ try {
1348
+ scope.close();
1349
+ }
1350
+ catch (error) {
1351
+ early.push(error);
1352
+ }
1353
+ this.registrations = this.registrations.filter((entry) => !registrations.includes(entry));
1354
+ for (const entry of registrations)
1355
+ this.actionConfigs.delete(entry.definition.id);
1356
+ this.scopes = this.scopes.filter((scope) => !scopes.includes(scope));
1357
+ const tasks = [() => Promise.all(runs.map((run) => run.promise)).then(() => { })];
1358
+ // Dependent scope cleanup can still use its provider's service until the next step.
1359
+ for (const id of [...ids].reverse())
1360
+ tasks.push(async () => {
1361
+ const own = scopes.find((scope) => scopeModule(scope).id === id);
1362
+ await cleanupSequence([
1363
+ ...(own ? [() => own.dispose()] : []),
1364
+ () => this.container.disposeModules(new Set([id])),
1365
+ ], (errors) => {
1366
+ this.lifecycleState.plugin(id, errors.length ? 'failed' : 'stopped', errors.length ? { plugin: id, message: 'Plugin cleanup failed.' } : undefined);
1367
+ cleanupFailure(errors, `Plugin "${id}" cleanup failed.`);
1368
+ });
1369
+ this.pluginEvents.delete(id);
1370
+ });
1371
+ await cleanupSequence(tasks, (errors) => cleanupFailure([...early, ...errors], 'Plugin update cleanup failed.'));
1372
+ this.observe(new Set([...this.container.observed, this.settings]), false);
1373
+ }
1374
+ async applyPluginUpdate(next, normalized, changed, affected, controller, commit, stopIds = affected, startIds = affected) {
1375
+ const result = (status, reasons = []) => Object.freeze({
1376
+ status,
1377
+ revision: this.revision,
1378
+ changed: Object.freeze(changed),
1379
+ affected: Object.freeze(affected),
1380
+ reasons: Object.freeze(reasons),
1381
+ });
1382
+ // Initial readiness remains true: only the affected owners become unavailable.
1383
+ this.setupComplete = false;
1384
+ this.lifecycleState.update({
1385
+ operation: Object.freeze({ kind: 'update', startedAt: Date.now() }),
1386
+ phase: 'starting',
1387
+ plugins: Object.freeze(this.lifecycle
1388
+ .get()
1389
+ .plugins.map((entry) => affected.includes(entry.id)
1390
+ ? Object.freeze({ ...entry, phase: 'stopping' })
1391
+ : entry)),
1392
+ });
1393
+ try {
1394
+ await this.stopPlugins(stopIds);
1395
+ }
1396
+ catch (error) {
1397
+ this.lifecycleState.update({ phase: 'failed', cleanup: 'failed' });
1398
+ return result('failed', [error instanceof Error ? error.message : String(error)]);
1399
+ }
1400
+ if (controller.signal.aborted)
1401
+ return result('blocked', ['Update cancelled by runtime shutdown.']);
1402
+ try {
1403
+ const blocked = commit?.();
1404
+ if (blocked) {
1405
+ // Affected owners are already stopped; retain declarations and report that actual state.
1406
+ for (const id of stopIds)
1407
+ this.lifecycleState.plugin(id, 'blocked', {
1408
+ plugin: changed[0],
1409
+ message: 'Plugin change blocked after cleanup.',
1410
+ });
1411
+ this.lifecycleState.update({ phase: 'failed', cleanup: 'complete' });
1412
+ return result('blocked', [blocked]);
1413
+ }
1414
+ this.currentConfig = { ...this.config, plugins: [...next] };
1415
+ this.currentModules = [
1416
+ this.modules.find((module) => module.id === this.appId),
1417
+ ...normalized,
1418
+ ];
1419
+ this.order = orderPlugins(this.modules, this.appId);
1420
+ this.revision++;
1421
+ if (commit) {
1422
+ const previous = this.lifecycle.get();
1423
+ const entries = (values, existing) => Object.freeze(values.map(({ id, plugin }) => {
1424
+ const before = existing.find((entry) => entry.id === id);
1425
+ const enabled = !this.disabledPlugins.has(plugin);
1426
+ return Object.freeze({
1427
+ ...before,
1428
+ id,
1429
+ plugin,
1430
+ enabled,
1431
+ phase: enabled ? (before?.phase ?? 'idle') : 'stopped',
1432
+ since: before?.since ?? Date.now(),
1433
+ });
1434
+ }));
1435
+ this.lifecycleState.update({
1436
+ plugins: entries([
1437
+ { id: this.appId, plugin: this.appId },
1438
+ ...next.map((plugin) => ({ id: plugin.id, plugin: plugin.id })),
1439
+ ], previous.plugins),
1440
+ services: entries(this.serviceEntries(), previous.services),
412
1441
  });
413
- if (cleanup)
414
- handle.onDispose(cleanup);
415
1442
  }
416
- this.registrations.push({ definition: adapted.definition, handle });
417
1443
  }
418
- }
419
- observe(observed) {
420
- for (const id of observed) {
421
- const service = this.services[id];
422
- this.extensionCleanups.push(service.subscribe(() => this.actions.refresh()));
1444
+ catch (error) {
1445
+ // A declaration commit cannot be rolled back safely after observers have run.
1446
+ this.lifecycleState.update({ phase: 'failed', cleanup: 'failed' });
1447
+ return result('failed', [error instanceof Error ? error.message : String(error)]);
1448
+ }
1449
+ const plugins = startIds.map((id) => this.modules.find((module) => module.id === id));
1450
+ const selected = new Set(startIds);
1451
+ try {
1452
+ for (const id of startIds)
1453
+ this.lifecycleState.plugin(id, 'starting');
1454
+ this.container.install(plugins.flatMap((plugin) => plugin.services));
1455
+ for (const plugin of plugins) {
1456
+ const events = createEventScope(this.events, plugin.id);
1457
+ this.pluginEvents.set(plugin.id, events);
1458
+ const scope = new PluginScope(this.actions, this.groups);
1459
+ assignScopeModule(scope, { id: plugin.id, app: false }, Object.freeze(this.modules
1460
+ .filter((module) => module.id !== this.appId)
1461
+ .map((module) => Object.freeze({ id: module.id, metadata: module.metadata }))), Object.freeze(this.modules.map((module) => Object.freeze({
1462
+ id: module.id,
1463
+ app: module.id === this.appId,
1464
+ metadata: module.metadata,
1465
+ settings: module.settings,
1466
+ ui: module.ui,
1467
+ }))), {
1468
+ translate: this.translator(),
1469
+ text: (key, fallback, values) => this.text(key, fallback, values),
1470
+ subscribe: this.subscribeTranslations,
1471
+ }, this.lifecycle);
1472
+ this.scopes.push(scope);
1473
+ scope.bindSlots(this.slotRuntime.bind(scope, plugin.id));
1474
+ scope.onClose(events.dispose);
1475
+ for (const action of plugin.actions)
1476
+ this.install(scope, action, plugin.id, events.events);
1477
+ for (const [index, view] of plugin.views.entries())
1478
+ if (this.slots.has(view.slot)) {
1479
+ const contribution = {
1480
+ slot: view.slot,
1481
+ id: view.id ?? `view:${index}`,
1482
+ component: view.component,
1483
+ key: view.key,
1484
+ order: view.order,
1485
+ when: view.when,
1486
+ };
1487
+ preserveContributionPath(view, contribution);
1488
+ scope.slots.attach(contribution, {
1489
+ availability: view.availability ?? 'wait',
1490
+ });
1491
+ }
1492
+ try {
1493
+ const cleanup = plugin.setup?.({ scope, services: this.services });
1494
+ if (cleanup)
1495
+ scope.own(cleanup);
1496
+ }
1497
+ catch (error) {
1498
+ throw this.attribute(error, plugin.id, 'Setup');
1499
+ }
1500
+ }
1501
+ this.observe(new Set([...this.container.observed, this.settings]));
1502
+ await this.container.start(controller.signal, selected);
1503
+ if (controller.signal.aborted) {
1504
+ await this.stopPlugins(startIds);
1505
+ return result('blocked', ['Update cancelled by runtime shutdown.']);
1506
+ }
1507
+ this.setupComplete = true;
1508
+ for (const id of startIds) {
1509
+ if (controller.signal.aborted)
1510
+ break;
1511
+ this.lifecycleState.plugin(id, 'ready');
1512
+ }
1513
+ if (!controller.signal.aborted)
1514
+ this.lifecycleState.update({ phase: 'ready', cleanup: 'none' });
1515
+ if (!controller.signal.aborted)
1516
+ this.setReady(true);
1517
+ if (controller.signal.aborted) {
1518
+ this.setReady(false);
1519
+ await this.stopPlugins(startIds);
1520
+ return result('blocked', ['Update cancelled by runtime shutdown.']);
1521
+ }
1522
+ return result('applied');
1523
+ }
1524
+ catch (error) {
1525
+ let cleanupError;
1526
+ try {
1527
+ await this.stopPlugins(startIds);
1528
+ }
1529
+ catch (failure) {
1530
+ cleanupError = failure;
1531
+ }
1532
+ const failed = isBitaKitStartupError(error) ? error.plugin : changed[0];
1533
+ for (const id of startIds)
1534
+ this.lifecycleState.plugin(id, id === failed ? 'failed' : 'blocked', {
1535
+ plugin: failed,
1536
+ message: 'Plugin update failed.',
1537
+ });
1538
+ this.lifecycleState.update({
1539
+ phase: 'failed',
1540
+ cleanup: cleanupError ? 'failed' : 'complete',
1541
+ });
1542
+ return result('failed', [
1543
+ error instanceof Error ? error.message : String(error),
1544
+ ...(cleanupError ? ['Cleanup also failed; restart is blocked.'] : []),
1545
+ ]);
423
1546
  }
424
- // Cover synchronous initial emissions and sources changed during setup.
425
- if (observed.size)
426
- this.actions.refresh();
427
1547
  }
428
1548
  unmount() {
1549
+ if (this.stopCompletion)
1550
+ return this.stopCompletion.promise;
1551
+ const completion = (this.stopCompletion = deferred());
429
1552
  this.setReady(false);
430
- const errors = [];
431
- for (const cleanup of this.extensionCleanups.splice(0).reverse()) {
1553
+ // Rejections are reported even if a host ignores the returned promise.
1554
+ void completion.promise.catch((error) => this.reportLifecycleError(error));
1555
+ // A hook or observer may request stop during synchronous construction. Finish recording
1556
+ // ownership first; never dispose a half-created service from inside its own factory.
1557
+ if (this.updating) {
1558
+ this.updateController?.abort();
1559
+ void this.updating.then(() => this.teardown(completion), () => this.teardown(completion));
1560
+ }
1561
+ else if (this.mounting) {
1562
+ this.lifecycleState.update({ cleanup: 'pending' });
1563
+ queueMicrotask(() => this.teardown(completion));
1564
+ }
1565
+ else
1566
+ this.teardown(completion);
1567
+ return completion.promise;
1568
+ }
1569
+ teardown(completion) {
1570
+ const previousCleanupFailed = this.lifecycle.get().cleanup === 'failed';
1571
+ this.tearingDown = true;
1572
+ const starting = this.startPending;
1573
+ this.startController?.abort();
1574
+ this.startController = undefined;
1575
+ if (this.mounted)
1576
+ this.setReady(false);
1577
+ this.lifecycleState.update({
1578
+ phase: 'stopping',
1579
+ operation: Object.freeze({ kind: 'stop', startedAt: Date.now() }),
1580
+ cleanup: 'pending',
1581
+ plugins: Object.freeze(this.lifecycle
1582
+ .get()
1583
+ .plugins.map((entry) => entry.phase === 'failed'
1584
+ ? entry
1585
+ : Object.freeze({ ...entry, phase: 'stopping' }))),
1586
+ });
1587
+ this.readyDeferred.reject(new Error('The runtime stopped before its services finished starting.'));
1588
+ // Unregister immediately: cancellation and new-work gating cannot wait behind an async disposer.
1589
+ const earlyErrors = previousCleanupFailed
1590
+ ? [
1591
+ new Error('Previous plugin update cleanup failed; external resource recovery is required.'),
1592
+ ]
1593
+ : [];
1594
+ for (const { handle } of this.registrations) {
432
1595
  try {
433
- cleanup();
1596
+ handle.unregister();
434
1597
  }
435
1598
  catch (error) {
436
- errors.push(error);
1599
+ earlyErrors.push(error);
437
1600
  }
438
1601
  }
439
- for (const scope of this.scopes.splice(0).reverse()) {
1602
+ for (const scope of this.scopes) {
440
1603
  try {
441
- scope.dispose();
1604
+ scope.close();
442
1605
  }
443
1606
  catch (error) {
444
- errors.push(error);
1607
+ earlyErrors.push(error);
445
1608
  }
446
1609
  }
447
- try {
448
- this.container?.dispose();
449
- }
450
- catch (error) {
451
- errors.push(error);
452
- }
453
- this.events.clear();
454
- this.container = undefined;
455
- this.registrations = [];
456
- this.actionConfigs.clear();
457
- this.publish(null);
458
- if (errors.length)
459
- throw new AggregateError(errors, 'Foundation cleanup failed.');
1610
+ const tasks = [];
1611
+ if (starting && this.startWork)
1612
+ tasks.push(() => this.startWork.then(() => { }, () => { }));
1613
+ const activeRuns = [...this.activeRuns.values()];
1614
+ if (activeRuns.length)
1615
+ tasks.push(() => Promise.all(activeRuns.map((run) => run.promise)).then(() => { }));
1616
+ tasks.push(...this.scopes
1617
+ .splice(0)
1618
+ .reverse()
1619
+ .map((scope) => async () => {
1620
+ try {
1621
+ await scope.dispose();
1622
+ }
1623
+ catch (error) {
1624
+ const plugin = scopeModule(scope).id;
1625
+ const failure = Object.assign(new Error(`Cleanup in plugin "${plugin}" failed.`, { cause: error }), { plugin });
1626
+ this.lifecycleState.plugin(plugin, 'failed', { plugin, message: failure.message });
1627
+ throw failure;
1628
+ }
1629
+ }));
1630
+ if (this.container)
1631
+ tasks.push(() => this.container.dispose());
1632
+ tasks.push(...this.extensionCleanups.splice(0).reverse());
1633
+ tasks.push(() => {
1634
+ for (const off of this.observations.values())
1635
+ off();
1636
+ this.observations.clear();
1637
+ this.pluginEvents.clear();
1638
+ });
1639
+ void cleanupSequence(tasks, (errors) => {
1640
+ errors.unshift(...earlyErrors);
1641
+ try {
1642
+ this.settings.deactivate();
1643
+ }
1644
+ catch (error) {
1645
+ errors.push(error);
1646
+ }
1647
+ this.container = undefined;
1648
+ this.view = undefined;
1649
+ this.registrations = [];
1650
+ this.actionConfigs.clear();
1651
+ this.activeRuns.clear();
1652
+ this.startWork = undefined;
1653
+ this.startPending = false;
1654
+ this.setupComplete = false;
1655
+ this.publish(null);
1656
+ this.lifecycleState.update({
1657
+ phase: errors.length ? 'failed' : 'stopped',
1658
+ cleanup: errors.length ? 'failed' : 'complete',
1659
+ plugins: Object.freeze(this.lifecycle
1660
+ .get()
1661
+ .plugins.map((entry) => entry.phase === 'failed'
1662
+ ? entry
1663
+ : Object.freeze({ ...entry, phase: 'stopped' }))),
1664
+ });
1665
+ this.events.clear();
1666
+ for (const module of this.modules)
1667
+ if (module.events)
1668
+ this.events.declare(module.id, module.events);
1669
+ cleanupFailure(errors, 'BitaKit cleanup failed.');
1670
+ }).then(() => {
1671
+ this.tearingDown = false;
1672
+ completion.resolve();
1673
+ }, (error) => {
1674
+ this.tearingDown = false;
1675
+ completion.reject(error);
1676
+ });
1677
+ }
1678
+ }
1679
+ function defaultFailure(error) {
1680
+ let development = true;
1681
+ try {
1682
+ development = process.env.NODE_ENV !== 'production';
1683
+ }
1684
+ catch {
1685
+ /* no process */
460
1686
  }
1687
+ if (!development)
1688
+ return 'Something went wrong.';
1689
+ return error instanceof Error && error.message ? error.message : 'Action failed.';
1690
+ }
1691
+ /**
1692
+ * Creates the runtime for one composition; `runtime.mount()` starts it and returns the stop
1693
+ * function. Core creates the ActionList unless you pass one. `services` supplies host-owned
1694
+ * services, such as authentication, under their contract names.
1695
+ */
1696
+ export function createRuntime(config, options = {}) {
1697
+ return new BitaKitRuntime(options.actions ?? createActionList(), config, options.services);
461
1698
  }