co-maintainer 0.7.2-beta.1 → 0.7.3

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 (194) hide show
  1. package/dist/package.json +2 -1
  2. package/dist/src/ai/anthropic.d.ts +1 -1
  3. package/dist/src/ai/anthropic.js +1 -1
  4. package/dist/src/ai/batch.d.ts +1 -1
  5. package/dist/src/ai/batch.js +3 -3
  6. package/dist/src/ai/copy_rule.d.ts +7 -0
  7. package/dist/src/ai/copy_rule.js +23 -0
  8. package/dist/src/ai/estimate.js +3 -3
  9. package/dist/src/ai/fake.js +2 -1
  10. package/dist/src/ai/mermaid.js +1 -0
  11. package/dist/src/ai/oauth/registry.d.ts +1 -1
  12. package/dist/src/ai/oauth/sign-in-with-chatgpt.d.ts +4 -4
  13. package/dist/src/ai/oauth/sign-in-with-chatgpt.js +6 -6
  14. package/dist/src/ai/openai.d.ts +3 -3
  15. package/dist/src/ai/openai.js +4 -4
  16. package/dist/src/ai/openrouter.d.ts +1 -1
  17. package/dist/src/ai/openrouter.js +1 -1
  18. package/dist/src/ai/pricing.js +1 -1
  19. package/dist/src/ai/provider.d.ts +2 -0
  20. package/dist/src/ai/provider.js +8 -2
  21. package/dist/src/ai/verify.d.ts +1 -1
  22. package/dist/src/ai/verify.js +1 -1
  23. package/dist/src/cli/args.js +1 -1
  24. package/dist/src/cli/command_json.d.ts +4 -2
  25. package/dist/src/cli/command_json.js +1 -0
  26. package/dist/src/cli/commands/config.d.ts +1 -1
  27. package/dist/src/cli/commands/config.js +1 -1
  28. package/dist/src/cli/commands/oauth.js +1 -1
  29. package/dist/src/cli/commands/probe.js +1 -1
  30. package/dist/src/cli/commands/review.js +2 -0
  31. package/dist/src/cli/commands/serve.d.ts +1 -1
  32. package/dist/src/cli/commands/serve.js +1 -1
  33. package/dist/src/cli/commands/set.d.ts +1 -1
  34. package/dist/src/cli/commands/set.js +23 -6
  35. package/dist/src/cli/commands/view.js +2 -2
  36. package/dist/src/cli/error.d.ts +1 -1
  37. package/dist/src/cli/error.js +1 -1
  38. package/dist/src/cli/pr_carry.d.ts +2 -0
  39. package/dist/src/cli/pr_carry.js +2 -2
  40. package/dist/src/cli/prompt.d.ts +2 -2
  41. package/dist/src/cli/prompt.js +3 -3
  42. package/dist/src/cli/review_args.js +2 -2
  43. package/dist/src/cli/review_carry.d.ts +3 -1
  44. package/dist/src/cli/review_carry.js +5 -3
  45. package/dist/src/cli/review_result.d.ts +13 -5
  46. package/dist/src/cli/review_result.js +19 -9
  47. package/dist/src/config.d.ts +20 -11
  48. package/dist/src/config.js +3 -3
  49. package/dist/src/github/app.d.ts +1 -1
  50. package/dist/src/github/app.js +1 -1
  51. package/dist/src/github/app_manifest.d.ts +1 -1
  52. package/dist/src/github/app_manifest.js +1 -1
  53. package/dist/src/github/client.d.ts +1 -1
  54. package/dist/src/github/client.js +1 -1
  55. package/dist/src/github/collect.d.ts +7 -1
  56. package/dist/src/github/collect.js +41 -16
  57. package/dist/src/github/gh.js +2 -2
  58. package/dist/src/github/jwt.d.ts +1 -1
  59. package/dist/src/github/jwt.js +1 -1
  60. package/dist/src/github/oauth.js +2 -2
  61. package/dist/src/knowledge/facts.js +3 -3
  62. package/dist/src/knowledge/guide.d.ts +24 -1
  63. package/dist/src/knowledge/guide.js +46 -16
  64. package/dist/src/knowledge/guide_ids.d.ts +9 -0
  65. package/dist/src/knowledge/guide_ids.js +26 -7
  66. package/dist/src/knowledge/probe.js +1 -1
  67. package/dist/src/knowledge/rule_changes.d.ts +18 -0
  68. package/dist/src/knowledge/rule_changes.js +41 -0
  69. package/dist/src/knowledge/rules.d.ts +11 -0
  70. package/dist/src/knowledge/rules.js +10 -1
  71. package/dist/src/knowledge/skill.js +1 -1
  72. package/dist/src/knowledge/stable_ids.d.ts +29 -0
  73. package/dist/src/knowledge/stable_ids.js +90 -0
  74. package/dist/src/knowledge/synthesis.d.ts +13 -1
  75. package/dist/src/knowledge/synthesis.js +94 -26
  76. package/dist/src/knowledge/types.d.ts +16 -0
  77. package/dist/src/local/carry_over_store.d.ts +1 -1
  78. package/dist/src/local/carry_over_store.js +1 -1
  79. package/dist/src/local/codegraph_prepare.js +1 -1
  80. package/dist/src/local/git_ops.js +1 -1
  81. package/dist/src/local/review_local.js +6 -5
  82. package/dist/src/local/review_lock.d.ts +1 -1
  83. package/dist/src/pr/checkout.d.ts +3 -3
  84. package/dist/src/pr/checkout.js +7 -7
  85. package/dist/src/pr/codegraph_tool_args.d.ts +1 -1
  86. package/dist/src/pr/codegraph_tool_args.js +1 -1
  87. package/dist/src/pr/findings.d.ts +3 -0
  88. package/dist/src/pr/findings.js +29 -10
  89. package/dist/src/pr/findings_json.d.ts +2 -2
  90. package/dist/src/pr/findings_json.js +15 -2
  91. package/dist/src/pr/github_revision.js +1 -1
  92. package/dist/src/pr/review_copy.d.ts +2 -3
  93. package/dist/src/pr/review_copy.js +2 -3
  94. package/dist/src/pr/reviewer.d.ts +7 -3
  95. package/dist/src/pr/reviewer.js +26 -26
  96. package/dist/src/pr/scope.d.ts +8 -8
  97. package/dist/src/pr/scope.js +4 -4
  98. package/dist/src/pr/snapshot.d.ts +2 -2
  99. package/dist/src/remote/client.js +4 -3
  100. package/dist/src/remote/schema.d.ts +1 -1
  101. package/dist/src/remote/schema.js +1 -1
  102. package/dist/src/remote/server/body.d.ts +1 -1
  103. package/dist/src/remote/server/body.js +1 -1
  104. package/dist/src/remote/server/guides.js +1 -1
  105. package/dist/src/remote/validate.js +1 -1
  106. package/dist/src/review/blocking.d.ts +3 -3
  107. package/dist/src/review/blocking.js +2 -2
  108. package/dist/src/review/carry_over.d.ts +9 -1
  109. package/dist/src/review/carry_over.js +10 -2
  110. package/dist/src/review/diagram.js +7 -6
  111. package/dist/src/review/engine.d.ts +1 -1
  112. package/dist/src/review/guides.js +1 -1
  113. package/dist/src/review/references.d.ts +68 -0
  114. package/dist/src/review/references.js +176 -0
  115. package/dist/src/review/system_prompt.d.ts +1 -1
  116. package/dist/src/review/system_prompt.js +1 -1
  117. package/dist/src/server/api/jobs.js +2 -2
  118. package/dist/src/server/api/repos.js +1 -1
  119. package/dist/src/server/app.js +1 -1
  120. package/dist/src/server/auth.d.ts +3 -3
  121. package/dist/src/server/auth.js +9 -4
  122. package/dist/src/server/http.js +5 -5
  123. package/dist/src/server/pages/activity.js +1 -1
  124. package/dist/src/server/pages/add_repo.js +1 -0
  125. package/dist/src/server/pages/client.d.ts +2 -2
  126. package/dist/src/server/pages/client.js +2 -2
  127. package/dist/src/server/pages/home.d.ts +1 -1
  128. package/dist/src/server/pages/home.js +1 -1
  129. package/dist/src/server/pages/icons.d.ts +1 -1
  130. package/dist/src/server/pages/icons.js +1 -1
  131. package/dist/src/server/pages/layout.d.ts +2 -2
  132. package/dist/src/server/pages/layout.js +3 -3
  133. package/dist/src/server/pages/pr.js +4 -0
  134. package/dist/src/server/pages/rate_limit_waits.js +2 -2
  135. package/dist/src/server/pages/references.d.ts +2 -0
  136. package/dist/src/server/pages/references.js +55 -0
  137. package/dist/src/server/pages/repo.js +26 -0
  138. package/dist/src/server/pages/repo_settings.js +1 -0
  139. package/dist/src/server/pages/router.js +3 -2
  140. package/dist/src/server/pages/styles.d.ts +2 -2
  141. package/dist/src/server/pages/styles.js +2 -2
  142. package/dist/src/server/pages/ui.d.ts +1 -1
  143. package/dist/src/server/pages/ui.js +2 -2
  144. package/dist/src/server/webhook/index.js +1 -1
  145. package/dist/src/services/clear.d.ts +2 -2
  146. package/dist/src/services/clear.js +2 -2
  147. package/dist/src/services/dashboard.d.ts +2 -0
  148. package/dist/src/services/dashboard.js +2 -0
  149. package/dist/src/services/probe.js +1 -1
  150. package/dist/src/services/push_review.js +4 -1
  151. package/dist/src/services/remote_review.js +5 -2
  152. package/dist/src/services/remote_review_abort.d.ts +1 -1
  153. package/dist/src/services/remote_review_abort.js +1 -1
  154. package/dist/src/services/remote_tokens.js +1 -1
  155. package/dist/src/services/replies.js +0 -2
  156. package/dist/src/services/review.d.ts +3 -5
  157. package/dist/src/services/review.js +43 -18
  158. package/dist/src/services/rules_build.d.ts +20 -1
  159. package/dist/src/services/rules_build.js +85 -6
  160. package/dist/src/services/setup.d.ts +2 -2
  161. package/dist/src/services/setup.js +36 -11
  162. package/dist/src/services/watch_comments.js +1 -2
  163. package/dist/src/services/watch_notes.js +1 -3
  164. package/dist/src/store/app_db.d.ts +1 -1
  165. package/dist/src/store/app_db.js +2 -2
  166. package/dist/src/store/findings.d.ts +2 -0
  167. package/dist/src/store/findings.js +3 -3
  168. package/dist/src/store/jobs.d.ts +2 -2
  169. package/dist/src/store/jobs.js +3 -3
  170. package/dist/src/store/migrations.d.ts +2 -2
  171. package/dist/src/store/migrations.js +35 -18
  172. package/dist/src/store/rows.d.ts +4 -2
  173. package/dist/src/store/rows.js +1 -1
  174. package/dist/src/store/rule_events.d.ts +15 -0
  175. package/dist/src/store/rule_events.js +20 -0
  176. package/dist/src/store/sessions.d.ts +1 -1
  177. package/dist/src/store/sessions.js +2 -2
  178. package/dist/src/store/sqlite.js +2 -2
  179. package/dist/src/tools/codegraph.d.ts +1 -1
  180. package/dist/src/tools/codegraph.js +3 -3
  181. package/dist/src/tools/codegraph_exec.d.ts +1 -1
  182. package/dist/src/tools/codegraph_exec.js +1 -1
  183. package/dist/src/types.d.ts +6 -2
  184. package/dist/src/util/keyed_lock.d.ts +1 -1
  185. package/dist/src/util/keyed_lock.js +1 -1
  186. package/dist/src/util/log.js +1 -1
  187. package/dist/src/util/redact.js +2 -1
  188. package/dist/src/util/run_summary.d.ts +3 -3
  189. package/dist/src/util/run_summary.js +3 -3
  190. package/dist/src/util/runtime.d.ts +4 -4
  191. package/dist/src/util/runtime.js +5 -5
  192. package/dist/src/util/time.d.ts +1 -1
  193. package/dist/src/util/time.js +1 -1
  194. package/package.json +2 -1
@@ -0,0 +1,176 @@
1
+ /** What a review finding rests on.
2
+ *
3
+ * The review answer names ids only: `R12` and `I3` from the guide and
4
+ * instruction lines, `codebase:<section>` for a CODEBASE CONVENTIONS section,
5
+ * and `system` for the review instructions themselves. No pull request number
6
+ * or date ever enters the prompt. Code turns each id into a reference from
7
+ * `RULES.json` at review time, and the result is stored with the finding, so
8
+ * a later `sync` never changes what an old review cited. */
9
+ import { RULE_ID } from "../knowledge/rules.js";
10
+ /** The ids as the model wrote them, one per entry, trimmed. */
11
+ export function referenceIds(value) {
12
+ if (!Array.isArray(value))
13
+ return [];
14
+ return [
15
+ ...new Set(value
16
+ .map((item) => (typeof item === "string" ? item.trim() : ""))
17
+ .filter(Boolean)),
18
+ ];
19
+ }
20
+ /** The `## ` section titles of CODEBASE.md, so a made-up section is not
21
+ * shown as if it existed. */
22
+ function codebaseSections(codebase) {
23
+ return new Set([...codebase.matchAll(/^##\s+(.+?)\s*$/gm)].map((match) => match[1].toLowerCase()));
24
+ }
25
+ function instructionUrl(repo, commit, path, line) {
26
+ if (!commit || !/^[\w.-]+\/[\w.-]+$/.test(repo))
27
+ return undefined;
28
+ // A space, `#` or `?` in a path would end the URL early, and a space or a
29
+ // parenthesis would break the Markdown link around it.
30
+ const encoded = path
31
+ .split("/")
32
+ .map((segment) => encodeURIComponent(segment).replace(/[()]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`))
33
+ .join("/");
34
+ return `https://github.com/${repo}/blob/${commit}/${encoded}#L${line}`;
35
+ }
36
+ /** Turns the ids of one finding into references. An id that is not in
37
+ * `RULES.json` is dropped, so a made-up id never shows. A finding that names
38
+ * nothing usable rests on the review instructions: `system`. */
39
+ export function resolveReferences(ids, input) {
40
+ const sections = codebaseSections(input.codebase);
41
+ const resolved = [];
42
+ const seen = new Set();
43
+ for (const raw of ids) {
44
+ const id = raw.replace(/^\[|\]$/g, "").trim();
45
+ const lower = id.toLowerCase();
46
+ if (lower === "system") {
47
+ if (!seen.has("system"))
48
+ resolved.push({ kind: "system" });
49
+ seen.add("system");
50
+ continue;
51
+ }
52
+ if (lower === "codebase" || lower.startsWith("codebase:")) {
53
+ const name = id.slice("codebase".length).replace(/^:/, "").trim();
54
+ const section = name && sections.has(name.toLowerCase()) ? name : undefined;
55
+ const key = `codebase:${section ?? ""}`;
56
+ if (!seen.has(key))
57
+ resolved.push({ kind: "codebase", section });
58
+ seen.add(key);
59
+ continue;
60
+ }
61
+ const upper = id.toUpperCase();
62
+ if (!RULE_ID.test(upper) || seen.has(upper))
63
+ continue;
64
+ const entry = input.rules?.rules[upper];
65
+ if (!entry)
66
+ continue;
67
+ seen.add(upper);
68
+ const sources = entry.sources.map((source) => "pr" in source
69
+ ? {
70
+ pr: source.pr,
71
+ ...(source.mergedAt ? { mergedAt: source.mergedAt } : {}),
72
+ ...(source.url ? { url: source.url } : {}),
73
+ }
74
+ : {
75
+ path: source.path,
76
+ line: source.line,
77
+ ...(() => {
78
+ const url = instructionUrl(input.repo, entry.commit, source.path, source.line);
79
+ return url ? { url } : {};
80
+ })(),
81
+ });
82
+ resolved.push({
83
+ kind: upper.startsWith("R") ? "rule" : "instruction",
84
+ id: upper,
85
+ sources,
86
+ });
87
+ }
88
+ return resolved.length ? resolved : [{ kind: "system" }];
89
+ }
90
+ function linkWith(links) {
91
+ return (text, url) => links && url ? `[${text}](${url})` : text;
92
+ }
93
+ /** One reference as a reader sees it:
94
+ * `Rules-12 · #212, #340 · 2026-03`, `Instructions-3 · AGENTS.md:14`,
95
+ * `System Prompt`, `Codebase · Tests`. */
96
+ export function referenceLine(reference, links = true) {
97
+ const link = linkWith(links);
98
+ switch (reference.kind) {
99
+ case "system":
100
+ return "System Prompt";
101
+ case "codebase":
102
+ return reference.section ? `Codebase · ${reference.section}` : "Codebase";
103
+ case "rule": {
104
+ const prs = reference.sources.flatMap((source) => "pr" in source ? [link(`#${source.pr}`, source.url)] : []);
105
+ const dates = reference.sources
106
+ .flatMap((source) => "pr" in source && source.mergedAt ? [source.mergedAt] : [])
107
+ .sort();
108
+ const newest = dates.at(-1)?.slice(0, 7);
109
+ return [`Rules-${reference.id.slice(1)}`, prs.join(", "), newest]
110
+ .filter(Boolean)
111
+ .join(" · ");
112
+ }
113
+ case "instruction": {
114
+ const lines = reference.sources.flatMap((source) => "path" in source
115
+ ? [link(`${source.path}:${source.line}`, source.url)]
116
+ : []);
117
+ return [`Instructions-${reference.id.slice(1)}`, lines.join(", ")]
118
+ .filter(Boolean)
119
+ .join(" · ");
120
+ }
121
+ }
122
+ }
123
+ /** The collapsed block under a finding, or `""` when there is nothing. */
124
+ export function referencesBlock(references) {
125
+ if (references.length === 0)
126
+ return "";
127
+ return [
128
+ `<details><summary>References (${references.length})</summary>`,
129
+ "",
130
+ ...references.map((reference) => `- ${referenceLine(reference)}`),
131
+ "",
132
+ "</details>",
133
+ ].join("\n");
134
+ }
135
+ /** Reads a stored `references_json` value. Anything that does not fit is
136
+ * skipped, so a bad row shows no references rather than failing a page. */
137
+ export function parseStoredReferences(text) {
138
+ if (!text)
139
+ return [];
140
+ try {
141
+ const value = JSON.parse(text);
142
+ if (!Array.isArray(value))
143
+ return [];
144
+ return value.filter((item) => !!item &&
145
+ typeof item === "object" &&
146
+ ["rule", "instruction", "codebase", "system"].includes(item.kind));
147
+ }
148
+ catch {
149
+ return [];
150
+ }
151
+ }
152
+ /** The `references_json` to store for a finding: a carried one keeps what it
153
+ * rested on, a new one resolves the ids its answer named. */
154
+ export function referencesJson(finding, repo, context) {
155
+ if (finding.references)
156
+ return JSON.stringify(finding.references);
157
+ return JSON.stringify(resolveReferences(finding.referenceIds ?? [], {
158
+ repo,
159
+ rules: context?.rules ?? null,
160
+ codebase: context?.codebase ?? "",
161
+ }));
162
+ }
163
+ /** Gives every row that has no references yet the ones its ids resolve to,
164
+ * so every output (stored row, JSON, carry file) carries the same list. */
165
+ export function withResolvedReferences(rows, repo, context) {
166
+ for (const row of rows) {
167
+ if (row.references)
168
+ continue;
169
+ row.references = resolveReferences(row.referenceIds ?? [], {
170
+ repo,
171
+ rules: context?.rules ?? null,
172
+ codebase: context?.codebase ?? "",
173
+ });
174
+ }
175
+ return rows;
176
+ }
@@ -6,7 +6,7 @@ import type { Options } from "../types.ts";
6
6
  import type { RepoConfig } from "../config.ts";
7
7
  /** Default cap on `reviewSystemPrompt`, in characters. */
8
8
  export declare const DEFAULT_REVIEW_SYSTEM_PROMPT_MAX_CHARS = 8000;
9
- /** The repository's cap, or `null` for no limit. Unset takes the default; a
9
+ /** The repository's cap, or `null` for no limit. Unset takes the default. A
10
10
  * non-positive value means unlimited. */
11
11
  export declare function reviewSystemPromptLimit(repoConfig: Pick<RepoConfig, "reviewSystemPromptMaxChars"> | undefined): number | null;
12
12
  /** The problem with a custom prompt, or `null` when it is fine. Blank text is
@@ -1,6 +1,6 @@
1
1
  /** Default cap on `reviewSystemPrompt`, in characters. */
2
2
  export const DEFAULT_REVIEW_SYSTEM_PROMPT_MAX_CHARS = 8000;
3
- /** The repository's cap, or `null` for no limit. Unset takes the default; a
3
+ /** The repository's cap, or `null` for no limit. Unset takes the default. A
4
4
  * non-positive value means unlimited. */
5
5
  export function reviewSystemPromptLimit(repoConfig) {
6
6
  const raw = repoConfig?.reviewSystemPromptMaxChars;
@@ -1,5 +1,5 @@
1
1
  /** The log stream is meant to be consumed with `fetch()` and a manual
2
- * reader, not the native `EventSource` API — `EventSource` cannot set an
2
+ * reader, not the native `EventSource` API, `EventSource` cannot set an
3
3
  * `Authorization` header, and every other `/api/*` route needs one. */
4
4
  import { errorResponse } from "../errors.js";
5
5
  import { cancel, getLogsSince, subscribeToLogs } from "../../services/jobs.js";
@@ -78,7 +78,7 @@ function streamLogs(jobId, fromSeq) {
78
78
  unsubscribe = subscribeToLogs(jobId, send);
79
79
  },
80
80
  cancel() {
81
- // The client disconnected — stop pushing to it.
81
+ // The client disconnected, stop pushing to it.
82
82
  closed = true;
83
83
  unsubscribe?.();
84
84
  },
@@ -147,7 +147,7 @@ export async function handleReposRoute(request, url, githubApp) {
147
147
  policyToKeep = stored.value;
148
148
  }
149
149
  // `patch` is the confirmed preview. It is optional so a caller that
150
- // never opened the preview keeps the old behavior; when present it is
150
+ // never opened the preview keeps the old behavior. When present it is
151
151
  // written before `activateRepo` so the enqueued init reads it.
152
152
  const patch = body.patch && typeof body.patch === "object"
153
153
  ? body.patch
@@ -1,4 +1,4 @@
1
- /** `createApp(deps).fetch(request)` — no port, no sockets, so it is testable
1
+ /** `createApp(deps).fetch(request)`, no port, no sockets, so it is testable
2
2
  * with a plain `Request`. */
3
3
  import { VERSION } from "../version.js";
4
4
  import { errorResponse } from "./errors.js";
@@ -5,7 +5,7 @@ export declare const SESSION_COOKIE = "cm";
5
5
  export declare const OAUTH_STATE_COOKIE = "cm_oauth_state";
6
6
  /** Which sign-in methods a running `serve` accepts. Resolved once at
7
7
  * startup (CLI flag, falling back to config) and threaded through
8
- * `AppDeps`/`PageDeps` — every route reads the same resolved value. */
8
+ * `AppDeps`/`PageDeps`, every route reads the same resolved value. */
9
9
  export type AuthMethods = {
10
10
  password: boolean;
11
11
  github: boolean;
@@ -35,7 +35,7 @@ export declare function checkPassword(password: string, store: PasswordStore, ip
35
35
  export declare function login(password: string, store: PasswordStore, ip: string): Promise<LoginResult | undefined>;
36
36
  export declare function revokeOtherSessions(keepToken: string): Promise<void>;
37
37
  /** Issues a session for the one dashboard identity, bypassing the password
38
- * check — used after GitHub OAuth has already verified the caller. */
38
+ * check, used after GitHub OAuth has already verified the caller. */
39
39
  export declare function createSession(): Promise<LoginResult>;
40
40
  export declare function verifySession(token: string): Promise<{
41
41
  username: string;
@@ -46,7 +46,7 @@ export declare function readSessionToken(request: Request): string | undefined;
46
46
  export declare function sessionCookieHeader(token: string, secure: boolean): string;
47
47
  export declare function clearSessionCookieHeader(secure: boolean): string;
48
48
  /** The GitHub OAuth `state` param, plus the post-login `next` path,
49
- * round-tripped through an HttpOnly cookie instead of server memory — one
49
+ * round-tripped through an HttpOnly cookie instead of server memory, one
50
50
  * admin, one in-flight login at a time, so a cookie is all this needs. */
51
51
  export declare function readOauthState(request: Request): {
52
52
  state: string;
@@ -1,4 +1,4 @@
1
- /** Only a token's hash ever reaches `store/sessions.ts`; the raw token is
1
+ /** Only a token's hash ever reaches `store/sessions.ts`. The raw token is
2
2
  * handed back once, at login, and never stored. */
3
3
  import { readConfig, writeUserConfig } from "../config.js";
4
4
  import { hashPassword, verifyPasswordHash } from "../util/password.js";
@@ -37,7 +37,7 @@ export function randomToken() {
37
37
  return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
38
38
  }
39
39
  // ponytail: an in-memory Map, one entry per distinct IP that has ever failed
40
- // a login. Fine for a single self-hosted admin; add eviction if this ever
40
+ // a login. Fine for a single self-hosted admin. Add eviction if this ever
41
41
  // needs to survive a hostile flood of spoofed source IPs.
42
42
  const attempts = new Map();
43
43
  export function recordAuthFailure(ip) {
@@ -116,7 +116,7 @@ export async function revokeOtherSessions(keepToken) {
116
116
  deleteOtherSessions(await sha256Hex(keepToken));
117
117
  }
118
118
  /** Issues a session for the one dashboard identity, bypassing the password
119
- * check — used after GitHub OAuth has already verified the caller. */
119
+ * check, used after GitHub OAuth has already verified the caller. */
120
120
  export async function createSession() {
121
121
  const token = randomToken();
122
122
  const expiresAt = new Date(Date.now() + SESSION_TTL_MS).toISOString();
@@ -139,6 +139,7 @@ export async function logout(token) {
139
139
  }
140
140
  function readCookie(request, name) {
141
141
  const cookie = request.headers.get("cookie") ?? "";
142
+ // punctuation: code, a Cookie header value is split at its semicolons
142
143
  for (const part of cookie.split(";")) {
143
144
  const trimmed = part.trim();
144
145
  const eq = trimmed.indexOf("=");
@@ -171,6 +172,7 @@ export function sessionCookieHeader(token, secure) {
171
172
  ];
172
173
  if (secure)
173
174
  flags.push("Secure");
175
+ // punctuation: code, the Cookie header joins its attributes with a semicolon
174
176
  return flags.join("; ");
175
177
  }
176
178
  export function clearSessionCookieHeader(secure) {
@@ -183,10 +185,11 @@ export function clearSessionCookieHeader(secure) {
183
185
  ];
184
186
  if (secure)
185
187
  flags.push("Secure");
188
+ // punctuation: code, the Cookie header joins its attributes with a semicolon
186
189
  return flags.join("; ");
187
190
  }
188
191
  /** The GitHub OAuth `state` param, plus the post-login `next` path,
189
- * round-tripped through an HttpOnly cookie instead of server memory — one
192
+ * round-tripped through an HttpOnly cookie instead of server memory, one
190
193
  * admin, one in-flight login at a time, so a cookie is all this needs. */
191
194
  export function readOauthState(request) {
192
195
  const value = readCookie(request, OAUTH_STATE_COOKIE);
@@ -215,6 +218,7 @@ export function oauthStateCookieHeader(state, next, secure) {
215
218
  ];
216
219
  if (secure)
217
220
  flags.push("Secure");
221
+ // punctuation: code, the Cookie header joins its attributes with a semicolon
218
222
  return flags.join("; ");
219
223
  }
220
224
  export function clearOauthStateCookieHeader(secure) {
@@ -227,5 +231,6 @@ export function clearOauthStateCookieHeader(secure) {
227
231
  ];
228
232
  if (secure)
229
233
  flags.push("Secure");
234
+ // punctuation: code, the Cookie header joins its attributes with a semicolon
230
235
  return flags.join("; ");
231
236
  }
@@ -2,8 +2,8 @@
2
2
  *
3
3
  * The app is written against the Web `Request`/`Response` types, which Deno
4
4
  * served natively. Node has both types but no server that speaks them
5
- * directly, so this translates per request and streams responses — including
6
- * the SSE job feed — instead of buffering them. */
5
+ * directly, so this translates per request and streams responses, including
6
+ * the SSE job feed, instead of buffering them. */
7
7
  import { createServer, } from "node:http";
8
8
  import { Readable } from "node:stream";
9
9
  function requestHeaders(req) {
@@ -19,8 +19,8 @@ function requestHeaders(req) {
19
19
  }
20
20
  return headers;
21
21
  }
22
- /** Node's `IncomingMessage` is a Node stream; `fetch` wants a Web body. A
23
- * GET/HEAD has none, and passing `undefined` is required there — a body on a
22
+ /** Node's `IncomingMessage` is a Node stream, `fetch` wants a Web body. A
23
+ * GET/HEAD has none, and passing `undefined` is required there, a body on a
24
24
  * GET makes undici throw. */
25
25
  function requestBody(req, method) {
26
26
  if (method === "GET" || method === "HEAD")
@@ -104,7 +104,7 @@ export function serveHttp(app, port) {
104
104
  server.once("error", reject);
105
105
  });
106
106
  // Slow-loris defence: cap how long a client may take to send headers and
107
- // the full request. Responses (SSE) are unaffected — those are measured on
107
+ // the full request. Responses (SSE) are unaffected, those are measured on
108
108
  // the response side, not here.
109
109
  server.headersTimeout = 20_000;
110
110
  server.requestTimeout = 120_000;
@@ -391,7 +391,7 @@ function failureExplanation(error) {
391
391
  return "";
392
392
  }
393
393
  /** The model a failed job ran with. A manual or webhook review does not put
394
- * the model in its job args; the review row records the one it resolved.
394
+ * the model in its job args. The review row records the one it resolved.
395
395
  * "unknown" is what a review stores when no model was set. */
396
396
  function failedModel(args, review) {
397
397
  const fromReview = review?.model && review.model !== "unknown" ? review.model : undefined;
@@ -46,6 +46,7 @@ export function renderAddRepo(username, picker) {
46
46
  title: "Add repository · co-maintainer",
47
47
  username,
48
48
  active: "/",
49
+ // punctuation: code, a script the page runs in the browser
49
50
  body: `<div class="wrap narrow">
50
51
  <div class="crumbs"><a href="/">Repositories</a> / Add</div>
51
52
  <div class="pagehead">
@@ -1,2 +1,2 @@
1
- /** Generated from src/server/pages/client.js by scripts/embed_assets.mjs — do not edit. */
2
- export declare const client = "function toast(message) {\n const host = document.getElementById(\"toasts\");\n if (!host) return;\n const el = document.createElement(\"div\");\n el.className = \"toast\";\n el.setAttribute(\"role\", \"status\");\n el.textContent = message;\n host.appendChild(el);\n setTimeout(function () {\n el.remove();\n }, 5000);\n}\n\nfunction fail(card, message, retry) {\n toast(message);\n if (!card) return;\n let box = card.querySelector(\"[data-fail]\");\n if (!box) {\n box = document.createElement(\"div\");\n box.setAttribute(\"data-fail\", \"1\");\n box.className = \"fail\";\n card.appendChild(box);\n }\n box.replaceChildren();\n const p = document.createElement(\"p\");\n p.textContent = message;\n const btn = document.createElement(\"button\");\n btn.className = \"btn sm\";\n btn.type = \"button\";\n btn.textContent = \"Retry\";\n btn.addEventListener(\"click\", retry);\n box.appendChild(p);\n box.appendChild(btn);\n}\n\nfunction clearFail(card) {\n const box = card && card.querySelector(\"[data-fail]\");\n if (box) box.remove();\n}\n\n/** Copy text for the `codeBlock` copy button. `navigator.clipboard` needs a\n * secure context, so the hidden-textarea path keeps Copy working on plain\n * http://localhost too. `done` runs only when one of the two paths worked. */\nfunction copyText(value, done, failed) {\n function fallback() {\n if (legacyCopy(value)) done();\n else if (failed) failed();\n }\n if (navigator.clipboard && navigator.clipboard.writeText) {\n navigator.clipboard.writeText(value).then(done, fallback);\n return;\n }\n fallback();\n}\n\nfunction legacyCopy(value) {\n const area = document.createElement(\"textarea\");\n area.value = value;\n area.setAttribute(\"readonly\", \"\");\n area.style.position = \"fixed\";\n area.style.opacity = \"0\";\n document.body.appendChild(area);\n area.select();\n let copied = false;\n try {\n copied = document.execCommand(\"copy\") === true;\n } catch {\n copied = false;\n }\n area.remove();\n return copied;\n}\n\nfunction skeleton(card, on) {\n if (!card) return;\n card.classList.toggle(\"busy\", on);\n}\n\nasync function api(method, url, body) {\n const res = await fetch(url, {\n method: method,\n headers: {\n \"content-type\": \"application/json\",\n \"x-requested-with\": \"co-maintainer\",\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n if (!res.ok) {\n let message = \"Request failed\";\n let code = \"\";\n let detail;\n try {\n const data = await res.json();\n if (data.error && data.error.message) message = data.error.message;\n if (data.error && data.error.code) code = data.error.code;\n if (data.error) detail = data.error.detail;\n } catch {\n // body was not JSON; keep the generic message\n }\n const error = new Error(message);\n if (code) error.code = code;\n error.detail = detail;\n throw error;\n }\n if (res.status === 204) return null;\n return await res.json();\n}\n\nasync function run(btn, card, fn) {\n if (btn) btn.disabled = true;\n skeleton(card, true);\n clearFail(card);\n try {\n await fn();\n } catch (err) {\n fail(card, err.message, function () {\n run(btn, card, fn);\n });\n } finally {\n if (btn) btn.disabled = false;\n skeleton(card, false);\n }\n}\n\nfunction saved(btn, card) {\n if (card) {\n let state = card.querySelector(\".save-state\");\n if (!state) {\n state = document.createElement(\"span\");\n state.className = \"save-state\";\n state.setAttribute(\"role\", \"status\");\n if (btn && btn.parentNode) {\n btn.parentNode.insertBefore(state, btn.nextSibling);\n }\n }\n state.textContent = \"Saved\";\n }\n toast(\"Saved\");\n}\nglobalThis.saved = saved;\n\n/** Polls one job until it reaches a terminal status. A running `init`/`remake`\n * ignores the abort signal, so \"wait for the sync\" is the only honest option\n * the clear pages can offer for it. */\nfunction waitForJob(id) {\n return new Promise(function (resolve, reject) {\n let attempts = 0;\n async function tick() {\n attempts++;\n try {\n const res = await fetch(\"/api/jobs/\" + encodeURIComponent(id), {\n headers: { \"x-requested-with\": \"co-maintainer\" },\n });\n if (!res.ok) throw new Error(\"Could not check the running job.\");\n const job = await res.json();\n if (job.status !== \"running\" && job.status !== \"queued\") {\n resolve();\n return;\n }\n if (attempts > 1200) {\n reject(new Error(\"The sync did not finish.\"));\n return;\n }\n setTimeout(tick, 3000);\n } catch (err) {\n reject(err);\n }\n }\n tick();\n });\n}\n\n/** Clears knowledge, asking about pending jobs when the server refuses.\n * Returns false when the user backed out, so the caller does not reload.\n * A running review is abortable and a running setup is not, which is the\n * difference between the two questions. Called from the inline scripts on the\n * knowledge pages, so it looks unused from inside this file. */\n// oxlint-disable-next-line no-unused-vars\nasync function clearKnowledge(url, includeCache) {\n const target = includeCache ? url + \"?includeCache=1\" : url;\n const retry = target.indexOf(\"?\") >= 0 ? \"&\" : \"?\";\n try {\n await api(\"DELETE\", target);\n } catch (err) {\n if (err.code !== \"jobs_running\") throw err;\n const detail = err.detail || { queued: 0, running: [] };\n const running = detail.running || [];\n const setup = running.find(function (job) {\n return job.abortable === false;\n });\n if (setup) {\n if (\n !confirm(\n \"A sync is running and cannot be stopped. Wait for it to finish and then clear?\",\n )\n ) {\n return false;\n }\n await waitForJob(setup.id);\n await api(\"DELETE\", target);\n return;\n }\n const parts = [];\n if (running.length) parts.push(running.length + \" running review(s)\");\n if (detail.queued) parts.push(detail.queued + \" queued job(s)\");\n if (!confirm(\"Stop \" + parts.join(\" and \") + \" and clear?\")) return false;\n try {\n await api(\"DELETE\", target + retry + \"onRunning=abort\");\n } catch (retryError) {\n // A setup job was claimed between the first 409 and this retry. It\n // cannot be aborted, so wait it out like the branch above.\n if (retryError.code !== \"job_not_abortable\") throw retryError;\n const jobId = retryError.detail && retryError.detail.id;\n if (jobId) await waitForJob(jobId);\n await api(\"DELETE\", target);\n }\n }\n}\n\nasync function postAndGo(url, body, next, btn) {\n const card = btn && btn.closest(\"[data-async]\");\n await run(btn, card, async function () {\n await api(\"POST\", url, body);\n location.href = next;\n });\n}\n\n// Called from the inline scripts on the repo list and repo pages, which deno lint\n// cannot see, so it looks unused from inside this file.\n// deno-lint-ignore no-unused-vars\n// oxlint-disable-next-line no-unused-vars\nfunction bindToggle(btn, url, field) {\n btn.addEventListener(\"click\", async function () {\n if (btn.disabled) return;\n const on = !btn.classList.contains(\"on\");\n btn.classList.toggle(\"on\", on);\n btn.setAttribute(\"data-on\", on ? \"1\" : \"0\");\n btn.disabled = true;\n const card = btn.closest(\"[data-async]\");\n try {\n const payload = {};\n payload[field] = on;\n await api(\"PATCH\", url, payload);\n } catch (err) {\n btn.classList.toggle(\"on\", !on);\n btn.setAttribute(\"data-on\", on ? \"0\" : \"1\");\n fail(card, err.message, function () {\n btn.click();\n });\n } finally {\n btn.disabled = false;\n }\n });\n}\n\nfunction logLevelClass(level) {\n return [\"info\", \"dim\", \"ok\", \"warn\", \"error\"].indexOf(level) >= 0\n ? level\n : \"info\";\n}\n\nfunction logClock(at) {\n const date = new Date(at);\n if (isNaN(date.getTime())) return \"--:--:--\";\n return date.toTimeString().slice(0, 8);\n}\n\n/** One append-only log panel. The rendered lines are the starting point, the\n * SSE stream resumes after their last seq, and a slow poll catches lines\n * written by another process (the CLI or a direct database write). */\nfunction startLogPanel(panel) {\n if (panel.getAttribute(\"data-started\") === \"1\") return;\n panel.setAttribute(\"data-started\", \"1\");\n const log = panel.querySelector(\".log\");\n if (!log) return;\n const jump = panel.querySelector(\"[data-log-jump]\");\n const jumpN = jump && jump.querySelector(\"span\");\n const count = panel.querySelector(\".cnt\");\n const pause = panel.querySelector(\"[data-log-pause]\");\n const clear = panel.querySelector(\"[data-log-clear]\");\n const status = panel.querySelector(\".st\");\n const errorBox = panel.querySelector(\"[data-log-error]\");\n const id = panel.getAttribute(\"data-job\") || panel.getAttribute(\"data-log\");\n let live = panel.getAttribute(\"data-live\") === \"1\";\n let baseStatus = live\n ? \"Running\"\n : panel.getAttribute(\"data-status\") || \"Done\";\n let baseClass = live\n ? \"run\"\n : baseStatus === \"Failed\"\n ? \"failed\"\n : baseStatus === \"Not posted\" || baseStatus === \"Canceled\"\n ? \"warn\"\n : \"done\";\n let lines = log.querySelectorAll(\".line\").length;\n let empty = log.querySelector(\".log-empty\");\n let pending = 0;\n let paused = false;\n let buffered = [];\n let lastSeq = Number(panel.getAttribute(\"data-seq\") || 0);\n if (!isFinite(lastSeq)) lastSeq = 0;\n const timers = [];\n let stream = null;\n\n function showEmpty() {\n if (empty) return;\n empty = document.createElement(\"p\");\n empty.className = \"log-empty\";\n empty.textContent =\n \"No log lines yet. New lines appear here as the job runs.\";\n log.appendChild(empty);\n }\n\n function hideEmpty() {\n if (!empty) return;\n empty.remove();\n empty = null;\n }\n\n function setError(message) {\n if (!errorBox) return;\n errorBox.textContent = message;\n errorBox.hidden = false;\n }\n\n function clearError() {\n if (!errorBox) return;\n errorBox.textContent = \"\";\n errorBox.hidden = true;\n }\n\n function atBottom() {\n return log.scrollTop + log.clientHeight >= log.scrollHeight - 4;\n }\n\n function setCount() {\n if (!count) return;\n count.textContent = lines + (lines === 1 ? \" line\" : \" lines\");\n }\n\n function setJump() {\n if (!jump) return;\n if (pending > 0) {\n if (jumpN) jumpN.textContent = \"(\" + pending + \")\";\n jump.hidden = false;\n } else {\n if (jumpN) jumpN.textContent = \"\";\n jump.hidden = true;\n }\n }\n\n function add(line) {\n if (!line || typeof line.seq !== \"number\" || line.seq <= lastSeq) return;\n const wasAtBottom = atBottom();\n const el = document.createElement(\"div\");\n el.className = \"line lv-\" + logLevelClass(line.level);\n el.setAttribute(\"data-seq\", String(line.seq));\n const t = document.createElement(\"span\");\n t.className = \"t\";\n t.textContent = logClock(line.at);\n const m = document.createElement(\"span\");\n m.className = \"msg\";\n m.textContent = String(line.message || \"\");\n el.appendChild(t);\n el.appendChild(m);\n log.appendChild(el);\n lines += 1;\n lastSeq = line.seq;\n hideEmpty();\n clearError();\n setCount();\n if (wasAtBottom) {\n log.scrollTop = log.scrollHeight;\n pending = 0;\n setJump();\n } else {\n pending += 1;\n setJump();\n }\n }\n\n function receive(line) {\n if (!line || typeof line.seq !== \"number\" || line.seq <= lastSeq) return;\n if (paused) {\n for (let index = 0; index < buffered.length; index++) {\n if (buffered[index].seq === line.seq) return;\n }\n buffered.push(line);\n return;\n }\n add(line);\n }\n\n function flush() {\n buffered.sort(function (a, b) {\n return a.seq - b.seq;\n });\n for (let index = 0; index < buffered.length; index++) add(buffered[index]);\n buffered = [];\n }\n\n function stopLive() {\n if (stream) {\n const current = stream;\n stream = null;\n try {\n current.abort();\n } catch {\n // the stream was already closed\n }\n }\n for (let index = 0; index < timers.length; index++) {\n clearInterval(timers[index]);\n }\n timers.length = 0;\n }\n\n function setLiveStatus(next) {\n live = false;\n panel.setAttribute(\"data-live\", \"0\");\n baseStatus =\n next === \"failed\" ? \"Failed\" : next === \"canceled\" ? \"Canceled\" : \"Done\";\n baseClass =\n next === \"failed\" ? \"failed\" : next === \"canceled\" ? \"warn\" : \"done\";\n panel.setAttribute(\"data-status\", baseStatus);\n if (!paused && status) {\n status.className = \"st \" + baseClass;\n status.textContent = baseStatus;\n }\n clearError();\n stopLive();\n }\n\n function poll() {\n if (!id) return;\n fetch(\"/api/jobs/\" + encodeURIComponent(id), {\n headers: { \"x-requested-with\": \"co-maintainer\" },\n })\n .then(function (res) {\n if (!res.ok) throw new Error(\"could not poll the job log\");\n return res.json();\n })\n .then(function (job) {\n if (!job) return;\n clearError();\n (job.logs || []).forEach(receive);\n if (job.status !== \"running\" && job.status !== \"queued\") {\n setLiveStatus(job.status);\n }\n })\n .catch(function () {\n if (live) setError(\"Log connection lost. Reconnecting...\");\n });\n }\n\n function connect() {\n if (!id || typeof fetch !== \"function\") return;\n const controller =\n typeof AbortController === \"function\" ? new AbortController() : null;\n stream = controller;\n fetch(\n \"/api/jobs/\" +\n encodeURIComponent(id) +\n \"/logs/stream?from=\" +\n encodeURIComponent(String(lastSeq)),\n {\n headers: {\n accept: \"text/event-stream\",\n \"x-requested-with\": \"co-maintainer\",\n },\n signal: controller ? controller.signal : undefined,\n },\n )\n .then(function (res) {\n if (!res.ok || !res.body || typeof res.body.getReader !== \"function\") {\n setError(\"Log connection lost. Reconnecting...\");\n return;\n }\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n function pump() {\n return reader.read().then(function (chunk) {\n if (chunk.done) return;\n buffer += decoder.decode(chunk.value, { stream: true });\n const frames = buffer.split(\"\\n\\n\");\n buffer = frames.pop() || \"\";\n frames.forEach(function (frame) {\n const data = [];\n frame.split(\"\\n\").forEach(function (line) {\n if (line.indexOf(\"data:\") === 0) {\n data.push(line.slice(5).replace(/^ /, \"\"));\n }\n });\n if (!data.length) return;\n try {\n receive(JSON.parse(data.join(\"\\n\")));\n } catch {\n // a malformed frame is skipped, not fatal\n }\n });\n return pump();\n });\n }\n return pump();\n })\n .catch(function () {\n if (stream === controller) {\n setError(\"Log connection lost. Reconnecting...\");\n }\n });\n }\n\n if (jump) {\n jump.addEventListener(\"click\", function () {\n log.scrollTop = log.scrollHeight;\n pending = 0;\n setJump();\n });\n }\n log.addEventListener(\"scroll\", function () {\n if (atBottom()) {\n pending = 0;\n setJump();\n }\n });\n if (pause) {\n pause.addEventListener(\"click\", function () {\n paused = !paused;\n pause.textContent = paused ? \"Resume\" : \"Pause\";\n if (status) {\n status.className = \"st \" + (paused ? \"paused\" : baseClass);\n status.textContent = paused ? \"Paused\" : baseStatus;\n }\n if (!paused) flush();\n });\n }\n if (clear) {\n clear.addEventListener(\"click\", function () {\n for (let index = 0; index < buffered.length; index++) {\n if (buffered[index].seq > lastSeq) lastSeq = buffered[index].seq;\n }\n log.replaceChildren();\n lines = 0;\n pending = 0;\n buffered = [];\n showEmpty();\n setCount();\n setJump();\n });\n }\n setCount();\n setJump();\n if (live) {\n connect();\n timers.push(setInterval(poll, 1000));\n }\n}\n\n/** The Ctrl K palette. Every query gets a sequence number and only the\n * newest answer is drawn, so a slow reply to an older query never replaces\n * the results of the newer one. The highlighted row is the one Enter opens. */\nfunction startPalette() {\n const pal = document.getElementById(\"pal\");\n const overlay = document.getElementById(\"pal-ov\");\n const input = document.getElementById(\"pal-q\");\n const list = document.getElementById(\"pal-list\");\n if (!pal || !overlay || !input || !list) return;\n let returnFocus = null;\n let seq = 0;\n let timer = 0;\n let index = 0;\n\n function items() {\n return list.querySelectorAll(\"[data-href]\");\n }\n function highlight(next) {\n const rows = items();\n if (rows.length === 0) return;\n index = (next + rows.length) % rows.length;\n rows.forEach(function (row, i) {\n row.classList.toggle(\"on\", i === index);\n row.setAttribute(\"aria-selected\", i === index ? \"true\" : \"false\");\n });\n input.setAttribute(\"aria-activedescendant\", rows[index].id);\n rows[index].scrollIntoView({ block: \"nearest\" });\n }\n function draw(result) {\n list.textContent = \"\";\n if (result.groups.length === 0) {\n const empty = document.createElement(\"div\");\n empty.className = \"none\";\n empty.textContent = \"No results\";\n list.appendChild(empty);\n input.removeAttribute(\"aria-activedescendant\");\n return;\n }\n let n = 0;\n result.groups.forEach(function (group) {\n const label = document.createElement(\"div\");\n label.className = \"gl\";\n label.textContent = group.label;\n list.appendChild(label);\n group.items.forEach(function (item) {\n const row = document.createElement(\"a\");\n row.className = \"it\";\n row.id = \"pal-it-\" + n++;\n row.href = item.href;\n row.setAttribute(\"data-href\", item.href);\n row.setAttribute(\"role\", \"option\");\n row.setAttribute(\"aria-selected\", \"false\");\n const name = document.createElement(\"span\");\n name.className = \"lbl\";\n name.textContent = item.label;\n row.innerHTML =\n '<svg class=\"ic\" aria-hidden=\"true\"><use href=\"#i-' +\n String(item.icon).replace(/[^a-z0-9-]/g, \"\") +\n '\"></use></svg>';\n row.appendChild(name);\n list.appendChild(row);\n });\n });\n highlight(0);\n }\n async function search() {\n const mine = ++seq;\n pal.setAttribute(\"data-loading\", \"\");\n try {\n const res = await fetch(\n \"/api/search?q=\" + encodeURIComponent(input.value),\n { headers: { \"x-requested-with\": \"co-maintainer\" } },\n );\n const result = await res.json();\n if (mine !== seq) return;\n draw(res.ok ? result : { groups: [] });\n } catch {\n if (mine === seq) draw({ groups: [] });\n } finally {\n if (mine === seq) pal.removeAttribute(\"data-loading\");\n }\n }\n function open() {\n if (!pal.hidden) return;\n returnFocus = document.activeElement;\n pal.hidden = false;\n overlay.hidden = false;\n input.value = \"\";\n input.focus();\n search();\n }\n function close() {\n if (pal.hidden) return;\n pal.hidden = true;\n overlay.hidden = true;\n seq++;\n pal.removeAttribute(\"data-loading\");\n if (returnFocus && returnFocus.focus) returnFocus.focus();\n }\n\n document.addEventListener(\"click\", function (ev) {\n if (ev.target && ev.target.closest && ev.target.closest(\"[data-palette]\")) {\n ev.preventDefault();\n open();\n }\n });\n overlay.addEventListener(\"click\", close);\n document.addEventListener(\"keydown\", function (ev) {\n if ((ev.ctrlKey || ev.metaKey) && ev.key.toLowerCase() === \"k\") {\n ev.preventDefault();\n if (pal.hidden) open();\n else close();\n return;\n }\n if (pal.hidden) return;\n if (ev.key === \"Escape\") {\n ev.preventDefault();\n close();\n } else if (ev.key === \"ArrowDown\") {\n ev.preventDefault();\n highlight(index + 1);\n } else if (ev.key === \"ArrowUp\") {\n ev.preventDefault();\n highlight(index - 1);\n } else if (ev.key === \"Enter\" && ev.target === input) {\n const row = items()[index];\n if (row && !pal.hasAttribute(\"data-loading\")) {\n ev.preventDefault();\n location.href = row.getAttribute(\"data-href\");\n }\n }\n });\n input.addEventListener(\"input\", function () {\n clearTimeout(timer);\n pal.setAttribute(\"data-loading\", \"\");\n timer = setTimeout(search, 120);\n });\n}\n\nfunction startLogPanels() {\n const panels = document.querySelectorAll(\"[data-log]\");\n for (let index = 0; index < panels.length; index++) {\n startLogPanel(panels[index]);\n }\n}\n\n// The helper is inlined into `<head>` by `layout.ts`, before any page script\n// runs, so this is the one place that can close over both `toast()` and\n// `bindToggle` without depending on point-in-time globals.\ndocument.addEventListener(\"DOMContentLoaded\", function () {\n // Client errors bubble to `window` from `document`.\n addEventListener(\"error\", function (ev) {\n toast((ev.error && ev.error.message) || \"Something broke\");\n });\n addEventListener(\"unhandledrejection\", function (ev) {\n toast((ev.reason && ev.reason.message) || \"Something broke\");\n });\n\n // Theme: the head bootstrap already applied the remembered choice; this only\n // flips it and stores the new one.\n const themeButton = document.getElementById(\"theme\");\n if (themeButton) {\n themeButton.addEventListener(\"click\", function () {\n const dark = document.documentElement.classList.toggle(\"dark\");\n try {\n localStorage.setItem(\"theme\", dark ? \"dark\" : \"light\");\n } catch {\n // storage may be unavailable; the class still applies for this page\n }\n });\n }\n\n // Mobile drawer. `open` on the aside slides it in; the overlay closes it and\n // choosing a link closes it before navigating.\n const drawer = document.querySelector(\"aside.side\");\n const overlay = document.getElementById(\"overlay\");\n const menuButton = document.getElementById(\"menu\");\n function setDrawer(open) {\n if (drawer) drawer.classList.toggle(\"open\", open);\n if (overlay) overlay.classList.toggle(\"on\", open);\n }\n if (menuButton) {\n menuButton.addEventListener(\"click\", function () {\n setDrawer(!(drawer && drawer.classList.contains(\"open\")));\n });\n }\n if (overlay) {\n overlay.addEventListener(\"click\", function () {\n setDrawer(false);\n });\n }\n if (drawer) {\n drawer.addEventListener(\"click\", function (ev) {\n if (ev.target && ev.target.closest && ev.target.closest(\"a\")) {\n setDrawer(false);\n }\n });\n }\n\n startPalette();\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest ? ev.target.closest(\"[data-copy]\") : null;\n if (!btn) return;\n const box = btn.closest(\".code\");\n const span = box && box.querySelector(\"span:not(.lbl)\");\n if (!span) return;\n ev.preventDefault();\n copyText(\n span.textContent || \"\",\n function () {\n toast(\"Copied\");\n },\n function () {\n toast(\"Copy failed. Select the text and copy it by hand.\");\n },\n );\n });\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest\n ? ev.target.closest(\"[data-copy-doc]\")\n : null;\n if (!btn) return;\n ev.preventDefault();\n const id = btn.getAttribute(\"data-copy-doc\");\n const sources = document.querySelectorAll(\"[data-doc-source]\");\n let source = null;\n for (let index = 0; index < sources.length; index++) {\n if (sources[index].getAttribute(\"data-doc-source\") === id) {\n source = sources[index];\n break;\n }\n }\n if (!source) return;\n copyText(\n source.textContent || \"\",\n function () {\n toast(\"Copied\");\n },\n function () {\n toast(\"Copy failed. Select the text and copy it by hand.\");\n },\n );\n });\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest\n ? ev.target.closest(\"[data-cancel], [data-post]\")\n : null;\n if (!btn) return;\n ev.preventDefault();\n if (btn.hasAttribute(\"data-cancel\")) {\n postAndGo(\n \"/api/jobs/\" + btn.getAttribute(\"data-cancel\") + \"/cancel\",\n {},\n \"/activity\",\n btn,\n );\n return;\n }\n const body = btn.getAttribute(\"data-body\");\n postAndGo(\n btn.getAttribute(\"data-post\"),\n body ? JSON.parse(body) : {},\n \"/activity\",\n btn,\n );\n });\n\n // Reads `activity-root` at call time, so it has to wait for the body even\n // though this file itself is already parsed.\n startLogPanels();\n if (!document.getElementById(\"activity-root\")) return;\n const jobPanel = document.querySelector(\"[data-log]\");\n if (jobPanel) {\n if (jobPanel.getAttribute(\"data-live\") !== \"1\") return;\n const progress = document.querySelector(\"[data-job-progress]\");\n if (!progress) return;\n const refreshError = document.querySelector(\"[data-job-refresh-error]\");\n let refreshing = false;\n const refreshJob = async function () {\n if (document.hidden || refreshing) return;\n refreshing = true;\n try {\n const res = await fetch(location.pathname + location.search, {\n headers: { accept: \"text/html\" },\n cache: \"no-store\",\n });\n if (!res.ok) throw new Error(\"refresh failed\");\n const doc = new DOMParser().parseFromString(\n await res.text(),\n \"text/html\",\n );\n const next = doc.querySelector(\"[data-job-progress]\");\n // A finished job renders its result page, which has no progress\n // block: load it rather than keep the running stages and Stop.\n if (!next) {\n location.reload();\n return;\n }\n progress.innerHTML = next.innerHTML;\n if (refreshError) {\n refreshError.textContent = \"\";\n refreshError.hidden = true;\n }\n } catch {\n if (refreshError) {\n refreshError.textContent =\n \"Connection lost. Could not refresh this job. Reconnecting...\";\n refreshError.hidden = false;\n }\n } finally {\n refreshing = false;\n }\n };\n setInterval(refreshJob, 2000);\n return;\n }\n setInterval(async function () {\n if (document.hidden) return;\n if (document.querySelector(\"[data-async].busy\")) return;\n const root = document.getElementById(\"activity-root\");\n if (!root) return;\n try {\n const res = await fetch(location.pathname + location.search, {\n headers: { accept: \"text/html\" },\n });\n if (!res.ok) return;\n const doc = new DOMParser().parseFromString(\n await res.text(),\n \"text/html\",\n );\n const next = doc.getElementById(\"activity-root\");\n if (!next || next.innerHTML === root.innerHTML) return;\n root.replaceWith(next);\n } catch {\n // a failed poll just waits for the next tick\n }\n }, 5000);\n});\n";
1
+ /** Generated from src/server/pages/client.js by scripts/embed_assets.mjs, do not edit. */
2
+ export declare const client = "function toast(message) {\n const host = document.getElementById(\"toasts\");\n if (!host) return;\n const el = document.createElement(\"div\");\n el.className = \"toast\";\n el.setAttribute(\"role\", \"status\");\n el.textContent = message;\n host.appendChild(el);\n setTimeout(function () {\n el.remove();\n }, 5000);\n}\n\nfunction fail(card, message, retry) {\n toast(message);\n if (!card) return;\n let box = card.querySelector(\"[data-fail]\");\n if (!box) {\n box = document.createElement(\"div\");\n box.setAttribute(\"data-fail\", \"1\");\n box.className = \"fail\";\n card.appendChild(box);\n }\n box.replaceChildren();\n const p = document.createElement(\"p\");\n p.textContent = message;\n const btn = document.createElement(\"button\");\n btn.className = \"btn sm\";\n btn.type = \"button\";\n btn.textContent = \"Retry\";\n btn.addEventListener(\"click\", retry);\n box.appendChild(p);\n box.appendChild(btn);\n}\n\nfunction clearFail(card) {\n const box = card && card.querySelector(\"[data-fail]\");\n if (box) box.remove();\n}\n\n/** Copy text for the `codeBlock` copy button. `navigator.clipboard` needs a\n * secure context, so the hidden-textarea path keeps Copy working on plain\n * http://localhost too. `done` runs only when one of the two paths worked. */\nfunction copyText(value, done, failed) {\n function fallback() {\n if (legacyCopy(value)) done();\n else if (failed) failed();\n }\n if (navigator.clipboard && navigator.clipboard.writeText) {\n navigator.clipboard.writeText(value).then(done, fallback);\n return;\n }\n fallback();\n}\n\nfunction legacyCopy(value) {\n const area = document.createElement(\"textarea\");\n area.value = value;\n area.setAttribute(\"readonly\", \"\");\n area.style.position = \"fixed\";\n area.style.opacity = \"0\";\n document.body.appendChild(area);\n area.select();\n let copied = false;\n try {\n copied = document.execCommand(\"copy\") === true;\n } catch {\n copied = false;\n }\n area.remove();\n return copied;\n}\n\nfunction skeleton(card, on) {\n if (!card) return;\n card.classList.toggle(\"busy\", on);\n}\n\nasync function api(method, url, body) {\n const res = await fetch(url, {\n method: method,\n headers: {\n \"content-type\": \"application/json\",\n \"x-requested-with\": \"co-maintainer\",\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n if (!res.ok) {\n let message = \"Request failed\";\n let code = \"\";\n let detail;\n try {\n const data = await res.json();\n if (data.error && data.error.message) message = data.error.message;\n if (data.error && data.error.code) code = data.error.code;\n if (data.error) detail = data.error.detail;\n } catch {\n // body was not JSON. Keep the generic message\n }\n const error = new Error(message);\n if (code) error.code = code;\n error.detail = detail;\n throw error;\n }\n if (res.status === 204) return null;\n return await res.json();\n}\n\nasync function run(btn, card, fn) {\n if (btn) btn.disabled = true;\n skeleton(card, true);\n clearFail(card);\n try {\n await fn();\n } catch (err) {\n fail(card, err.message, function () {\n run(btn, card, fn);\n });\n } finally {\n if (btn) btn.disabled = false;\n skeleton(card, false);\n }\n}\n\nfunction saved(btn, card) {\n if (card) {\n let state = card.querySelector(\".save-state\");\n if (!state) {\n state = document.createElement(\"span\");\n state.className = \"save-state\";\n state.setAttribute(\"role\", \"status\");\n if (btn && btn.parentNode) {\n btn.parentNode.insertBefore(state, btn.nextSibling);\n }\n }\n state.textContent = \"Saved\";\n }\n toast(\"Saved\");\n}\nglobalThis.saved = saved;\n\n/** Polls one job until it reaches a terminal status. A running `init`/`remake`\n * ignores the abort signal, so \"wait for the sync\" is the only honest option\n * the clear pages can offer for it. */\nfunction waitForJob(id) {\n return new Promise(function (resolve, reject) {\n let attempts = 0;\n async function tick() {\n attempts++;\n try {\n const res = await fetch(\"/api/jobs/\" + encodeURIComponent(id), {\n headers: { \"x-requested-with\": \"co-maintainer\" },\n });\n if (!res.ok) throw new Error(\"Could not check the running job.\");\n const job = await res.json();\n if (job.status !== \"running\" && job.status !== \"queued\") {\n resolve();\n return;\n }\n if (attempts > 1200) {\n reject(new Error(\"The sync did not finish.\"));\n return;\n }\n setTimeout(tick, 3000);\n } catch (err) {\n reject(err);\n }\n }\n tick();\n });\n}\n\n/** Clears knowledge, asking about pending jobs when the server refuses.\n * Returns false when the user backed out, so the caller does not reload.\n * A running review is abortable and a running setup is not, which is the\n * difference between the two questions. Called from the inline scripts on the\n * knowledge pages, so it looks unused from inside this file. */\n// oxlint-disable-next-line no-unused-vars\nasync function clearKnowledge(url, includeCache) {\n const target = includeCache ? url + \"?includeCache=1\" : url;\n const retry = target.indexOf(\"?\") >= 0 ? \"&\" : \"?\";\n try {\n await api(\"DELETE\", target);\n } catch (err) {\n if (err.code !== \"jobs_running\") throw err;\n const detail = err.detail || { queued: 0, running: [] };\n const running = detail.running || [];\n const setup = running.find(function (job) {\n return job.abortable === false;\n });\n if (setup) {\n if (\n !confirm(\n \"A sync is running and cannot be stopped. Wait for it to finish and then clear?\",\n )\n ) {\n return false;\n }\n await waitForJob(setup.id);\n await api(\"DELETE\", target);\n return;\n }\n const parts = [];\n if (running.length) parts.push(running.length + \" running review(s)\");\n if (detail.queued) parts.push(detail.queued + \" queued job(s)\");\n if (!confirm(\"Stop \" + parts.join(\" and \") + \" and clear?\")) return false;\n try {\n await api(\"DELETE\", target + retry + \"onRunning=abort\");\n } catch (retryError) {\n // A setup job was claimed between the first 409 and this retry. It\n // cannot be aborted, so wait it out like the branch above.\n if (retryError.code !== \"job_not_abortable\") throw retryError;\n const jobId = retryError.detail && retryError.detail.id;\n if (jobId) await waitForJob(jobId);\n await api(\"DELETE\", target);\n }\n }\n}\n\nasync function postAndGo(url, body, next, btn) {\n const card = btn && btn.closest(\"[data-async]\");\n await run(btn, card, async function () {\n await api(\"POST\", url, body);\n location.href = next;\n });\n}\n\n// Called from the inline scripts on the repo list and repo pages, which deno lint\n// cannot see, so it looks unused from inside this file.\n// deno-lint-ignore no-unused-vars\n// oxlint-disable-next-line no-unused-vars\nfunction bindToggle(btn, url, field) {\n btn.addEventListener(\"click\", async function () {\n if (btn.disabled) return;\n const on = !btn.classList.contains(\"on\");\n btn.classList.toggle(\"on\", on);\n btn.setAttribute(\"data-on\", on ? \"1\" : \"0\");\n btn.disabled = true;\n const card = btn.closest(\"[data-async]\");\n try {\n const payload = {};\n payload[field] = on;\n await api(\"PATCH\", url, payload);\n } catch (err) {\n btn.classList.toggle(\"on\", !on);\n btn.setAttribute(\"data-on\", on ? \"0\" : \"1\");\n fail(card, err.message, function () {\n btn.click();\n });\n } finally {\n btn.disabled = false;\n }\n });\n}\n\nfunction logLevelClass(level) {\n return [\"info\", \"dim\", \"ok\", \"warn\", \"error\"].indexOf(level) >= 0\n ? level\n : \"info\";\n}\n\nfunction logClock(at) {\n const date = new Date(at);\n if (isNaN(date.getTime())) return \"--:--:--\";\n return date.toTimeString().slice(0, 8);\n}\n\n/** One append-only log panel. The rendered lines are the starting point, the\n * SSE stream resumes after their last seq, and a slow poll catches lines\n * written by another process (the CLI or a direct database write). */\nfunction startLogPanel(panel) {\n if (panel.getAttribute(\"data-started\") === \"1\") return;\n panel.setAttribute(\"data-started\", \"1\");\n const log = panel.querySelector(\".log\");\n if (!log) return;\n const jump = panel.querySelector(\"[data-log-jump]\");\n const jumpN = jump && jump.querySelector(\"span\");\n const count = panel.querySelector(\".cnt\");\n const pause = panel.querySelector(\"[data-log-pause]\");\n const clear = panel.querySelector(\"[data-log-clear]\");\n const status = panel.querySelector(\".st\");\n const errorBox = panel.querySelector(\"[data-log-error]\");\n const id = panel.getAttribute(\"data-job\") || panel.getAttribute(\"data-log\");\n let live = panel.getAttribute(\"data-live\") === \"1\";\n let baseStatus = live\n ? \"Running\"\n : panel.getAttribute(\"data-status\") || \"Done\";\n let baseClass = live\n ? \"run\"\n : baseStatus === \"Failed\"\n ? \"failed\"\n : baseStatus === \"Not posted\" || baseStatus === \"Canceled\"\n ? \"warn\"\n : \"done\";\n let lines = log.querySelectorAll(\".line\").length;\n let empty = log.querySelector(\".log-empty\");\n let pending = 0;\n let paused = false;\n let buffered = [];\n let lastSeq = Number(panel.getAttribute(\"data-seq\") || 0);\n if (!isFinite(lastSeq)) lastSeq = 0;\n const timers = [];\n let stream = null;\n\n function showEmpty() {\n if (empty) return;\n empty = document.createElement(\"p\");\n empty.className = \"log-empty\";\n empty.textContent =\n \"No log lines yet. New lines appear here as the job runs.\";\n log.appendChild(empty);\n }\n\n function hideEmpty() {\n if (!empty) return;\n empty.remove();\n empty = null;\n }\n\n function setError(message) {\n if (!errorBox) return;\n errorBox.textContent = message;\n errorBox.hidden = false;\n }\n\n function clearError() {\n if (!errorBox) return;\n errorBox.textContent = \"\";\n errorBox.hidden = true;\n }\n\n function atBottom() {\n return log.scrollTop + log.clientHeight >= log.scrollHeight - 4;\n }\n\n function setCount() {\n if (!count) return;\n count.textContent = lines + (lines === 1 ? \" line\" : \" lines\");\n }\n\n function setJump() {\n if (!jump) return;\n if (pending > 0) {\n if (jumpN) jumpN.textContent = \"(\" + pending + \")\";\n jump.hidden = false;\n } else {\n if (jumpN) jumpN.textContent = \"\";\n jump.hidden = true;\n }\n }\n\n function add(line) {\n if (!line || typeof line.seq !== \"number\" || line.seq <= lastSeq) return;\n const wasAtBottom = atBottom();\n const el = document.createElement(\"div\");\n el.className = \"line lv-\" + logLevelClass(line.level);\n el.setAttribute(\"data-seq\", String(line.seq));\n const t = document.createElement(\"span\");\n t.className = \"t\";\n t.textContent = logClock(line.at);\n const m = document.createElement(\"span\");\n m.className = \"msg\";\n m.textContent = String(line.message || \"\");\n el.appendChild(t);\n el.appendChild(m);\n log.appendChild(el);\n lines += 1;\n lastSeq = line.seq;\n hideEmpty();\n clearError();\n setCount();\n if (wasAtBottom) {\n log.scrollTop = log.scrollHeight;\n pending = 0;\n setJump();\n } else {\n pending += 1;\n setJump();\n }\n }\n\n function receive(line) {\n if (!line || typeof line.seq !== \"number\" || line.seq <= lastSeq) return;\n if (paused) {\n for (let index = 0; index < buffered.length; index++) {\n if (buffered[index].seq === line.seq) return;\n }\n buffered.push(line);\n return;\n }\n add(line);\n }\n\n function flush() {\n buffered.sort(function (a, b) {\n return a.seq - b.seq;\n });\n for (let index = 0; index < buffered.length; index++) add(buffered[index]);\n buffered = [];\n }\n\n function stopLive() {\n if (stream) {\n const current = stream;\n stream = null;\n try {\n current.abort();\n } catch {\n // the stream was already closed\n }\n }\n for (let index = 0; index < timers.length; index++) {\n clearInterval(timers[index]);\n }\n timers.length = 0;\n }\n\n function setLiveStatus(next) {\n live = false;\n panel.setAttribute(\"data-live\", \"0\");\n baseStatus =\n next === \"failed\" ? \"Failed\" : next === \"canceled\" ? \"Canceled\" : \"Done\";\n baseClass =\n next === \"failed\" ? \"failed\" : next === \"canceled\" ? \"warn\" : \"done\";\n panel.setAttribute(\"data-status\", baseStatus);\n if (!paused && status) {\n status.className = \"st \" + baseClass;\n status.textContent = baseStatus;\n }\n clearError();\n stopLive();\n }\n\n function poll() {\n if (!id) return;\n fetch(\"/api/jobs/\" + encodeURIComponent(id), {\n headers: { \"x-requested-with\": \"co-maintainer\" },\n })\n .then(function (res) {\n if (!res.ok) throw new Error(\"could not poll the job log\");\n return res.json();\n })\n .then(function (job) {\n if (!job) return;\n clearError();\n (job.logs || []).forEach(receive);\n if (job.status !== \"running\" && job.status !== \"queued\") {\n setLiveStatus(job.status);\n }\n })\n .catch(function () {\n if (live) setError(\"Log connection lost. Reconnecting...\");\n });\n }\n\n function connect() {\n if (!id || typeof fetch !== \"function\") return;\n const controller =\n typeof AbortController === \"function\" ? new AbortController() : null;\n stream = controller;\n fetch(\n \"/api/jobs/\" +\n encodeURIComponent(id) +\n \"/logs/stream?from=\" +\n encodeURIComponent(String(lastSeq)),\n {\n headers: {\n accept: \"text/event-stream\",\n \"x-requested-with\": \"co-maintainer\",\n },\n signal: controller ? controller.signal : undefined,\n },\n )\n .then(function (res) {\n if (!res.ok || !res.body || typeof res.body.getReader !== \"function\") {\n setError(\"Log connection lost. Reconnecting...\");\n return;\n }\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n function pump() {\n return reader.read().then(function (chunk) {\n if (chunk.done) return;\n buffer += decoder.decode(chunk.value, { stream: true });\n const frames = buffer.split(\"\\n\\n\");\n buffer = frames.pop() || \"\";\n frames.forEach(function (frame) {\n const data = [];\n frame.split(\"\\n\").forEach(function (line) {\n if (line.indexOf(\"data:\") === 0) {\n data.push(line.slice(5).replace(/^ /, \"\"));\n }\n });\n if (!data.length) return;\n try {\n receive(JSON.parse(data.join(\"\\n\")));\n } catch {\n // a malformed frame is skipped, not fatal\n }\n });\n return pump();\n });\n }\n return pump();\n })\n .catch(function () {\n if (stream === controller) {\n setError(\"Log connection lost. Reconnecting...\");\n }\n });\n }\n\n if (jump) {\n jump.addEventListener(\"click\", function () {\n log.scrollTop = log.scrollHeight;\n pending = 0;\n setJump();\n });\n }\n log.addEventListener(\"scroll\", function () {\n if (atBottom()) {\n pending = 0;\n setJump();\n }\n });\n if (pause) {\n pause.addEventListener(\"click\", function () {\n paused = !paused;\n pause.textContent = paused ? \"Resume\" : \"Pause\";\n if (status) {\n status.className = \"st \" + (paused ? \"paused\" : baseClass);\n status.textContent = paused ? \"Paused\" : baseStatus;\n }\n if (!paused) flush();\n });\n }\n if (clear) {\n clear.addEventListener(\"click\", function () {\n for (let index = 0; index < buffered.length; index++) {\n if (buffered[index].seq > lastSeq) lastSeq = buffered[index].seq;\n }\n log.replaceChildren();\n lines = 0;\n pending = 0;\n buffered = [];\n showEmpty();\n setCount();\n setJump();\n });\n }\n setCount();\n setJump();\n if (live) {\n connect();\n timers.push(setInterval(poll, 1000));\n }\n}\n\n/** The Ctrl K palette. Every query gets a sequence number and only the\n * newest answer is drawn, so a slow reply to an older query never replaces\n * the results of the newer one. The highlighted row is the one Enter opens. */\nfunction startPalette() {\n const pal = document.getElementById(\"pal\");\n const overlay = document.getElementById(\"pal-ov\");\n const input = document.getElementById(\"pal-q\");\n const list = document.getElementById(\"pal-list\");\n if (!pal || !overlay || !input || !list) return;\n let returnFocus = null;\n let seq = 0;\n let timer = 0;\n let index = 0;\n\n function items() {\n return list.querySelectorAll(\"[data-href]\");\n }\n function highlight(next) {\n const rows = items();\n if (rows.length === 0) return;\n index = (next + rows.length) % rows.length;\n rows.forEach(function (row, i) {\n row.classList.toggle(\"on\", i === index);\n row.setAttribute(\"aria-selected\", i === index ? \"true\" : \"false\");\n });\n input.setAttribute(\"aria-activedescendant\", rows[index].id);\n rows[index].scrollIntoView({ block: \"nearest\" });\n }\n function draw(result) {\n list.textContent = \"\";\n if (result.groups.length === 0) {\n const empty = document.createElement(\"div\");\n empty.className = \"none\";\n empty.textContent = \"No results\";\n list.appendChild(empty);\n input.removeAttribute(\"aria-activedescendant\");\n return;\n }\n let n = 0;\n result.groups.forEach(function (group) {\n const label = document.createElement(\"div\");\n label.className = \"gl\";\n label.textContent = group.label;\n list.appendChild(label);\n group.items.forEach(function (item) {\n const row = document.createElement(\"a\");\n row.className = \"it\";\n row.id = \"pal-it-\" + n++;\n row.href = item.href;\n row.setAttribute(\"data-href\", item.href);\n row.setAttribute(\"role\", \"option\");\n row.setAttribute(\"aria-selected\", \"false\");\n const name = document.createElement(\"span\");\n name.className = \"lbl\";\n name.textContent = item.label;\n row.innerHTML =\n '<svg class=\"ic\" aria-hidden=\"true\"><use href=\"#i-' +\n String(item.icon).replace(/[^a-z0-9-]/g, \"\") +\n '\"></use></svg>';\n row.appendChild(name);\n list.appendChild(row);\n });\n });\n highlight(0);\n }\n async function search() {\n const mine = ++seq;\n pal.setAttribute(\"data-loading\", \"\");\n try {\n const res = await fetch(\n \"/api/search?q=\" + encodeURIComponent(input.value),\n { headers: { \"x-requested-with\": \"co-maintainer\" } },\n );\n const result = await res.json();\n if (mine !== seq) return;\n draw(res.ok ? result : { groups: [] });\n } catch {\n if (mine === seq) draw({ groups: [] });\n } finally {\n if (mine === seq) pal.removeAttribute(\"data-loading\");\n }\n }\n function open() {\n if (!pal.hidden) return;\n returnFocus = document.activeElement;\n pal.hidden = false;\n overlay.hidden = false;\n input.value = \"\";\n input.focus();\n search();\n }\n function close() {\n if (pal.hidden) return;\n pal.hidden = true;\n overlay.hidden = true;\n seq++;\n pal.removeAttribute(\"data-loading\");\n if (returnFocus && returnFocus.focus) returnFocus.focus();\n }\n\n document.addEventListener(\"click\", function (ev) {\n if (ev.target && ev.target.closest && ev.target.closest(\"[data-palette]\")) {\n ev.preventDefault();\n open();\n }\n });\n overlay.addEventListener(\"click\", close);\n document.addEventListener(\"keydown\", function (ev) {\n if ((ev.ctrlKey || ev.metaKey) && ev.key.toLowerCase() === \"k\") {\n ev.preventDefault();\n if (pal.hidden) open();\n else close();\n return;\n }\n if (pal.hidden) return;\n if (ev.key === \"Escape\") {\n ev.preventDefault();\n close();\n } else if (ev.key === \"ArrowDown\") {\n ev.preventDefault();\n highlight(index + 1);\n } else if (ev.key === \"ArrowUp\") {\n ev.preventDefault();\n highlight(index - 1);\n } else if (ev.key === \"Enter\" && ev.target === input) {\n const row = items()[index];\n if (row && !pal.hasAttribute(\"data-loading\")) {\n ev.preventDefault();\n location.href = row.getAttribute(\"data-href\");\n }\n }\n });\n input.addEventListener(\"input\", function () {\n clearTimeout(timer);\n pal.setAttribute(\"data-loading\", \"\");\n timer = setTimeout(search, 120);\n });\n}\n\nfunction startLogPanels() {\n const panels = document.querySelectorAll(\"[data-log]\");\n for (let index = 0; index < panels.length; index++) {\n startLogPanel(panels[index]);\n }\n}\n\n// The helper is inlined into `<head>` by `layout.ts`, before any page script\n// runs, so this is the one place that can close over both `toast()` and\n// `bindToggle` without depending on point-in-time globals.\ndocument.addEventListener(\"DOMContentLoaded\", function () {\n // Client errors bubble to `window` from `document`.\n addEventListener(\"error\", function (ev) {\n toast((ev.error && ev.error.message) || \"Something broke\");\n });\n addEventListener(\"unhandledrejection\", function (ev) {\n toast((ev.reason && ev.reason.message) || \"Something broke\");\n });\n\n // Theme: the head bootstrap already applied the remembered choice. This only\n // flips it and stores the new one.\n const themeButton = document.getElementById(\"theme\");\n if (themeButton) {\n themeButton.addEventListener(\"click\", function () {\n const dark = document.documentElement.classList.toggle(\"dark\");\n try {\n localStorage.setItem(\"theme\", dark ? \"dark\" : \"light\");\n } catch {\n // storage may be unavailable. The class still applies for this page\n }\n });\n }\n\n // Mobile drawer. `open` on the aside slides it in. The overlay closes it and\n // choosing a link closes it before navigating.\n const drawer = document.querySelector(\"aside.side\");\n const overlay = document.getElementById(\"overlay\");\n const menuButton = document.getElementById(\"menu\");\n function setDrawer(open) {\n if (drawer) drawer.classList.toggle(\"open\", open);\n if (overlay) overlay.classList.toggle(\"on\", open);\n }\n if (menuButton) {\n menuButton.addEventListener(\"click\", function () {\n setDrawer(!(drawer && drawer.classList.contains(\"open\")));\n });\n }\n if (overlay) {\n overlay.addEventListener(\"click\", function () {\n setDrawer(false);\n });\n }\n if (drawer) {\n drawer.addEventListener(\"click\", function (ev) {\n if (ev.target && ev.target.closest && ev.target.closest(\"a\")) {\n setDrawer(false);\n }\n });\n }\n\n startPalette();\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest ? ev.target.closest(\"[data-copy]\") : null;\n if (!btn) return;\n const box = btn.closest(\".code\");\n const span = box && box.querySelector(\"span:not(.lbl)\");\n if (!span) return;\n ev.preventDefault();\n copyText(\n span.textContent || \"\",\n function () {\n toast(\"Copied\");\n },\n function () {\n toast(\"Copy failed. Select the text and copy it by hand.\");\n },\n );\n });\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest\n ? ev.target.closest(\"[data-copy-doc]\")\n : null;\n if (!btn) return;\n ev.preventDefault();\n const id = btn.getAttribute(\"data-copy-doc\");\n const sources = document.querySelectorAll(\"[data-doc-source]\");\n let source = null;\n for (let index = 0; index < sources.length; index++) {\n if (sources[index].getAttribute(\"data-doc-source\") === id) {\n source = sources[index];\n break;\n }\n }\n if (!source) return;\n copyText(\n source.textContent || \"\",\n function () {\n toast(\"Copied\");\n },\n function () {\n toast(\"Copy failed. Select the text and copy it by hand.\");\n },\n );\n });\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest\n ? ev.target.closest(\"[data-cancel], [data-post]\")\n : null;\n if (!btn) return;\n ev.preventDefault();\n if (btn.hasAttribute(\"data-cancel\")) {\n postAndGo(\n \"/api/jobs/\" + btn.getAttribute(\"data-cancel\") + \"/cancel\",\n {},\n \"/activity\",\n btn,\n );\n return;\n }\n const body = btn.getAttribute(\"data-body\");\n postAndGo(\n btn.getAttribute(\"data-post\"),\n body ? JSON.parse(body) : {},\n \"/activity\",\n btn,\n );\n });\n\n // Reads `activity-root` at call time, so it has to wait for the body even\n // though this file itself is already parsed.\n startLogPanels();\n if (!document.getElementById(\"activity-root\")) return;\n const jobPanel = document.querySelector(\"[data-log]\");\n if (jobPanel) {\n if (jobPanel.getAttribute(\"data-live\") !== \"1\") return;\n const progress = document.querySelector(\"[data-job-progress]\");\n if (!progress) return;\n const refreshError = document.querySelector(\"[data-job-refresh-error]\");\n let refreshing = false;\n const refreshJob = async function () {\n if (document.hidden || refreshing) return;\n refreshing = true;\n try {\n const res = await fetch(location.pathname + location.search, {\n headers: { accept: \"text/html\" },\n cache: \"no-store\",\n });\n if (!res.ok) throw new Error(\"refresh failed\");\n const doc = new DOMParser().parseFromString(\n await res.text(),\n \"text/html\",\n );\n const next = doc.querySelector(\"[data-job-progress]\");\n // A finished job renders its result page, which has no progress\n // block: load it rather than keep the running stages and Stop.\n if (!next) {\n location.reload();\n return;\n }\n progress.innerHTML = next.innerHTML;\n if (refreshError) {\n refreshError.textContent = \"\";\n refreshError.hidden = true;\n }\n } catch {\n if (refreshError) {\n refreshError.textContent =\n \"Connection lost. Could not refresh this job. Reconnecting...\";\n refreshError.hidden = false;\n }\n } finally {\n refreshing = false;\n }\n };\n setInterval(refreshJob, 2000);\n return;\n }\n setInterval(async function () {\n if (document.hidden) return;\n if (document.querySelector(\"[data-async].busy\")) return;\n const root = document.getElementById(\"activity-root\");\n if (!root) return;\n try {\n const res = await fetch(location.pathname + location.search, {\n headers: { accept: \"text/html\" },\n });\n if (!res.ok) return;\n const doc = new DOMParser().parseFromString(\n await res.text(),\n \"text/html\",\n );\n const next = doc.getElementById(\"activity-root\");\n if (!next || next.innerHTML === root.innerHTML) return;\n root.replaceWith(next);\n } catch {\n // a failed poll just waits for the next tick\n }\n }, 5000);\n});\n";