@cortexkit/common-auth 0.42.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,47 +1,26 @@
1
- import type { RGBA } from '@opentui/core'
2
- import type { JSX } from '@opentui/solid'
3
1
  import {
4
- createContext,
5
- createMemo,
6
- createSignal,
7
- For,
8
- Index,
9
- mergeProps,
10
- Show,
11
- useContext,
12
- } from 'solid-js'
2
+ SidebarFrame as Frame,
3
+ type AccountView as FrameAccountView,
4
+ type PaceView,
5
+ type SidebarAppearance,
6
+ type SidebarTheme,
7
+ type Tone,
8
+ } from '@cortexkit/opencode-sidebar'
9
+ import type { JSX } from '@opentui/solid'
10
+ import { mapArray, mergeProps } from 'solid-js'
13
11
  import type { QuotaWindowPart } from '../quota/format.js'
14
12
  import { formatQuota, quotaWindowParts } from '../quota/format.js'
15
13
  import type { ProjectedQuota } from '../quota/projection.js'
16
14
 
17
- export type Tone =
18
- | 'text'
19
- | 'textMuted'
20
- | 'accent'
21
- | 'success'
22
- | 'warning'
23
- | 'error'
24
-
25
- export type SidebarTheme = Readonly<
26
- Partial<
27
- Record<Tone | 'background' | 'borderActive', RGBA | string | undefined>
28
- >
29
- >
30
-
31
- export interface SidebarAppearance {
32
- barWidth: number
33
- barFilledChar: string
34
- barEmptyChar: string
35
- warnThreshold: number
36
- errorThreshold: number
37
- }
38
-
39
- export interface PaceView {
40
- text: string
41
- tone: Tone
42
- /** The elapsed-window percentage, not the difference from usage. */
43
- overlay?: { kind: 'reserve' | 'deficit'; percent: number }
44
- }
15
+ export {
16
+ type PaceView,
17
+ type SidebarAppearance,
18
+ SidebarSection,
19
+ SidebarStatRow,
20
+ SidebarTextRow,
21
+ type SidebarTheme,
22
+ type Tone,
23
+ } from '@cortexkit/opencode-sidebar'
45
24
 
46
25
  export interface QuotaGroupView {
47
26
  title?: string
@@ -77,578 +56,41 @@ export interface SidebarFrameProps {
77
56
  collapsedSections?: () => JSX.Element
78
57
  }
79
58
 
80
- type FrameContextProps = Omit<SidebarFrameProps, 'theme'> & {
81
- theme: SidebarTheme
82
- }
83
-
84
- const FrameContext = createContext<FrameContextProps>()
85
-
86
- function frameContext(): FrameContextProps {
87
- const context = useContext(FrameContext)
88
- if (!context)
89
- throw new Error('Sidebar primitives must be inside SidebarFrame')
90
- return context
91
- }
92
-
93
- function displayWidth(text: string): number {
94
- const bun = (
95
- globalThis as { Bun?: { stringWidth?: (text: string) => number } }
96
- ).Bun
97
- return bun?.stringWidth ? bun.stringWidth(text) : Array.from(text).length
98
- }
99
-
100
- function fitText(text: string, columns: number): string {
101
- if (displayWidth(text) <= columns) return text
102
- if (columns < 1) return ''
103
- let kept = ''
104
- let used = 0
105
- for (const char of text) {
106
- const width = displayWidth(char)
107
- if (used + width > columns - 1) break
108
- kept += char
109
- used += width
110
- }
111
- return `${kept}\u2026`
112
- }
113
-
114
- /** A heading and its plugin-owned rows, with the frame's section spacing. */
115
- export function SidebarSection(props: {
116
- title: string
117
- children?: JSX.Element
118
- }) {
119
- const context = frameContext()
120
- return (
121
- <>
122
- <box width='100%' marginTop={1}>
123
- <text fg={context.theme.text}>
124
- <b>{props.title}</b>
125
- </text>
126
- </box>
127
- {props.children}
128
- </>
129
- )
130
- }
131
-
132
- /** Keep labels whole and reserve one blank cell before an ellipsized value. */
133
- export function SidebarStatRow(props: {
134
- label: string
135
- value: string
136
- tone?: Tone
137
- }) {
138
- const context = frameContext()
139
- const [width, setWidth] = createSignal(0)
140
- let row: { width: number } | undefined
141
- const value = () =>
142
- width() <= 0
143
- ? props.value
144
- : fitText(props.value, width() - displayWidth(props.label) - 1)
145
- return (
146
- <box
147
- ref={(element: { width: number }) => {
148
- row = element
149
- }}
150
- onSizeChange={() => setWidth(row?.width ?? 0)}
151
- width='100%'
152
- flexDirection='row'
153
- justifyContent='space-between'
154
- columnGap={1}
155
- >
156
- <text fg={context.theme.textMuted} wrapMode='none' flexShrink={0}>
157
- {props.label}
158
- </text>
159
- <text
160
- fg={context.theme[props.tone ?? 'text']}
161
- wrapMode='none'
162
- flexShrink={1}
163
- >
164
- <b>{value()}</b>
165
- </text>
166
- </box>
167
- )
168
- }
169
-
170
- export function SidebarTextRow(props: {
171
- text: string
172
- tone?: Tone
173
- wrapMode?: JSX.IntrinsicElements['text']['wrapMode']
174
- }) {
175
- const context = frameContext()
176
- return (
177
- <text
178
- fg={context.theme[props.tone ?? 'textMuted']}
179
- wrapMode={props.wrapMode}
180
- >
181
- {props.text}
182
- </text>
183
- )
184
- }
185
-
186
- function usageTone(used: number, appearance: SidebarAppearance): Tone {
187
- if (used >= appearance.errorThreshold) return 'error'
188
- if (used >= appearance.warnThreshold) return 'warning'
189
- return 'success'
190
- }
191
-
192
- function barSegments(
193
- used: number,
194
- appearance: SidebarAppearance,
195
- pace?: PaceView,
196
- ) {
197
- const width = appearance.barWidth
198
- const cells = (pct: number) =>
199
- Math.max(0, Math.min(Math.round((pct / 100) * width), width))
200
- const usedCells = cells(used)
201
- const tone = usageTone(used, appearance)
202
- // Keep the overlay's slot even when empty so live pacing changes reuse nodes.
203
- const plain = [
204
- { text: appearance.barFilledChar.repeat(usedCells), tone },
205
- { text: '', tone },
206
- { text: appearance.barEmptyChar.repeat(width - usedCells), tone },
207
- ]
208
- const overlay = pace?.overlay
209
- if (!overlay) return plain
210
- const paceCells = cells(overlay.percent)
211
- const lo = Math.min(usedCells, paceCells)
212
- const hi = Math.max(usedCells, paceCells)
213
- if (lo === hi) return plain
214
- return [
215
- { text: appearance.barFilledChar.repeat(lo), tone },
216
- {
217
- text: (overlay.kind === 'deficit' ? '\u2593' : '\u2592').repeat(hi - lo),
218
- tone:
219
- overlay.kind === 'deficit' ? ('error' as const) : ('success' as const),
220
- },
221
- { text: appearance.barEmptyChar.repeat(width - hi), tone },
222
- ]
223
- }
224
-
225
- function QuotaRow(props: {
226
- part: QuotaWindowPart
227
- pace?: PaceView
228
- labelWidth: number
229
- barCells: number
230
- resetWidth: number
231
- showReset: boolean
232
- }) {
233
- const context = frameContext()
234
- const [columns, setColumns] = createSignal(0)
235
- let row: { width: number } | undefined
236
- const label = () =>
237
- props.part.name +
238
- ' '.repeat(Math.max(0, props.labelWidth - displayWidth(props.part.name)))
239
- const figure = () =>
240
- ` ${props.part.kind === 'budget' && props.part.figure.startsWith(`${props.part.name} `) ? props.part.figure.slice(props.part.name.length + 1) : props.part.figure}`
241
- const hasReading = () => props.part.reading === 'known'
242
- const used = () => 100 - (props.part.remainingPercent ?? 100)
243
- // Size notifications can recompute an unchanged fit after text has been flushed
244
- // for the frame. Keep equal segments, and update fixed slots in place when the
245
- // bar changes, rather than replacing text nodes during layout.
246
- const segments = createMemo(
247
- () =>
248
- hasReading()
249
- ? barSegments(
250
- used(),
251
- { ...context.appearance, barWidth: props.barCells },
252
- props.pace,
253
- )
254
- : [],
255
- undefined,
256
- {
257
- equals: (previous, next) =>
258
- previous.length === next.length &&
259
- previous.every(
260
- (segment, index) =>
261
- segment.text === next[index]?.text &&
262
- segment.tone === next[index]?.tone,
263
- ),
59
+ export function SidebarFrame(props: SidebarFrameProps) {
60
+ const sources = new WeakMap<FrameAccountView, AccountView>()
61
+ const accounts = mapArray(
62
+ () => props.accounts,
63
+ (account) => {
64
+ // Keep account identity and live getters while the frame reads the caller's clock.
65
+ const adapted = mergeProps(account, {
66
+ get hasQuota() {
67
+ return quotaWindowParts(account.quota, {
68
+ now: props.now,
69
+ }).windows.some((part) => part.reading === 'known')
70
+ },
71
+ get collapsedQuotaText() {
72
+ return formatQuota(account.quota, { now: props.now, form: 'narrow' })
73
+ },
74
+ get quotaAge() {
75
+ return quotaWindowParts(account.quota, { now: props.now }).age
76
+ },
77
+ })
78
+ sources.set(adapted, account)
79
+ return adapted
264
80
  },
265
81
  )
266
- const paceLine = () => {
267
- const text = props.pace?.text
268
- if (!text || columns() <= 0) return text
269
- return fitText(text, columns() - props.labelWidth)
270
- }
271
82
  return (
272
- <>
273
- <box
274
- ref={(element: { width: number }) => {
275
- row = element
276
- }}
277
- onSizeChange={() => setColumns(row?.width ?? 0)}
278
- width='100%'
279
- flexDirection='row'
280
- justifyContent='space-between'
281
- >
282
- <box
283
- flexDirection='row'
284
- flexShrink={props.part.resetSinceReading ? 1 : 0}
285
- >
286
- <Show when={props.labelWidth > 0}>
287
- <text fg={context.theme.textMuted} wrapMode='none' flexShrink={0}>
288
- {label()}
289
- </text>
290
- </Show>
291
- <Show
292
- when={hasReading()}
293
- fallback={
294
- <text fg={context.theme.textMuted} wrapMode='none'>
295
- no reading
296
- </text>
297
- }
298
- >
299
- <Show
300
- when={!props.part.resetSinceReading}
301
- fallback={
302
- <text fg={context.theme.textMuted} wrapMode='none'>
303
- reset since last check
304
- </text>
305
- }
306
- >
307
- <Show when={props.barCells > 0}>
308
- {/* Text nodes clear omitted theme colours; empty slots must not reserve a cell. */}
309
- <Index each={segments()}>
310
- {(segment) => (
311
- <text
312
- fg={context.theme[segment().tone]}
313
- wrapMode='none'
314
- width={segment().text ? undefined : 0}
315
- >
316
- {segment().text}
317
- </text>
318
- )}
319
- </Index>
320
- </Show>
321
- <text
322
- fg={context.theme[usageTone(used(), context.appearance)]}
323
- wrapMode='none'
324
- >
325
- {figure()}
326
- </text>
327
- </Show>
328
- </Show>
329
- </box>
330
- <Show
331
- when={
332
- hasReading() && props.showReset && !props.part.resetSinceReading
333
- }
334
- >
335
- <box
336
- width={props.resetWidth}
337
- flexShrink={0}
338
- flexDirection='row'
339
- justifyContent='flex-end'
340
- >
341
- <Show when={props.part.resetIn}>
342
- <text fg={context.theme.textMuted} wrapMode='none'>
343
- {props.part.resetIn}
344
- </text>
345
- </Show>
346
- </box>
347
- </Show>
348
- </box>
349
- {/* A changed fitted line needs a fresh text node to draw at its new width. */}
350
- <Show
351
- when={hasReading() && !props.part.resetSinceReading && paceLine()}
352
- keyed
353
- >
354
- {(line: string) => (
355
- <box width='100%' flexDirection='row'>
356
- <Show when={props.labelWidth > 0}>
357
- <text fg={context.theme.textMuted}>
358
- {''.padEnd(props.labelWidth)}
359
- </text>
360
- </Show>
361
- <text
362
- fg={context.theme[props.pace?.tone ?? 'textMuted']}
363
- wrapMode='none'
364
- >
365
- {line}
366
- </text>
367
- </box>
368
- )}
369
- </Show>
370
- </>
371
- )
372
- }
373
-
374
- function CollapsedAccountRow(props: { account: AccountView }) {
375
- const context = frameContext()
376
- const [width, setWidth] = createSignal(0)
377
- let row: { width: number } | undefined
378
- const hasQuota = () =>
379
- quotaWindowParts(props.account.quota, { now: context.now }).windows.some(
380
- (part) => part.reading === 'known',
381
- )
382
- const text = () =>
383
- hasQuota()
384
- ? formatQuota(props.account.quota, { now: context.now, form: 'narrow' })
385
- : (props.account.emptyQuotaText?.collapsed ?? '\u2014')
386
- // Reserve an ellipsis, a separator and the trailing indicator before keeping quota.
387
- const showQuota = () => width() <= 0 || displayWidth(text()) + 4 <= width()
388
- const label = () => {
389
- if (width() <= 0) return props.account.label
390
- return fitText(
391
- props.account.label,
392
- width() - (showQuota() ? displayWidth(text()) + 3 : 2),
393
- )
394
- }
395
- const muted = () => props.account.collapsed?.muted ?? false
396
- const quotaTone = () =>
397
- muted() ? 'textMuted' : (props.account.collapsed?.quotaTone ?? 'success')
398
- return (
399
- <box
400
- ref={(element: { width: number }) => {
401
- row = element
83
+ <Frame
84
+ {...props}
85
+ accounts={accounts()}
86
+ beforeQuota={(account) => {
87
+ const source = sources.get(account)
88
+ return source && props.beforeQuota?.(source)
402
89
  }}
403
- onSizeChange={() => setWidth(row?.width ?? 0)}
404
- width='100%'
405
- flexDirection='row'
406
- justifyContent='space-between'
407
- columnGap={label() ? 1 : 0}
408
- >
409
- <Show when={label()}>
410
- <text
411
- fg={context.theme[muted() ? 'textMuted' : 'text']}
412
- wrapMode='none'
413
- flexShrink={1}
414
- >
415
- {label()}
416
- </text>
417
- </Show>
418
- <box flexDirection='row' flexShrink={0}>
419
- <Show when={showQuota()}>
420
- <Show
421
- when={hasQuota() && !muted()}
422
- fallback={<text fg={context.theme.textMuted}>{text()}</text>}
423
- >
424
- <text fg={context.theme[quotaTone()]}>
425
- <b>{text()}</b>
426
- </text>
427
- </Show>
428
- </Show>
429
- <text fg={context.theme[props.account.indicatorTone]}>
430
- {showQuota() ? ' ' : ''}
431
- {props.account.blocked ? '\u2298' : '\u25cf'}
432
- </text>
433
- </box>
434
- </box>
435
- )
436
- }
437
-
438
- function AccountBlock(props: { account: AccountView; marginTop: number }) {
439
- const context = frameContext()
440
- const [columns, setColumns] = createSignal(0)
441
- let block: { width: number } | undefined
442
- const rows = () => props.account.groups.flatMap((group) => group.rows)
443
- const labelWidth = () =>
444
- Math.max(
445
- 0,
446
- ...rows().map(({ part }) =>
447
- part.name ? Math.max(3, displayWidth(part.name) + 1) : 0,
448
- ),
449
- )
450
- const resetWidth = () =>
451
- Math.max(
452
- 0,
453
- ...rows().map(({ part }) =>
454
- part.reading === 'unknown' || part.resetSinceReading
455
- ? 0
456
- : displayWidth(part.resetIn ?? ''),
457
- ),
458
- )
459
- const figureWidth = createMemo(() =>
460
- Math.max(
461
- 10,
462
- ...rows()
463
- .filter(
464
- ({ part }) => part.reading === 'known' && !part.resetSinceReading,
465
- )
466
- .map(({ part }) =>
467
- displayWidth(
468
- ` ${part.kind === 'budget' && part.figure.startsWith(`${part.name} `) ? part.figure.slice(part.name.length + 1) : part.figure}`,
469
- ),
470
- ),
471
- ),
472
- )
473
- const fit = (rowLabelWidth: number) => {
474
- const desired = context.appearance.barWidth
475
- // Four cells still distinguish quarters of a window without sacrificing its reset.
476
- const minimum = Math.min(4, desired)
477
- if (columns() <= 0)
478
- return { barCells: desired, showReset: resetWidth() > 0 }
479
- const room = columns() - rowLabelWidth - figureWidth()
480
- const withReset = room - resetWidth() - 1
481
- const showReset = resetWidth() > 0 && withReset >= minimum
482
- const available = showReset ? withReset : room
483
- return {
484
- barCells: available >= minimum ? Math.min(desired, available) : 0,
485
- showReset,
486
- }
487
- }
488
- const label = () => {
489
- const full = `${props.account.label}${props.account.titleSuffix ? ` · ${props.account.titleSuffix}` : ''}`
490
- return columns() <= 0
491
- ? full
492
- : fitText(full, columns() - displayWidth(props.account.status.text) - 1)
493
- }
494
- const age = () =>
495
- quotaWindowParts(props.account.quota, { now: context.now }).age
496
- const hasRows = () =>
497
- props.account.groups.some((group) => group.rows.length > 0)
498
- return (
499
- <box
500
- ref={(element: { width: number }) => {
501
- block = element
90
+ afterQuota={(account) => {
91
+ const source = sources.get(account)
92
+ return source && props.afterQuota?.(source)
502
93
  }}
503
- onSizeChange={() => setColumns(block?.width ?? 0)}
504
- width='100%'
505
- flexDirection='column'
506
- marginTop={props.marginTop}
507
- >
508
- <box
509
- width='100%'
510
- flexDirection='row'
511
- justifyContent='space-between'
512
- columnGap={1}
513
- >
514
- <text fg={context.theme.text} wrapMode='none' flexShrink={1}>
515
- <b>{label()}</b>
516
- </text>
517
- <text
518
- fg={context.theme[props.account.status.tone]}
519
- wrapMode='none'
520
- flexShrink={0}
521
- >
522
- <b>{props.account.status.text}</b>
523
- </text>
524
- </box>
525
- {context.beforeQuota?.(props.account)}
526
- <Show
527
- when={hasRows()}
528
- fallback={
529
- <SidebarTextRow
530
- text={props.account.emptyQuotaText?.expanded ?? '\u2014'}
531
- wrapMode='none'
532
- />
533
- }
534
- >
535
- <For each={props.account.groups}>
536
- {(group) => (
537
- <>
538
- <Show when={group.title}>
539
- <SidebarTextRow
540
- text={group.title ?? ''}
541
- tone='text'
542
- wrapMode='none'
543
- />
544
- </Show>
545
- <For each={group.rows}>
546
- {(row) => {
547
- const rowLabelWidth = () => (row.part.name ? labelWidth() : 0)
548
- const rowFit = createMemo(() => fit(rowLabelWidth()))
549
- return (
550
- <QuotaRow
551
- part={row.part}
552
- pace={row.pace}
553
- labelWidth={rowLabelWidth()}
554
- barCells={rowFit().barCells}
555
- resetWidth={resetWidth()}
556
- showReset={rowFit().showReset}
557
- />
558
- )
559
- }}
560
- </For>
561
- </>
562
- )}
563
- </For>
564
- </Show>
565
- <Show when={age()}>
566
- {(text: () => string) => (
567
- <SidebarTextRow text={text()} wrapMode='none' />
568
- )}
569
- </Show>
570
- {context.afterQuota?.(props.account)}
571
- </box>
572
- )
573
- }
574
-
575
- /** Borderless, controlled presentation; host registration and provider policy stay in the plugin. */
576
- export function SidebarFrame(props: SidebarFrameProps) {
577
- const hasData = () => props.accounts.length > 0
578
- const headerLabel = () =>
579
- !hasData()
580
- ? props.header.badge
581
- : `${props.collapsed ? '\u25b6' : '\u25bc'} ${props.header.badge}`
582
- // Missing semantic colors inherit normal text; an unset palette uses terminal defaults.
583
- const context = mergeProps(props, {
584
- get theme(): SidebarTheme {
585
- const theme = props.theme
586
- return {
587
- ...theme,
588
- textMuted: theme?.textMuted ?? theme?.text,
589
- accent: theme?.accent ?? theme?.text,
590
- success: theme?.success ?? theme?.text,
591
- warning: theme?.warning ?? theme?.text,
592
- error: theme?.error ?? theme?.text,
593
- }
594
- },
595
- })
596
- // Inverting an incomplete badge palette can put light text on a light background.
597
- const invertBadge = () =>
598
- props.theme?.accent !== undefined && props.theme?.background !== undefined
599
- return (
600
- <FrameContext.Provider value={context}>
601
- <box width='100%' flexDirection='column'>
602
- {/* Blocked accounts retain their own indicators; the header always keeps its version. */}
603
- {/* biome-ignore lint/a11y/noStaticElementInteractions: OpenTUI terminal widgets do not have DOM roles */}
604
- <box
605
- width='100%'
606
- flexDirection='row'
607
- justifyContent='space-between'
608
- alignItems='center'
609
- onMouseDown={() => {
610
- if (hasData()) props.onToggle()
611
- }}
612
- >
613
- <box
614
- paddingLeft={1}
615
- paddingRight={1}
616
- backgroundColor={invertBadge() ? props.theme?.accent : undefined}
617
- >
618
- <text
619
- fg={
620
- invertBadge() ? props.theme?.background : context.theme.accent
621
- }
622
- >
623
- <b>{headerLabel()}</b>
624
- </text>
625
- </box>
626
- <Show when={props.header.version}>
627
- <text fg={context.theme.textMuted}>{props.header.version}</text>
628
- </Show>
629
- </box>
630
- <Show when={props.collapsed && hasData()}>
631
- <For each={props.accounts}>
632
- {(account) => <CollapsedAccountRow account={account} />}
633
- </For>
634
- {props.collapsedSections?.()}
635
- </Show>
636
- <Show when={!props.collapsed || !hasData()}>
637
- <Show when={props.showQuota && hasData()}>
638
- <SidebarSection title='Quota'>
639
- <For each={props.accounts}>
640
- {(account, index) => (
641
- <AccountBlock
642
- account={account}
643
- marginTop={index() === 0 ? 0 : 1}
644
- />
645
- )}
646
- </For>
647
- </SidebarSection>
648
- </Show>
649
- {props.sections?.()}
650
- </Show>
651
- </box>
652
- </FrameContext.Provider>
94
+ />
653
95
  )
654
96
  }