Repository navigation
Expand file tree
/
Copy pathhook-binder.ts
More file actions
497 lines (466 loc) · 21.8 KB
/
Copy pathhook-binder.ts
File metadata and controls
497 lines (466 loc) · 21.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* Hook Binder
*
* Single, canonical entry point that turns declarative `Hook` metadata into
* runtime registrations on the `ObjectQL` engine. Every metadata source —
* `defineStack({ hooks })` (consumed by `AppPlugin`), the per-project
* template seeder (`MultiProjectPlugin`), and the metadata service
* (`ObjectQLPlugin.loadMetadataFromService`) — funnels through here so
* that:
*
* - Inline function handlers and string-named handlers share one resolver.
* - Declarative fields (`condition`, `async`, `retryPolicy`, `timeoutMs`,
* `onError`) are honoured uniformly via `wrapDeclarativeHook`.
* - Hooks can be unregistered as a unit via `packageId`, enabling clean
* hot-reload and app uninstall.
*
* The ObjectQL engine itself stays simple — it knows how to store and
* trigger handlers, but knows nothing about declarative semantics. All
* metadata-aware behaviour lives in this binder + the wrapper module.
*/
import type { Hook, HookContext } from '@objectstack/spec/data';
import { normalizeFlowFunctionEntry, type FlowFunctionEntry } from '@objectstack/spec/automation';
import type { ObjectQL, HookHandler } from './engine.js';
import { wrapDeclarativeHook, type HookDiagnosticsLogger } from './hook-wrappers.js';
import type { HookMetricsRecorder } from './hook-metrics.js';
import { handlerOwnerPackageId } from './bare-name-one-holder.js';
export interface BindHooksOptions {
/** Owning package / app id — used for `unregisterHooksByPackage`. */
packageId?: string;
/**
* Optional name → function map for resolving string `handler` references.
* Typically supplied by `defineStack({ functions })` (an artifact's runtime
* module supplies it on the artifact path). A string `handler` resolves
* against this map, then against the functions registered on the engine
* under the SAME `packageId` — never another package's; a name neither
* holds is refused at registration ({@link HOOK_HANDLER_NOT_IN_PACKAGE_CODE}).
*
* A value may be the handler itself or a declaration record stating what the
* function does (`{ handler, effect: 'writes' }`, #4396) — the same two
* spellings `defineStack({ functions })` accepts. The declaration is stored
* on the registry entry, where the `script` node reads it to report the run's
* metrics honestly; hook binding itself only ever needs the handler.
*/
functions?: Record<string, FlowFunctionEntry>;
/**
* Optional factory that converts a metadata-only `Hook.body` (L1 expression
* or L2 sandboxed JS source) into an executable `HookHandler`. The runtime
* package wires this up using `QuickJSScriptRunner`; objectql itself stays
* sandbox-free so it can run in lightweight environments.
*
* If `hook.body` is set and this factory is missing, the hook is skipped
* with a clear error.
*/
bodyRunner?: (hook: Hook) => HookHandler | undefined;
/**
* Optional wrap for each handler the hook runs IN-PROCESS: an inline
* `handler` function, and the function a string `handler` names (from
* `functions` or the package's registered functions). It is applied here,
* after the name is resolved, so both kinds take the one wrap; the handler
* `bodyRunner` builds from a `body` never does. Called once per hook, at bind.
*
* The runtime passes the wrap that hands an in-process handler the
* `ctx.title(field?)` a sandboxed `body` gets (#24289). Absent, every handler
* binds exactly as resolved.
*/
wrapHandler?: (
handler: (context: HookContext) => unknown,
hook: Hook,
) => (context: HookContext) => unknown;
/**
* When true, treat unresolved hooks (body present but no runner, or handler
* string with no implementation) as fatal errors instead of warnings. Used
* by production runtimes to fail fast on misconfiguration. Defaults false.
*/
strict?: boolean;
/**
* When true, emit a deprecation warning for every hook that still relies
* on a `handler` ref string instead of the metadata-only `body`. Used by
* the CLI (compile time) and runtime (boot time) to nudge users away from
* the legacy `.mjs` runtime bundle path. Defaults false.
*/
warnLegacyHandler?: boolean;
/** Per-hook execution metrics sink. Defaults to no-op. */
metrics?: HookMetricsRecorder;
/**
* Logger; defaults to a silent no-op.
*
* The `Logger` contract, narrowed to the levels this layer uses — the SAME
* type the wrapper takes, since every logger handed to the binder is passed
* straight through to `wrapDeclarativeHook`. See
* {@link HookDiagnosticsLogger} for why this is not a locally-declared shape
* (#5637).
*/
logger?: HookDiagnosticsLogger;
}
const noopLogger: HookDiagnosticsLogger = {
debug: () => {},
info: () => {},
warn: () => {},
error: () => {},
};
/** Counter for stats. */
export interface BindHooksResult {
registered: number;
skipped: number;
/**
* One entry per hook that did not bind. `code` and `status` are set when the
* failure is a coded registration refusal (ADR-0112 envelope) — today a
* `handler` naming a function the hook's own package does not hold
* ({@link HOOK_HANDLER_NOT_IN_PACKAGE_CODE}).
*/
errors: Array<{ hook: string; reason: string; code?: string; status?: number }>;
}
/**
* The refusal of a hook whose `handler` names a function its own package does
* not hold, as the ADR-0112 envelope carries it.
*
* A hook's `handler` name resolves inside the hook's own package only: the
* functions handed to its bind (the package's `functions`, which its runtime
* module supplies) and the functions the same package registered on the
* engine. A name the package does not hold — a typo, or a function another
* package registered — is refused at registration and the hook is not bound.
*
* `INVALID_REFERENCE` is the standard catalog's member for a reference that
* does not resolve where it must; the condition is generic, so the ledger's
* admission rule sends it to the standard member rather than to a new code.
*/
export const HOOK_HANDLER_NOT_IN_PACKAGE_CODE = 'INVALID_REFERENCE';
export const HOOK_HANDLER_NOT_IN_PACKAGE_STATUS = 400;
type HookRegistrationRefusal = Error & {
code: string;
status: number;
hook: string;
handler: string;
packageId?: string;
};
function hookHandlerNotInPackageRefusal(
hookName: string,
fnName: string,
packageId: string | undefined,
): HookRegistrationRefusal {
const holder = packageId
? `its own package ('${packageId}') holds no function of that name`
: 'this bind names no owning package and was handed no function of that name';
const err = new Error(
`Hook '${hookName}' was not bound: its \`handler\` names '${fnName}', and ${holder}. `
+ "A hook's `handler` resolves only among the functions its own package declares — the package's "
+ "`functions`, its runtime module's among them — and never reaches a function another package "
+ 'registered. Give the hook a `body` (sandboxed JS), or declare the function in this package\'s own '
+ '`functions`; to reuse another package\'s function, import it from the package that owns it.',
) as HookRegistrationRefusal;
err.code = HOOK_HANDLER_NOT_IN_PACKAGE_CODE;
err.status = HOOK_HANDLER_NOT_IN_PACKAGE_STATUS;
err.hook = hookName;
err.handler = fnName;
if (packageId) err.packageId = packageId;
return err;
}
/**
* Bind a list of declarative `Hook` definitions to a running ObjectQL engine.
*
* Idempotent on `(packageId, hook.name, event, object)`: re-binding the
* same set after a hot reload first calls `unregisterHooksByPackage`
* (when `packageId` is provided).
*
* @throws {BareNameConflictError} once the cold boot has sealed the registry,
* when `opts.functions` brings a function another package holds
* (`bare-name-one-holder.ts`) — before anything is registered or bound.
*/
export function bindHooksToEngine(
engine: ObjectQL,
hooks: Hook[] | undefined,
opts: BindHooksOptions = {},
): BindHooksResult {
const logger = opts.logger ?? noopLogger;
const result: BindHooksResult = { registered: 0, skipped: 0, errors: [] };
// Pre-load any inline functions supplied via `bundle.functions` so
// string-handler resolution works. An entry may declare its effect (#4396);
// that declaration is registered WITH the handler, so a later `script`-node
// caller reads both off the one registry.
//
// BEFORE the no-hooks bail-out below, deliberately: `functions` is not a
// hook accessory. It also feeds a flow `script` node's `config.function`
// (an action `target` is a handler key, never a function), so a stack that
// declares functions and no hooks — the shape #4396's example has —
// registered NOTHING and every such `script` node failed with "no function
// named 'x' is registered", naming the one thing the author had actually
// done.
if (opts.functions && typeof (engine as any).registerFunction === 'function') {
// [#30803] The bare-name one-holder rule for a function
// (`bare-name-one-holder.ts`), narrowed to the namespace (ADR-0150 D2/D9:
// `function` is in `NAMESPACE_SCOPED_BARE_NAME_TYPES`). Before the seal
// the claims are only recorded, for the cold boot to read. Once the cold
// boot has sealed the registry, `claimBareNameFunctions` throws a
// `BareNameConflictError` naming both holders when this bind brings a
// function a package of its own namespace, a package with no namespace,
// or the platform already holds; a package of another namespace may hold
// the same name. The throw comes ahead of every registration below and is
// not caught here: the runtime's `bindAppArtifactHandlers` catches it per
// owner group and logs "Failed to bind declarative hooks" at `error`, so
// the package still installs and every function and hook of that owner
// group stays unbound. The engine keeps every holder of a name
// (`functionHoldersOf`) and a flow `script` node resolves it in the
// calling flow's package (#32073).
const claimable = Object.entries(opts.functions)
.filter(([, entry]) => normalizeFlowFunctionEntry(entry) !== undefined)
.map(([name]) => name);
const registry = (engine as { registry?: { claimBareNameFunctions?: (owner: string | undefined, names: readonly string[]) => void } }).registry;
if (typeof registry?.claimBareNameFunctions === 'function') registry.claimBareNameFunctions(opts.packageId, claimable);
for (const [name, entry] of Object.entries(opts.functions)) {
const fn = normalizeFlowFunctionEntry(entry);
if (!fn) {
logger.warn('[hook-binder] skipping function entry with no callable handler', { name });
continue;
}
if (fn.unrecognizedEffect !== undefined) {
logger.warn('[hook-binder] unrecognized function effect — counted as an uncountable write', {
name,
effect: fn.unrecognizedEffect,
expected: "'pure' | 'writes'",
});
}
try {
(engine as any).registerFunction(name, fn.handler, {
packageId: opts.packageId,
effect: fn.effect,
});
} catch (err: any) {
logger.warn('[hook-binder] failed to register function', {
name,
error: err?.message,
});
}
}
}
if (!Array.isArray(hooks) || hooks.length === 0) {
return result;
}
// Hot-reload friendly: drop anything we previously bound under this
// packageId so the new set fully replaces the old.
if (opts.packageId && typeof (engine as any).unregisterHooksByPackage === 'function') {
try {
(engine as any).unregisterHooksByPackage(opts.packageId);
} catch (err: any) {
logger.warn('[hook-binder] unregister-by-package failed; continuing', {
packageId: opts.packageId,
error: err?.message,
});
}
}
for (const hook of hooks) {
try {
const resolved = resolveHandler(engine, hook, opts);
if (!resolved) {
result.skipped += 1;
// A `handler` name the hook's own package does not hold is REFUSED at
// registration, as a coded refusal, whether the name exists nowhere or
// only in another package — the two are one condition from where the
// hook stands. Logged at `error`, beside the binder's other coded
// registration refusals, and fatal under `strict`.
if (!(hook as any).body && typeof hook.handler === 'string' && hook.handler.length > 0) {
const refusal = hookHandlerNotInPackageRefusal(hook.name, hook.handler, opts.packageId);
result.errors.push({
hook: hook.name,
reason: refusal.message,
code: refusal.code,
status: refusal.status,
});
if (opts.strict) throw refusal;
logger.error('[hook-binder] hook refused: its handler names no function of its own package', refusal, {
hook: hook.name,
handler: hook.handler,
packageId: opts.packageId,
code: refusal.code,
status: refusal.status,
});
continue;
}
const reason = (hook as any).body
? `hook body present but no bodyRunner supplied to bindHooksToEngine (runtime must wire QuickJSScriptRunner)`
: 'no handler';
result.errors.push({ hook: hook.name, reason });
if (opts.strict) {
throw new Error(`[hook-binder] strict: cannot bind hook '${hook.name}': ${reason}`);
}
logger.warn('[hook-binder] skipping hook with unresolved handler', {
hook: hook.name,
handler: hook.handler,
hasBody: Boolean((hook as any).body),
});
continue;
}
if (opts.warnLegacyHandler && !(hook as any).body && typeof hook.handler === 'string') {
logger.warn('[hook-binder] DEPRECATED: hook uses legacy handler ref without body', {
hook: hook.name,
handler: hook.handler,
hint: 'Move the handler source into Hook.body so the artifact stays metadata-only and the .mjs runtime bundle can be dropped.',
});
}
const objects = normalizeObjects(hook.object);
if (objects.length === 0) {
result.skipped += 1;
const reason =
'hook target names no object — an empty `object` is refused rather than widened to '
+ "the wildcard '*'. Name the object(s), or write `object: '*'` if firing on "
+ 'every object is the intent.';
result.errors.push({ hook: hook.name, reason });
if (opts.strict) {
throw new Error(`[hook-binder] strict: cannot bind hook '${hook.name}': ${reason}`);
}
logger.warn('[hook-binder] skipping hook with an empty object target', {
hook: hook.name,
object: hook.object,
});
continue;
}
// [#25653] `appAuthored`: every hook this binder binds is app-authored —
// the same set the `skipAutomations` opt-out keys on through `meta`
// below — so its inherited elevation and its `sudo()` carry the
// app-automation mark (`APP_AUTHORED_HOOK_API`, `hook-run-as.ts`).
const wrapped = wrapDeclarativeHook(hook, resolved, { logger, metrics: opts.metrics, appAuthored: true });
const events = Array.isArray(hook.events) ? hook.events : [];
for (const event of events) {
for (const object of objects) {
engine.registerHook(event, wrapped, {
object,
priority: typeof hook.priority === 'number' ? hook.priority : 100,
packageId: opts.packageId,
// `meta` is the METADATA BINDING, and the engine reads it: the
// `skipAutomations` opt-out skips every entry that carries it
// (`triggerHooks`, `dispatchUnscopedMultiWriteHooks`). So every hook
// bound here is skippable by that opt-out. A platform hook that must
// run under it — audit, security — is registered in code with
// `engine.registerHook` and no `meta`, never through this binder
// (#22070). `hookName` names the hook in the engine's diagnostics.
...({ meta: hook, hookName: hook.name } as any),
} as any);
result.registered += 1;
}
}
} catch (err: any) {
// `strict` is documented as "fail fast on misconfiguration", but this
// catch swallowed the throw the strict branches raise — including its
// own — so the option only ever recorded the failure twice and carried
// on. A production runtime that opted into fail-fast never got it.
// Under strict, every bind failure is fatal, as advertised.
if (opts.strict) throw err;
result.errors.push({ hook: hook.name, reason: err?.message ?? String(err) });
// Contract arg order (#5637): `error(message, error?: Error, meta?)`.
// `err` is the `any` of a catch clause — a bind failure may be thrown by
// user code and need not be an `Error` — so the Error slot stays empty
// and the diagnostic travels as meta, in the third parameter.
logger.error('[hook-binder] failed to bind hook', undefined, {
hook: hook.name,
error: err?.message,
});
}
}
if (result.registered > 0) {
logger.debug('[hook-binder] hooks bound', {
packageId: opts.packageId,
registered: result.registered,
skipped: result.skipped,
});
}
return result;
}
/**
* Resolve a hook's declared target to the object names it registers on.
*
* Returns `[]` when the target names nothing. This used to fall back to
* `['*']`, which is the engine's match-everything sentinel — so a hook whose
* target was blank (`''`, `[]`, or a list of blanks) silently registered on
* EVERY object, on every event it listed. Blank intent became the broadest
* possible blast radius with no diagnostic (#4001).
*
* `HookSchema` now refuses those shapes at parse time, but this binder accepts
* unparsed `Hook` input, so the guard has to hold here too. An empty result is
* skipped and recorded by the caller rather than widened: a wildcard hook is
* legitimate, it just has to be spelled `'*'` so a reviewer can see it.
*/
function normalizeObjects(target: Hook['object']): string[] {
const names = Array.isArray(target) ? target : [target];
return names.filter((name): name is string => typeof name === 'string' && name.trim().length > 0);
}
function resolveHandler(
engine: ObjectQL,
hook: Hook,
opts: BindHooksOptions,
): HookHandler | undefined {
// Metadata-only body (L1 expression or L2 sandboxed JS) takes precedence
// over the legacy `handler` field. This is the cloud-deployable path —
// the body string ships inside the artifact JSON and runs under a
// capability-gated sandbox supplied by the runtime.
const body = (hook as any).body;
if (body && typeof body === 'object') {
let runner = opts.bodyRunner;
if (typeof runner !== 'function') {
// [#4251] The public accessor — this read used to reach the private
// `_defaultBodyRunner` field through `as any`.
const fallback = engine?.getDefaultBodyRunner?.();
if (typeof fallback === 'function') runner = fallback;
}
if (typeof runner !== 'function') {
return undefined;
}
const fn = runner(hook);
if (typeof fn === 'function') return fn;
return undefined;
}
const fn = resolveInProcessHandler(engine, hook, opts);
if (!fn || typeof opts.wrapHandler !== 'function') return fn;
// The engine awaits a handler and discards its return value; so does this.
const wrapped = opts.wrapHandler(fn, hook);
return async (context) => {
await wrapped(context);
};
}
/** The in-process handler a hook with no `body` names: its inline function, or the function its string names. */
function resolveInProcessHandler(
engine: ObjectQL,
hook: Hook,
opts: BindHooksOptions,
): HookHandler | undefined {
const h = hook.handler;
if (typeof h === 'function') return h as HookHandler;
if (typeof h === 'string' && h.length > 0) {
// A name resolves inside the hook's OWN package only. First the functions
// handed to this bind — the package's `functions`, which an artifact's
// runtime module supplies (hot path during initial bind). A declaration
// record resolves to its handler — a hook cares only about the callable.
const fromBundle = normalizeFlowFunctionEntry(opts.functions?.[h]);
if (fromBundle) return fromBundle.handler as HookHandler;
// Then a function the SAME package registered on the engine earlier, read
// from that package's own holding: a hook never binds to a function
// another package registered under the same name — that package's code
// would run on this package's events.
return ownPackageFunction(engine, h, opts.packageId);
}
return undefined;
}
/**
* The engine-registered function `name` when — and only when — its owner is
* `packageId`. A bind that states no owner holds only the functions handed to
* it: an entry with no owner, or with another owner, is not this package's.
*
* [ADR-0150 D3 step 1, #32073] Read from the package's OWN holding
* (`ObjectQL#functionHoldersOf`), never from the bare map's one
* last-registered entry per name: a package's own function stays its own
* after another package registers the same name, where the bare map's entry
* would then name the other package and refuse the bind. The rule is still
* own package only — a holder in the hook's closure, the platform's
* owner-less function and every other package's are not this package's code.
*/
function ownPackageFunction(
engine: ObjectQL,
name: string,
packageId: string | undefined,
): HookHandler | undefined {
if (!packageId) return undefined;
if (typeof (engine as any).functionHoldersOf !== 'function') return undefined;
const entry = (engine as ObjectQL).functionHoldersOf(name).packageItem(handlerOwnerPackageId(packageId));
if (!entry || entry.packageId !== packageId) return undefined;
return typeof entry.handler === 'function' ? (entry.handler as HookHandler) : undefined;
}