@bitakit/core 0.2.8 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/AGENTS.md +42 -0
  2. package/dist/actions/action-list.d.ts +3 -2
  3. package/dist/actions/action-list.js +5 -0
  4. package/dist/actions/dependencies.js +4 -1
  5. package/dist/actions/execution.js +1 -0
  6. package/dist/actions/types.d.ts +7 -2
  7. package/dist/app/access.js +3 -2
  8. package/dist/app/action-access.js +2 -0
  9. package/dist/config-service.js +11 -3
  10. package/dist/configuration.js +3 -2
  11. package/dist/core.d.ts +4 -1
  12. package/dist/core.js +2 -0
  13. package/dist/definitions.d.ts +10 -0
  14. package/dist/discovered.d.ts +11 -0
  15. package/dist/discovered.js +29 -5
  16. package/dist/events/service.d.ts +2 -0
  17. package/dist/events/service.js +44 -9
  18. package/dist/events/types.d.ts +10 -6
  19. package/dist/interceptors/define.d.ts +6 -1
  20. package/dist/interceptors/define.js +7 -3
  21. package/dist/interceptors/service-observers.d.ts +1 -1
  22. package/dist/interceptors/service-observers.js +9 -2
  23. package/dist/lifecycle/controller.js +8 -7
  24. package/dist/lifecycle/reconcile.js +3 -2
  25. package/dist/name-resolution.d.ts +11 -0
  26. package/dist/name-resolution.js +24 -0
  27. package/dist/names.d.ts +4 -0
  28. package/dist/permissions.d.ts +103 -0
  29. package/dist/permissions.js +172 -0
  30. package/dist/runtime.js +68 -8
  31. package/dist/service-key.js +7 -1
  32. package/dist/service-names.js +6 -5
  33. package/dist/settings/access.js +5 -3
  34. package/dist/settings/define.d.ts +2 -1
  35. package/dist/settings/store.js +3 -2
  36. package/dist/slots/define.d.ts +2 -1
  37. package/dist/slots/runtime.js +4 -2
  38. package/dist/slots/select.js +4 -1
  39. package/dist/slots/types.d.ts +12 -10
  40. package/package.json +3 -3
@@ -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;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Resources and their operations a plugin owns, for example `{ content: ['read', 'edit', 'publish'] }`.
3
+ * Generated declarations extend it, so role grants are typed against the discovered catalog.
4
+ */
5
+ export interface PermissionMap {
6
+ }
7
+ /** Role IDs of the app's `roles.ts`; generated declarations extend it. */
8
+ export interface RoleMap {
9
+ }
10
+ export type PermissionSpec = Readonly<Record<string, readonly string[]>>;
11
+ export type PermissionsDefinition<Spec extends PermissionSpec = PermissionSpec> = {
12
+ readonly kind: 'permissions';
13
+ readonly permissions: Spec;
14
+ /** Project-relative file, set by discovery for diagnostics. */
15
+ readonly source?: string;
16
+ };
17
+ /**
18
+ * Declares the resources and operations a plugin owns, in its `permissions.ts`. A plugin declares
19
+ * capabilities only; which roles receive them is the app's decision in `roles.ts`.
20
+ */
21
+ export declare function definePermissions<const Spec extends PermissionSpec>(permissions: Spec): PermissionsDefinition<Spec>;
22
+ export declare function isPermissionsDefinition(value: unknown): value is PermissionsDefinition;
23
+ /** A provider's built-in organization roles a base role can extend. */
24
+ export type StandardRole = 'owner' | 'admin' | 'member';
25
+ export declare const standardRoles: readonly StandardRole[];
26
+ type KnownGrants = keyof PermissionMap extends never ? Readonly<Record<string, readonly string[]>> : {
27
+ readonly [Resource in keyof PermissionMap]?: readonly PermissionMap[Resource][];
28
+ };
29
+ export type RoleSpec = {
30
+ /** Extends the provider's built-in role with the explicit grants below. */
31
+ readonly standard?: StandardRole;
32
+ /** Default label; a translation `roles.<id>.label` wins. */
33
+ readonly label?: string;
34
+ /** Default explanation; a translation `roles.<id>.description` wins. */
35
+ readonly description?: string;
36
+ /** Operations per resource this role receives, from the discovered permission catalog. */
37
+ readonly grants?: KnownGrants;
38
+ };
39
+ export type RolesOptions = {
40
+ /** Let organizations create their own roles through the provider's dynamic roles. */
41
+ readonly customRoles?: boolean;
42
+ };
43
+ export type RolesDefinition<Roles extends Readonly<Record<string, RoleSpec>> = Readonly<Record<string, RoleSpec>>> = {
44
+ readonly kind: 'roles';
45
+ /** In declaration order: display order only, never a permission hierarchy. */
46
+ readonly roles: Roles;
47
+ readonly options: RolesOptions;
48
+ /** Project-relative file, set by discovery for diagnostics. */
49
+ readonly source?: string;
50
+ };
51
+ /**
52
+ * Declares the app's base roles in `src/roles.ts`. Roles are app configuration: plugins declare
53
+ * permissions, never roles, and base roles are read-only for organizations.
54
+ */
55
+ export declare function defineRoles<const Roles extends Readonly<Record<string, RoleSpec>>>(roles: Roles, options?: RolesOptions): RolesDefinition<Roles>;
56
+ export declare function isRolesDefinition(value: unknown): value is RolesDefinition;
57
+ /** Generated typing: the resources and operations of one `permissions.ts`. */
58
+ export type PermissionsOf<T> = T extends PermissionsDefinition<infer Spec> ? {
59
+ -readonly [Resource in keyof Spec]: Spec[Resource][number];
60
+ } : {};
61
+ /** Generated typing: the role IDs of the app's `roles.ts`. */
62
+ export type RoleIdsOf<T> = T extends RolesDefinition<infer Roles> ? {
63
+ -readonly [Id in keyof Roles]: true;
64
+ } : {};
65
+ /** One resource of the composed catalog with its owning module. */
66
+ export type PermissionResource = {
67
+ readonly owner: string;
68
+ readonly source?: string;
69
+ readonly actions: readonly string[];
70
+ };
71
+ export type PermissionCatalog = Readonly<Record<string, PermissionResource>>;
72
+ /** Configuration errors of roles and permissions, collected so every problem is reported at once. */
73
+ export declare class AccessConfigurationError extends Error {
74
+ readonly problems: readonly string[];
75
+ constructor(problems: readonly string[]);
76
+ }
77
+ /**
78
+ * Composes the modules' permission declarations into one catalog. A resource has exactly one
79
+ * owning module; a second claim is an error, never resolved by order or merging.
80
+ */
81
+ export declare function composePermissions(declarations: readonly {
82
+ owner: string;
83
+ definition: PermissionsDefinition;
84
+ }[]): PermissionCatalog;
85
+ /**
86
+ * Checks the app's base roles against the catalog: every granted resource and operation must be
87
+ * declared. Returns the problems instead of fixing anything.
88
+ */
89
+ export declare function roleProblems(roles: RolesDefinition, catalog: PermissionCatalog): string[];
90
+ /** Composed, validated access configuration: the permission catalog and the app's base roles. */
91
+ export type AccessConfiguration = {
92
+ readonly permissions: PermissionCatalog;
93
+ readonly roles?: RolesDefinition;
94
+ };
95
+ /** Composes and validates everything at once; throws one error listing every problem. */
96
+ export declare function composeAccessConfiguration(input: {
97
+ permissions: readonly {
98
+ owner: string;
99
+ definition: PermissionsDefinition;
100
+ }[];
101
+ roles?: RolesDefinition;
102
+ }): AccessConfiguration;
103
+ export {};
@@ -0,0 +1,172 @@
1
+ // Roles and permissions as configuration (0.3). Core owns only the vocabulary: the declaration shapes, their
2
+ // validation and the composed catalog. It has no provider dependency, stores nothing and authorizes nothing; an
3
+ // authorization provider (for example the Better Auth adapter) translates the declarations into its own configuration
4
+ // and remains the authority on every check.
5
+ const identifier = /^[a-z][a-zA-Z0-9-]*$/;
6
+ const show = (values) => values.map((value) => `"${value}"`).join(', ');
7
+ /**
8
+ * Declares the resources and operations a plugin owns, in its `permissions.ts`. A plugin declares
9
+ * capabilities only; which roles receive them is the app's decision in `roles.ts`.
10
+ */
11
+ export function definePermissions(permissions) {
12
+ if (!permissions || typeof permissions !== 'object' || Array.isArray(permissions))
13
+ throw new Error("definePermissions expects a record: definePermissions({ content: ['read', 'edit'] }).");
14
+ const resources = Object.keys(permissions);
15
+ if (!resources.length)
16
+ throw new Error('definePermissions needs at least one resource.');
17
+ for (const resource of resources) {
18
+ if (!identifier.test(resource))
19
+ throw new Error(`Invalid permission resource "${resource}". Start with a lowercase letter; use letters, digits and "-".`);
20
+ const actions = permissions[resource];
21
+ if (!Array.isArray(actions) || !actions.length)
22
+ throw new Error(`Permission resource "${resource}" needs a non-empty list of operations.`);
23
+ for (const action of actions)
24
+ if (typeof action !== 'string' || !identifier.test(action))
25
+ throw new Error(`Invalid operation "${String(action)}" of permission resource "${resource}". Start with a lowercase letter; use letters, digits and "-".`);
26
+ if (new Set(actions).size !== actions.length)
27
+ throw new Error(`Permission resource "${resource}" lists an operation twice.`);
28
+ }
29
+ return Object.freeze({
30
+ kind: 'permissions',
31
+ permissions: Object.freeze(Object.fromEntries(resources.map((resource) => [resource, Object.freeze([...permissions[resource]])]))),
32
+ });
33
+ }
34
+ export function isPermissionsDefinition(value) {
35
+ return (!!value && typeof value === 'object' && value.kind === 'permissions');
36
+ }
37
+ export const standardRoles = Object.freeze(['owner', 'admin', 'member']);
38
+ /**
39
+ * Declares the app's base roles in `src/roles.ts`. Roles are app configuration: plugins declare
40
+ * permissions, never roles, and base roles are read-only for organizations.
41
+ */
42
+ export function defineRoles(roles, options = {}) {
43
+ if (!roles || typeof roles !== 'object' || Array.isArray(roles))
44
+ throw new Error("defineRoles expects a record: defineRoles({ viewer: { grants: { content: ['read'] } } }).");
45
+ const ids = Object.keys(roles);
46
+ if (!ids.length)
47
+ throw new Error('defineRoles needs at least one role.');
48
+ const standards = new Map();
49
+ for (const id of ids) {
50
+ if (!identifier.test(id))
51
+ throw new Error(`Invalid role "${id}". Start with a lowercase letter; use letters, digits and "-".`);
52
+ const spec = roles[id];
53
+ if (!spec || typeof spec !== 'object' || Array.isArray(spec))
54
+ throw new Error(`Role "${id}" must be an object, for example { grants: { ... } }.`);
55
+ const unknownKeys = Object.keys(spec).filter((key) => !['standard', 'label', 'description', 'grants'].includes(key));
56
+ if (unknownKeys.length)
57
+ throw new Error(`Role "${id}" has unknown fields ${show(unknownKeys)}. Use standard, label, description and grants.`);
58
+ if (spec.standard !== undefined) {
59
+ if (!standardRoles.includes(spec.standard))
60
+ throw new Error(`Role "${id}" extends unknown standard role "${String(spec.standard)}". Use ${show(standardRoles)}.`);
61
+ const other = standards.get(spec.standard);
62
+ if (other)
63
+ throw new Error(`Roles "${other}" and "${id}" both extend the standard role "${spec.standard}". Each standard role is extended once.`);
64
+ standards.set(spec.standard, id);
65
+ }
66
+ for (const field of ['label', 'description'])
67
+ if (spec[field] !== undefined && (typeof spec[field] !== 'string' || !spec[field].trim()))
68
+ throw new Error(`The ${field} of role "${id}" must be a non-empty text.`);
69
+ if (spec.grants !== undefined) {
70
+ if (!spec.grants || typeof spec.grants !== 'object' || Array.isArray(spec.grants))
71
+ throw new Error(`The grants of role "${id}" must be a record of operation lists.`);
72
+ for (const [resource, actions] of Object.entries(spec.grants)) {
73
+ if (!Array.isArray(actions) || !actions.length)
74
+ throw new Error(`Role "${id}" grants "${resource}" without operations. List them or remove the resource.`);
75
+ if (new Set(actions).size !== actions.length)
76
+ throw new Error(`Role "${id}" grants an operation of "${resource}" twice.`);
77
+ }
78
+ }
79
+ }
80
+ if (options.customRoles !== undefined && typeof options.customRoles !== 'boolean')
81
+ throw new Error('defineRoles: the customRoles option is true or false.');
82
+ return Object.freeze({
83
+ kind: 'roles',
84
+ roles: Object.freeze(Object.fromEntries(ids.map((id) => {
85
+ const spec = roles[id];
86
+ return [
87
+ id,
88
+ Object.freeze({
89
+ ...spec,
90
+ ...(spec.grants
91
+ ? {
92
+ grants: Object.freeze(Object.fromEntries(Object.entries(spec.grants).map(([resource, actions]) => [resource, Object.freeze([...actions])]))),
93
+ }
94
+ : {}),
95
+ }),
96
+ ];
97
+ }))),
98
+ options: Object.freeze({ ...options }),
99
+ });
100
+ }
101
+ export function isRolesDefinition(value) {
102
+ return !!value && typeof value === 'object' && value.kind === 'roles';
103
+ }
104
+ /** Configuration errors of roles and permissions, collected so every problem is reported at once. */
105
+ export class AccessConfigurationError extends Error {
106
+ problems;
107
+ constructor(problems) {
108
+ super(`Roles and permissions are misconfigured:\n- ${problems.join('\n- ')}`);
109
+ this.name = 'AccessConfigurationError';
110
+ this.problems = problems;
111
+ }
112
+ }
113
+ const where = (owner, source) => source ? `"${owner}" (${source})` : `"${owner}"`;
114
+ /**
115
+ * Composes the modules' permission declarations into one catalog. A resource has exactly one
116
+ * owning module; a second claim is an error, never resolved by order or merging.
117
+ */
118
+ export function composePermissions(declarations) {
119
+ const catalog = Object.create(null);
120
+ const problems = [];
121
+ for (const { owner, definition } of declarations) {
122
+ if (!isPermissionsDefinition(definition)) {
123
+ problems.push(`${where(owner, definition?.source)} must default-export definePermissions({ ... }) in permissions.ts.`);
124
+ continue;
125
+ }
126
+ for (const [resource, actions] of Object.entries(definition.permissions)) {
127
+ const claimed = catalog[resource];
128
+ if (claimed) {
129
+ problems.push(`Permission resource "${resource}" is declared by ${where(claimed.owner, claimed.source)} and ${where(owner, definition.source)}. A resource has one owning plugin: rename one resource, or keep it in one plugin and use it from the other.`);
130
+ continue;
131
+ }
132
+ catalog[resource] = Object.freeze({ owner, source: definition.source, actions });
133
+ }
134
+ }
135
+ if (problems.length)
136
+ throw new AccessConfigurationError(problems);
137
+ return Object.freeze(catalog);
138
+ }
139
+ /**
140
+ * Checks the app's base roles against the catalog: every granted resource and operation must be
141
+ * declared. Returns the problems instead of fixing anything.
142
+ */
143
+ export function roleProblems(roles, catalog) {
144
+ const problems = [];
145
+ const file = roles.source ? ` in ${roles.source}` : '';
146
+ const known = Object.keys(catalog);
147
+ for (const [id, spec] of Object.entries(roles.roles)) {
148
+ for (const [resource, actions] of Object.entries((spec.grants ?? {}))) {
149
+ const declared = catalog[resource];
150
+ if (!declared) {
151
+ problems.push(`Role "${id}"${file} grants unknown resource "${resource}". Declared resources: ${known.length ? show(known) : 'none'}. Fix the grant or declare the resource in the owning plugin's permissions.ts.`);
152
+ continue;
153
+ }
154
+ const unknown = actions.filter((action) => !declared.actions.includes(action));
155
+ if (unknown.length)
156
+ problems.push(`Role "${id}"${file} grants unknown operations ${show(unknown)} of "${resource}" (declared by ${where(declared.owner, declared.source)}: ${show(declared.actions)}).`);
157
+ }
158
+ }
159
+ return problems;
160
+ }
161
+ /** Composes and validates everything at once; throws one error listing every problem. */
162
+ export function composeAccessConfiguration(input) {
163
+ const permissions = composePermissions(input.permissions);
164
+ if (input.roles !== undefined && !isRolesDefinition(input.roles))
165
+ throw new AccessConfigurationError([
166
+ `${input.roles?.source ?? 'roles.ts'} must default-export defineRoles({ ... }).`,
167
+ ]);
168
+ const problems = input.roles ? roleProblems(input.roles, permissions) : [];
169
+ if (problems.length)
170
+ throw new AccessConfigurationError(problems);
171
+ return Object.freeze({ permissions, ...(input.roles ? { roles: input.roles } : {}) });
172
+ }
package/dist/runtime.js CHANGED
@@ -1,5 +1,7 @@
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';
4
+ import { AccessConfigurationError, composeAccessConfiguration, isPermissionsDefinition, } from './permissions.js';
3
5
  import { SlotRuntime } from './slots/runtime.js';
4
6
  import { ConfigService } from './config-service.js';
5
7
  import { contributionPath, contributionSource, preserveContributionPath, setContributionPath, } from './contribution-origin.js';
@@ -71,6 +73,10 @@ function normalize(module, appId) {
71
73
  });
72
74
  if (module.settings !== undefined && !isSettingsDefinition(module.settings))
73
75
  throw new Error('settings must be declared with defineSettings({ ... }) in settings.ts.');
76
+ if (module.permissions !== undefined && !isPermissionsDefinition(module.permissions))
77
+ throw new Error('permissions must be declared with definePermissions({ ... }) in permissions.ts.');
78
+ if (!isApp && module.roles !== undefined)
79
+ throw new Error("Base roles belong to the app's src/roles.ts; a plugin declares permissions, never roles.");
74
80
  if (module.parent === id)
75
81
  throw new Error('A plugin cannot be its own parent.');
76
82
  return {
@@ -92,12 +98,38 @@ function normalize(module, appId) {
92
98
  throw attributed(error, id, 'Plugin definition', appId);
93
99
  }
94
100
  }
101
+ /**
102
+ * Roles and permissions are configuration: every module's permissions compose into one catalog
103
+ * and the app's base roles may only grant declared operations. Problems stop the start with one
104
+ * error naming each conflict; nothing is resolved by registration order.
105
+ */
106
+ function validateAccessDeclarations(modules, appId) {
107
+ const app = modules.find((module) => module.id === appId);
108
+ try {
109
+ composeAccessConfiguration({
110
+ permissions: modules
111
+ .filter((module) => module.permissions !== undefined)
112
+ .map((module) => ({ owner: module.id, definition: module.permissions })),
113
+ roles: app?.roles,
114
+ });
115
+ }
116
+ catch (error) {
117
+ if (error instanceof AccessConfigurationError)
118
+ throw new BitaKitStartupError(error.message, appId, {
119
+ app: true,
120
+ cause: error,
121
+ source: app?.roles?.source,
122
+ });
123
+ throw error;
124
+ }
125
+ }
95
126
  /** Installed plugins owned, directly or through other children, by any of `ids`. */
96
127
  function descendantsOf(installed, ids) {
97
128
  const found = [];
98
129
  for (let frontier = [...ids]; frontier.length;) {
99
130
  const children = installed
100
- .filter((plugin) => plugin.parent && frontier.includes(plugin.parent))
131
+ .filter((plugin) => plugin.parent &&
132
+ frontier.includes(resolveName(plugin.parent, installed.map((entry) => entry.id))))
101
133
  .map((plugin) => plugin.id)
102
134
  .filter((id) => !found.includes(id) && !ids.includes(id));
103
135
  found.push(...children);
@@ -106,6 +138,12 @@ function descendantsOf(installed, ids) {
106
138
  return found;
107
139
  }
108
140
  function orderPlugins(plugins, appId) {
141
+ const names = plugins.map((plugin) => plugin.id);
142
+ plugins = plugins.map((plugin) => ({
143
+ ...plugin,
144
+ dependencies: plugin.dependencies?.map((id) => resolveName(id, names)),
145
+ parent: plugin.parent ? resolveName(plugin.parent, names) : undefined,
146
+ }));
109
147
  const remaining = new Map();
110
148
  for (const plugin of plugins) {
111
149
  if (remaining.has(plugin.id))
@@ -223,7 +261,8 @@ export class BitaKitRuntime {
223
261
  /** Initial startup has completed and shutdown has not begun. Updates use owner readiness. */
224
262
  isReady = (plugin) => this.mounted &&
225
263
  (plugin === undefined ||
226
- this.lifecycle.get().plugins.some((entry) => entry.id === plugin && entry.phase === 'ready'));
264
+ this.lifecycle.get().plugins.some((entry) => entry.id ===
265
+ resolveName(plugin, this.modules.map((module) => module.id)) && entry.phase === 'ready'));
227
266
  subscribeReady = (listener) => {
228
267
  this.readinessListeners.add(listener);
229
268
  return () => {
@@ -286,6 +325,7 @@ export class BitaKitRuntime {
286
325
  ];
287
326
  this.order = orderPlugins(this.modules, this.appId);
288
327
  validateSlotDeclarations(this.modules, this.appId);
328
+ validateAccessDeclarations(this.modules, this.appId);
289
329
  this.events = new EventService(config.onEventError);
290
330
  const publishLifecycle = this.events.reserve('runtime');
291
331
  this.lifecycleState = createLifecycleState(this.modules.map((module) => module.id), this.serviceEntries().filter((entry) => !Object.hasOwn(this.providedServices, entry.id)), (snapshot) => publishLifecycle('runtime.lifecycle', snapshot), (error) => this.reportLifecycleError(error));
@@ -537,7 +577,18 @@ export class BitaKitRuntime {
537
577
  return translate;
538
578
  }
539
579
  override(id) {
540
- return this.config.actionOverrides?.[id];
580
+ const overrides = this.config.actionOverrides ?? {};
581
+ const keys = Object.keys(overrides);
582
+ const exact = keys.find((name) => name === id);
583
+ if (exact)
584
+ return overrides[exact];
585
+ const requested = keys.filter((name) => resolveName(name, [
586
+ ...this.modules.flatMap((module) => module.actions.map((action) => action.id)),
587
+ ...Object.keys(this.actions.getState().actions),
588
+ ]) === id);
589
+ if (requested.length > 1)
590
+ throw new Error(`Duplicate action override for "${id}".`);
591
+ return requested.length ? overrides[requested[0]] : undefined;
541
592
  }
542
593
  dialog() {
543
594
  return this.state;
@@ -690,7 +741,7 @@ export class BitaKitRuntime {
690
741
  const interceptors = plugins.flatMap((plugin) => plugin.interceptors ?? []);
691
742
  this.container = createServices(plugins.flatMap((plugin) => plugin.services), this.providedServices, (definition) => this.configuration.context(owners.get(definition) ??
692
743
  this.modules.find((module) => module.services.includes(definition))?.id ??
693
- this.appId), serviceObserver(interceptors, (id) => this.aliasesOf(id), () => this.view), this.events, {
744
+ this.appId), serviceObserver(interceptors, (id) => this.aliasesOf(id), () => this.view, () => this.names.names()), this.events, {
694
745
  names: this.names,
695
746
  appId: this.appId,
696
747
  moduleOf: (definition) => owners.get(definition) ??
@@ -891,6 +942,9 @@ export class BitaKitRuntime {
891
942
  module: plugin.id,
892
943
  app: plugin.id === this.appId,
893
944
  services: this.services,
945
+ config: this.configuration.context(plugin.id),
946
+ events: this.pluginEvents.get(plugin.id).events,
947
+ settings: this.settingsAccess,
894
948
  });
895
949
  if (cleanup)
896
950
  this.scopes[index].own(cleanup);
@@ -927,7 +981,7 @@ export class BitaKitRuntime {
927
981
  catch (error) {
928
982
  throw this.attribute(error, module, 'Interceptor', requester.source);
929
983
  }
930
- const applies = (id) => matchesTarget(definition.action ?? '*', id) &&
984
+ const applies = (id) => matchesTarget(definition.action ?? '*', id, Object.keys(this.actions.getState().actions)) &&
931
985
  (global || this.actionConfigs.get(id)?.module === module);
932
986
  const context = (base) => ({
933
987
  ...base,
@@ -1142,7 +1196,7 @@ export class BitaKitRuntime {
1142
1196
  const disabled = new Set(this.disabledPlugins);
1143
1197
  const ids = operation === 'add'
1144
1198
  ? values.map((plugin) => plugin.id)
1145
- : [...values];
1199
+ : values.map((id) => resolveName(id, installed.map((plugin) => plugin.id)));
1146
1200
  if (new Set(ids).size !== ids.length)
1147
1201
  return result('blocked', ['Plugin IDs must be unique.']);
1148
1202
  if (ids.includes(this.appId))
@@ -1180,7 +1234,10 @@ export class BitaKitRuntime {
1180
1234
  cascaded.set(parent, children.filter((child) => !ids.includes(child)));
1181
1235
  if (operation === 'enable')
1182
1236
  for (const id of [...ids]) {
1183
- const parent = installed.find((plugin) => plugin.id === id)?.parent;
1237
+ const declaredParent = installed.find((plugin) => plugin.id === id)?.parent;
1238
+ const parent = declaredParent
1239
+ ? resolveName(declaredParent, installed.map((plugin) => plugin.id))
1240
+ : undefined;
1184
1241
  if (parent && disabled.has(parent) && !ids.includes(parent))
1185
1242
  return result('blocked', [
1186
1243
  `Plugin "${id}" belongs to "${parent}", which is disabled. Enable "${parent}" first.`,
@@ -1234,7 +1291,8 @@ export class BitaKitRuntime {
1234
1291
  disabled.delete(id);
1235
1292
  if (operation === 'disable')
1236
1293
  changed = changed.filter((id) => !this.disabledPlugins.has(id));
1237
- const protectedOwners = changed.filter((id) => options?.preserve?.includes(id));
1294
+ const preserved = options?.preserve?.map((id) => resolveName(id, installed.map((plugin) => plugin.id))) ?? [];
1295
+ const protectedOwners = changed.filter((id) => preserved.includes(id));
1238
1296
  if ((operation === 'disable' || operation === 'remove' || operation === 'replace') &&
1239
1297
  protectedOwners.length)
1240
1298
  return result('blocked', ['The host requires these plugins to remain enabled.'], 'protected', protectedOwners);
@@ -1257,6 +1315,7 @@ export class BitaKitRuntime {
1257
1315
  const declarations = [app, ...nextInstalled.map((plugin) => normalize(plugin, this.appId))];
1258
1316
  orderPlugins(all, this.appId);
1259
1317
  validateSlotDeclarations(declarations, this.appId);
1318
+ validateAccessDeclarations(all, this.appId);
1260
1319
  validatePluginPages(all, layoutFamilies(all));
1261
1320
  // Failed updates may have already disposed a projection's scope. Recover its recorded
1262
1321
  // failure cohort when the host retries one of those owners, without restarting other failures.
@@ -1409,6 +1468,7 @@ export class BitaKitRuntime {
1409
1468
  ];
1410
1469
  orderPlugins(all, this.appId);
1411
1470
  validateSlotDeclarations(all, this.appId);
1471
+ validateAccessDeclarations(all, this.appId);
1412
1472
  validatePluginPages(all, layoutFamilies(all));
1413
1473
  // A projection that captured the composition is an explicit consumer of every revision.
1414
1474
  affected = updateClosure(all, [