-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.js
More file actions
729 lines (728 loc) · 25.9 KB
/
Copy pathclient.js
File metadata and controls
729 lines (728 loc) · 25.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
// dsh-opencode-usage — browser half (hand-written bundle, no build step).
//
// Mounts a composer-dock badge under the input card showing the OpenCode Go
// rolling / weekly / monthly usage (percent + reset countdown), expandable
// into a card with progress bars, an instant-refresh button, and the API key
// / base URL / refresh-interval configuration form. All data flows through
// the host's /api/dsh-opencode-usage routes (same-origin fetch), so the API
// key never lives in the browser.
//
// This file is the raw bundle the module loader serves at
// /plugins/@chen-001/dsh-opencode-usage/client.js — keep it dependency-free
// beyond the injected client runtime and React.
window.__ModuleLoader__.load({
id: "@chen-001/dsh-opencode-usage",
factory: (require) => {
var module = { exports: {} };
var exports = module.exports;
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
let react_jsx_runtime = require("react/jsx-runtime");
let react = require("react");
//#region lib/client-core.ts
/**
* Route paths (mirror of the host half's routes.mjs API_PATHS).
*/
const API_USAGE = "/api/dsh-opencode-usage/usage";
const API_CONFIG = "/api/dsh-opencode-usage/config";
/**
* Parse a JSON response or throw with the route's error message.
*/
async function readJson(response) {
let body;
try {
body = await response.json();
} catch {
throw new Error(`HTTP ${response.status}: invalid JSON response`);
}
if (!response.ok) {
const message = body && typeof body === "object" && typeof body.error === "string" ? body.error : `HTTP ${response.status}`;
throw new Error(message);
}
return body;
}
/**
* Fetch with a hard timeout (the browser's fetch has none by default: a
* request that never settles — e.g. a hung connection or an extension
* that intercepts the POST — would otherwise leave the save button stuck
* on "saving…" forever, since the save flow awaits it).
* @param {string} url - the request URL.
* @param {object} [options] - fetch options (merged with the signal).
* @param {number} [timeoutMs] - abort after this many milliseconds.
* @returns {Promise<Response>}
*/
async function fetchWithTimeout(url, options = {}, timeoutMs = 20000) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
return await fetch(url, { ...options, signal: controller.signal });
} finally {
clearTimeout(timer);
}
}
/**
* Fetch the current usage snapshot from the host proxy.
* @returns {Promise<object>} { ok, data?, error? }.
*/
async function fetchUsage() {
try {
const body = await readJson(await fetchWithTimeout(API_USAGE, { cache: "no-store" }));
return body;
} catch (error) {
return { ok: false, error: error instanceof Error ? error.message : String(error) };
}
}
/**
* Fetch the (secret-free) config.
* @returns {Promise<object>} the public config.
*/
async function fetchConfig() {
const body = await readJson(await fetchWithTimeout(API_CONFIG, { cache: "no-store" }));
return body.config;
}
/**
* Persist a config patch; resolves to the updated public config.
* @param {object} patch - { apiKey?, baseUrl?, refreshSeconds? }.
* @returns {Promise<object>} the public config.
*/
async function saveConfig(patch) {
const body = await readJson(await fetchWithTimeout(API_CONFIG, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(patch)
}));
return body.config;
}
/**
* Format a countdown in the active locale, e.g. "3 小时 20 分钟".
* @param {Function} t - namespace-bound translate function.
* @param {number|null} seconds - remaining seconds.
* @returns {string}
*/
function formatRemaining(t, seconds) {
if (seconds === null || seconds === undefined || !Number.isFinite(seconds)) return t("timeUnknown");
if (seconds <= 0) return t("timeReset");
const d = Math.floor(seconds / 86400);
const h = Math.floor((seconds % 86400) / 3600);
const m = Math.floor((seconds % 3600) / 60);
const parts = [];
if (d > 0) parts.push(t("timeDay", { n: d }));
if (h > 0) parts.push(t("timeHour", { n: h }));
if (m > 0) parts.push(t("timeMinute", { n: m }));
if (parts.length === 0) return t("timeLessMinute");
return parts.join(" ");
}
//#endregion
//#region UsageBadge.tsx
/**
* Shared inline styles (dsw alias variables keep the plugin theme-aware;
* every var() carries a fallback so an unset alias degrades gracefully).
*/
const S = {
row: {
boxSizing: "border-box",
display: "flex",
alignItems: "center",
justifyContent: "center",
gap: "6px",
margin: "0 auto",
maxWidth: "var(--dsh-chat-content-width, 748px)",
padding: "0 var(--dsh-composer-side-clearance, 0px)",
width: "100%",
textAlign: "center"
},
badge: {
border: "none",
background: "none",
padding: "2px 10px",
borderRadius: "10px",
cursor: "pointer",
color: "var(--dsw-alias-label-secondary, #61666b)",
fontSize: "12px",
lineHeight: "20px",
fontVariantNumeric: "tabular-nums",
whiteSpace: "nowrap",
display: "inline-flex",
alignItems: "center",
gap: "6px",
maxWidth: "100%",
overflow: "hidden"
},
badgeHover: {
background: "var(--dsw-alias-interactive-bg-hover, rgb(0 0 0 / 6%))"
},
dot: {
width: "8px",
height: "8px",
borderRadius: "50%",
flexShrink: 0
},
card: {
boxSizing: "border-box",
margin: "0 auto",
maxWidth: "var(--dsh-chat-content-width, 748px)",
padding: "0 var(--dsh-composer-side-clearance, 0px) 2px",
width: "100%"
},
cardBox: {
background: "var(--dsw-alias-bg-module-platform, #ffffff)",
border: "1px solid var(--dsw-alias-border-l2, rgb(0 0 0 / 10%))",
borderRadius: "12px",
boxShadow: "var(--dsw-shadow-lv2, 0 4px 16px rgb(0 0 0 / 12%))",
padding: "12px 14px",
fontSize: "13px",
lineHeight: "20px",
color: "var(--dsw-alias-label-primary, #0f1115)"
},
cardHead: {
display: "flex",
alignItems: "center",
gap: "8px",
marginBottom: "10px"
},
cardTitle: {
flex: 1,
fontWeight: 600,
fontSize: "13px"
},
headBtn: {
border: "1px solid var(--dsw-alias-border-l2, rgb(0 0 0 / 10%))",
background: "var(--dsw-alias-bg-module-platform, #ffffff)",
color: "var(--dsw-alias-label-secondary, #61666b)",
borderRadius: "8px",
padding: "2px 10px",
fontSize: "12px",
cursor: "pointer"
},
windowRow: {
display: "flex",
alignItems: "center",
gap: "10px",
padding: "6px 0"
},
windowLabel: {
width: "78px",
flexShrink: 0,
color: "var(--dsw-alias-label-secondary, #61666b)"
},
track: {
flex: 1,
height: "6px",
borderRadius: "3px",
background: "var(--dsw-alias-border-l2, rgb(0 0 0 / 10%))",
overflow: "hidden"
},
fill: {
height: "100%",
borderRadius: "3px",
transition: "width 300ms ease"
},
windowValue: {
width: "52px",
textAlign: "right",
flexShrink: 0,
fontVariantNumeric: "tabular-nums"
},
windowReset: {
width: "130px",
textAlign: "right",
flexShrink: 0,
color: "var(--dsw-alias-label-tertiary, #81858c)",
fontSize: "12px",
fontVariantNumeric: "tabular-nums"
},
meta: {
marginTop: "6px",
fontSize: "11px",
color: "var(--dsw-alias-label-tertiary, #81858c)",
display: "flex",
gap: "10px",
alignItems: "center",
flexWrap: "wrap"
},
error: {
marginTop: "8px",
fontSize: "12px",
color: "var(--dsw-alias-danger, #e5484d)",
wordBreak: "break-all"
},
config: {
marginTop: "10px",
borderTop: "1px solid var(--dsw-alias-border-l2, rgb(0 0 0 / 10%))",
paddingTop: "10px",
display: "flex",
flexDirection: "column",
gap: "8px"
},
field: {
display: "flex",
alignItems: "center",
gap: "8px"
},
fieldLabel: {
width: "88px",
flexShrink: 0,
fontSize: "12px",
color: "var(--dsw-alias-label-secondary, #61666b)"
},
input: {
flex: 1,
minWidth: 0,
background: "var(--dsw-alias-bg-input, var(--dsw-alias-bg-module-platform, #ffffff))",
border: "1px solid var(--dsw-alias-border-l2, rgb(0 0 0 / 10%))",
borderRadius: "8px",
color: "var(--dsw-alias-label-primary, #0f1115)",
padding: "4px 10px",
fontSize: "12px",
fontFamily: "inherit"
},
configActions: {
display: "flex",
justifyContent: "flex-end",
gap: "8px"
},
primaryBtn: {
border: "none",
background: "var(--dsw-alias-interactive-accent, #3964fe)",
color: "var(--dsw-alias-label-primary-invert, #ffffff)",
borderRadius: "8px",
padding: "4px 14px",
fontSize: "12px",
cursor: "pointer"
},
keySource: {
fontSize: "11px",
color: "var(--dsw-alias-label-tertiary, #81858c)"
},
langGroup: {
display: "flex",
gap: "4px",
alignItems: "center",
marginRight: "auto"
},
langPill: {
border: "1px solid var(--dsw-alias-border-l2, rgb(0 0 0 / 10%))",
background: "var(--dsw-alias-bg-module-platform, #ffffff)",
color: "var(--dsw-alias-label-secondary, #61666b)",
borderRadius: "6px",
padding: "2px 8px",
fontSize: "11px",
lineHeight: "16px",
cursor: "pointer"
},
langPillActive: {
border: "1px solid var(--dsw-alias-interactive-accent, #3964fe)",
background: "var(--dsw-alias-interactive-accent, #3964fe)",
color: "var(--dsw-alias-label-primary-invert, #ffffff)",
borderRadius: "6px",
padding: "2px 8px",
fontSize: "11px",
lineHeight: "16px",
cursor: "pointer"
}
};
/**
* Progress fill color by used percent.
* @param {number|null} percent - used share 0-100.
* @returns {string} css color.
*/
function fillColor(percent) {
if (percent === null || percent === undefined) return "var(--dsw-alias-border-l2, rgb(0 0 0 / 10%))";
if (percent >= 90) return "var(--dsw-alias-danger, #e5484d)";
if (percent >= 60) return "#e6a23c";
return "var(--dsw-alias-interactive-accent, #3964fe)";
}
/**
* The composer-dock badge + expandable usage card.
* @param {object} props - composed slot props.
* @param {Function} props.t - namespace-bound translate function (injected
* by the renderer because the entry registers `locale: NS`).
* @param {object} props.locale - the LocaleRuntime (passed via slot inject)
* powering the in-card 中文 / English toggle.
*/
function UsageBadge({ t, locale }) {
const [usage, setUsage] = react.useState(null);
const [error, setError] = react.useState(null);
const [expanded, setExpanded] = react.useState(false);
const [now, setNow] = react.useState(Date.now());
const [config, setConfig] = react.useState(null);
const [draft, setDraft] = react.useState({ apiKey: "", baseUrl: "", refreshSeconds: "", webUsageUrl: "" });
const [saving, setSaving] = react.useState(false);
const [saveError, setSaveError] = react.useState(null);
const [hover, setHover] = react.useState(false);
// Active locale snapshot: the renderer re-renders every outlet on a
// locale switch (useLocaleRevision), so a per-render read is always
// fresh. The `locale` runtime also powers the in-card language toggle.
const localeSnapshot = locale ? locale.getSnapshot() : null;
const activeLocale = localeSnapshot ? localeSnapshot.active : "zh";
const localeOptions = localeSnapshot ? localeSnapshot.locales : [{ id: "zh", label: "中文" }, { id: "en", label: "English" }];
const refreshSeconds = config && typeof config.refreshSeconds === "number" ? config.refreshSeconds : 300;
// Load config once; seed the draft from it.
react.useEffect(() => {
let alive = true;
fetchConfig().then((cfg) => {
if (!alive) return;
setConfig(cfg);
setDraft({
apiKey: "",
baseUrl: cfg.baseUrl || "",
refreshSeconds: String(cfg.refreshSeconds ?? 300),
webUsageUrl: cfg.webUsageUrl || ""
});
}).catch((err) => {
if (alive) setError(err instanceof Error ? err.message : String(err));
});
return () => { alive = false; };
}, []);
// Fetch usage immediately, then poll on the configured interval.
react.useEffect(() => {
let alive = true;
let timer = null;
const tick = async () => {
const result = await fetchUsage();
if (!alive) return;
if (result.ok) {
setUsage(result);
setError(null);
} else {
setUsage(null);
setError(result.error ?? t("queryFailed"));
}
};
tick();
timer = setInterval(tick, Math.max(10, refreshSeconds) * 1000);
return () => {
alive = false;
if (timer !== null) clearInterval(timer);
};
}, [refreshSeconds]);
// Countdown tick (only while the card is open; light either way).
react.useEffect(() => {
if (!expanded) return;
const timer = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(timer);
}, [expanded]);
// Derive live countdowns from fetched resetsInSeconds (host already
// computes relative to server time; drift here is capped by polling).
const windows = (usage && usage.ok ? usage.data.windows : []) || [];
const derived = windows.map((w) => {
let remaining = w.resetsInSeconds;
if (remaining !== null && remaining !== undefined) {
remaining = Math.max(0, remaining - Math.floor((now - (usage.data.fetchedAt || now)) / 1000));
}
return { ...w, remaining };
});
const sourceBadge = config ? (config.apiKeySource === "env" ? t("sourceEnv") : config.apiKeySource === "file" ? t("sourceFile") : t("sourceNone")) : "";
const onClickSave = async () => {
setSaving(true);
setSaveError(null);
// Belt-and-suspenders: force the button back even if a request
// somehow outlives its fetch timeout (never leave it stuck on
// "saving…").
const deadline = setTimeout(() => setSaving(false), 25000);
try {
const patch = {};
if (draft.apiKey !== "" && draft.apiKey !== undefined) patch.apiKey = draft.apiKey;
if (draft.baseUrl !== "") patch.baseUrl = draft.baseUrl;
if (draft.webUsageUrl !== undefined) patch.webUsageUrl = draft.webUsageUrl;
const parsedRefresh = Number(draft.refreshSeconds);
if (Number.isFinite(parsedRefresh) && parsedRefresh >= 10) patch.refreshSeconds = parsedRefresh;
const next = await saveConfig(patch);
setConfig(next);
setDraft((d) => ({ ...d, apiKey: "", baseUrl: next.baseUrl, refreshSeconds: String(next.refreshSeconds), webUsageUrl: next.webUsageUrl || "" }));
const result = await fetchUsage();
if (result.ok) {
setUsage(result);
setError(null);
} else {
setError(result.error ?? t("queryFailed"));
}
} catch (err) {
setSaveError(err instanceof Error ? err.message : String(err));
} finally {
clearTimeout(deadline);
setSaving(false);
}
};
const dotColor = error !== null ? "var(--dsw-alias-danger, #e5484d)" : usage === null ? "var(--dsw-alias-label-tertiary, #81858c)" : "var(--dsw-alias-interactive-accent, #3964fe)";
const badgeText = error !== null
? t("badgeFailed")
: usage === null
? t("badgeLoading")
: `${t("badgePrefix")}${derived.map((w) => `${t("window." + w.key) ?? w.key} ${w.percent === null ? "?" : w.percent + "%"}`).join(" · ")}`;
return react_jsx_runtime.jsxs(react.Fragment, {
children: [
react_jsx_runtime.jsx("div", {
style: S.row,
children: react_jsx_runtime.jsx("button", {
type: "button",
style: { ...S.badge, ...(hover ? S.badgeHover : null) },
onMouseEnter: () => setHover(true),
onMouseLeave: () => setHover(false),
onClick: () => setExpanded((v) => !v),
title: t("badgeTitle"),
"aria-expanded": expanded,
children: [
react_jsx_runtime.jsx("span", { style: { ...S.dot, background: dotColor } }),
react_jsx_runtime.jsx("span", { children: badgeText })
]
})
}),
expanded ? react_jsx_runtime.jsx("div", {
style: S.card,
children: react_jsx_runtime.jsx("div", {
style: S.cardBox,
children: [
react_jsx_runtime.jsxs("div", {
style: S.cardHead,
children: [
react_jsx_runtime.jsx("div", { style: S.cardTitle, children: t("title") }),
config && config.webUsageUrl ? react_jsx_runtime.jsx("a", {
href: config.webUsageUrl,
target: "_blank",
rel: "noopener noreferrer",
style: { ...S.headBtn, textDecoration: "none", display: "inline-flex", alignItems: "center" },
title: t("opencodeTitle"),
children: "opencode"
}) : null,
react_jsx_runtime.jsx("button", {
type: "button",
style: S.headBtn,
onClick: async () => {
const result = await fetchUsage();
if (result.ok) { setUsage(result); setError(null); } else { setUsage(null); setError(result.error ?? t("queryFailed")); }
},
children: t("refresh")
}),
react_jsx_runtime.jsx("button", {
type: "button",
style: S.headBtn,
onClick: () => setExpanded(false),
children: t("collapse")
})
]
}),
error !== null ? react_jsx_runtime.jsx("div", { style: S.error, children: config && config.hasApiKey === false ? t("errorNoKey") : error }) : null,
derived.map((w) => {
const percent = w.percent === null || w.percent === undefined ? 0 : Math.min(100, Math.max(0, w.percent));
return react_jsx_runtime.jsxs("div", {
style: S.windowRow,
children: [
react_jsx_runtime.jsx("div", { style: S.windowLabel, children: t("window." + w.key) ?? w.label }),
react_jsx_runtime.jsx("div", {
style: S.track,
children: react_jsx_runtime.jsx("div", { style: { ...S.fill, width: `${percent}%`, background: fillColor(w.percent) } })
}),
react_jsx_runtime.jsx("div", { style: S.windowValue, children: w.percent === null ? "?" : `${w.percent}%` }),
react_jsx_runtime.jsx("div", { style: S.windowReset, children: t("resetAt", { time: formatRemaining(t, w.remaining) }) })
]
}, w.key);
}),
react_jsx_runtime.jsxs("div", {
style: S.meta,
children: [
react_jsx_runtime.jsx("span", { children: t("metaApiKey", { source: sourceBadge }) }),
usage && usage.ok ? react_jsx_runtime.jsx("span", { children: t("metaBaseUrl", { url: usage.data.baseUrl }) }) : null,
react_jsx_runtime.jsx("span", { children: t("metaRefresh", { seconds: refreshSeconds }) })
]
}),
react_jsx_runtime.jsxs("div", {
style: S.config,
children: [
react_jsx_runtime.jsxs("div", {
style: S.field,
children: [
react_jsx_runtime.jsx("div", { style: S.fieldLabel, children: t("fieldApiKey") }),
react_jsx_runtime.jsx("input", {
type: "password",
style: S.input,
placeholder: t("placeholderApiKey"),
value: draft.apiKey,
onChange: (e) => setDraft((d) => ({ ...d, apiKey: e.target.value })),
autoComplete: "off"
})
]
}),
react_jsx_runtime.jsxs("div", {
style: S.field,
children: [
react_jsx_runtime.jsx("div", { style: S.fieldLabel, children: t("fieldBaseUrl") }),
react_jsx_runtime.jsx("input", {
type: "text",
style: S.input,
placeholder: "https://opencode.ai/zen/go",
value: draft.baseUrl,
onChange: (e) => setDraft((d) => ({ ...d, baseUrl: e.target.value }))
})
]
}),
react_jsx_runtime.jsxs("div", {
style: S.field,
children: [
react_jsx_runtime.jsx("div", { style: S.fieldLabel, children: t("fieldWebUsageUrl") }),
react_jsx_runtime.jsx("input", {
type: "text",
style: S.input,
placeholder: t("placeholderWebUsageUrl"),
value: draft.webUsageUrl,
onChange: (e) => setDraft((d) => ({ ...d, webUsageUrl: e.target.value }))
})
]
}),
react_jsx_runtime.jsxs("div", {
style: S.field,
children: [
react_jsx_runtime.jsx("div", { style: S.fieldLabel, children: t("fieldRefresh") }),
react_jsx_runtime.jsx("input", {
type: "number",
style: S.input,
min: 10,
value: draft.refreshSeconds,
onChange: (e) => setDraft((d) => ({ ...d, refreshSeconds: e.target.value }))
})
]
}),
saveError !== null ? react_jsx_runtime.jsx("div", { style: S.error, children: saveError }) : null,
react_jsx_runtime.jsxs("div", {
style: S.configActions,
children: [
react_jsx_runtime.jsx("div", {
style: S.langGroup,
title: t("langToggle"),
children: localeOptions.map((l) => react_jsx_runtime.jsx("button", {
type: "button",
style: l.id === activeLocale ? S.langPillActive : S.langPill,
onClick: () => { if (locale) locale.setLocale(l.id); },
"aria-pressed": l.id === activeLocale,
children: l.label
}, l.id))
}),
react_jsx_runtime.jsx("span", { style: S.keySource, children: t("storageHint") }),
react_jsx_runtime.jsx("button", {
type: "button",
style: S.primaryBtn,
disabled: saving,
onClick: onClickSave,
children: saving ? t("saving") : t("saveAndRefresh")
})
]
})
]
})
]
})
}) : null
]
});
}
//#endregion
//#region index.ts
/**
* Dictionary namespace owned by this plugin. The badge/card copy rides the
* framework-injected `t` seat (the entry registers `locale: NS`), so every
* string below is fully bilingual — zh is the key-set source of truth and
* en must stay complete. Language switching is the global DSH locale
* preference (Settings → General → Language row, plus the in-card toggle).
*/
const NS = "dsh-opencode-usage";
const zh = {
title: "OpenCode Go 套餐用量",
badgePrefix: "OpenCode Go:",
badgeLoading: "OpenCode Go:加载中…",
badgeFailed: "OpenCode Go:查询失败",
badgeTitle: "点击查看 OpenCode Go 套餐用量详情 / 配置",
"window.rolling": "滚动用量",
"window.weekly": "每周用量",
"window.monthly": "每月用量",
timeUnknown: "未知",
timeReset: "已重置",
timeDay: "{n} 天",
timeHour: "{n} 小时",
timeMinute: "{n} 分钟",
timeLessMinute: "不足 1 分钟",
queryFailed: "查询失败",
errorNoKey: "未配置 OpenCode Go API key:请在用量卡片中填写,或设置环境变量 OPENCODE_GO_API_KEY",
opencodeTitle: "在 opencode.ai 网页端查看用量",
refresh: "立即刷新",
collapse: "收起",
resetAt: "重置于 {time}",
sourceEnv: "环境变量",
sourceFile: "配置文件",
sourceNone: "未配置",
metaApiKey: "API key:{source}",
metaBaseUrl: "接口:{url}",
metaRefresh: "自动刷新:每 {seconds} 秒",
fieldApiKey: "API Key",
fieldBaseUrl: "Base URL",
fieldWebUsageUrl: "用量网页 URL",
fieldRefresh: "刷新间隔(秒)",
placeholderApiKey: "留空则沿用环境变量 / 现有配置",
placeholderWebUsageUrl: "https://opencode.ai/workspace/<workspace-id>/go(留空隐藏 opencode 按钮)",
storageHint: "API key 存于 ~/.dsh/dsh-opencode-usage.json(0600)",
saving: "保存中…",
saveAndRefresh: "保存并刷新",
langToggle: "界面语言(全局设置)"
};
const en = {
title: "OpenCode Go plan usage",
badgePrefix: "OpenCode Go: ",
badgeLoading: "OpenCode Go: loading…",
badgeFailed: "OpenCode Go: query failed",
badgeTitle: "View OpenCode Go plan usage details / configuration",
"window.rolling": "Rolling usage",
"window.weekly": "Weekly usage",
"window.monthly": "Monthly usage",
timeUnknown: "unknown",
timeReset: "reset",
timeDay: "{n} d",
timeHour: "{n} h",
timeMinute: "{n} min",
timeLessMinute: "less than a minute",
queryFailed: "Query failed",
errorNoKey: "No OpenCode Go API key configured: fill it in the usage card, or set the OPENCODE_GO_API_KEY environment variable",
opencodeTitle: "View usage on opencode.ai",
refresh: "Refresh",
collapse: "Collapse",
resetAt: "Resets in {time}",
sourceEnv: "Environment",
sourceFile: "Config file",
sourceNone: "Not configured",
metaApiKey: "API key: {source}",
metaBaseUrl: "Endpoint: {url}",
metaRefresh: "Auto-refresh every {seconds}s",
fieldApiKey: "API Key",
fieldBaseUrl: "Base URL",
fieldWebUsageUrl: "Web usage URL",
fieldRefresh: "Interval (s)",
placeholderApiKey: "Leave empty to keep the environment variable / existing config",
placeholderWebUsageUrl: "https://opencode.ai/workspace/<workspace-id>/go (empty hides the opencode button)",
storageHint: "API key stored in ~/.dsh/dsh-opencode-usage.json (0600)",
saving: "Saving…",
saveAndRefresh: "Save & refresh",
langToggle: "UI language (global)"
};
/**
* Required services.
*/
const inject = ["slots", "locale"];
/**
* Browser plugin body: register the composer-dock badge.
* @param ctx - client cordis context.
*/
function apply(ctx) {
ctx.effect(() => ctx.locale.register(NS, { zh, en }), "dsh-opencode-usage: dictionaries");
ctx.slots.inject("conversation.composer.dock", () => ctx.slots.register({
name: "conversation.composer.dock",
id: "opencode-usage",
order: 200,
locale: NS,
inject: () => ({ locale: ctx.locale })
}, UsageBadge));
ctx.effect(() => () => { /* slot registration is fiber-scoped */ }, "dsh-opencode-usage: ui");
}
//#endregion
exports.apply = apply;
exports.inject = inject;
exports.UsageBadge = UsageBadge;
return module.exports;
}
});