@bitakit/core 0.2.8 → 0.2.9

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.
package/AGENTS.md CHANGED
@@ -45,6 +45,28 @@ one plugin under Node (no browser); `plugin.execute(id, input)` resolves to the
45
45
  - Only the declaring plugin emits its events; others listen.
46
46
  - `enabled`, `visible` and interceptors are client rules; authorize on the server.
47
47
 
48
+ ## Identifier compatibility and integration contexts
49
+
50
+ Registered spellings and exact matches remain authoritative, including existing case-only
51
+ names. Service/contract lookup, declared events, Actions, plugin references and dependencies
52
+ also accept an unambiguous case-insensitive match. An ambiguous non-exact reference throws;
53
+ use an existing exact spelling. Generated map keys and namespace property types preserve
54
+ original spellings. String-based Action/event/service hooks resolve mixed case with payload
55
+ checking. Undeclared event strings retain their existing open-bus semantics; declare events
56
+ for a typed, resolvable public name. Filesystem paths, URLs and service method names are unchanged.
57
+
58
+ Optional integrations reuse `expandContributions` for folder/dotted/record declarations.
59
+ `ContributionInstallerContext` describes the full contributing owner context (config, events and
60
+ settings) supplied by the runtime. Installer callbacks retain `ContributionContext`, where these
61
+ fields are optional for legacy direct invocations. Installed cleanup
62
+ belongs to the contributor. Do not introduce a parallel context, registry or event bus.
63
+
64
+ Service interceptors receive `callId` and epoch `startedAt`, plus `durationMs` on completion or
65
+ failure (optional in the types for legacy manually constructed calls). Async settlement is observed without replacing the original promise or awaiting the
66
+ observer. These IDs are local to one runtime. Trusted observers may see arguments/results;
67
+ public inventory does not. Self-calls still bypass the service proxy; a producer that promises
68
+ observable execution must enter its public method through the service container.
69
+
48
70
  ## Plugin identity and inspection
49
71
 
50
72
  Discovery records provenance on definitions. `withPluginOrigin(plugin, record)` is the trusted
@@ -1,7 +1,8 @@
1
+ import type { CheckedName } from '../names.js';
1
2
  import { ActionStatus } from './state.js';
2
3
  import { type RegistrationOptions } from './groups.js';
3
4
  import { Action } from './action.js';
4
- import type { ActionDefinition, ActionSnapshot, ActionPatch, ActionRegistration, ActionId, ActionInput, ActionResult, ExecutionResult } from './types.js';
5
+ import type { ActionDefinition, ActionSnapshot, ActionPatch, ActionRegistration, KnownActionId, ActionInput, ActionResult, ExecutionResult } from './types.js';
5
6
  type State = {
6
7
  actions: Readonly<Record<string, ActionSnapshot>>;
7
8
  };
@@ -61,7 +62,7 @@ export declare function createActionList(initialActions?: readonly (ActionDefini
61
62
  attach(id: string, group: import("./groups.js").ActionGroup): () => void;
62
63
  update: (id: string, patch: ActionPatch) => boolean;
63
64
  /** Known IDs from ActionMap type their input and result; other IDs stay untyped. */
64
- execute: <Id extends ActionId>(id: Id, input?: ActionInput<Id>) => Promise<ExecutionResult<ActionResult<Id>>>;
65
+ execute: <Id extends string>(id: Id & CheckedName<Id, KnownActionId>, input?: ActionInput<Id>) => Promise<ExecutionResult<ActionResult<Id>>>;
65
66
  dispose: () => void;
66
67
  mount: (navigate?: (href: string) => void) => () => void;
67
68
  /** Read-only subscription surface; mutation stays in the methods above. */
@@ -1,3 +1,4 @@
1
+ import { resolveName } from '../name-resolution.js';
1
2
  import { ActionStatus } from './state.js';
2
3
  import { freezeGroups } from './groups.js';
3
4
  import { ExecutionLifecycle } from './interceptors.js';
@@ -107,10 +108,12 @@ export function createActionList(initialActions = [], options = {}) {
107
108
  publish(id);
108
109
  }
109
110
  const get = (id) => {
111
+ id = resolveName(id, Object.keys(definitions));
110
112
  const { actions } = store.getState();
111
113
  return Object.hasOwn(actions, id) ? actions[id] : undefined;
112
114
  };
113
115
  function resolve(id, input) {
116
+ id = resolveName(id, Object.keys(definitions));
114
117
  const action = source(id);
115
118
  if (!action)
116
119
  return undefined;
@@ -133,6 +136,7 @@ export function createActionList(initialActions = [], options = {}) {
133
136
  return Object.freeze({ ...resolved, ...options.project?.(resolved) });
134
137
  }
135
138
  function update(id, patch) {
139
+ id = resolveName(id, Object.keys(definitions));
136
140
  const current = source(id);
137
141
  if (!current || disposed)
138
142
  return false;
@@ -292,6 +296,7 @@ export function createActionList(initialActions = [], options = {}) {
292
296
  register,
293
297
  /** Attach an existing action without duplicating it; cleanup owns only this placement. */
294
298
  attach(id, group) {
299
+ id = resolveName(id, Object.keys(definitions));
295
300
  const action = get(id);
296
301
  const owner = owners.get(id);
297
302
  if (!action || !owner)
@@ -1,8 +1,10 @@
1
+ import { resolveName } from '../name-resolution.js';
1
2
  export function freezeDependencies(ids) {
2
3
  return ids ? Object.freeze([...new Set(ids)]) : undefined;
3
4
  }
4
5
  /** Missing nodes and cycles fail closed. No dependency handler is executed. */
5
6
  export function dependencyEnabled(id, actions, enabled, visiting = new Set(), cache = new Map()) {
7
+ id = resolveName(id, Object.keys(actions));
6
8
  if (cache.has(id))
7
9
  return cache.get(id);
8
10
  if (!Object.hasOwn(actions, id) || visiting.has(id))
@@ -20,7 +22,8 @@ export function affectedActions(actions, changed) {
20
22
  const affected = new Set([changed]);
21
23
  const dependents = new Map();
22
24
  for (const action of Object.values(actions)) {
23
- for (const id of action.dependsOn ?? []) {
25
+ for (const reference of action.dependsOn ?? []) {
26
+ const id = resolveName(reference, Object.keys(actions));
24
27
  const items = dependents.get(id) ?? [];
25
28
  items.push(action.id);
26
29
  dependents.set(id, items);
@@ -10,6 +10,7 @@ const keyOf = (action, input) => action.concurrency !== 'per-input'
10
10
  : String(input);
11
11
  export function createExecutor(setPending, owners, environment, get, resolve, update, lifecycle, running) {
12
12
  return async function execute(id, input) {
13
+ id = get(id)?.id ?? id;
13
14
  const owner = owners.get(id);
14
15
  const controller = new AbortController();
15
16
  const context = Object.freeze({
@@ -1,3 +1,4 @@
1
+ import type { NamedValue } from '../name-resolution.js';
1
2
  import type { ActionStatus } from './state.js';
2
3
  import type { PresentationType } from '../presentation.js';
3
4
  import type { RegistrationOptions } from './groups.js';
@@ -105,7 +106,11 @@ export type ActionId = ActionMapOptions extends {
105
106
  } ? KnownActionId : KnownActionId | (string & {});
106
107
  export type ActionInput<Id extends string = string> = Id extends KnownActionId ? ActionMap[Id] extends {
107
108
  input: infer Input;
108
- } ? Input : unknown : unknown;
109
+ } ? Input : unknown : NamedValue<ActionMap, Id> extends {
110
+ input: infer Input;
111
+ } ? Input : unknown;
109
112
  export type ActionResult<Id extends string = string> = Id extends KnownActionId ? ActionMap[Id] extends {
110
113
  result: infer Result;
111
- } ? Result : unknown : unknown;
114
+ } ? Result : unknown : NamedValue<ActionMap, Id> extends {
115
+ result: infer Result;
116
+ } ? Result : unknown;
@@ -1,3 +1,4 @@
1
+ import { namedRecord } from '../name-resolution.js';
1
2
  import { BitaKitServiceError } from './service-error.js';
2
3
  import { createActionAccess } from './action-access.js';
3
4
  /** Projects the runtime onto the app facade. Nothing is copied; every read is live. */
@@ -33,10 +34,10 @@ export function createBitaKitApp(runtime) {
33
34
  events: Object.freeze({ on: runtime.events.on.bind(runtime.events) }),
34
35
  actions: createActionAccess(runtime.actions),
35
36
  get config() {
36
- return Object.freeze(Object.fromEntries(runtime.modules.map((module) => [
37
+ return Object.freeze(namedRecord(Object.fromEntries(runtime.modules.map((module) => [
37
38
  module.id,
38
39
  runtime.configuration.plugin(module.id).snapshot(),
39
- ])));
40
+ ]))));
40
41
  },
41
42
  services,
42
43
  settings: runtime.settingsAccess,
@@ -1,8 +1,10 @@
1
+ import { resolveName } from '../name-resolution.js';
1
2
  import { createActionReference } from '../actions/reference.js';
2
3
  /** Projects dotted IDs onto stable handles; enumeration reads only current public registrations. */
3
4
  export function createActionAccess(list) {
4
5
  const references = new Map();
5
6
  const at = (path) => {
7
+ path = resolveName(path, Object.keys(list.getState().actions).flatMap((id) => id.split('.').map((_, index, parts) => parts.slice(0, index + 1).join('.'))));
6
8
  const cached = references.get(path);
7
9
  if (cached)
8
10
  return cached;
@@ -1,3 +1,4 @@
1
+ import { resolveName } from './name-resolution.js';
1
2
  const configDefinition = Symbol.for('bitakit.core.config');
2
3
  export function defineConfig(value) {
3
4
  if (!value || typeof value !== 'object' || (!('defaults' in value) && !('schema' in value)))
@@ -71,13 +72,20 @@ export class ConfigScope {
71
72
  export class ConfigService {
72
73
  modules = new Map();
73
74
  constructor(modules, overrides = {}) {
75
+ const resolvedOverrides = Object.create(null);
76
+ for (const [id, value] of Object.entries(overrides)) {
77
+ const resolved = resolveName(id, modules.map((module) => module.id));
78
+ if (Object.hasOwn(resolvedOverrides, resolved))
79
+ throw new Error(`Duplicate config override for "${resolved}".`);
80
+ resolvedOverrides[resolved] = value;
81
+ }
74
82
  for (const module of modules) {
75
83
  if (this.modules.has(module.id))
76
84
  throw new Error(`Duplicate config module "${module.id}".`);
77
- this.modules.set(module.id, new ConfigScope(resolve(module.config ?? {}, overrides[module.id])));
85
+ this.modules.set(module.id, new ConfigScope(resolve(module.config ?? {}, resolvedOverrides[module.id])));
78
86
  }
79
87
  for (const id of Object.keys(overrides))
80
- if (!this.modules.has(id))
88
+ if (!this.modules.has(resolveName(id, this.modules.keys())))
81
89
  throw new Error(`configOverrides names "${id}", but no plugin with that ID is enabled. Known: ${[...this.modules.keys()].join(', ')}.`);
82
90
  }
83
91
  /** Adopt prevalidated module scopes without replacing the public configuration service. */
@@ -87,7 +95,7 @@ export class ConfigService {
87
95
  this.modules.set(id, scope);
88
96
  }
89
97
  plugin(id) {
90
- const scope = this.modules.get(id);
98
+ const scope = this.modules.get(resolveName(id, this.modules.keys()));
91
99
  if (!scope)
92
100
  throw new Error(`Unknown config module "${id}".`);
93
101
  return scope;
@@ -1,3 +1,4 @@
1
+ import { resolveName } from './name-resolution.js';
1
2
  import { preservePluginOrigin } from './inspection/plugin-origin.js';
2
3
  const providersOf = (plugin) => plugin.ui?.providers ?? [];
3
4
  /** Undefined inherits. An explicit list replaces that domain, including an empty list. */
@@ -19,7 +20,7 @@ export function resolveBitaKitConfig(discovered, overrides = {}) {
19
20
  .filter((plugin) => !selectedPlugins.some((selected) => selected.id === plugin.id))
20
21
  .map((plugin) => plugin.id));
21
22
  if (config.configOverrides)
22
- config.configOverrides = Object.fromEntries(Object.entries(config.configOverrides).filter(([id]) => !removed.has(id)));
23
+ config.configOverrides = Object.fromEntries(Object.entries(config.configOverrides).filter(([id]) => !removed.has(resolveName(id, (discovered.plugins ?? []).map((plugin) => plugin.id)))));
23
24
  const pluginIds = new Set();
24
25
  for (const plugin of config.plugins ?? []) {
25
26
  if (!plugin.id || pluginIds.has(plugin.id))
@@ -35,7 +36,7 @@ export function resolveBitaKitConfig(discovered, overrides = {}) {
35
36
  if (!provider.id || seen.has(provider.id))
36
37
  throw new Error(`Invalid or duplicate provider "${provider.id}".`);
37
38
  for (const id of provider.requires ?? []) {
38
- if (!seen.has(id))
39
+ if (!seen.has(resolveName(id, providers.map((provider) => provider.id))))
39
40
  throw new Error(`Provider "${provider.id}" requires "${id}" before it.`);
40
41
  }
41
42
  seen.add(provider.id);
package/dist/core.d.ts CHANGED
@@ -3,7 +3,7 @@ export type * from './definitions.js';
3
3
  export { defineEvents, event, isEventsDefinition } from './events/define.js';
4
4
  export type { EventsDefinition, EventSpec, EventsOf, CancelableOf } from './events/define.js';
5
5
  export type * from './events/types.js';
6
- export type { GeneratedName } from './names.js';
6
+ export type { GeneratedName, CheckedName } from './names.js';
7
7
  export { EventService } from './events/service.js';
8
8
  export { defineSettings, setting, isSettingsDefinition, isSettingSpec, parseSetting, } from './settings/define.js';
9
9
  export type { SettingSpec, SettingScope, SettingControl, SettingOption, SettingsDefinition, SettingsSectionOptions, SettingsMap, SettingKey, SettingValue, SettingsOf, } from './settings/define.js';
@@ -49,3 +49,4 @@ export { configureAuthPaths, resolveAuthReturnTo, authSignInHref, type AuthPaths
49
49
  export type { PluginUpdateResult, PluginChangeResult, PluginDependentOptions, PluginChangeOptions, PluginToggleRequest, PluginReplacementRequest, PluginChangePreview, PluginChangeReason, } from './lifecycle/reconcile.js';
50
50
  export { createInventory, inspectRuntime, observeRuntimeInventory, inventoryMetadata, } from './inspection/inventory.js';
51
51
  export type { RuntimeInventory, InventoryPlugin, InventoryDeclaration, InventoryMetadata, InventoryKind, InventoryLive, } from './inspection/inventory.js';
52
+ export { resolveName, namedRecord, type NameKey, type NamedValue } from './name-resolution.js';
package/dist/core.js CHANGED
@@ -32,3 +32,4 @@ export { SlotError } from './slots/runtime.js';
32
32
  export { selectSingle, candidateNames } from './slots/select.js';
33
33
  export { configureAuthPaths, resolveAuthReturnTo, authSignInHref, } from './auth-navigation.js';
34
34
  export { createInventory, inspectRuntime, observeRuntimeInventory, inventoryMetadata, } from './inspection/inventory.js';
35
+ export { resolveName, namedRecord } from './name-resolution.js';
@@ -289,7 +289,13 @@ export type ContributionContext = {
289
289
  module: string;
290
290
  app: boolean;
291
291
  services: Services;
292
+ /** Context and event ownership of the contributing plugin, not the installer. */
293
+ config?: ConfigContext;
294
+ events?: Events;
295
+ settings?: SettingsAccess;
292
296
  };
297
+ /** Runtime installers always receive the full owner context; legacy manual contexts remain valid. */
298
+ export type ContributionInstallerContext = ContributionContext & Pick<ServiceContext, 'config' | 'events' | 'settings'>;
293
299
  export type ContributionInstaller<T = unknown> = (values: readonly T[], context: ContributionContext) => void | Cleanup;
294
300
  export type ContributionInstallers = {
295
301
  readonly [K in keyof ContributionMap]?: ContributionInstaller<ContributionMap[K]>;
@@ -11,6 +11,12 @@ export type DiscoveredFile<T = unknown, P extends string = string> = {
11
11
  source: string;
12
12
  };
13
13
  export declare function discoveredFile<T, const P extends string>(value: T, path: P, source: string): DiscoveredFile<T, P>;
14
+ /** Expands folder/dotted/record contributions for optional integration normalizers. */
15
+ export declare function expandContributions(files: readonly DiscoveredFile[], leaf: (value: any) => boolean, arrays?: boolean, failure?: (message: string, _source: string) => Error): {
16
+ value: any;
17
+ path: string[];
18
+ source: string;
19
+ }[];
14
20
  export declare function discoverActions(files: readonly DiscoveredFile[], moduleId?: string): Contribution[];
15
21
  export declare function discoverServices(files: readonly DiscoveredFile[], moduleId?: string): ServiceDefinition[];
16
22
  /** Slot leaves use the same record/path expansion as Actions and services. Explicit IDs are absolute. */
@@ -11,7 +11,8 @@ import { isSettingsDefinition, } from './settings/define.js';
11
11
  export function discoveredFile(value, path, source) {
12
12
  return { value, path, source };
13
13
  }
14
- function expand(files, leaf, arrays = false, failure = (message, _source) => new Error(message)) {
14
+ /** Expands folder/dotted/record contributions for optional integration normalizers. */
15
+ export function expandContributions(files, leaf, arrays = false, failure = (message, _source) => new Error(message)) {
15
16
  const results = [];
16
17
  const seen = new Map();
17
18
  function visit(value, segments, source) {
@@ -46,7 +47,7 @@ const isActionLike = (value) => isActionSpec(value) ||
46
47
  !('create' in value) &&
47
48
  !('kind' in value));
48
49
  export function discoverActions(files, moduleId = '') {
49
- return expand(files, isActionLike).map(({ value, path, source }) => {
50
+ return expandContributions(files, isActionLike).map(({ value, path, source }) => {
50
51
  const spec = isActionSpec(value) ? value : defineAction(value);
51
52
  const resolved = resolveContribution(spec, [moduleId, ...path].filter(Boolean).join('.'));
52
53
  setContributionPath(resolved, path, source);
@@ -55,7 +56,7 @@ export function discoverActions(files, moduleId = '') {
55
56
  }
56
57
  const isServiceLike = (value) => isServiceDefinition(value) || typeof value === 'function';
57
58
  export function discoverServices(files, moduleId = '') {
58
- return expand(files, isServiceLike).map(({ value, path, source }) => {
59
+ return expandContributions(files, isServiceLike).map(({ value, path, source }) => {
59
60
  const service = isServiceDefinition(value)
60
61
  ? value
61
62
  : defineService(value);
@@ -70,7 +71,7 @@ export function discoverServices(files, moduleId = '') {
70
71
  /** Slot leaves use the same record/path expansion as Actions and services. Explicit IDs are absolute. */
71
72
  export function discoverSlots(files, moduleId = '') {
72
73
  const seen = new Map();
73
- return expand(files, isSlotDefinition, false, (message, source) => new BitaKitStartupError(message, moduleId || 'app', { source, app: !moduleId })).map(({ value, path, source }) => {
74
+ return expandContributions(files, isSlotDefinition, false, (message, source) => new BitaKitStartupError(message, moduleId || 'app', { source, app: !moduleId })).map(({ value, path, source }) => {
74
75
  const id = value.id ?? [moduleId, ...path].filter(Boolean).join('.');
75
76
  if (typeof id !== 'string' || !actionIdPattern.test(id))
76
77
  throw new BitaKitStartupError(`Invalid slot ID "${id}" in ${source}.`, moduleId || 'app', {
@@ -86,7 +87,7 @@ export function discoverSlots(files, moduleId = '') {
86
87
  });
87
88
  }
88
89
  export function discoverInterceptors(files) {
89
- return expand(files, (value) => typeof value === 'function' ||
90
+ return expandContributions(files, (value) => typeof value === 'function' ||
90
91
  (!!value &&
91
92
  typeof value === 'object' &&
92
93
  !Array.isArray(value) &&
@@ -13,6 +13,7 @@ export declare class EventService implements Events {
13
13
  private observers;
14
14
  private declared;
15
15
  private reserved;
16
+ private reservedEvents;
16
17
  constructor(onError?: EventErrorHandler);
17
18
  /** Registers a plugin's `events.ts`; its names live under `<plugin>.`. */
18
19
  declare(plugin: string, definition: EventsDefinition): void;
@@ -20,6 +21,7 @@ export declare class EventService implements Events {
20
21
  undeclare(plugin: string): void;
21
22
  /** The plugin that declared the namespace of an event name, if any. */
22
23
  ownerOf(name: string): string | undefined;
24
+ resolve(name: string): string;
23
25
  isCancelable(name: string): boolean;
24
26
  /** Reserves a runtime-owned namespace and returns its private publishing capability. */
25
27
  reserve(namespace: string): (name: string, data: unknown) => void;
@@ -1,3 +1,4 @@
1
+ import { resolveName } from '../name-resolution.js';
1
2
  /**
2
3
  * One bus per runtime. Delivery is synchronous and ordered; async handlers are awaited only
3
4
  * for error reporting, or fully for cancelable events. Declared namespaces belong to the
@@ -11,6 +12,7 @@ export class EventService {
11
12
  observers = new Set();
12
13
  declared = new Map();
13
14
  reserved = new Set();
15
+ reservedEvents = new Set();
14
16
  constructor(onError = (error, event) => {
15
17
  console.error(`Event handler failed for "${event.type}".`, error);
16
18
  }) {
@@ -31,18 +33,30 @@ export class EventService {
31
33
  if (spec.schema)
32
34
  schemas.set(`${plugin}.${name}`, spec.schema);
33
35
  }
34
- this.declared.set(plugin, { plugin, cancelable, schemas });
36
+ this.declared.set(plugin, {
37
+ plugin,
38
+ names: Object.keys(definition.events).map((name) => `${plugin}.${name}`),
39
+ cancelable,
40
+ schemas,
41
+ });
35
42
  }
36
43
  /** Release a stopped owner’s declaration without removing other owners’ listeners. */
37
44
  undeclare(plugin) {
38
- this.declared.delete(plugin);
45
+ this.declared.delete(resolveName(plugin, this.declared.keys()));
39
46
  }
40
47
  /** The plugin that declared the namespace of an event name, if any. */
41
48
  ownerOf(name) {
42
- const prefix = name.split('.')[0];
49
+ const prefix = resolveName(name.split('.')[0], [...this.declared.keys(), ...this.reserved]);
43
50
  return this.declared.has(prefix) ? prefix : undefined;
44
51
  }
52
+ resolve(name) {
53
+ return resolveName(name, [
54
+ ...this.reservedEvents,
55
+ ...[...this.declared.values()].flatMap((entry) => entry.names),
56
+ ]);
57
+ }
45
58
  isCancelable(name) {
59
+ name = this.resolve(name);
46
60
  return this.declared.get(name.split('.')[0])?.cancelable.has(name) ?? false;
47
61
  }
48
62
  /** Reserves a runtime-owned namespace and returns its private publishing capability. */
@@ -53,15 +67,17 @@ export class EventService {
53
67
  return (name, data) => {
54
68
  if (!name.startsWith(`${namespace}.`))
55
69
  throw new Error('Event is outside the reserved namespace.');
70
+ this.reservedEvents.add(name);
56
71
  this.dispatch(name, data);
57
72
  };
58
73
  }
59
74
  emit = ((name, data) => {
60
- if (this.reserved.has(name.split('.')[0]))
75
+ if (this.reserved.has(resolveName(name.split('.')[0], [...this.reserved, ...this.declared.keys()])))
61
76
  throw new Error(`Event "${name}" is emitted only by the runtime.`);
62
77
  return this.dispatch(name, data);
63
78
  });
64
79
  dispatch = (name, data) => {
80
+ name = this.resolve(name);
65
81
  const schema = this.declared.get(name.split('.')[0])?.schemas.get(name);
66
82
  if (this.isCancelable(name)) {
67
83
  // Cancelable emits return a promise, so an invalid payload rejects it instead of throwing.
@@ -130,11 +146,22 @@ export class EventService {
130
146
  return !cancelled;
131
147
  }
132
148
  listenersFor(name) {
133
- const result = [...(this.exact.get(name) ?? [])];
149
+ const result = [];
150
+ const select = (listeners, matches) => {
151
+ try {
152
+ if (matches())
153
+ result.push(...listeners);
154
+ }
155
+ catch (error) {
156
+ this.report(error, Object.freeze({ type: name, data: undefined }));
157
+ }
158
+ };
159
+ for (const [requested, listeners] of this.exact)
160
+ select(listeners, () => this.resolve(requested) === name);
161
+ const namespaces = [...this.declared.keys(), ...this.reserved];
134
162
  for (const [prefix, listeners] of this.prefixes)
135
- if (name.startsWith(prefix))
136
- result.push(...listeners);
137
- return result;
163
+ select(listeners, () => name.startsWith(prefix ? `${resolveName(prefix.slice(0, -1), namespaces)}.` : ''));
164
+ return [...new Set(result)];
138
165
  }
139
166
  report(error, event) {
140
167
  try {
@@ -147,6 +174,12 @@ export class EventService {
147
174
  on = ((names, handler) => {
148
175
  const controller = new AbortController();
149
176
  const keys = [...new Set(typeof names === 'string' ? [names] : names)];
177
+ for (const name of keys) {
178
+ if (name.endsWith('.*'))
179
+ resolveName(name.slice(0, -2), [...this.declared.keys(), ...this.reserved]);
180
+ else if (name !== '*')
181
+ this.resolve(name);
182
+ }
150
183
  const invoke = (event) => {
151
184
  if (controller.signal.aborted)
152
185
  return;
@@ -210,7 +243,9 @@ export function createEventScope(events, owner) {
210
243
  if (!active)
211
244
  return undefined;
212
245
  const declaredBy = events.ownerOf(name);
213
- if (owner !== undefined && declaredBy !== undefined && declaredBy !== owner)
246
+ if (owner !== undefined &&
247
+ declaredBy !== undefined &&
248
+ declaredBy !== (events.ownerOf(`${owner}.__owner`) ?? owner))
214
249
  throw new Error(`"${owner}" cannot emit "${name}": that event belongs to plugin "${declaredBy}". Only the declaring plugin emits its events; listen with events.on instead.`);
215
250
  return events.emit(name, ...data);
216
251
  }),
@@ -1,4 +1,5 @@
1
- import type { GeneratedName } from '../names.js';
1
+ import type { NamedValue, NameKey } from '../name-resolution.js';
2
+ import type { GeneratedName, CheckedName } from '../names.js';
2
3
  /** Event names and payloads. Generated from every plugin's `events.ts`; may also be augmented by hand. */
3
4
  export interface EventMap {
4
5
  }
@@ -11,9 +12,12 @@ export type EventName = GeneratedName<KnownEventName>;
11
12
  type PatternOf<Name extends string> = Name extends `${infer Prefix}.${string}` ? `${Prefix}.*` : never;
12
13
  /** What a listener selects: an event, a `<prefix>.*` pattern of declared events, or `*`. */
13
14
  export type EventSelector = EventName | PatternOf<KnownEventName> | '*';
14
- export type EventData<Name extends string> = Name extends keyof EventMap ? EventMap[Name] : unknown;
15
+ export type EventData<Name extends string> = NamedValue<EventMap, Name>;
15
16
  /** `todos.*` matches every declared `todos.<name>` event. */
16
- export type EventsMatching<Pattern extends string> = Pattern extends `${infer Prefix}.*` ? Extract<keyof EventMap, `${Prefix}.${string}`> extends never ? string : Extract<keyof EventMap, `${Prefix}.${string}`> : Pattern;
17
+ type MatchingPrefix<Prefix extends string> = {
18
+ [K in KnownEventName]: K extends `${infer Owner}.${string}` ? Lowercase<Owner> extends Lowercase<Prefix> ? K : never : never;
19
+ }[KnownEventName];
20
+ export type EventsMatching<Pattern extends string> = Pattern extends unknown ? Pattern extends `${infer Prefix}.*` ? [MatchingPrefix<Prefix>] extends [never] ? string : MatchingPrefix<Prefix> : [NameKey<EventMap, Pattern>] extends [never] ? Pattern : NameKey<EventMap, Pattern> : never;
17
21
  export type BitaKitEvent<Name extends string = string> = Name extends string ? Readonly<{
18
22
  type: Name;
19
23
  data: EventData<Name>;
@@ -25,15 +29,15 @@ export type EventHandler<Name extends string = string> = (event: BitaKitEvent<Ev
25
29
  signal: AbortSignal;
26
30
  }) => void | Promise<void>;
27
31
  export type EventErrorHandler = (error: unknown, event: BitaKitEvent) => void;
28
- export type EmitResult<Name extends string> = Name extends keyof CancelableEventMap ? Promise<boolean> : void;
32
+ export type EmitResult<Name extends string> = [NameKey<CancelableEventMap, Name>] extends [never] ? void : NameKey<CancelableEventMap, Name> extends keyof CancelableEventMap ? Promise<boolean> : void;
29
33
  type EmitArguments<Name extends string> = undefined extends EventData<Name> ? [data?: EventData<Name>] : [data: EventData<Name>];
30
34
  export interface Events {
31
35
  /** Each matching event invokes the handler once. Returns the unsubscribe function. */
32
- on<const Name extends EventSelector>(names: Name | readonly Name[], handler: EventHandler<Name>): () => void;
36
+ on<const Name extends string>(names: (Name & CheckedName<Name, KnownEventName | PatternOf<KnownEventName> | '*'>) | readonly (Name & CheckedName<Name, KnownEventName | PatternOf<KnownEventName> | '*'>)[], handler: EventHandler<Name>): () => void;
33
37
  /**
34
38
  * Synchronous delivery; async handlers are observed for errors, not awaited. A cancelable
35
39
  * event waits for its handlers and resolves to false when one of them cancelled.
36
40
  */
37
- emit<Name extends EventName>(name: Name, ...data: EmitArguments<Name>): EmitResult<Name>;
41
+ emit<Name extends string>(name: Name & CheckedName<Name, KnownEventName>, ...data: EmitArguments<Name>): EmitResult<Name>;
38
42
  }
39
43
  export {};
@@ -38,6 +38,9 @@ export type ServiceCall<Name extends string = string, Key extends string = strin
38
38
  /** The called service's ID; a glob or alias target still reports the actual ID. */
39
39
  readonly service: string;
40
40
  readonly method: Key;
41
+ /** Supplied by runtime observers; optional to preserve manually constructed legacy calls. */
42
+ readonly callId?: number;
43
+ readonly startedAt?: number;
41
44
  readonly args: Readonly<Parameters<MethodOf<Name, Key>>>;
42
45
  };
43
46
  /**
@@ -59,9 +62,11 @@ export type ServiceInterceptorSpec<Name extends string = string, Key extends str
59
62
  order?: number;
60
63
  before?(call: ServiceCall<Name, Key> & ServiceHookContext): void;
61
64
  after?(call: ServiceCall<Name, Key> & ServiceHookContext & {
65
+ readonly durationMs?: number;
62
66
  readonly result: Awaited<ReturnType<MethodOf<Name, Key>>>;
63
67
  }): void;
64
68
  onError?(call: ServiceCall<Name, Key> & ServiceHookContext & {
69
+ readonly durationMs?: number;
65
70
  readonly error: unknown;
66
71
  }): void;
67
72
  };
@@ -81,5 +86,5 @@ export declare function isServiceInterceptor(spec: object): spec is ServiceInter
81
86
  kind: 'interceptor';
82
87
  };
83
88
  /** Glob matching for action IDs and service names: exact, `prefix.*`, or `*`. */
84
- export declare function matchesTarget(target: InterceptorTarget, id: string): boolean;
89
+ export declare function matchesTarget(target: InterceptorTarget, id: string, names?: readonly string[]): boolean;
85
90
  export {};
@@ -1,3 +1,4 @@
1
+ import { resolveName } from '../name-resolution.js';
1
2
  export function defineInterceptor(spec) {
2
3
  if (!spec || typeof spec !== 'object')
3
4
  throw new Error('defineInterceptor expects an object.');
@@ -13,11 +14,14 @@ export function isServiceInterceptor(spec) {
13
14
  return 'service' in spec && spec.service !== undefined;
14
15
  }
15
16
  /** Glob matching for action IDs and service names: exact, `prefix.*`, or `*`. */
16
- export function matchesTarget(target, id) {
17
+ export function matchesTarget(target, id, names = [id]) {
17
18
  const patterns = typeof target === 'string' ? [target] : target;
18
19
  return patterns.some((pattern) => pattern === '*'
19
20
  ? true
20
21
  : pattern.endsWith('.*')
21
- ? id.startsWith(pattern.slice(0, -1))
22
- : pattern === id);
22
+ ? id.startsWith(`${resolveName(pattern.slice(0, -2), names.flatMap((name) => name
23
+ .split('.')
24
+ .slice(0, -1)
25
+ .map((_, index, parts) => parts.slice(0, index + 1).join('.'))))}.`)
26
+ : resolveName(pattern, names) === id);
23
27
  }
@@ -4,4 +4,4 @@ import { type InterceptorSpec } from './define.js';
4
4
  * container consumers receive the same wrapper; frozen instances are supported. `services`
5
5
  * is read when a call happens, because the service tree exists only after the container does.
6
6
  */
7
- export declare function serviceObserver(interceptors: readonly InterceptorSpec[], namesOf: (id: string) => readonly string[], services: () => unknown): (id: string, instance: any, active: () => boolean) => any;
7
+ export declare function serviceObserver(interceptors: readonly InterceptorSpec[], namesOf: (id: string) => readonly string[], services: () => unknown, allNames?: () => readonly string[]): (id: string, instance: any, active: () => boolean) => any;
@@ -15,7 +15,8 @@ function notify(callback, event) {
15
15
  * container consumers receive the same wrapper; frozen instances are supported. `services`
16
16
  * is read when a call happens, because the service tree exists only after the container does.
17
17
  */
18
- export function serviceObserver(interceptors, namesOf, services) {
18
+ export function serviceObserver(interceptors, namesOf, services, allNames) {
19
+ let nextCallId = 0;
19
20
  const entries = interceptors
20
21
  .filter(isServiceInterceptor)
21
22
  .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
@@ -23,7 +24,7 @@ export function serviceObserver(interceptors, namesOf, services) {
23
24
  if (!instance || (typeof instance !== 'object' && typeof instance !== 'function'))
24
25
  return instance;
25
26
  const names = [id, ...namesOf(id)];
26
- const selected = entries.filter((entry) => names.some((name) => matchesTarget(entry.service, name)));
27
+ const selected = entries.filter((entry) => names.some((name) => matchesTarget(entry.service, name, allNames?.() ?? names)));
27
28
  if (!selected.length)
28
29
  return instance;
29
30
  const cache = new Map();
@@ -51,12 +52,18 @@ export function serviceObserver(interceptors, namesOf, services) {
51
52
  // A function Proxy keeps the method's own properties (for example `translate.has`);
52
53
  // only the call itself is observed.
53
54
  const call = (...args) => {
55
+ const callId = ++nextCallId;
56
+ const startedAt = Date.now();
57
+ const start = performance.now();
54
58
  const emit = (phase, extra = {}) => {
55
59
  if (!active())
56
60
  return;
57
61
  for (const entry of observers)
58
62
  notify(entry[phase], {
59
63
  service: id,
64
+ callId,
65
+ startedAt,
66
+ ...(phase === 'before' ? {} : { durationMs: performance.now() - start }),
60
67
  method: key,
61
68
  args: Object.freeze([...args]),
62
69
  services: services(),
@@ -1,3 +1,4 @@
1
+ import { resolveName } from '../name-resolution.js';
1
2
  import { createActionList } from '../actions/core.js';
2
3
  import { BitaKitRuntime } from '../runtime.js';
3
4
  import { isBitaKitStartupError } from '../startup-error.js';
@@ -30,19 +31,19 @@ export function failedPluginClosure(plugins, failures) {
30
31
  .flatMap((plugin) => plugin.ui?.providers?.map((provider) => provider.id) ?? []));
31
32
  for (const plugin of plugins) {
32
33
  const requirements = [
33
- ...(plugin.dependencies ?? []).map((id) => off.has(id)),
34
+ ...(plugin.dependencies ?? []).map((id) => off.has(resolveName(id, plugins.map((plugin) => plugin.id)))),
34
35
  ...Object.values(plugin.services ?? {})
35
36
  .flatMap((value) => value.requires ?? [])
36
- .map((name) => unavailable.has(name)),
37
+ .map((name) => unavailable.has(resolveName(name, plugins.flatMap(pluginServiceNames)))),
37
38
  ...Object.values(plugin.actions ?? {})
38
39
  .flatMap((value) => value.requires ?? [])
39
- .map((name) => unavailable.has(name)),
40
+ .map((name) => unavailable.has(resolveName(name, plugins.flatMap(pluginServiceNames)))),
40
41
  ...(plugin.interceptors ?? [])
41
42
  .flatMap((value) => value.requires ?? [])
42
- .map((name) => unavailable.has(name)),
43
+ .map((name) => unavailable.has(resolveName(name, plugins.flatMap(pluginServiceNames)))),
43
44
  ...(plugin.ui?.providers ?? [])
44
45
  .flatMap((value) => value.requires ?? [])
45
- .map((name) => unavailableProviders.has(name)),
46
+ .map((name) => unavailableProviders.has(resolveName(name, plugins.flatMap((plugin) => plugin.ui?.providers?.map((provider) => provider.id) ?? [])))),
46
47
  ];
47
48
  if (!off.has(plugin.id) && requirements.some(Boolean)) {
48
49
  off.add(plugin.id);
@@ -99,7 +100,7 @@ export class RuntimeController {
99
100
  const failure = failed.get(id);
100
101
  const phase = failure
101
102
  ? 'failed'
102
- : this.off.has(id)
103
+ : this.off.has(resolveName(id, (this.config.plugins ?? []).map((plugin) => plugin.id)))
103
104
  ? 'blocked'
104
105
  : (states.get(id)?.phase ?? 'idle');
105
106
  const previous = this.store.get().plugins.find((entry) => entry.id === id);
@@ -148,7 +149,7 @@ export class RuntimeController {
148
149
  ...this.config,
149
150
  plugins: active,
150
151
  configOverrides: this.config.configOverrides &&
151
- Object.fromEntries(Object.entries(this.config.configOverrides).filter(([id]) => !this.off.has(id))),
152
+ Object.fromEntries(Object.entries(this.config.configOverrides).filter(([id]) => !this.off.has(resolveName(id, (this.config.plugins ?? []).map((plugin) => plugin.id))))),
152
153
  ui: this.config.ui && {
153
154
  ...this.config.ui,
154
155
  providers: this.config.ui.providers?.filter((provider) => !removedProviders.has(provider)),
@@ -1,3 +1,4 @@
1
+ import { resolveName } from '../name-resolution.js';
1
2
  /** Lifecycle edges include required service aliases, not just explicit plugin dependencies. */
2
3
  export function pluginDependencies(modules) {
3
4
  const owners = new Map();
@@ -9,10 +10,10 @@ export function pluginDependencies(modules) {
9
10
  return new Map(modules.map((module) => [
10
11
  module.id,
11
12
  new Set([
12
- ...(module.dependencies ?? []),
13
+ ...(module.dependencies ?? []).map((id) => resolveName(id, modules.map((entry) => entry.id))),
13
14
  ...[...module.services, ...module.actions, ...(module.interceptors ?? [])]
14
15
  .flatMap((value) => value.requires ?? [])
15
- .map((name) => owners.get(name))
16
+ .map((name) => owners.get(resolveName(name, owners.keys())))
16
17
  .filter((id) => !!id && id !== module.id),
17
18
  ]),
18
19
  ]));
@@ -0,0 +1,11 @@
1
+ /** Exact spellings remain authoritative; a folded reference must identify exactly one name. */
2
+ export declare function resolveName(name: string, candidates: Iterable<string>): string;
3
+ /** Resolves keys without renaming stored entries or collapsing existing case-only definitions. */
4
+ export declare function namedRecord<T extends object>(record: T): T;
5
+ /** Exact map keys take precedence, including when two existing keys differ only in case. */
6
+ type FoldedKey<Keys extends string, Name extends string> = Keys extends unknown ? Lowercase<Keys> extends Lowercase<Name> ? Keys : never : never;
7
+ export type NameKey<Map, Name extends string> = string extends Name ? never : Name extends keyof Map ? Name : FoldedKey<Extract<keyof Map, string>, Name>;
8
+ export type NamedValue<Map, Name extends string, Fallback = unknown> = [
9
+ NameKey<Map, Name>
10
+ ] extends [never] ? Fallback : Map[NameKey<Map, Name>];
11
+ export {};
@@ -0,0 +1,24 @@
1
+ /** Exact spellings remain authoritative; a folded reference must identify exactly one name. */
2
+ export function resolveName(name, candidates) {
3
+ let match;
4
+ let ambiguous = false;
5
+ for (const candidate of candidates) {
6
+ if (candidate === name)
7
+ return name;
8
+ if (candidate.toLowerCase() !== name.toLowerCase())
9
+ continue;
10
+ if (match !== undefined && match !== candidate)
11
+ ambiguous = true;
12
+ match = candidate;
13
+ }
14
+ if (ambiguous)
15
+ throw new Error(`Ambiguous identifier "${name}". Use the exact registered spelling.`);
16
+ return match ?? name;
17
+ }
18
+ /** Resolves keys without renaming stored entries or collapsing existing case-only definitions. */
19
+ export function namedRecord(record) {
20
+ return new Proxy(record, {
21
+ get: (target, name, receiver) => Reflect.get(target, typeof name === 'string' ? resolveName(name, Object.keys(target)) : name, receiver),
22
+ has: (target, name) => Reflect.has(target, typeof name === 'string' ? resolveName(name, Object.keys(target)) : name),
23
+ });
24
+ }
package/dist/names.d.ts CHANGED
@@ -8,3 +8,7 @@ import type { ActionMapOptions } from './actions/types.js';
8
8
  export type GeneratedName<Known extends string> = ActionMapOptions extends {
9
9
  strict: true;
10
10
  } ? Known : Known | (string & {});
11
+ /** Checks a caller's string literal without enumerating exponentially many case permutations. */
12
+ export type CheckedName<Name extends string, Known extends string> = ActionMapOptions extends {
13
+ strict: true;
14
+ } ? Lowercase<Name> extends Lowercase<Known> ? Name : never : Name;
package/dist/runtime.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { resolveName } from './name-resolution.js';
1
2
  import { EventService, createEventScope } from './events/service.js';
2
3
  import { normalizeSlots, validateSlotDeclarations } from './slots/normalize.js';
3
4
  import { SlotRuntime } from './slots/runtime.js';
@@ -97,7 +98,8 @@ function descendantsOf(installed, ids) {
97
98
  const found = [];
98
99
  for (let frontier = [...ids]; frontier.length;) {
99
100
  const children = installed
100
- .filter((plugin) => plugin.parent && frontier.includes(plugin.parent))
101
+ .filter((plugin) => plugin.parent &&
102
+ frontier.includes(resolveName(plugin.parent, installed.map((entry) => entry.id))))
101
103
  .map((plugin) => plugin.id)
102
104
  .filter((id) => !found.includes(id) && !ids.includes(id));
103
105
  found.push(...children);
@@ -106,6 +108,12 @@ function descendantsOf(installed, ids) {
106
108
  return found;
107
109
  }
108
110
  function orderPlugins(plugins, appId) {
111
+ const names = plugins.map((plugin) => plugin.id);
112
+ plugins = plugins.map((plugin) => ({
113
+ ...plugin,
114
+ dependencies: plugin.dependencies?.map((id) => resolveName(id, names)),
115
+ parent: plugin.parent ? resolveName(plugin.parent, names) : undefined,
116
+ }));
109
117
  const remaining = new Map();
110
118
  for (const plugin of plugins) {
111
119
  if (remaining.has(plugin.id))
@@ -223,7 +231,8 @@ export class BitaKitRuntime {
223
231
  /** Initial startup has completed and shutdown has not begun. Updates use owner readiness. */
224
232
  isReady = (plugin) => this.mounted &&
225
233
  (plugin === undefined ||
226
- this.lifecycle.get().plugins.some((entry) => entry.id === plugin && entry.phase === 'ready'));
234
+ this.lifecycle.get().plugins.some((entry) => entry.id ===
235
+ resolveName(plugin, this.modules.map((module) => module.id)) && entry.phase === 'ready'));
227
236
  subscribeReady = (listener) => {
228
237
  this.readinessListeners.add(listener);
229
238
  return () => {
@@ -537,7 +546,18 @@ export class BitaKitRuntime {
537
546
  return translate;
538
547
  }
539
548
  override(id) {
540
- return this.config.actionOverrides?.[id];
549
+ const overrides = this.config.actionOverrides ?? {};
550
+ const keys = Object.keys(overrides);
551
+ const exact = keys.find((name) => name === id);
552
+ if (exact)
553
+ return overrides[exact];
554
+ const requested = keys.filter((name) => resolveName(name, [
555
+ ...this.modules.flatMap((module) => module.actions.map((action) => action.id)),
556
+ ...Object.keys(this.actions.getState().actions),
557
+ ]) === id);
558
+ if (requested.length > 1)
559
+ throw new Error(`Duplicate action override for "${id}".`);
560
+ return requested.length ? overrides[requested[0]] : undefined;
541
561
  }
542
562
  dialog() {
543
563
  return this.state;
@@ -690,7 +710,7 @@ export class BitaKitRuntime {
690
710
  const interceptors = plugins.flatMap((plugin) => plugin.interceptors ?? []);
691
711
  this.container = createServices(plugins.flatMap((plugin) => plugin.services), this.providedServices, (definition) => this.configuration.context(owners.get(definition) ??
692
712
  this.modules.find((module) => module.services.includes(definition))?.id ??
693
- this.appId), serviceObserver(interceptors, (id) => this.aliasesOf(id), () => this.view), this.events, {
713
+ this.appId), serviceObserver(interceptors, (id) => this.aliasesOf(id), () => this.view, () => this.names.names()), this.events, {
694
714
  names: this.names,
695
715
  appId: this.appId,
696
716
  moduleOf: (definition) => owners.get(definition) ??
@@ -891,6 +911,9 @@ export class BitaKitRuntime {
891
911
  module: plugin.id,
892
912
  app: plugin.id === this.appId,
893
913
  services: this.services,
914
+ config: this.configuration.context(plugin.id),
915
+ events: this.pluginEvents.get(plugin.id).events,
916
+ settings: this.settingsAccess,
894
917
  });
895
918
  if (cleanup)
896
919
  this.scopes[index].own(cleanup);
@@ -927,7 +950,7 @@ export class BitaKitRuntime {
927
950
  catch (error) {
928
951
  throw this.attribute(error, module, 'Interceptor', requester.source);
929
952
  }
930
- const applies = (id) => matchesTarget(definition.action ?? '*', id) &&
953
+ const applies = (id) => matchesTarget(definition.action ?? '*', id, Object.keys(this.actions.getState().actions)) &&
931
954
  (global || this.actionConfigs.get(id)?.module === module);
932
955
  const context = (base) => ({
933
956
  ...base,
@@ -1142,7 +1165,7 @@ export class BitaKitRuntime {
1142
1165
  const disabled = new Set(this.disabledPlugins);
1143
1166
  const ids = operation === 'add'
1144
1167
  ? values.map((plugin) => plugin.id)
1145
- : [...values];
1168
+ : values.map((id) => resolveName(id, installed.map((plugin) => plugin.id)));
1146
1169
  if (new Set(ids).size !== ids.length)
1147
1170
  return result('blocked', ['Plugin IDs must be unique.']);
1148
1171
  if (ids.includes(this.appId))
@@ -1180,7 +1203,10 @@ export class BitaKitRuntime {
1180
1203
  cascaded.set(parent, children.filter((child) => !ids.includes(child)));
1181
1204
  if (operation === 'enable')
1182
1205
  for (const id of [...ids]) {
1183
- const parent = installed.find((plugin) => plugin.id === id)?.parent;
1206
+ const declaredParent = installed.find((plugin) => plugin.id === id)?.parent;
1207
+ const parent = declaredParent
1208
+ ? resolveName(declaredParent, installed.map((plugin) => plugin.id))
1209
+ : undefined;
1184
1210
  if (parent && disabled.has(parent) && !ids.includes(parent))
1185
1211
  return result('blocked', [
1186
1212
  `Plugin "${id}" belongs to "${parent}", which is disabled. Enable "${parent}" first.`,
@@ -1234,7 +1260,8 @@ export class BitaKitRuntime {
1234
1260
  disabled.delete(id);
1235
1261
  if (operation === 'disable')
1236
1262
  changed = changed.filter((id) => !this.disabledPlugins.has(id));
1237
- const protectedOwners = changed.filter((id) => options?.preserve?.includes(id));
1263
+ const preserved = options?.preserve?.map((id) => resolveName(id, installed.map((plugin) => plugin.id))) ?? [];
1264
+ const protectedOwners = changed.filter((id) => preserved.includes(id));
1238
1265
  if ((operation === 'disable' || operation === 'remove' || operation === 'replace') &&
1239
1266
  protectedOwners.length)
1240
1267
  return result('blocked', ['The host requires these plugins to remain enabled.'], 'protected', protectedOwners);
@@ -1,3 +1,4 @@
1
+ import { resolveName } from './name-resolution.js';
1
2
  /**
2
3
  * Low-level key creation; `defineContract(name).of<T>()` is the documented form. Pass both type
3
4
  * arguments (`serviceKey<T, 'name'>('name')`) to keep the literal name.
@@ -18,7 +19,12 @@ export function defineContract(id) {
18
19
  /** Reads a contract from a services object (tree or flat); throws a clear error when absent. */
19
20
  export function getService(services, key) {
20
21
  let current = services;
21
- for (const segment of key.split('.')) {
22
+ for (const requested of key.split('.')) {
23
+ const segment = current && typeof current === 'object'
24
+ ? requested in current
25
+ ? requested
26
+ : resolveName(requested, Object.getOwnPropertyNames(current))
27
+ : requested;
22
28
  if (!current || typeof current !== 'object' || !(segment in current))
23
29
  throw new Error(`Missing service "${key}".`);
24
30
  current = current[segment];
@@ -1,3 +1,4 @@
1
+ import { resolveName } from './name-resolution.js';
1
2
  import { BitaKitStartupError } from './startup-error.js';
2
3
  import { BitaKitServiceError } from './app/service-error.js';
3
4
  /**
@@ -69,10 +70,10 @@ export class ServiceNames {
69
70
  }
70
71
  /** The container key that `name` refers to; unknown names are returned as-is. */
71
72
  key(name) {
72
- return this.ids.get(name) ?? name;
73
+ return this.ids.get(resolveName(name, this.ids.keys())) ?? name;
73
74
  }
74
75
  known(name) {
75
- return this.ids.has(name);
76
+ return this.ids.has(resolveName(name, this.ids.keys()));
76
77
  }
77
78
  /** Every known name, IDs first. */
78
79
  names() {
@@ -94,7 +95,7 @@ export class ServiceNames {
94
95
  if (typeof name !== 'string' || name === 'then' || name === 'toJSON')
95
96
  return undefined;
96
97
  const path = prefix ? `${prefix}.${name}` : name;
97
- const child = node.children.get(name);
98
+ const child = node.children.get(resolveName(name, node.children.keys()));
98
99
  if (!child) {
99
100
  throw new BitaKitServiceError(path, notReady?.() ? 'not-ready' : 'unregistered');
100
101
  }
@@ -106,9 +107,9 @@ export class ServiceNames {
106
107
  }
107
108
  return project(child, path);
108
109
  },
109
- has: (_target, name) => typeof name === 'string' && node.children.has(name),
110
+ has: (_target, name) => typeof name === 'string' && node.children.has(resolveName(name, node.children.keys())),
110
111
  ownKeys: () => [...node.children.keys()],
111
- getOwnPropertyDescriptor: (_target, name) => typeof name === 'string' && node.children.has(name)
112
+ getOwnPropertyDescriptor: (_target, name) => typeof name === 'string' && node.children.has(resolveName(name, node.children.keys()))
112
113
  ? { enumerable: true, configurable: true, writable: false, value: proxy[name] }
113
114
  : undefined,
114
115
  set: () => false,
@@ -1,3 +1,4 @@
1
+ import { resolveName } from '../name-resolution.js';
1
2
  const reserved = new Set(['then', 'toJSON', 'constructor', '__proto__']);
2
3
  /** Validates declarations; namespace proxies follow the current store without copying values. */
3
4
  export function createSettingsAccess(store) {
@@ -39,6 +40,7 @@ export function createSettingsAccess(store) {
39
40
  get(_object, name) {
40
41
  if (typeof name !== 'string' || reserved.has(name))
41
42
  return undefined;
43
+ name = resolveName(name, keys());
42
44
  const key = path ? `${path}.${name}` : name;
43
45
  if (store.has(key)) {
44
46
  const spec = store.definition(key).spec;
@@ -46,14 +48,14 @@ export function createSettingsAccess(store) {
46
48
  handles.set(key, { spec, value: handle(store, key, spec) });
47
49
  return handles.get(key).value;
48
50
  }
49
- if (keys().includes(name))
51
+ if (keys().includes(resolveName(name, keys())))
50
52
  return project(key);
51
53
  const owner = path ? `plugin "${path}"` : 'the app or a plugin';
52
54
  throw new Error(`Unknown setting "${key}". Declare it in settings.ts of ${owner}.`);
53
55
  },
54
- has: (_object, name) => typeof name === 'string' && keys().includes(name),
56
+ has: (_object, name) => typeof name === 'string' && keys().includes(resolveName(name, keys())),
55
57
  ownKeys: keys,
56
- getOwnPropertyDescriptor: (_object, name) => typeof name === 'string' && keys().includes(name)
58
+ getOwnPropertyDescriptor: (_object, name) => typeof name === 'string' && keys().includes(resolveName(name, keys()))
57
59
  ? { enumerable: true, configurable: true }
58
60
  : undefined,
59
61
  set: () => false,
@@ -1,3 +1,4 @@
1
+ import type { NamedValue } from '../name-resolution.js';
1
2
  import type { InputSchema, SchemaOutput } from '../definitions.js';
2
3
  import type { PresentationType } from '../presentation.js';
3
4
  import type { GeneratedName } from '../names.js';
@@ -103,7 +104,7 @@ export interface SettingsMap {
103
104
  }
104
105
  /** A declared setting key; strict generated apps reject unknown keys. */
105
106
  export type SettingKey = GeneratedName<Extract<keyof SettingsMap, string>>;
106
- export type SettingValue<Key extends string> = Key extends keyof SettingsMap ? SettingsMap[Key] : unknown;
107
+ export type SettingValue<Key extends string> = NamedValue<SettingsMap, Key>;
107
108
  type ValueOf<S> = S extends SettingSpec<infer T> ? T : never;
108
109
  /** `SettingsMap` entries of one declaration under a plugin prefix (none for the app module). */
109
110
  export type SettingsOf<D, Plugin extends string> = D extends SettingsDefinition<infer Specs> ? {
@@ -1,3 +1,4 @@
1
+ import { resolveName } from '../name-resolution.js';
1
2
  import { parseSetting } from './define.js';
2
3
  import { schemaErrorMessage } from '../schema.js';
3
4
  const message = (error, fallback) => schemaErrorMessage(error, fallback);
@@ -67,7 +68,7 @@ export class SettingsStore {
67
68
  return [...this.slots.values()].map((slot) => slot.entry);
68
69
  }
69
70
  has(key) {
70
- return this.slots.has(key);
71
+ return this.slots.has(resolveName(key, this.slots.keys()));
71
72
  }
72
73
  definition(key) {
73
74
  return this.slot(key).entry;
@@ -172,7 +173,7 @@ export class SettingsStore {
172
173
  }
173
174
  }
174
175
  slot(key) {
175
- const slot = this.slots.get(key);
176
+ const slot = this.slots.get(resolveName(key, this.slots.keys()));
176
177
  if (!slot) {
177
178
  const plugin = key.includes('.') ? `plugin "${key.slice(0, key.indexOf('.'))}"` : 'the app';
178
179
  throw new Error(`Unknown setting "${key}". Declare it in settings.ts of ${plugin}.`);
@@ -1,3 +1,4 @@
1
+ import type { NamedValue } from '../name-resolution.js';
1
2
  import type { InputSchema, SchemaOutput, EffectiveActionId } from '../definitions.js';
2
3
  import type { SlotMap } from '../presentation.js';
3
4
  /**
@@ -43,7 +44,7 @@ export declare function defineSlot<const T extends SlotOptions>(options: T): Rea
43
44
  }>;
44
45
  export declare function isSlotDefinition(value: unknown): value is SlotDefinition;
45
46
  /** Accept a generated name or a definition directly (manual composition needs no augmentation). */
46
- type DefinitionOf<T> = T extends keyof SlotMap ? SlotMap[T] : T;
47
+ type DefinitionOf<T> = T extends keyof SlotMap ? SlotMap[T] : T extends string ? NamedValue<SlotMap, T, T> : T;
47
48
  export type SlotPayload<T> = DefinitionOf<T> extends {
48
49
  payload: infer S;
49
50
  } ? SchemaOutput<S> : undefined;
@@ -1,3 +1,4 @@
1
+ import { resolveName } from '../name-resolution.js';
1
2
  import { BitaKitStartupError } from '../startup-error.js';
2
3
  import { createStore } from '../store.js';
3
4
  import { validate } from '../schema.js';
@@ -45,7 +46,7 @@ export class SlotRuntime {
45
46
  })),
46
47
  });
47
48
  this.reader = Object.freeze({
48
- has: (name) => this.entries.has(name),
49
+ has: (name) => this.entries.has(resolveName(name, this.entries.keys())),
49
50
  get: (name) => this.entry(name).store.get(),
50
51
  subscribe: (name, listener) => this.listen(this.entry(name).store, listener),
51
52
  watch: (name, listener) => this.listen(this.entry(name).store, listener, true),
@@ -54,7 +55,7 @@ export class SlotRuntime {
54
55
  }
55
56
  /** `source` names the contributing file when an unknown target comes from an attachment. */
56
57
  entry(name, plugin = this.appId, source) {
57
- const entry = this.entries.get(name);
58
+ const entry = this.entries.get(resolveName(name, this.entries.keys()));
58
59
  if (!entry)
59
60
  throw new SlotError('unknown-slot', name, plugin, 'no owning definition exists. Install and enable the plugin that declares it (in tests, pass that plugin to mountPlugin).', source, plugin === this.appId);
60
61
  return entry;
@@ -135,6 +136,7 @@ export class SlotRuntime {
135
136
  }
136
137
  attach(scope, plugin, name, contribution, availability) {
137
138
  const { definition } = this.entry(name, plugin, contributionSource(contribution));
139
+ name = definition.id;
138
140
  const source = contributionSource(contribution) ?? contributionSource(definition);
139
141
  const error = (code, message) => new SlotError(code, name, plugin, message, source, plugin === this.appId);
140
142
  if (availability !== 'require' && availability !== 'wait')
@@ -12,7 +12,10 @@ export function candidateNames(item) {
12
12
  */
13
13
  export function selectSingle(candidates, options) {
14
14
  if (options.choice !== undefined) {
15
- const matches = candidates.filter((item) => candidateNames(item).includes(options.choice));
15
+ const exact = candidates.filter((item) => candidateNames(item).includes(options.choice));
16
+ const matches = exact.length
17
+ ? exact
18
+ : candidates.filter((item) => candidateNames(item).some((name) => name.toLowerCase() === options.choice.toLowerCase()));
16
19
  if (matches.length === 1)
17
20
  return { selected: matches[0], candidates };
18
21
  return { reason: matches.length ? 'ambiguous' : 'choice-unavailable', candidates };
@@ -1,9 +1,11 @@
1
+ import type { CheckedName } from '../names.js';
2
+ import type { NamedValue } from '../name-resolution.js';
1
3
  import type { PresentationType, SlotMap, SlotName } from '../presentation.js';
2
4
  import type { LifecycleFailure, LifecyclePhase } from '../lifecycle/state.js';
3
5
  import type { SlotPayload, SlotData } from './define.js';
4
6
  import type { ActionId } from '../actions/core.js';
5
7
  export type SlotPredicate<Name extends string = string> = (context: {
6
- payload: Name extends keyof SlotMap ? SlotPayload<Name> : any;
8
+ payload: Lowercase<Name> extends Lowercase<Extract<keyof SlotMap, string>> ? SlotPayload<Name> : any;
7
9
  }) => boolean;
8
10
  export type SlotAvailability = 'require' | 'wait';
9
11
  export type SlotContent = {
@@ -24,14 +26,14 @@ export type SlotContent = {
24
26
  component?: never;
25
27
  data?: never;
26
28
  };
27
- type ContentFor<Name extends string> = Name extends keyof SlotMap ? SlotMap[Name] extends {
29
+ type ContentFor<Name extends string> = Lowercase<Name> extends Lowercase<Extract<keyof SlotMap, string>> ? NamedValue<SlotMap, Name> extends {
28
30
  accepts: 'data';
29
31
  } ? {
30
32
  data: SlotData<Name>;
31
33
  component?: never;
32
34
  actionId?: never;
33
35
  input?: never;
34
- } : SlotMap[Name] extends {
36
+ } : NamedValue<SlotMap, Name> extends {
35
37
  accepts: 'actions';
36
38
  } ? {
37
39
  actionId: ActionId;
@@ -40,7 +42,7 @@ type ContentFor<Name extends string> = Name extends keyof SlotMap ? SlotMap[Name
40
42
  }) => unknown;
41
43
  component?: never;
42
44
  data?: never;
43
- } : SlotMap[Name] extends {
45
+ } : NamedValue<SlotMap, Name> extends {
44
46
  accepts: 'component';
45
47
  } ? {
46
48
  component: PresentationType<'component'>;
@@ -54,7 +56,7 @@ export type SlotContribution<Name extends string = string> = ContentFor<Name> &
54
56
  order?: number;
55
57
  /** Pure per-outlet presentation filter; never changes shared attachment state. */
56
58
  when?: SlotPredicate<Name>;
57
- } & (Name extends keyof SlotMap ? SlotMap[Name] extends {
59
+ } & (Lowercase<Name> extends Lowercase<Extract<keyof SlotMap, string>> ? NamedValue<SlotMap, Name> extends {
58
60
  policy: 'keyed';
59
61
  } ? {
60
62
  key: string;
@@ -98,14 +100,14 @@ export type SlotAttachment = Readonly<{
98
100
  }>;
99
101
  export type SlotReader = Readonly<{
100
102
  has(name: string): boolean;
101
- get(name: SlotName): SlotSnapshot;
102
- subscribe(name: SlotName, listener: (state: SlotSnapshot) => void): () => void;
103
- watch(name: SlotName, listener: (state: SlotSnapshot) => void): () => void;
103
+ get<const Name extends string>(name: Name & CheckedName<Name, SlotName>): SlotSnapshot;
104
+ subscribe<const Name extends string>(name: Name & CheckedName<Name, SlotName>, listener: (state: SlotSnapshot) => void): () => void;
105
+ watch<const Name extends string>(name: Name & CheckedName<Name, SlotName>, listener: (state: SlotSnapshot) => void): () => void;
104
106
  }>;
105
107
  export type ScopedSlots = SlotReader & {
106
108
  /** `scope.slots.attach({ slot: 'shell.toolbar', actionId: 'notes.open' })`; the slot is part of the contribution. */
107
- attach<const Name extends SlotName>(contribution: {
108
- slot: Name;
109
+ attach<const Name extends string>(contribution: {
110
+ slot: Name & CheckedName<Name, SlotName>;
109
111
  } & SlotContribution<Name>, options?: {
110
112
  availability?: SlotAvailability;
111
113
  }): SlotAttachment;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bitakit/core",
3
- "version": "0.2.8",
3
+ "version": "0.2.9",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "files": [
@@ -54,7 +54,7 @@
54
54
  }
55
55
  },
56
56
  "devDependencies": {
57
- "@bitakit/discovery": "^0.2.5",
57
+ "@bitakit/discovery": "^0.2.6",
58
58
  "jiti": "^2.7.0",
59
59
  "typescript": "^5.9.3"
60
60
  },