@quenty/nevermore-cli 4.41.1 → 4.42.1-canary.783.30683193716.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 (207) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/args/global-args.d.ts +13 -0
  3. package/dist/args/global-args.d.ts.map +1 -1
  4. package/dist/commands/batch-command/batch-deploy-command.d.ts +3 -0
  5. package/dist/commands/batch-command/batch-deploy-command.d.ts.map +1 -1
  6. package/dist/commands/batch-command/batch-deploy-command.js +90 -1
  7. package/dist/commands/batch-command/batch-deploy-command.js.map +1 -1
  8. package/dist/commands/batch-command/batch-test-command.d.ts.map +1 -1
  9. package/dist/commands/batch-command/batch-test-command.js +25 -4
  10. package/dist/commands/batch-command/batch-test-command.js.map +1 -1
  11. package/dist/commands/deploy-command/deploy-init.js +1 -1
  12. package/dist/commands/deploy-command/deploy-init.js.map +1 -1
  13. package/dist/commands/deploy-command/index.d.ts +3 -0
  14. package/dist/commands/deploy-command/index.d.ts.map +1 -1
  15. package/dist/commands/deploy-command/index.js +297 -60
  16. package/dist/commands/deploy-command/index.js.map +1 -1
  17. package/dist/commands/deploy-command/select-target.js +1 -1
  18. package/dist/commands/deploy-command/select-target.js.map +1 -1
  19. package/dist/commands/deploy-command/version-command.d.ts.map +1 -1
  20. package/dist/commands/deploy-command/version-command.js +138 -12
  21. package/dist/commands/deploy-command/version-command.js.map +1 -1
  22. package/dist/commands/test-command/test-command.d.ts.map +1 -1
  23. package/dist/commands/test-command/test-command.js +23 -11
  24. package/dist/commands/test-command/test-command.js.map +1 -1
  25. package/dist/nevermore.js +17 -0
  26. package/dist/nevermore.js.map +1 -1
  27. package/dist/utils/batch/changed-packages-utils.d.ts +1 -1
  28. package/dist/utils/batch/changed-packages-utils.d.ts.map +1 -1
  29. package/dist/utils/batch/changed-packages-utils.js +1 -1
  30. package/dist/utils/batch/changed-packages-utils.js.map +1 -1
  31. package/dist/utils/build/base-place-resolver-factory.d.ts +25 -0
  32. package/dist/utils/build/base-place-resolver-factory.d.ts.map +1 -0
  33. package/dist/utils/build/base-place-resolver-factory.js +40 -0
  34. package/dist/utils/build/base-place-resolver-factory.js.map +1 -0
  35. package/dist/utils/build/build.d.ts +13 -2
  36. package/dist/utils/build/build.d.ts.map +1 -1
  37. package/dist/utils/build/build.js.map +1 -1
  38. package/dist/utils/build/upload.d.ts +1 -1
  39. package/dist/utils/build/upload.d.ts.map +1 -1
  40. package/dist/utils/deploy/deploy-metadata.d.ts +1 -1
  41. package/dist/utils/deploy/deploy-metadata.d.ts.map +1 -1
  42. package/dist/utils/job-context/base-job-context.d.ts +3 -1
  43. package/dist/utils/job-context/base-job-context.d.ts.map +1 -1
  44. package/dist/utils/job-context/base-job-context.js +45 -6
  45. package/dist/utils/job-context/base-job-context.js.map +1 -1
  46. package/dist/utils/job-context/batch-script-job-context.d.ts +6 -0
  47. package/dist/utils/job-context/batch-script-job-context.d.ts.map +1 -1
  48. package/dist/utils/job-context/batch-script-job-context.js +13 -0
  49. package/dist/utils/job-context/batch-script-job-context.js.map +1 -1
  50. package/dist/utils/job-context/cloud-job-context.d.ts +2 -1
  51. package/dist/utils/job-context/cloud-job-context.d.ts.map +1 -1
  52. package/dist/utils/job-context/cloud-job-context.js +2 -2
  53. package/dist/utils/job-context/cloud-job-context.js.map +1 -1
  54. package/dist/utils/job-context/local-job-context.d.ts +2 -1
  55. package/dist/utils/job-context/local-job-context.d.ts.map +1 -1
  56. package/dist/utils/job-context/local-job-context.js +2 -2
  57. package/dist/utils/job-context/local-job-context.js.map +1 -1
  58. package/dist/utils/open-cloud/open-cloud-client.d.ts +20 -2
  59. package/dist/utils/open-cloud/open-cloud-client.d.ts.map +1 -1
  60. package/dist/utils/open-cloud/open-cloud-client.js +78 -21
  61. package/dist/utils/open-cloud/open-cloud-client.js.map +1 -1
  62. package/dist/utils/open-cloud/open-cloud-client.test.js +89 -12
  63. package/dist/utils/open-cloud/open-cloud-client.test.js.map +1 -1
  64. package/dist/utils/testing/parsers/batch-log-parser.d.ts +13 -5
  65. package/dist/utils/testing/parsers/batch-log-parser.d.ts.map +1 -1
  66. package/dist/utils/testing/parsers/batch-log-parser.js +114 -68
  67. package/dist/utils/testing/parsers/batch-log-parser.js.map +1 -1
  68. package/dist/utils/testing/parsers/batch-log-parser.test.js +57 -5
  69. package/dist/utils/testing/parsers/batch-log-parser.test.js.map +1 -1
  70. package/dist/utils/testing/parsers/traceback-parser.d.ts +31 -0
  71. package/dist/utils/testing/parsers/traceback-parser.d.ts.map +1 -0
  72. package/dist/utils/testing/parsers/traceback-parser.js +91 -0
  73. package/dist/utils/testing/parsers/traceback-parser.js.map +1 -0
  74. package/dist/utils/testing/parsers/traceback-parser.test.d.ts +2 -0
  75. package/dist/utils/testing/parsers/traceback-parser.test.d.ts.map +1 -0
  76. package/dist/utils/testing/parsers/traceback-parser.test.js +45 -0
  77. package/dist/utils/testing/parsers/traceback-parser.test.js.map +1 -0
  78. package/dist/utils/testing/runner/combined-project-generator.d.ts +1 -1
  79. package/dist/utils/testing/runner/combined-project-generator.d.ts.map +1 -1
  80. package/dist/utils/testing/runner/test-runner.d.ts +9 -1
  81. package/dist/utils/testing/runner/test-runner.d.ts.map +1 -1
  82. package/dist/utils/testing/runner/test-runner.js +28 -3
  83. package/dist/utils/testing/runner/test-runner.js.map +1 -1
  84. package/dist/utils/testing/runner/test-runner.test.d.ts +2 -0
  85. package/dist/utils/testing/runner/test-runner.test.d.ts.map +1 -0
  86. package/dist/utils/testing/runner/test-runner.test.js +18 -0
  87. package/dist/utils/testing/runner/test-runner.test.js.map +1 -0
  88. package/dist/utils/testing/test-log-parser.d.ts +32 -1
  89. package/dist/utils/testing/test-log-parser.d.ts.map +1 -1
  90. package/dist/utils/testing/test-log-parser.js +53 -9
  91. package/dist/utils/testing/test-log-parser.js.map +1 -1
  92. package/dist/utils/testing/test-log-parser.test.d.ts +2 -0
  93. package/dist/utils/testing/test-log-parser.test.d.ts.map +1 -0
  94. package/dist/utils/testing/test-log-parser.test.js +56 -0
  95. package/dist/utils/testing/test-log-parser.test.js.map +1 -0
  96. package/dist/utils/watch/github-context.d.ts +50 -0
  97. package/dist/utils/watch/github-context.d.ts.map +1 -0
  98. package/dist/utils/watch/github-context.js +125 -0
  99. package/dist/utils/watch/github-context.js.map +1 -0
  100. package/dist/utils/watch/github-context.test.d.ts +2 -0
  101. package/dist/utils/watch/github-context.test.d.ts.map +1 -0
  102. package/dist/utils/watch/github-context.test.js +112 -0
  103. package/dist/utils/watch/github-context.test.js.map +1 -0
  104. package/dist/utils/watch/http-watch-registry.d.ts +40 -0
  105. package/dist/utils/watch/http-watch-registry.d.ts.map +1 -0
  106. package/dist/utils/watch/http-watch-registry.js +262 -0
  107. package/dist/utils/watch/http-watch-registry.js.map +1 -0
  108. package/dist/utils/watch/http-watch-registry.test.d.ts +2 -0
  109. package/dist/utils/watch/http-watch-registry.test.d.ts.map +1 -0
  110. package/dist/utils/watch/http-watch-registry.test.js +211 -0
  111. package/dist/utils/watch/http-watch-registry.test.js.map +1 -0
  112. package/dist/utils/watch/local-watch-loop.d.ts +50 -0
  113. package/dist/utils/watch/local-watch-loop.d.ts.map +1 -0
  114. package/dist/utils/watch/local-watch-loop.js +103 -0
  115. package/dist/utils/watch/local-watch-loop.js.map +1 -0
  116. package/dist/utils/watch/local-watch-loop.test.d.ts +2 -0
  117. package/dist/utils/watch/local-watch-loop.test.d.ts.map +1 -0
  118. package/dist/utils/watch/local-watch-loop.test.js +170 -0
  119. package/dist/utils/watch/local-watch-loop.test.js.map +1 -0
  120. package/dist/utils/watch/register-notify-watches.d.ts +41 -0
  121. package/dist/utils/watch/register-notify-watches.d.ts.map +1 -0
  122. package/dist/utils/watch/register-notify-watches.js +159 -0
  123. package/dist/utils/watch/register-notify-watches.js.map +1 -0
  124. package/dist/utils/watch/register-notify-watches.test.d.ts +2 -0
  125. package/dist/utils/watch/register-notify-watches.test.d.ts.map +1 -0
  126. package/dist/utils/watch/register-notify-watches.test.js +225 -0
  127. package/dist/utils/watch/register-notify-watches.test.js.map +1 -0
  128. package/dist/utils/watch/register-watches.d.ts +68 -0
  129. package/dist/utils/watch/register-watches.d.ts.map +1 -0
  130. package/dist/utils/watch/register-watches.js +221 -0
  131. package/dist/utils/watch/register-watches.js.map +1 -0
  132. package/dist/utils/watch/register-watches.test.d.ts +2 -0
  133. package/dist/utils/watch/register-watches.test.d.ts.map +1 -0
  134. package/dist/utils/watch/register-watches.test.js +576 -0
  135. package/dist/utils/watch/register-watches.test.js.map +1 -0
  136. package/dist/utils/watch/stream-watch-loop.d.ts +54 -0
  137. package/dist/utils/watch/stream-watch-loop.d.ts.map +1 -0
  138. package/dist/utils/watch/stream-watch-loop.js +282 -0
  139. package/dist/utils/watch/stream-watch-loop.js.map +1 -0
  140. package/dist/utils/watch/stream-watch-loop.test.d.ts +2 -0
  141. package/dist/utils/watch/stream-watch-loop.test.d.ts.map +1 -0
  142. package/dist/utils/watch/stream-watch-loop.test.js +392 -0
  143. package/dist/utils/watch/stream-watch-loop.test.js.map +1 -0
  144. package/dist/utils/watch/websocket-watch-stream.d.ts +25 -0
  145. package/dist/utils/watch/websocket-watch-stream.d.ts.map +1 -0
  146. package/dist/utils/watch/websocket-watch-stream.js +306 -0
  147. package/dist/utils/watch/websocket-watch-stream.js.map +1 -0
  148. package/dist/utils/watch/websocket-watch-stream.test.d.ts +2 -0
  149. package/dist/utils/watch/websocket-watch-stream.test.d.ts.map +1 -0
  150. package/dist/utils/watch/websocket-watch-stream.test.js +475 -0
  151. package/dist/utils/watch/websocket-watch-stream.test.js.map +1 -0
  152. package/package.json +7 -4
  153. package/src/args/global-args.ts +13 -0
  154. package/src/commands/batch-command/batch-deploy-command.ts +105 -1
  155. package/src/commands/batch-command/batch-test-command.ts +86 -60
  156. package/src/commands/deploy-command/deploy-init.ts +1 -1
  157. package/src/commands/deploy-command/index.ts +327 -32
  158. package/src/commands/deploy-command/select-target.ts +1 -1
  159. package/src/commands/deploy-command/version-command.ts +215 -21
  160. package/src/commands/test-command/test-command.ts +31 -22
  161. package/src/nevermore.ts +19 -0
  162. package/src/utils/batch/changed-packages-utils.ts +1 -1
  163. package/src/utils/build/base-place-resolver-factory.ts +49 -0
  164. package/src/utils/build/build.ts +13 -2
  165. package/src/utils/build/upload.ts +1 -1
  166. package/src/utils/deploy/deploy-metadata.ts +1 -1
  167. package/src/utils/job-context/base-job-context.ts +68 -6
  168. package/src/utils/job-context/batch-script-job-context.ts +18 -0
  169. package/src/utils/job-context/cloud-job-context.ts +7 -2
  170. package/src/utils/job-context/local-job-context.ts +7 -2
  171. package/src/utils/open-cloud/open-cloud-client.test.ts +133 -14
  172. package/src/utils/open-cloud/open-cloud-client.ts +131 -35
  173. package/src/utils/testing/parsers/batch-log-parser.test.ts +70 -5
  174. package/src/utils/testing/parsers/batch-log-parser.ts +141 -80
  175. package/src/utils/testing/parsers/traceback-parser.test.ts +64 -0
  176. package/src/utils/testing/parsers/traceback-parser.ts +122 -0
  177. package/src/utils/testing/runner/combined-project-generator.ts +1 -1
  178. package/src/utils/testing/runner/test-runner.test.ts +29 -0
  179. package/src/utils/testing/runner/test-runner.ts +36 -4
  180. package/src/utils/testing/test-log-parser.test.ts +70 -0
  181. package/src/utils/testing/test-log-parser.ts +80 -10
  182. package/src/utils/watch/github-context.test.ts +154 -0
  183. package/src/utils/watch/github-context.ts +184 -0
  184. package/src/utils/watch/http-watch-registry.test.ts +330 -0
  185. package/src/utils/watch/http-watch-registry.ts +341 -0
  186. package/src/utils/watch/local-watch-loop.test.ts +197 -0
  187. package/src/utils/watch/local-watch-loop.ts +190 -0
  188. package/src/utils/watch/register-notify-watches.test.ts +282 -0
  189. package/src/utils/watch/register-notify-watches.ts +226 -0
  190. package/src/utils/watch/register-watches.test.ts +696 -0
  191. package/src/utils/watch/register-watches.ts +369 -0
  192. package/src/utils/watch/stream-watch-loop.test.ts +625 -0
  193. package/src/utils/watch/stream-watch-loop.ts +411 -0
  194. package/src/utils/watch/websocket-watch-stream.test.ts +581 -0
  195. package/src/utils/watch/websocket-watch-stream.ts +403 -0
  196. package/tsconfig.json +19 -6
  197. package/tsconfig.tsbuildinfo +1 -1
  198. package/dist/utils/build/deploy-config.d.ts +0 -71
  199. package/dist/utils/build/deploy-config.d.ts.map +0 -1
  200. package/dist/utils/build/deploy-config.js +0 -164
  201. package/dist/utils/build/deploy-config.js.map +0 -1
  202. package/dist/utils/build/deploy-config.test.d.ts +0 -2
  203. package/dist/utils/build/deploy-config.test.d.ts.map +0 -1
  204. package/dist/utils/build/deploy-config.test.js +0 -126
  205. package/dist/utils/build/deploy-config.test.js.map +0 -1
  206. package/src/utils/build/deploy-config.test.ts +0 -149
  207. package/src/utils/build/deploy-config.ts +0 -259
@@ -10,27 +10,97 @@ export interface ParsedTestLogs {
10
10
  success: boolean;
11
11
  logs: string;
12
12
  testCounts?: ParsedTestCounts;
13
+ /** Why the run is not a pass. Empty when it is. */
14
+ failureReasons: string[];
15
+ }
16
+
17
+ export interface TestOutcomeOptions {
18
+ /**
19
+ * Require proof the runner ran. Off for probe scripts (--script-text), which
20
+ * legitimately produce no jest report.
21
+ */
22
+ requireTestReport?: boolean;
13
23
  }
14
24
 
15
25
  /**
16
- * Analyze test output for Jest failures and Luau runtime errors.
17
- * Shared by both Open Cloud log fetching and local run-in-roblox output.
26
+ * Decide whether test output represents a pass, and say why when it does not.
27
+ *
28
+ * The single definition of the rule. Both the single-package path and the batch
29
+ * path route through here — they previously carried divergent copies that
30
+ * disagreed about tracebacks, so the same commit could pass one and fail the
31
+ * other.
18
32
  */
19
- export function parseTestLogs(rawOutput: string): ParsedTestLogs {
33
+ export function evaluateTestOutcome(
34
+ rawOutput: string,
35
+ options: TestOutcomeOptions = {}
36
+ ): { success: boolean; failureReasons: string[] } {
20
37
  const cleanLogs = OutputHelper.stripAnsi(rawOutput);
38
+ const failureReasons: string[] = [];
21
39
 
22
- // Check for Jest-style test failures
23
40
  const failedSuites = cleanLogs.match(/Test Suites:\s*(\d+)\s+failed/);
24
41
  const failedTests = cleanLogs.match(/Tests:\s*(\d+)\s+failed/);
25
- const hasJestFailures =
26
- (failedSuites && parseInt(failedSuites[1], 10) > 0) ||
27
- (failedTests && parseInt(failedTests[1], 10) > 0);
42
+ if (failedSuites && parseInt(failedSuites[1], 10) > 0) {
43
+ failureReasons.push(`${failedSuites[1]} test suite(s) failed`);
44
+ }
45
+ if (failedTests && parseInt(failedTests[1], 10) > 0) {
46
+ failureReasons.push(`${failedTests[1]} test(s) failed`);
47
+ }
48
+
49
+ // Tracebacks always fail. They catch use-after-free bugs that jest cannot
50
+ // see, since a deferred-callback crash fires outside any test.
51
+ const tracebacks = countTracebacks(cleanLogs);
52
+ if (tracebacks > 0) {
53
+ failureReasons.push(
54
+ `${tracebacks} Luau traceback(s) — see attributed errors below`
55
+ );
56
+ }
28
57
 
29
- // Check for Luau runtime errors (stack traces)
30
- const hasRuntimeError = /Stack Begin\s/.test(cleanLogs);
58
+ if (options.requireTestReport && !hasTestReport(cleanLogs)) {
59
+ failureReasons.push(
60
+ 'no jest report in output — nothing proves any test ran'
61
+ );
62
+ }
63
+
64
+ return { success: failureReasons.length === 0, failureReasons };
65
+ }
66
+
67
+ /**
68
+ * True when jest reported at all, including reporting that it found nothing.
69
+ *
70
+ * "Ran and found no tests" is a legitimate answer for packages that ship
71
+ * without specs; "we never heard from jest" is not. Keying on the report
72
+ * rather than on a test count keeps `passWithNoTests` working.
73
+ */
74
+ export function hasTestReport(rawOutput: string): boolean {
75
+ const clean = OutputHelper.stripAnsi(rawOutput);
76
+ return (
77
+ /Tests:\s+/.test(clean) ||
78
+ /Test Suites:\s+/.test(clean) ||
79
+ /No tests found/i.test(clean)
80
+ );
81
+ }
82
+
83
+ /** Count Luau tracebacks in output. */
84
+ export function countTracebacks(rawOutput: string): number {
85
+ if (!rawOutput) {
86
+ return 0;
87
+ }
88
+ return OutputHelper.stripAnsi(rawOutput).match(/Stack Begin\s/g)?.length ?? 0;
89
+ }
90
+
91
+ /**
92
+ * Analyze test output for Jest failures and Luau runtime errors.
93
+ * Shared by both Open Cloud log fetching and local run-in-roblox output.
94
+ */
95
+ export function parseTestLogs(
96
+ rawOutput: string,
97
+ options: TestOutcomeOptions = {}
98
+ ): ParsedTestLogs {
99
+ const outcome = evaluateTestOutcome(rawOutput, options);
31
100
 
32
101
  return {
33
- success: !hasJestFailures && !hasRuntimeError,
102
+ success: outcome.success,
103
+ failureReasons: outcome.failureReasons,
34
104
  logs: rawOutput,
35
105
  testCounts: parseTestCounts(rawOutput),
36
106
  };
@@ -0,0 +1,154 @@
1
+ import { describe, it, expect, vi, afterEach } from 'vitest';
2
+ import {
3
+ describeMissingWatchToken,
4
+ parseGithubRepository,
5
+ tryResolveGithubDispatchContext,
6
+ } from './github-context.js';
7
+
8
+ // ESM exports cannot be spied on, so the module is mocked outright.
9
+ const execSyncMock = vi.hoisted(() => vi.fn());
10
+ vi.mock('child_process', () => ({ execSync: execSyncMock }));
11
+
12
+ afterEach(() => {
13
+ execSyncMock.mockReset();
14
+ vi.unstubAllEnvs();
15
+ });
16
+
17
+ /** Answers the subprocesses github-context shells out to. */
18
+ function stubCommands(answers: Record<string, string | Error>) {
19
+ execSyncMock.mockImplementation((cmd: string) => {
20
+ for (const [prefix, answer] of Object.entries(answers)) {
21
+ if (cmd.startsWith(prefix)) {
22
+ if (answer instanceof Error) {
23
+ throw answer;
24
+ }
25
+ return answer;
26
+ }
27
+ }
28
+ throw new Error(`unstubbed command: ${cmd}`);
29
+ });
30
+ }
31
+
32
+ describe('tryResolveGithubDispatchContext token', () => {
33
+ const REPO_AND_REF = {
34
+ 'git remote get-url origin': 'git@github.com:Quenty/Nevermore.git',
35
+ 'git rev-parse': 'main',
36
+ };
37
+
38
+ // Registering ships the token to the watch service, so it has to be one the
39
+ // user handed over. Nearly every dev machine has a logged-in `gh`, so reading
40
+ // it by default would turn a local watch into a silent credential send.
41
+ it('does not consult gh unless asked', () => {
42
+ vi.stubEnv('NEVERMORE_WATCH_TOKEN', '');
43
+ vi.stubEnv('GITHUB_TOKEN', '');
44
+ stubCommands({
45
+ ...REPO_AND_REF,
46
+ 'gh auth token': new Error('gh must not be consulted'),
47
+ });
48
+
49
+ const result = tryResolveGithubDispatchContext();
50
+ expect(result.success && result.context.token).toBeUndefined();
51
+ });
52
+
53
+ it('reads the GitHub CLI token when explicitly asked', () => {
54
+ vi.stubEnv('NEVERMORE_WATCH_TOKEN', '');
55
+ vi.stubEnv('GITHUB_TOKEN', '');
56
+ stubCommands({ ...REPO_AND_REF, 'gh auth token': 'gho_from_cli' });
57
+
58
+ const result = tryResolveGithubDispatchContext({ useGhAuth: true });
59
+ expect(result.success && result.context.token).toBe('gho_from_cli');
60
+ });
61
+
62
+ // CI sets the env var, and must never pay for the subprocess.
63
+ it('prefers the env var and does not shell out to gh', () => {
64
+ vi.stubEnv('NEVERMORE_WATCH_TOKEN', 'from-env');
65
+ stubCommands({
66
+ ...REPO_AND_REF,
67
+ 'gh auth token': new Error('gh should not be consulted'),
68
+ });
69
+
70
+ const result = tryResolveGithubDispatchContext({ useGhAuth: true });
71
+ expect(result.success && result.context.token).toBe('from-env');
72
+ });
73
+
74
+ it('reports no token when gh is missing or logged out', () => {
75
+ vi.stubEnv('NEVERMORE_WATCH_TOKEN', '');
76
+ vi.stubEnv('GITHUB_TOKEN', '');
77
+ stubCommands({
78
+ ...REPO_AND_REF,
79
+ 'gh auth token': new Error('gh: command not found'),
80
+ });
81
+
82
+ const result = tryResolveGithubDispatchContext({ useGhAuth: true });
83
+ expect(result.success && result.context.token).toBeUndefined();
84
+ });
85
+
86
+ // A logged-out `gh` exits non-zero, but a notice printed to stdout would sail
87
+ // through as a "token" and fail much later as a confusing 401.
88
+ it('refuses output that cannot be a token', () => {
89
+ vi.stubEnv('NEVERMORE_WATCH_TOKEN', '');
90
+ vi.stubEnv('GITHUB_TOKEN', '');
91
+ stubCommands({
92
+ ...REPO_AND_REF,
93
+ 'gh auth token': 'You are not logged in. Run gh auth login',
94
+ });
95
+
96
+ const result = tryResolveGithubDispatchContext({ useGhAuth: true });
97
+ expect(result.success && result.context.token).toBeUndefined();
98
+ });
99
+
100
+ it('names both ways of supplying a token when none is found', () => {
101
+ expect(describeMissingWatchToken()).toMatch(/NEVERMORE_WATCH_TOKEN/);
102
+ expect(describeMissingWatchToken()).toMatch(/--watch-use-gh-auth/);
103
+ });
104
+ });
105
+
106
+ describe('parseGithubRepository', () => {
107
+ it('parses an https remote', () => {
108
+ expect(
109
+ parseGithubRepository('https://github.com/Quenty/Nevermore.git')
110
+ ).toBe('Quenty/Nevermore');
111
+ });
112
+
113
+ it('parses an https remote without the .git suffix', () => {
114
+ expect(parseGithubRepository('https://github.com/Quenty/Nevermore')).toBe(
115
+ 'Quenty/Nevermore'
116
+ );
117
+ });
118
+
119
+ it('parses an scp-style ssh remote', () => {
120
+ expect(parseGithubRepository('git@github.com:Quenty/Nevermore.git')).toBe(
121
+ 'Quenty/Nevermore'
122
+ );
123
+ });
124
+
125
+ it('parses an ssh:// remote', () => {
126
+ expect(
127
+ parseGithubRepository('ssh://git@github.com/Quenty/Nevermore.git')
128
+ ).toBe('Quenty/Nevermore');
129
+ });
130
+
131
+ it('parses a remote with credentials embedded', () => {
132
+ expect(
133
+ parseGithubRepository(
134
+ 'https://user:token@github.com/Quenty/Nevermore.git'
135
+ )
136
+ ).toBe('Quenty/Nevermore');
137
+ });
138
+
139
+ it('tolerates surrounding whitespace and a trailing slash', () => {
140
+ expect(
141
+ parseGithubRepository(' https://github.com/Quenty/Nevermore/ ')
142
+ ).toBe('Quenty/Nevermore');
143
+ });
144
+
145
+ it('ignores a non-GitHub host', () => {
146
+ expect(
147
+ parseGithubRepository('https://gitlab.com/Quenty/Nevermore.git')
148
+ ).toBeUndefined();
149
+ });
150
+
151
+ it('ignores a local path remote', () => {
152
+ expect(parseGithubRepository('/srv/git/Nevermore.git')).toBeUndefined();
153
+ });
154
+ });
@@ -0,0 +1,184 @@
1
+ import { execSync } from 'child_process';
2
+
3
+ /**
4
+ * Env var holding the token the watch service dispatches with. Checked before
5
+ * `GITHUB_TOKEN` so a long-lived registration token can be kept separate from
6
+ * the short-lived one a workflow run is handed — an Actions `GITHUB_TOKEN`
7
+ * expires with its job, which would outlive nothing.
8
+ */
9
+ const WATCH_TOKEN_ENV = 'NEVERMORE_WATCH_TOKEN';
10
+
11
+ /** Everything the watch service needs to dispatch a workflow back at us. */
12
+ export interface GithubDispatchContext {
13
+ /** `owner/repo`. */
14
+ repository: string;
15
+ /** Git ref the dispatched workflow should run on. */
16
+ ref: string;
17
+ /** Token the service dispatches with; absent when none was provided. */
18
+ token?: string;
19
+ }
20
+
21
+ export interface GithubContextOptions {
22
+ /**
23
+ * Read the token from the GitHub CLI when no environment variable supplies
24
+ * one.
25
+ *
26
+ * Off unless asked for, and that is the whole point. Registering sends a PAT
27
+ * to the watch service and creates a monitor against the repository, so the
28
+ * credential has to be one the user handed over — an env var is handing it
29
+ * over, reading whatever `gh` happens to be holding is not. Nearly every
30
+ * developer machine has a logged-in `gh`, so defaulting this on would turn a
31
+ * command that used to watch locally into one that quietly ships a token.
32
+ */
33
+ useGhAuth?: boolean;
34
+ }
35
+
36
+ export type GithubContextResult =
37
+ | { success: true; context: GithubDispatchContext }
38
+ | {
39
+ success: false;
40
+ reason: 'no_repository' | 'no_ref' | 'undispatchable_ref';
41
+ };
42
+
43
+ /**
44
+ * A `pull_request` run exposes `GITHUB_REF_NAME` as `42/merge` — a synthetic
45
+ * merge ref that exists only for that check run. It is not a branch, so
46
+ * `workflow_dispatch` cannot run on it, and it disappears when the PR closes.
47
+ */
48
+ const MERGE_REF_PATTERN = /^\d+\/(merge|head)$/;
49
+
50
+ /**
51
+ * Read an env var, treating empty as absent.
52
+ *
53
+ * CI sets a variable to the empty string when the secret behind it is missing
54
+ * (`FOO: ${{ secrets.ABSENT }}`), which `??` would accept as a real value —
55
+ * so the documented fallback to the next source would never fire.
56
+ */
57
+ function _env(name: string): string | undefined {
58
+ const value = process.env[name];
59
+ return value == null || value === '' ? undefined : value;
60
+ }
61
+
62
+ /**
63
+ * Work out which repo and ref a watch should dispatch.
64
+ *
65
+ * Prefers the Actions environment, which is authoritative when we are already
66
+ * running inside the workflow being registered, and falls back to the git
67
+ * remote so `--watch <url>` also works from a developer's machine. Best-effort:
68
+ * outside a git repo with no Actions env there is simply nothing to dispatch.
69
+ */
70
+ export function tryResolveGithubDispatchContext(
71
+ options: GithubContextOptions = {}
72
+ ): GithubContextResult {
73
+ const repository = _env('GITHUB_REPOSITORY') ?? _repositoryFromRemote();
74
+ if (!repository) {
75
+ return { success: false, reason: 'no_repository' };
76
+ }
77
+
78
+ const ref =
79
+ _env('GITHUB_REF_NAME') ?? _git(['rev-parse', '--abbrev-ref', 'HEAD']);
80
+ // A detached HEAD gives "HEAD", which is not a ref a dispatch can run on.
81
+ if (!ref || ref === 'HEAD') {
82
+ return { success: false, reason: 'no_ref' };
83
+ }
84
+ if (MERGE_REF_PATTERN.test(ref)) {
85
+ return { success: false, reason: 'undispatchable_ref' };
86
+ }
87
+
88
+ const token =
89
+ _env(WATCH_TOKEN_ENV) ??
90
+ _env('GITHUB_TOKEN') ??
91
+ (options.useGhAuth ? _githubCliToken() : undefined);
92
+
93
+ return { success: true, context: { repository, ref, token } };
94
+ }
95
+
96
+ /** Human-facing explanation for a failed context resolution. */
97
+ export function describeGithubContextFailure(
98
+ reason: 'no_repository' | 'no_ref' | 'undispatchable_ref'
99
+ ): string {
100
+ if (reason === 'no_repository') {
101
+ return (
102
+ 'Could not determine the GitHub repository to dispatch. Set ' +
103
+ 'GITHUB_REPOSITORY (owner/repo), or run from a clone with a GitHub ' +
104
+ '"origin" remote.'
105
+ );
106
+ }
107
+ if (reason === 'undispatchable_ref') {
108
+ return (
109
+ 'Refusing to register a watch from a pull request merge ref. That ref ' +
110
+ 'exists only for this check run, so a dispatch against it would fail ' +
111
+ 'and it disappears when the PR closes. Register from a branch instead ' +
112
+ '(e.g. on push to main).'
113
+ );
114
+ }
115
+ return (
116
+ 'Could not determine the git ref to dispatch on. Set GITHUB_REF_NAME, or ' +
117
+ 'check out a branch (a detached HEAD has no ref to run a workflow from).'
118
+ );
119
+ }
120
+
121
+ /** Hint printed when a cloud registration has no credential to hand over. */
122
+ export function describeMissingWatchToken(): string {
123
+ return [
124
+ 'No GitHub token found. The watch service identifies you by repository, ' +
125
+ 'so registering needs a token with "actions: write" on it. Either:',
126
+ ` - Set: ${WATCH_TOKEN_ENV} (or GITHUB_TOKEN)`,
127
+ ' - Pass: --watch-use-gh-auth, to use the token `gh` already holds',
128
+ ].join('\n');
129
+ }
130
+
131
+ /**
132
+ * Pull `owner/repo` out of a git remote URL. Handles the HTTPS, SCP-style, and
133
+ * ssh:// spellings git hands out, and ignores non-GitHub hosts — a watch
134
+ * registration names a GitHub workflow, so anything else is not dispatchable.
135
+ */
136
+ export function parseGithubRepository(remoteUrl: string): string | undefined {
137
+ const trimmed = remoteUrl.trim();
138
+ const match =
139
+ /^(?:https?:\/\/|ssh:\/\/)?(?:[^@/]+@)?github\.com[:/]+([^/]+)\/(.+?)(?:\.git)?\/?$/i.exec(
140
+ trimmed
141
+ );
142
+ if (!match) {
143
+ return undefined;
144
+ }
145
+ return `${match[1]}/${match[2]}`;
146
+ }
147
+
148
+ function _repositoryFromRemote(): string | undefined {
149
+ const remote = _git(['remote', 'get-url', 'origin']);
150
+ return remote == null ? undefined : parseGithubRepository(remote);
151
+ }
152
+
153
+ /**
154
+ * The token `gh` is already holding, if it is installed and logged in.
155
+ *
156
+ * Only ever called when the caller opted in. Not stored anywhere by us on
157
+ * purpose: `gh` owns its own refresh, and copying a token into `~/.nevermore`
158
+ * would leave a stale duplicate to expire behind everyone's back — the point is
159
+ * reading the live one, for the one run that asked.
160
+ */
161
+ function _githubCliToken(): string | undefined {
162
+ const token = _run('gh', ['auth', 'token']);
163
+ // A logged-out `gh` exits non-zero, but an odd version could print a notice
164
+ // on stdout instead; a token is never whitespace.
165
+ return token == null || /\s/.test(token) ? undefined : token;
166
+ }
167
+
168
+ function _git(args: string[]): string | undefined {
169
+ return _run('git', args);
170
+ }
171
+
172
+ function _run(command: string, args: string[]): string | undefined {
173
+ try {
174
+ const output = execSync(`${command} ${args.join(' ')}`, {
175
+ encoding: 'utf-8',
176
+ timeout: 5000,
177
+ stdio: ['pipe', 'pipe', 'pipe'],
178
+ }).trim();
179
+ return output === '' ? undefined : output;
180
+ } catch {
181
+ // Not installed, not logged in, or not a repo — all "no answer here".
182
+ return undefined;
183
+ }
184
+ }