@hyperfrontend/versioning 0.1.0 → 0.2.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 (158) hide show
  1. package/ARCHITECTURE.md +50 -1
  2. package/CHANGELOG.md +23 -23
  3. package/README.md +12 -9
  4. package/changelog/index.cjs.js +23 -2
  5. package/changelog/index.cjs.js.map +1 -1
  6. package/changelog/index.esm.js +23 -2
  7. package/changelog/index.esm.js.map +1 -1
  8. package/changelog/models/entry.d.ts +5 -0
  9. package/changelog/models/entry.d.ts.map +1 -1
  10. package/changelog/models/index.cjs.js +2 -0
  11. package/changelog/models/index.cjs.js.map +1 -1
  12. package/changelog/models/index.esm.js +2 -0
  13. package/changelog/models/index.esm.js.map +1 -1
  14. package/changelog/operations/index.cjs.js.map +1 -1
  15. package/changelog/operations/index.esm.js.map +1 -1
  16. package/changelog/parse/index.cjs.js +23 -2
  17. package/changelog/parse/index.cjs.js.map +1 -1
  18. package/changelog/parse/index.esm.js +23 -2
  19. package/changelog/parse/index.esm.js.map +1 -1
  20. package/changelog/parse/line.d.ts.map +1 -1
  21. package/commits/classify/classifier.d.ts +73 -0
  22. package/commits/classify/classifier.d.ts.map +1 -0
  23. package/commits/classify/index.cjs.js +705 -0
  24. package/commits/classify/index.cjs.js.map +1 -0
  25. package/commits/classify/index.d.ts +8 -0
  26. package/commits/classify/index.d.ts.map +1 -0
  27. package/commits/classify/index.esm.js +678 -0
  28. package/commits/classify/index.esm.js.map +1 -0
  29. package/commits/classify/infrastructure.d.ts +205 -0
  30. package/commits/classify/infrastructure.d.ts.map +1 -0
  31. package/commits/classify/models.d.ts +108 -0
  32. package/commits/classify/models.d.ts.map +1 -0
  33. package/commits/classify/project-scopes.d.ts +59 -0
  34. package/commits/classify/project-scopes.d.ts.map +1 -0
  35. package/commits/index.cjs.js +702 -0
  36. package/commits/index.cjs.js.map +1 -1
  37. package/commits/index.d.ts +1 -0
  38. package/commits/index.d.ts.map +1 -1
  39. package/commits/index.esm.js +677 -1
  40. package/commits/index.esm.js.map +1 -1
  41. package/flow/executor/execute.d.ts +6 -0
  42. package/flow/executor/execute.d.ts.map +1 -1
  43. package/flow/executor/index.cjs.js +1604 -42
  44. package/flow/executor/index.cjs.js.map +1 -1
  45. package/flow/executor/index.esm.js +1610 -48
  46. package/flow/executor/index.esm.js.map +1 -1
  47. package/flow/index.cjs.js +6651 -2893
  48. package/flow/index.cjs.js.map +1 -1
  49. package/flow/index.esm.js +6655 -2899
  50. package/flow/index.esm.js.map +1 -1
  51. package/flow/models/index.cjs.js +125 -0
  52. package/flow/models/index.cjs.js.map +1 -1
  53. package/flow/models/index.esm.js +125 -0
  54. package/flow/models/index.esm.js.map +1 -1
  55. package/flow/models/types.d.ts +148 -3
  56. package/flow/models/types.d.ts.map +1 -1
  57. package/flow/presets/conventional.d.ts +9 -8
  58. package/flow/presets/conventional.d.ts.map +1 -1
  59. package/flow/presets/independent.d.ts.map +1 -1
  60. package/flow/presets/index.cjs.js +3588 -298
  61. package/flow/presets/index.cjs.js.map +1 -1
  62. package/flow/presets/index.esm.js +3588 -298
  63. package/flow/presets/index.esm.js.map +1 -1
  64. package/flow/presets/synced.d.ts.map +1 -1
  65. package/flow/steps/analyze-commits.d.ts +9 -6
  66. package/flow/steps/analyze-commits.d.ts.map +1 -1
  67. package/flow/steps/calculate-bump.d.ts.map +1 -1
  68. package/flow/steps/fetch-registry.d.ts.map +1 -1
  69. package/flow/steps/generate-changelog.d.ts.map +1 -1
  70. package/flow/steps/index.cjs.js +3604 -318
  71. package/flow/steps/index.cjs.js.map +1 -1
  72. package/flow/steps/index.d.ts +1 -0
  73. package/flow/steps/index.d.ts.map +1 -1
  74. package/flow/steps/index.esm.js +3603 -319
  75. package/flow/steps/index.esm.js.map +1 -1
  76. package/flow/steps/resolve-repository.d.ts +36 -0
  77. package/flow/steps/resolve-repository.d.ts.map +1 -0
  78. package/flow/steps/update-packages.d.ts.map +1 -1
  79. package/git/factory.d.ts +14 -0
  80. package/git/factory.d.ts.map +1 -1
  81. package/git/index.cjs.js +65 -0
  82. package/git/index.cjs.js.map +1 -1
  83. package/git/index.esm.js +66 -2
  84. package/git/index.esm.js.map +1 -1
  85. package/git/operations/index.cjs.js +40 -0
  86. package/git/operations/index.cjs.js.map +1 -1
  87. package/git/operations/index.d.ts +1 -1
  88. package/git/operations/index.d.ts.map +1 -1
  89. package/git/operations/index.esm.js +41 -2
  90. package/git/operations/index.esm.js.map +1 -1
  91. package/git/operations/log.d.ts +23 -0
  92. package/git/operations/log.d.ts.map +1 -1
  93. package/index.cjs.js +6962 -4413
  94. package/index.cjs.js.map +1 -1
  95. package/index.esm.js +6964 -4415
  96. package/index.esm.js.map +1 -1
  97. package/package.json +26 -1
  98. package/registry/index.cjs.js +3 -3
  99. package/registry/index.cjs.js.map +1 -1
  100. package/registry/index.esm.js +3 -3
  101. package/registry/index.esm.js.map +1 -1
  102. package/registry/models/index.cjs.js +2 -0
  103. package/registry/models/index.cjs.js.map +1 -1
  104. package/registry/models/index.esm.js +2 -0
  105. package/registry/models/index.esm.js.map +1 -1
  106. package/registry/models/version-info.d.ts +10 -0
  107. package/registry/models/version-info.d.ts.map +1 -1
  108. package/registry/npm/client.d.ts.map +1 -1
  109. package/registry/npm/index.cjs.js +1 -3
  110. package/registry/npm/index.cjs.js.map +1 -1
  111. package/registry/npm/index.esm.js +1 -3
  112. package/registry/npm/index.esm.js.map +1 -1
  113. package/repository/index.cjs.js +998 -0
  114. package/repository/index.cjs.js.map +1 -0
  115. package/repository/index.d.ts +4 -0
  116. package/repository/index.d.ts.map +1 -0
  117. package/repository/index.esm.js +981 -0
  118. package/repository/index.esm.js.map +1 -0
  119. package/repository/models/index.cjs.js +301 -0
  120. package/repository/models/index.cjs.js.map +1 -0
  121. package/repository/models/index.d.ts +7 -0
  122. package/repository/models/index.d.ts.map +1 -0
  123. package/repository/models/index.esm.js +290 -0
  124. package/repository/models/index.esm.js.map +1 -0
  125. package/repository/models/platform.d.ts +58 -0
  126. package/repository/models/platform.d.ts.map +1 -0
  127. package/repository/models/repository-config.d.ts +132 -0
  128. package/repository/models/repository-config.d.ts.map +1 -0
  129. package/repository/models/resolution.d.ts +121 -0
  130. package/repository/models/resolution.d.ts.map +1 -0
  131. package/repository/parse/index.cjs.js +755 -0
  132. package/repository/parse/index.cjs.js.map +1 -0
  133. package/repository/parse/index.d.ts +5 -0
  134. package/repository/parse/index.d.ts.map +1 -0
  135. package/repository/parse/index.esm.js +749 -0
  136. package/repository/parse/index.esm.js.map +1 -0
  137. package/repository/parse/package-json.d.ts +100 -0
  138. package/repository/parse/package-json.d.ts.map +1 -0
  139. package/repository/parse/url.d.ts +81 -0
  140. package/repository/parse/url.d.ts.map +1 -0
  141. package/repository/url/compare.d.ts +84 -0
  142. package/repository/url/compare.d.ts.map +1 -0
  143. package/repository/url/index.cjs.js +178 -0
  144. package/repository/url/index.cjs.js.map +1 -0
  145. package/repository/url/index.d.ts +3 -0
  146. package/repository/url/index.d.ts.map +1 -0
  147. package/repository/url/index.esm.js +176 -0
  148. package/repository/url/index.esm.js.map +1 -0
  149. package/workspace/discovery/index.cjs.js +324 -330
  150. package/workspace/discovery/index.cjs.js.map +1 -1
  151. package/workspace/discovery/index.esm.js +324 -330
  152. package/workspace/discovery/index.esm.js.map +1 -1
  153. package/workspace/discovery/packages.d.ts +0 -6
  154. package/workspace/discovery/packages.d.ts.map +1 -1
  155. package/workspace/index.cjs.js +0 -6
  156. package/workspace/index.cjs.js.map +1 -1
  157. package/workspace/index.esm.js +0 -6
  158. package/workspace/index.esm.js.map +1 -1
@@ -1,3 +1,6 @@
1
+ import { join, basename, relative } from 'node:path';
2
+ import { existsSync, readFileSync, statSync, lstatSync, readdirSync } from 'node:fs';
3
+
1
4
  /**
2
5
  * Safe copies of JSON built-in methods.
3
6
  *
@@ -27,125 +30,2741 @@ const stringify = _JSON.stringify;
27
30
  * @returns A FlowStep object
28
31
  *
29
32
  * @example
30
- * ```typescript
31
- * const fetchStep = createStep(
32
- * 'fetch-registry',
33
- * 'Fetch Registry Version',
34
- * async (ctx) => {
35
- * const version = await ctx.registry.getLatestVersion(ctx.packageName)
36
- * return {
37
- * status: 'success',
38
- * stateUpdates: { publishedVersion: version },
39
- * message: `Found published version: ${version}`
40
- * }
41
- * }
42
- * )
43
- * ```
33
+ * ```typescript
34
+ * const fetchStep = createStep(
35
+ * 'fetch-registry',
36
+ * 'Fetch Registry Version',
37
+ * async (ctx) => {
38
+ * const version = await ctx.registry.getLatestVersion(ctx.packageName)
39
+ * return {
40
+ * status: 'success',
41
+ * stateUpdates: { publishedVersion: version },
42
+ * message: `Found published version: ${version}`
43
+ * }
44
+ * }
45
+ * )
46
+ * ```
47
+ */
48
+ function createStep(id, name, execute, options = {}) {
49
+ return {
50
+ id,
51
+ name,
52
+ execute,
53
+ description: options.description,
54
+ skipIf: options.skipIf,
55
+ continueOnError: options.continueOnError,
56
+ dependsOn: options.dependsOn,
57
+ };
58
+ }
59
+ /**
60
+ * Creates a skipped step result.
61
+ *
62
+ * @param message - Explanation for why the step was skipped
63
+ * @returns A FlowStepResult with 'skipped' status
64
+ */
65
+ function createSkippedResult(message) {
66
+ return {
67
+ status: 'skipped',
68
+ message,
69
+ };
70
+ }
71
+
72
+ const FETCH_REGISTRY_STEP_ID = 'fetch-registry';
73
+ /**
74
+ * Creates the fetch-registry step.
75
+ *
76
+ * This step:
77
+ * 1. Queries the registry for the latest published version
78
+ * 2. Reads the current version from package.json
79
+ * 3. Determines if this is a first release
80
+ *
81
+ * State updates:
82
+ * - publishedVersion: Latest version on registry (null if not published)
83
+ * - currentVersion: Version from local package.json
84
+ * - isFirstRelease: True if never published
85
+ *
86
+ * @returns A FlowStep that fetches registry information
87
+ */
88
+ function createFetchRegistryStep() {
89
+ return createStep(FETCH_REGISTRY_STEP_ID, 'Fetch Registry Version', async (ctx) => {
90
+ const { registry, tree, projectRoot, packageName, logger } = ctx;
91
+ // Read local package.json for current version
92
+ const packageJsonPath = `${projectRoot}/package.json`;
93
+ let currentVersion = '0.0.0';
94
+ try {
95
+ const content = tree.read(packageJsonPath, 'utf-8');
96
+ if (content) {
97
+ const pkg = parse(content);
98
+ currentVersion = pkg.version ?? '0.0.0';
99
+ }
100
+ }
101
+ catch (error) {
102
+ logger.warn(`Could not read package.json: ${error}`);
103
+ }
104
+ // Query registry for published version
105
+ let publishedVersion = null;
106
+ let publishedCommit = null;
107
+ let isFirstRelease = true;
108
+ try {
109
+ publishedVersion = await registry.getLatestVersion(packageName);
110
+ isFirstRelease = publishedVersion === null;
111
+ // When published version exists, get its commit hash from gitHead
112
+ if (publishedVersion) {
113
+ try {
114
+ const versionInfo = await registry.getVersionInfo(packageName, publishedVersion);
115
+ publishedCommit = versionInfo?.gitHead ?? null;
116
+ if (publishedCommit) {
117
+ logger.debug(`Published ${publishedVersion} at commit ${publishedCommit.slice(0, 7)}`);
118
+ }
119
+ else {
120
+ logger.debug(`Published ${publishedVersion} has no gitHead (older package or published without git)`);
121
+ }
122
+ }
123
+ catch (error) {
124
+ // Version info fetch failed, but we still have the version
125
+ logger.debug(`Could not fetch version info for ${publishedVersion}: ${error}`);
126
+ }
127
+ }
128
+ }
129
+ catch (error) {
130
+ // Package might not exist yet, which is fine
131
+ logger.debug(`Registry query failed (package may not exist): ${error}`);
132
+ isFirstRelease = true;
133
+ }
134
+ const message = isFirstRelease
135
+ ? `First release (local: ${currentVersion})`
136
+ : `Published: ${publishedVersion}${publishedCommit ? ` @ ${publishedCommit.slice(0, 7)}` : ''}, Local: ${currentVersion}`;
137
+ return {
138
+ status: 'success',
139
+ stateUpdates: {
140
+ publishedVersion,
141
+ publishedCommit,
142
+ currentVersion,
143
+ isFirstRelease,
144
+ },
145
+ message,
146
+ };
147
+ });
148
+ }
149
+
150
+ /**
151
+ * Safe copies of Error built-ins via factory functions.
152
+ *
153
+ * Since constructors cannot be safely captured via Object.assign, this module
154
+ * provides factory functions that use Reflect.construct internally.
155
+ *
156
+ * These references are captured at module initialization time to protect against
157
+ * prototype pollution attacks. Import only what you need for tree-shaking.
158
+ *
159
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/error
160
+ */
161
+ // Capture references at module initialization time
162
+ const _Error = globalThis.Error;
163
+ const _Reflect$4 = globalThis.Reflect;
164
+ /**
165
+ * (Safe copy) Creates a new Error using the captured Error constructor.
166
+ * Use this instead of `new Error()`.
167
+ *
168
+ * @param message - Optional error message.
169
+ * @param options - Optional error options.
170
+ * @returns A new Error instance.
171
+ */
172
+ const createError = (message, options) => _Reflect$4.construct(_Error, [message, options]);
173
+
174
+ /**
175
+ * Creates a new RepositoryConfig.
176
+ *
177
+ * Normalizes the base URL by stripping trailing slashes and validating
178
+ * that custom platforms have a formatter function.
179
+ *
180
+ * @param options - Repository configuration options
181
+ * @returns A new RepositoryConfig object
182
+ * @throws {Error} if platform is 'custom' but no formatCompareUrl is provided
183
+ *
184
+ * @example
185
+ * ```typescript
186
+ * // GitHub repository
187
+ * const config = createRepositoryConfig({
188
+ * platform: 'github',
189
+ * baseUrl: 'https://github.com/owner/repo'
190
+ * })
191
+ *
192
+ * // Custom platform
193
+ * const customConfig = createRepositoryConfig({
194
+ * platform: 'custom',
195
+ * baseUrl: 'https://my-git.internal/repo',
196
+ * formatCompareUrl: (from, to) => `https://my-git.internal/diff/${from}/${to}`
197
+ * })
198
+ * ```
199
+ */
200
+ function createRepositoryConfig(options) {
201
+ const { platform, formatCompareUrl } = options;
202
+ // Validate custom platform has formatter
203
+ if (platform === 'custom' && !formatCompareUrl) {
204
+ throw createError("Repository config with platform 'custom' requires a formatCompareUrl function");
205
+ }
206
+ // Normalize base URL - strip trailing slashes
207
+ const baseUrl = normalizeBaseUrl(options.baseUrl);
208
+ return {
209
+ platform,
210
+ baseUrl,
211
+ formatCompareUrl,
212
+ };
213
+ }
214
+ /**
215
+ * Checks if a value is a RepositoryConfig object.
216
+ *
217
+ * @param value - Value to check
218
+ * @returns True if the value is a RepositoryConfig
219
+ *
220
+ * @example
221
+ * ```typescript
222
+ * const config = { platform: 'github', baseUrl: 'https://...' }
223
+ * if (isRepositoryConfig(config)) {
224
+ * // config is typed as RepositoryConfig
225
+ * }
226
+ * ```
227
+ */
228
+ function isRepositoryConfig(value) {
229
+ if (typeof value !== 'object' || value === null) {
230
+ return false;
231
+ }
232
+ const obj = value;
233
+ return (typeof obj['platform'] === 'string' &&
234
+ typeof obj['baseUrl'] === 'string' &&
235
+ (obj['formatCompareUrl'] === undefined || typeof obj['formatCompareUrl'] === 'function'));
236
+ }
237
+ /**
238
+ * Normalizes a base URL by stripping trailing slashes and .git suffix.
239
+ *
240
+ * @param url - URL to normalize
241
+ * @returns Normalized URL
242
+ *
243
+ * @internal
244
+ */
245
+ function normalizeBaseUrl(url) {
246
+ let normalized = url.trim();
247
+ // Remove trailing slashes
248
+ while (normalized.endsWith('/')) {
249
+ normalized = normalized.slice(0, -1);
250
+ }
251
+ // Remove .git suffix if present
252
+ if (normalized.endsWith('.git')) {
253
+ normalized = normalized.slice(0, -4);
254
+ }
255
+ return normalized;
256
+ }
257
+
258
+ /**
259
+ * Creates a disabled repository resolution configuration.
260
+ *
261
+ * No compare URLs will be generated.
262
+ *
263
+ * @returns A RepositoryResolution with mode 'disabled'
264
+ *
265
+ * @example
266
+ * ```typescript
267
+ * const config = createDisabledResolution()
268
+ * // { mode: 'disabled' }
269
+ * ```
270
+ */
271
+ /**
272
+ * Checks if a value is a RepositoryResolution object.
273
+ *
274
+ * @param value - Value to check
275
+ * @returns True if the value is a RepositoryResolution
276
+ */
277
+ function isRepositoryResolution(value) {
278
+ if (typeof value !== 'object' || value === null) {
279
+ return false;
280
+ }
281
+ const obj = value;
282
+ const mode = obj['mode'];
283
+ return mode === 'explicit' || mode === 'inferred' || mode === 'disabled';
284
+ }
285
+ /**
286
+ * Default inference order when mode is 'inferred'.
287
+ */
288
+ const DEFAULT_INFERENCE_ORDER = ['package-json', 'git-remote'];
289
+
290
+ /**
291
+ * Safe copies of Map built-in via factory function.
292
+ *
293
+ * Since constructors cannot be safely captured via Object.assign, this module
294
+ * provides a factory function that uses Reflect.construct internally.
295
+ *
296
+ * These references are captured at module initialization time to protect against
297
+ * prototype pollution attacks. Import only what you need for tree-shaking.
298
+ *
299
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/map
300
+ */
301
+ // Capture references at module initialization time
302
+ const _Map = globalThis.Map;
303
+ const _Reflect$3 = globalThis.Reflect;
304
+ /**
305
+ * (Safe copy) Creates a new Map using the captured Map constructor.
306
+ * Use this instead of `new Map()`.
307
+ *
308
+ * @param iterable - Optional iterable of key-value pairs.
309
+ * @returns A new Map instance.
310
+ */
311
+ const createMap = (iterable) => _Reflect$3.construct(_Map, iterable ? [iterable] : []);
312
+
313
+ /**
314
+ * Safe copies of Math built-in methods.
315
+ *
316
+ * These references are captured at module initialization time to protect against
317
+ * prototype pollution attacks. Import only what you need for tree-shaking.
318
+ *
319
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/math
320
+ */
321
+ // Capture references at module initialization time
322
+ const _Math = globalThis.Math;
323
+ // ============================================================================
324
+ // Min/Max
325
+ // ============================================================================
326
+ /**
327
+ * (Safe copy) Returns the larger of zero or more numbers.
328
+ */
329
+ const max = _Math.max;
330
+ /**
331
+ * (Safe copy) Returns the smaller of zero or more numbers.
332
+ */
333
+ const min = _Math.min;
334
+
335
+ /**
336
+ * Safe copies of URL built-ins via factory functions.
337
+ *
338
+ * Provides safe references to URL and URLSearchParams.
339
+ * These references are captured at module initialization time to protect against
340
+ * prototype pollution attacks. Import only what you need for tree-shaking.
341
+ *
342
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/url
343
+ */
344
+ // Capture references at module initialization time
345
+ const _URL = globalThis.URL;
346
+ const _Reflect$2 = globalThis.Reflect;
347
+ // ============================================================================
348
+ // URL
349
+ // ============================================================================
350
+ /**
351
+ * (Safe copy) Creates a new URL using the captured URL constructor.
352
+ * Use this instead of `new URL()`.
353
+ *
354
+ * @param url - The URL string to parse.
355
+ * @param base - Optional base URL for relative URLs.
356
+ * @returns A new URL instance.
357
+ */
358
+ const createURL = (url, base) => _Reflect$2.construct(_URL, [url, base]);
359
+ /**
360
+ * (Safe copy) Creates an object URL for the given object.
361
+ * Use this instead of `URL.createObjectURL()`.
362
+ *
363
+ * Note: This is a browser-only API. In Node.js environments, this will throw.
364
+ */
365
+ typeof _URL.createObjectURL === 'function'
366
+ ? _URL.createObjectURL.bind(_URL)
367
+ : () => {
368
+ throw new Error('URL.createObjectURL is not available in this environment');
369
+ };
370
+ /**
371
+ * (Safe copy) Revokes an object URL previously created with createObjectURL.
372
+ * Use this instead of `URL.revokeObjectURL()`.
373
+ *
374
+ * Note: This is a browser-only API. In Node.js environments, this will throw.
375
+ */
376
+ typeof _URL.revokeObjectURL === 'function'
377
+ ? _URL.revokeObjectURL.bind(_URL)
378
+ : () => {
379
+ throw new Error('URL.revokeObjectURL is not available in this environment');
380
+ };
381
+
382
+ /**
383
+ * Checks if a platform identifier is a known platform with built-in support.
384
+ *
385
+ * @param platform - Platform identifier to check
386
+ * @returns True if the platform is a known platform
387
+ *
388
+ * @example
389
+ * ```typescript
390
+ * isKnownPlatform('github') // true
391
+ * isKnownPlatform('gitlab') // true
392
+ * isKnownPlatform('custom') // false
393
+ * isKnownPlatform('unknown') // false
394
+ * ```
395
+ */
396
+ function isKnownPlatform(platform) {
397
+ return platform === 'github' || platform === 'gitlab' || platform === 'bitbucket' || platform === 'azure-devops';
398
+ }
399
+ /**
400
+ * Known platform hostnames mapped to their platform type.
401
+ * Used for automatic platform detection from repository URLs.
402
+ *
403
+ * Includes both standard SaaS domains and common patterns for self-hosted instances.
404
+ */
405
+ const PLATFORM_HOSTNAMES = createMap([
406
+ // GitHub
407
+ ['github.com', 'github'],
408
+ // GitLab
409
+ ['gitlab.com', 'gitlab'],
410
+ // Bitbucket
411
+ ['bitbucket.org', 'bitbucket'],
412
+ // Azure DevOps
413
+ ['dev.azure.com', 'azure-devops'],
414
+ ['visualstudio.com', 'azure-devops'],
415
+ ]);
416
+ /**
417
+ * Detects platform from a hostname.
418
+ *
419
+ * First checks for exact match in known platforms, then applies heuristics
420
+ * for self-hosted instances (e.g., `github.company.com` → `github`).
421
+ *
422
+ * @param hostname - Hostname to detect platform from (e.g., "github.com")
423
+ * @returns Detected platform or 'unknown' if not recognized
424
+ *
425
+ * @example
426
+ * ```typescript
427
+ * detectPlatformFromHostname('github.com') // 'github'
428
+ * detectPlatformFromHostname('gitlab.mycompany.com') // 'gitlab'
429
+ * detectPlatformFromHostname('custom-git.internal') // 'unknown'
430
+ * ```
431
+ */
432
+ function detectPlatformFromHostname(hostname) {
433
+ const normalized = hostname.toLowerCase();
434
+ // Check exact matches first
435
+ const exactMatch = PLATFORM_HOSTNAMES.get(normalized);
436
+ if (exactMatch) {
437
+ return exactMatch;
438
+ }
439
+ // Check for Azure DevOps legacy domain pattern
440
+ if (normalized.endsWith('.visualstudio.com')) {
441
+ return 'azure-devops';
442
+ }
443
+ // Check for Azure DevOps modern domain pattern (includes ssh.dev.azure.com)
444
+ if (normalized.endsWith('.azure.com')) {
445
+ return 'azure-devops';
446
+ }
447
+ // Heuristics for self-hosted instances
448
+ // GitHub Enterprise typically uses "github" in the hostname
449
+ if (normalized.includes('github')) {
450
+ return 'github';
451
+ }
452
+ // GitLab self-hosted typically uses "gitlab" in the hostname
453
+ if (normalized.includes('gitlab')) {
454
+ return 'gitlab';
455
+ }
456
+ // Bitbucket Data Center/Server might use "bitbucket" in hostname
457
+ if (normalized.includes('bitbucket')) {
458
+ return 'bitbucket';
459
+ }
460
+ return 'unknown';
461
+ }
462
+
463
+ /**
464
+ * Parses a git URL and extracts platform and base URL.
465
+ *
466
+ * Supports multiple URL formats:
467
+ * - `https://github.com/owner/repo`
468
+ * - `https://github.com/owner/repo.git`
469
+ * - `git+https://github.com/owner/repo.git`
470
+ * - `git://github.com/owner/repo.git`
471
+ * - `git@github.com:owner/repo.git` (SSH format)
472
+ *
473
+ * Handles self-hosted instances by detecting platform from hostname:
474
+ * - `github.mycompany.com` → `github`
475
+ * - `gitlab.internal.com` → `gitlab`
476
+ *
477
+ * Handles Azure DevOps URL formats:
478
+ * - `https://dev.azure.com/org/project/_git/repo`
479
+ * - `https://org.visualstudio.com/project/_git/repo`
480
+ *
481
+ * @param gitUrl - Git repository URL in any supported format
482
+ * @returns Parsed repository info with platform and base URL, or null if parsing fails
483
+ *
484
+ * @example
485
+ * ```typescript
486
+ * // GitHub HTTPS
487
+ * parseRepositoryUrl('https://github.com/owner/repo')
488
+ * // → { platform: 'github', baseUrl: 'https://github.com/owner/repo' }
489
+ *
490
+ * // SSH format
491
+ * parseRepositoryUrl('git@github.com:owner/repo.git')
492
+ * // → { platform: 'github', baseUrl: 'https://github.com/owner/repo' }
493
+ *
494
+ * // Azure DevOps
495
+ * parseRepositoryUrl('https://dev.azure.com/org/proj/_git/repo')
496
+ * // → { platform: 'azure-devops', baseUrl: 'https://dev.azure.com/org/proj/_git/repo' }
497
+ *
498
+ * // Self-hosted GitLab
499
+ * parseRepositoryUrl('https://gitlab.mycompany.com/team/project')
500
+ * // → { platform: 'gitlab', baseUrl: 'https://gitlab.mycompany.com/team/project' }
501
+ * ```
502
+ */
503
+ function parseRepositoryUrl(gitUrl) {
504
+ if (!gitUrl || typeof gitUrl !== 'string') {
505
+ return null;
506
+ }
507
+ const trimmed = gitUrl.trim();
508
+ if (!trimmed) {
509
+ return null;
510
+ }
511
+ // Try SSH format first: git@hostname:path
512
+ const sshParsed = parseSshUrl(trimmed);
513
+ if (sshParsed) {
514
+ return sshParsed;
515
+ }
516
+ // Try HTTP(S) formats
517
+ const httpParsed = parseHttpUrl(trimmed);
518
+ if (httpParsed) {
519
+ return httpParsed;
520
+ }
521
+ return null;
522
+ }
523
+ /**
524
+ * Parses an SSH-style git URL.
525
+ *
526
+ * @param url - URL to parse (e.g., "git@github.com:owner/repo.git")
527
+ * @returns Parsed repository or null
528
+ *
529
+ * @internal
530
+ */
531
+ function parseSshUrl(url) {
532
+ // Handle optional ssh:// prefix
533
+ let remaining = url;
534
+ if (remaining.startsWith('ssh://')) {
535
+ remaining = remaining.slice(6);
536
+ }
537
+ // Must start with git@
538
+ if (!remaining.startsWith('git@')) {
539
+ return null;
540
+ }
541
+ // Remove git@ prefix
542
+ remaining = remaining.slice(4);
543
+ // Find the separator (: or /)
544
+ const colonIndex = remaining.indexOf(':');
545
+ const slashIndex = remaining.indexOf('/');
546
+ let separatorIndex;
547
+ if (colonIndex === -1 && slashIndex === -1) {
548
+ return null;
549
+ }
550
+ else if (colonIndex === -1) {
551
+ separatorIndex = slashIndex;
552
+ }
553
+ else if (slashIndex === -1) {
554
+ separatorIndex = colonIndex;
555
+ }
556
+ else {
557
+ separatorIndex = min(colonIndex, slashIndex);
558
+ }
559
+ const hostname = remaining.slice(0, separatorIndex);
560
+ const pathPart = normalizePathPart(remaining.slice(separatorIndex + 1));
561
+ if (!hostname || !pathPart) {
562
+ return null;
563
+ }
564
+ const platform = detectPlatformFromHostname(hostname);
565
+ // For Azure DevOps, construct proper base URL
566
+ if (platform === 'azure-devops') {
567
+ const baseUrl = constructAzureDevOpsBaseUrl(hostname, pathPart);
568
+ if (baseUrl) {
569
+ return { platform, baseUrl };
570
+ }
571
+ return null;
572
+ }
573
+ // Standard platforms: https://hostname/path
574
+ const baseUrl = `https://${hostname}/${pathPart}`;
575
+ return { platform, baseUrl };
576
+ }
577
+ /**
578
+ * Parses an HTTP(S)-style git URL.
579
+ *
580
+ * @param url - URL to parse
581
+ * @returns Parsed repository or null
582
+ *
583
+ * @internal
584
+ */
585
+ function parseHttpUrl(url) {
586
+ // Normalize various git URL prefixes to https://
587
+ const normalized = url
588
+ .replace(/^git\+/, '') // git+https:// → https://
589
+ .replace(/^git:\/\//, 'https://'); // git:// → https://
590
+ let parsed;
591
+ try {
592
+ parsed = createURL(normalized);
593
+ }
594
+ catch {
595
+ return null;
596
+ }
597
+ // Only support http and https protocols
598
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
599
+ return null;
600
+ }
601
+ const hostname = parsed.hostname.toLowerCase();
602
+ const platform = detectPlatformFromHostname(hostname);
603
+ const pathPart = normalizePathPart(parsed.pathname);
604
+ if (!pathPart) {
605
+ return null;
606
+ }
607
+ // Handle Azure DevOps special URL structure
608
+ if (platform === 'azure-devops') {
609
+ const baseUrl = constructAzureDevOpsBaseUrl(hostname, pathPart);
610
+ if (baseUrl) {
611
+ return { platform, baseUrl };
612
+ }
613
+ // If Azure DevOps URL cannot be parsed properly, return null
614
+ return null;
615
+ }
616
+ // Standard platforms
617
+ const baseUrl = `${parsed.protocol}//${hostname}/${pathPart}`;
618
+ return { platform, baseUrl };
619
+ }
620
+ /**
621
+ * Normalizes a path part by removing leading slashes and .git suffix.
622
+ *
623
+ * @param path - Path to normalize
624
+ * @returns Normalized path or null if empty
625
+ *
626
+ * @internal
627
+ */
628
+ function normalizePathPart(path) {
629
+ let normalized = path.trim();
630
+ // Remove leading slashes
631
+ while (normalized.startsWith('/')) {
632
+ normalized = normalized.slice(1);
633
+ }
634
+ // Remove trailing slashes
635
+ while (normalized.endsWith('/')) {
636
+ normalized = normalized.slice(0, -1);
637
+ }
638
+ // Remove .git suffix
639
+ if (normalized.endsWith('.git')) {
640
+ normalized = normalized.slice(0, -4);
641
+ }
642
+ // Validate we have something
643
+ if (!normalized) {
644
+ return null;
645
+ }
646
+ return normalized;
647
+ }
648
+ /**
649
+ * Constructs the base URL for Azure DevOps repositories.
650
+ *
651
+ * Azure DevOps has special URL structures:
652
+ * - Modern: `https://dev.azure.com/{org}/{project}/_git/{repo}`
653
+ * - Legacy: `https://{org}.visualstudio.com/{project}/_git/{repo}`
654
+ * - SSH: `git@ssh.dev.azure.com:v3/{org}/{project}/{repo}`
655
+ *
656
+ * @param hostname - Hostname from the URL
657
+ * @param pathPart - Path portion after hostname
658
+ * @returns Constructed base URL or null if invalid
659
+ *
660
+ * @internal
661
+ */
662
+ function constructAzureDevOpsBaseUrl(hostname, pathPart) {
663
+ const pathParts = pathPart.split('/');
664
+ // dev.azure.com format: org/project/_git/repo
665
+ if (hostname === 'dev.azure.com' || hostname.endsWith('.azure.com')) {
666
+ // Need at least: org/project/_git/repo (4 parts)
667
+ // Or for SSH v3: v3/org/project/repo (4 parts)
668
+ if (pathParts.length >= 4) {
669
+ // Check for v3 SSH format
670
+ if (pathParts[0] === 'v3') {
671
+ // v3/org/project/repo → https://dev.azure.com/org/project/_git/repo
672
+ const org = pathParts[1];
673
+ const project = pathParts[2];
674
+ const repo = pathParts[3];
675
+ if (org && project && repo) {
676
+ return `https://dev.azure.com/${org}/${project}/_git/${repo}`;
677
+ }
678
+ }
679
+ // Standard format: org/project/_git/repo
680
+ const gitIndex = pathParts.indexOf('_git');
681
+ if (gitIndex >= 2 && pathParts[gitIndex + 1]) {
682
+ const org = pathParts.slice(0, gitIndex - 1).join('/');
683
+ const project = pathParts[gitIndex - 1];
684
+ const repo = pathParts[gitIndex + 1];
685
+ if (org && project && repo) {
686
+ return `https://dev.azure.com/${org}/${project}/_git/${repo}`;
687
+ }
688
+ }
689
+ }
690
+ return null;
691
+ }
692
+ // visualstudio.com format: {org}.visualstudio.com/project/_git/repo
693
+ if (hostname.endsWith('.visualstudio.com')) {
694
+ const org = hostname.replace('.visualstudio.com', '');
695
+ const gitIndex = pathParts.indexOf('_git');
696
+ if (gitIndex >= 1 && pathParts[gitIndex + 1]) {
697
+ const project = pathParts.slice(0, gitIndex).join('/');
698
+ const repo = pathParts[gitIndex + 1];
699
+ if (project && repo) {
700
+ // Normalize to dev.azure.com format
701
+ return `https://dev.azure.com/${org}/${project}/_git/${repo}`;
702
+ }
703
+ }
704
+ return null;
705
+ }
706
+ return null;
707
+ }
708
+ /**
709
+ * Creates a RepositoryConfig from a git URL.
710
+ *
711
+ * This is a convenience function that combines `parseRepositoryUrl` with
712
+ * `createRepositoryConfig` to produce a ready-to-use configuration.
713
+ *
714
+ * @param gitUrl - Git repository URL in any supported format
715
+ * @returns RepositoryConfig or null if URL cannot be parsed
716
+ *
717
+ * @example
718
+ * ```typescript
719
+ * const config = createRepositoryConfigFromUrl('https://github.com/owner/repo')
720
+ * // → { platform: 'github', baseUrl: 'https://github.com/owner/repo' }
721
+ *
722
+ * const config = createRepositoryConfigFromUrl('git@gitlab.com:group/project.git')
723
+ * // → { platform: 'gitlab', baseUrl: 'https://gitlab.com/group/project' }
724
+ * ```
725
+ */
726
+ function createRepositoryConfigFromUrl(gitUrl) {
727
+ const parsed = parseRepositoryUrl(gitUrl);
728
+ if (!parsed) {
729
+ return null;
730
+ }
731
+ // Don't create configs for unknown platforms as they can't generate URLs
732
+ if (parsed.platform === 'unknown') {
733
+ return null;
734
+ }
735
+ return createRepositoryConfig({
736
+ platform: parsed.platform,
737
+ baseUrl: parsed.baseUrl,
738
+ });
739
+ }
740
+
741
+ /**
742
+ * Shorthand platform prefixes supported in package.json repository field.
743
+ *
744
+ * Format: `"platform:owner/repo"` or `"owner/repo"` (defaults to GitHub)
745
+ *
746
+ * @see https://docs.npmjs.com/cli/v9/configuring-npm/package-json#repository
747
+ */
748
+ const SHORTHAND_PLATFORMS = createMap([
749
+ ['github', 'https://github.com'],
750
+ ['gitlab', 'https://gitlab.com'],
751
+ ['bitbucket', 'https://bitbucket.org'],
752
+ ['gist', 'https://gist.github.com'],
753
+ ]);
754
+ /**
755
+ * Infers repository configuration from package.json content.
756
+ *
757
+ * Handles multiple formats:
758
+ * - Shorthand: `"github:owner/repo"`, `"gitlab:group/project"`, `"bitbucket:team/repo"`
759
+ * - Bare shorthand: `"owner/repo"` (defaults to GitHub)
760
+ * - URL string: `"https://github.com/owner/repo"`
761
+ * - Object with URL: `{ "type": "git", "url": "https://..." }`
762
+ *
763
+ * @param packageJsonContent - Raw JSON string content of package.json
764
+ * @returns RepositoryConfig or null if repository cannot be inferred
765
+ *
766
+ * @example
767
+ * ```typescript
768
+ * // Shorthand format
769
+ * inferRepositoryFromPackageJson('{"repository": "github:owner/repo"}')
770
+ * // → { platform: 'github', baseUrl: 'https://github.com/owner/repo' }
771
+ *
772
+ * // URL string
773
+ * inferRepositoryFromPackageJson('{"repository": "https://github.com/owner/repo"}')
774
+ * // → { platform: 'github', baseUrl: 'https://github.com/owner/repo' }
775
+ *
776
+ * // Object format
777
+ * inferRepositoryFromPackageJson('{"repository": {"type": "git", "url": "https://github.com/owner/repo"}}')
778
+ * // → { platform: 'github', baseUrl: 'https://github.com/owner/repo' }
779
+ *
780
+ * // Bare shorthand (defaults to GitHub)
781
+ * inferRepositoryFromPackageJson('{"repository": "owner/repo"}')
782
+ * // → { platform: 'github', baseUrl: 'https://github.com/owner/repo' }
783
+ * ```
784
+ */
785
+ function inferRepositoryFromPackageJson(packageJsonContent) {
786
+ if (!packageJsonContent || typeof packageJsonContent !== 'string') {
787
+ return null;
788
+ }
789
+ let packageJson;
790
+ try {
791
+ packageJson = parse(packageJsonContent);
792
+ }
793
+ catch {
794
+ return null;
795
+ }
796
+ return inferRepositoryFromPackageJsonObject(packageJson);
797
+ }
798
+ /**
799
+ * Infers repository configuration from a parsed package.json object.
800
+ *
801
+ * This is useful when you already have the parsed object.
802
+ *
803
+ * @param packageJson - Parsed package.json object
804
+ * @returns RepositoryConfig or null if repository cannot be inferred
805
+ *
806
+ * @example
807
+ * ```typescript
808
+ * const pkg = { repository: 'github:owner/repo' }
809
+ * inferRepositoryFromPackageJsonObject(pkg)
810
+ * // → { platform: 'github', baseUrl: 'https://github.com/owner/repo' }
811
+ * ```
812
+ */
813
+ function inferRepositoryFromPackageJsonObject(packageJson) {
814
+ const { repository } = packageJson;
815
+ if (!repository) {
816
+ return null;
817
+ }
818
+ // Handle string format
819
+ if (typeof repository === 'string') {
820
+ return parseRepositoryString(repository);
821
+ }
822
+ // Handle object format
823
+ if (typeof repository === 'object' && repository.url) {
824
+ return createRepositoryConfigFromUrl(repository.url);
825
+ }
826
+ return null;
827
+ }
828
+ /**
829
+ * Parses a repository string (shorthand or URL).
830
+ *
831
+ * @param repoString - Repository string from package.json
832
+ * @returns RepositoryConfig or null
833
+ *
834
+ * @internal
835
+ */
836
+ function parseRepositoryString(repoString) {
837
+ const trimmed = repoString.trim();
838
+ if (!trimmed) {
839
+ return null;
840
+ }
841
+ // Check for shorthand format: platform:owner/repo
842
+ const colonIndex = trimmed.indexOf(':');
843
+ if (colonIndex > 0) {
844
+ const potentialPlatform = trimmed.slice(0, colonIndex);
845
+ // Platform must be only letters (a-z, case insensitive)
846
+ if (isOnlyLetters(potentialPlatform)) {
847
+ const platform = potentialPlatform.toLowerCase();
848
+ const path = trimmed.slice(colonIndex + 1);
849
+ if (path) {
850
+ const baseUrl = SHORTHAND_PLATFORMS.get(platform);
851
+ if (baseUrl) {
852
+ // Construct full URL and parse it
853
+ const fullUrl = `${baseUrl}/${path}`;
854
+ return createRepositoryConfigFromUrl(fullUrl);
855
+ }
856
+ // Unknown shorthand platform - try as URL
857
+ return createRepositoryConfigFromUrl(trimmed);
858
+ }
859
+ }
860
+ }
861
+ // Check for bare shorthand: owner/repo (no protocol, no platform prefix)
862
+ // Must match pattern like "owner/repo" but not "https://..." or "git@..."
863
+ if (!trimmed.includes('://') && !trimmed.startsWith('git@')) {
864
+ if (isBareShorthand(trimmed)) {
865
+ // Bare shorthand defaults to GitHub
866
+ const fullUrl = `https://github.com/${trimmed}`;
867
+ return createRepositoryConfigFromUrl(fullUrl);
868
+ }
869
+ }
870
+ // Try as a full URL
871
+ return createRepositoryConfigFromUrl(trimmed);
872
+ }
873
+ /**
874
+ * Checks if a string contains only ASCII letters (a-z, A-Z).
875
+ *
876
+ * @param str - String to check
877
+ * @returns True if string contains only letters
878
+ *
879
+ * @internal
880
+ */
881
+ function isOnlyLetters(str) {
882
+ for (let i = 0; i < str.length; i++) {
883
+ const char = str.charCodeAt(i);
884
+ const isLowercase = char >= 97 && char <= 122; // a-z
885
+ const isUppercase = char >= 65 && char <= 90; // A-Z
886
+ if (!isLowercase && !isUppercase) {
887
+ return false;
888
+ }
889
+ }
890
+ return str.length > 0;
891
+ }
892
+ /**
893
+ * Checks if a string is a bare shorthand format (owner/repo).
894
+ * Must have exactly one forward slash with content on both sides.
895
+ *
896
+ * @param str - String to check
897
+ * @returns True if string matches owner/repo format
898
+ *
899
+ * @internal
900
+ */
901
+ function isBareShorthand(str) {
902
+ const slashIndex = str.indexOf('/');
903
+ if (slashIndex <= 0 || slashIndex === str.length - 1) {
904
+ return false;
905
+ }
906
+ // Must not have another slash
907
+ return str.indexOf('/', slashIndex + 1) === -1;
908
+ }
909
+
910
+ const RESOLVE_REPOSITORY_STEP_ID = 'resolve-repository';
911
+ /**
912
+ * Creates the resolve-repository step.
913
+ *
914
+ * This step resolves repository configuration for compare URL generation.
915
+ * It supports multiple resolution modes:
916
+ *
917
+ * - `undefined` or `'disabled'`: No-op, backward compatible default
918
+ * - `'inferred'`: Auto-detect from package.json or git remote
919
+ * - `RepositoryConfig`: Direct repository configuration provided
920
+ * - `RepositoryResolution`: Fine-grained control with mode and options
921
+ *
922
+ * State updates:
923
+ * - repositoryConfig: Resolved repository configuration (if successful)
924
+ *
925
+ * @returns A FlowStep that resolves repository configuration
926
+ *
927
+ * @example
928
+ * ```typescript
929
+ * // Auto-detect repository
930
+ * const flow = createFlow({
931
+ * repository: 'inferred'
932
+ * })
933
+ *
934
+ * // Explicit repository
935
+ * const flow = createFlow({
936
+ * repository: {
937
+ * platform: 'github',
938
+ * baseUrl: 'https://github.com/owner/repo'
939
+ * }
940
+ * })
941
+ * ```
942
+ */
943
+ function createResolveRepositoryStep() {
944
+ return createStep(RESOLVE_REPOSITORY_STEP_ID, 'Resolve Repository', async (ctx) => {
945
+ const { config, logger, tree, git, projectRoot } = ctx;
946
+ const repoConfig = config.repository;
947
+ // Disabled or undefined - no-op for backward compatibility
948
+ if (repoConfig === undefined || repoConfig === 'disabled') {
949
+ logger.debug('Repository resolution disabled');
950
+ return {
951
+ status: 'skipped',
952
+ message: 'Repository resolution disabled',
953
+ };
954
+ }
955
+ // Direct RepositoryConfig provided
956
+ if (isRepositoryConfig(repoConfig)) {
957
+ logger.debug(`Using explicit repository config: ${repoConfig.platform}`);
958
+ return {
959
+ status: 'success',
960
+ stateUpdates: {
961
+ repositoryConfig: repoConfig,
962
+ },
963
+ message: `Using explicit ${repoConfig.platform} repository`,
964
+ };
965
+ }
966
+ // Shorthand 'inferred' mode
967
+ if (repoConfig === 'inferred') {
968
+ const resolved = await inferRepository(tree, git, projectRoot, DEFAULT_INFERENCE_ORDER, logger);
969
+ if (resolved) {
970
+ return {
971
+ status: 'success',
972
+ stateUpdates: {
973
+ repositoryConfig: resolved,
974
+ },
975
+ message: `Inferred ${resolved.platform} repository from ${resolved.baseUrl}`,
976
+ };
977
+ }
978
+ // Graceful degradation - no error, just no URLs
979
+ logger.debug('Could not infer repository from package.json or git remote');
980
+ return {
981
+ status: 'skipped',
982
+ message: 'Could not infer repository configuration',
983
+ };
984
+ }
985
+ // Full RepositoryResolution object
986
+ if (isRepositoryResolution(repoConfig)) {
987
+ return handleRepositoryResolution(repoConfig, tree, git, projectRoot, logger);
988
+ }
989
+ // Unknown configuration - should not happen with TypeScript
990
+ logger.warn('Unknown repository configuration format');
991
+ return {
992
+ status: 'skipped',
993
+ message: 'Unknown repository configuration format',
994
+ };
995
+ }, {
996
+ description: 'Resolves repository configuration for compare URL generation',
997
+ });
998
+ }
999
+ /**
1000
+ * Handles a full RepositoryResolution configuration.
1001
+ *
1002
+ * @param resolution - Repository resolution configuration
1003
+ * @param tree - Virtual file system tree
1004
+ * @param git - Git client instance
1005
+ * @param projectRoot - Path to the project root
1006
+ * @param logger - Logger instance
1007
+ * @returns Flow step result with repository config or skip/error status
1008
+ * @internal
1009
+ */
1010
+ async function handleRepositoryResolution(resolution, tree, git, projectRoot, logger) {
1011
+ const { mode, repository, inferenceOrder } = resolution;
1012
+ // Disabled mode
1013
+ if (mode === 'disabled') {
1014
+ logger.debug('Repository resolution explicitly disabled');
1015
+ return {
1016
+ status: 'skipped',
1017
+ message: 'Repository resolution disabled',
1018
+ };
1019
+ }
1020
+ // Explicit mode - must have repository
1021
+ if (mode === 'explicit') {
1022
+ if (!repository) {
1023
+ return {
1024
+ status: 'failed',
1025
+ message: 'Repository config required when mode is "explicit"',
1026
+ error: createError('Repository config required when mode is "explicit"'),
1027
+ };
1028
+ }
1029
+ logger.debug(`Using explicit repository config: ${repository.platform}`);
1030
+ return {
1031
+ status: 'success',
1032
+ stateUpdates: {
1033
+ repositoryConfig: repository,
1034
+ },
1035
+ message: `Using explicit ${repository.platform} repository`,
1036
+ };
1037
+ }
1038
+ // Inferred mode
1039
+ const order = inferenceOrder ?? DEFAULT_INFERENCE_ORDER;
1040
+ const resolved = await inferRepository(tree, git, projectRoot, order, logger);
1041
+ if (resolved) {
1042
+ return {
1043
+ status: 'success',
1044
+ stateUpdates: {
1045
+ repositoryConfig: resolved,
1046
+ },
1047
+ message: `Inferred ${resolved.platform} repository`,
1048
+ };
1049
+ }
1050
+ // Graceful degradation
1051
+ logger.debug('Could not infer repository configuration');
1052
+ return {
1053
+ status: 'skipped',
1054
+ message: 'Could not infer repository configuration',
1055
+ };
1056
+ }
1057
+ /**
1058
+ * Infers repository configuration from available sources.
1059
+ *
1060
+ * @param tree - Virtual file system tree
1061
+ * @param git - Git client instance
1062
+ * @param projectRoot - Path to the project root
1063
+ * @param order - Inference source order
1064
+ * @param logger - Logger instance
1065
+ * @returns Repository config or null if none found
1066
+ * @internal
1067
+ */
1068
+ async function inferRepository(tree, git, projectRoot, order, logger) {
1069
+ for (const source of order) {
1070
+ const config = await inferFromSource(tree, git, projectRoot, source, logger);
1071
+ if (config) {
1072
+ logger.debug(`Inferred repository from ${source}: ${config.platform}`);
1073
+ return config;
1074
+ }
1075
+ }
1076
+ return null;
1077
+ }
1078
+ /**
1079
+ * Infers repository from a single source.
1080
+ *
1081
+ * @param tree - Virtual file system tree
1082
+ * @param git - Git client instance
1083
+ * @param projectRoot - Path to the project root
1084
+ * @param source - Inference source type
1085
+ * @param logger - Logger instance
1086
+ * @returns Repository config or null if not found
1087
+ * @internal
1088
+ */
1089
+ async function inferFromSource(tree, git, projectRoot, source, logger) {
1090
+ if (source === 'package-json') {
1091
+ return inferFromPackageJson(tree, projectRoot, logger);
1092
+ }
1093
+ if (source === 'git-remote') {
1094
+ return inferFromGitRemote(git, logger);
1095
+ }
1096
+ logger.warn(`Unknown inference source: ${source}`);
1097
+ return null;
1098
+ }
1099
+ /**
1100
+ * Infers repository from package.json repository field.
1101
+ *
1102
+ * @param tree - Virtual file system tree
1103
+ * @param projectRoot - Path to the project root
1104
+ * @param logger - Logger instance
1105
+ * @returns Repository config or null if not found
1106
+ * @internal
1107
+ */
1108
+ function inferFromPackageJson(tree, projectRoot, logger) {
1109
+ const packageJsonPath = `${projectRoot}/package.json`;
1110
+ if (!tree.exists(packageJsonPath)) {
1111
+ logger.debug(`package.json not found at ${packageJsonPath}`);
1112
+ return null;
1113
+ }
1114
+ const content = tree.read(packageJsonPath, 'utf-8');
1115
+ if (!content) {
1116
+ logger.debug('Could not read package.json');
1117
+ return null;
1118
+ }
1119
+ const config = inferRepositoryFromPackageJson(content);
1120
+ if (config) {
1121
+ logger.debug(`Found repository in package.json: ${config.baseUrl}`);
1122
+ }
1123
+ return config;
1124
+ }
1125
+ /**
1126
+ * Infers repository from git remote URL.
1127
+ *
1128
+ * @param git - Git client instance
1129
+ * @param logger - Logger instance
1130
+ * @returns Repository config or null if not found
1131
+ * @internal
1132
+ */
1133
+ async function inferFromGitRemote(git, logger) {
1134
+ const remoteUrl = await git.getRemoteUrl('origin');
1135
+ if (!remoteUrl) {
1136
+ logger.debug('Could not get git remote URL');
1137
+ return null;
1138
+ }
1139
+ const config = createRepositoryConfigFromUrl(remoteUrl);
1140
+ if (config) {
1141
+ logger.debug(`Inferred repository from git remote: ${config.baseUrl}`);
1142
+ }
1143
+ return config;
1144
+ }
1145
+
1146
+ /**
1147
+ * Safe copies of Set built-in via factory function.
1148
+ *
1149
+ * Since constructors cannot be safely captured via Object.assign, this module
1150
+ * provides a factory function that uses Reflect.construct internally.
1151
+ *
1152
+ * These references are captured at module initialization time to protect against
1153
+ * prototype pollution attacks. Import only what you need for tree-shaking.
1154
+ *
1155
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/set
1156
+ */
1157
+ // Capture references at module initialization time
1158
+ const _Set = globalThis.Set;
1159
+ const _Reflect$1 = globalThis.Reflect;
1160
+ /**
1161
+ * (Safe copy) Creates a new Set using the captured Set constructor.
1162
+ * Use this instead of `new Set()`.
1163
+ *
1164
+ * @param iterable - Optional iterable of values.
1165
+ * @returns A new Set instance.
1166
+ */
1167
+ const createSet = (iterable) => _Reflect$1.construct(_Set, iterable ? [iterable] : []);
1168
+
1169
+ /**
1170
+ * Safe copies of Object built-in methods.
1171
+ *
1172
+ * These references are captured at module initialization time to protect against
1173
+ * prototype pollution attacks. Import only what you need for tree-shaking.
1174
+ *
1175
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/object
1176
+ */
1177
+ // Capture references at module initialization time
1178
+ const _Object = globalThis.Object;
1179
+ /**
1180
+ * (Safe copy) Prevents modification of existing property attributes and values,
1181
+ * and prevents the addition of new properties.
1182
+ */
1183
+ const freeze = _Object.freeze;
1184
+ /**
1185
+ * (Safe copy) Returns the names of the enumerable string properties and methods of an object.
1186
+ */
1187
+ const keys = _Object.keys;
1188
+ /**
1189
+ * (Safe copy) Returns an array of key/values of the enumerable own properties of an object.
1190
+ */
1191
+ const entries = _Object.entries;
1192
+ /**
1193
+ * (Safe copy) Returns an array of values of the enumerable own properties of an object.
1194
+ */
1195
+ const values = _Object.values;
1196
+ /**
1197
+ * (Safe copy) Adds one or more properties to an object, and/or modifies attributes of existing properties.
1198
+ */
1199
+ const defineProperties = _Object.defineProperties;
1200
+
1201
+ /**
1202
+ * Safe copies of Array built-in static methods.
1203
+ *
1204
+ * These references are captured at module initialization time to protect against
1205
+ * prototype pollution attacks. Import only what you need for tree-shaking.
1206
+ *
1207
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/array
1208
+ */
1209
+ // Capture references at module initialization time
1210
+ const _Array = globalThis.Array;
1211
+ /**
1212
+ * (Safe copy) Determines whether the passed value is an Array.
1213
+ */
1214
+ const isArray = _Array.isArray;
1215
+
1216
+ /**
1217
+ * Safe copies of Console built-in methods.
1218
+ *
1219
+ * These references are captured at module initialization time to protect against
1220
+ * prototype pollution attacks. Import only what you need for tree-shaking.
1221
+ *
1222
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/console
1223
+ */
1224
+ // Capture references at module initialization time
1225
+ const _console = globalThis.console;
1226
+ /**
1227
+ * (Safe copy) Outputs a message to the console.
1228
+ */
1229
+ const log = _console.log.bind(_console);
1230
+ /**
1231
+ * (Safe copy) Outputs a warning message to the console.
1232
+ */
1233
+ const warn = _console.warn.bind(_console);
1234
+ /**
1235
+ * (Safe copy) Outputs an error message to the console.
1236
+ */
1237
+ const error = _console.error.bind(_console);
1238
+ /**
1239
+ * (Safe copy) Outputs an informational message to the console.
1240
+ */
1241
+ const info = _console.info.bind(_console);
1242
+ /**
1243
+ * (Safe copy) Outputs a debug message to the console.
1244
+ */
1245
+ const debug = _console.debug.bind(_console);
1246
+ /**
1247
+ * (Safe copy) Outputs a stack trace to the console.
1248
+ */
1249
+ _console.trace.bind(_console);
1250
+ /**
1251
+ * (Safe copy) Displays an interactive listing of the properties of a specified object.
1252
+ */
1253
+ _console.dir.bind(_console);
1254
+ /**
1255
+ * (Safe copy) Displays tabular data as a table.
1256
+ */
1257
+ _console.table.bind(_console);
1258
+ /**
1259
+ * (Safe copy) Writes an error message to the console if the assertion is false.
1260
+ */
1261
+ _console.assert.bind(_console);
1262
+ /**
1263
+ * (Safe copy) Clears the console.
1264
+ */
1265
+ _console.clear.bind(_console);
1266
+ /**
1267
+ * (Safe copy) Logs the number of times that this particular call to count() has been called.
1268
+ */
1269
+ _console.count.bind(_console);
1270
+ /**
1271
+ * (Safe copy) Resets the counter used with console.count().
1272
+ */
1273
+ _console.countReset.bind(_console);
1274
+ /**
1275
+ * (Safe copy) Creates a new inline group in the console.
1276
+ */
1277
+ _console.group.bind(_console);
1278
+ /**
1279
+ * (Safe copy) Creates a new inline group in the console that is initially collapsed.
1280
+ */
1281
+ _console.groupCollapsed.bind(_console);
1282
+ /**
1283
+ * (Safe copy) Exits the current inline group.
1284
+ */
1285
+ _console.groupEnd.bind(_console);
1286
+ /**
1287
+ * (Safe copy) Starts a timer with a name specified as an input parameter.
1288
+ */
1289
+ _console.time.bind(_console);
1290
+ /**
1291
+ * (Safe copy) Stops a timer that was previously started.
1292
+ */
1293
+ _console.timeEnd.bind(_console);
1294
+ /**
1295
+ * (Safe copy) Logs the current value of a timer that was previously started.
1296
+ */
1297
+ _console.timeLog.bind(_console);
1298
+
1299
+ const registeredClasses = [];
1300
+
1301
+ /**
1302
+ * Returns the data type of the target.
1303
+ * Uses native `typeof` operator, however, makes distinction between `null`, `array`, and `object`.
1304
+ * Also, when classes are registered via `registerClass`, it checks if objects are instance of any known registered class.
1305
+ *
1306
+ * @param target - The target to get the data type of.
1307
+ * @returns The data type of the target.
1308
+ */
1309
+ const getType = (target) => {
1310
+ if (target === null)
1311
+ return 'null';
1312
+ const nativeDataType = typeof target;
1313
+ if (nativeDataType === 'object') {
1314
+ if (isArray(target))
1315
+ return 'array';
1316
+ for (const registeredClass of registeredClasses) {
1317
+ if (target instanceof registeredClass)
1318
+ return registeredClass.name;
1319
+ }
1320
+ }
1321
+ return nativeDataType;
1322
+ };
1323
+
1324
+ /**
1325
+ * Safe copies of Date built-in via factory function and static methods.
1326
+ *
1327
+ * Since constructors cannot be safely captured via Object.assign, this module
1328
+ * provides a factory function that uses Reflect.construct internally.
1329
+ *
1330
+ * These references are captured at module initialization time to protect against
1331
+ * prototype pollution attacks. Import only what you need for tree-shaking.
1332
+ *
1333
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/date
1334
+ */
1335
+ // Capture references at module initialization time
1336
+ const _Date = globalThis.Date;
1337
+ const _Reflect = globalThis.Reflect;
1338
+ function createDate(...args) {
1339
+ return _Reflect.construct(_Date, args);
1340
+ }
1341
+
1342
+ /* eslint-disable @typescript-eslint/no-explicit-any */
1343
+ /**
1344
+ * Creates a wrapper function that only executes the wrapped function if the condition function returns true.
1345
+ *
1346
+ * @param func - The function to be conditionally executed.
1347
+ * @param conditionFunc - A function that returns a boolean, determining if `func` should be executed.
1348
+ * @returns A wrapped version of `func` that executes conditionally.
1349
+ */
1350
+ function createConditionalExecutionFunction(func, conditionFunc) {
1351
+ return function (...args) {
1352
+ if (conditionFunc()) {
1353
+ return func(...args);
1354
+ }
1355
+ };
1356
+ }
1357
+
1358
+ /* eslint-disable @typescript-eslint/no-explicit-any */
1359
+ /**
1360
+ * Creates a wrapper function that silently ignores any errors thrown by the wrapped void function.
1361
+ * This function is specifically for wrapping functions that do not return a value (void functions).
1362
+ * Exceptions are swallowed without any logging or handling.
1363
+ *
1364
+ * @param func - The void function to be wrapped.
1365
+ * @returns A wrapped version of the input function that ignores errors.
1366
+ */
1367
+ function createErrorIgnoringFunction(func) {
1368
+ return function (...args) {
1369
+ try {
1370
+ func(...args);
1371
+ }
1372
+ catch {
1373
+ // Deliberately swallowing/ignoring the exception
1374
+ }
1375
+ };
1376
+ }
1377
+
1378
+ /* eslint-disable @typescript-eslint/no-unused-vars */
1379
+ /**
1380
+ * A no-operation function (noop) that does nothing regardless of the arguments passed.
1381
+ * It is designed to be as permissive as possible in its typing without using the `Function` keyword.
1382
+ *
1383
+ * @param args - Any arguments passed to the function (ignored)
1384
+ */
1385
+ const noop = (...args) => {
1386
+ // Intentionally does nothing
1387
+ };
1388
+
1389
+ const logLevels = ['none', 'error', 'warn', 'log', 'info', 'debug'];
1390
+ const priority = {
1391
+ error: 4,
1392
+ warn: 3,
1393
+ log: 2,
1394
+ info: 1,
1395
+ debug: 0,
1396
+ };
1397
+ /**
1398
+ * Validates whether a given string is a valid log level.
1399
+ *
1400
+ * @param level - The log level to validate
1401
+ * @returns True if the level is valid, false otherwise
1402
+ */
1403
+ function isValidLogLevel(level) {
1404
+ return logLevels.includes(level);
1405
+ }
1406
+ /**
1407
+ * Creates a log level configuration manager for controlling logging behavior.
1408
+ * Provides methods to get, set, and evaluate log levels based on priority.
1409
+ *
1410
+ * @param level - The initial log level (defaults to 'error')
1411
+ * @returns A configuration object with log level management methods
1412
+ * @throws {Error} When the provided level is not a valid log level
1413
+ */
1414
+ function createLogLevelConfig(level = 'error') {
1415
+ if (!isValidLogLevel(level)) {
1416
+ throw createError('Cannot create log level configuration with a valid default log level');
1417
+ }
1418
+ const state = { level };
1419
+ const getLogLevel = () => state.level;
1420
+ const setLogLevel = (level) => {
1421
+ if (!isValidLogLevel(level)) {
1422
+ throw createError(`Cannot set value '${level}' level. Expected levels are ${logLevels}.`);
1423
+ }
1424
+ state.level = level;
1425
+ };
1426
+ const shouldLog = (level) => {
1427
+ if (state.level === 'none' || level === 'none' || !isValidLogLevel(level)) {
1428
+ return false;
1429
+ }
1430
+ return priority[level] >= priority[state.level];
1431
+ };
1432
+ return freeze({
1433
+ getLogLevel,
1434
+ setLogLevel,
1435
+ shouldLog,
1436
+ });
1437
+ }
1438
+
1439
+ /**
1440
+ * Creates a logger instance with configurable log level filtering.
1441
+ * Each log function is wrapped to respect the current log level setting.
1442
+ *
1443
+ * @param error - Function to handle error-level logs (required)
1444
+ * @param warn - Function to handle warning-level logs (optional, defaults to noop)
1445
+ * @param log - Function to handle standard logs (optional, defaults to noop)
1446
+ * @param info - Function to handle info-level logs (optional, defaults to noop)
1447
+ * @param debug - Function to handle debug-level logs (optional, defaults to noop)
1448
+ * @returns A frozen logger object with log methods and level control
1449
+ * @throws {ErrorLevelFn} When any provided log function is invalid
1450
+ */
1451
+ function createLogger(error, warn = noop, log = noop, info = noop, debug = noop) {
1452
+ if (notValidLogFn(error)) {
1453
+ throw createError(notFnMsg('error'));
1454
+ }
1455
+ if (notValidLogFn(warn)) {
1456
+ throw createError(notFnMsg('warn'));
1457
+ }
1458
+ if (notValidLogFn(log)) {
1459
+ throw createError(notFnMsg('log'));
1460
+ }
1461
+ if (notValidLogFn(info)) {
1462
+ throw createError(notFnMsg('info'));
1463
+ }
1464
+ if (notValidLogFn(debug)) {
1465
+ throw createError(notFnMsg('debug'));
1466
+ }
1467
+ const { setLogLevel, getLogLevel, shouldLog } = createLogLevelConfig();
1468
+ const wrapLogFn = (fn, level) => {
1469
+ if (fn === noop)
1470
+ return fn;
1471
+ const condition = () => shouldLog(level);
1472
+ return createConditionalExecutionFunction(createErrorIgnoringFunction(fn), condition);
1473
+ };
1474
+ return freeze({
1475
+ error: wrapLogFn(error, 'error'),
1476
+ warn: wrapLogFn(warn, 'warn'),
1477
+ log: wrapLogFn(log, 'log'),
1478
+ info: wrapLogFn(info, 'info'),
1479
+ debug: wrapLogFn(debug, 'debug'),
1480
+ setLogLevel,
1481
+ getLogLevel,
1482
+ });
1483
+ }
1484
+ /**
1485
+ * Validates whether a given value is a valid log function.
1486
+ *
1487
+ * @param fn - The value to validate
1488
+ * @returns True if the value is not a function (invalid), false if it is valid
1489
+ */
1490
+ function notValidLogFn(fn) {
1491
+ return getType(fn) !== 'function' && fn !== noop;
1492
+ }
1493
+ /**
1494
+ * Generates an error message for invalid log function parameters.
1495
+ *
1496
+ * @param label - The name of the log function that failed validation
1497
+ * @returns A formatted error message string
1498
+ */
1499
+ function notFnMsg(label) {
1500
+ return `Cannot create a logger when ${label} is not a function`;
1501
+ }
1502
+
1503
+ createLogger(error, warn, log, info, debug);
1504
+
1505
+ /**
1506
+ * Global log level registry.
1507
+ * Tracks all created scoped loggers to allow global log level changes.
1508
+ */
1509
+ const loggerRegistry = createSet();
1510
+ /** Redacted placeholder for sensitive values */
1511
+ const REDACTED = '[REDACTED]';
1512
+ /**
1513
+ * Patterns that indicate a sensitive key name.
1514
+ * Keys containing these patterns will have their values sanitized.
1515
+ */
1516
+ const SENSITIVE_KEY_PATTERNS = [
1517
+ /token/i,
1518
+ /key/i,
1519
+ /password/i,
1520
+ /secret/i,
1521
+ /credential/i,
1522
+ /auth/i,
1523
+ /bearer/i,
1524
+ /api[_-]?key/i,
1525
+ /private/i,
1526
+ /passphrase/i,
1527
+ ];
1528
+ /**
1529
+ * Checks if a key name indicates sensitive data.
1530
+ *
1531
+ * @param key - Key name to check
1532
+ * @returns True if the key indicates sensitive data
1533
+ */
1534
+ function isSensitiveKey(key) {
1535
+ return SENSITIVE_KEY_PATTERNS.some((pattern) => pattern.test(key));
1536
+ }
1537
+ /**
1538
+ * Sanitizes an object by replacing sensitive values with REDACTED.
1539
+ * This function recursively processes nested objects and arrays.
1540
+ *
1541
+ * @param obj - Object to sanitize
1542
+ * @returns New object with sensitive values redacted
1543
+ */
1544
+ function sanitize(obj) {
1545
+ if (obj === null || obj === undefined) {
1546
+ return obj;
1547
+ }
1548
+ if (isArray(obj)) {
1549
+ return obj.map((item) => sanitize(item));
1550
+ }
1551
+ if (typeof obj === 'object') {
1552
+ const result = {};
1553
+ for (const [key, value] of entries(obj)) {
1554
+ if (isSensitiveKey(key)) {
1555
+ result[key] = REDACTED;
1556
+ }
1557
+ else if (typeof value === 'object' && value !== null) {
1558
+ result[key] = sanitize(value);
1559
+ }
1560
+ else {
1561
+ result[key] = value;
1562
+ }
1563
+ }
1564
+ return result;
1565
+ }
1566
+ return obj;
1567
+ }
1568
+ /**
1569
+ * Formats a log message with optional metadata.
1570
+ *
1571
+ * @param namespace - Logger namespace prefix
1572
+ * @param message - Log message
1573
+ * @param meta - Optional metadata object
1574
+ * @returns Formatted log string
1575
+ */
1576
+ function formatMessage(namespace, message, meta) {
1577
+ const prefix = `[${namespace}]`;
1578
+ if (meta && keys(meta).length > 0) {
1579
+ const sanitizedMeta = sanitize(meta);
1580
+ return `${prefix} ${message} ${stringify(sanitizedMeta)}`;
1581
+ }
1582
+ return `${prefix} ${message}`;
1583
+ }
1584
+ /**
1585
+ * Creates a scoped logger with namespace prefix and optional secret sanitization.
1586
+ * All log messages will be prefixed with [namespace] and sensitive metadata
1587
+ * values will be automatically redacted.
1588
+ *
1589
+ * @param namespace - Logger namespace (e.g., 'project-scope', 'analyze')
1590
+ * @param options - Logger configuration options
1591
+ * @returns A configured scoped logger instance
1592
+ *
1593
+ * @example
1594
+ * ```typescript
1595
+ * const logger = createScopedLogger('project-scope')
1596
+ * logger.setLogLevel('debug')
1597
+ *
1598
+ * // Basic logging
1599
+ * logger.info('Starting analysis', { path: './project' })
1600
+ *
1601
+ * // Sensitive data is automatically redacted
1602
+ * logger.debug('Config loaded', { apiKey: 'secret123' })
1603
+ * // Output: [project-scope] Config loaded {"apiKey":"[REDACTED]"}
1604
+ * ```
1605
+ */
1606
+ function createScopedLogger(namespace, options = {}) {
1607
+ const { level = 'error', sanitizeSecrets = true } = options;
1608
+ // Create wrapper functions that add namespace prefix and sanitization
1609
+ const createLogFn = (baseFn) => (message, meta) => {
1610
+ const processedMeta = sanitizeSecrets && meta ? sanitize(meta) : meta;
1611
+ baseFn(formatMessage(namespace, message, processedMeta));
1612
+ };
1613
+ // Create base logger with wrapped functions
1614
+ const baseLogger = createLogger(createLogFn(error), createLogFn(warn), createLogFn(log), createLogFn(info), createLogFn(debug));
1615
+ // Set initial log level (use global override if set)
1616
+ baseLogger.setLogLevel(level);
1617
+ const scopedLogger = freeze({
1618
+ error: (message, meta) => baseLogger.error(message, meta),
1619
+ warn: (message, meta) => baseLogger.warn(message, meta),
1620
+ log: (message, meta) => baseLogger.log(message, meta),
1621
+ info: (message, meta) => baseLogger.info(message, meta),
1622
+ debug: (message, meta) => baseLogger.debug(message, meta),
1623
+ setLogLevel: baseLogger.setLogLevel,
1624
+ getLogLevel: baseLogger.getLogLevel,
1625
+ });
1626
+ // Register logger for global level management
1627
+ loggerRegistry.add(scopedLogger);
1628
+ return scopedLogger;
1629
+ }
1630
+ /**
1631
+ * Default logger instance for the project-scope library.
1632
+ * Use this for general logging within the library.
1633
+ *
1634
+ * @example
1635
+ * ```typescript
1636
+ * import { logger } from '@hyperfrontend/project-scope/core'
1637
+ *
1638
+ * logger.setLogLevel('debug')
1639
+ * logger.debug('Analyzing project', { path: './src' })
1640
+ * ```
1641
+ */
1642
+ createScopedLogger('project-scope');
1643
+
1644
+ createScopedLogger('project-scope:fs');
1645
+ /**
1646
+ * Create a file system error with code and context.
1647
+ *
1648
+ * @param message - The error message describing what went wrong
1649
+ * @param code - The category code for this type of filesystem failure
1650
+ * @param context - Additional context including path, operation, and cause
1651
+ * @returns A configured Error object with code and context properties
1652
+ */
1653
+ function createFileSystemError(message, code, context) {
1654
+ const error = createError(message);
1655
+ defineProperties(error, {
1656
+ code: { value: code, enumerable: true },
1657
+ context: { value: context, enumerable: true },
1658
+ });
1659
+ return error;
1660
+ }
1661
+ /**
1662
+ * Read file if exists, return null otherwise.
1663
+ *
1664
+ * @param filePath - Path to file
1665
+ * @param encoding - File encoding (default: utf-8)
1666
+ * @returns File contents or null if file doesn't exist
1667
+ */
1668
+ function readFileIfExists(filePath, encoding = 'utf-8') {
1669
+ if (!existsSync(filePath)) {
1670
+ return null;
1671
+ }
1672
+ try {
1673
+ return readFileSync(filePath, { encoding });
1674
+ }
1675
+ catch {
1676
+ return null;
1677
+ }
1678
+ }
1679
+ /**
1680
+ * Read and parse JSON file if exists, return null otherwise.
1681
+ *
1682
+ * @param filePath - Path to JSON file
1683
+ * @returns Parsed JSON object or null if file doesn't exist or is invalid
1684
+ */
1685
+ function readJsonFileIfExists(filePath) {
1686
+ if (!existsSync(filePath)) {
1687
+ return null;
1688
+ }
1689
+ try {
1690
+ const content = readFileSync(filePath, { encoding: 'utf-8' });
1691
+ return parse(content);
1692
+ }
1693
+ catch {
1694
+ return null;
1695
+ }
1696
+ }
1697
+
1698
+ createScopedLogger('project-scope:fs:write');
1699
+
1700
+ /**
1701
+ * Get file stats with error handling.
1702
+ *
1703
+ * @param filePath - Path to file
1704
+ * @param followSymlinks - Whether to follow symlinks (default: true)
1705
+ * @returns File stats or null if path doesn't exist
1706
+ */
1707
+ function getFileStat(filePath, followSymlinks = true) {
1708
+ if (!existsSync(filePath)) {
1709
+ return null;
1710
+ }
1711
+ try {
1712
+ const stat = followSymlinks ? statSync(filePath) : lstatSync(filePath);
1713
+ return {
1714
+ isFile: stat.isFile(),
1715
+ isDirectory: stat.isDirectory(),
1716
+ isSymlink: stat.isSymbolicLink(),
1717
+ size: stat.size,
1718
+ created: stat.birthtime,
1719
+ modified: stat.mtime,
1720
+ accessed: stat.atime,
1721
+ mode: stat.mode,
1722
+ };
1723
+ }
1724
+ catch {
1725
+ return null;
1726
+ }
1727
+ }
1728
+ /**
1729
+ * Check if path is a directory.
1730
+ *
1731
+ * @param dirPath - Path to check
1732
+ * @returns True if path is a directory
1733
+ */
1734
+ function isDirectory(dirPath) {
1735
+ const stats = getFileStat(dirPath);
1736
+ return stats?.isDirectory ?? false;
1737
+ }
1738
+ /**
1739
+ * Check if path exists.
1740
+ *
1741
+ * @param filePath - Path to check
1742
+ * @returns True if path exists
1743
+ */
1744
+ function exists(filePath) {
1745
+ return existsSync(filePath);
1746
+ }
1747
+
1748
+ const fsDirLogger = createScopedLogger('project-scope:fs:dir');
1749
+ /**
1750
+ * List immediate contents of a directory.
1751
+ *
1752
+ * @param dirPath - Absolute or relative path to the directory
1753
+ * @returns Array of entries with metadata for each file/directory
1754
+ * @throws {Error} If directory doesn't exist or isn't a directory
1755
+ *
1756
+ * @example
1757
+ * ```typescript
1758
+ * import { readDirectory } from '@hyperfrontend/project-scope'
1759
+ *
1760
+ * const entries = readDirectory('./src')
1761
+ * for (const entry of entries) {
1762
+ * console.log(entry.name, entry.isFile ? 'file' : 'directory')
1763
+ * }
1764
+ * ```
1765
+ */
1766
+ function readDirectory(dirPath) {
1767
+ fsDirLogger.debug('Reading directory', { path: dirPath });
1768
+ if (!existsSync(dirPath)) {
1769
+ fsDirLogger.debug('Directory not found', { path: dirPath });
1770
+ throw createFileSystemError(`Directory not found: ${dirPath}`, 'FS_NOT_FOUND', { path: dirPath, operation: 'readdir' });
1771
+ }
1772
+ if (!isDirectory(dirPath)) {
1773
+ fsDirLogger.debug('Path is not a directory', { path: dirPath });
1774
+ throw createFileSystemError(`Not a directory: ${dirPath}`, 'FS_NOT_A_DIRECTORY', { path: dirPath, operation: 'readdir' });
1775
+ }
1776
+ try {
1777
+ const entries = readdirSync(dirPath, { withFileTypes: true });
1778
+ fsDirLogger.debug('Directory read complete', { path: dirPath, entryCount: entries.length });
1779
+ return entries.map((entry) => ({
1780
+ name: entry.name,
1781
+ path: join(dirPath, entry.name),
1782
+ isFile: entry.isFile(),
1783
+ isDirectory: entry.isDirectory(),
1784
+ isSymlink: entry.isSymbolicLink(),
1785
+ }));
1786
+ }
1787
+ catch (error) {
1788
+ fsDirLogger.warn('Failed to read directory', { path: dirPath, error: error instanceof Error ? error.message : String(error) });
1789
+ throw createFileSystemError(`Failed to read directory: ${dirPath}`, 'FS_READ_ERROR', {
1790
+ path: dirPath,
1791
+ operation: 'readdir',
1792
+ cause: error,
1793
+ });
1794
+ }
1795
+ }
1796
+
1797
+ createScopedLogger('project-scope:fs:traversal');
1798
+
1799
+ const packageLogger = createScopedLogger('project-scope:project:package');
1800
+ /**
1801
+ * Verifies that a value is an object with only string values,
1802
+ * used for validating dependency maps and script definitions.
1803
+ *
1804
+ * @param value - Value to check
1805
+ * @returns True if value is a record of strings
1806
+ */
1807
+ function isStringRecord(value) {
1808
+ if (typeof value !== 'object' || value === null)
1809
+ return false;
1810
+ return values(value).every((v) => typeof v === 'string');
1811
+ }
1812
+ /**
1813
+ * Extracts and normalizes the workspaces field from package.json,
1814
+ * supporting both array format and object with packages array.
1815
+ *
1816
+ * @param value - Raw workspaces value from package.json
1817
+ * @returns Normalized workspace patterns or undefined if invalid
1818
+ */
1819
+ function parseWorkspaces(value) {
1820
+ if (isArray(value) && value.every((v) => typeof v === 'string')) {
1821
+ return value;
1822
+ }
1823
+ if (typeof value === 'object' && value !== null) {
1824
+ const obj = value;
1825
+ if (isArray(obj['packages'])) {
1826
+ return { packages: obj['packages'] };
1827
+ }
1828
+ }
1829
+ return undefined;
1830
+ }
1831
+ /**
1832
+ * Validate and normalize package.json data.
1833
+ *
1834
+ * @param data - Raw parsed data
1835
+ * @returns Validated package.json
1836
+ */
1837
+ function validatePackageJson(data) {
1838
+ if (typeof data !== 'object' || data === null) {
1839
+ throw createError('package.json must be an object');
1840
+ }
1841
+ const pkg = data;
1842
+ return {
1843
+ name: typeof pkg['name'] === 'string' ? pkg['name'] : undefined,
1844
+ version: typeof pkg['version'] === 'string' ? pkg['version'] : undefined,
1845
+ description: typeof pkg['description'] === 'string' ? pkg['description'] : undefined,
1846
+ main: typeof pkg['main'] === 'string' ? pkg['main'] : undefined,
1847
+ module: typeof pkg['module'] === 'string' ? pkg['module'] : undefined,
1848
+ browser: typeof pkg['browser'] === 'string' ? pkg['browser'] : undefined,
1849
+ types: typeof pkg['types'] === 'string' ? pkg['types'] : undefined,
1850
+ bin: typeof pkg['bin'] === 'string' || isStringRecord(pkg['bin']) ? pkg['bin'] : undefined,
1851
+ scripts: isStringRecord(pkg['scripts']) ? pkg['scripts'] : undefined,
1852
+ dependencies: isStringRecord(pkg['dependencies']) ? pkg['dependencies'] : undefined,
1853
+ devDependencies: isStringRecord(pkg['devDependencies']) ? pkg['devDependencies'] : undefined,
1854
+ peerDependencies: isStringRecord(pkg['peerDependencies']) ? pkg['peerDependencies'] : undefined,
1855
+ optionalDependencies: isStringRecord(pkg['optionalDependencies']) ? pkg['optionalDependencies'] : undefined,
1856
+ workspaces: parseWorkspaces(pkg['workspaces']),
1857
+ exports: typeof pkg['exports'] === 'object' ? pkg['exports'] : undefined,
1858
+ engines: isStringRecord(pkg['engines']) ? pkg['engines'] : undefined,
1859
+ ...pkg,
1860
+ };
1861
+ }
1862
+ /**
1863
+ * Attempts to read and parse package.json if it exists,
1864
+ * returning null on missing file or parse failure.
1865
+ *
1866
+ * @param projectPath - Project directory path or path to package.json
1867
+ * @returns Parsed package.json or null if not found
1868
+ */
1869
+ function readPackageJsonIfExists(projectPath) {
1870
+ const packageJsonPath = projectPath.endsWith('package.json') ? projectPath : join(projectPath, 'package.json');
1871
+ const content = readFileIfExists(packageJsonPath);
1872
+ if (!content) {
1873
+ packageLogger.debug('Package.json not found', { path: packageJsonPath });
1874
+ return null;
1875
+ }
1876
+ try {
1877
+ const validated = validatePackageJson(parse(content));
1878
+ packageLogger.debug('Package.json loaded', { path: packageJsonPath, name: validated.name });
1879
+ return validated;
1880
+ }
1881
+ catch {
1882
+ packageLogger.debug('Failed to parse package.json, returning null', { path: packageJsonPath });
1883
+ return null;
1884
+ }
1885
+ }
1886
+
1887
+ createScopedLogger('project-scope:root');
1888
+
1889
+ const nxLogger = createScopedLogger('project-scope:nx');
1890
+ /**
1891
+ * Files indicating NX workspace root.
1892
+ */
1893
+ const NX_CONFIG_FILES = ['nx.json', 'workspace.json'];
1894
+ /**
1895
+ * NX-specific project file.
1896
+ */
1897
+ const NX_PROJECT_FILE = 'project.json';
1898
+ /**
1899
+ * Check if directory is an NX workspace root.
1900
+ *
1901
+ * @param path - Directory path to check
1902
+ * @returns True if the directory contains nx.json or workspace.json
1903
+ *
1904
+ * @example
1905
+ * ```typescript
1906
+ * import { isNxWorkspace } from '@hyperfrontend/project-scope'
1907
+ *
1908
+ * if (isNxWorkspace('./my-project')) {
1909
+ * console.log('This is an NX monorepo')
1910
+ * }
1911
+ * ```
1912
+ */
1913
+ function isNxWorkspace(path) {
1914
+ for (const configFile of NX_CONFIG_FILES) {
1915
+ if (exists(join(path, configFile))) {
1916
+ nxLogger.debug('NX workspace detected', { path, configFile });
1917
+ return true;
1918
+ }
1919
+ }
1920
+ nxLogger.debug('Not an NX workspace', { path });
1921
+ return false;
1922
+ }
1923
+ /**
1924
+ * Check if directory is an NX project.
1925
+ *
1926
+ * @param path - Directory path to check
1927
+ * @returns True if the directory contains project.json
1928
+ */
1929
+ function isNxProject(path) {
1930
+ const isProject = exists(join(path, NX_PROJECT_FILE));
1931
+ nxLogger.debug('NX project check', { path, isProject });
1932
+ return isProject;
1933
+ }
1934
+ /**
1935
+ * Detect NX version from package.json dependencies.
1936
+ *
1937
+ * @param workspacePath - Workspace root path
1938
+ * @returns NX version string (without semver range) or null
1939
+ */
1940
+ function detectNxVersion(workspacePath) {
1941
+ const packageJson = readPackageJsonIfExists(workspacePath);
1942
+ if (packageJson) {
1943
+ const nxVersion = packageJson.devDependencies?.['nx'] ?? packageJson.dependencies?.['nx'];
1944
+ if (nxVersion) {
1945
+ // Strip semver range characters (^, ~, >=, etc.)
1946
+ return nxVersion.replace(/^[\^~>=<]+/, '');
1947
+ }
1948
+ }
1949
+ return null;
1950
+ }
1951
+ /**
1952
+ * Check if workspace is integrated (not standalone).
1953
+ * Integrated repos typically have workspaceLayout, namedInputs, or targetDefaults.
1954
+ *
1955
+ * @param nxJson - Parsed nx.json configuration
1956
+ * @returns True if the workspace is integrated
1957
+ */
1958
+ function isIntegratedRepo(nxJson) {
1959
+ return nxJson.workspaceLayout !== undefined || nxJson.namedInputs !== undefined || nxJson.targetDefaults !== undefined;
1960
+ }
1961
+ /**
1962
+ * Get comprehensive NX workspace information.
1963
+ *
1964
+ * @param workspacePath - Workspace root path
1965
+ * @returns Workspace info or null if not an NX workspace
1966
+ */
1967
+ function getNxWorkspaceInfo(workspacePath) {
1968
+ nxLogger.debug('Getting NX workspace info', { workspacePath });
1969
+ if (!isNxWorkspace(workspacePath)) {
1970
+ return null;
1971
+ }
1972
+ const nxJson = readJsonFileIfExists(join(workspacePath, 'nx.json'));
1973
+ if (!nxJson) {
1974
+ // Check for workspace.json as fallback (older NX)
1975
+ const workspaceJson = readJsonFileIfExists(join(workspacePath, 'workspace.json'));
1976
+ if (!workspaceJson) {
1977
+ nxLogger.debug('No nx.json or workspace.json found', { workspacePath });
1978
+ return null;
1979
+ }
1980
+ nxLogger.debug('Using legacy workspace.json', { workspacePath });
1981
+ // Create minimal nx.json from workspace.json
1982
+ return {
1983
+ root: workspacePath,
1984
+ version: detectNxVersion(workspacePath),
1985
+ nxJson: {},
1986
+ isIntegrated: true,
1987
+ workspaceLayout: {
1988
+ appsDir: 'apps',
1989
+ libsDir: 'libs',
1990
+ },
1991
+ };
1992
+ }
1993
+ const info = {
1994
+ root: workspacePath,
1995
+ version: detectNxVersion(workspacePath),
1996
+ nxJson,
1997
+ isIntegrated: isIntegratedRepo(nxJson),
1998
+ defaultProject: nxJson.defaultProject,
1999
+ workspaceLayout: {
2000
+ appsDir: nxJson.workspaceLayout?.appsDir ?? 'apps',
2001
+ libsDir: nxJson.workspaceLayout?.libsDir ?? 'libs',
2002
+ },
2003
+ };
2004
+ nxLogger.debug('NX workspace info retrieved', {
2005
+ workspacePath,
2006
+ version: info.version,
2007
+ isIntegrated: info.isIntegrated,
2008
+ defaultProject: info.defaultProject,
2009
+ });
2010
+ return info;
2011
+ }
2012
+
2013
+ createScopedLogger('project-scope:nx:devkit');
2014
+
2015
+ const nxConfigLogger = createScopedLogger('project-scope:nx:config');
2016
+ /**
2017
+ * Read project.json for an NX project.
2018
+ *
2019
+ * @param projectPath - Project directory path
2020
+ * @returns Parsed project.json or null if not found
2021
+ */
2022
+ function readProjectJson(projectPath) {
2023
+ const projectJsonPath = join(projectPath, NX_PROJECT_FILE);
2024
+ nxConfigLogger.debug('Reading project.json', { path: projectJsonPath });
2025
+ const result = readJsonFileIfExists(projectJsonPath);
2026
+ if (result) {
2027
+ nxConfigLogger.debug('Project.json loaded', { path: projectJsonPath, name: result.name });
2028
+ }
2029
+ else {
2030
+ nxConfigLogger.debug('Project.json not found', { path: projectJsonPath });
2031
+ }
2032
+ return result;
2033
+ }
2034
+ /**
2035
+ * Get project configuration from project.json or package.json nx field.
2036
+ *
2037
+ * @param projectPath - Project directory path
2038
+ * @param workspacePath - Workspace root path (for relative path calculation)
2039
+ * @returns Project configuration or null if not found
2040
+ */
2041
+ function getProjectConfig(projectPath, workspacePath) {
2042
+ nxConfigLogger.debug('Getting project config', { projectPath, workspacePath });
2043
+ // Try project.json first
2044
+ const projectJson = readProjectJson(projectPath);
2045
+ if (projectJson) {
2046
+ nxConfigLogger.debug('Using project.json config', { projectPath, name: projectJson.name });
2047
+ return {
2048
+ ...projectJson,
2049
+ root: projectJson.root ?? relative(workspacePath, projectPath),
2050
+ };
2051
+ }
2052
+ // Try to infer from package.json nx field
2053
+ const packageJson = readPackageJsonIfExists(projectPath);
2054
+ if (packageJson && typeof packageJson['nx'] === 'object') {
2055
+ nxConfigLogger.debug('Using package.json nx field', { projectPath, name: packageJson.name });
2056
+ const nxConfig = packageJson['nx'];
2057
+ return {
2058
+ name: packageJson.name,
2059
+ root: relative(workspacePath, projectPath),
2060
+ ...nxConfig,
2061
+ };
2062
+ }
2063
+ nxConfigLogger.debug('No project config found', { projectPath });
2064
+ return null;
2065
+ }
2066
+ /**
2067
+ * Recursively scan directory for project.json files.
2068
+ *
2069
+ * @param dirPath - Directory to scan
2070
+ * @param workspacePath - Workspace root path
2071
+ * @param projects - Map to add discovered projects to
2072
+ * @param maxDepth - Maximum recursion depth
2073
+ * @param currentDepth - Current recursion depth
2074
+ */
2075
+ function scanForProjects(dirPath, workspacePath, projects, maxDepth, currentDepth = 0) {
2076
+ if (currentDepth > maxDepth)
2077
+ return;
2078
+ try {
2079
+ const entries = readDirectory(dirPath);
2080
+ for (const entry of entries) {
2081
+ // Skip node_modules and hidden directories
2082
+ if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'dist') {
2083
+ continue;
2084
+ }
2085
+ const fullPath = join(dirPath, entry.name);
2086
+ if (entry.isDirectory) {
2087
+ // Check if this directory is an NX project
2088
+ if (isNxProject(fullPath)) {
2089
+ const config = getProjectConfig(fullPath, workspacePath);
2090
+ if (config) {
2091
+ const name = config.name || relative(workspacePath, fullPath).replace(/[\\/]/g, '-');
2092
+ projects.set(name, {
2093
+ ...config,
2094
+ name,
2095
+ root: relative(workspacePath, fullPath),
2096
+ });
2097
+ }
2098
+ }
2099
+ // Recursively scan subdirectories
2100
+ scanForProjects(fullPath, workspacePath, projects, maxDepth, currentDepth + 1);
2101
+ }
2102
+ }
2103
+ }
2104
+ catch {
2105
+ // Directory not readable, skip
2106
+ }
2107
+ }
2108
+ /**
2109
+ * Discover all NX projects in workspace.
2110
+ * Supports both workspace.json (older format) and project.json (newer format).
2111
+ *
2112
+ * @param workspacePath - Workspace root path
2113
+ * @returns Map of project name to configuration
2114
+ */
2115
+ function discoverNxProjects(workspacePath) {
2116
+ const projects = createMap();
2117
+ // Check for workspace.json (older NX format)
2118
+ const workspaceJson = readJsonFileIfExists(join(workspacePath, 'workspace.json'));
2119
+ if (workspaceJson?.projects) {
2120
+ for (const [name, config] of entries(workspaceJson.projects)) {
2121
+ if (typeof config === 'string') {
2122
+ // Path reference to project directory
2123
+ const projectPath = join(workspacePath, config);
2124
+ const projectConfig = getProjectConfig(projectPath, workspacePath);
2125
+ if (projectConfig) {
2126
+ projects.set(name, { ...projectConfig, name });
2127
+ }
2128
+ }
2129
+ else if (typeof config === 'object' && config !== null) {
2130
+ // Inline config
2131
+ projects.set(name, { name, ...config });
2132
+ }
2133
+ }
2134
+ return projects;
2135
+ }
2136
+ // Scan for project.json files (newer NX format)
2137
+ const workspaceInfo = getNxWorkspaceInfo(workspacePath);
2138
+ const appsDir = workspaceInfo?.workspaceLayout.appsDir ?? 'apps';
2139
+ const libsDir = workspaceInfo?.workspaceLayout.libsDir ?? 'libs';
2140
+ const searchDirs = [appsDir, libsDir];
2141
+ // Also check packages directory (common in some setups)
2142
+ if (exists(join(workspacePath, 'packages'))) {
2143
+ searchDirs.push('packages');
2144
+ }
2145
+ for (const dir of searchDirs) {
2146
+ const dirPath = join(workspacePath, dir);
2147
+ if (exists(dirPath) && isDirectory(dirPath)) {
2148
+ try {
2149
+ scanForProjects(dirPath, workspacePath, projects, 3);
2150
+ }
2151
+ catch {
2152
+ // Directory not accessible
2153
+ }
2154
+ }
2155
+ }
2156
+ // Also check root-level projects (standalone projects in monorepo root)
2157
+ if (isNxProject(workspacePath)) {
2158
+ const config = readProjectJson(workspacePath);
2159
+ if (config) {
2160
+ const name = config.name || basename(workspacePath);
2161
+ projects.set(name, {
2162
+ ...config,
2163
+ name,
2164
+ root: '.',
2165
+ });
2166
+ }
2167
+ }
2168
+ return projects;
2169
+ }
2170
+ /**
2171
+ * Build a simple project graph from discovered projects.
2172
+ * For full graph capabilities, use `@nx/devkit`.
2173
+ *
2174
+ * @param workspacePath - Workspace root path
2175
+ * @param projects - Existing configuration map to skip auto-discovery
2176
+ * @returns NxProjectGraph with nodes and dependencies
2177
+ */
2178
+ function buildSimpleProjectGraph(workspacePath, projects) {
2179
+ const projectMap = projects ?? discoverNxProjects(workspacePath);
2180
+ const nodes = {};
2181
+ const dependencies = {};
2182
+ for (const [name, config] of projectMap) {
2183
+ nodes[name] = {
2184
+ name,
2185
+ type: config.projectType ?? 'library',
2186
+ data: config,
2187
+ };
2188
+ dependencies[name] = [];
2189
+ // Add implicit dependencies
2190
+ if (config.implicitDependencies) {
2191
+ for (const dep of config.implicitDependencies) {
2192
+ // Skip negative dependencies (those starting with !)
2193
+ if (!dep.startsWith('!')) {
2194
+ dependencies[name].push({
2195
+ target: dep,
2196
+ type: 'implicit',
2197
+ });
2198
+ }
2199
+ }
2200
+ }
2201
+ }
2202
+ return { nodes, dependencies };
2203
+ }
2204
+
2205
+ /**
2206
+ * Creates an empty classification summary.
2207
+ *
2208
+ * @returns A new ClassificationSummary with all counts at zero
2209
+ */
2210
+ function createEmptyClassificationSummary() {
2211
+ return {
2212
+ total: 0,
2213
+ included: 0,
2214
+ excluded: 0,
2215
+ bySource: {
2216
+ 'direct-scope': 0,
2217
+ 'direct-file': 0,
2218
+ 'unscoped-file': 0,
2219
+ 'indirect-dependency': 0,
2220
+ 'indirect-infra': 0,
2221
+ 'unscoped-global': 0,
2222
+ excluded: 0,
2223
+ },
2224
+ };
2225
+ }
2226
+ /**
2227
+ * Creates a classified commit.
2228
+ *
2229
+ * @param commit - The parsed conventional commit
2230
+ * @param raw - The raw git commit
2231
+ * @param source - How the commit relates to the project
2232
+ * @param options - Additional classification options
2233
+ * @param options.touchedFiles - Files in the project modified by this commit
2234
+ * @param options.dependencyPath - Chain of dependencies leading to indirect inclusion
2235
+ * @returns A new ClassifiedCommit object
2236
+ */
2237
+ function createClassifiedCommit(commit, raw, source, options) {
2238
+ const include = isIncludedSource(source);
2239
+ const preserveScope = shouldPreserveScope(source);
2240
+ return {
2241
+ commit,
2242
+ raw,
2243
+ source,
2244
+ include,
2245
+ preserveScope,
2246
+ touchedFiles: options?.touchedFiles,
2247
+ dependencyPath: options?.dependencyPath,
2248
+ };
2249
+ }
2250
+ /**
2251
+ * Determines if a source type should be included in changelog.
2252
+ *
2253
+ * @param source - The commit source type
2254
+ * @returns True if commits with this source should be included
2255
+ */
2256
+ function isIncludedSource(source) {
2257
+ switch (source) {
2258
+ case 'direct-scope':
2259
+ case 'direct-file':
2260
+ case 'unscoped-file':
2261
+ case 'indirect-dependency':
2262
+ case 'indirect-infra':
2263
+ return true;
2264
+ case 'unscoped-global':
2265
+ case 'excluded':
2266
+ return false;
2267
+ }
2268
+ }
2269
+ /**
2270
+ * Determines if scope should be preserved for a source type.
2271
+ *
2272
+ * Direct commits omit scope (redundant in project changelog).
2273
+ * Indirect commits preserve scope for context.
2274
+ *
2275
+ * @param source - The commit source type
2276
+ * @returns True if scope should be preserved in changelog
2277
+ */
2278
+ function shouldPreserveScope(source) {
2279
+ switch (source) {
2280
+ case 'direct-scope':
2281
+ case 'unscoped-file':
2282
+ return false; // Scope would be redundant
2283
+ case 'direct-file':
2284
+ case 'indirect-dependency':
2285
+ case 'indirect-infra':
2286
+ return true; // Scope provides context
2287
+ case 'unscoped-global':
2288
+ case 'excluded':
2289
+ return false; // Won't be shown
2290
+ }
2291
+ }
2292
+
2293
+ /**
2294
+ * Derives all scope variations that should match a project.
2295
+ *
2296
+ * Given a project named 'lib-versioning' with package '@hyperfrontend/versioning',
2297
+ * this generates variations like:
2298
+ * - 'lib-versioning' (full project name)
2299
+ * - 'versioning' (without lib- prefix)
2300
+ *
2301
+ * @param options - Project identification options
2302
+ * @returns Array of scope strings that match this project
2303
+ *
2304
+ * @example
2305
+ * deriveProjectScopes({ projectName: 'lib-versioning', packageName: '@hyperfrontend/versioning' })
2306
+ * // Returns: ['lib-versioning', 'versioning']
2307
+ *
2308
+ * @example
2309
+ * deriveProjectScopes({ projectName: 'app-demo', packageName: 'demo-app' })
2310
+ * // Returns: ['app-demo', 'demo']
2311
+ */
2312
+ function deriveProjectScopes(options) {
2313
+ const { projectName, packageName, additionalScopes = [] } = options;
2314
+ const scopes = createSet();
2315
+ // Always include the full project name
2316
+ scopes.add(projectName);
2317
+ // Add variations based on common prefixes
2318
+ const prefixVariations = extractPrefixVariations(projectName);
2319
+ for (const variation of prefixVariations) {
2320
+ scopes.add(variation);
2321
+ }
2322
+ // Add package name variations if provided
2323
+ if (packageName) {
2324
+ const packageVariations = extractPackageNameVariations(packageName);
2325
+ for (const variation of packageVariations) {
2326
+ scopes.add(variation);
2327
+ }
2328
+ }
2329
+ // Add any additional scopes
2330
+ for (const scope of additionalScopes) {
2331
+ if (scope) {
2332
+ scopes.add(scope);
2333
+ }
2334
+ }
2335
+ return [...scopes];
2336
+ }
2337
+ /**
2338
+ * Recognized project name prefixes that can be stripped for scope matching.
2339
+ */
2340
+ const PROJECT_PREFIXES = ['lib-', 'app-', 'e2e-', 'tool-', 'plugin-', 'feature-', 'package-'];
2341
+ /**
2342
+ * Generates scope variations by stripping recognized project prefixes.
2343
+ *
2344
+ * @param projectName - The project name to extract variations from
2345
+ * @returns Array of scope name variations
2346
+ */
2347
+ function extractPrefixVariations(projectName) {
2348
+ const variations = [];
2349
+ for (const prefix of PROJECT_PREFIXES) {
2350
+ if (projectName.startsWith(prefix)) {
2351
+ const withoutPrefix = projectName.slice(prefix.length);
2352
+ if (withoutPrefix) {
2353
+ variations.push(withoutPrefix);
2354
+ }
2355
+ break; // Only remove one prefix
2356
+ }
2357
+ }
2358
+ return variations;
2359
+ }
2360
+ /**
2361
+ * Extracts scope variations from an npm package name.
2362
+ *
2363
+ * @param packageName - The npm package name (e.g., '@scope/name')
2364
+ * @returns Array of name variations
2365
+ */
2366
+ function extractPackageNameVariations(packageName) {
2367
+ const variations = [];
2368
+ // Handle scoped packages: @scope/name -> name
2369
+ if (packageName.startsWith('@')) {
2370
+ const slashIndex = packageName.indexOf('/');
2371
+ if (slashIndex !== -1) {
2372
+ const unscoped = packageName.slice(slashIndex + 1);
2373
+ if (unscoped) {
2374
+ variations.push(unscoped);
2375
+ }
2376
+ }
2377
+ }
2378
+ else {
2379
+ // Non-scoped package: just use the name
2380
+ variations.push(packageName);
2381
+ }
2382
+ return variations;
2383
+ }
2384
+ /**
2385
+ * Checks if a commit scope matches any of the project scopes.
2386
+ *
2387
+ * @param commitScope - The scope from a conventional commit
2388
+ * @param projectScopes - Array of scopes that match the project
2389
+ * @returns True if the commit scope matches the project
2390
+ *
2391
+ * @example
2392
+ * scopeMatchesProject('versioning', ['lib-versioning', 'versioning']) // true
2393
+ * scopeMatchesProject('logging', ['lib-versioning', 'versioning']) // false
2394
+ */
2395
+ function scopeMatchesProject(commitScope, projectScopes) {
2396
+ if (!commitScope) {
2397
+ return false;
2398
+ }
2399
+ // Case-insensitive comparison
2400
+ const normalizedScope = commitScope.toLowerCase();
2401
+ return projectScopes.some((scope) => scope.toLowerCase() === normalizedScope);
2402
+ }
2403
+ /**
2404
+ * Checks if a commit scope should be explicitly excluded.
2405
+ *
2406
+ * @param commitScope - The scope from a conventional commit
2407
+ * @param excludeScopes - Array of scopes to exclude
2408
+ * @returns True if the scope should be excluded
2409
+ */
2410
+ function scopeIsExcluded(commitScope, excludeScopes) {
2411
+ if (!commitScope) {
2412
+ return false;
2413
+ }
2414
+ const normalizedScope = commitScope.toLowerCase();
2415
+ return excludeScopes.some((scope) => scope.toLowerCase() === normalizedScope);
2416
+ }
2417
+ /**
2418
+ * Default scopes to exclude from changelogs.
2419
+ *
2420
+ * These represent repository-level or infrastructure changes
2421
+ * that typically don't belong in individual project changelogs.
2422
+ */
2423
+ const DEFAULT_EXCLUDE_SCOPES = ['release', 'deps', 'workspace', 'root', 'repo', 'ci', 'build'];
2424
+
2425
+ /**
2426
+ * Classifies a single commit against a project.
2427
+ *
2428
+ * Implements the hybrid classification strategy:
2429
+ * 1. Check scope match (fast path)
2430
+ * 2. Check file touch (validation/catch-all)
2431
+ * 3. Check dependency touch (indirect)
2432
+ * 4. Fallback to excluded
2433
+ *
2434
+ * @param input - The commit to classify
2435
+ * @param context - Classification context with project info
2436
+ * @returns Classified commit with source attribution
2437
+ *
2438
+ * @example
2439
+ * const classified = classifyCommit(
2440
+ * { commit: parsedCommit, raw: gitCommit },
2441
+ * { projectScopes: ['versioning'], fileCommitHashes: new Set(['abc123']) }
2442
+ * )
2443
+ */
2444
+ function classifyCommit(input, context) {
2445
+ const { commit, raw } = input;
2446
+ const { projectScopes, fileCommitHashes, dependencyCommitMap, infrastructureCommitHashes, excludeScopes = DEFAULT_EXCLUDE_SCOPES, includeScopes = [], } = context;
2447
+ const scope = commit.scope;
2448
+ const hasScope = !!scope;
2449
+ const allProjectScopes = [...projectScopes, ...includeScopes];
2450
+ // First check: Is this scope explicitly excluded?
2451
+ if (hasScope && scopeIsExcluded(scope, excludeScopes)) {
2452
+ return createClassifiedCommit(commit, raw, 'excluded');
2453
+ }
2454
+ // Priority 1: Scope-based direct match (fast path)
2455
+ if (hasScope && scopeMatchesProject(scope, allProjectScopes)) {
2456
+ return createClassifiedCommit(commit, raw, 'direct-scope');
2457
+ }
2458
+ // Priority 2: File-based direct match (validation/catch-all)
2459
+ if (fileCommitHashes.has(raw.hash)) {
2460
+ // Commit touched project files
2461
+ if (hasScope) {
2462
+ // Has a scope but it's different - likely a typo or cross-cutting change
2463
+ return createClassifiedCommit(commit, raw, 'direct-file');
2464
+ }
2465
+ // No scope but touched project files
2466
+ return createClassifiedCommit(commit, raw, 'unscoped-file');
2467
+ }
2468
+ // Priority 3: Indirect dependency match
2469
+ if (hasScope && dependencyCommitMap) {
2470
+ const dependencyPath = findDependencyPath(scope, raw.hash, dependencyCommitMap);
2471
+ if (dependencyPath) {
2472
+ return createClassifiedCommit(commit, raw, 'indirect-dependency', { dependencyPath });
2473
+ }
2474
+ }
2475
+ // File-based infrastructure match
2476
+ if (infrastructureCommitHashes?.has(raw.hash)) {
2477
+ return createClassifiedCommit(commit, raw, 'indirect-infra');
2478
+ }
2479
+ // Fallback: No match found
2480
+ if (!hasScope) {
2481
+ // Unscoped commit that didn't touch any project files
2482
+ return createClassifiedCommit(commit, raw, 'unscoped-global');
2483
+ }
2484
+ // Scoped commit that doesn't match anything
2485
+ return createClassifiedCommit(commit, raw, 'excluded');
2486
+ }
2487
+ /**
2488
+ * Classifies multiple commits against a project.
2489
+ *
2490
+ * @param commits - Array of commits to classify
2491
+ * @param context - Classification context with project info
2492
+ * @returns Classification result with all commits and summary
2493
+ */
2494
+ function classifyCommits(commits, context) {
2495
+ const classified = [];
2496
+ const included = [];
2497
+ const excluded = [];
2498
+ const summary = createEmptyClassificationSummary();
2499
+ const bySource = { ...summary.bySource };
2500
+ for (const input of commits) {
2501
+ const result = classifyCommit(input, context);
2502
+ classified.push(result);
2503
+ // Update summary
2504
+ bySource[result.source]++;
2505
+ if (result.include) {
2506
+ included.push(result);
2507
+ }
2508
+ else {
2509
+ excluded.push(result);
2510
+ }
2511
+ }
2512
+ return {
2513
+ commits: classified,
2514
+ included,
2515
+ excluded,
2516
+ summary: {
2517
+ total: classified.length,
2518
+ included: included.length,
2519
+ excluded: excluded.length,
2520
+ bySource,
2521
+ },
2522
+ };
2523
+ }
2524
+ /**
2525
+ * Finds a dependency path for a given scope and commit hash.
2526
+ *
2527
+ * Verifies both:
2528
+ * 1. The scope matches a dependency name (or variation)
2529
+ * 2. The commit hash is in that dependency's commit set
2530
+ *
2531
+ * This prevents false positives from mislabeled commits.
2532
+ *
2533
+ * @param scope - The commit scope
2534
+ * @param hash - The commit hash to verify
2535
+ * @param dependencyCommitMap - Map of dependencies to their commit hashes
2536
+ * @returns Dependency path if found and hash verified, undefined otherwise
2537
+ */
2538
+ function findDependencyPath(scope, hash, dependencyCommitMap) {
2539
+ const normalizedScope = scope.toLowerCase();
2540
+ for (const [depName, depHashes] of dependencyCommitMap) {
2541
+ // Check if scope matches dependency name or variations
2542
+ const depVariations = getDependencyVariations(depName);
2543
+ if (depVariations.some((v) => v.toLowerCase() === normalizedScope)) {
2544
+ // CRITICAL: Verify the commit actually touched this dependency's files
2545
+ // This prevents false positives from mislabeled commits
2546
+ if (depHashes.has(hash)) {
2547
+ return [depName];
2548
+ }
2549
+ }
2550
+ }
2551
+ return undefined;
2552
+ }
2553
+ /**
2554
+ * Generates name variations for a dependency to enable flexible scope matching.
2555
+ *
2556
+ * @param depName - The dependency project or package name
2557
+ * @returns Array of name variations including stripped prefixes
2558
+ */
2559
+ function getDependencyVariations(depName) {
2560
+ const variations = [depName];
2561
+ // Handle lib- prefix
2562
+ if (depName.startsWith('lib-')) {
2563
+ variations.push(depName.slice(4));
2564
+ }
2565
+ // Handle @scope/name
2566
+ if (depName.startsWith('@')) {
2567
+ const slashIndex = depName.indexOf('/');
2568
+ if (slashIndex !== -1) {
2569
+ variations.push(depName.slice(slashIndex + 1));
2570
+ }
2571
+ }
2572
+ return variations;
2573
+ }
2574
+ /**
2575
+ * Creates a classification context from common inputs.
2576
+ *
2577
+ * @param projectScopes - Scopes that match the project
2578
+ * @param fileCommitHashes - Set of commit hashes that touched project files
2579
+ * @param options - Additional context options
2580
+ * @param options.dependencyCommitMap - Map of dependency names to commit hashes touching them
2581
+ * @param options.infrastructureCommitHashes - Set of commit hashes touching infrastructure paths
2582
+ * @param options.excludeScopes - Scopes to explicitly exclude from classification
2583
+ * @param options.includeScopes - Additional scopes to include as direct matches
2584
+ * @returns A ClassificationContext object
2585
+ */
2586
+ function createClassificationContext(projectScopes, fileCommitHashes, options) {
2587
+ return {
2588
+ projectScopes,
2589
+ fileCommitHashes,
2590
+ dependencyCommitMap: options?.dependencyCommitMap,
2591
+ infrastructureCommitHashes: options?.infrastructureCommitHashes,
2592
+ excludeScopes: options?.excludeScopes ?? DEFAULT_EXCLUDE_SCOPES,
2593
+ includeScopes: options?.includeScopes,
2594
+ };
2595
+ }
2596
+ /**
2597
+ * Creates a modified conventional commit with scope handling based on classification.
2598
+ *
2599
+ * For direct commits, the scope is removed (redundant in project changelog).
2600
+ * For indirect commits, the scope is preserved (provides context).
2601
+ *
2602
+ * @param classified - Commit with classification metadata determining scope display
2603
+ * @returns A conventional commit with appropriate scope handling
2604
+ */
2605
+ function toChangelogCommit(classified) {
2606
+ const { commit, preserveScope } = classified;
2607
+ if (!preserveScope && commit.scope) {
2608
+ // Remove the scope for direct commits
2609
+ return {
2610
+ ...commit,
2611
+ scope: undefined,
2612
+ // Rebuild raw to reflect removed scope
2613
+ raw: rebuildRawWithoutScope(commit),
2614
+ };
2615
+ }
2616
+ return commit;
2617
+ }
2618
+ /**
2619
+ * Reconstructs a conventional commit message string without the scope portion.
2620
+ *
2621
+ * @param commit - The conventional commit to rebuild
2622
+ * @returns Reconstructed raw message with scope removed
2623
+ */
2624
+ function rebuildRawWithoutScope(commit) {
2625
+ const breaking = commit.breaking && !commit.breakingDescription ? '!' : '';
2626
+ const header = `${commit.type}${breaking}: ${commit.subject}`;
2627
+ if (!commit.body && commit.footers.length === 0) {
2628
+ return header;
2629
+ }
2630
+ let raw = header;
2631
+ if (commit.body) {
2632
+ raw += `\n\n${commit.body}`;
2633
+ }
2634
+ for (const footer of commit.footers) {
2635
+ raw += `\n${footer.key}${footer.separator}${footer.value}`;
2636
+ }
2637
+ return raw;
2638
+ }
2639
+
2640
+ /**
2641
+ * Creates a matcher that checks if commit scope matches any of the given scopes.
2642
+ *
2643
+ * @param scopes - Scopes to match against (case-insensitive)
2644
+ * @returns Matcher that returns true if scope matches
2645
+ *
2646
+ * @example
2647
+ * const matcher = scopeMatcher(['ci', 'build', 'tooling'])
2648
+ * matcher({ scope: 'CI', ... }) // true
2649
+ * matcher({ scope: 'feat', ... }) // false
2650
+ */
2651
+ function scopeMatcher(scopes) {
2652
+ const normalizedScopes = createSet(scopes.map((s) => s.toLowerCase()));
2653
+ return (ctx) => {
2654
+ if (!ctx.scope)
2655
+ return false;
2656
+ return normalizedScopes.has(ctx.scope.toLowerCase());
2657
+ };
2658
+ }
2659
+ /**
2660
+ * Creates a matcher that checks if commit scope starts with any of the given prefixes.
2661
+ *
2662
+ * @param prefixes - Scope prefixes to match (case-insensitive)
2663
+ * @returns Matcher that returns true if scope starts with any prefix
2664
+ *
2665
+ * @example
2666
+ * const matcher = scopePrefixMatcher(['tool-', 'infra-'])
2667
+ * matcher({ scope: 'tool-package', ... }) // true
2668
+ * matcher({ scope: 'lib-utils', ... }) // false
44
2669
  */
45
- function createStep(id, name, execute, options = {}) {
46
- return {
47
- id,
48
- name,
49
- execute,
50
- description: options.description,
51
- skipIf: options.skipIf,
52
- continueOnError: options.continueOnError,
53
- dependsOn: options.dependsOn,
2670
+ function scopePrefixMatcher(prefixes) {
2671
+ const normalizedPrefixes = prefixes.map((p) => p.toLowerCase());
2672
+ return (ctx) => {
2673
+ if (!ctx.scope)
2674
+ return false;
2675
+ const normalizedScope = ctx.scope.toLowerCase();
2676
+ return normalizedPrefixes.some((prefix) => normalizedScope.startsWith(prefix));
54
2677
  };
55
2678
  }
56
2679
  /**
57
- * Creates a skipped step result.
2680
+ * Combines matchers with OR logic - returns true if ANY matcher matches.
58
2681
  *
59
- * @param message - Explanation for why the step was skipped
60
- * @returns A FlowStepResult with 'skipped' status
2682
+ * @param matchers - Matchers to combine
2683
+ * @returns Combined matcher
2684
+ *
2685
+ * @example
2686
+ * const combined = anyOf(
2687
+ * scopeMatcher(['ci', 'build']),
2688
+ * messageMatcher(['[infra]']),
2689
+ * custom((ctx) => ctx.scope?.startsWith('tool-'))
2690
+ * )
61
2691
  */
62
- function createSkippedResult(message) {
63
- return {
64
- status: 'skipped',
65
- message,
66
- };
2692
+ function anyOf(...matchers) {
2693
+ return (ctx) => matchers.some((matcher) => matcher(ctx));
67
2694
  }
68
-
69
- const FETCH_REGISTRY_STEP_ID = 'fetch-registry';
70
2695
  /**
71
- * Creates the fetch-registry step.
2696
+ * Matches common CI/CD scopes.
72
2697
  *
73
- * This step:
74
- * 1. Queries the registry for the latest published version
75
- * 2. Reads the current version from package.json
76
- * 3. Determines if this is a first release
2698
+ * Matches: ci, cd, build, pipeline, workflow, actions
2699
+ */
2700
+ const CI_SCOPE_MATCHER = scopeMatcher(['ci', 'cd', 'build', 'pipeline', 'workflow', 'actions']);
2701
+ /**
2702
+ * Matches common tooling/workspace scopes.
77
2703
  *
78
- * State updates:
79
- * - publishedVersion: Latest version on registry (null if not published)
80
- * - currentVersion: Version from local package.json
81
- * - isFirstRelease: True if never published
2704
+ * Matches: tooling, workspace, monorepo, nx, root
2705
+ */
2706
+ const TOOLING_SCOPE_MATCHER = scopeMatcher(['tooling', 'workspace', 'monorepo', 'nx', 'root']);
2707
+ /**
2708
+ * Matches tool-prefixed scopes (e.g., tool-package, tool-scripts).
2709
+ */
2710
+ const TOOL_PREFIX_MATCHER = scopePrefixMatcher(['tool-']);
2711
+ /**
2712
+ * Combined matcher for common infrastructure patterns.
82
2713
  *
83
- * @returns A FlowStep that fetches registry information
2714
+ * Combines CI, tooling, and tool-prefix matchers.
84
2715
  */
85
- function createFetchRegistryStep() {
86
- return createStep(FETCH_REGISTRY_STEP_ID, 'Fetch Registry Version', async (ctx) => {
87
- const { registry, tree, projectRoot, packageName, logger } = ctx;
88
- // Read local package.json for current version
89
- const packageJsonPath = `${projectRoot}/package.json`;
90
- let currentVersion = '0.0.0';
91
- try {
92
- const content = tree.read(packageJsonPath, 'utf-8');
93
- if (content) {
94
- const pkg = parse(content);
95
- currentVersion = pkg.version ?? '0.0.0';
96
- }
97
- }
98
- catch (error) {
99
- logger.warn(`Could not read package.json: ${error}`);
100
- }
101
- // Query registry for published version
102
- let publishedVersion = null;
103
- let isFirstRelease = true;
104
- try {
105
- publishedVersion = await registry.getLatestVersion(packageName);
106
- isFirstRelease = publishedVersion === null;
107
- }
108
- catch (error) {
109
- // Package might not exist yet, which is fine
110
- logger.debug(`Registry query failed (package may not exist): ${error}`);
111
- isFirstRelease = true;
112
- }
113
- const message = isFirstRelease ? `First release (local: ${currentVersion})` : `Published: ${publishedVersion}, Local: ${currentVersion}`;
114
- return {
115
- status: 'success',
116
- stateUpdates: {
117
- publishedVersion,
118
- currentVersion,
119
- isFirstRelease,
120
- },
121
- message,
122
- };
123
- });
124
- }
125
-
2716
+ anyOf(CI_SCOPE_MATCHER, TOOLING_SCOPE_MATCHER, TOOL_PREFIX_MATCHER);
126
2717
  /**
127
- * Safe copies of Error built-ins via factory functions.
2718
+ * Builds a combined matcher from infrastructure configuration.
128
2719
  *
129
- * Since constructors cannot be safely captured via Object.assign, this module
130
- * provides factory functions that use Reflect.construct internally.
2720
+ * Combines scope-based matching with any custom matcher using OR logic.
2721
+ * Path-based matching is handled separately via git queries.
131
2722
  *
132
- * These references are captured at module initialization time to protect against
133
- * prototype pollution attacks. Import only what you need for tree-shaking.
2723
+ * @param config - Infrastructure configuration
2724
+ * @returns Combined matcher, or null if no matchers configured
134
2725
  *
135
- * @module @hyperfrontend/immutable-api-utils/built-in-copy/error
2726
+ * @example
2727
+ * const matcher = buildInfrastructureMatcher({
2728
+ * scopes: ['ci', 'build'],
2729
+ * matcher: (ctx) => ctx.scope?.startsWith('tool-')
2730
+ * })
136
2731
  */
137
- // Capture references at module initialization time
138
- const _Error = globalThis.Error;
139
- const _Reflect$2 = globalThis.Reflect;
2732
+ function buildInfrastructureMatcher(config) {
2733
+ const matchers = [];
2734
+ // Add scope matcher if scopes configured
2735
+ if (config.scopes && config.scopes.length > 0) {
2736
+ matchers.push(scopeMatcher(config.scopes));
2737
+ }
2738
+ // Add custom matcher if provided
2739
+ if (config.matcher) {
2740
+ matchers.push(config.matcher);
2741
+ }
2742
+ // Return combined or null
2743
+ if (matchers.length === 0) {
2744
+ return null;
2745
+ }
2746
+ if (matchers.length === 1) {
2747
+ return matchers[0];
2748
+ }
2749
+ return anyOf(...matchers);
2750
+ }
140
2751
  /**
141
- * (Safe copy) Creates a new Error using the captured Error constructor.
142
- * Use this instead of `new Error()`.
2752
+ * Creates match context from a git commit.
143
2753
  *
144
- * @param message - Optional error message.
145
- * @param options - Optional error options.
146
- * @returns A new Error instance.
2754
+ * Extracts scope from conventional commit message if present.
2755
+ *
2756
+ * @param commit - Git commit to create context for
2757
+ * @param scope - Pre-parsed scope (optional, saves re-parsing)
2758
+ * @returns Match context for use with matchers
147
2759
  */
148
- const createError = (message, options) => _Reflect$2.construct(_Error, [message, options]);
2760
+ function createMatchContext(commit, scope) {
2761
+ return {
2762
+ commit,
2763
+ scope,
2764
+ subject: commit.subject,
2765
+ message: commit.message,
2766
+ };
2767
+ }
149
2768
 
150
2769
  /**
151
2770
  * Replaces all occurrences of a character in a string.
@@ -571,78 +3190,525 @@ function splitLines(message) {
571
3190
  return lines;
572
3191
  }
573
3192
 
3193
+ /**
3194
+ * Default scope filtering configuration.
3195
+ *
3196
+ * Uses DEFAULT_EXCLUDE_SCOPES from commits/classify to ensure consistency
3197
+ * between flow-level filtering and commit classification.
3198
+ */
3199
+ const DEFAULT_SCOPE_FILTERING_CONFIG = {
3200
+ strategy: 'hybrid',
3201
+ includeScopes: [],
3202
+ excludeScopes: DEFAULT_EXCLUDE_SCOPES,
3203
+ trackDependencyChanges: false,
3204
+ infrastructure: undefined,
3205
+ infrastructureMatcher: undefined,
3206
+ };
3207
+
574
3208
  const ANALYZE_COMMITS_STEP_ID = 'analyze-commits';
575
3209
  /**
576
3210
  * Creates the analyze-commits step.
577
3211
  *
578
3212
  * This step:
579
- * 1. Finds the last release tag for this package
580
- * 2. Gets all commits since that tag (or all commits if first release)
581
- * 3. Parses each commit using conventional commit format
582
- * 4. Filters to only release-worthy commits
3213
+ * 1. Uses publishedCommit from npm registry (set by fetch-registry step)
3214
+ * 2. Verifies the commit is reachable from current HEAD
3215
+ * 3. Gets all commits since that commit (or recent commits if first release/fallback)
3216
+ * 4. Parses each commit using conventional commit format
3217
+ * 5. Classifies commits based on scope filtering strategy
3218
+ * 6. Filters to only release-worthy commits that belong to this project
583
3219
  *
584
3220
  * State updates:
585
- * - lastReleaseTag: Tag name of last release (null if first release)
586
- * - commits: Array of parsed conventional commits
3221
+ * - effectiveBaseCommit: The verified base commit (null if fallback was used)
3222
+ * - commits: Array of parsed conventional commits (for backward compatibility)
3223
+ * - classificationResult: Full classification result with source attribution
587
3224
  *
588
3225
  * @returns A FlowStep that analyzes commits
589
3226
  */
590
3227
  function createAnalyzeCommitsStep() {
591
3228
  return createStep(ANALYZE_COMMITS_STEP_ID, 'Analyze Commits', async (ctx) => {
592
- const { git, projectName, packageName, config, logger, state } = ctx;
593
- // Find the last release tag for this package
594
- let lastReleaseTag = null;
595
- if (!state.isFirstRelease) {
596
- // Try to find a tag matching the package name pattern
597
- const tags = git.getTagsForPackage(packageName);
598
- if (tags.length > 0) {
599
- // Tags are returned in reverse chronological order
600
- lastReleaseTag = tags[0].name;
601
- logger.debug(`Found last release tag: ${lastReleaseTag}`);
3229
+ const { git, projectName, projectRoot, packageName, workspaceRoot, config, logger, state } = ctx;
3230
+ // Use publishedCommit from registry (set by fetch-registry step)
3231
+ const { publishedCommit, isFirstRelease } = state;
3232
+ let rawCommits;
3233
+ let effectiveBaseCommit = null;
3234
+ if (publishedCommit && !isFirstRelease) {
3235
+ // CRITICAL: Verify the commit exists and is reachable from HEAD
3236
+ if (git.commitReachableFromHead(publishedCommit)) {
3237
+ rawCommits = git.getCommitsSince(publishedCommit);
3238
+ effectiveBaseCommit = publishedCommit;
3239
+ logger.debug(`Found ${rawCommits.length} commits since ${publishedCommit.slice(0, 7)}`);
602
3240
  }
603
3241
  else {
604
- // Try with project name format
605
- const projectTags = git.getTagsForPackage(projectName);
606
- if (projectTags.length > 0) {
607
- lastReleaseTag = projectTags[0].name;
608
- logger.debug(`Found last release tag (project format): ${lastReleaseTag}`);
609
- }
3242
+ // GRACEFUL DEGRADATION: Commit not in history (rebase/force push occurred)
3243
+ logger.warn(`Published commit ${publishedCommit.slice(0, 7)} not found in history. ` +
3244
+ `This may indicate a rebase or force push occurred after publishing v${state.publishedVersion}. ` +
3245
+ `Falling back to recent commit analysis.`);
3246
+ rawCommits = git.getCommitLog({ maxCount: 100 });
3247
+ // effectiveBaseCommit stays null - no compare URL will be generated
610
3248
  }
611
3249
  }
612
- // Get commits
613
- let rawCommits;
614
- if (lastReleaseTag) {
615
- rawCommits = git.getCommitsSince(lastReleaseTag);
616
- logger.debug(`Found ${rawCommits.length} commits since ${lastReleaseTag}`);
617
- }
618
3250
  else {
619
- // First release - get all commits (limit to recent for performance)
3251
+ // First release or no published version
620
3252
  rawCommits = git.getCommitLog({ maxCount: 100 });
621
3253
  logger.debug(`First release - analyzing up to ${rawCommits.length} commits`);
622
3254
  }
623
- // Parse commits using conventional commit format
624
- const commits = [];
3255
+ // Get scope filtering configuration
3256
+ const scopeFilteringConfig = {
3257
+ ...DEFAULT_SCOPE_FILTERING_CONFIG,
3258
+ ...config.scopeFiltering,
3259
+ };
3260
+ const strategy = resolveStrategy(scopeFilteringConfig.strategy ?? 'hybrid', rawCommits);
3261
+ // Parse commits with conventional commit format
625
3262
  const releaseTypes = config.releaseTypes ?? ['feat', 'fix', 'perf', 'revert'];
3263
+ const parsedCommits = [];
626
3264
  for (const rawCommit of rawCommits) {
627
3265
  const parsed = parseConventionalCommit(rawCommit.message);
628
3266
  if (parsed.type && releaseTypes.includes(parsed.type)) {
629
- commits.push(parsed);
3267
+ parsedCommits.push({
3268
+ commit: parsed,
3269
+ raw: {
3270
+ hash: rawCommit.hash,
3271
+ shortHash: rawCommit.hash.slice(0, 7),
3272
+ message: rawCommit.message,
3273
+ subject: parsed.subject ?? rawCommit.message.split('\n')[0],
3274
+ body: parsed.body ?? '',
3275
+ authorName: '',
3276
+ authorEmail: '',
3277
+ authorDate: '',
3278
+ committerName: '',
3279
+ committerEmail: '',
3280
+ commitDate: '',
3281
+ parents: [],
3282
+ refs: [],
3283
+ },
3284
+ });
3285
+ }
3286
+ }
3287
+ // Build file commit hashes for hybrid/file-only strategies
3288
+ let fileCommitHashes = createSet();
3289
+ if (strategy === 'hybrid' || strategy === 'file-only') {
3290
+ // Get commits that touched project files using path filter
3291
+ const relativePath = getRelativePath(workspaceRoot, projectRoot);
3292
+ const pathFilteredCommits = effectiveBaseCommit
3293
+ ? git.getCommitsSince(effectiveBaseCommit, { path: relativePath })
3294
+ : git.getCommitLog({ maxCount: 100, path: relativePath });
3295
+ fileCommitHashes = createSet(pathFilteredCommits.map((c) => c.hash));
3296
+ logger.debug(`Found ${fileCommitHashes.size} commits touching ${relativePath}`);
3297
+ }
3298
+ // Derive project scopes
3299
+ const projectScopes = deriveProjectScopes({
3300
+ projectName,
3301
+ packageName,
3302
+ additionalScopes: scopeFilteringConfig.includeScopes,
3303
+ });
3304
+ logger.debug(`Project scopes: ${projectScopes.join(', ')}`);
3305
+ // Build infrastructure commit hashes for file-based infrastructure detection
3306
+ const infrastructureCommitHashes = buildInfrastructureCommitHashes(git, effectiveBaseCommit, rawCommits, parsedCommits, scopeFilteringConfig, logger);
3307
+ // Build dependency commit map if tracking is enabled (Phase 4)
3308
+ let dependencyCommitMap;
3309
+ if (scopeFilteringConfig.trackDependencyChanges) {
3310
+ dependencyCommitMap = buildDependencyCommitMap(git, workspaceRoot, projectName, effectiveBaseCommit, logger);
3311
+ }
3312
+ // Create classification context
3313
+ const classificationContext = createClassificationContext(projectScopes, fileCommitHashes, {
3314
+ excludeScopes: scopeFilteringConfig.excludeScopes,
3315
+ includeScopes: scopeFilteringConfig.includeScopes,
3316
+ infrastructureCommitHashes,
3317
+ dependencyCommitMap,
3318
+ });
3319
+ // Classify commits
3320
+ const classificationResult = classifyCommits(parsedCommits, classificationContext);
3321
+ // Apply strategy-specific filtering
3322
+ const includedCommits = applyStrategyFilter(classificationResult.included, strategy);
3323
+ // Extract conventional commits for backward compatibility
3324
+ // Use toChangelogCommit to properly handle scope based on classification
3325
+ const commits = includedCommits.map((c) => toChangelogCommit(c));
3326
+ // Build message with classification summary
3327
+ const { summary } = classificationResult;
3328
+ const message = buildSummaryMessage(commits.length, rawCommits.length, summary, strategy);
3329
+ logger.debug(`Classification breakdown: direct-scope=${summary.bySource['direct-scope']}, ` +
3330
+ `direct-file=${summary.bySource['direct-file']}, unscoped-file=${summary.bySource['unscoped-file']}, ` +
3331
+ `excluded=${summary.bySource['excluded']}`);
3332
+ return {
3333
+ status: 'success',
3334
+ stateUpdates: {
3335
+ effectiveBaseCommit,
3336
+ commits,
3337
+ classificationResult,
3338
+ },
3339
+ message,
3340
+ };
3341
+ }, {
3342
+ dependsOn: ['fetch-registry'],
3343
+ });
3344
+ }
3345
+ /**
3346
+ * Resolves the filtering strategy, handling 'inferred' by analyzing commits.
3347
+ *
3348
+ * @param strategy - The configured scope filtering strategy
3349
+ * @param commits - The commits to analyze for strategy inference
3350
+ * @returns The resolved strategy (never 'inferred')
3351
+ */
3352
+ function resolveStrategy(strategy, commits) {
3353
+ if (strategy !== 'inferred') {
3354
+ return strategy;
3355
+ }
3356
+ // Infer strategy from commit history
3357
+ // Count commits with conventional scopes
3358
+ let scopedCount = 0;
3359
+ for (const commit of commits) {
3360
+ const parsed = parseConventionalCommit(commit.message);
3361
+ if (parsed.scope) {
3362
+ scopedCount++;
3363
+ }
3364
+ }
3365
+ const scopeRatio = commits.length > 0 ? scopedCount / commits.length : 0;
3366
+ // If >70% of commits have scopes, scope-only is viable
3367
+ // If <30% have scopes, file-only is better
3368
+ // Otherwise, use hybrid
3369
+ if (scopeRatio > 0.7) {
3370
+ return 'scope-only';
3371
+ }
3372
+ else if (scopeRatio < 0.3) {
3373
+ return 'file-only';
3374
+ }
3375
+ return 'hybrid';
3376
+ }
3377
+ /**
3378
+ * Applies strategy-specific filtering to classified commits.
3379
+ *
3380
+ * @param commits - The classified commits to filter
3381
+ * @param strategy - The resolved filtering strategy to apply
3382
+ * @returns Filtered commits based on the strategy
3383
+ */
3384
+ function applyStrategyFilter(commits, strategy) {
3385
+ switch (strategy) {
3386
+ case 'scope-only':
3387
+ // Only include direct-scope commits
3388
+ return commits.filter((c) => c.source === 'direct-scope');
3389
+ case 'file-only':
3390
+ // Only include file-based commits (direct-file, unscoped-file)
3391
+ return commits.filter((c) => c.source === 'direct-file' || c.source === 'unscoped-file');
3392
+ case 'hybrid':
3393
+ default:
3394
+ // Include all non-excluded commits (already filtered in classifyCommits)
3395
+ return commits;
3396
+ }
3397
+ }
3398
+ /**
3399
+ * Gets the relative path from workspace root to project root.
3400
+ *
3401
+ * @param workspaceRoot - The absolute path to the workspace root
3402
+ * @param projectRoot - The absolute path to the project root
3403
+ * @returns The relative path from workspace to project
3404
+ */
3405
+ function getRelativePath(workspaceRoot, projectRoot) {
3406
+ if (projectRoot.startsWith(workspaceRoot)) {
3407
+ return projectRoot.slice(workspaceRoot.length).replace(/^\//, '');
3408
+ }
3409
+ return projectRoot;
3410
+ }
3411
+ /**
3412
+ * Builds a summary message for the step result.
3413
+ *
3414
+ * @param includedCount - Number of commits included in the release
3415
+ * @param totalCount - Total number of commits analyzed
3416
+ * @param summary - Classification summary object
3417
+ * @param summary.bySource - Count of commits by source type
3418
+ * @param strategy - The filtering strategy used
3419
+ * @returns A human-readable summary message
3420
+ */
3421
+ function buildSummaryMessage(includedCount, totalCount, summary, strategy) {
3422
+ if (includedCount === 0) {
3423
+ return `No releasable commits found for this project (${totalCount} total, strategy: ${strategy})`;
3424
+ }
3425
+ const parts = [`Found ${includedCount} releasable commits`, `(${totalCount} total`, `strategy: ${strategy})`];
3426
+ return parts.join(' ');
3427
+ }
3428
+ /**
3429
+ * Builds a set of commit hashes that touched infrastructure paths or match infrastructure criteria.
3430
+ *
3431
+ * Supports multiple detection methods combined with OR logic:
3432
+ * 1. Path-based: Commits touching configured infrastructure paths (via git)
3433
+ * 2. Scope-based: Commits with scopes matching infrastructure.scopes
3434
+ * 3. Custom matcher: User-provided matching logic
3435
+ *
3436
+ * @param git - Git client for querying commits by path
3437
+ * @param baseCommit - Base commit hash for commit range (null for first release/fallback)
3438
+ * @param rawCommits - All raw commits being analyzed
3439
+ * @param parsedCommits - Parsed commits with conventional commit data
3440
+ * @param config - Scope filtering configuration
3441
+ * @param logger - Logger with debug method for output
3442
+ * @param logger.debug - Debug logging function
3443
+ * @returns Set of commit hashes classified as infrastructure
3444
+ */
3445
+ function buildInfrastructureCommitHashes(git, baseCommit, rawCommits, parsedCommits, config, logger) {
3446
+ // Collect all infrastructure commit hashes
3447
+ let infraHashes = createSet();
3448
+ // Method 1: Path-based detection (query git for commits touching infra paths)
3449
+ const infraPaths = config.infrastructure?.paths ?? [];
3450
+ if (infraPaths.length > 0) {
3451
+ for (const infraPath of infraPaths) {
3452
+ const pathCommits = baseCommit
3453
+ ? git.getCommitsSince(baseCommit, { path: infraPath })
3454
+ : git.getCommitLog({ maxCount: 100, path: infraPath });
3455
+ for (const commit of pathCommits) {
3456
+ infraHashes = infraHashes.add(commit.hash);
3457
+ }
3458
+ }
3459
+ logger.debug(`Found ${infraHashes.size} commits touching infrastructure paths: ${infraPaths.join(', ')}`);
3460
+ }
3461
+ // Method 2 & 3: Scope-based and custom matcher detection
3462
+ // Build a combined matcher from infrastructure config and/or custom matcher
3463
+ const configMatcher = config.infrastructure ? buildInfrastructureMatcher(config.infrastructure) : null;
3464
+ const customMatcher = config.infrastructureMatcher;
3465
+ const combinedMatcher = combineMatcher(configMatcher, customMatcher);
3466
+ if (combinedMatcher) {
3467
+ // Build a lookup for parsed commits by hash
3468
+ let parsedByHash = createMap();
3469
+ for (const parsed of parsedCommits) {
3470
+ parsedByHash = parsedByHash.set(parsed.raw.hash, parsed);
3471
+ }
3472
+ // Evaluate each raw commit against the matcher
3473
+ for (const rawCommit of rawCommits) {
3474
+ // Skip if already matched by path
3475
+ if (infraHashes.has(rawCommit.hash))
3476
+ continue;
3477
+ // Get parsed scope if available
3478
+ const parsed = parsedByHash.get(rawCommit.hash);
3479
+ const scope = parsed?.commit.scope;
3480
+ // Create match context and evaluate
3481
+ const context = createMatchContext(rawCommit, scope);
3482
+ if (combinedMatcher(context)) {
3483
+ infraHashes = infraHashes.add(rawCommit.hash);
3484
+ }
3485
+ }
3486
+ logger.debug(`Infrastructure matcher found ${infraHashes.size} total commits`);
3487
+ }
3488
+ // Return undefined if no infrastructure detection configured
3489
+ if (infraHashes.size === 0 && infraPaths.length === 0 && !combinedMatcher) {
3490
+ return undefined;
3491
+ }
3492
+ return infraHashes;
3493
+ }
3494
+ /**
3495
+ * Combines two optional matchers into one using OR logic.
3496
+ *
3497
+ * @param a - First matcher (may be null)
3498
+ * @param b - Second matcher (may be undefined)
3499
+ * @returns Combined matcher or null if neither provided
3500
+ */
3501
+ function combineMatcher(a, b) {
3502
+ if (a && b) {
3503
+ return (ctx) => a(ctx) || b(ctx);
3504
+ }
3505
+ return a ?? b ?? null;
3506
+ }
3507
+ /**
3508
+ * Builds a map of dependency project names to the commit hashes that touched them.
3509
+ *
3510
+ * This enables accurate indirect-dependency classification by verifying that:
3511
+ * 1. A commit's scope matches a dependency name
3512
+ * 2. The commit actually touched that dependency's files (hash in set)
3513
+ *
3514
+ * Uses lib-project-scope for dependency discovery, avoiding hard NX dependency.
3515
+ *
3516
+ * @param git - Git client for querying commits by path
3517
+ * @param workspaceRoot - Absolute path to workspace root
3518
+ * @param projectName - Name of the project being versioned
3519
+ * @param baseCommit - Base commit hash for commit range (null for first release/fallback)
3520
+ * @param logger - Logger with debug method for output
3521
+ * @param logger.debug - Debug logging function
3522
+ * @returns Map of dependency names to commit hashes touching that dependency
3523
+ */
3524
+ function buildDependencyCommitMap(git, workspaceRoot, projectName, baseCommit, logger) {
3525
+ let dependencyMap = createMap();
3526
+ try {
3527
+ // Discover all projects in workspace using lib-project-scope
3528
+ // This gracefully handles NX and non-NX workspaces
3529
+ const projects = discoverNxProjects(workspaceRoot);
3530
+ const projectGraph = buildSimpleProjectGraph(workspaceRoot, projects);
3531
+ // Get dependencies for the current project
3532
+ const projectDeps = projectGraph.dependencies[projectName] ?? [];
3533
+ if (projectDeps.length === 0) {
3534
+ logger.debug(`No dependencies found for project: ${projectName}`);
3535
+ return dependencyMap;
3536
+ }
3537
+ logger.debug(`Found ${projectDeps.length} dependencies for ${projectName}: ${projectDeps.map((d) => d.target).join(', ')}`);
3538
+ // For each dependency, find commits that touched its files
3539
+ for (const dep of projectDeps) {
3540
+ const depNode = projectGraph.nodes[dep.target];
3541
+ if (!depNode?.data?.root) {
3542
+ logger.debug(`Skipping dependency ${dep.target}: no root path found`);
3543
+ continue;
3544
+ }
3545
+ const depRoot = depNode.data.root;
3546
+ // Query git for commits touching this dependency's path
3547
+ const depCommits = baseCommit
3548
+ ? git.getCommitsSince(baseCommit, { path: depRoot })
3549
+ : git.getCommitLog({ maxCount: 100, path: depRoot });
3550
+ if (depCommits.length > 0) {
3551
+ const hashSet = createSet(depCommits.map((c) => c.hash));
3552
+ dependencyMap = dependencyMap.set(dep.target, hashSet);
3553
+ logger.debug(`Dependency ${dep.target}: ${depCommits.length} commits at ${depRoot}`);
630
3554
  }
631
3555
  }
632
- const message = commits.length > 0
633
- ? `Found ${commits.length} releasable commits (${rawCommits.length} total)`
634
- : `No releasable commits found (${rawCommits.length} total)`;
635
- return {
636
- status: 'success',
637
- stateUpdates: {
638
- lastReleaseTag,
639
- commits,
640
- },
641
- message,
642
- };
643
- }, {
644
- dependsOn: ['fetch-registry'],
645
- });
3556
+ }
3557
+ catch (error) {
3558
+ // Graceful degradation: if project discovery fails, return empty map
3559
+ // This allows versioning to proceed without dependency tracking
3560
+ const message = error instanceof Error ? error.message : String(error);
3561
+ logger.debug(`Failed to build dependency map: ${message}`);
3562
+ }
3563
+ return dependencyMap;
3564
+ }
3565
+
3566
+ /**
3567
+ * Safe copies of Number built-in methods and constants.
3568
+ *
3569
+ * These references are captured at module initialization time to protect against
3570
+ * prototype pollution attacks. Import only what you need for tree-shaking.
3571
+ *
3572
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/number
3573
+ */
3574
+ // Capture references at module initialization time
3575
+ const _parseInt = globalThis.parseInt;
3576
+ const _isNaN = globalThis.isNaN;
3577
+ // ============================================================================
3578
+ // Parsing
3579
+ // ============================================================================
3580
+ /**
3581
+ * (Safe copy) Parses a string and returns an integer.
3582
+ */
3583
+ const parseInt = _parseInt;
3584
+ // ============================================================================
3585
+ // Global Type Checking (legacy, less strict)
3586
+ // ============================================================================
3587
+ /**
3588
+ * (Safe copy) Global isNaN function (coerces to number first, less strict than Number.isNaN).
3589
+ */
3590
+ const globalIsNaN = _isNaN;
3591
+
3592
+ /**
3593
+ * Compares two semantic versions.
3594
+ *
3595
+ * @param a - First version
3596
+ * @param b - Second version
3597
+ * @returns -1 if a < b, 0 if a == b, 1 if a > b
3598
+ *
3599
+ * @example
3600
+ * compare(parseVersion('1.0.0'), parseVersion('2.0.0')) // -1
3601
+ * compare(parseVersion('1.0.0'), parseVersion('1.0.0')) // 0
3602
+ * compare(parseVersion('2.0.0'), parseVersion('1.0.0')) // 1
3603
+ */
3604
+ function compare(a, b) {
3605
+ // Compare major, minor, patch
3606
+ if (a.major !== b.major) {
3607
+ return a.major < b.major ? -1 : 1;
3608
+ }
3609
+ if (a.minor !== b.minor) {
3610
+ return a.minor < b.minor ? -1 : 1;
3611
+ }
3612
+ if (a.patch !== b.patch) {
3613
+ return a.patch < b.patch ? -1 : 1;
3614
+ }
3615
+ // Compare prerelease
3616
+ // Version with prerelease has lower precedence than release
3617
+ if (a.prerelease.length === 0 && b.prerelease.length > 0) {
3618
+ return 1; // a is release, b is prerelease -> a > b
3619
+ }
3620
+ if (a.prerelease.length > 0 && b.prerelease.length === 0) {
3621
+ return -1; // a is prerelease, b is release -> a < b
3622
+ }
3623
+ // Both have prerelease - compare identifiers
3624
+ const maxLen = max(a.prerelease.length, b.prerelease.length);
3625
+ for (let i = 0; i < maxLen; i++) {
3626
+ const aId = a.prerelease[i];
3627
+ const bId = b.prerelease[i];
3628
+ // Shorter prerelease array has lower precedence
3629
+ if (aId === undefined && bId !== undefined) {
3630
+ return -1;
3631
+ }
3632
+ if (aId !== undefined && bId === undefined) {
3633
+ return 1;
3634
+ }
3635
+ if (aId === undefined || bId === undefined) {
3636
+ continue;
3637
+ }
3638
+ // Compare identifiers
3639
+ const cmp = compareIdentifiers(aId, bId);
3640
+ if (cmp !== 0) {
3641
+ return cmp;
3642
+ }
3643
+ }
3644
+ return 0;
3645
+ }
3646
+ /**
3647
+ * Checks if a > b.
3648
+ *
3649
+ * @param a - First version to compare
3650
+ * @param b - Second version to compare
3651
+ * @returns True if a is greater than b
3652
+ */
3653
+ function gt(a, b) {
3654
+ return compare(a, b) === 1;
3655
+ }
3656
+ // ============================================================================
3657
+ // Internal helpers
3658
+ // ============================================================================
3659
+ /**
3660
+ * Compares two prerelease identifiers.
3661
+ * Numeric identifiers have lower precedence than alphanumeric.
3662
+ * Numeric identifiers are compared numerically.
3663
+ * Alphanumeric identifiers are compared lexically.
3664
+ *
3665
+ * @param a - First prerelease identifier
3666
+ * @param b - Second prerelease identifier
3667
+ * @returns -1 if a < b, 0 if equal, 1 if a > b
3668
+ */
3669
+ function compareIdentifiers(a, b) {
3670
+ const aIsNumeric = isNumeric(a);
3671
+ const bIsNumeric = isNumeric(b);
3672
+ // Numeric identifiers have lower precedence
3673
+ if (aIsNumeric && !bIsNumeric) {
3674
+ return -1;
3675
+ }
3676
+ if (!aIsNumeric && bIsNumeric) {
3677
+ return 1;
3678
+ }
3679
+ // Both numeric - compare as numbers
3680
+ if (aIsNumeric && bIsNumeric) {
3681
+ const aNum = parseInt(a, 10);
3682
+ const bNum = parseInt(b, 10);
3683
+ if (aNum < bNum)
3684
+ return -1;
3685
+ if (aNum > bNum)
3686
+ return 1;
3687
+ return 0;
3688
+ }
3689
+ // Both alphanumeric - compare lexically
3690
+ if (a < b)
3691
+ return -1;
3692
+ if (a > b)
3693
+ return 1;
3694
+ return 0;
3695
+ }
3696
+ /**
3697
+ * Checks if a string consists only of digits.
3698
+ *
3699
+ * @param str - String to check for numeric content
3700
+ * @returns True if string contains only digits
3701
+ */
3702
+ function isNumeric(str) {
3703
+ if (str.length === 0)
3704
+ return false;
3705
+ for (let i = 0; i < str.length; i++) {
3706
+ const code = str.charCodeAt(i);
3707
+ if (code < 48 || code > 57) {
3708
+ return false;
3709
+ }
3710
+ }
3711
+ return true;
646
3712
  }
647
3713
 
648
3714
  /**
@@ -662,32 +3728,6 @@ function format(version) {
662
3728
  return result;
663
3729
  }
664
3730
 
665
- /**
666
- * Safe copies of Number built-in methods and constants.
667
- *
668
- * These references are captured at module initialization time to protect against
669
- * prototype pollution attacks. Import only what you need for tree-shaking.
670
- *
671
- * @module @hyperfrontend/immutable-api-utils/built-in-copy/number
672
- */
673
- // Capture references at module initialization time
674
- const _parseInt = globalThis.parseInt;
675
- const _isNaN = globalThis.isNaN;
676
- // ============================================================================
677
- // Parsing
678
- // ============================================================================
679
- /**
680
- * (Safe copy) Parses a string and returns an integer.
681
- */
682
- const parseInt = _parseInt;
683
- // ============================================================================
684
- // Global Type Checking (legacy, less strict)
685
- // ============================================================================
686
- /**
687
- * (Safe copy) Global isNaN function (coerces to number first, less strict than Number.isNaN).
688
- */
689
- const globalIsNaN = _isNaN;
690
-
691
3731
  /**
692
3732
  * Creates a new SemVer object.
693
3733
  *
@@ -1165,7 +4205,7 @@ function createCalculateBumpStep() {
1165
4205
  message: 'No version bump needed',
1166
4206
  };
1167
4207
  }
1168
- // Calculate next version
4208
+ // Parse versions for comparison
1169
4209
  const current = parseVersion(currentVersion ?? '0.0.0');
1170
4210
  if (!current.success || !current.version) {
1171
4211
  return {
@@ -1174,6 +4214,27 @@ function createCalculateBumpStep() {
1174
4214
  message: `Could not parse current version: ${currentVersion}`,
1175
4215
  };
1176
4216
  }
4217
+ const { publishedVersion } = state;
4218
+ const published = parseVersion(publishedVersion ?? '0.0.0');
4219
+ // Detect pending publication state: currentVersion > publishedVersion
4220
+ // This means a previous bump happened but was never published
4221
+ const isPendingPublication = published.success && published.version && publishedVersion != null && gt(current.version, published.version);
4222
+ if (isPendingPublication && published.version) {
4223
+ // ALWAYS calculate from publishedVersion - commits may have changed
4224
+ const next = increment(published.version, bumpType);
4225
+ const nextVersion = format(next);
4226
+ logger.info(`Pending publication detected: recalculating from ${publishedVersion} → ${nextVersion}`);
4227
+ return {
4228
+ status: 'success',
4229
+ stateUpdates: {
4230
+ bumpType,
4231
+ nextVersion,
4232
+ isPendingPublication: true,
4233
+ },
4234
+ message: `${bumpType} bump (pending): ${publishedVersion} → ${nextVersion}`,
4235
+ };
4236
+ }
4237
+ // Normal path: increment from currentVersion
1177
4238
  const next = increment(current.version, bumpType);
1178
4239
  const nextVersion = format(next);
1179
4240
  return {
@@ -1228,24 +4289,6 @@ function createCheckIdempotencyStep() {
1228
4289
  });
1229
4290
  }
1230
4291
 
1231
- /**
1232
- * Safe copies of Date built-in via factory function and static methods.
1233
- *
1234
- * Since constructors cannot be safely captured via Object.assign, this module
1235
- * provides a factory function that uses Reflect.construct internally.
1236
- *
1237
- * These references are captured at module initialization time to protect against
1238
- * prototype pollution attacks. Import only what you need for tree-shaking.
1239
- *
1240
- * @module @hyperfrontend/immutable-api-utils/built-in-copy/date
1241
- */
1242
- // Capture references at module initialization time
1243
- const _Date = globalThis.Date;
1244
- const _Reflect$1 = globalThis.Reflect;
1245
- function createDate(...args) {
1246
- return _Reflect$1.construct(_Date, args);
1247
- }
1248
-
1249
4292
  /**
1250
4293
  * Creates a new changelog item.
1251
4294
  *
@@ -1260,6 +4303,8 @@ function createChangelogItem(description, options) {
1260
4303
  commits: options?.commits ?? [],
1261
4304
  references: options?.references ?? [],
1262
4305
  breaking: options?.breaking ?? false,
4306
+ source: options?.source,
4307
+ indirect: options?.indirect,
1263
4308
  };
1264
4309
  }
1265
4310
  /**
@@ -1383,96 +4428,6 @@ function getSectionType(heading) {
1383
4428
  return SECTION_TYPE_MAP[normalized] ?? 'other';
1384
4429
  }
1385
4430
 
1386
- /**
1387
- * Safe copies of Map built-in via factory function.
1388
- *
1389
- * Since constructors cannot be safely captured via Object.assign, this module
1390
- * provides a factory function that uses Reflect.construct internally.
1391
- *
1392
- * These references are captured at module initialization time to protect against
1393
- * prototype pollution attacks. Import only what you need for tree-shaking.
1394
- *
1395
- * @module @hyperfrontend/immutable-api-utils/built-in-copy/map
1396
- */
1397
- // Capture references at module initialization time
1398
- const _Map = globalThis.Map;
1399
- const _Reflect = globalThis.Reflect;
1400
- /**
1401
- * (Safe copy) Creates a new Map using the captured Map constructor.
1402
- * Use this instead of `new Map()`.
1403
- *
1404
- * @param iterable - Optional iterable of key-value pairs.
1405
- * @returns A new Map instance.
1406
- */
1407
- const createMap = (iterable) => _Reflect.construct(_Map, iterable ? [iterable] : []);
1408
-
1409
- /**
1410
- * Safe copies of Object built-in methods.
1411
- *
1412
- * These references are captured at module initialization time to protect against
1413
- * prototype pollution attacks. Import only what you need for tree-shaking.
1414
- *
1415
- * @module @hyperfrontend/immutable-api-utils/built-in-copy/object
1416
- */
1417
- // Capture references at module initialization time
1418
- const _Object = globalThis.Object;
1419
- /**
1420
- * (Safe copy) Returns an array of key/values of the enumerable own properties of an object.
1421
- */
1422
- const entries = _Object.entries;
1423
-
1424
- /**
1425
- * Safe copies of URL built-ins via factory functions.
1426
- *
1427
- * Provides safe references to URL and URLSearchParams.
1428
- * These references are captured at module initialization time to protect against
1429
- * prototype pollution attacks. Import only what you need for tree-shaking.
1430
- *
1431
- * @module @hyperfrontend/immutable-api-utils/built-in-copy/url
1432
- */
1433
- // Capture references at module initialization time
1434
- const _URL = globalThis.URL;
1435
- /**
1436
- * (Safe copy) Creates an object URL for the given object.
1437
- * Use this instead of `URL.createObjectURL()`.
1438
- *
1439
- * Note: This is a browser-only API. In Node.js environments, this will throw.
1440
- */
1441
- typeof _URL.createObjectURL === 'function'
1442
- ? _URL.createObjectURL.bind(_URL)
1443
- : () => {
1444
- throw new Error('URL.createObjectURL is not available in this environment');
1445
- };
1446
- /**
1447
- * (Safe copy) Revokes an object URL previously created with createObjectURL.
1448
- * Use this instead of `URL.revokeObjectURL()`.
1449
- *
1450
- * Note: This is a browser-only API. In Node.js environments, this will throw.
1451
- */
1452
- typeof _URL.revokeObjectURL === 'function'
1453
- ? _URL.revokeObjectURL.bind(_URL)
1454
- : () => {
1455
- throw new Error('URL.revokeObjectURL is not available in this environment');
1456
- };
1457
-
1458
- /**
1459
- * Safe copies of Math built-in methods.
1460
- *
1461
- * These references are captured at module initialization time to protect against
1462
- * prototype pollution attacks. Import only what you need for tree-shaking.
1463
- *
1464
- * @module @hyperfrontend/immutable-api-utils/built-in-copy/math
1465
- */
1466
- // Capture references at module initialization time
1467
- const _Math = globalThis.Math;
1468
- // ============================================================================
1469
- // Min/Max
1470
- // ============================================================================
1471
- /**
1472
- * (Safe copy) Returns the larger of zero or more numbers.
1473
- */
1474
- const max = _Math.max;
1475
-
1476
4431
  /**
1477
4432
  * Line Parser
1478
4433
  *
@@ -1528,6 +4483,25 @@ function parseVersionFromHeading(heading) {
1528
4483
  if (trimmed[pos] === ']') {
1529
4484
  pos++;
1530
4485
  }
4486
+ // Handle markdown link format [version](url) - jscutlery/semver style
4487
+ // This extracts the compare URL from patterns like [0.0.4](https://github.com/.../compare/...)
4488
+ if (trimmed[pos] === '(') {
4489
+ const urlStart = pos + 1;
4490
+ let depth = 1;
4491
+ pos++;
4492
+ // Find matching closing parenthesis (handles nested parens in URLs)
4493
+ while (pos < trimmed.length && depth > 0) {
4494
+ if (trimmed[pos] === '(')
4495
+ depth++;
4496
+ else if (trimmed[pos] === ')')
4497
+ depth--;
4498
+ pos++;
4499
+ }
4500
+ // Extract URL if we found the closing paren
4501
+ if (depth === 0) {
4502
+ compareUrl = trimmed.slice(urlStart, pos - 1);
4503
+ }
4504
+ }
1531
4505
  // Skip whitespace and separator
1532
4506
  while (pos < trimmed.length && (trimmed[pos] === ' ' || trimmed[pos] === '-' || trimmed[pos] === '–')) {
1533
4507
  pos++;
@@ -1544,8 +4518,8 @@ function parseVersionFromHeading(heading) {
1544
4518
  while (pos < trimmed.length && trimmed[pos] === ' ') {
1545
4519
  pos++;
1546
4520
  }
1547
- // Check for link at end: [compare](url)
1548
- if (pos < trimmed.length) {
4521
+ // Check for link at end: [compare](url) - only if no URL was already extracted
4522
+ if (pos < trimmed.length && !compareUrl) {
1549
4523
  const linkMatch = extractLink(trimmed.slice(pos));
1550
4524
  if (linkMatch?.url) {
1551
4525
  compareUrl = linkMatch.url;
@@ -2942,20 +5916,28 @@ function serializeIssueRef(ref) {
2942
5916
  * ```
2943
5917
  */
2944
5918
  function addEntry(changelog, entry, options) {
5919
+ const position = options?.position ?? 'start';
5920
+ const replaceExisting = options?.replaceExisting ?? false;
5921
+ const updateMetadata = options?.updateMetadata ?? false;
2945
5922
  // Check for existing entry
2946
5923
  const existingIndex = changelog.entries.findIndex((e) => e.version === entry.version);
2947
- if (existingIndex !== -1 && true) {
5924
+ if (existingIndex !== -1 && !replaceExisting) {
2948
5925
  throw createError(`Entry with version "${entry.version}" already exists. Use replaceExisting: true to replace.`);
2949
5926
  }
2950
5927
  let newEntries;
2951
- {
5928
+ if (existingIndex !== -1 && replaceExisting) {
5929
+ // Replace existing entry
5930
+ newEntries = [...changelog.entries];
5931
+ newEntries[existingIndex] = entry;
5932
+ }
5933
+ else {
2952
5934
  // Add new entry
2953
- const insertIndex = 0 ;
5935
+ const insertIndex = position === 'start' ? 0 : position === 'end' ? changelog.entries.length : position;
2954
5936
  newEntries = [...changelog.entries];
2955
5937
  newEntries.splice(insertIndex, 0, entry);
2956
5938
  }
2957
5939
  // Build new metadata if requested
2958
- const metadata = changelog.metadata;
5940
+ const metadata = updateMetadata ? { ...changelog.metadata, warnings: [] } : changelog.metadata;
2959
5941
  return {
2960
5942
  ...changelog,
2961
5943
  entries: newEntries,
@@ -2963,6 +5945,144 @@ function addEntry(changelog, entry, options) {
2963
5945
  };
2964
5946
  }
2965
5947
 
5948
+ /**
5949
+ * Changelog Entry Removal
5950
+ *
5951
+ * Functions for removing entries from a changelog.
5952
+ */
5953
+ /**
5954
+ * Removes multiple entries from a changelog.
5955
+ *
5956
+ * @param changelog - The changelog to remove from
5957
+ * @param versions - The versions to remove
5958
+ * @param options - Optional removal options
5959
+ * @returns A new changelog without the specified entries
5960
+ */
5961
+ function removeEntries(changelog, versions, options) {
5962
+ const versionsSet = createSet(versions);
5963
+ const newEntries = changelog.entries.filter((e) => !versionsSet.has(e.version));
5964
+ return {
5965
+ ...changelog,
5966
+ entries: newEntries,
5967
+ };
5968
+ }
5969
+
5970
+ /**
5971
+ * Creates a platform-specific compare URL for viewing changes between two commits.
5972
+ *
5973
+ * Each platform has a different URL format:
5974
+ * - **GitHub**: `{baseUrl}/compare/{fromCommit}...{toCommit}` (three dots)
5975
+ * - **GitLab**: `{baseUrl}/-/compare/{fromCommit}...{toCommit}` (three dots, `/-/` prefix)
5976
+ * - **Bitbucket**: `{baseUrl}/compare/{toCommit}..{fromCommit}` (two dots, reversed order)
5977
+ * - **Azure DevOps**: `{baseUrl}/compare?version=GT{toCommit}&compareVersion=GT{fromCommit}` (query params)
5978
+ *
5979
+ * For `custom` platforms, a `formatCompareUrl` function must be provided in the repository config.
5980
+ * For `unknown` platforms, returns `null`.
5981
+ *
5982
+ * @param options - Compare URL options including repository, fromCommit, and toCommit
5983
+ * @returns The compare URL string, or null if URL cannot be generated
5984
+ *
5985
+ * @example
5986
+ * ```typescript
5987
+ * // GitHub
5988
+ * createCompareUrl({
5989
+ * repository: { platform: 'github', baseUrl: 'https://github.com/owner/repo' },
5990
+ * fromCommit: 'abc1234',
5991
+ * toCommit: 'def5678'
5992
+ * })
5993
+ * // → 'https://github.com/owner/repo/compare/abc1234...def5678'
5994
+ *
5995
+ * // GitLab
5996
+ * createCompareUrl({
5997
+ * repository: { platform: 'gitlab', baseUrl: 'https://gitlab.com/group/project' },
5998
+ * fromCommit: 'abc1234',
5999
+ * toCommit: 'def5678'
6000
+ * })
6001
+ * // → 'https://gitlab.com/group/project/-/compare/abc1234...def5678'
6002
+ *
6003
+ * // Bitbucket (reversed order)
6004
+ * createCompareUrl({
6005
+ * repository: { platform: 'bitbucket', baseUrl: 'https://bitbucket.org/owner/repo' },
6006
+ * fromCommit: 'abc1234',
6007
+ * toCommit: 'def5678'
6008
+ * })
6009
+ * // → 'https://bitbucket.org/owner/repo/compare/def5678..abc1234'
6010
+ *
6011
+ * // Azure DevOps
6012
+ * createCompareUrl({
6013
+ * repository: { platform: 'azure-devops', baseUrl: 'https://dev.azure.com/org/proj/_git/repo' },
6014
+ * fromCommit: 'abc1234',
6015
+ * toCommit: 'def5678'
6016
+ * })
6017
+ * // → 'https://dev.azure.com/org/proj/_git/repo/compare?version=GTdef5678&compareVersion=GTabc1234'
6018
+ *
6019
+ * // Custom formatter
6020
+ * createCompareUrl({
6021
+ * repository: {
6022
+ * platform: 'custom',
6023
+ * baseUrl: 'https://my-git.internal/repo',
6024
+ * formatCompareUrl: (from, to) => `https://my-git.internal/diff/${from}/${to}`
6025
+ * },
6026
+ * fromCommit: 'abc1234',
6027
+ * toCommit: 'def5678'
6028
+ * })
6029
+ * // → 'https://my-git.internal/diff/abc1234/def5678'
6030
+ * ```
6031
+ */
6032
+ function createCompareUrl(options) {
6033
+ const { repository, fromCommit, toCommit } = options;
6034
+ // Validate inputs
6035
+ if (!repository || !fromCommit || !toCommit) {
6036
+ return null;
6037
+ }
6038
+ // If custom formatter is provided, use it (works for any platform including overrides)
6039
+ if (repository.formatCompareUrl) {
6040
+ return repository.formatCompareUrl(fromCommit, toCommit);
6041
+ }
6042
+ const { platform, baseUrl } = repository;
6043
+ // Cannot generate URL for unknown platforms without a formatter
6044
+ if (platform === 'unknown') {
6045
+ return null;
6046
+ }
6047
+ // Custom platform requires a formatter
6048
+ if (platform === 'custom') {
6049
+ return null;
6050
+ }
6051
+ // Generate URL for known platforms
6052
+ if (isKnownPlatform(platform)) {
6053
+ return formatKnownPlatformCompareUrl(platform, baseUrl, fromCommit, toCommit);
6054
+ }
6055
+ return null;
6056
+ }
6057
+ /**
6058
+ * Formats a compare URL for known platforms.
6059
+ *
6060
+ * @param platform - Known platform type
6061
+ * @param baseUrl - Repository base URL
6062
+ * @param fromCommit - Source commit hash (older version)
6063
+ * @param toCommit - Target commit hash (newer version)
6064
+ * @returns Formatted compare URL
6065
+ *
6066
+ * @internal
6067
+ */
6068
+ function formatKnownPlatformCompareUrl(platform, baseUrl, fromCommit, toCommit) {
6069
+ switch (platform) {
6070
+ case 'github':
6071
+ // GitHub: {baseUrl}/compare/{fromCommit}...{toCommit}
6072
+ return `${baseUrl}/compare/${fromCommit}...${toCommit}`;
6073
+ case 'gitlab':
6074
+ // GitLab: {baseUrl}/-/compare/{fromCommit}...{toCommit}
6075
+ return `${baseUrl}/-/compare/${fromCommit}...${toCommit}`;
6076
+ case 'bitbucket':
6077
+ // Bitbucket: {baseUrl}/compare/{toCommit}..{fromCommit} (reversed order, two dots)
6078
+ return `${baseUrl}/compare/${toCommit}..${fromCommit}`;
6079
+ case 'azure-devops':
6080
+ // Azure DevOps: {baseUrl}/compare?version=GT{toCommit}&compareVersion=GT{fromCommit}
6081
+ // Use encodeURIComponent for query parameter values
6082
+ return `${baseUrl}/compare?version=GT${encodeURIComponent(toCommit)}&compareVersion=GT${encodeURIComponent(fromCommit)}`;
6083
+ }
6084
+ }
6085
+
2966
6086
  const GENERATE_CHANGELOG_STEP_ID = 'generate-changelog';
2967
6087
  /**
2968
6088
  * Maps conventional commit types to changelog section types.
@@ -2980,6 +6100,32 @@ const COMMIT_TYPE_TO_SECTION = {
2980
6100
  chore: 'chores',
2981
6101
  style: 'other',
2982
6102
  };
6103
+ /**
6104
+ * Checks if a commit source represents an indirect change.
6105
+ *
6106
+ * @param source - The commit source type
6107
+ * @returns True if the commit is indirect (dependency or infrastructure)
6108
+ */
6109
+ function isIndirectSource(source) {
6110
+ return source === 'indirect-dependency' || source === 'indirect-infra';
6111
+ }
6112
+ /**
6113
+ * Groups classified commits by their section type.
6114
+ *
6115
+ * @param commits - Array of classified commits
6116
+ * @returns Record of section type to classified commits
6117
+ */
6118
+ function groupClassifiedCommitsBySection(commits) {
6119
+ const groups = {};
6120
+ for (const classified of commits) {
6121
+ const sectionType = COMMIT_TYPE_TO_SECTION[classified.commit.type ?? 'chore'] ?? 'chores';
6122
+ if (!groups[sectionType]) {
6123
+ groups[sectionType] = [];
6124
+ }
6125
+ groups[sectionType].push(classified);
6126
+ }
6127
+ return groups;
6128
+ }
2983
6129
  /**
2984
6130
  * Groups commits by their section type.
2985
6131
  *
@@ -2997,6 +6143,35 @@ function groupCommitsBySection(commits) {
2997
6143
  }
2998
6144
  return groups;
2999
6145
  }
6146
+ /**
6147
+ * Creates a changelog item from a classified commit.
6148
+ *
6149
+ * Applies scope display rules:
6150
+ * - Direct commits: scope omitted (redundant in project changelog)
6151
+ * - Indirect commits: scope preserved (provides context)
6152
+ *
6153
+ * @param classified - The classified commit with source metadata
6154
+ * @returns A changelog item with proper scope handling
6155
+ */
6156
+ function classifiedCommitToItem(classified) {
6157
+ // Apply scope transformation based on classification
6158
+ const commit = toChangelogCommit(classified);
6159
+ const indirect = isIndirectSource(classified.source);
6160
+ let text = commit.subject;
6161
+ // Add scope prefix if preserved (indirect commits)
6162
+ if (commit.scope) {
6163
+ text = `**${commit.scope}:** ${text}`;
6164
+ }
6165
+ // Add breaking change indicator
6166
+ if (commit.breaking) {
6167
+ text = `⚠️ BREAKING: ${text}`;
6168
+ }
6169
+ return createChangelogItem(text, {
6170
+ source: classified.source,
6171
+ indirect,
6172
+ breaking: commit.breaking,
6173
+ });
6174
+ }
3000
6175
  /**
3001
6176
  * Creates a changelog item from a conventional commit.
3002
6177
  *
@@ -3042,9 +6217,26 @@ function createGenerateChangelogStep() {
3042
6217
  }
3043
6218
  // Handle case with no commits (e.g., first release)
3044
6219
  if (!commits || commits.length === 0) {
6220
+ // Generate compare URL using commit hashes ONLY
6221
+ // Only generate if we have a valid base commit (effectiveBaseCommit will be null if fallback was used)
6222
+ let compareUrl;
6223
+ if (state.repositoryConfig && state.effectiveBaseCommit) {
6224
+ const currentCommit = ctx.git.getHeadHash();
6225
+ compareUrl =
6226
+ createCompareUrl({
6227
+ repository: state.repositoryConfig,
6228
+ fromCommit: state.effectiveBaseCommit,
6229
+ toCommit: currentCommit,
6230
+ }) ?? undefined;
6231
+ }
6232
+ else if (state.publishedCommit && !state.effectiveBaseCommit) {
6233
+ // Log why we're not generating a compare URL
6234
+ ctx.logger.info('Compare URL omitted: published commit not in current history');
6235
+ }
3045
6236
  const entry = createChangelogEntry(nextVersion, {
3046
6237
  date: createDate().toISOString().split('T')[0],
3047
6238
  sections: [createChangelogSection('features', 'Features', [createChangelogItem('Initial release')])],
6239
+ compareUrl,
3048
6240
  });
3049
6241
  return {
3050
6242
  status: 'success',
@@ -3052,41 +6244,109 @@ function createGenerateChangelogStep() {
3052
6244
  message: 'Generated initial release changelog entry',
3053
6245
  };
3054
6246
  }
3055
- // Group commits by section
3056
- const grouped = groupCommitsBySection(commits);
3057
- // Create sections
6247
+ // Use classification result when available for proper scope handling
6248
+ const { classificationResult } = state;
3058
6249
  const sections = [];
3059
- // Add breaking changes section first if any
3060
- const breakingCommits = commits.filter((c) => c.breaking);
3061
- if (breakingCommits.length > 0) {
3062
- sections.push(createChangelogSection('breaking', 'Breaking Changes', breakingCommits.map((c) => {
3063
- const text = c.breakingDescription ?? c.subject;
3064
- return createChangelogItem(c.scope ? `**${c.scope}:** ${text}` : text);
3065
- })));
3066
- }
3067
- // Add other sections in conventional order
3068
- const sectionOrder = [
3069
- { type: 'features', heading: 'Features' },
3070
- { type: 'fixes', heading: 'Bug Fixes' },
3071
- { type: 'performance', heading: 'Performance' },
3072
- { type: 'documentation', heading: 'Documentation' },
3073
- { type: 'refactoring', heading: 'Code Refactoring' },
3074
- { type: 'build', heading: 'Build' },
3075
- { type: 'ci', heading: 'Continuous Integration' },
3076
- { type: 'tests', heading: 'Tests' },
3077
- { type: 'chores', heading: 'Chores' },
3078
- { type: 'other', heading: 'Other' },
3079
- ];
3080
- for (const { type: sectionType, heading } of sectionOrder) {
3081
- const sectionCommits = grouped[sectionType];
3082
- if (sectionCommits && sectionCommits.length > 0) {
3083
- sections.push(createChangelogSection(sectionType, heading, sectionCommits.map(commitToItem)));
6250
+ if (classificationResult && classificationResult.included.length > 0) {
6251
+ // Use classified commits for proper scope display rules
6252
+ const classifiedCommits = classificationResult.included;
6253
+ // Separate direct and indirect commits
6254
+ const directCommits = classifiedCommits.filter((c) => !isIndirectSource(c.source));
6255
+ const indirectCommits = classifiedCommits.filter((c) => isIndirectSource(c.source));
6256
+ // Add breaking changes section first if any
6257
+ const breakingCommits = classifiedCommits.filter((c) => c.commit.breaking);
6258
+ if (breakingCommits.length > 0) {
6259
+ sections.push(createChangelogSection('breaking', 'Breaking Changes', breakingCommits.map((c) => {
6260
+ const commit = toChangelogCommit(c);
6261
+ const text = commit.breakingDescription ?? commit.subject;
6262
+ const indirect = isIndirectSource(c.source);
6263
+ return createChangelogItem(commit.scope ? `**${commit.scope}:** ${text}` : text, {
6264
+ source: c.source,
6265
+ indirect,
6266
+ breaking: true,
6267
+ });
6268
+ })));
6269
+ }
6270
+ // Group direct commits by section
6271
+ const groupedDirect = groupClassifiedCommitsBySection(directCommits);
6272
+ // Add other sections in conventional order (direct commits only)
6273
+ const sectionOrder = [
6274
+ { type: 'features', heading: 'Features' },
6275
+ { type: 'fixes', heading: 'Bug Fixes' },
6276
+ { type: 'performance', heading: 'Performance' },
6277
+ { type: 'documentation', heading: 'Documentation' },
6278
+ { type: 'refactoring', heading: 'Code Refactoring' },
6279
+ { type: 'build', heading: 'Build' },
6280
+ { type: 'ci', heading: 'Continuous Integration' },
6281
+ { type: 'tests', heading: 'Tests' },
6282
+ { type: 'chores', heading: 'Chores' },
6283
+ { type: 'other', heading: 'Other' },
6284
+ ];
6285
+ for (const { type: sectionType, heading } of sectionOrder) {
6286
+ const sectionCommits = groupedDirect[sectionType];
6287
+ if (sectionCommits && sectionCommits.length > 0) {
6288
+ sections.push(createChangelogSection(sectionType, heading, sectionCommits.map(classifiedCommitToItem)));
6289
+ }
6290
+ }
6291
+ // Add Dependency Updates section for indirect commits if any
6292
+ if (indirectCommits.length > 0) {
6293
+ sections.push(createChangelogSection('other', // Use 'other' as section type for dependency updates
6294
+ 'Dependency Updates', indirectCommits.map((c) => classifiedCommitToItem(c))));
6295
+ }
6296
+ }
6297
+ else {
6298
+ // Fallback: use commits without classification (backward compatibility)
6299
+ const grouped = groupCommitsBySection(commits);
6300
+ // Add breaking changes section first if any
6301
+ const breakingCommits = commits.filter((c) => c.breaking);
6302
+ if (breakingCommits.length > 0) {
6303
+ sections.push(createChangelogSection('breaking', 'Breaking Changes', breakingCommits.map((c) => {
6304
+ const text = c.breakingDescription ?? c.subject;
6305
+ return createChangelogItem(c.scope ? `**${c.scope}:** ${text}` : text);
6306
+ })));
6307
+ }
6308
+ // Add other sections in conventional order
6309
+ const sectionOrder = [
6310
+ { type: 'features', heading: 'Features' },
6311
+ { type: 'fixes', heading: 'Bug Fixes' },
6312
+ { type: 'performance', heading: 'Performance' },
6313
+ { type: 'documentation', heading: 'Documentation' },
6314
+ { type: 'refactoring', heading: 'Code Refactoring' },
6315
+ { type: 'build', heading: 'Build' },
6316
+ { type: 'ci', heading: 'Continuous Integration' },
6317
+ { type: 'tests', heading: 'Tests' },
6318
+ { type: 'chores', heading: 'Chores' },
6319
+ { type: 'other', heading: 'Other' },
6320
+ ];
6321
+ for (const { type: sectionType, heading } of sectionOrder) {
6322
+ const sectionCommits = grouped[sectionType];
6323
+ if (sectionCommits && sectionCommits.length > 0) {
6324
+ sections.push(createChangelogSection(sectionType, heading, sectionCommits.map(commitToItem)));
6325
+ }
3084
6326
  }
3085
6327
  }
6328
+ // Generate compare URL using commit hashes ONLY
6329
+ // Only generate if we have a valid base commit (effectiveBaseCommit will be null if fallback was used)
6330
+ let compareUrl;
6331
+ if (state.repositoryConfig && state.effectiveBaseCommit) {
6332
+ const currentCommit = ctx.git.getHeadHash();
6333
+ compareUrl =
6334
+ createCompareUrl({
6335
+ repository: state.repositoryConfig,
6336
+ fromCommit: state.effectiveBaseCommit,
6337
+ toCommit: currentCommit,
6338
+ }) ?? undefined;
6339
+ ctx.logger.debug(`Compare URL: ${state.effectiveBaseCommit.slice(0, 7)}...${currentCommit.slice(0, 7)}`);
6340
+ }
6341
+ else if (state.publishedCommit && !state.effectiveBaseCommit) {
6342
+ // Log why we're not generating a compare URL
6343
+ ctx.logger.info('Compare URL omitted: published commit not in current history');
6344
+ }
3086
6345
  // Create the entry
3087
6346
  const entry = createChangelogEntry(nextVersion, {
3088
6347
  date: createDate().toISOString().split('T')[0],
3089
6348
  sections,
6349
+ compareUrl,
3090
6350
  });
3091
6351
  return {
3092
6352
  status: 'success',
@@ -3142,7 +6402,28 @@ function createWriteChangelogStep() {
3142
6402
  }
3143
6403
  // Parse existing and add entry
3144
6404
  const existing = parseChangelog(existingContent);
3145
- const updated = addEntry(existing, changelogEntry);
6405
+ const isPendingPublication = state.isPendingPublication === true;
6406
+ let changelog = existing;
6407
+ // Clean up stacked entries when in pending publication state
6408
+ if (isPendingPublication && state.publishedVersion) {
6409
+ const publishedVer = parseVersion(state.publishedVersion);
6410
+ if (publishedVer.success && publishedVer.version) {
6411
+ const pubVer = publishedVer.version;
6412
+ const toRemove = changelog.entries
6413
+ .filter((e) => !e.unreleased)
6414
+ .filter((e) => {
6415
+ const ver = parseVersion(e.version);
6416
+ return ver.success && ver.version && gt(ver.version, pubVer);
6417
+ })
6418
+ .map((e) => e.version);
6419
+ if (toRemove.length > 0) {
6420
+ logger.info(`Removing stacked entries: ${toRemove.join(', ')}`);
6421
+ changelog = removeEntries(changelog, toRemove);
6422
+ }
6423
+ }
6424
+ }
6425
+ // Add entry (replaceExisting handles case where nextVersion entry already exists)
6426
+ const updated = addEntry(changelog, changelogEntry, { replaceExisting: isPendingPublication });
3146
6427
  const serialized = serializeChangelog(updated);
3147
6428
  tree.write(changelogPath, serialized);
3148
6429
  return {
@@ -3179,23 +6460,26 @@ function createUpdatePackageStep() {
3179
6460
  return createSkippedResult('No version bump needed');
3180
6461
  }
3181
6462
  const packageJsonPath = `${projectRoot}/package.json`;
6463
+ logger.debug(`Reading package.json from: ${packageJsonPath}`);
3182
6464
  // Read package.json
3183
6465
  let content;
3184
6466
  try {
3185
6467
  content = tree.read(packageJsonPath, 'utf-8') ?? '';
3186
6468
  if (!content) {
6469
+ logger.error(`package.json not found at ${packageJsonPath}`);
3187
6470
  return {
3188
6471
  status: 'failed',
3189
- error: createError('package.json not found'),
3190
- message: 'Could not read package.json',
6472
+ error: createError(`package.json not found at ${packageJsonPath}`),
6473
+ message: `Could not read package.json at ${packageJsonPath}`,
3191
6474
  };
3192
6475
  }
3193
6476
  }
3194
6477
  catch (error) {
6478
+ logger.error(`Failed to read package.json at ${packageJsonPath}: ${error}`);
3195
6479
  return {
3196
6480
  status: 'failed',
3197
6481
  error: error instanceof Error ? error : createError(String(error)),
3198
- message: 'Failed to read package.json',
6482
+ message: `Failed to read package.json at ${packageJsonPath}`,
3199
6483
  };
3200
6484
  }
3201
6485
  // Parse and update version
@@ -3500,5 +6784,5 @@ function createPushTagStep() {
3500
6784
  });
3501
6785
  }
3502
6786
 
3503
- export { ANALYZE_COMMITS_STEP_ID, CALCULATE_BUMP_STEP_ID, CREATE_COMMIT_STEP_ID, CREATE_TAG_STEP_ID, FETCH_REGISTRY_STEP_ID, GENERATE_CHANGELOG_STEP_ID, UPDATE_PACKAGES_STEP_ID, createAnalyzeCommitsStep, createCalculateBumpStep, createCascadeDependenciesStep, createCheckIdempotencyStep, createFetchRegistryStep, createGenerateChangelogStep, createGitCommitStep, createPushTagStep, createTagStep, createUpdatePackageStep, createWriteChangelogStep };
6787
+ export { ANALYZE_COMMITS_STEP_ID, CALCULATE_BUMP_STEP_ID, CREATE_COMMIT_STEP_ID, CREATE_TAG_STEP_ID, FETCH_REGISTRY_STEP_ID, GENERATE_CHANGELOG_STEP_ID, RESOLVE_REPOSITORY_STEP_ID, UPDATE_PACKAGES_STEP_ID, createAnalyzeCommitsStep, createCalculateBumpStep, createCascadeDependenciesStep, createCheckIdempotencyStep, createFetchRegistryStep, createGenerateChangelogStep, createGitCommitStep, createPushTagStep, createResolveRepositoryStep, createTagStep, createUpdatePackageStep, createWriteChangelogStep };
3504
6788
  //# sourceMappingURL=index.esm.js.map