@bitakit/core 0.1.2 → 0.2.1

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 (157) hide show
  1. package/README.md +44 -207
  2. package/discovery/index.d.ts +1 -41
  3. package/discovery/index.mjs +1 -4
  4. package/dist/actions/action-list.d.ts +4 -0
  5. package/dist/actions/action-list.js +58 -16
  6. package/dist/actions/action.d.ts +2 -0
  7. package/dist/actions/action.js +4 -0
  8. package/dist/actions/brand.d.ts +21 -0
  9. package/dist/actions/brand.js +36 -0
  10. package/dist/actions/core.d.ts +4 -3
  11. package/dist/actions/core.js +4 -2
  12. package/dist/actions/execution.d.ts +2 -2
  13. package/dist/actions/execution.js +61 -9
  14. package/dist/actions/feedback.d.ts +2 -0
  15. package/dist/actions/feedback.js +8 -0
  16. package/dist/actions/groups.js +5 -1
  17. package/dist/actions/instance-bindings.js +3 -2
  18. package/dist/actions/interceptors.d.ts +9 -3
  19. package/dist/actions/interceptors.js +31 -3
  20. package/dist/actions/navigation.d.ts +2 -1
  21. package/dist/actions/navigation.js +10 -5
  22. package/dist/actions/reference.js +10 -5
  23. package/dist/actions/types.d.ts +9 -1
  24. package/dist/app/access.d.ts +4 -4
  25. package/dist/app/access.js +33 -71
  26. package/dist/app/action-access.d.ts +2 -2
  27. package/dist/app/action-access.js +6 -4
  28. package/dist/app/service-error.d.ts +2 -2
  29. package/dist/app/service-error.js +10 -6
  30. package/dist/app/types.d.ts +76 -33
  31. package/dist/config-service.d.ts +30 -6
  32. package/dist/config-service.js +25 -9
  33. package/dist/configuration.d.ts +6 -3
  34. package/dist/configuration.js +8 -6
  35. package/dist/contracts.d.ts +4 -2
  36. package/dist/contracts.js +3 -3
  37. package/dist/contribution-origin.d.ts +4 -1
  38. package/dist/contribution-origin.js +14 -1
  39. package/dist/contributions/action.d.ts +26 -0
  40. package/dist/contributions/action.js +171 -0
  41. package/dist/contributions/host.d.ts +14 -11
  42. package/dist/contributions/index.d.ts +1 -26
  43. package/dist/contributions/index.js +1 -18
  44. package/dist/conventions.d.ts +8 -4
  45. package/dist/conventions.js +12 -31
  46. package/dist/core.d.ts +41 -18
  47. package/dist/core.js +25 -13
  48. package/dist/definitions.d.ts +272 -306
  49. package/dist/definitions.js +28 -56
  50. package/dist/destinations.d.ts +25 -0
  51. package/dist/destinations.js +21 -0
  52. package/dist/discovered.d.ts +52 -21
  53. package/dist/discovered.js +89 -35
  54. package/dist/events/define.d.ts +43 -0
  55. package/dist/events/define.js +17 -0
  56. package/dist/events/service.d.ts +35 -8
  57. package/dist/events/service.js +184 -42
  58. package/dist/events/types.d.ts +29 -9
  59. package/dist/inspection/inventory.d.ts +86 -0
  60. package/dist/inspection/inventory.js +132 -0
  61. package/dist/interceptors/define.d.ts +76 -0
  62. package/dist/interceptors/define.js +23 -0
  63. package/dist/interceptors/service-observers.d.ts +6 -3
  64. package/dist/interceptors/service-observers.js +13 -10
  65. package/dist/lifecycle/cleanup.d.ts +5 -0
  66. package/dist/lifecycle/cleanup.js +41 -0
  67. package/dist/lifecycle/controller.d.ts +82 -0
  68. package/dist/lifecycle/controller.js +276 -0
  69. package/dist/lifecycle/reconcile.d.ts +19 -0
  70. package/dist/lifecycle/reconcile.js +68 -0
  71. package/dist/lifecycle/state.d.ts +53 -0
  72. package/dist/lifecycle/state.js +86 -0
  73. package/dist/names.d.ts +10 -0
  74. package/dist/names.js +1 -0
  75. package/dist/pages.d.ts +39 -6
  76. package/dist/pages.js +93 -11
  77. package/dist/presentation.d.ts +9 -0
  78. package/dist/runtime.d.ts +166 -28
  79. package/dist/runtime.js +1485 -248
  80. package/dist/schema.d.ts +13 -0
  81. package/dist/schema.js +38 -0
  82. package/dist/scope.d.ts +59 -4
  83. package/dist/scope.js +133 -11
  84. package/dist/service-key.d.ts +33 -14
  85. package/dist/service-key.js +21 -5
  86. package/dist/service-names.d.ts +39 -0
  87. package/dist/service-names.js +175 -0
  88. package/dist/services.d.ts +24 -5
  89. package/dist/services.js +230 -37
  90. package/dist/settings/access.d.ts +19 -0
  91. package/dist/settings/access.js +78 -0
  92. package/dist/settings/define.d.ts +97 -0
  93. package/dist/settings/define.js +83 -0
  94. package/dist/settings/storage.d.ts +45 -0
  95. package/dist/settings/storage.js +102 -0
  96. package/dist/settings/store.d.ts +74 -0
  97. package/dist/settings/store.js +345 -0
  98. package/dist/slots/action-placement.d.ts +47 -0
  99. package/dist/slots/action-placement.js +1 -0
  100. package/dist/slots/define.d.ts +52 -0
  101. package/dist/slots/define.js +12 -0
  102. package/dist/slots/normalize.d.ts +7 -0
  103. package/dist/slots/normalize.js +36 -0
  104. package/dist/slots/runtime.d.ts +43 -0
  105. package/dist/slots/runtime.js +348 -0
  106. package/dist/slots/types.d.ts +113 -0
  107. package/dist/slots/types.js +1 -0
  108. package/dist/startup-error.d.ts +21 -0
  109. package/dist/startup-error.js +29 -0
  110. package/dist/store.d.ts +24 -0
  111. package/dist/store.js +40 -0
  112. package/dist/translation.d.ts +9 -4
  113. package/dist/translation.js +2 -3
  114. package/examples/todos/actions/create.mjs +1 -3
  115. package/examples/todos/actions/delete.mjs +3 -10
  116. package/examples/todos/actions/list.mjs +1 -3
  117. package/examples/todos/events.mjs +5 -0
  118. package/examples/todos/plugin.mjs +4 -2
  119. package/examples/todos/services/tasks.mjs +14 -20
  120. package/examples/todos.mjs +8 -7
  121. package/package.json +36 -9
  122. package/testing/index.d.ts +59 -0
  123. package/testing/index.mjs +150 -0
  124. package/assets/bitakit-banner.png +0 -0
  125. package/discovery/entries.mjs +0 -124
  126. package/discovery/generate.mjs +0 -321
  127. package/discovery/host.mjs +0 -12
  128. package/discovery/modules.mjs +0 -13
  129. package/discovery/packages.mjs +0 -57
  130. package/discovery/watch.mjs +0 -23
  131. package/dist/app/service-aliases.d.ts +0 -4
  132. package/dist/app/service-aliases.js +0 -14
  133. package/dist/contributions/command.d.ts +0 -8
  134. package/dist/contributions/command.js +0 -59
  135. package/dist/contributions/dialog.d.ts +0 -8
  136. package/dist/contributions/dialog.js +0 -18
  137. package/dist/contributions/form.d.ts +0 -10
  138. package/dist/contributions/form.js +0 -67
  139. package/dist/contributions/native.d.ts +0 -11
  140. package/dist/contributions/native.js +0 -87
  141. package/dist/contributions/shared.d.ts +0 -19
  142. package/dist/contributions/shared.js +0 -48
  143. package/dist/contributions/stateful-action.d.ts +0 -29
  144. package/dist/contributions/stateful-action.js +0 -33
  145. package/dist/events/action-setup.d.ts +0 -19
  146. package/dist/events/action-setup.js +0 -24
  147. package/dist/interceptors/service.d.ts +0 -37
  148. package/dist/interceptors/service.js +0 -7
  149. package/dist/replacements.d.ts +0 -22
  150. package/dist/replacements.js +0 -54
  151. package/dist/validation.d.ts +0 -2
  152. package/dist/validation.js +0 -16
  153. package/docs/auth.md +0 -106
  154. package/docs/events.md +0 -157
  155. package/docs/file-contributions.md +0 -174
  156. package/docs/reference.md +0 -404
  157. package/docs/todo-tutorial.md +0 -88
@@ -0,0 +1,13 @@
1
+ import type { InputSchema } from './definitions.js';
2
+ export declare const isThenable: (value: unknown) => value is PromiseLike<unknown>;
3
+ /** A readable message for schema errors; zod's message is JSON, but its `issues` are not. */
4
+ export declare function schemaErrorMessage(error: unknown, fallback?: string): string;
5
+ /** Undefined when the schema validates asynchronously; callers then await `validate`. */
6
+ export declare function validateSync<T>(schema: InputSchema<T> | undefined, input: unknown): {
7
+ ok: true;
8
+ value: T;
9
+ } | {
10
+ ok: false;
11
+ error: Error;
12
+ } | undefined;
13
+ export declare function validate<T>(schema: InputSchema<T>, input: unknown): Promise<T>;
package/dist/schema.js ADDED
@@ -0,0 +1,38 @@
1
+ export const isThenable = (value) => !!value && typeof value.then === 'function';
2
+ const invalid = (issues) => new Error(`Invalid input: ${issues.map((issue) => issue.message).join('; ')}`);
3
+ /** A readable message for schema errors; zod's message is JSON, but its `issues` are not. */
4
+ export function schemaErrorMessage(error, fallback = 'Invalid input.') {
5
+ const issues = error?.issues;
6
+ if (Array.isArray(issues) && issues.every((issue) => typeof issue?.message === 'string'))
7
+ return issues.map((issue) => issue.message).join('; ');
8
+ return error instanceof Error && error.message ? error.message : fallback;
9
+ }
10
+ /** Undefined when the schema validates asynchronously; callers then await `validate`. */
11
+ export function validateSync(schema, input) {
12
+ if (!schema)
13
+ return undefined;
14
+ try {
15
+ if ('parse' in schema)
16
+ return { ok: true, value: schema.parse(input) };
17
+ const result = schema['~standard'].validate(input);
18
+ if (isThenable(result))
19
+ return undefined;
20
+ if ('issues' in result)
21
+ return {
22
+ ok: false,
23
+ error: invalid(result.issues),
24
+ };
25
+ return { ok: true, value: result.value };
26
+ }
27
+ catch (error) {
28
+ return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };
29
+ }
30
+ }
31
+ export async function validate(schema, input) {
32
+ if ('parse' in schema)
33
+ return schema.parse(input);
34
+ const result = await schema['~standard'].validate(input);
35
+ if ('issues' in result)
36
+ throw invalid(result.issues);
37
+ return result.value;
38
+ }
package/dist/scope.d.ts CHANGED
@@ -1,23 +1,75 @@
1
1
  import { ActionGroup, type ActionDefinition, type ActionList } from '@bitakit/core/actions';
2
+ import type { PluginMetadata, PluginUI, Translator } from './definitions.js';
3
+ import type { SettingsDefinition } from './settings/define.js';
4
+ import { type Cleanup } from './lifecycle/cleanup.js';
5
+ import type { LifecycleState } from './lifecycle/state.js';
6
+ import type { ScopedSlots } from './slots/types.js';
2
7
  export type ScopeModule = Readonly<{
3
8
  id: string;
4
9
  app: boolean;
5
10
  }>;
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;
11
+ /** A plugin as integrations may present it: its ID and metadata, never its services. */
12
+ export type ComposedPlugin = Readonly<{
13
+ id: string;
14
+ metadata?: PluginMetadata;
15
+ }>;
16
+ /** A composed module with its declarations, for integrations that project them (settings pages, overviews). */
17
+ export type ComposedModule = Readonly<{
18
+ id: string;
19
+ app: boolean;
20
+ metadata?: PluginMetadata;
21
+ settings?: SettingsDefinition<any>;
22
+ ui?: PluginUI;
23
+ }>;
24
+ /** The host's live translation, whichever way it was supplied (`i18n` service or provider prop). */
25
+ export type ScopeTranslation = Readonly<{
26
+ translate: Translator;
27
+ /** The translated key when the catalog has it, otherwise the fallback. */
28
+ text(key: string | undefined, fallback: string, values?: Parameters<Translator>[1]): string;
29
+ subscribe(listener: () => void): () => void;
30
+ }>;
31
+ /** Internal: projections that capture composition must be restarted when it changes. */
32
+ export declare const readsComposition: (scope: PluginScope) => boolean;
33
+ /**
34
+ * Runtime only: records which module a scope belongs to and the plugins composed with it. Not
35
+ * exported from the package.
36
+ */
37
+ export declare function assignScopeModule(scope: PluginScope, module: ScopeModule, plugins?: readonly ComposedPlugin[], composed?: readonly ComposedModule[], translation?: ScopeTranslation, lifecycle?: LifecycleState): void;
8
38
  /**
9
39
  * The module that owns a runtime-issued scope. Integrations derive ownership and layer from it,
10
40
  * so a plugin cannot register on behalf of the application or another plugin.
11
41
  */
12
42
  export declare function scopeModule(scope: PluginScope): ScopeModule;
43
+ /**
44
+ * The plugins composed with the runtime that issued a scope, in install order and without the
45
+ * application, for integrations that list or link plugins, such as a plugin overview.
46
+ */
47
+ export declare function scopePlugins(scope: PluginScope): readonly ComposedPlugin[];
48
+ /** Every composed module including the app, in install order, with settings and UI declarations. */
49
+ export declare function scopeModules(scope: PluginScope): readonly ComposedModule[];
50
+ /** The host translation for projections built in `setup`; follows language changes. */
51
+ export declare function scopeTranslation(scope: PluginScope): ScopeTranslation;
52
+ /** Runtime status for projections; subscriptions are revoked as soon as this scope closes. */
53
+ export declare function scopeLifecycle(scope: PluginScope): LifecycleState;
13
54
  /** Scoped facade over the host list, never a second action registry. */
14
55
  export declare class PluginScope {
15
56
  private list;
16
57
  private groups;
17
58
  private cleanups;
59
+ private completion?;
60
+ private registrations;
18
61
  private active;
62
+ private closeErrors;
63
+ private closing;
64
+ private slotBindings?;
19
65
  constructor(list: ActionList, groups: Map<string, ActionGroup>);
20
- own(cleanup: () => void): void;
66
+ /** Owned slot access is supplied only by a runtime-issued scope. */
67
+ get slots(): ScopedSlots;
68
+ /** @internal Runtime binding; never a second registration path. */
69
+ bindSlots(slots: ScopedSlots): void;
70
+ /** @internal Invalidate registrations immediately; asynchronous resource cleanup uses own(). */
71
+ onClose(cleanup: () => void): () => void;
72
+ own(cleanup: Cleanup): void;
21
73
  private assertActive;
22
74
  actions: {
23
75
  getGroup: (id: string) => {
@@ -30,5 +82,8 @@ export declare class PluginScope {
30
82
  };
31
83
  };
32
84
  };
33
- dispose(): void;
85
+ /** Prevent new registrations and cancel owned Action runs before asynchronous teardown. */
86
+ close(): void;
87
+ ownsAction(id: string): boolean;
88
+ dispose(): Promise<void>;
34
89
  }
package/dist/scope.js CHANGED
@@ -1,8 +1,25 @@
1
1
  import { ActionGroup } from '@bitakit/core/actions';
2
+ import { cleanupSequence, cleanupFailure } from './lifecycle/cleanup.js';
3
+ const compositionReaders = new WeakSet();
4
+ /** Internal: projections that capture composition must be restarted when it changes. */
5
+ export const readsComposition = (scope) => compositionReaders.has(scope);
2
6
  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) {
7
+ const compositions = new WeakMap();
8
+ const moduleLists = new WeakMap();
9
+ const lifecycles = new WeakMap();
10
+ const translations = new WeakMap();
11
+ /**
12
+ * Runtime only: records which module a scope belongs to and the plugins composed with it. Not
13
+ * exported from the package.
14
+ */
15
+ export function assignScopeModule(scope, module, plugins = [], composed = [], translation, lifecycle) {
5
16
  modules.set(scope, Object.freeze({ ...module }));
17
+ compositions.set(scope, plugins);
18
+ moduleLists.set(scope, composed);
19
+ if (translation)
20
+ translations.set(scope, translation);
21
+ if (lifecycle)
22
+ lifecycles.set(scope, lifecycle);
6
23
  }
7
24
  /**
8
25
  * The module that owns a runtime-issued scope. Integrations derive ownership and layer from it,
@@ -14,16 +31,98 @@ export function scopeModule(scope) {
14
31
  throw new Error('Unknown plugin scope. Use the scope passed to setup.');
15
32
  return module;
16
33
  }
34
+ /**
35
+ * The plugins composed with the runtime that issued a scope, in install order and without the
36
+ * application, for integrations that list or link plugins, such as a plugin overview.
37
+ */
38
+ export function scopePlugins(scope) {
39
+ scopeModule(scope);
40
+ compositionReaders.add(scope);
41
+ return compositions.get(scope) ?? [];
42
+ }
43
+ /** Every composed module including the app, in install order, with settings and UI declarations. */
44
+ export function scopeModules(scope) {
45
+ scopeModule(scope);
46
+ compositionReaders.add(scope);
47
+ return moduleLists.get(scope) ?? [];
48
+ }
49
+ const untranslated = Object.freeze({
50
+ translate: (key) => key,
51
+ text: (key, fallback) => (key === undefined ? fallback : fallback),
52
+ subscribe: () => () => { },
53
+ });
54
+ /** The host translation for projections built in `setup`; follows language changes. */
55
+ export function scopeTranslation(scope) {
56
+ scopeModule(scope);
57
+ return translations.get(scope) ?? untranslated;
58
+ }
59
+ /** Runtime status for projections; subscriptions are revoked as soon as this scope closes. */
60
+ export function scopeLifecycle(scope) {
61
+ scopeModule(scope);
62
+ const lifecycle = lifecycles.get(scope);
63
+ if (!lifecycle)
64
+ throw new Error('Lifecycle state requires a runtime-issued scope.');
65
+ const owned = (listen) => {
66
+ let closed = false;
67
+ let off = () => { };
68
+ const release = scope.onClose(() => {
69
+ closed = true;
70
+ off();
71
+ });
72
+ try {
73
+ off = listen();
74
+ }
75
+ catch (error) {
76
+ release();
77
+ throw error;
78
+ }
79
+ if (closed)
80
+ off();
81
+ return () => {
82
+ off();
83
+ release();
84
+ };
85
+ };
86
+ return {
87
+ get: lifecycle.get,
88
+ subscribe: (listener) => owned(() => lifecycle.subscribe(listener)),
89
+ watch: (listener) => owned(() => lifecycle.watch(listener)),
90
+ };
91
+ }
17
92
  /** Scoped facade over the host list, never a second action registry. */
18
93
  export class PluginScope {
19
94
  list;
20
95
  groups;
21
96
  cleanups = [];
97
+ completion;
98
+ registrations = new Map();
22
99
  active = true;
100
+ closeErrors = [];
101
+ closing = new Set();
102
+ slotBindings;
23
103
  constructor(list, groups) {
24
104
  this.list = list;
25
105
  this.groups = groups;
26
106
  }
107
+ /** Owned slot access is supplied only by a runtime-issued scope. */
108
+ get slots() {
109
+ this.assertActive();
110
+ if (!this.slotBindings)
111
+ throw new Error('Slots require a runtime-issued plugin scope.');
112
+ return this.slotBindings;
113
+ }
114
+ /** @internal Runtime binding; never a second registration path. */
115
+ bindSlots(slots) {
116
+ this.slotBindings = slots;
117
+ }
118
+ /** @internal Invalidate registrations immediately; asynchronous resource cleanup uses own(). */
119
+ onClose(cleanup) {
120
+ this.assertActive();
121
+ this.closing.add(cleanup);
122
+ return () => {
123
+ this.closing.delete(cleanup);
124
+ };
125
+ }
27
126
  own(cleanup) {
28
127
  this.assertActive();
29
128
  this.cleanups.push(cleanup);
@@ -52,27 +151,50 @@ export class PluginScope {
52
151
  const handle = this.list.register(action, {
53
152
  groups: [...(action.groups ?? []), group],
54
153
  });
154
+ this.registrations.set(action.id, handle.unregister);
55
155
  this.own(handle.unregister);
56
156
  return { dispose: handle.unregister, update: handle.update };
57
157
  },
58
158
  };
59
159
  },
60
160
  };
61
- dispose() {
62
- if (!this.active)
63
- return;
161
+ /** Prevent new registrations and cancel owned Action runs before asynchronous teardown. */
162
+ close() {
64
163
  this.active = false;
65
- const errors = [];
66
- for (const cleanup of this.cleanups.reverse()) {
164
+ for (const cleanup of this.closing) {
67
165
  try {
68
166
  cleanup();
69
167
  }
70
168
  catch (error) {
71
- errors.push(error);
169
+ this.closeErrors.push(error);
72
170
  }
73
171
  }
74
- this.cleanups = [];
75
- if (errors.length)
76
- throw new AggregateError(errors, 'Plugin cleanup failed.');
172
+ this.closing.clear();
173
+ for (const unregister of this.registrations.values()) {
174
+ try {
175
+ unregister();
176
+ }
177
+ catch (error) {
178
+ this.closeErrors.push(error);
179
+ }
180
+ }
181
+ this.registrations.clear();
182
+ }
183
+ ownsAction(id) {
184
+ return this.registrations.has(id);
185
+ }
186
+ dispose() {
187
+ if (this.completion)
188
+ return this.completion;
189
+ let resolve;
190
+ let reject;
191
+ this.completion = new Promise((done, fail) => {
192
+ resolve = done;
193
+ reject = fail;
194
+ });
195
+ this.close();
196
+ const tasks = this.cleanups.splice(0).reverse();
197
+ void cleanupSequence(tasks, (errors) => cleanupFailure([...this.closeErrors, ...errors], 'Plugin cleanup failed.')).then(resolve, reject);
198
+ return this.completion;
77
199
  }
78
200
  }
@@ -1,19 +1,38 @@
1
- import type { ServiceDefinition, Services } from './definitions.js';
1
+ import type { ServiceDefinition } from './definitions.js';
2
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;
3
+ declare const serviceName: unique symbol;
4
+ /**
5
+ * A stable runtime name carrying a TypeScript contract. Share it between the plugin that
6
+ * provides a service and the plugins that use it. The phantom is contravariant, so a richer
7
+ * instance may satisfy a narrower contract. Created as `serviceKey<T, 'name'>('name')`, the
8
+ * key also carries its literal name, which types `services.name` in the generated maps.
9
+ */
10
+ export type ServiceKey<T, Name extends string = string> = Name & {
11
+ readonly [serviceType]: (value: T) => void;
12
+ readonly [serviceName]?: Name;
6
13
  };
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, const Name extends string>(key: ServiceKey<T>, definition: Omit<ServiceDefinition<NoInfer<T>>, 'id'> & {
11
- exposeAs: Name;
12
- }): ServiceDefinition<T> & {
13
- id: ServiceKey<T>;
14
- exposeAs: Name;
14
+ /** The literal name a key carries, or `string` for keys created without one. */
15
+ export type ContractName<Key> = Key extends {
16
+ readonly [serviceName]?: infer Name extends string;
17
+ } ? Name : string;
18
+ /**
19
+ * Low-level key creation; `defineContract(name).of<T>()` is the documented form. Pass both type
20
+ * arguments (`serviceKey<T, 'name'>('name')`) to keep the literal name.
21
+ */
22
+ export declare function serviceKey<T, const Name extends string = string>(id: Name): ServiceKey<T, Name>;
23
+ /** A named contract waiting for its type: `defineContract('auth').of<AuthService>()`. */
24
+ export type ContractBuilder<Name extends string> = {
25
+ /** The typed key. Its literal name types `services.<name>` for the service that `provides` it. */
26
+ of<T>(): ServiceKey<T, Name>;
15
27
  };
16
- export declare function provideService<T>(key: ServiceKey<T>, definition: Omit<ServiceDefinition<NoInfer<T>>, 'id'>): ServiceDefinition<T> & {
17
- id: ServiceKey<T>;
28
+ /**
29
+ * Defines a service contract shared by the plugin that provides it and the plugins that use it.
30
+ * The name is written once and stays literal: `defineContract('auth').of<AuthService>()`.
31
+ */
32
+ export declare function defineContract<const Name extends string>(id: Name): ContractBuilder<Name>;
33
+ /** Reads a contract from a services object (tree or flat); throws a clear error when absent. */
34
+ export declare function getService<T>(services: object, key: ServiceKey<T>): T;
35
+ export type ProvidedService<T> = ServiceDefinition<T> & {
36
+ readonly provides: ServiceKey<T>;
18
37
  };
19
38
  export {};
@@ -1,13 +1,29 @@
1
+ /**
2
+ * Low-level key creation; `defineContract(name).of<T>()` is the documented form. Pass both type
3
+ * arguments (`serviceKey<T, 'name'>('name')`) to keep the literal name.
4
+ */
1
5
  export function serviceKey(id) {
2
6
  if (!id.trim())
3
7
  throw new Error('A service key must not be empty.');
4
8
  return id;
5
9
  }
10
+ /**
11
+ * Defines a service contract shared by the plugin that provides it and the plugins that use it.
12
+ * The name is written once and stays literal: `defineContract('auth').of<AuthService>()`.
13
+ */
14
+ export function defineContract(id) {
15
+ const key = serviceKey(id);
16
+ return Object.freeze({ of: () => key });
17
+ }
18
+ /** Reads a contract from a services object (tree or flat); throws a clear error when absent. */
6
19
  export function getService(services, key) {
7
- if (!Object.hasOwn(services, key))
20
+ let current = services;
21
+ for (const segment of key.split('.')) {
22
+ if (!current || typeof current !== 'object' || !(segment in current))
23
+ throw new Error(`Missing service "${key}".`);
24
+ current = current[segment];
25
+ }
26
+ if (current === undefined)
8
27
  throw new Error(`Missing service "${key}".`);
9
- return services[key];
10
- }
11
- export function provideService(key, definition) {
12
- return { ...definition, id: key };
28
+ return current;
13
29
  }
@@ -0,0 +1,39 @@
1
+ import { BitaKitStartupError } from './startup-error.js';
2
+ import type { Services } from './definitions.js';
3
+ /** Who asked for a service. Only used to explain failures. */
4
+ export type ServiceRequester = {
5
+ label: string;
6
+ source?: string;
7
+ };
8
+ export type ServiceEntry = {
9
+ id: string;
10
+ aliases: readonly string[];
11
+ plugin: string;
12
+ };
13
+ /**
14
+ * Service names as contributions see them: IDs such as `todos.items` form the tree
15
+ * `services.todos.items`; aliases (`exposeAs`, contracts) are extra paths onto the same
16
+ * instance. Resolution never creates instances; the container stays the only owner.
17
+ */
18
+ export declare class ServiceNames {
19
+ private readonly appId;
20
+ private readonly ids;
21
+ private readonly root;
22
+ constructor(entries: readonly ServiceEntry[], appId: string);
23
+ /** Replace declarations while preserving live namespace proxies held by existing services. */
24
+ replace(entries: readonly ServiceEntry[]): void;
25
+ private add;
26
+ private label;
27
+ /** The container key that `name` refers to; unknown names are returned as-is. */
28
+ key(name: string): string;
29
+ known(name: string): boolean;
30
+ /** Every known name, IDs first. */
31
+ names(): string[];
32
+ /**
33
+ * The live tree over a container. Reads resolve at access time, so the tree can be handed to
34
+ * services that are still under construction. Unknown names throw a named error.
35
+ */
36
+ tree(instances: Readonly<Record<string, unknown>>, notReady?: () => boolean): Services;
37
+ /** Explains a missing requirement of `module` with the closest usable names. */
38
+ missing(module: string, name: string, requester: ServiceRequester, exists: (key: string) => boolean): BitaKitStartupError;
39
+ }
@@ -0,0 +1,175 @@
1
+ import { BitaKitStartupError } from './startup-error.js';
2
+ import { BitaKitServiceError } from './app/service-error.js';
3
+ /**
4
+ * Service names as contributions see them: IDs such as `todos.items` form the tree
5
+ * `services.todos.items`; aliases (`exposeAs`, contracts) are extra paths onto the same
6
+ * instance. Resolution never creates instances; the container stays the only owner.
7
+ */
8
+ export class ServiceNames {
9
+ appId;
10
+ ids = new Map();
11
+ root = { children: new Map() };
12
+ constructor(entries, appId) {
13
+ this.appId = appId;
14
+ for (const entry of entries) {
15
+ this.add(entry.id, entry.id, entry.plugin);
16
+ for (const alias of entry.aliases)
17
+ this.add(alias, entry.id, entry.plugin);
18
+ }
19
+ }
20
+ /** Replace declarations while preserving live namespace proxies held by existing services. */
21
+ replace(entries) {
22
+ const next = new ServiceNames(entries, this.appId);
23
+ const sync = (target, source) => {
24
+ target.leaf = source.leaf;
25
+ for (const [name, child] of target.children) {
26
+ const replacement = source.children.get(name);
27
+ if (replacement)
28
+ sync(child, replacement);
29
+ else {
30
+ sync(child, { children: new Map() });
31
+ target.children.delete(name);
32
+ }
33
+ }
34
+ for (const [name, child] of source.children)
35
+ if (!target.children.has(name))
36
+ target.children.set(name, child);
37
+ };
38
+ sync(this.root, next.root);
39
+ this.ids.clear();
40
+ for (const [name, id] of next.ids)
41
+ this.ids.set(name, id);
42
+ }
43
+ add(name, id, plugin) {
44
+ const segments = name.split('.');
45
+ if (segments.some((segment) => !segment || ['then', 'toJSON', '__proto__', 'constructor'].includes(segment)))
46
+ throw new BitaKitStartupError(`Service name "${name}" in ${this.label(plugin)} is empty or uses a reserved segment.`, plugin, { app: plugin === this.appId });
47
+ const existing = this.ids.get(name);
48
+ if (existing !== undefined && existing !== id)
49
+ throw new BitaKitStartupError(`Two services are named "${name}" (${existing} and ${id}). Rename one of the files, or set exposeAs on one of them.`, plugin, { app: plugin === this.appId });
50
+ this.ids.set(name, id);
51
+ let node = this.root;
52
+ for (const [index, segment] of segments.entries()) {
53
+ let child = node.children.get(segment);
54
+ if (!child)
55
+ node.children.set(segment, (child = { children: new Map() }));
56
+ const last = index === segments.length - 1;
57
+ if (last) {
58
+ if (child.children.size)
59
+ throw new BitaKitStartupError(`Service name "${name}" in ${this.label(plugin)} is already used as a namespace by ${[...child.children.keys()].map((key) => `${name}.${key}`).join(', ')}. A plugin cannot provide or expose a service under its own ID; rename the plugin folder (for example "${name}-provider") or choose another alias.`, plugin, { app: plugin === this.appId });
60
+ child.leaf = id;
61
+ }
62
+ else if (child.leaf !== undefined)
63
+ throw new BitaKitStartupError(`Service name "${name}" in ${this.label(plugin)} is nested under "${segments.slice(0, index + 1).join('.')}", which is already a service.`, plugin, { app: plugin === this.appId });
64
+ node = child;
65
+ }
66
+ }
67
+ label(plugin) {
68
+ return plugin === this.appId ? 'the app' : `plugin "${plugin}"`;
69
+ }
70
+ /** The container key that `name` refers to; unknown names are returned as-is. */
71
+ key(name) {
72
+ return this.ids.get(name) ?? name;
73
+ }
74
+ known(name) {
75
+ return this.ids.has(name);
76
+ }
77
+ /** Every known name, IDs first. */
78
+ names() {
79
+ return [...this.ids.keys()];
80
+ }
81
+ /**
82
+ * The live tree over a container. Reads resolve at access time, so the tree can be handed to
83
+ * services that are still under construction. Unknown names throw a named error.
84
+ */
85
+ tree(instances, notReady) {
86
+ const cache = new WeakMap();
87
+ const project = (node, prefix) => {
88
+ const cached = cache.get(node);
89
+ if (cached)
90
+ return cached;
91
+ const target = Object.create(null);
92
+ const proxy = new Proxy(target, {
93
+ get: (_target, name) => {
94
+ if (typeof name !== 'string' || name === 'then' || name === 'toJSON')
95
+ return undefined;
96
+ const path = prefix ? `${prefix}.${name}` : name;
97
+ const child = node.children.get(name);
98
+ if (!child) {
99
+ throw new BitaKitServiceError(path, notReady?.() ? 'not-ready' : 'unregistered');
100
+ }
101
+ if (child.leaf !== undefined) {
102
+ if (!Object.hasOwn(instances, child.leaf)) {
103
+ throw new BitaKitServiceError(path, notReady?.() ? 'not-ready' : 'missing');
104
+ }
105
+ return instances[child.leaf];
106
+ }
107
+ return project(child, path);
108
+ },
109
+ has: (_target, name) => typeof name === 'string' && node.children.has(name),
110
+ ownKeys: () => [...node.children.keys()],
111
+ getOwnPropertyDescriptor: (_target, name) => typeof name === 'string' && node.children.has(name)
112
+ ? { enumerable: true, configurable: true, writable: false, value: proxy[name] }
113
+ : undefined,
114
+ set: () => false,
115
+ defineProperty: () => false,
116
+ deleteProperty: () => false,
117
+ });
118
+ cache.set(node, proxy);
119
+ return proxy;
120
+ };
121
+ return project(this.root, '');
122
+ }
123
+ /** Explains a missing requirement of `module` with the closest usable names. */
124
+ missing(module, name, requester, exists) {
125
+ const available = this.names().filter((item) => exists(this.key(item)));
126
+ const suggestions = suggest(name, available);
127
+ const lines = [
128
+ `${requester.label} requires service "${name}", but no service has that name.`,
129
+ ...(suggestions.length
130
+ ? [`Did you mean ${suggestions.map((item) => `"${item}"`).join(' or ')}?`]
131
+ : []),
132
+ available.length
133
+ ? `Available services: ${list(available)}.`
134
+ : 'No services are available. Add one under services/ or install the plugin that provides it.',
135
+ ...(requester.source ? [`Source: ${requester.source}`] : []),
136
+ ];
137
+ return new BitaKitStartupError(lines.join('\n'), module, {
138
+ source: requester.source,
139
+ app: module === this.appId,
140
+ });
141
+ }
142
+ }
143
+ function list(names) {
144
+ return names.length > 12 ? `${names.slice(0, 12).join(', ')}, …` : names.join(', ');
145
+ }
146
+ /** Close names by edit distance, plus names ending in the requested local name. */
147
+ function suggest(name, available) {
148
+ const scored = new Map();
149
+ const lower = name.toLowerCase();
150
+ for (const candidate of available) {
151
+ if (candidate === name)
152
+ continue;
153
+ if (candidate.toLowerCase() === lower)
154
+ scored.set(candidate, 0);
155
+ if (candidate.endsWith(`.${name}`))
156
+ scored.set(candidate, Math.min(scored.get(candidate) ?? 1, 1));
157
+ const distance = editDistance(lower, candidate.toLowerCase());
158
+ if (distance <= Math.max(1, Math.floor(name.length / 3)))
159
+ scored.set(candidate, Math.min(scored.get(candidate) ?? distance, distance));
160
+ }
161
+ return [...scored]
162
+ .sort((a, b) => a[1] - b[1])
163
+ .slice(0, 3)
164
+ .map(([candidate]) => candidate);
165
+ }
166
+ function editDistance(a, b) {
167
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
168
+ for (let i = 1; i <= a.length; i++) {
169
+ const current = [i];
170
+ for (let j = 1; j <= b.length; j++)
171
+ current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
172
+ previous = current;
173
+ }
174
+ return previous[b.length];
175
+ }
@@ -1,7 +1,26 @@
1
- import type { Events } from './events/types.js';
1
+ import { EventService } from './events/service.js';
2
2
  import { type ConfigContext } from './config-service.js';
3
- import type { ServiceDefinition, Services } from './definitions.js';
4
- export declare function createServices(definitions: readonly ServiceDefinition<any>[], provided?: Partial<Services>, configFor?: (definition: ServiceDefinition<any>) => ConfigContext, decorate?: (id: string, instance: any, active: () => boolean) => any, events?: Events): {
5
- services: Services;
6
- dispose: () => void;
3
+ import type { ServiceDefinition } from './definitions.js';
4
+ import type { SettingsAccess } from './settings/access.js';
5
+ import type { ServiceNames } from './service-names.js';
6
+ import type { LifecyclePhase } from './lifecycle/state.js';
7
+ export type ServiceScope = {
8
+ names: ServiceNames;
9
+ appId: string;
10
+ moduleOf(definition: ServiceDefinition<any>): string;
11
+ sourceOf(definition: ServiceDefinition<any>): string | undefined;
12
+ };
13
+ export type Observable = {
14
+ subscribe(listener: () => void): () => void;
15
+ };
16
+ /** Allocates ownership before initialization, so partial factory failures can be fully stopped. */
17
+ export declare function createServices(definitions: readonly ServiceDefinition<any>[], provided?: Readonly<Record<string, unknown>>, configFor?: (definition: ServiceDefinition<any>) => ConfigContext, decorate?: (id: string, instance: any, active: () => boolean) => any, events?: EventService, scope?: ServiceScope, idOf?: (definition: ServiceDefinition<any>) => string, settings?: SettingsAccess, onPhase?: (id: string, phase: LifecyclePhase, error?: unknown) => void): {
18
+ services: Readonly<Record<string, unknown>>;
19
+ observed: Set<Observable>;
20
+ initialize: () => void;
21
+ install: (entries: readonly ServiceDefinition<any>[]) => void;
22
+ disposeModules: (modules: ReadonlySet<string>) => Promise<void>;
23
+ readonly hasStartHooks: boolean;
24
+ start: (signal: AbortSignal, modules?: ReadonlySet<string>) => Promise<void>;
25
+ dispose: () => Promise<void>;
7
26
  };