@bitakit/core 0.2.1 → 0.2.3

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/README.md CHANGED
@@ -44,19 +44,19 @@ resolve within a repository checkout and follow the branch viewed on GitHub. Run
44
44
  `npm run dev:docs` from the repository root to read the rendered handbook at
45
45
  `http://localhost:3002/docs`. A public documentation address is not configured yet.
46
46
 
47
- | Topic | Guide |
48
- | --- | --- |
49
- | Services and cleanup | [Service reference](../../apps/docs/content/docs/reference/services.mdx) |
50
- | Actions and React bindings | [Action reference](../../apps/docs/content/docs/reference/actions.mdx) |
51
- | Events and interception | [Events](../../apps/docs/content/docs/concepts/events.mdx), [Interceptors](../../apps/docs/content/docs/concepts/interceptors.mdx) |
52
- | Files and developer configuration | [Discovery](../../apps/docs/content/docs/concepts/discovery.mdx), [Configuration](../../apps/docs/content/docs/concepts/configuration.mdx) |
53
- | Extension points and preferences | [Slots](../../apps/docs/content/docs/reference/slots.mdx), [Settings](../../apps/docs/content/docs/reference/settings.mdx) |
54
- | Runtime updates and diagnostics | [Runtime management](../../apps/docs/content/docs/concepts/runtime-management.mdx) |
55
- | Enable, disable, add and remove plugins | [Plugin manager](../../apps/docs/content/docs/plugin-management.mdx) |
56
- | Activate a trusted package catalog | [Package manager](../../apps/docs/content/docs/package-management.mdx) |
57
- | Authentication contract | [Client authentication](../../apps/docs/content/docs/reference/authentication.mdx) |
58
- | Test a plugin folder | [Testing](../../apps/docs/content/docs/reference/testing.mdx) |
59
- | Standalone example | [To-do walkthrough](../../apps/docs/content/docs/concepts/tutorial.mdx); runnable JavaScript files in `examples/` |
47
+ | Topic | Guide |
48
+ | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
49
+ | Services and cleanup | [Service reference](../../apps/docs/content/docs/reference/services.mdx) |
50
+ | Actions and React bindings | [Action reference](../../apps/docs/content/docs/reference/actions.mdx) |
51
+ | Events and interception | [Events](../../apps/docs/content/docs/concepts/events.mdx), [Interceptors](../../apps/docs/content/docs/concepts/interceptors.mdx) |
52
+ | Files and developer configuration | [Discovery](../../apps/docs/content/docs/concepts/discovery.mdx), [Configuration](../../apps/docs/content/docs/concepts/configuration.mdx) |
53
+ | Extension points and preferences | [Slots](../../apps/docs/content/docs/reference/slots.mdx), [Settings](../../apps/docs/content/docs/reference/settings.mdx) |
54
+ | Runtime updates and diagnostics | [Runtime management](../../apps/docs/content/docs/concepts/runtime-management.mdx) |
55
+ | Enable, disable, add and remove plugins | [Plugin manager](../../apps/docs/content/docs/plugin-management.mdx) |
56
+ | Activate a trusted package catalog | [Package manager](../../apps/docs/content/docs/package-management.mdx) |
57
+ | Authentication contract | [Client authentication](../../apps/docs/content/docs/reference/authentication.mdx) |
58
+ | Test a plugin folder | [Testing](../../apps/docs/content/docs/reference/testing.mdx) |
59
+ | Standalone example | [To-do walkthrough](../../apps/docs/content/docs/concepts/tutorial.mdx); runnable JavaScript files in `examples/` |
60
60
 
61
61
  Plugins are trusted application code. Core is not a sandbox, package installer or remote
62
62
  marketplace. Services own state and resources; the host owns routing, persistence providers
@@ -58,7 +58,9 @@ export type PublicEventsOf<Plugins extends readonly Plugin[]> = [Plugins[number]
58
58
  events: infer E;
59
59
  } ? EventsOf<E, Id> : {} : never>;
60
60
  /** `CancelableEventMap` entries of manually composed or installed package plugins. */
61
- export type PublicCancelableOf<Plugins extends readonly Plugin[]> = [Plugins[number]] extends [never] ? {} : Intersection<Plugins[number] extends infer P ? P extends {
61
+ export type PublicCancelableOf<Plugins extends readonly Plugin[]> = [Plugins[number]] extends [
62
+ never
63
+ ] ? {} : Intersection<Plugins[number] extends infer P ? P extends {
62
64
  id: infer Id extends string;
63
65
  events: infer E;
64
66
  } ? CancelableOf<E, Id> : {} : never>;
@@ -74,7 +76,7 @@ type AtPath<Path extends string, Value> = Path extends `${infer Head}.${infer Ta
74
76
  } : {
75
77
  readonly [K in Path]: Value;
76
78
  };
77
- /** Dotted names become nested namespaces: `todos.items` is `services.todos.items`. */
79
+ /** Dotted names become nested namespaces: `todos.list` is `services.todos.list`. */
78
80
  export type Namespace<Entries extends object> = keyof Entries extends never ? {} : Intersection<{
79
81
  [K in keyof Entries & string]: AtPath<K, Entries[K]>;
80
82
  }[keyof Entries & string]>;
package/dist/runtime.js CHANGED
@@ -895,7 +895,9 @@ export class BitaKitRuntime {
895
895
  });
896
896
  }
897
897
  connectTranslation() {
898
- const i18n = this.hasService('i18n') ? getService(this.services, translationService) : undefined;
898
+ const i18n = this.hasService('i18n')
899
+ ? getService(this.services, translationService)
900
+ : undefined;
899
901
  if (!i18n)
900
902
  return;
901
903
  this.setTranslations(i18n.translate);
@@ -11,8 +11,8 @@ export type ServiceEntry = {
11
11
  plugin: string;
12
12
  };
13
13
  /**
14
- * Service names as contributions see them: IDs such as `todos.items` form the tree
15
- * `services.todos.items`; aliases (`exposeAs`, contracts) are extra paths onto the same
14
+ * Service names as contributions see them: IDs such as `todos.list` form the tree
15
+ * `services.todos.list`; aliases (`exposeAs`, contracts) are extra paths onto the same
16
16
  * instance. Resolution never creates instances; the container stays the only owner.
17
17
  */
18
18
  export declare class ServiceNames {
@@ -1,8 +1,8 @@
1
1
  import { BitaKitStartupError } from './startup-error.js';
2
2
  import { BitaKitServiceError } from './app/service-error.js';
3
3
  /**
4
- * Service names as contributions see them: IDs such as `todos.items` form the tree
5
- * `services.todos.items`; aliases (`exposeAs`, contracts) are extra paths onto the same
4
+ * Service names as contributions see them: IDs such as `todos.list` form the tree
5
+ * `services.todos.list`; aliases (`exposeAs`, contracts) are extra paths onto the same
6
6
  * instance. Resolution never creates instances; the container stays the only owner.
7
7
  */
8
8
  export class ServiceNames {
@@ -1,5 +1,5 @@
1
1
  import { defineAction } from '@bitakit/core';
2
2
 
3
3
  export default defineAction({
4
- execute: ({ services }) => services.todos.tasks.list(),
4
+ execute: ({ services }) => services.todos.list.all(),
5
5
  });
@@ -1,5 +1,5 @@
1
1
  import { defineAction } from '@bitakit/core';
2
2
 
3
3
  export default defineAction({
4
- execute: ({ services, input }) => services.todos.tasks.create(input),
4
+ execute: ({ services, input }) => services.todos.list.create(input),
5
5
  });
@@ -1,7 +1,7 @@
1
1
  import { defineAction } from '@bitakit/core';
2
2
 
3
3
  export default defineAction({
4
- // Re-evaluated whenever the tasks store changes: disabled while the list is empty.
5
- enabled: ({ services }) => services.todos.tasks.state.get().items.length > 0,
6
- execute: ({ services, input }) => services.todos.tasks.delete(input),
4
+ // Re-evaluated whenever the list store changes: disabled while the list is empty.
5
+ enabled: ({ services }) => services.todos.list.state.get().todos.length > 0,
6
+ execute: ({ services, input }) => services.todos.list.delete(input),
7
7
  });
@@ -1,13 +1,13 @@
1
1
  import { definePlugin } from '@bitakit/core';
2
- import tasks from './services/tasks.mjs';
2
+ import list from './services/list.mjs';
3
3
  import events from './events.mjs';
4
4
  import create from './actions/create.mjs';
5
- import list from './actions/list.mjs';
5
+ import all from './actions/all.mjs';
6
6
  import remove from './actions/delete.mjs';
7
7
 
8
8
  export default definePlugin({
9
9
  id: 'todos',
10
10
  events,
11
- services: { tasks },
12
- actions: { create, list, delete: remove },
11
+ services: { list },
12
+ actions: { create, all, delete: remove },
13
13
  });
@@ -0,0 +1,24 @@
1
+ import { defineService } from '@bitakit/core';
2
+
3
+ /** The Todos data and behavior: an observable store plus the methods that change it. */
4
+ export default defineService(({ store, events }) => {
5
+ const state = store({ todos: [], nextId: 1 });
6
+
7
+ return {
8
+ state,
9
+ create(title) {
10
+ const todo = { id: state.get().nextId, title, done: false };
11
+ state.set((s) => ({ todos: [...s.todos, todo], nextId: s.nextId + 1 }));
12
+ events.emit('todos.changed', { kind: 'added', id: todo.id });
13
+ return todo;
14
+ },
15
+ all: () => [...state.get().todos],
16
+ delete(id) {
17
+ const before = state.get().todos.length;
18
+ state.set((s) => ({ ...s, todos: s.todos.filter((todo) => todo.id !== id) }));
19
+ const removed = state.get().todos.length < before;
20
+ if (removed) events.emit('todos.changed', { kind: 'removed', id });
21
+ return removed;
22
+ },
23
+ };
24
+ });
@@ -10,9 +10,9 @@ try {
10
10
  await actions.execute('todos.create', 'Learn plugins');
11
11
  await actions.execute('todos.create', 'Connect a service');
12
12
  console.log('Delete enabled after:', actions.get('todos.delete').enabled);
13
- console.log('Before:', (await actions.execute('todos.list')).value);
13
+ console.log('Before:', (await actions.execute('todos.all')).value);
14
14
  await actions.execute('todos.delete', 2);
15
- console.log('After:', (await actions.execute('todos.list')).value);
15
+ console.log('After:', (await actions.execute('todos.all')).value);
16
16
  } finally {
17
17
  await stop();
18
18
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bitakit/core",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "files": [
@@ -39,7 +39,7 @@
39
39
  "zustand": "^5.0.0"
40
40
  },
41
41
  "peerDependencies": {
42
- "@bitakit/discovery": "^0.2.1",
42
+ "@bitakit/discovery": "^0.2.2",
43
43
  "jiti": "^2.7.0"
44
44
  },
45
45
  "peerDependenciesMeta": {
@@ -51,7 +51,7 @@
51
51
  }
52
52
  },
53
53
  "devDependencies": {
54
- "@bitakit/discovery": "^0.2.1",
54
+ "@bitakit/discovery": "^0.2.2",
55
55
  "jiti": "^2.7.0",
56
56
  "typescript": "^5.9.3"
57
57
  },
@@ -1,4 +1,5 @@
1
1
  import type {
2
+ AuthService,
2
3
  EventService,
3
4
  BitaKitApp,
4
5
  BitaKitEvent,
@@ -20,7 +21,7 @@ export type MountedPlugin = {
20
21
  app: BitaKitApp;
21
22
  /** The runtime's ActionList; IDs known from `ActionMap` type the input and result of `execute`. */
22
23
  actions: ActionList;
23
- /** Services as the plugin's contributions see them: `services.notes.items`. */
24
+ /** Services as the plugin's contributions see them: `services.notes.list`. */
24
25
  services: Services;
25
26
  /** The runtime bus plus every event emitted while mounted. */
26
27
  events: EventService & { recorded: Pick<BitaKitEvent, 'type' | 'data'>[] };
@@ -57,3 +58,19 @@ export function mountPlugin(
57
58
  configOverrides?: Readonly<Record<string, Record<string, unknown>>>;
58
59
  },
59
60
  ): Promise<MountedPlugin>;
61
+
62
+ /**
63
+ * Checks an `auth` provider against the AuthService contract, for the provider's own tests:
64
+ * a stable snapshot, working subscribe/unsubscribe, a string `user.id` after `signIn`, an
65
+ * awaited `signOut` that clears the user, and valid optional `paths` and `signIn`. Rejects with
66
+ * the first broken rule.
67
+ */
68
+ export function assertAuthContract(
69
+ service: AuthService,
70
+ options: {
71
+ /** Signs a test user in through the provider's own login. Called twice. */
72
+ signIn(): Promise<unknown>;
73
+ /** Milliseconds to wait for a pending session or a sign-in to settle (default 2000). */
74
+ timeout?: number;
75
+ },
76
+ ): Promise<void>;
package/testing/index.mjs CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  discoverServices,
14
14
  discoverSlots,
15
15
  discoveredFile,
16
+ configureAuthPaths,
16
17
  } from '../dist/core.js';
17
18
 
18
19
  /** The plugin ID a package declares (`bitakit.id`), or one derived from its name. */
@@ -104,9 +105,7 @@ export async function mountPlugin(directory = 'src', options = {}) {
104
105
  const plugin = await loadPlugin(directory, options.id);
105
106
  const { id } = plugin;
106
107
  const others = await Promise.all(
107
- (options.plugins ?? []).map((other) =>
108
- typeof other === 'string' ? loadPlugin(other) : other,
109
- ),
108
+ (options.plugins ?? []).map((other) => (typeof other === 'string' ? loadPlugin(other) : other)),
110
109
  );
111
110
  const runtime = createRuntime(
112
111
  { plugins: [plugin, ...others], configOverrides: options.configOverrides },
@@ -129,7 +128,9 @@ export async function mountPlugin(directory = 'src', options = {}) {
129
128
  runtime.mount();
130
129
  await runtime.ready;
131
130
  } catch (error) {
132
- try { await release(); } catch (cleanupError) {
131
+ try {
132
+ await release();
133
+ } catch (cleanupError) {
133
134
  throw new AggregateError([error, cleanupError], 'Plugin startup and cleanup failed.');
134
135
  }
135
136
  throw error;
@@ -139,7 +140,7 @@ export async function mountPlugin(directory = 'src', options = {}) {
139
140
  runtime,
140
141
  app: runtime.app,
141
142
  actions,
142
- /** Services as the plugin's contributions see them: `services.notes.items`. */
143
+ /** Services as the plugin's contributions see them: `services.notes.list`. */
143
144
  services: runtime.services,
144
145
  events: Object.assign(runtime.events, { recorded }),
145
146
  /** Executes `<plugin>.<name>` (or a full action ID) and returns the execution outcome. */
@@ -148,3 +149,72 @@ export async function mountPlugin(directory = 'src', options = {}) {
148
149
  [Symbol.asyncDispose]: release,
149
150
  };
150
151
  }
152
+
153
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
154
+
155
+ /** Waits until `ready()` holds, failing with `message` after `timeout` milliseconds. */
156
+ async function until(ready, message, timeout) {
157
+ const deadline = Date.now() + timeout;
158
+ while (!ready()) {
159
+ if (Date.now() > deadline) throw new Error(`auth contract: ${message}`);
160
+ await new Promise((resolve) => setTimeout(resolve, 5));
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Checks an `auth` provider against the AuthService contract, for the provider's own tests:
166
+ * a stable snapshot, working subscribe/unsubscribe, a string `user.id` after `signIn`, an
167
+ * awaited `signOut` that clears the user, and valid optional `paths`/`signIn`. `signIn` drives
168
+ * the provider's own login. Rejects with the first broken rule.
169
+ */
170
+ export async function assertAuthContract(service, { signIn, timeout = 2000 }) {
171
+ const fail = (rule) => {
172
+ throw new Error(`auth contract: ${rule}`);
173
+ };
174
+ for (const method of ['getSnapshot', 'subscribe', 'signOut'])
175
+ if (typeof service?.[method] !== 'function') fail(`${method}() is missing.`);
176
+ if (service.signIn !== undefined && typeof service.signIn !== 'function')
177
+ fail('signIn must be a function when present.');
178
+ if (service.paths !== undefined) {
179
+ try {
180
+ configureAuthPaths(service.paths);
181
+ } catch (error) {
182
+ fail(`paths are invalid: ${error.message}`);
183
+ }
184
+ }
185
+ await until(() => !service.getSnapshot().pending, 'the snapshot stays pending.', timeout);
186
+ const initial = service.getSnapshot();
187
+ for (const key of ['user', 'pending', 'error'])
188
+ if (!(key in initial)) fail(`the snapshot has no "${key}".`);
189
+ if (service.getSnapshot() !== initial)
190
+ fail('getSnapshot() must return the same object until it changes.');
191
+ if (initial.user !== null && !initial.error) await service.signOut();
192
+
193
+ let notified = 0;
194
+ const unsubscribe = service.subscribe(() => notified++);
195
+ if (typeof unsubscribe !== 'function') fail('subscribe() must return an unsubscribe function.');
196
+ await signIn();
197
+ await until(() => service.getSnapshot().user !== null, 'no user after signIn.', timeout);
198
+ const signedIn = service.getSnapshot();
199
+ if (typeof signedIn.user.id !== 'string' || !signedIn.user.id)
200
+ fail('user.id must be a non-empty string.');
201
+ if (signedIn.pending) fail('pending must be false once the user is known.');
202
+ if (signedIn.error) fail('a signed-in snapshot must not carry an error.');
203
+ if (signedIn === initial) fail('the snapshot must be a new object after a change.');
204
+ if (service.getSnapshot() !== signedIn) fail('the signed-in snapshot must be stable.');
205
+ if (notified === 0) fail('subscribe() listeners must be called when the session changes.');
206
+
207
+ const result = service.signOut();
208
+ if (typeof result?.then !== 'function') fail('signOut() must return a promise.');
209
+ await result;
210
+ const signedOut = service.getSnapshot();
211
+ if (signedOut.user !== null) fail('signOut() must resolve after the user is cleared.');
212
+ if (signedOut.pending) fail('pending must be false after signOut().');
213
+
214
+ unsubscribe();
215
+ const after = notified;
216
+ await signIn();
217
+ await settle();
218
+ if (notified !== after) fail('listeners must not be called after unsubscribe.');
219
+ await service.signOut();
220
+ }
@@ -1,24 +0,0 @@
1
- import { defineService } from '@bitakit/core';
2
-
3
- /** The Todos data and behavior: an observable store plus the methods that change it. */
4
- export default defineService(({ store, events }) => {
5
- const state = store({ items: [], nextId: 1 });
6
-
7
- return {
8
- state,
9
- create(title) {
10
- const task = { id: state.get().nextId, title, done: false };
11
- state.set((s) => ({ items: [...s.items, task], nextId: s.nextId + 1 }));
12
- events.emit('todos.changed', { kind: 'added', id: task.id });
13
- return task;
14
- },
15
- list: () => [...state.get().items],
16
- delete(id) {
17
- const before = state.get().items.length;
18
- state.set((s) => ({ ...s, items: s.items.filter((task) => task.id !== id) }));
19
- const removed = state.get().items.length < before;
20
- if (removed) events.emit('todos.changed', { kind: 'removed', id });
21
- return removed;
22
- },
23
- };
24
- });