@bitakit/core 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +137 -337
  2. package/discovery/generate.mjs +2 -8
  3. package/dist/actions/action-list.d.ts +1 -1
  4. package/dist/actions/action-list.js +53 -4
  5. package/dist/actions/action.d.ts +3 -3
  6. package/dist/actions/types.d.ts +4 -0
  7. package/dist/app/access.js +2 -1
  8. package/dist/app/service-aliases.d.ts +4 -0
  9. package/dist/app/service-aliases.js +14 -0
  10. package/dist/app/types.d.ts +12 -1
  11. package/dist/auth-navigation.d.ts +13 -0
  12. package/dist/auth-navigation.js +33 -0
  13. package/dist/contracts.d.ts +5 -0
  14. package/dist/contributions/command.js +9 -0
  15. package/dist/contributions/index.d.ts +1 -0
  16. package/dist/core.d.ts +4 -0
  17. package/dist/core.js +2 -0
  18. package/dist/definitions.d.ts +30 -4
  19. package/dist/discovered.d.ts +9 -5
  20. package/dist/discovered.js +3 -2
  21. package/dist/events/action-setup.d.ts +19 -0
  22. package/dist/events/action-setup.js +24 -0
  23. package/dist/events/service.d.ts +18 -0
  24. package/dist/events/service.js +98 -0
  25. package/dist/events/types.d.ts +19 -0
  26. package/dist/events/types.js +1 -0
  27. package/dist/replacements.d.ts +1 -1
  28. package/dist/runtime.d.ts +2 -0
  29. package/dist/runtime.js +18 -2
  30. package/dist/service-key.d.ts +6 -0
  31. package/dist/service-key.js +0 -1
  32. package/dist/services.d.ts +2 -1
  33. package/dist/services.js +5 -1
  34. package/docs/auth.md +106 -0
  35. package/docs/events.md +157 -0
  36. package/docs/file-contributions.md +13 -0
  37. package/docs/reference.md +404 -0
  38. package/docs/todo-tutorial.md +88 -0
  39. package/examples/todos/actions/create.mjs +7 -0
  40. package/examples/todos/actions/delete.mjs +14 -0
  41. package/examples/todos/actions/list.mjs +7 -0
  42. package/examples/todos/plugin.mjs +11 -0
  43. package/examples/todos/services/tasks.mjs +30 -0
  44. package/examples/todos.mjs +17 -0
  45. package/package.json +4 -2
package/README.md CHANGED
@@ -1,382 +1,182 @@
1
- # @bitakit/core
1
+ # BitaKit Core
2
2
 
3
- ## Public app access and installed plugins
3
+ **Give your application a shared home for plugins, services, and actions.**
4
4
 
5
- Local plugins need only their contribution files:
5
+ `@bitakit/core` coordinates how features start, work together, and stop. It runs
6
+ without React, a browser, or a particular router. Your application still owns its
7
+ pages, interface, business rules, and data storage.
6
8
 
7
- ```text
8
- src/plugins/documents/
9
- services/documents.ts
10
- actions/create.ts
11
- ```
12
-
13
- Each immediate plugin folder supplies its default plugin ID. `plugin.config.ts` is
14
- optional. `defineService({ create: () => ({ ... }) })` infers its public name from the
15
- relative service path; `defineAction({ execute: ({ app }) => ... })` infers its ID
16
- from the plugin ID and action path. Explicit `id` values override these defaults.
17
- Discovery generates registration and types, including service method inputs and outputs.
18
-
19
- Use `app.services.documents` and `app.actions.documents.create.execute()`. Action references
20
- delegate to the existing ActionList, preserving execution guards and lifecycle behavior.
21
- Internal actions stay out of enumeration. React ActionButton, ActionBinding and useAction
22
- accept these references; a reference must belong to the same provider's ActionList.
23
-
24
- `app.config.<plugin>.<path>` reads the immutable resolved configuration snapshot, including
25
- host overrides. `defineConfig({ defaults: { pageSize: 20 } })` works without a schema;
26
- optional schemas retain their parse contract. Low-level scoped reads remain available through
27
- `runtime.configuration` and the existing action/service config context.
28
- Optional packages can project instance-local facades through `appExtensions` and augment
29
- `AppExtensionMap`. Core owns no Settings implementation or duplicate state.
30
-
31
- Plugins publish selected existing service keys through `publicServices`. Public names must be unique within the service namespace.
32
-
33
- ```ts
34
- const documents = serviceKey<Documents>('editor.documents');
35
- export default function documentsPlugin() {
36
- return definePlugin({
37
- id: 'documents',
38
- publicServices: { documents },
39
- services: [provideService(documents, { create: () => createDocumentsService() })],
40
- });
41
- }
42
- ```
43
-
44
- `runtime.app.services.documents` resolves that same container instance. Required access reports
45
- FoundationServiceError (`code`, `service`, `reason`, optional `plugin`) when unavailable.
46
- `app.optional.services.documents` returns undefined before mount or when unavailable. After mount,
47
- `app.ready` is true; disposal makes optional reads unavailable again. Obtaining a service
48
- does not subscribe to its data. Existing dependency checks and reverse cleanup still apply.
49
- Do not cache service instances across runtime replacement.
50
-
51
- The React hook `useFoundationApp` lives in UI and follows readiness; Core remains usable
52
- without React. Its default public contract is generated from local contributions and installed opt-in plugins.
53
- Manual typed compositions use `FoundationApp<PublicServicesOf<typeof plugins>>` or the
54
- corresponding hook generic. Keep precise factory return types instead of widening them to
55
- `Plugin` if callers need public-service completion.
56
-
57
- A package can opt into discovery with public package exports and metadata:
58
-
59
- ```json
60
- {
61
- "exports": {
62
- "./package.json": "./package.json",
63
- "./foundation": "./dist/foundation.js"
64
- },
65
- "foundation": { "plugin": "./foundation" }
66
- }
67
- ```
68
-
69
- The plugin entry default-exports a synchronous factory returning one Plugin. By default it
70
- receives no arguments. Optional metadata `"configuration": "shell"` passes that path from the
71
- resolved root app config (including defaults and app overrides), or `{}` when absent. It describes services/providers; it must not acquire external resources at factory
72
- time. Core owns their creation and cleanup. Direct dependencies and optionalDependencies
73
- are considered; transitive and development dependencies are not automatically activated.
74
- Only packages exposing their package.json and explicit Foundation metadata participate.
75
- `foundation.config.ts` can disable all package contributions with `packages: false`, or
76
- individual packages with `packages: { 'package-name': false }`.
77
-
78
- An optional `foundation.discovery` export default-exports a Node-safe function returning
79
- contribution kind descriptors. Explicit `kinds` overrides replace package defaults by name.
80
- Client plugin factories are never executed by build discovery; these discovery adapters
81
- are trusted build code. Removing/disabling a package removes its generated import and types.
82
- Local source discovery continues through the same existing pipeline.
83
-
84
- Source responsibilities: `app/types.ts` owns public typing, `app/access.ts` projects current
85
- services, and `app/service-error.ts` owns diagnostics. `discovery/packages.mjs` reads opt-in
86
- metadata; `discovery/generate.mjs` emits imports and app types. None is a second runtime registry.
87
-
88
- Framework-independent Actions, plugin lifecycle and services. React bindings live in the separate @bitakit/ui package. Import general APIs from `@bitakit/core` and UI APIs from `@bitakit/ui`. This package does not create another ActionProvider, settings store, router, authentication session, or API client.
89
-
90
- The shared filename grammar, configuration service, migration rules and current limits are documented in [File contributions and config](docs/file-contributions.md).
91
-
92
- ## Small plugin
93
-
94
- ```ts
95
- // actions/invite.form-action.ts
96
- import { defineFormAction } from '@bitakit/core';
97
-
98
- export default defineFormAction({
99
- groups: ['userManagement.dropdownMenu'],
100
- requires: ['users'],
101
- fields: {
102
- email: { type: 'email', required: true },
103
- },
104
- async submit(values, { services }) {
105
- return services.users.invite(values);
106
- },
107
- });
108
- ```
109
-
110
- File discovery infers `users.invite` from the plugin ID and relative action filename. Standalone React configs supply an explicit `id`, or call `resolveContribution(definition, inferredId)` in their own build integration. No setup file is needed for declarative groups. Groups are created on first use; a central group catalog is optional. Explicit typed ActionGroup objects remain supported. A group does not create UI: bind a menu to its ID.
111
-
112
- ```tsx
113
- <ActionMenu group="userManagement.dropdownMenu" label="User actions" />
114
- ```
115
-
116
- Optional `setup` runs after all selected plugins' actions are registered. Its scoped facade tracks registrations and placements; no manual cleanup is required for `getGroup().add()` or `attach()`. It can return cleanup for its own external subscriptions. Async setup is intentionally unsupported. Invalid group IDs, duplicate action IDs and missing/cyclic dependencies fail explicitly. Failed setup rolls back the contributions already installed.
117
-
118
- `add()` accepts a core ActionDefinition. Declarative forms/dialogs are supplied in the plugin's `actions` contribution array (or discovered by the Next adapter); use `attach()` for their placements. `attach()` adds a placement without changing the action's global order. Set `order` on the action definition when ordering matters.
119
-
120
- ## Optional conventions
121
-
122
- Explicit properties win over conventions. A definition with `id: 'custom.invite'` keeps that ID even if its file moves. With no `title`, the default key is `<id>.title`; each field uses `<id>.fields.<name>`. `title`, `description` and field `label` accept a translation key when present in the current catalog, otherwise literal text. There are no separate action key properties. Button, menu, dialog heading and submit button read the same action title; the dialog reads its action description. Missing labels fall back to a readable ID/field name. Supply a translator with `has(key)` (such as next-intl's translator) to avoid querying missing keys.
123
-
124
- `success` and `failure` each accept a literal string, `{ messageKey, values? }`, `{ message }`, a synchronous callback returning any of these, or `false`. Absent feedback, `false`, empty messages and callback `undefined` are silent. Success callbacks receive `{ result, input, services }`; failure callbacks receive `{ error, input, services }`. Results retain the inferred return type of `submit`/`execute`; errors are `unknown` and should be narrowed before use. Feedback callbacks are for presentation and cannot reverse an already completed operation if they throw.
125
-
126
- There are no inferred outcome messages. Explicit `messageKey` and `values` use the current translator; literal strings remain literal. Raw errors are never used as display text.
127
-
128
- ```ts
129
- success: ({ result }) => ({
130
- messageKey: 'users.invite.created',
131
- values: { invitationId: result.invitationId },
132
- }),
133
- failure: ({ error }) => error instanceof InviteLimitError
134
- ? { messageKey: 'users.invite.limit' }
135
- : undefined, // default failure text
136
- ```
137
-
138
- `success: false` hides the success message; forms still close. Set `closeOnSuccess: false` to keep the form open. Existing `{ closeDialog: false, messageKey: '...' }` feedback is also supported; `closeOnSuccess` wins when both are supplied. `failure: false` leaves a failed form open silently. Opening a form/dialog never displays a success message. Commands report through the provider's `notify`; forms do so on the normal submission path, including custom render's `submit` function. The low-level `<id>.submit` action is an internal execution primitive; programmatic consumers should use `runtime.submitForm(runtime.getSnapshot().definition, values)` for the full form flow.
139
-
140
- Set `conventions: false` on an action to require explicit ID/title and disable inferred field keys. Explicit messages and groups still work. The Next discovery config offers the same switch globally; an action can override it. Core actions registered directly in the ActionList remain unchanged.
9
+ BitaKit is a composition layer alongside frameworks such as Next.js and TanStack
10
+ Start, not a replacement for them. Its explicit plugin, service, and action
11
+ conventions give people and AI coding assistants a shared structure to work with.
141
12
 
142
- Command failures throw `ActionFailure`: `feedback` contains the selected string or `false`, and `cause` retains the original error. The runtime observes failed execution once and sends explicit feedback to `notify(message, kind)`, where kind is `success` or `failure`. Do not toast the same `ActionFailure` again in `onError`. Form failures also retain their inline feedback. The notifier may return a promise; throws and rejections cannot change execution outcomes. `setNotifier` returns owner-safe cleanup. No parallel execution or notification registry is introduced.
13
+ ## Designed for typed composition
143
14
 
144
- ## Host integration
15
+ - **Typed contracts:** shared service keys connect providers and consumers; action definitions carry inputs, results and custom state.
16
+ - **Inferred application APIs:** discovery generates ActionMap, ServiceMap and ConfigMap from supported contributions.
17
+ - **Typed notifications:** the workspace EventMap connects known event names to their payloads.
18
+ - **Names beside implementations:** the workspace `exposeAs` service option supplies the typed app-facing name directly; discovery defaults it from the file.
19
+ - **Flexible authoring:** flat and nested contribution files resolve to the same logical paths; explicit composition remains available.
20
+ - **Owned lifecycle:** one runtime coordinates dependencies, registrations and cleanup.
145
21
 
146
- FoundationProvider owns the root ActionProvider or reuses an existing outer provider. Supply stable `config`, `ui`, `translate`, localized `labels`, and an optional outcome-aware `notify(message, kind)` callback to the generic UI entry. The Next adapter provides standard UI, labels and navigation defaults. The package owns form state, validation, pending/error behavior and lifecycle.
22
+ Unknown action IDs remain allowed unless strict mode is enabled. External data still
23
+ needs runtime validation. See the [type-safety guide](../../apps/docs/content/docs/concepts/type-safety.mdx)
24
+ and [Core learning path](../../apps/docs/content/docs/concepts/index.mdx) for examples and boundaries.
147
25
 
148
- A standalone React application can supply an explicit `FoundationConfig`; Next is not required. The provider owns no global singleton. Services are created on mount, in dependency order, and disposed in reverse order. Their optional `dispose(instance)` handles external resources. Locale changes update presentation through the original registrations without recreating services or pending actions. Changing the config object replaces that plugin composition deliberately.
26
+ ## How the pieces fit
149
27
 
150
- Form actions register the public opening action and an `<id>.submit` registration flagged `internal`: it stays executable so interceptors, pending state and execution events apply, but `useActions()` and group views hide it. Both use the existing execution engine. Submission validates required/text/email/select fields even if invoked programmatically; the form maintains drafts on failures. Disable/hide checks apply again at execution. Closing is blocked during a pending submission. Only one foundation dialog is open at a time. `render` can override the form body using `values`, `setValue`, `submit`, `pending`, `enabled`, and `error`. `defineDialogAction` provides a custom body without form submission machinery.
28
+ Imagine a **To-do plugin** that lets someone add a task:
151
29
 
152
- `ActionBoundary` gates children on current action visibility/enabled state, fails closed for missing actions, and accepts a fallback. It is a UI gate, never a substitute for server authorization. Hiding/unmounting children discards their local React state.
153
-
154
- ## Types and translation
155
-
156
- Core discovery generates a `ConfigMap` for module config and a `ServiceMap` augmentation using each service factory's return type, and an `ActionMap` augmentation from discovered action definitions: the effective ID (`replaces`, then an explicit `id`, then the file path) maps to the definition's input and result types, so `useAction`, `list.execute` and the UI bindings autocomplete IDs and type their input and completed `value`. Class and function exports establish their ID at construction and are excluded; augment `ActionMap` manually for those. With global `conventions: false` only explicit IDs are emitted. Unknown IDs remain allowed unless `ActionMapOptions` is augmented with `{ strict: true }`. Explicit consumers may augment `@bitakit/core` themselves. `requires` declares runtime dependencies; TypeScript provides method input/output inference. API responses still need runtime validation in the service.
157
-
158
- `mergePluginMessages` merges each key in this priority: app current language, plugin current language, app fallback language, plugin fallback language (highest priority first). Packaged catalogs are exported by their owning package; local discovery catalogs retain their plugin namespace. Pass the result to your normal translation provider. The package does not create a second locale store.
159
-
160
- ## Scope
161
-
162
- Implemented: local trusted plugins, synchronous typed service factories, actions/forms/dialogs, scoped group placement, lifecycle, translation composition and UI boundaries. Existing SettingsCatalog contributions continue through the settings package; there is no parallel settings loader. Remote plugin installation, untrusted code sandboxes, server frameworks, migrations and a TanStack adapter are not included.
163
-
164
- ### Shared unavailable message
165
-
166
- ```tsx
167
- const access = defineAction({
168
- id: 'users.access',
169
- title: 'users.title',
170
- enabled: false,
171
- unavailable: { messageKey: 'users.unavailable' },
172
- });
173
- // Supply once as a plugin contribution to the shared host list.
174
- <ActionBoundary action="users.access">
175
- <UserPage />
176
- </ActionBoundary>;
30
+ ```text
31
+ Application — chooses which plugins to use
32
+ │
33
+ ▼
34
+ BitaKit Core — starts plugins and checks their dependencies
35
+ │
36
+ └── To-do plugin — groups one feature's contributions
37
+ ├── Service: holds tasks and provides add/list operations
38
+ └── Action: calls the service to add a task
39
+
40
+ Button or server code
41
+ │ executes "todos.create"
42
+ ▼
43
+ Action ──calls──▶ To-do service ──returns──▶ Task
44
+
45
+ Application UI displays the result; Core does not render it.
177
46
  ```
178
47
 
179
- A disabled boundary uses the action's localized unavailable message by default. A custom `fallback` may be content or `(message) => ReactNode`. Unknown actions remain blocked. The core treats the metadata as opaque; React rendering stays in this package.
180
-
181
- ## Discovery and explicit composition
48
+ | Concept | What it does | In this example |
49
+ | ---------------- | ------------------------------------------------------------------- | ------------------------------------------------- |
50
+ | **Plugin** | Bundles the parts of a feature. | The To-do feature. |
51
+ | **Service** | Owns reusable behavior and, when needed, state or resources. | Stores tasks and exposes `create()` and `list()`. |
52
+ | **Action** | Provides a named operation that application code or UI can execute. | `todos.create` adds a task through the service. |
53
+ | **Core runtime** | Coordinates dependencies, registrations, startup, and cleanup. | Creates the service and registers the action. |
182
54
 
183
- `@bitakit/core/discovery` is a Node-only build entry point. It scans files and emits imports; the browser provider never reads the filesystem. Adapters call `generateFoundation(root)` initially and `watchFoundation(root)` during development. Next integration is a separate package. Production changes require rebuilding and deployment.
55
+ Core manages the lifecycle of plugin-created services. A service that acquires
56
+ resources can supply disposal logic. Core does not automatically save data to a
57
+ database or subscribe your UI to service changes.
184
58
 
185
- The generated config and the optional `FoundationProvider` props `actions`, `plugins`, `interceptors`, and `providers` follow one selection rule:
59
+ ## Install
186
60
 
187
- - Omitted: inherit the generated configuration.
188
- - Explicit array: replace that domain.
189
- - Empty array: select none.
190
-
191
- An explicit `actions` array replaces all declarative Actions, including selected plugins' Action contributions. Those plugins' services and setup still run; imperative registrations made by setup or the public API remain explicitly owned by their caller. A setup that requires an excluded Action must be adjusted as well. `plugins=[]` excludes plugins but retains independent app Actions.
192
-
193
- ```tsx
194
- // Pseudocode: keep configuration and these arrays stable across renders.
195
- <FoundationProvider
196
- config={discovered}
197
- interceptors={[confirmation, audit]}
198
- providers={[theme, widgets]}
199
- ui={ui}
200
- translate={translate}
201
- labels={labels}
202
- >
203
- <App />
204
- </FoundationProvider>
61
+ ```sh
62
+ npm install @bitakit/core
205
63
  ```
206
64
 
207
- Interceptors execute in ascending `order`, preserving registration order for ties. App discovery activates discovered interceptors by default; an explicit `enabled` list selects them (an empty list disables them). Plugin interceptors are local unless marked `scope: 'global'`; host interceptors remain global by default. React providers still require an explicit ordered `enabled` list. The shared file grammar accepts flat, directory and legacy suffix forms. Direct interceptor instances and `defineInterceptor({ requires, create })` factories are supported. The Foundation owns only its registrations; manually installed low-level ActionProvider interceptors are independent and are not removed by a Foundation override.
208
-
209
- React providers use `defineProvider({ id, component, requires })`. The first entry wraps the others. Required providers must appear earlier; duplicate IDs and missing or reversed dependencies fail before mounting. These wrappers live inside the Foundation context, including its dialog host. They do not replace the host's root authentication or Settings providers.
210
-
211
- Host services supplied through `services` retain host ownership. Plugin-created services and interceptor registrations are cleaned up with the runtime. Keep service objects and explicit arrays stable; replacing their identity deliberately replaces the runtime composition. Translation changes alone preserve the ActionList, mounted services and pending actions.
212
-
213
- `actionOverrides` can cap an Action's `enabled` or `visible` state by final ID. A false cap cannot be bypassed by a reactive subscription; true does not bypass business guards or permissions. This affects UI availability, not server authorization.
65
+ The example below uses Node.js and no UI. For a React application, bindings live
66
+ in `@bitakit/ui`; framework-specific integration lives in `@bitakit/next` or
67
+ `@bitakit/tanstack`. Those packages are separate from Core and are being prepared
68
+ for publication. TanStack support is experimental.
214
69
 
215
- ## Direct Action exports
70
+ ## Try a To-do plugin
216
71
 
217
- An Action file can default-export an `Action` subclass directly. No registration wrapper or separate factory builder is required. The runtime constructs a fresh instance per runtime, reads its metadata, translates its title and owns its connection lifetime. Its explicit ID wins over the inferred file ID.
72
+ Follow the [To-do tutorial](docs/todo-tutorial.md) to run three actions: create a
73
+ task, list tasks, and delete a task. Each action lives in its own file:
218
74
 
219
- ```ts
220
- export default class Logout extends Action {
221
- constructor() {
222
- super({ title: 'Nav.logout' });
223
- }
224
- async execute() {
225
- await logout();
226
- }
227
- }
75
+ ```text
76
+ examples/
77
+ ├── todos.mjs # Starts the runtime and executes the actions
78
+ └── todos/
79
+ ├── plugin.mjs # Groups the service and actions
80
+ ├── services/
81
+ │ └── tasks.mjs # In-memory task operations
82
+ └── actions/
83
+ ├── create.mjs # todos.create
84
+ ├── list.mjs # todos.list
85
+ └── delete.mjs # todos.delete
228
86
  ```
229
87
 
230
- For Action dependencies, export a function receiving the typed `ActionEnvironment` (`services`, `translate`, `config`) and returning an Action. The same context is passed to class constructors that need it. Constructors/functions should only create instances; put subscriptions in `connect()` so the ActionList owns cleanup. Discovery does not execute these exports. Plain, form and dialog definitions remain supported. Do not export mutable singleton Action instances.
231
-
232
- `execute(input, context)` receives the invocation context as its second argument, and its return value becomes the completed result's `value`. A class may declare `success` and `failure` feedback fields; they run through the same translated feedback pipeline as declarative definitions. Without them, class actions keep raw errors and stay silent, so navigation and setting bindings never toast by accident.
233
-
234
- ## Runtime structure
88
+ The plugin uses explicit imports, so no framework or discovery setup is required.
89
+ The script creates three tasks, lists them, deletes the second, and lists the two
90
+ remaining tasks. Stopping the runtime releases its registrations. Data stays in
91
+ memory and is lost on restart.
235
92
 
236
- Every contribution kind (plain command, form, dialog, class export) is normalized by an adapter in `src/contributions` into registrations plus the services it requires or watches. The runtime only orders plugins, creates services, registers the adapted entries, subscribes to watched services and re-translates registrations on locale changes. Add a new contribution kind by adding an adapter, not by extending the mount sequence.
93
+ With a configured framework adapter, contribution files can instead live under
94
+ `src/plugins/todos/services` and `src/plugins/todos/actions`. Its build integration
95
+ generates registration and types. Installing Core alone does not scan folders.
96
+ See [file contributions](docs/file-contributions.md) for the exact conventions.
237
97
 
238
- ## Integration contributions
98
+ ## React to events
239
99
 
240
- Optional integrations add declarative contribution kinds without teaching Core their meaning. A
241
- module lists values under `contributions: { [kind]: values }`; exactly one module claims each kind
242
- with `installs: { [kind]: (values, { module, app, services }) => cleanup }`. During mount the
243
- runtime installs contributions after services, translation and interceptors and before actions and
244
- setup, kind by kind in module dependency order. The cleanup belongs to the contributing module's
245
- scope. A contributed kind without an installer, or a kind claimed twice, fails the mount.
246
- Integrations type their kinds by augmenting `ContributionMap`.
100
+ The following API is available in the workspace and is not yet part of the
101
+ published Core 0.1.0 release. Each runtime owns one event service. Services emit
102
+ notifications after updating their data; actions declare `events` and `onEvent`.
247
103
 
248
- `runtime.contributionsOf(kind)` returns the same values in install order without mounting, so a UI
249
- integration can prepare an initial render snapshot that equals the mounted state.
250
- `scopeModule(scope)` identifies the module of a runtime-issued `PluginScope` (the scope passed to
251
- `setup`); integrations use it to derive ownership instead of trusting caller-supplied owner strings.
252
-
253
- Discovery supports integration kinds in `foundation.config.ts`:
104
+ With file discovery configured, IDs can be omitted:
254
105
 
255
106
  ```ts
256
- export default defineFoundation({
257
- kinds: [{ name: 'settings.renderers', directory: 'renderers', from: '@bitakit/app-preferences/foundation', normalize: 'discoverSettingsRenderers' }],
107
+ // src/services/todos.ts
108
+ import { defineService } from '@bitakit/core';
109
+
110
+ export default defineService({
111
+ create({ events }) {
112
+ let items: { id: number; title: string }[] = [];
113
+ let nextId = 1;
114
+ return {
115
+ list: () => [...items],
116
+ add(title: string) {
117
+ const todo = { id: nextId++, title };
118
+ items.push(todo);
119
+ events.emit('todos.changed', { kind: 'added', id: todo.id });
120
+ },
121
+ remove(id: number) {
122
+ items = items.filter((todo) => todo.id !== id);
123
+ events.emit('todos.changed', { kind: 'removed', id });
124
+ },
125
+ };
126
+ },
258
127
  });
259
128
  ```
260
129
 
261
- Each kind names the folder that identifies it inside every module root and the normalizer to
262
- import. Generation emits `contributions: { 'settings.renderers': normalize([files], moduleId) }` for
263
- the app and each enabled plugin; it never executes the files. Folders cannot collide with built-in
264
- kinds or each other, and a plugin manifest can override a kind's folder through `entries`.
265
-
266
- ## Provider plugins and typed services
267
-
268
- Provider adapters live in separate packages: `@bitakit/better-auth` and
269
- `@bitakit/next-intl`. They return ordinary plugins. Pass them through `plugins`;
270
- there is no separate integration lifecycle or configuration list. Core has no vendor imports.
271
- Plugins may contribute services and ordered providers as well as actions, pages and views.
272
- Use `serviceKey<T>`, `provideService` and `getService` to preserve input/output types without
273
- pretending that an optional provider is always installed. See `docs/integrations.md`.
274
-
275
- Plain Actions can declare `watch: ['auth']` and derive contextual presentation with `resolve(input, { services })`. The runtime validates the observable service, subscribes once per service (even for multiple Actions), refreshes the shared ActionList on changes and owns cleanup. There is no copied session state and no Action-level subscription boilerplate. `requires` remains useful for non-observable dependencies.
276
-
277
- ### Paket-Styles
278
-
279
- Für die Verwendung der Oberfläche in einem Tailwind-4-Host `@import '@bitakit/core/styles.css';` einbinden. Der öffentliche Einstieg registriert die eigenen ausgelieferten Klassen; er definiert kein zweites Theme.
280
-
281
- Core has no React dependencies or renderer source files. Presentation values are opaque host extension types. The backend runtime does not require the UI package. See the headless-boundary regression test.
282
-
283
- ## Typed custom Action state
284
-
285
130
  ```ts
286
- // src/plugins/documents/actions/save.ts
287
- export default defineAction<{ title: string }>()({
288
- initialState: { savedCount: 0, lastTitle: '' },
289
- async execute(input) {
290
- const document = await this.app.services.documents.save(input.title);
291
- this.state.update(current => ({
292
- savedCount: current.savedCount + 1,
293
- lastTitle: document.title,
294
- }));
295
- return document;
131
+ // src/actions/todos/delete.ts
132
+ import { defineAction } from '@bitakit/core';
133
+
134
+ export default defineAction<number>({
135
+ requires: ['todos'],
136
+ events: ['todos.changed'],
137
+ setup({ services, action }) {
138
+ action.enabled = services.todos.list().length > 0;
139
+ },
140
+ onEvent(event, { services, action }) {
141
+ action.enabled = services.todos.list().length > 0;
296
142
  },
143
+ execute: ({ services, input }) => services.todos.remove(input),
297
144
  });
298
145
  ```
299
146
 
300
- Use method syntax for execute; arrow functions do not receive the bound `this`.
301
- Input is explicit; state and result types are inferred and included in discovery's ActionMap.
302
- The original defineAction({...}) context-based API remains available. Keep definitions in
303
- contribution files and consumers in their own modules. A same-module app lookup preceding
304
- its own inferred definition can cause a TypeScript augmentation cycle, including with the
305
- original API; avoid that self-reference or supply an explicit definition type.
306
-
307
- `this.app`, `this.services` and `this.config` use the existing execution context.
308
- `this.state.get()` reads current state; `this.state.update(updater)` publishes through the
309
- existing ActionList. State starts as a structured clone of initialState for each registration;
310
- use cloneable values and immutable updates. It is shared by bindings to that registration,
311
- not persisted across unregistration or reload. Input and return values are not stored as state.
312
- Late updates from a removed or replaced registration return false.
313
-
314
- Core exports ActionStatus.Idle, Pending, Succeeded and Failed. Snapshots expose status and
315
- error; the executor owns both. The existing pending guard prevents concurrent execution of
316
- the same registration. Skipped calls preserve the previous status/error (an intercepted call
317
- may temporarily enter Pending). ExecutionResult retains its completed/skipped contract, and
318
- failed executions still reject. A successful retry clears the error.
319
-
320
- Source responsibilities: actions/state.ts owns lifecycle names and mapped state types;
321
- contributions/stateful-action.ts adapts instance-style authoring. ActionList remains the sole
322
- snapshot store, and actions/execution.ts owns lifecycle transitions.
147
+ Here discovery supplies `todos` and `todos.delete` from the paths (with no explicit
148
+ app namespace). Plugin contributions also receive their plugin namespace. Provide
149
+ an explicit `id` when you need a custom identity. Direct imports without discovery,
150
+ including the Node tutorial above, still need explicit IDs.
323
151
 
324
- ## Mixed interceptor files
325
-
326
- Both interceptor kinds share `interceptors/`. Subfolders and dotted filenames organize entries;
327
- the helper's discriminator decides the kind. Default-export a single definition, a named object
328
- collection, or an array (including collections containing arrays).
329
-
330
- ```ts
331
- // src/plugins/documents/interceptors/logging.ts
332
- import { defineActionInterceptor, defineServiceInterceptor } from '@bitakit/core';
333
-
334
- export default [
335
- defineActionInterceptor({ before() { console.log('Action started'); } }),
336
- defineServiceInterceptor({
337
- service: 'documents',
338
- method: 'save',
339
- before({ args }) { console.log(args[0]); },
340
- after({ result }) { console.log(result.title); },
341
- onError({ error }) { console.error(error); },
342
- }),
343
- ];
344
- ```
152
+ `events: ['todos.loaded', 'todos.changed']` calls `onEvent` for
153
+ **each** matching event. Handlers receive `{ type, data }` and can be synchronous or
154
+ asynchronous. Core owns subscriptions created in action `setup` and service
155
+ `create`, including cleanup after failed setup. No manual unsubscribe is needed.
156
+ For dynamic subscriptions, `setup` still offers `events.watch`. React components use `useWatchEvent` from `@bitakit/ui`.
345
157
 
346
- Omit `method` to observe all public string-named methods of the selected service. Service names
347
- resolve through public service aliases or raw container keys. Known service methods infer argument
348
- and awaited result types. Action interceptors retain existing plugin/global scope and cancellation;
349
- `defineInterceptor` remains the legacy Action helper. Service observers explicitly target a service,
350
- independently of the organizing folder. `order` sorts observers ascending with stable ties.
158
+ See [events and action setup](docs/events.md) for payload typing, errors, async
159
+ cancellation, and the distinction from observable-service `watch`.
351
160
 
352
- Service hooks are observation-only. Return values are ignored, callback failures are isolated, and
353
- callbacks are not awaited. Do not mutate observed arguments or results. Business methods retain
354
- synchronous return behavior, original Promises and original errors. The wrapper binds methods and
355
- getters to their original instance, preserving private fields. Internal self-calls and calls through
356
- an original reference outside the container bypass observation. Symbol methods and constructors
357
- are not observed. The method facade supports ordinary object/class services, including frozen
358
- objects; it is not a general-purpose transparent reflection or callable-function proxy.
161
+ ## What belongs outside Core?
359
162
 
360
- Every container consumer, including dependent service factories and Actions, sees the same wrapped
361
- instance. Disposal disables callbacks, including settlement of an already-running call, and still
362
- cleans up the original service instance. No second service registry is introduced.
163
+ - **React rendering:** the UI bindings and your visual components.
164
+ - **Routes and navigation:** your application's router and its BitaKit adapter.
165
+ - **Settings:** the separate App Preferences package.
166
+ - **Email, authentication, and persistence:** optional integrations or your own services.
363
167
 
364
- Source responsibilities: `interceptors/service.ts` contains definitions and inferred contracts;
365
- `interceptors/service-observers.ts` wraps method access. `services.ts` owns construction/disposal,
366
- and runtime routes Action definitions to the existing Action interception pipeline.
168
+ Plugins are trusted application code. Core is not a sandbox or a remote plugin marketplace.
367
169
 
170
+ ## Go deeper
368
171
 
369
- ### Declarative keyboard metadata
172
+ - [Runnable To-do example](examples/todos.mjs)
173
+ - [Core reference](docs/reference.md): configuration, typed services, actions, lifecycle, and advanced integration.
174
+ - [File contributions and configuration](docs/file-contributions.md): discovery and folder conventions.
175
+ - [Source repository](https://github.com/mvavesal/bitakit)
370
176
 
371
- `shortcut: { keys: 'Mod+Shift+S' }` declares a keyboard binding without DOM or vendor imports in Core.
372
- Commands with a required typed input must supply `shortcut.input` of that type; the adapter never
373
- infers input from focused controls or a last-clicked row. Class Actions, commands and form/dialog
374
- openers retain this metadata. Internal form-submit registrations are excluded. Browser handling
375
- belongs to UI's existing ActionProvider; see its README for scopes and collision behavior.
177
+ ## License
376
178
 
377
- ## Navigation boundary
179
+ [MIT](LICENSE). Third-party dependencies retain their own licenses.
378
180
 
379
- Core does not access browser globals for navigation. Mount an ActionList with an explicit
380
- navigation callback when executing URL Actions outside the UI provider. Without a navigation
381
- host, URL execution reports an error. The UI ActionProvider supplies browser navigation by
382
- default; the optional Next and TanStack providers use the application's existing router.
181
+ See [client authentication](docs/auth.md) for the shared provider contract, externally
182
+ configured login/logout paths, UI bindings and an adapter template (workspace APIs).
@@ -32,7 +32,6 @@ export async function generateFoundation(root) {
32
32
  const definitions = [];
33
33
  const serviceTypes = [];
34
34
  const publicServiceTypes = [];
35
- const publicServicesByModule = new Map();
36
35
  const configTypes = [];
37
36
  const allMessages = {};
38
37
  const pluginIds = new Set();
@@ -122,10 +121,6 @@ export async function generateFoundation(root) {
122
121
  `DiscoveredActionEntry<typeof ${name}, ${quote(moduleId)}, ${conventions}>`,
123
122
  );
124
123
  if (kind === 'services') {
125
- publicServicesByModule.set(
126
- moduleId,
127
- `discoverPublicServices([${names}], ${quote(moduleId)})`,
128
- );
129
124
  for (const name of names) {
130
125
  serviceTypes.push(`DiscoveredServiceEntry<typeof ${name}, ${quote(moduleId)}>`);
131
126
  publicServiceTypes.push(`DiscoveredPublicServiceEntry<typeof ${name}>`);
@@ -162,7 +157,6 @@ export async function generateFoundation(root) {
162
157
  const appSetup = appSetupFile ? importFile(appSetupFile) : 'undefined';
163
158
  const appActions = emit('actions', await appEntries('actions'), appManifest.id ?? '');
164
159
  const appServices = emit('services', await appEntries('services'), appManifest.id ?? '');
165
- const appPublicServices = publicServicesByModule.get(appManifest.id ?? '');
166
160
  const appConfig = emit('configs', await appEntries('configs'), appId);
167
161
  let interceptorEntries = await appEntries('interceptors');
168
162
  if (config.interceptors?.enabled !== undefined) {
@@ -279,7 +273,7 @@ export async function generateFoundation(root) {
279
273
  manifest.id,
280
274
  );
281
275
  definitions.push(
282
- `{ id: ${quote(manifest.id)}, publicServices: ${publicServicesByModule.get(manifest.id)}, metadata: ${quote(metadata)}, dependencies: ${quote(manifest.dependencies ?? [])}, actions: ${actions}, services: ${services}, config: ${pluginConfig}, interceptors: ${pluginInterceptors}, views: [${views}], pages: [${pages}], setup: ${setup}, contributions: ${pluginContributions} }`,
276
+ `{ id: ${quote(manifest.id)}, metadata: ${quote(metadata)}, dependencies: ${quote(manifest.dependencies ?? [])}, actions: ${actions}, services: ${services}, config: ${pluginConfig}, interceptors: ${pluginInterceptors}, views: [${views}], pages: [${pages}], setup: ${setup}, contributions: ${pluginContributions} }`,
283
277
  );
284
278
  for (const file of await resolveEntry('locales', 'locales')) {
285
279
  if (!file.endsWith('.json')) continue;
@@ -294,7 +288,7 @@ export async function generateFoundation(root) {
294
288
  await writeChanged(
295
289
  path.join(output, 'plugins.ts'),
296
290
  `${header}${[...contributionTypes.values()].map(({ kind, index, entries }) => `type KindMap${index} = ${entries.join(' & ')}; declare module ${quote(kind.from)} { interface ${kind.types.map} extends KindMap${index} {} }`).join('\n')}
297
- ${imports.join('\n')}\nimport { ${imports.some(entry => entry.includes('= discoveredFile(')) ? 'discoveredFile, ' : ''}discoverActions, discoverServices, discoverPublicServices, discoverInterceptors, discoverConfig, ${actionTypes.length ? 'type DiscoveredActionEntry, ' : ''}${serviceTypes.length ? 'type DiscoveredServiceEntry, ' : ''}${publicServiceTypes.length ? 'type DiscoveredPublicServiceEntry, ' : ''}${configTypes.some(entry => entry.includes('DiscoveredConfigEntry')) ? 'type DiscoveredConfigEntry, ' : ''}type FoundationConfig } from '@bitakit/core';\ntype DiscoveredServices = ${serviceTypes.join(' & ') || '{}'};\ntype DiscoveredPublicServices = ${publicServiceTypes.join(' & ') || '{}'};\ntype DiscoveredActions = ${actionTypes.join(' & ') || '{}'};\ndeclare module '@bitakit/core' { interface PublicServiceMap extends DiscoveredPublicServices {} interface ServiceMap extends DiscoveredServices {} interface ActionMap extends DiscoveredActions {} interface ConfigMap { ${configTypes.join(' \n')} } }\nexport const foundationConfig = { publicServices: ${appPublicServices}, appId: ${quote(appId)}, metadata: ${quote(appManifest.metadata ?? {})}, dependencies: ${quote(appManifest.dependencies ?? [])}, pages: [${appPages}], views: [${appViews}], setup: ${appSetup}, groups: ${quote(config.groups ?? [])}, actionOverrides: ${quote((config.actions && config.actions.overrides) || {})}, config: ${appConfig}, configOverrides: ${quote(Object.fromEntries(Object.entries(config.configOverrides ?? {}).filter(([id]) => !pluginIds.has(id) || enabledModuleIds.has(id))))}, services: ${appServices}, interceptors: ${interceptors}, providers: [${providers}], actions: ${appActions}, contributions: ${appContributions}, plugins: [${definitions.join(',\n')}] } satisfies FoundationConfig;\n`,
291
+ ${imports.join('\n')}\nimport { ${imports.some(entry => entry.includes('= discoveredFile(')) ? 'discoveredFile, ' : ''}discoverActions, discoverServices, discoverInterceptors, discoverConfig, ${actionTypes.length ? 'type DiscoveredActionEntry, ' : ''}${serviceTypes.length ? 'type DiscoveredServiceEntry, ' : ''}${publicServiceTypes.length ? 'type DiscoveredPublicServiceEntry, ' : ''}${configTypes.some(entry => entry.includes('DiscoveredConfigEntry')) ? 'type DiscoveredConfigEntry, ' : ''}type FoundationConfig } from '@bitakit/core';\ntype DiscoveredServices = ${serviceTypes.join(' & ') || '{}'};\ntype DiscoveredPublicServices = ${publicServiceTypes.join(' & ') || '{}'};\ntype DiscoveredActions = ${actionTypes.join(' & ') || '{}'};\ndeclare module '@bitakit/core' { interface PublicServiceMap extends DiscoveredPublicServices {} interface ServiceMap extends DiscoveredServices {} interface ActionMap extends DiscoveredActions {} interface ConfigMap { ${configTypes.join(' \n')} } }\nexport const foundationConfig = { appId: ${quote(appId)}, metadata: ${quote(appManifest.metadata ?? {})}, dependencies: ${quote(appManifest.dependencies ?? [])}, pages: [${appPages}], views: [${appViews}], setup: ${appSetup}, groups: ${quote(config.groups ?? [])}, actionOverrides: ${quote((config.actions && config.actions.overrides) || {})}, config: ${appConfig}, configOverrides: ${quote(Object.fromEntries(Object.entries(config.configOverrides ?? {}).filter(([id]) => !pluginIds.has(id) || enabledModuleIds.has(id))))}, services: ${appServices}, interceptors: ${interceptors}, providers: [${providers}], actions: ${appActions}, contributions: ${appContributions}, plugins: [${definitions.join(',\n')}] } satisfies FoundationConfig;\n`,
298
292
  );
299
293
  await writeChanged(
300
294
  path.join(output, 'messages.json'),
@@ -31,8 +31,8 @@ export declare function createActionList(initialActions?: readonly (ActionDefini
31
31
  resolve: ((input: unknown) => import("./types.js").ActionPresentation) | undefined;
32
32
  enabled: boolean;
33
33
  visible: boolean;
34
- variant?: "default" | "destructive";
35
34
  icon?: import("./types.js").ActionIcon;
35
+ variant?: "default" | "destructive";
36
36
  href?: string;
37
37
  checked?: boolean;
38
38
  value?: unknown;