@bitakit/core 0.1.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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +382 -0
  3. package/discovery/entries.mjs +124 -0
  4. package/discovery/generate.mjs +327 -0
  5. package/discovery/host.mjs +12 -0
  6. package/discovery/index.d.ts +41 -0
  7. package/discovery/index.mjs +4 -0
  8. package/discovery/modules.mjs +13 -0
  9. package/discovery/packages.mjs +57 -0
  10. package/discovery/watch.mjs +23 -0
  11. package/dist/actions/action-list.d.ts +69 -0
  12. package/dist/actions/action-list.js +247 -0
  13. package/dist/actions/action.d.ts +96 -0
  14. package/dist/actions/action.js +145 -0
  15. package/dist/actions/base/url-action.d.ts +8 -0
  16. package/dist/actions/base/url-action.js +15 -0
  17. package/dist/actions/core.d.ts +14 -0
  18. package/dist/actions/core.js +8 -0
  19. package/dist/actions/dependencies.d.ts +8 -0
  20. package/dist/actions/dependencies.js +34 -0
  21. package/dist/actions/execution.d.ts +4 -0
  22. package/dist/actions/execution.js +64 -0
  23. package/dist/actions/feedback.d.ts +17 -0
  24. package/dist/actions/feedback.js +21 -0
  25. package/dist/actions/groups.d.ts +13 -0
  26. package/dist/actions/groups.js +21 -0
  27. package/dist/actions/instance-bindings.d.ts +16 -0
  28. package/dist/actions/instance-bindings.js +93 -0
  29. package/dist/actions/interceptors.d.ts +24 -0
  30. package/dist/actions/interceptors.js +42 -0
  31. package/dist/actions/navigation.d.ts +12 -0
  32. package/dist/actions/navigation.js +42 -0
  33. package/dist/actions/reference.d.ts +17 -0
  34. package/dist/actions/reference.js +39 -0
  35. package/dist/actions/state.d.ts +11 -0
  36. package/dist/actions/state.js +8 -0
  37. package/dist/actions/types.d.ts +99 -0
  38. package/dist/actions/types.js +1 -0
  39. package/dist/app/access.d.ts +4 -0
  40. package/dist/app/access.js +85 -0
  41. package/dist/app/action-access.d.ts +4 -0
  42. package/dist/app/action-access.js +20 -0
  43. package/dist/app/service-error.d.ts +8 -0
  44. package/dist/app/service-error.js +19 -0
  45. package/dist/app/types.d.ts +47 -0
  46. package/dist/app/types.js +1 -0
  47. package/dist/config-service.d.ts +49 -0
  48. package/dist/config-service.js +83 -0
  49. package/dist/configuration.d.ts +4 -0
  50. package/dist/configuration.js +42 -0
  51. package/dist/confirmation.d.ts +14 -0
  52. package/dist/confirmation.js +26 -0
  53. package/dist/contracts.d.ts +27 -0
  54. package/dist/contracts.js +3 -0
  55. package/dist/contribution-origin.d.ts +3 -0
  56. package/dist/contribution-origin.js +13 -0
  57. package/dist/contributions/command.d.ts +8 -0
  58. package/dist/contributions/command.js +50 -0
  59. package/dist/contributions/dialog.d.ts +8 -0
  60. package/dist/contributions/dialog.js +18 -0
  61. package/dist/contributions/form.d.ts +10 -0
  62. package/dist/contributions/form.js +67 -0
  63. package/dist/contributions/host.d.ts +40 -0
  64. package/dist/contributions/host.js +1 -0
  65. package/dist/contributions/index.d.ts +26 -0
  66. package/dist/contributions/index.js +18 -0
  67. package/dist/contributions/native.d.ts +11 -0
  68. package/dist/contributions/native.js +87 -0
  69. package/dist/contributions/shared.d.ts +19 -0
  70. package/dist/contributions/shared.js +48 -0
  71. package/dist/contributions/stateful-action.d.ts +29 -0
  72. package/dist/contributions/stateful-action.js +33 -0
  73. package/dist/conventions.d.ts +4 -0
  74. package/dist/conventions.js +38 -0
  75. package/dist/core.d.ts +21 -0
  76. package/dist/core.js +18 -0
  77. package/dist/definitions.d.ts +356 -0
  78. package/dist/definitions.js +60 -0
  79. package/dist/discovered.d.ts +49 -0
  80. package/dist/discovered.js +120 -0
  81. package/dist/interceptors/service-observers.d.ts +3 -0
  82. package/dist/interceptors/service-observers.js +80 -0
  83. package/dist/interceptors/service.d.ts +37 -0
  84. package/dist/interceptors/service.js +7 -0
  85. package/dist/messages.d.ts +9 -0
  86. package/dist/messages.js +21 -0
  87. package/dist/metadata.d.ts +3 -0
  88. package/dist/metadata.js +13 -0
  89. package/dist/pages.d.ts +8 -0
  90. package/dist/pages.js +22 -0
  91. package/dist/presentation.d.ts +4 -0
  92. package/dist/presentation.js +1 -0
  93. package/dist/replacements.d.ts +22 -0
  94. package/dist/replacements.js +54 -0
  95. package/dist/runtime.d.ts +88 -0
  96. package/dist/runtime.js +445 -0
  97. package/dist/scope.d.ts +34 -0
  98. package/dist/scope.js +78 -0
  99. package/dist/service-key.d.ts +13 -0
  100. package/dist/service-key.js +14 -0
  101. package/dist/services.d.ts +6 -0
  102. package/dist/services.js +53 -0
  103. package/dist/translation.d.ts +13 -0
  104. package/dist/translation.js +43 -0
  105. package/dist/validation.d.ts +2 -0
  106. package/dist/validation.js +16 -0
  107. package/docs/file-contributions.md +161 -0
  108. package/package.json +48 -0
@@ -0,0 +1,445 @@
1
+ import { serviceObserver } from './interceptors/service-observers.js';
2
+ import { isServiceInterceptor } from './interceptors/service.js';
3
+ import { ConfigService } from './config-service.js';
4
+ import { contributionPath } from './contribution-origin.js';
5
+ import { applyActionReplacements } from './replacements.js';
6
+ import { validatePluginPages } from './pages.js';
7
+ import { resolveText } from './translation.js';
8
+ import { ActionGroup, } from '@bitakit/core/actions';
9
+ import { PluginScope, assignScopeModule } from './scope.js';
10
+ import { createServices } from './services.js';
11
+ import { createFoundationApp } from './app/access.js';
12
+ import { fallbackTitle } from './conventions.js';
13
+ import { ActionFailure, evaluateFeedback, } from './actions/feedback.js';
14
+ import { adaptContribution, } from './contributions/index.js';
15
+ function orderPlugins(plugins) {
16
+ const remaining = new Map(plugins.map((plugin) => [plugin.id, plugin]));
17
+ if (remaining.size !== plugins.length)
18
+ throw new Error('Duplicate plugin ID.');
19
+ const ordered = [];
20
+ while (remaining.size) {
21
+ const plugin = [...remaining.values()].find((item) => item.dependencies?.every((id) => ordered.some((done) => done.id === id)) ?? true);
22
+ if (!plugin)
23
+ throw new Error('Missing or cyclic plugin dependency.');
24
+ ordered.push(plugin);
25
+ remaining.delete(plugin.id);
26
+ }
27
+ return ordered;
28
+ }
29
+ /**
30
+ * Mounts plugins into the host's ActionList. Each contribution kind is normalized by an adapter
31
+ * in `./contributions`; the runtime owns services, translation, dialogs, ordering and cleanup.
32
+ */
33
+ export class FoundationRuntime {
34
+ actions;
35
+ config;
36
+ providedServices;
37
+ app;
38
+ configuration;
39
+ modules;
40
+ actionConfigs = new Map();
41
+ ready = false;
42
+ readinessListeners = new Set();
43
+ isReady = () => this.ready;
44
+ subscribeReady = (listener) => {
45
+ this.readinessListeners.add(listener);
46
+ return () => {
47
+ this.readinessListeners.delete(listener);
48
+ };
49
+ };
50
+ setReady(ready) {
51
+ this.ready = ready;
52
+ this.readinessListeners.forEach((listener) => listener());
53
+ }
54
+ listeners = new Set();
55
+ state = null;
56
+ registrations = [];
57
+ scopes = [];
58
+ extensionCleanups = [];
59
+ container;
60
+ translate = (key) => key;
61
+ translationRevision = 0;
62
+ translationListeners = new Set();
63
+ getTranslationRevision = () => this.translationRevision;
64
+ subscribeTranslations = (listener) => {
65
+ this.translationListeners.add(listener);
66
+ return () => { this.translationListeners.delete(listener); };
67
+ };
68
+ notifier;
69
+ formFeedback = new WeakMap();
70
+ groups;
71
+ constructor(actions, config, providedServices = {}) {
72
+ this.actions = actions;
73
+ this.config = config;
74
+ this.providedServices = providedServices;
75
+ this.modules = [
76
+ { ...config, id: config.appId ?? '@foundation/app' },
77
+ ...(config.plugins ?? []),
78
+ ];
79
+ this.app = createFoundationApp(this);
80
+ this.configuration = new ConfigService([{ id: config.appId ?? '@foundation/app', config: config.config }, ...(config.plugins ?? [])], config.configOverrides);
81
+ validatePluginPages(this.modules);
82
+ if (new Set(config.groups ?? []).size !== (config.groups ?? []).length)
83
+ throw new Error('Duplicate action group.');
84
+ this.groups = new Map((config.groups ?? []).map((id) => [id, new ActionGroup(id)]));
85
+ }
86
+ get appId() {
87
+ return this.config.appId ?? '@foundation/app';
88
+ }
89
+ order;
90
+ /** Modules in install order: dependencies first, the application module included. */
91
+ moduleOrder() {
92
+ this.order ??= orderPlugins([
93
+ {
94
+ id: this.appId,
95
+ dependencies: this.config.dependencies,
96
+ contributions: this.config.contributions,
97
+ installs: this.config.installs,
98
+ },
99
+ ...(this.config.plugins ?? []),
100
+ ]);
101
+ return this.order;
102
+ }
103
+ /**
104
+ * Declarative contributions of one kind in install order. Pure and available before mount, so
105
+ * UI integrations can derive an initial render snapshot equivalent to the mounted state.
106
+ */
107
+ contributionsOf(kind) {
108
+ return this.moduleOrder().flatMap((module) => {
109
+ const values = module.contributions?.[kind];
110
+ return values?.length
111
+ ? [{ module: module.id, app: module.id === this.appId, values: values }]
112
+ : [];
113
+ });
114
+ }
115
+ getGroup = (entry) => {
116
+ const id = typeof entry === 'string' ? entry : entry.id;
117
+ let group = this.groups.get(id);
118
+ if (!group) {
119
+ group = typeof entry === 'string' ? new ActionGroup(id) : entry;
120
+ this.groups.set(id, group);
121
+ }
122
+ return group;
123
+ };
124
+ get services() {
125
+ if (!this.container)
126
+ throw new Error('Foundation is not mounted.');
127
+ return this.container.services;
128
+ }
129
+ getSnapshot = () => this.state;
130
+ getServerSnapshot = () => null;
131
+ subscribe = (listener) => {
132
+ this.listeners.add(listener);
133
+ return () => {
134
+ this.listeners.delete(listener);
135
+ };
136
+ };
137
+ publish(state) {
138
+ this.state = state;
139
+ this.listeners.forEach((listener) => listener());
140
+ }
141
+ t = (key) => this.translate(key);
142
+ text(key, fallback, values) {
143
+ return resolveText(this.translate, key, fallback, values);
144
+ }
145
+ title(definition) {
146
+ return definition.title !== undefined
147
+ ? this.text(definition.title, this.text(`${definition.id}.title`, definition.title))
148
+ : this.text(definition.conventions !== false ? `${definition.id}.title` : undefined, fallbackTitle(definition));
149
+ }
150
+ description(definition) {
151
+ return definition.description === undefined
152
+ ? undefined
153
+ : this.text(definition.description, this.text(`${definition.id}.description`, definition.description));
154
+ }
155
+ fieldLabel(definition, name, field) {
156
+ const key = field.label ??
157
+ (definition.conventions !== false ? `${definition.id}.fields.${name}` : undefined);
158
+ return this.text(key, field.label ?? name.charAt(0).toUpperCase() + name.slice(1));
159
+ }
160
+ /** Installs one presentation sink; disposing an older owner cannot clear its replacement. */
161
+ setNotifier(notify) {
162
+ this.notifier = notify;
163
+ return () => {
164
+ if (this.notifier === notify)
165
+ this.notifier = undefined;
166
+ };
167
+ }
168
+ /** Presentation failures, including rejected promises, never change the Action outcome. */
169
+ notify(message, kind = 'success') {
170
+ if (!message)
171
+ return;
172
+ try {
173
+ Promise.resolve(this.notifier?.(message, kind)).catch(() => { });
174
+ }
175
+ catch {
176
+ /* presentation only */
177
+ }
178
+ }
179
+ translator() {
180
+ const translate = (key, values) => this.translate(key, values);
181
+ translate.has = (key) => this.translate.has?.(key) ?? true;
182
+ return translate;
183
+ }
184
+ override(id) {
185
+ return this.config.actionOverrides?.[id];
186
+ }
187
+ dialog() {
188
+ return this.state;
189
+ }
190
+ openDialog(definition, input) {
191
+ this.publish({ definition, input, token: Symbol() });
192
+ }
193
+ rememberFormFeedback(state, outcome) {
194
+ this.formFeedback.set(state, outcome);
195
+ }
196
+ feedback(definition, kind, option, context) {
197
+ const value = evaluateFeedback(option, context);
198
+ if (value === false)
199
+ return { message: false, closeDialog: true };
200
+ try {
201
+ return {
202
+ message: (value.message ? this.text(value.message, this.text(`${definition.id}.${kind}`, value.message, value.values), value.values) : value.message) ??
203
+ (value.messageKey ? this.text(value.messageKey, value.messageKey, value.values) : false),
204
+ closeDialog: value.closeDialog ?? true,
205
+ };
206
+ }
207
+ catch {
208
+ return { message: false, closeDialog: true };
209
+ }
210
+ }
211
+ /** Public submission path; the internal submit registration owns validation and pending guards. */
212
+ async submitForm(definition, values) {
213
+ const state = this.state;
214
+ if (state?.definition !== definition)
215
+ return;
216
+ const outcome = await this.actions.execute(`${definition.id}.submit`, values);
217
+ if (outcome.status !== 'completed' || this.state !== state)
218
+ return;
219
+ const feedback = this.formFeedback.get(state);
220
+ this.formFeedback.delete(state);
221
+ if (!feedback)
222
+ return;
223
+ this.notify(feedback.message);
224
+ if (feedback.closeDialog)
225
+ this.close();
226
+ }
227
+ setTranslations(translate) {
228
+ this.translate = translate;
229
+ this.translationRevision += 1;
230
+ this.translationListeners.forEach((listener) => listener());
231
+ for (const { definition, handle } of this.registrations) {
232
+ handle.update({
233
+ title: this.title(definition),
234
+ description: this.description(definition),
235
+ tooltip: definition.tooltip === undefined
236
+ ? undefined
237
+ : this.text(definition.tooltip, this.text(`${definition.id}.tooltip`, definition.tooltip)),
238
+ });
239
+ }
240
+ }
241
+ close = () => {
242
+ if (this.state?.definition.kind === 'form' &&
243
+ this.actions.get(`${this.state.definition.id}.submit`)?.pending)
244
+ return;
245
+ this.publish(null);
246
+ };
247
+ mount() {
248
+ if (this.container)
249
+ throw new Error('Foundation is already mounted.');
250
+ const selected = applyActionReplacements(this.config.plugins ?? [], this.config.actions ?? []);
251
+ const plugins = orderPlugins([
252
+ {
253
+ id: this.config.appId ?? '@foundation/app',
254
+ dependencies: this.config.dependencies,
255
+ setup: this.config.setup,
256
+ actions: selected.actions,
257
+ services: this.config.services,
258
+ config: this.config.config,
259
+ contributions: this.config.contributions,
260
+ installs: this.config.installs,
261
+ },
262
+ ...selected.plugins,
263
+ ]);
264
+ const serviceModules = new Map(plugins.flatMap((plugin) => (plugin.services ?? []).map((service) => [service, plugin.id])));
265
+ this.container = createServices(plugins.flatMap((plugin) => plugin.services ?? []), this.providedServices, (definition) => this.configuration.context(serviceModules.get(definition)), serviceObserver(this.modules));
266
+ try {
267
+ this.extensionCleanups.push(this.actions.subscribeExecution((event) => {
268
+ if (event.phase === 'failed' &&
269
+ event.context.get() &&
270
+ event.error instanceof ActionFailure)
271
+ this.notify(event.error.feedback, 'failure');
272
+ }));
273
+ this.connectTranslation();
274
+ this.installInterceptors(plugins);
275
+ for (const plugin of plugins) {
276
+ const scope = new PluginScope(this.actions, this.groups);
277
+ assignScopeModule(scope, { id: plugin.id, app: plugin.id === this.appId });
278
+ this.scopes.push(scope);
279
+ }
280
+ this.installContributions(plugins);
281
+ const observed = new Set();
282
+ plugins.forEach((plugin, index) => {
283
+ for (const contribution of plugin.actions ?? [])
284
+ this.install(this.scopes[index], contribution, observed, plugin.id);
285
+ });
286
+ this.observe(observed);
287
+ plugins.forEach((plugin, index) => {
288
+ const scope = this.scopes[index];
289
+ const cleanup = plugin.setup?.({ app: scope, services: this.services });
290
+ if (cleanup)
291
+ scope.own(cleanup);
292
+ });
293
+ }
294
+ catch (error) {
295
+ this.unmount();
296
+ throw error;
297
+ }
298
+ this.setReady(true);
299
+ return () => this.unmount();
300
+ }
301
+ /** Routes each contribution kind to the one module that installs it; cleanup stays with the contributor. */
302
+ installContributions(plugins) {
303
+ const installers = new Map();
304
+ for (const plugin of plugins)
305
+ for (const [kind, install] of Object.entries(plugin.installs ?? {})) {
306
+ if (!install)
307
+ continue;
308
+ const existing = installers.get(kind);
309
+ if (existing)
310
+ throw new Error(`Contribution kind "${kind}" is installed by both "${existing.module}" and "${plugin.id}".`);
311
+ installers.set(kind, { module: plugin.id, install });
312
+ }
313
+ for (const plugin of plugins)
314
+ for (const [kind, values] of Object.entries(plugin.contributions ?? {}))
315
+ if (values?.length && !installers.has(kind))
316
+ throw new Error(`"${plugin.id}" contributes "${kind}", but no enabled plugin installs that kind.`);
317
+ for (const [kind, { install }] of installers)
318
+ plugins.forEach((plugin, index) => {
319
+ const values = plugin.contributions?.[kind];
320
+ if (!values?.length)
321
+ return;
322
+ const cleanup = install(values, {
323
+ module: plugin.id,
324
+ app: plugin.id === this.appId,
325
+ services: this.services,
326
+ });
327
+ if (cleanup)
328
+ this.scopes[index].own(cleanup);
329
+ });
330
+ }
331
+ connectTranslation() {
332
+ const i18n = this.services.i18n;
333
+ if (!i18n)
334
+ return;
335
+ this.setTranslations(i18n.translate);
336
+ this.extensionCleanups.push(i18n.subscribe(() => this.setTranslations(i18n.translate)));
337
+ }
338
+ installInterceptors(plugins) {
339
+ const entries = [
340
+ ...(this.config.interceptors ?? []).map((definition) => ({
341
+ definition,
342
+ module: this.config.appId ?? '@foundation/app',
343
+ global: !isServiceInterceptor(definition) && definition.scope !== 'plugin',
344
+ })),
345
+ ...plugins.flatMap((plugin) => (plugin.interceptors ?? []).map((definition) => ({
346
+ definition,
347
+ module: plugin.id,
348
+ global: !isServiceInterceptor(definition) && definition.scope === 'global',
349
+ }))),
350
+ ].sort((a, b) => (a.definition.order ?? 0) - (b.definition.order ?? 0));
351
+ for (const { definition, module, global } of entries) {
352
+ if (isServiceInterceptor(definition))
353
+ continue;
354
+ if ('create' in definition)
355
+ this.requireServices(definition.requires);
356
+ const interceptor = 'create' in definition
357
+ ? definition.create({
358
+ services: this.services,
359
+ translate: this.translator(),
360
+ config: this.configuration.context(module),
361
+ })
362
+ : definition;
363
+ this.extensionCleanups.push(this.actions.use({
364
+ before: (context) => {
365
+ const target = this.actionConfigs.get(context.id);
366
+ if (!global && target?.module !== module)
367
+ return;
368
+ return interceptor.before({
369
+ ...context,
370
+ config: target?.config ?? this.configuration.context(module),
371
+ });
372
+ },
373
+ }));
374
+ }
375
+ }
376
+ requireServices(ids = []) {
377
+ for (const id of ids)
378
+ if (!Object.hasOwn(this.services, id))
379
+ throw new Error(`Missing service "${id}".`);
380
+ }
381
+ /** One path for every kind: adapt, check dependencies, register, remember for re-translation. */
382
+ install(scope, contribution, observed, module) {
383
+ const path = (typeof contribution === 'object' ? contribution.configPath : undefined) ??
384
+ contributionPath(contribution) ??
385
+ (typeof contribution === 'object' && contribution.id ? contribution.id.split('.') : []);
386
+ const config = this.configuration.context(module, path);
387
+ const adapted = adaptContribution(contribution, this, config);
388
+ this.requireServices(adapted.requires);
389
+ for (const id of adapted.watch) {
390
+ const service = this.services[id];
391
+ if (!service || typeof service.subscribe !== 'function')
392
+ throw new Error(`Observed service "${id}" must provide subscribe(listener).`);
393
+ observed.add(id);
394
+ }
395
+ for (const registration of adapted.registrations) {
396
+ this.actionConfigs.set(registration.id, { module, config });
397
+ const handle = registration.instance
398
+ ? this.actions.add(registration.id, registration.instance, registration.placement)
399
+ : this.actions.register(registration.definition, registration.placement);
400
+ scope.own(handle.unregister);
401
+ this.registrations.push({ definition: adapted.definition, handle });
402
+ }
403
+ }
404
+ observe(observed) {
405
+ for (const id of observed) {
406
+ const service = this.services[id];
407
+ this.extensionCleanups.push(service.subscribe(() => this.actions.refresh()));
408
+ }
409
+ // Cover synchronous initial emissions and sources changed during setup.
410
+ if (observed.size)
411
+ this.actions.refresh();
412
+ }
413
+ unmount() {
414
+ this.setReady(false);
415
+ const errors = [];
416
+ for (const cleanup of this.extensionCleanups.splice(0).reverse()) {
417
+ try {
418
+ cleanup();
419
+ }
420
+ catch (error) {
421
+ errors.push(error);
422
+ }
423
+ }
424
+ for (const scope of this.scopes.splice(0).reverse()) {
425
+ try {
426
+ scope.dispose();
427
+ }
428
+ catch (error) {
429
+ errors.push(error);
430
+ }
431
+ }
432
+ try {
433
+ this.container?.dispose();
434
+ }
435
+ catch (error) {
436
+ errors.push(error);
437
+ }
438
+ this.container = undefined;
439
+ this.registrations = [];
440
+ this.actionConfigs.clear();
441
+ this.publish(null);
442
+ if (errors.length)
443
+ throw new AggregateError(errors, 'Foundation cleanup failed.');
444
+ }
445
+ }
@@ -0,0 +1,34 @@
1
+ import { ActionGroup, type ActionDefinition, type ActionList } from '@bitakit/core/actions';
2
+ export type ScopeModule = Readonly<{
3
+ id: string;
4
+ app: boolean;
5
+ }>;
6
+ /** Runtime only: records which module a scope belongs to. Not exported from the package. */
7
+ export declare function assignScopeModule(scope: PluginScope, module: ScopeModule): void;
8
+ /**
9
+ * The module that owns a runtime-issued scope. Integrations derive ownership and layer from it,
10
+ * so a plugin cannot register on behalf of the application or another plugin.
11
+ */
12
+ export declare function scopeModule(scope: PluginScope): ScopeModule;
13
+ /** Scoped facade over the host list, never a second action registry. */
14
+ export declare class PluginScope {
15
+ private list;
16
+ private groups;
17
+ private cleanups;
18
+ private active;
19
+ constructor(list: ActionList, groups: Map<string, ActionGroup>);
20
+ own(cleanup: () => void): void;
21
+ private assertActive;
22
+ actions: {
23
+ getGroup: (id: string) => {
24
+ attach: (actionId: string) => {
25
+ dispose: () => void;
26
+ };
27
+ add: (action: ActionDefinition) => {
28
+ dispose: () => void;
29
+ update: (patch: import("@bitakit/core/actions").ActionPatch) => boolean;
30
+ };
31
+ };
32
+ };
33
+ dispose(): void;
34
+ }
package/dist/scope.js ADDED
@@ -0,0 +1,78 @@
1
+ import { ActionGroup } from '@bitakit/core/actions';
2
+ const modules = new WeakMap();
3
+ /** Runtime only: records which module a scope belongs to. Not exported from the package. */
4
+ export function assignScopeModule(scope, module) {
5
+ modules.set(scope, Object.freeze({ ...module }));
6
+ }
7
+ /**
8
+ * The module that owns a runtime-issued scope. Integrations derive ownership and layer from it,
9
+ * so a plugin cannot register on behalf of the application or another plugin.
10
+ */
11
+ export function scopeModule(scope) {
12
+ const module = modules.get(scope);
13
+ if (!module)
14
+ throw new Error('Unknown plugin scope. Use the scope passed to setup.');
15
+ return module;
16
+ }
17
+ /** Scoped facade over the host list, never a second action registry. */
18
+ export class PluginScope {
19
+ list;
20
+ groups;
21
+ cleanups = [];
22
+ active = true;
23
+ constructor(list, groups) {
24
+ this.list = list;
25
+ this.groups = groups;
26
+ }
27
+ own(cleanup) {
28
+ this.assertActive();
29
+ this.cleanups.push(cleanup);
30
+ }
31
+ assertActive() {
32
+ if (!this.active)
33
+ throw new Error('Plugin scope is no longer active.');
34
+ }
35
+ actions = {
36
+ getGroup: (id) => {
37
+ this.assertActive();
38
+ let group = this.groups.get(id);
39
+ if (!group) {
40
+ group = new ActionGroup(id);
41
+ this.groups.set(id, group);
42
+ }
43
+ return {
44
+ attach: (actionId) => {
45
+ this.assertActive();
46
+ const dispose = this.list.attach(actionId, group);
47
+ this.own(dispose);
48
+ return { dispose };
49
+ },
50
+ add: (action) => {
51
+ this.assertActive();
52
+ const handle = this.list.register(action, {
53
+ groups: [...(action.groups ?? []), group],
54
+ });
55
+ this.own(handle.unregister);
56
+ return { dispose: handle.unregister, update: handle.update };
57
+ },
58
+ };
59
+ },
60
+ };
61
+ dispose() {
62
+ if (!this.active)
63
+ return;
64
+ this.active = false;
65
+ const errors = [];
66
+ for (const cleanup of this.cleanups.reverse()) {
67
+ try {
68
+ cleanup();
69
+ }
70
+ catch (error) {
71
+ errors.push(error);
72
+ }
73
+ }
74
+ this.cleanups = [];
75
+ if (errors.length)
76
+ throw new AggregateError(errors, 'Plugin cleanup failed.');
77
+ }
78
+ }
@@ -0,0 +1,13 @@
1
+ import type { ServiceDefinition, Services } from './definitions.js';
2
+ declare const serviceType: unique symbol;
3
+ /** A stable runtime ID carrying an invariant TypeScript contract. Share it between providers and consumers. */
4
+ export type ServiceKey<T> = string & {
5
+ readonly [serviceType]: (value: T) => T;
6
+ };
7
+ export declare function serviceKey<T>(id: string): ServiceKey<T>;
8
+ export declare function getService<T>(services: Partial<Services>, key: ServiceKey<T>): T;
9
+ /** The provider must implement the shared contract; registration and cleanup use the normal container. */
10
+ export declare function provideService<T>(key: ServiceKey<T>, definition: Omit<ServiceDefinition<NoInfer<T>>, 'id'>): ServiceDefinition<T> & {
11
+ id: ServiceKey<T>;
12
+ };
13
+ export {};
@@ -0,0 +1,14 @@
1
+ export function serviceKey(id) {
2
+ if (!id.trim())
3
+ throw new Error('A service key must not be empty.');
4
+ return id;
5
+ }
6
+ export function getService(services, key) {
7
+ if (!Object.hasOwn(services, key))
8
+ throw new Error(`Missing service "${key}".`);
9
+ return services[key];
10
+ }
11
+ /** The provider must implement the shared contract; registration and cleanup use the normal container. */
12
+ export function provideService(key, definition) {
13
+ return { ...definition, id: key };
14
+ }
@@ -0,0 +1,6 @@
1
+ import { type ConfigContext } from './config-service.js';
2
+ import type { ServiceDefinition, Services } from './definitions.js';
3
+ export declare function createServices(definitions: readonly ServiceDefinition<any>[], provided?: Partial<Services>, configFor?: (definition: ServiceDefinition<any>) => ConfigContext, decorate?: (id: string, instance: any, active: () => boolean) => any): {
4
+ services: Services;
5
+ dispose: () => void;
6
+ };
@@ -0,0 +1,53 @@
1
+ import { ConfigService } from './config-service.js';
2
+ export function createServices(definitions, provided = {}, configFor = () => new ConfigService([{ id: 'app' }]).context('app'), decorate = (_id, instance) => instance) {
3
+ let active = true;
4
+ const pending = new Map();
5
+ const instances = Object.create(null);
6
+ for (const [id, instance] of Object.entries(provided))
7
+ instances[id] = decorate(id, instance, () => active);
8
+ const cleanups = [];
9
+ const dispose = () => {
10
+ active = false;
11
+ const errors = [];
12
+ for (const cleanup of cleanups.splice(0).reverse()) {
13
+ try {
14
+ cleanup();
15
+ }
16
+ catch (error) {
17
+ errors.push(error);
18
+ }
19
+ }
20
+ if (errors.length)
21
+ throw new AggregateError(errors, 'Service cleanup failed.');
22
+ };
23
+ for (const definition of definitions) {
24
+ if (pending.has(definition.id) || Object.hasOwn(instances, definition.id))
25
+ throw new Error(`Duplicate service "${definition.id}".`);
26
+ pending.set(definition.id, definition);
27
+ }
28
+ try {
29
+ while (pending.size) {
30
+ let progressed = false;
31
+ for (const [id, definition] of pending) {
32
+ if (definition.requires?.some((key) => !Object.hasOwn(instances, key)))
33
+ continue;
34
+ const instance = definition.create({
35
+ services: instances,
36
+ config: configFor(definition),
37
+ });
38
+ if (definition.dispose)
39
+ cleanups.push(() => definition.dispose(instance));
40
+ instances[id] = decorate(id, instance, () => active);
41
+ pending.delete(id);
42
+ progressed = true;
43
+ }
44
+ if (!progressed)
45
+ throw new Error(`Missing or cyclic service dependencies: ${[...pending.keys()].join(', ')}.`);
46
+ }
47
+ }
48
+ catch (error) {
49
+ dispose();
50
+ throw error;
51
+ }
52
+ return { services: Object.freeze(instances), dispose };
53
+ }
@@ -0,0 +1,13 @@
1
+ import type { Translator } from './definitions.js';
2
+ import { type TranslationService } from './contracts.js';
3
+ /** Shared key-or-literal resolution for automatic and imperatively registered Actions. */
4
+ export declare function resolveText(translate: Translator, value: string | undefined, fallback?: string, values?: Parameters<Translator>[1]): string;
5
+ /** Adapter primitive. No locale store: the current translator delegates to its provider. */
6
+ export declare function createTranslationPlugin(initial: Translator, catalog?: TranslationService['getCatalog']): {
7
+ readonly id: "translation";
8
+ readonly services: readonly [import("./definitions.js").ServiceDefinition<TranslationService> & {
9
+ id: import("./service-key.js").ServiceKey<TranslationService>;
10
+ }];
11
+ readonly translation: TranslationService;
12
+ readonly update: (next: Translator, nextCatalog?: ((namespace?: string) => import("./contracts.js").TranslationCatalog | undefined) | undefined) => void;
13
+ };