@bitakit/core 0.3.1 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +58 -2
- package/README.md +61 -18
- package/dist/contributions/action.d.ts +0 -5
- package/dist/contributions/action.js +12 -0
- package/dist/contributions/host.d.ts +3 -0
- package/dist/core.d.ts +4 -0
- package/dist/core.js +1 -0
- package/dist/definitions.d.ts +10 -0
- package/dist/events/service.d.ts +14 -0
- package/dist/events/service.js +109 -39
- package/dist/events/types.d.ts +5 -1
- package/dist/inspection/inventory.d.ts +1 -1
- package/dist/operation-error.d.ts +75 -0
- package/dist/operation-error.js +123 -0
- package/dist/remote.d.ts +60 -0
- package/dist/remote.js +156 -0
- package/dist/request-context.d.ts +62 -0
- package/dist/request-context.js +2 -0
- package/dist/runtime-mode.d.ts +35 -0
- package/dist/runtime-mode.js +6 -0
- package/dist/runtime.d.ts +17 -1
- package/dist/runtime.js +118 -50
- package/dist/server/access.d.ts +31 -0
- package/dist/server/access.js +109 -0
- package/dist/server/compile.d.ts +59 -0
- package/dist/server/compile.js +211 -0
- package/dist/server/contributions.d.ts +13 -0
- package/dist/server/contributions.js +17 -0
- package/dist/server/create-server.d.ts +15 -0
- package/dist/server/create-server.js +132 -0
- package/dist/server/define.d.ts +40 -0
- package/dist/server/define.js +15 -0
- package/dist/server/fetch-handler.d.ts +17 -0
- package/dist/server/fetch-handler.js +139 -0
- package/dist/server/index.d.ts +22 -0
- package/dist/server/index.js +21 -0
- package/dist/server/kernel.d.ts +44 -0
- package/dist/server/kernel.js +278 -0
- package/dist/server/types.d.ts +208 -0
- package/dist/server/types.js +1 -0
- package/dist/server/validate.d.ts +31 -0
- package/dist/server/validate.js +60 -0
- package/dist/services.d.ts +5 -1
- package/dist/services.js +5 -1
- package/dist/settings/access.d.ts +5 -2
- package/dist/settings/access.js +7 -4
- package/dist/settings/server.d.ts +28 -0
- package/dist/settings/server.js +94 -0
- package/package.json +7 -3
- package/testing/index.d.ts +104 -0
- package/testing/index.mjs +349 -14
package/dist/events/service.js
CHANGED
|
@@ -1,4 +1,16 @@
|
|
|
1
1
|
import { resolveName } from '../name-resolution.js';
|
|
2
|
+
/** Cached resolutions are per declaration state; the cap bounds dynamic names between changes. */
|
|
3
|
+
const cacheLimit = 1024;
|
|
4
|
+
function cached(cache, name, candidates) {
|
|
5
|
+
let resolved = cache.get(name);
|
|
6
|
+
if (resolved === undefined) {
|
|
7
|
+
resolved = resolveName(name, candidates);
|
|
8
|
+
if (cache.size >= cacheLimit)
|
|
9
|
+
cache.clear();
|
|
10
|
+
cache.set(name, resolved);
|
|
11
|
+
}
|
|
12
|
+
return resolved;
|
|
13
|
+
}
|
|
2
14
|
/**
|
|
3
15
|
* One bus per runtime. Delivery is synchronous and ordered; async handlers are awaited only
|
|
4
16
|
* for error reporting, or fully for cancelable events. Declared namespaces belong to the
|
|
@@ -13,6 +25,7 @@ export class EventService {
|
|
|
13
25
|
declared = new Map();
|
|
14
26
|
reserved = new Set();
|
|
15
27
|
reservedEvents = new Set();
|
|
28
|
+
lookupCache;
|
|
16
29
|
constructor(onError = (error, event) => {
|
|
17
30
|
console.error(`Event handler failed for "${event.type}".`, error);
|
|
18
31
|
}) {
|
|
@@ -39,21 +52,37 @@ export class EventService {
|
|
|
39
52
|
cancelable,
|
|
40
53
|
schemas,
|
|
41
54
|
});
|
|
55
|
+
this.lookupCache = undefined;
|
|
42
56
|
}
|
|
43
57
|
/** Release a stopped owner’s declaration without removing other owners’ listeners. */
|
|
44
58
|
undeclare(plugin) {
|
|
45
59
|
this.declared.delete(resolveName(plugin, this.declared.keys()));
|
|
60
|
+
this.lookupCache = undefined;
|
|
61
|
+
}
|
|
62
|
+
get lookup() {
|
|
63
|
+
return (this.lookupCache ??= {
|
|
64
|
+
names: [
|
|
65
|
+
...this.reservedEvents,
|
|
66
|
+
...[...this.declared.values()].flatMap((entry) => entry.names),
|
|
67
|
+
],
|
|
68
|
+
namespaces: [...this.declared.keys(), ...this.reserved],
|
|
69
|
+
events: new Map(),
|
|
70
|
+
owners: new Map(),
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/** The declared or reserved namespace a (case-folded) namespace reference names. */
|
|
74
|
+
namespace(name) {
|
|
75
|
+
const lookup = this.lookup;
|
|
76
|
+
return cached(lookup.owners, name, lookup.namespaces);
|
|
46
77
|
}
|
|
47
78
|
/** The plugin that declared the namespace of an event name, if any. */
|
|
48
79
|
ownerOf(name) {
|
|
49
|
-
const prefix =
|
|
80
|
+
const prefix = this.namespace(name.split('.')[0]);
|
|
50
81
|
return this.declared.has(prefix) ? prefix : undefined;
|
|
51
82
|
}
|
|
52
83
|
resolve(name) {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
...[...this.declared.values()].flatMap((entry) => entry.names),
|
|
56
|
-
]);
|
|
84
|
+
const lookup = this.lookup;
|
|
85
|
+
return cached(lookup.events, name, lookup.names);
|
|
57
86
|
}
|
|
58
87
|
isCancelable(name) {
|
|
59
88
|
name = this.resolve(name);
|
|
@@ -64,19 +93,28 @@ export class EventService {
|
|
|
64
93
|
if (this.declared.has(namespace) || this.reserved.has(namespace))
|
|
65
94
|
throw new Error(`Event namespace "${namespace}" is already owned.`);
|
|
66
95
|
this.reserved.add(namespace);
|
|
96
|
+
this.lookupCache = undefined;
|
|
67
97
|
return (name, data) => {
|
|
68
98
|
if (!name.startsWith(`${namespace}.`))
|
|
69
99
|
throw new Error('Event is outside the reserved namespace.');
|
|
70
|
-
this.reservedEvents.
|
|
100
|
+
if (!this.reservedEvents.has(name)) {
|
|
101
|
+
this.reservedEvents.add(name);
|
|
102
|
+
this.lookupCache = undefined;
|
|
103
|
+
}
|
|
71
104
|
this.dispatch(name, data);
|
|
72
105
|
};
|
|
73
106
|
}
|
|
74
|
-
emit = ((name, data) =>
|
|
75
|
-
|
|
107
|
+
emit = ((name, data) => this.emitWithContext(undefined, name, data));
|
|
108
|
+
/**
|
|
109
|
+
* Emits on behalf of a server call: listeners receive `ctx` as `{ signal, ctx }`. It is never
|
|
110
|
+
* part of the event object. `undefined` behaves exactly like `emit`.
|
|
111
|
+
*/
|
|
112
|
+
emitWithContext(ctx, name, data) {
|
|
113
|
+
if (this.reserved.has(this.namespace(name.split('.')[0])))
|
|
76
114
|
throw new Error(`Event "${name}" is emitted only by the runtime.`);
|
|
77
|
-
return this.dispatch(name, data);
|
|
78
|
-
}
|
|
79
|
-
dispatch = (name, data) => {
|
|
115
|
+
return this.dispatch(name, data, ctx);
|
|
116
|
+
}
|
|
117
|
+
dispatch = (name, data, ctx) => {
|
|
80
118
|
name = this.resolve(name);
|
|
81
119
|
const schema = this.declared.get(name.split('.')[0])?.schemas.get(name);
|
|
82
120
|
if (this.isCancelable(name)) {
|
|
@@ -88,13 +126,13 @@ export class EventService {
|
|
|
88
126
|
catch (error) {
|
|
89
127
|
return Promise.reject(error);
|
|
90
128
|
}
|
|
91
|
-
return this.emitCancelable(name, checked);
|
|
129
|
+
return this.emitCancelable(name, checked, ctx);
|
|
92
130
|
}
|
|
93
131
|
const payload = schema ? schema.parse(data) : data;
|
|
94
132
|
const event = Object.freeze({ type: name, data: payload });
|
|
95
133
|
for (const listener of this.listenersFor(name)) {
|
|
96
134
|
try {
|
|
97
|
-
const result = listener(event);
|
|
135
|
+
const result = listener(event, ctx);
|
|
98
136
|
if (result && typeof result.then === 'function')
|
|
99
137
|
void result.catch((error) => this.report(error, event));
|
|
100
138
|
}
|
|
@@ -111,7 +149,7 @@ export class EventService {
|
|
|
111
149
|
}
|
|
112
150
|
}
|
|
113
151
|
};
|
|
114
|
-
async emitCancelable(name, data) {
|
|
152
|
+
async emitCancelable(name, data, ctx) {
|
|
115
153
|
let cancelled = false;
|
|
116
154
|
const event = Object.freeze({
|
|
117
155
|
type: name,
|
|
@@ -126,7 +164,7 @@ export class EventService {
|
|
|
126
164
|
const pending = [];
|
|
127
165
|
for (const listener of this.listenersFor(name)) {
|
|
128
166
|
try {
|
|
129
|
-
const result = listener(event);
|
|
167
|
+
const result = listener(event, ctx);
|
|
130
168
|
if (result && typeof result.then === 'function')
|
|
131
169
|
pending.push(result.catch((error) => this.report(error, event)));
|
|
132
170
|
}
|
|
@@ -145,24 +183,46 @@ export class EventService {
|
|
|
145
183
|
}
|
|
146
184
|
return !cancelled;
|
|
147
185
|
}
|
|
186
|
+
/** Exact listeners (in subscription order), then prefix listeners; each listener once. */
|
|
148
187
|
listenersFor(name) {
|
|
188
|
+
const lookup = this.lookup;
|
|
189
|
+
const exact = (lookup.exact ??= this.indexExact());
|
|
190
|
+
const failed = (error) => this.report(error, Object.freeze({ type: name, data: undefined }));
|
|
191
|
+
exact.failures.forEach(failed);
|
|
149
192
|
const result = [];
|
|
150
|
-
const
|
|
193
|
+
for (const listeners of exact.byName.get(name) ?? [])
|
|
194
|
+
result.push(...listeners);
|
|
195
|
+
for (const [prefix, listeners] of this.prefixes) {
|
|
151
196
|
try {
|
|
152
|
-
if (
|
|
197
|
+
if (name.startsWith(prefix ? `${this.namespace(prefix.slice(0, -1))}.` : ''))
|
|
153
198
|
result.push(...listeners);
|
|
154
199
|
}
|
|
155
200
|
catch (error) {
|
|
156
|
-
|
|
201
|
+
failed(error);
|
|
157
202
|
}
|
|
158
|
-
}
|
|
159
|
-
for (const [requested, listeners] of this.exact)
|
|
160
|
-
select(listeners, () => this.resolve(requested) === name);
|
|
161
|
-
const namespaces = [...this.declared.keys(), ...this.reserved];
|
|
162
|
-
for (const [prefix, listeners] of this.prefixes)
|
|
163
|
-
select(listeners, () => name.startsWith(prefix ? `${resolveName(prefix.slice(0, -1), namespaces)}.` : ''));
|
|
203
|
+
}
|
|
164
204
|
return [...new Set(result)];
|
|
165
205
|
}
|
|
206
|
+
indexExact() {
|
|
207
|
+
const byName = new Map();
|
|
208
|
+
const failures = [];
|
|
209
|
+
for (const [requested, listeners] of this.exact) {
|
|
210
|
+
let name;
|
|
211
|
+
try {
|
|
212
|
+
name = this.resolve(requested);
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
failures.push(error);
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
const sets = byName.get(name);
|
|
219
|
+
if (sets)
|
|
220
|
+
sets.push(listeners);
|
|
221
|
+
else
|
|
222
|
+
byName.set(name, [listeners]);
|
|
223
|
+
}
|
|
224
|
+
return { byName, failures };
|
|
225
|
+
}
|
|
166
226
|
report(error, event) {
|
|
167
227
|
try {
|
|
168
228
|
this.onError(error, event);
|
|
@@ -176,14 +236,14 @@ export class EventService {
|
|
|
176
236
|
const keys = [...new Set(typeof names === 'string' ? [names] : names)];
|
|
177
237
|
for (const name of keys) {
|
|
178
238
|
if (name.endsWith('.*'))
|
|
179
|
-
|
|
239
|
+
this.namespace(name.slice(0, -2));
|
|
180
240
|
else if (name !== '*')
|
|
181
241
|
this.resolve(name);
|
|
182
242
|
}
|
|
183
|
-
const invoke = (event) => {
|
|
243
|
+
const invoke = (event, ctx) => {
|
|
184
244
|
if (controller.signal.aborted)
|
|
185
245
|
return;
|
|
186
|
-
return handler(event, { signal: controller.signal });
|
|
246
|
+
return handler(event, ctx === undefined ? { signal: controller.signal } : { signal: controller.signal, ctx });
|
|
187
247
|
};
|
|
188
248
|
const targets = keys.map((key) => key.endsWith('.*')
|
|
189
249
|
? { map: this.prefixes, key: key.slice(0, -1) }
|
|
@@ -192,8 +252,11 @@ export class EventService {
|
|
|
192
252
|
: { map: this.exact, key });
|
|
193
253
|
for (const { map, key } of targets) {
|
|
194
254
|
let set = map.get(key);
|
|
195
|
-
if (!set)
|
|
255
|
+
if (!set) {
|
|
196
256
|
map.set(key, (set = new Set()));
|
|
257
|
+
if (map === this.exact && this.lookupCache)
|
|
258
|
+
this.lookupCache.exact = undefined;
|
|
259
|
+
}
|
|
197
260
|
set.add(invoke);
|
|
198
261
|
}
|
|
199
262
|
const unsubscribe = () => {
|
|
@@ -202,8 +265,11 @@ export class EventService {
|
|
|
202
265
|
for (const { map, key } of targets) {
|
|
203
266
|
const set = map.get(key);
|
|
204
267
|
set?.delete(invoke);
|
|
205
|
-
if (set && !set.size)
|
|
268
|
+
if (set && !set.size) {
|
|
206
269
|
map.delete(key);
|
|
270
|
+
if (map === this.exact && this.lookupCache)
|
|
271
|
+
this.lookupCache.exact = undefined;
|
|
272
|
+
}
|
|
207
273
|
}
|
|
208
274
|
this.subscriptions.delete(unsubscribe);
|
|
209
275
|
controller.abort();
|
|
@@ -229,6 +295,7 @@ export class EventService {
|
|
|
229
295
|
this.prefixes.clear();
|
|
230
296
|
this.observers.clear();
|
|
231
297
|
this.declared.clear();
|
|
298
|
+
this.lookupCache = undefined;
|
|
232
299
|
}
|
|
233
300
|
}
|
|
234
301
|
/**
|
|
@@ -238,17 +305,18 @@ export class EventService {
|
|
|
238
305
|
export function createEventScope(events, owner) {
|
|
239
306
|
let active = true;
|
|
240
307
|
const cleanups = new Set();
|
|
308
|
+
const emitter = (ctx) => ((name, data) => {
|
|
309
|
+
if (!active)
|
|
310
|
+
return undefined;
|
|
311
|
+
const declaredBy = events.ownerOf(name);
|
|
312
|
+
if (owner !== undefined &&
|
|
313
|
+
declaredBy !== undefined &&
|
|
314
|
+
declaredBy !== (events.ownerOf(`${owner}.__owner`) ?? owner))
|
|
315
|
+
throw new Error(`"${owner}" cannot emit "${name}": that event belongs to plugin "${declaredBy}". Only the declaring plugin emits its events; listen with events.on instead.`);
|
|
316
|
+
return events.emitWithContext(ctx, name, data);
|
|
317
|
+
});
|
|
241
318
|
const scoped = {
|
|
242
|
-
emit: (
|
|
243
|
-
if (!active)
|
|
244
|
-
return undefined;
|
|
245
|
-
const declaredBy = events.ownerOf(name);
|
|
246
|
-
if (owner !== undefined &&
|
|
247
|
-
declaredBy !== undefined &&
|
|
248
|
-
declaredBy !== (events.ownerOf(`${owner}.__owner`) ?? owner))
|
|
249
|
-
throw new Error(`"${owner}" cannot emit "${name}": that event belongs to plugin "${declaredBy}". Only the declaring plugin emits its events; listen with events.on instead.`);
|
|
250
|
-
return events.emit(name, ...data);
|
|
251
|
-
}),
|
|
319
|
+
emit: emitter(undefined),
|
|
252
320
|
on: ((names, handler) => {
|
|
253
321
|
if (!active)
|
|
254
322
|
throw new Error('Event scope is no longer active.');
|
|
@@ -263,6 +331,8 @@ export function createEventScope(events, owner) {
|
|
|
263
331
|
};
|
|
264
332
|
return {
|
|
265
333
|
events: scoped,
|
|
334
|
+
/** The same view whose `emit` hands a server call's `ctx` to listeners. */
|
|
335
|
+
withContext: (ctx) => ({ emit: emitter(ctx), on: scoped.on }),
|
|
266
336
|
dispose() {
|
|
267
337
|
if (!active)
|
|
268
338
|
return;
|
package/dist/events/types.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { NamedValue, NameKey } from '../name-resolution.js';
|
|
2
2
|
import type { GeneratedName, CheckedName } from '../names.js';
|
|
3
|
+
import type { RequestContext } from '../request-context.js';
|
|
3
4
|
/** Event names and payloads. Generated from every plugin's `events.ts`; may also be augmented by hand. */
|
|
4
5
|
export interface EventMap {
|
|
5
6
|
}
|
|
@@ -25,8 +26,11 @@ export type BitaKitEvent<Name extends string = string> = Name extends string ? R
|
|
|
25
26
|
cancel?: (reason?: string) => void;
|
|
26
27
|
cancelled?: boolean;
|
|
27
28
|
}> : never;
|
|
28
|
-
export type EventHandler<Name extends string = string> = (event: BitaKitEvent<EventsMatching<Name>>,
|
|
29
|
+
export type EventHandler<Name extends string = string> = (event: BitaKitEvent<EventsMatching<Name>>,
|
|
30
|
+
/** `ctx` is the request context when a server operation emitted the event, else absent. */
|
|
31
|
+
context: {
|
|
29
32
|
signal: AbortSignal;
|
|
33
|
+
ctx?: RequestContext;
|
|
30
34
|
}) => void | Promise<void>;
|
|
31
35
|
export type EventErrorHandler = (error: unknown, event: BitaKitEvent) => void;
|
|
32
36
|
export type EmitResult<Name extends string> = [NameKey<CancelableEventMap, Name>] extends [never] ? void : NameKey<CancelableEventMap, Name> extends keyof CancelableEventMap ? Promise<boolean> : void;
|
|
@@ -2,7 +2,7 @@ import type { PluginMetadata } from '../definitions.js';
|
|
|
2
2
|
import type { LifecyclePhase, LifecycleSnapshot } from '../lifecycle/state.js';
|
|
3
3
|
import type { BitaKitRuntime } from '../runtime.js';
|
|
4
4
|
import { type PluginOrigin, type PackageIdentity, type PluginMembership } from './plugin-origin.js';
|
|
5
|
-
export type InventoryKind = 'service' | 'action' | 'event' | 'page' | 'setting' | 'slot' | 'widget' | 'provider' | 'config' | 'interceptor';
|
|
5
|
+
export type InventoryKind = 'service' | 'action' | 'event' | 'page' | 'setting' | 'slot' | 'widget' | 'provider' | 'config' | 'interceptor' | 'server-action' | 'server-service' | 'server-interceptor';
|
|
6
6
|
export type InventoryDeclaration = Readonly<{
|
|
7
7
|
kind: InventoryKind;
|
|
8
8
|
id: string | null;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The request-error model of server operations, shared by the server kernel, its HTTP handler
|
|
3
|
+
* and the client's `remote`. Startup errors (`BitaKitStartupError`) remain a separate model.
|
|
4
|
+
*/
|
|
5
|
+
declare const statuses: {
|
|
6
|
+
readonly BAD_REQUEST: 400;
|
|
7
|
+
readonly UNAUTHORIZED: 401;
|
|
8
|
+
readonly FORBIDDEN: 403;
|
|
9
|
+
readonly NOT_FOUND: 404;
|
|
10
|
+
readonly METHOD_NOT_SUPPORTED: 405;
|
|
11
|
+
readonly CONFLICT: 409;
|
|
12
|
+
readonly PAYLOAD_TOO_LARGE: 413;
|
|
13
|
+
readonly UNSUPPORTED_MEDIA_TYPE: 415;
|
|
14
|
+
readonly TOO_MANY_REQUESTS: 429;
|
|
15
|
+
readonly INTERNAL_SERVER_ERROR: 500;
|
|
16
|
+
readonly SERVICE_UNAVAILABLE: 503;
|
|
17
|
+
};
|
|
18
|
+
export type OperationErrorCode = keyof typeof statuses;
|
|
19
|
+
/** One input problem: the path into the input (`['items', 0, 'title']`) and a safe message. */
|
|
20
|
+
export type OperationIssue = {
|
|
21
|
+
readonly path: readonly (string | number)[];
|
|
22
|
+
readonly message: string;
|
|
23
|
+
};
|
|
24
|
+
/** Why an access check failed, for clients that react differently to each case. */
|
|
25
|
+
export type OperationErrorReason = 'NO_ACTIVE_ORGANIZATION' | 'NOT_A_MEMBER' | 'PERMISSION' | 'ORGANIZATION_CHANGED' | 'INTERCEPTED';
|
|
26
|
+
export type OperationErrorJSON = {
|
|
27
|
+
code: OperationErrorCode;
|
|
28
|
+
message: string;
|
|
29
|
+
issues?: readonly OperationIssue[];
|
|
30
|
+
reason?: OperationErrorReason | (string & {});
|
|
31
|
+
requestId?: string;
|
|
32
|
+
};
|
|
33
|
+
/** The HTTP status of a code; unknown codes answer 500. */
|
|
34
|
+
export declare function operationStatus(code: string): number;
|
|
35
|
+
/** The code of an HTTP error status (`429` → TOO_MANY_REQUESTS); any other status is a 500. */
|
|
36
|
+
export declare function operationCodeOf(status: number): OperationErrorCode;
|
|
37
|
+
/** True for a code this version knows. */
|
|
38
|
+
export declare const isOperationErrorCode: (code: unknown) => code is OperationErrorCode;
|
|
39
|
+
/**
|
|
40
|
+
* An error an operation may show to its caller. Only `safeMessage`, `code`, `issues`, `reason`
|
|
41
|
+
* and `requestId` ever leave the server (`toJSON`); `cause` and `stack` stay in the logs. The
|
|
42
|
+
* kernel passes only branded instances through, so throw this for expected failures (not found,
|
|
43
|
+
* conflict, invalid state) and let everything else become INTERNAL_SERVER_ERROR.
|
|
44
|
+
*/
|
|
45
|
+
export declare class OperationError extends Error {
|
|
46
|
+
readonly code: OperationErrorCode;
|
|
47
|
+
/** The text clients may display; never contains internal details. */
|
|
48
|
+
readonly safeMessage: string;
|
|
49
|
+
readonly issues?: readonly OperationIssue[];
|
|
50
|
+
readonly reason?: OperationErrorReason | (string & {});
|
|
51
|
+
/**
|
|
52
|
+
* Correlates the answer with the server log line; set on kernel-made 500 and 503 errors and on
|
|
53
|
+
* an input error whose cause the kernel logged.
|
|
54
|
+
*/
|
|
55
|
+
readonly requestId?: string;
|
|
56
|
+
readonly status: number;
|
|
57
|
+
constructor(code: OperationErrorCode, safeMessage: string, options?: {
|
|
58
|
+
issues?: readonly OperationIssue[];
|
|
59
|
+
reason?: OperationErrorReason | (string & {});
|
|
60
|
+
requestId?: string;
|
|
61
|
+
cause?: unknown;
|
|
62
|
+
});
|
|
63
|
+
toJSON(): OperationErrorJSON;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* True for errors created by any copy of `OperationError` (the brand is `Symbol.for`), so it holds
|
|
67
|
+
* across bundles and package copies. It never looks at `code`: an error-like object from another
|
|
68
|
+
* library with `code: 'NOT_FOUND'` is not an OperationError.
|
|
69
|
+
*/
|
|
70
|
+
export declare function isOperationError(value: unknown): value is OperationError;
|
|
71
|
+
/** The wire form, read field by field so a foreign copy's extra fields never leak. */
|
|
72
|
+
export declare function operationErrorBody(error: OperationError): OperationErrorJSON;
|
|
73
|
+
/** Rebuilds an error from its wire form (the client's `remote`); malformed bodies become a 500. */
|
|
74
|
+
export declare function operationErrorFrom(body: unknown): OperationError;
|
|
75
|
+
export {};
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The request-error model of server operations, shared by the server kernel, its HTTP handler
|
|
3
|
+
* and the client's `remote`. Startup errors (`BitaKitStartupError`) remain a separate model.
|
|
4
|
+
*/
|
|
5
|
+
const statuses = {
|
|
6
|
+
BAD_REQUEST: 400,
|
|
7
|
+
UNAUTHORIZED: 401,
|
|
8
|
+
FORBIDDEN: 403,
|
|
9
|
+
NOT_FOUND: 404,
|
|
10
|
+
METHOD_NOT_SUPPORTED: 405,
|
|
11
|
+
CONFLICT: 409,
|
|
12
|
+
PAYLOAD_TOO_LARGE: 413,
|
|
13
|
+
UNSUPPORTED_MEDIA_TYPE: 415,
|
|
14
|
+
TOO_MANY_REQUESTS: 429,
|
|
15
|
+
INTERNAL_SERVER_ERROR: 500,
|
|
16
|
+
SERVICE_UNAVAILABLE: 503,
|
|
17
|
+
};
|
|
18
|
+
const brand = Symbol.for('bitakit.operation-error');
|
|
19
|
+
/** The HTTP status of a code; unknown codes answer 500. */
|
|
20
|
+
export function operationStatus(code) {
|
|
21
|
+
return Object.hasOwn(statuses, code) ? statuses[code] : 500;
|
|
22
|
+
}
|
|
23
|
+
/** The code of an HTTP error status (`429` → TOO_MANY_REQUESTS); any other status is a 500. */
|
|
24
|
+
export function operationCodeOf(status) {
|
|
25
|
+
for (const [code, value] of Object.entries(statuses))
|
|
26
|
+
if (value === status)
|
|
27
|
+
return code;
|
|
28
|
+
return 'INTERNAL_SERVER_ERROR';
|
|
29
|
+
}
|
|
30
|
+
/** True for a code this version knows. */
|
|
31
|
+
export const isOperationErrorCode = (code) => typeof code === 'string' && Object.hasOwn(statuses, code);
|
|
32
|
+
/**
|
|
33
|
+
* An error an operation may show to its caller. Only `safeMessage`, `code`, `issues`, `reason`
|
|
34
|
+
* and `requestId` ever leave the server (`toJSON`); `cause` and `stack` stay in the logs. The
|
|
35
|
+
* kernel passes only branded instances through, so throw this for expected failures (not found,
|
|
36
|
+
* conflict, invalid state) and let everything else become INTERNAL_SERVER_ERROR.
|
|
37
|
+
*/
|
|
38
|
+
export class OperationError extends Error {
|
|
39
|
+
code;
|
|
40
|
+
/** The text clients may display; never contains internal details. */
|
|
41
|
+
safeMessage;
|
|
42
|
+
issues;
|
|
43
|
+
reason;
|
|
44
|
+
/**
|
|
45
|
+
* Correlates the answer with the server log line; set on kernel-made 500 and 503 errors and on
|
|
46
|
+
* an input error whose cause the kernel logged.
|
|
47
|
+
*/
|
|
48
|
+
requestId;
|
|
49
|
+
status;
|
|
50
|
+
constructor(code, safeMessage, options = {}) {
|
|
51
|
+
if (!Object.hasOwn(statuses, code))
|
|
52
|
+
throw new TypeError(`Unknown operation error code "${String(code)}".`);
|
|
53
|
+
super(safeMessage, options.cause === undefined ? undefined : { cause: options.cause });
|
|
54
|
+
this.name = 'OperationError';
|
|
55
|
+
this.code = code;
|
|
56
|
+
this.safeMessage = String(safeMessage);
|
|
57
|
+
this.status = statuses[code];
|
|
58
|
+
if (options.issues)
|
|
59
|
+
this.issues = Object.freeze(options.issues.map(freezeIssue));
|
|
60
|
+
if (options.reason !== undefined)
|
|
61
|
+
this.reason = options.reason;
|
|
62
|
+
if (options.requestId !== undefined)
|
|
63
|
+
this.requestId = options.requestId;
|
|
64
|
+
Object.defineProperty(this, brand, { value: true });
|
|
65
|
+
}
|
|
66
|
+
toJSON() {
|
|
67
|
+
return operationErrorBody(this);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function freezeIssue(issue) {
|
|
71
|
+
return Object.freeze({
|
|
72
|
+
path: Object.freeze([...(issue.path ?? [])]),
|
|
73
|
+
message: String(issue.message),
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* True for errors created by any copy of `OperationError` (the brand is `Symbol.for`), so it holds
|
|
78
|
+
* across bundles and package copies. It never looks at `code`: an error-like object from another
|
|
79
|
+
* library with `code: 'NOT_FOUND'` is not an OperationError.
|
|
80
|
+
*/
|
|
81
|
+
export function isOperationError(value) {
|
|
82
|
+
return !!value && typeof value === 'object' && value[brand] === true;
|
|
83
|
+
}
|
|
84
|
+
/** The wire form, read field by field so a foreign copy's extra fields never leak. */
|
|
85
|
+
export function operationErrorBody(error) {
|
|
86
|
+
const code = Object.hasOwn(statuses, error.code) ? error.code : 'INTERNAL_SERVER_ERROR';
|
|
87
|
+
return {
|
|
88
|
+
code,
|
|
89
|
+
message: String(error.safeMessage),
|
|
90
|
+
...(error.issues?.length
|
|
91
|
+
? {
|
|
92
|
+
issues: error.issues.map((issue) => ({
|
|
93
|
+
path: [...issue.path],
|
|
94
|
+
message: String(issue.message),
|
|
95
|
+
})),
|
|
96
|
+
}
|
|
97
|
+
: {}),
|
|
98
|
+
...(typeof error.reason === 'string' ? { reason: error.reason } : {}),
|
|
99
|
+
...(typeof error.requestId === 'string' ? { requestId: error.requestId } : {}),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/** Rebuilds an error from its wire form (the client's `remote`); malformed bodies become a 500. */
|
|
103
|
+
export function operationErrorFrom(body) {
|
|
104
|
+
const value = (body ?? {});
|
|
105
|
+
const code = typeof value.code === 'string' && Object.hasOwn(statuses, value.code)
|
|
106
|
+
? value.code
|
|
107
|
+
: 'INTERNAL_SERVER_ERROR';
|
|
108
|
+
const issues = Array.isArray(value.issues)
|
|
109
|
+
? value.issues
|
|
110
|
+
.filter((issue) => issue && typeof issue.message === 'string')
|
|
111
|
+
.map((issue) => ({
|
|
112
|
+
path: Array.isArray(issue.path)
|
|
113
|
+
? issue.path.filter((part) => typeof part === 'string' || typeof part === 'number')
|
|
114
|
+
: [],
|
|
115
|
+
message: issue.message,
|
|
116
|
+
}))
|
|
117
|
+
: undefined;
|
|
118
|
+
return new OperationError(code, typeof value.message === 'string' ? value.message : 'Something went wrong.', {
|
|
119
|
+
issues,
|
|
120
|
+
reason: typeof value.reason === 'string' ? value.reason : undefined,
|
|
121
|
+
requestId: typeof value.requestId === 'string' ? value.requestId : undefined,
|
|
122
|
+
});
|
|
123
|
+
}
|
package/dist/remote.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { Namespace } from './app/types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Every server Action as `{ input; result; exposed }`, by ID. Empty here; the generated server
|
|
4
|
+
* file (`src/bitakit.gen.server.ts`) augments it. `remote` types the exposed entries, the
|
|
5
|
+
* server's in-process `Caller` all of them.
|
|
6
|
+
*/
|
|
7
|
+
export interface ServerActionMap {
|
|
8
|
+
}
|
|
9
|
+
/** Server services by ID and alias; augmented by the generated server file, never `ServiceMap`. */
|
|
10
|
+
export interface ServerServiceMap {
|
|
11
|
+
}
|
|
12
|
+
/** Per-call options of `remote.<plugin>.<name>(input, options)`. */
|
|
13
|
+
export type RemoteCallOptions = {
|
|
14
|
+
signal?: AbortSignal;
|
|
15
|
+
/**
|
|
16
|
+
* The organization the caller's data was loaded under; overrides the `auth` snapshot. The server
|
|
17
|
+
* answers CONFLICT (`ORGANIZATION_CHANGED`) when the session's organization differs. `null` or
|
|
18
|
+
* `''` means "none".
|
|
19
|
+
*/
|
|
20
|
+
organizationId?: string | null;
|
|
21
|
+
};
|
|
22
|
+
/** One function per operation; the input is optional when the operation takes none. */
|
|
23
|
+
export type OperationFunction<Entry, Options> = Entry extends {
|
|
24
|
+
input: infer Input;
|
|
25
|
+
result: infer Result;
|
|
26
|
+
} ? undefined extends Input ? (input?: Input, options?: Options) => Promise<Result> : (input: Input, options?: Options) => Promise<Result> : never;
|
|
27
|
+
type ExposedId = {
|
|
28
|
+
[K in keyof ServerActionMap & string]: ServerActionMap[K] extends {
|
|
29
|
+
exposed: true;
|
|
30
|
+
} ? K : never;
|
|
31
|
+
}[keyof ServerActionMap & string];
|
|
32
|
+
/** The exposed server operations as nested functions: `remote.todos.add(input)`. */
|
|
33
|
+
export type Remote = Namespace<{
|
|
34
|
+
[K in ExposedId]: OperationFunction<ServerActionMap[K], RemoteCallOptions>;
|
|
35
|
+
}>;
|
|
36
|
+
/** Generated into the client config when exposed server Actions exist. */
|
|
37
|
+
export type RemoteConfig = {
|
|
38
|
+
readonly endpoint: string;
|
|
39
|
+
readonly operations: readonly string[];
|
|
40
|
+
};
|
|
41
|
+
export declare const organizationHeader = "x-bitakit-organization";
|
|
42
|
+
/**
|
|
43
|
+
* Name segments no server Action ID may use. As properties of `remote` or the in-process caller
|
|
44
|
+
* they would make a namespace thenable (`then`), observable (`subscribe`), or called by
|
|
45
|
+
* serialization and conversion (`toJSON`, `valueOf`, `toString`), or shadow Promise and object
|
|
46
|
+
* plumbing (`catch`, `finally`, `constructor`, `prototype`). The kernel refuses such IDs at
|
|
47
|
+
* startup; `remote` and the caller never offer them.
|
|
48
|
+
*/
|
|
49
|
+
export declare const reservedSegments: ReadonlySet<string>;
|
|
50
|
+
/** The first reserved segment of an operation ID, if it has one. */
|
|
51
|
+
export declare const reservedSegmentOf: (id: string) => string | undefined;
|
|
52
|
+
/**
|
|
53
|
+
* Builds `remote` once per runtime: nested plain, frozen functions (never a Proxy, never
|
|
54
|
+
* observable), one per configured operation, each a `POST <endpoint>/<id>` with a JSON body.
|
|
55
|
+
* `organization` reads the default organization header at call time (undefined: no header).
|
|
56
|
+
* Without a configuration every call rejects with SERVICE_UNAVAILABLE instead of a TypeError.
|
|
57
|
+
* IDs with a reserved segment (`reservedSegments`) are left out with one warning.
|
|
58
|
+
*/
|
|
59
|
+
export declare function createRemote(config: RemoteConfig | undefined, organization?: () => string | undefined): Remote;
|
|
60
|
+
export {};
|