@reelout/core 0.1.1 → 0.5.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.
Files changed (138) hide show
  1. package/LICENSE +21 -0
  2. package/dist/analyzer.js +33 -0
  3. package/dist/analyzer.js.map +1 -0
  4. package/dist/builder.js +64 -0
  5. package/dist/builder.js.map +1 -0
  6. package/dist/changelog.js +63 -0
  7. package/dist/changelog.js.map +1 -0
  8. package/dist/formatError-BXNdyRfu.js +23 -0
  9. package/dist/formatError-BXNdyRfu.js.map +1 -0
  10. package/dist/index.js +225 -1
  11. package/dist/index.js.map +1 -0
  12. package/dist/types-la_KkjCS.js +1 -0
  13. package/dist/types.js +2 -0
  14. package/dist/workflow-CroJ6v4g.js +2736 -0
  15. package/dist/workflow-CroJ6v4g.js.map +1 -0
  16. package/package.json +35 -6
  17. package/src/analyzer.ts +59 -0
  18. package/src/builder.ts +116 -0
  19. package/src/cache/TTLCache.ts +100 -0
  20. package/src/cache/index.ts +4 -0
  21. package/src/changelog.ts +107 -0
  22. package/src/config/const.ts +104 -0
  23. package/src/config/createPlugin.ts +41 -0
  24. package/src/config/findReleaseRule.ts +26 -0
  25. package/src/config/index.ts +15 -0
  26. package/src/config/isSemVer.ts +31 -0
  27. package/src/config/isSemVerGitTag.ts +25 -0
  28. package/src/config/normalizeCommitFilter.ts +37 -0
  29. package/src/config/normalizeReleaseRule.ts +66 -0
  30. package/src/config/normalizeWorkspace.ts +34 -0
  31. package/src/config/resolvePlugin.ts +57 -0
  32. package/src/config/resolveReleaseChannel.ts +47 -0
  33. package/src/config/resolveVersionQualifier.ts +53 -0
  34. package/src/config/sanitizePrereleaseLabel.ts +18 -0
  35. package/src/git/branch/getCurrentGitBranch.ts +18 -0
  36. package/src/git/branch/index.ts +4 -0
  37. package/src/git/commit/createGitCommit.ts +29 -0
  38. package/src/git/commit/extractMentions.ts +34 -0
  39. package/src/git/commit/getCurrentGitCommit.ts +19 -0
  40. package/src/git/commit/getParsedGitCommit.ts +49 -0
  41. package/src/git/commit/index.ts +9 -0
  42. package/src/git/commit/parseGitCommit.ts +114 -0
  43. package/src/git/commit/parseGitPrettyFormat.ts +76 -0
  44. package/src/git/history/countGitHistory.ts +28 -0
  45. package/src/git/history/expandGitHistory.ts +112 -0
  46. package/src/git/history/index.ts +9 -0
  47. package/src/git/history/mergeGitHistory.ts +76 -0
  48. package/src/git/history/restoreFullGitHistory.ts +19 -0
  49. package/src/git/history/showGitHistory.ts +80 -0
  50. package/src/git/history/showParsedGitHistory.ts +28 -0
  51. package/src/git/index.ts +9 -0
  52. package/src/git/repository/ensureGitUserConfig.ts +50 -0
  53. package/src/git/repository/getGitConfigValue.ts +27 -0
  54. package/src/git/repository/getGitRemote.ts +20 -0
  55. package/src/git/repository/index.ts +10 -0
  56. package/src/git/repository/isGitShallowRepository.ts +21 -0
  57. package/src/git/repository/pushGitChanges.ts +26 -0
  58. package/src/git/repository/resolveGitRepository.ts +40 -0
  59. package/src/git/repository/withShallowLock.ts +62 -0
  60. package/src/git/revision/detectGitRelationship.ts +43 -0
  61. package/src/git/revision/index.ts +7 -0
  62. package/src/git/revision/isGitAncestor.ts +33 -0
  63. package/src/git/revision/readGitFile.ts +29 -0
  64. package/src/git/revision/resolveGitRevision.ts +23 -0
  65. package/src/git/tag/createGitTag.ts +25 -0
  66. package/src/git/tag/deleteGitTag.ts +17 -0
  67. package/src/git/tag/ensureGitTag.ts +63 -0
  68. package/src/git/tag/generateGitTagName.ts +43 -0
  69. package/src/git/tag/getCurrentGitTag.ts +23 -0
  70. package/src/git/tag/getGitTagMessage.ts +35 -0
  71. package/src/git/tag/getLatestGitTag.ts +22 -0
  72. package/src/git/tag/index.ts +13 -0
  73. package/src/git/tag/isGitTagConnected.ts +33 -0
  74. package/src/git/tag/isGitTagPointed.ts +38 -0
  75. package/src/git/tag/isGitTagPresent.ts +17 -0
  76. package/src/index.ts +9 -2
  77. package/src/plugin/HookManager.ts +128 -0
  78. package/src/plugin/index.ts +4 -0
  79. package/src/types.ts +259 -0
  80. package/src/util/buildTrailerPattern.ts +20 -0
  81. package/src/util/compact.ts +14 -0
  82. package/src/util/execCommand.ts +196 -0
  83. package/src/util/execGit.ts +27 -0
  84. package/src/util/formatError.ts +21 -0
  85. package/src/util/formatFile.ts +41 -0
  86. package/src/util/index.ts +19 -0
  87. package/src/util/interpolate.ts +141 -0
  88. package/src/util/isCI.ts +18 -0
  89. package/src/util/isClass.ts +34 -0
  90. package/src/util/isDefined.ts +12 -0
  91. package/src/util/isMatch.ts +43 -0
  92. package/src/util/isQuietEnvironment.ts +35 -0
  93. package/src/util/isTruthyString.ts +19 -0
  94. package/src/util/readJson.ts +47 -0
  95. package/src/util/unique.ts +26 -0
  96. package/src/util/writeJson.ts +28 -0
  97. package/src/workflow/analysis/deriveChangeReleases.ts +76 -0
  98. package/src/workflow/analysis/deriveTransitionReleases.ts +134 -0
  99. package/src/workflow/analysis/index.ts +10 -0
  100. package/src/workflow/analysis/isCommitForPackage.ts +23 -0
  101. package/src/workflow/analysis/promotePrereleaseVersions.ts +51 -0
  102. package/src/workflow/analysis/propagateDependencyUpdates.ts +71 -0
  103. package/src/workflow/analysis/sliceUnreleased.ts +36 -0
  104. package/src/workflow/analysis/streamPackageCommits.ts +34 -0
  105. package/src/workflow/changelog/buildChangelog.ts +79 -0
  106. package/src/workflow/changelog/buildReleaseNotes.ts +50 -0
  107. package/src/workflow/changelog/conventional-changelog-conventionalcommits.d.ts +7 -0
  108. package/src/workflow/changelog/extractLatestVersion.ts +22 -0
  109. package/src/workflow/changelog/extractPlainText.ts +38 -0
  110. package/src/workflow/changelog/extractPreviousVersion.ts +77 -0
  111. package/src/workflow/changelog/extractSemVer.ts +33 -0
  112. package/src/workflow/changelog/index.ts +12 -0
  113. package/src/workflow/changelog/iterateChangelogVersions.ts +70 -0
  114. package/src/workflow/changelog/prependChangelog.ts +59 -0
  115. package/src/workflow/changelog/writeChangelog.ts +27 -0
  116. package/src/workflow/committing/generateReleaseCommitMessage.ts +121 -0
  117. package/src/workflow/committing/index.ts +5 -0
  118. package/src/workflow/committing/isReleaseCommit.ts +56 -0
  119. package/src/workflow/discovery/buildDependencyGraph.ts +43 -0
  120. package/src/workflow/discovery/discoverPackageTag.ts +98 -0
  121. package/src/workflow/discovery/index.ts +9 -0
  122. package/src/workflow/discovery/resolvePackageStableTag.ts +88 -0
  123. package/src/workflow/discovery/resolvePackageTag.ts +45 -0
  124. package/src/workflow/discovery/sortPackages.ts +75 -0
  125. package/src/workflow/discovery/verifyPackageTag.ts +49 -0
  126. package/src/workflow/executeReleaseWorkflow.ts +130 -0
  127. package/src/workflow/index.ts +10 -0
  128. package/src/workflow/report/generateReleaseReport.ts +54 -0
  129. package/src/workflow/report/index.ts +5 -0
  130. package/src/workflow/report/printReleaseReport.ts +97 -0
  131. package/src/workflow/versioning/bumpVersion.ts +76 -0
  132. package/src/workflow/versioning/deriveReleaseType.ts +33 -0
  133. package/src/workflow/versioning/determineReleaseType.ts +35 -0
  134. package/src/workflow/versioning/extractVersionQualifier.ts +29 -0
  135. package/src/workflow/versioning/index.ts +10 -0
  136. package/src/workflow/versioning/isSameReleaseCycle.ts +36 -0
  137. package/src/workflow/versioning/isStableVersion.ts +31 -0
  138. package/src/workflow/versioning/pickPriorityReleaseType.ts +27 -0
@@ -0,0 +1,29 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { execGit } from '#util'
5
+
6
+ /**
7
+ * Read a file's contents from a specific Git revision.
8
+ *
9
+ * Runs `git show <ref>:<filePath>` and returns the command output as a
10
+ * string. If the file does not exist at the given revision or the Git
11
+ * command fails for any reason, the function returns `null`.
12
+ *
13
+ * The returned string is the raw file contents as emitted by Git; callers
14
+ * that need binary-safe handling should decode or process the bytes
15
+ * accordingly. This function intentionally swallows Git errors and signals
16
+ * absence via a `null` result rather than throwing.
17
+ *
18
+ * @param cwd Repository working directory
19
+ * @param ref Commit-ish reference (commit SHA, tag, or branch) to read from
20
+ * @param filePath Path to the file relative to the repository root
21
+ * @returns File contents as a string, or `null` if the file is unavailable at the ref
22
+ */
23
+ export function readGitFile(
24
+ cwd: string,
25
+ ref: string,
26
+ filePath: string
27
+ ): Promise<string | null> {
28
+ return execGit(cwd, ['show', `${ref}:${filePath}`]).catch(() => null)
29
+ }
@@ -0,0 +1,23 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { execGit } from '#util'
5
+
6
+ /**
7
+ * Resolve a Git revision or commit-ish expression to its full commit hash.
8
+ *
9
+ * Runs `git rev-parse --verify <revision>^{commit}` under the hood. Peels annotated
10
+ * tags, branches, short SHAs, and relative expressions down to a verified commit object.
11
+ *
12
+ * @param cwd The repository working directory
13
+ * @param revision The Git revision or expression to resolve
14
+ * @returns A promise that resolves to the full, trimmed commit SHA-1 string
15
+ */
16
+ export async function resolveGitRevision(
17
+ cwd: string,
18
+ revision: string
19
+ ): Promise<string> {
20
+ return (
21
+ await execGit(cwd, ['rev-parse', '--verify', `${revision}^{commit}`])
22
+ ).trim()
23
+ }
@@ -0,0 +1,25 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { execGit } from '#util'
5
+
6
+ /**
7
+ * Create a git tag in the repository at `cwd`.
8
+ *
9
+ * Creates an annotated tag when `message` is provided.
10
+ *
11
+ * @param cwd Repository working directory
12
+ * @param tag Tag name to create
13
+ * @param message Optional tag message (creates an annotated tag when present)
14
+ * @returns Promise that resolves when the tag is created
15
+ */
16
+ export async function createGitTag(
17
+ cwd: string,
18
+ tag: string,
19
+ message?: string
20
+ ): Promise<void> {
21
+ await execGit(cwd, [
22
+ 'tag',
23
+ ...(message ? ['-a', tag, '-m', message, '--cleanup=whitespace'] : [tag]),
24
+ ])
25
+ }
@@ -0,0 +1,17 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { execGit } from '#util'
5
+
6
+ /**
7
+ * Delete a local git tag in the repository at `cwd`.
8
+ *
9
+ * @param cwd Repository working directory
10
+ * @param tag Tag name to delete
11
+ * @returns `true` when deletion succeeded, otherwise `false`
12
+ */
13
+ export function deleteGitTag(cwd: string, tag: string): Promise<boolean> {
14
+ return execGit(cwd, ['tag', '-d', tag])
15
+ .then(() => true)
16
+ .catch(() => false)
17
+ }
@@ -0,0 +1,63 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { execGit } from '#util'
5
+ import { countGitHistory } from '../history/countGitHistory'
6
+ import { withShallowLock } from '../repository/withShallowLock'
7
+ import { deleteGitTag } from './deleteGitTag'
8
+ import { isGitTagPresent } from './isGitTagPresent'
9
+
10
+ const MIN_HISTORY_DEPTH = 2
11
+ const ORIGIN_NOT_REPO = `fatal: 'origin' does not appear to be a git repository`
12
+ const REMOTE_REF_NOT_FOUND = `fatal: couldn't find remote ref`
13
+
14
+ /**
15
+ * Ensure a tag exists locally, fetching it shallowly from `origin` if needed.
16
+ *
17
+ * Acquires a shallow-fetch lock, verifies local presence and history depth,
18
+ * attempts a shallow fetch of `refs/tags/<tag>` when required, and removes a
19
+ * local tag if the remote reports the tag is missing.
20
+ *
21
+ * @param cwd Working directory
22
+ * @param tag Tag name (for example `v1.2.0`)
23
+ * @returns `true` if the tag is present or was fetched; otherwise `false`
24
+ */
25
+ export function ensureGitTag(cwd: string, tag: string): Promise<boolean> {
26
+ return withShallowLock(cwd, async () => {
27
+ const tagRef = `refs/tags/${tag}`
28
+
29
+ if (
30
+ (await isGitTagPresent(cwd, tag)) &&
31
+ (await countGitHistory(cwd, tagRef)) >= MIN_HISTORY_DEPTH
32
+ ) {
33
+ return true
34
+ }
35
+
36
+ try {
37
+ await execGit(cwd, [
38
+ 'fetch',
39
+ 'origin',
40
+ `${tagRef}:${tagRef}`,
41
+ `--depth=${MIN_HISTORY_DEPTH}`,
42
+ '--update-shallow',
43
+ '--force',
44
+ ])
45
+
46
+ return true
47
+ } catch (err) {
48
+ const errorMessage = (err as Error | undefined)?.message
49
+
50
+ if (errorMessage?.includes(ORIGIN_NOT_REPO)) {
51
+ return await isGitTagPresent(cwd, tag)
52
+ }
53
+
54
+ if (errorMessage?.includes(REMOTE_REF_NOT_FOUND)) {
55
+ if (await isGitTagPresent(cwd, tag)) {
56
+ await deleteGitTag(cwd, tag)
57
+ }
58
+ }
59
+ }
60
+
61
+ return false
62
+ })
63
+ }
@@ -0,0 +1,43 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ /**
5
+ * Generate a git tag name for a package.
6
+ *
7
+ * For entry packages the tag is `v<version>`. For non-entry packages the
8
+ * tag is `<name>@<version>`. Returns `null` when `version` is not provided.
9
+ *
10
+ * @param entry Whether the package is the repository entry package
11
+ * @param name Package name (required for non-entry packages)
12
+ * @param version Package version
13
+ * @returns Tag string, or `null` when `version` is absent
14
+ */
15
+ export function generateGitTagName(
16
+ entry: boolean,
17
+ name: string | null | undefined,
18
+ version: string
19
+ ): string
20
+ export function generateGitTagName(
21
+ entry: boolean,
22
+ name: string | null | undefined,
23
+ version: string | null | undefined
24
+ ): string | null
25
+ export function generateGitTagName(
26
+ entry: boolean,
27
+ name: string | null | undefined,
28
+ version: string | null | undefined
29
+ ): string | null {
30
+ if (!version) {
31
+ return null
32
+ }
33
+
34
+ if (entry) {
35
+ return `v${version}`
36
+ }
37
+
38
+ if (!name) {
39
+ throw new Error('Package name is required to build a tag name.')
40
+ }
41
+
42
+ return `${name}@${version}`
43
+ }
@@ -0,0 +1,23 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { execGit } from '#util'
5
+
6
+ /**
7
+ * Get the tag name that exactly matches the current `HEAD`, if any.
8
+ *
9
+ * @param cwd Repository working directory
10
+ * @returns Tag name or `null` when no exact tag matches HEAD
11
+ */
12
+ export async function getCurrentGitTag(cwd: string): Promise<string | null> {
13
+ try {
14
+ const stdout = await execGit(cwd, ['describe', '--tags', '--exact-match'])
15
+
16
+ const tag = stdout.trim()
17
+
18
+ /* istanbul ignore next */
19
+ return tag ? tag : null
20
+ } catch {
21
+ return null
22
+ }
23
+ }
@@ -0,0 +1,35 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { execGit } from '#util'
5
+
6
+ /**
7
+ * Get the message of an annotated git tag in the repository at `cwd`.
8
+ *
9
+ * @param cwd Repository working directory
10
+ * @param tag Tag name to query
11
+ * @returns The tag message string when found, otherwise `undefined`
12
+ */
13
+ export async function getGitTagMessage(
14
+ cwd: string,
15
+ tag: string
16
+ ): Promise<string | undefined> {
17
+ try {
18
+ const stdout = await execGit(cwd, [
19
+ 'for-each-ref',
20
+ '--format=%(objecttype)%00%(contents)',
21
+ `refs/tags/${tag}`,
22
+ ])
23
+
24
+ const [objectType, message] = stdout.split('\0')
25
+
26
+ if (objectType?.trim() !== 'tag') {
27
+ return undefined
28
+ }
29
+
30
+ return message?.trim() || undefined
31
+ } catch {
32
+ /* istanbul ignore next */
33
+ return undefined
34
+ }
35
+ }
@@ -0,0 +1,22 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { execGit } from '#util'
5
+
6
+ /**
7
+ * Get the most recent tag reachable from `HEAD`.
8
+ *
9
+ * @param cwd Repository working directory
10
+ * @returns Latest tag string or `null` when none is found
11
+ */
12
+ export async function getLatestGitTag(cwd: string): Promise<string | null> {
13
+ try {
14
+ const stdout = await execGit(cwd, ['describe', '--tags', '--abbrev=0'])
15
+ const tag = stdout.trim()
16
+
17
+ /* istanbul ignore next */
18
+ return tag ? tag : null
19
+ } catch {
20
+ return null
21
+ }
22
+ }
@@ -0,0 +1,13 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ export * from './createGitTag'
5
+ export * from './deleteGitTag'
6
+ export * from './ensureGitTag'
7
+ export * from './generateGitTagName'
8
+ export * from './getCurrentGitTag'
9
+ export * from './getGitTagMessage'
10
+ export * from './getLatestGitTag'
11
+ export * from './isGitTagConnected'
12
+ export * from './isGitTagPointed'
13
+ export * from './isGitTagPresent'
@@ -0,0 +1,33 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { execGit } from '#util'
5
+
6
+ /**
7
+ * Determine whether a specific git tag commit is reachable from the current HEAD.
8
+ *
9
+ * Uses `git merge-base --is-ancestor refs/tags/<tag>^{commit} HEAD` to verify
10
+ * that the tag's commit is an ancestor of the current reference. Any non-zero
11
+ * exit status or execution error is treated as "not reachable".
12
+ *
13
+ * @param cwd Working directory where the git command will run
14
+ * @param tag Tag name to evaluate (for example, "v1.2.0")
15
+ * @returns True if the tag commit is reachable from HEAD, false otherwise
16
+ */
17
+ export async function isGitTagConnected(
18
+ cwd: string,
19
+ tag: string
20
+ ): Promise<boolean> {
21
+ try {
22
+ await execGit(cwd, [
23
+ 'merge-base',
24
+ '--is-ancestor',
25
+ `refs/tags/${tag}^{commit}`,
26
+ 'HEAD',
27
+ ])
28
+
29
+ return true
30
+ } catch {
31
+ return false
32
+ }
33
+ }
@@ -0,0 +1,38 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { execGit } from '#util'
5
+
6
+ /**
7
+ * Check whether a given tag points to the provided commit.
8
+ *
9
+ * @param cwd Repository working directory
10
+ * @param tag Tag name to resolve
11
+ * @param commit Commit hash to compare against
12
+ * @returns `true` when the tag points at `commit`, otherwise `false`
13
+ */
14
+ export async function isGitTagPointed(
15
+ cwd: string,
16
+ tag: string,
17
+ commit: string
18
+ ): Promise<boolean> {
19
+ try {
20
+ await execGit(cwd, [
21
+ 'merge-base',
22
+ '--is-ancestor',
23
+ `refs/tags/${tag}^{commit}`,
24
+ commit,
25
+ ])
26
+
27
+ await execGit(cwd, [
28
+ 'merge-base',
29
+ '--is-ancestor',
30
+ commit,
31
+ `refs/tags/${tag}^{commit}`,
32
+ ])
33
+
34
+ return true
35
+ } catch {
36
+ return false
37
+ }
38
+ }
@@ -0,0 +1,17 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { resolveGitRevision } from '../revision/resolveGitRevision'
5
+
6
+ /**
7
+ * Determine whether a specific git tag exists locally in the repository.
8
+ *
9
+ * @param cwd Working directory for the git command
10
+ * @param tag Name of the tag to evaluate
11
+ * @returns True if the tag reference exists locally, false otherwise
12
+ */
13
+ export function isGitTagPresent(cwd: string, tag: string): Promise<boolean> {
14
+ return resolveGitRevision(cwd, `refs/tags/${tag}`)
15
+ .then(() => true)
16
+ .catch(() => false)
17
+ }
package/src/index.ts CHANGED
@@ -1,3 +1,10 @@
1
- // Copyright (c) 2026 Fai Chen. Licensed under the MIT License.
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
2
3
 
3
- export {}
4
+ export * from './cache'
5
+ export * from './config'
6
+ export * from './git'
7
+ export * from './plugin'
8
+ export * from './types'
9
+ export * from './util'
10
+ export * from './workflow'
@@ -0,0 +1,128 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ export type NextFunction<Context> = (context: Context) => Promise<void>
5
+
6
+ export type HookHandler<Context> = {
7
+ bivariant(context: Context, next: NextFunction<Context>): void | Promise<void>
8
+ }['bivariant']
9
+
10
+ export const HookPriority = {
11
+ High: 50,
12
+ Normal: 0,
13
+ Low: -50,
14
+ } as const
15
+
16
+ interface HookRegistration<HookName, Context> {
17
+ name: HookName
18
+ handler: HookHandler<Context>
19
+ priority: number
20
+ }
21
+
22
+ export type InferContext<Handler> =
23
+ Handler extends HookHandler<infer Context> ? Context : never
24
+
25
+ /**
26
+ * Manage hook registrations and asynchronous execution chains.
27
+ *
28
+ * Stores handlers in a prioritized registry and executes them sequentially in
29
+ * priority order.
30
+ */
31
+ export class HookManager<
32
+ HookMap extends Record<keyof HookMap, HookHandler<unknown>>,
33
+ > {
34
+ readonly #registry = new Map<
35
+ keyof HookMap,
36
+ HookRegistration<keyof HookMap, unknown>[]
37
+ >()
38
+
39
+ /**
40
+ * Register a handler function for a specific hook.
41
+ *
42
+ * Adds the `handler` to the internal registry for `name` and sorts the list
43
+ * so higher-priority handlers run first.
44
+ *
45
+ * @param name Name of the hook to register
46
+ * @param handler Callback function executed when the hook triggers
47
+ * @param priority Execution order rank where higher values run earlier
48
+ */
49
+ on<HookName extends keyof HookMap>(
50
+ name: HookName,
51
+ handler: HookMap[HookName],
52
+ priority: number = HookPriority.Normal
53
+ ): void {
54
+ const registrations = this.#registry.get(name) ?? []
55
+
56
+ registrations.push({ name, handler, priority })
57
+
58
+ registrations.sort((a, b) => b.priority - a.priority)
59
+
60
+ this.#registry.set(name, registrations)
61
+ }
62
+
63
+ /**
64
+ * Unregister a handler function from a specific hook.
65
+ *
66
+ * Removes matching `handler` references from the internal registry for
67
+ * `name`. Takes no action if `name` has no registered handlers.
68
+ *
69
+ * @param name Name of the hook to unregister from
70
+ * @param handler Reference of the handler function to remove
71
+ */
72
+ off<HookName extends keyof HookMap>(
73
+ name: HookName,
74
+ handler: HookMap[HookName]
75
+ ): void {
76
+ const registrations = this.#registry.get(name)
77
+
78
+ if (!registrations) return
79
+
80
+ this.#registry.set(
81
+ name,
82
+ registrations.filter((registration) => registration.handler !== handler)
83
+ )
84
+ }
85
+
86
+ /**
87
+ * Trigger execution of all handlers registered to a hook.
88
+ *
89
+ * Passes `context` through the handler pipeline in descending priority order.
90
+ * Enables handlers to control execution flow using `next` and executes `done`
91
+ * after the last handler completes.
92
+ *
93
+ * @param name Name of the hook to trigger
94
+ * @param context Shared payload passed into each handler
95
+ * @param done Optional final callback run after the pipeline completes
96
+ * @returns Promise that resolves when execution completes
97
+ */
98
+ async emit<HookName extends keyof HookMap>(
99
+ name: HookName,
100
+ context: InferContext<HookMap[HookName]>,
101
+ done?: NextFunction<InferContext<HookMap[HookName]>>
102
+ ): Promise<void> {
103
+ type Context = InferContext<HookMap[HookName]>
104
+
105
+ const registrations = (this.#registry.get(name) ?? []) as HookRegistration<
106
+ HookName,
107
+ Context
108
+ >[]
109
+
110
+ const dispatch = async (index: number, context: Context): Promise<void> => {
111
+ const registration = registrations[index]
112
+
113
+ if (!registration) {
114
+ return done ? await done(context) : undefined
115
+ }
116
+
117
+ let isNextCalled = false
118
+
119
+ return await registration.handler(context, async (context) => {
120
+ if (isNextCalled) return
121
+ isNextCalled = true
122
+ return await dispatch(index + 1, context)
123
+ })
124
+ }
125
+
126
+ return await dispatch(0, context)
127
+ }
128
+ }
@@ -0,0 +1,4 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ export * from './HookManager'