@bitakit/core 0.1.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.
- package/LICENSE +21 -0
- package/README.md +382 -0
- package/discovery/entries.mjs +124 -0
- package/discovery/generate.mjs +327 -0
- package/discovery/host.mjs +12 -0
- package/discovery/index.d.ts +41 -0
- package/discovery/index.mjs +4 -0
- package/discovery/modules.mjs +13 -0
- package/discovery/packages.mjs +57 -0
- package/discovery/watch.mjs +23 -0
- package/dist/actions/action-list.d.ts +69 -0
- package/dist/actions/action-list.js +247 -0
- package/dist/actions/action.d.ts +96 -0
- package/dist/actions/action.js +145 -0
- package/dist/actions/base/url-action.d.ts +8 -0
- package/dist/actions/base/url-action.js +15 -0
- package/dist/actions/core.d.ts +14 -0
- package/dist/actions/core.js +8 -0
- package/dist/actions/dependencies.d.ts +8 -0
- package/dist/actions/dependencies.js +34 -0
- package/dist/actions/execution.d.ts +4 -0
- package/dist/actions/execution.js +64 -0
- package/dist/actions/feedback.d.ts +17 -0
- package/dist/actions/feedback.js +21 -0
- package/dist/actions/groups.d.ts +13 -0
- package/dist/actions/groups.js +21 -0
- package/dist/actions/instance-bindings.d.ts +16 -0
- package/dist/actions/instance-bindings.js +93 -0
- package/dist/actions/interceptors.d.ts +24 -0
- package/dist/actions/interceptors.js +42 -0
- package/dist/actions/navigation.d.ts +12 -0
- package/dist/actions/navigation.js +42 -0
- package/dist/actions/reference.d.ts +17 -0
- package/dist/actions/reference.js +39 -0
- package/dist/actions/state.d.ts +11 -0
- package/dist/actions/state.js +8 -0
- package/dist/actions/types.d.ts +99 -0
- package/dist/actions/types.js +1 -0
- package/dist/app/access.d.ts +4 -0
- package/dist/app/access.js +85 -0
- package/dist/app/action-access.d.ts +4 -0
- package/dist/app/action-access.js +20 -0
- package/dist/app/service-error.d.ts +8 -0
- package/dist/app/service-error.js +19 -0
- package/dist/app/types.d.ts +47 -0
- package/dist/app/types.js +1 -0
- package/dist/config-service.d.ts +49 -0
- package/dist/config-service.js +83 -0
- package/dist/configuration.d.ts +4 -0
- package/dist/configuration.js +42 -0
- package/dist/confirmation.d.ts +14 -0
- package/dist/confirmation.js +26 -0
- package/dist/contracts.d.ts +27 -0
- package/dist/contracts.js +3 -0
- package/dist/contribution-origin.d.ts +3 -0
- package/dist/contribution-origin.js +13 -0
- package/dist/contributions/command.d.ts +8 -0
- package/dist/contributions/command.js +50 -0
- package/dist/contributions/dialog.d.ts +8 -0
- package/dist/contributions/dialog.js +18 -0
- package/dist/contributions/form.d.ts +10 -0
- package/dist/contributions/form.js +67 -0
- package/dist/contributions/host.d.ts +40 -0
- package/dist/contributions/host.js +1 -0
- package/dist/contributions/index.d.ts +26 -0
- package/dist/contributions/index.js +18 -0
- package/dist/contributions/native.d.ts +11 -0
- package/dist/contributions/native.js +87 -0
- package/dist/contributions/shared.d.ts +19 -0
- package/dist/contributions/shared.js +48 -0
- package/dist/contributions/stateful-action.d.ts +29 -0
- package/dist/contributions/stateful-action.js +33 -0
- package/dist/conventions.d.ts +4 -0
- package/dist/conventions.js +38 -0
- package/dist/core.d.ts +21 -0
- package/dist/core.js +18 -0
- package/dist/definitions.d.ts +356 -0
- package/dist/definitions.js +60 -0
- package/dist/discovered.d.ts +49 -0
- package/dist/discovered.js +120 -0
- package/dist/interceptors/service-observers.d.ts +3 -0
- package/dist/interceptors/service-observers.js +80 -0
- package/dist/interceptors/service.d.ts +37 -0
- package/dist/interceptors/service.js +7 -0
- package/dist/messages.d.ts +9 -0
- package/dist/messages.js +21 -0
- package/dist/metadata.d.ts +3 -0
- package/dist/metadata.js +13 -0
- package/dist/pages.d.ts +8 -0
- package/dist/pages.js +22 -0
- package/dist/presentation.d.ts +4 -0
- package/dist/presentation.js +1 -0
- package/dist/replacements.d.ts +22 -0
- package/dist/replacements.js +54 -0
- package/dist/runtime.d.ts +88 -0
- package/dist/runtime.js +445 -0
- package/dist/scope.d.ts +34 -0
- package/dist/scope.js +78 -0
- package/dist/service-key.d.ts +13 -0
- package/dist/service-key.js +14 -0
- package/dist/services.d.ts +6 -0
- package/dist/services.js +53 -0
- package/dist/translation.d.ts +13 -0
- package/dist/translation.js +43 -0
- package/dist/validation.d.ts +2 -0
- package/dist/validation.js +16 -0
- package/docs/file-contributions.md +161 -0
- package/package.json +48 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Majid Vesal
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
# @bitakit/core
|
|
2
|
+
|
|
3
|
+
## Public app access and installed plugins
|
|
4
|
+
|
|
5
|
+
Local plugins need only their contribution files:
|
|
6
|
+
|
|
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.
|
|
141
|
+
|
|
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.
|
|
143
|
+
|
|
144
|
+
## Host integration
|
|
145
|
+
|
|
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.
|
|
147
|
+
|
|
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.
|
|
149
|
+
|
|
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.
|
|
151
|
+
|
|
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>;
|
|
177
|
+
```
|
|
178
|
+
|
|
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
|
|
182
|
+
|
|
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.
|
|
184
|
+
|
|
185
|
+
The generated config and the optional `FoundationProvider` props `actions`, `plugins`, `interceptors`, and `providers` follow one selection rule:
|
|
186
|
+
|
|
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>
|
|
205
|
+
```
|
|
206
|
+
|
|
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.
|
|
214
|
+
|
|
215
|
+
## Direct Action exports
|
|
216
|
+
|
|
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.
|
|
218
|
+
|
|
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
|
+
}
|
|
228
|
+
```
|
|
229
|
+
|
|
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
|
|
235
|
+
|
|
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.
|
|
237
|
+
|
|
238
|
+
## Integration contributions
|
|
239
|
+
|
|
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`.
|
|
247
|
+
|
|
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`:
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
export default defineFoundation({
|
|
257
|
+
kinds: [{ name: 'settings.renderers', directory: 'renderers', from: '@bitakit/app-preferences/foundation', normalize: 'discoverSettingsRenderers' }],
|
|
258
|
+
});
|
|
259
|
+
```
|
|
260
|
+
|
|
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
|
+
```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;
|
|
296
|
+
},
|
|
297
|
+
});
|
|
298
|
+
```
|
|
299
|
+
|
|
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.
|
|
323
|
+
|
|
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
|
+
```
|
|
345
|
+
|
|
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.
|
|
351
|
+
|
|
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.
|
|
359
|
+
|
|
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.
|
|
363
|
+
|
|
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.
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
### Declarative keyboard metadata
|
|
370
|
+
|
|
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.
|
|
376
|
+
|
|
377
|
+
## Navigation boundary
|
|
378
|
+
|
|
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.
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { readdir, readFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import ts from 'typescript';
|
|
4
|
+
|
|
5
|
+
/** Shared traversal for every contribution kind. Nested modules are separate boundaries. */
|
|
6
|
+
export async function files(directory, boundaries = new Set()) {
|
|
7
|
+
let entries;
|
|
8
|
+
try {
|
|
9
|
+
entries = await readdir(directory, { withFileTypes: true });
|
|
10
|
+
} catch (error) {
|
|
11
|
+
if (error.code === 'ENOENT') return [];
|
|
12
|
+
throw error;
|
|
13
|
+
}
|
|
14
|
+
const result = [];
|
|
15
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
16
|
+
const file = path.join(directory, entry.name);
|
|
17
|
+
if (entry.isSymbolicLink()) throw new Error(`Symlink contribution: ${file}`);
|
|
18
|
+
if (entry.isDirectory()) {
|
|
19
|
+
if (['node_modules', '.git', '.foundation', '.next', 'dist'].includes(entry.name)) continue;
|
|
20
|
+
if (!boundaries.has(file)) result.push(...(await files(file, boundaries)));
|
|
21
|
+
} else result.push(file);
|
|
22
|
+
}
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const contributionKinds = {
|
|
27
|
+
actions: ['form-action', 'dialog-action', 'action'],
|
|
28
|
+
services: ['service'],
|
|
29
|
+
interceptors: ['interceptor'],
|
|
30
|
+
configs: [],
|
|
31
|
+
providers: ['provider'],
|
|
32
|
+
views: ['view'],
|
|
33
|
+
pages: ['page'],
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Validates integration kinds from `foundation.config.ts`. Each names a contribution kind, the
|
|
38
|
+
* folder that identifies it inside every module root, and the runtime normalizer to import.
|
|
39
|
+
*/
|
|
40
|
+
export function contributionKindSpecs(kinds = []) {
|
|
41
|
+
if (!Array.isArray(kinds)) throw new Error('Discovery "kinds" must be an array.');
|
|
42
|
+
const names = new Set();
|
|
43
|
+
const folders = new Map(
|
|
44
|
+
Object.keys(contributionKinds).map((kind) => [kind, `built-in kind "${kind}"`]),
|
|
45
|
+
);
|
|
46
|
+
return kinds.map((kind) => {
|
|
47
|
+
const { name, directory, from, normalize } = kind ?? {};
|
|
48
|
+
if (typeof name !== 'string' || !/^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)*$/.test(name))
|
|
49
|
+
throw new Error(`Invalid contribution kind name: ${JSON.stringify(name)}`);
|
|
50
|
+
if (names.has(name)) throw new Error(`Duplicate contribution kind "${name}".`);
|
|
51
|
+
names.add(name);
|
|
52
|
+
if (Object.hasOwn(contributionKinds, name))
|
|
53
|
+
throw new Error(`Contribution kind "${name}" is built in.`);
|
|
54
|
+
const folder =
|
|
55
|
+
typeof directory === 'string' ? directory.replace(/^\.\//, '').replace(/\/+$/, '') : '';
|
|
56
|
+
if (!folder || folder.split('/').some((part) => !/^[a-z0-9][a-z0-9_-]*$/i.test(part)))
|
|
57
|
+
throw new Error(
|
|
58
|
+
`Contribution kind "${name}" needs a relative folder name, got ${JSON.stringify(directory)}.`,
|
|
59
|
+
);
|
|
60
|
+
const first = folder.split('/')[0];
|
|
61
|
+
if (folders.has(first))
|
|
62
|
+
throw new Error(
|
|
63
|
+
`Contribution kind "${name}" uses folder "${first}", already used by ${folders.get(first)}.`,
|
|
64
|
+
);
|
|
65
|
+
folders.set(first, `kind "${name}"`);
|
|
66
|
+
if (typeof from !== 'string' || !from.trim())
|
|
67
|
+
throw new Error(`Contribution kind "${name}" needs the module that exports its normalizer.`);
|
|
68
|
+
if (typeof normalize !== 'string' || !/^[A-Za-z_$][\w$]*$/.test(normalize))
|
|
69
|
+
throw new Error(`Contribution kind "${name}" needs the normalizer export name.`);
|
|
70
|
+
return Object.freeze({ name, directory: folder, from, normalize, types: kind.types });
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Folders and dots have identical meaning. Legacy suffixes are migration aliases. */
|
|
75
|
+
export async function discoverEntries(base, paths, kind, { directory, explicitFile } = {}) {
|
|
76
|
+
const extension = typeof kind === 'object' && kind !== null;
|
|
77
|
+
const suffixes = extension ? [] : contributionKinds[kind];
|
|
78
|
+
if (!suffixes) throw new Error(`Unknown contribution kind: ${kind}`);
|
|
79
|
+
const folder = extension ? kind.directory.split('/') : [kind];
|
|
80
|
+
const label = extension ? kind.name : kind;
|
|
81
|
+
const result = [];
|
|
82
|
+
const seen = new Map();
|
|
83
|
+
for (const file of paths) {
|
|
84
|
+
if (!/\.tsx?$/.test(file) || /\.d\.ts$/.test(file)) continue;
|
|
85
|
+
const relative = path.relative(base, file);
|
|
86
|
+
if (!directory && !explicitFile && (relative.startsWith('..') || path.isAbsolute(relative)))
|
|
87
|
+
continue;
|
|
88
|
+
let segments = relative.replace(/\.tsx?$/, '').split(/[\\/.]/);
|
|
89
|
+
if (segments.some((segment) => segment.startsWith('-'))) continue;
|
|
90
|
+
// This discovery entry emits client-importable contributions only.
|
|
91
|
+
if (segments.includes('server')) continue;
|
|
92
|
+
if (explicitFile === file) segments = [path.basename(file).replace(/\.tsx?$/, '')];
|
|
93
|
+
else if (directory) {
|
|
94
|
+
const local = path.relative(directory, file);
|
|
95
|
+
if (local.startsWith('..') || path.isAbsolute(local)) continue;
|
|
96
|
+
segments = local.replace(/\.tsx?$/, '').split(/[\\/.]/);
|
|
97
|
+
} else {
|
|
98
|
+
if (folder.some((part, index) => segments[index] !== part)) continue;
|
|
99
|
+
segments = segments.slice(folder.length);
|
|
100
|
+
}
|
|
101
|
+
const legacy = suffixes.includes(segments.at(-1));
|
|
102
|
+
if (legacy) segments.pop();
|
|
103
|
+
if (!legacy && segments.at(-1) === 'index') segments.pop();
|
|
104
|
+
if (segments.some((segment) => !segment)) throw new Error(`Empty contribution path: ${file}`);
|
|
105
|
+
const sourceText = await readFile(file, 'utf8');
|
|
106
|
+
const syntax = ts.createSourceFile(file, sourceText, ts.ScriptTarget.Latest, false);
|
|
107
|
+
const hasDefault = syntax.statements.some(
|
|
108
|
+
(statement) =>
|
|
109
|
+
(ts.isExportAssignment(statement) && !statement.isExportEquals) ||
|
|
110
|
+
statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword) ||
|
|
111
|
+
(ts.isExportDeclaration(statement) &&
|
|
112
|
+
statement.exportClause &&
|
|
113
|
+
ts.isNamedExports(statement.exportClause) &&
|
|
114
|
+
statement.exportClause.elements.some((element) => element.name.text === 'default')),
|
|
115
|
+
);
|
|
116
|
+
if (!hasDefault) continue;
|
|
117
|
+
const key = segments.join('.');
|
|
118
|
+
if (seen.has(key))
|
|
119
|
+
throw new Error(`Duplicate ${label} path "${key}": ${seen.get(key)} and ${file}`);
|
|
120
|
+
seen.set(key, file);
|
|
121
|
+
result.push({ file, path: segments, source: relative });
|
|
122
|
+
}
|
|
123
|
+
return result;
|
|
124
|
+
}
|