@narumitw/pi-usage 0.59.0 → 0.60.1

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,143 @@
1
+ import { sanitizeDisplayText } from "./core.js";
2
+ import type {
3
+ ResolvedUsageAuth,
4
+ UsageProviderAdapter,
5
+ UsageProviderTarget,
6
+ UsageRequestGuard,
7
+ } from "./types.js";
8
+
9
+ const MAX_TARGETS = 1_000;
10
+ const MAX_TARGET_ID_CHARS = 256;
11
+ const MAX_TARGET_LABEL_CHARS = 120;
12
+ const MAX_TARGET_DESCRIPTION_CHARS = 180;
13
+
14
+ export type UsageTargetResolution =
15
+ | { kind: "selected"; targetId?: string }
16
+ | {
17
+ kind: "selection-required";
18
+ choices: readonly UsageProviderTarget[];
19
+ };
20
+
21
+ export interface UsageTargetSelectOptions {
22
+ options: readonly string[];
23
+ targetIdFor(option: string): string | undefined;
24
+ }
25
+
26
+ export async function resolveUsageTarget(
27
+ adapter: UsageProviderAdapter,
28
+ auth: ResolvedUsageAuth,
29
+ rememberedTargetId: string | undefined,
30
+ signal: AbortSignal,
31
+ timeoutMs: number,
32
+ guard: UsageRequestGuard,
33
+ ): Promise<UsageTargetResolution> {
34
+ if (!adapter.targets) return { kind: "selected" };
35
+ if (rememberedTargetId !== undefined && !isBoundedTargetId(rememberedTargetId)) {
36
+ throw new Error(`The remembered ${adapter.targets.singularLabel} identifier was invalid.`);
37
+ }
38
+ const choices = await listUsageTargets(adapter, auth, signal, timeoutMs, guard);
39
+ if (rememberedTargetId) {
40
+ return choices.some((choice) => choice.id === rememberedTargetId)
41
+ ? { kind: "selected", targetId: rememberedTargetId }
42
+ : { kind: "selection-required", choices };
43
+ }
44
+ if (choices.length === 1) return { kind: "selected", targetId: choices[0]?.id };
45
+ return { kind: "selection-required", choices };
46
+ }
47
+
48
+ export async function listUsageTargets(
49
+ adapter: UsageProviderAdapter,
50
+ auth: ResolvedUsageAuth,
51
+ signal: AbortSignal,
52
+ timeoutMs: number,
53
+ guard: UsageRequestGuard,
54
+ ): Promise<readonly UsageProviderTarget[]> {
55
+ if (!adapter.targets) return [];
56
+ const startedAt = Date.now();
57
+ await guard();
58
+ const listed = await adapter.targets.list(
59
+ auth,
60
+ signal,
61
+ remainingTargetTimeout(timeoutMs, startedAt),
62
+ guard,
63
+ );
64
+ await guard();
65
+ remainingTargetTimeout(timeoutMs, startedAt);
66
+ const choices = normalizeUsageTargets(listed);
67
+ if (choices.length === 0) {
68
+ throw new Error(`${adapter.targets.pluralLabel} discovery returned no choices.`);
69
+ }
70
+ return choices;
71
+ }
72
+
73
+ export function normalizeUsageTargets(
74
+ targets: readonly UsageProviderTarget[],
75
+ ): readonly UsageProviderTarget[] {
76
+ if (!Array.isArray(targets)) throw new Error("Target discovery did not return a choices array.");
77
+ if (targets.length > MAX_TARGETS) {
78
+ throw new Error(`Target discovery exceeded ${MAX_TARGETS} choices.`);
79
+ }
80
+ const seen = new Set<string>();
81
+ return targets.map((target) => {
82
+ if (!target || typeof target !== "object" || Array.isArray(target)) {
83
+ throw new Error("Target discovery returned an invalid choice.");
84
+ }
85
+ const { id, label, description } = target as Partial<UsageProviderTarget>;
86
+ if (!isBoundedTargetId(id)) throw new Error("Target discovery returned an invalid ID.");
87
+ if (seen.has(id)) throw new Error(`Target discovery repeated ${id}.`);
88
+ seen.add(id);
89
+ if (typeof label !== "string") {
90
+ throw new Error("Target discovery returned an invalid display label.");
91
+ }
92
+ if (description !== undefined && typeof description !== "string") {
93
+ throw new Error("Target discovery returned an invalid description.");
94
+ }
95
+ const safeLabel = sanitizeDisplayText(label, MAX_TARGET_LABEL_CHARS);
96
+ if (!safeLabel) throw new Error("Target discovery returned an empty display label.");
97
+ const safeDescription = description
98
+ ? sanitizeDisplayText(description, MAX_TARGET_DESCRIPTION_CHARS)
99
+ : undefined;
100
+ return { id, label: safeLabel, ...(safeDescription ? { description: safeDescription } : {}) };
101
+ });
102
+ }
103
+
104
+ export function createUsageTargetSelectOptions(
105
+ targets: readonly UsageProviderTarget[],
106
+ ): UsageTargetSelectOptions {
107
+ const normalized = normalizeUsageTargets(targets);
108
+ const ids = new Map<string, string>();
109
+ const options = normalized.map((target) => {
110
+ const base = target.description ? `${target.label} — ${target.description}` : target.label;
111
+ let option = base;
112
+ if (ids.has(option)) {
113
+ const safeId = sanitizeDisplayText(target.id, 80) || "target";
114
+ option = `${base} · ${safeId}`;
115
+ let duplicate = 2;
116
+ while (ids.has(option)) {
117
+ option = `${base} · ${safeId} (${duplicate})`;
118
+ duplicate += 1;
119
+ }
120
+ }
121
+ ids.set(option, target.id);
122
+ return option;
123
+ });
124
+ return { options, targetIdFor: (option) => ids.get(option) };
125
+ }
126
+
127
+ function remainingTargetTimeout(timeoutMs: number, startedAt: number): number {
128
+ const remaining = timeoutMs - (Date.now() - startedAt);
129
+ if (remaining <= 0) throw new Error("Timed out while discovering provider targets.");
130
+ return remaining;
131
+ }
132
+
133
+ export function isBoundedTargetId(value: unknown): value is string {
134
+ return (
135
+ typeof value === "string" &&
136
+ value.length > 0 &&
137
+ value.length <= MAX_TARGET_ID_CHARS &&
138
+ ![...value].some((character) => {
139
+ const codePoint = character.codePointAt(0) ?? 0;
140
+ return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);
141
+ })
142
+ );
143
+ }