@reelout/core 0.10.0 → 0.12.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
@@ -178,6 +178,7 @@ export interface ReleaseContext<P extends Package = Package> {
178
178
  releaseChannel: string | undefined
179
179
  allowEmpty: boolean
180
180
  dryRun: boolean
181
+ strict: boolean
181
182
  packages: P[]
182
183
  plans: ReleasePlan<P>[]
183
184
  outcome: ReleaseOutcome | null
@@ -223,11 +224,11 @@ export interface ReleasePlan<P extends Package = Package> {
223
224
 
224
225
  export interface ReleaseHookDefinition<P extends Package = Package> {
225
226
  priority?: number | undefined
226
- handler: HookHandler<ReleaseContext<P>>
227
+ middleware: Middleware<ReleaseContext<P>>
227
228
  }
228
229
 
229
230
  export type ReleaseHook<P extends Package = Package> =
230
- HookHandler<ReleaseContext<P>> | ReleaseHookDefinition<P>
231
+ Middleware<ReleaseContext<P>> | ReleaseHookDefinition<P>
231
232
 
232
233
  export interface ReleasePlugin<P extends Package = Package> {
233
234
  name: string
@@ -2,8 +2,13 @@
2
2
  // Copyright (c) 2026 Fai
3
3
 
4
4
  import { RELEASE_HOOK_NAMES } from '#config'
5
- import { HookManager, type HookHandler } from '#plugin'
6
- import type { ReleaseContext, ReleaseHookName, ReleasePlugin } from '#types'
5
+ import { HookDispatcher, type Middleware } from '#plugin'
6
+ import type {
7
+ ReleaseContext,
8
+ ReleaseHookDefinition,
9
+ ReleaseHookName,
10
+ ReleasePlugin,
11
+ } from '#types'
7
12
  import { colors } from 'consola/utils'
8
13
  import {
9
14
  appendReleaseReportSummary,
@@ -12,125 +17,39 @@ import {
12
17
  printReleaseReportAnnotation,
13
18
  } from './report'
14
19
 
15
- /** Failure of a `finalize` handler, collected for the post-report warning. */
16
- interface FinalizeFailure {
20
+ /** Failure of a hook middleware, recorded with the owning hook and plugin. */
21
+ interface MiddlewareFailure {
22
+ hook: ReleaseHookName
17
23
  plugin: string
18
24
  error: unknown
19
25
  }
20
26
 
21
- interface PluginHookRegistration {
22
- /** Hook name the plugin handler registers under. */
23
- hookName: ReleaseHookName
24
- /** Plugin owning the hook entry. */
25
- plugin: ReleasePlugin
26
- /**
27
- * Handle a thrown handler error instead of rethrowing it.
28
- *
29
- * When provided, the wrapper passes a thrown error to this callback and
30
- * continues the middleware chain, so later handlers still run.
31
- */
32
- onHandlerError?: (error: unknown) => void
33
- }
34
-
35
27
  /**
36
- * Register a plugin's hook handler on the workflow hook manager.
28
+ * Resolve a plugin's hook entry into a normalized hook definition.
37
29
  *
38
- * Normalizes the plugin's hook entry into a handler and priority, wraps the
39
- * handler in shared timing and logging middleware, and registers it under
40
- * the registration's hook name. When `onHandlerError` is provided, a thrown
41
- * handler error is passed to it and the middleware chain continues so later
42
- * handlers still run; without it the wrapper attributes the failure to the
43
- * current hook and plugin on `context.outcome` before rethrowing.
30
+ * Accepts a bare middleware function or a `{ priority, middleware }`
31
+ * definition and extracts its middleware and priority.
44
32
  *
45
- * @param manager Hook manager receiving the wrapped handler
46
- * @param registration Plugin hook registration carrying the error strategy
33
+ * @param hookName Name of the hook to resolve
34
+ * @param plugin Plugin owning the hook entry
35
+ * @returns Normalized hook definition, or `undefined` when unimplemented
47
36
  */
48
- function registerPluginHook(
49
- manager: HookManager<Record<ReleaseHookName, HookHandler<ReleaseContext>>>,
50
- registration: PluginHookRegistration
51
- ): void {
52
- const { hookName, plugin } = registration
53
-
37
+ function resolvePluginHook(
38
+ hookName: ReleaseHookName,
39
+ plugin: ReleasePlugin
40
+ ): ReleaseHookDefinition | undefined {
54
41
  let hook = plugin[hookName]
55
42
 
56
43
  if (typeof hook === 'function') {
57
- hook = { handler: hook }
44
+ hook = { middleware: hook }
58
45
  }
59
46
 
60
- const handler = hook?.handler
47
+ const middleware = hook?.middleware
61
48
  const priority = hook?.priority
62
49
 
63
- if (!handler) return
64
-
65
- const isSilent = import.meta.env.MODE === 'test'
66
-
67
- manager.on(
68
- hookName,
69
- async (context, next) => {
70
- const current = {
71
- hook: hookName,
72
- plugin: plugin.name,
73
- }
74
-
75
- const label = `${colors.gray(`[${current.hook}]`)} ${current.plugin}`
76
- let startedLogging = false
77
- let hasError = false
78
-
79
- if (!isSilent) {
80
- startedLogging = true
81
- context.logger.start(label)
82
- }
83
-
84
- const currentFrame = { startTime: performance.now() }
85
- const nextFrame = { duration: 0 }
86
-
87
- const runNext = async () => {
88
- const startTime = performance.now()
50
+ if (!middleware) return
89
51
 
90
- try {
91
- return await next(context)
92
- } finally {
93
- nextFrame.duration = performance.now() - startTime
94
- }
95
- }
96
-
97
- try {
98
- return await handler.call(plugin, context, runNext)
99
- } catch (err) {
100
- hasError = true
101
-
102
- if (registration.onHandlerError) {
103
- registration.onHandlerError(err)
104
- return await runNext()
105
- }
106
-
107
- context.outcome ??= {
108
- status: 'failure',
109
- error: err,
110
- phase: current,
111
- }
112
-
113
- throw err
114
- } finally {
115
- if (startedLogging) {
116
- const duration =
117
- performance.now() - currentFrame.startTime - nextFrame.duration
118
- const color = duration >= 5000 ? colors.yellow : colors.cyan
119
- const message = [
120
- label,
121
- color(`${(duration / 1000).toFixed(2)}s`),
122
- ].join(' ')
123
-
124
- if (hasError) {
125
- context.logger.error(message)
126
- } else {
127
- context.logger.success(message)
128
- }
129
- }
130
- }
131
- },
132
- priority
133
- )
52
+ return { priority, middleware }
134
53
  }
135
54
 
136
55
  /**
@@ -154,22 +73,57 @@ function throwIfCancelled(context: ReleaseContext): void {
154
73
  }
155
74
  }
156
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
+
157
107
  /**
158
108
  * Execute the complete release workflow across all configured plugins.
159
109
  *
160
110
  * Runs each lifecycle phase sequentially, dispatching plugin hooks in onion
161
111
  * order based on declared priority, and checks the abort signal before each
162
- * phase. Emits the `finalize` hook on every terminal outcome so plugins can
163
- * send notifications and clean up: when a phase hook throws, plugin rollbacks
164
- * run while the error unwinds, then every `finalize` handler runs with the
165
- * failure recorded on `context.outcome`. When a `finalize` handler throws,
166
- * the remaining handlers still run and each failure is logged as a warning
167
- * after the report. A failing `finalize` handler never changes the workflow
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
168
122
  * outcome and never masks the original workflow error.
169
123
  *
170
124
  * @param context Release execution context containing runtime options and logger
171
125
  * @param plugins List of release plugins to execute
172
- * @returns Promise that resolves when all phases and `finalize` handlers
126
+ * @returns Promise that resolves when all phases and `finalize` middleware
173
127
  * complete
174
128
  * @throws If a lifecycle hook fails or the workflow is cancelled
175
129
  */
@@ -177,19 +131,98 @@ export async function executeReleaseWorkflow(
177
131
  context: ReleaseContext,
178
132
  plugins: readonly ReleasePlugin[]
179
133
  ): Promise<void> {
180
- const phaseHookNames = RELEASE_HOOK_NAMES.filter(
181
- (name) => name !== 'finalize'
182
- )
183
-
184
134
  context.outcome = null
185
135
 
186
- const manager = new HookManager<
187
- Record<ReleaseHookName, HookHandler<ReleaseContext>>
188
- >()
136
+ const isSilent = import.meta.env.MODE === 'test'
189
137
 
190
- for (const hookName of phaseHookNames) {
138
+ const middlewareFailures: MiddlewareFailure[] = []
139
+
140
+ const dispatcher = new HookDispatcher<
141
+ Record<ReleaseHookName, Middleware<ReleaseContext>>,
142
+ ReleasePlugin
143
+ >(async (context, registration, 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
+ }
185
+ }
186
+
187
+ try {
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
+ }
214
+ })
215
+
216
+ for (const hookName of RELEASE_HOOK_NAMES) {
191
217
  for (const plugin of plugins) {
192
- registerPluginHook(manager, { hookName, plugin })
218
+ const definition = resolvePluginHook(hookName, plugin)
219
+
220
+ if (!definition) continue
221
+
222
+ dispatcher.on(hookName, definition.middleware, {
223
+ priority: definition.priority,
224
+ meta: plugin,
225
+ })
193
226
  }
194
227
  }
195
228
 
@@ -197,13 +230,15 @@ export async function executeReleaseWorkflow(
197
230
  index: number,
198
231
  context: ReleaseContext
199
232
  ): Promise<void> => {
200
- const hook = phaseHookNames[index]
233
+ const hook = RELEASE_HOOK_NAMES[index]
201
234
 
202
235
  if (!hook) return
203
236
 
237
+ if (hook === 'finalize') return await dispatch(index + 1, context)
238
+
204
239
  throwIfCancelled(context)
205
240
 
206
- return await manager.emit(hook, context, (context) =>
241
+ return await dispatcher.dispatch(hook, context, (context) =>
207
242
  dispatch(index + 1, context)
208
243
  )
209
244
  }
@@ -224,18 +259,7 @@ export async function executeReleaseWorkflow(
224
259
  }
225
260
  }
226
261
 
227
- const finalizeFailures: FinalizeFailure[] = []
228
-
229
- for (const plugin of plugins) {
230
- registerPluginHook(manager, {
231
- hookName: 'finalize',
232
- plugin,
233
- onHandlerError: (error) =>
234
- finalizeFailures.push({ plugin: plugin.name, error }),
235
- })
236
- }
237
-
238
- await manager.emit('finalize', context)
262
+ await dispatcher.dispatch('finalize', context)
239
263
 
240
264
  const report = generateReleaseReport(context)
241
265
 
@@ -243,7 +267,8 @@ export async function executeReleaseWorkflow(
243
267
  appendReleaseReportSummary(context.logger, context.env, report)
244
268
  printReleaseReportAnnotation(context.env, context.stdout, report)
245
269
 
246
- for (const failure of finalizeFailures) {
270
+ for (const failure of middlewareFailures) {
271
+ if (failure.hook !== 'finalize') continue
247
272
  if (failure.error === context.outcome.error) continue
248
273
 
249
274
  context.logger.warn(