@reelout/core 0.8.0 → 0.9.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.
@@ -12,128 +12,265 @@ import {
12
12
  printReleaseReportAnnotation,
13
13
  } from './report'
14
14
 
15
+ /** Failure of a `finalize` handler, collected for the post-report warning. */
16
+ interface FinalizeFailure {
17
+ plugin: string
18
+ error: unknown
19
+ }
20
+
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
+ /**
36
+ * Register a plugin's hook handler on the workflow hook manager.
37
+ *
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.
44
+ *
45
+ * @param manager Hook manager receiving the wrapped handler
46
+ * @param registration Plugin hook registration carrying the error strategy
47
+ */
48
+ function registerPluginHook(
49
+ manager: HookManager<Record<ReleaseHookName, HookHandler<ReleaseContext>>>,
50
+ registration: PluginHookRegistration
51
+ ): void {
52
+ const { hookName, plugin } = registration
53
+
54
+ let hook = plugin[hookName]
55
+
56
+ if (typeof hook === 'function') {
57
+ hook = { handler: hook }
58
+ }
59
+
60
+ const handler = hook?.handler
61
+ const priority = hook?.priority
62
+
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()
89
+
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
+ )
134
+ }
135
+
136
+ /**
137
+ * Throw a cancellation error when the context abort signal has fired.
138
+ *
139
+ * Wraps the underlying `AbortError` so the workflow reports a readable
140
+ * cancellation instead of a bare DOM exception.
141
+ *
142
+ * @param context Release execution context carrying the optional abort signal
143
+ * @throws If the context abort signal has already fired
144
+ */
145
+ function throwIfCancelled(context: ReleaseContext): void {
146
+ const signal = context.signal
147
+
148
+ if (!signal?.aborted) return
149
+
150
+ try {
151
+ signal.throwIfAborted()
152
+ } catch (err) {
153
+ throw new Error('Release cancelled.', { cause: err })
154
+ }
155
+ }
156
+
15
157
  /**
16
158
  * Execute the complete release workflow across all configured plugins.
17
159
  *
18
160
  * Runs each lifecycle phase sequentially, dispatching plugin hooks in onion
19
- * order based on declared priority. Logs hook execution timing for non-silent
20
- * runs and prints a release report upon completion or failure.
161
+ * 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: on a failed workflow each failure is
167
+ * logged as a warning after the report, while on a successful workflow the
168
+ * first failure fails the release. Failures in `finalize` never mask the
169
+ * original workflow error.
21
170
  *
22
171
  * @param context Release execution context containing runtime options and logger
23
172
  * @param plugins List of release plugins to execute
24
- * @returns Promise that resolves when all workflow phases complete
25
- * @throws If any lifecycle hook execution fails
173
+ * @returns Promise that resolves when all phases and `finalize` handlers
174
+ * complete
175
+ * @throws If a lifecycle hook fails, the workflow is cancelled, or a finalize
176
+ * handler fails on an otherwise successful workflow
26
177
  */
27
178
  export async function executeReleaseWorkflow(
28
179
  context: ReleaseContext,
29
180
  plugins: readonly ReleasePlugin[]
30
181
  ): Promise<void> {
31
- const isSilent = import.meta.env.MODE === 'test'
182
+ const phaseHookNames = RELEASE_HOOK_NAMES.filter(
183
+ (name) => name !== 'finalize'
184
+ )
32
185
 
33
- try {
34
- context.status = null
35
- context.error = null
186
+ context.outcome = null
36
187
 
37
- const manager = new HookManager<
38
- Record<ReleaseHookName, HookHandler<ReleaseContext>>
39
- >()
188
+ const manager = new HookManager<
189
+ Record<ReleaseHookName, HookHandler<ReleaseContext>>
190
+ >()
40
191
 
41
- for (const hookName of RELEASE_HOOK_NAMES) {
42
- for (const plugin of plugins) {
43
- let hook = plugin[hookName]
192
+ for (const hookName of phaseHookNames) {
193
+ for (const plugin of plugins) {
194
+ registerPluginHook(manager, { hookName, plugin })
195
+ }
196
+ }
44
197
 
45
- if (typeof hook === 'function') {
46
- hook = { handler: hook }
47
- }
198
+ const dispatch = async (
199
+ index: number,
200
+ context: ReleaseContext
201
+ ): Promise<void> => {
202
+ const hook = phaseHookNames[index]
48
203
 
49
- const handler = hook?.handler
50
- const priority = hook?.priority
51
-
52
- if (handler) {
53
- manager.on(
54
- hookName,
55
- async (context, next) => {
56
- const current = (context.phase = {
57
- hook: hookName,
58
- plugin: plugin.name,
59
- })
60
-
61
- const label = `${colors.gray(`[${current.hook}]`)} ${current.plugin}`
62
- let startedLogging = false
63
- let hasError = false
64
-
65
- if (!isSilent) {
66
- startedLogging = true
67
- context.logger.start(label)
68
- }
69
-
70
- const currentFrame = { startTime: performance.now() }
71
- const nextFrame = { duration: 0 }
72
-
73
- try {
74
- return await handler.call(plugin, context, async () => {
75
- const startTime = performance.now()
76
-
77
- try {
78
- return await next(context)
79
- } finally {
80
- nextFrame.duration = performance.now() - startTime
81
- }
82
- })
83
- } catch (err) {
84
- hasError = true
85
- throw err
86
- } finally {
87
- if (startedLogging) {
88
- const duration =
89
- performance.now() -
90
- currentFrame.startTime -
91
- nextFrame.duration
92
- const color = duration >= 5000 ? colors.yellow : colors.cyan
93
- const message = [
94
- label,
95
- color(`${(duration / 1000).toFixed(2)}s`),
96
- ].join(' ')
97
-
98
- if (hasError) {
99
- context.logger.error(message)
100
- } else {
101
- context.logger.success(message)
102
- }
103
- }
104
- }
105
- },
106
- priority
107
- )
108
- }
109
- }
204
+ if (!hook) return
205
+
206
+ throwIfCancelled(context)
207
+
208
+ return await manager.emit(hook, context, (context) =>
209
+ dispatch(index + 1, context)
210
+ )
211
+ }
212
+
213
+ try {
214
+ await dispatch(0, context)
215
+
216
+ context.outcome = {
217
+ status: 'success',
218
+ error: null,
219
+ phase: null,
110
220
  }
221
+ } catch (err) {
222
+ context.outcome ??= {
223
+ status: 'failure',
224
+ error: err,
225
+ phase: null,
226
+ }
227
+ }
228
+
229
+ const finalizeFailures: FinalizeFailure[] = []
111
230
 
112
- const dispatch = async (
113
- index: number,
114
- context: ReleaseContext
115
- ): Promise<void> => {
116
- const hook = RELEASE_HOOK_NAMES[index]
231
+ for (const plugin of plugins) {
232
+ registerPluginHook(manager, {
233
+ hookName: 'finalize',
234
+ plugin,
235
+ onHandlerError: (error) =>
236
+ finalizeFailures.push({ plugin: plugin.name, error }),
237
+ })
238
+ }
239
+
240
+ await manager.emit('finalize', context)
117
241
 
118
- if (!hook) return
242
+ const [firstFinalizeFailure] = finalizeFailures
119
243
 
120
- return await manager.emit(hook, context, (context) =>
121
- dispatch(index + 1, context)
122
- )
244
+ if (context.outcome.status === 'success' && firstFinalizeFailure) {
245
+ context.outcome = {
246
+ status: 'failure',
247
+ error: firstFinalizeFailure.error,
248
+ phase: {
249
+ hook: 'finalize',
250
+ plugin: firstFinalizeFailure.plugin,
251
+ },
123
252
  }
253
+ }
124
254
 
125
- await dispatch(0, context)
255
+ const report = generateReleaseReport(context)
126
256
 
127
- context.status = 'success'
128
- } catch (err) {
129
- context.status = 'failure'
130
- context.error = err
131
- throw err
132
- } finally {
133
- const report = generateReleaseReport(context)
134
-
135
- printReleaseReport(context.logger, report)
136
- appendReleaseReportSummary(context.logger, context.env, report)
137
- printReleaseReportAnnotation(context.env, context.stdout, report)
257
+ printReleaseReport(context.logger, report)
258
+ appendReleaseReportSummary(context.logger, context.env, report)
259
+ printReleaseReportAnnotation(context.env, context.stdout, report)
260
+
261
+ for (const failure of finalizeFailures) {
262
+ if (failure.error === context.outcome.error) continue
263
+
264
+ context.logger.warn(
265
+ `Plugin "${failure.plugin}" could not finalize: ${
266
+ failure.error instanceof Error
267
+ ? failure.error.message
268
+ : String(failure.error)
269
+ }`
270
+ )
271
+ }
272
+
273
+ if (context.outcome.status === 'failure') {
274
+ throw context.outcome.error
138
275
  }
139
276
  }
@@ -5,6 +5,7 @@ import type { ReleaseReport } from '#types'
5
5
  import { isGitHubActions } from '#util'
6
6
  import type { ConsolaInstance } from 'consola/core'
7
7
  import { appendFileSync } from 'node:fs'
8
+ import { resolveOutcomeErrorMessage } from './resolveErrorMessage'
8
9
 
9
10
  const STATUS_LABELS = {
10
11
  success: 'Success',
@@ -24,7 +25,7 @@ type ReportPlan = ReleaseReport['plans'][number]
24
25
  *
25
26
  * @param logger Logger instance for reporting summary write failures
26
27
  * @param env Readonly process environment variables object
27
- * @param report Release report containing status and package details
28
+ * @param report Release report containing outcome and package details
28
29
  */
29
30
  export function appendReleaseReportSummary(
30
31
  logger: ConsolaInstance,
@@ -55,13 +56,12 @@ const formatPackageLabel = (plan: ReportPlan): string => {
55
56
  const formatReleaseReportSummary = (report: ReleaseReport): string => {
56
57
  const lines: string[] = ['## ReelOut Release Report', '']
57
58
 
58
- if (report.status) {
59
- lines.push(`**Status:** ${STATUS_LABELS[report.status]}`, '')
59
+ if (report.outcome) {
60
+ lines.push(`**Status:** ${STATUS_LABELS[report.outcome.status]}`, '')
60
61
  }
61
62
 
62
- if (report.status === 'failure') {
63
- const message =
64
- report.error || 'An unexpected error occurred during the release process.'
63
+ if (report.outcome?.status === 'failure') {
64
+ const message = resolveOutcomeErrorMessage(report.outcome)
65
65
 
66
66
  lines.push(...message.split('\n').map((line) => `> ${line}`), '')
67
67
 
@@ -8,21 +8,15 @@ import { compact } from '#util'
8
8
  * Generate a structured release report from the current workflow state.
9
9
  *
10
10
  * Extracts state information from `context` and organizes it into a report
11
- * containing workflow status, release plans, and package metadata. Omits
12
- * unversioned release plans from the finalized output.
11
+ * containing the terminal release outcome, release plans, and package
12
+ * metadata. Omits unversioned release plans from the finalized output.
13
13
  *
14
14
  * @param context Release execution context containing workflow state and plans
15
15
  * @returns Structured release report object containing workflow results
16
16
  */
17
17
  export function generateReleaseReport(context: ReleaseContext): ReleaseReport {
18
18
  return {
19
- status: context.status,
20
- phase: context.phase,
21
- error: Error.isError(context.error)
22
- ? context.error.message
23
- : typeof context.error === 'string'
24
- ? context.error
25
- : null,
19
+ outcome: context.outcome,
26
20
  packages: context.packages.map((pkg) => ({
27
21
  location: pkg.location,
28
22
  name: pkg.name,
@@ -5,38 +5,36 @@ import type { ReleaseReport } from '#types'
5
5
  import type { ConsolaInstance } from 'consola/core'
6
6
  import { colors } from 'consola/utils'
7
7
  import path from 'node:path'
8
+ import { resolveOutcomeErrorMessage } from './resolveErrorMessage'
8
9
 
9
10
  /**
10
11
  * Print a formatted release report to the logger.
11
12
  *
12
- * Logs workflow `status` and details for planned package releases. Displays
13
- * package names, directories, and version changes on success, or outputs the
14
- * error message on failure.
13
+ * Logs the terminal outcome status and details for planned package releases.
14
+ * Displays package names, directories, and version changes on success, or
15
+ * outputs the error message on failure.
15
16
  *
16
17
  * @param logger Logger instance for outputting messages
17
- * @param report Release report containing status and package details
18
+ * @param report Release report containing outcome and package details
18
19
  */
19
20
  export function printReleaseReport(
20
21
  logger: ConsolaInstance,
21
22
  report: ReleaseReport
22
23
  ): void {
23
- if (report.status) {
24
+ if (report.outcome) {
24
25
  const statusLabel = {
25
26
  success: colors.green('SUCCESS'),
26
27
  failure: colors.red('FAILURE'),
27
- }[report.status]
28
+ }[report.outcome.status]
28
29
 
29
30
  logger.info(`Status: ${statusLabel}`)
30
31
  }
31
32
 
32
- if (report.status === 'failure') {
33
+ if (report.outcome?.status === 'failure') {
33
34
  return logger.error(
34
35
  [
35
36
  'Release complete:',
36
- colors.red(
37
- report.error ||
38
- 'An unexpected error occurred during the release process.'
39
- ),
37
+ colors.red(resolveOutcomeErrorMessage(report.outcome)),
40
38
  ].join(' ')
41
39
  )
42
40
  }
@@ -3,6 +3,7 @@
3
3
 
4
4
  import type { ReleaseReport } from '#types'
5
5
  import { isGitHubActions } from '#util'
6
+ import { resolveOutcomeErrorMessage } from './resolveErrorMessage'
6
7
 
7
8
  /**
8
9
  * Print a GitHub Actions error annotation for a failed release.
@@ -15,17 +16,17 @@ import { isGitHubActions } from '#util'
15
16
  *
16
17
  * @param env Readonly process environment variables object
17
18
  * @param stdout Writable stream receiving the annotation command
18
- * @param report Release report containing status and failure details
19
+ * @param report Release report containing outcome and failure details
19
20
  */
20
21
  export function printReleaseReportAnnotation(
21
22
  env: Readonly<NodeJS.ProcessEnv>,
22
23
  stdout: NodeJS.WritableStream,
23
24
  report: ReleaseReport
24
25
  ): void {
25
- if (!isGitHubActions(env) || report.status !== 'failure') return
26
+ if (!isGitHubActions(env) || report.outcome?.status !== 'failure') return
26
27
 
27
28
  const message = formatAnnotationMessage(
28
- report.error || 'An unexpected error occurred during the release process.'
29
+ resolveOutcomeErrorMessage(report.outcome)
29
30
  )
30
31
 
31
32
  stdout.write(`::error title=Release failed::${message}\n`)
@@ -0,0 +1,36 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import type { ReleaseOutcome } from '#types'
5
+
6
+ /**
7
+ * Resolve a displayable message from an unknown error value.
8
+ *
9
+ * Normalizes `Error` instances to their `message` and passes string values
10
+ * through unchanged. Returns `null` for any other shape so callers can fall
11
+ * back to a generic message.
12
+ *
13
+ * @param error Unknown error value carried on a release outcome
14
+ * @returns The resolved error message, or `null` when none can be resolved
15
+ */
16
+ export function resolveErrorMessage(error: unknown): string | null {
17
+ if (Error.isError(error)) return error.message
18
+
19
+ return typeof error === 'string' ? error : null
20
+ }
21
+
22
+ const FALLBACK_ERROR_MESSAGE =
23
+ 'An unexpected error occurred during the release process.'
24
+
25
+ /**
26
+ * Resolve a displayable failure message from a release outcome.
27
+ *
28
+ * Normalizes the outcome error to its message and falls back to a generic
29
+ * message when the error carries no displayable content.
30
+ *
31
+ * @param outcome Failure outcome whose error is rendered
32
+ * @returns The resolved error message, or the fallback message
33
+ */
34
+ export function resolveOutcomeErrorMessage(outcome: ReleaseOutcome): string {
35
+ return resolveErrorMessage(outcome.error) || FALLBACK_ERROR_MESSAGE
36
+ }