dsh-provider-proxy 0.6.0 → 0.6.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.
- package/README.md +5 -0
- package/lib/index.js +165 -18
- package/lib/index.js.map +2 -2
- package/package.json +1 -1
package/lib/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/index.ts", "../src/fetch-router.ts", "../src/proxy-table.ts", "../src/config.ts", "../src/proxy-address.ts", "../node_modules/@deepseek-ai/schemastery/lib/index.mjs", "../node_modules/@deepseek-ai/cosmokit/lib/index.js", "../src/host-rules.ts"],
|
|
4
|
-
"sourcesContent": ["/**\r\n * dsh-provider-proxy \u2014 Host half.\r\n *\r\n * Routes the model calls of the providers the user enabled through that\r\n * provider's own forward proxy. Every other provider, and all other DSH\r\n * traffic, keeps using the normal network path.\r\n */\r\n\r\nimport { fetch as undiciFetch } from 'undici'\r\n\r\nimport { acquireFetchRouter } from './fetch-router.js'\r\nimport { buildRouteEntry, closeTable, createProxyTable, type RouteEntry } from './proxy-table.js'\r\nimport {\r\n normalizeDefaultProxy,\r\n type DefaultProxyValue,\r\n type ProviderProxyRouteValue,\r\n} from './config.js'\r\n\r\nexport const name = 'dsh-provider-proxy'\r\nexport const inject = ['llm']\r\n\r\n/**\r\n * Reserved provider id whose route carries `ctx.web.search` traffic.\r\n *\r\n * It lives in the ordinary provider dictionary, so its card, its settings write\r\n * path, its hit counter and its diagnostics are all the normal ones. A real\r\n * provider colliding with this id would simply share the route \u2014 harmless, and\r\n * far less likely than the alternative of a separate top-level field needing a\r\n * special case in every one of those places.\r\n */\r\nexport const WEB_SEARCH_KEY = 'web-search'\r\n\r\n/**\r\n * The Config this fiber receives.\r\n *\r\n * It is NOT `ConfigShape`: under the Loader `providers` is a Volatile REFERENCE,\r\n * not the dictionary, so it has to be read through `.get()`. Declaring the plain\r\n * shape here made the two incompatible and hid every real value.\r\n */\r\ninterface ProxyConfig {\r\n /** The provider dictionary, or the Volatile wrapper around it. */\r\n readonly providers?: unknown\r\n /** The shared default endpoint, or the Volatile wrapper around it. */\r\n readonly defaultProxy?: unknown\r\n /** Whether loopback/private targets stay direct, or the Volatile wrapper. */\r\n readonly localDirect?: unknown\r\n /** The self-check URL, or the Volatile wrapper around it. */\r\n readonly testUrl?: unknown\r\n}\r\n\r\nfunction plainProviders(\r\n config: ProxyConfig | undefined,\r\n): Record<string, Partial<ProviderProxyRouteValue>> {\r\n const raw = config?.providers\r\n if (raw === undefined) return {}\r\n // Under the Loader this is a Volatile reference; read it fresh every time so\r\n // a settings write is visible to the next request without a remount.\r\n const snapshot = (raw as { get?: () => unknown }).get\r\n const value = typeof snapshot === 'function' ? snapshot.call(raw) : raw\r\n return (value ?? {}) as Record<string, Partial<ProviderProxyRouteValue>>\r\n}\r\n\r\n/** Read the shared default endpoint, which is Volatile under the Loader too. */\r\nfunction plainDefaultProxy(config: ProxyConfig | undefined): Partial<DefaultProxyValue> {\r\n const raw = config?.defaultProxy\r\n if (raw === undefined) return {}\r\n const snapshot = (raw as { get?: () => unknown }).get\r\n const value = typeof snapshot === 'function' ? snapshot.call(raw) : raw\r\n return (value ?? {}) as Partial<DefaultProxyValue>\r\n}\r\n\r\n/**\r\n * Read `localDirect`, Volatile like everything else the settings page writes.\r\n *\r\n * Absent or malformed means ON: the default is what keeps a loopback relay from\r\n * being forced through a proxy that cannot reach it.\r\n */\r\nfunction plainLocalDirect(config: ProxyConfig | undefined): boolean {\r\n const raw = config?.localDirect\r\n if (raw === undefined) return true\r\n const snapshot = (raw as { get?: () => unknown }).get\r\n const value = typeof snapshot === 'function' ? snapshot.call(raw) : raw\r\n return value !== false\r\n}\r\n\r\nexport function apply(ctx: any, config?: ProxyConfig): void {\r\n const router = acquireFetchRouter()\r\n let current = new Map<string, RouteEntry>()\r\n let problems = new Map<string, string>()\r\n let closed = false\r\n /** Whether a `web` service exists, i.e. whether the reserved route has anything to carry. */\r\n let webAvailable = false\r\n\r\n // Request counts, keyed by provider id. Held OUTSIDE the proxy table so a\r\n // rebuild (a settings write) never resets them; only a plugin reload does.\r\n // Counted at request initiation \u2014 see fetch-router.ts.\r\n const hits = new Map<string, number>()\r\n /**\r\n * Per-provider liveness. `startedAt` is when the last proxied request BEGAN;\r\n * `at`/`ok`/`code` describe the last request that FINISHED. They are kept apart\r\n * because LLM calls are concurrent: a single `at` shared by both would pair one\r\n * request's start time with another's outcome, and a card could name a failure\r\n * that belongs to a call which in fact succeeded.\r\n */\r\n const lastUse = new Map<string, { startedAt: number; at?: number; ok?: boolean; code?: string }>()\r\n const bump = (provider: string): void => {\r\n hits.set(provider, (hits.get(provider) ?? 0) + 1)\r\n // Only the START moves here. The outcome fields are written once a request\r\n // settles, so an in-flight call cannot overwrite the last COMPLETED result.\r\n lastUse.set(provider, { ...lastUse.get(provider), startedAt: Date.now() })\r\n }\r\n const settle = (provider: string) => (ok: boolean, detail: unknown): void => {\r\n const previous = lastUse.get(provider)\r\n lastUse.set(provider, {\r\n startedAt: previous?.startedAt ?? Date.now(),\r\n // `at` is the FINISH time, written together with the outcome it belongs to.\r\n at: Date.now(),\r\n ok,\r\n code: ok ? String((detail as { status?: unknown } | undefined)?.status ?? '') : failureCodeOf(detail),\r\n })\r\n }\r\n\r\n /** Where the self-check sends its request; overridable so a blocked echo host can be replaced. */\r\n const DEFAULT_TEST_URL = 'https://api.ipify.org?format=json'\r\n /** How many `testUrl` candidates one check may walk. Bounds the outbound cost. */\r\n const MAX_TEST_TARGETS = 5\r\n const TEST_TIMEOUT_MS = 10_000\r\n /** The self-check body carries one provider id; anything larger is refused, not buffered. */\r\n const MAX_REQUEST_BYTES = 8 * 1024\r\n /** One in-flight check per provider, so a repeated click cannot multiply outbound requests. */\r\n const selfChecks = new Map<string, Promise<Record<string, unknown>>>()\r\n /**\r\n * The last COMPLETED check per provider, with its finish time. A click inside\r\n * the cooldown gets the remembered answer back instead of a new outbound\r\n * request: the in-flight dedup above only merges CONCURRENT checks, so without\r\n * this, a slow echo target could be hammered serially by impatient clicks.\r\n * The answer is the truth about a configuration that has not changed \u2014 not a\r\n * stale value \u2014 and it is marked `cached` so a caller can tell.\r\n */\r\n const SELF_CHECK_COOLDOWN_MS = 3_000\r\n const lastChecks = new Map<string, { at: number; result: Record<string, unknown> }>()\r\n\r\n /**\r\n * Read `testUrl`, which is Volatile under the Loader and therefore needs\r\n * `.get()`.\r\n *\r\n * It may name SEVERAL candidates, separated by commas or whitespace: any single\r\n * public echo host can be unreachable on some networks, and a check that fails\r\n * for that reason is a check nobody trusts. The list is capped so a long one\r\n * cannot quietly multiply outbound requests.\r\n */\r\n const plainTestUrls = (): string[] => {\r\n const raw = (config as { testUrl?: unknown } | undefined)?.testUrl\r\n const snapshot = (raw as { get?: () => unknown } | undefined)?.get\r\n const value = typeof snapshot === 'function' ? snapshot.call(raw) : raw\r\n const list =\r\n typeof value === 'string'\r\n ? value\r\n .split(/[,\\s]+/)\r\n .map(entry => entry.trim())\r\n .filter(entry => entry.length > 0)\r\n : []\r\n return list.length > 0 ? list.slice(0, MAX_TEST_TARGETS) : [DEFAULT_TEST_URL]\r\n }\r\n\r\n /** Walk `path` down a value, giving up at the first non-object. */\r\n const walk = (value: unknown, path: readonly unknown[]): unknown => {\r\n let node = value\r\n for (const key of path) {\r\n if (node === null || typeof node !== 'object') return undefined\r\n node = (node as Record<string, unknown>)[key as string]\r\n }\r\n return node\r\n }\r\n\r\n /**\r\n * The endpoint a provider actually calls, when its adapter publishes one.\r\n *\r\n * Read from the adapter's SETTINGS SECTION rather than from `listProviders()`,\r\n * which carries only `{ id, name }`. `listConfigurableProviders()` supplies the\r\n * address \u2014 the settings namespace plus the path to the route's profile \u2014 and\r\n * that is exactly what a configuration surface is meant to consume.\r\n *\r\n * Everything here is optional and defensively read: a composition without the\r\n * settings service, an adapter that registers no section, or a profile that\r\n * stores no address all simply yield `undefined`, and the caller falls back to\r\n * the top-level `testUrl` exactly as before.\r\n */\r\n const upstreamOf = (provider: string): string | undefined => {\r\n let settings: any\r\n try {\r\n settings = typeof ctx?.get === 'function' ? ctx.get('settings') : undefined\r\n } catch {\r\n return undefined\r\n }\r\n if (settings === undefined || typeof settings.get !== 'function') return undefined\r\n let entry: any\r\n try {\r\n const entries: any[] = ctx.llm?.listConfigurableProviders?.() ?? []\r\n entry = entries.find(candidate => candidate?.provider === provider)\r\n } catch {\r\n return undefined\r\n }\r\n if (entry === undefined) return undefined\r\n let profile: unknown\r\n try {\r\n profile = walk(settings.get(entry.settingsNs), entry.settingsPath ?? [])\r\n } catch {\r\n return undefined\r\n }\r\n const baseURL = (profile as { baseURL?: unknown } | undefined)?.baseURL\r\n return typeof baseURL === 'string' && baseURL.trim().length > 0 ? baseURL.trim() : undefined\r\n }\r\n\r\n /**\r\n * The `dsh-provider-proxy: ` prefix on a recorded problem is a Host-log\r\n * convention. Both endpoints that serve the settings page are UI payloads, so\r\n * the prefix is stripped at the boundary; `providerProxyState` and the log\r\n * keep the string exactly as the table recorded it.\r\n */\r\n const bareMessage = (message: string): string => message.replace(/^dsh-provider-proxy:\\s*/, '')\r\n\r\n /**\r\n * Every error reachable from one throw: the value itself, its `cause` chain,\r\n * and any `AggregateError.errors` on the way.\r\n *\r\n * `fetch` wraps a connection failure as `TypeError: fetch failed` and hides\r\n * the real `ECONNREFUSED` in `cause`, so a classifier that only reads the top\r\n * value cannot tell \"the proxy is down\" from \"the target refused\".\r\n */\r\n const causesOf = (error: unknown): unknown[] => {\r\n const out: unknown[] = []\r\n const seen = new Set<unknown>()\r\n const queue: unknown[] = [error]\r\n while (queue.length > 0) {\r\n const node = queue.shift()\r\n if (node === null || typeof node !== 'object' || seen.has(node)) continue\r\n seen.add(node)\r\n out.push(node)\r\n const cause = (node as { cause?: unknown }).cause\r\n if (cause !== undefined && cause !== null) queue.push(cause)\r\n const errors = (node as { errors?: unknown }).errors\r\n if (Array.isArray(errors)) queue.push(...errors)\r\n }\r\n return out\r\n }\r\n\r\n /**\r\n * Classify a self-check failure so the report points at the hop that actually\r\n * failed.\r\n *\r\n * `viaProxy` decides WHICH hop that is: the same connection error means \"the\r\n * proxy is unreachable\" on a proxied probe but \"the target is unreachable\" on a\r\n * direct one. Naming the proxy for a direct probe would send the operator after\r\n * a hop the check never used.\r\n */\r\n const classifyTestError = (\r\n error: unknown,\r\n viaProxy: boolean,\r\n rawTarget: string,\r\n ): { kind: string; error: string } => {\r\n const chain = causesOf(error)\r\n const names = chain\r\n .map(node => (node as { name?: unknown }).name)\r\n .filter((name): name is string => typeof name === 'string')\r\n const codes = chain\r\n .map(node => (node as { code?: unknown }).code)\r\n .filter((code): code is string => typeof code === 'string')\r\n // undici THROWS on a proxy 407 rather than returning the response, and the\r\n // only place the \"407\" appears is a CAUSE's message (\"Proxy Authentication\r\n // Required (407)\") \u2014 the top-level message is the generic \"fetch failed\". So\r\n // the whole chain is searched, not just the value that was thrown.\r\n const messages = chain\r\n .map(node => (node as { message?: unknown }).message)\r\n .filter((text): text is string => typeof text === 'string')\r\n // The thrown message may quote the raw target, including userinfo or a\r\n // query token. Keep the useful classification but never pass that message\r\n // through verbatim.\r\n const message = redactTargetFromText(\r\n error instanceof Error ? error.message : String(error),\r\n rawTarget,\r\n )\r\n if (names.includes('TimeoutError') || names.includes('AbortError')) {\r\n return { kind: 'timeout', error: `\u8D85\u65F6\uFF08${TEST_TIMEOUT_MS / 1000}s\uFF09\uFF1A\u4EE3\u7406\u6216\u76EE\u6807\u65E0\u54CD\u5E94` }\r\n }\r\n const connectivity = ['ECONNREFUSED', 'ENOTFOUND', 'EHOSTUNREACH', 'ENETUNREACH', 'ECONNRESET', 'EAI_AGAIN']\r\n const code = connectivity.find(candidate => codes.includes(candidate))\r\n if (code !== undefined) {\r\n return viaProxy\r\n ? { kind: 'proxy-unreachable', error: `\u4EE3\u7406\u4E0D\u53EF\u8FBE\uFF08${code}\uFF09\uFF1A${message}` }\r\n : { kind: 'target', error: `\u76EE\u6807\u4E0D\u53EF\u8FBE\uFF08${code}\uFF09\uFF1A${message}` }\r\n }\r\n if (names.includes('ProxyAuthentication') || messages.some(text => text.includes('407'))) {\r\n return { kind: 'proxy-auth', error: `\u4EE3\u7406\u8981\u6C42\u8BA4\u8BC1\uFF08HTTP 407\uFF09\uFF1A${message}` }\r\n }\r\n return { kind: 'target', error: `\u8BF7\u6C42\u5931\u8D25\uFF1A${message}` }\r\n }\r\n\r\n /**\r\n * Collapse a target to the origin and pathname for display.\r\n *\r\n * Userinfo, query values and fragments are removed before the value is\r\n * returned to the page. Invalid targets lose a `scheme://userinfo@` prefix and\r\n * everything from the first query/fragment marker, then are bounded in length.\r\n */\r\n const sanitizeTargetForDisplay = (target: string): string => {\r\n const raw = String(target ?? '')\r\n try {\r\n const url = new URL(raw)\r\n return `${url.protocol}//${url.host}${url.pathname}`\r\n } catch {\r\n const withoutUserinfo = raw.replace(\r\n /^([a-z][a-z0-9+.-]*:\\/\\/)[^/@\\s]+@/i,\r\n '$1',\r\n )\r\n const withoutQuery = withoutUserinfo.split(/[?#]/, 1)[0] ?? ''\r\n const bounded = withoutQuery.length > 160 ? `${withoutQuery.slice(0, 160)}\u2026` : withoutQuery\r\n return bounded\r\n }\r\n }\r\n\r\n /** Remove a raw target (and URL secrets) from a Host-generated error. */\r\n const redactTargetFromText = (text: string, rawTarget: string): string => {\r\n let safe = text\r\n if (rawTarget.length > 0) safe = safe.split(rawTarget).join('[\u76EE\u6807\u5DF2\u8131\u654F]')\r\n // The error chain may contain the target in a re-serialized form, so strip\r\n // every URLs credentials and query/fragment tail, not only the exact input.\r\n safe = safe.replace(/\\b([a-z][a-z0-9+.-]*:\\/\\/)[^/@\\s]+@/gi, '$1')\r\n safe = safe.replace(/([?&#])[^\\s\"'<>]*/g, '$1')\r\n return safe.length > 500 ? `${safe.slice(0, 500)}\u2026` : safe\r\n }\r\n\r\n /**\r\n * A short machine code for a transport failure, for a card's \"last failure\".\r\n *\r\n * Walks the same cause chain the self-check classifier does: `fetch` hides the\r\n * real code one or two levels down, so reading only the top value would report\r\n * a useless \"fetch failed\" for every kind of outage.\r\n */\r\n const failureCodeOf = (error: unknown): string => {\r\n const chain = causesOf(error)\r\n const names = chain\r\n .map(node => (node as { name?: unknown }).name)\r\n .filter((name): name is string => typeof name === 'string')\r\n if (names.includes('TimeoutError')) return 'TIMEOUT'\r\n if (names.includes('AbortError')) return 'ABORTED'\r\n for (const node of chain) {\r\n const code = (node as { code?: unknown }).code\r\n if (typeof code === 'string' && code.length > 0) return code\r\n }\r\n return 'ERROR'\r\n }\r\n\r\n /**\r\n * Send one request to ONE target, honoured the way real traffic would be.\r\n *\r\n * The proxy/direct decision comes from the route's OWN `decide`, exactly as a\r\n * live request consults it: a loopback/private target, a `bypassHosts` match,\r\n * or an `onlyHosts` miss goes DIRECT, and only a proxied probe carries the\r\n * dispatcher. This matters most now that the check defaults to the provider's\r\n * real upstream: a local relay upstream (LiteLLM, Ollama) would otherwise be\r\n * forced through a forward proxy that cannot reach it, and the check would\r\n * report a healthy route as \"the proxy is broken\" \u2014 the very false positive\r\n * `localDirect` exists to remove.\r\n *\r\n * When it IS proxied, the dispatcher is passed EXPLICITLY rather than by\r\n * entering the router's AsyncLocalStorage scope: that scope intercepts\r\n * `globalThis.fetch`, so a plain `undici.fetch` call would go straight out and\r\n * report a broken proxy as a success \u2014 the one failure this whole feature\r\n * exists to eliminate.\r\n */\r\n const probeTarget = async (\r\n target: string,\r\n route: RouteEntry,\r\n ): Promise<Record<string, unknown>> => {\r\n const displayTarget = sanitizeTargetForDisplay(target)\r\n let host: string | undefined\r\n try {\r\n host = new URL(target).hostname\r\n } catch {\r\n return {\r\n ok: false,\r\n kind: 'target',\r\n target: displayTarget,\r\n error: `\u81EA\u68C0\u76EE\u6807\u4E0D\u662F\u5408\u6CD5 URL\uFF1A${displayTarget}`,\r\n }\r\n }\r\n const viaProxy = route.decide(host) === 'proxy'\r\n const started = performance.now()\r\n try {\r\n // WHATWG URL keeps userinfo out of `origin`, but the request URL still\r\n // carries it. The self-check never needs embedded credentials, so remove\r\n // them from the request too rather than merely hiding them on display.\r\n const requestTarget = ((): string => {\r\n const url = new URL(target)\r\n url.username = ''\r\n url.password = ''\r\n return url.toString()\r\n })()\r\n const response = await undiciFetch(requestTarget, {\r\n // A direct probe must NOT carry the dispatcher, or undici would force it\r\n // through the proxy anyway.\r\n ...(viaProxy ? { dispatcher: route.dispatcher } : {}),\r\n signal: AbortSignal.timeout(TEST_TIMEOUT_MS),\r\n } as never)\r\n const ms = Math.round(performance.now() - started)\r\n const targetField = { target: displayTarget }\r\n // 407 is the proxy demanding credentials: a RESULT, not a throw. Only a\r\n // proxied request can be answered by a proxy this way.\r\n if (viaProxy && response.status === 407) {\r\n return {\r\n ok: false,\r\n ms,\r\n status: 407,\r\n kind: 'proxy-auth',\r\n viaProxy,\r\n ...targetField,\r\n error: `\u4EE3\u7406\u8981\u6C42\u8BA4\u8BC1\uFF08HTTP 407\uFF09\uFF1A${displayTarget}`,\r\n }\r\n }\r\n let exitIp: string | undefined\r\n try {\r\n const body = (await response.json()) as { ip?: unknown } | null\r\n if (typeof body?.ip === 'string' && body.ip.length > 0) exitIp = body.ip\r\n } catch {\r\n // A non-JSON echo still proves the request crossed the proxy.\r\n }\r\n // Any status below 500 means the request DID reach something \u2014 the target\r\n // when it went direct, or the far side of the proxy. Against a real upstream\r\n // a bare GET normally answers 4xx (401/404) \u2014 the expected answer, and\r\n // proof the path works. A 5xx is the opposite: an HTTP proxy that cannot\r\n // reach its upstream answers 502/503/504 ITSELF, so it reads as a broken\r\n // path rather than a refused request.\r\n const reachable = response.status < 500\r\n if (reachable) {\r\n return {\r\n ok: true,\r\n ms,\r\n status: response.status,\r\n viaProxy,\r\n ...targetField,\r\n ...(exitIp === undefined ? {} : { exitIp }),\r\n kind: 'ok',\r\n }\r\n }\r\n return {\r\n ok: false,\r\n ms,\r\n status: response.status,\r\n viaProxy,\r\n ...targetField,\r\n kind: 'target',\r\n // The status travels in its own field; the reason text must not repeat\r\n // it, or the page shows the same code twice in different colours.\r\n error: `\u76EE\u6807\u8FD4\u56DE 5xx\uFF08\u4E0A\u6E38\u6216\u94FE\u8DEF\u5F02\u5E38\uFF09\uFF1A${displayTarget}`,\r\n }\r\n } catch (error) {\r\n return {\r\n ok: false,\r\n ms: Math.round(performance.now() - started),\r\n viaProxy,\r\n ...classifyTestError(error, viaProxy, target),\r\n target: displayTarget,\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Every target this check may try, in order.\r\n *\r\n * A route's own `testTarget` first, then the provider's REAL upstream when its\r\n * adapter publishes one, then the top-level `testUrl` \u2014 which may itself name\r\n * several echo services.\r\n *\r\n * Takes the target as a plain string so the cooldown key can call it too, with\r\n * the raw config's value: the key must be built from the SAME resolution the\r\n * check uses, or the two can disagree about what the next request would try.\r\n */\r\n /**\r\n * The check's targets, and WHERE they came from.\r\n *\r\n * The target is NOT always the top-level `testUrl`: a route's own\r\n * `testTarget` wins, then the provider's REAL upstream, and only a provider\r\n * that publishes none falls back to `testUrl`. Without this the page cannot\r\n * explain why editing `testUrl` changed one card and not another.\r\n *\r\n * The upstream is read ONCE: reading it twice could disagree if the settings\r\n * service moved in between, and the target list and the reported source must\r\n * never contradict each other.\r\n */\r\n const selfCheckTargetsOf = (\r\n provider: string,\r\n testTarget: string | undefined,\r\n ): { targets: string[]; source: 'route' | 'upstream' | 'testUrl' } => {\r\n const own = (testTarget ?? '').trim()\r\n if (own.length > 0) return { targets: [own], source: 'route' }\r\n const upstream = upstreamOf(provider)\r\n if (upstream !== undefined) return { targets: [upstream], source: 'upstream' }\r\n return { targets: plainTestUrls(), source: 'testUrl' }\r\n }\r\n\r\n /**\r\n * A fingerprint of every input that can change one provider's check ANSWER.\r\n *\r\n * The cooldown is a cache, and a cache keyed only by provider would answer a\r\n * question about a configuration the user has since edited. The route's own\r\n * transport fields are used, plus `testTarget`; when the route opts into the\r\n * shared endpoint, that endpoint's fields are what actually carry the request,\r\n * so they are folded in instead.\r\n *\r\n * `onlyHosts`/`bypassHosts`/`localDirect` and the resolved target list are part\r\n * of the answer too, and each one changes it visibly: they decide whether the\r\n * probe is proxied or direct (`viaProxy`), and the target list is where the\r\n * top-level `testUrl` enters when the route names no target of its own. Leaving\r\n * them out meant an edit inside the cooldown handed back the pre-edit verdict\r\n * with `cached: true` and issued no request at all. It is held in memory only\r\n * and never logged.\r\n */\r\n const selfCheckKey = (provider: string): string => {\r\n const raw = plainProviders(config)[provider] ?? {}\r\n const endpoint =\r\n raw.useDefault === true\r\n ? (plainDefaultProxy(config) as Partial<ProviderProxyRouteValue>)\r\n : raw\r\n return JSON.stringify([\r\n provider,\r\n endpoint.protocol ?? 'http',\r\n endpoint.host ?? '',\r\n endpoint.port ?? 0,\r\n endpoint.username ?? '',\r\n endpoint.password ?? '',\r\n raw.testTarget ?? '',\r\n raw.onlyHosts ?? '',\r\n raw.bypassHosts ?? '',\r\n plainLocalDirect(config),\r\n selfCheckTargetsOf(provider, raw.testTarget).targets,\r\n ])\r\n }\r\n\r\n /**\r\n * Run the connection self-check for one provider.\r\n *\r\n * A route the table carries is used directly \u2014 including one the guards\r\n * REJECTED, whose recorded problem is what explains it. A route that is merely\r\n * CONFIGURED gets a dispatcher built for this check alone, through the SAME\r\n * builder routing uses, so a setting can be verified BEFORE it is switched on\r\n * and a bad one is reported with the reason routing would have given.\r\n */\r\n const runSelfCheck = async (provider: string): Promise<Record<string, unknown>> => {\r\n let route = current.get(provider)\r\n let temporary = false\r\n if (route === undefined) {\r\n // Two very different reasons land here. A route the guards REJECTED (a bad\r\n // port, an HTTP password with no username) is missing from the table too,\r\n // and answering \"not enabled\" for it names a cause that is not the case \u2014\r\n // the setting IS on. The problem the table recorded is what explains it.\r\n const problem = problems.get(provider)\r\n if (problem !== undefined) {\r\n return { ok: false, kind: 'route-rejected', error: bareMessage(problem) }\r\n }\r\n const configured = plainProviders(config)[provider]\r\n if (configured === undefined || configured.enabled === true) {\r\n return { ok: false, kind: 'no-route', error: `provider \"${provider}\" \u672A\u542F\u7528\u4EE3\u7406` }\r\n }\r\n const built = buildRouteEntry(provider, configured, {\r\n defaultProxy: normalizeDefaultProxy(plainDefaultProxy(config)),\r\n requireEnabled: false,\r\n localDirect: plainLocalDirect(config),\r\n })\r\n if (!built.ok) {\r\n return { ok: false, kind: 'route-rejected', error: bareMessage(built.problem) }\r\n }\r\n route = built.entry\r\n temporary = true\r\n }\r\n try {\r\n let last: Record<string, unknown> | undefined\r\n const { targets, source } = selfCheckTargetsOf(provider, route.testTarget)\r\n for (const target of targets) {\r\n const outcome = await probeTarget(target, route)\r\n if (outcome.ok === true) return { ...outcome, targetSource: source }\r\n last = outcome\r\n // 407 is about the PROXY, not the target: another candidate would ask the\r\n // same question and get the same answer.\r\n if (outcome.kind === 'proxy-auth') break\r\n }\r\n return last === undefined\r\n ? { ok: false, kind: 'target', target: '', targetSource: source, error: '\u6CA1\u6709\u53EF\u7528\u7684\u81EA\u68C0\u76EE\u6807' }\r\n : { ...last, targetSource: source }\r\n } finally {\r\n // A dispatcher built for one check must not outlive it: the table owns the\r\n // long-lived ones, and this one was never in the table to begin with.\r\n if (temporary) await route.dispatcher.close().catch(() => undefined)\r\n }\r\n }\r\n\r\n // One line on activation so a user can tell \"mounted\" from \"not mounted\" in\r\n // the Host log without guessing. Never prints a credential.\r\n try {\r\n ctx.logger.info('dsh-provider-proxy mounted (pid %d)', process.pid)\r\n } catch {\r\n // A context without a logger still works; the diagnostics getter remains.\r\n }\r\n\r\n const rebuild = async (): Promise<void> => {\r\n const next = createProxyTable(plainProviders(config), {\r\n defaultProxy: plainDefaultProxy(config),\r\n localDirect: plainLocalDirect(config),\r\n })\r\n const previous = current\r\n current = next.entries\r\n problems = next.problems\r\n // Retire the previous table only after the new one is live, so an in-flight\r\n // stream keeps a dispatcher that still works.\r\n void closeTable(previous)\r\n }\r\n\r\n const ready = rebuild()\r\n\r\n /**\r\n * The provider catalogue, read from `ctx.llm` where it is actually available.\r\n *\r\n * The browser has no LLM service in this release, so the page cannot ask for\r\n * this list itself. Serving it from the Host is the supported path: the\r\n * `webServer` service is confirmed live, and the shipped dsh-llm-retry-settings\r\n * registers its routes the same way.\r\n */\r\n const catalog = (): { providers: { id: string; name: string; live: boolean }[] } => {\r\n const live = new Set<string>()\r\n const out: { id: string; name: string; live: boolean }[] = []\r\n const seen = new Set<string>()\r\n try {\r\n for (const entry of ctx.llm?.listProviders?.() ?? []) {\r\n const id = entry?.id\r\n if (typeof id !== 'string' || id.length === 0) continue\r\n live.add(id)\r\n if (seen.has(id)) continue\r\n seen.add(id)\r\n const name = typeof entry?.name === 'string' && entry.name.length > 0 ? entry.name : id\r\n out.push({ id, name, live: true })\r\n }\r\n } catch {\r\n // no llm service in this composition\r\n }\r\n try {\r\n for (const entry of ctx.llm?.listConfigurableProviders?.() ?? []) {\r\n const id = entry?.provider\r\n if (typeof id !== 'string' || id.length === 0) continue\r\n const name =\r\n typeof entry.displayName === 'string' && entry.displayName.length > 0 ? entry.displayName : id\r\n const existing = out.find(row => row.id === id)\r\n if (existing === undefined) out.push({ id, name, live: live.has(id) })\r\n else existing.name = name\r\n }\r\n } catch {\r\n // ignore\r\n }\r\n // The reserved route rides in the provider dictionary, so its card and its\r\n // settings write path are the ordinary ones; publishing a row is what lets\r\n // the page render it without a special case. It appears only when the web\r\n // service actually exists \u2014 otherwise there is nothing for it to route.\r\n if (webAvailable && out.every(row => row.id !== WEB_SEARCH_KEY)) {\r\n out.push({ id: WEB_SEARCH_KEY, name: 'Web \u641C\u7D22', live: true })\r\n }\r\n out.sort((a, b) => a.name.localeCompare(b.name))\r\n return { providers: out }\r\n }\r\n\r\n // The page reads this same-origin JSON endpoint for the provider list. Mounted\r\n // inside an optional child so a composition without a web server still runs.\r\n ctx.inject?.(['webServer'], (wctx: any) => {\r\n try {\r\n wctx?.webServer?.register?.({\r\n kind: 'exact',\r\n path: '/dsh-provider-proxy/providers',\r\n handler: (_req: unknown, res: any) => {\r\n try {\r\n const text = JSON.stringify({\r\n ...catalog(),\r\n problems: Object.fromEntries(\r\n [...problems].map(([id, message]) => [id, bareMessage(message)]),\r\n ),\r\n hits: Object.fromEntries(hits),\r\n lastUse: Object.fromEntries(lastUse),\r\n })\r\n res.writeHead(200, {\r\n 'content-type': 'application/json; charset=utf-8',\r\n 'cache-control': 'no-store',\r\n 'content-length': Buffer.byteLength(text),\r\n })\r\n res.end(text)\r\n } catch (error) {\r\n res.writeHead(500, { 'content-type': 'application/json' })\r\n res.end(JSON.stringify({ providers: [], error: String(error) }))\r\n }\r\n },\r\n })\r\n\r\n // Connection self-check: one request through the provider's own dispatcher.\r\n // POST-only, the provider must be in the LIVE table, and at most one check\r\n // per provider is in flight \u2014 so this cannot become an outbound amplifier.\r\n wctx?.webServer?.register?.({\r\n kind: 'exact',\r\n path: '/dsh-provider-proxy/test',\r\n handler: (req: any, res: any) => {\r\n // One response per request, whatever arrives later: an aborted\r\n // connection can fire 'error', and a body that was already refused can\r\n // still be followed by 'end'.\r\n let replied = false\r\n const send = (status: number, payload: unknown): void => {\r\n if (replied) return\r\n replied = true\r\n const text = JSON.stringify(payload)\r\n res.writeHead(status, {\r\n 'content-type': 'application/json; charset=utf-8',\r\n 'cache-control': 'no-store',\r\n 'content-length': Buffer.byteLength(text),\r\n })\r\n res.end(text)\r\n }\r\n if (req?.method !== 'POST') {\r\n send(405, { ok: false, kind: 'method', error: '\u81EA\u68C0\u7AEF\u70B9\u53EA\u63A5\u53D7 POST' })\r\n return\r\n }\r\n if (typeof req.on !== 'function') {\r\n send(400, { ok: false, kind: 'body', error: '\u65E0\u6CD5\u8BFB\u53D6\u8BF7\u6C42\u4F53' })\r\n return\r\n }\r\n let bytes = 0\r\n const chunks: Buffer[] = []\r\n req.on('data', (chunk: Buffer) => {\r\n if (replied) return\r\n bytes += chunk.length\r\n // The body is one provider id. Anything larger is not a caller this\r\n // endpoint serves, and buffering it would be a free memory sink on a\r\n // webServer deployments may bind beyond loopback. The rest of the\r\n // stream is discarded rather than read.\r\n if (bytes > MAX_REQUEST_BYTES) {\r\n send(413, {\r\n ok: false,\r\n kind: 'body',\r\n error: `\u8BF7\u6C42\u4F53\u8D85\u8FC7 ${MAX_REQUEST_BYTES} \u5B57\u8282\u4E0A\u9650`,\r\n })\r\n return\r\n }\r\n chunks.push(chunk)\r\n })\r\n req.on('error', () => send(400, { ok: false, kind: 'body', error: '\u8BFB\u53D6\u8BF7\u6C42\u4F53\u5931\u8D25' }))\r\n req.on('end', () => {\r\n if (replied) return\r\n void (async () => {\r\n let provider: unknown\r\n try {\r\n const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')\r\n provider = (parsed as { provider?: unknown })?.provider\r\n } catch {\r\n send(400, { ok: false, kind: 'body', error: '\u8BF7\u6C42\u4F53\u4E0D\u662F\u5408\u6CD5 JSON' })\r\n return\r\n }\r\n if (typeof provider !== 'string' || provider.length === 0) {\r\n send(400, { ok: false, kind: 'body', error: '\u7F3A\u5C11 provider' })\r\n return\r\n }\r\n // Every input the check's ANSWER depends on, so the cooldown below\r\n // cannot hand back a result that belonged to a DIFFERENT\r\n // configuration. Without this, a user who tests, sees a failure,\r\n // fixes the port, and re-tests within the cooldown would be shown\r\n // the pre-fix result and think the fix did nothing.\r\n const key = selfCheckKey(provider)\r\n let pending = selfChecks.get(key)\r\n if (pending === undefined) {\r\n const last = lastChecks.get(key)\r\n if (last !== undefined && Date.now() - last.at < SELF_CHECK_COOLDOWN_MS) {\r\n send(200, { ...last.result, cached: true })\r\n return\r\n }\r\n pending = runSelfCheck(provider).then(result => {\r\n lastChecks.set(key, { at: Date.now(), result })\r\n return result\r\n })\r\n selfChecks.set(key, pending)\r\n void pending.finally(() => {\r\n if (selfChecks.get(key) === pending) selfChecks.delete(key)\r\n })\r\n }\r\n send(200, await pending)\r\n })().catch((error: unknown) => {\r\n send(500, { ok: false, kind: 'internal', error: String(error) })\r\n })\r\n })\r\n },\r\n })\r\n } catch (error) {\r\n // The page degrades to whatever is already configured.\r\n void error\r\n }\r\n })\r\n\r\n // `web_search` reaches the network with a bare global `fetch`, and `ctx.web`\r\n // exposes no waterfall to hook. Wrapping the service METHOD is therefore the\r\n // only seam. Entering the router scope around the call is enough \u2014 the scope\r\n // propagates through `await`, and the search is await-to-completion rather than\r\n // a lazily-consumed stream, so no per-iterator wrapping is needed here.\r\n //\r\n // Two preconditions make this work, and a future provider could break either:\r\n // the tool accesses `ctx.web.search` afresh on every call (no early\r\n // destructure), and the provider's `search()` awaits to completion.\r\n ctx.inject?.(['web'], (wctx: any) => {\r\n const web = wctx?.web\r\n if (web === undefined || typeof web.search !== 'function') return\r\n webAvailable = true\r\n const original = web.search\r\n const patched = function (this: unknown, request: unknown, signal?: unknown): unknown {\r\n const route = current.get(WEB_SEARCH_KEY)\r\n if (route === undefined) return original.call(this, request, signal)\r\n return router.run(\r\n {\r\n dispatcher: route.dispatcher,\r\n onHit: () => bump(WEB_SEARCH_KEY),\r\n onSettle: settle(WEB_SEARCH_KEY),\r\n decide: route.decide,\r\n },\r\n () => original.call(this, request, signal),\r\n )\r\n }\r\n web.search = patched\r\n // Restore on dispose: `ctx.web` is a Cordis traceable proxy, so READING\r\n // `web.search` returns a fresh wrapper every time and `web.search === patched`\r\n // can never be true \u2014 a guard written that way never fires. The own property\r\n // is the only place the installed function is actually observable, and\r\n // deleting it is the real restore: it drops our property and lets the\r\n // prototype method show through, where reassigning would leave an own\r\n // property shadowing the prototype forever.\r\n //\r\n // A plugin that wrapped the method AFTER us installed its own property, so\r\n // this guard deliberately leaves that wrapper in place.\r\n const registerEffect = typeof wctx?.effect === 'function' ? wctx.effect.bind(wctx) : ctx.effect?.bind(ctx)\r\n registerEffect?.(() => () => {\r\n if (Object.getOwnPropertyDescriptor(web, 'search')?.value === patched) delete web.search\r\n })\r\n })\r\n\r\n ctx.effect(() => {\r\n const stop = ctx.on(\r\n 'llm/stream',\r\n (options: { provider?: string }, next: () => AsyncIterable<unknown>) => {\r\n const provider = options?.provider\r\n if (typeof provider !== 'string') return next()\r\n const route = current.get(provider)\r\n if (route === undefined) return next()\r\n // The stream is consumed lazily; wrap it so the scope survives. The hit\r\n // counter rides inside the scope, so an abandoned stream still counts.\r\n return router.wrap(\r\n {\r\n dispatcher: route.dispatcher,\r\n onHit: () => bump(provider),\r\n onSettle: settle(provider),\r\n decide: route.decide,\r\n },\r\n next as () => AsyncIterable<unknown>,\r\n )\r\n },\r\n { global: true },\r\n )\r\n\r\n const onConfig = (): void => {\r\n void rebuild()\r\n }\r\n ctx.on('loader/volatile-update', onConfig, { global: true })\r\n\r\n return async () => {\r\n stop()\r\n if (closed) return\r\n closed = true\r\n await ready.catch(() => undefined)\r\n await closeTable(current)\r\n current = new Map()\r\n router.release()\r\n }\r\n }, 'dsh-provider-proxy: provider-scoped proxy routing')\r\n\r\n // Diagnostics, exported for the Host log and for tests. Never includes a\r\n // password: `proxyOrigin` is the sanitized origin only.\r\n Object.defineProperty(ctx, 'providerProxyState', {\r\n configurable: true,\r\n get: () => ({\r\n routes: [...current.values()].map(entry => ({\r\n provider: entry.provider,\r\n proxyOrigin: entry.proxyOrigin,\r\n })),\r\n problems: Object.fromEntries(problems),\r\n hits: Object.fromEntries(hits),\r\n lastUse: Object.fromEntries(lastUse),\r\n }),\r\n })\r\n}\r\n\r\nexport { acquireFetchRouter } from './fetch-router.js'\r\nexport { buildRouteEntry, createProxyTable, closeTable, proxyUrl } from './proxy-table.js'\r\nexport { Config, ProviderProxyRoute, normalizeRoute, normalizeDefaultProxy, PROTOCOLS } from './config.js'\r\nexport { defaultProxyProblem, proxyHostProblem } from './proxy-address.js'\r\nexport { deadRuleEntries, hostMatches, hostRuleProblem, parseHostList, splitHostRules } from './host-rules.js'\r\n", "/**\r\n * Provider-scoped fetch routing.\r\n *\r\n * DeepSeek Harness 0.2.0-rc.2 offers no supported seam for giving one LLM\r\n * provider its own transport:\r\n *\r\n * - `llm-deepseek` calls the unqualified global `fetch` with no `dispatcher`;\r\n * - `llm-pi-ai` delegates to the pi-ai SDK, whose HTTP layer DSH cannot\r\n * configure (its own source notes a fetch/dispatcher hook does not exist);\r\n * - `LlmCallControls` carries only reasoningEffort/temperature/maxTokens/stop;\r\n * - `llm/stream` intercepts already-decoded `StreamChunk`s, i.e. after HTTP;\r\n * - `ctx.web` serves `web_search`/`web_fetch` only, never provider traffic;\r\n * - the official `@deepseek-ai/dsh-http-proxy` is a library with a private\r\n * installer: one process-wide policy from env vars, no service, no Config.\r\n *\r\n * So the request is routed where the only available signal actually is: the\r\n * `llm/stream` waterfall, whose `options.provider` names the route. An\r\n * AsyncLocalStorage scope carries the chosen dispatcher over the stream, and a\r\n * thin `globalThis.fetch` wrapper applies it. Because every provider gets its\r\n * OWN dispatcher instance, one provider's proxy can never be picked up by\r\n * another provider's call \u2014 including two providers that resolve to the same\r\n * upstream host.\r\n *\r\n * IMPORTANT \u2014 one undici realm only. Node's built-in `fetch` uses an internal\r\n * undici and REJECTS a dispatcher built by the npm `undici` package with\r\n * `invalid onRequestStart method`, and vice versa. Every dispatcher here is\r\n * built from the npm `undici` that this module imports, so the wrapper must\r\n * dispatch through THAT same package's `fetch` rather than re-entering Node's.\r\n * The proxy therefore receives an absolute-form request line\r\n * (`GET http://host/path HTTP/1.1`), which is how an HTTP forward proxy is\r\n * addressed; an `https:` target is tunnelled with CONNECT.\r\n *\r\n * In-flight streams keep the dispatcher they started on; a configuration\r\n * change only affects new requests.\r\n */\r\n\r\nimport { AsyncLocalStorage } from 'node:async_hooks'\r\nimport { fetch as undiciFetch } from 'undici'\r\n\r\n/** Undici dispatcher, kept structurally typed so this file needs no undici types. */\r\nexport interface DispatcherLike {\r\n close(): Promise<void>\r\n}\r\n\r\nexport interface RouterStore {\r\n dispatcher: DispatcherLike\r\n /** Called once per request that actually leaves through the proxy. */\r\n onHit?: () => void\r\n /**\r\n * Called once the request is ANSWERED \u2014 a response arrives, or it fails\r\n * outright.\r\n *\r\n * \"Answered\" is the point at which `fetch` resolves, i.e. response HEADERS,\r\n * NOT the end of the body. `ok` therefore means \"a response below 500 came\r\n * back\", exactly as the connection self-check reads it; it does NOT mean the\r\n * whole stream ran to completion. A body cut off mid-transfer still reads ok,\r\n * and that is deliberate: the body is a lazily-consumed stream a proxy must\r\n * forward without draining, so its end is not observable here. The card's\r\n * \"last ok\" carries that same meaning.\r\n *\r\n * `detail` is the response on success, or the raw error on failure \u2014 left\r\n * unclassified so the caller can name the failure with whatever error\r\n * vocabulary it already has.\r\n */\r\n onSettle?: (ok: boolean, detail: unknown) => void\r\n /**\r\n * Decide whether one request is proxied or sent directly, given its target\r\n * host (`undefined` when the input carries no parsable URL). Absent means\r\n * \"always proxy within this scope\".\r\n */\r\n decide?: (host: string | undefined) => 'proxy' | 'direct'\r\n}\r\n\r\n/** Shared across every plugin instance in one process, keyed so copies cooperate. */\r\nconst STATE_KEY = Symbol.for('dsh-provider-proxy.fetch-router.v1')\r\n\r\ninterface RouterState {\r\n owners: number\r\n storage: AsyncLocalStorage<RouterStore>\r\n originalFetch: typeof globalThis.fetch\r\n routedFetch: typeof globalThis.fetch\r\n descriptor?: PropertyDescriptor\r\n}\r\n\r\n/**\r\n * The host a fetch input targets, or `undefined` when it carries none.\r\n *\r\n * `new URL` THROWS on a relative or malformed input instead of returning\r\n * `undefined`, so every branch is guarded; an unparsable input falls through to\r\n * `undefined`, and the scope's `decide` decides what that means (the plugin's\r\n * route treats it as \"keep proxying\", i.e. fail-closed).\r\n */\r\nfunction requestHost(input: unknown): string | undefined {\r\n try {\r\n if (typeof input === 'string') return new URL(input).hostname\r\n if (input instanceof URL) return input.hostname\r\n const url = (input as { url?: unknown } | null | undefined)?.url\r\n if (typeof url === 'string') return new URL(url).hostname\r\n } catch {\r\n return undefined\r\n }\r\n return undefined\r\n}\r\n\r\nfunction installSharedRouter(): RouterState {\r\n const current = (globalThis as Record<symbol, RouterState | undefined>)[STATE_KEY]\r\n if (current !== undefined) {\r\n current.owners += 1\r\n return current\r\n }\r\n\r\n if (typeof globalThis.fetch !== 'function') {\r\n throw new Error('dsh-provider-proxy: this Node runtime does not expose global fetch')\r\n }\r\n\r\n const storage = new AsyncLocalStorage<RouterStore>()\r\n const originalFetch = globalThis.fetch\r\n const descriptor = Object.getOwnPropertyDescriptor(globalThis, 'fetch')\r\n\r\n const routedFetch = function routedFetch(\r\n this: unknown,\r\n input: Parameters<typeof globalThis.fetch>[0],\r\n init?: Parameters<typeof globalThis.fetch>[1],\r\n ): ReturnType<typeof globalThis.fetch> {\r\n const active = storage.getStore()\r\n // No scope, or a caller that already picked a dispatcher: stay out of the way.\r\n if (active === undefined) return originalFetch.call(globalThis, input, init)\r\n if (init !== undefined && init !== null && (init as { dispatcher?: unknown }).dispatcher !== undefined) {\r\n return originalFetch.call(globalThis, input, init)\r\n }\r\n // A `direct` verdict from the route's target-host rules keeps the native\r\n // path, exactly as if there were no scope at all.\r\n if (active.decide !== undefined && active.decide(requestHost(input)) === 'direct') {\r\n return originalFetch.call(globalThis, input, init)\r\n }\r\n // Counted at INITIATION: the request is about to cross the proxy. A stream\r\n // abandoned later still counts, which is the documented semantics.\r\n active.onHit?.()\r\n // Same undici realm as the dispatcher \u2014 Node's own fetch would reject it.\r\n // The init is passed through structurally: the DOM `RequestInit` and the\r\n // undici one disagree on `body`/`duplex`, so both are erased here.\r\n const inFlight = undiciFetch(input as never, {\r\n ...(init as Record<string, unknown> | undefined),\r\n dispatcher: active.dispatcher as never,\r\n } as never) as unknown as Promise<{ status: number }>\r\n if (active.onSettle !== undefined) {\r\n const settle = active.onSettle\r\n // Observe the reply without changing the caller's promise: the handlers\r\n // hang off a DERIVED promise, both arms are handled here so nothing can\r\n // surface as an unhandled rejection, and the original is returned as-is.\r\n // This fires when `fetch` resolves \u2014 response HEADERS \u2014 not when the body\r\n // ends; see `onSettle`.\r\n void inFlight\r\n .then(\r\n response => settle(response.status < 500, response),\r\n (error: unknown) => settle(false, error),\r\n )\r\n .catch(() => undefined)\r\n }\r\n return inFlight as never\r\n }\r\n\r\n Object.defineProperty(globalThis, 'fetch', {\r\n ...(descriptor ?? { configurable: true, enumerable: true, writable: true }),\r\n value: routedFetch,\r\n })\r\n\r\n const state: RouterState = { owners: 1, storage, originalFetch, routedFetch, descriptor }\r\n Object.defineProperty(globalThis, STATE_KEY, {\r\n configurable: true,\r\n value: state,\r\n })\r\n return state\r\n}\r\n\r\n/**\r\n * Re-apply the AsyncLocalStorage scope to every iterator operation.\r\n *\r\n * This is essential, not cosmetic: an adapter's stream is consumed lazily, so\r\n * the HTTP call typically happens inside a later `next()`, long after\r\n * `als.run(...)` returned. Without wrapping the iterator, every request would\r\n * silently fall back to the default dispatcher.\r\n */\r\nfunction contextualIterable(\r\n storage: AsyncLocalStorage<RouterStore>,\r\n store: RouterStore,\r\n factory: () => AsyncIterable<unknown>,\r\n): AsyncIterable<unknown> {\r\n return {\r\n [Symbol.asyncIterator]() {\r\n let iterator: AsyncIterator<unknown> | undefined\r\n\r\n const ensureIterator = (): AsyncIterator<unknown> => {\r\n if (iterator !== undefined) return iterator\r\n const iterable = factory()\r\n if (iterable === null || typeof iterable?.[Symbol.asyncIterator] !== 'function') {\r\n throw new TypeError('dsh-provider-proxy: llm/stream next() did not return an AsyncIterable')\r\n }\r\n iterator = iterable[Symbol.asyncIterator]()\r\n return iterator\r\n }\r\n\r\n const invoke = (method: 'next' | 'return' | 'throw', value?: unknown): Promise<IteratorResult<unknown>> =>\r\n storage.run(store, () => {\r\n // A stream abandoned before its first next() must not touch the adapter.\r\n if (method === 'return' && iterator === undefined) return Promise.resolve({ done: true, value })\r\n if (method === 'throw' && iterator === undefined) return Promise.reject(value)\r\n const target = ensureIterator()\r\n const operation = target[method]\r\n if (typeof operation !== 'function') {\r\n if (method === 'return') return Promise.resolve({ done: true, value })\r\n return Promise.reject(value)\r\n }\r\n return Promise.resolve(Reflect.apply(operation, target, method === 'next' ? [] : [value]))\r\n })\r\n\r\n return {\r\n next: (value?: unknown) => invoke('next', value),\r\n return: (value?: unknown) => invoke('return', value),\r\n throw: (value?: unknown) => invoke('throw', value),\r\n [Symbol.asyncIterator]() {\r\n return this\r\n },\r\n }\r\n },\r\n }\r\n}\r\n\r\nexport interface FetchRouter {\r\n /** Run one synchronous callback inside the scope. */\r\n run(store: RouterStore, callback: () => unknown): unknown\r\n /** Wrap a lazy stream so every consumption step keeps the scope. */\r\n wrap(store: RouterStore, factory: () => AsyncIterable<unknown>): AsyncIterable<unknown>\r\n /** Release this holder; the shim is removed once the last holder releases. */\r\n release(): void\r\n}\r\n\r\n/** Install (or share) the single process-wide fetch shim. */\r\nexport function acquireFetchRouter(): FetchRouter {\r\n const state = installSharedRouter()\r\n let released = false\r\n\r\n return {\r\n run(store, callback) {\r\n return state.storage.run(store, callback)\r\n },\r\n wrap(store, factory) {\r\n return contextualIterable(state.storage, store, factory)\r\n },\r\n release() {\r\n if (released) return\r\n released = true\r\n state.owners -= 1\r\n if (state.owners !== 0) return\r\n\r\n if (globalThis.fetch === state.routedFetch) {\r\n if (state.descriptor === undefined) delete (globalThis as { fetch?: unknown }).fetch\r\n else Object.defineProperty(globalThis, 'fetch', state.descriptor)\r\n }\r\n delete (globalThis as Record<symbol, unknown>)[STATE_KEY]\r\n state.storage.disable()\r\n },\r\n }\r\n}", "/**\r\n * The proxy table: one dispatcher per enabled provider.\r\n *\r\n * A dispatcher is created per provider rather than shared, so a proxied\r\n * provider can never leak its transport into another provider's call even when\r\n * both resolve to the same upstream host.\r\n *\r\n * Two transports are supported, and they come from the SAME npm undici instance\r\n * (the build leaves `undici` external), which is what lets both be handed to\r\n * `undiciFetch` by the router:\r\n *\r\n * - `http`/`https` \u2192 `ProxyAgent`, which speaks HTTP CONNECT to an HTTP proxy;\r\n * - `socks5` \u2192 `Socks5ProxyAgent`, undici's built-in RFC 1928/1929 client,\r\n * which tunnels the target instead of forwarding to it.\r\n */\r\n\r\nimport { ProxyAgent, Socks5ProxyAgent } from 'undici'\r\n\r\nimport {\r\n normalizeDefaultProxy,\r\n normalizeRoute,\r\n type DefaultProxyValue,\r\n type ProviderProxyRouteValue,\r\n} from './config.js'\r\nimport { hostMatches, parseHostList } from './host-rules.js'\r\nimport { defaultProxyProblem } from './proxy-address.js'\r\nimport type { DispatcherLike } from './fetch-router.js'\r\n\r\nexport interface RouteEntry {\r\n provider: string\r\n /** Normalized proxy origin, for diagnostics only. Never logged with credentials. */\r\n proxyOrigin: string\r\n dispatcher: DispatcherLike\r\n /** Whether one request's target host goes through the proxy or stays direct. */\r\n decide: (host: string | undefined) => 'proxy' | 'direct'\r\n /**\r\n * This route's self-check target: a URL, or '' to use the top-level `testUrl`.\r\n * Only the self-check reads it; a bad value fails a check, never a route.\r\n */\r\n testTarget: string\r\n}\r\n\r\nfunction proxyUrl(route: ProviderProxyRouteValue): string {\r\n // A colon in the username stays percent-encoded (%3A), never rewritten to a\r\n // literal ':'. A WHATWG URL splits userinfo at the FIRST literal colon, so a\r\n // literal one coming from a name like `a:b` would be misread as the password\r\n // separator (`a` + password `b`); keeping it encoded is exactly what lets\r\n // undici's decodeURIComponent restore the real name. Earlier code rewrote %3A\r\n // back to ':' \u2014 that was subtly wrong.\r\n //\r\n // HTTP/HTTPS carry credentials in the userinfo, which undici turns into a\r\n // Proxy-Authorization header. SOCKS5 embeds the USERNAME only: its password is\r\n // handed to Socks5ProxyAgent as an option, so it never enters this string (nor\r\n // the credential-free origin derived from it).\r\n const credentials =\r\n route.username.length === 0\r\n ? ''\r\n : route.password.length > 0 && route.protocol !== 'socks5'\r\n ? `${encodeURIComponent(route.username)}:${encodeURIComponent(route.password)}@`\r\n : `${encodeURIComponent(route.username)}@`\r\n // IPv6 literals need brackets in a URL authority.\r\n const host = route.host.includes(':') && !route.host.startsWith('[') ? `[${route.host}]` : route.host\r\n return `${route.protocol}://${credentials}${host}:${route.port}`\r\n}\r\n\r\n/**\r\n * A credential-free origin, for diagnostics only.\r\n *\r\n * `new URL(url).origin` is NOT usable for socks5: socks5 is a non-special\r\n * scheme, and WHATWG URL serializes the origin of a non-special scheme as the\r\n * string `'null'` (the same rule that made `gopher` return `'null'` in Node\r\n * 15). That value is surfaced verbatim in `ctx.providerProxyState` and in the\r\n * settings page's diagnostics, so it would hide which proxy a SOCKS5 provider\r\n * is using. HTTP keeps using `.origin`, which is what it already did.\r\n *\r\n * Credentials are never part of this string: it is built from host and port.\r\n */\r\nfunction displayOrigin(route: ProviderProxyRouteValue, url: string): string {\r\n if (route.protocol !== 'socks5') return new URL(url).origin\r\n const host = route.host.includes(':') && !route.host.startsWith('[') ? `[${route.host}]` : route.host\r\n return `${route.protocol}://${host}:${route.port}`\r\n}\r\n\r\n/**\r\n * Build the dispatcher for one route.\r\n *\r\n * SOCKS5 authentication is passed as options rather than through the URL so the\r\n * password never appears in the proxy address. `Socks5ProxyAgent` also accepts\r\n * userinfo in the URL, but `proxyUrl()` already emits the username there for\r\n * the HTTP case, and the explicit option takes precedence \u2014 so the password\r\n * stays out of the string that is logged and reported.\r\n */\r\nfunction createDispatcher(\r\n route: ProviderProxyRouteValue,\r\n url: string,\r\n password: string,\r\n): DispatcherLike {\r\n if (route.protocol === 'socks5') {\r\n const auth: { username?: string; password?: string } = {}\r\n if (route.username.length > 0) auth.username = route.username\r\n if (password.length > 0) auth.password = password\r\n return new Socks5ProxyAgent(url, auth) as unknown as DispatcherLike\r\n }\r\n return new ProxyAgent({ uri: url }) as unknown as DispatcherLike\r\n}\r\n\r\n/**\r\n * Whether a target host is loopback or on a private network.\r\n *\r\n * Such a target is almost always a relay running on the same machine (LiteLLM,\r\n * Ollama, a local mock), which a forward proxy cannot reach at all \u2014 forcing it\r\n * through one fails, and the failure reads as \"the proxy is broken\". Sending it\r\n * direct is the only answer that can work.\r\n *\r\n * Matched by ADDRESS, not by the domain-suffix matcher above: `192.168.1.5` is\r\n * not a suffix of anything, so `hostMatches` cannot express these rules.\r\n */\r\nfunction isLocalHost(host: string): boolean {\r\n // WHATWG URL keeps an IPv6 literal bracketed (`[::1]`), so strip first.\r\n const bare = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host\r\n if (bare === 'localhost' || bare.endsWith('.localhost')) return true\r\n if (bare === '::1') return true\r\n\r\n const octets = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(bare)\r\n if (octets === null) return false\r\n const [a, b, c, d] = octets.slice(1).map(Number)\r\n if (a > 255 || b > 255 || c > 255 || d > 255) return false\r\n if (a === 127) return true // 127.0.0.0/8 \u2014 loopback\r\n if (a === 10) return true // 10.0.0.0/8 \u2014 private\r\n if (a === 192 && b === 168) return true // 192.168.0.0/16 \u2014 private\r\n if (a === 169 && b === 254) return true // 169.254.0.0/16 \u2014 link-local\r\n if (a === 172 && b >= 16 && b <= 31) return true // 172.16.0.0/12 \u2014 private\r\n return false\r\n}\r\n\r\n/**\r\n * Build the proxy/direct decision for one route.\r\n *\r\n * FAIL-CLOSED: an enabled route proxies by default, and only explicit exceptions\r\n * send a request direct \u2014 a loopback/private target (when `localDirect` is on),\r\n * a `bypassHosts` match, and an `onlyHosts` list that does not cover the target.\r\n * A target whose host cannot be parsed (`undefined`) stays on the proxy, so a\r\n * malformed URL cannot quietly leak a credentialed request.\r\n */\r\nfunction buildDecide(\r\n route: ProviderProxyRouteValue,\r\n localDirect: boolean,\r\n): (host: string | undefined) => 'proxy' | 'direct' {\r\n const only = parseHostList(route.onlyHosts)\r\n const bypass = parseHostList(route.bypassHosts)\r\n return host => {\r\n if (host === undefined) return 'proxy'\r\n if (localDirect && isLocalHost(host)) return 'direct'\r\n if (hostMatches(host, bypass)) return 'direct'\r\n if (only.length > 0 && !hostMatches(host, only)) return 'direct'\r\n return 'proxy'\r\n }\r\n}\r\n\r\n/**\r\n * Apply the shared default endpoint to one route that opted into it.\r\n *\r\n * Only the TRANSPORT fields move; `onlyHosts`/`bypassHosts`/`testTarget` stay the\r\n * route's own, because they describe that provider's traffic, not the proxy. The\r\n * merge happens AFTER the endpoint is proven usable, so a route can never be\r\n * silently downgraded to its own (empty) fields while the user believes it is\r\n * using the default.\r\n */\r\nfunction withDefaultProxy(\r\n route: Partial<ProviderProxyRouteValue>,\r\n defaultProxy: DefaultProxyValue,\r\n): Partial<ProviderProxyRouteValue> {\r\n return {\r\n ...route,\r\n protocol: defaultProxy.protocol,\r\n host: defaultProxy.host,\r\n port: defaultProxy.port,\r\n username: defaultProxy.username,\r\n password: defaultProxy.password,\r\n }\r\n}\r\n\r\n/** One built route, or the reason it could not be built. */\r\nexport type RouteBuildResult =\r\n | { ok: true; entry: RouteEntry }\r\n | { ok: false; problem: string }\r\n\r\n/** Everything one route's build needs beyond its own settings. */\r\nexport interface RouteBuildOptions {\r\n /** The shared endpoint, already normalized. */\r\n defaultProxy: DefaultProxyValue\r\n /**\r\n * Forwarded to `normalizeRoute`. The table passes `true` \u2014 it skips a disabled\r\n * route before building it \u2014 while the self-check passes `false` to get exactly\r\n * the validation routing would apply once the route is switched on.\r\n */\r\n requireEnabled: boolean\r\n /** Whether loopback/private targets are sent direct; see {@link buildDecide}. */\r\n localDirect: boolean\r\n}\r\n\r\n/**\r\n * Build one route entry, or explain why it cannot be built.\r\n *\r\n * Shared by the routing table and the connection self-check ON PURPOSE: the\r\n * check must run the exact validations routing runs, or it would report a route\r\n * healthy that the table refuses \u2014 the false positive this whole feature exists\r\n * to eliminate.\r\n */\r\nexport function buildRouteEntry(\r\n provider: string,\r\n raw: Partial<ProviderProxyRouteValue>,\r\n options: RouteBuildOptions,\r\n): RouteBuildResult {\r\n let effective = raw\r\n // A route that opted into the shared endpoint takes the proxy address from it.\r\n // Checked BEFORE the merge so the refusal names the setting the user actually\r\n // has to fix \u2014 the default block \u2014 instead of the card's empty fields.\r\n if (raw?.useDefault === true) {\r\n const why = defaultProxyProblem(options.defaultProxy)\r\n if (why !== undefined) {\r\n return {\r\n ok: false,\r\n problem: `dsh-provider-proxy: provider \"${provider}\" \u542F\u7528\u4E86\u300C\u4F7F\u7528\u9ED8\u8BA4\u4EE3\u7406\u300D\uFF0C\u4F46\u9876\u5C42\u9ED8\u8BA4\u4EE3\u7406\u4E0D\u53EF\u7528\uFF1A${why}`,\r\n }\r\n }\r\n effective = withDefaultProxy(raw, options.defaultProxy)\r\n }\r\n\r\n let route: ProviderProxyRouteValue\r\n try {\r\n route = normalizeRoute(provider, effective, { requireEnabled: options.requireEnabled })\r\n } catch (error) {\r\n return { ok: false, problem: error instanceof Error ? error.message : String(error) }\r\n }\r\n\r\n // A SOCKS5 username without a password must be REFUSED, not downgraded.\r\n //\r\n // undici's Socks5Client only offers USERNAME_PASSWORD when both parts are\r\n // present (`if (options.username && options.password)`); with a username\r\n // alone it quietly advertises NO_AUTH. Against a proxy that requires\r\n // authentication the user would then be told \"Authentication failed\" \u2014 a\r\n // wrong diagnosis pointing at the proxy rather than at the missing setting.\r\n if (route.protocol === 'socks5' && route.username.length > 0 && route.password.length === 0) {\r\n return {\r\n ok: false,\r\n problem: 'dsh-provider-proxy: SOCKS5 \u914D\u7F6E\u4E86\u7528\u6237\u540D\u4F46\u6CA1\u6709\u5BC6\u7801\uFF1B\u8BF7\u8865\u5168\u5BC6\u7801\u6216\u6E05\u7A7A\u7528\u6237\u540D',\r\n }\r\n }\r\n\r\n // The mirror of the rule above, for the same reason: undici only offers\r\n // USERNAME_PASSWORD when BOTH parts are present, so a lone password is worse\r\n // than useless \u2014 the client advertises NO_AUTH. The tunnel would succeed\r\n // against an open proxy and fail against the one the credential was entered\r\n // for, which reads as \"the password is wrong\" when it was never sent.\r\n if (route.protocol === 'socks5' && route.password.length > 0 && route.username.length === 0) {\r\n return {\r\n ok: false,\r\n problem: 'dsh-provider-proxy: SOCKS5 \u914D\u7F6E\u4E86\u5BC6\u7801\u4F46\u6CA1\u6709\u7528\u6237\u540D\uFF1B\u8BF7\u8865\u5168\u7528\u6237\u540D\u6216\u6E05\u7A7A\u5BC6\u7801',\r\n }\r\n }\r\n\r\n // An HTTP/HTTPS password WITHOUT a username is refused outright: basic auth\r\n // cannot send a password alone, and silently dropping it would leave the user\r\n // believing a credential is in use when it is not. This is the symmetric\r\n // counterpart of the SOCKS5 guard above and lives on the same `problems`\r\n // path, so both mistakes are reported the same way.\r\n if (route.protocol !== 'socks5' && route.password.length > 0 && route.username.length === 0) {\r\n return {\r\n ok: false,\r\n problem: 'dsh-provider-proxy: \u914D\u7F6E\u4E86\u4EE3\u7406\u5BC6\u7801\u4F46\u6CA1\u6709\u7528\u6237\u540D\uFF1B\u8BF7\u8865\u5168\u7528\u6237\u540D\u6216\u6E05\u7A7A\u5BC6\u7801',\r\n }\r\n }\r\n\r\n // The mirror for HTTP/HTTPS, where the asymmetry is worth spelling out:\r\n // undici WOULD send `Basic base64(\"alice:\")` \u2014 a username with an EMPTY\r\n // password \u2014 so nothing is dropped and a lenient proxy accepts it. It is\r\n // refused anyway, because a half-filled credential is nearly always a\r\n // half-typed one, and \"both or neither\" is one rule to hold across all three\r\n // transports instead of \"the pairing each transport happens to carry\". The\r\n // cost is real and documented in the README: a proxy whose credential truly\r\n // has an empty password cannot be configured here.\r\n if (route.protocol !== 'socks5' && route.username.length > 0 && route.password.length === 0) {\r\n return {\r\n ok: false,\r\n problem: 'dsh-provider-proxy: \u914D\u7F6E\u4E86\u4EE3\u7406\u7528\u6237\u540D\u4F46\u6CA1\u6709\u5BC6\u7801\uFF1B\u8BF7\u8865\u5168\u5BC6\u7801\u6216\u6E05\u7A7A\u7528\u6237\u540D',\r\n }\r\n }\r\n\r\n const url = proxyUrl(route)\r\n let dispatcher: DispatcherLike\r\n try {\r\n dispatcher = createDispatcher(route, url, route.password)\r\n } catch (error) {\r\n return { ok: false, problem: error instanceof Error ? error.message : String(error) }\r\n }\r\n return {\r\n ok: true,\r\n entry: {\r\n provider,\r\n proxyOrigin: displayOrigin(route, url),\r\n dispatcher,\r\n decide: buildDecide(route, options.localDirect),\r\n testTarget: route.testTarget,\r\n },\r\n }\r\n}\r\n\r\n/** Everything the table build needs beyond the routes themselves. */\r\nexport interface ProxyTableOptions {\r\n /** The shared endpoint a route may opt into with `useDefault`. */\r\n defaultProxy?: Partial<DefaultProxyValue>\r\n /**\r\n * Whether a loopback/private target is sent direct instead of through the\r\n * proxy. Defaults to true; `undefined`/absent means \"on\".\r\n */\r\n localDirect?: boolean\r\n}\r\n\r\n/**\r\n * Build the dispatchers for every enabled, valid route.\r\n *\r\n * Invalid routes are skipped rather than thrown: one mistyped provider must not\r\n * stop the others from proxying. The caller surfaces the reason through\r\n * `problems`, which the Client shows instead of failing the whole table.\r\n *\r\n * Only an ENABLED route is carried \u2014 and, consequently, only an enabled route\r\n * is ever refused: a route nobody has switched on has not asked for anything\r\n * yet, so a half-typed endpoint on it is not a problem to report. The self-check\r\n * is what makes a disabled route buildable on demand.\r\n */\r\nexport function createProxyTable(\r\n config: { readonly [provider: string]: Partial<ProviderProxyRouteValue> } | undefined,\r\n options: ProxyTableOptions = {},\r\n): { entries: Map<string, RouteEntry>; problems: Map<string, string> } {\r\n const entries = new Map<string, RouteEntry>()\r\n const problems = new Map<string, string>()\r\n const buildOptions: RouteBuildOptions = {\r\n defaultProxy: normalizeDefaultProxy(options.defaultProxy),\r\n requireEnabled: true,\r\n localDirect: options.localDirect !== false,\r\n }\r\n\r\n for (const [provider, raw] of Object.entries(config ?? {})) {\r\n if (raw?.enabled !== true) continue\r\n const built = buildRouteEntry(provider, raw, buildOptions)\r\n if (!built.ok) problems.set(provider, built.problem)\r\n else entries.set(provider, built.entry)\r\n }\r\n\r\n return { entries, problems }\r\n}\r\n\r\n/** Close every dispatcher, ignoring individual failures. */\r\nexport async function closeTable(entries: Map<string, RouteEntry>): Promise<void> {\r\n const closing = [...entries.values()].map(entry => entry.dispatcher.close().catch(() => undefined))\r\n await Promise.allSettled(closing)\r\n entries.clear()\r\n}\r\n\r\nexport { proxyUrl }\r\n", "/**\r\n * Plugin Config.\r\n *\r\n * Shape notes, all verified against DeepSeek Harness 0.2.0-rc.2:\r\n *\r\n * - `schemastery` is NOT guaranteed to be resolvable from a profile-hoisted\r\n * install, so the real package is preferred at runtime when `createRequire`\r\n * can see it and a bundled fallback is used otherwise. The reference plugin\r\n * `dsh-llm-retry-settings` does exactly this.\r\n * - Every editable field is `.volatile()` so a settings write is committed\r\n * into the running fiber WITHOUT remounting the plugin; the Host then\r\n * rebuilds its proxy table. Ordinary (non-volatile) fields would restart the\r\n * plugin instead, which is not what a settings page wants.\r\n * - The SOCKS5 proxy password lives directly on the route as `password`, so the\r\n * settings page writes it into cordis.patch.yml in the clear. It is only ever\r\n * handed to `Socks5ProxyAgent` as an option, never embedded in the proxy URL\r\n * that is logged or shown in the diagnostics.\r\n */\r\n\r\nimport { createRequire } from 'node:module'\r\n\r\nimport { proxyHostProblem } from './proxy-address.js'\r\n\r\n// Imported statically so the bundler inlines it, making the package\r\n// self-contained. `loadSchemastery` below still PREFERS the profile's own copy\r\n// when one is reachable, so a DSH-provided instance stays authoritative; this\r\n// bundled copy is only the fallback that lets the plugin load at all.\r\nimport * as BundledSchema from '@deepseek-ai/schemastery'\r\n\r\ntype SchemaLike = {\r\n object: (...args: any[]) => any\r\n string: (...args: any[]) => any\r\n boolean: (...args: any[]) => any\r\n number: (...args: any[]) => any\r\n dict: (...args: any[]) => any\r\n union: (...args: any[]) => any\r\n}\r\n\r\n/**\r\n * Resolve the schemastery module for this fiber.\r\n *\r\n * A profile installation hoists dependencies next to the profile rather than\r\n * under this package, so a bare `import` can fail even when the Host itself\r\n * uses schemastery. `createRequire` resolves against this file's real\r\n * location, which is the best available view of the installation tree.\r\n *\r\n * When that finds nothing \u2014 a plain `npm install` of this package, which pulls\r\n * no schemastery \u2014 the BUNDLED copy is used, so the plugin still loads instead\r\n * of throwing at require time.\r\n */\r\nfunction loadSchemastery(): SchemaLike {\r\n try {\r\n const require = createRequire(import.meta.url)\r\n const candidate = require('@deepseek-ai/schemastery')\r\n const live = (candidate as { default?: SchemaLike })?.default ?? (candidate as SchemaLike)\r\n if (live && typeof live.object === 'function') return live\r\n } catch {\r\n // Fall through to the bundled copy below.\r\n }\r\n // The static import is only a fallback; what it actually exposes is decided at\r\n // runtime, which this structural type deliberately does not pin.\r\n const bundled = (BundledSchema as { default?: unknown }).default ?? BundledSchema\r\n if (typeof (bundled as SchemaLike).object === 'function') return bundled as SchemaLike\r\n throw new Error('dsh-provider-proxy: no usable @deepseek-ai/schemastery in this installation')\r\n}\r\n\r\nconst z = loadSchemastery()\r\n\r\n/** Apply `.volatile()` when the resolved schemastery supports it. */\r\nfunction vol<T>(field: T): T {\r\n const volatile = (field as { volatile?: () => unknown }).volatile\r\n return typeof volatile === 'function' ? (volatile.call(field) as T) : field\r\n}\r\n\r\n/** Forward-compatible passthrough for schemastery extensions used below. */\r\nfunction stepMin<T extends { step?: (n: number) => T; min?: (n: number) => T }>(field: T, step?: number): T {\r\n let out = field\r\n if (step !== undefined && typeof out.step === 'function') out = out.step(step)\r\n return out\r\n}\r\n\r\n/** Supported forward-proxy transports. */\r\nexport const PROTOCOLS = ['http', 'https', 'socks5'] as const\r\nexport type Protocol = (typeof PROTOCOLS)[number]\r\n\r\n/**\r\n * The shared endpoint a route may opt into with `useDefault`.\r\n *\r\n * There is deliberately NO `enabled` flag here: a default is \"configured\" when\r\n * it has a host and an in-range port, and nothing else. A second switch would\r\n * create the state \"default configured but switched off\", from which every route\r\n * that opted in would silently lose its proxy \u2014 a failure mode with no upside,\r\n * because a route opts in individually with `useDefault` and can be switched off\r\n * on its own card.\r\n */\r\nexport const DefaultProxy = z.object({\r\n protocol: z.union(PROTOCOLS).default('http'),\r\n /** Proxy host or IP, without scheme, port, or path. */\r\n host: z.string().default(''),\r\n /** Proxy port. 0 means \"not configured\". */\r\n port: z.number().default(0),\r\n username: z.string().default(''),\r\n password: z.string().default(''),\r\n})\r\n\r\n/**\r\n * One provider's proxy settings. Keyed by provider route id.\r\n *\r\n * `port` is deliberately NOT constrained by schemastery's min/max: an unset\r\n * proxy is `0` (meaning \"no port chosen yet\"), and a bound of 1 here would make\r\n * that default fail to parse. The real range check lives in `normalizeRoute`,\r\n * which runs only when a route is actually enabled, so the error can name the\r\n * provider instead of surfacing a bare schema path.\r\n */\r\nexport const ProviderProxyRoute = z.object({\r\n /** Whether this provider's calls are routed through the proxy below. */\r\n enabled: z.boolean().default(false),\r\n /**\r\n * When true, this route's TRANSPORT fields (protocol/host/port/username/\r\n * password) come from the top-level `defaultProxy` instead of its own, so the\r\n * same endpoint is configured once for every provider that shares it. The\r\n * target-host rules and the self-check target stay the route's own. There is\r\n * no partial inheritance: to use a different endpoint, turn this off and fill\r\n * the fields in.\r\n */\r\n useDefault: z.boolean().default(false),\r\n /** Proxy transport. `socks5` is accepted but only honoured when the socks helper loaded. */\r\n protocol: z.union(PROTOCOLS).default('http'),\r\n /** Proxy host or IP, without scheme, port, or path. */\r\n host: z.string().default(''),\r\n /** Proxy port. 0 means \"not configured\"; enabled routes require 1-65535. */\r\n port: z.number().default(0),\r\n /** Optional proxy username. */\r\n username: z.string().default(''),\r\n /** SOCKS5 proxy password. Only used when `protocol` is `socks5`. */\r\n password: z.string().default(''),\r\n /**\r\n * Comma/space-separated TARGET hosts that must go through the proxy. Empty\r\n * means \"no restriction\" (every target is proxied). Suffix match.\r\n */\r\n onlyHosts: z.string().default(''),\r\n /** Comma/space-separated TARGET hosts that bypass the proxy; takes priority over `onlyHosts`. */\r\n bypassHosts: z.string().default(''),\r\n /**\r\n * Optional self-check target for THIS provider's \u6D4B\u8BD5 button. Empty falls back\r\n * to the top-level `testUrl`. Only the self-check reads it; routing never\r\n * touches it, so a bad value costs a failed check, never a broken route.\r\n */\r\n testTarget: z.string().default(''),\r\n})\r\n\r\nexport const Config = z.object({\r\n /** Per-provider proxy routes, keyed by provider route id (e.g. `sensenova`). */\r\n providers: vol(z.dict(ProviderProxyRoute).default({})),\r\n /**\r\n * Shared endpoint for every route that sets `useDefault`. Volatile for the\r\n * same reason as `providers`: a settings write is committed into the running\r\n * fiber instead of remounting the plugin.\r\n */\r\n defaultProxy: vol(DefaultProxy.default({})),\r\n /**\r\n * Whether a loopback/private-address target is sent DIRECT instead of through\r\n * the proxy. On by default: such a target is normally a relay on this very\r\n * machine (LiteLLM, Ollama, a local mock), which a forward proxy cannot reach\r\n * at all \u2014 forcing it through one fails, and the failure reads as \"the proxy\r\n * is broken\". Turn this off only when the proxy itself is the target.\r\n */\r\n localDirect: vol(z.boolean().default(true)),\r\n /**\r\n * URL the per-provider connection self-check requests THROUGH the proxy.\r\n * Volatile, so a settings write does not remount the plugin; the default is an\r\n * IP echo service, which lets the check report the exit address.\r\n */\r\n testUrl: vol(z.string().default('https://api.ipify.org?format=json')),\r\n})\r\n\r\nexport interface ProviderProxyRouteValue {\r\n enabled: boolean\r\n useDefault: boolean\r\n protocol: Protocol\r\n host: string\r\n port: number\r\n username: string\r\n password: string\r\n onlyHosts: string\r\n bypassHosts: string\r\n testTarget: string\r\n}\r\n\r\n/** The normalized shared endpoint; see {@link DefaultProxy}. */\r\nexport interface DefaultProxyValue {\r\n protocol: Protocol\r\n host: string\r\n port: number\r\n username: string\r\n password: string\r\n}\r\n\r\nexport interface ConfigShape {\r\n providers: { readonly [provider: string]: ProviderProxyRouteValue }\r\n defaultProxy: DefaultProxyValue\r\n localDirect: boolean\r\n testUrl: string\r\n}\r\n\r\n/** Read a schemastery-parsed object's plain value, whichever shape it takes. */\r\nfunction plain<T>(parsed: unknown): T {\r\n const get = (parsed as { get?: () => unknown }).get\r\n return (typeof get === 'function' ? get.call(parsed) : parsed) as T\r\n}\r\n\r\n/**\r\n * Normalize the shared default endpoint. Mirrors {@link normalizeRoute} so both\r\n * the Host and a test can hand `createProxyTable` a raw object.\r\n *\r\n * Format is validated lazily, exactly like a route: a malformed default costs a\r\n * `problems` entry naming each route that opted into it, never a crash.\r\n */\r\nexport function normalizeDefaultProxy(raw: Partial<DefaultProxyValue> | undefined): DefaultProxyValue {\r\n const value = plain<DefaultProxyValue>(DefaultProxy(raw ?? {}))\r\n return {\r\n protocol: value.protocol,\r\n host: value.host.trim(),\r\n port: value.port,\r\n username: value.username.trim(),\r\n password: value.password,\r\n }\r\n}\r\n\r\n/**\r\n * Validate one route and return the normalized value, or throw with a\r\n * field-scoped message. Used by both the Host (before opening a dispatcher)\r\n * and the settings form (before writing), so an invalid value never reaches\r\n * disk or the network.\r\n */\r\nexport function normalizeRoute(\r\n provider: string,\r\n raw: Partial<ProviderProxyRouteValue> | undefined,\r\n options?: { requireEnabled?: boolean },\r\n): ProviderProxyRouteValue {\r\n const value = plain<ProviderProxyRouteValue>(ProviderProxyRoute(raw ?? {}))\r\n\r\n // Host rules are stored normalized (trimmed, lower-cased) so the matcher built\r\n // from them never re-parses on the hot path. WHATWG URL already lower-cases a\r\n // hostname, so both sides of the comparison agree.\r\n const onlyHosts = value.onlyHosts.trim().toLowerCase()\r\n const bypassHosts = value.bypassHosts.trim().toLowerCase()\r\n const testTarget = value.testTarget.trim()\r\n\r\n // A disabled route is normally returned untouched: nothing has been asked of\r\n // it, so a half-typed endpoint must not be reported as a problem. The\r\n // self-check DOES ask \u2014 it builds a dispatcher for a route the user has not\r\n // switched on yet \u2014 so it passes `requireEnabled: false` to get exactly the\r\n // validation routing would apply once the route is on.\r\n if (!value.enabled && options?.requireEnabled !== false) {\r\n return { ...value, port: value.port || 0, onlyHosts, bypassHosts, testTarget }\r\n }\r\n\r\n const host = value.host.trim()\r\n const hostProblem = proxyHostProblem(host)\r\n if (hostProblem !== undefined) {\r\n throw new TypeError(\r\n hostProblem === '\u672A\u586B\u5199\u4EE3\u7406\u5730\u5740'\r\n ? `dsh-provider-proxy: provider \"${provider}\" \u542F\u7528\u4E86\u4EE3\u7406\uFF0C\u4F46\u672A\u586B\u5199\u4EE3\u7406\u5730\u5740`\r\n : `dsh-provider-proxy: provider \"${provider}\" \u7684${hostProblem}`,\r\n )\r\n }\r\n if (!Number.isInteger(value.port) || value.port < 1 || value.port > 65535) {\r\n throw new TypeError(\r\n `dsh-provider-proxy: provider \"${provider}\" \u7684\u4EE3\u7406\u7AEF\u53E3\u65E0\u6548\uFF08\u9700\u4E3A 1-65535 \u7684\u6574\u6570\uFF09`,\r\n )\r\n }\r\n return { ...value, host, username: value.username.trim(), onlyHosts, bypassHosts, testTarget }\r\n}", "/**\n * The proxy-endpoint usability predicate, in ONE place.\n *\n * This lives in its own module \u2014 free of Node and schemastery imports \u2014 so the\n * BROWSER half can import the very same rule the Host applies. It exists because\n * the browser used to keep its own weaker copy that checked only \"host non-empty\n * and port in range\": against `https://1.2.3.4` that copy lit the default block\n * green and enabled the bulk \"use the default\" button, while the Host refused\n * every route that pointed at it (a host carrying a scheme or path is rejected by\n * `normalizeRoute`). One predicate, imported by both halves, cannot disagree\n * with itself.\n */\nexport interface ProxyEndpoint {\n /**\n * Proxy host or IP, without scheme, port, or path.\n *\n * Optional because the browser calls this with whatever the settings document\n * currently holds, which mid-edit is not yet a complete endpoint.\n */\n host?: string\n /** Proxy port. 0 means \"not configured\". */\n port?: number\n /**\n * Credential parts, if the endpoint carries any. A HALF-filled pair is a\n * problem, the same way it is on the route itself \u2014 see below.\n */\n username?: string\n password?: string\n}\n\nconst PROXY_HOST_INVALID = '\u4EE3\u7406\u5730\u5740\u53EA\u80FD\u586B IPv4\u3001IPv6 \u6216\u57DF\u540D'\nconst IPV4 = /^(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)$/\nconst DOMAIN = /^(?=.*[a-z])(?=.{1,253}$)(?!.*\\.\\d+$)[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?)*$/i\nconst IPV6_CHARS = /^[0-9a-f:.]+$/i\n\n/**\n * Accept exactly one of: IPv4, IPv6, or a DNS host name. The field carries the\n * proxy address only; a port, scheme, path, credential, or other URL text belongs\n * in its own field and is rejected here.\n */\nexport function proxyHostProblem(rawHost?: string): string | undefined {\n const host = (rawHost ?? '').trim().replace(/\\.$/, '')\n if (host.length === 0) return '\u672A\u586B\u5199\u4EE3\u7406\u5730\u5740'\n if (IPV4.test(host)) return undefined\n\n // A colon or bracket means the value is claiming to be IPv6. Validate it as\n // an IPv6 literal; never fall back to accepting the text as a host name.\n if (host.includes(':') || host.startsWith('[')) {\n const literal = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host\n if (!IPV6_CHARS.test(literal)) return PROXY_HOST_INVALID\n try {\n new URL(`http://[${literal}]:1`)\n return undefined\n } catch {\n return PROXY_HOST_INVALID\n }\n }\n\n return DOMAIN.test(host) ? undefined : PROXY_HOST_INVALID\n}\n\n/**\n * Why this endpoint cannot carry a request, or `undefined` when it can.\n *\n * The host and port checks mirror `normalizeRoute` exactly, so the browser's\n * verdict and the Host's are the same verdict. The credential pairing check\n * mirrors the guards in `buildRouteEntry`, which is what makes this predicate a\n * truthful preview of whether a route that opts into the default will actually be\n * built: without it, a default carrying `alice` and no password lit the block\n * green and enabled the bulk button, and every card it pointed at was then\n * refused by the credential guard with `entries.size === 0`.\n *\n * Tolerates a partial object (`{}`, `host: undefined`) rather than throwing: the\n * browser calls this with whatever the settings document currently holds, which\n * during a half-typed edit is not yet a complete endpoint.\n */\nexport function defaultProxyProblem(endpoint: ProxyEndpoint): string | undefined {\n const hostProblem = proxyHostProblem(endpoint.host)\n if (hostProblem !== undefined) return hostProblem\n // `?? 0` rather than a throw: an absent port is \"not configured\", which is the\n // same thing 0 already means everywhere else in this plugin.\n const port = endpoint.port ?? 0\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n return '\u4EE3\u7406\u7AEF\u53E3\u65E0\u6548\uFF08\u9700\u4E3A 1-65535 \u7684\u6574\u6570\uFF09'\n }\n // \"Both or neither\", exactly as `buildRouteEntry` enforces per transport. The\n // wording stays transport-neutral here because the default block carries a\n // protocol the user may still change; the route-level guards spell out the\n // protocol-specific reason once it is pinned. The Host trims the username\n // before its guards, so this predicate must trim it too; the password is not\n // trimmed by either side.\n const hasUser = (endpoint.username ?? '').trim().length > 0\n const hasPassword = (endpoint.password ?? '').length > 0\n if (hasUser !== hasPassword) {\n return hasUser\n ? '\u914D\u7F6E\u4E86\u4EE3\u7406\u7528\u6237\u540D\u4F46\u6CA1\u6709\u5BC6\u7801\uFF1B\u8BF7\u8865\u5168\u5BC6\u7801\u6216\u6E05\u7A7A\u7528\u6237\u540D'\n : '\u914D\u7F6E\u4E86\u4EE3\u7406\u5BC6\u7801\u4F46\u6CA1\u6709\u7528\u6237\u540D\uFF1B\u8BF7\u8865\u5168\u7528\u6237\u540D\u6216\u6E05\u7A7A\u5BC6\u7801'\n }\n return undefined\n}\n", "import { Binary, clone, createVolatile, deepEqual, filterKeys, isNullable, isPlainObject, isVolatile, pick, valueMap } from \"@deepseek-ai/cosmokit\";\n//#region lib/types/index.js\nconst kSchema = Symbol.for(\"schemastery\");\nconst kValidationError = Symbol.for(\"ValidationError\");\nglobalThis.__schemastery_index__ ??= 0;\nglobalThis.__schemastery_refs__ = void 0;\nvar ValidationError = class extends TypeError {\n\toptions;\n\tname = \"ValidationError\";\n\tconstructor(message, options) {\n\t\tlet prefix = \"$\";\n\t\tfor (const segment of options.path || []) if (typeof segment === \"string\") prefix += \".\" + segment;\n\t\telse if (typeof segment === \"number\") prefix += \"[\" + segment + \"]\";\n\t\telse if (typeof segment === \"symbol\") prefix += `[Symbol(${segment.toString()})]`;\n\t\tif (prefix.startsWith(\".\")) prefix = prefix.slice(1);\n\t\tsuper((prefix === \"$\" ? \"\" : `${prefix} `) + message);\n\t\tthis.options = options;\n\t}\n\tstatic is(error) {\n\t\treturn !!error?.[kValidationError];\n\t}\n};\nObject.defineProperty(ValidationError.prototype, kValidationError, { value: true });\nconst Schema = function(options) {\n\tconst schema = function(data, options = {}) {\n\t\treturn Schema.resolve(data, schema, options)[0];\n\t};\n\tif (options.refs) {\n\t\tconst refs = valueMap(options.refs, (options) => new Schema(options));\n\t\tconst getRef = (uid) => refs[uid];\n\t\tfor (const key in refs) {\n\t\t\tconst options = refs[key];\n\t\t\toptions.sKey = getRef(options.sKey);\n\t\t\toptions.inner = getRef(options.inner);\n\t\t\toptions.list = options.list && options.list.map(getRef);\n\t\t\toptions.dict = options.dict && valueMap(options.dict, getRef);\n\t\t}\n\t\treturn refs[options.uid];\n\t}\n\tObject.assign(schema, options);\n\tif (typeof schema.callback === \"string\") try {\n\t\tschema.callback = new Function(\"return \" + schema.callback)();\n\t} catch {}\n\tObject.defineProperty(schema, \"uid\", { value: globalThis.__schemastery_index__++ });\n\tObject.setPrototypeOf(schema, Schema.prototype);\n\tschema.meta ||= {};\n\tschema.toString = schema.toString.bind(schema);\n\treturn schema;\n};\nSchema.prototype = Object.create(Function.prototype);\nSchema.prototype[kSchema] = true;\nObject.defineProperty(Schema.prototype, \"~standard\", { get() {\n\treturn {\n\t\tversion: 1,\n\t\tvendor: \"schemastery\",\n\t\tvalidate: (value) => {\n\t\t\ttry {\n\t\t\t\treturn { value: Schema.resolve(value, this, {})[0] };\n\t\t\t} catch (error) {\n\t\t\t\tif (ValidationError.is(error)) return { issues: [{\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tpath: error.options.path\n\t\t\t\t}] };\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t};\n} });\nSchema.ValidationError = ValidationError;\nSchema.prototype.toJSON = function toJSON() {\n\tif (globalThis.__schemastery_refs__) {\n\t\tglobalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));\n\t\treturn this.uid;\n\t}\n\tglobalThis.__schemastery_refs__ = { [this.uid]: { ...this } };\n\tglobalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));\n\tconst result = {\n\t\tuid: this.uid,\n\t\trefs: globalThis.__schemastery_refs__\n\t};\n\tglobalThis.__schemastery_refs__ = void 0;\n\treturn result;\n};\nSchema.prototype.set = function set(key, value) {\n\tthis.dict[key] = value;\n\treturn this;\n};\nSchema.prototype.push = function push(value) {\n\tthis.list.push(value);\n\treturn this;\n};\nfunction mergeDesc(original, messages) {\n\tconst result = typeof original === \"string\" ? { \"\": original } : { ...original };\n\tfor (const locale in messages) {\n\t\tconst value = messages[locale];\n\t\tif (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;\n\t\telse if (typeof value === \"string\") result[locale] = value;\n\t}\n\treturn result;\n}\nfunction getInner(value) {\n\treturn value?.$value ?? value?.$inner;\n}\nfunction extractKeys(data) {\n\treturn filterKeys(data ?? {}, (key) => !key.startsWith(\"$\"));\n}\nSchema.prototype.i18n = function i18n(messages) {\n\tconst schema = Schema(this);\n\tconst desc = mergeDesc(schema.meta.description, messages);\n\tif (Object.keys(desc).length) schema.meta.description = desc;\n\tif (schema.dict) schema.dict = valueMap(schema.dict, (inner, key) => {\n\t\treturn inner.i18n(valueMap(messages, (data) => getInner(data)?.[key] ?? data?.[key]));\n\t});\n\tif (schema.list) schema.list = schema.list.map((inner, index) => {\n\t\treturn inner.i18n(valueMap(messages, (data = {}) => {\n\t\t\tif (Array.isArray(getInner(data))) return getInner(data)[index];\n\t\t\tif (Array.isArray(data)) return data[index];\n\t\t\treturn extractKeys(data);\n\t\t}));\n\t});\n\tif (schema.inner) schema.inner = schema.inner.i18n(valueMap(messages, (data) => {\n\t\tif (getInner(data)) return getInner(data);\n\t\treturn extractKeys(data);\n\t}));\n\tif (schema.sKey) schema.sKey = schema.sKey.i18n(valueMap(messages, (data) => data?.$key));\n\treturn schema;\n};\nSchema.prototype.extra = function extra(key, value) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n};\nfor (const key of [\n\t\"required\",\n\t\"disabled\",\n\t\"collapse\",\n\t\"hidden\",\n\t\"loose\"\n]) Object.assign(Schema.prototype, { [key](value = true) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n} });\nSchema.prototype.deprecated = function deprecated() {\n\tconst schema = Schema(this);\n\tschema.meta.badges ||= [];\n\tschema.meta.badges.push({\n\t\ttext: \"deprecated\",\n\t\ttype: \"danger\"\n\t});\n\treturn schema;\n};\nSchema.prototype.experimental = function experimental() {\n\tconst schema = Schema(this);\n\tschema.meta.badges ||= [];\n\tschema.meta.badges.push({\n\t\ttext: \"experimental\",\n\t\ttype: \"warning\"\n\t});\n\treturn schema;\n};\nSchema.prototype.pattern = function pattern(regexp) {\n\tconst schema = Schema(this);\n\tconst pattern = pick(regexp, [\"source\", \"flags\"]);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\tpattern\n\t};\n\treturn schema;\n};\nSchema.prototype.simplify = function simplify(value) {\n\tif (isVolatile(value)) value = value.get();\n\tif (deepEqual(value, this.meta.default, this.type === \"dict\")) return null;\n\tif (isNullable(value)) return value;\n\tif (this.type === \"object\" || this.type === \"dict\") {\n\t\tconst result = {};\n\t\tfor (const key in value) {\n\t\t\tconst item = (this.type === \"object\" ? this.dict[key] : this.inner)?.simplify(value[key]);\n\t\t\tif (this.type === \"dict\" || !isNullable(item)) result[key] = item;\n\t\t}\n\t\tif (deepEqual(result, this.meta.default, this.type === \"dict\")) return null;\n\t\treturn result;\n\t} else if (this.type === \"array\" || this.type === \"tuple\") {\n\t\tconst result = [];\n\t\tvalue.forEach((value, index) => {\n\t\t\tconst schema = this.type === \"array\" ? this.inner : this.list[index];\n\t\t\tconst item = schema ? schema.simplify(value) : value;\n\t\t\tresult.push(item);\n\t\t});\n\t\treturn result;\n\t} else if (this.type === \"intersect\") {\n\t\tconst result = {};\n\t\tfor (const item of this.list) Object.assign(result, item.simplify(value));\n\t\treturn result;\n\t} else if (this.type === \"union\") for (const schema of this.list) try {\n\t\tSchema.resolve(value, schema, {});\n\t\treturn schema.simplify(value);\n\t} catch {}\n\treturn value;\n};\nSchema.prototype.toString = function toString(inline) {\n\treturn formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;\n};\nSchema.prototype.role = function role(role, extra) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\trole,\n\t\textra\n\t};\n\treturn schema;\n};\nfor (const key of [\n\t\"default\",\n\t\"link\",\n\t\"comment\",\n\t\"description\",\n\t\"max\",\n\t\"min\",\n\t\"step\"\n]) Object.assign(Schema.prototype, { [key](value) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n} });\nSchema.prototype.volatile = function volatile() {\n\tif (this.meta.volatile) throw new TypeError(\"volatile schema is already wrapped\");\n\treturn this.extra(\"volatile\", true);\n};\nconst resolvers = {};\nconst checkedVolatile = Symbol(\"checked-volatile-schema\");\nfunction validateVolatileSchema(schema, path = [], blocked = false, seen = /* @__PURE__ */ new Map()) {\n\tconst states = seen.get(schema) ?? /* @__PURE__ */ new Set();\n\tif (states.has(blocked)) return;\n\tstates.add(blocked);\n\tseen.set(schema, states);\n\tif (schema.meta?.volatile && blocked) throw new ValidationError(\"volatile fields require a fixed object path without an enclosing volatile field\", { path });\n\tconst nested = blocked || !!schema.meta?.volatile;\n\tif (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen);\n\tif (schema.sKey) validateVolatileSchema(schema.sKey, [...path, \"<key>\"], true, seen);\n\tif (schema.inner && (schema.type !== \"lazy\" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, \"*\"], true, seen);\n\tif (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);\n}\nSchema.extend = function extend(type, resolve) {\n\tresolvers[type] = resolve;\n};\nSchema.resolve = function resolve(data, schema, options = {}, strict = false) {\n\tif (!schema) return [data];\n\tif (!options[checkedVolatile]) {\n\t\tvalidateVolatileSchema(schema, options.path);\n\t\toptions = {\n\t\t\t...options,\n\t\t\t[checkedVolatile]: true\n\t\t};\n\t}\n\tif (schema.meta?.volatile) {\n\t\tconst inner = Schema(schema);\n\t\tinner.meta = {\n\t\t\t...schema.meta,\n\t\t\tvolatile: false\n\t\t};\n\t\tconst [value, adapted] = Schema.resolve(data, inner, options, strict);\n\t\ttry {\n\t\t\treturn [createVolatile(value), adapted];\n\t\t} catch (error) {\n\t\t\tthrow new ValidationError(error instanceof Error ? error.message : String(error), options);\n\t\t}\n\t}\n\tif (options.ignore?.(data, schema)) return [data];\n\tif (isNullable(data) && schema.type !== \"lazy\") {\n\t\tif (schema.meta.required) throw new ValidationError(`missing required value`, options);\n\t\tlet current = schema;\n\t\tlet fallback = schema.meta.default;\n\t\twhile (current?.type === \"intersect\" && isNullable(fallback)) {\n\t\t\tcurrent = current.list[0];\n\t\t\tfallback = current?.meta.default;\n\t\t}\n\t\tif (isNullable(fallback)) return [data];\n\t\tdata = clone(fallback);\n\t}\n\tconst callback = resolvers[schema.type];\n\tif (!callback) throw new ValidationError(`unsupported type \"${schema.type}\"`, options);\n\ttry {\n\t\treturn callback(data, schema, options, strict);\n\t} catch (error) {\n\t\tif (!schema.meta.loose) throw error;\n\t\treturn [schema.meta.default];\n\t}\n};\nSchema.from = function from(source) {\n\tif (isNullable(source)) return Schema.any();\n\telse if ([\n\t\t\"string\",\n\t\t\"number\",\n\t\t\"boolean\"\n\t].includes(typeof source)) return Schema.const(source).required();\n\telse if (source[kSchema]) return source;\n\telse if (typeof source === \"function\") switch (source) {\n\t\tcase String: return Schema.string().required();\n\t\tcase Number: return Schema.number().required();\n\t\tcase Boolean: return Schema.boolean().required();\n\t\tcase Function: return Schema.function().required();\n\t\tdefault: return Schema.is(source).required();\n\t}\n\telse throw new TypeError(`cannot infer schema from ${source}`);\n};\nSchema.lazy = function lazy(builder) {\n\tconst toJSON = () => {\n\t\tif (!schema.inner[kSchema]) {\n\t\t\tschema.inner = schema.builder();\n\t\t\tschema.inner.meta = {\n\t\t\t\t...schema.meta,\n\t\t\t\t...schema.inner.meta\n\t\t\t};\n\t\t}\n\t\treturn schema.inner.toJSON();\n\t};\n\tconst schema = new Schema({\n\t\ttype: \"lazy\",\n\t\tbuilder,\n\t\tinner: { toJSON }\n\t});\n\treturn schema;\n};\nSchema.natural = function natural() {\n\treturn Schema.number().step(1).min(0);\n};\nSchema.percent = function percent() {\n\treturn Schema.number().step(.01).min(0).max(1).role(\"slider\");\n};\nSchema.date = function date() {\n\treturn Schema.union([Schema.is(Date), Schema.transform(Schema.string().role(\"datetime\"), (value, options) => {\n\t\tconst date = new Date(value);\n\t\tif (isNaN(+date)) throw new ValidationError(`invalid date \"${value}\"`, options);\n\t\treturn date;\n\t}, true)]);\n};\nSchema.regExp = function regExp(flag = \"\") {\n\treturn Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role(\"regexp\", { flag }), (value, options) => {\n\t\ttry {\n\t\t\treturn new RegExp(value, flag);\n\t\t} catch (e) {\n\t\t\tthrow new ValidationError(e.message, options);\n\t\t}\n\t}, true)]);\n};\nSchema.arrayBuffer = function arrayBuffer(encoding) {\n\treturn Schema.union([\n\t\tSchema.is(ArrayBuffer),\n\t\tSchema.is(SharedArrayBuffer),\n\t\tSchema.transform(Schema.any(), (value, options) => {\n\t\t\tif (Binary.isSource(value)) return Binary.fromSource(value);\n\t\t\tthrow new ValidationError(`expected ArrayBufferSource but got ${value}`, options);\n\t\t}, true),\n\t\t...encoding ? [Schema.transform(Schema.string(), (value, options) => {\n\t\t\ttry {\n\t\t\t\treturn encoding === \"base64\" ? Binary.fromBase64(value) : Binary.fromHex(value);\n\t\t\t} catch (e) {\n\t\t\t\tthrow new ValidationError(e.message, options);\n\t\t\t}\n\t\t}, true)] : []\n\t]);\n};\nSchema.extend(\"lazy\", (data, schema, options, strict) => {\n\tif (!schema.inner[kSchema]) {\n\t\tschema.inner = schema.builder();\n\t\tschema.inner.meta = {\n\t\t\t...schema.meta,\n\t\t\t...schema.inner.meta\n\t\t};\n\t\tvalidateVolatileSchema(schema.inner, options.path, true);\n\t}\n\treturn Schema.resolve(data, schema.inner, options, strict);\n});\nSchema.extend(\"any\", (data) => {\n\treturn [data];\n});\nSchema.extend(\"never\", (data, _, options) => {\n\tthrow new ValidationError(`expected nullable but got ${data}`, options);\n});\nSchema.extend(\"const\", (data, { value }, options) => {\n\tif (deepEqual(data, value)) return [value];\n\tthrow new ValidationError(`expected ${value} but got ${data}`, options);\n});\nfunction checkWithinRange(data, meta, description, options, skipMin = false) {\n\tconst { max = Infinity, min = -Infinity } = meta;\n\tif (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);\n\tif (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);\n}\nSchema.extend(\"string\", (data, { meta }, options) => {\n\tif (typeof data !== \"string\") throw new ValidationError(`expected string but got ${data}`, options);\n\tif (meta.pattern) {\n\t\tconst regexp = new RegExp(meta.pattern.source, meta.pattern.flags);\n\t\tif (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);\n\t}\n\tcheckWithinRange(data.length, meta, \"string length\", options);\n\treturn [data];\n});\nfunction decimalShift(data, digits) {\n\tconst str = data.toString();\n\tif (str.includes(\"e\")) return data * Math.pow(10, digits);\n\tconst index = str.indexOf(\".\");\n\tif (index === -1) return data * Math.pow(10, digits);\n\tconst frac = str.slice(index + 1);\n\tconst integer = str.slice(0, index);\n\tif (frac.length <= digits) return +(integer + frac.padEnd(digits, \"0\"));\n\treturn +(integer + frac.slice(0, digits) + \".\" + frac.slice(digits));\n}\nfunction isMultipleOf(data, min, step) {\n\tstep = Math.abs(step);\n\tif (!/^\\d+\\.\\d+$/.test(step.toString())) return (data - min) % step === 0;\n\tconst index = step.toString().indexOf(\".\");\n\tconst digits = step.toString().slice(index + 1).length;\n\treturn Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;\n}\nSchema.extend(\"number\", (data, { meta }, options) => {\n\tif (typeof data !== \"number\") throw new ValidationError(`expected number but got ${data}`, options);\n\tcheckWithinRange(data, meta, \"number\", options);\n\tconst { step } = meta;\n\tif (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);\n\treturn [data];\n});\nSchema.extend(\"boolean\", (data, _, options) => {\n\tif (typeof data === \"boolean\") return [data];\n\tthrow new ValidationError(`expected boolean but got ${data}`, options);\n});\nSchema.extend(\"bitset\", (data, { bits, meta }, options) => {\n\tlet value = 0, keys = [];\n\tif (typeof data === \"number\") {\n\t\tvalue = data;\n\t\tfor (const key in bits) if (data & bits[key]) keys.push(key);\n\t} else if (Array.isArray(data)) {\n\t\tkeys = data;\n\t\tfor (const key of keys) {\n\t\t\tif (typeof key !== \"string\") throw new ValidationError(`expected string but got ${key}`, options);\n\t\t\tif (key in bits) value |= bits[key];\n\t\t}\n\t} else throw new ValidationError(`expected number or array but got ${data}`, options);\n\tif (value === meta.default) return [value];\n\treturn [value, keys];\n});\nSchema.extend(\"function\", (data, _, options) => {\n\tif (typeof data === \"function\") return [data];\n\tthrow new ValidationError(`expected function but got ${data}`, options);\n});\nSchema.extend(\"is\", (data, { constructor }, options) => {\n\tif (typeof constructor === \"function\") {\n\t\tif (data instanceof constructor) return [data];\n\t\tthrow new ValidationError(`expected ${constructor.name} but got ${data}`, options);\n\t} else {\n\t\tif (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);\n\t\tlet prototype = Object.getPrototypeOf(data);\n\t\twhile (prototype) {\n\t\t\tif (prototype.constructor?.name === constructor) return [data];\n\t\t\tprototype = Object.getPrototypeOf(prototype);\n\t\t}\n\t\tthrow new ValidationError(`expected ${constructor} but got ${data}`, options);\n\t}\n});\nfunction property(data, key, schema, options) {\n\ttry {\n\t\tconst [value, adapted] = Schema.resolve(data[key], schema, {\n\t\t\t...options,\n\t\t\tpath: [...options.path || [], key]\n\t\t});\n\t\tif (adapted !== void 0) data[key] = adapted;\n\t\treturn value;\n\t} catch (e) {\n\t\tif (!options?.autofix) throw e;\n\t\tdelete data[key];\n\t\treturn schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;\n\t}\n}\nSchema.extend(\"array\", (data, { inner, meta }, options) => {\n\tif (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);\n\tcheckWithinRange(data.length, meta, \"array length\", options, !isNullable(inner.meta.default));\n\treturn [data.map((_, index) => property(data, index, inner, options))];\n});\nSchema.extend(\"dict\", (data, { inner, sKey }, options, strict) => {\n\tif (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);\n\tconst result = {};\n\tfor (const key in data) {\n\t\tlet rKey;\n\t\ttry {\n\t\t\trKey = Schema.resolve(key, sKey, options)[0];\n\t\t} catch (error) {\n\t\t\tif (strict) continue;\n\t\t\tthrow error;\n\t\t}\n\t\tresult[rKey] = property(data, key, inner, options);\n\t\tdata[rKey] = data[key];\n\t\tif (key !== rKey) delete data[key];\n\t}\n\treturn [result];\n});\nSchema.extend(\"tuple\", (data, { list }, options, strict) => {\n\tif (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);\n\tconst result = list.map((inner, index) => property(data, index, inner, options));\n\tif (strict) return [result];\n\tresult.push(...data.slice(list.length));\n\treturn [result];\n});\nfunction merge(result, data) {\n\tfor (const key in data) {\n\t\tif (key in result) continue;\n\t\tresult[key] = data[key];\n\t}\n}\nSchema.extend(\"object\", (data, { dict }, options, strict) => {\n\tif (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);\n\tconst result = {};\n\tfor (const key in dict) {\n\t\tconst value = property(data, key, dict[key], options);\n\t\tif (!isNullable(value) || key in data) result[key] = value;\n\t}\n\tif (!strict) merge(result, data);\n\treturn [result];\n});\nSchema.extend(\"union\", (data, { list, toString }, options, strict) => {\n\tconst messages = [];\n\tfor (const inner of list) try {\n\t\treturn Schema.resolve(data, inner, options, strict);\n\t} catch (error) {\n\t\tmessages.push(error);\n\t}\n\tthrow new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n});\nSchema.extend(\"intersect\", (data, { list, toString }, options, strict) => {\n\tif (!list.length) return [data];\n\tlet result;\n\tfor (const inner of list) {\n\t\tconst value = Schema.resolve(data, inner, options, true)[0];\n\t\tif (isNullable(value)) continue;\n\t\tif (isNullable(result)) result = value;\n\t\telse if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n\t\telse if (typeof value === \"object\") merge(result ??= {}, value);\n\t\telse if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n\t}\n\tif (!strict && isPlainObject(data)) merge(result, data);\n\treturn [result];\n});\nSchema.extend(\"transform\", (data, { inner, callback, preserve }, options) => {\n\tconst [result, adapted = data] = Schema.resolve(data, inner, options, true);\n\tif (preserve) return [callback(result)];\n\telse return [callback(result), callback(adapted)];\n});\nconst formatters = {};\nfunction defineMethod(name, keys, format) {\n\tformatters[name] = format;\n\tObject.assign(Schema, { [name](...args) {\n\t\tconst schema = new Schema({ type: name });\n\t\tkeys.forEach((key, index) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase \"sKey\":\n\t\t\t\t\tschema.sKey = args[index] ?? Schema.string();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"inner\":\n\t\t\t\t\tschema.inner = Schema.from(args[index]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"list\":\n\t\t\t\t\tschema.list = args[index].map(Schema.from);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"dict\":\n\t\t\t\t\tschema.dict = valueMap(args[index], Schema.from);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"bits\":\n\t\t\t\t\tschema.bits = {};\n\t\t\t\t\tfor (const key in args[index]) {\n\t\t\t\t\t\tif (typeof args[index][key] !== \"number\") continue;\n\t\t\t\t\t\tschema.bits[key] = args[index][key];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"callback\": {\n\t\t\t\t\tconst callback = schema.callback = args[index];\n\t\t\t\t\tcallback[\"toJSON\"] ||= () => callback.toString();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"constructor\": {\n\t\t\t\t\tconst constructor = schema.constructor = args[index];\n\t\t\t\t\tif (typeof constructor === \"function\") constructor[\"toJSON\"] ||= () => constructor[\"name\"];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault: schema[key] = args[index];\n\t\t\t}\n\t\t});\n\t\tif (name === \"object\" || name === \"dict\") schema.meta.default = {};\n\t\telse if (name === \"array\" || name === \"tuple\") schema.meta.default = [];\n\t\telse if (name === \"bitset\") schema.meta.default = 0;\n\t\treturn schema;\n\t} });\n}\ndefineMethod(\"is\", [\"constructor\"], ({ constructor }) => {\n\tif (typeof constructor === \"function\") return constructor.name;\n\telse return constructor;\n});\ndefineMethod(\"any\", [], () => \"any\");\ndefineMethod(\"never\", [], () => \"never\");\ndefineMethod(\"const\", [\"value\"], ({ value }) => typeof value === \"string\" ? JSON.stringify(value) : value);\ndefineMethod(\"string\", [], () => \"string\");\ndefineMethod(\"number\", [], () => \"number\");\ndefineMethod(\"boolean\", [], () => \"boolean\");\ndefineMethod(\"bitset\", [\"bits\"], () => \"bitset\");\ndefineMethod(\"function\", [], () => \"function\");\ndefineMethod(\"array\", [\"inner\"], ({ inner }) => `${inner.toString(true)}[]`);\ndefineMethod(\"dict\", [\"inner\", \"sKey\"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);\ndefineMethod(\"tuple\", [\"list\"], ({ list }) => `[${list.map((inner) => inner.toString()).join(\", \")}]`);\ndefineMethod(\"object\", [\"dict\"], ({ dict }) => {\n\tif (Object.keys(dict).length === 0) return \"{}\";\n\treturn `{ ${Object.entries(dict).map(([key, inner]) => {\n\t\treturn `${key}${inner.meta.required ? \"\" : \"?\"}: ${inner.toString()}`;\n\t}).join(\", \")} }`;\n});\ndefineMethod(\"union\", [\"list\"], ({ list }, inline) => {\n\tconst result = list.map(({ toString: format }) => format()).join(\" | \");\n\treturn inline ? `(${result})` : result;\n});\ndefineMethod(\"intersect\", [\"list\"], ({ list }) => {\n\treturn `${list.map((inner) => inner.toString(true)).join(\" & \")}`;\n});\ndefineMethod(\"transform\", [\n\t\"inner\",\n\t\"callback\",\n\t\"preserve\"\n], ({ inner }, isInner) => inner.toString(isInner));\n//#endregion\nexport { Schema as default };\n", "//#region lib/types/misc.js\n/** No-op callback returning `undefined` at runtime and `any` at type level. */\nfunction noop() {}\n/** Return true when a value is `null` or `undefined`. */\nfunction isNullable(value) {\n\treturn value === null || value === void 0;\n}\n/** Return true when a value is neither `null` nor `undefined`. */\nfunction isNonNullable(value) {\n\treturn !isNullable(value);\n}\n/** Return true for non-array object values. */\nfunction isPlainObject(data) {\n\treturn data && typeof data === \"object\" && !Array.isArray(data);\n}\n/** Filter object entries and return a new object. */\nfunction filterKeys(object, filter) {\n\treturn Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));\n}\n/** Map object values while preserving the original key set. */\nfunction mapValues(object, transform) {\n\treturn Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));\n}\n/** Pick selected keys from an object, optionally including `undefined` values. */\nfunction pick(source, keys, forced) {\n\tif (!keys) return { ...source };\n\tconst result = {};\n\tfor (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];\n\treturn result;\n}\n/** Omit selected keys from a shallow object copy. */\nfunction omit(source, keys) {\n\tif (!keys) return { ...source };\n\tconst result = { ...source };\n\tfor (const key of keys) Reflect.deleteProperty(result, key);\n\treturn result;\n}\n/** Define a non-enumerable writable property and return the object. */\nfunction defineProperty(object, key, value) {\n\treturn Object.defineProperty(object, key, {\n\t\twritable: true,\n\t\tvalue,\n\t\tenumerable: false\n\t});\n}\n//#endregion\n//#region lib/types/array.js\n/** Return true when every item in `array2` is present in `array1`. */\nfunction contain(array1, array2) {\n\treturn array2.every((item) => array1.includes(item));\n}\n/** Return items that appear in both arrays. */\nfunction intersection(array1, array2) {\n\treturn array1.filter((item) => array2.includes(item));\n}\n/** Return items from `array1` that do not appear in `array2`. */\nfunction difference(array1, array2) {\n\treturn array1.filter((item) => !array2.includes(item));\n}\n/** Return the set-union of two arrays while preserving first occurrence order. */\nfunction union(array1, array2) {\n\treturn Array.from(new Set([...array1, ...array2]));\n}\n/** Remove duplicate values while preserving first occurrence order. */\nfunction deduplicate(array) {\n\treturn [...new Set(array)];\n}\n/** Remove one item from an array and report whether it was found. */\nfunction remove(list, item) {\n\tconst index = list?.indexOf(item);\n\tif (index >= 0) {\n\t\tlist.splice(index, 1);\n\t\treturn true;\n\t} else return false;\n}\n/** Normalize nullish, scalar, or array input to an array. */\nfunction makeArray(source) {\n\treturn Array.isArray(source) ? source : isNullable(source) ? [] : [source];\n}\n//#endregion\n//#region lib/types/volatile.js\n/** Shared config references used by schema validators and plugin runtimes. */\nconst write = Symbol.for(\"cosmokit.volatile.write\");\nfunction snapshot(value, ancestors = /* @__PURE__ */ new Set()) {\n\tif (typeof value === \"function\") throw new TypeError(\"volatile config cannot contain functions\");\n\tif (value === null || typeof value !== \"object\") return value;\n\tif (ancestors.has(value)) throw new TypeError(\"volatile config cannot contain cycles\");\n\tancestors.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));\n\t\tif (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError(\"volatile config objects must be plain objects or arrays\");\n\t\treturn Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));\n\t} finally {\n\t\tancestors.delete(value);\n\t}\n}\n/**\n* Create a detached reference containing an immutable copy of the supplied data.\n* @param value - validated config data; class instances and functions are unsupported.\n* @returns a reference whose value is updated only by its owning runtime.\n*/\nfunction createVolatile(value) {\n\tlet current = snapshot(value);\n\treturn Object.freeze({\n\t\tget: () => current,\n\t\t[write]: (value) => {\n\t\t\tcurrent = value;\n\t\t}\n\t});\n}\n/**\n* Identify references across ESM/CJS copies of the shared library.\n* @param value - a parsed config value.\n* @returns whether the value implements the shared reference protocol.\n*/\nfunction isVolatile(value) {\n\treturn typeof value === \"object\" && value !== null && write in value;\n}\n/**\n* Collect config references without descending into their snapshots or opaque objects.\n* @internal\n* @param value - parsed config; cyclic ordinary fields are visited once per path.\n* @returns references and their object-key paths, including an empty path for a root reference.\n*/\nfunction volatileEntries(value) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tfunction visit(value, path) {\n\t\tif (isVolatile(value)) return [{\n\t\t\tpath,\n\t\t\tref: value\n\t\t}];\n\t\tif (!value || typeof value !== \"object\" || ancestors.has(value)) return [];\n\t\tif (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return [];\n\t\tancestors.add(value);\n\t\ttry {\n\t\t\treturn Object.entries(value).flatMap(([key, child]) => visit(child, [...path, key]));\n\t\t} finally {\n\t\t\tancestors.delete(value);\n\t\t}\n\t}\n\treturn visit(value, []);\n}\n/**\n* Commit an already validated immutable snapshot from another reference.\n* @internal\n* @param target - the owning plugin's stable reference.\n* @param source - a newly parsed candidate reference.\n*/\nfunction updateVolatile(target, source) {\n\ttarget[write](source.get());\n}\n//#endregion\n//#region lib/types/types.js\n/** Test values using `instanceof` with a `toStringTag` fallback. */\nfunction is(type, value) {\n\tif (arguments.length === 1) return (value) => is(type, value);\n\treturn type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;\n}\nfunction isArrayBufferLike(value) {\n\treturn is(\"ArrayBuffer\", value) || is(\"SharedArrayBuffer\", value);\n}\nfunction isArrayBufferSource(value) {\n\treturn isArrayBufferLike(value) || ArrayBuffer.isView(value);\n}\n/** Binary source detection and base64/hex conversion helpers. */\nvar Binary;\n(function(Binary) {\n\tBinary.is = isArrayBufferLike;\n\tBinary.isSource = isArrayBufferSource;\n\tfunction fromSource(source) {\n\t\tif (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);\n\t\telse return source;\n\t}\n\tBinary.fromSource = fromSource;\n\tfunction toBase64(source) {\n\t\tsource = fromSource(source);\n\t\tif (typeof Buffer !== \"undefined\") return Buffer.from(source).toString(\"base64\");\n\t\tlet binary = \"\";\n\t\tconst bytes = new Uint8Array(source);\n\t\tfor (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);\n\t\treturn btoa(binary);\n\t}\n\tBinary.toBase64 = toBase64;\n\tfunction fromBase64(source) {\n\t\tif (typeof Buffer !== \"undefined\") return fromSource(Buffer.from(source, \"base64\"));\n\t\treturn Uint8Array.from(atob(source), (c) => c.charCodeAt(0));\n\t}\n\tBinary.fromBase64 = fromBase64;\n\tfunction toHex(source) {\n\t\tsource = fromSource(source);\n\t\tif (typeof Buffer !== \"undefined\") return Buffer.from(source).toString(\"hex\");\n\t\treturn Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\t}\n\tBinary.toHex = toHex;\n\tfunction fromHex(source) {\n\t\tif (typeof Buffer !== \"undefined\") return fromSource(Buffer.from(source, \"hex\"));\n\t\tconst hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);\n\t\tconst buffer = [];\n\t\tfor (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));\n\t\treturn Uint8Array.from(buffer).buffer;\n\t}\n\tBinary.fromHex = fromHex;\n})(Binary || (Binary = {}));\n/** Decode a base64 string into binary data. */\nconst base64ToArrayBuffer = Binary.fromBase64;\n/** Encode binary data as base64. */\nconst arrayBufferToBase64 = Binary.toBase64;\n/** Decode a hex string into binary data. */\nconst hexToArrayBuffer = Binary.fromHex;\n/** Encode binary data as hex. */\nconst arrayBufferToHex = Binary.toHex;\n/** Deep-clone common JavaScript values while preserving prototypes and cycles. */\nfunction clone(source, refs = /* @__PURE__ */ new Map()) {\n\tif (!source || typeof source !== \"object\") return source;\n\tif (is(\"Date\", source)) return new Date(source.valueOf());\n\tif (is(\"RegExp\", source)) return new RegExp(source.source, source.flags);\n\tif (isArrayBufferLike(source)) return source.slice(0);\n\tif (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);\n\tconst cached = refs.get(source);\n\tif (cached) return cached;\n\tif (Array.isArray(source)) {\n\t\tconst result = [];\n\t\trefs.set(source, result);\n\t\tsource.forEach((value, index) => {\n\t\t\tresult[index] = Reflect.apply(clone, null, [value, refs]);\n\t\t});\n\t\treturn result;\n\t}\n\tconst result = Object.create(Object.getPrototypeOf(source));\n\trefs.set(source, result);\n\tfor (const key of Reflect.ownKeys(source)) {\n\t\tconst descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };\n\t\tif (\"value\" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);\n\t\tReflect.defineProperty(result, key, descriptor);\n\t}\n\treturn result;\n}\n/**\n* Compare values recursively, treating two volatile references as equal regardless of value.\n* Strict comparison distinguishes null/undefined, treats opaque objects by identity,\n* compares URLs by normalized href, treats array holes as undefined, and considers distinct cyclic structures unequal.\n* @param a - first value.\n* @param b - second value.\n* @param strict - whether to require strict data equality outside volatile references.\n* @returns whether the values compare equal.\n*/\nfunction deepEqual(a, b, strict) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tfunction compare(a, b) {\n\t\tif (a === b) return true;\n\t\tif (isVolatile(a) || isVolatile(b)) return isVolatile(a) && isVolatile(b);\n\t\tif (!strict && isNullable(a) && isNullable(b)) return true;\n\t\tif (typeof a !== typeof b || typeof a !== \"object\" || !a || !b) return false;\n\t\tif (ancestors.has(a)) return false;\n\t\tfunction check(test, then) {\n\t\t\treturn test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;\n\t\t}\n\t\tancestors.add(a);\n\t\ttry {\n\t\t\treturn check(Array.isArray, (a, b) => {\n\t\t\t\tif (a.length !== b.length) return false;\n\t\t\t\tfor (let index = 0; index < a.length; index++) if (!compare(a[index], b[index])) return false;\n\t\t\t\treturn true;\n\t\t\t}) ?? check(is(\"Date\"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is(\"URL\"), (a, b) => a.href === b.href) ?? check(is(\"RegExp\"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {\n\t\t\t\tif (a.byteLength !== b.byteLength) return false;\n\t\t\t\tconst viewA = new Uint8Array(a);\n\t\t\t\tconst viewB = new Uint8Array(b);\n\t\t\t\tfor (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;\n\t\t\t\treturn true;\n\t\t\t}) ?? ((!strict || [a, b].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({\n\t\t\t\t...a,\n\t\t\t\t...b\n\t\t\t}).every((key) => compare(a[key], b[key])));\n\t\t} finally {\n\t\t\tancestors.delete(a);\n\t\t}\n\t}\n\treturn compare(a, b);\n}\n//#endregion\n//#region lib/types/string.js\n/** Uppercase the first character of a string. */\nfunction capitalize(source) {\n\treturn source.charAt(0).toUpperCase() + source.slice(1);\n}\n/** Lowercase the first character of a string. */\nfunction uncapitalize(source) {\n\treturn source.charAt(0).toLowerCase() + source.slice(1);\n}\n/** Convert dash or underscore delimited text to camelCase. */\nfunction camelCase(source) {\n\treturn source.replace(/[_-][a-z]/g, (str) => str.slice(1).toUpperCase());\n}\nfunction tokenize(source, delimiters, delimiter) {\n\tconst output = [];\n\tlet state = 0;\n\tfor (let i = 0; i < source.length; i++) {\n\t\tconst code = source.charCodeAt(i);\n\t\tif (code >= 65 && code <= 90) {\n\t\t\tif (state === 1) {\n\t\t\t\tconst next = source.charCodeAt(i + 1);\n\t\t\t\tif (next >= 97 && next <= 122) output.push(delimiter);\n\t\t\t\toutput.push(code + 32);\n\t\t\t} else {\n\t\t\t\tif (state !== 0) output.push(delimiter);\n\t\t\t\toutput.push(code + 32);\n\t\t\t}\n\t\t\tstate = 1;\n\t\t} else if (code >= 97 && code <= 122) {\n\t\t\toutput.push(code);\n\t\t\tstate = 2;\n\t\t} else if (delimiters.includes(code)) {\n\t\t\tif (state !== 0) output.push(delimiter);\n\t\t\tstate = 0;\n\t\t} else output.push(code);\n\t}\n\treturn String.fromCharCode(...output);\n}\n/** Convert text to dash-delimited parameter case. */\nfunction paramCase(source) {\n\treturn tokenize(source, [45, 95], 45);\n}\n/** Convert text to underscore-delimited snake case. */\nfunction snakeCase(source) {\n\treturn tokenize(source, [45, 95], 95);\n}\n/** Runtime alias for `camelCase`. */\nconst camelize = camelCase;\n/** Runtime alias for `paramCase`. */\nconst hyphenate = paramCase;\n/** Format a property key as a JavaScript member access suffix. */\nfunction formatProperty(key) {\n\tif (typeof key !== \"string\") return `[${key.toString()}]`;\n\treturn /^[a-z_$][\\w$]*$/i.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;\n}\n/** Remove one trailing slash from a path string. */\nfunction trimSlash(source) {\n\treturn source.replace(/\\/$/, \"\");\n}\n/** Ensure a path starts with `/` and has no trailing slash. */\nfunction sanitize(source) {\n\tif (!source.startsWith(\"/\")) source = \"/\" + source;\n\treturn trimSlash(source);\n}\n//#endregion\n//#region lib/types/time.js\n/** Time constants plus parsing and formatting helpers. */\nvar Time;\n(function(Time) {\n\tTime.millisecond = 1;\n\tTime.second = 1e3;\n\tTime.minute = Time.second * 60;\n\tTime.hour = Time.minute * 60;\n\tTime.day = Time.hour * 24;\n\tTime.week = Time.day * 7;\n\tlet timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();\n\tfunction setTimezoneOffset(offset) {\n\t\ttimezoneOffset = offset;\n\t}\n\tTime.setTimezoneOffset = setTimezoneOffset;\n\tfunction getTimezoneOffset() {\n\t\treturn timezoneOffset;\n\t}\n\tTime.getTimezoneOffset = getTimezoneOffset;\n\tfunction getDateNumber(date = /* @__PURE__ */ new Date(), offset) {\n\t\tif (typeof date === \"number\") date = new Date(date);\n\t\tif (offset === void 0) offset = timezoneOffset;\n\t\treturn Math.floor((date.valueOf() / Time.minute - offset) / 1440);\n\t}\n\tTime.getDateNumber = getDateNumber;\n\tfunction fromDateNumber(value, offset) {\n\t\tconst date = new Date(value * Time.day);\n\t\tif (offset === void 0) offset = timezoneOffset;\n\t\treturn new Date(+date + offset * Time.minute);\n\t}\n\tTime.fromDateNumber = fromDateNumber;\n\tconst numeric = /\\d+(?:\\.\\d+)?/.source;\n\tconst timeRegExp = new RegExp(`^${[\n\t\t\"w(?:eek(?:s)?)?\",\n\t\t\"d(?:ay(?:s)?)?\",\n\t\t\"h(?:our(?:s)?)?\",\n\t\t\"m(?:in(?:ute)?(?:s)?)?\",\n\t\t\"s(?:ec(?:ond)?(?:s)?)?\"\n\t].map((unit) => `(${numeric}${unit})?`).join(\"\")}$`);\n\tfunction parseTime(source) {\n\t\tconst capture = timeRegExp.exec(source);\n\t\tif (!capture) return 0;\n\t\treturn (parseFloat(capture[1]) * Time.week || 0) + (parseFloat(capture[2]) * Time.day || 0) + (parseFloat(capture[3]) * Time.hour || 0) + (parseFloat(capture[4]) * Time.minute || 0) + (parseFloat(capture[5]) * Time.second || 0);\n\t}\n\tTime.parseTime = parseTime;\n\tfunction parseDate(date) {\n\t\tconst parsed = parseTime(date);\n\t\tif (parsed) date = Date.now() + parsed;\n\t\telse if (/^\\d{1,2}(:\\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;\n\t\telse if (/^\\d{1,2}-\\d{1,2}-\\d{1,2}(:\\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;\n\t\treturn date ? new Date(date) : /* @__PURE__ */ new Date();\n\t}\n\tTime.parseDate = parseDate;\n\tfunction format(ms) {\n\t\tconst abs = Math.abs(ms);\n\t\tif (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + \"d\";\n\t\telse if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + \"h\";\n\t\telse if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + \"m\";\n\t\telse if (abs >= Time.second) return Math.round(ms / Time.second) + \"s\";\n\t\treturn ms + \"ms\";\n\t}\n\tTime.format = format;\n\tfunction toDigits(source, length = 2) {\n\t\treturn source.toString().padStart(length, \"0\");\n\t}\n\tTime.toDigits = toDigits;\n\tfunction template(template, time = /* @__PURE__ */ new Date()) {\n\t\treturn template.replace(\"yyyy\", time.getFullYear().toString()).replace(\"yy\", time.getFullYear().toString().slice(2)).replace(\"MM\", toDigits(time.getMonth() + 1)).replace(\"dd\", toDigits(time.getDate())).replace(\"hh\", toDigits(time.getHours())).replace(\"mm\", toDigits(time.getMinutes())).replace(\"ss\", toDigits(time.getSeconds())).replace(\"SSS\", toDigits(time.getMilliseconds(), 3));\n\t}\n\tTime.template = template;\n})(Time || (Time = {}));\n//#endregion\nexport { Binary, Time, arrayBufferToBase64, arrayBufferToHex, base64ToArrayBuffer, camelCase, camelize, capitalize, clone, contain, createVolatile, deduplicate, deepEqual, defineProperty, difference, filterKeys, formatProperty, hexToArrayBuffer, hyphenate, intersection, is, isNonNullable, isNullable, isPlainObject, isVolatile, makeArray, mapValues, mapValues as valueMap, noop, omit, paramCase, pick, remove, sanitize, snakeCase, trimSlash, uncapitalize, union, updateVolatile, volatileEntries };\n", "/**\r\n * Target-host rule parsing shared by the Host matcher and the settings page.\r\n *\r\n * This module deliberately has no undici import: the browser bundle imports it\r\n * too, and the two halves must agree on what an entry means before either can\r\n * safely warn about an entry that will never match.\r\n */\r\n\r\n/** Split a host-rule string into raw, non-empty tokens. */\r\nexport function splitHostRules(raw: string): string[] {\r\n return raw\r\n .split(/[,\\s]+/)\r\n .map(entry => entry.trim())\r\n .filter(entry => entry.length > 0)\r\n}\r\n\r\n/**\r\n * Normalize one raw rule for suffix matching.\r\n *\r\n * A leading `.` or `*.` is dropped: both spellings mean \"this host and its\r\n * subdomains\". Lower-casing belongs here as well, because the Host compares\r\n * against a WHATWG hostname that is already lower-cased.\r\n */\r\nexport function normalizeHostRule(raw: string): string {\r\n return raw.trim().replace(/^\\*?\\./, '').toLowerCase()\r\n}\r\n\r\n/** Split and normalize a host-rule string into matchable entries. */\r\nexport function parseHostList(raw: string): string[] {\r\n return splitHostRules(raw)\r\n .map(normalizeHostRule)\r\n .filter(entry => entry.length > 0)\r\n}\r\n\r\n/**\r\n * Whether a host is covered by one rule list.\r\n *\r\n * `*` matches everything; otherwise a rule matches the host itself or any\r\n * subdomain of it (`example.com` covers `api.example.com`).\r\n */\r\nexport function hostMatches(host: string, rules: readonly string[]): boolean {\r\n for (const rule of rules) {\r\n if (rule === '*') return true\r\n if (host === rule || host.endsWith(`.${rule}`)) return true\r\n }\r\n return false\r\n}\r\n\r\n/** Whether a raw token is a bracketed IPv6 literal, e.g. `[::1]`. */\r\nfunction isBracketedIpv6(token: string): boolean {\r\n return /^\\[[0-9a-f:.]+\\]$/i.test(token)\r\n}\r\n\r\n/** Whether a raw token can never match the Host's hostname comparison. */\r\nexport function hostRuleProblem(raw: string): string | undefined {\r\n const token = raw.trim()\r\n if (token.length === 0) return undefined\r\n // A bare `*.` normalizes to an empty string and disappears from the match\r\n // list entirely; report it rather than silently accepting a no-op.\r\n if (token === '*.' || normalizeHostRule(token).length === 0) return '\u7A7A\u901A\u914D\u7B26'\r\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(token)) return '\u5E26\u534F\u8BAE\u524D\u7F00'\r\n if (token.includes('/')) return '\u5E26\u8DEF\u5F84'\r\n // Host compares hostnames, never `host:port`; a bracketed IPv6 literal is the\r\n // one legitimate colon in a hostname.\r\n if (token.includes(':') && !isBracketedIpv6(token)) return '\u5E26\u7AEF\u53E3\u6216\u975E\u6CD5\u5192\u53F7'\r\n // Host strips only a leading `.`/`*.`; any other `*` cannot be a hostname.\r\n const withoutLeadingWildcard = token.replace(/^\\*\\./, '')\r\n if (withoutLeadingWildcard.includes('*') && token !== '*') return '\u6742\u6563\u901A\u914D\u7B26'\r\n return undefined\r\n}\r\n\r\n/** Every raw token that will never match, in the order it was typed. */\r\nexport function deadRuleEntries(raw: string): string[] {\r\n return splitHostRules(raw).filter(entry => hostRuleProblem(entry) !== undefined)\r\n}\r\n"],
|
|
5
|
-
"mappings": ";;;;;;;AAQA,SAAS,SAASA,oBAAmB;;;AC4BrC,SAAS,yBAAyB;A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AAmD;AAItD,SAAO,eAAe,KAAK,sBAAsB;AAAA,IAC/C,cAAc;AAAA,IACd,KAAK,OAAO;AAAA,MACV,QAAQ,CAAC,GAAG,QAAQ,OAAO,CAAC,EAAE,IAAI,YAAU;AAAA,QAC1C,UAAU,MAAM;AAAA,QAChB,aAAa,MAAM;AAAA,MACrB,EAAE;AAAA,MACF,UAAU,OAAO,YAAY,QAAQ;AAAA,MACrC,MAAM,OAAO,YAAY,IAAI;AAAA,MAC7B,SAAS,OAAO,YAAY,OAAO;AAAA,IACrC;AAAA,EACF,CAAC;AACH;",
|
|
4
|
+
"sourcesContent": ["/**\r\n * dsh-provider-proxy \u2014 Host half.\r\n *\r\n * Routes the model calls of the providers the user enabled through that\r\n * provider's own forward proxy. Every other provider, and all other DSH\r\n * traffic, keeps using the normal network path.\r\n */\r\n\r\nimport { fetch as undiciFetch } from 'undici'\r\n\r\nimport { acquireFetchRouter } from './fetch-router.js'\r\nimport {\r\n buildRouteEntry,\r\n closeTable,\r\n createProxyTable,\r\n routeFingerprint,\r\n routeStateDecision,\r\n type RouteEntry,\r\n type RouteState,\r\n} from './proxy-table.js'\r\nimport {\r\n normalizeDefaultProxy,\r\n type DefaultProxyValue,\r\n type ProviderProxyRouteValue,\r\n} from './config.js'\r\n\r\nexport const name = 'dsh-provider-proxy'\r\nexport const inject = ['llm']\r\n\r\n/**\r\n * Reserved provider id whose route carries `ctx.web.search` traffic.\r\n *\r\n * It lives in the ordinary provider dictionary, so its card, its settings write\r\n * path, its hit counter and its diagnostics are all the normal ones. A real\r\n * provider colliding with this id would simply share the route \u2014 harmless, and\r\n * far less likely than the alternative of a separate top-level field needing a\r\n * special case in every one of those places.\r\n */\r\nexport const WEB_SEARCH_KEY = 'web-search'\r\n\r\n/**\r\n * The Config this fiber receives.\r\n *\r\n * It is NOT `ConfigShape`: under the Loader `providers` is a Volatile REFERENCE,\r\n * not the dictionary, so it has to be read through `.get()`. Declaring the plain\r\n * shape here made the two incompatible and hid every real value.\r\n */\r\ninterface ProxyConfig {\r\n /** The provider dictionary, or the Volatile wrapper around it. */\r\n readonly providers?: unknown\r\n /** The shared default endpoint, or the Volatile wrapper around it. */\r\n readonly defaultProxy?: unknown\r\n /** Whether loopback/private targets stay direct, or the Volatile wrapper. */\r\n readonly localDirect?: unknown\r\n /** The self-check URL, or the Volatile wrapper around it. */\r\n readonly testUrl?: unknown\r\n}\r\n\r\nfunction plainProviders(\r\n config: ProxyConfig | undefined,\r\n): Record<string, Partial<ProviderProxyRouteValue>> {\r\n const raw = config?.providers\r\n if (raw === undefined) return {}\r\n // Under the Loader this is a Volatile reference; read it fresh every time so\r\n // a settings write is visible to the next request without a remount.\r\n const snapshot = (raw as { get?: () => unknown }).get\r\n const value = typeof snapshot === 'function' ? snapshot.call(raw) : raw\r\n return (value ?? {}) as Record<string, Partial<ProviderProxyRouteValue>>\r\n}\r\n\r\n/** Read the shared default endpoint, which is Volatile under the Loader too. */\r\nfunction plainDefaultProxy(config: ProxyConfig | undefined): Partial<DefaultProxyValue> {\r\n const raw = config?.defaultProxy\r\n if (raw === undefined) return {}\r\n const snapshot = (raw as { get?: () => unknown }).get\r\n const value = typeof snapshot === 'function' ? snapshot.call(raw) : raw\r\n return (value ?? {}) as Partial<DefaultProxyValue>\r\n}\r\n\r\n/**\r\n * Read `localDirect`, Volatile like everything else the settings page writes.\r\n *\r\n * Absent or malformed means ON: the default is what keeps a loopback relay from\r\n * being forced through a proxy that cannot reach it.\r\n */\r\nfunction plainLocalDirect(config: ProxyConfig | undefined): boolean {\r\n const raw = config?.localDirect\r\n if (raw === undefined) return true\r\n const snapshot = (raw as { get?: () => unknown }).get\r\n const value = typeof snapshot === 'function' ? snapshot.call(raw) : raw\r\n return value !== false\r\n}\r\n\r\nexport function apply(ctx: any, config?: ProxyConfig): void {\r\n const router = acquireFetchRouter()\r\n let current = new Map<string, RouteEntry>()\r\n let problems = new Map<string, string>()\r\n let closed = false\r\n /** Whether a `web` service exists, i.e. whether the reserved route has anything to carry. */\r\n let webAvailable = false\r\n\r\n // Request counts, keyed by provider id. Held OUTSIDE the proxy table so a\r\n // rebuild (a settings write) never resets them; only a plugin reload does.\r\n // Counted at request initiation \u2014 see fetch-router.ts.\r\n const hits = new Map<string, number>()\r\n /**\r\n * The immutable identity of the route each request was bound to.\r\n *\r\n * `lastUse` answers \"does THIS configuration still work\", so an in-flight\r\n * request from an older route must never write to the current one. Tokens are\r\n * global and never reused, which also makes delete-and-re-add distinguishable\r\n * from an unchanged provider.\r\n */\r\n const routeStates = new Map<string, RouteState>()\r\n let nextRouteToken = 1\r\n /**\r\n * Per-provider liveness. `startedAt` is when the last proxied request BEGAN;\r\n * `at`/`ok`/`code` describe the last request that FINISHED. They are kept apart\r\n * because LLM calls are concurrent: a single `at` shared by both would pair one\r\n * request's start time with another's outcome, and a card could name a failure\r\n * that belongs to a call which in fact succeeded.\r\n */\r\n const lastUse = new Map<string, { startedAt: number; at?: number; ok?: boolean; code?: string }>()\r\n const bump = (provider: string, token: number): void => {\r\n hits.set(provider, (hits.get(provider) ?? 0) + 1)\r\n if (routeStates.get(provider)?.token !== token) return\r\n // Only the START moves here. The outcome fields are written once a request\r\n // settles, so an in-flight call cannot overwrite the last COMPLETED result.\r\n lastUse.set(provider, { ...lastUse.get(provider), startedAt: Date.now() })\r\n }\r\n const settle = (provider: string, token: number) => (ok: boolean, detail: unknown): void => {\r\n if (routeStates.get(provider)?.token !== token) return\r\n const previous = lastUse.get(provider)\r\n lastUse.set(provider, {\r\n startedAt: previous?.startedAt ?? Date.now(),\r\n // `at` is the FINISH time, written together with the outcome it belongs to.\r\n at: Date.now(),\r\n ok,\r\n code: ok ? String((detail as { status?: unknown } | undefined)?.status ?? '') : failureCodeOf(detail),\r\n })\r\n }\r\n\r\n /** Where the self-check sends its request; overridable so a blocked echo host can be replaced. */\r\n const DEFAULT_TEST_URL = 'https://api.ipify.org?format=json'\r\n /** How many `testUrl` candidates one check may walk. Bounds the outbound cost. */\r\n const MAX_TEST_TARGETS = 5\r\n const TEST_TIMEOUT_MS = 10_000\r\n /** The self-check body carries one provider id; anything larger is refused, not buffered. */\r\n const MAX_REQUEST_BYTES = 8 * 1024\r\n /** One in-flight check per provider, so a repeated click cannot multiply outbound requests. */\r\n const selfChecks = new Map<string, Promise<Record<string, unknown>>>()\r\n /**\r\n * The last COMPLETED check per provider, with its finish time. A click inside\r\n * the cooldown gets the remembered answer back instead of a new outbound\r\n * request: the in-flight dedup above only merges CONCURRENT checks, so without\r\n * this, a slow echo target could be hammered serially by impatient clicks.\r\n * The answer is the truth about a configuration that has not changed \u2014 not a\r\n * stale value \u2014 and it is marked `cached` so a caller can tell.\r\n */\r\n const SELF_CHECK_COOLDOWN_MS = 3_000\r\n const MAX_CHECK_ENTRIES_PER_PROVIDER = 8\r\n const MAX_CHECK_PROVIDERS = 64\r\n const lastChecks = new Map<string, Map<string, { at: number; result: Record<string, unknown> }>>()\r\n /** Cache key without its provider id, so the inner map can be indexed by provider. */\r\n const checkKeyOf = (provider: string, key: string): string => key.slice(provider.length)\r\n\r\n const pruneCheckCache = (now = Date.now()): void => {\r\n for (const [provider, entries] of lastChecks) {\r\n for (const [key, entry] of entries) {\r\n if (now - entry.at >= SELF_CHECK_COOLDOWN_MS) entries.delete(key)\r\n }\r\n if (entries.size === 0) lastChecks.delete(provider)\r\n }\r\n while (lastChecks.size > MAX_CHECK_PROVIDERS) {\r\n let oldestProvider: string | undefined\r\n let oldestAt = Infinity\r\n for (const [provider, entries] of lastChecks) {\r\n let latest = -Infinity\r\n for (const entry of entries.values()) latest = Math.max(latest, entry.at)\r\n if (latest < oldestAt) {\r\n oldestAt = latest\r\n oldestProvider = provider\r\n }\r\n }\r\n if (oldestProvider === undefined) break\r\n lastChecks.delete(oldestProvider)\r\n }\r\n }\r\n\r\n const rememberCheck = (\r\n provider: string,\r\n key: string,\r\n result: Record<string, unknown>,\r\n ): void => {\r\n pruneCheckCache()\r\n let entries = lastChecks.get(provider)\r\n if (entries === undefined) {\r\n entries = new Map()\r\n lastChecks.set(provider, entries)\r\n }\r\n entries.set(checkKeyOf(provider, key), { at: Date.now(), result })\r\n while (entries.size > MAX_CHECK_ENTRIES_PER_PROVIDER) {\r\n let oldestKey: string | undefined\r\n let oldestAt = Infinity\r\n for (const [candidate, entry] of entries) {\r\n if (entry.at < oldestAt) {\r\n oldestAt = entry.at\r\n oldestKey = candidate\r\n }\r\n }\r\n if (oldestKey === undefined) break\r\n entries.delete(oldestKey)\r\n }\r\n pruneCheckCache()\r\n }\r\n\r\n /** Drop both completed and in-flight checks for one route identity. */\r\n const forgetChecks = (provider: string): void => {\r\n lastChecks.delete(provider)\r\n for (const key of [...selfChecks.keys()]) {\r\n if (key.startsWith(`${provider}\\u0000`)) selfChecks.delete(key)\r\n }\r\n }\r\n\r\n /**\r\n * Read `testUrl`, which is Volatile under the Loader and therefore needs\r\n * `.get()`.\r\n *\r\n * It may name SEVERAL candidates, separated by commas or whitespace: any single\r\n * public echo host can be unreachable on some networks, and a check that fails\r\n * for that reason is a check nobody trusts. The list is capped so a long one\r\n * cannot quietly multiply outbound requests.\r\n */\r\n const plainTestUrls = (): string[] => {\r\n const raw = (config as { testUrl?: unknown } | undefined)?.testUrl\r\n const snapshot = (raw as { get?: () => unknown } | undefined)?.get\r\n const value = typeof snapshot === 'function' ? snapshot.call(raw) : raw\r\n const list =\r\n typeof value === 'string'\r\n ? value\r\n .split(/[,\\s]+/)\r\n .map(entry => entry.trim())\r\n .filter(entry => entry.length > 0)\r\n : []\r\n return list.length > 0 ? list.slice(0, MAX_TEST_TARGETS) : [DEFAULT_TEST_URL]\r\n }\r\n\r\n /** Walk `path` down a value, giving up at the first non-object. */\r\n const walk = (value: unknown, path: readonly unknown[]): unknown => {\r\n let node = value\r\n for (const key of path) {\r\n if (node === null || typeof node !== 'object') return undefined\r\n node = (node as Record<string, unknown>)[key as string]\r\n }\r\n return node\r\n }\r\n\r\n /**\r\n * The endpoint a provider actually calls, when its adapter publishes one.\r\n *\r\n * Read from the adapter's SETTINGS SECTION rather than from `listProviders()`,\r\n * which carries only `{ id, name }`. `listConfigurableProviders()` supplies the\r\n * address \u2014 the settings namespace plus the path to the route's profile \u2014 and\r\n * that is exactly what a configuration surface is meant to consume.\r\n *\r\n * Everything here is optional and defensively read: a composition without the\r\n * settings service, an adapter that registers no section, or a profile that\r\n * stores no address all simply yield `undefined`, and the caller falls back to\r\n * the top-level `testUrl` exactly as before.\r\n */\r\n const upstreamOf = (provider: string): string | undefined => {\r\n let settings: any\r\n try {\r\n settings = typeof ctx?.get === 'function' ? ctx.get('settings') : undefined\r\n } catch {\r\n return undefined\r\n }\r\n if (settings === undefined || typeof settings.get !== 'function') return undefined\r\n let entry: any\r\n try {\r\n const entries: any[] = ctx.llm?.listConfigurableProviders?.() ?? []\r\n entry = entries.find(candidate => candidate?.provider === provider)\r\n } catch {\r\n return undefined\r\n }\r\n if (entry === undefined) return undefined\r\n let profile: unknown\r\n try {\r\n profile = walk(settings.get(entry.settingsNs), entry.settingsPath ?? [])\r\n } catch {\r\n return undefined\r\n }\r\n const baseURL = (profile as { baseURL?: unknown } | undefined)?.baseURL\r\n return typeof baseURL === 'string' && baseURL.trim().length > 0 ? baseURL.trim() : undefined\r\n }\r\n\r\n /**\r\n * The `dsh-provider-proxy: ` prefix on a recorded problem is a Host-log\r\n * convention. Both endpoints that serve the settings page are UI payloads, so\r\n * the prefix is stripped at the boundary; `providerProxyState` and the log\r\n * keep the string exactly as the table recorded it.\r\n */\r\n const bareMessage = (message: string): string => message.replace(/^dsh-provider-proxy:\\s*/, '')\r\n\r\n /**\r\n * Every error reachable from one throw: the value itself, its `cause` chain,\r\n * and any `AggregateError.errors` on the way.\r\n *\r\n * `fetch` wraps a connection failure as `TypeError: fetch failed` and hides\r\n * the real `ECONNREFUSED` in `cause`, so a classifier that only reads the top\r\n * value cannot tell \"the proxy is down\" from \"the target refused\".\r\n */\r\n const causesOf = (error: unknown): unknown[] => {\r\n const out: unknown[] = []\r\n const seen = new Set<unknown>()\r\n const queue: unknown[] = [error]\r\n while (queue.length > 0) {\r\n const node = queue.shift()\r\n if (node === null || typeof node !== 'object' || seen.has(node)) continue\r\n seen.add(node)\r\n out.push(node)\r\n const cause = (node as { cause?: unknown }).cause\r\n if (cause !== undefined && cause !== null) queue.push(cause)\r\n const errors = (node as { errors?: unknown }).errors\r\n if (Array.isArray(errors)) queue.push(...errors)\r\n }\r\n return out\r\n }\r\n\r\n /**\r\n * Classify a self-check failure so the report points at the hop that actually\r\n * failed.\r\n *\r\n * `viaProxy` decides WHICH hop that is: the same connection error means \"the\r\n * proxy is unreachable\" on a proxied probe but \"the target is unreachable\" on a\r\n * direct one. Naming the proxy for a direct probe would send the operator after\r\n * a hop the check never used.\r\n */\r\n const classifyTestError = (\r\n error: unknown,\r\n viaProxy: boolean,\r\n rawTarget: string,\r\n ): { kind: string; error: string } => {\r\n const chain = causesOf(error)\r\n const names = chain\r\n .map(node => (node as { name?: unknown }).name)\r\n .filter((name): name is string => typeof name === 'string')\r\n const codes = chain\r\n .map(node => (node as { code?: unknown }).code)\r\n .filter((code): code is string => typeof code === 'string')\r\n // undici THROWS on a proxy 407 rather than returning the response, and the\r\n // only place the \"407\" appears is a CAUSE's message (\"Proxy Authentication\r\n // Required (407)\") \u2014 the top-level message is the generic \"fetch failed\". So\r\n // the whole chain is searched, not just the value that was thrown.\r\n const messages = chain\r\n .map(node => (node as { message?: unknown }).message)\r\n .filter((text): text is string => typeof text === 'string')\r\n // The thrown message may quote the raw target, including userinfo or a\r\n // query token. Keep the useful classification but never pass that message\r\n // through verbatim.\r\n const message = redactTargetFromText(\r\n error instanceof Error ? error.message : String(error),\r\n rawTarget,\r\n )\r\n if (names.includes('TimeoutError') || names.includes('AbortError')) {\r\n return { kind: 'timeout', error: `\u8D85\u65F6\uFF08${TEST_TIMEOUT_MS / 1000}s\uFF09\uFF1A\u4EE3\u7406\u6216\u76EE\u6807\u65E0\u54CD\u5E94` }\r\n }\r\n const connectivity = ['ECONNREFUSED', 'ENOTFOUND', 'EHOSTUNREACH', 'ENETUNREACH', 'ECONNRESET', 'EAI_AGAIN']\r\n const code = connectivity.find(candidate => codes.includes(candidate))\r\n if (code !== undefined) {\r\n return viaProxy\r\n ? { kind: 'proxy-unreachable', error: `\u4EE3\u7406\u4E0D\u53EF\u8FBE\uFF08${code}\uFF09\uFF1A${message}` }\r\n : { kind: 'target', error: `\u76EE\u6807\u4E0D\u53EF\u8FBE\uFF08${code}\uFF09\uFF1A${message}` }\r\n }\r\n if (names.includes('ProxyAuthentication') || messages.some(text => text.includes('407'))) {\r\n return { kind: 'proxy-auth', error: `\u4EE3\u7406\u8981\u6C42\u8BA4\u8BC1\uFF08HTTP 407\uFF09\uFF1A${message}` }\r\n }\r\n return { kind: 'target', error: `\u8BF7\u6C42\u5931\u8D25\uFF1A${message}` }\r\n }\r\n\r\n /**\r\n * Collapse a target to the origin and pathname for display.\r\n *\r\n * Userinfo, query values and fragments are removed before the value is\r\n * returned to the page. Invalid targets lose a `scheme://userinfo@` prefix and\r\n * everything from the first query/fragment marker, then are bounded in length.\r\n */\r\n const sanitizeTargetForDisplay = (target: string): string => {\r\n const raw = String(target ?? '')\r\n try {\r\n const url = new URL(raw)\r\n return `${url.protocol}//${url.host}${url.pathname}`\r\n } catch {\r\n const withoutUserinfo = raw.replace(\r\n /^([a-z][a-z0-9+.-]*:\\/\\/)[^/@\\s]+@/i,\r\n '$1',\r\n )\r\n const withoutQuery = withoutUserinfo.split(/[?#]/, 1)[0] ?? ''\r\n const bounded = withoutQuery.length > 160 ? `${withoutQuery.slice(0, 160)}\u2026` : withoutQuery\r\n return bounded\r\n }\r\n }\r\n\r\n /** Remove a raw target (and URL secrets) from a Host-generated error. */\r\n const redactTargetFromText = (text: string, rawTarget: string): string => {\r\n let safe = text\r\n if (rawTarget.length > 0) safe = safe.split(rawTarget).join('[\u76EE\u6807\u5DF2\u8131\u654F]')\r\n // The error chain may contain the target in a re-serialized form, so strip\r\n // every URLs credentials and query/fragment tail, not only the exact input.\r\n safe = safe.replace(/\\b([a-z][a-z0-9+.-]*:\\/\\/)[^/@\\s]+@/gi, '$1')\r\n safe = safe.replace(/([?&#])[^\\s\"'<>]*/g, '$1')\r\n return safe.length > 500 ? `${safe.slice(0, 500)}\u2026` : safe\r\n }\r\n\r\n /**\r\n * A short machine code for a transport failure, for a card's \"last failure\".\r\n *\r\n * Walks the same cause chain the self-check classifier does: `fetch` hides the\r\n * real code one or two levels down, so reading only the top value would report\r\n * a useless \"fetch failed\" for every kind of outage.\r\n */\r\n const failureCodeOf = (error: unknown): string => {\r\n const chain = causesOf(error)\r\n const names = chain\r\n .map(node => (node as { name?: unknown }).name)\r\n .filter((name): name is string => typeof name === 'string')\r\n if (names.includes('TimeoutError')) return 'TIMEOUT'\r\n if (names.includes('AbortError')) return 'ABORTED'\r\n for (const node of chain) {\r\n const code = (node as { code?: unknown }).code\r\n if (typeof code === 'string' && code.length > 0) return code\r\n }\r\n return 'ERROR'\r\n }\r\n\r\n /**\r\n * Send one request to ONE target, honoured the way real traffic would be.\r\n *\r\n * The proxy/direct decision comes from the route's OWN `decide`, exactly as a\r\n * live request consults it: a loopback/private target, a `bypassHosts` match,\r\n * or an `onlyHosts` miss goes DIRECT, and only a proxied probe carries the\r\n * dispatcher. This matters most now that the check defaults to the provider's\r\n * real upstream: a local relay upstream (LiteLLM, Ollama) would otherwise be\r\n * forced through a forward proxy that cannot reach it, and the check would\r\n * report a healthy route as \"the proxy is broken\" \u2014 the very false positive\r\n * `localDirect` exists to remove.\r\n *\r\n * When it IS proxied, the dispatcher is passed EXPLICITLY rather than by\r\n * entering the router's AsyncLocalStorage scope: that scope intercepts\r\n * `globalThis.fetch`, so a plain `undici.fetch` call would go straight out and\r\n * report a broken proxy as a success \u2014 the one failure this whole feature\r\n * exists to eliminate.\r\n */\r\n const probeTarget = async (\r\n target: string,\r\n route: RouteEntry,\r\n ): Promise<Record<string, unknown>> => {\r\n const displayTarget = sanitizeTargetForDisplay(target)\r\n let host: string | undefined\r\n try {\r\n host = new URL(target).hostname\r\n } catch {\r\n return {\r\n ok: false,\r\n kind: 'target',\r\n target: displayTarget,\r\n error: `\u81EA\u68C0\u76EE\u6807\u4E0D\u662F\u5408\u6CD5 URL\uFF1A${displayTarget}`,\r\n }\r\n }\r\n const viaProxy = route.decide(host) === 'proxy'\r\n const started = performance.now()\r\n try {\r\n // WHATWG URL keeps userinfo out of `origin`, but the request URL still\r\n // carries it. The self-check never needs embedded credentials, so remove\r\n // them from the request too rather than merely hiding them on display.\r\n const requestTarget = ((): string => {\r\n const url = new URL(target)\r\n url.username = ''\r\n url.password = ''\r\n return url.toString()\r\n })()\r\n const response = await undiciFetch(requestTarget, {\r\n // A direct probe must NOT carry the dispatcher, or undici would force it\r\n // through the proxy anyway.\r\n ...(viaProxy ? { dispatcher: route.dispatcher } : {}),\r\n signal: AbortSignal.timeout(TEST_TIMEOUT_MS),\r\n } as never)\r\n const ms = Math.round(performance.now() - started)\r\n const targetField = { target: displayTarget }\r\n // 407 is the proxy demanding credentials: a RESULT, not a throw. Only a\r\n // proxied request can be answered by a proxy this way.\r\n if (viaProxy && response.status === 407) {\r\n return {\r\n ok: false,\r\n ms,\r\n status: 407,\r\n kind: 'proxy-auth',\r\n viaProxy,\r\n ...targetField,\r\n error: `\u4EE3\u7406\u8981\u6C42\u8BA4\u8BC1\uFF08HTTP 407\uFF09\uFF1A${displayTarget}`,\r\n }\r\n }\r\n let exitIp: string | undefined\r\n try {\r\n const body = (await response.json()) as { ip?: unknown } | null\r\n if (typeof body?.ip === 'string' && body.ip.length > 0) exitIp = body.ip\r\n } catch {\r\n // A non-JSON echo still proves the request crossed the proxy.\r\n }\r\n // Any status below 500 means the request DID reach something \u2014 the target\r\n // when it went direct, or the far side of the proxy. Against a real upstream\r\n // a bare GET normally answers 4xx (401/404) \u2014 the expected answer, and\r\n // proof the path works. A 5xx is the opposite: an HTTP proxy that cannot\r\n // reach its upstream answers 502/503/504 ITSELF, so it reads as a broken\r\n // path rather than a refused request.\r\n const reachable = response.status < 500\r\n if (reachable) {\r\n return {\r\n ok: true,\r\n ms,\r\n status: response.status,\r\n viaProxy,\r\n ...targetField,\r\n ...(exitIp === undefined ? {} : { exitIp }),\r\n kind: 'ok',\r\n }\r\n }\r\n return {\r\n ok: false,\r\n ms,\r\n status: response.status,\r\n viaProxy,\r\n ...targetField,\r\n kind: 'target',\r\n // The status travels in its own field; the reason text must not repeat\r\n // it, or the page shows the same code twice in different colours.\r\n error: `\u76EE\u6807\u8FD4\u56DE 5xx\uFF08\u4E0A\u6E38\u6216\u94FE\u8DEF\u5F02\u5E38\uFF09\uFF1A${displayTarget}`,\r\n }\r\n } catch (error) {\r\n return {\r\n ok: false,\r\n ms: Math.round(performance.now() - started),\r\n viaProxy,\r\n ...classifyTestError(error, viaProxy, target),\r\n target: displayTarget,\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Every target this check may try, in order.\r\n *\r\n * A route's own `testTarget` first, then the provider's REAL upstream when its\r\n * adapter publishes one, then the top-level `testUrl` \u2014 which may itself name\r\n * several echo services.\r\n *\r\n * Takes the target as a plain string so the cooldown key can call it too, with\r\n * the raw config's value: the key must be built from the SAME resolution the\r\n * check uses, or the two can disagree about what the next request would try.\r\n */\r\n /**\r\n * The check's targets, and WHERE they came from.\r\n *\r\n * The target is NOT always the top-level `testUrl`: a route's own\r\n * `testTarget` wins, then the provider's REAL upstream, and only a provider\r\n * that publishes none falls back to `testUrl`. Without this the page cannot\r\n * explain why editing `testUrl` changed one card and not another.\r\n *\r\n * The upstream is read ONCE: reading it twice could disagree if the settings\r\n * service moved in between, and the target list and the reported source must\r\n * never contradict each other.\r\n */\r\n const selfCheckTargetsOf = (\r\n provider: string,\r\n testTarget: string | undefined,\r\n ): { targets: string[]; source: 'route' | 'upstream' | 'testUrl' } => {\r\n const own = (testTarget ?? '').trim()\r\n if (own.length > 0) return { targets: [own], source: 'route' }\r\n const upstream = upstreamOf(provider)\r\n if (upstream !== undefined) return { targets: [upstream], source: 'upstream' }\r\n return { targets: plainTestUrls(), source: 'testUrl' }\r\n }\r\n\r\n /**\r\n * A fingerprint of every input that can change one provider's check ANSWER.\r\n *\r\n * The cooldown is a cache, and a cache keyed only by provider would answer a\r\n * question about a configuration the user has since edited. The route's own\r\n * transport fields are used, plus `testTarget`; when the route opts into the\r\n * shared endpoint, that endpoint's fields are what actually carry the request,\r\n * so they are folded in instead.\r\n *\r\n * `onlyHosts`/`bypassHosts`/`localDirect` and the resolved target list are part\r\n * of the answer too, and each one changes it visibly: they decide whether the\r\n * probe is proxied or direct (`viaProxy`), and the target list is where the\r\n * top-level `testUrl` enters when the route names no target of its own. Leaving\r\n * them out meant an edit inside the cooldown handed back the pre-edit verdict\r\n * with `cached: true` and issued no request at all. It is held in memory only\r\n * and never logged.\r\n */\r\n const selfCheckKey = (provider: string): string => {\r\n const raw = plainProviders(config)[provider] ?? {}\r\n const endpoint =\r\n raw.useDefault === true\r\n ? (plainDefaultProxy(config) as Partial<ProviderProxyRouteValue>)\r\n : raw\r\n return JSON.stringify([\r\n provider,\r\n endpoint.protocol ?? 'http',\r\n endpoint.host ?? '',\r\n endpoint.port ?? 0,\r\n endpoint.username ?? '',\r\n endpoint.password ?? '',\r\n raw.testTarget ?? '',\r\n raw.onlyHosts ?? '',\r\n raw.bypassHosts ?? '',\r\n plainLocalDirect(config),\r\n selfCheckTargetsOf(provider, raw.testTarget).targets,\r\n ])\r\n }\r\n\r\n /**\r\n * Run the connection self-check for one provider.\r\n *\r\n * A route the table carries is used directly \u2014 including one the guards\r\n * REJECTED, whose recorded problem is what explains it. A route that is merely\r\n * CONFIGURED gets a dispatcher built for this check alone, through the SAME\r\n * builder routing uses, so a setting can be verified BEFORE it is switched on\r\n * and a bad one is reported with the reason routing would have given.\r\n */\r\n const runSelfCheck = async (provider: string): Promise<Record<string, unknown>> => {\r\n let route = current.get(provider)\r\n let temporary = false\r\n if (route === undefined) {\r\n // Two very different reasons land here. A route the guards REJECTED (a bad\r\n // port, an HTTP password with no username) is missing from the table too,\r\n // and answering \"not enabled\" for it names a cause that is not the case \u2014\r\n // the setting IS on. The problem the table recorded is what explains it.\r\n const problem = problems.get(provider)\r\n if (problem !== undefined) {\r\n return { ok: false, kind: 'route-rejected', error: bareMessage(problem) }\r\n }\r\n const configured = plainProviders(config)[provider]\r\n if (configured === undefined || configured.enabled === true) {\r\n return { ok: false, kind: 'no-route', error: `provider \"${provider}\" \u672A\u542F\u7528\u4EE3\u7406` }\r\n }\r\n const built = buildRouteEntry(provider, configured, {\r\n defaultProxy: normalizeDefaultProxy(plainDefaultProxy(config)),\r\n requireEnabled: false,\r\n localDirect: plainLocalDirect(config),\r\n })\r\n if (!built.ok) {\r\n return { ok: false, kind: 'route-rejected', error: bareMessage(built.problem) }\r\n }\r\n route = built.entry\r\n temporary = true\r\n }\r\n try {\r\n let last: Record<string, unknown> | undefined\r\n const { targets, source } = selfCheckTargetsOf(provider, route.testTarget)\r\n for (const target of targets) {\r\n const outcome = await probeTarget(target, route)\r\n if (outcome.ok === true) return { ...outcome, targetSource: source }\r\n last = outcome\r\n // 407 is about the PROXY, not the target: another candidate would ask the\r\n // same question and get the same answer.\r\n if (outcome.kind === 'proxy-auth') break\r\n }\r\n return last === undefined\r\n ? { ok: false, kind: 'target', target: '', targetSource: source, error: '\u6CA1\u6709\u53EF\u7528\u7684\u81EA\u68C0\u76EE\u6807' }\r\n : { ...last, targetSource: source }\r\n } finally {\r\n // A dispatcher built for one check must not outlive it: the table owns the\r\n // long-lived ones, and this one was never in the table to begin with.\r\n if (temporary) await route.dispatcher.close().catch(() => undefined)\r\n }\r\n }\r\n\r\n // One line on activation so a user can tell \"mounted\" from \"not mounted\" in\r\n // the Host log without guessing. Never prints a credential.\r\n try {\r\n ctx.logger.info('dsh-provider-proxy mounted (pid %d)', process.pid)\r\n } catch {\r\n // A context without a logger still works; the diagnostics getter remains.\r\n }\r\n\r\n const rebuild = (): Promise<void> => {\r\n // One snapshot feeds the table, the route-state diff and every cleanup.\r\n // Reading the Volatile fields more than once could mix two settings writes.\r\n const providers = plainProviders(config)\r\n const defaultProxy = plainDefaultProxy(config)\r\n const localDirect = plainLocalDirect(config)\r\n const next = createProxyTable(providers, { defaultProxy, localDirect })\r\n const previous = current\r\n current = next.entries\r\n problems = next.problems\r\n\r\n const configured = new Set(Object.keys(providers))\r\n for (const provider of [...routeStates.keys()]) {\r\n if (configured.has(provider)) continue\r\n routeStates.delete(provider)\r\n lastUse.delete(provider)\r\n forgetChecks(provider)\r\n }\r\n\r\n for (const [provider, raw] of Object.entries(providers)) {\r\n const effective =\r\n raw?.useDefault === true\r\n ? { ...raw, ...defaultProxy }\r\n : raw\r\n const fingerprint = routeFingerprint({\r\n ...effective,\r\n localDirect,\r\n })\r\n const decision = routeStateDecision(routeStates.get(provider), {\r\n fingerprint,\r\n enabled: raw?.enabled === true,\r\n })\r\n const token = decision.token === 'new' ? nextRouteToken++ : routeStates.get(provider)!.token\r\n if (decision.clearLastUse) {\r\n lastUse.delete(provider)\r\n forgetChecks(provider)\r\n }\r\n routeStates.set(provider, { fingerprint, enabled: raw?.enabled === true, token })\r\n }\r\n pruneCheckCache()\r\n // Retire the previous table only after the new one is live, so an in-flight\r\n // stream keeps a dispatcher that still works.\r\n void closeTable(previous)\r\n return Promise.resolve()\r\n }\r\n\r\n let rebuildQueue = Promise.resolve()\r\n const enqueueRebuild = (): Promise<void> => {\r\n if (closed) return Promise.resolve()\r\n // The table build is synchronous; commit immediately to preserve apply()'s\r\n // long-standing \"catalog is usable as soon as apply returns\" contract.\r\n // `rebuildQueue` still records the completion for disposal ordering.\r\n try {\r\n const done = rebuild()\r\n rebuildQueue = rebuildQueue.then(() => done).catch(() => undefined)\r\n return done\r\n } catch (error) {\r\n const failed = Promise.reject(error)\r\n rebuildQueue = failed.catch(() => undefined)\r\n return failed\r\n }\r\n }\r\n\r\n enqueueRebuild()\r\n\r\n /**\r\n * The provider catalogue, read from `ctx.llm` where it is actually available.\r\n *\r\n * The browser has no LLM service in this release, so the page cannot ask for\r\n * this list itself. Serving it from the Host is the supported path: the\r\n * `webServer` service is confirmed live, and the shipped dsh-llm-retry-settings\r\n * registers its routes the same way.\r\n */\r\n const catalog = (): { providers: { id: string; name: string; live: boolean }[] } => {\r\n const live = new Set<string>()\r\n const out: { id: string; name: string; live: boolean }[] = []\r\n const seen = new Set<string>()\r\n try {\r\n for (const entry of ctx.llm?.listProviders?.() ?? []) {\r\n const id = entry?.id\r\n if (typeof id !== 'string' || id.length === 0) continue\r\n live.add(id)\r\n if (seen.has(id)) continue\r\n seen.add(id)\r\n const name = typeof entry?.name === 'string' && entry.name.length > 0 ? entry.name : id\r\n out.push({ id, name, live: true })\r\n }\r\n } catch {\r\n // no llm service in this composition\r\n }\r\n try {\r\n for (const entry of ctx.llm?.listConfigurableProviders?.() ?? []) {\r\n const id = entry?.provider\r\n if (typeof id !== 'string' || id.length === 0) continue\r\n const name =\r\n typeof entry.displayName === 'string' && entry.displayName.length > 0 ? entry.displayName : id\r\n const existing = out.find(row => row.id === id)\r\n if (existing === undefined) out.push({ id, name, live: live.has(id) })\r\n else existing.name = name\r\n }\r\n } catch {\r\n // ignore\r\n }\r\n // The reserved route rides in the provider dictionary, so its card and its\r\n // settings write path are the ordinary ones; publishing a row is what lets\r\n // the page render it without a special case. It appears only when the web\r\n // service actually exists \u2014 otherwise there is nothing for it to route.\r\n if (webAvailable && out.every(row => row.id !== WEB_SEARCH_KEY)) {\r\n out.push({ id: WEB_SEARCH_KEY, name: 'Web \u641C\u7D22', live: true })\r\n }\r\n out.sort((a, b) => a.name.localeCompare(b.name))\r\n return { providers: out }\r\n }\r\n\r\n // The page reads this same-origin JSON endpoint for the provider list. Mounted\r\n // inside an optional child so a composition without a web server still runs.\r\n ctx.inject?.(['webServer'], (wctx: any) => {\r\n try {\r\n wctx?.webServer?.register?.({\r\n kind: 'exact',\r\n path: '/dsh-provider-proxy/providers',\r\n handler: (_req: unknown, res: any) => {\r\n try {\r\n const text = JSON.stringify({\r\n ...catalog(),\r\n problems: Object.fromEntries(\r\n [...problems].map(([id, message]) => [id, bareMessage(message)]),\r\n ),\r\n hits: Object.fromEntries(hits),\r\n lastUse: Object.fromEntries(lastUse),\r\n })\r\n res.writeHead(200, {\r\n 'content-type': 'application/json; charset=utf-8',\r\n 'cache-control': 'no-store',\r\n 'content-length': Buffer.byteLength(text),\r\n })\r\n res.end(text)\r\n } catch (error) {\r\n res.writeHead(500, { 'content-type': 'application/json' })\r\n res.end(JSON.stringify({ providers: [], error: String(error) }))\r\n }\r\n },\r\n })\r\n\r\n // Connection self-check: one request through the provider's own dispatcher.\r\n // POST-only, the provider must be in the LIVE table, and at most one check\r\n // per provider is in flight \u2014 so this cannot become an outbound amplifier.\r\n wctx?.webServer?.register?.({\r\n kind: 'exact',\r\n path: '/dsh-provider-proxy/test',\r\n handler: (req: any, res: any) => {\r\n // One response per request, whatever arrives later: an aborted\r\n // connection can fire 'error', and a body that was already refused can\r\n // still be followed by 'end'.\r\n let replied = false\r\n const send = (status: number, payload: unknown): void => {\r\n if (replied) return\r\n replied = true\r\n const text = JSON.stringify(payload)\r\n res.writeHead(status, {\r\n 'content-type': 'application/json; charset=utf-8',\r\n 'cache-control': 'no-store',\r\n 'content-length': Buffer.byteLength(text),\r\n })\r\n res.end(text)\r\n }\r\n if (req?.method !== 'POST') {\r\n send(405, { ok: false, kind: 'method', error: '\u81EA\u68C0\u7AEF\u70B9\u53EA\u63A5\u53D7 POST' })\r\n return\r\n }\r\n if (typeof req.on !== 'function') {\r\n send(400, { ok: false, kind: 'body', error: '\u65E0\u6CD5\u8BFB\u53D6\u8BF7\u6C42\u4F53' })\r\n return\r\n }\r\n let bytes = 0\r\n const chunks: Buffer[] = []\r\n req.on('data', (chunk: Buffer) => {\r\n if (replied) return\r\n bytes += chunk.length\r\n // The body is one provider id. Anything larger is not a caller this\r\n // endpoint serves, and buffering it would be a free memory sink on a\r\n // webServer deployments may bind beyond loopback. The rest of the\r\n // stream is discarded rather than read.\r\n if (bytes > MAX_REQUEST_BYTES) {\r\n send(413, {\r\n ok: false,\r\n kind: 'body',\r\n error: `\u8BF7\u6C42\u4F53\u8D85\u8FC7 ${MAX_REQUEST_BYTES} \u5B57\u8282\u4E0A\u9650`,\r\n })\r\n return\r\n }\r\n chunks.push(chunk)\r\n })\r\n req.on('error', () => send(400, { ok: false, kind: 'body', error: '\u8BFB\u53D6\u8BF7\u6C42\u4F53\u5931\u8D25' }))\r\n req.on('end', () => {\r\n if (replied) return\r\n void (async () => {\r\n let provider: unknown\r\n try {\r\n const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')\r\n provider = (parsed as { provider?: unknown })?.provider\r\n } catch {\r\n send(400, { ok: false, kind: 'body', error: '\u8BF7\u6C42\u4F53\u4E0D\u662F\u5408\u6CD5 JSON' })\r\n return\r\n }\r\n if (typeof provider !== 'string' || provider.length === 0) {\r\n send(400, { ok: false, kind: 'body', error: '\u7F3A\u5C11 provider' })\r\n return\r\n }\r\n // Every input the check's ANSWER depends on, so the cooldown below\r\n // cannot hand back a result that belonged to a DIFFERENT\r\n // configuration. Without this, a user who tests, sees a failure,\r\n // fixes the port, and re-tests within the cooldown would be shown\r\n // the pre-fix result and think the fix did nothing.\r\n const key = `${provider}\\u0000${selfCheckKey(provider)}`\r\n let pending = selfChecks.get(key)\r\n if (pending === undefined) {\r\n pruneCheckCache()\r\n const last = lastChecks.get(provider)?.get(checkKeyOf(provider, key))\r\n if (last !== undefined && Date.now() - last.at < SELF_CHECK_COOLDOWN_MS) {\r\n send(200, { ...last.result, cached: true })\r\n return\r\n }\r\n const checkToken = routeStates.get(provider)?.token\r\n pending = runSelfCheck(provider).then(result => {\r\n // A provider deleted while its check was in flight must not\r\n // resurrect a cache entry under the same id.\r\n if (checkToken !== undefined && routeStates.get(provider)?.token === checkToken) {\r\n rememberCheck(provider, key, result)\r\n }\r\n return result\r\n })\r\n selfChecks.set(key, pending)\r\n void pending.finally(() => {\r\n if (selfChecks.get(key) === pending) selfChecks.delete(key)\r\n })\r\n }\r\n send(200, await pending)\r\n })().catch((error: unknown) => {\r\n send(500, { ok: false, kind: 'internal', error: String(error) })\r\n })\r\n })\r\n },\r\n })\r\n } catch (error) {\r\n // The page degrades to whatever is already configured.\r\n void error\r\n }\r\n })\r\n\r\n // `web_search` reaches the network with a bare global `fetch`, and `ctx.web`\r\n // exposes no waterfall to hook. Wrapping the service METHOD is therefore the\r\n // only seam. Entering the router scope around the call is enough \u2014 the scope\r\n // propagates through `await`, and the search is await-to-completion rather than\r\n // a lazily-consumed stream, so no per-iterator wrapping is needed here.\r\n //\r\n // Two preconditions make this work, and a future provider could break either:\r\n // the tool accesses `ctx.web.search` afresh on every call (no early\r\n // destructure), and the provider's `search()` awaits to completion.\r\n ctx.inject?.(['web'], (wctx: any) => {\r\n const web = wctx?.web\r\n if (web === undefined || typeof web.search !== 'function') return\r\n webAvailable = true\r\n const original = web.search\r\n const patched = function (this: unknown, request: unknown, signal?: unknown): unknown {\r\n const route = current.get(WEB_SEARCH_KEY)\r\n if (route === undefined) return original.call(this, request, signal)\r\n const token = routeStates.get(WEB_SEARCH_KEY)?.token\r\n if (token === undefined) return original.call(this, request, signal)\r\n return router.run(\r\n {\r\n dispatcher: route.dispatcher,\r\n onHit: () => bump(WEB_SEARCH_KEY, token),\r\n onSettle: settle(WEB_SEARCH_KEY, token),\r\n decide: route.decide,\r\n },\r\n () => original.call(this, request, signal),\r\n )\r\n }\r\n web.search = patched\r\n // Restore on dispose: `ctx.web` is a Cordis traceable proxy, so READING\r\n // `web.search` returns a fresh wrapper every time and `web.search === patched`\r\n // can never be true \u2014 a guard written that way never fires. The own property\r\n // is the only place the installed function is actually observable, and\r\n // deleting it is the real restore: it drops our property and lets the\r\n // prototype method show through, where reassigning would leave an own\r\n // property shadowing the prototype forever.\r\n //\r\n // A plugin that wrapped the method AFTER us installed its own property, so\r\n // this guard deliberately leaves that wrapper in place.\r\n const registerEffect = typeof wctx?.effect === 'function' ? wctx.effect.bind(wctx) : ctx.effect?.bind(ctx)\r\n registerEffect?.(() => () => {\r\n if (Object.getOwnPropertyDescriptor(web, 'search')?.value === patched) delete web.search\r\n })\r\n })\r\n\r\n ctx.effect(() => {\r\n const stop = ctx.on(\r\n 'llm/stream',\r\n (options: { provider?: string }, next: () => AsyncIterable<unknown>) => {\r\n const provider = options?.provider\r\n if (typeof provider !== 'string') return next()\r\n const route = current.get(provider)\r\n if (route === undefined) return next()\r\n const token = routeStates.get(provider)?.token\r\n if (token === undefined) return next()\r\n // The stream is consumed lazily; wrap it so the scope survives. The hit\r\n // counter rides inside the scope, so an abandoned stream still counts.\r\n return router.wrap(\r\n {\r\n dispatcher: route.dispatcher,\r\n onHit: () => bump(provider, token),\r\n onSettle: settle(provider, token),\r\n decide: route.decide,\r\n },\r\n next as () => AsyncIterable<unknown>,\r\n )\r\n },\r\n { global: true },\r\n )\r\n\r\n const onConfig = (): void => {\r\n void enqueueRebuild()\r\n }\r\n ctx.on('loader/volatile-update', onConfig, { global: true })\r\n\r\n return async () => {\r\n stop()\r\n if (closed) return\r\n closed = true\r\n await rebuildQueue.catch(() => undefined)\r\n await closeTable(current)\r\n current = new Map()\r\n router.release()\r\n }\r\n }, 'dsh-provider-proxy: provider-scoped proxy routing')\r\n\r\n // Diagnostics, exported for the Host log and for tests. Never includes a\r\n // password: `proxyOrigin` is the sanitized origin only.\r\n Object.defineProperty(ctx, 'providerProxyState', {\r\n configurable: true,\r\n get: () => ({\r\n routes: [...current.values()].map(entry => ({\r\n provider: entry.provider,\r\n proxyOrigin: entry.proxyOrigin,\r\n })),\r\n problems: Object.fromEntries(problems),\r\n hits: Object.fromEntries(hits),\r\n lastUse: Object.fromEntries(lastUse),\r\n selfCheckCache: (() => {\r\n let expiredEntries = 0\r\n let maxPerProvider = 0\r\n let totalEntries = 0\r\n for (const entries of lastChecks.values()) {\r\n totalEntries += entries.size\r\n maxPerProvider = Math.max(maxPerProvider, entries.size)\r\n for (const entry of entries.values()) {\r\n if (Date.now() - entry.at >= SELF_CHECK_COOLDOWN_MS) expiredEntries += 1\r\n }\r\n }\r\n return {\r\n providers: lastChecks.size,\r\n pending: selfChecks.size,\r\n expiredEntries,\r\n totalEntries,\r\n maxPerProvider,\r\n }\r\n })(),\r\n }),\r\n })\r\n}\r\n\r\nexport { acquireFetchRouter } from './fetch-router.js'\r\nexport {\r\n buildRouteEntry,\r\n createProxyTable,\r\n closeTable,\r\n proxyUrl,\r\n routeFingerprint,\r\n routeStateDecision,\r\n} from './proxy-table.js'\r\nexport { Config, ProviderProxyRoute, normalizeRoute, normalizeDefaultProxy, PROTOCOLS } from './config.js'\r\nexport { defaultProxyProblem, proxyHostProblem } from './proxy-address.js'\r\nexport { deadRuleEntries, hostMatches, hostRuleProblem, parseHostList, splitHostRules } from './host-rules.js'\r\n", "/**\r\n * Provider-scoped fetch routing.\r\n *\r\n * DeepSeek Harness 0.2.0-rc.2 offers no supported seam for giving one LLM\r\n * provider its own transport:\r\n *\r\n * - `llm-deepseek` calls the unqualified global `fetch` with no `dispatcher`;\r\n * - `llm-pi-ai` delegates to the pi-ai SDK, whose HTTP layer DSH cannot\r\n * configure (its own source notes a fetch/dispatcher hook does not exist);\r\n * - `LlmCallControls` carries only reasoningEffort/temperature/maxTokens/stop;\r\n * - `llm/stream` intercepts already-decoded `StreamChunk`s, i.e. after HTTP;\r\n * - `ctx.web` serves `web_search`/`web_fetch` only, never provider traffic;\r\n * - the official `@deepseek-ai/dsh-http-proxy` is a library with a private\r\n * installer: one process-wide policy from env vars, no service, no Config.\r\n *\r\n * So the request is routed where the only available signal actually is: the\r\n * `llm/stream` waterfall, whose `options.provider` names the route. An\r\n * AsyncLocalStorage scope carries the chosen dispatcher over the stream, and a\r\n * thin `globalThis.fetch` wrapper applies it. Because every provider gets its\r\n * OWN dispatcher instance, one provider's proxy can never be picked up by\r\n * another provider's call \u2014 including two providers that resolve to the same\r\n * upstream host.\r\n *\r\n * IMPORTANT \u2014 one undici realm only. Node's built-in `fetch` uses an internal\r\n * undici and REJECTS a dispatcher built by the npm `undici` package with\r\n * `invalid onRequestStart method`, and vice versa. Every dispatcher here is\r\n * built from the npm `undici` that this module imports, so the wrapper must\r\n * dispatch through THAT same package's `fetch` rather than re-entering Node's.\r\n * The proxy therefore receives an absolute-form request line\r\n * (`GET http://host/path HTTP/1.1`), which is how an HTTP forward proxy is\r\n * addressed; an `https:` target is tunnelled with CONNECT.\r\n *\r\n * In-flight streams keep the dispatcher they started on; a configuration\r\n * change only affects new requests.\r\n */\r\n\r\nimport { AsyncLocalStorage } from 'node:async_hooks'\r\nimport { fetch as undiciFetch } from 'undici'\r\n\r\n/** Undici dispatcher, kept structurally typed so this file needs no undici types. */\r\nexport interface DispatcherLike {\r\n close(): Promise<void>\r\n}\r\n\r\nexport interface RouterStore {\r\n dispatcher: DispatcherLike\r\n /** Called once per request that actually leaves through the proxy. */\r\n onHit?: () => void\r\n /**\r\n * Called once the request is ANSWERED \u2014 a response arrives, or it fails\r\n * outright.\r\n *\r\n * \"Answered\" is the point at which `fetch` resolves, i.e. response HEADERS,\r\n * NOT the end of the body. `ok` therefore means \"a response below 500 came\r\n * back\", exactly as the connection self-check reads it; it does NOT mean the\r\n * whole stream ran to completion. A body cut off mid-transfer still reads ok,\r\n * and that is deliberate: the body is a lazily-consumed stream a proxy must\r\n * forward without draining, so its end is not observable here. The card's\r\n * \"last ok\" carries that same meaning.\r\n *\r\n * `detail` is the response on success, or the raw error on failure \u2014 left\r\n * unclassified so the caller can name the failure with whatever error\r\n * vocabulary it already has.\r\n */\r\n onSettle?: (ok: boolean, detail: unknown) => void\r\n /**\r\n * Decide whether one request is proxied or sent directly, given its target\r\n * host (`undefined` when the input carries no parsable URL). Absent means\r\n * \"always proxy within this scope\".\r\n */\r\n decide?: (host: string | undefined) => 'proxy' | 'direct'\r\n}\r\n\r\n/** Shared across every plugin instance in one process, keyed so copies cooperate. */\r\nconst STATE_KEY = Symbol.for('dsh-provider-proxy.fetch-router.v1')\r\n\r\ninterface RouterState {\r\n owners: number\r\n storage: AsyncLocalStorage<RouterStore>\r\n originalFetch: typeof globalThis.fetch\r\n routedFetch: typeof globalThis.fetch\r\n descriptor?: PropertyDescriptor\r\n}\r\n\r\n/**\r\n * The host a fetch input targets, or `undefined` when it carries none.\r\n *\r\n * `new URL` THROWS on a relative or malformed input instead of returning\r\n * `undefined`, so every branch is guarded; an unparsable input falls through to\r\n * `undefined`, and the scope's `decide` decides what that means (the plugin's\r\n * route treats it as \"keep proxying\", i.e. fail-closed).\r\n */\r\nfunction requestHost(input: unknown): string | undefined {\r\n try {\r\n if (typeof input === 'string') return new URL(input).hostname\r\n if (input instanceof URL) return input.hostname\r\n const url = (input as { url?: unknown } | null | undefined)?.url\r\n if (typeof url === 'string') return new URL(url).hostname\r\n } catch {\r\n return undefined\r\n }\r\n return undefined\r\n}\r\n\r\nfunction installSharedRouter(): RouterState {\r\n const current = (globalThis as Record<symbol, RouterState | undefined>)[STATE_KEY]\r\n if (current !== undefined) {\r\n current.owners += 1\r\n return current\r\n }\r\n\r\n if (typeof globalThis.fetch !== 'function') {\r\n throw new Error('dsh-provider-proxy: this Node runtime does not expose global fetch')\r\n }\r\n\r\n const storage = new AsyncLocalStorage<RouterStore>()\r\n const originalFetch = globalThis.fetch\r\n const descriptor = Object.getOwnPropertyDescriptor(globalThis, 'fetch')\r\n\r\n const routedFetch = function routedFetch(\r\n this: unknown,\r\n input: Parameters<typeof globalThis.fetch>[0],\r\n init?: Parameters<typeof globalThis.fetch>[1],\r\n ): ReturnType<typeof globalThis.fetch> {\r\n const active = storage.getStore()\r\n // No scope, or a caller that already picked a dispatcher: stay out of the way.\r\n if (active === undefined) return originalFetch.call(globalThis, input, init)\r\n if (init !== undefined && init !== null && (init as { dispatcher?: unknown }).dispatcher !== undefined) {\r\n return originalFetch.call(globalThis, input, init)\r\n }\r\n // A `direct` verdict from the route's target-host rules keeps the native\r\n // path, exactly as if there were no scope at all.\r\n if (active.decide !== undefined && active.decide(requestHost(input)) === 'direct') {\r\n return originalFetch.call(globalThis, input, init)\r\n }\r\n // Counted at INITIATION: the request is about to cross the proxy. A stream\r\n // abandoned later still counts, which is the documented semantics.\r\n active.onHit?.()\r\n // Same undici realm as the dispatcher \u2014 Node's own fetch would reject it.\r\n // The init is passed through structurally: the DOM `RequestInit` and the\r\n // undici one disagree on `body`/`duplex`, so both are erased here.\r\n const inFlight = undiciFetch(input as never, {\r\n ...(init as Record<string, unknown> | undefined),\r\n dispatcher: active.dispatcher as never,\r\n } as never) as unknown as Promise<{ status: number }>\r\n if (active.onSettle !== undefined) {\r\n const settle = active.onSettle\r\n // Observe the reply without changing the caller's promise: the handlers\r\n // hang off a DERIVED promise, both arms are handled here so nothing can\r\n // surface as an unhandled rejection, and the original is returned as-is.\r\n // This fires when `fetch` resolves \u2014 response HEADERS \u2014 not when the body\r\n // ends; see `onSettle`.\r\n void inFlight\r\n .then(\r\n response => settle(response.status < 500, response),\r\n (error: unknown) => settle(false, error),\r\n )\r\n .catch(() => undefined)\r\n }\r\n return inFlight as never\r\n }\r\n\r\n Object.defineProperty(globalThis, 'fetch', {\r\n ...(descriptor ?? { configurable: true, enumerable: true, writable: true }),\r\n value: routedFetch,\r\n })\r\n\r\n const state: RouterState = { owners: 1, storage, originalFetch, routedFetch, descriptor }\r\n Object.defineProperty(globalThis, STATE_KEY, {\r\n configurable: true,\r\n value: state,\r\n })\r\n return state\r\n}\r\n\r\n/**\r\n * Re-apply the AsyncLocalStorage scope to every iterator operation.\r\n *\r\n * This is essential, not cosmetic: an adapter's stream is consumed lazily, so\r\n * the HTTP call typically happens inside a later `next()`, long after\r\n * `als.run(...)` returned. Without wrapping the iterator, every request would\r\n * silently fall back to the default dispatcher.\r\n */\r\nfunction contextualIterable(\r\n storage: AsyncLocalStorage<RouterStore>,\r\n store: RouterStore,\r\n factory: () => AsyncIterable<unknown>,\r\n): AsyncIterable<unknown> {\r\n return {\r\n [Symbol.asyncIterator]() {\r\n let iterator: AsyncIterator<unknown> | undefined\r\n\r\n const ensureIterator = (): AsyncIterator<unknown> => {\r\n if (iterator !== undefined) return iterator\r\n const iterable = factory()\r\n if (iterable === null || typeof iterable?.[Symbol.asyncIterator] !== 'function') {\r\n throw new TypeError('dsh-provider-proxy: llm/stream next() did not return an AsyncIterable')\r\n }\r\n iterator = iterable[Symbol.asyncIterator]()\r\n return iterator\r\n }\r\n\r\n const invoke = (method: 'next' | 'return' | 'throw', value?: unknown): Promise<IteratorResult<unknown>> =>\r\n storage.run(store, () => {\r\n // A stream abandoned before its first next() must not touch the adapter.\r\n if (method === 'return' && iterator === undefined) return Promise.resolve({ done: true, value })\r\n if (method === 'throw' && iterator === undefined) return Promise.reject(value)\r\n const target = ensureIterator()\r\n const operation = target[method]\r\n if (typeof operation !== 'function') {\r\n if (method === 'return') return Promise.resolve({ done: true, value })\r\n return Promise.reject(value)\r\n }\r\n return Promise.resolve(Reflect.apply(operation, target, method === 'next' ? [] : [value]))\r\n })\r\n\r\n return {\r\n next: (value?: unknown) => invoke('next', value),\r\n return: (value?: unknown) => invoke('return', value),\r\n throw: (value?: unknown) => invoke('throw', value),\r\n [Symbol.asyncIterator]() {\r\n return this\r\n },\r\n }\r\n },\r\n }\r\n}\r\n\r\nexport interface FetchRouter {\r\n /** Run one synchronous callback inside the scope. */\r\n run(store: RouterStore, callback: () => unknown): unknown\r\n /** Wrap a lazy stream so every consumption step keeps the scope. */\r\n wrap(store: RouterStore, factory: () => AsyncIterable<unknown>): AsyncIterable<unknown>\r\n /** Release this holder; the shim is removed once the last holder releases. */\r\n release(): void\r\n}\r\n\r\n/** Install (or share) the single process-wide fetch shim. */\r\nexport function acquireFetchRouter(): FetchRouter {\r\n const state = installSharedRouter()\r\n let released = false\r\n\r\n return {\r\n run(store, callback) {\r\n return state.storage.run(store, callback)\r\n },\r\n wrap(store, factory) {\r\n return contextualIterable(state.storage, store, factory)\r\n },\r\n release() {\r\n if (released) return\r\n released = true\r\n state.owners -= 1\r\n if (state.owners !== 0) return\r\n\r\n if (globalThis.fetch === state.routedFetch) {\r\n if (state.descriptor === undefined) delete (globalThis as { fetch?: unknown }).fetch\r\n else Object.defineProperty(globalThis, 'fetch', state.descriptor)\r\n }\r\n delete (globalThis as Record<symbol, unknown>)[STATE_KEY]\r\n state.storage.disable()\r\n },\r\n }\r\n}", "/**\r\n * The proxy table: one dispatcher per enabled provider.\r\n *\r\n * A dispatcher is created per provider rather than shared, so a proxied\r\n * provider can never leak its transport into another provider's call even when\r\n * both resolve to the same upstream host.\r\n *\r\n * Two transports are supported, and they come from the SAME npm undici instance\r\n * (the build leaves `undici` external), which is what lets both be handed to\r\n * `undiciFetch` by the router:\r\n *\r\n * - `http`/`https` \u2192 `ProxyAgent`, which speaks HTTP CONNECT to an HTTP proxy;\r\n * - `socks5` \u2192 `Socks5ProxyAgent`, undici's built-in RFC 1928/1929 client,\r\n * which tunnels the target instead of forwarding to it.\r\n */\r\n\r\nimport { ProxyAgent, Socks5ProxyAgent } from 'undici'\r\n\r\nimport {\r\n normalizeDefaultProxy,\r\n normalizeRoute,\r\n type DefaultProxyValue,\r\n type ProviderProxyRouteValue,\r\n} from './config.js'\r\nimport { hostMatches, normalizeHostRule, parseHostList } from './host-rules.js'\r\nimport { defaultProxyProblem } from './proxy-address.js'\r\nimport type { DispatcherLike } from './fetch-router.js'\r\n\r\nexport interface RouteEntry {\r\n provider: string\r\n /** Normalized proxy origin, for diagnostics only. Never logged with credentials. */\r\n proxyOrigin: string\r\n dispatcher: DispatcherLike\r\n /** Whether one request's target host goes through the proxy or stays direct. */\r\n decide: (host: string | undefined) => 'proxy' | 'direct'\r\n /**\r\n * This route's self-check target: a URL, or '' to use the top-level `testUrl`.\r\n * Only the self-check reads it; a bad value fails a check, never a route.\r\n */\r\n testTarget: string\r\n}\r\n\r\n/** The routing inputs that make one route's `lastUse` meaningful. */\r\nexport interface RouteFingerprintInput {\r\n enabled?: boolean\r\n useDefault?: boolean\r\n protocol?: string\r\n host?: string\r\n port?: number\r\n username?: string\r\n password?: string\r\n onlyHosts?: string\r\n bypassHosts?: string\r\n localDirect?: boolean\r\n}\r\n\r\n/** Stable, non-secret representation of the rule set in one route. */\r\nfunction normalizedRuleSet(raw: string | undefined): string[] {\r\n const rules = (raw ?? '')\r\n .split(/[,\\s]+/)\r\n .map(normalizeHostRule)\r\n .filter(entry => entry.length > 0)\r\n return [...new Set(rules)].sort()\r\n}\r\n\r\n/**\r\n * A pure fingerprint of everything that decides where a route's traffic goes.\r\n *\r\n * `enabled` and the self-check target are deliberately absent: switching a route\r\n * off does not invalidate its last result, and a probe URL cannot change real\r\n * traffic. Host-rule lists are ordered SETS, so reordering or deduplicating a\r\n * list must not clear the card's health record.\r\n */\r\nexport function routeFingerprint(input: RouteFingerprintInput): string {\r\n return JSON.stringify([\r\n input.protocol ?? 'http',\r\n String(input.host ?? '').trim(),\r\n input.port ?? 0,\r\n String(input.username ?? '').trim(),\r\n input.password ?? '',\r\n normalizedRuleSet(input.onlyHosts),\r\n normalizedRuleSet(input.bypassHosts),\r\n input.localDirect !== false,\r\n ])\r\n}\r\n\r\nexport interface RouteState {\r\n fingerprint: string\r\n enabled: boolean\r\n token: number\r\n}\r\n\r\n/**\r\n * Whether a config diff allocates a fresh token and/or clears `lastUse`.\r\n *\r\n * Kept pure so the token rules can be tested without a dispatcher or a live\r\n * config. The caller owns the global monotonically increasing token counter.\r\n */\r\nexport function routeStateDecision(\r\n previous: Pick<RouteState, 'fingerprint' | 'enabled' | 'token'> | undefined,\r\n next: Pick<RouteState, 'fingerprint' | 'enabled'>,\r\n): { token: 'new' | 'keep'; clearLastUse: boolean } {\r\n if (previous === undefined) return { token: 'new', clearLastUse: false }\r\n if (previous.fingerprint !== next.fingerprint) return { token: 'new', clearLastUse: true }\r\n if (previous.enabled !== next.enabled) return { token: 'new', clearLastUse: false }\r\n return { token: 'keep', clearLastUse: false }\r\n}\r\n\r\nfunction proxyUrl(route: ProviderProxyRouteValue): string {\r\n // A colon in the username stays percent-encoded (%3A), never rewritten to a\r\n // literal ':'. A WHATWG URL splits userinfo at the FIRST literal colon, so a\r\n // literal one coming from a name like `a:b` would be misread as the password\r\n // separator (`a` + password `b`); keeping it encoded is exactly what lets\r\n // undici's decodeURIComponent restore the real name. Earlier code rewrote %3A\r\n // back to ':' \u2014 that was subtly wrong.\r\n //\r\n // HTTP/HTTPS carry credentials in the userinfo, which undici turns into a\r\n // Proxy-Authorization header. SOCKS5 embeds the USERNAME only: its password is\r\n // handed to Socks5ProxyAgent as an option, so it never enters this string (nor\r\n // the credential-free origin derived from it).\r\n const credentials =\r\n route.username.length === 0\r\n ? ''\r\n : route.password.length > 0 && route.protocol !== 'socks5'\r\n ? `${encodeURIComponent(route.username)}:${encodeURIComponent(route.password)}@`\r\n : `${encodeURIComponent(route.username)}@`\r\n // IPv6 literals need brackets in a URL authority.\r\n const host = route.host.includes(':') && !route.host.startsWith('[') ? `[${route.host}]` : route.host\r\n return `${route.protocol}://${credentials}${host}:${route.port}`\r\n}\r\n\r\n/**\r\n * A credential-free origin, for diagnostics only.\r\n *\r\n * `new URL(url).origin` is NOT usable for socks5: socks5 is a non-special\r\n * scheme, and WHATWG URL serializes the origin of a non-special scheme as the\r\n * string `'null'` (the same rule that made `gopher` return `'null'` in Node\r\n * 15). That value is surfaced verbatim in `ctx.providerProxyState` and in the\r\n * settings page's diagnostics, so it would hide which proxy a SOCKS5 provider\r\n * is using. HTTP keeps using `.origin`, which is what it already did.\r\n *\r\n * Credentials are never part of this string: it is built from host and port.\r\n */\r\nfunction displayOrigin(route: ProviderProxyRouteValue, url: string): string {\r\n if (route.protocol !== 'socks5') return new URL(url).origin\r\n const host = route.host.includes(':') && !route.host.startsWith('[') ? `[${route.host}]` : route.host\r\n return `${route.protocol}://${host}:${route.port}`\r\n}\r\n\r\n/**\r\n * Build the dispatcher for one route.\r\n *\r\n * SOCKS5 authentication is passed as options rather than through the URL so the\r\n * password never appears in the proxy address. `Socks5ProxyAgent` also accepts\r\n * userinfo in the URL, but `proxyUrl()` already emits the username there for\r\n * the HTTP case, and the explicit option takes precedence \u2014 so the password\r\n * stays out of the string that is logged and reported.\r\n */\r\nfunction createDispatcher(\r\n route: ProviderProxyRouteValue,\r\n url: string,\r\n password: string,\r\n): DispatcherLike {\r\n if (route.protocol === 'socks5') {\r\n const auth: { username?: string; password?: string } = {}\r\n if (route.username.length > 0) auth.username = route.username\r\n if (password.length > 0) auth.password = password\r\n return new Socks5ProxyAgent(url, auth) as unknown as DispatcherLike\r\n }\r\n return new ProxyAgent({ uri: url }) as unknown as DispatcherLike\r\n}\r\n\r\n/**\r\n * Whether a target host is loopback or on a private network.\r\n *\r\n * Such a target is almost always a relay running on the same machine (LiteLLM,\r\n * Ollama, a local mock), which a forward proxy cannot reach at all \u2014 forcing it\r\n * through one fails, and the failure reads as \"the proxy is broken\". Sending it\r\n * direct is the only answer that can work.\r\n *\r\n * Matched by ADDRESS, not by the domain-suffix matcher above: `192.168.1.5` is\r\n * not a suffix of anything, so `hostMatches` cannot express these rules.\r\n */\r\nfunction isLocalHost(host: string): boolean {\r\n // WHATWG URL keeps an IPv6 literal bracketed (`[::1]`), so strip first.\r\n const bare = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host\r\n if (bare === 'localhost' || bare.endsWith('.localhost')) return true\r\n if (bare === '::1') return true\r\n\r\n const octets = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(bare)\r\n if (octets === null) return false\r\n const [a, b, c, d] = octets.slice(1).map(Number)\r\n if (a > 255 || b > 255 || c > 255 || d > 255) return false\r\n if (a === 127) return true // 127.0.0.0/8 \u2014 loopback\r\n if (a === 10) return true // 10.0.0.0/8 \u2014 private\r\n if (a === 192 && b === 168) return true // 192.168.0.0/16 \u2014 private\r\n if (a === 169 && b === 254) return true // 169.254.0.0/16 \u2014 link-local\r\n if (a === 172 && b >= 16 && b <= 31) return true // 172.16.0.0/12 \u2014 private\r\n return false\r\n}\r\n\r\n/**\r\n * Build the proxy/direct decision for one route.\r\n *\r\n * FAIL-CLOSED: an enabled route proxies by default, and only explicit exceptions\r\n * send a request direct \u2014 a loopback/private target (when `localDirect` is on),\r\n * a `bypassHosts` match, and an `onlyHosts` list that does not cover the target.\r\n * A target whose host cannot be parsed (`undefined`) stays on the proxy, so a\r\n * malformed URL cannot quietly leak a credentialed request.\r\n */\r\nfunction buildDecide(\r\n route: ProviderProxyRouteValue,\r\n localDirect: boolean,\r\n): (host: string | undefined) => 'proxy' | 'direct' {\r\n const only = parseHostList(route.onlyHosts)\r\n const bypass = parseHostList(route.bypassHosts)\r\n return host => {\r\n if (host === undefined) return 'proxy'\r\n if (localDirect && isLocalHost(host)) return 'direct'\r\n if (hostMatches(host, bypass)) return 'direct'\r\n if (only.length > 0 && !hostMatches(host, only)) return 'direct'\r\n return 'proxy'\r\n }\r\n}\r\n\r\n/**\r\n * Apply the shared default endpoint to one route that opted into it.\r\n *\r\n * Only the TRANSPORT fields move; `onlyHosts`/`bypassHosts`/`testTarget` stay the\r\n * route's own, because they describe that provider's traffic, not the proxy. The\r\n * merge happens AFTER the endpoint is proven usable, so a route can never be\r\n * silently downgraded to its own (empty) fields while the user believes it is\r\n * using the default.\r\n */\r\nfunction withDefaultProxy(\r\n route: Partial<ProviderProxyRouteValue>,\r\n defaultProxy: DefaultProxyValue,\r\n): Partial<ProviderProxyRouteValue> {\r\n return {\r\n ...route,\r\n protocol: defaultProxy.protocol,\r\n host: defaultProxy.host,\r\n port: defaultProxy.port,\r\n username: defaultProxy.username,\r\n password: defaultProxy.password,\r\n }\r\n}\r\n\r\n/** One built route, or the reason it could not be built. */\r\nexport type RouteBuildResult =\r\n | { ok: true; entry: RouteEntry }\r\n | { ok: false; problem: string }\r\n\r\n/** Everything one route's build needs beyond its own settings. */\r\nexport interface RouteBuildOptions {\r\n /** The shared endpoint, already normalized. */\r\n defaultProxy: DefaultProxyValue\r\n /**\r\n * Forwarded to `normalizeRoute`. The table passes `true` \u2014 it skips a disabled\r\n * route before building it \u2014 while the self-check passes `false` to get exactly\r\n * the validation routing would apply once the route is switched on.\r\n */\r\n requireEnabled: boolean\r\n /** Whether loopback/private targets are sent direct; see {@link buildDecide}. */\r\n localDirect: boolean\r\n}\r\n\r\n/**\r\n * Build one route entry, or explain why it cannot be built.\r\n *\r\n * Shared by the routing table and the connection self-check ON PURPOSE: the\r\n * check must run the exact validations routing runs, or it would report a route\r\n * healthy that the table refuses \u2014 the false positive this whole feature exists\r\n * to eliminate.\r\n */\r\nexport function buildRouteEntry(\r\n provider: string,\r\n raw: Partial<ProviderProxyRouteValue>,\r\n options: RouteBuildOptions,\r\n): RouteBuildResult {\r\n let effective = raw\r\n // A route that opted into the shared endpoint takes the proxy address from it.\r\n // Checked BEFORE the merge so the refusal names the setting the user actually\r\n // has to fix \u2014 the default block \u2014 instead of the card's empty fields.\r\n if (raw?.useDefault === true) {\r\n const why = defaultProxyProblem(options.defaultProxy)\r\n if (why !== undefined) {\r\n return {\r\n ok: false,\r\n problem: `dsh-provider-proxy: provider \"${provider}\" \u542F\u7528\u4E86\u300C\u4F7F\u7528\u9ED8\u8BA4\u4EE3\u7406\u300D\uFF0C\u4F46\u9876\u5C42\u9ED8\u8BA4\u4EE3\u7406\u4E0D\u53EF\u7528\uFF1A${why}`,\r\n }\r\n }\r\n effective = withDefaultProxy(raw, options.defaultProxy)\r\n }\r\n\r\n let route: ProviderProxyRouteValue\r\n try {\r\n route = normalizeRoute(provider, effective, { requireEnabled: options.requireEnabled })\r\n } catch (error) {\r\n return { ok: false, problem: error instanceof Error ? error.message : String(error) }\r\n }\r\n\r\n // A SOCKS5 username without a password must be REFUSED, not downgraded.\r\n //\r\n // undici's Socks5Client only offers USERNAME_PASSWORD when both parts are\r\n // present (`if (options.username && options.password)`); with a username\r\n // alone it quietly advertises NO_AUTH. Against a proxy that requires\r\n // authentication the user would then be told \"Authentication failed\" \u2014 a\r\n // wrong diagnosis pointing at the proxy rather than at the missing setting.\r\n if (route.protocol === 'socks5' && route.username.length > 0 && route.password.length === 0) {\r\n return {\r\n ok: false,\r\n problem: 'dsh-provider-proxy: SOCKS5 \u914D\u7F6E\u4E86\u7528\u6237\u540D\u4F46\u6CA1\u6709\u5BC6\u7801\uFF1B\u8BF7\u8865\u5168\u5BC6\u7801\u6216\u6E05\u7A7A\u7528\u6237\u540D',\r\n }\r\n }\r\n\r\n // The mirror of the rule above, for the same reason: undici only offers\r\n // USERNAME_PASSWORD when BOTH parts are present, so a lone password is worse\r\n // than useless \u2014 the client advertises NO_AUTH. The tunnel would succeed\r\n // against an open proxy and fail against the one the credential was entered\r\n // for, which reads as \"the password is wrong\" when it was never sent.\r\n if (route.protocol === 'socks5' && route.password.length > 0 && route.username.length === 0) {\r\n return {\r\n ok: false,\r\n problem: 'dsh-provider-proxy: SOCKS5 \u914D\u7F6E\u4E86\u5BC6\u7801\u4F46\u6CA1\u6709\u7528\u6237\u540D\uFF1B\u8BF7\u8865\u5168\u7528\u6237\u540D\u6216\u6E05\u7A7A\u5BC6\u7801',\r\n }\r\n }\r\n\r\n // An HTTP/HTTPS password WITHOUT a username is refused outright: basic auth\r\n // cannot send a password alone, and silently dropping it would leave the user\r\n // believing a credential is in use when it is not. This is the symmetric\r\n // counterpart of the SOCKS5 guard above and lives on the same `problems`\r\n // path, so both mistakes are reported the same way.\r\n if (route.protocol !== 'socks5' && route.password.length > 0 && route.username.length === 0) {\r\n return {\r\n ok: false,\r\n problem: 'dsh-provider-proxy: \u914D\u7F6E\u4E86\u4EE3\u7406\u5BC6\u7801\u4F46\u6CA1\u6709\u7528\u6237\u540D\uFF1B\u8BF7\u8865\u5168\u7528\u6237\u540D\u6216\u6E05\u7A7A\u5BC6\u7801',\r\n }\r\n }\r\n\r\n // The mirror for HTTP/HTTPS, where the asymmetry is worth spelling out:\r\n // undici WOULD send `Basic base64(\"alice:\")` \u2014 a username with an EMPTY\r\n // password \u2014 so nothing is dropped and a lenient proxy accepts it. It is\r\n // refused anyway, because a half-filled credential is nearly always a\r\n // half-typed one, and \"both or neither\" is one rule to hold across all three\r\n // transports instead of \"the pairing each transport happens to carry\". The\r\n // cost is real and documented in the README: a proxy whose credential truly\r\n // has an empty password cannot be configured here.\r\n if (route.protocol !== 'socks5' && route.username.length > 0 && route.password.length === 0) {\r\n return {\r\n ok: false,\r\n problem: 'dsh-provider-proxy: \u914D\u7F6E\u4E86\u4EE3\u7406\u7528\u6237\u540D\u4F46\u6CA1\u6709\u5BC6\u7801\uFF1B\u8BF7\u8865\u5168\u5BC6\u7801\u6216\u6E05\u7A7A\u7528\u6237\u540D',\r\n }\r\n }\r\n\r\n const url = proxyUrl(route)\r\n let dispatcher: DispatcherLike\r\n try {\r\n dispatcher = createDispatcher(route, url, route.password)\r\n } catch (error) {\r\n return { ok: false, problem: error instanceof Error ? error.message : String(error) }\r\n }\r\n return {\r\n ok: true,\r\n entry: {\r\n provider,\r\n proxyOrigin: displayOrigin(route, url),\r\n dispatcher,\r\n decide: buildDecide(route, options.localDirect),\r\n testTarget: route.testTarget,\r\n },\r\n }\r\n}\r\n\r\n/** Everything the table build needs beyond the routes themselves. */\r\nexport interface ProxyTableOptions {\r\n /** The shared endpoint a route may opt into with `useDefault`. */\r\n defaultProxy?: Partial<DefaultProxyValue>\r\n /**\r\n * Whether a loopback/private target is sent direct instead of through the\r\n * proxy. Defaults to true; `undefined`/absent means \"on\".\r\n */\r\n localDirect?: boolean\r\n}\r\n\r\n/**\r\n * Build the dispatchers for every enabled, valid route.\r\n *\r\n * Invalid routes are skipped rather than thrown: one mistyped provider must not\r\n * stop the others from proxying. The caller surfaces the reason through\r\n * `problems`, which the Client shows instead of failing the whole table.\r\n *\r\n * Only an ENABLED route is carried \u2014 and, consequently, only an enabled route\r\n * is ever refused: a route nobody has switched on has not asked for anything\r\n * yet, so a half-typed endpoint on it is not a problem to report. The self-check\r\n * is what makes a disabled route buildable on demand.\r\n */\r\nexport function createProxyTable(\r\n config: { readonly [provider: string]: Partial<ProviderProxyRouteValue> } | undefined,\r\n options: ProxyTableOptions = {},\r\n): { entries: Map<string, RouteEntry>; problems: Map<string, string> } {\r\n const entries = new Map<string, RouteEntry>()\r\n const problems = new Map<string, string>()\r\n const buildOptions: RouteBuildOptions = {\r\n defaultProxy: normalizeDefaultProxy(options.defaultProxy),\r\n requireEnabled: true,\r\n localDirect: options.localDirect !== false,\r\n }\r\n\r\n for (const [provider, raw] of Object.entries(config ?? {})) {\r\n if (raw?.enabled !== true) continue\r\n const built = buildRouteEntry(provider, raw, buildOptions)\r\n if (!built.ok) problems.set(provider, built.problem)\r\n else entries.set(provider, built.entry)\r\n }\r\n\r\n return { entries, problems }\r\n}\r\n\r\n/** Close every dispatcher, ignoring individual failures. */\r\nexport async function closeTable(entries: Map<string, RouteEntry>): Promise<void> {\r\n const closing = [...entries.values()].map(entry => entry.dispatcher.close().catch(() => undefined))\r\n await Promise.allSettled(closing)\r\n entries.clear()\r\n}\r\n\r\nexport { proxyUrl }\r\n", "/**\r\n * Plugin Config.\r\n *\r\n * Shape notes, all verified against DeepSeek Harness 0.2.0-rc.2:\r\n *\r\n * - `schemastery` is NOT guaranteed to be resolvable from a profile-hoisted\r\n * install, so the real package is preferred at runtime when `createRequire`\r\n * can see it and a bundled fallback is used otherwise. The reference plugin\r\n * `dsh-llm-retry-settings` does exactly this.\r\n * - Every editable field is `.volatile()` so a settings write is committed\r\n * into the running fiber WITHOUT remounting the plugin; the Host then\r\n * rebuilds its proxy table. Ordinary (non-volatile) fields would restart the\r\n * plugin instead, which is not what a settings page wants.\r\n * - The SOCKS5 proxy password lives directly on the route as `password`, so the\r\n * settings page writes it into cordis.patch.yml in the clear. It is only ever\r\n * handed to `Socks5ProxyAgent` as an option, never embedded in the proxy URL\r\n * that is logged or shown in the diagnostics.\r\n */\r\n\r\nimport { createRequire } from 'node:module'\r\n\r\nimport { proxyHostProblem } from './proxy-address.js'\r\n\r\n// Imported statically so the bundler inlines it, making the package\r\n// self-contained. `loadSchemastery` below still PREFERS the profile's own copy\r\n// when one is reachable, so a DSH-provided instance stays authoritative; this\r\n// bundled copy is only the fallback that lets the plugin load at all.\r\nimport * as BundledSchema from '@deepseek-ai/schemastery'\r\n\r\ntype SchemaLike = {\r\n object: (...args: any[]) => any\r\n string: (...args: any[]) => any\r\n boolean: (...args: any[]) => any\r\n number: (...args: any[]) => any\r\n dict: (...args: any[]) => any\r\n union: (...args: any[]) => any\r\n}\r\n\r\n/**\r\n * Resolve the schemastery module for this fiber.\r\n *\r\n * A profile installation hoists dependencies next to the profile rather than\r\n * under this package, so a bare `import` can fail even when the Host itself\r\n * uses schemastery. `createRequire` resolves against this file's real\r\n * location, which is the best available view of the installation tree.\r\n *\r\n * When that finds nothing \u2014 a plain `npm install` of this package, which pulls\r\n * no schemastery \u2014 the BUNDLED copy is used, so the plugin still loads instead\r\n * of throwing at require time.\r\n */\r\nfunction loadSchemastery(): SchemaLike {\r\n try {\r\n const require = createRequire(import.meta.url)\r\n const candidate = require('@deepseek-ai/schemastery')\r\n const live = (candidate as { default?: SchemaLike })?.default ?? (candidate as SchemaLike)\r\n if (live && typeof live.object === 'function') return live\r\n } catch {\r\n // Fall through to the bundled copy below.\r\n }\r\n // The static import is only a fallback; what it actually exposes is decided at\r\n // runtime, which this structural type deliberately does not pin.\r\n const bundled = (BundledSchema as { default?: unknown }).default ?? BundledSchema\r\n if (typeof (bundled as SchemaLike).object === 'function') return bundled as SchemaLike\r\n throw new Error('dsh-provider-proxy: no usable @deepseek-ai/schemastery in this installation')\r\n}\r\n\r\nconst z = loadSchemastery()\r\n\r\n/** Apply `.volatile()` when the resolved schemastery supports it. */\r\nfunction vol<T>(field: T): T {\r\n const volatile = (field as { volatile?: () => unknown }).volatile\r\n return typeof volatile === 'function' ? (volatile.call(field) as T) : field\r\n}\r\n\r\n/** Forward-compatible passthrough for schemastery extensions used below. */\r\nfunction stepMin<T extends { step?: (n: number) => T; min?: (n: number) => T }>(field: T, step?: number): T {\r\n let out = field\r\n if (step !== undefined && typeof out.step === 'function') out = out.step(step)\r\n return out\r\n}\r\n\r\n/** Supported forward-proxy transports. */\r\nexport const PROTOCOLS = ['http', 'https', 'socks5'] as const\r\nexport type Protocol = (typeof PROTOCOLS)[number]\r\n\r\n/**\r\n * The shared endpoint a route may opt into with `useDefault`.\r\n *\r\n * There is deliberately NO `enabled` flag here: a default is \"configured\" when\r\n * it has a host and an in-range port, and nothing else. A second switch would\r\n * create the state \"default configured but switched off\", from which every route\r\n * that opted in would silently lose its proxy \u2014 a failure mode with no upside,\r\n * because a route opts in individually with `useDefault` and can be switched off\r\n * on its own card.\r\n */\r\nexport const DefaultProxy = z.object({\r\n protocol: z.union(PROTOCOLS).default('http'),\r\n /** Proxy host or IP, without scheme, port, or path. */\r\n host: z.string().default(''),\r\n /** Proxy port. 0 means \"not configured\". */\r\n port: z.number().default(0),\r\n username: z.string().default(''),\r\n password: z.string().default(''),\r\n})\r\n\r\n/**\r\n * One provider's proxy settings. Keyed by provider route id.\r\n *\r\n * `port` is deliberately NOT constrained by schemastery's min/max: an unset\r\n * proxy is `0` (meaning \"no port chosen yet\"), and a bound of 1 here would make\r\n * that default fail to parse. The real range check lives in `normalizeRoute`,\r\n * which runs only when a route is actually enabled, so the error can name the\r\n * provider instead of surfacing a bare schema path.\r\n */\r\nexport const ProviderProxyRoute = z.object({\r\n /** Whether this provider's calls are routed through the proxy below. */\r\n enabled: z.boolean().default(false),\r\n /**\r\n * When true, this route's TRANSPORT fields (protocol/host/port/username/\r\n * password) come from the top-level `defaultProxy` instead of its own, so the\r\n * same endpoint is configured once for every provider that shares it. The\r\n * target-host rules and the self-check target stay the route's own. There is\r\n * no partial inheritance: to use a different endpoint, turn this off and fill\r\n * the fields in.\r\n */\r\n useDefault: z.boolean().default(false),\r\n /** Proxy transport. `socks5` is accepted but only honoured when the socks helper loaded. */\r\n protocol: z.union(PROTOCOLS).default('http'),\r\n /** Proxy host or IP, without scheme, port, or path. */\r\n host: z.string().default(''),\r\n /** Proxy port. 0 means \"not configured\"; enabled routes require 1-65535. */\r\n port: z.number().default(0),\r\n /** Optional proxy username. */\r\n username: z.string().default(''),\r\n /** SOCKS5 proxy password. Only used when `protocol` is `socks5`. */\r\n password: z.string().default(''),\r\n /**\r\n * Comma/space-separated TARGET hosts that must go through the proxy. Empty\r\n * means \"no restriction\" (every target is proxied). Suffix match.\r\n */\r\n onlyHosts: z.string().default(''),\r\n /** Comma/space-separated TARGET hosts that bypass the proxy; takes priority over `onlyHosts`. */\r\n bypassHosts: z.string().default(''),\r\n /**\r\n * Optional self-check target for THIS provider's \u6D4B\u8BD5 button. Empty falls back\r\n * to the top-level `testUrl`. Only the self-check reads it; routing never\r\n * touches it, so a bad value costs a failed check, never a broken route.\r\n */\r\n testTarget: z.string().default(''),\r\n})\r\n\r\nexport const Config = z.object({\r\n /** Per-provider proxy routes, keyed by provider route id (e.g. `sensenova`). */\r\n providers: vol(z.dict(ProviderProxyRoute).default({})),\r\n /**\r\n * Shared endpoint for every route that sets `useDefault`. Volatile for the\r\n * same reason as `providers`: a settings write is committed into the running\r\n * fiber instead of remounting the plugin.\r\n */\r\n defaultProxy: vol(DefaultProxy.default({})),\r\n /**\r\n * Whether a loopback/private-address target is sent DIRECT instead of through\r\n * the proxy. On by default: such a target is normally a relay on this very\r\n * machine (LiteLLM, Ollama, a local mock), which a forward proxy cannot reach\r\n * at all \u2014 forcing it through one fails, and the failure reads as \"the proxy\r\n * is broken\". Turn this off only when the proxy itself is the target.\r\n */\r\n localDirect: vol(z.boolean().default(true)),\r\n /**\r\n * URL the per-provider connection self-check requests THROUGH the proxy.\r\n * Volatile, so a settings write does not remount the plugin; the default is an\r\n * IP echo service, which lets the check report the exit address.\r\n */\r\n testUrl: vol(z.string().default('https://api.ipify.org?format=json')),\r\n})\r\n\r\nexport interface ProviderProxyRouteValue {\r\n enabled: boolean\r\n useDefault: boolean\r\n protocol: Protocol\r\n host: string\r\n port: number\r\n username: string\r\n password: string\r\n onlyHosts: string\r\n bypassHosts: string\r\n testTarget: string\r\n}\r\n\r\n/** The normalized shared endpoint; see {@link DefaultProxy}. */\r\nexport interface DefaultProxyValue {\r\n protocol: Protocol\r\n host: string\r\n port: number\r\n username: string\r\n password: string\r\n}\r\n\r\nexport interface ConfigShape {\r\n providers: { readonly [provider: string]: ProviderProxyRouteValue }\r\n defaultProxy: DefaultProxyValue\r\n localDirect: boolean\r\n testUrl: string\r\n}\r\n\r\n/** Read a schemastery-parsed object's plain value, whichever shape it takes. */\r\nfunction plain<T>(parsed: unknown): T {\r\n const get = (parsed as { get?: () => unknown }).get\r\n return (typeof get === 'function' ? get.call(parsed) : parsed) as T\r\n}\r\n\r\n/**\r\n * Normalize the shared default endpoint. Mirrors {@link normalizeRoute} so both\r\n * the Host and a test can hand `createProxyTable` a raw object.\r\n *\r\n * Format is validated lazily, exactly like a route: a malformed default costs a\r\n * `problems` entry naming each route that opted into it, never a crash.\r\n */\r\nexport function normalizeDefaultProxy(raw: Partial<DefaultProxyValue> | undefined): DefaultProxyValue {\r\n const value = plain<DefaultProxyValue>(DefaultProxy(raw ?? {}))\r\n return {\r\n protocol: value.protocol,\r\n host: value.host.trim(),\r\n port: value.port,\r\n username: value.username.trim(),\r\n password: value.password,\r\n }\r\n}\r\n\r\n/**\r\n * Validate one route and return the normalized value, or throw with a\r\n * field-scoped message. Used by both the Host (before opening a dispatcher)\r\n * and the settings form (before writing), so an invalid value never reaches\r\n * disk or the network.\r\n */\r\nexport function normalizeRoute(\r\n provider: string,\r\n raw: Partial<ProviderProxyRouteValue> | undefined,\r\n options?: { requireEnabled?: boolean },\r\n): ProviderProxyRouteValue {\r\n const value = plain<ProviderProxyRouteValue>(ProviderProxyRoute(raw ?? {}))\r\n\r\n // Host rules are stored normalized (trimmed, lower-cased) so the matcher built\r\n // from them never re-parses on the hot path. WHATWG URL already lower-cases a\r\n // hostname, so both sides of the comparison agree.\r\n const onlyHosts = value.onlyHosts.trim().toLowerCase()\r\n const bypassHosts = value.bypassHosts.trim().toLowerCase()\r\n const testTarget = value.testTarget.trim()\r\n\r\n // A disabled route is normally returned untouched: nothing has been asked of\r\n // it, so a half-typed endpoint must not be reported as a problem. The\r\n // self-check DOES ask \u2014 it builds a dispatcher for a route the user has not\r\n // switched on yet \u2014 so it passes `requireEnabled: false` to get exactly the\r\n // validation routing would apply once the route is on.\r\n if (!value.enabled && options?.requireEnabled !== false) {\r\n return { ...value, port: value.port || 0, onlyHosts, bypassHosts, testTarget }\r\n }\r\n\r\n const host = value.host.trim()\r\n const hostProblem = proxyHostProblem(host)\r\n if (hostProblem !== undefined) {\r\n throw new TypeError(\r\n hostProblem === '\u672A\u586B\u5199\u4EE3\u7406\u5730\u5740'\r\n ? `dsh-provider-proxy: provider \"${provider}\" \u542F\u7528\u4E86\u4EE3\u7406\uFF0C\u4F46\u672A\u586B\u5199\u4EE3\u7406\u5730\u5740`\r\n : `dsh-provider-proxy: provider \"${provider}\" \u7684${hostProblem}`,\r\n )\r\n }\r\n if (!Number.isInteger(value.port) || value.port < 1 || value.port > 65535) {\r\n throw new TypeError(\r\n `dsh-provider-proxy: provider \"${provider}\" \u7684\u4EE3\u7406\u7AEF\u53E3\u65E0\u6548\uFF08\u9700\u4E3A 1-65535 \u7684\u6574\u6570\uFF09`,\r\n )\r\n }\r\n return { ...value, host, username: value.username.trim(), onlyHosts, bypassHosts, testTarget }\r\n}", "/**\n * The proxy-endpoint usability predicate, in ONE place.\n *\n * This lives in its own module \u2014 free of Node and schemastery imports \u2014 so the\n * BROWSER half can import the very same rule the Host applies. It exists because\n * the browser used to keep its own weaker copy that checked only \"host non-empty\n * and port in range\": against `https://1.2.3.4` that copy lit the default block\n * green and enabled the bulk \"use the default\" button, while the Host refused\n * every route that pointed at it (a host carrying a scheme or path is rejected by\n * `normalizeRoute`). One predicate, imported by both halves, cannot disagree\n * with itself.\n */\nexport interface ProxyEndpoint {\n /**\n * Proxy host or IP, without scheme, port, or path.\n *\n * Optional because the browser calls this with whatever the settings document\n * currently holds, which mid-edit is not yet a complete endpoint.\n */\n host?: string\n /** Proxy port. 0 means \"not configured\". */\n port?: number\n /**\n * Credential parts, if the endpoint carries any. A HALF-filled pair is a\n * problem, the same way it is on the route itself \u2014 see below.\n */\n username?: string\n password?: string\n}\n\nconst PROXY_HOST_INVALID = '\u4EE3\u7406\u5730\u5740\u53EA\u80FD\u586B IPv4\u3001IPv6 \u6216\u57DF\u540D'\nconst IPV4 = /^(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)$/\nconst DOMAIN = /^(?=.*[a-z])(?=.{1,253}$)(?!.*\\.\\d+$)[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?)*$/i\nconst IPV6_CHARS = /^[0-9a-f:.]+$/i\n\n/**\n * Accept exactly one of: IPv4, IPv6, or a DNS host name. The field carries the\n * proxy address only; a port, scheme, path, credential, or other URL text belongs\n * in its own field and is rejected here.\n */\nexport function proxyHostProblem(rawHost?: string): string | undefined {\n const host = (rawHost ?? '').trim().replace(/\\.$/, '')\n if (host.length === 0) return '\u672A\u586B\u5199\u4EE3\u7406\u5730\u5740'\n if (IPV4.test(host)) return undefined\n\n // A colon or bracket means the value is claiming to be IPv6. Validate it as\n // an IPv6 literal; never fall back to accepting the text as a host name.\n if (host.includes(':') || host.startsWith('[')) {\n const literal = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host\n if (!IPV6_CHARS.test(literal)) return PROXY_HOST_INVALID\n try {\n new URL(`http://[${literal}]:1`)\n return undefined\n } catch {\n return PROXY_HOST_INVALID\n }\n }\n\n return DOMAIN.test(host) ? undefined : PROXY_HOST_INVALID\n}\n\n/**\n * Why this endpoint cannot carry a request, or `undefined` when it can.\n *\n * The host and port checks mirror `normalizeRoute` exactly, so the browser's\n * verdict and the Host's are the same verdict. The credential pairing check\n * mirrors the guards in `buildRouteEntry`, which is what makes this predicate a\n * truthful preview of whether a route that opts into the default will actually be\n * built: without it, a default carrying `alice` and no password lit the block\n * green and enabled the bulk button, and every card it pointed at was then\n * refused by the credential guard with `entries.size === 0`.\n *\n * Tolerates a partial object (`{}`, `host: undefined`) rather than throwing: the\n * browser calls this with whatever the settings document currently holds, which\n * during a half-typed edit is not yet a complete endpoint.\n */\nexport function defaultProxyProblem(endpoint: ProxyEndpoint): string | undefined {\n const hostProblem = proxyHostProblem(endpoint.host)\n if (hostProblem !== undefined) return hostProblem\n // `?? 0` rather than a throw: an absent port is \"not configured\", which is the\n // same thing 0 already means everywhere else in this plugin.\n const port = endpoint.port ?? 0\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n return '\u4EE3\u7406\u7AEF\u53E3\u65E0\u6548\uFF08\u9700\u4E3A 1-65535 \u7684\u6574\u6570\uFF09'\n }\n // \"Both or neither\", exactly as `buildRouteEntry` enforces per transport. The\n // wording stays transport-neutral here because the default block carries a\n // protocol the user may still change; the route-level guards spell out the\n // protocol-specific reason once it is pinned. The Host trims the username\n // before its guards, so this predicate must trim it too; the password is not\n // trimmed by either side.\n const hasUser = (endpoint.username ?? '').trim().length > 0\n const hasPassword = (endpoint.password ?? '').length > 0\n if (hasUser !== hasPassword) {\n return hasUser\n ? '\u914D\u7F6E\u4E86\u4EE3\u7406\u7528\u6237\u540D\u4F46\u6CA1\u6709\u5BC6\u7801\uFF1B\u8BF7\u8865\u5168\u5BC6\u7801\u6216\u6E05\u7A7A\u7528\u6237\u540D'\n : '\u914D\u7F6E\u4E86\u4EE3\u7406\u5BC6\u7801\u4F46\u6CA1\u6709\u7528\u6237\u540D\uFF1B\u8BF7\u8865\u5168\u7528\u6237\u540D\u6216\u6E05\u7A7A\u5BC6\u7801'\n }\n return undefined\n}\n", "import { Binary, clone, createVolatile, deepEqual, filterKeys, isNullable, isPlainObject, isVolatile, pick, valueMap } from \"@deepseek-ai/cosmokit\";\n//#region lib/types/index.js\nconst kSchema = Symbol.for(\"schemastery\");\nconst kValidationError = Symbol.for(\"ValidationError\");\nglobalThis.__schemastery_index__ ??= 0;\nglobalThis.__schemastery_refs__ = void 0;\nvar ValidationError = class extends TypeError {\n\toptions;\n\tname = \"ValidationError\";\n\tconstructor(message, options) {\n\t\tlet prefix = \"$\";\n\t\tfor (const segment of options.path || []) if (typeof segment === \"string\") prefix += \".\" + segment;\n\t\telse if (typeof segment === \"number\") prefix += \"[\" + segment + \"]\";\n\t\telse if (typeof segment === \"symbol\") prefix += `[Symbol(${segment.toString()})]`;\n\t\tif (prefix.startsWith(\".\")) prefix = prefix.slice(1);\n\t\tsuper((prefix === \"$\" ? \"\" : `${prefix} `) + message);\n\t\tthis.options = options;\n\t}\n\tstatic is(error) {\n\t\treturn !!error?.[kValidationError];\n\t}\n};\nObject.defineProperty(ValidationError.prototype, kValidationError, { value: true });\nconst Schema = function(options) {\n\tconst schema = function(data, options = {}) {\n\t\treturn Schema.resolve(data, schema, options)[0];\n\t};\n\tif (options.refs) {\n\t\tconst refs = valueMap(options.refs, (options) => new Schema(options));\n\t\tconst getRef = (uid) => refs[uid];\n\t\tfor (const key in refs) {\n\t\t\tconst options = refs[key];\n\t\t\toptions.sKey = getRef(options.sKey);\n\t\t\toptions.inner = getRef(options.inner);\n\t\t\toptions.list = options.list && options.list.map(getRef);\n\t\t\toptions.dict = options.dict && valueMap(options.dict, getRef);\n\t\t}\n\t\treturn refs[options.uid];\n\t}\n\tObject.assign(schema, options);\n\tif (typeof schema.callback === \"string\") try {\n\t\tschema.callback = new Function(\"return \" + schema.callback)();\n\t} catch {}\n\tObject.defineProperty(schema, \"uid\", { value: globalThis.__schemastery_index__++ });\n\tObject.setPrototypeOf(schema, Schema.prototype);\n\tschema.meta ||= {};\n\tschema.toString = schema.toString.bind(schema);\n\treturn schema;\n};\nSchema.prototype = Object.create(Function.prototype);\nSchema.prototype[kSchema] = true;\nObject.defineProperty(Schema.prototype, \"~standard\", { get() {\n\treturn {\n\t\tversion: 1,\n\t\tvendor: \"schemastery\",\n\t\tvalidate: (value) => {\n\t\t\ttry {\n\t\t\t\treturn { value: Schema.resolve(value, this, {})[0] };\n\t\t\t} catch (error) {\n\t\t\t\tif (ValidationError.is(error)) return { issues: [{\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tpath: error.options.path\n\t\t\t\t}] };\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t};\n} });\nSchema.ValidationError = ValidationError;\nSchema.prototype.toJSON = function toJSON() {\n\tif (globalThis.__schemastery_refs__) {\n\t\tglobalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));\n\t\treturn this.uid;\n\t}\n\tglobalThis.__schemastery_refs__ = { [this.uid]: { ...this } };\n\tglobalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));\n\tconst result = {\n\t\tuid: this.uid,\n\t\trefs: globalThis.__schemastery_refs__\n\t};\n\tglobalThis.__schemastery_refs__ = void 0;\n\treturn result;\n};\nSchema.prototype.set = function set(key, value) {\n\tthis.dict[key] = value;\n\treturn this;\n};\nSchema.prototype.push = function push(value) {\n\tthis.list.push(value);\n\treturn this;\n};\nfunction mergeDesc(original, messages) {\n\tconst result = typeof original === \"string\" ? { \"\": original } : { ...original };\n\tfor (const locale in messages) {\n\t\tconst value = messages[locale];\n\t\tif (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;\n\t\telse if (typeof value === \"string\") result[locale] = value;\n\t}\n\treturn result;\n}\nfunction getInner(value) {\n\treturn value?.$value ?? value?.$inner;\n}\nfunction extractKeys(data) {\n\treturn filterKeys(data ?? {}, (key) => !key.startsWith(\"$\"));\n}\nSchema.prototype.i18n = function i18n(messages) {\n\tconst schema = Schema(this);\n\tconst desc = mergeDesc(schema.meta.description, messages);\n\tif (Object.keys(desc).length) schema.meta.description = desc;\n\tif (schema.dict) schema.dict = valueMap(schema.dict, (inner, key) => {\n\t\treturn inner.i18n(valueMap(messages, (data) => getInner(data)?.[key] ?? data?.[key]));\n\t});\n\tif (schema.list) schema.list = schema.list.map((inner, index) => {\n\t\treturn inner.i18n(valueMap(messages, (data = {}) => {\n\t\t\tif (Array.isArray(getInner(data))) return getInner(data)[index];\n\t\t\tif (Array.isArray(data)) return data[index];\n\t\t\treturn extractKeys(data);\n\t\t}));\n\t});\n\tif (schema.inner) schema.inner = schema.inner.i18n(valueMap(messages, (data) => {\n\t\tif (getInner(data)) return getInner(data);\n\t\treturn extractKeys(data);\n\t}));\n\tif (schema.sKey) schema.sKey = schema.sKey.i18n(valueMap(messages, (data) => data?.$key));\n\treturn schema;\n};\nSchema.prototype.extra = function extra(key, value) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n};\nfor (const key of [\n\t\"required\",\n\t\"disabled\",\n\t\"collapse\",\n\t\"hidden\",\n\t\"loose\"\n]) Object.assign(Schema.prototype, { [key](value = true) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n} });\nSchema.prototype.deprecated = function deprecated() {\n\tconst schema = Schema(this);\n\tschema.meta.badges ||= [];\n\tschema.meta.badges.push({\n\t\ttext: \"deprecated\",\n\t\ttype: \"danger\"\n\t});\n\treturn schema;\n};\nSchema.prototype.experimental = function experimental() {\n\tconst schema = Schema(this);\n\tschema.meta.badges ||= [];\n\tschema.meta.badges.push({\n\t\ttext: \"experimental\",\n\t\ttype: \"warning\"\n\t});\n\treturn schema;\n};\nSchema.prototype.pattern = function pattern(regexp) {\n\tconst schema = Schema(this);\n\tconst pattern = pick(regexp, [\"source\", \"flags\"]);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\tpattern\n\t};\n\treturn schema;\n};\nSchema.prototype.simplify = function simplify(value) {\n\tif (isVolatile(value)) value = value.get();\n\tif (deepEqual(value, this.meta.default, this.type === \"dict\")) return null;\n\tif (isNullable(value)) return value;\n\tif (this.type === \"object\" || this.type === \"dict\") {\n\t\tconst result = {};\n\t\tfor (const key in value) {\n\t\t\tconst item = (this.type === \"object\" ? this.dict[key] : this.inner)?.simplify(value[key]);\n\t\t\tif (this.type === \"dict\" || !isNullable(item)) result[key] = item;\n\t\t}\n\t\tif (deepEqual(result, this.meta.default, this.type === \"dict\")) return null;\n\t\treturn result;\n\t} else if (this.type === \"array\" || this.type === \"tuple\") {\n\t\tconst result = [];\n\t\tvalue.forEach((value, index) => {\n\t\t\tconst schema = this.type === \"array\" ? this.inner : this.list[index];\n\t\t\tconst item = schema ? schema.simplify(value) : value;\n\t\t\tresult.push(item);\n\t\t});\n\t\treturn result;\n\t} else if (this.type === \"intersect\") {\n\t\tconst result = {};\n\t\tfor (const item of this.list) Object.assign(result, item.simplify(value));\n\t\treturn result;\n\t} else if (this.type === \"union\") for (const schema of this.list) try {\n\t\tSchema.resolve(value, schema, {});\n\t\treturn schema.simplify(value);\n\t} catch {}\n\treturn value;\n};\nSchema.prototype.toString = function toString(inline) {\n\treturn formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;\n};\nSchema.prototype.role = function role(role, extra) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\trole,\n\t\textra\n\t};\n\treturn schema;\n};\nfor (const key of [\n\t\"default\",\n\t\"link\",\n\t\"comment\",\n\t\"description\",\n\t\"max\",\n\t\"min\",\n\t\"step\"\n]) Object.assign(Schema.prototype, { [key](value) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n} });\nSchema.prototype.volatile = function volatile() {\n\tif (this.meta.volatile) throw new TypeError(\"volatile schema is already wrapped\");\n\treturn this.extra(\"volatile\", true);\n};\nconst resolvers = {};\nconst checkedVolatile = Symbol(\"checked-volatile-schema\");\nfunction validateVolatileSchema(schema, path = [], blocked = false, seen = /* @__PURE__ */ new Map()) {\n\tconst states = seen.get(schema) ?? /* @__PURE__ */ new Set();\n\tif (states.has(blocked)) return;\n\tstates.add(blocked);\n\tseen.set(schema, states);\n\tif (schema.meta?.volatile && blocked) throw new ValidationError(\"volatile fields require a fixed object path without an enclosing volatile field\", { path });\n\tconst nested = blocked || !!schema.meta?.volatile;\n\tif (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen);\n\tif (schema.sKey) validateVolatileSchema(schema.sKey, [...path, \"<key>\"], true, seen);\n\tif (schema.inner && (schema.type !== \"lazy\" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, \"*\"], true, seen);\n\tif (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);\n}\nSchema.extend = function extend(type, resolve) {\n\tresolvers[type] = resolve;\n};\nSchema.resolve = function resolve(data, schema, options = {}, strict = false) {\n\tif (!schema) return [data];\n\tif (!options[checkedVolatile]) {\n\t\tvalidateVolatileSchema(schema, options.path);\n\t\toptions = {\n\t\t\t...options,\n\t\t\t[checkedVolatile]: true\n\t\t};\n\t}\n\tif (schema.meta?.volatile) {\n\t\tconst inner = Schema(schema);\n\t\tinner.meta = {\n\t\t\t...schema.meta,\n\t\t\tvolatile: false\n\t\t};\n\t\tconst [value, adapted] = Schema.resolve(data, inner, options, strict);\n\t\ttry {\n\t\t\treturn [createVolatile(value), adapted];\n\t\t} catch (error) {\n\t\t\tthrow new ValidationError(error instanceof Error ? error.message : String(error), options);\n\t\t}\n\t}\n\tif (options.ignore?.(data, schema)) return [data];\n\tif (isNullable(data) && schema.type !== \"lazy\") {\n\t\tif (schema.meta.required) throw new ValidationError(`missing required value`, options);\n\t\tlet current = schema;\n\t\tlet fallback = schema.meta.default;\n\t\twhile (current?.type === \"intersect\" && isNullable(fallback)) {\n\t\t\tcurrent = current.list[0];\n\t\t\tfallback = current?.meta.default;\n\t\t}\n\t\tif (isNullable(fallback)) return [data];\n\t\tdata = clone(fallback);\n\t}\n\tconst callback = resolvers[schema.type];\n\tif (!callback) throw new ValidationError(`unsupported type \"${schema.type}\"`, options);\n\ttry {\n\t\treturn callback(data, schema, options, strict);\n\t} catch (error) {\n\t\tif (!schema.meta.loose) throw error;\n\t\treturn [schema.meta.default];\n\t}\n};\nSchema.from = function from(source) {\n\tif (isNullable(source)) return Schema.any();\n\telse if ([\n\t\t\"string\",\n\t\t\"number\",\n\t\t\"boolean\"\n\t].includes(typeof source)) return Schema.const(source).required();\n\telse if (source[kSchema]) return source;\n\telse if (typeof source === \"function\") switch (source) {\n\t\tcase String: return Schema.string().required();\n\t\tcase Number: return Schema.number().required();\n\t\tcase Boolean: return Schema.boolean().required();\n\t\tcase Function: return Schema.function().required();\n\t\tdefault: return Schema.is(source).required();\n\t}\n\telse throw new TypeError(`cannot infer schema from ${source}`);\n};\nSchema.lazy = function lazy(builder) {\n\tconst toJSON = () => {\n\t\tif (!schema.inner[kSchema]) {\n\t\t\tschema.inner = schema.builder();\n\t\t\tschema.inner.meta = {\n\t\t\t\t...schema.meta,\n\t\t\t\t...schema.inner.meta\n\t\t\t};\n\t\t}\n\t\treturn schema.inner.toJSON();\n\t};\n\tconst schema = new Schema({\n\t\ttype: \"lazy\",\n\t\tbuilder,\n\t\tinner: { toJSON }\n\t});\n\treturn schema;\n};\nSchema.natural = function natural() {\n\treturn Schema.number().step(1).min(0);\n};\nSchema.percent = function percent() {\n\treturn Schema.number().step(.01).min(0).max(1).role(\"slider\");\n};\nSchema.date = function date() {\n\treturn Schema.union([Schema.is(Date), Schema.transform(Schema.string().role(\"datetime\"), (value, options) => {\n\t\tconst date = new Date(value);\n\t\tif (isNaN(+date)) throw new ValidationError(`invalid date \"${value}\"`, options);\n\t\treturn date;\n\t}, true)]);\n};\nSchema.regExp = function regExp(flag = \"\") {\n\treturn Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role(\"regexp\", { flag }), (value, options) => {\n\t\ttry {\n\t\t\treturn new RegExp(value, flag);\n\t\t} catch (e) {\n\t\t\tthrow new ValidationError(e.message, options);\n\t\t}\n\t}, true)]);\n};\nSchema.arrayBuffer = function arrayBuffer(encoding) {\n\treturn Schema.union([\n\t\tSchema.is(ArrayBuffer),\n\t\tSchema.is(SharedArrayBuffer),\n\t\tSchema.transform(Schema.any(), (value, options) => {\n\t\t\tif (Binary.isSource(value)) return Binary.fromSource(value);\n\t\t\tthrow new ValidationError(`expected ArrayBufferSource but got ${value}`, options);\n\t\t}, true),\n\t\t...encoding ? [Schema.transform(Schema.string(), (value, options) => {\n\t\t\ttry {\n\t\t\t\treturn encoding === \"base64\" ? Binary.fromBase64(value) : Binary.fromHex(value);\n\t\t\t} catch (e) {\n\t\t\t\tthrow new ValidationError(e.message, options);\n\t\t\t}\n\t\t}, true)] : []\n\t]);\n};\nSchema.extend(\"lazy\", (data, schema, options, strict) => {\n\tif (!schema.inner[kSchema]) {\n\t\tschema.inner = schema.builder();\n\t\tschema.inner.meta = {\n\t\t\t...schema.meta,\n\t\t\t...schema.inner.meta\n\t\t};\n\t\tvalidateVolatileSchema(schema.inner, options.path, true);\n\t}\n\treturn Schema.resolve(data, schema.inner, options, strict);\n});\nSchema.extend(\"any\", (data) => {\n\treturn [data];\n});\nSchema.extend(\"never\", (data, _, options) => {\n\tthrow new ValidationError(`expected nullable but got ${data}`, options);\n});\nSchema.extend(\"const\", (data, { value }, options) => {\n\tif (deepEqual(data, value)) return [value];\n\tthrow new ValidationError(`expected ${value} but got ${data}`, options);\n});\nfunction checkWithinRange(data, meta, description, options, skipMin = false) {\n\tconst { max = Infinity, min = -Infinity } = meta;\n\tif (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);\n\tif (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);\n}\nSchema.extend(\"string\", (data, { meta }, options) => {\n\tif (typeof data !== \"string\") throw new ValidationError(`expected string but got ${data}`, options);\n\tif (meta.pattern) {\n\t\tconst regexp = new RegExp(meta.pattern.source, meta.pattern.flags);\n\t\tif (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);\n\t}\n\tcheckWithinRange(data.length, meta, \"string length\", options);\n\treturn [data];\n});\nfunction decimalShift(data, digits) {\n\tconst str = data.toString();\n\tif (str.includes(\"e\")) return data * Math.pow(10, digits);\n\tconst index = str.indexOf(\".\");\n\tif (index === -1) return data * Math.pow(10, digits);\n\tconst frac = str.slice(index + 1);\n\tconst integer = str.slice(0, index);\n\tif (frac.length <= digits) return +(integer + frac.padEnd(digits, \"0\"));\n\treturn +(integer + frac.slice(0, digits) + \".\" + frac.slice(digits));\n}\nfunction isMultipleOf(data, min, step) {\n\tstep = Math.abs(step);\n\tif (!/^\\d+\\.\\d+$/.test(step.toString())) return (data - min) % step === 0;\n\tconst index = step.toString().indexOf(\".\");\n\tconst digits = step.toString().slice(index + 1).length;\n\treturn Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;\n}\nSchema.extend(\"number\", (data, { meta }, options) => {\n\tif (typeof data !== \"number\") throw new ValidationError(`expected number but got ${data}`, options);\n\tcheckWithinRange(data, meta, \"number\", options);\n\tconst { step } = meta;\n\tif (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);\n\treturn [data];\n});\nSchema.extend(\"boolean\", (data, _, options) => {\n\tif (typeof data === \"boolean\") return [data];\n\tthrow new ValidationError(`expected boolean but got ${data}`, options);\n});\nSchema.extend(\"bitset\", (data, { bits, meta }, options) => {\n\tlet value = 0, keys = [];\n\tif (typeof data === \"number\") {\n\t\tvalue = data;\n\t\tfor (const key in bits) if (data & bits[key]) keys.push(key);\n\t} else if (Array.isArray(data)) {\n\t\tkeys = data;\n\t\tfor (const key of keys) {\n\t\t\tif (typeof key !== \"string\") throw new ValidationError(`expected string but got ${key}`, options);\n\t\t\tif (key in bits) value |= bits[key];\n\t\t}\n\t} else throw new ValidationError(`expected number or array but got ${data}`, options);\n\tif (value === meta.default) return [value];\n\treturn [value, keys];\n});\nSchema.extend(\"function\", (data, _, options) => {\n\tif (typeof data === \"function\") return [data];\n\tthrow new ValidationError(`expected function but got ${data}`, options);\n});\nSchema.extend(\"is\", (data, { constructor }, options) => {\n\tif (typeof constructor === \"function\") {\n\t\tif (data instanceof constructor) return [data];\n\t\tthrow new ValidationError(`expected ${constructor.name} but got ${data}`, options);\n\t} else {\n\t\tif (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);\n\t\tlet prototype = Object.getPrototypeOf(data);\n\t\twhile (prototype) {\n\t\t\tif (prototype.constructor?.name === constructor) return [data];\n\t\t\tprototype = Object.getPrototypeOf(prototype);\n\t\t}\n\t\tthrow new ValidationError(`expected ${constructor} but got ${data}`, options);\n\t}\n});\nfunction property(data, key, schema, options) {\n\ttry {\n\t\tconst [value, adapted] = Schema.resolve(data[key], schema, {\n\t\t\t...options,\n\t\t\tpath: [...options.path || [], key]\n\t\t});\n\t\tif (adapted !== void 0) data[key] = adapted;\n\t\treturn value;\n\t} catch (e) {\n\t\tif (!options?.autofix) throw e;\n\t\tdelete data[key];\n\t\treturn schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;\n\t}\n}\nSchema.extend(\"array\", (data, { inner, meta }, options) => {\n\tif (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);\n\tcheckWithinRange(data.length, meta, \"array length\", options, !isNullable(inner.meta.default));\n\treturn [data.map((_, index) => property(data, index, inner, options))];\n});\nSchema.extend(\"dict\", (data, { inner, sKey }, options, strict) => {\n\tif (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);\n\tconst result = {};\n\tfor (const key in data) {\n\t\tlet rKey;\n\t\ttry {\n\t\t\trKey = Schema.resolve(key, sKey, options)[0];\n\t\t} catch (error) {\n\t\t\tif (strict) continue;\n\t\t\tthrow error;\n\t\t}\n\t\tresult[rKey] = property(data, key, inner, options);\n\t\tdata[rKey] = data[key];\n\t\tif (key !== rKey) delete data[key];\n\t}\n\treturn [result];\n});\nSchema.extend(\"tuple\", (data, { list }, options, strict) => {\n\tif (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);\n\tconst result = list.map((inner, index) => property(data, index, inner, options));\n\tif (strict) return [result];\n\tresult.push(...data.slice(list.length));\n\treturn [result];\n});\nfunction merge(result, data) {\n\tfor (const key in data) {\n\t\tif (key in result) continue;\n\t\tresult[key] = data[key];\n\t}\n}\nSchema.extend(\"object\", (data, { dict }, options, strict) => {\n\tif (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);\n\tconst result = {};\n\tfor (const key in dict) {\n\t\tconst value = property(data, key, dict[key], options);\n\t\tif (!isNullable(value) || key in data) result[key] = value;\n\t}\n\tif (!strict) merge(result, data);\n\treturn [result];\n});\nSchema.extend(\"union\", (data, { list, toString }, options, strict) => {\n\tconst messages = [];\n\tfor (const inner of list) try {\n\t\treturn Schema.resolve(data, inner, options, strict);\n\t} catch (error) {\n\t\tmessages.push(error);\n\t}\n\tthrow new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n});\nSchema.extend(\"intersect\", (data, { list, toString }, options, strict) => {\n\tif (!list.length) return [data];\n\tlet result;\n\tfor (const inner of list) {\n\t\tconst value = Schema.resolve(data, inner, options, true)[0];\n\t\tif (isNullable(value)) continue;\n\t\tif (isNullable(result)) result = value;\n\t\telse if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n\t\telse if (typeof value === \"object\") merge(result ??= {}, value);\n\t\telse if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n\t}\n\tif (!strict && isPlainObject(data)) merge(result, data);\n\treturn [result];\n});\nSchema.extend(\"transform\", (data, { inner, callback, preserve }, options) => {\n\tconst [result, adapted = data] = Schema.resolve(data, inner, options, true);\n\tif (preserve) return [callback(result)];\n\telse return [callback(result), callback(adapted)];\n});\nconst formatters = {};\nfunction defineMethod(name, keys, format) {\n\tformatters[name] = format;\n\tObject.assign(Schema, { [name](...args) {\n\t\tconst schema = new Schema({ type: name });\n\t\tkeys.forEach((key, index) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase \"sKey\":\n\t\t\t\t\tschema.sKey = args[index] ?? Schema.string();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"inner\":\n\t\t\t\t\tschema.inner = Schema.from(args[index]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"list\":\n\t\t\t\t\tschema.list = args[index].map(Schema.from);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"dict\":\n\t\t\t\t\tschema.dict = valueMap(args[index], Schema.from);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"bits\":\n\t\t\t\t\tschema.bits = {};\n\t\t\t\t\tfor (const key in args[index]) {\n\t\t\t\t\t\tif (typeof args[index][key] !== \"number\") continue;\n\t\t\t\t\t\tschema.bits[key] = args[index][key];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"callback\": {\n\t\t\t\t\tconst callback = schema.callback = args[index];\n\t\t\t\t\tcallback[\"toJSON\"] ||= () => callback.toString();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"constructor\": {\n\t\t\t\t\tconst constructor = schema.constructor = args[index];\n\t\t\t\t\tif (typeof constructor === \"function\") constructor[\"toJSON\"] ||= () => constructor[\"name\"];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault: schema[key] = args[index];\n\t\t\t}\n\t\t});\n\t\tif (name === \"object\" || name === \"dict\") schema.meta.default = {};\n\t\telse if (name === \"array\" || name === \"tuple\") schema.meta.default = [];\n\t\telse if (name === \"bitset\") schema.meta.default = 0;\n\t\treturn schema;\n\t} });\n}\ndefineMethod(\"is\", [\"constructor\"], ({ constructor }) => {\n\tif (typeof constructor === \"function\") return constructor.name;\n\telse return constructor;\n});\ndefineMethod(\"any\", [], () => \"any\");\ndefineMethod(\"never\", [], () => \"never\");\ndefineMethod(\"const\", [\"value\"], ({ value }) => typeof value === \"string\" ? JSON.stringify(value) : value);\ndefineMethod(\"string\", [], () => \"string\");\ndefineMethod(\"number\", [], () => \"number\");\ndefineMethod(\"boolean\", [], () => \"boolean\");\ndefineMethod(\"bitset\", [\"bits\"], () => \"bitset\");\ndefineMethod(\"function\", [], () => \"function\");\ndefineMethod(\"array\", [\"inner\"], ({ inner }) => `${inner.toString(true)}[]`);\ndefineMethod(\"dict\", [\"inner\", \"sKey\"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);\ndefineMethod(\"tuple\", [\"list\"], ({ list }) => `[${list.map((inner) => inner.toString()).join(\", \")}]`);\ndefineMethod(\"object\", [\"dict\"], ({ dict }) => {\n\tif (Object.keys(dict).length === 0) return \"{}\";\n\treturn `{ ${Object.entries(dict).map(([key, inner]) => {\n\t\treturn `${key}${inner.meta.required ? \"\" : \"?\"}: ${inner.toString()}`;\n\t}).join(\", \")} }`;\n});\ndefineMethod(\"union\", [\"list\"], ({ list }, inline) => {\n\tconst result = list.map(({ toString: format }) => format()).join(\" | \");\n\treturn inline ? `(${result})` : result;\n});\ndefineMethod(\"intersect\", [\"list\"], ({ list }) => {\n\treturn `${list.map((inner) => inner.toString(true)).join(\" & \")}`;\n});\ndefineMethod(\"transform\", [\n\t\"inner\",\n\t\"callback\",\n\t\"preserve\"\n], ({ inner }, isInner) => inner.toString(isInner));\n//#endregion\nexport { Schema as default };\n", "//#region lib/types/misc.js\n/** No-op callback returning `undefined` at runtime and `any` at type level. */\nfunction noop() {}\n/** Return true when a value is `null` or `undefined`. */\nfunction isNullable(value) {\n\treturn value === null || value === void 0;\n}\n/** Return true when a value is neither `null` nor `undefined`. */\nfunction isNonNullable(value) {\n\treturn !isNullable(value);\n}\n/** Return true for non-array object values. */\nfunction isPlainObject(data) {\n\treturn data && typeof data === \"object\" && !Array.isArray(data);\n}\n/** Filter object entries and return a new object. */\nfunction filterKeys(object, filter) {\n\treturn Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));\n}\n/** Map object values while preserving the original key set. */\nfunction mapValues(object, transform) {\n\treturn Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));\n}\n/** Pick selected keys from an object, optionally including `undefined` values. */\nfunction pick(source, keys, forced) {\n\tif (!keys) return { ...source };\n\tconst result = {};\n\tfor (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];\n\treturn result;\n}\n/** Omit selected keys from a shallow object copy. */\nfunction omit(source, keys) {\n\tif (!keys) return { ...source };\n\tconst result = { ...source };\n\tfor (const key of keys) Reflect.deleteProperty(result, key);\n\treturn result;\n}\n/** Define a non-enumerable writable property and return the object. */\nfunction defineProperty(object, key, value) {\n\treturn Object.defineProperty(object, key, {\n\t\twritable: true,\n\t\tvalue,\n\t\tenumerable: false\n\t});\n}\n//#endregion\n//#region lib/types/array.js\n/** Return true when every item in `array2` is present in `array1`. */\nfunction contain(array1, array2) {\n\treturn array2.every((item) => array1.includes(item));\n}\n/** Return items that appear in both arrays. */\nfunction intersection(array1, array2) {\n\treturn array1.filter((item) => array2.includes(item));\n}\n/** Return items from `array1` that do not appear in `array2`. */\nfunction difference(array1, array2) {\n\treturn array1.filter((item) => !array2.includes(item));\n}\n/** Return the set-union of two arrays while preserving first occurrence order. */\nfunction union(array1, array2) {\n\treturn Array.from(new Set([...array1, ...array2]));\n}\n/** Remove duplicate values while preserving first occurrence order. */\nfunction deduplicate(array) {\n\treturn [...new Set(array)];\n}\n/** Remove one item from an array and report whether it was found. */\nfunction remove(list, item) {\n\tconst index = list?.indexOf(item);\n\tif (index >= 0) {\n\t\tlist.splice(index, 1);\n\t\treturn true;\n\t} else return false;\n}\n/** Normalize nullish, scalar, or array input to an array. */\nfunction makeArray(source) {\n\treturn Array.isArray(source) ? source : isNullable(source) ? [] : [source];\n}\n//#endregion\n//#region lib/types/volatile.js\n/** Shared config references used by schema validators and plugin runtimes. */\nconst write = Symbol.for(\"cosmokit.volatile.write\");\nfunction snapshot(value, ancestors = /* @__PURE__ */ new Set()) {\n\tif (typeof value === \"function\") throw new TypeError(\"volatile config cannot contain functions\");\n\tif (value === null || typeof value !== \"object\") return value;\n\tif (ancestors.has(value)) throw new TypeError(\"volatile config cannot contain cycles\");\n\tancestors.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));\n\t\tif (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError(\"volatile config objects must be plain objects or arrays\");\n\t\treturn Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));\n\t} finally {\n\t\tancestors.delete(value);\n\t}\n}\n/**\n* Create a detached reference containing an immutable copy of the supplied data.\n* @param value - validated config data; class instances and functions are unsupported.\n* @returns a reference whose value is updated only by its owning runtime.\n*/\nfunction createVolatile(value) {\n\tlet current = snapshot(value);\n\treturn Object.freeze({\n\t\tget: () => current,\n\t\t[write]: (value) => {\n\t\t\tcurrent = value;\n\t\t}\n\t});\n}\n/**\n* Identify references across ESM/CJS copies of the shared library.\n* @param value - a parsed config value.\n* @returns whether the value implements the shared reference protocol.\n*/\nfunction isVolatile(value) {\n\treturn typeof value === \"object\" && value !== null && write in value;\n}\n/**\n* Collect config references without descending into their snapshots or opaque objects.\n* @internal\n* @param value - parsed config; cyclic ordinary fields are visited once per path.\n* @returns references and their object-key paths, including an empty path for a root reference.\n*/\nfunction volatileEntries(value) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tfunction visit(value, path) {\n\t\tif (isVolatile(value)) return [{\n\t\t\tpath,\n\t\t\tref: value\n\t\t}];\n\t\tif (!value || typeof value !== \"object\" || ancestors.has(value)) return [];\n\t\tif (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return [];\n\t\tancestors.add(value);\n\t\ttry {\n\t\t\treturn Object.entries(value).flatMap(([key, child]) => visit(child, [...path, key]));\n\t\t} finally {\n\t\t\tancestors.delete(value);\n\t\t}\n\t}\n\treturn visit(value, []);\n}\n/**\n* Commit an already validated immutable snapshot from another reference.\n* @internal\n* @param target - the owning plugin's stable reference.\n* @param source - a newly parsed candidate reference.\n*/\nfunction updateVolatile(target, source) {\n\ttarget[write](source.get());\n}\n//#endregion\n//#region lib/types/types.js\n/** Test values using `instanceof` with a `toStringTag` fallback. */\nfunction is(type, value) {\n\tif (arguments.length === 1) return (value) => is(type, value);\n\treturn type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;\n}\nfunction isArrayBufferLike(value) {\n\treturn is(\"ArrayBuffer\", value) || is(\"SharedArrayBuffer\", value);\n}\nfunction isArrayBufferSource(value) {\n\treturn isArrayBufferLike(value) || ArrayBuffer.isView(value);\n}\n/** Binary source detection and base64/hex conversion helpers. */\nvar Binary;\n(function(Binary) {\n\tBinary.is = isArrayBufferLike;\n\tBinary.isSource = isArrayBufferSource;\n\tfunction fromSource(source) {\n\t\tif (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);\n\t\telse return source;\n\t}\n\tBinary.fromSource = fromSource;\n\tfunction toBase64(source) {\n\t\tsource = fromSource(source);\n\t\tif (typeof Buffer !== \"undefined\") return Buffer.from(source).toString(\"base64\");\n\t\tlet binary = \"\";\n\t\tconst bytes = new Uint8Array(source);\n\t\tfor (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);\n\t\treturn btoa(binary);\n\t}\n\tBinary.toBase64 = toBase64;\n\tfunction fromBase64(source) {\n\t\tif (typeof Buffer !== \"undefined\") return fromSource(Buffer.from(source, \"base64\"));\n\t\treturn Uint8Array.from(atob(source), (c) => c.charCodeAt(0));\n\t}\n\tBinary.fromBase64 = fromBase64;\n\tfunction toHex(source) {\n\t\tsource = fromSource(source);\n\t\tif (typeof Buffer !== \"undefined\") return Buffer.from(source).toString(\"hex\");\n\t\treturn Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\t}\n\tBinary.toHex = toHex;\n\tfunction fromHex(source) {\n\t\tif (typeof Buffer !== \"undefined\") return fromSource(Buffer.from(source, \"hex\"));\n\t\tconst hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);\n\t\tconst buffer = [];\n\t\tfor (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));\n\t\treturn Uint8Array.from(buffer).buffer;\n\t}\n\tBinary.fromHex = fromHex;\n})(Binary || (Binary = {}));\n/** Decode a base64 string into binary data. */\nconst base64ToArrayBuffer = Binary.fromBase64;\n/** Encode binary data as base64. */\nconst arrayBufferToBase64 = Binary.toBase64;\n/** Decode a hex string into binary data. */\nconst hexToArrayBuffer = Binary.fromHex;\n/** Encode binary data as hex. */\nconst arrayBufferToHex = Binary.toHex;\n/** Deep-clone common JavaScript values while preserving prototypes and cycles. */\nfunction clone(source, refs = /* @__PURE__ */ new Map()) {\n\tif (!source || typeof source !== \"object\") return source;\n\tif (is(\"Date\", source)) return new Date(source.valueOf());\n\tif (is(\"RegExp\", source)) return new RegExp(source.source, source.flags);\n\tif (isArrayBufferLike(source)) return source.slice(0);\n\tif (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);\n\tconst cached = refs.get(source);\n\tif (cached) return cached;\n\tif (Array.isArray(source)) {\n\t\tconst result = [];\n\t\trefs.set(source, result);\n\t\tsource.forEach((value, index) => {\n\t\t\tresult[index] = Reflect.apply(clone, null, [value, refs]);\n\t\t});\n\t\treturn result;\n\t}\n\tconst result = Object.create(Object.getPrototypeOf(source));\n\trefs.set(source, result);\n\tfor (const key of Reflect.ownKeys(source)) {\n\t\tconst descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };\n\t\tif (\"value\" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);\n\t\tReflect.defineProperty(result, key, descriptor);\n\t}\n\treturn result;\n}\n/**\n* Compare values recursively, treating two volatile references as equal regardless of value.\n* Strict comparison distinguishes null/undefined, treats opaque objects by identity,\n* compares URLs by normalized href, treats array holes as undefined, and considers distinct cyclic structures unequal.\n* @param a - first value.\n* @param b - second value.\n* @param strict - whether to require strict data equality outside volatile references.\n* @returns whether the values compare equal.\n*/\nfunction deepEqual(a, b, strict) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tfunction compare(a, b) {\n\t\tif (a === b) return true;\n\t\tif (isVolatile(a) || isVolatile(b)) return isVolatile(a) && isVolatile(b);\n\t\tif (!strict && isNullable(a) && isNullable(b)) return true;\n\t\tif (typeof a !== typeof b || typeof a !== \"object\" || !a || !b) return false;\n\t\tif (ancestors.has(a)) return false;\n\t\tfunction check(test, then) {\n\t\t\treturn test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;\n\t\t}\n\t\tancestors.add(a);\n\t\ttry {\n\t\t\treturn check(Array.isArray, (a, b) => {\n\t\t\t\tif (a.length !== b.length) return false;\n\t\t\t\tfor (let index = 0; index < a.length; index++) if (!compare(a[index], b[index])) return false;\n\t\t\t\treturn true;\n\t\t\t}) ?? check(is(\"Date\"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is(\"URL\"), (a, b) => a.href === b.href) ?? check(is(\"RegExp\"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {\n\t\t\t\tif (a.byteLength !== b.byteLength) return false;\n\t\t\t\tconst viewA = new Uint8Array(a);\n\t\t\t\tconst viewB = new Uint8Array(b);\n\t\t\t\tfor (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;\n\t\t\t\treturn true;\n\t\t\t}) ?? ((!strict || [a, b].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({\n\t\t\t\t...a,\n\t\t\t\t...b\n\t\t\t}).every((key) => compare(a[key], b[key])));\n\t\t} finally {\n\t\t\tancestors.delete(a);\n\t\t}\n\t}\n\treturn compare(a, b);\n}\n//#endregion\n//#region lib/types/string.js\n/** Uppercase the first character of a string. */\nfunction capitalize(source) {\n\treturn source.charAt(0).toUpperCase() + source.slice(1);\n}\n/** Lowercase the first character of a string. */\nfunction uncapitalize(source) {\n\treturn source.charAt(0).toLowerCase() + source.slice(1);\n}\n/** Convert dash or underscore delimited text to camelCase. */\nfunction camelCase(source) {\n\treturn source.replace(/[_-][a-z]/g, (str) => str.slice(1).toUpperCase());\n}\nfunction tokenize(source, delimiters, delimiter) {\n\tconst output = [];\n\tlet state = 0;\n\tfor (let i = 0; i < source.length; i++) {\n\t\tconst code = source.charCodeAt(i);\n\t\tif (code >= 65 && code <= 90) {\n\t\t\tif (state === 1) {\n\t\t\t\tconst next = source.charCodeAt(i + 1);\n\t\t\t\tif (next >= 97 && next <= 122) output.push(delimiter);\n\t\t\t\toutput.push(code + 32);\n\t\t\t} else {\n\t\t\t\tif (state !== 0) output.push(delimiter);\n\t\t\t\toutput.push(code + 32);\n\t\t\t}\n\t\t\tstate = 1;\n\t\t} else if (code >= 97 && code <= 122) {\n\t\t\toutput.push(code);\n\t\t\tstate = 2;\n\t\t} else if (delimiters.includes(code)) {\n\t\t\tif (state !== 0) output.push(delimiter);\n\t\t\tstate = 0;\n\t\t} else output.push(code);\n\t}\n\treturn String.fromCharCode(...output);\n}\n/** Convert text to dash-delimited parameter case. */\nfunction paramCase(source) {\n\treturn tokenize(source, [45, 95], 45);\n}\n/** Convert text to underscore-delimited snake case. */\nfunction snakeCase(source) {\n\treturn tokenize(source, [45, 95], 95);\n}\n/** Runtime alias for `camelCase`. */\nconst camelize = camelCase;\n/** Runtime alias for `paramCase`. */\nconst hyphenate = paramCase;\n/** Format a property key as a JavaScript member access suffix. */\nfunction formatProperty(key) {\n\tif (typeof key !== \"string\") return `[${key.toString()}]`;\n\treturn /^[a-z_$][\\w$]*$/i.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;\n}\n/** Remove one trailing slash from a path string. */\nfunction trimSlash(source) {\n\treturn source.replace(/\\/$/, \"\");\n}\n/** Ensure a path starts with `/` and has no trailing slash. */\nfunction sanitize(source) {\n\tif (!source.startsWith(\"/\")) source = \"/\" + source;\n\treturn trimSlash(source);\n}\n//#endregion\n//#region lib/types/time.js\n/** Time constants plus parsing and formatting helpers. */\nvar Time;\n(function(Time) {\n\tTime.millisecond = 1;\n\tTime.second = 1e3;\n\tTime.minute = Time.second * 60;\n\tTime.hour = Time.minute * 60;\n\tTime.day = Time.hour * 24;\n\tTime.week = Time.day * 7;\n\tlet timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();\n\tfunction setTimezoneOffset(offset) {\n\t\ttimezoneOffset = offset;\n\t}\n\tTime.setTimezoneOffset = setTimezoneOffset;\n\tfunction getTimezoneOffset() {\n\t\treturn timezoneOffset;\n\t}\n\tTime.getTimezoneOffset = getTimezoneOffset;\n\tfunction getDateNumber(date = /* @__PURE__ */ new Date(), offset) {\n\t\tif (typeof date === \"number\") date = new Date(date);\n\t\tif (offset === void 0) offset = timezoneOffset;\n\t\treturn Math.floor((date.valueOf() / Time.minute - offset) / 1440);\n\t}\n\tTime.getDateNumber = getDateNumber;\n\tfunction fromDateNumber(value, offset) {\n\t\tconst date = new Date(value * Time.day);\n\t\tif (offset === void 0) offset = timezoneOffset;\n\t\treturn new Date(+date + offset * Time.minute);\n\t}\n\tTime.fromDateNumber = fromDateNumber;\n\tconst numeric = /\\d+(?:\\.\\d+)?/.source;\n\tconst timeRegExp = new RegExp(`^${[\n\t\t\"w(?:eek(?:s)?)?\",\n\t\t\"d(?:ay(?:s)?)?\",\n\t\t\"h(?:our(?:s)?)?\",\n\t\t\"m(?:in(?:ute)?(?:s)?)?\",\n\t\t\"s(?:ec(?:ond)?(?:s)?)?\"\n\t].map((unit) => `(${numeric}${unit})?`).join(\"\")}$`);\n\tfunction parseTime(source) {\n\t\tconst capture = timeRegExp.exec(source);\n\t\tif (!capture) return 0;\n\t\treturn (parseFloat(capture[1]) * Time.week || 0) + (parseFloat(capture[2]) * Time.day || 0) + (parseFloat(capture[3]) * Time.hour || 0) + (parseFloat(capture[4]) * Time.minute || 0) + (parseFloat(capture[5]) * Time.second || 0);\n\t}\n\tTime.parseTime = parseTime;\n\tfunction parseDate(date) {\n\t\tconst parsed = parseTime(date);\n\t\tif (parsed) date = Date.now() + parsed;\n\t\telse if (/^\\d{1,2}(:\\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;\n\t\telse if (/^\\d{1,2}-\\d{1,2}-\\d{1,2}(:\\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;\n\t\treturn date ? new Date(date) : /* @__PURE__ */ new Date();\n\t}\n\tTime.parseDate = parseDate;\n\tfunction format(ms) {\n\t\tconst abs = Math.abs(ms);\n\t\tif (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + \"d\";\n\t\telse if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + \"h\";\n\t\telse if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + \"m\";\n\t\telse if (abs >= Time.second) return Math.round(ms / Time.second) + \"s\";\n\t\treturn ms + \"ms\";\n\t}\n\tTime.format = format;\n\tfunction toDigits(source, length = 2) {\n\t\treturn source.toString().padStart(length, \"0\");\n\t}\n\tTime.toDigits = toDigits;\n\tfunction template(template, time = /* @__PURE__ */ new Date()) {\n\t\treturn template.replace(\"yyyy\", time.getFullYear().toString()).replace(\"yy\", time.getFullYear().toString().slice(2)).replace(\"MM\", toDigits(time.getMonth() + 1)).replace(\"dd\", toDigits(time.getDate())).replace(\"hh\", toDigits(time.getHours())).replace(\"mm\", toDigits(time.getMinutes())).replace(\"ss\", toDigits(time.getSeconds())).replace(\"SSS\", toDigits(time.getMilliseconds(), 3));\n\t}\n\tTime.template = template;\n})(Time || (Time = {}));\n//#endregion\nexport { Binary, Time, arrayBufferToBase64, arrayBufferToHex, base64ToArrayBuffer, camelCase, camelize, capitalize, clone, contain, createVolatile, deduplicate, deepEqual, defineProperty, difference, filterKeys, formatProperty, hexToArrayBuffer, hyphenate, intersection, is, isNonNullable, isNullable, isPlainObject, isVolatile, makeArray, mapValues, mapValues as valueMap, noop, omit, paramCase, pick, remove, sanitize, snakeCase, trimSlash, uncapitalize, union, updateVolatile, volatileEntries };\n", "/**\r\n * Target-host rule parsing shared by the Host matcher and the settings page.\r\n *\r\n * This module deliberately has no undici import: the browser bundle imports it\r\n * too, and the two halves must agree on what an entry means before either can\r\n * safely warn about an entry that will never match.\r\n */\r\n\r\n/** Split a host-rule string into raw, non-empty tokens. */\r\nexport function splitHostRules(raw: string): string[] {\r\n return raw\r\n .split(/[,\\s]+/)\r\n .map(entry => entry.trim())\r\n .filter(entry => entry.length > 0)\r\n}\r\n\r\n/**\r\n * Normalize one raw rule for suffix matching.\r\n *\r\n * A leading `.` or `*.` is dropped: both spellings mean \"this host and its\r\n * subdomains\". Lower-casing belongs here as well, because the Host compares\r\n * against a WHATWG hostname that is already lower-cased.\r\n */\r\nexport function normalizeHostRule(raw: string): string {\r\n return raw.trim().replace(/^\\*?\\./, '').toLowerCase()\r\n}\r\n\r\n/** Split and normalize a host-rule string into matchable entries. */\r\nexport function parseHostList(raw: string): string[] {\r\n return splitHostRules(raw)\r\n .map(normalizeHostRule)\r\n .filter(entry => entry.length > 0)\r\n}\r\n\r\n/**\r\n * Whether a host is covered by one rule list.\r\n *\r\n * `*` matches everything; otherwise a rule matches the host itself or any\r\n * subdomain of it (`example.com` covers `api.example.com`).\r\n */\r\nexport function hostMatches(host: string, rules: readonly string[]): boolean {\r\n for (const rule of rules) {\r\n if (rule === '*') return true\r\n if (host === rule || host.endsWith(`.${rule}`)) return true\r\n }\r\n return false\r\n}\r\n\r\n/** Whether a raw token is a bracketed IPv6 literal, e.g. `[::1]`. */\r\nfunction isBracketedIpv6(token: string): boolean {\r\n return /^\\[[0-9a-f:.]+\\]$/i.test(token)\r\n}\r\n\r\n/** Whether a raw token can never match the Host's hostname comparison. */\r\nexport function hostRuleProblem(raw: string): string | undefined {\r\n const token = raw.trim()\r\n if (token.length === 0) return undefined\r\n // A bare `*.` normalizes to an empty string and disappears from the match\r\n // list entirely; report it rather than silently accepting a no-op.\r\n if (token === '*.' || normalizeHostRule(token).length === 0) return '\u7A7A\u901A\u914D\u7B26'\r\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(token)) return '\u5E26\u534F\u8BAE\u524D\u7F00'\r\n if (token.includes('/')) return '\u5E26\u8DEF\u5F84'\r\n // Host compares hostnames, never `host:port`; a bracketed IPv6 literal is the\r\n // one legitimate colon in a hostname.\r\n if (token.includes(':') && !isBracketedIpv6(token)) return '\u5E26\u7AEF\u53E3\u6216\u975E\u6CD5\u5192\u53F7'\r\n // Host strips only a leading `.`/`*.`; any other `*` cannot be a hostname.\r\n const withoutLeadingWildcard = token.replace(/^\\*\\./, '')\r\n if (withoutLeadingWildcard.includes('*') && token !== '*') return '\u6742\u6563\u901A\u914D\u7B26'\r\n return undefined\r\n}\r\n\r\n/** Every raw token that will never match, in the order it was typed. */\r\nexport function deadRuleEntries(raw: string): string[] {\r\n return splitHostRules(raw).filter(entry => hostRuleProblem(entry) !== undefined)\r\n}\r\n"],
|
|
5
|
+
"mappings": ";;;;;;;AAQA,SAAS,SAASA,oBAAmB;;;AC4BrC,SAAS,yBAAyB;AAClC,SAAS,SAAS,mBAAmB;AAqCrC,IAAM,YAAY,uBAAO,IAAI,oCAAoC;AAkBjE,SAAS,YAAY,OAAoC;AACvD,MAAI;AACF,QAAI,OAAO,UAAU,SAAU,QAAO,IAAI,IAAI,KAAK,EAAE;AACrD,QAAI,iBAAiB,IAAK,QAAO,MAAM;AACvC,UAAM,MAAO,OAAgD;AAC7D,QAAI,OAAO,QAAQ,SAAU,QAAO,IAAI,IAAI,GAAG,EAAE;AAAA,EACnD,QAAQ;AACN,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,sBAAmC;AAC1C,QAAM,UAAW,WAAuD,SAAS;AACjF,MAAI,YAAY,QAAW;AACzB,YAAQ,UAAU;AAClB,WAAO;AAAA,EACT;AAEA,MAAI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AU,MAAM;AAAA,QAChB,aAAa,MAAM;AAAA,MACrB,EAAE;AAAA,MACF,UAAU,OAAO,YAAY,QAAQ;AAAA,MACrC,MAAM,OAAO,YAAY,IAAI;AAAA,MAC7B,SAAS,OAAO,YAAY,OAAO;AAAA,MACnC,iBAAiB,MAAM;AACrB,YAAI,iBAAiB;AACrB,YAAI,iBAAiB;AACrB,YAAI,eAAe;AACnB,mBAAW,WAAW,WAAW,OAAO,GAAG;AACzC,0BAAgB,QAAQ;AACxB,2BAAiB,KAAK,IAAI,gBAAgB,QAAQ,IAAI;AACtD,qBAAW,SAAS,QAAQ,OAAO,GAAG;AACpC,gBAAI,KAAK,IAAI,IAAI,MAAM,MAAM,uBAAwB,mBAAkB;AAAA,UACzE;AAAA,QACF;AACA,eAAO;AAAA,UACL,WAAW,WAAW;AAAA,UACtB,SAAS,WAAW;AAAA,UACpB;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,MACF,GAAG;AAAA,IACL;AAAA,EACF,CAAC;AACH;",
|
|
6
6
|
"names": ["undiciFetch", "routedFetch", "value", "value", "Binary", "result", "a", "b", "Time", "date", "template", "options", "pattern", "value", "extra", "resolve", "toJSON", "date", "toString", "name", "key", "require", "volatile", "snapshot", "name", "code", "undiciFetch"]
|
|
7
7
|
}
|