@kud/ai-conventional-commit-cli 3.2.3 → 3.2.5

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 (51) hide show
  1. package/dist/{chunk-IWJLYYKM.js → chunk-EHJXGWTJ.js} +3 -19
  2. package/dist/index.cjs +1200 -0
  3. package/dist/index.d.cts +1 -0
  4. package/dist/index.js +59 -43
  5. package/dist/{reword-3MH2DYFS.js → reword-BKQ7K33J.js} +1 -1
  6. package/dist/{reword-3JBE7MPQ.js → reword-QQO7UBGM.js} +2 -0
  7. package/package.json +1 -1
  8. package/dist/chunk-2WRUFO3O.js +0 -689
  9. package/dist/chunk-2X3JJVRR.js +0 -639
  10. package/dist/chunk-7FBRAH4R.js +0 -643
  11. package/dist/chunk-7U4J2ORD.js +0 -614
  12. package/dist/chunk-CC3NIT53.js +0 -650
  13. package/dist/chunk-CLQ6OPLU.js +0 -668
  14. package/dist/chunk-F3BOAVBY.js +0 -122
  15. package/dist/chunk-FYJNHXAR.js +0 -700
  16. package/dist/chunk-H4W6AMGZ.js +0 -549
  17. package/dist/chunk-HJR5M6U7.js +0 -120
  18. package/dist/chunk-HOUMTU6H.js +0 -699
  19. package/dist/chunk-KEEMHNNS.js +0 -628
  20. package/dist/chunk-OLEHSPCO.js +0 -707
  21. package/dist/chunk-RHXNXVGI.js +0 -621
  22. package/dist/chunk-SNV4RWS4.js +0 -696
  23. package/dist/chunk-W7OC77AV.js +0 -649
  24. package/dist/chunk-WFXVVHL2.js +0 -645
  25. package/dist/chunk-YIXP5EWA.js +0 -545
  26. package/dist/chunk-YRVQGOVW.js +0 -649
  27. package/dist/chunk-ZLYMV2NJ.js +0 -644
  28. package/dist/config-C3S4LWLD.js +0 -12
  29. package/dist/config-RHGCFLHQ.js +0 -12
  30. package/dist/reword-2ASH5EH5.js +0 -212
  31. package/dist/reword-6EWRZ6WZ.js +0 -212
  32. package/dist/reword-CZDYMQEV.js +0 -150
  33. package/dist/reword-D5YVSCPO.js +0 -212
  34. package/dist/reword-ESY2TLBT.js +0 -212
  35. package/dist/reword-FE5N4MGV.js +0 -150
  36. package/dist/reword-IN2D2J4H.js +0 -212
  37. package/dist/reword-JRE6KAF7.js +0 -212
  38. package/dist/reword-KIR2DMTO.js +0 -212
  39. package/dist/reword-KUE3IVBE.js +0 -212
  40. package/dist/reword-LIVSGNUN.js +0 -212
  41. package/dist/reword-MCQOCOZ2.js +0 -212
  42. package/dist/reword-NGEKVTD6.js +0 -212
  43. package/dist/reword-PEOUOAT7.js +0 -212
  44. package/dist/reword-Q7MES34W.js +0 -212
  45. package/dist/reword-T44WTP5I.js +0 -212
  46. package/dist/reword-UA3EG7DK.js +0 -212
  47. package/dist/reword-UE5IP5V3.js +0 -212
  48. package/dist/reword-VKG5G6CB.js +0 -212
  49. package/dist/reword-VRH7B6BE.js +0 -205
  50. package/dist/reword-WFCNTOEU.js +0 -203
  51. package/dist/reword-XWYWVQRZ.js +0 -212
@@ -1,614 +0,0 @@
1
- // src/prompt.ts
2
- var matchesPattern = (filePath, pattern) => {
3
- const regexPattern = pattern.replace(/\*\*/g, "\xA7DOUBLESTAR\xA7").replace(/\*/g, "[^/]*").replace(/§DOUBLESTAR§/g, ".*").replace(/\./g, "\\.").replace(/\?/g, ".");
4
- const regex = new RegExp(`^${regexPattern}$`);
5
- return regex.test(filePath);
6
- };
7
- var summarizeDiffForPrompt = (files, privacy, maxFileLines, skipFilePatterns) => {
8
- const getTotalLines = (f) => {
9
- return f.hunks.reduce((sum, h) => sum + h.lines.length, 0);
10
- };
11
- const shouldSkipFile = (filePath) => {
12
- return skipFilePatterns.some((pattern) => matchesPattern(filePath, pattern));
13
- };
14
- if (privacy === "high") {
15
- return files.map((f) => {
16
- const totalLines = getTotalLines(f);
17
- const patternSkipped = shouldSkipFile(f.file);
18
- const sizeSkipped = totalLines > maxFileLines;
19
- const skipped = patternSkipped || sizeSkipped;
20
- const reason = patternSkipped ? "generated/lock file" : "large file";
21
- return `file: ${f.file} (+${f.additions} -${f.deletions}) hunks:${f.hunks.length}${skipped ? ` [${reason}, content skipped]` : ""}`;
22
- }).join("\n");
23
- }
24
- if (privacy === "medium") {
25
- return files.map((f) => {
26
- const totalLines = getTotalLines(f);
27
- const patternSkipped = shouldSkipFile(f.file);
28
- const sizeSkipped = totalLines > maxFileLines;
29
- if (patternSkipped || sizeSkipped) {
30
- const reason = patternSkipped ? "generated/lock file" : "large file";
31
- return `file: ${f.file} (+${f.additions} -${f.deletions}) hunks:${f.hunks.length} [${reason}, content skipped]`;
32
- }
33
- return `file: ${f.file}
34
- ` + f.hunks.map(
35
- (h) => ` hunk ${h.hash} context:${h.functionContext || ""} +${h.added} -${h.removed}`
36
- ).join("\n");
37
- }).join("\n");
38
- }
39
- return files.map((f) => {
40
- const totalLines = getTotalLines(f);
41
- const patternSkipped = shouldSkipFile(f.file);
42
- const sizeSkipped = totalLines > maxFileLines;
43
- if (patternSkipped || sizeSkipped) {
44
- const reason = patternSkipped ? "generated/lock file" : "large file";
45
- return `file: ${f.file} (+${f.additions} -${f.deletions}) hunks:${f.hunks.length} [${reason}, content skipped]`;
46
- }
47
- return `file: ${f.file}
48
- ` + f.hunks.map(
49
- (h) => `${h.header}
50
- ${h.lines.slice(0, 40).join("\n")}${h.lines.length > 40 ? "\n[truncated]" : ""}`
51
- ).join("\n");
52
- }).join("\n");
53
- };
54
- var buildGenerationMessages = (opts) => {
55
- const { files, style, config, mode, desiredCommits } = opts;
56
- const diff = summarizeDiffForPrompt(
57
- files,
58
- config.privacy,
59
- config.maxFileLines,
60
- config.skipFilePatterns
61
- );
62
- const TYPE_MAP = {
63
- feat: "A new feature or capability added for the user",
64
- fix: "A bug fix resolving incorrect behavior",
65
- chore: "Internal change with no user-facing impact",
66
- docs: "Documentation-only changes",
67
- refactor: "Code change that neither fixes a bug nor adds a feature",
68
- test: "Adding or improving tests only",
69
- ci: "Changes to CI configuration or scripts",
70
- perf: "Performance improvement",
71
- style: "Formatting or stylistic change (no logic)",
72
- build: "Build system or dependency changes",
73
- revert: "Revert a previous commit",
74
- merge: "Merge branches (rare; only if truly a merge commit)",
75
- security: "Security-related change or hardening",
76
- release: "Version bump or release meta change"
77
- };
78
- const specLines = [];
79
- specLines.push(
80
- "Purpose: Generate high-quality Conventional Commit messages for the provided git diff."
81
- );
82
- specLines.push("Locale: en");
83
- specLines.push(
84
- 'Output JSON Schema: { "commits": [ { "title": string, "body": string, "score": 0-100, "reasons": string[], "files"?: string[] } ], "meta": { "splitRecommended": boolean } }'
85
- );
86
- specLines.push("Primary Output Field: commits[ ].title");
87
- specLines.push("Title Format (REQUIRED): <type>(<scope>): <subject>");
88
- specLines.push(
89
- "Title Length Guidance: Aim for <=50 chars ideal; absolute max 72 (do not exceed)."
90
- );
91
- specLines.push("Types (JSON mapping follows on next line)");
92
- specLines.push("TypeMap: " + JSON.stringify(TYPE_MAP));
93
- specLines.push(
94
- "Scope Rules: ALWAYS include a concise lowercase kebab-case scope (derive from dominant directory, package, or feature); never omit."
95
- );
96
- specLines.push(
97
- "Subject Rules: imperative mood, present tense, no leading capital unless proper noun, no trailing period."
98
- );
99
- specLines.push(
100
- "Length Rule: Keep titles concise; prefer 50 or fewer chars; MUST be <=72 including type/scope."
101
- );
102
- specLines.push(
103
- "Emoji Rule: " + (config.style === "gitmoji" || config.style === "gitmoji-pure" ? "OPTIONAL single leading gitmoji BEFORE the type only if confidently adds clarity; do not invent or stack; omit if unsure." : "Disallow all emojis and gitmoji codes; output must start directly with the type.")
104
- );
105
- specLines.push(
106
- "Forbidden: breaking changes notation, exclamation mark after type unless truly semver-major (avoid unless diff clearly indicates)."
107
- );
108
- specLines.push("Fallback Type: use chore when no other type clearly fits.");
109
- specLines.push("Consistency: prefer existing top prefixes: " + style.topPrefixes.join(", "));
110
- specLines.push("Provide score (0-100) measuring clarity & specificity (higher is better).");
111
- specLines.push(
112
- "Provide reasons array citing concrete diff elements: filenames, functions, tests, metrics."
113
- );
114
- specLines.push(
115
- 'When mode is split, WHERE POSSIBLE add a "files" array per commit listing the most relevant changed file paths (1-6, minimize overlap across commits).'
116
- );
117
- specLines.push("Return ONLY the JSON object. No surrounding text or markdown.");
118
- specLines.push("Do not add fields not listed in schema.");
119
- specLines.push("Never fabricate content not present or implied by the diff.");
120
- specLines.push(
121
- "If mode is split and multiple logical changes exist, set meta.splitRecommended=true."
122
- );
123
- return [
124
- {
125
- role: "system",
126
- content: specLines.join("\n")
127
- },
128
- {
129
- role: "user",
130
- content: `Mode: ${mode}
131
- RequestedCommitCount: ${desiredCommits || (mode === "split" ? "2-6" : 1)}
132
- StyleFingerprint: ${JSON.stringify(style)}
133
- Diff:
134
- ${diff}
135
- Generate commit candidates now.`
136
- }
137
- ];
138
- };
139
- var buildRefineMessages = (opts) => {
140
- const { originalPlan, index, instructions, config } = opts;
141
- const target = originalPlan.commits[index];
142
- const spec = [];
143
- spec.push("Purpose: Refine a single Conventional Commit message while preserving intent.");
144
- spec.push("Locale: en");
145
- spec.push("Input: one existing commit JSON object.");
146
- spec.push(
147
- 'Output JSON Schema: { "commits": [ { "title": string, "body": string, "score": 0-100, "reasons": string[] } ] }'
148
- );
149
- spec.push("Title Format (REQUIRED): <type>(<scope>): <subject> (<=72 chars)");
150
- spec.push("Subject: imperative, present tense, no trailing period.");
151
- spec.push(
152
- "Emoji Rule: " + (config.style === "gitmoji" || config.style === "gitmoji-pure" ? "OPTIONAL single leading gitmoji BEFORE type if it adds clarity; omit if unsure." : "Disallow all emojis; start directly with the type.")
153
- );
154
- spec.push(
155
- "Preserve semantic meaning; ensure a scope is present (infer one if missing); only improve clarity, brevity, conformity."
156
- );
157
- spec.push("If instructions request scope or emoji, incorporate only if justified by content.");
158
- spec.push("Return ONLY JSON (commits array length=1).");
159
- return [
160
- { role: "system", content: spec.join("\n") },
161
- {
162
- role: "user",
163
- content: `Current commit object:
164
- ${JSON.stringify(target, null, 2)}
165
- Instructions:
166
- ${instructions.join("\n") || "None"}
167
- Refine now.`
168
- }
169
- ];
170
- };
171
-
172
- // src/model/provider.ts
173
- import { z } from "zod";
174
- import { createServer } from "net";
175
- import { createOpencode } from "@opencode-ai/sdk/v2";
176
- function findFreePort() {
177
- return new Promise((resolve, reject) => {
178
- const server = createServer();
179
- server.on("error", reject);
180
- server.listen(0, "127.0.0.1", () => {
181
- const port = server.address().port;
182
- server.close(() => resolve(port));
183
- });
184
- });
185
- }
186
- var OpenCodeProvider = class {
187
- constructor(model = "github-copilot/gpt-4.1") {
188
- this.model = model;
189
- }
190
- name() {
191
- return "opencode";
192
- }
193
- async chat(messages, _opts) {
194
- const debug = process.env.AICC_DEBUG === "true";
195
- const mockMode = process.env.AICC_DEBUG_PROVIDER === "mock";
196
- const timeoutMs = parseInt(process.env.AICC_MODEL_TIMEOUT_MS || "120000", 10);
197
- if (mockMode) {
198
- if (debug) console.error("[ai-cc][mock] Returning deterministic mock response");
199
- return JSON.stringify({
200
- commits: [
201
- {
202
- title: "chore: mock commit from provider",
203
- body: "",
204
- score: 80,
205
- reasons: ["mock mode"]
206
- }
207
- ],
208
- meta: { splitRecommended: false }
209
- });
210
- }
211
- const userAggregate = messages.map((m) => `${m.role.toUpperCase()}: ${m.content}`).join("\n\n");
212
- const fullPrompt = `Generate high-quality commit message candidates based on the staged git diff.
213
-
214
- Context:
215
- ${userAggregate}`;
216
- const slashIdx = this.model.indexOf("/");
217
- const providerID = slashIdx !== -1 ? this.model.slice(0, slashIdx) : this.model;
218
- const modelID = slashIdx !== -1 ? this.model.slice(slashIdx + 1) : this.model;
219
- const ac = new AbortController();
220
- const timer = setTimeout(() => ac.abort(), timeoutMs);
221
- const start = Date.now();
222
- let server;
223
- try {
224
- if (debug) console.error("[ai-cc][provider] starting opencode server (mcp disabled)");
225
- const port = await findFreePort();
226
- const opencode = await createOpencode({ signal: ac.signal, port, config: { mcp: {} } });
227
- server = opencode.server;
228
- const client = opencode.client;
229
- const sessionResult = await client.session.create({ title: "aicc" });
230
- if (!sessionResult.data) {
231
- const errMsg = sessionResult.error?.message ?? JSON.stringify(sessionResult.error) ?? "unknown";
232
- throw new Error(`Failed to create opencode session: ${errMsg}`);
233
- }
234
- const result = await client.session.prompt({
235
- sessionID: sessionResult.data.id,
236
- model: { providerID, modelID },
237
- format: {
238
- type: "json_schema",
239
- schema: COMMIT_PLAN_JSON_SCHEMA
240
- },
241
- parts: [{ type: "text", text: fullPrompt }]
242
- });
243
- if (debug) {
244
- const elapsed = Date.now() - start;
245
- console.error(
246
- `[ai-cc][provider] model=${this.model} elapsedMs=${elapsed} promptChars=${fullPrompt.length}`
247
- );
248
- console.error("[ai-cc][provider] result.data =", JSON.stringify(result.data, null, 2));
249
- }
250
- const structured = result.data?.info?.structured;
251
- if (structured == null) {
252
- const err = result.data?.info?.error;
253
- throw new Error(
254
- err ? `Model error: ${JSON.stringify(err)}` : "No structured output in response"
255
- );
256
- }
257
- return JSON.stringify(structured);
258
- } catch (e) {
259
- if (ac.signal.aborted) {
260
- throw new Error(`Model call timed out after ${timeoutMs}ms`);
261
- }
262
- if (debug) console.error("[ai-cc][provider] failure", e.message);
263
- throw new Error(e.message || "opencode SDK call failed");
264
- } finally {
265
- clearTimeout(timer);
266
- server?.close();
267
- }
268
- }
269
- };
270
- var CommitSchema = z.object({
271
- title: z.string().min(5).max(150),
272
- body: z.string().optional().default(""),
273
- score: z.number().min(0).max(100),
274
- reasons: z.array(z.string()).optional().default([]),
275
- files: z.array(z.string()).optional().default([])
276
- });
277
- var PlanSchema = z.object({
278
- commits: z.array(CommitSchema).min(1),
279
- meta: z.object({
280
- splitRecommended: z.boolean().optional()
281
- }).optional()
282
- });
283
- var COMMIT_PLAN_JSON_SCHEMA = {
284
- type: "object",
285
- required: ["commits"],
286
- properties: {
287
- commits: {
288
- type: "array",
289
- minItems: 1,
290
- items: {
291
- type: "object",
292
- required: ["title", "score"],
293
- properties: {
294
- title: { type: "string" },
295
- body: { type: "string" },
296
- score: { type: "number", minimum: 0, maximum: 100 },
297
- reasons: { type: "array", items: { type: "string" } },
298
- files: { type: "array", items: { type: "string" } }
299
- }
300
- }
301
- },
302
- meta: {
303
- type: "object",
304
- properties: {
305
- splitRecommended: { type: "boolean" }
306
- }
307
- }
308
- }
309
- };
310
- var extractJSON = (raw) => {
311
- const trimmed = raw.trim();
312
- let jsonText = null;
313
- if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
314
- jsonText = trimmed;
315
- } else {
316
- const match = raw.match(/\{[\s\S]*\}$/m);
317
- if (match) jsonText = match[0];
318
- }
319
- if (!jsonText) throw new Error("No JSON object detected.");
320
- let parsed;
321
- try {
322
- parsed = JSON.parse(jsonText);
323
- } catch {
324
- throw new Error("Invalid JSON parse");
325
- }
326
- return PlanSchema.parse(parsed);
327
- };
328
-
329
- // src/guardrails.ts
330
- var SECRET_PATTERNS = [
331
- /AWS_[A-Z0-9_]+/i,
332
- /BEGIN RSA PRIVATE KEY/,
333
- /-----BEGIN PRIVATE KEY-----/,
334
- /ssh-rsa AAAA/
335
- ];
336
- var CONVENTIONAL_RE = /^(?:([\p{Emoji}\p{So}\p{Sk}]+)\s+(feat|fix|chore|docs|refactor|test|ci|perf|style|build|revert|merge|security|release)(\(.+\))?:\s|([\p{Emoji}\p{So}\p{Sk}]+):\s.*|([\p{Emoji}\p{So}\p{Sk}]+):\s*$|(feat|fix|chore|docs|refactor|test|ci|perf|style|build|revert|merge|security|release)(\(.+\))?:\s)/u;
337
- var sanitizeTitle = (title, allowEmoji) => {
338
- let t = title.trim();
339
- if (allowEmoji) {
340
- const multi = t.match(/^((?:[\p{Emoji}\p{So}\p{Sk}]+)[\p{Emoji}\p{So}\p{Sk}\s]*)+/u);
341
- if (multi) {
342
- const first = Array.from(multi[0].trim())[0];
343
- t = first + " " + t.slice(multi[0].length).trimStart();
344
- }
345
- } else {
346
- t = t.replace(/^([\p{Emoji}\p{So}\p{Sk}\p{P}]+\s*)+/u, "").trimStart();
347
- }
348
- return t;
349
- };
350
- var normalizeConventionalTitle = (title) => {
351
- let original = title.trim();
352
- let leadingEmoji = "";
353
- const emojiCluster = original.match(/^[\p{Emoji}\p{So}\p{Sk}]+/u);
354
- if (emojiCluster) {
355
- leadingEmoji = Array.from(emojiCluster[0])[0];
356
- }
357
- let t = original.replace(/^([\p{Emoji}\p{So}\p{Sk}\p{P}]+\s*)+/u, "").trim();
358
- const m = t.match(/^(\w+)(\(.+\))?:\s+(.*)$/);
359
- let result;
360
- if (m) {
361
- const type = m[1].toLowerCase();
362
- const scope = m[2] || "";
363
- let subject = m[3].trim();
364
- subject = subject.replace(/\.$/, "");
365
- subject = subject.charAt(0).toLowerCase() + subject.slice(1);
366
- result = `${type}${scope}: ${subject}`;
367
- } else if (!/^\w+\(.+\)?: /.test(t)) {
368
- t = t.replace(/\.$/, "");
369
- t = t.charAt(0).toLowerCase() + t.slice(1);
370
- result = `chore: ${t}`;
371
- } else {
372
- result = t;
373
- }
374
- if (leadingEmoji) {
375
- result = `${leadingEmoji} ${result}`;
376
- }
377
- return result;
378
- };
379
- var checkCandidate = (candidate) => {
380
- const errs = [];
381
- if (!CONVENTIONAL_RE.test(candidate.title)) {
382
- errs.push("Not a valid conventional commit title.");
383
- }
384
- if (/^[A-Z]/.test(candidate.title)) {
385
- }
386
- const body = candidate.body || "";
387
- for (const pat of SECRET_PATTERNS) {
388
- if (pat.test(body)) {
389
- errs.push("Potential secret detected.");
390
- break;
391
- }
392
- }
393
- return errs;
394
- };
395
-
396
- // src/title-format.ts
397
- var EMOJI_MAP = {
398
- feat: "\u2728",
399
- fix: "\u{1F41B}",
400
- chore: "\u{1F9F9}",
401
- docs: "\u{1F4DD}",
402
- refactor: "\u267B\uFE0F",
403
- test: "\u2705",
404
- ci: "\u{1F916}",
405
- perf: "\u26A1\uFE0F",
406
- style: "\u{1F3A8}",
407
- build: "\u{1F3D7}\uFE0F",
408
- revert: "\u23EA",
409
- merge: "\u{1F500}",
410
- security: "\u{1F512}",
411
- release: "\u{1F3F7}\uFE0F"
412
- };
413
- var EMOJI_TYPE_RE = /^([\p{Emoji}\p{So}\p{Sk}])\s+(\w+)(\(.+\))?:\s+(.*)$/u;
414
- var TYPE_RE = /^(\w+)(\(.+\))?:\s+(.*)$/;
415
- var formatCommitTitle = (raw, opts) => {
416
- const { allowGitmoji, mode = "standard" } = opts;
417
- let norm = normalizeConventionalTitle(sanitizeTitle(raw, allowGitmoji));
418
- if (!allowGitmoji || mode !== "gitmoji" && mode !== "gitmoji-pure") {
419
- return norm;
420
- }
421
- if (mode === "gitmoji-pure") {
422
- let m2 = norm.match(EMOJI_TYPE_RE);
423
- if (m2) {
424
- const emoji = m2[1];
425
- const subject = m2[4];
426
- norm = `${emoji}: ${subject}`;
427
- } else if (m2 = norm.match(TYPE_RE)) {
428
- const type = m2[1];
429
- const subject = m2[3];
430
- const em = EMOJI_MAP[type] || "\u{1F527}";
431
- norm = `${em}: ${subject}`;
432
- } else if (!/^([\p{Emoji}\p{So}\p{Sk}])+:/u.test(norm)) {
433
- norm = `\u{1F527}: ${norm}`;
434
- }
435
- return norm;
436
- }
437
- let m = norm.match(EMOJI_TYPE_RE);
438
- if (m) {
439
- return norm;
440
- }
441
- if (m = norm.match(TYPE_RE)) {
442
- const type = m[1];
443
- const scope = m[2] || "";
444
- const subject = m[3];
445
- const em = EMOJI_MAP[type] || "\u{1F527}";
446
- norm = `${em} ${type}${scope}: ${subject}`;
447
- } else if (!/^([\p{Emoji}\p{So}\p{Sk}])+\s+\w+.*:/u.test(norm)) {
448
- norm = `\u{1F527} chore: ${norm}`;
449
- }
450
- return norm;
451
- };
452
-
453
- // src/workflow/ui.ts
454
- import chalk from "chalk";
455
- function animateHeaderBase(text = "ai-conventional-commit", modelSegment) {
456
- const mainText = text;
457
- const modelSeg = modelSegment ? ` (using ${modelSegment})` : "";
458
- if (!process.stdout.isTTY || process.env.AICC_NO_ANIMATION) {
459
- if (modelSeg) console.log("\n\u250C " + chalk.bold(mainText) + chalk.dim(modelSeg));
460
- else console.log("\n\u250C " + chalk.bold(mainText));
461
- return Promise.resolve();
462
- }
463
- const palette = [
464
- "#3a0d6d",
465
- "#5a1ea3",
466
- "#7a32d6",
467
- "#9a4dff",
468
- "#b267ff",
469
- "#c37dff",
470
- "#b267ff",
471
- "#9a4dff",
472
- "#7a32d6",
473
- "#5a1ea3"
474
- ];
475
- process.stdout.write("\n");
476
- return palette.reduce(async (p, color) => {
477
- await p;
478
- const frame = chalk.bold.hex(color)(mainText);
479
- if (modelSeg) process.stdout.write("\r\u250C " + frame + chalk.dim(modelSeg));
480
- else process.stdout.write("\r\u250C " + frame);
481
- await new Promise((r) => setTimeout(r, 60));
482
- }, Promise.resolve()).then(() => process.stdout.write("\n"));
483
- }
484
- function borderLine(content) {
485
- if (!content) console.log("\u2502");
486
- else console.log("\u2502 " + content);
487
- }
488
- function sectionTitle(label) {
489
- console.log("\u2299 " + chalk.bold(label));
490
- }
491
- function abortMessage() {
492
- console.log("\u2514 \u{1F645}\u200D\u2640\uFE0F No commit created.");
493
- console.log();
494
- }
495
- function finalSuccess(opts) {
496
- const elapsedMs = Date.now() - opts.startedAt;
497
- const seconds = elapsedMs / 1e3;
498
- const dur = seconds >= 0.1 ? seconds.toFixed(1) + "s" : elapsedMs + "ms";
499
- const plural = opts.count !== 1;
500
- if (plural) console.log(`\u2514 \u2728 ${opts.count} commits created in ${dur}.`);
501
- else console.log(`\u2514 \u2728 commit created in ${dur}.`);
502
- console.log();
503
- }
504
- function createPhasedSpinner(oraLib) {
505
- const useAnim = process.stdout.isTTY && !process.env.AICC_NO_ANIMATION && !process.env.AICC_NO_SPINNER_ANIM;
506
- const palette = [
507
- "#3a0d6d",
508
- "#5a1ea3",
509
- "#7a32d6",
510
- "#9a4dff",
511
- "#b267ff",
512
- "#c37dff",
513
- "#b267ff",
514
- "#9a4dff",
515
- "#7a32d6",
516
- "#5a1ea3"
517
- ];
518
- let label = "Starting";
519
- let i = 0;
520
- const spinner = oraLib({ text: chalk.bold(label), spinner: "dots" }).start();
521
- let interval = null;
522
- function frame() {
523
- if (!useAnim) return;
524
- spinner.text = chalk.bold.hex(palette[i])(label);
525
- i = (i + 1) % palette.length;
526
- }
527
- if (useAnim) {
528
- frame();
529
- interval = setInterval(frame, 80);
530
- }
531
- function setLabel(next) {
532
- label = next;
533
- if (useAnim) {
534
- i = 0;
535
- frame();
536
- } else {
537
- spinner.text = chalk.bold(label);
538
- }
539
- }
540
- function stopAnim() {
541
- if (interval) {
542
- clearInterval(interval);
543
- interval = null;
544
- }
545
- }
546
- return {
547
- spinner,
548
- async step(l, fn) {
549
- setLabel(l);
550
- try {
551
- return await fn();
552
- } catch (e) {
553
- stopAnim();
554
- const msg = `${l} failed: ${e?.message || e}`.replace(/^\s+/, "");
555
- spinner.fail(msg);
556
- throw e;
557
- }
558
- },
559
- phase(l) {
560
- setLabel(l);
561
- },
562
- stop() {
563
- stopAnim();
564
- spinner.stop();
565
- }
566
- };
567
- }
568
- function renderCommitBlock(opts) {
569
- const dim = (s) => chalk.dim(s);
570
- const white = (s) => chalk.white(s);
571
- const msgColor = opts.messageLabelColor || dim;
572
- const descColor = opts.descriptionLabelColor || dim;
573
- const titleColor = opts.titleColor || white;
574
- const bodyFirst = opts.bodyFirstLineColor || white;
575
- const bodyRest = opts.bodyLineColor || white;
576
- if (opts.fancy) {
577
- const heading = opts.heading ? chalk.hex("#9a4dff").bold(opts.heading) : void 0;
578
- if (heading) borderLine(heading);
579
- borderLine(msgColor("Title:") + " " + titleColor(`${opts.indexPrefix || ""}${opts.title}`));
580
- } else {
581
- if (opts.heading) borderLine(chalk.bold(opts.heading));
582
- if (!opts.hideMessageLabel)
583
- borderLine(msgColor("Message:") + " " + titleColor(`${opts.indexPrefix || ""}${opts.title}`));
584
- else
585
- borderLine(msgColor("Title:") + " " + titleColor(`${opts.indexPrefix || ""}${opts.title}`));
586
- }
587
- borderLine();
588
- if (opts.body) {
589
- const lines = opts.body.split("\n");
590
- lines.forEach((line, i) => {
591
- if (line.trim().length === 0) borderLine();
592
- else if (i === 0) {
593
- borderLine(descColor("Description:"));
594
- borderLine(bodyFirst(line));
595
- } else borderLine(bodyRest(line));
596
- });
597
- }
598
- }
599
-
600
- export {
601
- buildGenerationMessages,
602
- buildRefineMessages,
603
- OpenCodeProvider,
604
- extractJSON,
605
- checkCandidate,
606
- formatCommitTitle,
607
- animateHeaderBase,
608
- borderLine,
609
- sectionTitle,
610
- abortMessage,
611
- finalSuccess,
612
- createPhasedSpinner,
613
- renderCommitBlock
614
- };