@bitakit/core 0.1.2 → 0.2.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 (157) hide show
  1. package/README.md +44 -207
  2. package/discovery/index.d.ts +1 -41
  3. package/discovery/index.mjs +1 -4
  4. package/dist/actions/action-list.d.ts +4 -0
  5. package/dist/actions/action-list.js +58 -16
  6. package/dist/actions/action.d.ts +2 -0
  7. package/dist/actions/action.js +4 -0
  8. package/dist/actions/brand.d.ts +21 -0
  9. package/dist/actions/brand.js +36 -0
  10. package/dist/actions/core.d.ts +4 -3
  11. package/dist/actions/core.js +4 -2
  12. package/dist/actions/execution.d.ts +2 -2
  13. package/dist/actions/execution.js +61 -9
  14. package/dist/actions/feedback.d.ts +2 -0
  15. package/dist/actions/feedback.js +8 -0
  16. package/dist/actions/groups.js +5 -1
  17. package/dist/actions/instance-bindings.js +3 -2
  18. package/dist/actions/interceptors.d.ts +9 -3
  19. package/dist/actions/interceptors.js +31 -3
  20. package/dist/actions/navigation.d.ts +2 -1
  21. package/dist/actions/navigation.js +10 -5
  22. package/dist/actions/reference.js +10 -5
  23. package/dist/actions/types.d.ts +9 -1
  24. package/dist/app/access.d.ts +4 -4
  25. package/dist/app/access.js +33 -71
  26. package/dist/app/action-access.d.ts +2 -2
  27. package/dist/app/action-access.js +6 -4
  28. package/dist/app/service-error.d.ts +2 -2
  29. package/dist/app/service-error.js +10 -6
  30. package/dist/app/types.d.ts +76 -33
  31. package/dist/config-service.d.ts +30 -6
  32. package/dist/config-service.js +25 -9
  33. package/dist/configuration.d.ts +6 -3
  34. package/dist/configuration.js +8 -6
  35. package/dist/contracts.d.ts +4 -2
  36. package/dist/contracts.js +3 -3
  37. package/dist/contribution-origin.d.ts +4 -1
  38. package/dist/contribution-origin.js +14 -1
  39. package/dist/contributions/action.d.ts +26 -0
  40. package/dist/contributions/action.js +171 -0
  41. package/dist/contributions/host.d.ts +14 -11
  42. package/dist/contributions/index.d.ts +1 -26
  43. package/dist/contributions/index.js +1 -18
  44. package/dist/conventions.d.ts +8 -4
  45. package/dist/conventions.js +12 -31
  46. package/dist/core.d.ts +41 -18
  47. package/dist/core.js +25 -13
  48. package/dist/definitions.d.ts +272 -306
  49. package/dist/definitions.js +28 -56
  50. package/dist/destinations.d.ts +25 -0
  51. package/dist/destinations.js +21 -0
  52. package/dist/discovered.d.ts +52 -21
  53. package/dist/discovered.js +89 -35
  54. package/dist/events/define.d.ts +43 -0
  55. package/dist/events/define.js +17 -0
  56. package/dist/events/service.d.ts +35 -8
  57. package/dist/events/service.js +184 -42
  58. package/dist/events/types.d.ts +29 -9
  59. package/dist/inspection/inventory.d.ts +86 -0
  60. package/dist/inspection/inventory.js +132 -0
  61. package/dist/interceptors/define.d.ts +76 -0
  62. package/dist/interceptors/define.js +23 -0
  63. package/dist/interceptors/service-observers.d.ts +6 -3
  64. package/dist/interceptors/service-observers.js +13 -10
  65. package/dist/lifecycle/cleanup.d.ts +5 -0
  66. package/dist/lifecycle/cleanup.js +41 -0
  67. package/dist/lifecycle/controller.d.ts +82 -0
  68. package/dist/lifecycle/controller.js +276 -0
  69. package/dist/lifecycle/reconcile.d.ts +19 -0
  70. package/dist/lifecycle/reconcile.js +68 -0
  71. package/dist/lifecycle/state.d.ts +53 -0
  72. package/dist/lifecycle/state.js +86 -0
  73. package/dist/names.d.ts +10 -0
  74. package/dist/names.js +1 -0
  75. package/dist/pages.d.ts +39 -6
  76. package/dist/pages.js +93 -11
  77. package/dist/presentation.d.ts +9 -0
  78. package/dist/runtime.d.ts +166 -28
  79. package/dist/runtime.js +1485 -248
  80. package/dist/schema.d.ts +13 -0
  81. package/dist/schema.js +38 -0
  82. package/dist/scope.d.ts +59 -4
  83. package/dist/scope.js +133 -11
  84. package/dist/service-key.d.ts +33 -14
  85. package/dist/service-key.js +21 -5
  86. package/dist/service-names.d.ts +39 -0
  87. package/dist/service-names.js +175 -0
  88. package/dist/services.d.ts +24 -5
  89. package/dist/services.js +230 -37
  90. package/dist/settings/access.d.ts +19 -0
  91. package/dist/settings/access.js +78 -0
  92. package/dist/settings/define.d.ts +97 -0
  93. package/dist/settings/define.js +83 -0
  94. package/dist/settings/storage.d.ts +45 -0
  95. package/dist/settings/storage.js +102 -0
  96. package/dist/settings/store.d.ts +74 -0
  97. package/dist/settings/store.js +345 -0
  98. package/dist/slots/action-placement.d.ts +47 -0
  99. package/dist/slots/action-placement.js +1 -0
  100. package/dist/slots/define.d.ts +52 -0
  101. package/dist/slots/define.js +12 -0
  102. package/dist/slots/normalize.d.ts +7 -0
  103. package/dist/slots/normalize.js +36 -0
  104. package/dist/slots/runtime.d.ts +43 -0
  105. package/dist/slots/runtime.js +348 -0
  106. package/dist/slots/types.d.ts +113 -0
  107. package/dist/slots/types.js +1 -0
  108. package/dist/startup-error.d.ts +21 -0
  109. package/dist/startup-error.js +29 -0
  110. package/dist/store.d.ts +24 -0
  111. package/dist/store.js +40 -0
  112. package/dist/translation.d.ts +9 -4
  113. package/dist/translation.js +2 -3
  114. package/examples/todos/actions/create.mjs +1 -3
  115. package/examples/todos/actions/delete.mjs +3 -10
  116. package/examples/todos/actions/list.mjs +1 -3
  117. package/examples/todos/events.mjs +5 -0
  118. package/examples/todos/plugin.mjs +4 -2
  119. package/examples/todos/services/tasks.mjs +14 -20
  120. package/examples/todos.mjs +8 -7
  121. package/package.json +36 -9
  122. package/testing/index.d.ts +59 -0
  123. package/testing/index.mjs +150 -0
  124. package/assets/bitakit-banner.png +0 -0
  125. package/discovery/entries.mjs +0 -124
  126. package/discovery/generate.mjs +0 -321
  127. package/discovery/host.mjs +0 -12
  128. package/discovery/modules.mjs +0 -13
  129. package/discovery/packages.mjs +0 -57
  130. package/discovery/watch.mjs +0 -23
  131. package/dist/app/service-aliases.d.ts +0 -4
  132. package/dist/app/service-aliases.js +0 -14
  133. package/dist/contributions/command.d.ts +0 -8
  134. package/dist/contributions/command.js +0 -59
  135. package/dist/contributions/dialog.d.ts +0 -8
  136. package/dist/contributions/dialog.js +0 -18
  137. package/dist/contributions/form.d.ts +0 -10
  138. package/dist/contributions/form.js +0 -67
  139. package/dist/contributions/native.d.ts +0 -11
  140. package/dist/contributions/native.js +0 -87
  141. package/dist/contributions/shared.d.ts +0 -19
  142. package/dist/contributions/shared.js +0 -48
  143. package/dist/contributions/stateful-action.d.ts +0 -29
  144. package/dist/contributions/stateful-action.js +0 -33
  145. package/dist/events/action-setup.d.ts +0 -19
  146. package/dist/events/action-setup.js +0 -24
  147. package/dist/interceptors/service.d.ts +0 -37
  148. package/dist/interceptors/service.js +0 -7
  149. package/dist/replacements.d.ts +0 -22
  150. package/dist/replacements.js +0 -54
  151. package/dist/validation.d.ts +0 -2
  152. package/dist/validation.js +0 -16
  153. package/docs/auth.md +0 -106
  154. package/docs/events.md +0 -157
  155. package/docs/file-contributions.md +0 -174
  156. package/docs/reference.md +0 -404
  157. package/docs/todo-tutorial.md +0 -88
package/dist/services.js CHANGED
@@ -1,57 +1,250 @@
1
1
  import { EventService, createEventScope } from './events/service.js';
2
2
  import { ConfigService } from './config-service.js';
3
- export function createServices(definitions, provided = {}, configFor = () => new ConfigService([{ id: 'app' }]).context('app'), decorate = (_id, instance) => instance, events = new EventService()) {
3
+ import { BitaKitStartupError, isBitaKitStartupError, moduleLabel } from './startup-error.js';
4
+ import { createStore, isObservable, isStore } from './store.js';
5
+ import { cleanupSequence, cleanupFailure } from './lifecycle/cleanup.js';
6
+ /** Allocates ownership before initialization, so partial factory failures can be fully stopped. */
7
+ export function createServices(definitions, provided = {}, configFor = () => new ConfigService([{ id: 'app' }]).context('app'), decorate = (_id, instance) => instance, events = new EventService(), scope, idOf = (definition) => definition.id, settings = Object.freeze({}), onPhase = () => { }) {
4
8
  let active = true;
9
+ let initialized = false;
10
+ let stopping = false;
11
+ let completion;
5
12
  const pending = new Map();
6
13
  const instances = Object.create(null);
7
- for (const [id, instance] of Object.entries(provided))
14
+ const observed = new Set();
15
+ const providedSources = new Set();
16
+ const owned = [];
17
+ for (const [id, instance] of Object.entries(provided)) {
8
18
  instances[id] = decorate(id, instance, () => active);
9
- const cleanups = [];
10
- const dispose = () => {
11
- active = false;
12
- const errors = [];
13
- for (const cleanup of cleanups.splice(0).reverse()) {
14
- try {
15
- cleanup();
16
- }
17
- catch (error) {
18
- errors.push(error);
19
- }
19
+ if (isObservable(instance)) {
20
+ observed.add(instance);
21
+ providedSources.add(instance);
20
22
  }
21
- if (errors.length)
22
- throw new AggregateError(errors, 'Service cleanup failed.');
23
- };
24
- for (const definition of definitions) {
25
- if (pending.has(definition.id) || Object.hasOwn(instances, definition.id))
26
- throw new Error(`Duplicate service "${definition.id}".`);
27
- pending.set(definition.id, definition);
28
23
  }
29
- try {
24
+ const requirements = (definition) => (definition.requires ?? []).map((name) => ({
25
+ name,
26
+ key: scope ? scope.names.key(name) : name,
27
+ }));
28
+ const view = scope ? scope.names.tree(instances) : instances;
29
+ const attributed = (error, service, phase) => {
30
+ if (phase === 'onStart' && isBitaKitStartupError(error))
31
+ return error;
32
+ const message = `${phase} in ${scope ? moduleLabel(service.module, scope.appId) : service.module} failed: ${error instanceof Error ? error.message : String(error)}`;
33
+ if (phase === 'onStart')
34
+ return new BitaKitStartupError(message, service.module, {
35
+ cause: error,
36
+ source: service.source,
37
+ app: service.module === scope?.appId,
38
+ });
39
+ return Object.assign(new Error(message, { cause: error }), {
40
+ name: 'BitaKitCleanupError',
41
+ plugin: service.module,
42
+ service: service.id,
43
+ source: service.source,
44
+ });
45
+ };
46
+ const install = (entries) => {
47
+ for (const definition of entries) {
48
+ const id = idOf(definition);
49
+ if (!id)
50
+ throw new Error('A service needs an ID: pass { id } for manual composition.');
51
+ if (pending.has(id) || Object.hasOwn(instances, id))
52
+ throw new Error(`Duplicate service "${id}".`);
53
+ pending.set(id, definition);
54
+ }
30
55
  while (pending.size) {
31
56
  let progressed = false;
32
57
  for (const [id, definition] of pending) {
33
- if (definition.requires?.some((key) => !Object.hasOwn(instances, key)))
58
+ if (requirements(definition).some(({ key }) => !Object.hasOwn(instances, key)))
34
59
  continue;
35
- const eventScope = createEventScope(events);
36
- cleanups.push(eventScope.dispose);
37
- const instance = definition.create({
38
- events: eventScope.events,
39
- services: instances,
40
- config: configFor(definition),
41
- });
42
- if (definition.dispose)
43
- cleanups.push(() => definition.dispose(instance));
44
- instances[id] = decorate(id, instance, () => active);
60
+ const owner = scope?.moduleOf(definition) ?? '';
61
+ const eventScope = createEventScope(events, owner || undefined);
62
+ const service = {
63
+ id,
64
+ module: owner,
65
+ source: scope?.sourceOf(definition),
66
+ starts: [],
67
+ stops: [],
68
+ release: eventScope.dispose,
69
+ active: true,
70
+ starting: false,
71
+ stopping: false,
72
+ observed: new Set(),
73
+ };
74
+ owned.push(service);
75
+ onPhase(id, 'starting');
76
+ let instance;
77
+ try {
78
+ instance = definition.create({
79
+ events: eventScope.events,
80
+ services: view,
81
+ config: configFor(definition),
82
+ settings,
83
+ store: (initial) => {
84
+ const store = createStore(initial);
85
+ observed.add(store);
86
+ service.observed.add(store);
87
+ return store;
88
+ },
89
+ onStart: (hook) => {
90
+ if (service.starting || service.stopping || stopping)
91
+ throw new Error('Register onStart during service creation.');
92
+ service.starts.push(hook);
93
+ },
94
+ onStop: (hook) => {
95
+ if (service.stopping || stopping)
96
+ throw new Error('Service cleanup registration is closed.');
97
+ service.stops.push(hook);
98
+ },
99
+ });
100
+ }
101
+ catch (error) {
102
+ onPhase(id, 'failed', error);
103
+ if (!scope || isBitaKitStartupError(error))
104
+ throw error;
105
+ throw new BitaKitStartupError(`Service "${id}" in ${moduleLabel(owner, scope.appId)} failed to start: ${error instanceof Error ? error.message : String(error)}`, owner, { cause: error, source: service.source, app: owner === scope.appId });
106
+ }
107
+ if (isObservable(instance)) {
108
+ observed.add(instance);
109
+ service.observed.add(instance);
110
+ }
111
+ if (instance && typeof instance === 'object')
112
+ for (const value of Object.values(instance))
113
+ if (isStore(value)) {
114
+ observed.add(value);
115
+ service.observed.add(value);
116
+ }
117
+ instances[id] = decorate(id, instance, () => active && service.active);
45
118
  pending.delete(id);
46
119
  progressed = true;
47
120
  }
48
121
  if (!progressed)
49
- throw new Error(`Missing or cyclic service dependencies: ${[...pending.keys()].join(', ')}.`);
122
+ throw unresolved(pending, instances, requirements, scope, idOf);
50
123
  }
124
+ };
125
+ const initialize = () => {
126
+ if (initialized)
127
+ throw new Error('Services are already initialized.');
128
+ initialized = true;
129
+ install(definitions);
130
+ };
131
+ const start = async (signal, modules) => {
132
+ for (const service of owned) {
133
+ if (modules && !modules.has(service.module))
134
+ continue;
135
+ if (signal.aborted)
136
+ return;
137
+ service.starting = true;
138
+ try {
139
+ for (const hook of service.starts) {
140
+ if (signal.aborted)
141
+ return;
142
+ await hook({ signal });
143
+ }
144
+ if (!signal.aborted)
145
+ onPhase(service.id, 'ready');
146
+ }
147
+ catch (error) {
148
+ onPhase(service.id, 'failed', error);
149
+ throw attributed(error, service, 'onStart');
150
+ }
151
+ }
152
+ };
153
+ const stopService = (service) => {
154
+ if (service.completion)
155
+ return service.completion;
156
+ service.stopping = true;
157
+ let resolve, reject;
158
+ service.completion = new Promise((done, fail) => {
159
+ resolve = done;
160
+ reject = fail;
161
+ });
162
+ onPhase(service.id, 'stopping');
163
+ void cleanupSequence([...service.stops].reverse(), (errors) => {
164
+ try {
165
+ service.release();
166
+ }
167
+ catch (error) {
168
+ errors.push(error);
169
+ }
170
+ service.active = false;
171
+ for (const source of service.observed) {
172
+ if (!providedSources.has(source) &&
173
+ !owned.some((other) => other !== service && other.active && other.observed.has(source)))
174
+ observed.delete(source);
175
+ }
176
+ delete instances[service.id];
177
+ onPhase(service.id, errors.length ? 'failed' : 'stopped', errors[0]);
178
+ cleanupFailure(errors.map((error) => attributed(error, service, 'onStop')), `Service "${service.id}" cleanup failed.`);
179
+ }).then(resolve, reject);
180
+ return service.completion;
181
+ };
182
+ const disposeModules = async (modules) => {
183
+ const selected = owned.filter((service) => modules.has(service.module));
184
+ await cleanupSequence([...selected].reverse().map((service) => () => stopService(service)), (errors) => {
185
+ for (const service of selected)
186
+ owned.splice(owned.indexOf(service), 1);
187
+ for (const [id, definition] of pending)
188
+ if (modules.has(scope?.moduleOf(definition) ?? ''))
189
+ pending.delete(id);
190
+ cleanupFailure(errors, 'Service cleanup failed.');
191
+ });
192
+ };
193
+ const dispose = () => {
194
+ if (completion)
195
+ return completion;
196
+ stopping = true;
197
+ let resolve, reject;
198
+ completion = new Promise((done, fail) => {
199
+ resolve = done;
200
+ reject = fail;
201
+ });
202
+ void cleanupSequence([...owned].reverse().map((service) => () => stopService(service)), (errors) => {
203
+ active = false;
204
+ observed.clear();
205
+ cleanupFailure(errors, 'Service cleanup failed.');
206
+ }).then(resolve, reject);
207
+ return completion;
208
+ };
209
+ return {
210
+ services: instances,
211
+ observed,
212
+ initialize,
213
+ install,
214
+ disposeModules,
215
+ get hasStartHooks() {
216
+ return owned.some((service) => service.starts.length > 0);
217
+ },
218
+ start,
219
+ dispose,
220
+ };
221
+ }
222
+ /** Reports the first missing requirement, otherwise the dependency cycle that blocks startup. */
223
+ function unresolved(pending, instances, requirements, scope, idOf) {
224
+ const exists = (key) => Object.hasOwn(instances, key) || pending.has(key);
225
+ for (const [id, definition] of pending) {
226
+ const missing = requirements(definition).find(({ key }) => !exists(key));
227
+ if (!missing)
228
+ continue;
229
+ if (!scope)
230
+ return new Error(`Missing service "${missing.name}" required by service "${id}".`);
231
+ return scope.names.missing(scope.moduleOf(definition), missing.name, { label: `Service "${id}"`, source: scope.sourceOf(definition) }, exists);
51
232
  }
52
- catch (error) {
53
- dispose();
54
- throw error;
233
+ const path = [];
234
+ let current = pending.keys().next().value;
235
+ while (!path.includes(current)) {
236
+ path.push(current);
237
+ current = requirements(pending.get(current)).find(({ key }) => pending.has(key)).key;
55
238
  }
56
- return { services: Object.freeze(instances), dispose };
239
+ const cycle = [...path.slice(path.indexOf(current)), current].join(' → ');
240
+ const message = `Service dependency cycle: ${cycle}. Move the shared logic into a separate service that both can require.`;
241
+ if (!scope)
242
+ return new Error(message);
243
+ const definition = pending.get(current);
244
+ const owner = scope.moduleOf(definition);
245
+ void idOf;
246
+ return new BitaKitStartupError(message, owner, {
247
+ source: scope.sourceOf(definition),
248
+ app: owner === scope.appId,
249
+ });
57
250
  }
@@ -0,0 +1,19 @@
1
+ import type { Namespace } from '../app/types.js';
2
+ import type { SettingSpec, SettingsMap } from './define.js';
3
+ import type { SaveResult, SettingState, SettingsStore } from './store.js';
4
+ /** One setting as every context sees it: `settings.todos.pageSize.get()`. */
5
+ export type SettingHandle<T = unknown> = {
6
+ readonly key: string;
7
+ readonly definition: SettingSpec<T>;
8
+ get(): T;
9
+ state(): SettingState<T>;
10
+ set(value: T): Promise<SaveResult>;
11
+ reset(): Promise<SaveResult>;
12
+ subscribe(listener: () => void): () => void;
13
+ };
14
+ /** Typed handles under plugin namespaces, generated from every `settings.ts`. */
15
+ export type SettingsAccess = Namespace<{
16
+ [K in keyof SettingsMap]: SettingHandle<SettingsMap[K]>;
17
+ }>;
18
+ /** Validates declarations; namespace proxies follow the current store without copying values. */
19
+ export declare function createSettingsAccess(store: SettingsStore): SettingsAccess;
@@ -0,0 +1,78 @@
1
+ const reserved = new Set(['then', 'toJSON', 'constructor', '__proto__']);
2
+ /** Validates declarations; namespace proxies follow the current store without copying values. */
3
+ export function createSettingsAccess(store) {
4
+ const root = { children: new Map(), path: '' };
5
+ for (const entry of store.entries()) {
6
+ const segments = entry.key.split('.');
7
+ let node = root;
8
+ for (const [index, segment] of segments.entries()) {
9
+ if (reserved.has(segment))
10
+ throw new Error(`Setting "${entry.key}" uses the reserved name "${segment}".`);
11
+ const path = node.path ? `${node.path}.${segment}` : segment;
12
+ let child = node.children.get(segment);
13
+ if (!child)
14
+ node.children.set(segment, (child = { children: new Map(), path }));
15
+ if (index === segments.length - 1) {
16
+ if (child.children.size)
17
+ throw new Error(`Setting "${entry.key}" clashes with the settings of plugin "${path}". Rename the app setting.`);
18
+ child.handle = handle(store, entry.key, entry.spec);
19
+ }
20
+ else if (child.handle)
21
+ throw new Error(`Plugin "${path}" declares settings, but the app also declares a setting named "${path}". Rename the app setting.`);
22
+ node = child;
23
+ }
24
+ }
25
+ const branches = new Map();
26
+ const handles = new Map();
27
+ const project = (path) => {
28
+ const cached = branches.get(path);
29
+ if (cached)
30
+ return cached;
31
+ const keys = () => [
32
+ ...new Set(store
33
+ .entries()
34
+ .filter((entry) => !path || entry.key.startsWith(`${path}.`))
35
+ .map((entry) => entry.key.slice(path ? path.length + 1 : 0).split('.')[0])),
36
+ ];
37
+ const target = Object.create(null);
38
+ const proxy = new Proxy(target, {
39
+ get(_object, name) {
40
+ if (typeof name !== 'string' || reserved.has(name))
41
+ return undefined;
42
+ const key = path ? `${path}.${name}` : name;
43
+ if (store.has(key)) {
44
+ const spec = store.definition(key).spec;
45
+ if (handles.get(key)?.spec !== spec)
46
+ handles.set(key, { spec, value: handle(store, key, spec) });
47
+ return handles.get(key).value;
48
+ }
49
+ if (keys().includes(name))
50
+ return project(key);
51
+ const owner = path ? `plugin "${path}"` : 'the app or a plugin';
52
+ throw new Error(`Unknown setting "${key}". Declare it in settings.ts of ${owner}.`);
53
+ },
54
+ has: (_object, name) => typeof name === 'string' && keys().includes(name),
55
+ ownKeys: keys,
56
+ getOwnPropertyDescriptor: (_object, name) => typeof name === 'string' && keys().includes(name)
57
+ ? { enumerable: true, configurable: true }
58
+ : undefined,
59
+ set: () => false,
60
+ defineProperty: () => false,
61
+ deleteProperty: () => false,
62
+ });
63
+ branches.set(path, proxy);
64
+ return proxy;
65
+ };
66
+ return project('');
67
+ }
68
+ function handle(store, key, definition) {
69
+ return Object.freeze({
70
+ key,
71
+ definition,
72
+ get: () => store.get(key),
73
+ state: () => store.state(key),
74
+ set: (value) => store.set(key, value),
75
+ reset: () => store.reset(key),
76
+ subscribe: (listener) => store.subscribe(key, listener),
77
+ });
78
+ }
@@ -0,0 +1,97 @@
1
+ import type { InputSchema, SchemaOutput } from '../definitions.js';
2
+ import type { PresentationType } from '../presentation.js';
3
+ import type { GeneratedName } from '../names.js';
4
+ /** Who a value belongs to: the signed-in user, the active organization, or this browser. */
5
+ export type SettingScope = 'user' | 'organization' | 'device';
6
+ export type SettingControl = 'switch' | 'select' | 'radio' | 'cards' | 'text' | 'textarea' | 'number';
7
+ export type SettingOption<T = unknown> = {
8
+ readonly value: T;
9
+ readonly label?: string;
10
+ readonly description?: string;
11
+ readonly icon?: PresentationType<'icon'>;
12
+ };
13
+ declare const settingType: unique symbol;
14
+ /** One declared setting. Values are read and written through `settings.<plugin>.<name>`. */
15
+ export type SettingSpec<T = unknown> = {
16
+ readonly kind: 'setting';
17
+ readonly default: T;
18
+ /** zod, valibot or any Standard Schema that validates synchronously. */
19
+ readonly schema?: InputSchema<T>;
20
+ readonly scope: SettingScope;
21
+ readonly label?: string;
22
+ readonly description?: string;
23
+ /** Presentation hint for generated settings pages; inferred from the value when omitted. */
24
+ readonly control?: SettingControl;
25
+ readonly options?: readonly SettingOption<T>[];
26
+ readonly order?: number;
27
+ readonly group?: string;
28
+ /** Readable and writable, but left out of generated settings pages. */
29
+ readonly hidden?: boolean;
30
+ readonly [settingType]?: T;
31
+ };
32
+ type SettingInput<T> = {
33
+ default: T;
34
+ schema?: InputSchema<T>;
35
+ scope?: SettingScope;
36
+ label?: string;
37
+ description?: string;
38
+ control?: SettingControl;
39
+ options?: readonly SettingOption<T>[];
40
+ order?: number;
41
+ group?: string;
42
+ hidden?: boolean;
43
+ };
44
+ /** `setting({ schema: z.number().min(1), default: 20 })`: the type follows the schema. */
45
+ export declare function setting<S extends InputSchema<any>>(spec: Omit<SettingInput<SchemaOutput<S>>, 'schema'> & {
46
+ schema: S;
47
+ }): SettingSpec<SchemaOutput<S>>;
48
+ /** `setting({ default: 'system', options: [{ value: 'light' }, ...] })`: the type is the option union. */
49
+ export declare function setting<const O extends readonly SettingOption<any>[]>(spec: Omit<SettingInput<O[number]['value']>, 'schema' | 'options'> & {
50
+ schema?: undefined;
51
+ options: O;
52
+ }): SettingSpec<O[number]['value']>;
53
+ /** `setting({ default: true })`: the type follows the default. */
54
+ export declare function setting<T>(spec: SettingInput<T> & {
55
+ schema?: undefined;
56
+ options?: undefined;
57
+ }): SettingSpec<T>;
58
+ export declare function isSettingSpec(value: unknown): value is SettingSpec;
59
+ /** Optional presentation of the generated settings section of one plugin. */
60
+ export type SettingsSectionOptions = {
61
+ title?: string;
62
+ description?: string;
63
+ icon?: PresentationType<'icon'>;
64
+ /** URL segment of the generated page; defaults to the plugin ID (`general` for the app). */
65
+ path?: string;
66
+ /** Keyboard shortcut of the navigation action that opens the page, for example `Alt+Shift+O`. */
67
+ shortcut?: string;
68
+ /** Groups sections in navigation, for example `appearance` or `account`. */
69
+ category?: string;
70
+ order?: number;
71
+ };
72
+ export type SettingsDefinition<Specs extends Record<string, SettingSpec<any>> = Record<string, SettingSpec<any>>> = {
73
+ readonly kind: 'settings';
74
+ readonly settings: Specs;
75
+ readonly section?: SettingsSectionOptions;
76
+ };
77
+ /**
78
+ * Declares a plugin's settings in `settings.ts`. Keys are prefixed with the plugin ID, so
79
+ * `pageSize` in plugin `todos` is `todos.pageSize` (app settings keep their plain name). Values
80
+ * are owned by the runtime and persisted through the `settings.storage` contract.
81
+ */
82
+ export declare function defineSettings<const Specs extends Record<string, SettingSpec<any>>>(settings: Specs, section?: SettingsSectionOptions): SettingsDefinition<Specs>;
83
+ export declare function isSettingsDefinition(value: unknown): value is SettingsDefinition;
84
+ /** Validates a value against its declaration: the schema, then the option list, then the default's type. */
85
+ export declare function parseSetting<T>(spec: SettingSpec<T>, value: unknown, key?: string): T;
86
+ /** Setting keys and value types. Generated from every `settings.ts`; may also be augmented by hand. */
87
+ export interface SettingsMap {
88
+ }
89
+ /** A declared setting key; strict generated apps reject unknown keys. */
90
+ export type SettingKey = GeneratedName<Extract<keyof SettingsMap, string>>;
91
+ export type SettingValue<Key extends string> = Key extends keyof SettingsMap ? SettingsMap[Key] : unknown;
92
+ type ValueOf<S> = S extends SettingSpec<infer T> ? T : never;
93
+ /** `SettingsMap` entries of one declaration under a plugin prefix (none for the app module). */
94
+ export type SettingsOf<D, Plugin extends string> = D extends SettingsDefinition<infer Specs> ? {
95
+ [K in keyof Specs & string as Plugin extends '' ? K : `${Plugin}.${K}`]: ValueOf<Specs[K]>;
96
+ } : {};
97
+ export {};
@@ -0,0 +1,83 @@
1
+ import { validateSync } from '../schema.js';
2
+ const scopes = ['user', 'organization', 'device'];
3
+ const controls = [
4
+ 'switch',
5
+ 'select',
6
+ 'radio',
7
+ 'cards',
8
+ 'text',
9
+ 'textarea',
10
+ 'number',
11
+ ];
12
+ export function setting(spec) {
13
+ if (!spec || typeof spec !== 'object' || !('default' in spec))
14
+ throw new Error('setting() needs a default value, for example setting({ default: true }).');
15
+ const scope = spec.scope ?? 'user';
16
+ if (!scopes.includes(scope))
17
+ throw new Error(`Invalid setting scope "${scope}". Use "user", "organization" or "device".`);
18
+ if (spec.control !== undefined && !controls.includes(spec.control))
19
+ throw new Error(`Invalid setting control "${spec.control}". Use one of ${controls.join(', ')}.`);
20
+ return Object.freeze({ ...spec, kind: 'setting', scope });
21
+ }
22
+ export function isSettingSpec(value) {
23
+ return !!value && typeof value === 'object' && value.kind === 'setting';
24
+ }
25
+ /**
26
+ * Declares a plugin's settings in `settings.ts`. Keys are prefixed with the plugin ID, so
27
+ * `pageSize` in plugin `todos` is `todos.pageSize` (app settings keep their plain name). Values
28
+ * are owned by the runtime and persisted through the `settings.storage` contract.
29
+ */
30
+ export function defineSettings(settings, section) {
31
+ if (!settings || typeof settings !== 'object' || Array.isArray(settings))
32
+ throw new Error('defineSettings expects a record: defineSettings({ name: setting({ ... }) }).');
33
+ for (const [name, spec] of Object.entries(settings)) {
34
+ if (!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name))
35
+ throw new Error(`Invalid setting name "${name}". Use letters, digits, "_" or "-" without dots.`);
36
+ if (!isSettingSpec(spec))
37
+ throw new Error(`Setting "${name}" must be declared with setting({ default, ... }).`);
38
+ try {
39
+ parseSetting(spec, spec.default, name);
40
+ }
41
+ catch (error) {
42
+ throw new Error(`The default of setting "${name}" is invalid: ${error instanceof Error ? error.message : String(error)}`);
43
+ }
44
+ }
45
+ if (section?.path !== undefined && !/^[a-z][a-z0-9-]*$/.test(section.path))
46
+ throw new Error(`Invalid settings section path "${section.path}". Use lowercase letters, digits and hyphens.`);
47
+ if (section?.category !== undefined && !/^[a-z][a-z0-9-]*$/.test(section.category))
48
+ throw new Error(`Invalid settings category "${section.category}". Use lowercase letters, digits and hyphens.`);
49
+ return Object.freeze({ kind: 'settings', settings, section });
50
+ }
51
+ export function isSettingsDefinition(value) {
52
+ return !!value && typeof value === 'object' && value.kind === 'settings';
53
+ }
54
+ const show = (value) => {
55
+ try {
56
+ return JSON.stringify(value) ?? String(value);
57
+ }
58
+ catch {
59
+ return String(value);
60
+ }
61
+ };
62
+ /** Validates a value against its declaration: the schema, then the option list, then the default's type. */
63
+ export function parseSetting(spec, value, key = 'setting') {
64
+ if (spec.schema) {
65
+ const checked = validateSync(spec.schema, value);
66
+ if (!checked)
67
+ throw new Error(`Setting "${key}" uses a schema that validates asynchronously; settings schemas must be synchronous.`);
68
+ if (!checked.ok)
69
+ throw checked.error;
70
+ return checked.value;
71
+ }
72
+ if (spec.options) {
73
+ if (!spec.options.some((option) => Object.is(option.value, value)))
74
+ throw new Error(`Setting "${key}" accepts ${spec.options.map((option) => show(option.value)).join(', ')}; got ${show(value)}.`);
75
+ return value;
76
+ }
77
+ const expected = typeof spec.default;
78
+ if (spec.default !== null && spec.default !== undefined && typeof value !== expected)
79
+ throw new Error(`Setting "${key}" expects a ${expected}; got ${value === null ? 'null' : typeof value}.`);
80
+ if (expected === 'number' && !Number.isFinite(value))
81
+ throw new Error(`Setting "${key}" expects a finite number; got ${String(value)}.`);
82
+ return value;
83
+ }
@@ -0,0 +1,45 @@
1
+ import type { SettingScope } from './define.js';
2
+ /** Who a stored value belongs to. Storage decides how to key and authorize it. */
3
+ export type SettingsContext = {
4
+ readonly scope: SettingScope;
5
+ readonly userId?: string;
6
+ readonly organizationId?: string;
7
+ };
8
+ /** `value` undefined means "no stored value, use the default". */
9
+ export type StoredSetting = {
10
+ value: unknown;
11
+ writable: boolean;
12
+ };
13
+ export type SettingsLoadRequest = {
14
+ key: string;
15
+ context: SettingsContext;
16
+ };
17
+ export interface SettingsStorage {
18
+ load(key: string, context: SettingsContext): StoredSetting | Promise<StoredSetting>;
19
+ save(key: string, value: unknown, context: SettingsContext): void | Promise<void>;
20
+ /** Optional batch load; keys missing from the result are loaded individually. */
21
+ loadMany?(requests: readonly SettingsLoadRequest[]): Promise<Record<string, StoredSetting>>;
22
+ /** Removes the stored value. Without it, a reset saves the default. */
23
+ reset?(key: string, context: SettingsContext): StoredSetting | Promise<StoredSetting>;
24
+ }
25
+ /**
26
+ * The storage contract. Browser storage is the default; a host persists settings on a server
27
+ * with one service: `defineService(() => ({ load, save }), { provides: settingsStorage })`.
28
+ */
29
+ export declare const settingsStorage: import("../service-key.js").ServiceKey<SettingsStorage, "settings.storage">;
30
+ /** The slot a value lives in, or undefined when the scope has no owner yet. */
31
+ export declare function settingsOwner(context: SettingsContext): string | undefined;
32
+ export type KeyValueStore = {
33
+ getItem(key: string): string | null;
34
+ setItem(key: string, value: string): void;
35
+ removeItem(key: string): void;
36
+ };
37
+ /** In-memory storage for tests and servers without persistence. `initial` seeds values by key. */
38
+ export declare function createMemorySettingsStorage(initial?: Readonly<Record<string, unknown>>): SettingsStorage & {
39
+ readonly data: Map<string, unknown>;
40
+ };
41
+ /** Browser storage keyed by scope owner; falls back to memory where no storage exists. */
42
+ export declare function createLocalSettingsStorage(options?: {
43
+ prefix?: string;
44
+ store?: KeyValueStore;
45
+ }): SettingsStorage;