@reelout/core 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,204 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ /**
5
+ * Continuation that resumes the chain with the following middleware.
6
+ */
7
+ export type Next<Context> = (context: Context) => Promise<void>
8
+
9
+ /**
10
+ * Function executed as a single link in a hook dispatch chain.
11
+ */
12
+ export type Middleware<Context> = {
13
+ bivariant(context: Context, next: Next<Context>): void | Promise<void>
14
+ }['bivariant']
15
+
16
+ /**
17
+ * Priority ranks that order middleware within a hook.
18
+ */
19
+ export const Priority = {
20
+ High: 50,
21
+ Normal: 0,
22
+ Low: -50,
23
+ } as const
24
+
25
+ /**
26
+ * Registration options accepted by `on`.
27
+ */
28
+ export interface RegistrationOptions<Meta> {
29
+ priority?: number | undefined
30
+ meta?: Meta | undefined
31
+ }
32
+
33
+ /**
34
+ * A registration entry captured by `on`.
35
+ *
36
+ * Carries the `middleware`, its `priority` sort rank, and the `meta` exposed
37
+ * to the constructor interceptor.
38
+ */
39
+ export interface Registration<HookName, Context, Meta = undefined> {
40
+ hook: HookName
41
+ priority: number
42
+ middleware: Middleware<Context>
43
+ meta: Meta | undefined
44
+ }
45
+
46
+ /**
47
+ * Intercept a registered middleware during dispatch.
48
+ *
49
+ * Runs in place of every registered middleware, receiving the shared
50
+ * `context`, the `registration` being dispatched — including its `priority`
51
+ * and `meta` — and the `next` function that continues with the following
52
+ * middleware.
53
+ */
54
+ export type Interceptor<HookName, Context, Meta = undefined> = (
55
+ context: Context,
56
+ registration: Registration<HookName, Context, Meta>,
57
+ next: Next<Context>
58
+ ) => void | Promise<void>
59
+
60
+ type InferContext<M extends Middleware<unknown>> =
61
+ M extends Middleware<infer Context> ? Context : never
62
+
63
+ /**
64
+ * Dispatch registered hooks through asynchronous execution chains.
65
+ *
66
+ * Stores middleware in a prioritized registry and executes them sequentially
67
+ * in priority order.
68
+ */
69
+ export class HookDispatcher<
70
+ HookMap extends Record<keyof HookMap, Middleware<unknown>>,
71
+ Meta = undefined,
72
+ > {
73
+ readonly #registry = new Map<
74
+ keyof HookMap,
75
+ Registration<keyof HookMap, InferContext<HookMap[keyof HookMap]>, Meta>[]
76
+ >()
77
+
78
+ readonly #interceptor:
79
+ | Interceptor<keyof HookMap, InferContext<HookMap[keyof HookMap]>, Meta>
80
+ | undefined
81
+
82
+ /**
83
+ * Create a hook dispatcher.
84
+ *
85
+ * @param interceptor Wrapper invoked in place of every registered
86
+ * middleware during dispatch
87
+ */
88
+ constructor(
89
+ interceptor?: Interceptor<
90
+ keyof HookMap,
91
+ InferContext<HookMap[keyof HookMap]>,
92
+ Meta
93
+ >
94
+ ) {
95
+ this.#interceptor = interceptor
96
+ }
97
+
98
+ /**
99
+ * Register middleware for a specific hook.
100
+ *
101
+ * Adds the `middleware` to the internal registry for `hook` and sorts the
102
+ * list so higher-priority middleware runs first. An omitted or `undefined`
103
+ * `options.priority` defaults to `Priority.Normal`; `options.meta` is
104
+ * carried on the registration for the constructor interceptor.
105
+ *
106
+ * @param hook Name of the hook to register
107
+ * @param middleware Function executed when the hook dispatches
108
+ * @param options Registration options carrying the execution order rank and
109
+ * the metadata exposed to the constructor interceptor
110
+ */
111
+ on<HookName extends keyof HookMap>(
112
+ hook: HookName,
113
+ middleware: Middleware<InferContext<HookMap[HookName]>>,
114
+ options?: RegistrationOptions<Meta>
115
+ ): void {
116
+ const registrations = this.#registry.get(hook) ?? []
117
+
118
+ registrations.push({
119
+ hook,
120
+ middleware,
121
+ priority: options?.priority ?? Priority.Normal,
122
+ meta: options?.meta,
123
+ })
124
+
125
+ registrations.sort((a, b) => b.priority - a.priority)
126
+
127
+ this.#registry.set(hook, registrations)
128
+ }
129
+
130
+ /**
131
+ * Unregister middleware from a specific hook.
132
+ *
133
+ * Removes matching `middleware` references from the internal registry for
134
+ * `hook`. Takes no action if `hook` has no registered middleware.
135
+ *
136
+ * @param hook Name of the hook to unregister from
137
+ * @param middleware Reference of the middleware function to remove
138
+ */
139
+ off<HookName extends keyof HookMap>(
140
+ hook: HookName,
141
+ middleware: Middleware<InferContext<HookMap[HookName]>>
142
+ ): void {
143
+ const registrations = this.#registry.get(hook)
144
+
145
+ if (!registrations) return
146
+
147
+ this.#registry.set(
148
+ hook,
149
+ registrations.filter(
150
+ (registration) => registration.middleware !== middleware
151
+ )
152
+ )
153
+ }
154
+
155
+ /**
156
+ * Dispatch all middleware registered to a hook.
157
+ *
158
+ * Passes `context` through the middleware pipeline in descending priority
159
+ * order and dispatches each registration through the constructor
160
+ * interceptor when one is provided. Enables middleware to control
161
+ * execution flow using `next` and executes `done` after the last
162
+ * middleware completes.
163
+ *
164
+ * @param hook Name of the hook to dispatch
165
+ * @param context Shared payload passed into each middleware
166
+ * @param done Optional final callback run after the pipeline completes
167
+ * @returns Promise that resolves when execution completes
168
+ */
169
+ async dispatch<HookName extends keyof HookMap>(
170
+ hook: HookName,
171
+ context: InferContext<HookMap[HookName]>,
172
+ done?: Next<InferContext<HookMap[HookName]>>
173
+ ): Promise<void> {
174
+ type Context = InferContext<HookMap[HookName]>
175
+
176
+ const registrations = this.#registry.get(hook) ?? []
177
+
178
+ const interceptor = this.#interceptor
179
+
180
+ const run = async (index: number, context: Context): Promise<void> => {
181
+ const registration = registrations[index]
182
+
183
+ if (!registration) {
184
+ return done ? await done(context) : undefined
185
+ }
186
+
187
+ let isNextCalled = false
188
+
189
+ const next: Next<Context> = async (context) => {
190
+ if (isNextCalled) return
191
+ isNextCalled = true
192
+ return await run(index + 1, context)
193
+ }
194
+
195
+ const middleware: Middleware<Context> = interceptor
196
+ ? (context, next) => interceptor(context, registration, next)
197
+ : registration.middleware
198
+
199
+ return await middleware(context, next)
200
+ }
201
+
202
+ return await run(0, context)
203
+ }
204
+ }
@@ -1,4 +1,4 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  // Copyright (c) 2026 Fai
3
3
 
4
- export * from './HookManager'
4
+ export * from './HookDispatcher'
package/src/types.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  import type { ConsolaInstance } from 'consola/core'
5
5
  import type { CommitBase, CommitNote } from 'conventional-commits-parser'
6
6
  import type { Hosts } from 'hosted-git-info'
7
- import type { HookHandler } from './plugin'
7
+ import type { Middleware } from './plugin'
8
8
 
9
9
  export type GitRefType = 'branch'
10
10
 
@@ -150,7 +150,7 @@ export interface ReleasePhase {
150
150
  *
151
151
  * On failure, `error` holds the thrown error and `phase` attributes it to
152
152
  * the in-flight hook and plugin, or `null` when the failure arose outside
153
- * any plugin hook handler; on success both are `null`.
153
+ * any plugin hook middleware; on success both are `null`.
154
154
  */
155
155
  export interface ReleaseOutcome {
156
156
  status: ReleaseStatus
@@ -224,11 +224,11 @@ export interface ReleasePlan<P extends Package = Package> {
224
224
 
225
225
  export interface ReleaseHookDefinition<P extends Package = Package> {
226
226
  priority?: number | undefined
227
- handler: HookHandler<ReleaseContext<P>>
227
+ middleware: Middleware<ReleaseContext<P>>
228
228
  }
229
229
 
230
230
  export type ReleaseHook<P extends Package = Package> =
231
- HookHandler<ReleaseContext<P>> | ReleaseHookDefinition<P>
231
+ Middleware<ReleaseContext<P>> | ReleaseHookDefinition<P>
232
232
 
233
233
  export interface ReleasePlugin<P extends Package = Package> {
234
234
  name: string
@@ -2,7 +2,7 @@
2
2
  // Copyright (c) 2026 Fai
3
3
 
4
4
  import { RELEASE_HOOK_NAMES } from '#config'
5
- import { HookManager, type HookHandler } from '#plugin'
5
+ import { HookDispatcher, type Middleware } from '#plugin'
6
6
  import type {
7
7
  ReleaseContext,
8
8
  ReleaseHookDefinition,
@@ -17,8 +17,8 @@ import {
17
17
  printReleaseReportAnnotation,
18
18
  } from './report'
19
19
 
20
- /** Failure of a hook handler, recorded with the owning hook and plugin. */
21
- interface HandlerFailure {
20
+ /** Failure of a hook middleware, recorded with the owning hook and plugin. */
21
+ interface MiddlewareFailure {
22
22
  hook: ReleaseHookName
23
23
  plugin: string
24
24
  error: unknown
@@ -27,18 +27,12 @@ interface HandlerFailure {
27
27
  /**
28
28
  * Resolve a plugin's hook entry into a normalized hook definition.
29
29
  *
30
- * Normalizes the plugin's hook entry — a bare handler function or a
31
- * `{ priority, handler }` definition — and wraps the handler in shared timing
32
- * and logging middleware. When the wrapped handler throws, the failure is
33
- * attributed to the current hook and plugin on `context.outcome` before
34
- * rethrowing it. The `??=` assignment never overwrites a recorded outcome,
35
- * so `finalize` failures — which run after the outcome is recorded — leave it
36
- * unchanged.
30
+ * Accepts a bare middleware function or a `{ priority, middleware }`
31
+ * definition and extracts its middleware and priority.
37
32
  *
38
33
  * @param hookName Name of the hook to resolve
39
34
  * @param plugin Plugin owning the hook entry
40
- * @returns Normalized hook definition, or `undefined` when the plugin does not
41
- * implement the hook
35
+ * @returns Normalized hook definition, or `undefined` when unimplemented
42
36
  */
43
37
  function resolvePluginHook(
44
38
  hookName: ReleaseHookName,
@@ -47,107 +41,15 @@ function resolvePluginHook(
47
41
  let hook = plugin[hookName]
48
42
 
49
43
  if (typeof hook === 'function') {
50
- hook = { handler: hook }
44
+ hook = { middleware: hook }
51
45
  }
52
46
 
53
- const handler = hook?.handler
47
+ const middleware = hook?.middleware
54
48
  const priority = hook?.priority
55
49
 
56
- if (!handler) return
50
+ if (!middleware) return
57
51
 
58
- const isSilent = import.meta.env.MODE === 'test'
59
-
60
- return {
61
- priority,
62
- handler: async (context, next) => {
63
- const current = {
64
- hook: hookName,
65
- plugin: plugin.name,
66
- }
67
-
68
- const label = `${colors.gray(`[${current.hook}]`)} ${current.plugin}`
69
- let startedLogging = false
70
- let hasError = false
71
-
72
- if (!isSilent) {
73
- startedLogging = true
74
- context.logger.start(label)
75
- }
76
-
77
- const currentFrame = { startTime: performance.now() }
78
- const nextFrame = { duration: 0 }
79
-
80
- const runNext = async () => {
81
- const startTime = performance.now()
82
-
83
- try {
84
- return await next(context)
85
- } finally {
86
- nextFrame.duration = performance.now() - startTime
87
- }
88
- }
89
-
90
- try {
91
- return await handler.call(plugin, context, runNext)
92
- } catch (err) {
93
- hasError = true
94
-
95
- context.outcome ??= {
96
- status: 'failure',
97
- error: err,
98
- phase: current,
99
- }
100
-
101
- throw err
102
- } finally {
103
- if (startedLogging) {
104
- const duration =
105
- performance.now() - currentFrame.startTime - nextFrame.duration
106
- const color = duration >= 5000 ? colors.yellow : colors.cyan
107
- const message = [
108
- label,
109
- color(`${(duration / 1000).toFixed(2)}s`),
110
- ].join(' ')
111
-
112
- if (hasError) {
113
- context.logger.error(message)
114
- } else {
115
- context.logger.success(message)
116
- }
117
- }
118
- }
119
- },
120
- }
121
- }
122
-
123
- /**
124
- * Wrap a hook handler so a thrown error is recorded before rethrowing.
125
- *
126
- * Each recorded failure keeps the owning hook and plugin. The hook manager
127
- * middleware rescues rethrown `finalize` errors so the remaining
128
- * `finalize` handlers still run; other hook errors keep the fail-fast
129
- * unwinding behavior.
130
- *
131
- * @param handler Hook handler to wrap
132
- * @param hookName Name of the hook the handler is registered for
133
- * @param plugin Plugin owning the hook handler
134
- * @param failures Array of recorded handler failures
135
- * @returns Wrapped hook handler
136
- */
137
- function wrapHandlerWithFailureCollection(
138
- handler: HookHandler<ReleaseContext>,
139
- hookName: ReleaseHookName,
140
- plugin: ReleasePlugin,
141
- failures: HandlerFailure[]
142
- ): HookHandler<ReleaseContext> {
143
- return async (context, next) => {
144
- try {
145
- return await handler(context, next)
146
- } catch (error) {
147
- failures.push({ hook: hookName, plugin: plugin.name, error })
148
- throw error
149
- }
150
- }
52
+ return { priority, middleware }
151
53
  }
152
54
 
153
55
  /**
@@ -171,23 +73,57 @@ function throwIfCancelled(context: ReleaseContext): void {
171
73
  }
172
74
  }
173
75
 
76
+ /**
77
+ * Format a duration in milliseconds as a seconds string.
78
+ *
79
+ * @param duration Duration in milliseconds
80
+ * @returns Duration formatted as seconds with two decimal places
81
+ */
82
+ function formatDuration(duration: number): string {
83
+ return `${(duration / 1000).toFixed(2)}s`
84
+ }
85
+
86
+ /**
87
+ * Pick the console color for a duration, highlighting slow middleware.
88
+ *
89
+ * @param duration Duration in milliseconds
90
+ * @returns Color function that highlights durations of five seconds or more
91
+ */
92
+ function durationColor(duration: number): (text: string) => string {
93
+ return duration >= 5000 ? colors.yellow : colors.cyan
94
+ }
95
+
96
+ /**
97
+ * Format a hook and its owning plugin as a display label.
98
+ *
99
+ * @param hook Name of the hook
100
+ * @param plugin Name of the plugin owning the hook
101
+ * @returns Gray hook name followed by the plugin name
102
+ */
103
+ function hookLabel(hook: ReleaseHookName, plugin: string): string {
104
+ return `${colors.gray(`[${hook}]`)} ${plugin}`
105
+ }
106
+
174
107
  /**
175
108
  * Execute the complete release workflow across all configured plugins.
176
109
  *
177
110
  * Runs each lifecycle phase sequentially, dispatching plugin hooks in onion
178
111
  * order based on declared priority, and checks the abort signal before each
179
- * phase. Emits the `finalize` hook on every terminal outcome so plugins can
180
- * send notifications and clean up: when a phase hook throws, plugin rollbacks
181
- * run while the error unwinds, then every `finalize` handler runs with the
182
- * failure recorded on `context.outcome`. When a `finalize` handler throws,
183
- * the hook manager middleware rescues the error so the remaining handlers
184
- * still run, and each `finalize` failure is logged as a warning after the
185
- * report. A failing `finalize` handler never changes the workflow outcome
186
- * and never masks the original workflow error.
112
+ * phase. Each dispatched middleware runs through a single constructor
113
+ * interceptor that also attributes failures to the owning hook and plugin,
114
+ * collects middleware failures, and rescues `finalize` errors so the
115
+ * remaining `finalize` middleware still runs. Outside `test` mode the
116
+ * interceptor logs every middleware's exclusive duration — its wall-clock
117
+ * time minus the time consumed by downstream middleware — on completion.
118
+ * When a phase hook throws, plugin rollbacks run while the error unwinds,
119
+ * then every `finalize` middleware runs with the failure recorded on
120
+ * `context.outcome`. Each `finalize` failure is logged as a warning after
121
+ * the report. A failing `finalize` middleware never changes the workflow
122
+ * outcome and never masks the original workflow error.
187
123
  *
188
124
  * @param context Release execution context containing runtime options and logger
189
125
  * @param plugins List of release plugins to execute
190
- * @returns Promise that resolves when all phases and `finalize` handlers
126
+ * @returns Promise that resolves when all phases and `finalize` middleware
191
127
  * complete
192
128
  * @throws If a lifecycle hook fails or the workflow is cancelled
193
129
  */
@@ -197,19 +133,83 @@ export async function executeReleaseWorkflow(
197
133
  ): Promise<void> {
198
134
  context.outcome = null
199
135
 
200
- const handlerFailures: HandlerFailure[] = []
136
+ const isSilent = import.meta.env.MODE === 'test'
137
+
138
+ const middlewareFailures: MiddlewareFailure[] = []
201
139
 
202
- const manager = new HookManager<
203
- Record<ReleaseHookName, HookHandler<ReleaseContext>>
140
+ const dispatcher = new HookDispatcher<
141
+ Record<ReleaseHookName, Middleware<ReleaseContext>>,
142
+ ReleasePlugin
204
143
  >(async (context, registration, next) => {
205
- if (registration.name !== 'finalize') {
206
- return registration.handler(context, next)
144
+ const plugin = registration.meta
145
+
146
+ /* istanbul ignore next */
147
+ if (!plugin) {
148
+ throw new Error(
149
+ `Registration for hook "${registration.hook}" is missing plugin metadata.`
150
+ )
151
+ }
152
+
153
+ const hook = registration.hook
154
+ const label = hookLabel(hook, plugin.name)
155
+
156
+ if (!isSilent) {
157
+ context.logger.start(label)
158
+ }
159
+
160
+ const startedAt = performance.now()
161
+ let downstreamDuration = 0
162
+
163
+ const runNext = async () => {
164
+ const downstreamStart = performance.now()
165
+
166
+ try {
167
+ return await next(context)
168
+ } finally {
169
+ downstreamDuration += performance.now() - downstreamStart
170
+ }
171
+ }
172
+
173
+ const finish = (hasError: boolean): void => {
174
+ if (isSilent) return
175
+
176
+ const duration = performance.now() - startedAt - downstreamDuration
177
+ const color = durationColor(duration)
178
+ const message = [label, color(formatDuration(duration))].join(' ')
179
+
180
+ if (hasError) {
181
+ context.logger.error(message)
182
+ } else {
183
+ context.logger.success(message)
184
+ }
207
185
  }
208
186
 
209
187
  try {
210
- return await registration.handler(context, next)
211
- } catch {
212
- return next(context)
188
+ const result = await registration.middleware.call(
189
+ plugin,
190
+ context,
191
+ runNext
192
+ )
193
+
194
+ finish(false)
195
+
196
+ return result
197
+ } catch (error) {
198
+ const phase = { hook, plugin: plugin.name }
199
+
200
+ middlewareFailures.push({ ...phase, error })
201
+
202
+ context.outcome ??= {
203
+ status: 'failure',
204
+ error,
205
+ phase,
206
+ }
207
+
208
+ finish(true)
209
+
210
+ if (hook === 'finalize') return next(context)
211
+
212
+ throw error
213
213
  }
214
214
  })
215
215
 
@@ -219,14 +219,10 @@ export async function executeReleaseWorkflow(
219
219
 
220
220
  if (!definition) continue
221
221
 
222
- const handler = wrapHandlerWithFailureCollection(
223
- definition.handler,
224
- hookName,
225
- plugin,
226
- handlerFailures
227
- )
228
-
229
- manager.on(hookName, handler, definition.priority)
222
+ dispatcher.on(hookName, definition.middleware, {
223
+ priority: definition.priority,
224
+ meta: plugin,
225
+ })
230
226
  }
231
227
  }
232
228
 
@@ -242,7 +238,7 @@ export async function executeReleaseWorkflow(
242
238
 
243
239
  throwIfCancelled(context)
244
240
 
245
- return await manager.emit(hook, context, (context) =>
241
+ return await dispatcher.dispatch(hook, context, (context) =>
246
242
  dispatch(index + 1, context)
247
243
  )
248
244
  }
@@ -263,7 +259,7 @@ export async function executeReleaseWorkflow(
263
259
  }
264
260
  }
265
261
 
266
- await manager.emit('finalize', context)
262
+ await dispatcher.dispatch('finalize', context)
267
263
 
268
264
  const report = generateReleaseReport(context)
269
265
 
@@ -271,7 +267,7 @@ export async function executeReleaseWorkflow(
271
267
  appendReleaseReportSummary(context.logger, context.env, report)
272
268
  printReleaseReportAnnotation(context.env, context.stdout, report)
273
269
 
274
- for (const failure of handlerFailures) {
270
+ for (const failure of middlewareFailures) {
275
271
  if (failure.hook !== 'finalize') continue
276
272
  if (failure.error === context.outcome.error) continue
277
273