@demon-utils/playwright 0.1.6 → 0.1.7

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.
@@ -0,0 +1,1421 @@
1
+ import { createRequire } from "node:module";
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __toESM = (mod, isNodeMode, target) => {
8
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
9
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
10
+ for (let key of __getOwnPropNames(mod))
11
+ if (!__hasOwnProp.call(to, key))
12
+ __defProp(to, key, {
13
+ get: () => mod[key],
14
+ enumerable: true
15
+ });
16
+ return to;
17
+ };
18
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
19
+
20
+ // src/review-generator.ts
21
+ import { existsSync, readdirSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
22
+ import { join, dirname, relative } from "node:path";
23
+ import { fileURLToPath } from "node:url";
24
+
25
+ // src/review.ts
26
+ import { spawn } from "node:child_process";
27
+ import { Readable } from "node:stream";
28
+ var GIT_DIFF_MAX_CHARS = 50000;
29
+ function buildReviewPrompt(options) {
30
+ const { filenames, stepsMap, gitDiff, guidelines } = options;
31
+ const demoEntries = filenames.map((f) => {
32
+ const steps = stepsMap[f] ?? [];
33
+ const stepLines = steps.map((s) => `- [${s.timestampSeconds}s] ${s.text}`).join(`
34
+ `);
35
+ return `Video: ${f}
36
+ Recorded steps:
37
+ ${stepLines || "(no steps recorded)"}`;
38
+ });
39
+ const sections = [];
40
+ if (guidelines && guidelines.length > 0) {
41
+ sections.push(`## Coding Guidelines
42
+
43
+ ${guidelines.join(`
44
+
45
+ `)}`);
46
+ }
47
+ if (gitDiff) {
48
+ let diff = gitDiff;
49
+ if (diff.length > GIT_DIFF_MAX_CHARS) {
50
+ diff = diff.slice(0, GIT_DIFF_MAX_CHARS) + `
51
+
52
+ ... (diff truncated at 50k characters)`;
53
+ }
54
+ sections.push(`## Git Diff
55
+
56
+ \`\`\`diff
57
+ ${diff}
58
+ \`\`\``);
59
+ }
60
+ sections.push(`## Demo Recordings
61
+
62
+ ${demoEntries.join(`
63
+
64
+ `)}`);
65
+ return `You are a code reviewer. You are given a git diff, coding guidelines, and demo recordings that show the feature in action.
66
+
67
+ ${sections.join(`
68
+
69
+ `)}
70
+
71
+ ## Task
72
+
73
+ Review the code changes and demo recordings. Generate a JSON object matching this exact schema:
74
+
75
+ {
76
+ "demos": [
77
+ {
78
+ "file": "<filename>",
79
+ "summary": "<a meaningful sentence describing what this demo showcases based on the steps>"
80
+ }
81
+ ],
82
+ "review": {
83
+ "summary": "<2-3 sentence overview of the changes>",
84
+ "highlights": ["<positive aspect 1>", "<positive aspect 2>"],
85
+ "verdict": "approve" | "request_changes",
86
+ "verdictReason": "<one sentence justifying the verdict>",
87
+ "issues": [
88
+ {
89
+ "severity": "major" | "minor" | "nit",
90
+ "description": "<what the issue is and how to fix it>"
91
+ }
92
+ ]
93
+ }
94
+ }
95
+
96
+ Rules:
97
+ - Return ONLY the JSON object, no markdown fences or extra text.
98
+ - Include one entry in "demos" for each filename, in the same order.
99
+ - "file" must exactly match the provided filename.
100
+ - "verdict" must be exactly "approve" or "request_changes".
101
+ - Use "request_changes" if there are any "major" issues.
102
+ - "severity" must be exactly "major", "minor", or "nit".
103
+ - "major": bugs, security issues, broken functionality, guideline violations.
104
+ - "minor": code quality, readability, missing edge cases.
105
+ - "nit": style, naming, trivial improvements.
106
+ - "highlights" must have at least one entry.
107
+ - "issues" can be an empty array if there are no issues.
108
+ - Verify that demo steps demonstrate the acceptance criteria being met.`;
109
+ }
110
+ async function invokeClaude(prompt, options) {
111
+ const spawnFn = options?.spawn ?? defaultSpawn;
112
+ const agent = options?.agent ?? "claude";
113
+ const proc = spawnFn([agent, "-p", prompt]);
114
+ const reader = proc.stdout.getReader();
115
+ const chunks = [];
116
+ for (;; ) {
117
+ const { done, value } = await reader.read();
118
+ if (done)
119
+ break;
120
+ chunks.push(value);
121
+ }
122
+ const exitCode = await proc.exitCode;
123
+ const output = new TextDecoder().decode(concatUint8Arrays(chunks));
124
+ if (exitCode !== 0) {
125
+ throw new Error(`claude process exited with code ${exitCode}: ${output.trim()}`);
126
+ }
127
+ return output.trim();
128
+ }
129
+ var VALID_VERDICTS = new Set(["approve", "request_changes"]);
130
+ var VALID_SEVERITIES = new Set(["major", "minor", "nit"]);
131
+ function extractJson(raw) {
132
+ try {
133
+ JSON.parse(raw);
134
+ return raw;
135
+ } catch {}
136
+ const start = raw.indexOf("{");
137
+ const end = raw.lastIndexOf("}");
138
+ if (start === -1 || end === -1 || end <= start) {
139
+ throw new Error(`No JSON object found in LLM response: ${raw.slice(0, 200)}`);
140
+ }
141
+ return raw.slice(start, end + 1);
142
+ }
143
+ function parseLlmResponse(raw) {
144
+ const jsonStr = extractJson(raw);
145
+ let parsed;
146
+ try {
147
+ parsed = JSON.parse(jsonStr);
148
+ } catch {
149
+ throw new Error(`Invalid JSON from LLM: ${raw.slice(0, 200)}`);
150
+ }
151
+ if (typeof parsed !== "object" || parsed === null || !("demos" in parsed)) {
152
+ throw new Error("Missing 'demos' array in review metadata");
153
+ }
154
+ const obj = parsed;
155
+ if (!Array.isArray(obj["demos"])) {
156
+ throw new Error("'demos' must be an array");
157
+ }
158
+ for (const demo of obj["demos"]) {
159
+ if (typeof demo !== "object" || demo === null) {
160
+ throw new Error("Each demo must be an object");
161
+ }
162
+ const d = demo;
163
+ if (typeof d["file"] !== "string") {
164
+ throw new Error("Each demo must have a 'file' string");
165
+ }
166
+ if (typeof d["summary"] !== "string") {
167
+ throw new Error("Each demo must have a 'summary' string");
168
+ }
169
+ }
170
+ if (typeof obj["review"] !== "object" || obj["review"] === null) {
171
+ throw new Error("Missing 'review' object in response");
172
+ }
173
+ const review = obj["review"];
174
+ if (typeof review["summary"] !== "string") {
175
+ throw new Error("review.summary must be a string");
176
+ }
177
+ if (!Array.isArray(review["highlights"])) {
178
+ throw new Error("review.highlights must be an array");
179
+ }
180
+ if (review["highlights"].length === 0) {
181
+ throw new Error("review.highlights must not be empty");
182
+ }
183
+ for (const h of review["highlights"]) {
184
+ if (typeof h !== "string") {
185
+ throw new Error("Each highlight must be a string");
186
+ }
187
+ }
188
+ if (typeof review["verdict"] !== "string" || !VALID_VERDICTS.has(review["verdict"])) {
189
+ throw new Error("review.verdict must be 'approve' or 'request_changes'");
190
+ }
191
+ if (typeof review["verdictReason"] !== "string") {
192
+ throw new Error("review.verdictReason must be a string");
193
+ }
194
+ if (!Array.isArray(review["issues"])) {
195
+ throw new Error("review.issues must be an array");
196
+ }
197
+ for (const issue of review["issues"]) {
198
+ if (typeof issue !== "object" || issue === null) {
199
+ throw new Error("Each issue must be an object");
200
+ }
201
+ const i = issue;
202
+ if (typeof i["severity"] !== "string" || !VALID_SEVERITIES.has(i["severity"])) {
203
+ throw new Error("Each issue severity must be 'major', 'minor', or 'nit'");
204
+ }
205
+ if (typeof i["description"] !== "string") {
206
+ throw new Error("Each issue must have a 'description' string");
207
+ }
208
+ }
209
+ return parsed;
210
+ }
211
+ function defaultSpawn(cmd) {
212
+ const [command, ...args] = cmd;
213
+ const proc = spawn(command, args, {
214
+ stdio: ["ignore", "pipe", "pipe"]
215
+ });
216
+ const exitCode = new Promise((resolve) => {
217
+ proc.on("close", (code) => resolve(code ?? 1));
218
+ });
219
+ const stdout = Readable.toWeb(proc.stdout);
220
+ return { exitCode, stdout };
221
+ }
222
+ function concatUint8Arrays(arrays) {
223
+ const totalLength = arrays.reduce((sum, a) => sum + a.length, 0);
224
+ const result = new Uint8Array(totalLength);
225
+ let offset = 0;
226
+ for (const a of arrays) {
227
+ result.set(a, offset);
228
+ offset += a.length;
229
+ }
230
+ return result;
231
+ }
232
+
233
+ // src/git-context.ts
234
+ import { readFileSync } from "node:fs";
235
+ import { spawnSync } from "node:child_process";
236
+ async function detectDefaultBase(exec, gitRoot) {
237
+ let currentBranch;
238
+ try {
239
+ currentBranch = (await exec(["git", "rev-parse", "--abbrev-ref", "HEAD"], gitRoot)).trim();
240
+ } catch {
241
+ return null;
242
+ }
243
+ if (currentBranch === "main" || currentBranch === "master") {
244
+ return null;
245
+ }
246
+ for (const candidate of ["main", "master"]) {
247
+ try {
248
+ await exec(["git", "rev-parse", "--verify", candidate], gitRoot);
249
+ return candidate;
250
+ } catch {}
251
+ }
252
+ return null;
253
+ }
254
+ var defaultExec = async (cmd, cwd) => {
255
+ const [command, ...args] = cmd;
256
+ const proc = spawnSync(command, args, { cwd, encoding: "utf-8" });
257
+ if (proc.status !== 0) {
258
+ const stderr = (proc.stderr ?? "").trim();
259
+ throw new Error(`Command failed (exit ${proc.status}): ${cmd.join(" ")}${stderr ? `: ${stderr}` : ""}`);
260
+ }
261
+ return proc.stdout ?? "";
262
+ };
263
+ var defaultReadFile = (path) => {
264
+ return readFileSync(path, "utf-8");
265
+ };
266
+ async function getRepoContext(demosDir, options) {
267
+ const exec = options?.exec ?? defaultExec;
268
+ const readFile = options?.readFile ?? defaultReadFile;
269
+ const gitRoot = (await exec(["git", "rev-parse", "--show-toplevel"], demosDir)).trim();
270
+ const diffBase = options?.diffBase ?? await detectDefaultBase(exec, gitRoot);
271
+ let gitDiff;
272
+ if (diffBase) {
273
+ gitDiff = (await exec(["git", "diff", `${diffBase}...HEAD`], gitRoot)).trim();
274
+ } else {
275
+ const workingDiff = (await exec(["git", "diff", "HEAD"], gitRoot)).trim();
276
+ if (workingDiff.length > 0) {
277
+ gitDiff = workingDiff;
278
+ } else {
279
+ gitDiff = (await exec(["git", "diff", "HEAD~1..HEAD"], gitRoot)).trim();
280
+ }
281
+ }
282
+ const lsOutput = (await exec(["git", "ls-files"], gitRoot)).trim();
283
+ const files = lsOutput.split(`
284
+ `).filter((f) => f.length > 0);
285
+ const guidelinePatterns = ["CLAUDE.md", "SKILL.md"];
286
+ const guidelines = [];
287
+ for (const file of files) {
288
+ const basename = file.split("/").pop() ?? "";
289
+ if (guidelinePatterns.includes(basename)) {
290
+ const fullPath = `${gitRoot}/${file}`;
291
+ const content = readFile(fullPath);
292
+ guidelines.push(`# ${file}
293
+ ${content}`);
294
+ }
295
+ }
296
+ return { gitDiff, guidelines };
297
+ }
298
+
299
+ // src/review-generator.ts
300
+ function getReviewTemplate() {
301
+ const currentFile = fileURLToPath(import.meta.url);
302
+ const distDir = dirname(currentFile);
303
+ const templatePath = join(distDir, "review-template.html");
304
+ if (!existsSync(templatePath)) {
305
+ throw new Error(`Review template not found at ${templatePath}. ` + `Make sure to build the review-app package first.`);
306
+ }
307
+ return readFileSync2(templatePath, "utf-8");
308
+ }
309
+ function escapeHtml(s) {
310
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
311
+ }
312
+ function generateReviewHtml(appData) {
313
+ const template = getReviewTemplate();
314
+ const jsonData = JSON.stringify(appData);
315
+ return template.replace("<title>Demo Review</title>", `<title>${escapeHtml(appData.title)}</title>`).replace('"{{__INJECT_REVIEW_DATA__}}"', jsonData);
316
+ }
317
+ function discoverDemoFiles(directory) {
318
+ const files = [];
319
+ const processFile = (filePath, filename) => {
320
+ const relativePath = relative(directory, filePath);
321
+ if (filename.endsWith(".webm")) {
322
+ files.push({ path: filePath, filename, relativePath, type: "web-ux" });
323
+ } else if (filename.endsWith(".jsonl")) {
324
+ files.push({ path: filePath, filename, relativePath, type: "log-based" });
325
+ }
326
+ };
327
+ for (const f of readdirSync(directory)) {
328
+ processFile(join(directory, f), f);
329
+ }
330
+ if (files.length === 0) {
331
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
332
+ if (!entry.isDirectory())
333
+ continue;
334
+ const subdir = join(directory, entry.name);
335
+ for (const f of readdirSync(subdir)) {
336
+ processFile(join(subdir, f), f);
337
+ }
338
+ }
339
+ }
340
+ return files.sort((a, b) => a.filename.localeCompare(b.filename));
341
+ }
342
+ async function generateReview(options) {
343
+ const { directory, agent, feedbackEndpoint, title = "Demo Review", diffBase } = options;
344
+ const demoFiles = discoverDemoFiles(directory);
345
+ const webUxDemos = demoFiles.filter((d) => d.type === "web-ux");
346
+ const logBasedDemos = demoFiles.filter((d) => d.type === "log-based");
347
+ if (demoFiles.length === 0) {
348
+ throw new Error(`No .webm or .jsonl files found in "${directory}" or its subdirectories.`);
349
+ }
350
+ const filenameToRelativePath = new Map(demoFiles.map((d) => [d.filename, d.relativePath]));
351
+ const stepsMapByFilename = {};
352
+ const stepsMapByRelativePath = {};
353
+ for (const demo of webUxDemos) {
354
+ const stepsPath = join(dirname(demo.path), "demo-steps.json");
355
+ if (!existsSync(stepsPath))
356
+ continue;
357
+ try {
358
+ const raw = readFileSync2(stepsPath, "utf-8");
359
+ const parsed = JSON.parse(raw);
360
+ if (Array.isArray(parsed)) {
361
+ stepsMapByFilename[demo.filename] = parsed;
362
+ stepsMapByRelativePath[demo.relativePath] = parsed;
363
+ }
364
+ } catch {}
365
+ }
366
+ const logsMap = {};
367
+ for (const demo of logBasedDemos) {
368
+ logsMap[demo.relativePath] = readFileSync2(demo.path, "utf-8");
369
+ }
370
+ const hasWebUxDemos = webUxDemos.length > 0;
371
+ const hasLogDemos = logBasedDemos.length > 0;
372
+ if (hasWebUxDemos && Object.keys(stepsMapByFilename).length === 0) {
373
+ throw new Error("No demo-steps.json found alongside any .webm files. " + "Use DemoRecorder in your demo tests to generate step data.");
374
+ }
375
+ if (!hasWebUxDemos && !hasLogDemos) {
376
+ throw new Error("No demo files found.");
377
+ }
378
+ let gitDiff;
379
+ let guidelines;
380
+ try {
381
+ const repoContext = await getRepoContext(directory, { diffBase });
382
+ gitDiff = repoContext.gitDiff;
383
+ guidelines = repoContext.guidelines;
384
+ } catch {}
385
+ const allFilenames = demoFiles.map((d) => d.filename);
386
+ const prompt = buildReviewPrompt({ filenames: allFilenames, stepsMap: stepsMapByFilename, gitDiff, guidelines });
387
+ const rawOutput = await invokeClaude(prompt, { agent });
388
+ const llmResponse = parseLlmResponse(rawOutput);
389
+ const typeMap = new Map(demoFiles.map((d) => [d.filename, d.type]));
390
+ const metadata = {
391
+ demos: llmResponse.demos.map((demo) => {
392
+ const relativePath = filenameToRelativePath.get(demo.file) ?? demo.file;
393
+ return {
394
+ file: relativePath,
395
+ type: typeMap.get(demo.file) ?? "web-ux",
396
+ summary: demo.summary,
397
+ steps: stepsMapByRelativePath[relativePath] ?? []
398
+ };
399
+ }),
400
+ review: llmResponse.review
401
+ };
402
+ const metadataPath = join(directory, "review-metadata.json");
403
+ writeFileSync(metadataPath, JSON.stringify(metadata, null, 2) + `
404
+ `);
405
+ const appData = {
406
+ metadata,
407
+ title,
408
+ videos: {},
409
+ logs: Object.keys(logsMap).length > 0 ? logsMap : undefined,
410
+ feedbackEndpoint
411
+ };
412
+ const html = generateReviewHtml(appData);
413
+ const htmlPath = join(directory, "review.html");
414
+ writeFileSync(htmlPath, html);
415
+ return { htmlPath, metadataPath, metadata };
416
+ }
417
+
418
+ // ../../node_modules/universal-user-agent/index.js
419
+ function getUserAgent() {
420
+ if (typeof navigator === "object" && "userAgent" in navigator) {
421
+ return navigator.userAgent;
422
+ }
423
+ if (typeof process === "object" && process.version !== undefined) {
424
+ return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;
425
+ }
426
+ return "<environment undetectable>";
427
+ }
428
+
429
+ // ../../node_modules/@octokit/endpoint/dist-bundle/index.js
430
+ var VERSION = "0.0.0-development";
431
+ var userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`;
432
+ var DEFAULTS = {
433
+ method: "GET",
434
+ baseUrl: "https://api.github.com",
435
+ headers: {
436
+ accept: "application/vnd.github.v3+json",
437
+ "user-agent": userAgent
438
+ },
439
+ mediaType: {
440
+ format: ""
441
+ }
442
+ };
443
+ function lowercaseKeys(object) {
444
+ if (!object) {
445
+ return {};
446
+ }
447
+ return Object.keys(object).reduce((newObj, key) => {
448
+ newObj[key.toLowerCase()] = object[key];
449
+ return newObj;
450
+ }, {});
451
+ }
452
+ function isPlainObject(value) {
453
+ if (typeof value !== "object" || value === null)
454
+ return false;
455
+ if (Object.prototype.toString.call(value) !== "[object Object]")
456
+ return false;
457
+ const proto = Object.getPrototypeOf(value);
458
+ if (proto === null)
459
+ return true;
460
+ const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
461
+ return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
462
+ }
463
+ function mergeDeep(defaults, options) {
464
+ const result = Object.assign({}, defaults);
465
+ Object.keys(options).forEach((key) => {
466
+ if (isPlainObject(options[key])) {
467
+ if (!(key in defaults))
468
+ Object.assign(result, { [key]: options[key] });
469
+ else
470
+ result[key] = mergeDeep(defaults[key], options[key]);
471
+ } else {
472
+ Object.assign(result, { [key]: options[key] });
473
+ }
474
+ });
475
+ return result;
476
+ }
477
+ function removeUndefinedProperties(obj) {
478
+ for (const key in obj) {
479
+ if (obj[key] === undefined) {
480
+ delete obj[key];
481
+ }
482
+ }
483
+ return obj;
484
+ }
485
+ function merge(defaults, route, options) {
486
+ if (typeof route === "string") {
487
+ let [method, url] = route.split(" ");
488
+ options = Object.assign(url ? { method, url } : { url: method }, options);
489
+ } else {
490
+ options = Object.assign({}, route);
491
+ }
492
+ options.headers = lowercaseKeys(options.headers);
493
+ removeUndefinedProperties(options);
494
+ removeUndefinedProperties(options.headers);
495
+ const mergedOptions = mergeDeep(defaults || {}, options);
496
+ if (options.url === "/graphql") {
497
+ if (defaults && defaults.mediaType.previews?.length) {
498
+ mergedOptions.mediaType.previews = defaults.mediaType.previews.filter((preview) => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews);
499
+ }
500
+ mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, ""));
501
+ }
502
+ return mergedOptions;
503
+ }
504
+ function addQueryParameters(url, parameters) {
505
+ const separator = /\?/.test(url) ? "&" : "?";
506
+ const names = Object.keys(parameters);
507
+ if (names.length === 0) {
508
+ return url;
509
+ }
510
+ return url + separator + names.map((name) => {
511
+ if (name === "q") {
512
+ return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+");
513
+ }
514
+ return `${name}=${encodeURIComponent(parameters[name])}`;
515
+ }).join("&");
516
+ }
517
+ var urlVariableRegex = /\{[^{}}]+\}/g;
518
+ function removeNonChars(variableName) {
519
+ return variableName.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g, "").split(/,/);
520
+ }
521
+ function extractUrlVariableNames(url) {
522
+ const matches = url.match(urlVariableRegex);
523
+ if (!matches) {
524
+ return [];
525
+ }
526
+ return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
527
+ }
528
+ function omit(object, keysToOmit) {
529
+ const result = { __proto__: null };
530
+ for (const key of Object.keys(object)) {
531
+ if (keysToOmit.indexOf(key) === -1) {
532
+ result[key] = object[key];
533
+ }
534
+ }
535
+ return result;
536
+ }
537
+ function encodeReserved(str) {
538
+ return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) {
539
+ if (!/%[0-9A-Fa-f]/.test(part)) {
540
+ part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
541
+ }
542
+ return part;
543
+ }).join("");
544
+ }
545
+ function encodeUnreserved(str) {
546
+ return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
547
+ return "%" + c.charCodeAt(0).toString(16).toUpperCase();
548
+ });
549
+ }
550
+ function encodeValue(operator, value, key) {
551
+ value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
552
+ if (key) {
553
+ return encodeUnreserved(key) + "=" + value;
554
+ } else {
555
+ return value;
556
+ }
557
+ }
558
+ function isDefined(value) {
559
+ return value !== undefined && value !== null;
560
+ }
561
+ function isKeyOperator(operator) {
562
+ return operator === ";" || operator === "&" || operator === "?";
563
+ }
564
+ function getValues(context, operator, key, modifier) {
565
+ var value = context[key], result = [];
566
+ if (isDefined(value) && value !== "") {
567
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
568
+ value = value.toString();
569
+ if (modifier && modifier !== "*") {
570
+ value = value.substring(0, parseInt(modifier, 10));
571
+ }
572
+ result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
573
+ } else {
574
+ if (modifier === "*") {
575
+ if (Array.isArray(value)) {
576
+ value.filter(isDefined).forEach(function(value2) {
577
+ result.push(encodeValue(operator, value2, isKeyOperator(operator) ? key : ""));
578
+ });
579
+ } else {
580
+ Object.keys(value).forEach(function(k) {
581
+ if (isDefined(value[k])) {
582
+ result.push(encodeValue(operator, value[k], k));
583
+ }
584
+ });
585
+ }
586
+ } else {
587
+ const tmp = [];
588
+ if (Array.isArray(value)) {
589
+ value.filter(isDefined).forEach(function(value2) {
590
+ tmp.push(encodeValue(operator, value2));
591
+ });
592
+ } else {
593
+ Object.keys(value).forEach(function(k) {
594
+ if (isDefined(value[k])) {
595
+ tmp.push(encodeUnreserved(k));
596
+ tmp.push(encodeValue(operator, value[k].toString()));
597
+ }
598
+ });
599
+ }
600
+ if (isKeyOperator(operator)) {
601
+ result.push(encodeUnreserved(key) + "=" + tmp.join(","));
602
+ } else if (tmp.length !== 0) {
603
+ result.push(tmp.join(","));
604
+ }
605
+ }
606
+ }
607
+ } else {
608
+ if (operator === ";") {
609
+ if (isDefined(value)) {
610
+ result.push(encodeUnreserved(key));
611
+ }
612
+ } else if (value === "" && (operator === "&" || operator === "?")) {
613
+ result.push(encodeUnreserved(key) + "=");
614
+ } else if (value === "") {
615
+ result.push("");
616
+ }
617
+ }
618
+ return result;
619
+ }
620
+ function parseUrl(template) {
621
+ return {
622
+ expand: expand.bind(null, template)
623
+ };
624
+ }
625
+ function expand(template, context) {
626
+ var operators = ["+", "#", ".", "/", ";", "?", "&"];
627
+ template = template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function(_, expression, literal) {
628
+ if (expression) {
629
+ let operator = "";
630
+ const values = [];
631
+ if (operators.indexOf(expression.charAt(0)) !== -1) {
632
+ operator = expression.charAt(0);
633
+ expression = expression.substr(1);
634
+ }
635
+ expression.split(/,/g).forEach(function(variable) {
636
+ var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
637
+ values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
638
+ });
639
+ if (operator && operator !== "+") {
640
+ var separator = ",";
641
+ if (operator === "?") {
642
+ separator = "&";
643
+ } else if (operator !== "#") {
644
+ separator = operator;
645
+ }
646
+ return (values.length !== 0 ? operator : "") + values.join(separator);
647
+ } else {
648
+ return values.join(",");
649
+ }
650
+ } else {
651
+ return encodeReserved(literal);
652
+ }
653
+ });
654
+ if (template === "/") {
655
+ return template;
656
+ } else {
657
+ return template.replace(/\/$/, "");
658
+ }
659
+ }
660
+ function parse(options) {
661
+ let method = options.method.toUpperCase();
662
+ let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
663
+ let headers = Object.assign({}, options.headers);
664
+ let body;
665
+ let parameters = omit(options, [
666
+ "method",
667
+ "baseUrl",
668
+ "url",
669
+ "headers",
670
+ "request",
671
+ "mediaType"
672
+ ]);
673
+ const urlVariableNames = extractUrlVariableNames(url);
674
+ url = parseUrl(url).expand(parameters);
675
+ if (!/^http/.test(url)) {
676
+ url = options.baseUrl + url;
677
+ }
678
+ const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl");
679
+ const remainingParameters = omit(parameters, omittedParameters);
680
+ const isBinaryRequest = /application\/octet-stream/i.test(headers.accept);
681
+ if (!isBinaryRequest) {
682
+ if (options.mediaType.format) {
683
+ headers.accept = headers.accept.split(/,/).map((format) => format.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(",");
684
+ }
685
+ if (url.endsWith("/graphql")) {
686
+ if (options.mediaType.previews?.length) {
687
+ const previewsFromAcceptHeader = headers.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g) || [];
688
+ headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => {
689
+ const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
690
+ return `application/vnd.github.${preview}-preview${format}`;
691
+ }).join(",");
692
+ }
693
+ }
694
+ }
695
+ if (["GET", "HEAD"].includes(method)) {
696
+ url = addQueryParameters(url, remainingParameters);
697
+ } else {
698
+ if ("data" in remainingParameters) {
699
+ body = remainingParameters.data;
700
+ } else {
701
+ if (Object.keys(remainingParameters).length) {
702
+ body = remainingParameters;
703
+ }
704
+ }
705
+ }
706
+ if (!headers["content-type"] && typeof body !== "undefined") {
707
+ headers["content-type"] = "application/json; charset=utf-8";
708
+ }
709
+ if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
710
+ body = "";
711
+ }
712
+ return Object.assign({ method, url, headers }, typeof body !== "undefined" ? { body } : null, options.request ? { request: options.request } : null);
713
+ }
714
+ function endpointWithDefaults(defaults, route, options) {
715
+ return parse(merge(defaults, route, options));
716
+ }
717
+ function withDefaults(oldDefaults, newDefaults) {
718
+ const DEFAULTS2 = merge(oldDefaults, newDefaults);
719
+ const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2);
720
+ return Object.assign(endpoint2, {
721
+ DEFAULTS: DEFAULTS2,
722
+ defaults: withDefaults.bind(null, DEFAULTS2),
723
+ merge: merge.bind(null, DEFAULTS2),
724
+ parse
725
+ });
726
+ }
727
+ var endpoint = withDefaults(null, DEFAULTS);
728
+
729
+ // ../../node_modules/fast-content-type-parse/index.js
730
+ var NullObject = function NullObject2() {};
731
+ NullObject.prototype = Object.create(null);
732
+ var paramRE = /; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu;
733
+ var quotedPairRE = /\\([\v\u0020-\u00ff])/gu;
734
+ var mediaTypeRE = /^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u;
735
+ var defaultContentType = { type: "", parameters: new NullObject };
736
+ Object.freeze(defaultContentType.parameters);
737
+ Object.freeze(defaultContentType);
738
+ function safeParse(header) {
739
+ if (typeof header !== "string") {
740
+ return defaultContentType;
741
+ }
742
+ let index = header.indexOf(";");
743
+ const type = index !== -1 ? header.slice(0, index).trim() : header.trim();
744
+ if (mediaTypeRE.test(type) === false) {
745
+ return defaultContentType;
746
+ }
747
+ const result = {
748
+ type: type.toLowerCase(),
749
+ parameters: new NullObject
750
+ };
751
+ if (index === -1) {
752
+ return result;
753
+ }
754
+ let key;
755
+ let match;
756
+ let value;
757
+ paramRE.lastIndex = index;
758
+ while (match = paramRE.exec(header)) {
759
+ if (match.index !== index) {
760
+ return defaultContentType;
761
+ }
762
+ index += match[0].length;
763
+ key = match[1].toLowerCase();
764
+ value = match[2];
765
+ if (value[0] === '"') {
766
+ value = value.slice(1, value.length - 1);
767
+ quotedPairRE.test(value) && (value = value.replace(quotedPairRE, "$1"));
768
+ }
769
+ result.parameters[key] = value;
770
+ }
771
+ if (index !== header.length) {
772
+ return defaultContentType;
773
+ }
774
+ return result;
775
+ }
776
+ var $safeParse = safeParse;
777
+
778
+ // ../../node_modules/@octokit/request-error/dist-src/index.js
779
+ class RequestError extends Error {
780
+ name;
781
+ status;
782
+ request;
783
+ response;
784
+ constructor(message, statusCode, options) {
785
+ super(message);
786
+ this.name = "HttpError";
787
+ this.status = Number.parseInt(statusCode);
788
+ if (Number.isNaN(this.status)) {
789
+ this.status = 0;
790
+ }
791
+ if ("response" in options) {
792
+ this.response = options.response;
793
+ }
794
+ const requestCopy = Object.assign({}, options.request);
795
+ if (options.request.headers.authorization) {
796
+ requestCopy.headers = Object.assign({}, options.request.headers, {
797
+ authorization: options.request.headers.authorization.replace(/(?<! ) .*$/, " [REDACTED]")
798
+ });
799
+ }
800
+ requestCopy.url = requestCopy.url.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]").replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
801
+ this.request = requestCopy;
802
+ }
803
+ }
804
+
805
+ // ../../node_modules/@octokit/request/dist-bundle/index.js
806
+ var VERSION2 = "9.2.4";
807
+ var defaults_default = {
808
+ headers: {
809
+ "user-agent": `octokit-request.js/${VERSION2} ${getUserAgent()}`
810
+ }
811
+ };
812
+ function isPlainObject2(value) {
813
+ if (typeof value !== "object" || value === null)
814
+ return false;
815
+ if (Object.prototype.toString.call(value) !== "[object Object]")
816
+ return false;
817
+ const proto = Object.getPrototypeOf(value);
818
+ if (proto === null)
819
+ return true;
820
+ const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
821
+ return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
822
+ }
823
+ async function fetchWrapper(requestOptions) {
824
+ const fetch = requestOptions.request?.fetch || globalThis.fetch;
825
+ if (!fetch) {
826
+ throw new Error("fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing");
827
+ }
828
+ const log = requestOptions.request?.log || console;
829
+ const parseSuccessResponseBody = requestOptions.request?.parseSuccessResponseBody !== false;
830
+ const body = isPlainObject2(requestOptions.body) || Array.isArray(requestOptions.body) ? JSON.stringify(requestOptions.body) : requestOptions.body;
831
+ const requestHeaders = Object.fromEntries(Object.entries(requestOptions.headers).map(([name, value]) => [
832
+ name,
833
+ String(value)
834
+ ]));
835
+ let fetchResponse;
836
+ try {
837
+ fetchResponse = await fetch(requestOptions.url, {
838
+ method: requestOptions.method,
839
+ body,
840
+ redirect: requestOptions.request?.redirect,
841
+ headers: requestHeaders,
842
+ signal: requestOptions.request?.signal,
843
+ ...requestOptions.body && { duplex: "half" }
844
+ });
845
+ } catch (error) {
846
+ let message = "Unknown Error";
847
+ if (error instanceof Error) {
848
+ if (error.name === "AbortError") {
849
+ error.status = 500;
850
+ throw error;
851
+ }
852
+ message = error.message;
853
+ if (error.name === "TypeError" && "cause" in error) {
854
+ if (error.cause instanceof Error) {
855
+ message = error.cause.message;
856
+ } else if (typeof error.cause === "string") {
857
+ message = error.cause;
858
+ }
859
+ }
860
+ }
861
+ const requestError = new RequestError(message, 500, {
862
+ request: requestOptions
863
+ });
864
+ requestError.cause = error;
865
+ throw requestError;
866
+ }
867
+ const status = fetchResponse.status;
868
+ const url = fetchResponse.url;
869
+ const responseHeaders = {};
870
+ for (const [key, value] of fetchResponse.headers) {
871
+ responseHeaders[key] = value;
872
+ }
873
+ const octokitResponse = {
874
+ url,
875
+ status,
876
+ headers: responseHeaders,
877
+ data: ""
878
+ };
879
+ if ("deprecation" in responseHeaders) {
880
+ const matches = responseHeaders.link && responseHeaders.link.match(/<([^<>]+)>; rel="deprecation"/);
881
+ const deprecationLink = matches && matches.pop();
882
+ log.warn(`[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${responseHeaders.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`);
883
+ }
884
+ if (status === 204 || status === 205) {
885
+ return octokitResponse;
886
+ }
887
+ if (requestOptions.method === "HEAD") {
888
+ if (status < 400) {
889
+ return octokitResponse;
890
+ }
891
+ throw new RequestError(fetchResponse.statusText, status, {
892
+ response: octokitResponse,
893
+ request: requestOptions
894
+ });
895
+ }
896
+ if (status === 304) {
897
+ octokitResponse.data = await getResponseData(fetchResponse);
898
+ throw new RequestError("Not modified", status, {
899
+ response: octokitResponse,
900
+ request: requestOptions
901
+ });
902
+ }
903
+ if (status >= 400) {
904
+ octokitResponse.data = await getResponseData(fetchResponse);
905
+ throw new RequestError(toErrorMessage(octokitResponse.data), status, {
906
+ response: octokitResponse,
907
+ request: requestOptions
908
+ });
909
+ }
910
+ octokitResponse.data = parseSuccessResponseBody ? await getResponseData(fetchResponse) : fetchResponse.body;
911
+ return octokitResponse;
912
+ }
913
+ async function getResponseData(response) {
914
+ const contentType = response.headers.get("content-type");
915
+ if (!contentType) {
916
+ return response.text().catch(() => "");
917
+ }
918
+ const mimetype = $safeParse(contentType);
919
+ if (isJSONResponse(mimetype)) {
920
+ let text = "";
921
+ try {
922
+ text = await response.text();
923
+ return JSON.parse(text);
924
+ } catch (err) {
925
+ return text;
926
+ }
927
+ } else if (mimetype.type.startsWith("text/") || mimetype.parameters.charset?.toLowerCase() === "utf-8") {
928
+ return response.text().catch(() => "");
929
+ } else {
930
+ return response.arrayBuffer().catch(() => new ArrayBuffer(0));
931
+ }
932
+ }
933
+ function isJSONResponse(mimetype) {
934
+ return mimetype.type === "application/json" || mimetype.type === "application/scim+json";
935
+ }
936
+ function toErrorMessage(data) {
937
+ if (typeof data === "string") {
938
+ return data;
939
+ }
940
+ if (data instanceof ArrayBuffer) {
941
+ return "Unknown error";
942
+ }
943
+ if ("message" in data) {
944
+ const suffix = "documentation_url" in data ? ` - ${data.documentation_url}` : "";
945
+ return Array.isArray(data.errors) ? `${data.message}: ${data.errors.map((v) => JSON.stringify(v)).join(", ")}${suffix}` : `${data.message}${suffix}`;
946
+ }
947
+ return `Unknown error: ${JSON.stringify(data)}`;
948
+ }
949
+ function withDefaults2(oldEndpoint, newDefaults) {
950
+ const endpoint2 = oldEndpoint.defaults(newDefaults);
951
+ const newApi = function(route, parameters) {
952
+ const endpointOptions = endpoint2.merge(route, parameters);
953
+ if (!endpointOptions.request || !endpointOptions.request.hook) {
954
+ return fetchWrapper(endpoint2.parse(endpointOptions));
955
+ }
956
+ const request2 = (route2, parameters2) => {
957
+ return fetchWrapper(endpoint2.parse(endpoint2.merge(route2, parameters2)));
958
+ };
959
+ Object.assign(request2, {
960
+ endpoint: endpoint2,
961
+ defaults: withDefaults2.bind(null, endpoint2)
962
+ });
963
+ return endpointOptions.request.hook(request2, endpointOptions);
964
+ };
965
+ return Object.assign(newApi, {
966
+ endpoint: endpoint2,
967
+ defaults: withDefaults2.bind(null, endpoint2)
968
+ });
969
+ }
970
+ var request = withDefaults2(endpoint, defaults_default);
971
+
972
+ // ../../node_modules/@octokit/graphql/dist-bundle/index.js
973
+ var VERSION3 = "0.0.0-development";
974
+ function _buildMessageForResponseErrors(data) {
975
+ return `Request failed due to following response errors:
976
+ ` + data.errors.map((e) => ` - ${e.message}`).join(`
977
+ `);
978
+ }
979
+ var GraphqlResponseError = class extends Error {
980
+ constructor(request2, headers, response) {
981
+ super(_buildMessageForResponseErrors(response));
982
+ this.request = request2;
983
+ this.headers = headers;
984
+ this.response = response;
985
+ this.errors = response.errors;
986
+ this.data = response.data;
987
+ if (Error.captureStackTrace) {
988
+ Error.captureStackTrace(this, this.constructor);
989
+ }
990
+ }
991
+ name = "GraphqlResponseError";
992
+ errors;
993
+ data;
994
+ };
995
+ var NON_VARIABLE_OPTIONS = [
996
+ "method",
997
+ "baseUrl",
998
+ "url",
999
+ "headers",
1000
+ "request",
1001
+ "query",
1002
+ "mediaType",
1003
+ "operationName"
1004
+ ];
1005
+ var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"];
1006
+ var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
1007
+ function graphql(request2, query, options) {
1008
+ if (options) {
1009
+ if (typeof query === "string" && "query" in options) {
1010
+ return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`));
1011
+ }
1012
+ for (const key in options) {
1013
+ if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key))
1014
+ continue;
1015
+ return Promise.reject(new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`));
1016
+ }
1017
+ }
1018
+ const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query;
1019
+ const requestOptions = Object.keys(parsedOptions).reduce((result, key) => {
1020
+ if (NON_VARIABLE_OPTIONS.includes(key)) {
1021
+ result[key] = parsedOptions[key];
1022
+ return result;
1023
+ }
1024
+ if (!result.variables) {
1025
+ result.variables = {};
1026
+ }
1027
+ result.variables[key] = parsedOptions[key];
1028
+ return result;
1029
+ }, {});
1030
+ const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl;
1031
+ if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
1032
+ requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
1033
+ }
1034
+ return request2(requestOptions).then((response) => {
1035
+ if (response.data.errors) {
1036
+ const headers = {};
1037
+ for (const key of Object.keys(response.headers)) {
1038
+ headers[key] = response.headers[key];
1039
+ }
1040
+ throw new GraphqlResponseError(requestOptions, headers, response.data);
1041
+ }
1042
+ return response.data.data;
1043
+ });
1044
+ }
1045
+ function withDefaults3(request2, newDefaults) {
1046
+ const newRequest = request2.defaults(newDefaults);
1047
+ const newApi = (query, options) => {
1048
+ return graphql(newRequest, query, options);
1049
+ };
1050
+ return Object.assign(newApi, {
1051
+ defaults: withDefaults3.bind(null, newRequest),
1052
+ endpoint: newRequest.endpoint
1053
+ });
1054
+ }
1055
+ var graphql2 = withDefaults3(request, {
1056
+ headers: {
1057
+ "user-agent": `octokit-graphql.js/${VERSION3} ${getUserAgent()}`
1058
+ },
1059
+ method: "POST",
1060
+ url: "/graphql"
1061
+ });
1062
+
1063
+ // src/github-issue.ts
1064
+ import { spawnSync as spawnSync2 } from "node:child_process";
1065
+ var ISSUE_QUERY = `
1066
+ query($owner: String!, $repo: String!, $number: Int!) {
1067
+ repository(owner: $owner, name: $repo) {
1068
+ issue(number: $number) {
1069
+ number
1070
+ title
1071
+ body
1072
+ state
1073
+ labels(first: 20) {
1074
+ nodes {
1075
+ name
1076
+ }
1077
+ }
1078
+ }
1079
+ }
1080
+ }
1081
+ `;
1082
+ function getRepoInfoFromGit() {
1083
+ try {
1084
+ const proc = spawnSync2("git", ["remote", "get-url", "origin"], { encoding: "utf-8" });
1085
+ if (proc.status !== 0 || !proc.stdout) {
1086
+ return null;
1087
+ }
1088
+ const url = proc.stdout.trim();
1089
+ const sshMatch = url.match(/git@github\.com:([^/]+)\/(.+?)(?:\.git)?$/);
1090
+ if (sshMatch) {
1091
+ return { owner: sshMatch[1], repo: sshMatch[2] };
1092
+ }
1093
+ const httpsMatch = url.match(/https:\/\/github\.com\/([^/]+)\/(.+?)(?:\.git)?$/);
1094
+ if (httpsMatch) {
1095
+ return { owner: httpsMatch[1], repo: httpsMatch[2] };
1096
+ }
1097
+ return null;
1098
+ } catch {
1099
+ return null;
1100
+ }
1101
+ }
1102
+ function getTokenFromEnvironment() {
1103
+ return process.env["GITHUB_TOKEN"] ?? process.env["GH_TOKEN"] ?? null;
1104
+ }
1105
+ async function fetchGitHubIssue(issueId, options) {
1106
+ const issueNumber = typeof issueId === "string" ? parseInt(issueId, 10) : issueId;
1107
+ if (isNaN(issueNumber)) {
1108
+ throw new Error(`Invalid issue ID: ${issueId}`);
1109
+ }
1110
+ let owner = options?.owner;
1111
+ let repo = options?.repo;
1112
+ if (!owner || !repo) {
1113
+ const detected = getRepoInfoFromGit();
1114
+ if (!detected) {
1115
+ throw new Error("Could not detect repository owner/name from git remote. " + "Please provide owner and repo options, or run from a git repository with a GitHub origin.");
1116
+ }
1117
+ owner = owner ?? detected.owner;
1118
+ repo = repo ?? detected.repo;
1119
+ }
1120
+ const token = options?.token ?? getTokenFromEnvironment();
1121
+ if (!token) {
1122
+ throw new Error("No GitHub token found. Please set GITHUB_TOKEN or GH_TOKEN environment variable, " + "or provide token in options.");
1123
+ }
1124
+ const graphqlFn = options?.graphql ?? graphql2.defaults({
1125
+ headers: {
1126
+ authorization: `token ${token}`
1127
+ }
1128
+ });
1129
+ const response = await graphqlFn(ISSUE_QUERY, {
1130
+ owner,
1131
+ repo,
1132
+ number: issueNumber
1133
+ });
1134
+ const issue = response.repository.issue;
1135
+ return {
1136
+ number: issue.number,
1137
+ title: issue.title,
1138
+ body: issue.body ?? "",
1139
+ labels: issue.labels.nodes.map((l) => l.name),
1140
+ state: issue.state.toLowerCase()
1141
+ };
1142
+ }
1143
+
1144
+ // src/orchestrator.ts
1145
+ import { mkdirSync, existsSync as existsSync2, writeFileSync as writeFileSync2, readFileSync as readFileSync3 } from "node:fs";
1146
+ import { join as join2, dirname as pathDirname } from "node:path";
1147
+ import { spawnSync as spawnSync3 } from "node:child_process";
1148
+ var GIT_DIFF_MAX_CHARS2 = 50000;
1149
+ var defaultExec2 = async (cmd, cwd) => {
1150
+ const [command, ...args] = cmd;
1151
+ const proc = spawnSync3(command, args, { cwd, encoding: "utf-8" });
1152
+ if (proc.status !== 0) {
1153
+ const stderr = (proc.stderr ?? "").trim();
1154
+ throw new Error(`Command failed (exit ${proc.status}): ${cmd.join(" ")}${stderr ? `: ${stderr}` : ""}`);
1155
+ }
1156
+ return proc.stdout ?? "";
1157
+ };
1158
+ async function getGitRoot(exec, cwd) {
1159
+ return (await exec(["git", "rev-parse", "--show-toplevel"], cwd)).trim();
1160
+ }
1161
+ async function getCurrentBranch(exec, cwd) {
1162
+ const branch = (await exec(["git", "branch", "--show-current"], cwd)).trim();
1163
+ return branch.replace(/\//g, "-") || "unknown";
1164
+ }
1165
+ function buildPresenterPrompt(options) {
1166
+ const { issue, gitDiff, guidelines, reviewFolder, assetsFolder, testsFolder } = options;
1167
+ let diff = gitDiff;
1168
+ if (diff.length > GIT_DIFF_MAX_CHARS2) {
1169
+ diff = diff.slice(0, GIT_DIFF_MAX_CHARS2) + `
1170
+
1171
+ ... (diff truncated at 50k characters)`;
1172
+ }
1173
+ const sections = [];
1174
+ sections.push(`## GitHub Issue #${issue.number}: ${issue.title}
1175
+
1176
+ ${issue.body}`);
1177
+ if (guidelines.length > 0) {
1178
+ sections.push(`## Coding Guidelines
1179
+
1180
+ ${guidelines.join(`
1181
+
1182
+ `)}`);
1183
+ }
1184
+ sections.push(`## Git Diff
1185
+
1186
+ \`\`\`diff
1187
+ ${diff}
1188
+ \`\`\``);
1189
+ return `You are a demo presenter. You must create demo recordings that showcase the feature described in the GitHub issue.
1190
+
1191
+ ${sections.join(`
1192
+
1193
+ `)}
1194
+
1195
+ ## Configuration
1196
+
1197
+ - **Review Folder:** ${reviewFolder}
1198
+ - **Assets Directory:** ${assetsFolder}
1199
+ - **Tests Directory:** ${testsFolder}
1200
+
1201
+ ## Task
1202
+
1203
+ Based on the GitHub issue and git diff above, create demo recordings that demonstrate each acceptance criterion is met.
1204
+
1205
+ For web-ux demos:
1206
+ - Create Playwright test files in the Tests Directory
1207
+ - Use DemoRecorder to capture steps
1208
+ - Save recordings to the Assets Directory
1209
+
1210
+ For log-based demos:
1211
+ - Create .jsonl files directly in the Assets Directory
1212
+ - Use demon__highlight annotations for key lines
1213
+
1214
+ After creating demos, report:
1215
+ 1. List of demo test files created (paths to .demo.ts files)
1216
+ 2. List of artifact files generated (.webm for web-ux, .jsonl for log-based)
1217
+ 3. Any errors encountered`;
1218
+ }
1219
+ function buildReviewerPrompt(options) {
1220
+ const { issue, gitDiff, guidelines, demoFiles, stepsMap, logsMap } = options;
1221
+ let diff = gitDiff;
1222
+ if (diff.length > GIT_DIFF_MAX_CHARS2) {
1223
+ diff = diff.slice(0, GIT_DIFF_MAX_CHARS2) + `
1224
+
1225
+ ... (diff truncated at 50k characters)`;
1226
+ }
1227
+ const sections = [];
1228
+ sections.push(`## GitHub Issue #${issue.number}: ${issue.title}
1229
+
1230
+ ${issue.body}`);
1231
+ if (guidelines.length > 0) {
1232
+ sections.push(`## Coding Guidelines
1233
+
1234
+ ${guidelines.join(`
1235
+
1236
+ `)}`);
1237
+ }
1238
+ sections.push(`## Git Diff
1239
+
1240
+ \`\`\`diff
1241
+ ${diff}
1242
+ \`\`\``);
1243
+ const demoEntries = demoFiles.map((f) => {
1244
+ if (f.type === "web-ux") {
1245
+ const steps = stepsMap[f.filename] ?? stepsMap[f.relativePath] ?? [];
1246
+ const stepLines = steps.map((s) => `- [${s.timestampSeconds}s] ${s.text}`).join(`
1247
+ `);
1248
+ return `Video: ${f.relativePath}
1249
+ Recorded steps:
1250
+ ${stepLines || "(no steps recorded)"}`;
1251
+ } else {
1252
+ const logContent = logsMap[f.relativePath] ?? "";
1253
+ const preview = logContent.split(`
1254
+ `).slice(0, 20).join(`
1255
+ `);
1256
+ return `Log: ${f.relativePath}
1257
+ Content preview:
1258
+ ${preview}`;
1259
+ }
1260
+ });
1261
+ sections.push(`## Demo Recordings
1262
+
1263
+ ${demoEntries.join(`
1264
+
1265
+ `)}`);
1266
+ return `You are a code reviewer. You are given a GitHub issue, git diff, coding guidelines, and demo recordings that show the feature in action.
1267
+
1268
+ ${sections.join(`
1269
+
1270
+ `)}
1271
+
1272
+ ## Task
1273
+
1274
+ Review the code changes and demo recordings against the GitHub issue's acceptance criteria. Generate a JSON object matching this exact schema:
1275
+
1276
+ {
1277
+ "demos": [
1278
+ {
1279
+ "file": "<filename>",
1280
+ "summary": "<a meaningful sentence describing what this demo showcases based on the steps>"
1281
+ }
1282
+ ],
1283
+ "review": {
1284
+ "summary": "<2-3 sentence overview of the changes>",
1285
+ "highlights": ["<positive aspect 1>", "<positive aspect 2>"],
1286
+ "verdict": "approve" | "request_changes",
1287
+ "verdictReason": "<one sentence justifying the verdict>",
1288
+ "issues": [
1289
+ {
1290
+ "severity": "major" | "minor" | "nit",
1291
+ "description": "<what the issue is and how to fix it>"
1292
+ }
1293
+ ]
1294
+ }
1295
+ }
1296
+
1297
+ Rules:
1298
+ - Return ONLY the JSON object, no markdown fences or extra text.
1299
+ - Include one entry in "demos" for each demo file, in the same order.
1300
+ - "file" must exactly match the provided relative path.
1301
+ - "verdict" must be exactly "approve" or "request_changes".
1302
+ - Use "request_changes" if acceptance criteria from the issue are not demonstrated.
1303
+ - "severity" must be exactly "major", "minor", or "nit".
1304
+ - "major": bugs, security issues, broken functionality, missing acceptance criteria.
1305
+ - "minor": code quality, readability, missing edge cases.
1306
+ - "nit": style, naming, trivial improvements.
1307
+ - "highlights" must have at least one entry.
1308
+ - "issues" can be an empty array if there are no issues.
1309
+ - Verify that demo steps demonstrate ALL acceptance criteria from the issue.`;
1310
+ }
1311
+ function collectDemoData(demoFiles) {
1312
+ const stepsMapByFilename = {};
1313
+ const stepsMapByRelativePath = {};
1314
+ const logsMap = {};
1315
+ for (const demo of demoFiles) {
1316
+ if (demo.type === "web-ux") {
1317
+ const stepsPath = join2(pathDirname(demo.path), "demo-steps.json");
1318
+ if (existsSync2(stepsPath)) {
1319
+ try {
1320
+ const raw = readFileSync3(stepsPath, "utf-8");
1321
+ const parsed = JSON.parse(raw);
1322
+ if (Array.isArray(parsed)) {
1323
+ stepsMapByFilename[demo.filename] = parsed;
1324
+ stepsMapByRelativePath[demo.relativePath] = parsed;
1325
+ }
1326
+ } catch {}
1327
+ }
1328
+ } else {
1329
+ logsMap[demo.relativePath] = readFileSync3(demo.path, "utf-8");
1330
+ }
1331
+ }
1332
+ return { stepsMapByFilename, stepsMapByRelativePath, logsMap };
1333
+ }
1334
+ async function runReviewOrchestration(options) {
1335
+ const exec = options.exec ?? defaultExec2;
1336
+ const cwd = options.cwd ?? process.cwd();
1337
+ const issue = options.issue ?? await fetchGitHubIssue(options.issueId, options.github);
1338
+ const gitRoot = await getGitRoot(exec, cwd);
1339
+ const branchName = await getCurrentBranch(exec, cwd);
1340
+ const repoContext = await getRepoContext(gitRoot, {
1341
+ exec,
1342
+ diffBase: options.diffBase
1343
+ });
1344
+ const reviewFolder = join2(gitRoot, ".demoon", "reviews", branchName);
1345
+ const assetsFolder = join2(reviewFolder, "assets");
1346
+ const testsFolder = join2(reviewFolder, "tests");
1347
+ if (!existsSync2(reviewFolder)) {
1348
+ mkdirSync(reviewFolder, { recursive: true });
1349
+ }
1350
+ if (!existsSync2(assetsFolder)) {
1351
+ mkdirSync(assetsFolder, { recursive: true });
1352
+ }
1353
+ if (!existsSync2(testsFolder)) {
1354
+ mkdirSync(testsFolder, { recursive: true });
1355
+ }
1356
+ const presenterPrompt = buildPresenterPrompt({
1357
+ issue,
1358
+ gitDiff: repoContext.gitDiff,
1359
+ guidelines: repoContext.guidelines,
1360
+ reviewFolder,
1361
+ assetsFolder,
1362
+ testsFolder
1363
+ });
1364
+ await invokeClaude(presenterPrompt, { agent: options.agent, spawn: options.spawn });
1365
+ const demoFiles = discoverDemoFiles(assetsFolder);
1366
+ if (demoFiles.length === 0) {
1367
+ throw new Error(`No demo files (.webm or .jsonl) found in ${assetsFolder} after Presenter phase`);
1368
+ }
1369
+ const { stepsMapByFilename, stepsMapByRelativePath, logsMap } = collectDemoData(demoFiles);
1370
+ const reviewerPrompt = buildReviewerPrompt({
1371
+ issue,
1372
+ gitDiff: repoContext.gitDiff,
1373
+ guidelines: repoContext.guidelines,
1374
+ demoFiles,
1375
+ stepsMap: stepsMapByFilename,
1376
+ logsMap
1377
+ });
1378
+ const rawOutput = await invokeClaude(reviewerPrompt, { agent: options.agent, spawn: options.spawn });
1379
+ const llmResponse = parseLlmResponse(rawOutput);
1380
+ const filenameToRelativePath = new Map(demoFiles.map((d) => [d.filename, d.relativePath]));
1381
+ const typeMap = new Map(demoFiles.map((d) => [d.filename, d.type]));
1382
+ const metadata = {
1383
+ demos: llmResponse.demos.map((demo) => {
1384
+ const relativePath = filenameToRelativePath.get(demo.file) ?? demo.file;
1385
+ return {
1386
+ file: relativePath,
1387
+ type: typeMap.get(demo.file) ?? "web-ux",
1388
+ summary: demo.summary,
1389
+ steps: stepsMapByRelativePath[relativePath] ?? []
1390
+ };
1391
+ }),
1392
+ review: llmResponse.review
1393
+ };
1394
+ const metadataPath = join2(assetsFolder, "review-metadata.json");
1395
+ writeFileSync2(metadataPath, JSON.stringify(metadata, null, 2) + `
1396
+ `);
1397
+ const appData = {
1398
+ metadata,
1399
+ title: `Review: Issue #${issue.number} - ${issue.title}`,
1400
+ videos: {},
1401
+ logs: Object.keys(logsMap).length > 0 ? logsMap : undefined,
1402
+ feedbackEndpoint: options.feedbackEndpoint
1403
+ };
1404
+ const html = generateReviewHtml(appData);
1405
+ const htmlPath = join2(assetsFolder, "review.html");
1406
+ writeFileSync2(htmlPath, html);
1407
+ return {
1408
+ reviewFolder,
1409
+ htmlPath,
1410
+ metadataPath,
1411
+ metadata,
1412
+ issue
1413
+ };
1414
+ }
1415
+ export {
1416
+ runReviewOrchestration,
1417
+ buildReviewerPrompt,
1418
+ buildPresenterPrompt
1419
+ };
1420
+
1421
+ //# debugId=83F2B7601D6B64A664756E2164756E21