@bitakit/core 0.2.4 → 0.2.6

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 ADDED
@@ -0,0 +1,46 @@
1
+ # @bitakit/core — guide for agents
2
+
3
+ > For agents building an app with this package (it ships in `node_modules/@bitakit/core`). To
4
+ > change the package itself, follow the repository's own AGENTS.md instead.
5
+
6
+ The framework-independent runtime: plugins, services, Actions, events, settings, slots,
7
+ interceptors and configuration. It has no React; React bindings are in `@bitakit/ui`. Apps
8
+ rarely call the runtime directly: files in `src/plugins/<id>/` are discovered, and the
9
+ `bitakit-app-development` skill has a recipe for each kind.
10
+
11
+ ## The define helpers (import from `@bitakit/core`)
12
+
13
+ | File (in a plugin) | Helper | ID |
14
+ | ------------------------ | -------------------------------------------------------------- | ------------------ |
15
+ | `services/<name>.ts` | `defineService(({ store, events, settings, onStart }) => ...)` | `<plugin>.<name>` |
16
+ | `actions/<name>.ts` | `defineAction({ title, enabled, execute, ... })` | `<plugin>.<name>` |
17
+ | `events.ts` | `defineEvents({ changed: event<T>() })` | `<plugin>.changed` |
18
+ | `settings.ts` | `defineSettings({ name: setting({ default }) }, page)` | `<plugin>.<name>` |
19
+ | `slots/<name>.ts` | `defineSlot({ accepts, policy?, payload? })` | `<plugin>.<name>` |
20
+ | `interceptors/<name>.ts` | `defineInterceptor({ action, before, after })` | — |
21
+ | `configs/<name>.ts` | `defineConfig({ defaults, schema? })` | `<plugin>.<name>` |
22
+ | `setup.ts` | `Setup` function (`scope.slots.attach`, cleanup) | — |
23
+
24
+ ## Slots and replaceable parts
25
+
26
+ - `policy: 'list'` (default): every contribution renders. `'keyed'`: outlets pick one by key.
27
+ - `policy: 'single'`: a replaceable part. Several plugins may offer a candidate; one renders:
28
+ the app's `choose` entry in `bitakit.config.ts`, else the app's own contribution, else the
29
+ only candidate; a tie renders the owner's default. `selectSingle(candidates, { choice, appId })`
30
+ is the rule, exported for tools.
31
+ - Layout families are `single` slots named `layout.<family>`; screens such as
32
+ `screen.not-found` are `single` slots too.
33
+
34
+ ## Testing
35
+
36
+ `mountPlugin(folder, { plugins, services })` from `@bitakit/core/testing` discovers and starts
37
+ one plugin under Node (no browser); `plugin.execute(id, input)` resolves to the outcome
38
+ (`completed` or `skipped`) and rejects on failure; `plugin.events.recorded` lists emitted events.
39
+
40
+ ## Rules
41
+
42
+ - One `defineAction` shape; state belongs in a service `store()`, replaced with `state.set`.
43
+ - Reading a missing service throws; list other plugins' services in `requires`, or check
44
+ `app.has(name)` for optional ones.
45
+ - Only the declaring plugin emits its events; others listen.
46
+ - `enabled`, `visible` and interceptors are client rules; authorize on the server.
package/CLAUDE.md ADDED
@@ -0,0 +1 @@
1
+ @AGENTS.md
package/dist/core.d.ts CHANGED
@@ -31,7 +31,7 @@ export { resolveContribution, fallbackTitle } from './conventions.js';
31
31
  export { ConfirmationController, type Confirmation } from './confirmation.js';
32
32
  export * from './contracts.js';
33
33
  export { resolveText, createTranslationPlugin } from './translation.js';
34
- export { findPluginPage, validatePluginPages, pluginPage, pluginSlot, pluginProvider, pluginSettingsPage, pluginLayout, } from './pages.js';
34
+ export { findPluginPage, validatePluginPages, pluginPage, pluginSlot, pluginProvider, pluginSettingsPage, pluginLayout, layoutSlots, layoutFamilies, type LayoutSlot, } from './pages.js';
35
35
  export { destinationMetadata, type Destination, type DestinationKind } from './destinations.js';
36
36
  export * from './actions/core.js';
37
37
  export { pluginMetadata } from './metadata.js';
@@ -42,6 +42,7 @@ export type * from './slots/define.js';
42
42
  export type * from './slots/types.js';
43
43
  export type { ActionSlotPlacement } from './slots/action-placement.js';
44
44
  export { SlotError } from './slots/runtime.js';
45
+ export { selectSingle, candidateNames, type SingleSelection } from './slots/select.js';
45
46
  export { configureAuthPaths, resolveAuthReturnTo, authSignInHref, type AuthPaths, type AuthSignInOptions, } from './auth-navigation.js';
46
47
  export type { PluginUpdateResult, PluginChangeResult, PluginDependentOptions, PluginChangeOptions, PluginToggleRequest, PluginChangePreview, PluginChangeReason, } from './lifecycle/reconcile.js';
47
48
  export { createInventory, inspectRuntime, observeRuntimeInventory, inventoryMetadata, } from './inspection/inventory.js';
package/dist/core.js CHANGED
@@ -21,12 +21,13 @@ export { resolveContribution, fallbackTitle } from './conventions.js';
21
21
  export { ConfirmationController } from './confirmation.js';
22
22
  export * from './contracts.js';
23
23
  export { resolveText, createTranslationPlugin } from './translation.js';
24
- export { findPluginPage, validatePluginPages, pluginPage, pluginSlot, pluginProvider, pluginSettingsPage, pluginLayout, } from './pages.js';
24
+ export { findPluginPage, validatePluginPages, pluginPage, pluginSlot, pluginProvider, pluginSettingsPage, pluginLayout, layoutSlots, layoutFamilies, } from './pages.js';
25
25
  export { destinationMetadata } from './destinations.js';
26
26
  export * from './actions/core.js';
27
27
  export { pluginMetadata } from './metadata.js';
28
28
  export * from './discovered.js';
29
29
  export { defineSlot, isSlotDefinition } from './slots/define.js';
30
30
  export { SlotError } from './slots/runtime.js';
31
+ export { selectSingle, candidateNames } from './slots/select.js';
31
32
  export { configureAuthPaths, resolveAuthReturnTo, authSignInHref, } from './auth-navigation.js';
32
33
  export { createInventory, inspectRuntime, observeRuntimeInventory, inventoryMetadata, } from './inspection/inventory.js';
@@ -326,6 +326,11 @@ export type BitaKitRuntimeConfig = Omit<Plugin, 'id' | 'dependencies' | 'parent'
326
326
  enabled?: boolean;
327
327
  visible?: boolean;
328
328
  }>>;
329
+ /**
330
+ * The occupant of each `single` slot the app decides, by slot ID: `<plugin>`, `<plugin>:<key>`
331
+ * or `<key>` of a contribution. From `choose` in bitakit.config.ts; see `selectSingle`.
332
+ */
333
+ choose?: Readonly<Record<string, string>>;
329
334
  plugins?: readonly Plugin[];
330
335
  };
331
336
  /** A literal string wins; a widened `string` or a missing value falls back. */
package/dist/pages.d.ts CHANGED
@@ -32,8 +32,32 @@ type Exported<T> = {
32
32
  export declare function pluginPage(module: Exported<unknown>, path: string): PluginPageDefinition;
33
33
  /** A slot view from `ui/slots/<slot>.tsx`. */
34
34
  export declare function pluginSlot(module: Exported<unknown>, slot: string, source?: string): PluginView;
35
- /** A layout from `src/layouts/<name>.tsx`: the default export wraps pages that name it. */
36
- export declare function pluginLayout(module: Exported<unknown>): PresentationType<'component'>;
35
+ /**
36
+ * A layout file, `src/layouts/<family>[/<variant>].tsx` or a plugin's `ui/layouts/...`: a
37
+ * candidate for the `layout.<family>` slot whose key is the variant (`default` for a flat file).
38
+ * Its default export wraps the pages that name the family.
39
+ */
40
+ export declare function pluginLayout(module: Exported<unknown>, family: string, variant?: string, source?: string): PluginView;
41
+ /** The declaration of a layout family: a replaceable component part that wraps pages. */
42
+ export type LayoutSlot = Readonly<{
43
+ kind: 'slot';
44
+ accepts: 'component';
45
+ policy: 'single';
46
+ conflict: 'error';
47
+ }>;
48
+ /** App-owned declarations for layout families that only layout files name (generated by discovery). */
49
+ export declare function layoutSlots(families: readonly string[]): (LayoutSlot & {
50
+ id: string;
51
+ })[];
52
+ /** The layout families pages may name: declared `layout.<family>` slots and legacy app layouts. */
53
+ export declare function layoutFamilies(modules: readonly {
54
+ slots: readonly {
55
+ id: string;
56
+ }[];
57
+ ui?: {
58
+ layouts?: object;
59
+ };
60
+ }[]): ReadonlySet<string>;
37
61
  /** The settings page from `ui/settings/page.tsx`; it replaces the generated page of the plugin. */
38
62
  export declare function pluginSettingsPage(module: Exported<unknown>): PluginSettingsPage;
39
63
  /** A React provider from `ui/providers/<name>.tsx`. */
package/dist/pages.js CHANGED
@@ -2,6 +2,7 @@ import { setContributionSource } from './contribution-origin.js';
2
2
  import { BitaKitStartupError } from './startup-error.js';
3
3
  /** Exact, canonical paths only. Routers remain responsible for dynamic parameters. */
4
4
  export function validatePluginPages(plugins, layouts = new Set()) {
5
+ const known = [...layouts].sort();
5
6
  const owners = new Map();
6
7
  for (const plugin of plugins) {
7
8
  for (const page of plugin.pages ?? []) {
@@ -9,7 +10,7 @@ export function validatePluginPages(plugins, layouts = new Set()) {
9
10
  page.layout !== 'app' &&
10
11
  page.layout !== 'blank' &&
11
12
  !layouts.has(page.layout))
12
- throw new BitaKitStartupError(`Page ${page.path} of plugin "${plugin.id}" names layout "${page.layout}", but src/layouts/${page.layout}.tsx does not exist.${layouts.size ? ` Known layouts: ${[...layouts].join(', ')}.` : ''} Use "app", "blank" or an existing layout.`, plugin.id);
13
+ throw new BitaKitStartupError(`Page ${page.path} of plugin "${plugin.id}" names layout "${page.layout}", but no layout family "${page.layout}" exists. Add src/layouts/${page.layout}.tsx (or src/layouts/${page.layout}/<variant>.tsx), or a plugin's ui/layouts/${page.layout}.tsx.${known.length ? ` Known layouts: ${known.join(', ')}.` : ''} Use "app", "blank" or an existing layout.`, plugin.id);
13
14
  if (!/^\/(?:(?:[a-zA-Z0-9_-]+|\[[a-zA-Z0-9_-]+\])(?:\/(?:[a-zA-Z0-9_-]+|\[[a-zA-Z0-9_-]+\]))*)?$/.test(page.path))
14
15
  throw new BitaKitStartupError(`Invalid plugin page path "${page.path}" in plugin "${plugin.id}". Use a root-relative path such as /todos.`, plugin.id);
15
16
  const owner = owners.get(page.path);
@@ -80,9 +81,42 @@ export function pluginSlot(module, slot, source) {
80
81
  setContributionSource(view, source);
81
82
  return view;
82
83
  }
83
- /** A layout from `src/layouts/<name>.tsx`: the default export wraps pages that name it. */
84
- export function pluginLayout(module) {
85
- return module.default;
84
+ /**
85
+ * A layout file, `src/layouts/<family>[/<variant>].tsx` or a plugin's `ui/layouts/...`: a
86
+ * candidate for the `layout.<family>` slot whose key is the variant (`default` for a flat file).
87
+ * Its default export wraps the pages that name the family.
88
+ */
89
+ export function pluginLayout(module, family, variant = 'default', source) {
90
+ const view = {
91
+ slot: `layout.${family}`,
92
+ key: variant,
93
+ component: module.default,
94
+ };
95
+ if (source)
96
+ setContributionSource(view, source);
97
+ return view;
98
+ }
99
+ /** App-owned declarations for layout families that only layout files name (generated by discovery). */
100
+ export function layoutSlots(families) {
101
+ return families.map((family) => Object.freeze({
102
+ kind: 'slot',
103
+ accepts: 'component',
104
+ policy: 'single',
105
+ conflict: 'error',
106
+ id: `layout.${family}`,
107
+ }));
108
+ }
109
+ /** The layout families pages may name: declared `layout.<family>` slots and legacy app layouts. */
110
+ export function layoutFamilies(modules) {
111
+ const families = new Set();
112
+ for (const module of modules) {
113
+ for (const slot of module.slots)
114
+ if (slot.id.startsWith('layout.'))
115
+ families.add(slot.id.slice('layout.'.length));
116
+ for (const name of Object.keys(module.ui?.layouts ?? {}))
117
+ families.add(name);
118
+ }
119
+ return families;
86
120
  }
87
121
  /** The settings page from `ui/settings/page.tsx`; it replaces the generated page of the plugin. */
88
122
  export function pluginSettingsPage(module) {
package/dist/runtime.js CHANGED
@@ -5,7 +5,7 @@ import { ConfigService } from './config-service.js';
5
5
  import { contributionPath, contributionSource, preserveContributionPath, setContributionPath, } from './contribution-origin.js';
6
6
  import { ServiceNames } from './service-names.js';
7
7
  import { BitaKitStartupError, isBitaKitStartupError, moduleLabel } from './startup-error.js';
8
- import { findPluginPage, validatePluginPages } from './pages.js';
8
+ import { findPluginPage, layoutFamilies, validatePluginPages } from './pages.js';
9
9
  import { projectedDestination } from './destinations.js';
10
10
  import { resolveText } from './translation.js';
11
11
  import { ActionGroup, createActionList, } from '@bitakit/core/actions';
@@ -312,7 +312,7 @@ export class BitaKitRuntime {
312
312
  catch (error) {
313
313
  throw attributed(error, this.appId, 'Configuration', this.appId);
314
314
  }
315
- validatePluginPages(this.modules, new Set(Object.keys(this.modules.find((module) => module.id === this.appId)?.ui?.layouts ?? {})));
315
+ validatePluginPages(this.modules, layoutFamilies(this.modules));
316
316
  const groups = config.groups ?? [];
317
317
  const duplicate = groups.find((id, index) => groups.indexOf(id) !== index);
318
318
  if (duplicate)
@@ -1228,7 +1228,7 @@ export class BitaKitRuntime {
1228
1228
  const declarations = [app, ...nextInstalled.map((plugin) => normalize(plugin, this.appId))];
1229
1229
  orderPlugins(all, this.appId);
1230
1230
  validateSlotDeclarations(declarations, this.appId);
1231
- validatePluginPages(all, new Set(Object.keys(app.ui?.layouts ?? {})));
1231
+ validatePluginPages(all, layoutFamilies(all));
1232
1232
  // Failed updates may have already disposed a projection's scope. Recover its recorded
1233
1233
  // failure cohort when the host retries one of those owners, without restarting other failures.
1234
1234
  const lifecycle = this.lifecycle.get();
@@ -1380,7 +1380,7 @@ export class BitaKitRuntime {
1380
1380
  ];
1381
1381
  orderPlugins(all, this.appId);
1382
1382
  validateSlotDeclarations(all, this.appId);
1383
- validatePluginPages(all, new Set(Object.keys(all[0].ui?.layouts ?? {})));
1383
+ validatePluginPages(all, layoutFamilies(all));
1384
1384
  // A projection that captured the composition is an explicit consumer of every revision.
1385
1385
  affected = updateClosure(all, [
1386
1386
  ...changed,
@@ -1,5 +1,10 @@
1
1
  import type { InputSchema, SchemaOutput, EffectiveActionId } from '../definitions.js';
2
2
  import type { SlotMap } from '../presentation.js';
3
+ /**
4
+ * `list`: every contribution renders, sorted by `order`. `single`: a replaceable part; several
5
+ * contributors may offer a candidate and outlets render the one `selectSingle` picks, or the
6
+ * owner's fallback. `keyed`: contributions need unique keys and an outlet picks one by key.
7
+ */
3
8
  export type SlotPolicy = 'list' | 'single' | 'keyed';
4
9
  /** Payload is supplied by the owner; schema describes contributed data, not UI. */
5
10
  export type SlotOptions = {
@@ -154,10 +154,13 @@ export class SlotRuntime {
154
154
  (typeof contribution.key !== 'string' || !contribution.key))
155
155
  throw error('invalid-contribution', 'a keyed slot requires a non-empty key.');
156
156
  const id = `${plugin}:${contribution.id ?? ++this.serial}`;
157
+ // A single slot collects candidates from several contributors; outlets select one.
157
158
  for (const current of this.attachments)
158
159
  if (current.slot === name &&
159
160
  (current.id === id ||
160
- definition.policy === 'single' ||
161
+ (definition.policy === 'single' &&
162
+ current.plugin === plugin &&
163
+ current.key === contribution.key) ||
161
164
  (definition.policy === 'keyed' && current.key === contribution.key)))
162
165
  throw error('conflict', `contribution "${id}" conflicts with "${current.id}"; remove it explicitly first.`);
163
166
  let resolve, reject;
@@ -0,0 +1,23 @@
1
+ import type { SlotItem } from './types.js';
2
+ /**
3
+ * The result of selecting the occupant of a `single` slot. `reason` explains why no candidate
4
+ * was selected: several candidates without a decision (`ambiguous`), or a choice that names no
5
+ * available candidate (`choice-unavailable`). Without candidates, both are absent.
6
+ */
7
+ export type SingleSelection<T extends Pick<SlotItem, 'plugin' | 'key'> = SlotItem> = Readonly<{
8
+ selected?: T;
9
+ reason?: 'ambiguous' | 'choice-unavailable';
10
+ candidates: readonly T[];
11
+ }>;
12
+ /** The names a choice may use for a candidate: `<plugin>`, `<plugin>:<key>` and `<key>`. */
13
+ export declare function candidateNames(item: Pick<SlotItem, 'plugin' | 'key'>): readonly string[];
14
+ /**
15
+ * Selects the occupant of a `single` slot from its eligible candidates. The app's choice wins
16
+ * (`choose` in bitakit.config.ts), then a contribution of the app itself, then the only
17
+ * candidate. Several candidates without a decision select none, so owners render their default
18
+ * instead of an arbitrary contribution.
19
+ */
20
+ export declare function selectSingle<T extends Pick<SlotItem, 'plugin' | 'key'>>(candidates: readonly T[], options: {
21
+ choice?: string;
22
+ appId: string;
23
+ }): SingleSelection<T>;
@@ -0,0 +1,25 @@
1
+ /** The names a choice may use for a candidate: `<plugin>`, `<plugin>:<key>` and `<key>`. */
2
+ export function candidateNames(item) {
3
+ return item.key === undefined
4
+ ? [item.plugin]
5
+ : [item.plugin, `${item.plugin}:${item.key}`, item.key];
6
+ }
7
+ /**
8
+ * Selects the occupant of a `single` slot from its eligible candidates. The app's choice wins
9
+ * (`choose` in bitakit.config.ts), then a contribution of the app itself, then the only
10
+ * candidate. Several candidates without a decision select none, so owners render their default
11
+ * instead of an arbitrary contribution.
12
+ */
13
+ export function selectSingle(candidates, options) {
14
+ if (options.choice !== undefined) {
15
+ const matches = candidates.filter((item) => candidateNames(item).includes(options.choice));
16
+ if (matches.length === 1)
17
+ return { selected: matches[0], candidates };
18
+ return { reason: matches.length ? 'ambiguous' : 'choice-unavailable', candidates };
19
+ }
20
+ const own = candidates.filter((item) => item.plugin === options.appId);
21
+ const pool = own.length ? own : candidates;
22
+ if (pool.length === 1)
23
+ return { selected: pool[0], candidates };
24
+ return pool.length ? { reason: 'ambiguous', candidates } : { candidates };
25
+ }
package/package.json CHANGED
@@ -1,11 +1,13 @@
1
1
  {
2
2
  "name": "@bitakit/core",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "files": [
7
7
  "dist",
8
8
  "README.md",
9
+ "AGENTS.md",
10
+ "CLAUDE.md",
9
11
  "assets",
10
12
  "discovery",
11
13
  "examples",
@@ -51,7 +53,7 @@
51
53
  }
52
54
  },
53
55
  "devDependencies": {
54
- "@bitakit/discovery": "^0.2.2",
56
+ "@bitakit/discovery": "^0.2.4",
55
57
  "jiti": "^2.7.0",
56
58
  "typescript": "^5.9.3"
57
59
  },