thebird 1.2.79 → 1.2.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/.github/workflows/publish.yml +9 -1
  2. package/CHANGELOG.md +217 -0
  3. package/CLAUDE.md +16 -0
  4. package/docs/agent-chat.js +7 -4
  5. package/docs/app.js +14 -11
  6. package/docs/defaults.json +1 -1
  7. package/docs/index.html +23 -6
  8. package/docs/kilo-fs-mirror.js +15 -0
  9. package/docs/kilo-http-stream.js +47 -0
  10. package/docs/node-builtins.js +24 -0
  11. package/docs/preview/index.html +32 -0
  12. package/docs/preview-sw-client.js +37 -6
  13. package/docs/preview-sw.js +55 -51
  14. package/docs/shell-awk.js +113 -0
  15. package/docs/shell-builtins-extra.js +121 -0
  16. package/docs/shell-builtins-text.js +109 -0
  17. package/docs/shell-builtins-util.js +112 -0
  18. package/docs/shell-builtins.js +183 -0
  19. package/docs/shell-bun.js +45 -0
  20. package/docs/shell-control.js +132 -0
  21. package/docs/shell-deno.js +54 -0
  22. package/docs/shell-exec.js +85 -0
  23. package/docs/shell-expand.js +164 -0
  24. package/docs/shell-fd.js +86 -0
  25. package/docs/shell-jobs.js +86 -0
  26. package/docs/shell-node-advanced.js +86 -0
  27. package/docs/shell-node-brotli.js +22 -0
  28. package/docs/shell-node-busnet.js +90 -0
  29. package/docs/shell-node-cipher.js +61 -0
  30. package/docs/shell-node-cluster.js +33 -0
  31. package/docs/shell-node-coreutils.js +36 -0
  32. package/docs/shell-node-crypto.js +137 -0
  33. package/docs/shell-node-dns.js +41 -0
  34. package/docs/shell-node-extras.js +148 -0
  35. package/docs/shell-node-firefox.js +95 -0
  36. package/docs/shell-node-git.js +60 -0
  37. package/docs/shell-node-inspector.js +39 -0
  38. package/docs/shell-node-io.js +131 -0
  39. package/docs/shell-node-ipc.js +15 -0
  40. package/docs/shell-node-keyobject.js +60 -0
  41. package/docs/shell-node-modules.js +157 -0
  42. package/docs/shell-node-native.js +31 -0
  43. package/docs/shell-node-net.js +71 -0
  44. package/docs/shell-node-observe.js +80 -0
  45. package/docs/shell-node-opfs.js +54 -0
  46. package/docs/shell-node-procfs.js +42 -0
  47. package/docs/shell-node-profiler.js +50 -0
  48. package/docs/shell-node-registry.js +24 -0
  49. package/docs/shell-node-resolve.js +147 -0
  50. package/docs/shell-node-runtime.js +83 -0
  51. package/docs/shell-node-srcmap.js +52 -0
  52. package/docs/shell-node-stdlib.js +103 -0
  53. package/docs/shell-node-streams.js +66 -0
  54. package/docs/shell-node-tar.js +47 -0
  55. package/docs/shell-node-testrunner.js +35 -0
  56. package/docs/shell-node-util-extras.js +66 -0
  57. package/docs/shell-node.js +175 -169
  58. package/docs/shell-npm.js +173 -0
  59. package/docs/shell-parser.js +122 -0
  60. package/docs/shell-pm-layout.js +62 -0
  61. package/docs/shell-pm.js +39 -0
  62. package/docs/shell-posix.js +70 -0
  63. package/docs/shell-procsub.js +65 -0
  64. package/docs/shell-readline.js +59 -4
  65. package/docs/shell-runtime.js +37 -0
  66. package/docs/shell-sed.js +83 -0
  67. package/docs/shell-signals.js +54 -0
  68. package/docs/shell-sw-jobs.js +76 -0
  69. package/docs/shell-ts.js +30 -0
  70. package/docs/shell.js +161 -152
  71. package/docs/terminal.js +9 -11
  72. package/docs/todo.html +211 -0
  73. package/package.json +1 -1
  74. package/server.js +43 -4
  75. package/start-kilo.js +45 -0
  76. package/test.js +199 -0
  77. package/.codeinsight +0 -73
  78. package/docs/acp-stream.js +0 -102
  79. package/docs/coi-serviceworker.js +0 -2
@@ -1 +1 @@
1
- {"package.json":"{\r\n \"name\": \"thebird\",\r\n \"version\": \"1.2.66\",\r\n \"description\": \"Anthropic SDK to Gemini streaming bridge — drop-in proxy that translates Anthropic message format and tool calls to Google Gemini\",\r\n \"scripts\": {\r\n \"start\": \"node serve.js\"\r\n },\r\n \"main\": \"index.js\",\r\n \"types\": \"index.d.ts\",\r\n \"exports\": {\r\n \".\": {\r\n \"types\": \"./index.d.ts\",\r\n \"require\": \"./index.js\",\r\n \"import\": \"./index.js\",\r\n \"default\": \"./index.js\"\r\n }\r\n },\r\n \"keywords\": [\r\n \"anthropic\",\r\n \"gemini\",\r\n \"google\",\r\n \"ai\",\r\n \"streaming\",\r\n \"proxy\",\r\n \"bridge\",\r\n \"tool-use\",\r\n \"vision\",\r\n \"multimodal\",\r\n \"router\",\r\n \"openai\",\r\n \"deepseek\",\r\n \"multi-provider\"\r\n ],\r\n \"author\": \"AnEntrypoint\",\r\n \"license\": \"MIT\",\r\n \"repository\": {\r\n \"type\": \"git\",\r\n \"url\": \"https://github.com/AnEntrypoint/thebird.git\"\r\n },\r\n \"dependencies\": {\r\n \"@anthropic-ai/sdk\": \"^0.88.0\",\r\n \"@google/genai\": \"^1.0.0\"\r\n },\r\n \"engines\": {\r\n \"node\": \">=18\"\r\n },\r\n \"devDependencies\": {\r\n \"@tailwindcss/cli\": \"^4.2.2\",\r\n \"@webcontainer/api\": \"^1.6.4\",\r\n \"@xterm/addon-fit\": \"^0.11.0\",\r\n \"@xterm/xterm\": \"^6.0.0\",\r\n \"esbuild\": \"^0.28.0\",\r\n \"htm\": \"^3.1.1\",\r\n \"tailwindcss\": \"^4.2.2\",\r\n \"webjsx\": \"^0.0.73\"\r\n }\r\n}\r\n","lib/client.js":"const { GoogleGenAI } = require('@google/genai');\r\n\r\nlet _client = null;\r\n\r\nfunction getClient(apiKey) {\r\n if (!_client || apiKey) _client = new GoogleGenAI({ apiKey: apiKey || process.env.GEMINI_API_KEY });\r\n return _client;\r\n}\r\n\r\nmodule.exports = { getClient };\r\n","lib/errors.js":"class GeminiError extends Error {\r\n constructor(message, { status, code, retryable = false } = {}) {\r\n super(message);\r\n this.name = 'GeminiError';\r\n this.status = status;\r\n this.code = code;\r\n this.retryable = retryable;\r\n }\r\n}\r\n\r\nfunction isRetryable(err) {\r\n if (err instanceof GeminiError) return err.retryable;\r\n const status = err?.status ?? err?.code;\r\n if (status === 429) return true;\r\n if (typeof status === 'number' && status >= 500) return true;\r\n const msg = err?.message ?? '';\r\n return /quota|rate.?limit|overloaded|unavailable/i.test(msg);\r\n}\r\n\r\nfunction parseRetryDelay(err) {\r\n try {\r\n const body = typeof err.message === 'string' ? JSON.parse(err.message) : err.message;\r\n const details = body?.error?.details || [];\r\n const retryInfo = details.find(d => d['@type']?.includes('RetryInfo'));\r\n if (retryInfo?.retryDelay) {\r\n const secs = parseFloat(retryInfo.retryDelay);\r\n if (!isNaN(secs)) return secs * 1000;\r\n }\r\n } catch (_) {}\r\n return null;\r\n}\r\n\r\nasync function withRetry(fn, maxRetries = 3) {\r\n let lastErr;\r\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\r\n try {\r\n return await fn();\r\n } catch (err) {\r\n lastErr = err;\r\n if (!isRetryable(err) || attempt === maxRetries) throw err;\r\n const suggested = parseRetryDelay(err);\r\n const delay = suggested != null ? suggested + Math.random() * 1000 : Math.min(1000 * 2 ** attempt + Math.random() * 200, 16000);\r\n await new Promise(r => setTimeout(r, delay));\r\n }\r\n }\r\n throw lastErr;\r\n}\r\n\r\nmodule.exports = { GeminiError, isRetryable, withRetry };\r\n","lib/convert.js":"function cleanSchema(schema) {\r\n if (!schema || typeof schema !== 'object') return schema;\r\n if (Array.isArray(schema)) return schema.map(cleanSchema);\r\n const out = {};\r\n for (const [k, v] of Object.entries(schema)) {\r\n if (k === 'additionalProperties' || k === '$schema') continue;\r\n out[k] = cleanSchema(v);\r\n }\r\n return out;\r\n}\r\n\r\nfunction convertTools(tools) {\r\n if (!tools || typeof tools !== 'object') return [];\r\n return Object.entries(tools).map(([name, t]) => ({\r\n name,\r\n description: t.description || '',\r\n parameters: cleanSchema(t.parameters?.jsonSchema || t.parameters || { type: 'object' })\r\n }));\r\n}\r\n\r\nfunction convertImageBlock(b) {\r\n // Handle inlineData: { mimeType, data } (base64)\r\n if (b.inlineData || b.type === 'image') {\r\n const src = b.inlineData || b.source;\r\n if (src?.data) return { inlineData: { mimeType: src.mimeType || 'image/jpeg', data: src.data } };\r\n if (src?.url) return { fileData: { mimeType: src.mimeType || 'image/jpeg', fileUri: src.url } };\r\n }\r\n // Handle fileData: { mimeType, fileUri }\r\n if (b.fileData) return { fileData: { mimeType: b.fileData.mimeType, fileUri: b.fileData.fileUri } };\r\n // Anthropic-style image block\r\n if (b.type === 'image' && b.source) {\r\n if (b.source.type === 'base64') return { inlineData: { mimeType: b.source.media_type, data: b.source.data } };\r\n if (b.source.type === 'url') return { fileData: { mimeType: b.source.media_type || 'image/jpeg', fileUri: b.source.url } };\r\n }\r\n return null;\r\n}\r\n\r\nfunction convertMessages(messages) {\r\n const contents = [];\r\n for (const m of messages) {\r\n const role = m.role === 'assistant' ? 'model' : 'user';\r\n if (typeof m.content === 'string') {\r\n if (m.content) contents.push({ role, parts: [{ text: m.content }] });\r\n continue;\r\n }\r\n if (Array.isArray(m.content)) {\r\n const parts = m.content.map(b => {\r\n if (b.type === 'text' && b.text) return { text: b.text };\r\n if (b.type === 'image' || b.inlineData || b.fileData) return convertImageBlock(b);\r\n if (b.type === 'tool_use') return { functionCall: { name: b.name, args: b.input || {} } };\r\n if (b.type === 'tool_result') {\r\n let resp;\r\n try { resp = typeof b.content === 'string' ? JSON.parse(b.content) : (b.content || {}); }\r\n catch { resp = { result: b.content }; }\r\n return { functionResponse: { name: b.name || 'unknown', response: resp } };\r\n }\r\n return null;\r\n }).filter(Boolean);\r\n if (parts.length) contents.push({ role, parts });\r\n }\r\n }\r\n return contents;\r\n}\r\n\r\nfunction extractModelId(model) {\r\n if (typeof model === 'string') return model;\r\n if (model?.modelId) return model.modelId;\r\n if (model?.id) return model.id;\r\n return 'gemini-2.0-flash';\r\n}\r\n\r\nfunction buildConfig({ system, tools, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities } = {}) {\r\n const geminiTools = convertTools(tools);\r\n const config = {\r\n maxOutputTokens: maxOutputTokens ?? 8192,\r\n temperature: temperature ?? 0.5,\r\n topP: topP ?? 0.95\r\n };\r\n if (topK != null) config.topK = topK;\r\n if (system) config.systemInstruction = system;\r\n if (geminiTools.length > 0) config.tools = [{ functionDeclarations: geminiTools }];\r\n if (safetySettings) config.safetySettings = safetySettings;\r\n if (responseModalities) config.responseModalities = responseModalities;\r\n return { config, geminiTools };\r\n}\r\n\r\nmodule.exports = { cleanSchema, convertTools, convertMessages, extractModelId, buildConfig, convertImageBlock };\r\n","lib/config.js":"const fs = require('fs');\r\nconst path = require('path');\r\nconst os = require('os');\r\n\r\nfunction interpolateEnv(val) {\r\n if (typeof val === 'string') return val.replace(/\\$\\{([^}]+)\\}|\\$([A-Z_][A-Z0-9_]*)/g, (_, a, b) => process.env[a || b] || '');\r\n if (Array.isArray(val)) return val.map(interpolateEnv);\r\n if (val && typeof val === 'object') {\r\n const out = {};\r\n for (const [k, v] of Object.entries(val)) out[k] = interpolateEnv(v);\r\n return out;\r\n }\r\n return val;\r\n}\r\n\r\nfunction loadConfig(configPath) {\r\n const fp = configPath || process.env.THEBIRD_CONFIG || path.join(os.homedir(), '.thebird', 'config.json');\r\n try {\r\n const raw = JSON.parse(fs.readFileSync(fp, 'utf8'));\r\n return interpolateEnv(raw);\r\n } catch { return {}; }\r\n}\r\n\r\nmodule.exports = { loadConfig, interpolateEnv };\r\n","lib/router.js":"const { loadConfig } = require('./config');\r\n\r\nconst SUBAGENT_RE = /<CCR-SUBAGENT-MODEL>([^<]+)<\\/CCR-SUBAGENT-MODEL>/;\r\n\r\nfunction estimateTokens(messages, system) {\r\n let chars = typeof system === 'string' ? system.length : (system ? JSON.stringify(system).length : 0);\r\n for (const m of (messages || [])) {\r\n chars += typeof m.content === 'string' ? m.content.length : JSON.stringify(m.content || '').length;\r\n }\r\n return Math.ceil(chars / 4);\r\n}\r\n\r\nfunction extractSubagentModel(messages) {\r\n const first = messages?.[0];\r\n if (!first) return null;\r\n const text = typeof first.content === 'string' ? first.content :\r\n (Array.isArray(first.content) ? first.content.map(b => b.text || '').join('') : '');\r\n const m = SUBAGENT_RE.exec(text);\r\n return m ? m[1].trim() : null;\r\n}\r\n\r\nfunction parseProviderModel(str) {\r\n const idx = str.indexOf(',');\r\n if (idx === -1) return { providerName: null, modelName: str };\r\n return { providerName: str.slice(0, idx), modelName: str.slice(idx + 1) };\r\n}\r\n\r\nasync function route(params, routerCfg, customRouterFn) {\r\n const { messages, system, taskType } = params;\r\n\r\n if (customRouterFn) {\r\n const custom = await customRouterFn(params, routerCfg);\r\n if (custom) return parseProviderModel(custom);\r\n }\r\n\r\n const subagent = extractSubagentModel(messages);\r\n if (subagent) return parseProviderModel(subagent);\r\n\r\n if (taskType === 'background' && routerCfg.background) return parseProviderModel(routerCfg.background);\r\n if (taskType === 'think' && routerCfg.think) return parseProviderModel(routerCfg.think);\r\n if (taskType === 'webSearch' && routerCfg.webSearch) return parseProviderModel(routerCfg.webSearch);\r\n if (taskType === 'image' && routerCfg.image) return parseProviderModel(routerCfg.image);\r\n\r\n const threshold = routerCfg.longContextThreshold || 60000;\r\n if (routerCfg.longContext && estimateTokens(messages, system) > threshold) return parseProviderModel(routerCfg.longContext);\r\n\r\n if (routerCfg.default) return parseProviderModel(routerCfg.default);\r\n return { providerName: null, modelName: null };\r\n}\r\n\r\nmodule.exports = { route, estimateTokens, parseProviderModel };\r\n","lib/transformers.js":"function removeCacheControl(obj) {\r\n if (!obj || typeof obj !== 'object') return obj;\r\n if (Array.isArray(obj)) return obj.map(removeCacheControl);\r\n const out = {};\r\n for (const [k, v] of Object.entries(obj)) {\r\n if (k === 'cache_control') continue;\r\n out[k] = removeCacheControl(v);\r\n }\r\n return out;\r\n}\r\n\r\nconst BUILT_IN = {\r\n cleancache: {\r\n request(req) { return { ...req, messages: removeCacheControl(req.messages), system: removeCacheControl(req.system) }; }\r\n },\r\n deepseek: {\r\n request(req) {\r\n const r = removeCacheControl(req);\r\n if (r.system && typeof r.system !== 'string') {\r\n r.system = (Array.isArray(r.system) ? r.system : [r.system]).map(b => b.text || '').join('\\n');\r\n }\r\n return r;\r\n }\r\n },\r\n openrouter: {\r\n options: {},\r\n request(req, opts) {\r\n const headers = { 'HTTP-Referer': 'https://github.com/AnEntrypoint/thebird', 'X-Title': 'thebird', ...(opts || {}).headers };\r\n if ((opts || {}).provider) req = { ...req, provider: (opts || {}).provider };\r\n return { ...req, _extraHeaders: { ...(req._extraHeaders || {}), ...headers } };\r\n }\r\n },\r\n maxtoken: {\r\n request(req, opts) { return { ...req, max_tokens: (opts || {}).max_tokens || req.max_tokens }; }\r\n },\r\n tooluse: {\r\n request(req) {\r\n if (req.tools && req.tools.length > 0) return { ...req, tool_choice: { type: 'required' } };\r\n return req;\r\n }\r\n },\r\n reasoning: {\r\n request(req) { return req; },\r\n response(res) {\r\n if (!res.choices) return res;\r\n return {\r\n ...res,\r\n choices: res.choices.map(c => {\r\n if (!c.message) return c;\r\n const msg = { ...c.message };\r\n if (msg.reasoning_content) { msg._reasoning = msg.reasoning_content; delete msg.reasoning_content; }\r\n return { ...c, message: msg };\r\n })\r\n };\r\n }\r\n },\r\n sampling: {\r\n request(req) {\r\n const r = { ...req };\r\n delete r.top_k;\r\n delete r.repetition_penalty;\r\n return r;\r\n }\r\n },\r\n groq: {\r\n request(req) {\r\n const r = { ...req };\r\n delete r.top_k;\r\n return r;\r\n }\r\n }\r\n};\r\n\r\nfunction resolveTransformers(useList, customMap) {\r\n if (!useList) return [];\r\n return useList.map(entry => {\r\n const name = Array.isArray(entry) ? entry[0] : entry;\r\n const opts = Array.isArray(entry) ? entry[1] : undefined;\r\n const t = (customMap && customMap[name]) || BUILT_IN[name];\r\n if (!t) { console.warn('[thebird] unknown transformer:', name); return null; }\r\n return { transformer: t, opts };\r\n }).filter(Boolean);\r\n}\r\n\r\nfunction applyRequestTransformers(req, transformers) {\r\n return transformers.reduce((r, { transformer, opts }) => transformer.request ? transformer.request(r, opts) : r, req);\r\n}\r\n\r\nfunction applyResponseTransformers(res, transformers) {\r\n return transformers.reduce((r, { transformer, opts }) => transformer.response ? transformer.response(r, opts) : r, res);\r\n}\r\n\r\nmodule.exports = { resolveTransformers, applyRequestTransformers, applyResponseTransformers, BUILT_IN };\r\n","lib/providers/openai.js":"const { GeminiError } = require('../errors');\r\n\r\nfunction convertMessages(messages, system) {\r\n const result = [];\r\n if (system) result.push({ role: 'system', content: typeof system === 'string' ? system : JSON.stringify(system) });\r\n for (const m of messages) {\r\n if (typeof m.content === 'string') { result.push({ role: m.role, content: m.content }); continue; }\r\n if (!Array.isArray(m.content)) continue;\r\n const toolCalls = m.content.filter(b => b.type === 'tool_use');\r\n const toolResults = m.content.filter(b => b.type === 'tool_result');\r\n if (toolResults.length) {\r\n for (const b of toolResults) {\r\n const c = typeof b.content === 'string' ? b.content : JSON.stringify(b.content || '');\r\n result.push({ role: 'tool', tool_call_id: b.tool_use_id || b.id || b.name, content: c });\r\n }\r\n continue;\r\n }\r\n const textParts = m.content.filter(b => b.type === 'text').map(b => b.text).join('');\r\n if (toolCalls.length) {\r\n result.push({ role: 'assistant', content: textParts || null,\r\n tool_calls: toolCalls.map(b => ({ id: b.id || ('call_' + Math.random().toString(36).slice(2,8)), type: 'function',\r\n function: { name: b.name, arguments: JSON.stringify(b.input || {}) } })) });\r\n } else {\r\n result.push({ role: m.role, content: textParts });\r\n }\r\n }\r\n return result;\r\n}\r\n\r\nfunction convertTools(tools) {\r\n if (!tools || typeof tools !== 'object') return undefined;\r\n const list = Object.entries(tools).map(([name, t]) => ({\r\n type: 'function', function: { name, description: t.description || '',\r\n parameters: t.parameters?.jsonSchema || t.parameters || { type: 'object' } }\r\n }));\r\n return list.length ? list : undefined;\r\n}\r\n\r\nasync function callOpenAI({ url, apiKey, headers, body }) {\r\n const res = await fetch(url, { method: 'POST',\r\n headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}`, ...(headers || {}) },\r\n body: JSON.stringify(body) });\r\n if (!res.ok) { const t = await res.text(); throw new GeminiError(t, { status: res.status, retryable: res.status === 429 || res.status >= 500 }); }\r\n return res;\r\n}\r\n\r\nasync function* streamOpenAI({ url, apiKey, headers, body, tools, onStepFinish }) {\r\n while (true) {\r\n yield { type: 'start-step' };\r\n const res = await callOpenAI({ url, apiKey, headers, body: { ...body, stream: true } });\r\n const reader = res.body.getReader();\r\n const dec = new TextDecoder();\r\n let buf = '', toolCallsMap = {};\r\n try {\r\n while (true) {\r\n const { done, value } = await reader.read();\r\n if (done) break;\r\n buf += dec.decode(value, { stream: true });\r\n const lines = buf.split('\\n');\r\n buf = lines.pop();\r\n for (const line of lines) {\r\n if (!line.startsWith('data: ')) continue;\r\n const d = line.slice(6).trim();\r\n if (d === '[DONE]') break;\r\n let chunk; try { chunk = JSON.parse(d); } catch { continue; }\r\n const delta = chunk.choices?.[0]?.delta;\r\n if (!delta) continue;\r\n if (delta.content) yield { type: 'text-delta', textDelta: delta.content };\r\n if (delta.tool_calls) {\r\n for (const tc of delta.tool_calls) {\r\n const idx = tc.index ?? 0;\r\n if (!toolCallsMap[idx]) toolCallsMap[idx] = { id: tc.id || '', name: '', args: '' };\r\n if (tc.id) toolCallsMap[idx].id = tc.id;\r\n if (tc.function?.name) toolCallsMap[idx].name += tc.function.name;\r\n if (tc.function?.arguments) toolCallsMap[idx].args += tc.function.arguments;\r\n }\r\n }\r\n }\r\n }\r\n } finally { reader.releaseLock(); }\r\n\r\n const pending = Object.values(toolCallsMap);\r\n if (!pending.length) {\r\n yield { type: 'finish-step', finishReason: 'stop' };\r\n if (onStepFinish) await onStepFinish();\r\n return;\r\n }\r\n const toolResultMsgs = [];\r\n for (const tc of pending) {\r\n let args; try { args = JSON.parse(tc.args || '{}'); } catch { args = {}; }\r\n const toolDef = tools?.[tc.name];\r\n let result = toolDef ? null : { error: true, message: 'Tool not found: ' + tc.name };\r\n if (toolDef?.execute) try { result = await toolDef.execute(args, { toolCallId: tc.id }); } catch(e) { result = { error: true, message: e.message }; }\r\n yield { type: 'tool-call', toolCallId: tc.id, toolName: tc.name, args };\r\n yield { type: 'tool-result', toolCallId: tc.id, toolName: tc.name, args, result };\r\n toolResultMsgs.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(result ?? '') });\r\n }\r\n yield { type: 'finish-step', finishReason: 'tool-calls' };\r\n if (onStepFinish) await onStepFinish();\r\n body = { ...body, messages: [...body.messages,\r\n { role: 'assistant', content: null, tool_calls: pending.map(tc => ({ id: tc.id, type: 'function', function: { name: tc.name, arguments: tc.args } })) },\r\n ...toolResultMsgs\r\n ]};\r\n toolCallsMap = {};\r\n }\r\n}\r\n\r\nasync function generateOpenAI({ url, apiKey, headers, body, tools }) {\r\n while (true) {\r\n const res = await callOpenAI({ url, apiKey, headers, body: { ...body, stream: false } });\r\n const data = await res.json();\r\n const msg = data.choices?.[0]?.message;\r\n if (!msg) throw new GeminiError('No message in response', { retryable: false });\r\n if (!msg.tool_calls?.length) return { text: msg.content || '', response: data };\r\n const toolResultMsgs = [];\r\n for (const tc of msg.tool_calls) {\r\n let args; try { args = JSON.parse(tc.function?.arguments || '{}'); } catch { args = {}; }\r\n const toolDef = tools?.[tc.function?.name];\r\n let result = toolDef ? null : { error: true, message: 'Tool not found: ' + tc.function?.name };\r\n if (toolDef?.execute) try { result = await toolDef.execute(args); } catch(e) { result = { error: true, message: e.message }; }\r\n toolResultMsgs.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(result ?? '') });\r\n }\r\n body = { ...body, messages: [...body.messages, msg, ...toolResultMsgs] };\r\n }\r\n}\r\n\r\nmodule.exports = { streamOpenAI, generateOpenAI, convertMessages, convertTools };\r\n","lib/cloud-generate.js":"const { convertMessages, convertTools, cleanSchema, extractModelId, buildConfig } = require('./convert');\r\nconst { ensureAuth, CODE_ASSIST_BASE, CODE_ASSIST_HEADERS } = require('./oauth');\r\nconst crypto = require('crypto');\r\n\r\nfunction buildUserAgent(model) {\r\n return `gemini-cli/0.30.0 (node; ${process.platform}) model/${model || 'unknown'}`;\r\n}\r\n\r\nasync function cloudGenerate({ model, system, messages, tools, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities, authPort }) {\r\n const tokens = await ensureAuth(authPort);\r\n const modelId = extractModelId(model);\r\n const contents = convertMessages(messages);\r\n const { config } = buildConfig({ system, tools, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities });\r\n\r\n const request = { contents };\r\n if (config.systemInstruction) request.systemInstruction = { parts: [{ text: config.systemInstruction }] };\r\n if (config.tools) request.tools = config.tools;\r\n const genConfig = {};\r\n if (config.maxOutputTokens) genConfig.maxOutputTokens = config.maxOutputTokens;\r\n if (config.temperature != null) genConfig.temperature = config.temperature;\r\n if (config.topP != null) genConfig.topP = config.topP;\r\n if (config.topK != null) genConfig.topK = config.topK;\r\n if (config.responseModalities) genConfig.responseModalities = config.responseModalities;\r\n if (Object.keys(genConfig).length) request.generationConfig = genConfig;\r\n\r\n const envelope = { project: tokens.projectId, model: modelId, user_prompt_id: crypto.randomUUID(), request };\r\n\r\n const res = await fetch(`${CODE_ASSIST_BASE}:generateContent`, {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n Authorization: `Bearer ${tokens.accessToken}`,\r\n 'User-Agent': buildUserAgent(modelId),\r\n 'x-activity-request-id': crypto.randomUUID(),\r\n ...CODE_ASSIST_HEADERS\r\n },\r\n body: JSON.stringify(envelope)\r\n });\r\n\r\n if (!res.ok) throw new Error(`Cloud generate failed (${res.status}): ${await res.text()}`);\r\n const data = await res.json();\r\n const inner = data.response || data;\r\n const candidate = inner.candidates?.[0];\r\n if (!candidate) throw new Error('No candidates returned');\r\n const allParts = candidate.content?.parts || [];\r\n const text = allParts.filter(p => p.text && !p.thought).map(p => p.text).join('');\r\n return { text, parts: allParts, response: inner };\r\n}\r\n\r\nasync function* cloudStream({ model, system, messages, tools, onStepFinish, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities, authPort }) {\r\n const tokens = await ensureAuth(authPort);\r\n const modelId = extractModelId(model);\r\n const contents = convertMessages(messages);\r\n const { config } = buildConfig({ system, tools, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities });\r\n\r\n const request = { contents };\r\n if (config.systemInstruction) request.systemInstruction = { parts: [{ text: config.systemInstruction }] };\r\n if (config.tools) request.tools = config.tools;\r\n const genConfig = {};\r\n if (config.maxOutputTokens) genConfig.maxOutputTokens = config.maxOutputTokens;\r\n if (config.temperature != null) genConfig.temperature = config.temperature;\r\n if (config.topP != null) genConfig.topP = config.topP;\r\n if (config.topK != null) genConfig.topK = config.topK;\r\n if (config.responseModalities) genConfig.responseModalities = config.responseModalities;\r\n if (Object.keys(genConfig).length) request.generationConfig = genConfig;\r\n\r\n const envelope = { project: tokens.projectId, model: modelId, user_prompt_id: crypto.randomUUID(), request };\r\n\r\n const res = await fetch(`${CODE_ASSIST_BASE}:streamGenerateContent?alt=sse`, {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n Authorization: `Bearer ${tokens.accessToken}`,\r\n 'User-Agent': buildUserAgent(modelId),\r\n 'x-activity-request-id': crypto.randomUUID(),\r\n Accept: 'text/event-stream',\r\n ...CODE_ASSIST_HEADERS\r\n },\r\n body: JSON.stringify(envelope)\r\n });\r\n\r\n if (!res.ok) throw new Error(`Cloud stream failed (${res.status}): ${await res.text()}`);\r\n\r\n yield { type: 'start-step' };\r\n const reader = res.body.getReader();\r\n const decoder = new TextDecoder();\r\n let buffer = '';\r\n\r\n while (true) {\r\n const { done, value } = await reader.read();\r\n if (done) break;\r\n buffer += decoder.decode(value, { stream: true });\r\n const lines = buffer.split('\\n');\r\n buffer = lines.pop() || '';\r\n for (const line of lines) {\r\n const trimmed = line.trim();\r\n if (!trimmed.startsWith('data:')) continue;\r\n const json = trimmed.slice(5).trim();\r\n if (!json || json === '[DONE]') continue;\r\n try {\r\n const parsed = JSON.parse(json);\r\n const inner = parsed.response || parsed;\r\n const parts = inner.candidates?.[0]?.content?.parts || [];\r\n for (const part of parts) {\r\n if (part.text && !part.thought) yield { type: 'text-delta', textDelta: part.text };\r\n if (part.inlineData) yield { type: 'image-data', inlineData: part.inlineData };\r\n }\r\n } catch {}\r\n }\r\n }\r\n yield { type: 'finish-step', finishReason: 'stop' };\r\n if (onStepFinish) await onStepFinish();\r\n}\r\n\r\nfunction streamCloud(params) {\r\n return { fullStream: cloudStream(params), warnings: Promise.resolve([]) };\r\n}\r\n\r\nmodule.exports = { cloudGenerate, cloudStream, streamCloud };\r\n","lib/oauth.js":"const http = require('http');\r\nconst crypto = require('crypto');\r\nconst fs = require('fs');\r\nconst path = require('path');\r\n\r\nconst CLIENT_ID = process.env.GOOGLE_OAUTH_CLIENT_ID || '';\r\nconst CLIENT_SECRET = process.env.GOOGLE_OAUTH_CLIENT_SECRET || '';\r\nconst SCOPES = 'https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile';\r\nconst AUTH_URL = 'https://accounts.google.com/o/oauth2/v2/auth';\r\nconst TOKEN_URL = 'https://oauth2.googleapis.com/token';\r\nconst CODE_ASSIST_BASE = 'https://cloudcode-pa.googleapis.com/v1internal';\r\nconst CODE_ASSIST_HEADERS = { 'X-Goog-Api-Client': 'gl-node/22.17.0', 'Client-Metadata': 'ideType=IDE_UNSPECIFIED,platform=PLATFORM_UNSPECIFIED,pluginType=GEMINI' };\r\nconst TOKEN_PATH = path.join(process.env.HOME || process.env.USERPROFILE || '.', '.thebird', 'oauth-tokens.json');\r\n\r\nfunction base64url(buf) {\r\n return buf.toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\r\n}\r\n\r\nfunction generatePkce() {\r\n const verifier = base64url(crypto.randomBytes(32));\r\n const challenge = base64url(crypto.createHash('sha256').update(verifier).digest());\r\n return { verifier, challenge };\r\n}\r\n\r\nfunction readTokens() {\r\n try { return JSON.parse(fs.readFileSync(TOKEN_PATH, 'utf8')); } catch { return null; }\r\n}\r\n\r\nfunction writeTokens(tokens) {\r\n fs.mkdirSync(path.dirname(TOKEN_PATH), { recursive: true });\r\n fs.writeFileSync(TOKEN_PATH, JSON.stringify(tokens, null, 2));\r\n}\r\n\r\nasync function refreshAccessToken(refreshToken) {\r\n const res = await fetch(TOKEN_URL, {\r\n method: 'POST',\r\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\r\n body: new URLSearchParams({ grant_type: 'refresh_token', refresh_token: refreshToken, client_id: CLIENT_ID, client_secret: CLIENT_SECRET })\r\n });\r\n if (!res.ok) throw new Error('Token refresh failed: ' + await res.text());\r\n const data = await res.json();\r\n return { accessToken: data.access_token, refreshToken: data.refresh_token || refreshToken, expiresAt: Date.now() + data.expires_in * 1000 };\r\n}\r\n\r\nasync function getValidToken() {\r\n const tokens = readTokens();\r\n if (!tokens?.refreshToken) return null;\r\n if (tokens.expiresAt && tokens.expiresAt > Date.now() + 60000) return tokens;\r\n const refreshed = await refreshAccessToken(tokens.refreshToken);\r\n const updated = { ...tokens, ...refreshed };\r\n writeTokens(updated);\r\n return updated;\r\n}\r\n\r\nasync function resolveProject(accessToken) {\r\n const res = await fetch(`${CODE_ASSIST_BASE}:loadCodeAssist`, {\r\n method: 'POST',\r\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}`, ...CODE_ASSIST_HEADERS },\r\n body: JSON.stringify({ metadata: { ideType: 'IDE_UNSPECIFIED', platform: 'PLATFORM_UNSPECIFIED', pluginType: 'GEMINI' } })\r\n });\r\n if (!res.ok) throw new Error('Failed to load Code Assist project');\r\n const data = await res.json();\r\n const proj = data.cloudaicompanionProject;\r\n if (proj) return typeof proj === 'string' ? proj : proj.id;\r\n const tier = data.allowedTiers?.find(t => t.id === 'free-tier') || data.allowedTiers?.[0];\r\n if (!tier) throw new Error('No eligible tier: ' + (data.ineligibleTiers?.[0]?.reasonMessage || 'unknown'));\r\n const obRes = await fetch(`${CODE_ASSIST_BASE}:onboardUser`, {\r\n method: 'POST',\r\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}`, ...CODE_ASSIST_HEADERS },\r\n body: JSON.stringify({ tierId: tier.id || 'legacy-tier', metadata: { ideType: 'IDE_UNSPECIFIED', platform: 'PLATFORM_UNSPECIFIED', pluginType: 'GEMINI' } })\r\n });\r\n if (!obRes.ok) throw new Error('Onboarding failed');\r\n let op = await obRes.json();\r\n for (let i = 0; i < 10 && !op.done && op.name; i++) {\r\n await new Promise(r => setTimeout(r, 5000));\r\n const pollRes = await fetch(`${CODE_ASSIST_BASE}/${op.name}`, { headers: { Authorization: `Bearer ${accessToken}`, ...CODE_ASSIST_HEADERS } });\r\n if (pollRes.ok) op = await pollRes.json();\r\n }\r\n return op.response?.cloudaicompanionProject?.id;\r\n}\r\n\r\nfunction login(port) {\r\n return new Promise((resolve, reject) => {\r\n const { verifier, challenge } = generatePkce();\r\n const state = crypto.randomBytes(32).toString('hex');\r\n const callbackUrl = `http://localhost:${port}/callback`;\r\n const url = new URL(AUTH_URL);\r\n url.searchParams.set('client_id', CLIENT_ID);\r\n url.searchParams.set('response_type', 'code');\r\n url.searchParams.set('redirect_uri', callbackUrl);\r\n url.searchParams.set('scope', SCOPES);\r\n url.searchParams.set('code_challenge', challenge);\r\n url.searchParams.set('code_challenge_method', 'S256');\r\n url.searchParams.set('state', state);\r\n url.searchParams.set('access_type', 'offline');\r\n url.searchParams.set('prompt', 'consent');\r\n\r\n const server = http.createServer(async (req, res) => {\r\n const u = new URL(req.url, `http://localhost:${port}`);\r\n if (!u.pathname.startsWith('/callback')) { res.end('waiting...'); return; }\r\n if (u.searchParams.get('state') !== state) { res.end('Invalid state'); server.close(); reject(new Error('Invalid state')); return; }\r\n const code = u.searchParams.get('code');\r\n try {\r\n const tokRes = await fetch(TOKEN_URL, {\r\n method: 'POST',\r\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\r\n body: new URLSearchParams({ client_id: CLIENT_ID, client_secret: CLIENT_SECRET, code, grant_type: 'authorization_code', redirect_uri: callbackUrl, code_verifier: verifier })\r\n });\r\n if (!tokRes.ok) throw new Error('Token exchange failed: ' + await tokRes.text());\r\n const payload = await tokRes.json();\r\n if (!payload.refresh_token) throw new Error('No refresh token — ensure prompt=consent');\r\n const projectId = await resolveProject(payload.access_token);\r\n const tokens = { accessToken: payload.access_token, refreshToken: payload.refresh_token, expiresAt: Date.now() + payload.expires_in * 1000, projectId };\r\n writeTokens(tokens);\r\n res.end('Authenticated! You can close this tab.');\r\n server.close();\r\n resolve(tokens);\r\n } catch (e) { res.end('Error: ' + e.message); server.close(); reject(e); }\r\n });\r\n server.listen(port, () => {\r\n console.log(`Open this URL to authenticate:\\n${url.toString()}\\n`);\r\n try { const { exec } = require('child_process'); exec(`start \"\" \"${url.toString()}\"`); } catch {}\r\n });\r\n });\r\n}\r\n\r\nasync function ensureAuth(port) {\r\n const existing = await getValidToken();\r\n if (existing?.accessToken && existing?.projectId) return existing;\r\n return login(port || 8585);\r\n}\r\n\r\nmodule.exports = { login, ensureAuth, getValidToken, readTokens, writeTokens, resolveProject, CODE_ASSIST_BASE, CODE_ASSIST_HEADERS };\r\n","index.js":"const { getClient } = require('./lib/client');\r\nconst { GeminiError, withRetry } = require('./lib/errors');\r\nconst { convertMessages, convertTools, cleanSchema, extractModelId, buildConfig } = require('./lib/convert');\r\nconst { loadConfig } = require('./lib/config');\r\nconst { route } = require('./lib/router');\r\nconst { resolveTransformers, applyRequestTransformers } = require('./lib/transformers');\r\nconst openaiProv = require('./lib/providers/openai');\r\n\r\nfunction streamGemini({ model, system, messages, tools, onStepFinish, apiKey,\r\n temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities }) {\r\n return {\r\n fullStream: createFullStream({ model, system, messages, tools, onStepFinish, apiKey, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities }),\r\n warnings: Promise.resolve([])\r\n };\r\n}\r\n\r\nasync function* createFullStream({ model, system, messages, tools, onStepFinish, apiKey, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities }) {\r\n const client = getClient(apiKey);\r\n const modelId = extractModelId(model);\r\n let contents = convertMessages(messages);\r\n const { config } = buildConfig({ system, tools, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities });\r\n while (true) {\r\n yield { type: 'start-step' };\r\n try {\r\n const stream = await withRetry(() => client.models.generateContentStream({ model: modelId, contents, config }));\r\n const allParts = [];\r\n for await (const chunk of stream) {\r\n for (const candidate of (chunk.candidates || [])) {\r\n for (const part of (candidate.content?.parts || [])) {\r\n allParts.push(part);\r\n if (part.text && !part.thought) yield { type: 'text-delta', textDelta: part.text };\r\n }\r\n }\r\n }\r\n const fcParts = allParts.filter(p => p.functionCall);\r\n if (fcParts.length === 0) {\r\n yield { type: 'finish-step', finishReason: 'stop' };\r\n if (onStepFinish) await onStepFinish();\r\n return;\r\n }\r\n const toolResultParts = [];\r\n for (const part of fcParts) {\r\n const name = part.functionCall.name;\r\n const args = part.functionCall.args || {};\r\n const toolId = 'toolu_' + Math.random().toString(36).slice(2, 10);\r\n yield { type: 'tool-call', toolCallId: toolId, toolName: name, args };\r\n const toolDef = tools?.[name];\r\n let result = toolDef ? null : { error: true, message: 'Tool not found: ' + name };\r\n if (toolDef?.execute) {\r\n try { result = await toolDef.execute(args, { toolCallId: toolId }); }\r\n catch (e) { result = { error: true, message: e.message }; }\r\n }\r\n yield { type: 'tool-result', toolCallId: toolId, toolName: name, args, result };\r\n toolResultParts.push({ functionResponse: { name, response: typeof result === 'string' ? { output: result } : (result || {}) } });\r\n }\r\n yield { type: 'finish-step', finishReason: 'tool-calls' };\r\n if (onStepFinish) await onStepFinish();\r\n contents.push({ role: 'model', parts: allParts });\r\n contents.push({ role: 'user', parts: toolResultParts });\r\n } catch (err) {\r\n yield { type: 'error', error: err };\r\n yield { type: 'finish-step', finishReason: 'error' };\r\n if (onStepFinish) await onStepFinish();\r\n return;\r\n }\r\n }\r\n}\r\n\r\nasync function generateGemini({ model, system, messages, tools, apiKey, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities }) {\r\n const client = getClient(apiKey);\r\n const modelId = extractModelId(model);\r\n let contents = convertMessages(messages);\r\n const { config } = buildConfig({ system, tools, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities });\r\n while (true) {\r\n const response = await withRetry(() => client.models.generateContent({ model: modelId, contents, config }));\r\n const candidate = response.candidates?.[0];\r\n if (!candidate) throw new GeminiError('No candidates returned', { retryable: false });\r\n const allParts = candidate.content?.parts || [];\r\n const fcParts = allParts.filter(p => p.functionCall);\r\n if (fcParts.length === 0) {\r\n const text = allParts.filter(p => p.text && !p.thought).map(p => p.text).join('');\r\n return { text, parts: allParts, response };\r\n }\r\n const toolResultParts = [];\r\n for (const part of fcParts) {\r\n const name = part.functionCall.name;\r\n const args = part.functionCall.args || {};\r\n const toolDef = tools?.[name];\r\n let result = toolDef ? null : { error: true, message: 'Tool not found: ' + name };\r\n if (toolDef?.execute) {\r\n try { result = await toolDef.execute(args); }\r\n catch (e) { result = { error: true, message: e.message }; }\r\n }\r\n toolResultParts.push({ functionResponse: { name, response: typeof result === 'string' ? { output: result } : (result || {}) } });\r\n }\r\n contents.push({ role: 'model', parts: allParts });\r\n contents.push({ role: 'user', parts: toolResultParts });\r\n }\r\n}\r\n\r\nfunction isGeminiProvider(p) {\r\n return p.name === 'gemini' || (p.api_base_url || '').includes('generativelanguage.googleapis.com');\r\n}\r\n\r\nfunction findProvider(providers, providerName, modelName) {\r\n if (providerName) return providers.find(p => p.name === providerName);\r\n if (modelName) return providers.find(p => (p.models || []).includes(modelName));\r\n return providers[0];\r\n}\r\n\r\nfunction buildOpenAIUrl(base) {\r\n const clean = (base || '').replace(/\\/$/g, '');\r\n return clean.includes('/completions') ? clean : clean + '/chat/completions';\r\n}\r\n\r\nfunction resolveForProvider(provider, model, customMap) {\r\n const useList = provider.transformer?.[model]?.use || provider.transformer?.use || [];\r\n return resolveTransformers(useList, customMap);\r\n}\r\n\r\nasync function* routerStream(params, resolver) {\r\n const { provider, actualModel, transformers } = await resolver(params);\r\n if (isGeminiProvider(provider)) {\r\n yield* createFullStream({ ...params, model: actualModel, apiKey: provider.api_key || params.apiKey });\r\n } else {\r\n const oaiMsgs = openaiProv.convertMessages(params.messages, params.system);\r\n const oaiTools = openaiProv.convertTools(params.tools);\r\n let req = { messages: oaiMsgs, model: actualModel, max_tokens: params.maxOutputTokens || 8192, temperature: params.temperature ?? 0.5 };\r\n if (oaiTools) req.tools = oaiTools;\r\n req = applyRequestTransformers(req, transformers);\r\n yield* openaiProv.streamOpenAI({ url: buildOpenAIUrl(provider.api_base_url), apiKey: provider.api_key, headers: req._extraHeaders, body: req, tools: params.tools, onStepFinish: params.onStepFinish });\r\n }\r\n}\r\n\r\nfunction createRouter(config) {\r\n const providers = config.Providers || config.providers || [];\r\n const routerCfg = config.Router || {};\r\n async function resolve(params) {\r\n const { providerName, modelName } = await route(params, routerCfg, config.customRouter);\r\n const provider = findProvider(providers, providerName, modelName) || providers[0];\r\n if (!provider) throw new Error('[thebird] no provider configured');\r\n const actualModel = modelName || (provider.models || [])[0] || extractModelId(params.model) || 'gemini-2.0-flash';\r\n const transformers = resolveForProvider(provider, actualModel, config._transformers);\r\n return { provider, actualModel, transformers };\r\n }\r\n return {\r\n stream(params) { return { fullStream: routerStream(params, resolve), warnings: Promise.resolve([]) }; },\r\n async generate(params) {\r\n const { provider, actualModel, transformers } = await resolve(params);\r\n if (isGeminiProvider(provider)) return generateGemini({ ...params, model: actualModel, apiKey: provider.api_key || params.apiKey });\r\n const oaiMsgs = openaiProv.convertMessages(params.messages, params.system);\r\n const oaiTools = openaiProv.convertTools(params.tools);\r\n let req = { messages: oaiMsgs, model: actualModel, max_tokens: params.maxOutputTokens || 8192, temperature: params.temperature ?? 0.5 };\r\n if (oaiTools) req.tools = oaiTools;\r\n req = applyRequestTransformers(req, transformers);\r\n return openaiProv.generateOpenAI({ url: buildOpenAIUrl(provider.api_base_url), apiKey: provider.api_key, headers: req._extraHeaders, body: req, tools: params.tools });\r\n }\r\n };\r\n}\r\n\r\nfunction streamRouter(params) {\r\n const config = loadConfig(params.configPath);\r\n if (!(config.Providers || config.providers)?.length) return streamGemini(params);\r\n return createRouter(config).stream(params);\r\n}\r\n\r\nasync function generateRouter(params) {\r\n const config = loadConfig(params.configPath);\r\n if (!(config.Providers || config.providers)?.length) return generateGemini(params);\r\n return createRouter(config).generate(params);\r\n}\r\n\r\nconst { cloudGenerate, streamCloud, cloudStream } = require('./lib/cloud-generate');\r\nconst { ensureAuth, login: oauthLogin } = require('./lib/oauth');\r\n\r\nmodule.exports = { streamGemini, generateGemini, streamRouter, generateRouter, createRouter, convertMessages, convertTools, cleanSchema, GeminiError, cloudGenerate, streamCloud, cloudStream, ensureAuth, oauthLogin };\r\n","server.js":"const http = require('http');\r\nconst { streamGemini, generateGemini } = require('./index.js');\r\n\r\nconst PORT = process.env.PORT || 3456;\r\nconst state = { requests: 0, errors: 0, active: 0 };\r\n\r\nconst sse = (ev, data) => `event: ${ev}\\ndata: ${JSON.stringify(data)}\\n\\n`;\r\n\r\nconst msgId = () => 'msg_' + Math.random().toString(36).slice(2, 12);\r\n\r\nasync function handleMessages(req, res) {\r\n let body = '';\r\n for await (const chunk of req) body += chunk;\r\n const { model, messages, system, stream, max_tokens } = JSON.parse(body);\r\n const apiKey = process.env.GEMINI_API_KEY;\r\n if (!apiKey) { res.writeHead(500); res.end(JSON.stringify({ error: 'GEMINI_API_KEY required' })); return; }\r\n const params = { model: model || 'gemini-2.5-flash', messages, system, apiKey, maxOutputTokens: max_tokens || 8192 };\r\n\r\n if (!stream) {\r\n const result = await generateGemini(params);\r\n res.writeHead(200, { 'Content-Type': 'application/json' });\r\n res.end(JSON.stringify({\r\n id: msgId(), type: 'message', role: 'assistant', model: params.model,\r\n content: [{ type: 'text', text: result.text }],\r\n stop_reason: 'end_turn', usage: { input_tokens: 0, output_tokens: 0 },\r\n }));\r\n return;\r\n }\r\n\r\n res.writeHead(200, {\r\n 'Content-Type': 'text/event-stream',\r\n 'Cache-Control': 'no-cache',\r\n 'Connection': 'keep-alive',\r\n });\r\n\r\n const id = msgId();\r\n res.write(sse('message_start', { type: 'message_start', message: { id, type: 'message', role: 'assistant', content: [], model: params.model, stop_reason: null, usage: { input_tokens: 0, output_tokens: 0 } } }));\r\n res.write(sse('content_block_start', { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }));\r\n res.write(sse('ping', { type: 'ping' }));\r\n\r\n let outputTokens = 0;\r\n for await (const ev of streamGemini(params).fullStream) {\r\n if (ev.type === 'text-delta') {\r\n outputTokens += ev.textDelta.length;\r\n res.write(sse('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: ev.textDelta } }));\r\n }\r\n }\r\n\r\n res.write(sse('content_block_stop', { type: 'content_block_stop', index: 0 }));\r\n res.write(sse('message_delta', { type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: outputTokens } }));\r\n res.write(sse('message_stop', { type: 'message_stop' }));\r\n res.end();\r\n}\r\n\r\nhttp.createServer(async (req, res) => {\r\n state.requests++;\r\n state.active++;\r\n try {\r\n if (req.method === 'GET' && req.url === '/debug/server') {\r\n res.writeHead(200, { 'Content-Type': 'application/json' });\r\n res.end(JSON.stringify(state));\r\n return;\r\n }\r\n if (req.method === 'POST' && req.url === '/v1/messages') {\r\n await handleMessages(req, res);\r\n return;\r\n }\r\n res.writeHead(404);\r\n res.end(JSON.stringify({ error: 'not found' }));\r\n } catch (err) {\r\n state.errors++;\r\n res.writeHead(500);\r\n res.end(JSON.stringify({ error: err.message }));\r\n } finally {\r\n state.active--;\r\n }\r\n}).listen(PORT, () => process.stderr.write(`thebird proxy listening on ${PORT}\\n`));\r\n"}
1
+ {"app.js":"import { createElement, applyDiff, htm } from './vendor/ui-libs.js';\r\nimport { agentGenerate } from './agent-chat.js';\r\n\r\nconst html = htm.bind(createElement);\r\n\r\nconst PROVIDERS = {\r\n gemini: { label: 'Google Gemini', baseUrl: 'https://generativelanguage.googleapis.com/v1beta', keyPlaceholder: 'GEMINI_API_KEY', models: [] },\r\n openai: { label: 'OpenAI', baseUrl: 'https://api.openai.com/v1', keyPlaceholder: 'OPENAI_API_KEY', models: ['gpt-4.1', 'gpt-4o', 'gpt-4o-mini', 'o3', 'o4-mini'] },\r\n xai: { label: 'xAI Grok', baseUrl: 'https://api.x.ai/v1', keyPlaceholder: 'XAI_API_KEY', models: ['grok-3', 'grok-3-mini', 'grok-3-fast'] },\r\n groq: { label: 'Groq', baseUrl: 'https://api.groq.com/openai/v1', keyPlaceholder: 'GROQ_API_KEY', models: ['llama-3.3-70b-versatile', 'llama-3.1-8b-instant', 'mixtral-8x7b-32768'] },\r\n mistral: { label: 'Mistral', baseUrl: 'https://api.mistral.ai/v1', keyPlaceholder: 'MISTRAL_API_KEY', models: ['mistral-large-latest', 'mistral-small-latest', 'codestral-latest'] },\r\n deepseek: { label: 'DeepSeek', baseUrl: 'https://api.deepseek.com/v1', keyPlaceholder: 'DEEPSEEK_API_KEY', models: ['deepseek-chat', 'deepseek-reasoner'] },\r\n cerebras: { label: 'Cerebras', baseUrl: 'https://api.cerebras.ai/v1', keyPlaceholder: 'CEREBRAS_API_KEY', models: ['gpt-oss-120b', 'llama3.1-8b'] },\r\n acp: { label: 'ACP Agent', baseUrl: 'ws://localhost:3000', keyPlaceholder: '(no key needed)', models: ['default'] },\r\n custom: { label: 'Custom (OpenAI-compat)', baseUrl: '', keyPlaceholder: 'API_KEY', models: [] },\r\n};\r\n\r\nasync function fetchGeminiModels(apiKey) {\r\n const res = await fetch(`https://generativelanguage.googleapis.com/v1beta/models?key=${apiKey}`);\r\n if (!res.ok) throw new Error(`Models API ${res.status}`);\r\n const { models = [] } = await res.json();\r\n return models\r\n .filter(m => m.supportedGenerationMethods?.includes('generateContent'))\r\n .map(m => ({ id: m.name.replace('models/', ''), label: m.displayName || m.name }));\r\n}\r\n\r\nasync function fetchOpenAIModels(baseUrl, apiKey) {\r\n const url = baseUrl.replace(/\\/$/, '') + '/models';\r\n const res = await fetch(url, { headers: { 'Authorization': `Bearer ${apiKey}` } });\r\n if (!res.ok) throw new Error(`Models API ${res.status}`);\r\n const { data = [] } = await res.json();\r\n return data.map(m => ({ id: m.id, label: m.id })).sort((a, b) => a.id.localeCompare(b.id));\r\n}\r\n\r\nasync function fetchModels(providerType, baseUrl, apiKey) {\r\n if (providerType === 'gemini') return fetchGeminiModels(apiKey);\r\n const staticModels = PROVIDERS[providerType]?.models || [];\r\n try {\r\n return await fetchOpenAIModels(baseUrl, apiKey);\r\n } catch {\r\n return staticModels.map(id => ({ id, label: id }));\r\n }\r\n}\r\n\r\nclass BirdChat extends HTMLElement {\r\n constructor() {\r\n super();\r\n const savedProvider = localStorage.getItem('provider_type') || 'gemini';\r\n const savedBaseUrl = localStorage.getItem('provider_base_url') || PROVIDERS[savedProvider]?.baseUrl || '';\r\n this.state = {\r\n messages: [], streaming: false,\r\n providerType: savedProvider,\r\n baseUrl: savedBaseUrl,\r\n model: localStorage.getItem('provider_model') || (savedProvider === 'gemini' ? 'gemini-2.5-flash' : (PROVIDERS[savedProvider]?.models[0] || '')),\r\n apiKey: localStorage.getItem('provider_api_key') || '',\r\n models: [], modelsLoading: false, status: '', streamingText: '',\r\n };\r\n const self = this;\r\n Object.assign(window.__debug = window.__debug || {}, {\r\n get state() { return self.state; },\r\n get messages() { return self.state.messages; },\r\n get models() { return self.state.models; },\r\n });\r\n }\r\n\r\n connectedCallback() {\r\n this.render();\r\n Object.assign(window.__debug, { acp: { baseUrl: this.state.baseUrl, provider: this.state.providerType } });\r\n if (this.state.apiKey) this.loadModels();\r\n }\r\n\r\n setState(patch) { Object.assign(this.state, patch); this.render(); }\r\n\r\n async loadModels() {\r\n const { providerType, baseUrl, apiKey } = this.state;\r\n this.setState({ modelsLoading: true, status: '' });\r\n try {\r\n const models = await fetchModels(providerType, baseUrl, apiKey);\r\n const current = this.state.model;\r\n const model = models.find(m => m.id === current) ? current : (models[0]?.id || current);\r\n this.setState({ models, model, modelsLoading: false });\r\n } catch (err) {\r\n this.setState({ modelsLoading: false, status: 'Failed to load models: ' + (err?.message || String(err)) });\r\n }\r\n }\r\n\r\n setProvider(type) {\r\n const def = PROVIDERS[type] || {};\r\n const baseUrl = type === 'custom' ? '' : (def.baseUrl || '');\r\n const model = def.models?.[0] || '';\r\n localStorage.setItem('provider_type', type);\r\n localStorage.setItem('provider_base_url', baseUrl);\r\n localStorage.setItem('provider_model', model);\r\n this.setState({ providerType: type, baseUrl, model, models: [], apiKey: localStorage.getItem('provider_api_key') || '' });\r\n }\r\n\r\n render() {\r\n const { messages, streaming, model, apiKey, models, modelsLoading, status, providerType, baseUrl, streamingText } = this.state;\r\n const provDef = PROVIDERS[providerType] || PROVIDERS.custom;\r\n const opts = (models.length === 0 ? (provDef.models.length ? provDef.models.map(id => ({ id, label: id })) : [{ id: model, label: model }]) : models)\r\n .map(m => html`<option value=${m.id} selected=${m.id === model}>${m.label}</option>`);\r\n const provOpts = Object.entries(PROVIDERS).map(([id, p]) =>\r\n html`<option value=${id} selected=${id === providerType}>${p.label}</option>`);\r\n\r\n applyDiff(this, html`\r\n <div style=\"display:flex;flex-direction:column;height:100%\">\r\n <div class=\"tui-toolbar\">\r\n <label>provider:</label>\r\n <select class=\"tui-select\" onchange=${e => this.setProvider(e.target.value)}>${provOpts}</select>\r\n ${(providerType === 'custom' || providerType === 'acp') ? html`\r\n <input type=\"text\" class=\"tui-input\" style=\"flex:1;min-width:140px\"\r\n placeholder=${providerType === 'acp' ? 'ws://localhost:3000' : 'https://your-endpoint/v1'} value=${baseUrl}\r\n onchange=${e => { localStorage.setItem('provider_base_url', e.target.value); this.setState({ baseUrl: e.target.value }); }} />` : ''}\r\n ${providerType !== 'acp' ? html`<input id=\"api-key-input\" type=\"password\" class=\"tui-input\" style=\"flex:1;min-width:120px\"\r\n placeholder=${provDef.keyPlaceholder} value=${apiKey}\r\n onchange=${e => {\r\n const v = e.target.value.trim();\r\n localStorage.setItem('provider_api_key', v);\r\n this.setState({ apiKey: v });\r\n if (v) this.loadModels();\r\n }} />` : ''}\r\n ${modelsLoading\r\n ? html`<span class=\"tui-spinner\"></span>`\r\n : html`<select class=\"tui-select\" value=${model}\r\n onchange=${e => { localStorage.setItem('provider_model', e.target.value); this.setState({ model: e.target.value }); }}>${opts}</select>`}\r\n <button class=\"tui-btn\" onclick=${() => this.setState({ messages: [], status: '' })}>[clear]</button>\r\n </div>\r\n\r\n <div id=\"msg-list\" class=\"tui-msglist\">\r\n ${messages.map((m, i) => html`\r\n <div key=${i} class=${'tui-msg ' + m.role}>${m.content}</div>`)}\r\n ${streaming && !streamingText && html`<div class=\"tui-msg assistant\"><span class=\"tui-spinner\"></span> thinking...</div>`}\r\n </div>\r\n\r\n ${status && html`<div class=\"tui-error-text\" style=\"padding:0 1ch\">${status}</div>`}\r\n\r\n <form class=\"tui-compose\" onsubmit=${e => { e.preventDefault(); this.send(); }}>\r\n <textarea id=\"chat-input\" class=\"tui-textarea\" style=\"flex:1;resize:none;min-height:24px;max-height:120px\"\r\n placeholder=\"type message... (shift+enter for newline)\" rows=\"1\" disabled=${streaming}\r\n onkeydown=${e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); this.send(); } }}\r\n oninput=${e => { e.target.style.height = 'auto'; e.target.style.height = Math.min(e.target.scrollHeight, 120) + 'px'; }}></textarea>\r\n <button type=\"submit\" class=\"tui-btn primary\" disabled=${streaming}>\r\n ${streaming ? html`<span class=\"tui-spinner\"></span>` : '[send]'}\r\n </button>\r\n </form>\r\n </div>`);\r\n }\r\n\r\n async send() {\r\n const input = this.querySelector('#chat-input');\r\n const text = input?.value.trim();\r\n if (!text || this.state.streaming) return;\r\n const { apiKey, model, providerType, baseUrl } = this.state;\r\n if (!apiKey && providerType !== 'acp') { this.setState({ status: 'Enter an API key above.' }); return; }\r\n input.value = '';\r\n input.style.height = 'auto';\r\n const normalizedMessages = [...this.state.messages, { role: 'user', content: text }].map(m => ({\r\n ...m, content: typeof m.content === 'string' ? [{ type: 'text', text: m.content }] : m.content\r\n }));\r\n this.setState({ messages: normalizedMessages, streaming: true, status: '', streamingText: '' });\r\n const provider = { type: providerType, apiKey, model, baseUrl: providerType === 'gemini' ? '' : baseUrl };\r\n try {\r\n let full = '';\r\n const streamEl = document.createElement('div');\r\n streamEl.className = 'tui-msg assistant';\r\n const cursor = document.createElement('span');\r\n cursor.style.cssText = 'animation:blink 0.5s step-end infinite';\r\n cursor.textContent = '█';\r\n const wrap = document.createElement('div');\r\n wrap.appendChild(streamEl);\r\n wrap.appendChild(cursor);\r\n const list = this.querySelector('#msg-list');\r\n if (list) list.appendChild(wrap);\r\n await agentGenerate(provider, normalizedMessages,\r\n chunk => { full += chunk; streamEl.textContent = full; const l = this.querySelector('#msg-list'); if (l) l.scrollTop = l.scrollHeight; },\r\n (name, args) => { full += `\\n[tool: ${name}(${JSON.stringify(args)})]\\n`; streamEl.textContent = full; }\r\n );\r\n wrap.remove();\r\n this.setState({ messages: [...normalizedMessages, { role: 'assistant', content: [{ type: 'text', text: full || '(empty)' }] }], streaming: false, streamingText: '' });\r\n const l2 = this.querySelector('#msg-list');\r\n if (l2) l2.scrollTop = l2.scrollHeight;\r\n } catch (err) {\r\n this.setState({ streaming: false, streamingText: '', status: 'Error: ' + (err?.message || String(err)) });\r\n }\r\n }\r\n}\r\n\r\ncustomElements.define('bird-chat', BirdChat);\r\n","agent-chat.js":"import { streamGemini, streamOpenAI } from './vendor/thebird-browser.js';\r\nimport { streamACP } from './acp-stream.js';\r\n\r\nfunction idbRead(path) {\r\n const snap = window.__debug.idbSnapshot;\r\n if (!snap) throw new Error('idb snapshot not ready');\r\n if (!(path in snap)) throw new Error('not found in snapshot: ' + path);\r\n return snap[path];\r\n}\r\n\r\nfunction idbWrite(path, content) {\r\n const snap = window.__debug.idbSnapshot;\r\n if (!snap) throw new Error('idb snapshot not ready');\r\n snap[path] = content;\r\n window.__debug.idbPersist?.();\r\n window.__debug.shell?.onPreviewWrite?.();\r\n}\r\n\r\nconst TOOLS = {\r\n read_file: {\r\n description: 'Read a file from the filesystem',\r\n parameters: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] },\r\n execute: async ({ path }) => {\r\n const c = window.__debug.container;\r\n if (c) return await c.fs.readFile(path, 'utf-8');\r\n return idbRead(path);\r\n },\r\n },\r\n write_file: {\r\n description: 'Write content to a file',\r\n parameters: { type: 'object', properties: { path: { type: 'string' }, content: { type: 'string' } }, required: ['path', 'content'] },\r\n execute: async ({ path, content }) => {\r\n const c = window.__debug.container;\r\n if (c) await c.fs.writeFile(path, content);\r\n idbWrite(path, content);\r\n return 'written: ' + path;\r\n },\r\n },\r\n list_files: {\r\n description: 'List files available in the filesystem',\r\n parameters: { type: 'object', properties: { prefix: { type: 'string' } }, required: [] },\r\n execute: async ({ prefix }) => {\r\n const snap = window.__debug.idbSnapshot || {};\r\n const keys = Object.keys(snap).sort();\r\n return (prefix ? keys.filter(k => k.startsWith(prefix)) : keys).join('\\n') || '(empty)';\r\n },\r\n },\r\n run_command: {\r\n description: 'Run a shell command in the WebContainer',\r\n parameters: { type: 'object', properties: { command: { type: 'string' }, cwd: { type: 'string' } }, required: ['command'] },\r\n execute: async ({ command, cwd }) => {\r\n const c = window.__debug.container;\r\n if (!c) throw new Error('container not ready');\r\n const proc = await c.spawn('sh', ['-c', command], cwd ? { cwd } : undefined);\r\n let out = '';\r\n await proc.output.pipeTo(new WritableStream({ write: d => { out += d; } }));\r\n await proc.exit;\r\n return out || '(no output)';\r\n },\r\n },\r\n read_terminal: {\r\n description: 'Read the current terminal display (last N lines)',\r\n parameters: { type: 'object', properties: { lines: { type: 'number' } }, required: [] },\r\n execute: async ({ lines = 50 }) => {\r\n const term = window.__debug.term;\r\n if (!term) throw new Error('terminal not ready');\r\n const buf = term.buffer.active;\r\n const end = buf.length;\r\n const start = Math.max(0, end - lines);\r\n const out = [];\r\n for (let y = start; y < end; y++) {\r\n const line = buf.getLine(y);\r\n if (line) out.push(line.translateToString(true));\r\n }\r\n return out.join('\\n').trimEnd() || '(empty)';\r\n },\r\n },\r\n send_to_terminal: {\r\n description: 'Send input to the terminal shell (use \\\\n for newline/Enter)',\r\n parameters: { type: 'object', properties: { input: { type: 'string' } }, required: ['input'] },\r\n execute: async ({ input }) => {\r\n const w = window.__debug.shellWriter;\r\n if (!w) throw new Error('shell not ready');\r\n await w.write(input);\r\n return 'sent: ' + JSON.stringify(input);\r\n },\r\n },\r\n};\r\n\r\nfunction buildStream(provider) {\r\n if (provider.type === 'gemini') {\r\n return streamGemini({ model: provider.model, messages: provider.messages, tools: TOOLS, apiKey: provider.apiKey, maxOutputTokens: 8192 }).fullStream;\r\n }\r\n if (provider.type === 'acp') {\r\n return streamACP({ url: provider.baseUrl, model: provider.model, messages: provider.messages, tools: TOOLS, maxOutputTokens: 8192 });\r\n }\r\n const url = (provider.baseUrl || '').replace(/\\/$/, '') + '/chat/completions';\r\n return streamOpenAI({ url, apiKey: provider.apiKey, messages: provider.messages, model: provider.model, tools: TOOLS, maxOutputTokens: 8192 });\r\n}\r\n\r\nexport async function agentGenerate(provider, messages, onChunk, onTool) {\r\n Object.assign(window.__debug = window.__debug || {}, {\r\n agent: { provider: provider.type, model: provider.model, active: true, lastTool: null, lastError: null },\r\n });\r\n try {\r\n for await (const ev of buildStream({ ...provider, messages })) {\r\n if (ev.type === 'text-delta') onChunk(ev.textDelta);\r\n else if (ev.type === 'tool-call') {\r\n window.__debug.agent.lastTool = { name: ev.toolName, args: ev.args };\r\n onTool(ev.toolName, ev.args);\r\n } else if (ev.type === 'error') throw ev.error;\r\n }\r\n } catch (e) {\r\n window.__debug.agent.lastError = { message: e.message, stack: e.stack, timestamp: Date.now() };\r\n throw e;\r\n } finally {\r\n window.__debug.agent.active = false;\r\n }\r\n}\r\n","terminal.js":"import { Terminal, FitAddon } from './vendor/xterm-bundle.js';\r\nimport { createMachine, createActor } from './vendor/xstate.js';\r\nimport { createShell } from './shell.js';\r\nimport { registerPreviewSW } from './preview-sw-client.js';\r\n\r\nconst IDB_KEY = 'thebird_fs_v4';\r\n\r\nasync function idbLoad() {\r\n return new Promise((res, rej) => {\r\n const req = indexedDB.open('thebird', 1);\r\n req.onupgradeneeded = e => e.target.result.createObjectStore('fs');\r\n req.onsuccess = e => {\r\n const tx = e.target.result.transaction('fs', 'readonly');\r\n const get = tx.objectStore('fs').get(IDB_KEY);\r\n get.onsuccess = () => res(get.result || null);\r\n get.onerror = rej;\r\n };\r\n req.onerror = rej;\r\n });\r\n}\r\n\r\nasync function idbSave(data) {\r\n return new Promise((res, rej) => {\r\n const req = indexedDB.open('thebird', 1);\r\n req.onsuccess = e => {\r\n const tx = e.target.result.transaction('fs', 'readwrite');\r\n tx.objectStore('fs').put(data, IDB_KEY);\r\n tx.oncomplete = res;\r\n tx.onerror = rej;\r\n };\r\n req.onerror = rej;\r\n });\r\n}\r\n\r\nconst bootMachine = createMachine({ id: 'terminal', initial: 'loading-idb', states: {\r\n 'loading-idb': { on: { IDB_READY: 'registering-sw' } },\r\n 'registering-sw': { on: { SW_READY: 'ready', SW_ERROR: 'ready' } },\r\n 'ready': {},\r\n 'error': {},\r\n}});\r\n\r\nlet reloadTimer = null;\r\nfunction scheduleReload() {\r\n clearTimeout(reloadTimer);\r\n reloadTimer = setTimeout(() => {\r\n if (typeof window.refreshPreview === 'function') window.refreshPreview();\r\n }, 1000);\r\n}\r\n\r\nasync function boot() {\r\n const el = document.getElementById('term-container');\r\n if (!el) return;\r\n\r\n const bootActor = createActor(bootMachine);\r\n bootActor.start();\r\n\r\n window.__debug = window.__debug || {};\r\n window.__debug.terminal = { get state() { return bootActor.getSnapshot().value; } };\r\n\r\n const term = new Terminal({ theme: { background: '#000000', foreground: '#33ff33' }, convertEol: true });\r\n const fit = new FitAddon();\r\n term.loadAddon(fit);\r\n term.open(el);\r\n fit.fit();\r\n window.addEventListener('resize', () => fit.fit());\r\n\r\n const saved = await idbLoad();\r\n let files;\r\n if (saved) {\r\n files = JSON.parse(saved);\r\n } else {\r\n const r = await fetch('./defaults.json');\r\n files = await r.json();\r\n }\r\n\r\n window.__debug.idbSnapshot = files;\r\n window.__debug.idbPersist = () => idbSave(JSON.stringify(window.__debug.idbSnapshot));\r\n window.__debug.term = term;\r\n bootActor.send({ type: 'IDB_READY' });\r\n\r\n const shell = createShell({ term, onPreviewWrite: scheduleReload });\r\n window.__debug.shell = shell;\r\n\r\n registerPreviewSW().then(() => {\r\n bootActor.send({ type: 'SW_READY' });\r\n }).catch(e => {\r\n console.log('[terminal] SW error:', e.message);\r\n window.__debug.sw = window.__debug.sw || {};\r\n window.__debug.sw.bootError = e.message;\r\n bootActor.send({ type: 'SW_ERROR' });\r\n });\r\n window.__debug.shellWriter = { write: line => shell.run(line.replace(/\\n$/, '')) };\r\n}\r\n\r\nboot().catch(e => {\r\n console.error('[terminal] boot error:', e);\r\n throw e;\r\n});\r\n","shell.js":"import { createMachine, createActor } from './vendor/xstate.js';\nimport { createNodeEnv } from './shell-node.js';\nimport { createReadline } from './shell-readline.js';\nimport { makeBuiltins, resolvePath } from './shell-builtins.js';\nimport { makeNpm, makeNpx } from './shell-npm.js';\nimport { makePmDispatcher, makeCorepackStub, detectPm } from './shell-pm.js';\nimport { makeDlx } from './shell-pm-layout.js';\nimport { tokenize, splitTopLevel, parsePipes } from './shell-parser.js';\nimport { fullExpand } from './shell-expand.js';\nimport { isControlStart, isBlockOpen, runControl, runScript } from './shell-control.js';\nimport { createSignals, makeKillBuiltin, makeTrapBuiltin } from './shell-signals.js';\nimport { createJobRegistry, makeJobsBuiltin, makeFgBuiltin, makeBgBuiltin, makeDisownBuiltin } from './shell-jobs.js';\nimport { createFdTable, makeExecBuiltin } from './shell-fd.js';\nimport { readStream } from './shell-procsub.js';\nimport { makeExpander, makeCaptureRun, makeNodeRunner, makeNpmResultRunner } from './shell-exec.js';\nimport { createSwJobs, makeNohupBuiltin, makeNetcatStub, makeCurlBuiltin } from './shell-sw-jobs.js';\n\nconst machine = createMachine({ id: 'shell', initial: 'idle', states: {\n idle: { on: { RUN: 'executing', ENTER_REPL: 'node-repl', NODE_START: 'node-running' } },\n executing: { on: { DONE: 'idle', ERROR: 'idle' } },\n 'node-running': { on: { DONE: 'idle', ERROR: 'idle' } },\n 'node-repl': { on: { EXIT_REPL: 'idle', RUN: 'node-repl' } },\n}});\n\nexport function createShell({ term, onPreviewWrite }) {\n const ctx = { term, cwd: '/', prevCwd: '/', env: {}, history: [], lastExitCode: 0, argv: [], functions: {}, opts: {}, localStack: [], loopFlag: null, arrays: {}, bgJobs: {}, traps: {} };\n const actor = createActor(machine);\n actor.start();\n const httpHandlers = {};\n window.__debug = window.__debug || {};\n\n let inputQueue = [];\n function drainQueue(onData) { const items = inputQueue.slice(); inputQueue = []; for (const d of items) onData(d); }\n\n const toKey = p => p.replace(/^\\//, '');\n const snap = () => window.__debug.idbSnapshot || {};\n\n const BUILTINS = makeBuiltins(ctx, actor, invokeBuiltin);\n ctx.builtinsRef = BUILTINS;\n const _exp = makeExpander(ctx, l => captureRun(l), t => parseRedirect(t));\n expandTokens = _exp.expandTokens;\n captureRun = makeCaptureRun(ctx, BUILTINS, actor, t => parseRedirect(t), t => expandTokens(t));\n ctx.signals = createSignals(ctx);\n ctx.fdTable = createFdTable(ctx);\n ctx.swJobs = createSwJobs();\n const jobRegistry = createJobRegistry(ctx);\n ctx.jobRegistry = jobRegistry;\n ctx.runPipeline = line => runPipeline(line);\n Object.assign(BUILTINS, { kill: makeKillBuiltin(ctx), trap: makeTrapBuiltin(ctx), jobs: makeJobsBuiltin(ctx, jobRegistry), fg: makeFgBuiltin(ctx, jobRegistry), bg: makeBgBuiltin(ctx, jobRegistry), disown: makeDisownBuiltin(ctx), exec: makeExecBuiltin(ctx, ctx.fdTable), nohup: makeNohupBuiltin(ctx), nc: makeNetcatStub(ctx), curl: makeCurlBuiltin(ctx) });\n ctx.runScript = text => runScript(text, run, ctx);\n ctx.expand = token => fullExpand(token, ctx.env, ctx.lastExitCode, ctx.argv, captureRun, ctx.arrays);\n const npmCmd = makeNpm(ctx); const npxCmd = makeNpx(npmCmd); ctx.exec = line => run(line);\n const pmDispatch = makePmDispatcher(term, null, () => window.__debug.idbPersist?.(), ctx); const corepackCmd = makeCorepackStub(term); const dlxCmd = makeDlx(term, null, ctx, run);\n ctx.nodeEval = createNodeEnv({ ctx, term });\n const runNode = makeNodeRunner(ctx, actor);\n const runNpmResult = makeNpmResultRunner(ctx, line => run(line));\n\n let expandTokens, captureRun;\n\n async function captureFn(fn) {\n let out = ''; const orig = term.write.bind(term); term.write = s => { out += s; };\n try { await fn(); } finally { term.write = orig; }\n return out;\n }\n\n async function runFunction(name, args) {\n const savedArgv = ctx.argv; ctx.argv = [name, ...args]; ctx.localStack.push({});\n try { await runScript(ctx.functions[name], run, ctx); }\n finally {\n const locals = ctx.localStack.pop();\n for (const k of Object.keys(locals)) { if (locals[k] === undefined) delete ctx.env[k]; else ctx.env[k] = locals[k]; }\n ctx.argv = savedArgv;\n }\n }\n\n async function invokeBuiltin(name, args, withCaptureInto, stdinBuf) {\n if (ctx.functions[name]) {\n if (!withCaptureInto) { await runFunction(name, args); return ''; }\n return captureFn(() => runFunction(name, args));\n }\n const fn = BUILTINS[name];\n if (!fn) throw new Error('command not found: ' + name);\n if (!withCaptureInto) { await fn(args, actor, stdinBuf, invokeBuiltin, run); return ''; }\n return captureFn(() => fn(args, actor, stdinBuf, invokeBuiltin, run));\n }\n\n function evalKV(kv) { const eq = kv.indexOf('='); return [kv.slice(0, eq), fullExpand(kv.slice(eq + 1), ctx.env, ctx.lastExitCode, ctx.argv, captureRun)]; }\n\n async function runSingleCommand(line) {\n const arrM = line.trim().match(/^([A-Za-z_][A-Za-z0-9_]*)=\\((.*)\\)\\s*$/);\n if (arrM) { (ctx.arrays = ctx.arrays || {})[arrM[1]] = tokenize(arrM[2]).map(t => fullExpand(t, ctx.env, ctx.lastExitCode, ctx.argv, captureRun, ctx.arrays)); return; }\n const idxM = line.trim().match(/^([A-Za-z_][A-Za-z0-9_]*)\\[([^\\]]+)\\]=(.*)$/);\n if (idxM) { ctx.arrays = ctx.arrays || {}; if (!ctx.arrays[idxM[1]]) ctx.arrays[idxM[1]] = {}; const a = ctx.arrays[idxM[1]], ex = t => fullExpand(t, ctx.env, ctx.lastExitCode, ctx.argv, captureRun, ctx.arrays), k = ex(idxM[2]), v = ex(idxM[3]); if (Array.isArray(a)) a[parseInt(k, 10)] = v; else a[k] = v; return; }\n const raw = tokenize(line); if (!raw.length) return;\n let i = 0; const varAssigns = [];\n while (i < raw.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(raw[i])) varAssigns.push(raw[i++]);\n const rest = raw.slice(i);\n if (!rest.length) { for (const kv of varAssigns) { const [k, v] = evalKV(kv); ctx.env[k] = v; } return; }\n const { args: [cmd, ...args], stdout: rout, append } = parseRedirect(expandTokens(rest));\n const writeOut = rout ? buf => { const k = toKey(resolvePath(ctx.cwd, rout)); snap()[k] = append ? (snap()[k] || '') + buf : buf; window.__debug.idbPersist?.(); } : null;\n const prevEnv = {}; for (const kv of varAssigns) { const [k, v] = evalKV(kv); prevEnv[k] = ctx.env[k]; ctx.env[k] = v; }\n try {\n if (cmd === 'npm') { if (writeOut) { writeOut(await captureFn(async () => { await runNpmResult(await npmCmd(args)); })); return; } await runNpmResult(await npmCmd(args)); return; }\n if (cmd === 'npx') { await runNpmResult(await npxCmd(args)); return; }\n if (cmd === 'pnpm' || cmd === 'yarn' || cmd === 'bun') { ctx.lastExitCode = args[0] === 'dlx' || args[0] === 'x' ? await dlxCmd(args.slice(1)) : await pmDispatch(cmd, args[0] || 'install', args.slice(1)); return; }\n if (cmd === 'deno') { if (args[0] === 'run') { await runNode(args.slice(1)); return; } ctx.lastExitCode = await pmDispatch('deno', args[0] || 'task', args.slice(1)); return; }\n if (cmd === 'corepack') { ctx.lastExitCode = await corepackCmd(args); return; }\n if (cmd === 'node') { await runNode(args); return; }\n if (cmd === 'exit') { BUILTINS.exit([], actor); return; }\n if (writeOut) { writeOut(await invokeBuiltin(cmd, args, true)); return; }\n await invokeBuiltin(cmd, args, false);\n } finally { for (const k of Object.keys(prevEnv)) { if (prevEnv[k] === undefined) delete ctx.env[k]; else ctx.env[k] = prevEnv[k]; } }\n }\n\n function parseRedirect(tokens) {\n const out = { args: [], stdout: null, append: false };\n for (let i = 0; i < tokens.length; i++) {\n const t = tokens[i];\n if (t === '>' || t === '>>') { out.stdout = tokens[++i]; out.append = t === '>>'; } else out.args.push(t);\n }\n return out;\n }\n\n async function runPipeline(line) {\n const pipes = parsePipes(line);\n if (pipes.length === 1) { await runSingleCommand(pipes[0]); return; }\n let buf = '';\n for (let i = 0; i < pipes.length; i++) {\n const isLast = i === pipes.length - 1;\n const { args: [cmd, ...args], stdout: rout, append } = parseRedirect(expandTokens(tokenize(pipes[i])));\n const sArgs = i === 0 ? args : (buf && cmd !== 'node' ? [buf, ...args] : args);\n const stdinForStage = cmd === 'node' ? buf : buf;\n if (isLast && !rout) {\n if (cmd === 'node') { await runNode(args, stdinForStage); buf = ''; continue; }\n await invokeBuiltin(cmd, sArgs, false, stdinForStage); buf = ''; continue;\n }\n const out = cmd === 'node' ? await captureFn(() => runNode(args, stdinForStage)) : await invokeBuiltin(cmd, sArgs, true, stdinForStage);\n if (rout) { const k = toKey(resolvePath(ctx.cwd, rout)); snap()[k] = append ? (snap()[k] || '') + out : out; window.__debug.idbPersist?.(); buf = ''; } else { buf = out; }\n }\n }\n\n let blockLines = [];\n\n async function run(line, onData) {\n if (!line.trim()) return;\n ctx.history.push(line);\n const st = actor.getSnapshot().value;\n if (st === 'node-repl') {\n const t = line.trim();\n if (t === 'exit' || t === '.exit' || t === '.quit') { actor.send({ type: 'EXIT_REPL' }); return; }\n if (t === '.help') { term.write('.exit Exit the REPL\\r\\n.help Show this list\\r\\n.clear Break out of current expression\\r\\n'); return; }\n if (t === '.clear') return;\n const exprCode = 'try { const __r = (' + line + '); if (__r !== undefined) console.log(require(\"util\").inspect(__r)); } catch (__e1) { try {\\n' + line + '\\n} catch (__e2) { console.error(__e2.message); } }';\n await ctx.nodeEval(exprCode); return;\n }\n if (ctx.opts.xtrace) term.write('\\x1b[90m+ ' + line + '\\x1b[0m\\r\\n');\n const chain = splitTopLevel(line, ['&&', '||', ';', '&']);\n let lastOk = true;\n for (const { cmd, sep } of chain) {\n if (ctx.loopFlag) break;\n if (sep === '&&' && !lastOk) continue;\n if (sep === '||' && lastOk) { lastOk = true; continue; }\n if (sep === '&') { const id = jobRegistry.spawnJob(cmd, runPipeline); ctx.env['!'] = id; term.write('[' + id + '] spawned\\r\\n'); continue; }\n actor.send({ type: 'RUN' });\n try { ctx.lastExitCode = 0; await runPipeline(cmd); lastOk = ctx.lastExitCode === 0; actor.send({ type: 'DONE' }); }\n catch (e) { term.write('\\x1b[31m' + e.message + '\\x1b[0m\\r\\n'); ctx.lastExitCode = 1; lastOk = false; actor.send({ type: 'ERROR' }); }\n if (ctx.opts.errexit && !lastOk) break;\n if (ctx.signals) await ctx.signals.check(l => run(l));\n }\n if (onData) drainQueue(onData);\n }\n\n const getCompletions = (line, word) => (line.trim().split(/\\s+/).length <= 1 && !line.includes(' ')) ? Object.keys(BUILTINS).concat(['npm', 'node', 'pnpm', 'yarn', 'bun', 'deno', 'npx', 'corepack']).filter(c => c.startsWith(word)) : Object.keys(snap()).filter(f => f.startsWith(word));\n\n const handleLine = line => {\n if (blockLines.length > 0 || isControlStart(line)) {\n blockLines.push(line); if (isBlockOpen(blockLines)) { rl.showContinuation(); return; }\n const block = blockLines.slice(); blockLines = [];\n runControl(block, run, ctx).then(() => rl.showPrompt()).catch(e => { term.write('\\x1b[31m' + e.message + '\\x1b[0m\\r\\n'); rl.showPrompt(); });\n return;\n }\n run(line, onData).then(() => rl.showPrompt());\n };\n const rl = createReadline({ term, getCompletions, getPrompt: () => actor.getSnapshot().value === 'node-repl' ? '> ' : ctx.cwd, isBlockOpen: () => blockLines.length > 0, onLine: handleLine });\n function onData(data) {\n if (data === '\\x03') { actor.send({ type: 'ERROR' }); inputQueue = []; blockLines = []; term.write('^C'); rl.showPrompt(); return; }\n const st = actor.getSnapshot().value;\n if (st !== 'idle' && st !== 'node-repl') inputQueue.push(data); else rl.onData(data);\n }\n term.onData(onData);\n rl.showPrompt();\n return {\n run: line => run(line, onData), onPreviewWrite, httpHandlers, procsubRead: id => readStream(id), fdRead: fd => ctx.fdTable.readFd(fd),\n get state() { return actor.getSnapshot().value; }, get cwd() { return ctx.cwd; }, get env() { return ctx.env; }, get history() { return ctx.history; },\n get lastExitCode() { return ctx.lastExitCode; }, get inputQueue() { return inputQueue.slice(); },\n };\n}\n","shell-node.js":"import { createPath, createFs, createEvents, createUrl, createQuerystring, createBuffer } from './node-builtins.js';\r\nimport { createExpress, createHttp, createSqlite, createConsole, createProcess, NODE_VERSION, NODE_VERSIONS, NodeExit } from './shell-node-modules.js';\r\nimport { inspect, format, createZlib, preloadFflate } from './shell-node-stdlib.js';\r\nimport { createHash, createHmac, pbkdf2Sync, randomBytes } from './shell-node-crypto.js';\r\nimport { createChildProcess, createHttpClient, extendProcess, rewriteStack, isEsmCode, runEsm, parseDotEnv } from './shell-node-io.js';\r\nimport { resolveExports, resolveImports, walkUpNodeModules, resolvePackageEntry, makeModuleModule, makeModuleNotFoundError, makeFsPromises, makeFsWatch, makeNetStub, makeDgramStub, makeWorkerThreadsStub } from './shell-node-resolve.js';\r\nimport { extendBuffer, extendPath, createUrlExt, makeStringDecoder, makeReadline, makeTimersMod, makePerfHooks, makeV8Mod, makeAsyncHooks, makeStubs, makeErrorCodes, extendProcessExtras, makeStreamConsumers } from './shell-node-extras.js';\r\nimport { makeStream, extendFsStreams } from './shell-node-streams.js';\r\nimport { extendCrypto } from './shell-node-cipher.js';\r\nimport { extendKeys } from './shell-node-keyobject.js';\r\nimport { makeStreamingZlib, makeVmModule, makeModuleRegister, makeHttp2, makeWasi } from './shell-node-advanced.js';\r\nimport { makeDebugRegistry, makeDiagnosticsChannel, makeTraceEvents, makeBufferPool, makeProcessBindings, makePerfMemory, makeFetchPool, makeFsWatchReal, installPrepareStackTraceHook, installCaptureStackTrace } from './shell-node-observe.js';\r\nimport { makeWorkerThreads, makeChildProcessReal, makeRepl } from './shell-node-runtime.js';\r\nimport { detectBrowser, registerPolyfill, makeCompressionStreamZlib, makeWebCodecs, makeWebPush, makeStorageHelpers } from './shell-node-firefox.js';\r\nimport { makeOpfsBackend, wireOpfsIntoFs } from './shell-node-opfs.js';\r\nimport { preloadBrotli, makeBrotli } from './shell-node-brotli.js';\r\nimport { preloadSourceMap, installSourceMapStacks } from './shell-node-srcmap.js';\r\nimport { makeNet, makeTls, makeDgram } from './shell-node-net.js';\r\nimport { makeInspector } from './shell-node-inspector.js';\r\nimport { makeV8Profiler, makeHeapSnapshot } from './shell-node-profiler.js';\r\nimport { makeCluster } from './shell-node-cluster.js';\r\nimport { preloadX509 } from './shell-node-keyobject.js';\r\nimport { detectRuntime, registerRuntime, switchRuntime, logRuntimeSwitch } from './shell-runtime.js';\r\nimport { makeDenoGlobal } from './shell-deno.js'; import { makeBunGlobal } from './shell-bun.js';\r\nimport { makePmDispatcher, detectPm, makeCorepackStub } from './shell-pm.js';\r\nimport { isTsFile, preprocessSource } from './shell-ts.js'; import { installPosixFs, installFds, installTmpAndMisc } from './shell-posix.js';\r\nimport { makeTestRunner, makeTapReporter } from './shell-node-testrunner.js'; import { makeForkIpc } from './shell-node-ipc.js';\r\nimport { styleText, stripVTControlCharacters, getCallSites, MIMEType, MIMEParams, makeConsoleExtras } from './shell-node-util-extras.js';\r\nimport { makeProcFs, wireProcFs } from './shell-node-procfs.js'; import { makeGit } from './shell-node-git.js'; import { makeTar } from './shell-node-tar.js'; import { makeDns } from './shell-node-dns.js'; import { makeNativeLoader } from './shell-node-native.js'; import { makeRegistry } from './shell-node-registry.js';\r\nimport { makeBusnet, makeBusHttp } from './shell-node-busnet.js';\r\n\r\nexport function createNodeEnv({ ctx, term }) {\r\n const pathmod = extendPath(createPath()); const Buf = makeBufferPool(extendBuffer(createBuffer())); const debugReg = makeDebugRegistry();\r\n const browserInfo = detectBrowser(); debugReg.browser = browserInfo; const snapFn = () => window.__debug?.idbSnapshot || {};\r\n const fsmod = installTmpAndMisc(installFds(installPosixFs(extendFsStreams(createFs(), Buf), Buf, ctx), Buf), Buf, ctx);\r\n const opfs = makeOpfsBackend(Buf); if (opfs) wireOpfsIntoFs(fsmod, opfs, debugReg);\r\n const runtime = detectRuntime(); registerRuntime(debugReg, runtime); fsmod.promises = makeFsPromises(fsmod); fsmod.watch = makeFsWatchReal(snapFn);\r\n fsmod.glob = (pat, opts, cb) => { if (typeof opts === 'function') { cb = opts; opts = {}; } const matches = Object.keys(window.__debug?.idbSnapshot || {}).filter(k => new RegExp('^' + pat.replace(/\\*\\*/g, '.+').replace(/\\*/g, '[^/]*') + '$').test(k)); queueMicrotask(() => cb?.(null, matches)); };\r\n fsmod.globSync = pat => Object.keys(window.__debug?.idbSnapshot || {}).filter(k => new RegExp('^' + pat.replace(/\\*\\*/g, '.+').replace(/\\*/g, '[^/]*') + '$').test(k));\r\n const zlibMod = createZlib(Buf); const httpClient = createHttpClient(Buf); const cpMod = createChildProcess(ctx); const streamMod = makeStream();\r\n const cpReal = makeChildProcessReal(Buf, streamMod); Object.assign(cpMod, { exec: cpReal.exec.bind(cpReal), spawn: cpReal.spawn.bind(cpReal), execFile: cpReal.execFile.bind(cpReal), execSync: cpReal.execSync, spawnSync: cpReal.spawnSync, fork: cpReal.fork });\r\n let cryptoMod = { createHash, createHmac, pbkdf2Sync, pbkdf2: (pw, salt, iter, len, dig, cb) => queueMicrotask(() => { try { cb(null, Buf.from(pbkdf2Sync(pw, salt, iter, len, dig))); } catch (e) { cb(e); } }), randomBytes: n => Buf.from(randomBytes(n)), randomUUID: () => crypto.randomUUID(), randomInt: (a, b) => Math.floor(Math.random() * (b - a) + a), webcrypto: globalThis.crypto, constants: {} };\r\n cryptoMod = extendKeys(extendCrypto(cryptoMod, Buf)); cryptoMod._ops = () => ++debugReg.cryptoOps; cryptoMod.secureHeapUsed = () => ({ total: 0, min: 0, used: 0, utilization: 0 });\r\n const errorCodes = makeErrorCodes(); const stubs = makeStubs(ctx); const diagCh = makeDiagnosticsChannel(); const traceEv = makeTraceEvents(debugReg);\r\n const vmMod = makeVmModule(); const http2Mod = makeHttp2(); const wasiMod = makeWasi(); const moduleRegister = makeModuleRegister(); const workerThreads = makeWorkerThreads(snapFn, Buf);\r\n const getMem = makePerfMemory(performance); const FetchAgent = makeFetchPool(); const netMod = makeNet(Buf); const tlsMod = makeTls(netMod, Buf); const dgramMod = makeDgram(Buf);\r\n const v8Real = makeV8Profiler(debugReg); const heapSnap = makeHeapSnapshot(); const clusterReal = makeCluster(); const inspector = makeInspector(debugReg);\r\n const nativeCS = makeCompressionStreamZlib(streamMod, Buf); const webCodecs = makeWebCodecs(); const webPush = makeWebPush(); const storage = makeStorageHelpers();\r\n const gitMod = makeGit(fsmod); const tarMod = makeTar(fsmod, null, Buf); const dnsMod = makeDns(); const nativeLoader = makeNativeLoader(); const registryMod = makeRegistry(); const busnet = makeBusnet(); globalThis.__busnet = busnet; const busHttp = makeBusHttp(busnet); debugReg.busnet = busnet;\r\n if (nativeCS) registerPolyfill(debugReg, 'compressionStream', 'native', 'CompressionStream available'); if (browserInfo.capabilities.webCodecs) registerPolyfill(debugReg, 'webCodecs', 'native', 'WebCodecs available');\r\n const proc = extendProcessExtras(extendProcess(createProcess(term, ctx), ctx), ctx);\r\n proc.stdin.setRawMode = () => proc.stdin; proc.stdin.isRaw = false; proc.binding = makeProcessBindings(); proc.memoryUsage = getMem; proc.storage = storage; proc.storageBuckets = storage.buckets; proc.cwd = () => ctx.cwd; proc.chdir = p => { ctx.cwd = p.startsWith('/') ? p : pathmod.resolve(ctx.cwd, p); }; proc.umask = m => { const prev = ctx.umask || 0o022; if (m != null) ctx.umask = m; return prev; }; makeForkIpc(proc); proc.dlopen = (t, p) => nativeLoader.dlopen(t, p); proc.resourceUsage = () => { const m = performance.memory || {}; return { userCPUTime: performance.now() * 1000 | 0, systemCPUTime: 0, maxRSS: (m.totalJSHeapSize || 0) / 1024 | 0, sharedMemorySize: 0, unsharedDataSize: 0, unsharedStackSize: 0, minorPageFault: 0, majorPageFault: 0, swappedOut: 0, fsRead: 0, fsWrite: 0, ipcSent: 0, ipcReceived: 0, signalsCount: 0, voluntaryContextSwitches: 0, involuntaryContextSwitches: 0 }; };\r\n wireProcFs(fsmod, makeProcFs(proc)); const denoGlobal = makeDenoGlobal(fsmod, proc, cpMod, ctx.httpHandlers || {}, Buf); const bunGlobal = makeBunGlobal(fsmod, proc, cpMod, ctx.httpHandlers || {}, Buf, streamMod, cryptoMod);\r\n const MODULES = {\r\n path: () => pathmod, fs: () => fsmod, events: () => createEvents(), url: () => createUrlExt(), querystring: () => createQuerystring(),\r\n os: () => { const n=navigator?.hardwareConcurrency||1; const mem=performance.memory||{}; return { platform: () => 'linux', arch: () => 'x64', homedir: () => ctx.env.HOME || '/root', tmpdir: () => '/tmp', cpus: () => Array.from({length:n},(_,i)=>({model:'Browser CPU',speed:3000,times:{user:0,nice:0,sys:0,idle:0,irq:0}})), totalmem: () => mem.jsHeapSizeLimit || 1073741824, freemem: () => (mem.jsHeapSizeLimit || 1073741824) - (mem.usedJSHeapSize || 0), hostname: () => ctx.env.HOSTNAME || 'thebird', EOL: '\\n', release: () => '6.0.0-browser', type: () => 'Linux', uptime: () => performance.now() / 1000, networkInterfaces: () => ({ lo: [{ address: '127.0.0.1', netmask: '255.0.0.0', family: 'IPv4', mac: '00:00:00:00:00:00', internal: true, cidr: '127.0.0.1/8' }] }), loadavg: () => [0, 0, 0], userInfo: () => ({ username: ctx.env.USER || 'root', uid: 0, gid: 0, shell: ctx.env.SHELL || '/bin/sh', homedir: ctx.env.HOME || '/root' }), endianness: () => 'LE', version: () => '#1 SMP', machine: () => 'x86_64', devNull: '/dev/null', availableParallelism: () => n, constants: { signals: { SIGINT: 2, SIGTERM: 15, SIGKILL: 9, SIGHUP: 1 }, errno: { EACCES: 13, EEXIST: 17, ENOENT: 2, EISDIR: 21, ENOTDIR: 20 } } }; },\r\n util: () => ({ inspect, format, promisify: fn => (...a) => new Promise((r, j) => fn(...a, (e, v) => e ? j(e) : r(v))), callbackify: fn => (...a) => { const cb = a.pop(); fn(...a).then(v => cb(null, v), e => cb(e)); }, types: { isPromise: p => p instanceof Promise, isDate: v => v instanceof Date, isRegExp: v => v instanceof RegExp, isBuffer: v => v instanceof Uint8Array, isTypedArray: v => ArrayBuffer.isView(v) && !(v instanceof DataView), isAsyncFunction: f => f?.constructor?.name === 'AsyncFunction', isNativeError: e => e instanceof Error }, deprecate: fn => fn, inherits: (a, b) => { Object.setPrototypeOf(a.prototype, b.prototype); }, debuglog: () => () => {}, isDeepStrictEqual: (a, b) => JSON.stringify(a) === JSON.stringify(b), styleText, stripVTControlCharacters, getCallSites, MIMEType, MIMEParams, parseArgs: ({ args = [], options = {} }) => { const values = {}, positionals = []; for (let i = 0; i < args.length; i++) { const a = args[i]; if (a.startsWith('--')) { const [k, v] = a.slice(2).split('='); if (v !== undefined) values[k] = v; else if (options[k]?.type === 'string') values[k] = args[++i]; else values[k] = true; } else positionals.push(a); } return { values, positionals }; } }),\r\n crypto: () => cryptoMod,\r\n stream: () => streamMod, 'stream/promises': () => streamMod.promises, 'stream/consumers': () => makeStreamConsumers(), 'stream/web': () => ({ ReadableStream, WritableStream, TransformStream }),\r\n http: () => ({ ...httpClient, Agent: FetchAgent, globalAgent: new FetchAgent() }), https: () => ({ ...httpClient, Agent: FetchAgent, globalAgent: new FetchAgent() }),\r\n http2: () => http2Mod, 'node:http2': () => http2Mod,\r\n vm: () => vmMod, 'node:vm': () => vmMod,\r\n buffer: () => ({ Buffer: Buf, constants: { MAX_LENGTH: 4294967295, MAX_STRING_LENGTH: 536870888 }, kMaxLength: 4294967295, Blob, File }),\r\n child_process: () => cpMod,\r\n net: () => netMod, dgram: () => dgramMod, tls: () => tlsMod, worker_threads: () => workerThreads,\r\n zlib: () => ({ ...zlibMod, ...makeStreamingZlib(streamMod, Buf, globalThis.__fflate || {}), ...(nativeCS || {}), ...makeBrotli(streamMod, Buf) }),\r\n assert: () => { const a = (v, m) => { if (!v) throw new Error(m || 'assertion failed'); }; a.ok = a; a.equal = (x, y, m) => a(x === y, m); a.deepEqual = (x, y, m) => a(JSON.stringify(x) === JSON.stringify(y), m); a.deepStrictEqual = a.deepEqual; a.strictEqual = a.equal; a.notEqual = (x, y, m) => a(x !== y, m); a.notDeepEqual = (x, y, m) => a(JSON.stringify(x) !== JSON.stringify(y), m); a.notStrictEqual = a.notEqual; a.throws = (fn, m) => { try { fn(); throw new Error('did not throw'); } catch (e) {} }; a.doesNotThrow = fn => fn(); a.rejects = async fn => { try { await (typeof fn === 'function' ? fn() : fn); throw new Error('did not reject'); } catch {} }; a.fail = m => { throw new Error(m || 'failed'); }; a.match = (s, re) => a(re.test(s)); return a; },\r\n string_decoder: () => stubs.string_decoder, readline: () => makeReadline(term, proc), 'readline/promises': () => stubs.readline_promises,\r\n timers: () => makeTimersMod(), 'timers/promises': () => makeTimersMod().promises, perf_hooks: () => makePerfHooks(),\r\n v8: () => ({ ...makeV8Mod(), ...v8Real, ...heapSnap }), async_hooks: () => makeAsyncHooks(),\r\n inspector: () => inspector, cluster: () => clusterReal || stubs.cluster,\r\n codecs: () => { if (!webCodecs) throw makeModuleNotFoundError('codecs', []); return webCodecs; }, 'web-push': () => webPush,\r\n sea: () => stubs.sea, 'node:sea': () => stubs.sea, test: () => makeTestRunner(term), 'node:test': () => makeTestRunner(term),\r\n 'node:test/reporters': () => ({ tap: makeTapReporter(term), spec: class {}, dot: class {} }), tty: () => stubs.tty, domain: () => stubs.domain,\r\n diagnostics_channel: () => diagCh, punycode: () => stubs.punycode, errors: () => errorCodes, trace_events: () => traceEv,\r\n wasi: () => wasiMod, module: () => ({ ...makeModuleModule(() => {}, MODULES), register: moduleRegister.register, _registerHooks: moduleRegister._hooks }), express: () => createExpress(term, fsmod),\r\n 'better-sqlite3': createSqlite, sqlite: () => ({ DatabaseSync: createSqlite, StatementSync: class {} }), 'node:sqlite': () => ({ DatabaseSync: createSqlite, StatementSync: class {} }),\r\n dns: () => dnsMod, 'dns/promises': () => dnsMod.promises, 'node:dns': () => dnsMod, 'isomorphic-git': () => gitMod, git: () => gitMod, tar: () => tarMod, 'npm-registry-fetch': () => registryMod,\r\n busnet: () => busnet, 'bus-http': () => busHttp,\r\n };\r\n for (const k of Object.keys(MODULES)) if (!k.startsWith('node:')) MODULES['node:' + k] = MODULES[k];\r\n const cons = createConsole(term);\r\n cons.log = (...a) => term.write(format(...a) + '\\r\\n'); cons.info = cons.log; cons.error = (...a) => term.write('\\x1b[31m' + format(...a) + '\\x1b[0m\\r\\n'); cons.warn = (...a) => term.write('\\x1b[33m' + format(...a) + '\\x1b[0m\\r\\n'); cons.debug = cons.log; Object.assign(cons, makeConsoleExtras(cons, term));\r\n const pkgCache = {}; const reqCache = {}; let requireStack = [];\r\n function loadDotEnv() { const envFile = snapFn()[ctx.cwd.replace(/^\\//, '').replace(/\\/$/, '') + '/.env'] || snapFn()['.env']; if (!envFile) return; for (const [k, v] of Object.entries(parseDotEnv(envFile))) if (!(k in ctx.env)) ctx.env[k] = v; }\r\n\r\n const resolveCandidates = (dir, id) => [pathmod.resolve(dir, id) + '.js', pathmod.resolve(dir, id), pathmod.resolve(dir, id) + '/index.js', pathmod.resolve(dir, id, 'index.js')];\r\n function findPkgJsonDir(s, dir) { let d = dir.replace(/^\\//, '').replace(/\\/$/, ''); while (true) { const k = (d ? d + '/' : '') + 'package.json'; if (k in s) return d; if (!d) return null; const up = d.slice(0, d.lastIndexOf('/')); if (up === d) return null; d = up; } }\r\n function isEsmPkg(s, filePath) { const pjDir = findPkgJsonDir(s, pathmod.dirname(filePath)); try { const pj = JSON.parse(s[(pjDir || '') + (pjDir ? '/' : '') + 'package.json']); return pj.type === 'module'; } catch { return false; } }\r\n\r\n function makeRequire(dir) {\r\n const req = function require(id) {\r\n if (id === 'module') return makeModuleModule(req, MODULES);\r\n if (MODULES[id]) return MODULES[id]();\r\n const s = snapFn();\r\n if (id.startsWith('#')) {\r\n const pjRoot = findPkgJsonDir(s, dir);\r\n if (pjRoot) { const pj = JSON.parse(s[pjRoot + '/package.json']); const target = resolveImports(pj, id); if (target) { const resolved = pathmod.resolve('/' + pjRoot, target); return loadFile(resolved.replace(/^\\//, ''), s); } }\r\n throw makeModuleNotFoundError(id, requireStack);\r\n }\r\n if (!id.startsWith('.')) {\r\n if (pkgCache[id]) return pkgCache[id];\r\n const pkgDir = walkUpNodeModules(s, dir, id);\r\n if (pkgDir) { const entry = resolvePackageEntry(s, pkgDir); if (entry) { const m = loadFile(entry.replace(/^\\//, ''), s); if (m) return m; } }\r\n throw makeModuleNotFoundError(id, requireStack);\r\n }\r\n for (const c of resolveCandidates(dir, id)) {\r\n const key = c.replace(/^\\//, '');\r\n if (key in s) { const loaded = loadFile(key, s); if (loaded !== undefined) return loaded; }\r\n }\r\n throw makeModuleNotFoundError(id, requireStack);\r\n };\r\n function loadFile(key, s) {\r\n if (key.endsWith('.json')) return JSON.parse(s[key]);\r\n if (reqCache[key]) return reqCache[key].exports;\r\n const mod = { exports: {} };\r\n reqCache[key] = mod;\r\n const modDir = pathmod.dirname('/' + key);\r\n requireStack.push('/' + key);\r\n try {\r\n const src = s[key]; const esm = key.endsWith('.mjs') || (key.endsWith('.js') && isEsmPkg(s, '/' + key)) || isEsmCode(src);\r\n if (esm) throw new Error(\"ESM module '\" + key + \"' requested via require() — use dynamic import() or run entry as ESM\");\r\n new Function('module', 'exports', 'require', '__filename', '__dirname', 'process', 'console', 'Buffer', 'setTimeout', 'setInterval', 'clearTimeout', 'clearInterval', 'fetch', src)(mod, mod.exports, makeRequire(modDir), '/' + key, modDir, proc, cons, Buf, setTimeout, setInterval, clearTimeout, clearInterval, fetch);\r\n }\r\n finally { requireStack.pop(); }\r\n mod.loaded = true;\r\n return mod.exports;\r\n }\r\n req.resolve = id => {\r\n if (MODULES[id] || id === 'module') return id;\r\n const s = snapFn();\r\n if (!id.startsWith('.')) { const pkgDir = walkUpNodeModules(s, dir, id); if (pkgDir) return resolvePackageEntry(s, pkgDir) || pkgDir; throw makeModuleNotFoundError(id, requireStack); }\r\n for (const c of resolveCandidates(dir, id)) { const key = c.replace(/^\\//, ''); if (key in s) return '/' + key; }\r\n throw makeModuleNotFoundError(id, requireStack);\r\n };\r\n req.cache = reqCache;\r\n return req;\r\n }\r\n\r\n async function preloadAsyncPkgs(entryCode, entryDir) {\r\n const s = snapFn();\r\n const visited = new Set(); const queue = [{ code: entryCode, dir: entryDir }]; const pkgIds = new Set();\r\n const re = /require\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\r\n while (queue.length) {\r\n const { code, dir } = queue.shift(); let m; re.lastIndex = 0;\r\n while ((m = re.exec(code))) { const id = m[1]; if (MODULES[id]) continue; if (!id.startsWith('.')) { pkgIds.add(id); continue; } for (const c of resolveCandidates(dir, id)) { const key = c.replace(/^\\//, ''); if (visited.has(key) || !(key in s)) continue; visited.add(key); queue.push({ code: s[key], dir: pathmod.dirname('/' + key) }); break; } }\r\n }\r\n for (const id of pkgIds) {\r\n if (pkgCache[id]) continue;\r\n const key = 'node_modules/' + id + '/index.js'; if (!(key in s)) continue;\r\n const urlMatch = s[key].match(/import\\((\".+?\")\\)/); if (!urlMatch) continue;\r\n const url = JSON.parse(urlMatch[1]);\r\n try { const mod = await import(url); const exp = { ...mod }; if (mod.default && typeof mod.default === 'object') Object.assign(exp, mod.default); pkgCache[id] = mod.default && Object.keys(mod).length === 1 ? mod.default : exp; }\r\n catch (e) { term.write('\\x1b[31mfailed to load ' + id + ': ' + e.message + '\\x1b[0m\\r\\n'); }\r\n }\r\n }\r\n\r\n return async function nodeEval(code, filename, argv, stdinBuf) {\r\n const dir = filename ? pathmod.dirname(filename) : ctx.cwd;\r\n const fpath = filename || '[eval]';\r\n proc.argv = filename ? ['node', fpath, ...(argv || [])] : ['node'];\r\n proc.exitCode = 0;\r\n loadDotEnv();\r\n globalThis.__fflate = await preloadFflate().catch(() => ({}));\r\n if (proc.sourceMapsEnabled) { await preloadSourceMap().catch(() => {}); installSourceMapStacks(snapFn); }\r\n const rtName = switchRuntime(code.startsWith('#!') ? code.slice(0, code.indexOf('\\n')) : ''); logRuntimeSwitch(debugReg, debugReg.runtime.active, rtName, fpath);\r\n if (isTsFile(fpath)) code = await preprocessSource(fpath, code);\r\n await preloadAsyncPkgs(code, dir);\r\n const reqFn = makeRequire(dir);\r\n const scope = { process: proc, console: cons, require: reqFn, Buffer: Buf, __filename: fpath, __dirname: dir, setTimeout, setInterval, clearTimeout, clearInterval, fetch, module: { exports: {} }, exports: {}, global: globalThis, URL, URLSearchParams, TextEncoder, TextDecoder };\r\n const prevGlobals = { process: globalThis.process, Buffer: globalThis.Buffer, Deno: globalThis.Deno, Bun: globalThis.Bun };\r\n globalThis.process = proc; globalThis.Buffer = Buf;\r\n if (rtName === 'deno') globalThis.Deno = denoGlobal; else delete globalThis.Deno;\r\n if (rtName === 'bun') globalThis.Bun = bunGlobal; else delete globalThis.Bun;\r\n installCaptureStackTrace(); installPrepareStackTraceHook();\r\n const unhandledH = e => { e.preventDefault?.(); const err = e.reason || e; term.write('\\x1b[31m' + rewriteStack(err, fpath) + '\\x1b[0m\\r\\n'); ctx.lastExitCode = 1; };\r\n window.addEventListener('unhandledrejection', unhandledH);\r\n try {\r\n if (isEsmCode(code)) { const preamble = '\\nconst __filename = ' + JSON.stringify(fpath) + ';\\nconst __dirname = ' + JSON.stringify(dir) + ';\\n'; const mod = await runEsm(preamble + code, scope); if (mod && !filename) { for (const [k, v] of Object.entries(mod)) if (k !== 'default') cons.log(k + ':', v); } ctx.lastExitCode = proc.exitCode | 0; return; }\r\n const keys = Object.keys(scope), vals = Object.values(scope);\r\n const fn = new Function(...keys, 'return (async () => {\\n' + code + '\\n})()');\r\n const pending = fn(...vals);\r\n if (stdinBuf) queueMicrotask(() => proc.stdin._feed(stdinBuf));\r\n const result = await pending;\r\n if (result !== undefined && !filename) cons.log(result);\r\n ctx.lastExitCode = proc.exitCode | 0;\r\n } catch (e) {\r\n if (e && e.__nodeExit) { ctx.lastExitCode = e.code | 0; return; }\r\n term.write('\\x1b[31m' + rewriteStack(e, fpath) + '\\x1b[0m\\r\\n');\r\n ctx.lastExitCode = 1;\r\n } finally {\r\n window.removeEventListener('unhandledrejection', unhandledH);\r\n if (prevGlobals.process !== undefined) globalThis.process = prevGlobals.process; else delete globalThis.process;\r\n if (prevGlobals.Buffer !== undefined) globalThis.Buffer = prevGlobals.Buffer; else delete globalThis.Buffer;\r\n if (prevGlobals.Deno !== undefined) globalThis.Deno = prevGlobals.Deno; else delete globalThis.Deno;\r\n if (prevGlobals.Bun !== undefined) globalThis.Bun = prevGlobals.Bun; else delete globalThis.Bun;\r\n }\r\n };\r\n}\r\n","shell-readline.js":"export function createReadline({ term, getCompletions, onLine, getPrompt, isBlockOpen }) {\r\n let buf = '';\r\n let pos = 0;\r\n let histIdx = -1;\r\n let escBuf = '';\r\n let inEsc = false;\r\n let heredocTag = null;\r\n let heredocBody = '';\r\n let heredocPrefix = '';\r\n\r\n const write = s => term.write(s);\r\n\r\n function promptStr() { return '\\r\\n\\x1b[32m' + getPrompt() + ' $ \\x1b[0m'; }\r\n function showPrompt() { write(promptStr()); }\r\n\r\n function redraw() {\r\n write('\\r\\x1b[2K\\x1b[32m' + getPrompt() + ' $ \\x1b[0m' + buf);\r\n if (pos < buf.length) write('\\x1b[' + (buf.length - pos) + 'D');\r\n }\r\n\r\n function insert(ch) {\r\n buf = buf.slice(0, pos) + ch + buf.slice(pos);\r\n pos++;\r\n redraw();\r\n }\r\n\r\n function delBefore() {\r\n if (!pos) return;\r\n buf = buf.slice(0, pos - 1) + buf.slice(pos);\r\n pos--;\r\n redraw();\r\n }\r\n\r\n function delAfter() {\r\n if (pos >= buf.length) return;\r\n buf = buf.slice(0, pos) + buf.slice(pos + 1);\r\n redraw();\r\n }\r\n\r\n function moveTo(n) {\r\n pos = Math.max(0, Math.min(buf.length, n));\r\n const pLen = getPrompt().length + 3;\r\n if (pLen + pos > 0) write('\\r\\x1b[' + (pLen + pos) + 'C');\r\n else write('\\r');\r\n }\r\n\r\n function handleTab() {\r\n const word = buf.slice(0, pos).split(/\\s+/).pop() || '';\r\n const completions = getCompletions(buf, word);\r\n if (!completions.length) return;\r\n if (completions.length === 1) {\r\n const rest = completions[0].slice(word.length);\r\n buf = buf.slice(0, pos) + rest + buf.slice(pos);\r\n pos += rest.length;\r\n redraw();\r\n return;\r\n }\r\n const common = completions.reduce((a, b) => {\r\n let i = 0;\r\n while (i < a.length && a[i] === b[i]) i++;\r\n return a.slice(0, i);\r\n });\r\n if (common.length > word.length) {\r\n const rest = common.slice(word.length);\r\n buf = buf.slice(0, pos) + rest + buf.slice(pos);\r\n pos += rest.length;\r\n redraw();\r\n return;\r\n }\r\n write('\\r\\n' + completions.join(' '));\r\n redraw();\r\n }\r\n\r\n function commit() {\r\n const line = buf;\r\n write('\\r\\n');\r\n if (heredocTag !== null) {\r\n if (line === heredocTag) {\r\n const full = heredocPrefix + \" '\" + heredocBody.replace(/'/g, \"'\\\\''\") + \"'\";\r\n heredocTag = null; heredocBody = ''; heredocPrefix = '';\r\n buf = ''; pos = 0; histIdx = -1;\r\n onLine(full);\r\n return;\r\n }\r\n heredocBody += line + '\\n';\r\n buf = ''; pos = 0;\r\n write('\\x1b[32m> \\x1b[0m');\r\n return;\r\n }\r\n const hd = line.match(/^(.*?)<<-?\\s*(['\"]?)(\\w+)\\2\\s*$/);\r\n if (hd) {\r\n heredocPrefix = hd[1].trim();\r\n heredocTag = hd[3];\r\n heredocBody = '';\r\n buf = ''; pos = 0;\r\n write('\\x1b[32m> \\x1b[0m');\r\n return;\r\n }\r\n const hereStr = line.match(/^(.*?)<<<\\s*(.+)$/);\r\n if (hereStr) {\r\n const body = hereStr[2].replace(/^[\"']|[\"']$/g, '');\r\n const full = hereStr[1].trim() + ' \"' + body.replace(/\"/g, '\\\\\"') + '\"';\r\n buf = ''; pos = 0; histIdx = -1;\r\n const hist = getHistory();\r\n if (line.trim()) hist.unshift(line);\r\n onLine(full);\r\n return;\r\n }\r\n if (line.endsWith('\\\\')) {\r\n buf = line.slice(0, -1) + '\\n';\r\n pos = buf.length;\r\n write('\\x1b[32m> \\x1b[0m');\r\n return;\r\n }\r\n const hist = getHistory();\r\n const expanded = expandBang(line, hist);\r\n if (expanded !== line) { write('\\x1b[33m' + expanded + '\\x1b[0m\\r\\n'); }\r\n if (expanded.trim()) hist.unshift(expanded);\r\n buf = '';\r\n pos = 0;\r\n histIdx = -1;\r\n onLine(expanded);\r\n }\r\n\r\n function getHistory() { return window.__debug?.shell?.history || []; }\r\n\r\n function histNav(dir) {\r\n const hist = getHistory();\r\n if (!hist.length) return;\r\n histIdx = Math.max(-1, Math.min(hist.length - 1, histIdx + dir));\r\n buf = histIdx === -1 ? '' : hist[histIdx];\r\n pos = buf.length;\r\n redraw();\r\n }\r\n\r\n const ESC_MAP = {\r\n '[A': () => histNav(1),\r\n '[B': () => histNav(-1),\r\n '[C': () => { if (pos < buf.length) { pos++; write('\\x1b[C'); } },\r\n '[D': () => { if (pos > 0) { pos--; write('\\x1b[D'); } },\r\n '[H': () => moveTo(0),\r\n '[F': () => moveTo(buf.length),\r\n '[3~': () => delAfter(),\r\n '[1~': () => moveTo(0),\r\n '[4~': () => moveTo(buf.length),\r\n };\r\n\r\n function onData(data) {\r\n if (inEsc) {\r\n escBuf += data;\r\n if (escBuf === '[') return;\r\n if (escBuf.match(/^\\[[\\x40-\\x7E]$/) || escBuf.match(/^\\[\\d+~$/)) {\r\n const handler = ESC_MAP[escBuf];\r\n if (handler) handler();\r\n inEsc = false; escBuf = '';\r\n return;\r\n }\r\n if (escBuf.length > 6) { inEsc = false; escBuf = ''; }\r\n return;\r\n }\r\n if (data === '\\x1b') { inEsc = true; escBuf = ''; return; }\r\n if (data === '\\x01') { moveTo(0); return; }\r\n if (data === '\\x05') { moveTo(buf.length); return; }\r\n if (data === '\\x0b') { buf = buf.slice(0, pos); redraw(); return; }\r\n if (data === '\\x15') { buf = buf.slice(pos); pos = 0; redraw(); return; }\r\n if (data === '\\x09') { handleTab(); return; }\r\n if (data === '\\r') { commit(); return; }\r\n if (data === '\\x7f') { delBefore(); return; }\r\n if (data >= ' ') { insert(data); return; }\r\n }\r\n\r\n function showContinuation() { write('\\x1b[32m> \\x1b[0m'); }\r\n\r\n return { onData, showPrompt, showContinuation };\r\n}\r\n\r\nfunction expandBang(line, hist) {\r\n if (!line.includes('!') || !hist.length) return line;\r\n return line.replace(/!(!|-?\\d+|[A-Za-z]\\w*)/g, (m, ref) => {\r\n if (ref === '!') return hist[0] || m;\r\n if (/^-?\\d+$/.test(ref)) { const n = +ref; return (n < 0 ? hist[-n - 1] : hist[hist.length - n]) || m; }\r\n const found = hist.find(h => h.startsWith(ref));\r\n return found || m;\r\n });\r\n}\r\n","node-builtins.js":"const snap = () => window.__debug?.idbSnapshot || {};\r\nconst toKey = p => p.replace(/^\\//, '');\r\nconst persist = () => window.__debug?.idbPersist?.();\r\nconst previewWrite = () => window.__debug?.shell?.onPreviewWrite?.();\r\n\r\nexport function createPath() {\r\n const sep = '/';\r\n const normalize = p => {\r\n const parts = [];\r\n for (const s of p.split('/')) {\r\n if (s === '..') parts.pop();\r\n else if (s && s !== '.') parts.push(s);\r\n }\r\n return (p.startsWith('/') ? '/' : '') + parts.join('/');\r\n };\r\n return {\r\n sep,\r\n normalize,\r\n join: (...a) => normalize(a.join('/')),\r\n resolve: (...a) => {\r\n let r = '';\r\n for (const p of a) r = p.startsWith('/') ? p : r + '/' + p;\r\n return normalize(r);\r\n },\r\n dirname: p => { const i = p.lastIndexOf('/'); return i <= 0 ? '/' : p.slice(0, i); },\r\n basename: (p, ext) => { const b = p.split('/').pop() || ''; return ext && b.endsWith(ext) ? b.slice(0, -ext.length) : b; },\r\n extname: p => { const b = p.split('/').pop() || ''; const i = b.lastIndexOf('.'); return i > 0 ? b.slice(i) : ''; },\r\n isAbsolute: p => p.startsWith('/'),\r\n relative: (from, to) => to.replace(from.replace(/\\/$/, '') + '/', ''),\r\n parse: p => {\r\n const dir = p.slice(0, p.lastIndexOf('/')) || '/';\r\n const base = p.split('/').pop() || '';\r\n const ext = base.lastIndexOf('.') > 0 ? base.slice(base.lastIndexOf('.')) : '';\r\n return { root: '/', dir, base, ext, name: ext ? base.slice(0, -ext.length) : base };\r\n },\r\n };\r\n}\r\n\r\nexport function createFs() {\r\n const resolveP = p => typeof p === 'string' ? p : p.toString();\r\n return {\r\n readFileSync: (p, enc) => {\r\n const key = toKey(resolveP(p));\r\n const data = snap()[key];\r\n if (data == null) throw Object.assign(new Error('ENOENT: ' + p), { code: 'ENOENT' });\r\n return enc ? data : data;\r\n },\r\n writeFileSync: (p, data) => {\r\n const s = snap();\r\n s[toKey(resolveP(p))] = typeof data === 'string' ? data : String(data);\r\n persist();\r\n previewWrite();\r\n },\r\n appendFileSync: (p, data) => {\r\n const key = toKey(resolveP(p));\r\n const s = snap();\r\n s[key] = (s[key] || '') + (typeof data === 'string' ? data : String(data));\r\n persist();\r\n },\r\n existsSync: p => toKey(resolveP(p)) in snap(),\r\n unlinkSync: p => {\r\n const key = toKey(resolveP(p));\r\n if (!(key in snap())) throw Object.assign(new Error('ENOENT: ' + p), { code: 'ENOENT' });\r\n delete snap()[key];\r\n persist();\r\n },\r\n mkdirSync: (p, opts) => {\r\n const key = toKey(resolveP(p));\r\n if (!snap()[key + '/.keep']) { snap()[key + '/.keep'] = ''; persist(); }\r\n },\r\n readdirSync: p => {\r\n const prefix = toKey(resolveP(p));\r\n const pLen = prefix ? prefix.length + 1 : 0;\r\n const seen = new Set();\r\n for (const k of Object.keys(snap())) {\r\n if (prefix && !k.startsWith(prefix + '/') && k !== prefix) continue;\r\n if (!prefix && !k.includes('/')) { seen.add(k); continue; }\r\n const rest = k.slice(pLen);\r\n const first = rest.split('/')[0];\r\n if (first && first !== '.keep') seen.add(first);\r\n }\r\n return [...seen];\r\n },\r\n statSync: p => {\r\n const key = toKey(resolveP(p));\r\n const s = snap();\r\n const isFile = key in s;\r\n const isDir = !isFile && Object.keys(s).some(k => k.startsWith(key + '/'));\r\n if (!isFile && !isDir) throw Object.assign(new Error('ENOENT: ' + p), { code: 'ENOENT' });\r\n return { isFile: () => isFile, isDirectory: () => isDir, size: isFile ? (s[key]?.length || 0) : 0 };\r\n },\r\n renameSync: (o, n) => {\r\n const s = snap();\r\n const ok = toKey(resolveP(o)), nk = toKey(resolveP(n));\r\n if (!(ok in s)) throw Object.assign(new Error('ENOENT: ' + o), { code: 'ENOENT' });\r\n s[nk] = s[ok];\r\n delete s[ok];\r\n persist();\r\n },\r\n copyFileSync: (s, d) => {\r\n const src = snap()[toKey(resolveP(s))];\r\n if (src == null) throw Object.assign(new Error('ENOENT: ' + s), { code: 'ENOENT' });\r\n snap()[toKey(resolveP(d))] = src;\r\n persist();\r\n },\r\n rmSync: (p, opts = {}) => {\r\n const key = toKey(resolveP(p)); const s = snap();\r\n if (key in s) { delete s[key]; persist(); return; }\r\n if (opts.recursive) { for (const k of Object.keys(s)) if (k === key || k.startsWith(key + '/')) delete s[k]; persist(); return; }\r\n if (!opts.force) throw Object.assign(new Error('ENOENT: ' + p), { code: 'ENOENT' });\r\n },\r\n rmdirSync: (p, opts = {}) => { const key = toKey(resolveP(p)); for (const k of Object.keys(snap())) if (k.startsWith(key + '/')) delete snap()[k]; persist(); },\r\n accessSync: p => { if (!(toKey(resolveP(p)) in snap())) throw Object.assign(new Error('ENOENT: ' + p), { code: 'ENOENT' }); },\r\n realpathSync: p => resolveP(p),\r\n promises: null,\r\n };\r\n}\r\n\r\nexport function createEvents() {\r\n return class EventEmitter {\r\n constructor() { this._e = {}; }\r\n on(ev, fn) { (this._e[ev] = this._e[ev] || []).push(fn); return this; }\r\n once(ev, fn) { const w = (...a) => { this.off(ev, w); fn(...a); }; return this.on(ev, w); }\r\n off(ev, fn) { this._e[ev] = (this._e[ev] || []).filter(f => f !== fn); return this; }\r\n removeListener(ev, fn) { return this.off(ev, fn); }\r\n removeAllListeners(ev) { if (ev) delete this._e[ev]; else this._e = {}; return this; }\r\n emit(ev, ...a) { for (const fn of (this._e[ev] || [])) fn(...a); return (this._e[ev] || []).length > 0; }\r\n listeners(ev) { return (this._e[ev] || []).slice(); }\r\n listenerCount(ev) { return (this._e[ev] || []).length; }\r\n };\r\n}\r\n\r\nexport function createUrl() {\r\n return {\r\n parse: s => {\r\n const u = new URL(s);\r\n return { protocol: u.protocol, host: u.host, hostname: u.hostname, port: u.port, pathname: u.pathname, search: u.search, query: u.search.slice(1), hash: u.hash, href: u.href };\r\n },\r\n format: o => {\r\n const u = new URL('http://x');\r\n for (const [k, v] of Object.entries(o)) { try { u[k] = v; } catch {} }\r\n return u.href;\r\n },\r\n resolve: (from, to) => new URL(to, from).href,\r\n };\r\n}\r\n\r\nexport function createQuerystring() {\r\n return {\r\n parse: s => Object.fromEntries(new URLSearchParams(s)),\r\n stringify: o => new URLSearchParams(o).toString(),\r\n escape: s => encodeURIComponent(s),\r\n unescape: s => decodeURIComponent(s),\r\n };\r\n}\r\n\r\nexport function createBuffer() {\r\n class Buf extends Uint8Array {\r\n toString(enc) {\r\n if (enc === 'base64') return btoa(String.fromCharCode(...this));\r\n if (enc === 'hex') return [...this].map(b => b.toString(16).padStart(2, '0')).join('');\r\n return new TextDecoder().decode(this);\r\n }\r\n toJSON() { return { type: 'Buffer', data: [...this] }; }\r\n slice(s, e) { return Buf.from(super.slice(s, e)); }\r\n subarray(s, e) { return Buf.from(super.subarray(s, e)); }\r\n equals(o) { if (!(o instanceof Uint8Array) || o.length !== this.length) return false; for (let i = 0; i < this.length; i++) if (this[i] !== o[i]) return false; return true; }\r\n compare(o) { const l = Math.min(this.length, o.length); for (let i = 0; i < l; i++) { if (this[i] < o[i]) return -1; if (this[i] > o[i]) return 1; } return this.length === o.length ? 0 : this.length < o.length ? -1 : 1; }\r\n indexOf(v, fromIdx = 0) { const bytes = typeof v === 'string' ? new TextEncoder().encode(v) : v instanceof Uint8Array ? v : new Uint8Array([v]); outer: for (let i = fromIdx; i <= this.length - bytes.length; i++) { for (let j = 0; j < bytes.length; j++) if (this[i + j] !== bytes[j]) continue outer; return i; } return -1; }\r\n includes(v) { return this.indexOf(v) !== -1; }\r\n write(str, offset = 0, length, encoding) { if (typeof offset === 'string') { encoding = offset; offset = 0; } const bytes = new TextEncoder().encode(str); const n = Math.min(bytes.length, this.length - offset, length ?? bytes.length); this.set(bytes.subarray(0, n), offset); return n; }\r\n readUInt8(o = 0) { return this[o]; }\r\n readUInt16BE(o = 0) { return (this[o] << 8) | this[o + 1]; }\r\n readUInt16LE(o = 0) { return this[o] | (this[o + 1] << 8); }\r\n readUInt32BE(o = 0) { return ((this[o] * 0x1000000) + (this[o + 1] << 16) | (this[o + 2] << 8) | this[o + 3]) >>> 0; }\r\n writeUInt8(v, o = 0) { this[o] = v & 0xff; return o + 1; }\r\n }\r\n Buf.from = (d, enc) => {\r\n if (d instanceof Uint8Array) return new Buf(d);\r\n if (Array.isArray(d)) return new Buf(d);\r\n if (typeof d !== 'string') return new Buf(0);\r\n if (enc === 'base64') return new Buf(Uint8Array.from(atob(d), c => c.charCodeAt(0)));\r\n if (enc === 'hex') return new Buf(d.match(/.{2}/g).map(h => parseInt(h, 16)));\r\n return new Buf(new TextEncoder().encode(d));\r\n };\r\n Buf.alloc = (n, fill) => { const b = new Buf(n); if (fill) b.fill(typeof fill === 'number' ? fill : fill.charCodeAt(0)); return b; };\r\n Buf.concat = list => { const t = list.reduce((s, b) => s + b.length, 0); const r = new Buf(t); let o = 0; for (const b of list) { r.set(b, o); o += b.length; } return r; };\r\n Buf.isBuffer = o => o instanceof Buf;\r\n Buf.byteLength = (s, enc) => Buf.from(s, enc).length;\r\n Buf.compare = (a, b) => a.compare(b);\r\n Buf.allocUnsafe = n => new Buf(n);\r\n Buf.poolSize = 8192;\r\n return Buf;\r\n}\r\n","preview-sw-client.js":"const SW_PATH = new URL('./preview-sw.js', import.meta.url).href;\r\nconst SCOPE = new URL('./preview/', import.meta.url).href;\r\n\r\nwindow.__debug = window.__debug || {};\r\nwindow.__debug.sw = { registered: false, error: null };\r\n\r\nexport async function registerPreviewSW() {\r\n if (!('serviceWorker' in navigator)) {\r\n window.__debug.sw.error = 'unsupported';\r\n throw new Error('ServiceWorker not supported');\r\n }\r\n try {\r\n const reg = await navigator.serviceWorker.register(SW_PATH, { scope: SCOPE });\r\n await navigator.serviceWorker.ready;\r\n window.__debug.sw.registered = true;\r\n window.__debug.sw.registration = reg;\r\n return reg;\r\n } catch (err) {\r\n window.__debug.sw.error = err.message;\r\n throw err;\r\n }\r\n}\r\n\r\nnavigator.serviceWorker?.addEventListener('message', e => {\r\n if (e.data?.type === 'SW_STREAM_READ') {\r\n const path = e.data.path;\r\n const procsub = path.match(/^\\/procsub\\/(\\d+)$/);\r\n if (procsub && window.__debug?.shell?.procsubRead) {\r\n const data = window.__debug.shell.procsubRead(procsub[1]);\r\n e.ports[0]?.postMessage({ data: data || '', found: data != null });\r\n return;\r\n }\r\n const fdM = path.match(/^\\/dev\\/fd\\/(\\d+)$/);\r\n if (fdM && window.__debug?.shell?.fdRead) {\r\n try { const data = window.__debug.shell.fdRead(fdM[1]); e.ports[0]?.postMessage({ data: data || '', found: true }); }\r\n catch { e.ports[0]?.postMessage({ data: '', found: false }); }\r\n return;\r\n }\r\n e.ports[0]?.postMessage({ found: false });\r\n return;\r\n }\r\n if (e.data?.type !== 'EXPRESS_REQUEST') return;\r\n const { path, method, body: reqBody, headers: reqHeaders } = e.data;\r\n const replyPort = e.ports[0];\r\n const handlers = window.__debug?.shell?.httpHandlers || {};\r\n const app = Object.values(handlers)[0];\r\n if (!app?.routes) { replyPort.postMessage({ status: 503, body: '<h1>503</h1><p>no server running — run <code>node server.js</code> in terminal</p>', contentType: 'text/html' }); return; }\r\n const routes = app.routes[method] || [];\r\n const match = routes.find(r => r.path === '*' || r.path === path || path.startsWith(r.path));\r\n if (!match) { replyPort.postMessage({ status: 404, body: 'no route for ' + method + ' ' + path, contentType: 'text/plain' }); return; }\r\n let done = false;\r\n const finish = (status, body, ct) => { if (done) return; done = true; replyPort.postMessage({ status, body, contentType: ct }); };\r\n const res = {\r\n _body: '', _status: 200, _ct: 'text/html',\r\n writeHead(code, headers) { this._status = code; if (headers?.['Content-Type']) this._ct = headers['Content-Type']; return this; },\r\n setHeader(k, v) { if (k.toLowerCase() === 'content-type') this._ct = v; return this; },\r\n write(chunk) { this._body += String(chunk); return true; },\r\n end(chunk) { if (chunk != null) this._body += String(chunk); finish(this._status, this._body, this._ct); },\r\n send(b) { this._body = typeof b === 'string' ? b : JSON.stringify(b); finish(this._status, this._body, this._ct); },\r\n json(o) { this._ct = 'application/json'; this.send(JSON.stringify(o)); },\r\n status(n) { this._status = n; return this; },\r\n };\r\n let bodyConsumed = false;\r\n const req = {\r\n method, url: path, path, query: {}, headers: reqHeaders || {},\r\n [Symbol.asyncIterator]: async function* () { if (!bodyConsumed && reqBody) { bodyConsumed = true; yield reqBody; } },\r\n };\r\n try {\r\n const r = match.fn(req, res);\r\n if (r && typeof r.then === 'function') r.catch(err => finish(500, '<h1>500</h1><pre>' + String(err.message).replace(/</g, '&lt;') + '</pre>', 'text/html'));\r\n } catch (err) { finish(500, '<h1>500</h1><pre>' + String(err.message).replace(/</g, '&lt;') + '</pre>', 'text/html'); }\r\n setTimeout(() => finish(res._status, res._body, res._ct), 10000);\r\n});\r\n","preview-sw.js":"const swJobs = new Map();\nconst swFds = new Map();\nconst swProcsubs = new Map();\n\nself.addEventListener('install', e => self.skipWaiting());\nself.addEventListener('activate', e => e.waitUntil(clients.claim()));\n\nself.addEventListener('message', e => {\n const d = e.data;\n if (!d) return;\n if (d.type === 'JOB_REGISTER') swJobs.set(d.id + '@' + d.tabId, { id: d.id, cmd: d.cmd, tabId: d.tabId, startedAt: Date.now() });\n else if (d.type === 'JOB_UNREGISTER') swJobs.delete(d.id + '@' + d.tabId);\n else if (d.type === 'JOB_LIST') e.ports?.[0]?.postMessage({ jobs: [...swJobs.values()] });\n else if (d.type === 'PROCSUB_PUT') swProcsubs.set(d.id, d.data);\n else if (d.type === 'FD_PUT') swFds.set(d.id, d.data);\n});\n\nself.addEventListener('fetch', e => {\n const url = new URL(e.request.url);\n const swScope = new URL(self.registration.scope);\n if (!url.pathname.startsWith(swScope.pathname)) return;\n const path = '/' + url.pathname.slice(swScope.pathname.length).replace(/^\\//, '') || '/';\n\n const procsubM = path.match(/^\\/procsub\\/(\\d+)$/);\n if (procsubM) { e.respondWith(serveFromClient(path, e.request)); return; }\n if (path.startsWith('/dev/fd/')) { e.respondWith(serveFromClient(path, e.request)); return; }\n const tcpM = path.match(/^\\/dev\\/tcp\\/([^/]+)\\/(\\d+)(\\/.*)?$/);\n if (tcpM) { e.respondWith(fetch('http://' + tcpM[1] + ':' + tcpM[2] + (tcpM[3] || '/'), { method: e.request.method, body: e.request.method !== 'GET' ? e.request.body : undefined })); return; }\n\n e.respondWith(forwardExpress(e.request, path));\n});\n\nasync function serveFromClient(path, request) {\n const clients_ = await clients.matchAll({ includeUncontrolled: true });\n const target = clients_.find(c => c.frameType !== 'nested') || clients_[0];\n if (!target) return new Response('no client', { status: 503 });\n const chan = new MessageChannel();\n target.postMessage({ type: 'SW_STREAM_READ', path }, [chan.port2]);\n return new Promise(res => {\n const timeout = setTimeout(() => res(new Response('timeout', { status: 504 })), 5000);\n chan.port1.onmessage = msg => {\n clearTimeout(timeout);\n if (!msg.data?.found) res(new Response('not found', { status: 404 }));\n else res(new Response(msg.data.data, { status: 200, headers: { 'Content-Type': 'text/plain' } }));\n };\n });\n}\n\nasync function forwardExpress(request, path) {\n const body = ['POST', 'PUT', 'PATCH'].includes(request.method) ? await request.text() : null;\n const headers = {};\n request.headers.forEach((v, k) => { headers[k] = v; });\n const chan = new MessageChannel();\n const clients_ = await clients.matchAll({ includeUncontrolled: true });\n const target = clients_.find(c => c.frameType !== 'nested') || clients_[0];\n if (!target) return new Response('no client', { status: 503 });\n target.postMessage({ type: 'EXPRESS_REQUEST', path, method: request.method, body, headers }, [chan.port2]);\n return new Promise(res => {\n const timeout = setTimeout(() => res(new Response('timeout', { status: 504 })), 10000);\n chan.port1.onmessage = msg => {\n clearTimeout(timeout);\n res(new Response(msg.data.body, { status: msg.data.status || 200, headers: { 'Content-Type': msg.data.contentType || 'text/html' } }));\n };\n });\n}\n","acp-stream.js":"import { ClientSideConnection } from './vendor/acp-sdk.js';\r\n\r\nfunction wsStream(url) {\r\n const ws = new WebSocket(url);\r\n const incoming = [];\r\n let notify = null;\r\n Object.assign(window.__debug = window.__debug || {}, {\r\n acp: Object.assign(window.__debug?.acp || {}, { wsUrl: url, wsState: 'connecting' })\r\n });\r\n ws.addEventListener('message', e => {\r\n const msg = JSON.parse(e.data);\r\n if (notify) { const fn = notify; notify = null; fn(msg); }\r\n else incoming.push(msg);\r\n });\r\n const readable = new ReadableStream({\r\n start(ctrl) {\r\n ws.addEventListener('close', () => {\r\n window.__debug.acp.wsState = 'closed';\r\n ctrl.close();\r\n });\r\n ws.addEventListener('error', e => {\r\n window.__debug.acp.wsState = 'error';\r\n window.__debug.acp.wsError = e.message || String(e);\r\n ctrl.error(e);\r\n });\r\n },\r\n pull() {\r\n return new Promise(res => {\r\n if (incoming.length) { res(incoming.shift()); return; }\r\n notify = msg => res(msg);\r\n }).then(msg => {});\r\n }\r\n });\r\n const writable = new WritableStream({\r\n write(msg) { ws.send(JSON.stringify(msg)); }\r\n });\r\n return new Promise((res, rej) => {\r\n ws.addEventListener('open', () => {\r\n window.__debug.acp.wsState = 'open';\r\n res({ readable, writable });\r\n });\r\n ws.addEventListener('error', (e) => {\r\n window.__debug.acp.wsState = 'error';\r\n const errMsg = e?.message || 'WebSocket connection failed';\r\n window.__debug.acp.wsError = errMsg;\r\n console.log('[ACP] Connection error:', errMsg);\r\n rej(new Error(errMsg));\r\n });\r\n });\r\n}\r\n\r\nexport async function* streamACP({ url, model, messages, system, tools, maxOutputTokens, onStepFinish }) {\r\n yield { type: 'start-step' };\r\n const stream = await wsStream(url);\r\n let sessionUpdates = [];\r\n let notifyUpdate = null;\r\n const client = new ClientSideConnection(agent => ({\r\n sessionUpdate(params) {\r\n if (notifyUpdate) { const fn = notifyUpdate; notifyUpdate = null; fn(params); }\r\n else sessionUpdates.push(params);\r\n },\r\n requestPermission() { return Promise.resolve({ outcome: 'allow_once' }); },\r\n readTextFile({ path }) {\r\n const t = tools?.read_file;\r\n return t?.execute?.({ path }).then(c => ({ content: c })) || Promise.resolve({ content: '' });\r\n },\r\n writeTextFile({ path, content }) {\r\n const t = tools?.write_file;\r\n return t?.execute?.({ path, content }).then(() => ({})) || Promise.resolve({});\r\n },\r\n }), stream);\r\n\r\n await client.initialize({ protocolVersion: '0.1', capabilities: {}, clientInfo: { name: 'thebird', version: '1.0' } });\r\n const { sessionId } = await client.newSession({ cwd: '/' });\r\n\r\n const userText = messages.filter(m => m.role === 'user').map(m =>\r\n typeof m.content === 'string' ? m.content : m.content.filter(b => b.type === 'text').map(b => b.text).join('')\r\n ).join('\\n');\r\n\r\n const promptPromise = client.prompt({ sessionId, message: { role: 'user', content: [{ type: 'text', text: userText }] } });\r\n\r\n const getUpdate = () => new Promise(res => {\r\n if (sessionUpdates.length) { res(sessionUpdates.shift()); return; }\r\n notifyUpdate = res;\r\n });\r\n\r\n let done = false;\r\n promptPromise.then(() => { done = true; if (notifyUpdate) { const fn = notifyUpdate; notifyUpdate = null; fn(null); } });\r\n\r\n while (!done) {\r\n const update = await getUpdate();\r\n if (!update) break;\r\n for (const item of (update.updates || [])) {\r\n if (item.type === 'message_chunk' && item.chunk?.type === 'text') {\r\n yield { type: 'text-delta', textDelta: item.chunk.text };\r\n }\r\n }\r\n }\r\n\r\n yield { type: 'finish-step', finishReason: 'stop' };\r\n if (onStepFinish) await onStepFinish();\r\n}\r\n","tui.css":":root {\r\n --tui-fg: #33ff33;\r\n --tui-fg-dim: #1a9a1a;\r\n --tui-fg-bright: #66ff66;\r\n --tui-bg: #0a0a0a;\r\n --tui-bg-alt: #111311;\r\n --tui-border: #33ff33;\r\n --tui-border-dim: #1a5a1a;\r\n --tui-accent: #ffcc00;\r\n --tui-error: #ff3333;\r\n --tui-user: #00ccff;\r\n}\r\n*, *::before, *::after { font-family: 'Cascadia Code', 'Fira Code', 'JetBrains Mono', 'SF Mono', 'Consolas', monospace !important; }\r\nhtml, body { background: var(--tui-bg); color: var(--tui-fg); height: 100%; margin: 0; font-size: 14px; line-height: 1.4; }\r\n::selection { background: var(--tui-fg); color: var(--tui-bg); }\r\n.tui-header {\r\n border-bottom: 1px solid var(--tui-border-dim);\r\n background: var(--tui-bg);\r\n padding: 0;\r\n white-space: pre;\r\n font-size: 11px;\r\n line-height: 1.2;\r\n color: var(--tui-fg-dim);\r\n overflow: hidden;\r\n}\r\n.tui-header .logo { color: var(--tui-fg-bright); }\r\n.tui-header .ver { color: var(--tui-accent); }\r\n.tui-tabs {\r\n display: flex;\r\n gap: 0;\r\n background: var(--tui-bg);\r\n border-bottom: 1px solid var(--tui-border-dim);\r\n padding: 0 1ch;\r\n}\r\n.tui-tab {\r\n background: none;\r\n border: 1px solid var(--tui-border-dim);\r\n border-bottom: none;\r\n color: var(--tui-fg-dim);\r\n padding: 2px 2ch;\r\n cursor: pointer;\r\n font-size: 13px;\r\n margin-bottom: -1px;\r\n position: relative;\r\n}\r\n.tui-tab:hover { color: var(--tui-fg); }\r\n.tui-tab.active {\r\n color: var(--tui-accent);\r\n border-color: var(--tui-border);\r\n background: var(--tui-bg-alt);\r\n border-bottom: 1px solid var(--tui-bg-alt);\r\n}\r\n.tui-input, .tui-select, .tui-textarea {\r\n background: var(--tui-bg);\r\n border: 1px solid var(--tui-border-dim);\r\n color: var(--tui-fg);\r\n padding: 2px 1ch;\r\n font-size: 13px;\r\n outline: none;\r\n}\r\n.tui-input:focus, .tui-select:focus, .tui-textarea:focus {\r\n border-color: var(--tui-border);\r\n box-shadow: 0 0 4px rgba(51, 255, 51, 0.15);\r\n}\r\n.tui-select { appearance: none; padding-right: 2ch; background-image: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='5'%3E%3Cpath d='M0 0l4 5 4-5z' fill='%2333ff33'/%3E%3C/svg%3E\"); background-repeat: no-repeat; background-position: right 0.5ch center; }\r\n.tui-btn {\r\n background: var(--tui-bg);\r\n border: 1px solid var(--tui-border-dim);\r\n color: var(--tui-fg);\r\n padding: 2px 2ch;\r\n cursor: pointer;\r\n font-size: 13px;\r\n}\r\n.tui-btn:hover { border-color: var(--tui-border); color: var(--tui-fg-bright); }\r\n.tui-btn.primary { border-color: var(--tui-accent); color: var(--tui-accent); }\r\n.tui-btn.primary:hover { background: var(--tui-accent); color: var(--tui-bg); }\r\n.tui-msg {\r\n max-width: 72ch;\r\n padding: 4px 1ch;\r\n white-space: pre-wrap;\r\n word-break: break-word;\r\n font-size: 13px;\r\n line-height: 1.4;\r\n}\r\n.tui-msg.user { color: var(--tui-user); }\r\n.tui-msg.user::before { content: '> '; color: var(--tui-user); }\r\n.tui-msg.assistant { color: var(--tui-fg); }\r\n.tui-msg.assistant::before { content: '< '; color: var(--tui-fg-dim); }\r\n.tui-status { color: var(--tui-accent); font-size: 12px; }\r\n.tui-error-text { color: var(--tui-error); font-size: 12px; }\r\n.tui-spinner::after { content: '⠋'; animation: tui-spin 0.6s steps(6) infinite; }\r\n@keyframes tui-spin {\r\n 0% { content: '⠋'; } 16% { content: '⠙'; } 33% { content: '⠹'; }\r\n 50% { content: '⠸'; } 66% { content: '⠼'; } 83% { content: '⠴'; }\r\n}\r\n.tui-toolbar {\r\n display: flex;\r\n gap: 1ch;\r\n padding: 2px 1ch;\r\n border-bottom: 1px solid var(--tui-border-dim);\r\n background: var(--tui-bg);\r\n align-items: center;\r\n flex-wrap: wrap;\r\n font-size: 13px;\r\n}\r\n.tui-toolbar label { color: var(--tui-fg-dim); font-size: 12px; }\r\n.tui-msglist {\r\n flex: 1;\r\n overflow-y: auto;\r\n padding: 1ch;\r\n display: flex;\r\n flex-direction: column;\r\n gap: 4px;\r\n}\r\n.tui-compose {\r\n display: flex;\r\n gap: 1ch;\r\n padding: 4px 1ch;\r\n border-top: 1px solid var(--tui-border-dim);\r\n background: var(--tui-bg);\r\n}\r\n.tui-scanline {\r\n pointer-events: none;\r\n position: fixed;\r\n top: 0; left: 0; right: 0; bottom: 0;\r\n background: repeating-linear-gradient(0deg, transparent, transparent 2px, rgba(0,0,0,0.03) 2px, rgba(0,0,0,0.03) 4px);\r\n z-index: 9999;\r\n}\r\n@keyframes blink { 50% { opacity: 0; } }\r\n#pane-term { background: #000; }\r\n.hidden { display: none !important; }\r\n","vendor/xterm-bundle.js":"var xr=Object.defineProperty,xn=Object.getOwnPropertyDescriptor,En=(e,t)=>{for(var i in t)xr(e,i,{get:t[i],enumerable:!0})},q=(e,t,i,s)=>{for(var r=s>1?void 0:s?xn(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(r=(s?o(t,i,r):o(r))||r);return s&&r&&xr(t,i,r),r},y=(e,t)=>(i,s)=>t(i,s,e),ys=\"Terminal input\",Bi={get:()=>ys,set:e=>ys=e},Cs=\"Too much output to announce, navigate to rows manually to read\",Ri={get:()=>Cs,set:e=>Cs=e};function Dn(e){return e.replace(/\\r?\\n/g,\"\\r\")}function Bn(e,t){return t?\"\\x1B[200~\"+e+\"\\x1B[201~\":e}function Rn(e,t){e.clipboardData&&e.clipboardData.setData(\"text/plain\",t.selectionText),e.preventDefault()}function Ln(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let r=e.clipboardData.getData(\"text/plain\");Er(r,t,i,s)}}function Er(e,t,i,s){e=Dn(e),e=Bn(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=\"\"}function Dr(e,t,i){let s=i.getBoundingClientRect(),r=e.clientX-s.left-10,n=e.clientY-s.top-10;t.style.width=\"20px\",t.style.height=\"20px\",t.style.left=`${r}px`,t.style.top=`${n}px`,t.style.zIndex=\"1000\",t.focus()}function ks(e,t,i,s,r){Dr(e,t,i),r&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function Ue(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function ri(e,t=0,i=e.length){let s=\"\";for(let r=t;r<i;++r){let n=e[r];n>65535?(n-=65536,s+=String.fromCharCode((n>>10)+55296)+String.fromCharCode(n%1024+56320)):s+=String.fromCharCode(n)}return s}var Mn=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let s=0,r=0;if(this._interim){let n=e.charCodeAt(r++);56320<=n&&n<=57343?t[s++]=(this._interim-55296)*1024+n-56320+65536:(t[s++]=this._interim,t[s++]=n),this._interim=0}for(let n=r;n<i;++n){let o=e.charCodeAt(n);if(55296<=o&&o<=56319){if(++n>=i)return this._interim=o,s;let a=e.charCodeAt(n);56320<=a&&a<=57343?t[s++]=(o-55296)*1024+a-56320+65536:(t[s++]=o,t[s++]=a);continue}o!==65279&&(t[s++]=o)}return s}},Pn=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let s=0,r,n,o,a,l=0,h=0;if(this.interim[0]){let u=!1,f=this.interim[0];f&=(f&224)===192?31:(f&240)===224?15:7;let _=0,p;for(;(p=this.interim[++_]&63)&&_<4;)f<<=6,f|=p;let C=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,D=C-_;for(;h<D;){if(h>=i)return 0;if(p=e[h++],(p&192)!==128){h--,u=!0;break}else this.interim[_++]=p,f<<=6,f|=p&63}u||(C===2?f<128?h--:t[s++]=f:C===3?f<2048||f>=55296&&f<=57343||f===65279||(t[s++]=f):f<65536||f>1114111||(t[s++]=f)),this.interim.fill(0)}let d=i-4,c=h;for(;c<i;){for(;c<d&&!((r=e[c])&128)&&!((n=e[c+1])&128)&&!((o=e[c+2])&128)&&!((a=e[c+3])&128);)t[s++]=r,t[s++]=n,t[s++]=o,t[s++]=a,c+=4;if(r=e[c++],r<128)t[s++]=r;else if((r&224)===192){if(c>=i)return this.interim[0]=r,s;if(n=e[c++],(n&192)!==128){c--;continue}if(l=(r&31)<<6|n&63,l<128){c--;continue}t[s++]=l}else if((r&240)===224){if(c>=i)return this.interim[0]=r,s;if(n=e[c++],(n&192)!==128){c--;continue}if(c>=i)return this.interim[0]=r,this.interim[1]=n,s;if(o=e[c++],(o&192)!==128){c--;continue}if(l=(r&15)<<12|(n&63)<<6|o&63,l<2048||l>=55296&&l<=57343||l===65279)continue;t[s++]=l}else if((r&248)===240){if(c>=i)return this.interim[0]=r,s;if(n=e[c++],(n&192)!==128){c--;continue}if(c>=i)return this.interim[0]=r,this.interim[1]=n,s;if(o=e[c++],(o&192)!==128){c--;continue}if(c>=i)return this.interim[0]=r,this.interim[1]=n,this.interim[2]=o,s;if(a=e[c++],(a&192)!==128){c--;continue}if(l=(r&7)<<18|(n&63)<<12|(o&63)<<6|a&63,l<65536||l>1114111)continue;t[s++]=l}}return s}},Br=\"\",qe=\" \",Bt=class Rr{constructor(){this.fg=0,this.bg=0,this.extended=new jt}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new Rr;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},jt=class Lr{constructor(t=0,i=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=i}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new Lr(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},we=class Mr extends Bt{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new jt,this.combinedData=\"\"}static fromCharData(t){let i=new Mr;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Ue(this.content&2097151):\"\"}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let r=t[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(s-55296)*1024+r-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},xs=\"di$target\",Li=\"di$dependencies\",_i=new Map;function Tn(e){return e[Li]||[]}function se(e){if(_i.has(e))return _i.get(e);let t=function(i,s,r){if(arguments.length!==3)throw new Error(\"@IServiceName-decorator can only be used to decorate a parameter\");An(t,i,r)};return t._id=e,_i.set(e,t),t}function An(e,t,i){t[xs]===t?t[Li].push({id:e,index:i}):(t[Li]=[{id:e,index:i}],t[xs]=t)}var ce=se(\"BufferService\"),Pr=se(\"CoreMouseService\"),tt=se(\"CoreService\"),On=se(\"CharsetService\"),_s=se(\"InstantiationService\"),Tr=se(\"LogService\"),de=se(\"OptionsService\"),Ar=se(\"OscLinkService\"),In=se(\"UnicodeService\"),Rt=se(\"DecorationService\"),Mi=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let s=[],r=this._optionsService.rawOptions.linkHandler,n=new we,o=i.getTrimmedLength(),a=-1,l=-1,h=!1;for(let d=0;d<o;d++)if(!(l===-1&&!i.hasContent(d))){if(i.loadCell(d,n),n.hasExtendedAttrs()&&n.extended.urlId)if(l===-1){l=d,a=n.extended.urlId;continue}else h=n.extended.urlId!==a;else l!==-1&&(h=!0);if(h||l!==-1&&d===o-1){let c=this._oscLinkService.getLinkData(a)?.uri;if(c){let u={start:{x:l+1,y:e},end:{x:d+(!h&&d===o-1?1:0),y:e}},f=!1;if(!r?.allowNonHttpProtocols)try{let _=new URL(c);[\"http:\",\"https:\"].includes(_.protocol)||(f=!0)}catch{f=!0}f||s.push({text:c,range:u,activate:(_,p)=>r?r.activate(_,p,u):Nn(_,p),hover:(_,p)=>r?.hover?.(_,p,u),leave:(_,p)=>r?.leave?.(_,p,u)})}h=!1,n.hasExtendedAttrs()&&n.extended.urlId?(l=d,a=n.extended.urlId):(l=-1,a=-1)}}t(s)}};Mi=q([y(0,ce),y(1,de),y(2,Ar)],Mi);function Nn(e,t){if(confirm(`Do you want to navigate to ${t}?\r\n\r\nWARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn(\"Opening link blocked as opener could not be cleared\")}}var ni=se(\"CharSizeService\"),Oe=se(\"CoreBrowserService\"),us=se(\"MouseService\"),Ie=se(\"RenderService\"),Hn=se(\"SelectionService\"),Or=se(\"CharacterJoinerService\"),nt=se(\"ThemeService\"),Ir=se(\"LinkProviderService\"),Wn=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?Es.isErrorNoTelemetry(e)?new Es(e.message+`\r\n\r\n`+e.stack):new Error(e.message+`\r\n\r\n`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},zn=new Wn;function Wt(e){Fn(e)||zn.onUnexpectedError(e)}var Pi=\"Canceled\";function Fn(e){return e instanceof $n?!0:e instanceof Error&&e.name===Pi&&e.message===Pi}var $n=class extends Error{constructor(){super(Pi),this.name=this.message}};function Kn(e){return e?new Error(`Illegal argument: ${e}`):new Error(\"Illegal argument\")}var Es=class Ti extends Error{constructor(t){super(t),this.name=\"CodeExpectedError\"}static fromError(t){if(t instanceof Ti)return t;let i=new Ti;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name===\"CodeExpectedError\"}},Ai=class Nr extends Error{constructor(t){super(t||\"An unexpected bug occurred.\"),Object.setPrototypeOf(this,Nr.prototype)}};function Un(e,t,i=0,s=e.length){let r=i,n=s;for(;r<n;){let o=Math.floor((r+n)/2);t(e[o])?r=o+1:n=o}return r-1}var qn=class Hr{constructor(t){this._array=t,this._findLastMonotonousLastIdx=0}findLastMonotonous(t){if(Hr.assertInvariants){if(this._prevFindLastPredicate){for(let s of this._array)if(this._prevFindLastPredicate(s)&&!t(s))throw new Error(\"MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.\")}this._prevFindLastPredicate=t}let i=Un(this._array,t,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=i+1,i===-1?void 0:this._array[i]}};qn.assertInvariants=!1;function ue(e,t=0){return e[e.length-(1+t)]}var Wr;(e=>{function t(n){return n<0}e.isLessThan=t;function i(n){return n<=0}e.isLessThanOrEqual=i;function s(n){return n>0}e.isGreaterThan=s;function r(n){return n===0}e.isNeitherLessOrGreaterThan=r,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(Wr||={});function Vn(e,t){return(i,s)=>t(e(i),e(s))}var Yn=(e,t)=>e-t,Ds=class Oi{constructor(t){this.iterate=t}forEach(t){this.iterate(i=>(t(i),!0))}toArray(){let t=[];return this.iterate(i=>(t.push(i),!0)),t}filter(t){return new Oi(i=>this.iterate(s=>t(s)?i(s):!0))}map(t){return new Oi(i=>this.iterate(s=>i(t(s))))}some(t){let i=!1;return this.iterate(s=>(i=t(s),!i)),i}findFirst(t){let i;return this.iterate(s=>t(s)?(i=s,!1):!0),i}findLast(t){let i;return this.iterate(s=>(t(s)&&(i=s),!0)),i}findLastMaxBy(t){let i,s=!0;return this.iterate(r=>((s||Wr.isGreaterThan(t(r,i)))&&(s=!1,i=r),!0)),i}};Ds.empty=new Ds(e=>{});function Xn(e,t){let i=Object.create(null);for(let s of e){let r=t(s),n=i[r];n||(n=i[r]=[]),n.push(s)}return i}var Bs,Rs,_l=class{constructor(e,t){this.toKey=t,this._map=new Map,this[Bs]=\"SetWithKey\";for(let i of e)this.add(i)}get size(){return this._map.size}add(e){let t=this.toKey(e);return this._map.set(t,e),this}delete(e){return this._map.delete(this.toKey(e))}has(e){return this._map.has(this.toKey(e))}*entries(){for(let e of this._map.values())yield[e,e]}keys(){return this.values()}*values(){for(let e of this._map.values())yield e}clear(){this._map.clear()}forEach(e,t){this._map.forEach(i=>e.call(t,i,i,this))}[(Rs=Symbol.iterator,Bs=Symbol.toStringTag,Rs)](){return this.values()}},jn=class{constructor(){this.map=new Map}add(e,t){let i=this.map.get(e);i||(i=new Set,this.map.set(e,i)),i.add(t)}delete(e,t){let i=this.map.get(e);i&&(i.delete(t),i.size===0&&this.map.delete(e))}forEach(e,t){let i=this.map.get(e);i&&i.forEach(t)}get(e){return this.map.get(e)||new Set}};function Gn(e,t){let i=this,s=!1,r;return function(){if(s)return r;if(s=!0,t)try{r=e.apply(i,arguments)}finally{t()}else r=e.apply(i,arguments);return r}}var zr;(e=>{function t(E){return E&&typeof E==\"object\"&&typeof E[Symbol.iterator]==\"function\"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*r(E){yield E}e.single=r;function n(E){return t(E)?E:r(E)}e.wrap=n;function o(E){return E||i}e.from=o;function*a(E){for(let T=E.length-1;T>=0;T--)yield E[T]}e.reverse=a;function l(E){return!E||E[Symbol.iterator]().next().done===!0}e.isEmpty=l;function h(E){return E[Symbol.iterator]().next().value}e.first=h;function d(E,T){let A=0;for(let re of E)if(T(re,A++))return!0;return!1}e.some=d;function c(E,T){for(let A of E)if(T(A))return A}e.find=c;function*u(E,T){for(let A of E)T(A)&&(yield A)}e.filter=u;function*f(E,T){let A=0;for(let re of E)yield T(re,A++)}e.map=f;function*_(E,T){let A=0;for(let re of E)yield*T(re,A++)}e.flatMap=_;function*p(...E){for(let T of E)yield*T}e.concat=p;function C(E,T,A){let re=A;for(let be of E)re=T(re,be);return re}e.reduce=C;function*D(E,T,A=E.length){for(T<0&&(T+=E.length),A<0?A+=E.length:A>E.length&&(A=E.length);T<A;T++)yield E[T]}e.slice=D;function I(E,T=Number.POSITIVE_INFINITY){let A=[];if(T===0)return[A,E];let re=E[Symbol.iterator]();for(let be=0;be<T;be++){let Ce=re.next();if(Ce.done)return[A,e.empty()];A.push(Ce.value)}return[A,{[Symbol.iterator](){return re}}]}e.consume=I;async function M(E){let T=[];for await(let A of E)T.push(A);return Promise.resolve(T)}e.asyncToArray=M})(zr||={});var Jn=!1,Ze=null,Zn=class Fr{constructor(){this.livingDisposables=new Map}getDisposableData(t){let i=this.livingDisposables.get(t);return i||(i={parent:null,source:null,isSingleton:!1,value:t,idx:Fr.idx++},this.livingDisposables.set(t,i)),i}trackDisposable(t){let i=this.getDisposableData(t);i.source||(i.source=new Error().stack)}setParent(t,i){let s=this.getDisposableData(t);s.parent=i}markAsDisposed(t){this.livingDisposables.delete(t)}markAsSingleton(t){this.getDisposableData(t).isSingleton=!0}getRootParent(t,i){let s=i.get(t);if(s)return s;let r=t.parent?this.getRootParent(this.getDisposableData(t.parent),i):t;return i.set(t,r),r}getTrackedDisposables(){let t=new Map;return[...this.livingDisposables.entries()].filter(([,i])=>i.source!==null&&!this.getRootParent(i,t).isSingleton).flatMap(([i])=>i)}computeLeakingDisposables(t=10,i){let s;if(i)s=i;else{let l=new Map,h=[...this.livingDisposables.values()].filter(c=>c.source!==null&&!this.getRootParent(c,l).isSingleton);if(h.length===0)return;let d=new Set(h.map(c=>c.value));if(s=h.filter(c=>!(c.parent&&d.has(c.parent))),s.length===0)throw new Error(\"There are cyclic diposable chains!\")}if(!s)return;function r(l){function h(c,u){for(;c.length>0&&u.some(f=>typeof f==\"string\"?f===c[0]:c[0].match(f));)c.shift()}let d=l.source.split(`\r\n`).map(c=>c.trim().replace(\"at \",\"\")).filter(c=>c!==\"\");return h(d,[\"Error\",/^trackDisposable \\(.*\\)$/,/^DisposableTracker.trackDisposable \\(.*\\)$/]),d.reverse()}let n=new jn;for(let l of s){let h=r(l);for(let d=0;d<=h.length;d++)n.add(h.slice(0,d).join(`\r\n`),l)}s.sort(Vn(l=>l.idx,Yn));let o=\"\",a=0;for(let l of s.slice(0,t)){a++;let h=r(l),d=[];for(let c=0;c<h.length;c++){let u=h[c];u=`(shared with ${n.get(h.slice(0,c+1).join(`\r\n`)).size}/${s.length} leaks) at ${u}`;let f=n.get(h.slice(0,c).join(`\r\n`)),_=Xn([...f].map(p=>r(p)[c]),p=>p);delete _[h[c]];for(let[p,C]of Object.entries(_))d.unshift(` - stacktraces of ${C.length} other leaks continue with ${p}`);d.unshift(u)}o+=`\r\n\r\n\r\n==================== Leaking disposable ${a}/${s.length}: ${l.value.constructor.name} ====================\r\n${d.join(`\r\n`)}\r\n============================================================\r\n\r\n`}return s.length>t&&(o+=`\r\n\r\n\r\n... and ${s.length-t} more leaking disposables\r\n\r\n`),{leaks:s,details:o}}};Zn.idx=0;function Qn(e){Ze=e}if(Jn){let e=\"__is_disposable_tracked__\";Qn(new class{trackDisposable(t){let i=new Error(\"Potentially leaked disposable\").stack;setTimeout(()=>{t[e]||console.log(i)},3e3)}setParent(t,i){if(t&&t!==R.None)try{t[e]=!0}catch{}}markAsDisposed(t){if(t&&t!==R.None)try{t[e]=!0}catch{}}markAsSingleton(t){}})}function oi(e){return Ze?.trackDisposable(e),e}function hi(e){Ze?.markAsDisposed(e)}function kt(e,t){Ze?.setParent(e,t)}function eo(e,t){if(Ze)for(let i of e)Ze.setParent(i,t)}function Ls(e){return Ze?.markAsSingleton(e),e}function Qe(e){if(zr.is(e)){let t=[];for(let i of e)if(i)try{i.dispose()}catch(s){t.push(s)}if(t.length===1)throw t[0];if(t.length>1)throw new AggregateError(t,\"Encountered errors while disposing of store\");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function to(...e){let t=W(()=>Qe(e));return eo(e,t),t}function W(e){let t=oi({dispose:Gn(()=>{hi(t),e()})});return t}var $r=class Kr{constructor(){this._toDispose=new Set,this._isDisposed=!1,oi(this)}dispose(){this._isDisposed||(hi(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Qe(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error(\"Cannot register a disposable on itself!\");return kt(t,this),this._isDisposed?Kr.DISABLE_DISPOSED_WARNING||console.warn(new Error(\"Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!\").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error(\"Cannot dispose a disposable on itself!\");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),kt(t,null))}};$r.DISABLE_DISPOSED_WARNING=!1;var Ve=$r,R=class{constructor(){this._store=new Ve,oi(this),kt(this._store,this)}dispose(){hi(this),this._store.dispose()}_register(e){if(e===this)throw new Error(\"Cannot register a disposable on itself!\");return this._store.add(e)}};R.None=Object.freeze({dispose(){}});var rt=class{constructor(){this._isDisposed=!1,oi(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&kt(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,hi(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&kt(e,null),e}},ge=typeof window==\"object\"?window:globalThis,Ii=class Ni{constructor(t){this.element=t,this.next=Ni.Undefined,this.prev=Ni.Undefined}};Ii.Undefined=new Ii(void 0);var $=Ii,Ms=class{constructor(){this._first=$.Undefined,this._last=$.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===$.Undefined}clear(){let e=this._first;for(;e!==$.Undefined;){let t=e.next;e.prev=$.Undefined,e.next=$.Undefined,e=t}this._first=$.Undefined,this._last=$.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new $(e);if(this._first===$.Undefined)this._first=i,this._last=i;else if(t){let r=this._last;this._last=i,i.prev=r,r.next=i}else{let r=this._first;this._first=i,i.next=r,r.prev=i}this._size+=1;let s=!1;return()=>{s||(s=!0,this._remove(i))}}shift(){if(this._first!==$.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==$.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==$.Undefined&&e.next!==$.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===$.Undefined&&e.next===$.Undefined?(this._first=$.Undefined,this._last=$.Undefined):e.next===$.Undefined?(this._last=this._last.prev,this._last.next=$.Undefined):e.prev===$.Undefined&&(this._first=this._first.next,this._first.prev=$.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==$.Undefined;)yield e.element,e=e.next}},io=globalThis.performance&&typeof globalThis.performance.now==\"function\",so=class Ur{static create(t){return new Ur(t)}constructor(t){this._now=io&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},ro=!1,Ps=!1,no=!1,oe;(e=>{e.None=()=>R.None;function t(w){if(no){let{onDidAddListener:m}=w,k=zi.create(),b=0;w.onDidAddListener=()=>{++b===2&&(console.warn(\"snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here\"),k.print()),m?.()}}}function i(w,m){return u(w,()=>{},0,void 0,!0,void 0,m)}e.defer=i;function s(w){return(m,k=null,b)=>{let x=!1,S;return S=w(P=>{if(!x)return S?S.dispose():x=!0,m.call(k,P)},null,b),x&&S.dispose(),S}}e.once=s;function r(w,m,k){return d((b,x=null,S)=>w(P=>b.call(x,m(P)),null,S),k)}e.map=r;function n(w,m,k){return d((b,x=null,S)=>w(P=>{m(P),b.call(x,P)},null,S),k)}e.forEach=n;function o(w,m,k){return d((b,x=null,S)=>w(P=>m(P)&&b.call(x,P),null,S),k)}e.filter=o;function a(w){return w}e.signal=a;function l(...w){return(m,k=null,b)=>{let x=to(...w.map(S=>S(P=>m.call(k,P))));return c(x,b)}}e.any=l;function h(w,m,k,b){let x=k;return r(w,S=>(x=m(x,S),x),b)}e.reduce=h;function d(w,m){let k,b={onWillAddFirstListener(){k=w(x.fire,x)},onDidRemoveLastListener(){k?.dispose()}};m||t(b);let x=new v(b);return m?.add(x),x.event}function c(w,m){return m instanceof Array?m.push(w):m&&m.add(w),w}function u(w,m,k=100,b=!1,x=!1,S,P){let F,ne,ke,Le=0,Z,Ne={leakWarningThreshold:S,onWillAddFirstListener(){F=w(Ye=>{Le++,ne=m(ne,Ye),b&&!ke&&(ae.fire(ne),ne=void 0),Z=()=>{let ht=ne;ne=void 0,ke=void 0,(!b||Le>1)&&ae.fire(ht),Le=0},typeof k==\"number\"?(clearTimeout(ke),ke=setTimeout(Z,k)):ke===void 0&&(ke=0,queueMicrotask(Z))})},onWillRemoveListener(){x&&Le>0&&Z?.()},onDidRemoveLastListener(){Z=void 0,F.dispose()}};P||t(Ne);let ae=new v(Ne);return P?.add(ae),ae.event}e.debounce=u;function f(w,m=0,k){return e.debounce(w,(b,x)=>b?(b.push(x),b):[x],m,void 0,!0,void 0,k)}e.accumulate=f;function _(w,m=(b,x)=>b===x,k){let b=!0,x;return o(w,S=>{let P=b||!m(S,x);return b=!1,x=S,P},k)}e.latch=_;function p(w,m,k){return[e.filter(w,m,k),e.filter(w,b=>!m(b),k)]}e.split=p;function C(w,m=!1,k=[],b){let x=k.slice(),S=w(ne=>{x?x.push(ne):F.fire(ne)});b&&b.add(S);let P=()=>{x?.forEach(ne=>F.fire(ne)),x=null},F=new v({onWillAddFirstListener(){S||(S=w(ne=>F.fire(ne)),b&&b.add(S))},onDidAddFirstListener(){x&&(m?setTimeout(P):P())},onDidRemoveLastListener(){S&&S.dispose(),S=null}});return b&&b.add(F),F.event}e.buffer=C;function D(w,m){return(k,b,x)=>{let S=m(new M);return w(function(P){let F=S.evaluate(P);F!==I&&k.call(b,F)},void 0,x)}}e.chain=D;let I=Symbol(\"HaltChainable\");class M{constructor(){this.steps=[]}map(m){return this.steps.push(m),this}forEach(m){return this.steps.push(k=>(m(k),k)),this}filter(m){return this.steps.push(k=>m(k)?k:I),this}reduce(m,k){let b=k;return this.steps.push(x=>(b=m(b,x),b)),this}latch(m=(k,b)=>k===b){let k=!0,b;return this.steps.push(x=>{let S=k||!m(x,b);return k=!1,b=x,S?x:I}),this}evaluate(m){for(let k of this.steps)if(m=k(m),m===I)break;return m}}function E(w,m,k=b=>b){let b=(...F)=>P.fire(k(...F)),x=()=>w.on(m,b),S=()=>w.removeListener(m,b),P=new v({onWillAddFirstListener:x,onDidRemoveLastListener:S});return P.event}e.fromNodeEventEmitter=E;function T(w,m,k=b=>b){let b=(...F)=>P.fire(k(...F)),x=()=>w.addEventListener(m,b),S=()=>w.removeEventListener(m,b),P=new v({onWillAddFirstListener:x,onDidRemoveLastListener:S});return P.event}e.fromDOMEventEmitter=T;function A(w){return new Promise(m=>s(w)(m))}e.toPromise=A;function re(w){let m=new v;return w.then(k=>{m.fire(k)},()=>{m.fire(void 0)}).finally(()=>{m.dispose()}),m.event}e.fromPromise=re;function be(w,m){return w(k=>m.fire(k))}e.forward=be;function Ce(w,m,k){return m(k),w(b=>m(b))}e.runAndSubscribe=Ce;class Pt{constructor(m,k){this._observable=m,this._counter=0,this._hasChanged=!1;let b={onWillAddFirstListener:()=>{m.addObserver(this)},onDidRemoveLastListener:()=>{m.removeObserver(this)}};k||t(b),this.emitter=new v(b),k&&k.add(this.emitter)}beginUpdate(m){this._counter++}handlePossibleChange(m){}handleChange(m,k){this._hasChanged=!0}endUpdate(m){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function z(w,m){return new Pt(w,m).emitter.event}e.fromObservable=z;function ci(w){return(m,k,b)=>{let x=0,S=!1,P={beginUpdate(){x++},endUpdate(){x--,x===0&&(w.reportChanges(),S&&(S=!1,m.call(k)))},handlePossibleChange(){},handleChange(){S=!0}};w.addObserver(P),w.reportChanges();let F={dispose(){w.removeObserver(P)}};return b instanceof Ve?b.add(F):Array.isArray(b)&&b.push(F),F}}e.fromObservableLight=ci})(oe||={});var Hi=class Wi{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Wi._idPool++}`,Wi.all.add(this)}start(t){this._stopWatch=new so,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Hi.all=new Set,Hi._idPool=0;var oo=Hi,Ts=-1,qr=class Vr{constructor(t,i,s=(Vr._idPool++).toString(16).padStart(3,\"0\")){this._errorHandler=t,this.threshold=i,this.name=s,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(t,i){let s=this.threshold;if(s<=0||i<s)return;this._stacks||(this._stacks=new Map);let r=this._stacks.get(t.value)||0;if(this._stacks.set(t.value,r+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=s*.5;let[n,o]=this.getMostFrequentStack(),a=`[${this.name}] potential listener LEAK detected, having ${i} listeners already. MOST frequent listener (${o}):`;console.warn(a),console.warn(n);let l=new ao(a,n);this._errorHandler(l)}return()=>{let n=this._stacks.get(t.value)||0;this._stacks.set(t.value,n-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,i=0;for(let[s,r]of this._stacks)(!t||i<r)&&(t=[s,r],i=r);return t}};qr._idPool=1;var ho=qr,zi=class Yr{constructor(t){this.value=t}static create(){let t=new Error;return new Yr(t.stack??\"\")}print(){console.warn(this.value.split(`\r\n`).slice(2).join(`\r\n`))}},ao=class extends Error{constructor(e,t){super(e),this.name=\"ListenerLeakError\",this.stack=t}},lo=class extends Error{constructor(e,t){super(e),this.name=\"ListenerRefusalError\",this.stack=t}},co=0,zt=class{constructor(e){this.value=e,this.id=co++}},_o=2,uo=(e,t)=>{if(e instanceof zt)t(e);else for(let i=0;i<e.length;i++){let s=e[i];s&&t(s)}},Ft;if(ro){let e=[];setInterval(()=>{e.length!==0&&(console.warn(\"[LEAKING LISTENERS] GC'ed these listeners that were NOT yet disposed:\"),console.warn(e.join(`\r\n`)),e.length=0)},3e3),Ft=new FinalizationRegistry(t=>{typeof t==\"string\"&&e.push(t)})}var v=class{constructor(e){this._size=0,this._options=e,this._leakageMon=Ts>0||this._options?.leakWarningThreshold?new ho(e?.onListenerError??Wt,this._options?.leakWarningThreshold??Ts):void 0,this._perfMon=this._options?._profName?new oo(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){if(!this._disposed){if(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners){if(Ps){let e=this._listeners;queueMicrotask(()=>{uo(e,t=>t.stack?.print())})}this._listeners=void 0,this._size=0}this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose()}}get event(){return this._event??=(e,t,i)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let a=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(a);let l=this._leakageMon.getMostFrequentStack()??[\"UNKNOWN stack\",-1],h=new lo(`${a}. HINT: Stack shows most frequent listener (${l[1]}-times)`,l[0]);return(this._options?.onListenerError||Wt)(h),R.None}if(this._disposed)return R.None;t&&(e=e.bind(t));let s=new zt(e),r,n;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(s.stack=zi.create(),r=this._leakageMon.check(s.stack,this._size+1)),Ps&&(s.stack=n??zi.create()),this._listeners?this._listeners instanceof zt?(this._deliveryQueue??=new fo,this._listeners=[this._listeners,s]):this._listeners.push(s):(this._options?.onWillAddFirstListener?.(this),this._listeners=s,this._options?.onDidAddFirstListener?.(this)),this._size++;let o=W(()=>{Ft?.unregister(o),r?.(),this._removeListener(s)});if(i instanceof Ve?i.add(o):Array.isArray(i)&&i.push(o),Ft){let a=new Error().stack.split(`\r\n`).slice(2,3).join(`\r\n`).trim(),l=/(file:|vscode-file:\\/\\/vscode-app)?(\\/[^:]*:\\d+:\\d+)/.exec(a);Ft.register(o,l?.[2]??a,o)}return o},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,i=t.indexOf(e);if(i===-1)throw console.log(\"disposed?\",this._disposed),console.log(\"size?\",this._size),console.log(\"arr?\",JSON.stringify(this._listeners)),new Error(\"Attempted to dispose unknown listener\");this._size--,t[i]=void 0;let s=this._deliveryQueue.current===this;if(this._size*_o<=t.length){let r=0;for(let n=0;n<t.length;n++)t[n]?t[r++]=t[n]:s&&(this._deliveryQueue.end--,r<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=r}}_deliver(e,t){if(!e)return;let i=this._options?.onListenerError||Wt;if(!i){e.value(t);return}try{e.value(t)}catch(s){i(s)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof zt)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}this._perfMon?.stop()}hasListeners(){return this._size>0}},fo=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Fi=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new v,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new v,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,i){if(this.getZoomLevel(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToZoomLevel.set(s,t),this._onDidChangeZoomLevel.fire(s)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,i){this.mapWindowIdToZoomFactor.set(this.getWindowId(i),t)}setFullscreen(t,i){if(this.isFullscreen(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToFullScreen.set(s,t),this._onDidChangeFullscreen.fire(s)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};Fi.INSTANCE=new Fi;var fs=Fi;function po(e,t,i){typeof t==\"string\"&&(t=e.matchMedia(t)),t.addEventListener(\"change\",i)}var fl=fs.INSTANCE.onDidChangeZoomLevel;function go(e){return fs.INSTANCE.getZoomFactor(e)}var pl=fs.INSTANCE.onDidChangeFullscreen,ot=typeof navigator==\"object\"?navigator.userAgent:\"\",$i=ot.indexOf(\"Firefox\")>=0,$t=ot.indexOf(\"AppleWebKit\")>=0,ps=ot.indexOf(\"Chrome\")>=0,Xr=!ps&&ot.indexOf(\"Safari\")>=0,gl=ot.indexOf(\"Electron/\")>=0,vl=ot.indexOf(\"Android\")>=0,Kt=!1;if(typeof ge.matchMedia==\"function\"){let e=ge.matchMedia(\"(display-mode: standalone) or (display-mode: window-controls-overlay)\"),t=ge.matchMedia(\"(display-mode: fullscreen)\");Kt=e.matches,po(ge,e,({matches:i})=>{Kt&&t.matches||(Kt=i)})}function vo(){return Kt}var st=\"en\",Gt=!1,Jt=!1,yt=!1,mo=!1,jr=!1,Gr=!1,So=!1,wo=!1,bo=!1,yo=!1,At,Ut=st,As=st,Co,Pe,Ae=globalThis,pe;typeof Ae.vscode<\"u\"&&typeof Ae.vscode.process<\"u\"?pe=Ae.vscode.process:typeof process<\"u\"&&typeof process?.versions?.node==\"string\"&&(pe=process);var Jr=typeof pe?.versions?.electron==\"string\",ko=Jr&&pe?.type===\"renderer\";if(typeof pe==\"object\"){Gt=pe.platform===\"win32\",Jt=pe.platform===\"darwin\",yt=pe.platform===\"linux\",mo=yt&&!!pe.env.SNAP&&!!pe.env.SNAP_REVISION,So=Jr,bo=!!pe.env.CI||!!pe.env.BUILD_ARTIFACTSTAGINGDIRECTORY,At=st,Ut=st;let e=pe.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);At=t.userLocale,As=t.osLocale,Ut=t.resolvedLanguage||st,Co=t.languagePack?.translationsConfigFile}catch{}jr=!0}else typeof navigator==\"object\"&&!ko?(Pe=navigator.userAgent,Gt=Pe.indexOf(\"Windows\")>=0,Jt=Pe.indexOf(\"Macintosh\")>=0,wo=(Pe.indexOf(\"Macintosh\")>=0||Pe.indexOf(\"iPad\")>=0||Pe.indexOf(\"iPhone\")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,yt=Pe.indexOf(\"Linux\")>=0,yo=Pe?.indexOf(\"Mobi\")>=0,Gr=!0,Ut=globalThis._VSCODE_NLS_LANGUAGE||st,At=navigator.language.toLowerCase(),As=At):console.error(\"Unable to resolve platform.\");var ui=0;Jt?ui=1:Gt?ui=3:yt&&(ui=2);var Zr=Gt,Be=Jt,xo=yt,fi=jr,Eo=Gr&&typeof Ae.importScripts==\"function\",ml=Eo?Ae.origin:void 0,Re=Pe,ze=Ut,Do;(e=>{function t(){return ze}e.value=t;function i(){return ze.length===2?ze===\"en\":ze.length>=3?ze[0]===\"e\"&&ze[1]===\"n\"&&ze[2]===\"-\":!1}e.isDefaultVariant=i;function s(){return ze===\"en\"}e.isDefault=s})(Do||={});var Bo=typeof Ae.postMessage==\"function\"&&!Ae.importScripts,Ro=(()=>{if(Bo){let e=[];Ae.addEventListener(\"message\",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let s=0,r=e.length;s<r;s++){let n=e[s];if(n.id===i.data.vscodeScheduleAsyncWork){e.splice(s,1),n.callback();return}}});let t=0;return i=>{let s=++t;e.push({id:s,callback:i}),Ae.postMessage({vscodeScheduleAsyncWork:s},\"*\")}}return e=>setTimeout(e)})(),Lo=!!(Re&&Re.indexOf(\"Chrome\")>=0),Sl=!!(Re&&Re.indexOf(\"Firefox\")>=0),wl=!!(!Lo&&Re&&Re.indexOf(\"Safari\")>=0),bl=!!(Re&&Re.indexOf(\"Edg/\")>=0),yl=!!(Re&&Re.indexOf(\"Android\")>=0),Fe=typeof navigator==\"object\"?navigator:{},Cl={clipboard:{writeText:fi||document.queryCommandSupported&&document.queryCommandSupported(\"copy\")||!!(Fe&&Fe.clipboard&&Fe.clipboard.writeText),readText:fi||!!(Fe&&Fe.clipboard&&Fe.clipboard.readText)},keyboard:fi||vo()?0:Fe.keyboard||Xr?1:2,touch:\"ontouchstart\"in ge||Fe.maxTouchPoints>0,pointerEvents:ge.PointerEvent&&(\"ontouchstart\"in ge||navigator.maxTouchPoints>0)},gs=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},pi=new gs,Os=new gs,Is=new gs,Mo=new Array(230),Qr;(e=>{function t(a){return pi.keyCodeToStr(a)}e.toString=t;function i(a){return pi.strToKeyCode(a)}e.fromString=i;function s(a){return Os.keyCodeToStr(a)}e.toUserSettingsUS=s;function r(a){return Is.keyCodeToStr(a)}e.toUserSettingsGeneral=r;function n(a){return Os.strToKeyCode(a)||Is.strToKeyCode(a)}e.fromUserSettings=n;function o(a){if(a>=98&&a<=113)return null;switch(a){case 16:return\"Up\";case 18:return\"Down\";case 15:return\"Left\";case 17:return\"Right\"}return pi.keyCodeToStr(a)}e.toElectronAccelerator=o})(Qr||={});var Po=class en{constructor(t,i,s,r,n){this.ctrlKey=t,this.shiftKey=i,this.altKey=s,this.metaKey=r,this.keyCode=n}equals(t){return t instanceof en&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?\"1\":\"0\",i=this.shiftKey?\"1\":\"0\",s=this.altKey?\"1\":\"0\",r=this.metaKey?\"1\":\"0\";return`K${t}${i}${s}${r}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new To([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},To=class{constructor(e){if(e.length===0)throw Kn(\"chords\");this.chords=e}getHashCode(){let e=\"\";for(let t=0,i=this.chords.length;t<i;t++)t!==0&&(e+=\";\"),e+=this.chords[t].getHashCode();return e}equals(e){if(e===null||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};function Ao(e){if(e.charCode){let i=String.fromCharCode(e.charCode).toUpperCase();return Qr.fromString(i)}let t=e.keyCode;if(t===3)return 7;if($i)switch(t){case 59:return 85;case 60:if(xo)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(Be)return 57;break}else if($t&&(Be&&t===93||!Be&&t===92))return 57;return Mo[t]||0}var Oo=Be?256:2048,Io=512,No=1024,Ho=Be?2048:256,Ki=class{constructor(e){this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=t.getModifierState?.(\"AltGraph\"),this.keyCode=Ao(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===5,this.altKey=this.altKey||this.keyCode===6,this.shiftKey=this.shiftKey||this.keyCode===4,this.metaKey=this.metaKey||this.keyCode===57,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=Oo),this.altKey&&(t|=Io),this.shiftKey&&(t|=No),this.metaKey&&(t|=Ho),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new Po(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},Ns=new WeakMap;function Wo(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,i=e.parent.location;if(t.origin!==\"null\"&&i.origin!==\"null\"&&t.origin!==i.origin)return null}catch{return null}return e.parent}var zo=class{static getSameOriginWindowChain(e){let t=Ns.get(e);if(!t){t=[],Ns.set(e,t);let i=e,s;do s=Wo(i),s?t.push({window:new WeakRef(i),iframeElement:i.frameElement||null}):t.push({window:new WeakRef(i),iframeElement:null}),i=s;while(i)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let i=0,s=0,r=this.getSameOriginWindowChain(e);for(let n of r){let o=n.window.deref();if(i+=o?.scrollY??0,s+=o?.scrollX??0,o===t||!n.iframeElement)break;let a=n.iframeElement.getBoundingClientRect();i+=a.top,s+=a.left}return{top:i,left:s}}},gt=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type===\"dblclick\"&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX==\"number\"?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let i=zo.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=i.left,this.posy-=i.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},Hs=class{constructor(e,t=0,i=0){this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=i,this.deltaX=t;let s=!1;if(ps){let r=navigator.userAgent.match(/Chrome\\/(\\d+)/);s=(r?parseInt(r[1]):123)<=122}if(e){let r=e,n=e,o=e.view?.devicePixelRatio||1;if(typeof r.wheelDeltaY<\"u\")s?this.deltaY=r.wheelDeltaY/(120*o):this.deltaY=r.wheelDeltaY/120;else if(typeof n.VERTICAL_AXIS<\"u\"&&n.axis===n.VERTICAL_AXIS)this.deltaY=-n.detail/3;else if(e.type===\"wheel\"){let a=e;a.deltaMode===a.DOM_DELTA_LINE?$i&&!Be?this.deltaY=-e.deltaY/3:this.deltaY=-e.deltaY:this.deltaY=-e.deltaY/40}if(typeof r.wheelDeltaX<\"u\")Xr&&Zr?this.deltaX=-(r.wheelDeltaX/120):s?this.deltaX=r.wheelDeltaX/(120*o):this.deltaX=r.wheelDeltaX/120;else if(typeof n.HORIZONTAL_AXIS<\"u\"&&n.axis===n.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type===\"wheel\"){let a=e;a.deltaMode===a.DOM_DELTA_LINE?$i&&!Be?this.deltaX=-e.deltaX/3:this.deltaX=-e.deltaX:this.deltaX=-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(s?this.deltaY=e.wheelDelta/(120*o):this.deltaY=e.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}},tn=Object.freeze(function(e,t){let i=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(i)}}}),Fo;(e=>{function t(i){return i===e.None||i===e.Cancelled||i instanceof $o?!0:!i||typeof i!=\"object\"?!1:typeof i.isCancellationRequested==\"boolean\"&&typeof i.onCancellationRequested==\"function\"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:oe.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:tn})})(Fo||={});var $o=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?tn:(this._emitter||(this._emitter=new v),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}};var vs=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e==\"function\"&&typeof t==\"number\"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new Ai(\"Calling 'cancelAndSet' on a disposed TimeoutTimer\");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Ai(\"Calling 'setIfNotSet' on a disposed TimeoutTimer\");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},Ko=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new Ai(\"Calling 'cancelAndSet' on a disposed IntervalTimer\");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=W(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Uo,gi;(function(){typeof globalThis.requestIdleCallback!=\"function\"||typeof globalThis.cancelIdleCallback!=\"function\"?gi=(e,t)=>{Ro(()=>{if(i)return;let s=Date.now()+15;t(Object.freeze({didTimeout:!0,timeRemaining(){return Math.max(0,s-Date.now())}}))});let i=!1;return{dispose(){i||(i=!0)}}}:gi=(e,t,i)=>{let s=e.requestIdleCallback(t,typeof i==\"number\"?{timeout:i}:void 0),r=!1;return{dispose(){r||(r=!0,e.cancelIdleCallback(s))}}},Uo=e=>gi(globalThis,e)})();var qo;(e=>{async function t(s){let r,n=await Promise.all(s.map(o=>o.then(a=>a,a=>{r||(r=a)})));if(typeof r<\"u\")throw r;return n}e.settled=t;function i(s){return new Promise(async(r,n)=>{try{await s(r,n)}catch(o){n(o)}})}e.withAsyncBody=i})(qo||={});var Ws=class me{static fromArray(t){return new me(i=>{i.emitMany(t)})}static fromPromise(t){return new me(async i=>{i.emitMany(await t)})}static fromPromises(t){return new me(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new me(async i=>{await Promise.all(t.map(async s=>{for await(let r of s)i.emitOne(r)}))})}constructor(t,i){this._state=0,this._results=[],this._error=null,this._onReturn=i,this._onStateChanged=new v,queueMicrotask(async()=>{let s={emitOne:r=>this.emitOne(r),emitMany:r=>this.emitMany(r),reject:r=>this.reject(r)};try{await Promise.resolve(t(s)),this.resolve()}catch(r){this.reject(r)}finally{s.emitOne=void 0,s.emitMany=void 0,s.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t<this._results.length)return{done:!1,value:this._results[t++]};if(this._state===1)return{done:!0,value:void 0};await oe.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,i){return new me(async s=>{for await(let r of t)s.emitOne(i(r))})}map(t){return me.map(this,t)}static filter(t,i){return new me(async s=>{for await(let r of t)i(r)&&s.emitOne(r)})}filter(t){return me.filter(this,t)}static coalesce(t){return me.filter(t,i=>!!i)}coalesce(){return me.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return me.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};Ws.EMPTY=Ws.fromArray([]);function Vo(e){return 55296<=e&&e<=56319}function zs(e){return 56320<=e&&e<=57343}function Yo(e,t){return(e-55296<<10)+(t-56320)+65536}function Xo(e){return ms(e,0)}function ms(e,t){switch(typeof e){case\"object\":return e===null?Te(349,t):Array.isArray(e)?Go(e,t):Jo(e,t);case\"string\":return sn(e,t);case\"boolean\":return jo(e,t);case\"number\":return Te(e,t);case\"undefined\":return Te(937,t);default:return Te(617,t)}}function Te(e,t){return(t<<5)-t+e|0}function jo(e,t){return Te(e?433:863,t)}function sn(e,t){t=Te(149417,t);for(let i=0,s=e.length;i<s;i++)t=Te(e.charCodeAt(i),t);return t}function Go(e,t){return t=Te(104579,t),e.reduce((i,s)=>ms(s,i),t)}function Jo(e,t){return t=Te(181387,t),Object.keys(e).sort().reduce((i,s)=>(i=sn(s,i),ms(e[s],i)),t)}function vi(e,t,i=32){let s=i-t,r=~((1<<s)-1);return(e<<t|(r&e)>>>s)>>>0}function Fs(e,t=0,i=e.byteLength,s=0){for(let r=0;r<i;r++)e[t+r]=s}function Zo(e,t,i=\"0\"){for(;e.length<t;)e=i+e;return e}function lt(e,t=32){return e instanceof ArrayBuffer?Array.from(new Uint8Array(e)).map(i=>i.toString(16).padStart(2,\"0\")).join(\"\"):Zo((e>>>0).toString(16),t/4)}var Qo=class rn{constructor(){this._h0=1732584193,this._h1=4023233417,this._h2=2562383102,this._h3=271733878,this._h4=3285377520,this._buff=new Uint8Array(67),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}update(t){let i=t.length;if(i===0)return;let s=this._buff,r=this._buffLen,n=this._leftoverHighSurrogate,o,a;for(n!==0?(o=n,a=-1,n=0):(o=t.charCodeAt(0),a=0);;){let l=o;if(Vo(o))if(a+1<i){let h=t.charCodeAt(a+1);zs(h)?(a++,l=Yo(o,h)):l=65533}else{n=o;break}else zs(o)&&(l=65533);if(r=this._push(s,r,l),a++,a<i)o=t.charCodeAt(a);else break}this._buffLen=r,this._leftoverHighSurrogate=n}_push(t,i,s){return s<128?t[i++]=s:s<2048?(t[i++]=192|(s&1984)>>>6,t[i++]=128|(s&63)>>>0):s<65536?(t[i++]=224|(s&61440)>>>12,t[i++]=128|(s&4032)>>>6,t[i++]=128|(s&63)>>>0):(t[i++]=240|(s&1835008)>>>18,t[i++]=128|(s&258048)>>>12,t[i++]=128|(s&4032)>>>6,t[i++]=128|(s&63)>>>0),i>=64&&(this._step(),i-=64,this._totalLen+=64,t[0]=t[64],t[1]=t[65],t[2]=t[66]),i}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,65533)),this._totalLen+=this._buffLen,this._wrapUp()),lt(this._h0)+lt(this._h1)+lt(this._h2)+lt(this._h3)+lt(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,Fs(this._buff,this._buffLen),this._buffLen>56&&(this._step(),Fs(this._buff));let t=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(t/4294967296),!1),this._buffDV.setUint32(60,t%4294967296,!1),this._step()}_step(){let t=rn._bigBlock32,i=this._buffDV;for(let c=0;c<64;c+=4)t.setUint32(c,i.getUint32(c,!1),!1);for(let c=64;c<320;c+=4)t.setUint32(c,vi(t.getUint32(c-12,!1)^t.getUint32(c-32,!1)^t.getUint32(c-56,!1)^t.getUint32(c-64,!1),1),!1);let s=this._h0,r=this._h1,n=this._h2,o=this._h3,a=this._h4,l,h,d;for(let c=0;c<80;c++)c<20?(l=r&n|~r&o,h=1518500249):c<40?(l=r^n^o,h=1859775393):c<60?(l=r&n|r&o|n&o,h=2400959708):(l=r^n^o,h=3395469782),d=vi(s,5)+l+a+h+t.getUint32(c*4,!1)&4294967295,a=o,o=n,n=vi(r,30),r=s,s=d;this._h0=this._h0+s&4294967295,this._h1=this._h1+r&4294967295,this._h2=this._h2+n&4294967295,this._h3=this._h3+o&4294967295,this._h4=this._h4+a&4294967295}};Qo._bigBlock32=new DataView(new ArrayBuffer(320));var{registerWindow:kl,getWindow:ye,getDocument:xl,getWindows:El,getWindowsCount:Dl,getWindowId:$s,getWindowById:Bl,hasWindow:Rl,onDidRegisterWindow:eh,onWillUnregisterWindow:Ll,onDidUnregisterWindow:Ml}=(function(){let e=new Map,t={window:ge,disposables:new Ve};e.set(ge.vscodeWindowId,t);let i=new v,s=new v,r=new v;function n(o,a){return(typeof o==\"number\"?e.get(o):void 0)??(a?t:void 0)}return{onDidRegisterWindow:i.event,onWillUnregisterWindow:r.event,onDidUnregisterWindow:s.event,registerWindow(o){if(e.has(o.vscodeWindowId))return R.None;let a=new Ve,l={window:o,disposables:a.add(new Ve)};return e.set(o.vscodeWindowId,l),a.add(W(()=>{e.delete(o.vscodeWindowId),s.fire(o)})),a.add(B(o,Q.BEFORE_UNLOAD,()=>{r.fire(o)})),i.fire(l),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(o){return o.vscodeWindowId},hasWindow(o){return e.has(o)},getWindowById:n,getWindow(o){let a=o;if(a?.ownerDocument?.defaultView)return a.ownerDocument.defaultView.window;let l=o;return l?.view?l.view.window:ge},getDocument(o){return ye(o).document}}})(),th=class{constructor(e,t,i,s){this._node=e,this._type=t,this._handler=i,this._options=s||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function B(e,t,i,s){return new th(e,t,i,s)}function ih(e,t){return function(i){return t(new gt(e,i))}}function sh(e){return function(t){return e(new Ki(t))}}var Ks=function(e,t,i,s){let r=i;return t===\"click\"||t===\"mousedown\"||t===\"contextmenu\"?r=ih(ye(e),i):(t===\"keydown\"||t===\"keypress\"||t===\"keyup\")&&(r=sh(i)),B(e,t,r,s)},rh,Zt,nh=class extends Ko{constructor(e){super(),this.defaultTarget=e&&ye(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},mi=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){Wt(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,s=new Map,r=n=>{i.set(n,!1);let o=e.get(n)??[];for(t.set(n,o),e.set(n,[]),s.set(n,!0);o.length>0;)o.sort(mi.sort),o.shift().execute();s.set(n,!1)};Zt=(n,o,a=0)=>{let l=$s(n),h=new mi(o,a),d=e.get(l);return d||(d=[],e.set(l,d)),d.push(h),i.get(l)||(i.set(l,!0),n.requestAnimationFrame(()=>r(l))),h},rh=(n,o,a)=>{let l=$s(n);if(s.get(l)){let h=new mi(o,a),d=t.get(l);return d||(d=[],t.set(l,d)),d.push(h),h}else return Zt(n,o,a)}})();var Us=class qt{constructor(t,i){this.width=t,this.height=i}with(t=this.width,i=this.height){return t!==this.width||i!==this.height?new qt(t,i):this}static is(t){return typeof t==\"object\"&&typeof t.height==\"number\"&&typeof t.width==\"number\"}static lift(t){return t instanceof qt?t:new qt(t.width,t.height)}static equals(t,i){return t===i?!0:!t||!i?!1:t.width===i.width&&t.height===i.height}};Us.None=new Us(0,0);function oh(e){let t=e.getBoundingClientRect(),i=ye(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var Pl=new class{constructor(){this.mutationObservers=new Map}observe(e,t,i){let s=this.mutationObservers.get(e);s||(s=new Map,this.mutationObservers.set(e,s));let r=Xo(i),n=s.get(r);if(n)n.users+=1;else{let o=new v,a=new MutationObserver(h=>o.fire(h));a.observe(e,i);let l=n={users:1,observer:a,onDidMutate:o.event};t.add(W(()=>{l.users-=1,l.users===0&&(o.dispose(),a.disconnect(),s?.delete(r),s?.size===0&&this.mutationObservers.delete(e))})),s.set(r,n)}return n.onDidMutate}},Q={CLICK:\"click\",AUXCLICK:\"auxclick\",DBLCLICK:\"dblclick\",MOUSE_UP:\"mouseup\",MOUSE_DOWN:\"mousedown\",MOUSE_OVER:\"mouseover\",MOUSE_MOVE:\"mousemove\",MOUSE_OUT:\"mouseout\",MOUSE_ENTER:\"mouseenter\",MOUSE_LEAVE:\"mouseleave\",MOUSE_WHEEL:\"wheel\",POINTER_UP:\"pointerup\",POINTER_DOWN:\"pointerdown\",POINTER_MOVE:\"pointermove\",POINTER_LEAVE:\"pointerleave\",CONTEXT_MENU:\"contextmenu\",WHEEL:\"wheel\",KEY_DOWN:\"keydown\",KEY_PRESS:\"keypress\",KEY_UP:\"keyup\",LOAD:\"load\",BEFORE_UNLOAD:\"beforeunload\",UNLOAD:\"unload\",PAGE_SHOW:\"pageshow\",PAGE_HIDE:\"pagehide\",PASTE:\"paste\",ABORT:\"abort\",ERROR:\"error\",RESIZE:\"resize\",SCROLL:\"scroll\",FULLSCREEN_CHANGE:\"fullscreenchange\",WK_FULLSCREEN_CHANGE:\"webkitfullscreenchange\",SELECT:\"select\",CHANGE:\"change\",SUBMIT:\"submit\",RESET:\"reset\",FOCUS:\"focus\",FOCUS_IN:\"focusin\",FOCUS_OUT:\"focusout\",BLUR:\"blur\",INPUT:\"input\",STORAGE:\"storage\",DRAG_START:\"dragstart\",DRAG:\"drag\",DRAG_ENTER:\"dragenter\",DRAG_LEAVE:\"dragleave\",DRAG_OVER:\"dragover\",DROP:\"drop\",DRAG_END:\"dragend\",ANIMATION_START:$t?\"webkitAnimationStart\":\"animationstart\",ANIMATION_END:$t?\"webkitAnimationEnd\":\"animationend\",ANIMATION_ITERATION:$t?\"webkitAnimationIteration\":\"animationiteration\"},hh=/([\\w\\-]+)?(#([\\w\\-]+))?((\\.([\\w\\-]+))*)/;function nn(e,t,i,...s){let r=hh.exec(t);if(!r)throw new Error(\"Bad use of emmet\");let n=r[1]||\"div\",o;return e!==\"http://www.w3.org/1999/xhtml\"?o=document.createElementNS(e,n):o=document.createElement(n),r[3]&&(o.id=r[3]),r[4]&&(o.className=r[4].replace(/\\./g,\" \").trim()),i&&Object.entries(i).forEach(([a,l])=>{typeof l>\"u\"||(/^on\\w+$/.test(a)?o[a]=l:a===\"selected\"?l&&o.setAttribute(a,\"true\"):o.setAttribute(a,l))}),o.append(...s),o}function ah(e,t,...i){return nn(\"http://www.w3.org/1999/xhtml\",e,t,...i)}ah.SVG=function(e,t,...i){return nn(\"http://www.w3.org/2000/svg\",e,t,...i)};var lh=class{constructor(e){this.domNode=e,this._maxWidth=\"\",this._width=\"\",this._height=\"\",this._top=\"\",this._left=\"\",this._bottom=\"\",this._right=\"\",this._paddingTop=\"\",this._paddingLeft=\"\",this._paddingBottom=\"\",this._paddingRight=\"\",this._fontFamily=\"\",this._fontWeight=\"\",this._fontSize=\"\",this._fontStyle=\"\",this._fontFeatureSettings=\"\",this._fontVariationSettings=\"\",this._textDecoration=\"\",this._lineHeight=\"\",this._letterSpacing=\"\",this._className=\"\",this._display=\"\",this._position=\"\",this._visibility=\"\",this._color=\"\",this._backgroundColor=\"\",this._layerHint=!1,this._contain=\"none\",this._boxShadow=\"\"}setMaxWidth(e){let t=_e(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=_e(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=_e(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=_e(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=_e(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=_e(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=_e(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=_e(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=_e(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=_e(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=_e(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=_e(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=_e(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=_e(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?\"translate3d(0px, 0px, 0px)\":\"\")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function _e(e){return typeof e==\"number\"?`${e}px`:e}function Ct(e){return new lh(e)}var on=class{constructor(){this._hooks=new Ve,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,s,r){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=r;let n=e;try{e.setPointerCapture(t),this._hooks.add(W(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{n=ye(e)}this._hooks.add(B(n,Q.POINTER_MOVE,o=>{if(o.buttons!==i){this.stopMonitoring(!0);return}o.preventDefault(),this._pointerMoveCallback(o)})),this._hooks.add(B(n,Q.POINTER_UP,o=>this.stopMonitoring(!0)))}};function ch(e,t,i){let s=null,r=null;if(typeof i.value==\"function\"?(s=\"value\",r=i.value,r.length!==0&&console.warn(\"Memoize should only be used in functions with zero parameters\")):typeof i.get==\"function\"&&(s=\"get\",r=i.get),!r)throw new Error(\"not supported\");let n=`$memoize$${t}`;i[s]=function(...o){return this.hasOwnProperty(n)||Object.defineProperty(this,n,{configurable:!1,enumerable:!1,writable:!1,value:r.apply(this,o)}),this[n]}}var De;(e=>(e.Tap=\"-xterm-gesturetap\",e.Change=\"-xterm-gesturechange\",e.Start=\"-xterm-gesturestart\",e.End=\"-xterm-gesturesend\",e.Contextmenu=\"-xterm-gesturecontextmenu\"))(De||={});var vt=class he extends R{constructor(){super(),this.dispatched=!1,this.targets=new Ms,this.ignoreTargets=new Ms,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(oe.runAndSubscribe(eh,({window:t,disposables:i})=>{i.add(B(t.document,\"touchstart\",s=>this.onTouchStart(s),{passive:!1})),i.add(B(t.document,\"touchend\",s=>this.onTouchEnd(t,s))),i.add(B(t.document,\"touchmove\",s=>this.onTouchMove(s),{passive:!1}))},{window:ge,disposables:this._store}))}static addTarget(t){if(!he.isTouchDevice())return R.None;he.INSTANCE||(he.INSTANCE=Ls(new he));let i=he.INSTANCE.targets.push(t);return W(i)}static ignoreTarget(t){if(!he.isTouchDevice())return R.None;he.INSTANCE||(he.INSTANCE=Ls(new he));let i=he.INSTANCE.ignoreTargets.push(t);return W(i)}static isTouchDevice(){return\"ontouchstart\"in ge||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let s=0,r=t.targetTouches.length;s<r;s++){let n=t.targetTouches.item(s);this.activeTouches[n.identifier]={id:n.identifier,initialTarget:n.target,initialTimeStamp:i,initialPageX:n.pageX,initialPageY:n.pageY,rollingTimestamps:[i],rollingPageX:[n.pageX],rollingPageY:[n.pageY]};let o=this.newGestureEvent(De.Start,n.target);o.pageX=n.pageX,o.pageY=n.pageY,this.dispatchEvent(o)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}onTouchEnd(t,i){let s=Date.now(),r=Object.keys(this.activeTouches).length;for(let n=0,o=i.changedTouches.length;n<o;n++){let a=i.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(a.identifier))){console.warn(\"move of an UNKNOWN touch\",a);continue}let l=this.activeTouches[a.identifier],h=Date.now()-l.initialTimeStamp;if(h<he.HOLD_DELAY&&Math.abs(l.initialPageX-ue(l.rollingPageX))<30&&Math.abs(l.initialPageY-ue(l.rollingPageY))<30){let d=this.newGestureEvent(De.Tap,l.initialTarget);d.pageX=ue(l.rollingPageX),d.pageY=ue(l.rollingPageY),this.dispatchEvent(d)}else if(h>=he.HOLD_DELAY&&Math.abs(l.initialPageX-ue(l.rollingPageX))<30&&Math.abs(l.initialPageY-ue(l.rollingPageY))<30){let d=this.newGestureEvent(De.Contextmenu,l.initialTarget);d.pageX=ue(l.rollingPageX),d.pageY=ue(l.rollingPageY),this.dispatchEvent(d)}else if(r===1){let d=ue(l.rollingPageX),c=ue(l.rollingPageY),u=ue(l.rollingTimestamps)-l.rollingTimestamps[0],f=d-l.rollingPageX[0],_=c-l.rollingPageY[0],p=[...this.targets].filter(C=>l.initialTarget instanceof Node&&C.contains(l.initialTarget));this.inertia(t,p,s,Math.abs(f)/u,f>0?1:-1,d,Math.abs(_)/u,_>0?1:-1,c)}this.dispatchEvent(this.newGestureEvent(De.End,l.initialTarget)),delete this.activeTouches[a.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,i){let s=document.createEvent(\"CustomEvent\");return s.initEvent(t,!1,!0),s.initialTarget=i,s.tapCount=0,s}dispatchEvent(t){if(t.type===De.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>he.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===De.Change||t.type===De.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let s of this.ignoreTargets)if(s.contains(t.initialTarget))return;let i=[];for(let s of this.targets)if(s.contains(t.initialTarget)){let r=0,n=t.initialTarget;for(;n&&n!==s;)r++,n=n.parentElement;i.push([r,s])}i.sort((s,r)=>s[0]-r[0]);for(let[s,r]of i)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,s,r,n,o,a,l,h){this.handle=Zt(t,()=>{let d=Date.now(),c=d-s,u=0,f=0,_=!0;r+=he.SCROLL_FRICTION*c,a+=he.SCROLL_FRICTION*c,r>0&&(_=!1,u=n*r*c),a>0&&(_=!1,f=l*a*c);let p=this.newGestureEvent(De.Change);p.translationX=u,p.translationY=f,i.forEach(C=>C.dispatchEvent(p)),_||this.inertia(t,i,d,r,n,o+u,a,l,h+f)})}onTouchMove(t){let i=Date.now();for(let s=0,r=t.changedTouches.length;s<r;s++){let n=t.changedTouches.item(s);if(!this.activeTouches.hasOwnProperty(String(n.identifier))){console.warn(\"end of an UNKNOWN touch\",n);continue}let o=this.activeTouches[n.identifier],a=this.newGestureEvent(De.Change,o.initialTarget);a.translationX=n.pageX-ue(o.rollingPageX),a.translationY=n.pageY-ue(o.rollingPageY),a.pageX=n.pageX,a.pageY=n.pageY,this.dispatchEvent(a),o.rollingPageX.length>3&&(o.rollingPageX.shift(),o.rollingPageY.shift(),o.rollingTimestamps.shift()),o.rollingPageX.push(n.pageX),o.rollingPageY.push(n.pageY),o.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};vt.SCROLL_FRICTION=-.005,vt.HOLD_DELAY=700,vt.CLEAR_TAP_COUNT_TIME=400,q([ch],vt,\"isTouchDevice\",1);var dh=vt,Ss=class extends R{onclick(e,t){this._register(B(e,Q.CLICK,i=>t(new gt(ye(e),i))))}onmousedown(e,t){this._register(B(e,Q.MOUSE_DOWN,i=>t(new gt(ye(e),i))))}onmouseover(e,t){this._register(B(e,Q.MOUSE_OVER,i=>t(new gt(ye(e),i))))}onmouseleave(e,t){this._register(B(e,Q.MOUSE_LEAVE,i=>t(new gt(ye(e),i))))}onkeydown(e,t){this._register(B(e,Q.KEY_DOWN,i=>t(new Ki(i))))}onkeyup(e,t){this._register(B(e,Q.KEY_UP,i=>t(new Ki(i))))}oninput(e,t){this._register(B(e,Q.INPUT,t))}onblur(e,t){this._register(B(e,Q.BLUR,t))}onfocus(e,t){this._register(B(e,Q.FOCUS,t))}onchange(e,t){this._register(B(e,Q.CHANGE,t))}ignoreGesture(e){return dh.ignoreTarget(e)}},qs=11,_h=class extends Ss{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement(\"div\"),this.bgDomNode.className=\"arrow-background\",this.bgDomNode.style.position=\"absolute\",this.bgDomNode.style.width=e.bgWidth+\"px\",this.bgDomNode.style.height=e.bgHeight+\"px\",typeof e.top<\"u\"&&(this.bgDomNode.style.top=\"0px\"),typeof e.left<\"u\"&&(this.bgDomNode.style.left=\"0px\"),typeof e.bottom<\"u\"&&(this.bgDomNode.style.bottom=\"0px\"),typeof e.right<\"u\"&&(this.bgDomNode.style.right=\"0px\"),this.domNode=document.createElement(\"div\"),this.domNode.className=e.className,this.domNode.style.position=\"absolute\",this.domNode.style.width=qs+\"px\",this.domNode.style.height=qs+\"px\",typeof e.top<\"u\"&&(this.domNode.style.top=e.top+\"px\"),typeof e.left<\"u\"&&(this.domNode.style.left=e.left+\"px\"),typeof e.bottom<\"u\"&&(this.domNode.style.bottom=e.bottom+\"px\"),typeof e.right<\"u\"&&(this.domNode.style.right=e.right+\"px\"),this._pointerMoveMonitor=this._register(new on),this._register(Ks(this.bgDomNode,Q.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(Ks(this.domNode,Q.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new nh),this._pointerdownScheduleRepeatTimer=this._register(new vs)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,ye(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},uh=class Ui{constructor(t,i,s,r,n,o,a){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,s=s|0,r=r|0,n=n|0,o=o|0,a=a|0),this.rawScrollLeft=r,this.rawScrollTop=a,i<0&&(i=0),r+i>s&&(r=s-i),r<0&&(r=0),n<0&&(n=0),a+n>o&&(a=o-n),a<0&&(a=0),this.width=i,this.scrollWidth=s,this.scrollLeft=r,this.height=n,this.scrollHeight=o,this.scrollTop=a}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,i){return new Ui(this._forceIntegerValues,typeof t.width<\"u\"?t.width:this.width,typeof t.scrollWidth<\"u\"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<\"u\"?t.height:this.height,typeof t.scrollHeight<\"u\"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new Ui(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<\"u\"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<\"u\"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,i){let s=this.width!==t.width,r=this.scrollWidth!==t.scrollWidth,n=this.scrollLeft!==t.scrollLeft,o=this.height!==t.height,a=this.scrollHeight!==t.scrollHeight,l=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:s,scrollWidthChanged:r,scrollLeftChanged:n,heightChanged:o,scrollHeightChanged:a,scrollTopChanged:l}}},fh=class extends R{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new v),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new uh(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let i=this._state.withScrollDimensions(e,t);this._setState(i,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>\"u\"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>\"u\"?this._smoothScrolling.to.scrollTop:e.scrollTop};let i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let s;t?s=new Ys(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):s=this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=s}else{let i=this._state.withScrollPosition(e);this._smoothScrolling=Ys.start(this._state,i,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},Vs=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function Si(e,t){let i=t-e;return function(s){return e+i*vh(s)}}function ph(e,t,i){return function(s){return s<i?e(s/i):t((s-i)/(1-i))}}var Ys=class qi{constructor(t,i,s,r){this.from=t,this.to=i,this.duration=r,this.startTime=s,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(t,i,s){if(Math.abs(t-i)>2.5*s){let r,n;return t<i?(r=t+.75*s,n=i-.75*s):(r=t-.75*s,n=i+.75*s),ph(Si(t,r),Si(n,i),.33)}return Si(t,i)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(t){this.to=t.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(t){let i=(t-this.startTime)/this.duration;if(i<1){let s=this.scrollLeft(i),r=this.scrollTop(i);return new Vs(s,r,!1)}return new Vs(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,i,s){return qi.start(t,i,s)}static start(t,i,s){s=s+10;let r=Date.now()-10;return new qi(t,i,r,s)}};function gh(e){return Math.pow(e,3)}function vh(e){return 1-gh(1-e)}var mh=class extends R{constructor(e,t,i){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=i,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new vs)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3?!0:this._rawShouldBeVisible}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){if(!this._isNeeded){this._hide(!1);return}this._shouldBeVisible?this._reveal():this._hide(!0)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?\" fade\":\"\")))}},Sh=140,hn=class extends Ss{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new mh(e.visibility,\"visible scrollbar \"+e.extraScrollbarClassName,\"invisible scrollbar \"+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new on),this._shouldRender=!0,this.domNode=Ct(document.createElement(\"div\")),this.domNode.setAttribute(\"role\",\"presentation\"),this.domNode.setAttribute(\"aria-hidden\",\"true\"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition(\"absolute\"),this._register(B(this.domNode.domNode,Q.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new _h(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=Ct(document.createElement(\"div\")),this.slider.setClassName(\"slider\"),this.slider.setPosition(\"absolute\"),this.slider.setTop(e),this.slider.setLeft(t),typeof i==\"number\"&&this.slider.setWidth(i),typeof s==\"number\"&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain(\"strict\"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(B(this.slider.domNode,Q.POINTER_DOWN,r=>{r.button===0&&(r.preventDefault(),this._sliderPointerDown(r))})),this.onclick(this.slider.domNode,r=>{r.leftButton&&r.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,i=t+this._scrollbarState.getSliderPosition(),s=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),r=this._sliderPointerPosition(e);i<=r&&r<=s?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&typeof e.offsetX==\"number\"&&typeof e.offsetY==\"number\")t=e.offsetX,i=e.offsetY;else{let r=oh(this.domNode.domNode);t=e.pageX-r.left,i=e.pageY-r.top}let s=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(s):this._scrollbarState.getDesiredScrollPositionFromOffset(s)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),s=this._scrollbarState.clone();this.slider.toggleClassName(\"active\",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,r=>{let n=this._sliderOrthogonalPointerPosition(r),o=Math.abs(n-i);if(Zr&&o>Sh){this._setDesiredScrollPositionNow(s.getScrollPosition());return}let a=this._sliderPointerPosition(r)-t;this._setDesiredScrollPositionNow(s.getDesiredScrollPositionFromDelta(a))},()=>{this.slider.toggleClassName(\"active\",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},an=class Vi{constructor(t,i,s,r,n,o){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(s),this._arrowSize=Math.round(t),this._visibleSize=r,this._scrollSize=n,this._scrollPosition=o,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new Vi(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,s,r,n){let o=Math.max(0,s-t),a=Math.max(0,o-2*i),l=r>0&&r>s;if(!l)return{computedAvailableSize:Math.round(o),computedIsNeeded:l,computedSliderSize:Math.round(a),computedSliderRatio:0,computedSliderPosition:0};let h=Math.round(Math.max(20,Math.floor(s*a/r))),d=(a-h)/(r-s),c=n*d;return{computedAvailableSize:Math.round(o),computedIsNeeded:l,computedSliderSize:Math.round(h),computedSliderRatio:d,computedSliderPosition:Math.round(c)}}_refreshComputedValues(){let t=Vi._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,s=this._scrollPosition;return i<this._computedSliderPosition?s-=this._visibleSize:s+=this._visibleSize,s}getDesiredScrollPositionFromDelta(t){if(!this._computedIsNeeded)return 0;let i=this._computedSliderPosition+t;return Math.round(i/this._computedSliderRatio)}},wh=class extends hn{constructor(e,t,i){let s=e.getScrollDimensions(),r=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new an(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,s.width,s.scrollWidth,r.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:\"horizontal\",scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw new Error(\"horizontalHasArrows is not supported in xterm.js\");this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===2?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},bh=class extends hn{constructor(e,t,i){let s=e.getScrollDimensions(),r=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new an(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,s.height,s.scrollHeight,r.scrollTop),visibility:t.vertical,extraScrollbarClassName:\"vertical\",scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw new Error(\"horizontalHasArrows is not supported in xterm.js\");this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},yh=500,Xs=50,js=!0,Ch=class{constructor(e,t,i){this.timestamp=e,this.deltaX=t,this.deltaY=i,this.score=0}},Yi=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let t=1,i=0,s=1,r=this._rear;do{let n=r===this._front?t:Math.pow(2,-s);if(t-=n,i+=this._memory[r].score*n,r===this._front)break;r=(this._capacity+r-1)%this._capacity,s++}while(!0);return i<=.5}acceptStandardWheelEvent(t){if(ps){let i=ye(t.browserEvent),s=go(i);this.accept(Date.now(),t.deltaX*s,t.deltaY*s)}else this.accept(Date.now(),t.deltaX,t.deltaY)}accept(t,i,s){let r=null,n=new Ch(t,i,s);this._front===-1&&this._rear===-1?(this._memory[0]=n,this._front=0,this._rear=0):(r=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=n),n.score=this._computeScore(n,r)}_computeScore(t,i){if(Math.abs(t.deltaX)>0&&Math.abs(t.deltaY)>0)return 1;let s=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(s+=.25),i){let r=Math.abs(t.deltaX),n=Math.abs(t.deltaY),o=Math.abs(i.deltaX),a=Math.abs(i.deltaY),l=Math.max(Math.min(r,o),1),h=Math.max(Math.min(n,a),1),d=Math.max(r,o),c=Math.max(n,a);d%l===0&&c%h===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};Yi.INSTANCE=new Yi;var kh=Yi,xh=class extends Ss{constructor(e,t,i){super(),this._onScroll=this._register(new v),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new v),this.onWillScroll=this._onWillScroll.event,this._options=Dh(t),this._scrollable=i,this._register(this._scrollable.onScroll(r=>{this._onWillScroll.fire(r),this._onDidScroll(r),this._onScroll.fire(r)}));let s={onMouseWheel:r=>this._onMouseWheel(r),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new bh(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new wh(this._scrollable,this._options,s)),this._domNode=document.createElement(\"div\"),this._domNode.className=\"xterm-scrollable-element \"+this._options.className,this._domNode.setAttribute(\"role\",\"presentation\"),this._domNode.style.position=\"relative\",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=Ct(document.createElement(\"div\")),this._leftShadowDomNode.setClassName(\"shadow\"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Ct(document.createElement(\"div\")),this._topShadowDomNode.setClassName(\"shadow\"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Ct(document.createElement(\"div\")),this._topLeftShadowDomNode.setClassName(\"shadow\"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,r=>this._onMouseOver(r)),this.onmouseleave(this._listenOnDomNode,r=>this._onMouseLeave(r)),this._hideTimeout=this._register(new vs),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=Qe(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Be&&(this._options.className+=\" mac\"),this._domNode.className=\"xterm-scrollable-element \"+this._options.className}updateOptions(e){typeof e.handleMouseWheel<\"u\"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<\"u\"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<\"u\"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<\"u\"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<\"u\"&&(this._options.horizontal=e.horizontal),typeof e.vertical<\"u\"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<\"u\"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<\"u\"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<\"u\"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new Hs(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=Qe(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new Hs(i))};this._mouseWheelToDispose.push(B(this._listenOnDomNode,Q.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=kh.INSTANCE;js&&t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,n=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&n+r===0?n=r=0:Math.abs(r)>=Math.abs(n)?n=0:r=0),this._options.flipAxes&&([r,n]=[n,r]);let o=!Be&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||o)&&!n&&(n=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(n=n*this._options.fastScrollSensitivity,r=r*this._options.fastScrollSensitivity);let a=this._scrollable.getFutureScrollPosition(),l={};if(r){let h=Xs*r,d=a.scrollTop-(h<0?Math.floor(h):Math.ceil(h));this._verticalScrollbar.writeScrollPosition(l,d)}if(n){let h=Xs*n,d=a.scrollLeft-(h<0?Math.floor(h):Math.ceil(h));this._horizontalScrollbar.writeScrollPosition(l,d)}l=this._scrollable.validateScrollPosition(l),(a.scrollLeft!==l.scrollLeft||a.scrollTop!==l.scrollTop)&&(js&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(l):this._scrollable.setScrollPositionNow(l),i=!0)}let s=i;!s&&this._options.alwaysConsumeMouseWheel&&(s=!0),!s&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(s=!0),s&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error(\"Please use `lazyRender` together with `renderNow`!\");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,i=e.scrollLeft>0,s=i?\" left\":\"\",r=t?\" top\":\"\",n=i||t?\" top-left-corner\":\"\";this._leftShadowDomNode.setClassName(`shadow${s}`),this._topShadowDomNode.setClassName(`shadow${r}`),this._topLeftShadowDomNode.setClassName(`shadow${n}${r}${s}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),yh)}},Eh=class extends xh{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function Dh(e){let t={lazyRender:typeof e.lazyRender<\"u\"?e.lazyRender:!1,className:typeof e.className<\"u\"?e.className:\"\",useShadows:typeof e.useShadows<\"u\"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<\"u\"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<\"u\"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<\"u\"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<\"u\"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<\"u\"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<\"u\"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<\"u\"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<\"u\"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<\"u\"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<\"u\"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<\"u\"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<\"u\"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<\"u\"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<\"u\"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<\"u\"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<\"u\"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<\"u\"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<\"u\"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<\"u\"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<\"u\"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<\"u\"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<\"u\"?e.verticalSliderSize:t.verticalScrollbarSize,Be&&(t.className+=\" mac\"),t}var Xi=class extends R{constructor(e,t,i,s,r,n,o,a){super(),this._bufferService=i,this._optionsService=o,this._renderService=a,this._onRequestScrollLines=this._register(new v),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let l=this._register(new fh({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:h=>Zt(s.window,h)}));this._register(this._optionsService.onSpecificOptionChange(\"smoothScrollDuration\",()=>{l.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new Eh(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},l)),this._register(this._optionsService.onMultipleOptionChange([\"scrollSensitivity\",\"fastScrollSensitivity\",\"overviewRuler\"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(r.onProtocolChange(h=>{this._scrollableElement.updateOptions({handleMouseWheel:!(h&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(oe.runAndSubscribe(n.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=n.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(W(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement(\"style\"),t.appendChild(this._styleElement),this._register(W(()=>this._styleElement.remove())),this._register(oe.runAndSubscribe(n.onChangeColors,()=>{this._styleElement.textContent=[\".xterm .xterm-scrollable-element > .scrollbar > .slider {\",` background: ${n.colors.scrollbarSliderBackground.css};`,\"}\",\".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {\",` background: ${n.colors.scrollbarSliderHoverBackground.css};`,\"}\",\".xterm .xterm-scrollable-element > .scrollbar > .slider.active {\",` background: ${n.colors.scrollbarSliderActiveBackground.css};`,\"}\"].join(`\r\n`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(h=>this._handleScroll(h)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};Xi=q([y(2,ce),y(3,Oe),y(4,Pr),y(5,nt),y(6,de),y(7,Ie)],Xi);var ji=class extends R{constructor(e,t,i,s,r){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=r,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(\"div\"),this._container.classList.add(\"xterm-decoration-container\"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(n=>this._removeDecoration(n))),this._register(W(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(\"div\");t.classList.add(\"xterm-decoration\"),t.classList.toggle(\"xterm-decoration-top-layer\",e?.options?.layer===\"top\"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display=\"none\"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=\"none\",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?\"none\":\"block\",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||\"left\")===\"right\"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:\"\":t.style.left=i?`${i*this._renderService.dimensions.css.cell.width}px`:\"\"}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};ji=q([y(1,ce),y(2,Oe),y(3,Rt),y(4,Ie)],ji);var Bh=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||\"full\"]&&t<=e.endBufferLine+this._linePadding[i||\"full\"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},xe={full:0,left:0,center:0,right:0},$e={full:0,left:0,center:0,right:0},ct={full:0,left:0,center:0,right:0},Qt=class extends R{constructor(e,t,i,s,r,n,o,a){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=s,this._renderService=r,this._optionsService=n,this._themeService=o,this._coreBrowserService=a,this._colorZoneStore=new Bh,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement(\"canvas\"),this._canvas.classList.add(\"xterm-decoration-overview-ruler\"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(W(()=>this._canvas?.remove()));let l=this._canvas.getContext(\"2d\");if(l)this._ctx=l;else throw new Error(\"Ctx cannot be null\");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?\"none\":\"block\"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange(\"overviewRuler\",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);$e.full=this._canvas.width,$e.left=e,$e.center=t,$e.right=e,this._refreshDrawHeightConstants(),ct.full=1,ct.left=1,ct.center=1+$e.left,ct.right=1+$e.left+$e.center}_refreshDrawHeightConstants(){xe.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);xe.left=t,xe.center=t,xe.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*xe.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*xe.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*xe.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*xe.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!==\"full\"&&this._renderColorZone(t);for(let t of e)t.position===\"full\"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(ct[e.position||\"full\"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-xe[e.position||\"full\"]/2),$e[e.position||\"full\"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+xe[e.position||\"full\"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};Qt=q([y(2,ce),y(3,Rt),y(4,Ie),y(5,de),y(6,nt),y(7,Oe)],Qt);var g;(e=>(e.NUL=\"\\0\",e.SOH=\"\u0001\",e.STX=\"\u0002\",e.ETX=\"\u0003\",e.EOT=\"\u0004\",e.ENQ=\"\u0005\",e.ACK=\"\u0006\",e.BEL=\"\\x07\",e.BS=\"\\b\",e.HT=\"\t\",e.LF=`\r\n`,e.VT=\"\\v\",e.FF=\"\\f\",e.CR=\"\\r\",e.SO=\"\u000e\",e.SI=\"\u000f\",e.DLE=\"\u0010\",e.DC1=\"\u0011\",e.DC2=\"\u0012\",e.DC3=\"\u0013\",e.DC4=\"\u0014\",e.NAK=\"\u0015\",e.SYN=\"\u0016\",e.ETB=\"\u0017\",e.CAN=\"\u0018\",e.EM=\"\u0019\",e.SUB=\"\u001a\",e.ESC=\"\\x1B\",e.FS=\"\u001c\",e.GS=\"\u001d\",e.RS=\"\u001e\",e.US=\"\u001f\",e.SP=\" \",e.DEL=\"\\x7F\"))(g||={});var Vt;(e=>(e.PAD=\"\\x80\",e.HOP=\"\\x81\",e.BPH=\"\\x82\",e.NBH=\"\\x83\",e.IND=\"\\x84\",e.NEL=\"\\x85\",e.SSA=\"\\x86\",e.ESA=\"\\x87\",e.HTS=\"\\x88\",e.HTJ=\"\\x89\",e.VTS=\"\\x8A\",e.PLD=\"\\x8B\",e.PLU=\"\\x8C\",e.RI=\"\\x8D\",e.SS2=\"\\x8E\",e.SS3=\"\\x8F\",e.DCS=\"\\x90\",e.PU1=\"\\x91\",e.PU2=\"\\x92\",e.STS=\"\\x93\",e.CCH=\"\\x94\",e.MW=\"\\x95\",e.SPA=\"\\x96\",e.EPA=\"\\x97\",e.SOS=\"\\x98\",e.SGCI=\"\\x99\",e.SCI=\"\\x9A\",e.CSI=\"\\x9B\",e.ST=\"\\x9C\",e.OSC=\"\\x9D\",e.PM=\"\\x9E\",e.APC=\"\\x9F\"))(Vt||={});var ln;(e=>e.ST=`${g.ESC}\\\\`)(ln||={});var Gi=class{constructor(e,t,i,s,r,n){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=r,this._renderService=n,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=\"\"}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=\"\",this._dataAlreadySent=\"\",this._compositionView.classList.add(\"active\")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove(\"active\"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,\"\");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.length<e.length?this._coreService.triggerDataEvent(`${g.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let t=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),i=this._renderService.dimensions.css.cell.height,s=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=t*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+\"px\",this._compositionView.style.top=s+\"px\",this._compositionView.style.height=i+\"px\",this._compositionView.style.lineHeight=i+\"px\",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+\"px\";let n=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+\"px\",this._textarea.style.top=s+\"px\",this._textarea.style.width=Math.max(n.width,1)+\"px\",this._textarea.style.height=Math.max(n.height,1)+\"px\",this._textarea.style.lineHeight=n.height+\"px\"}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};Gi=q([y(2,ce),y(3,de),y(4,tt),y(5,Ie)],Gi);var ee=0,te=0,ie=0,U=0,Gs={css:\"#00000000\",rgba:0},X;(e=>{function t(r,n,o,a){return a!==void 0?`#${Xe(r)}${Xe(n)}${Xe(o)}${Xe(a)}`:`#${Xe(r)}${Xe(n)}${Xe(o)}`}e.toCss=t;function i(r,n,o,a=255){return(r<<24|n<<16|o<<8|a)>>>0}e.toRgba=i;function s(r,n,o,a){return{css:e.toCss(r,n,o,a),rgba:e.toRgba(r,n,o,a)}}e.toColor=s})(X||={});var H;(e=>{function t(l,h){if(U=(h.rgba&255)/255,U===1)return{css:h.css,rgba:h.rgba};let d=h.rgba>>24&255,c=h.rgba>>16&255,u=h.rgba>>8&255,f=l.rgba>>24&255,_=l.rgba>>16&255,p=l.rgba>>8&255;ee=f+Math.round((d-f)*U),te=_+Math.round((c-_)*U),ie=p+Math.round((u-p)*U);let C=X.toCss(ee,te,ie),D=X.toRgba(ee,te,ie);return{css:C,rgba:D}}e.blend=t;function i(l){return(l.rgba&255)===255}e.isOpaque=i;function s(l,h,d){let c=Yt.ensureContrastRatio(l.rgba,h.rgba,d);if(c)return X.toColor(c>>24&255,c>>16&255,c>>8&255)}e.ensureContrastRatio=s;function r(l){let h=(l.rgba|255)>>>0;return[ee,te,ie]=Yt.toChannels(h),{css:X.toCss(ee,te,ie),rgba:h}}e.opaque=r;function n(l,h){return U=Math.round(h*255),[ee,te,ie]=Yt.toChannels(l.rgba),{css:X.toCss(ee,te,ie,U),rgba:X.toRgba(ee,te,ie,U)}}e.opacity=n;function o(l,h){return U=l.rgba&255,n(l,U*h/255)}e.multiplyOpacity=o;function a(l){return[l.rgba>>24&255,l.rgba>>16&255,l.rgba>>8&255]}e.toColorRGB=a})(H||={});var K;(e=>{let t,i;try{let r=document.createElement(\"canvas\");r.width=1,r.height=1;let n=r.getContext(\"2d\",{willReadFrequently:!0});n&&(t=n,t.globalCompositeOperation=\"copy\",i=t.createLinearGradient(0,0,1,1))}catch{}function s(r){if(r.match(/#[\\da-f]{3,8}/i))switch(r.length){case 4:return ee=parseInt(r.slice(1,2).repeat(2),16),te=parseInt(r.slice(2,3).repeat(2),16),ie=parseInt(r.slice(3,4).repeat(2),16),X.toColor(ee,te,ie);case 5:return ee=parseInt(r.slice(1,2).repeat(2),16),te=parseInt(r.slice(2,3).repeat(2),16),ie=parseInt(r.slice(3,4).repeat(2),16),U=parseInt(r.slice(4,5).repeat(2),16),X.toColor(ee,te,ie,U);case 7:return{css:r,rgba:(parseInt(r.slice(1),16)<<8|255)>>>0};case 9:return{css:r,rgba:parseInt(r.slice(1),16)>>>0}}let n=r.match(/rgba?\\(\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*(,\\s*(0|1|\\d?\\.(\\d+))\\s*)?\\)/);if(n)return ee=parseInt(n[1]),te=parseInt(n[2]),ie=parseInt(n[3]),U=Math.round((n[5]===void 0?1:parseFloat(n[5]))*255),X.toColor(ee,te,ie,U);if(!t||!i)throw new Error(\"css.toColor: Unsupported css format\");if(t.fillStyle=i,t.fillStyle=r,typeof t.fillStyle!=\"string\")throw new Error(\"css.toColor: Unsupported css format\");if(t.fillRect(0,0,1,1),[ee,te,ie,U]=t.getImageData(0,0,1,1).data,U!==255)throw new Error(\"css.toColor: Unsupported css format\");return{rgba:X.toRgba(ee,te,ie,U),css:r}}e.toColor=s})(K||={});var le;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,r,n){let o=s/255,a=r/255,l=n/255,h=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4),d=a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4),c=l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4);return h*.2126+d*.7152+c*.0722}e.relativeLuminance2=i})(le||={});var Yt;(e=>{function t(o,a){if(U=(a&255)/255,U===1)return a;let l=a>>24&255,h=a>>16&255,d=a>>8&255,c=o>>24&255,u=o>>16&255,f=o>>8&255;return ee=c+Math.round((l-c)*U),te=u+Math.round((h-u)*U),ie=f+Math.round((d-f)*U),X.toRgba(ee,te,ie)}e.blend=t;function i(o,a,l){let h=le.relativeLuminance(o>>8),d=le.relativeLuminance(a>>8);if(Me(h,d)<l){if(d<h){let f=s(o,a,l),_=Me(h,le.relativeLuminance(f>>8));if(_<l){let p=r(o,a,l),C=Me(h,le.relativeLuminance(p>>8));return _>C?f:p}return f}let c=r(o,a,l),u=Me(h,le.relativeLuminance(c>>8));if(u<l){let f=s(o,a,l),_=Me(h,le.relativeLuminance(f>>8));return u>_?c:f}return c}}e.ensureContrastRatio=i;function s(o,a,l){let h=o>>24&255,d=o>>16&255,c=o>>8&255,u=a>>24&255,f=a>>16&255,_=a>>8&255,p=Me(le.relativeLuminance2(u,f,_),le.relativeLuminance2(h,d,c));for(;p<l&&(u>0||f>0||_>0);)u-=Math.max(0,Math.ceil(u*.1)),f-=Math.max(0,Math.ceil(f*.1)),_-=Math.max(0,Math.ceil(_*.1)),p=Me(le.relativeLuminance2(u,f,_),le.relativeLuminance2(h,d,c));return(u<<24|f<<16|_<<8|255)>>>0}e.reduceLuminance=s;function r(o,a,l){let h=o>>24&255,d=o>>16&255,c=o>>8&255,u=a>>24&255,f=a>>16&255,_=a>>8&255,p=Me(le.relativeLuminance2(u,f,_),le.relativeLuminance2(h,d,c));for(;p<l&&(u<255||f<255||_<255);)u=Math.min(255,u+Math.ceil((255-u)*.1)),f=Math.min(255,f+Math.ceil((255-f)*.1)),_=Math.min(255,_+Math.ceil((255-_)*.1)),p=Me(le.relativeLuminance2(u,f,_),le.relativeLuminance2(h,d,c));return(u<<24|f<<16|_<<8|255)>>>0}e.increaseLuminance=r;function n(o){return[o>>24&255,o>>16&255,o>>8&255,o&255]}e.toChannels=n})(Yt||={});function Xe(e){let t=e.toString(16);return t.length<2?\"0\"+t:t}function Me(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var Rh=class extends Bt{constructor(e,t,i){super(),this.content=0,this.combinedData=\"\",this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=i}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw new Error(\"not implemented\")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},ei=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new we}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let i=[],s=t.translateToString(!0),r=0,n=0,o=0,a=t.getFg(0),l=t.getBg(0);for(let h=0;h<t.getTrimmedLength();h++)if(t.loadCell(h,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==a||this._workCell.bg!==l){if(h-r>1){let d=this._getJoinedRanges(s,o,n,t,r);for(let c=0;c<d.length;c++)i.push(d[c])}r=h,o=n,a=this._workCell.fg,l=this._workCell.bg}n+=this._workCell.getChars().length||qe.length}if(this._bufferService.cols-r>1){let h=this._getJoinedRanges(s,o,n,t,r);for(let d=0;d<h.length;d++)i.push(h[d])}return i}_getJoinedRanges(e,t,i,s,r){let n=e.substring(t,i),o=[];try{o=this._characterJoiners[0].handler(n)}catch(a){console.error(a)}for(let a=1;a<this._characterJoiners.length;a++)try{let l=this._characterJoiners[a].handler(n);for(let h=0;h<l.length;h++)ei._mergeRanges(o,l[h])}catch(l){console.error(l)}return this._stringRangesToCellRanges(o,s,r),o}_stringRangesToCellRanges(e,t,i){let s=0,r=!1,n=0,o=e[s];if(o){for(let a=i;a<this._bufferService.cols;a++){let l=t.getWidth(a),h=t.getString(a).length||qe.length;if(l!==0){if(!r&&o[0]<=n&&(o[0]=a,r=!0),o[1]<=n){if(o[1]=a,o=e[++s],!o)break;o[0]<=n?(o[0]=a,r=!0):r=!1}n+=h}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let i=!1;for(let s=0;s<e.length;s++){let r=e[s];if(i){if(t[1]<=r[0])return e[s-1][1]=t[1],e;if(t[1]<=r[1])return e[s-1][1]=Math.max(t[1],r[1]),e.splice(s,1),e;e.splice(s,1),s--}else{if(t[1]<=r[0])return e.splice(s,0,t),e;if(t[1]<=r[1])return r[0]=Math.min(t[0],r[0]),e;t[0]<r[1]&&(r[0]=Math.min(t[0],r[0]),i=!0);continue}}return i?e[e.length-1][1]=t[1]:e.push(t),e}};ei=q([y(0,ce)],ei);function Lh(e){return 57508<=e&&e<=57558}function Mh(e){return 9472<=e&&e<=9631}function Ph(e){return Lh(e)||Mh(e)}function Th(){return{css:{canvas:Ot(),cell:Ot()},device:{canvas:Ot(),cell:Ot(),char:{width:0,height:0,left:0,top:0}}}}function Ot(){return{width:0,height:0}}var Ji=class{constructor(e,t,i,s,r,n,o){this._document=e,this._characterJoinerService=t,this._optionsService=i,this._coreBrowserService=s,this._coreService=r,this._decorationService=n,this._themeService=o,this._workCell=new we,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,i){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=i}createRow(e,t,i,s,r,n,o,a,l,h,d){let c=[],u=this._characterJoinerService.getJoinedCharacters(t),f=this._themeService.colors,_=e.getNoBgTrimmedLength();i&&_<n+1&&(_=n+1);let p,C=0,D=\"\",I=0,M=0,E=0,T=0,A=!1,re=0,be=!1,Ce=0,Pt=0,z=[],ci=h!==-1&&d!==-1;for(let w=0;w<_;w++){e.loadCell(w,this._workCell);let m=this._workCell.getWidth();if(m===0)continue;let k=!1,b=w>=Pt,x=w,S=this._workCell;if(u.length>0&&w===u[0][0]&&b){let O=u.shift(),di=this._isCellInSelection(O[0],t);for(I=O[0]+1;I<O[1];I++)b&&=di===this._isCellInSelection(I,t);b&&=!i||n<O[0]||n>=O[1],b?(k=!0,S=new Rh(this._workCell,e.translateToString(!0,O[0],O[1]),O[1]-O[0]),x=O[1]-1,m=S.getWidth()):Pt=O[1]}let P=this._isCellInSelection(w,t),F=i&&w===n,ne=ci&&w>=h&&w<=d,ke=!1;this._decorationService.forEachDecorationAtCell(w,t,void 0,O=>{ke=!0});let Le=S.getChars()||qe;if(Le===\" \"&&(S.isUnderline()||S.isOverline())&&(Le=\"\\xA0\"),Ce=m*a-l.get(Le,S.isBold(),S.isItalic()),!p)p=this._document.createElement(\"span\");else if(C&&(P&&be||!P&&!be&&S.bg===M)&&(P&&be&&f.selectionForeground||S.fg===E)&&S.extended.ext===T&&ne===A&&Ce===re&&!F&&!k&&!ke&&b){S.isInvisible()?D+=qe:D+=Le,C++;continue}else C&&(p.textContent=D),p=this._document.createElement(\"span\"),C=0,D=\"\";if(M=S.bg,E=S.fg,T=S.extended.ext,A=ne,re=Ce,be=P,k&&n>=w&&n<=x&&(n=w),!this._coreService.isCursorHidden&&F&&this._coreService.isCursorInitialized){if(z.push(\"xterm-cursor\"),this._coreBrowserService.isFocused)o&&z.push(\"xterm-cursor-blink\"),z.push(s===\"bar\"?\"xterm-cursor-bar\":s===\"underline\"?\"xterm-cursor-underline\":\"xterm-cursor-block\");else if(r)switch(r){case\"outline\":z.push(\"xterm-cursor-outline\");break;case\"block\":z.push(\"xterm-cursor-block\");break;case\"bar\":z.push(\"xterm-cursor-bar\");break;case\"underline\":z.push(\"xterm-cursor-underline\");break;default:break}}if(S.isBold()&&z.push(\"xterm-bold\"),S.isItalic()&&z.push(\"xterm-italic\"),S.isDim()&&z.push(\"xterm-dim\"),S.isInvisible()?D=qe:D=S.getChars()||qe,S.isUnderline()&&(z.push(`xterm-underline-${S.extended.underlineStyle}`),D===\" \"&&(D=\"\\xA0\"),!S.isUnderlineColorDefault()))if(S.isUnderlineColorRGB())p.style.textDecorationColor=`rgb(${Bt.toColorRGB(S.getUnderlineColor()).join(\",\")})`;else{let O=S.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&S.isBold()&&O<8&&(O+=8),p.style.textDecorationColor=f.ansi[O].css}S.isOverline()&&(z.push(\"xterm-overline\"),D===\" \"&&(D=\"\\xA0\")),S.isStrikethrough()&&z.push(\"xterm-strikethrough\"),ne&&(p.style.textDecoration=\"underline\");let Z=S.getFgColor(),Ne=S.getFgColorMode(),ae=S.getBgColor(),Ye=S.getBgColorMode(),ht=!!S.isInverse();if(ht){let O=Z;Z=ae,ae=O;let di=Ne;Ne=Ye,Ye=di}let He,Tt,at=!1;this._decorationService.forEachDecorationAtCell(w,t,void 0,O=>{O.options.layer!==\"top\"&&at||(O.backgroundColorRGB&&(Ye=50331648,ae=O.backgroundColorRGB.rgba>>8&16777215,He=O.backgroundColorRGB),O.foregroundColorRGB&&(Ne=50331648,Z=O.foregroundColorRGB.rgba>>8&16777215,Tt=O.foregroundColorRGB),at=O.options.layer===\"top\")}),!at&&P&&(He=this._coreBrowserService.isFocused?f.selectionBackgroundOpaque:f.selectionInactiveBackgroundOpaque,ae=He.rgba>>8&16777215,Ye=50331648,at=!0,f.selectionForeground&&(Ne=50331648,Z=f.selectionForeground.rgba>>8&16777215,Tt=f.selectionForeground)),at&&z.push(\"xterm-decoration-top\");let We;switch(Ye){case 16777216:case 33554432:We=f.ansi[ae],z.push(`xterm-bg-${ae}`);break;case 50331648:We=X.toColor(ae>>16,ae>>8&255,ae&255),this._addStyle(p,`background-color:#${Js((ae>>>0).toString(16),\"0\",6)}`);break;default:ht?(We=f.foreground,z.push(\"xterm-bg-257\")):We=f.background}switch(He||S.isDim()&&(He=H.multiplyOpacity(We,.5)),Ne){case 16777216:case 33554432:S.isBold()&&Z<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(Z+=8),this._applyMinimumContrast(p,We,f.ansi[Z],S,He,void 0)||z.push(`xterm-fg-${Z}`);break;case 50331648:let O=X.toColor(Z>>16&255,Z>>8&255,Z&255);this._applyMinimumContrast(p,We,O,S,He,Tt)||this._addStyle(p,`color:#${Js(Z.toString(16),\"0\",6)}`);break;default:this._applyMinimumContrast(p,We,f.foreground,S,He,Tt)||ht&&z.push(\"xterm-fg-257\")}z.length&&(p.className=z.join(\" \"),z.length=0),!F&&!k&&!ke&&b?C++:p.textContent=D,Ce!==this.defaultSpacing&&(p.style.letterSpacing=`${Ce}px`),c.push(p),w=x}return p&&C&&(p.textContent=D),c}_applyMinimumContrast(e,t,i,s,r,n){if(this._optionsService.rawOptions.minimumContrastRatio===1||Ph(s.getCode()))return!1;let o=this._getContrastCache(s),a;if(!r&&!n&&(a=o.getColor(t.rgba,i.rgba)),a===void 0){let l=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);a=H.ensureContrastRatio(r||t,n||i,l),o.setColor((r||t).rgba,(n||i).rgba,a??null)}return a?(this._addStyle(e,`color:${a.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute(\"style\",`${e.getAttribute(\"style\")||\"\"}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,s=this._selectionEnd;return!i||!s?!1:this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e<s[0]&&t<=s[1]:e<i[0]&&t>=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t<s[1]||i[1]===s[1]&&t===i[1]&&e>=i[0]&&e<s[0]||i[1]<s[1]&&t===s[1]&&e<s[0]||i[1]<s[1]&&t===i[1]&&e>=i[0]}};Ji=q([y(1,Or),y(2,de),y(3,Oe),y(4,tt),y(5,Rt),y(6,nt)],Ji);function Js(e,t,i){for(;e.length<i;)e=t+e;return e}var Ah=class{constructor(e,t){this._flat=new Float32Array(256),this._font=\"\",this._fontSize=0,this._weight=\"normal\",this._weightBold=\"bold\",this._measureElements=[],this._container=e.createElement(\"div\"),this._container.classList.add(\"xterm-width-cache-measure-container\"),this._container.setAttribute(\"aria-hidden\",\"true\"),this._container.style.whiteSpace=\"pre\",this._container.style.fontKerning=\"none\";let i=e.createElement(\"span\");i.classList.add(\"xterm-char-measure-element\");let s=e.createElement(\"span\");s.classList.add(\"xterm-char-measure-element\"),s.style.fontWeight=\"bold\";let r=e.createElement(\"span\");r.classList.add(\"xterm-char-measure-element\"),r.style.fontStyle=\"italic\";let n=e.createElement(\"span\");n.classList.add(\"xterm-char-measure-element\"),n.style.fontWeight=\"bold\",n.style.fontStyle=\"italic\",this._measureElements=[i,s,r,n],this._container.appendChild(i),this._container.appendChild(s),this._container.appendChild(r),this._container.appendChild(n),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,i,s){e===this._font&&t===this._fontSize&&i===this._weight&&s===this._weightBold||(this._font=e,this._fontSize=t,this._weight=i,this._weightBold=s,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${i}`,this._measureElements[1].style.fontWeight=`${s}`,this._measureElements[2].style.fontWeight=`${i}`,this._measureElements[3].style.fontWeight=`${s}`,this.clear())}get(e,t,i){let s=0;if(!t&&!i&&e.length===1&&(s=e.charCodeAt(0))<256){if(this._flat[s]!==-9999)return this._flat[s];let o=this._measure(e,0);return o>0&&(this._flat[s]=o),o}let r=e;t&&(r+=\"B\"),i&&(r+=\"I\");let n=this._holey.get(r);if(n===void 0){let o=0;t&&(o|=1),i&&(o|=2),n=this._measure(e,o),n>0&&this._holey.set(r,n)}return n}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},Oh=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,i,s=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1]){this.clear();return}let r=e.buffers.active.ydisp,n=t[1]-r,o=i[1]-r,a=Math.max(n,0),l=Math.min(o,e.rows-1);if(a>=e.rows||l<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=n,this.viewportEndRow=o,this.viewportCappedStartRow=a,this.viewportCappedEndRow=l,this.startCol=t[0],this.endCol=i[0]}isCellSelected(e,t,i){return this.hasSelection?(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t<this.endCol&&i<=this.viewportCappedEndRow:t<this.startCol&&i>=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol):!1}};function Ih(){return new Oh}var wi=\"xterm-dom-renderer-owner-\",ve=\"xterm-rows\",It=\"xterm-fg-\",Zs=\"xterm-bg-\",dt=\"xterm-focus\",Nt=\"xterm-selection\",Nh=1,Zi=class extends R{constructor(e,t,i,s,r,n,o,a,l,h,d,c,u,f){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=s,this._viewportElement=r,this._helperContainer=n,this._linkifier2=o,this._charSizeService=l,this._optionsService=h,this._bufferService=d,this._coreService=c,this._coreBrowserService=u,this._themeService=f,this._terminalClass=Nh++,this._rowElements=[],this._selectionRenderModel=Ih(),this.onRequestRedraw=this._register(new v).event,this._rowContainer=this._document.createElement(\"div\"),this._rowContainer.classList.add(ve),this._rowContainer.style.lineHeight=\"normal\",this._rowContainer.setAttribute(\"aria-hidden\",\"true\"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement(\"div\"),this._selectionContainer.classList.add(Nt),this._selectionContainer.setAttribute(\"aria-hidden\",\"true\"),this.dimensions=Th(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(_=>this._injectCss(_))),this._injectCss(this._themeService.colors),this._rowFactory=a.createInstance(Ji,document),this._element.classList.add(wi+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(_=>this._handleLinkHover(_))),this._register(this._linkifier2.onHideLinkUnderline(_=>this._handleLinkLeave(_))),this._register(W(()=>{this._element.classList.remove(wi+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new Ah(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow=\"hidden\";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(\"style\"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${ve} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement(\"style\"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${ve} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${ve} .xterm-dim { color: ${H.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let i=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,r=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% { box-shadow: none; }}`,t+=`@keyframes ${r} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${ve}.${dt} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${ve}.${dt} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${ve}.${dt} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${ve} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${ve} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${ve} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${ve} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${ve} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Nt} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Nt} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Nt} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,o]of e.ansi.entries())t+=`${this._terminalSelector} .${It}${n} { color: ${o.css}; }${this._terminalSelector} .${It}${n}.xterm-dim { color: ${H.multiplyOpacity(o,.5).css}; }${this._terminalSelector} .${Zs}${n} { background-color: ${o.css}; }`;t+=`${this._terminalSelector} .${It}257 { color: ${H.opaque(e.background).css}; }${this._terminalSelector} .${It}257.xterm-dim { color: ${H.multiplyOpacity(H.opaque(e.background),.5).css}; }${this._terminalSelector} .${Zs}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get(\"W\",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let s=this._document.createElement(\"div\");this._rowContainer.appendChild(s),this._rowElements.push(s)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(dt),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(dt),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let s=this._selectionRenderModel.viewportStartRow,r=this._selectionRenderModel.viewportEndRow,n=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,a=this._document.createDocumentFragment();if(i){let l=e[0]>t[0];a.appendChild(this._createSelectionElement(n,l?t[0]:e[0],l?e[0]:t[0],o-n+1))}else{let l=s===n?e[0]:0,h=n===r?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(n,l,h));let d=o-n-1;if(a.appendChild(this._createSelectionElement(n+1,0,this._bufferService.cols,d)),n!==o){let c=r===o?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(o,0,c))}}this._selectionContainer.appendChild(a)}_createSelectionElement(e,t,i,s=1){let r=this._document.createElement(\"div\"),n=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(i-t);return n+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-n),r.style.height=`${s*this.dimensions.css.cell.height}px`,r.style.top=`${e*this.dimensions.css.cell.height}px`,r.style.left=`${n}px`,r.style.width=`${o}px`,r}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let i=this._bufferService.buffer,s=i.ybase+i.y,r=Math.min(i.x,this._bufferService.cols-1),n=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,a=this._optionsService.rawOptions.cursorInactiveStyle;for(let l=e;l<=t;l++){let h=l+i.ydisp,d=this._rowElements[l],c=i.lines.get(h);if(!d||!c)break;d.replaceChildren(...this._rowFactory.createRow(c,h,h===s,o,a,r,n,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${wi}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,r,n){i<0&&(e=0),s<0&&(t=0);let o=this._bufferService.rows-1;i=Math.max(Math.min(i,o),0),s=Math.max(Math.min(s,o),0),r=Math.min(r,this._bufferService.cols);let a=this._bufferService.buffer,l=a.ybase+a.y,h=Math.min(a.x,r-1),d=this._optionsService.rawOptions.cursorBlink,c=this._optionsService.rawOptions.cursorStyle,u=this._optionsService.rawOptions.cursorInactiveStyle;for(let f=i;f<=s;++f){let _=f+a.ydisp,p=this._rowElements[f],C=a.lines.get(_);if(!p||!C)break;p.replaceChildren(...this._rowFactory.createRow(C,_,_===l,c,u,h,d,this.dimensions.css.cell.width,this._widthCache,n?f===i?e:0:-1,n?(f===s?t:r)-1:-1))}}};Zi=q([y(7,_s),y(8,ni),y(9,de),y(10,ce),y(11,tt),y(12,Oe),y(13,nt)],Zi);var Qi=class extends R{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new v),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new Wh(this._optionsService))}catch{this._measureStrategy=this._register(new Hh(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange([\"fontFamily\",\"fontSize\"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};Qi=q([y(2,de)],Qi);var cn=class extends R{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},Hh=class extends cn{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement(\"span\"),this._measureElement.classList.add(\"xterm-char-measure-element\"),this._measureElement.textContent=\"W\".repeat(32),this._measureElement.setAttribute(\"aria-hidden\",\"true\"),this._measureElement.style.whiteSpace=\"pre\",this._measureElement.style.fontKerning=\"none\",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},Wh=class extends cn{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext(\"2d\");let t=this._ctx.measureText(\"W\");if(!(\"width\"in t&&\"fontBoundingBoxAscent\"in t&&\"fontBoundingBoxDescent\"in t))throw new Error(\"Required font metrics not supported\")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText(\"W\");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},zh=class extends R{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new Fh(this._window)),this._onDprChange=this._register(new v),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new v),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(oe.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(B(this._textarea,\"focus\",()=>this._isFocused=!0)),this._register(B(this._textarea,\"blur\",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},Fh=class extends R{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new rt),this._onDprChange=this._register(new v),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(W(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=B(this._parentWindow,\"resize\",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},$h=class extends R{constructor(){super(),this.linkProviders=[],this._register(W(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function ws(e,t,i){let s=i.getBoundingClientRect(),r=e.getComputedStyle(i),n=parseInt(r.getPropertyValue(\"padding-left\")),o=parseInt(r.getPropertyValue(\"padding-top\"));return[t.clientX-s.left-n,t.clientY-s.top-o]}function Kh(e,t,i,s,r,n,o,a,l){if(!n)return;let h=ws(e,t,i);if(h)return h[0]=Math.ceil((h[0]+(l?o/2:0))/o),h[1]=Math.ceil(h[1]/a),h[0]=Math.min(Math.max(h[0],1),s+(l?1:0)),h[1]=Math.min(Math.max(h[1],1),r),h}var es=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,r){return Kh(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,r)}getMouseReportCoords(e,t){let i=ws(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};es=q([y(0,Ie),y(1,ni)],es);var Uh=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},dn={};En(dn,{getSafariVersion:()=>Vh,isChromeOS:()=>pn,isFirefox:()=>_n,isIpad:()=>Yh,isIphone:()=>Xh,isLegacyEdge:()=>qh,isLinux:()=>bs,isMac:()=>ti,isNode:()=>ai,isSafari:()=>un,isWindows:()=>fn});var ai=typeof process<\"u\"&&\"title\"in process,Lt=ai?\"node\":navigator.userAgent,Mt=ai?\"node\":navigator.platform,_n=Lt.includes(\"Firefox\"),qh=Lt.includes(\"Edge\"),un=/^((?!chrome|android).)*safari/i.test(Lt);function Vh(){if(!un)return 0;let e=Lt.match(/Version\\/(\\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var ti=[\"Macintosh\",\"MacIntel\",\"MacPPC\",\"Mac68K\"].includes(Mt),Yh=Mt===\"iPad\",Xh=Mt===\"iPhone\",fn=[\"Windows\",\"Win16\",\"Win32\",\"WinCE\"].includes(Mt),bs=Mt.indexOf(\"Linux\")>=0,pn=/\\bCrOS\\b/.test(Lt),gn=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(e){this._idleCallback=void 0;let t=0,i=0,s=e.timeRemaining(),r=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),i=Math.max(t,i),r=e.timeRemaining(),i*1.5>r){s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),this._start();return}s=r}this.clear()}},jh=class extends gn{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},Gh=class extends gn{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},ii=!ai&&\"requestIdleCallback\"in window?Gh:jh,Jh=class{constructor(){this._queue=new ii}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},ts=class extends R{constructor(e,t,i,s,r,n,o,a,l){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=s,this._coreService=r,this._coreBrowserService=a,this._renderer=this._register(new rt),this._pausedResizeTask=new Jh,this._observerDisposable=this._register(new rt),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new v),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new v),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new v),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new v),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new Uh((h,d)=>this._renderRows(h,d),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new Zh(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(W(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(n.onDecorationRegistered(()=>this._fullRefresh())),this._register(n.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange([\"customGlyphs\",\"drawBoldTextInBrightColors\",\"letterSpacing\",\"lineHeight\",\"fontFamily\",\"fontSize\",\"fontWeight\",\"fontWeightBold\",\"minimumContrastRatio\",\"rescaleOverlappingGlyphs\"],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange([\"cursorBlink\",\"cursorStyle\"],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(l.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(h=>this._registerIntersectionObserver(h,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if(\"IntersectionObserver\"in e){let i=new e.IntersectionObserver(s=>this._handleIntersectionChange(s[s.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=W(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let s=this._syncOutputHandler.flush();s&&(e=Math.min(e,s.start),t=Math.max(t,s.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,i){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,this._renderer.value?.handleSelectionChanged(e,t,i)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};ts=q([y(2,de),y(3,ni),y(4,tt),y(5,Rt),y(6,ce),y(7,Oe),y(8,nt)],ts);var Zh=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function Qh(e,t,i,s){let r=i.buffer.x,n=i.buffer.y;if(!i.buffer.hasScrollback)return ia(r,n,e,t,i,s)+li(n,t,i,s)+sa(r,n,e,t,i,s);let o;if(n===t)return o=r>e?\"D\":\"C\",Et(Math.abs(r-e),xt(o,s));o=n>t?\"D\":\"C\";let a=Math.abs(n-t),l=ta(n>t?e:r,i)+(a-1)*i.cols+1+ea(n>t?r:e,i);return Et(l,xt(o,s))}function ea(e,t){return e-1}function ta(e,t){return t.cols-e}function ia(e,t,i,s,r,n){return li(t,s,r,n).length===0?\"\":Et(mn(e,t,e,t-et(t,r),!1,r).length,xt(\"D\",n))}function li(e,t,i,s){let r=e-et(e,i),n=t-et(t,i),o=Math.abs(r-n)-ra(e,t,i);return Et(o,xt(vn(e,t),s))}function sa(e,t,i,s,r,n){let o;li(t,s,r,n).length>0?o=s-et(s,r):o=t;let a=s,l=na(e,t,i,s,r,n);return Et(mn(e,o,i,a,l===\"C\",r).length,xt(l,n))}function ra(e,t,i){let s=0,r=e-et(e,i),n=t-et(t,i);for(let o=0;o<Math.abs(r-n);o++){let a=vn(e,t)===\"A\"?-1:1;i.buffer.lines.get(r+a*o)?.isWrapped&&s++}return s}function et(e,t){let i=0,s=t.buffer.lines.get(e),r=s?.isWrapped;for(;r&&e>=0&&e<t.rows;)i++,s=t.buffer.lines.get(--e),r=s?.isWrapped;return i}function na(e,t,i,s,r,n){let o;return li(i,s,r,n).length>0?o=s-et(s,r):o=t,e<i&&o<=s||e>=i&&o<s?\"C\":\"D\"}function vn(e,t){return e>t?\"A\":\"B\"}function mn(e,t,i,s,r,n){let o=e,a=t,l=\"\";for(;(o!==i||a!==s)&&a>=0&&a<n.buffer.lines.length;)o+=r?1:-1,r&&o>n.cols-1?(l+=n.buffer.translateBufferLineToString(a,!1,e,o),o=0,e=0,a++):!r&&o<0&&(l+=n.buffer.translateBufferLineToString(a,!1,0,e+1),o=n.cols-1,e=o,a--);return l+n.buffer.translateBufferLineToString(a,!1,e,o)}function xt(e,t){let i=t?\"O\":\"[\";return g.ESC+i+e}function Et(e,t){e=Math.floor(e);let i=\"\";for(let s=0;s<e;s++)i+=t;return i}var oa=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function Qs(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var bi=50,ha=15,aa=50,la=500,ca=\"\\xA0\",da=new RegExp(ca,\"g\"),is=class extends R{constructor(e,t,i,s,r,n,o,a,l){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=r,this._mouseService=n,this._optionsService=o,this._renderService=a,this._coreBrowserService=l,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new we,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new v),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new v),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new v),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new v),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=h=>this._handleMouseMove(h),this._mouseUpListener=h=>this._handleMouseUp(h),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(h=>this._handleTrim(h)),this._register(this._bufferService.buffers.onBufferActivate(h=>this._handleBufferActivate(h))),this.enable(),this._model=new oa(this._bufferService),this._activeSelectionMode=0,this._register(W(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(h=>{h.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return\"\";let i=this._bufferService.buffer,s=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return\"\";let r=e[0]<t[0]?e[0]:t[0],n=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let a=i.translateBufferLineToString(o,!0,r,n);s.push(a)}}else{let r=e[1]===t[1]?t[0]:void 0;s.push(i.translateBufferLineToString(e[1],!0,e[0],r));for(let n=e[1]+1;n<=t[1]-1;n++){let o=i.lines.get(n),a=i.translateBufferLineToString(n,!0);o?.isWrapped?s[s.length-1]+=a:s.push(a)}if(e[1]!==t[1]){let n=i.lines.get(t[1]),o=i.translateBufferLineToString(t[1],!0,0,t[0]);n&&n.isWrapped?s[s.length-1]+=o:s.push(o)}}return s.map(r=>r.replace(da,\" \")).join(fn?`\\r\r\n`:`\r\n`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),bs&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s||!t?!1:this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s?!1:this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]<i[1]||t[1]===i[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<i[0]||t[1]<i[1]&&e[1]===i[1]&&e[0]<i[0]||t[1]<i[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let i=this._linkifier.currentLink?.link?.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=Qs(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let s=this._getMouseBufferCoords(e);return s?(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=ws(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-bi),bi),t/=bi,t/Math.abs(t)+Math.round(t*(ha-1)))}shouldForceSelection(e){return ti?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(\"mousemove\",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(\"mouseup\",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),aa)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(\"mousemove\",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(\"mouseup\",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(ti&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]<i.lines.length){let s=i.lines.get(this._model.selectionEnd[1]);s&&s.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(!(!this._model.selectionEnd||!this._model.selectionStart)&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<la&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let i=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(i&&i[0]!==void 0&&i[1]!==void 0){let s=Qh(i[0]-1,i[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(s,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,i=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);if(!i){this._oldHasSelection&&this._fireOnSelectionChange(e,t,i);return}!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,i)}_fireOnSelectionChange(e,t,i){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=i,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(t=>this._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){let r=e.loadCell(s,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:r>1&&t!==s&&(i+=r-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;let r=this._bufferService.buffer,n=r.lines.get(e[1]);if(!n)return;let o=r.translateBufferLineToString(e[1],!1),a=this._convertViewportColToCharacterIndex(n,e[0]),l=a,h=e[0]-a,d=0,c=0,u=0,f=0;if(o.charAt(a)===\" \"){for(;a>0&&o.charAt(a-1)===\" \";)a--;for(;l<o.length&&o.charAt(l+1)===\" \";)l++}else{let C=e[0],D=e[0];n.getWidth(C)===0&&(d++,C--),n.getWidth(D)===2&&(c++,D++);let I=n.getString(D).length;for(I>1&&(f+=I-1,l+=I-1);C>0&&a>0&&!this._isCharWordSeparator(n.loadCell(C-1,this._workCell));){n.loadCell(C-1,this._workCell);let M=this._workCell.getChars().length;this._workCell.getWidth()===0?(d++,C--):M>1&&(u+=M-1,a-=M-1),a--,C--}for(;D<n.length&&l+1<o.length&&!this._isCharWordSeparator(n.loadCell(D+1,this._workCell));){n.loadCell(D+1,this._workCell);let M=this._workCell.getChars().length;this._workCell.getWidth()===2?(c++,D++):M>1&&(f+=M-1,l+=M-1),l++,D++}}l++;let _=a+h-d+u,p=Math.min(this._bufferService.cols,l-a+d+c-u-f);if(!(!t&&o.slice(a,l).trim()===\"\")){if(i&&_===0&&n.getCodePoint(0)!==32){let C=r.lines.get(e[1]-1);if(C&&n.isWrapped&&C.getCodePoint(this._bufferService.cols-1)!==32){let D=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(D){let I=this._bufferService.cols-D.start;_-=I,p+=I}}}if(s&&_+p===this._bufferService.cols&&n.getCodePoint(this._bufferService.cols-1)!==32){let C=r.lines.get(e[1]+1);if(C?.isWrapped&&C.getCodePoint(0)!==32){let D=this._getWordAt([0,e[1]+1],!1,!1,!0);D&&(p+=D.length)}}return{start:_,length:p}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Qs(i,this._bufferService.cols)}};is=q([y(3,ce),y(4,tt),y(5,us),y(6,de),y(7,Ie),y(8,Oe)],is);var er=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},tr=class{constructor(){this._color=new er,this._css=new er}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},j=Object.freeze((()=>{let e=[K.toColor(\"#2e3436\"),K.toColor(\"#cc0000\"),K.toColor(\"#4e9a06\"),K.toColor(\"#c4a000\"),K.toColor(\"#3465a4\"),K.toColor(\"#75507b\"),K.toColor(\"#06989a\"),K.toColor(\"#d3d7cf\"),K.toColor(\"#555753\"),K.toColor(\"#ef2929\"),K.toColor(\"#8ae234\"),K.toColor(\"#fce94f\"),K.toColor(\"#729fcf\"),K.toColor(\"#ad7fa8\"),K.toColor(\"#34e2e2\"),K.toColor(\"#eeeeec\")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],r=t[i/6%6|0],n=t[i%6];e.push({css:X.toCss(s,r,n),rgba:X.toRgba(s,r,n)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:X.toCss(s,s,s),rgba:X.toRgba(s,s,s)})}return e})()),je=K.toColor(\"#ffffff\"),mt=K.toColor(\"#000000\"),ir=K.toColor(\"#ffffff\"),sr=mt,_t={css:\"rgba(255, 255, 255, 0.3)\",rgba:4294967117},_a=je,ss=class extends R{constructor(e){super(),this._optionsService=e,this._contrastCache=new tr,this._halfContrastCache=new tr,this._onChangeColors=this._register(new v),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:je,background:mt,cursor:ir,cursorAccent:sr,selectionForeground:void 0,selectionBackgroundTransparent:_t,selectionBackgroundOpaque:H.blend(mt,_t),selectionInactiveBackgroundTransparent:_t,selectionInactiveBackgroundOpaque:H.blend(mt,_t),scrollbarSliderBackground:H.opacity(je,.2),scrollbarSliderHoverBackground:H.opacity(je,.4),scrollbarSliderActiveBackground:H.opacity(je,.5),overviewRulerBorder:je,ansi:j.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange(\"minimumContrastRatio\",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange(\"theme\",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=N(e.foreground,je),t.background=N(e.background,mt),t.cursor=H.blend(t.background,N(e.cursor,ir)),t.cursorAccent=H.blend(t.background,N(e.cursorAccent,sr)),t.selectionBackgroundTransparent=N(e.selectionBackground,_t),t.selectionBackgroundOpaque=H.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=N(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=H.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?N(e.selectionForeground,Gs):void 0,t.selectionForeground===Gs&&(t.selectionForeground=void 0),H.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=H.opacity(t.selectionBackgroundTransparent,.3)),H.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=H.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=N(e.scrollbarSliderBackground,H.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=N(e.scrollbarSliderHoverBackground,H.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=N(e.scrollbarSliderActiveBackground,H.opacity(t.foreground,.5)),t.overviewRulerBorder=N(e.overviewRulerBorder,_a),t.ansi=j.slice(),t.ansi[0]=N(e.black,j[0]),t.ansi[1]=N(e.red,j[1]),t.ansi[2]=N(e.green,j[2]),t.ansi[3]=N(e.yellow,j[3]),t.ansi[4]=N(e.blue,j[4]),t.ansi[5]=N(e.magenta,j[5]),t.ansi[6]=N(e.cyan,j[6]),t.ansi[7]=N(e.white,j[7]),t.ansi[8]=N(e.brightBlack,j[8]),t.ansi[9]=N(e.brightRed,j[9]),t.ansi[10]=N(e.brightGreen,j[10]),t.ansi[11]=N(e.brightYellow,j[11]),t.ansi[12]=N(e.brightBlue,j[12]),t.ansi[13]=N(e.brightMagenta,j[13]),t.ansi[14]=N(e.brightCyan,j[14]),t.ansi[15]=N(e.brightWhite,j[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let s=0;s<i;s++)t.ansi[s+16]=N(e.extendedAnsi[s],j[s+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0){for(let t=0;t<this._restoreColors.ansi.length;++t)this._colors.ansi[t]=this._restoreColors.ansi[t];return}switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};ss=q([y(0,de)],ss);function N(e,t){if(e!==void 0)try{return K.toColor(e)}catch{}return t}var ua=class{constructor(...e){this._entries=new Map;for(let[t,i]of e)this.set(t,i)}set(e,t){let i=this._entries.get(e);return this._entries.set(e,t),i}forEach(e){for(let[t,i]of this._entries.entries())e(t,i)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},fa=class{constructor(){this._services=new ua,this._services.set(_s,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let i=Tn(e).sort((n,o)=>n.index-o.index),s=[];for(let n of i){let o=this._services.get(n.id);if(!o)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${n.id._id}.`);s.push(o)}let r=i.length>0?i[0].index:t.length;if(t.length!==r)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${r+1} conflicts with ${t.length} static arguments`);return new e(...t,...s)}},pa={trace:0,debug:1,info:2,warn:3,error:4,off:5},ga=\"xterm.js: \",rs=class extends R{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(\"logLevel\",()=>this._updateLogLevel())),va=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=pa[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==\"function\"&&(e[t]=e[t]())}_log(e,t,i){this._evalLazyOptionalParams(i),e.call(console,(this._optionsService.options.logger?\"\":ga)+t,...i)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};rs=q([y(0,de)],rs);var va,rr=class extends R{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new v),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new v),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new v),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=new Array(e);for(let i=0;i<Math.min(e,this.length);i++)t[i]=this._array[this._getCyclicIndex(i)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error(\"Can only recycle when the buffer is full\");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...i){if(t){for(let s=e;s<this._length-t;s++)this._array[this._getCyclicIndex(s)]=this._array[this._getCyclicIndex(s+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let s=this._length-1;s>=e;s--)this._array[this._getCyclicIndex(s+i.length)]=this._array[this._getCyclicIndex(s)];for(let s=0;s<i.length;s++)this._array[this._getCyclicIndex(e+s)]=i[s];if(i.length&&this.onInsertEmitter.fire({index:e,amount:i.length}),this._length+i.length>this._maxLength){let s=this._length+i.length-this._maxLength;this._startIndex+=s,this._length=this._maxLength,this.onTrimEmitter.fire(s)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error(\"start argument out of range\");if(e+i<0)throw new Error(\"Cannot shift elements in list beyond index 0\");if(i>0){for(let r=t-1;r>=0;r--)this.set(e+r+i,this.get(e+r));let s=e+t+i-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s<t;s++)this.set(e+s+i,this.get(e+s))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},L=3,Y=Object.freeze(new Bt),Ht=0,yi=2,St=class Sn{constructor(t,i,s=!1){this.isWrapped=s,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(t*L);let r=i||we.fromCharData([0,Br,1,0]);for(let n=0;n<t;++n)this.setCell(n,r);this.length=t}get(t){let i=this._data[t*L+0],s=i&2097151;return[this._data[t*L+1],i&2097152?this._combined[t]:s?Ue(s):\"\",i>>22,i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):s]}set(t,i){this._data[t*L+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*L+0]=t|2097152|i[2]<<22):this._data[t*L+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*L+0]>>22}hasWidth(t){return this._data[t*L+0]&12582912}getFg(t){return this._data[t*L+1]}getBg(t){return this._data[t*L+2]}hasContent(t){return this._data[t*L+0]&4194303}getCodePoint(t){let i=this._data[t*L+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*L+0]&2097152}getString(t){let i=this._data[t*L+0];return i&2097152?this._combined[t]:i&2097151?Ue(i&2097151):\"\"}isProtected(t){return this._data[t*L+2]&536870912}loadCell(t,i){return Ht=t*L,i.content=this._data[Ht+0],i.fg=this._data[Ht+1],i.bg=this._data[Ht+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*L+0]=i.content,this._data[t*L+1]=i.fg,this._data[t*L+2]=i.bg}setCellFromCodepoint(t,i,s,r){r.bg&268435456&&(this._extendedAttrs[t]=r.extended),this._data[t*L+0]=i|s<<22,this._data[t*L+1]=r.fg,this._data[t*L+2]=r.bg}addCodepointToCell(t,i,s){let r=this._data[t*L+0];r&2097152?this._combined[t]+=Ue(i):r&2097151?(this._combined[t]=Ue(r&2097151)+Ue(i),r&=-2097152,r|=2097152):r=i|1<<22,s&&(r&=-12582913,r|=s<<22),this._data[t*L+0]=r}insertCells(t,i,s){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),i<this.length-t){let r=new we;for(let n=this.length-t-i-1;n>=0;--n)this.setCell(t+i+n,this.loadCell(t+n,r));for(let n=0;n<i;++n)this.setCell(t+n,s)}else for(let r=t;r<this.length;++r)this.setCell(r,s);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,s)}deleteCells(t,i,s){if(t%=this.length,i<this.length-t){let r=new we;for(let n=0;n<this.length-t-i;++n)this.setCell(t+n,this.loadCell(t+i+n,r));for(let n=this.length-i;n<this.length;++n)this.setCell(n,s)}else for(let r=t;r<this.length;++r)this.setCell(r,s);t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),this.getWidth(t)===0&&!this.hasContent(t)&&this.setCellFromCodepoint(t,0,1,s)}replaceCells(t,i,s,r=!1){if(r){for(t&&this.getWidth(t-1)===2&&!this.isProtected(t-1)&&this.setCellFromCodepoint(t-1,0,1,s),i<this.length&&this.getWidth(i-1)===2&&!this.isProtected(i)&&this.setCellFromCodepoint(i,0,1,s);t<i&&t<this.length;)this.isProtected(t)||this.setCell(t,s),t++;return}for(t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),i<this.length&&this.getWidth(i-1)===2&&this.setCellFromCodepoint(i,0,1,s);t<i&&t<this.length;)this.setCell(t++,s)}resize(t,i){if(t===this.length)return this._data.length*4*yi<this._data.buffer.byteLength;let s=t*L;if(t>this.length){if(this._data.buffer.byteLength>=s*4)this._data=new Uint32Array(this._data.buffer,0,s);else{let r=new Uint32Array(s);r.set(this._data),this._data=r}for(let r=this.length;r<t;++r)this.setCell(r,i)}else{this._data=this._data.subarray(0,s);let r=Object.keys(this._combined);for(let o=0;o<r.length;o++){let a=parseInt(r[o],10);a>=t&&delete this._combined[a]}let n=Object.keys(this._extendedAttrs);for(let o=0;o<n.length;o++){let a=parseInt(n[o],10);a>=t&&delete this._extendedAttrs[a]}}return this.length=t,s*4*yi<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*yi<this._data.buffer.byteLength){let t=new Uint32Array(this._data.length);return t.set(this._data),this._data=t,1}return 0}fill(t,i=!1){if(i){for(let s=0;s<this.length;++s)this.isProtected(s)||this.setCell(s,t);return}this._combined={},this._extendedAttrs={};for(let s=0;s<this.length;++s)this.setCell(s,t)}copyFrom(t){this.length!==t.length?this._data=new Uint32Array(t._data):this._data.set(t._data),this.length=t.length,this._combined={};for(let i in t._combined)this._combined[i]=t._combined[i];this._extendedAttrs={};for(let i in t._extendedAttrs)this._extendedAttrs[i]=t._extendedAttrs[i];this.isWrapped=t.isWrapped}clone(){let t=new Sn(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let i in this._combined)t._combined[i]=this._combined[i];for(let i in this._extendedAttrs)t._extendedAttrs[i]=this._extendedAttrs[i];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*L+0]&4194303)return t+(this._data[t*L+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*L+0]&4194303||this._data[t*L+2]&50331648)return t+(this._data[t*L+0]>>22);return 0}copyCellsFrom(t,i,s,r,n){let o=t._data;if(n)for(let l=r-1;l>=0;l--){for(let h=0;h<L;h++)this._data[(s+l)*L+h]=o[(i+l)*L+h];o[(i+l)*L+2]&268435456&&(this._extendedAttrs[s+l]=t._extendedAttrs[i+l])}else for(let l=0;l<r;l++){for(let h=0;h<L;h++)this._data[(s+l)*L+h]=o[(i+l)*L+h];o[(i+l)*L+2]&268435456&&(this._extendedAttrs[s+l]=t._extendedAttrs[i+l])}let a=Object.keys(t._combined);for(let l=0;l<a.length;l++){let h=parseInt(a[l],10);h>=i&&(this._combined[h-i+s]=t._combined[h])}}translateToString(t,i,s,r){i=i??0,s=s??this.length,t&&(s=Math.min(s,this.getTrimmedLength())),r&&(r.length=0);let n=\"\";for(;i<s;){let o=this._data[i*L+0],a=o&2097151,l=o&2097152?this._combined[i]:a?Ue(a):qe;if(n+=l,r)for(let h=0;h<l.length;++h)r.push(i);i+=o>>22||1}return r&&r.push(i),n}};function ma(e,t,i,s,r,n){let o=[];for(let a=0;a<e.length-1;a++){let l=a,h=e.get(++l);if(!h.isWrapped)continue;let d=[e.get(a)];for(;l<e.length&&h.isWrapped;)d.push(h),h=e.get(++l);if(!n&&s>=a&&s<l){a+=d.length-1;continue}let c=0,u=Dt(d,c,t),f=1,_=0;for(;f<d.length;){let C=Dt(d,f,t),D=C-_,I=i-u,M=Math.min(D,I);d[c].copyCellsFrom(d[f],_,u,M,!1),u+=M,u===i&&(c++,u=0),_+=M,_===C&&(f++,_=0),u===0&&c!==0&&d[c-1].getWidth(i-1)===2&&(d[c].copyCellsFrom(d[c-1],i-1,u++,1,!1),d[c-1].setCell(i-1,r))}d[c].replaceCells(u,i,r);let p=0;for(let C=d.length-1;C>0&&(C>c||d[C].getTrimmedLength()===0);C--)p++;p>0&&(o.push(a+d.length-p),o.push(p)),a+=d.length-1}return o}function Sa(e,t){let i=[],s=0,r=t[s],n=0;for(let o=0;o<e.length;o++)if(r===o){let a=t[++s];e.onDeleteEmitter.fire({index:o-n,amount:a}),o+=a-1,n+=a,r=t[++s]}else i.push(o);return{layout:i,countRemoved:n}}function wa(e,t){let i=[];for(let s=0;s<t.length;s++)i.push(e.get(t[s]));for(let s=0;s<i.length;s++)e.set(s,i[s]);e.length=t.length}function ba(e,t,i){let s=[],r=e.map((l,h)=>Dt(e,h,t)).reduce((l,h)=>l+h),n=0,o=0,a=0;for(;a<r;){if(r-a<i){s.push(r-a);break}n+=i;let l=Dt(e,o,t);n>l&&(n-=l,o++);let h=e[o].getWidth(n-1)===2;h&&n--;let d=h?i-1:i;s.push(d),a+=d}return s}function Dt(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let s=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,r=e[t+1].getWidth(0)===2;return s&&r?i-1:i}var wn=class bn{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=bn._nextId++,this._onDispose=this.register(new v),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),Qe(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};wn._nextId=1;var ya=wn,J={},Ge=J.B;J[0]={\"`\":\"\\u25C6\",a:\"\\u2592\",b:\"\\u2409\",c:\"\\u240C\",d:\"\\u240D\",e:\"\\u240A\",f:\"\\xB0\",g:\"\\xB1\",h:\"\\u2424\",i:\"\\u240B\",j:\"\\u2518\",k:\"\\u2510\",l:\"\\u250C\",m:\"\\u2514\",n:\"\\u253C\",o:\"\\u23BA\",p:\"\\u23BB\",q:\"\\u2500\",r:\"\\u23BC\",s:\"\\u23BD\",t:\"\\u251C\",u:\"\\u2524\",v:\"\\u2534\",w:\"\\u252C\",x:\"\\u2502\",y:\"\\u2264\",z:\"\\u2265\",\"{\":\"\\u03C0\",\"|\":\"\\u2260\",\"}\":\"\\xA3\",\"~\":\"\\xB7\"};J.A={\"#\":\"\\xA3\"};J.B=void 0;J[4]={\"#\":\"\\xA3\",\"@\":\"\\xBE\",\"[\":\"ij\",\"\\\\\":\"\\xBD\",\"]\":\"|\",\"{\":\"\\xA8\",\"|\":\"f\",\"}\":\"\\xBC\",\"~\":\"\\xB4\"};J.C=J[5]={\"[\":\"\\xC4\",\"\\\\\":\"\\xD6\",\"]\":\"\\xC5\",\"^\":\"\\xDC\",\"`\":\"\\xE9\",\"{\":\"\\xE4\",\"|\":\"\\xF6\",\"}\":\"\\xE5\",\"~\":\"\\xFC\"};J.R={\"#\":\"\\xA3\",\"@\":\"\\xE0\",\"[\":\"\\xB0\",\"\\\\\":\"\\xE7\",\"]\":\"\\xA7\",\"{\":\"\\xE9\",\"|\":\"\\xF9\",\"}\":\"\\xE8\",\"~\":\"\\xA8\"};J.Q={\"@\":\"\\xE0\",\"[\":\"\\xE2\",\"\\\\\":\"\\xE7\",\"]\":\"\\xEA\",\"^\":\"\\xEE\",\"`\":\"\\xF4\",\"{\":\"\\xE9\",\"|\":\"\\xF9\",\"}\":\"\\xE8\",\"~\":\"\\xFB\"};J.K={\"@\":\"\\xA7\",\"[\":\"\\xC4\",\"\\\\\":\"\\xD6\",\"]\":\"\\xDC\",\"{\":\"\\xE4\",\"|\":\"\\xF6\",\"}\":\"\\xFC\",\"~\":\"\\xDF\"};J.Y={\"#\":\"\\xA3\",\"@\":\"\\xA7\",\"[\":\"\\xB0\",\"\\\\\":\"\\xE7\",\"]\":\"\\xE9\",\"`\":\"\\xF9\",\"{\":\"\\xE0\",\"|\":\"\\xF2\",\"}\":\"\\xE8\",\"~\":\"\\xEC\"};J.E=J[6]={\"@\":\"\\xC4\",\"[\":\"\\xC6\",\"\\\\\":\"\\xD8\",\"]\":\"\\xC5\",\"^\":\"\\xDC\",\"`\":\"\\xE4\",\"{\":\"\\xE6\",\"|\":\"\\xF8\",\"}\":\"\\xE5\",\"~\":\"\\xFC\"};J.Z={\"#\":\"\\xA3\",\"@\":\"\\xA7\",\"[\":\"\\xA1\",\"\\\\\":\"\\xD1\",\"]\":\"\\xBF\",\"{\":\"\\xB0\",\"|\":\"\\xF1\",\"}\":\"\\xE7\"};J.H=J[7]={\"@\":\"\\xC9\",\"[\":\"\\xC4\",\"\\\\\":\"\\xD6\",\"]\":\"\\xC5\",\"^\":\"\\xDC\",\"`\":\"\\xE9\",\"{\":\"\\xE4\",\"|\":\"\\xF6\",\"}\":\"\\xE5\",\"~\":\"\\xFC\"};J[\"=\"]={\"#\":\"\\xF9\",\"@\":\"\\xE0\",\"[\":\"\\xE9\",\"\\\\\":\"\\xE7\",\"]\":\"\\xEA\",\"^\":\"\\xEE\",_:\"\\xE8\",\"`\":\"\\xF4\",\"{\":\"\\xE4\",\"|\":\"\\xF6\",\"}\":\"\\xFC\",\"~\":\"\\xFB\"};var nr=4294967295,or=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Y.clone(),this.savedCharset=Ge,this.markers=[],this._nullCell=we.fromCharData([0,Br,1,0]),this._whitespaceCell=we.fromCharData([0,qe,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new ii,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new rr(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new jt),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new jt),this._whitespaceCell}getBlankLine(e,t){return new St(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>nr?nr:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Y);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new rr(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Y),s=0,r=this._getCorrectBufferLength(t);if(r>this.lines.maxLength&&(this.lines.maxLength=r),this.lines.length>0){if(this._cols<e)for(let o=0;o<this.lines.length;o++)s+=+this.lines.get(o).resize(e,i);let n=0;if(this._rows<t)for(let o=this._rows;o<t;o++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new St(e,i)):this.ybase>0&&this.lines.length<=this.ybase+this.y+n+1?(this.ybase--,n++,this.ydisp>0&&this.ydisp--):this.lines.push(new St(e,i)));else for(let o=this._rows;o>t;o--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(r<this.lines.maxLength){let o=this.lines.length-r;o>0&&(this.lines.trimStart(o),this.ybase=Math.max(this.ybase-o,0),this.ydisp=Math.max(this.ydisp-o,0),this.savedY=Math.max(this.savedY-o,0)),this.lines.maxLength=r}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),n&&(this.y+=n),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let n=0;n<this.lines.length;n++)s+=+this.lines.get(n).resize(e,i);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),s>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===\"conpty\"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=ma(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Y),i);if(s.length>0){let r=Sa(this.lines,s);wa(this.lines,r.layout),this._reflowLargerAdjustViewport(e,t,r.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(Y),r=i;for(;r-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new St(e,s))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-i,0)}_reflowSmaller(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=this.getNullCell(Y),r=[],n=0;for(let o=this.lines.length-1;o>=0;o--){let a=this.lines.get(o);if(!a||!a.isWrapped&&a.getTrimmedLength()<=e)continue;let l=[a];for(;a.isWrapped&&o>0;)a=this.lines.get(--o),l.unshift(a);if(!i){let M=this.ybase+this.y;if(M>=o&&M<o+l.length)continue}let h=l[l.length-1].getTrimmedLength(),d=ba(l,this._cols,e),c=d.length-l.length,u;this.ybase===0&&this.y!==this.lines.length-1?u=Math.max(0,this.y-this.lines.maxLength+c):u=Math.max(0,this.lines.length-this.lines.maxLength+c);let f=[];for(let M=0;M<c;M++){let E=this.getBlankLine(Y,!0);f.push(E)}f.length>0&&(r.push({start:o+l.length+n,newLines:f}),n+=f.length),l.push(...f);let _=d.length-1,p=d[_];p===0&&(_--,p=d[_]);let C=l.length-c-1,D=h;for(;C>=0;){let M=Math.min(D,p);if(l[_]===void 0)break;if(l[_].copyCellsFrom(l[C],D-M,p-M,M,!0),p-=M,p===0&&(_--,p=d[_]),D-=M,D===0){C--;let E=Math.max(C,0);D=Dt(l,E,this._cols)}}for(let M=0;M<l.length;M++)d[M]<e&&l[M].setCell(d[M],s);let I=c-u;for(;I-- >0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+n)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+c,this.ybase+t-1)}if(r.length>0){let o=[],a=[];for(let p=0;p<this.lines.length;p++)a.push(this.lines.get(p));let l=this.lines.length,h=l-1,d=0,c=r[d];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+n);let u=0;for(let p=Math.min(this.lines.maxLength-1,l+n-1);p>=0;p--)if(c&&c.start>h+u){for(let C=c.newLines.length-1;C>=0;C--)this.lines.set(p--,c.newLines[C]);p++,o.push({index:h+1,amount:c.newLines.length}),u+=c.newLines.length,c=r[++d]}else this.lines.set(p,a[h--]);let f=0;for(let p=o.length-1;p>=0;p--)o[p].index+=f,this.lines.onInsertEmitter.fire(o[p]),f+=o[p].amount;let _=Math.max(0,l+n-this.lines.maxLength);_>0&&this.lines.onTrimEmitter.fire(_)}}translateBufferLineToString(e,t,i=0,s){let r=this.lines.get(e);return r?r.translateToString(t,i,s):\"\"}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+1<this.lines.length&&this.lines.get(i+1).isWrapped;)i++;return{first:t,last:i}}setupTabStops(e){for(e!=null?this.tabs[e]||(e=this.prevStop(e)):(this.tabs={},e=0);e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e==null&&(e=this.x);!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new ya(e);return this.markers.push(t),t.register(this.lines.onTrim(i=>{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.line<i.index+i.amount&&t.dispose(),t.line>i.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},Ca=class extends R{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new v),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange(\"scrollback\",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange(\"tabStopWidth\",()=>this.setupTabStops()))}reset(){this._normal=new or(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new or(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},yn=2,Cn=1,ns=class extends R{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new v),this.onResize=this._onResize.event,this._onScroll=this._register(new v),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,yn),this.rows=Math.max(e.rawOptions.rows||0,Cn),this.buffers=this._register(new Ca(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,s=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,s;s=this._cachedBlankLine,(!s||s.length!==this.cols||s.getFg(0)!==e.fg||s.getBg(0)!==e.bg)&&(s=i.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;let r=i.ybase+i.scrollTop,n=i.ybase+i.scrollBottom;if(i.scrollTop===0){let o=i.lines.isFull;n===i.lines.length-1?o?i.lines.recycle().copyFrom(s):i.lines.push(s.clone()):i.lines.splice(n+1,0,s.clone()),o?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let o=n-r+1;i.lines.shiftElements(r+1,o-1,-1),i.lines.set(n,s.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let s=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),s!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};ns=q([y(0,de)],ns);var it={cols:80,rows:24,cursorBlink:!1,cursorStyle:\"block\",cursorWidth:1,cursorInactiveStyle:\"outline\",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:\"alt\",fastScrollSensitivity:5,fontFamily:\"monospace\",fontSize:15,fontWeight:\"normal\",fontWeightBold:\"bold\",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:\"info\",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:ti,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:\" ()[]{}',\\\"`\",altClickMovesCursor:!0,convertEol:!1,termName:\"xterm\",cancelEvents:!1,overviewRuler:{}},ka=[\"normal\",\"bold\",\"100\",\"200\",\"300\",\"400\",\"500\",\"600\",\"700\",\"800\",\"900\"],xa=class extends R{constructor(e){super(),this._onOptionChange=this._register(new v),this.onOptionChange=this._onOptionChange.event;let t={...it};for(let i in e)if(i in t)try{let s=e[i];t[i]=this._sanitizeAndValidateOption(i,s)}catch(s){console.error(s)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(W(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in it))throw new Error(`No option with key \"${i}\"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in it))throw new Error(`No option with key \"${i}\"`);s=this._sanitizeAndValidateOption(i,s),this.rawOptions[i]!==s&&(this.rawOptions[i]=s,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let s={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,s)}}_sanitizeAndValidateOption(e,t){switch(e){case\"cursorStyle\":if(t||(t=it[e]),!Ea(t))throw new Error(`\"${t}\" is not a valid value for ${e}`);break;case\"wordSeparator\":t||(t=it[e]);break;case\"fontWeight\":case\"fontWeightBold\":if(typeof t==\"number\"&&1<=t&&t<=1e3)break;t=ka.includes(t)?t:it[e];break;case\"cursorWidth\":t=Math.floor(t);case\"lineHeight\":case\"tabStopWidth\":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case\"minimumContrastRatio\":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case\"scrollback\":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case\"fastScrollSensitivity\":case\"scrollSensitivity\":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case\"rows\":case\"cols\":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case\"windowsPty\":t=t??{};break}return t}};function Ea(e){return e===\"block\"||e===\"underline\"||e===\"bar\"}function wt(e,t=5){if(typeof e!=\"object\")return e;let i=Array.isArray(e)?[]:{};for(let s in e)i[s]=t<=1?e[s]:e[s]&&wt(e[s],t-1);return i}var hr=Object.freeze({insertMode:!1}),ar=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),os=class extends R{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new v),this.onData=this._onData.event,this._onUserInput=this._register(new v),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new v),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new v),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=wt(hr),this.decPrivateModes=wt(ar)}reset(){this.modes=wt(hr),this.decPrivateModes=wt(ar)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data \"${e}\"`),this._logService.trace(\"sending data (codes)\",()=>e.split(\"\").map(s=>s.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary \"${e}\"`),this._logService.trace(\"sending binary (codes)\",()=>e.split(\"\").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};os=q([y(0,ce),y(1,Tr),y(2,de)],os);var lr={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function Ci(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}var ki=String.fromCharCode,cr={DEFAULT:e=>{let t=[Ci(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?\"\":`\\x1B[M${ki(t[0])}${ki(t[1])}${ki(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?\"m\":\"M\";return`\\x1B[<${Ci(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?\"m\":\"M\";return`\\x1B[<${Ci(e,!0)};${e.x};${e.y}${t}`}},hs=class extends R{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol=\"\",this._activeEncoding=\"\",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new v),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(lr))this.addProtocol(s,lr[s]);for(let s of Object.keys(cr))this.addEncoding(s,cr[s]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol \"${e}\"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding \"${e}\"`);this._activeEncoding=e}reset(){this.activeProtocol=\"NONE\",this.activeEncoding=\"DEFAULT\",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let s=t/i,r=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(r/=s+0,Math.abs(e.deltaY)<50&&(r*=.3),this._wheelPartialScroll+=r,r=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(r*=this._bufferService.rows),r}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===\"SGR_PIXELS\"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===\"DEFAULT\"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};hs=q([y(0,ce),y(1,tt),y(2,de)],hs);var xi=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],Da=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],G;function Ba(e,t){let i=0,s=t.length-1,r;if(e<t[0][0]||e>t[s][1])return!1;for(;s>=i;)if(r=i+s>>1,e>t[r][1])i=r+1;else if(e<t[r][0])s=r-1;else return!0;return!1}var Ra=class{constructor(){if(this.version=\"6\",!G){G=new Uint8Array(65536),G.fill(1),G[0]=0,G.fill(0,1,32),G.fill(0,127,160),G.fill(2,4352,4448),G[9001]=2,G[9002]=2,G.fill(2,11904,42192),G[12351]=1,G.fill(2,44032,55204),G.fill(2,63744,64256),G.fill(2,65040,65050),G.fill(2,65072,65136),G.fill(2,65280,65377),G.fill(2,65504,65511);for(let e=0;e<xi.length;++e)G.fill(0,xi[e][0],xi[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?G[e]:Ba(e,Da)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),s=i===0&&t!==0;if(s){let r=Je.extractWidth(t);r===0?s=!1:r>i&&(i=r)}return Je.createPropertyValue(0,i,s)}},Je=class Xt{constructor(){this._providers=Object.create(null),this._active=\"\",this._onChange=new v,this.onChange=this._onChange.event;let t=new Ra;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,i,s=!1){return(t&16777215)<<3|(i&3)<<1|(s?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version \"${t}\"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let i=0,s=0,r=t.length;for(let n=0;n<r;++n){let o=t.charCodeAt(n);if(55296<=o&&o<=56319){if(++n>=r)return i+this.wcwidth(o);let h=t.charCodeAt(n);56320<=h&&h<=57343?o=(o-55296)*1024+h-56320+65536:i+=this.wcwidth(h)}let a=this.charProperties(o,s),l=Xt.extractWidth(a);Xt.extractShouldJoin(a)&&(l-=Xt.extractWidth(s)),i+=l,s=a}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},La=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function dr(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);i&&t&&(i.isWrapped=t[3]!==0&&t[3]!==32)}var ut=2147483647,Ma=256,kn=class as{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>Ma)throw new Error(\"maxSubParamsLength must not be greater than 256\");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new as;if(!t.length)return i;for(let s=Array.isArray(t[0])?1:0;s<t.length;++s){let r=t[s];if(Array.isArray(r))for(let n=0;n<r.length;++n)i.addSubParam(r[n]);else i.addParam(r)}return i}clone(){let t=new as(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let t=[];for(let i=0;i<this.length;++i){t.push(this.params[i]);let s=this._subParamsIdx[i]>>8,r=this._subParamsIdx[i]&255;r-s>0&&t.push(Array.prototype.slice.call(this._subParams,s,r))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error(\"values lesser than -1 are not allowed\");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>ut?ut:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error(\"values lesser than -1 are not allowed\");this._subParams[this._subParamsLength++]=t>ut?ut:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,s=this._subParamsIdx[t]&255;return s-i>0?this._subParams.subarray(i,s):null}getSubParamsAll(){let t={};for(let i=0;i<this.length;++i){let s=this._subParamsIdx[i]>>8,r=this._subParamsIdx[i]&255;r-s>0&&(t[i]=this._subParams.slice(s,r))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let s=this._digitIsSub?this._subParams:this.params,r=s[i-1];s[i-1]=~r?Math.min(r*10+t,ut):t}},ft=[],Pa=class{constructor(){this._state=0,this._active=ft,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=ft}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=ft,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||ft,!this._active.length)this._handlerFb(this._id,\"START\");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,i){if(!this._active.length)this._handlerFb(this._id,\"PUT\",ri(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t<i;){let s=e[t++];if(s===59){this._state=2,this._start();break}if(s<48||57<s){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+s-48}this._state===2&&i-t>0&&this._put(e,t,i)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,\"END\",e);else{let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&i===!1){for(;s>=0&&(i=this._active[s].end(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=ft,this._id=-1,this._state=0}}},fe=class{constructor(e){this._handler=e,this._data=\"\",this._hitLimit=!1}start(){this._data=\"\",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=ri(e,t,i),this._data.length>1e7&&(this._data=\"\",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(i=>(this._data=\"\",this._hitLimit=!1,i));return this._data=\"\",this._hitLimit=!1,t}},pt=[],Ta=class{constructor(){this._handlers=Object.create(null),this._active=pt,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=pt}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=pt,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||pt,!this._active.length)this._handlerFb(this._ident,\"HOOK\",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,\"PUT\",ri(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,\"UNHOOK\",e);else{let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&i===!1){for(;s>=0&&(i=this._active[s].unhook(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=pt,this._ident=0}},bt=new kn;bt.addParam(0);var _r=class{constructor(e){this._handler=e,this._data=\"\",this._params=bt,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():bt,this._data=\"\",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=ri(e,t,i),this._data.length>1e7&&(this._data=\"\",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(i=>(this._params=bt,this._data=\"\",this._hitLimit=!1,i));return this._params=bt,this._data=\"\",this._hitLimit=!1,t}},Aa=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,s){this.table[t<<8|e]=i<<4|s}addMany(e,t,i,s){for(let r=0;r<e.length;r++)this.table[t<<8|e[r]]=i<<4|s}},Se=160,Oa=(function(){let e=new Aa(4095),t=Array.apply(null,Array(256)).map((a,l)=>l),i=(a,l)=>t.slice(a,l),s=i(32,127),r=i(0,24);r.push(25),r.push.apply(r,i(28,32));let n=i(0,14),o;e.setDefault(1,0),e.addMany(s,0,2,0);for(o in n)e.addMany([24,26,153,154],o,3,0),e.addMany(i(128,144),o,3,0),e.addMany(i(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(r,0,3,0),e.addMany(r,1,3,1),e.add(127,1,0,1),e.addMany(r,8,0,8),e.addMany(r,3,3,3),e.add(127,3,0,3),e.addMany(r,4,3,4),e.add(127,4,0,4),e.addMany(r,6,3,6),e.addMany(r,5,3,5),e.add(127,5,0,5),e.addMany(r,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(s,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(r,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(r,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(r,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(r,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(r,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(r,13,13,13),e.addMany(s,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(Se,0,2,0),e.add(Se,8,5,8),e.add(Se,6,0,6),e.add(Se,11,0,11),e.add(Se,13,13,13),e})(),Ia=class extends R{constructor(e=Oa){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new kn,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,i,s)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,i)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(W(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new Pa),this._dcsParser=this._register(new Ta),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:\"\\\\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error(\"only one byte as prefix supported\");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error(\"prefix must be in range 0x3c .. 0x3f\")}if(e.intermediates){if(e.intermediates.length>2)throw new Error(\"only two bytes as intermediates are supported\");for(let r=0;r<e.intermediates.length;++r){let n=e.intermediates.charCodeAt(r);if(32>n||n>47)throw new Error(\"intermediate must be in range 0x20 .. 0x2f\");i<<=8,i|=n}}if(e.final.length!==1)throw new Error(\"final must be a single byte\");let s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join(\"\")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let i=this._identifier(e,[48,126]);this._escHandlers[i]===void 0&&(this._escHandlers[i]=[]);let s=this._escHandlers[i];return s.push(t),{dispose:()=>{let r=s.indexOf(t);r!==-1&&s.splice(r,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let i=this._identifier(e);this._csiHandlers[i]===void 0&&(this._csiHandlers[i]=[]);let s=this._csiHandlers[i];return s.push(t),{dispose:()=>{let r=s.indexOf(t);r!==-1&&s.splice(r,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,s,r){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=r}parse(e,t,i){let s=0,r=0,n=0,o;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,n=this._parseStack.chunkPos+1;else{if(i===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error(\"improper continuation due to previous async handler, giving up parsing\");let a=this._parseStack.handlers,l=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(i===!1&&l>-1){for(;l>=0&&(o=a[l](this._params),o!==!0);l--)if(o instanceof Promise)return this._parseStack.handlerPos=l,o}this._parseStack.handlers=[];break;case 4:if(i===!1&&l>-1){for(;l>=0&&(o=a[l](),o!==!0);l--)if(o instanceof Promise)return this._parseStack.handlerPos=l,o}this._parseStack.handlers=[];break;case 6:if(s=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(s!==24&&s!==26,i),o)return o;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(s=e[this._parseStack.chunkPos],o=this._oscParser.end(s!==24&&s!==26,i),o)return o;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,n=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let a=n;a<t;++a){switch(s=e[a],r=this._transitions.table[this.currentState<<8|(s<160?s:Se)],r>>4){case 2:for(let u=a+1;;++u){if(u>=t||(s=e[u])<32||s>126&&s<Se){this._printHandler(e,a,u),a=u-1;break}if(++u>=t||(s=e[u])<32||s>126&&s<Se){this._printHandler(e,a,u),a=u-1;break}if(++u>=t||(s=e[u])<32||s>126&&s<Se){this._printHandler(e,a,u),a=u-1;break}if(++u>=t||(s=e[u])<32||s>126&&s<Se){this._printHandler(e,a,u),a=u-1;break}}break;case 3:this._executeHandlers[s]?this._executeHandlers[s]():this._executeHandlerFb(s),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:a,code:s,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let l=this._csiHandlers[this._collect<<8|s],h=l?l.length-1:-1;for(;h>=0&&(o=l[h](this._params),o!==!0);h--)if(o instanceof Promise)return this._preserveStack(3,l,h,r,a),o;h<0&&this._csiHandlerFb(this._collect<<8|s,this._params),this.precedingJoinState=0;break;case 8:do switch(s){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(s-48)}while(++a<t&&(s=e[a])>47&&s<60);a--;break;case 9:this._collect<<=8,this._collect|=s;break;case 10:let d=this._escHandlers[this._collect<<8|s],c=d?d.length-1:-1;for(;c>=0&&(o=d[c](),o!==!0);c--)if(o instanceof Promise)return this._preserveStack(4,d,c,r,a),o;c<0&&this._escHandlerFb(this._collect<<8|s),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|s,this._params);break;case 13:for(let u=a+1;;++u)if(u>=t||(s=e[u])===24||s===26||s===27||s>127&&s<Se){this._dcsParser.put(e,a,u),a=u-1;break}break;case 14:if(o=this._dcsParser.unhook(s!==24&&s!==26),o)return this._preserveStack(6,[],0,r,a),o;s===27&&(r|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let u=a+1;;u++)if(u>=t||(s=e[u])<32||s>127&&s<Se){this._oscParser.put(e,a,u),a=u-1;break}break;case 6:if(o=this._oscParser.end(s!==24&&s!==26),o)return this._preserveStack(5,[],0,r,a),o;s===27&&(r|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break}this.currentState=r&15}}},Na=/^([\\da-f])\\/([\\da-f])\\/([\\da-f])$|^([\\da-f]{2})\\/([\\da-f]{2})\\/([\\da-f]{2})$|^([\\da-f]{3})\\/([\\da-f]{3})\\/([\\da-f]{3})$|^([\\da-f]{4})\\/([\\da-f]{4})\\/([\\da-f]{4})$/,Ha=/^[\\da-f]+$/;function ur(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(\"rgb:\")===0){t=t.slice(4);let i=Na.exec(t);if(i){let s=i[1]?15:i[4]?255:i[7]?4095:65535;return[Math.round(parseInt(i[1]||i[4]||i[7]||i[10],16)/s*255),Math.round(parseInt(i[2]||i[5]||i[8]||i[11],16)/s*255),Math.round(parseInt(i[3]||i[6]||i[9]||i[12],16)/s*255)]}}else if(t.indexOf(\"#\")===0&&(t=t.slice(1),Ha.exec(t)&&[3,6,9,12].includes(t.length))){let i=t.length/3,s=[0,0,0];for(let r=0;r<3;++r){let n=parseInt(t.slice(i*r,i*r+i),16);s[r]=i===1?n<<4:i===2?n:i===3?n>>4:n>>8}return s}}function Ei(e,t){let i=e.toString(16),s=i.length<2?\"0\"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}function Wa(e,t=16){let[i,s,r]=e;return`rgb:${Ei(i,t)}/${Ei(s,t)}/${Ei(r,t)}`}var za={\"(\":0,\")\":1,\"*\":2,\"+\":3,\"-\":1,\".\":2},Ke=131072,fr=10;function pr(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var gr=5e3,vr=0,Fa=class extends R{constructor(e,t,i,s,r,n,o,a,l=new Ia){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=s,this._optionsService=r,this._oscLinkService=n,this._coreMouseService=o,this._unicodeService=a,this._parser=l,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new Mn,this._utf8Decoder=new Pn,this._windowTitle=\"\",this._iconName=\"\",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Y.clone(),this._eraseAttrDataInternal=Y.clone(),this._onRequestBell=this._register(new v),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new v),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new v),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new v),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new v),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new v),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new v),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new v),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new v),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new v),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new v),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new v),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new v),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new ls(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(h=>this._activeBuffer=h.activeBuffer)),this._parser.setCsiHandlerFallback((h,d)=>{this._logService.debug(\"Unknown CSI code: \",{identifier:this._parser.identToString(h),params:d.toArray()})}),this._parser.setEscHandlerFallback(h=>{this._logService.debug(\"Unknown ESC code: \",{identifier:this._parser.identToString(h)})}),this._parser.setExecuteHandlerFallback(h=>{this._logService.debug(\"Unknown EXECUTE code: \",{code:h})}),this._parser.setOscHandlerFallback((h,d,c)=>{this._logService.debug(\"Unknown OSC code: \",{identifier:h,action:d,data:c})}),this._parser.setDcsHandlerFallback((h,d,c)=>{d===\"HOOK\"&&(c=c.toArray()),this._logService.debug(\"Unknown DCS code: \",{identifier:this._parser.identToString(h),action:d,payload:c})}),this._parser.setPrintHandler((h,d,c)=>this.print(h,d,c)),this._parser.registerCsiHandler({final:\"@\"},h=>this.insertChars(h)),this._parser.registerCsiHandler({intermediates:\" \",final:\"@\"},h=>this.scrollLeft(h)),this._parser.registerCsiHandler({final:\"A\"},h=>this.cursorUp(h)),this._parser.registerCsiHandler({intermediates:\" \",final:\"A\"},h=>this.scrollRight(h)),this._parser.registerCsiHandler({final:\"B\"},h=>this.cursorDown(h)),this._parser.registerCsiHandler({final:\"C\"},h=>this.cursorForward(h)),this._parser.registerCsiHandler({final:\"D\"},h=>this.cursorBackward(h)),this._parser.registerCsiHandler({final:\"E\"},h=>this.cursorNextLine(h)),this._parser.registerCsiHandler({final:\"F\"},h=>this.cursorPrecedingLine(h)),this._parser.registerCsiHandler({final:\"G\"},h=>this.cursorCharAbsolute(h)),this._parser.registerCsiHandler({final:\"H\"},h=>this.cursorPosition(h)),this._parser.registerCsiHandler({final:\"I\"},h=>this.cursorForwardTab(h)),this._parser.registerCsiHandler({final:\"J\"},h=>this.eraseInDisplay(h,!1)),this._parser.registerCsiHandler({prefix:\"?\",final:\"J\"},h=>this.eraseInDisplay(h,!0)),this._parser.registerCsiHandler({final:\"K\"},h=>this.eraseInLine(h,!1)),this._parser.registerCsiHandler({prefix:\"?\",final:\"K\"},h=>this.eraseInLine(h,!0)),this._parser.registerCsiHandler({final:\"L\"},h=>this.insertLines(h)),this._parser.registerCsiHandler({final:\"M\"},h=>this.deleteLines(h)),this._parser.registerCsiHandler({final:\"P\"},h=>this.deleteChars(h)),this._parser.registerCsiHandler({final:\"S\"},h=>this.scrollUp(h)),this._parser.registerCsiHandler({final:\"T\"},h=>this.scrollDown(h)),this._parser.registerCsiHandler({final:\"X\"},h=>this.eraseChars(h)),this._parser.registerCsiHandler({final:\"Z\"},h=>this.cursorBackwardTab(h)),this._parser.registerCsiHandler({final:\"`\"},h=>this.charPosAbsolute(h)),this._parser.registerCsiHandler({final:\"a\"},h=>this.hPositionRelative(h)),this._parser.registerCsiHandler({final:\"b\"},h=>this.repeatPrecedingCharacter(h)),this._parser.registerCsiHandler({final:\"c\"},h=>this.sendDeviceAttributesPrimary(h)),this._parser.registerCsiHandler({prefix:\">\",final:\"c\"},h=>this.sendDeviceAttributesSecondary(h)),this._parser.registerCsiHandler({final:\"d\"},h=>this.linePosAbsolute(h)),this._parser.registerCsiHandler({final:\"e\"},h=>this.vPositionRelative(h)),this._parser.registerCsiHandler({final:\"f\"},h=>this.hVPosition(h)),this._parser.registerCsiHandler({final:\"g\"},h=>this.tabClear(h)),this._parser.registerCsiHandler({final:\"h\"},h=>this.setMode(h)),this._parser.registerCsiHandler({prefix:\"?\",final:\"h\"},h=>this.setModePrivate(h)),this._parser.registerCsiHandler({final:\"l\"},h=>this.resetMode(h)),this._parser.registerCsiHandler({prefix:\"?\",final:\"l\"},h=>this.resetModePrivate(h)),this._parser.registerCsiHandler({final:\"m\"},h=>this.charAttributes(h)),this._parser.registerCsiHandler({final:\"n\"},h=>this.deviceStatus(h)),this._parser.registerCsiHandler({prefix:\"?\",final:\"n\"},h=>this.deviceStatusPrivate(h)),this._parser.registerCsiHandler({intermediates:\"!\",final:\"p\"},h=>this.softReset(h)),this._parser.registerCsiHandler({intermediates:\" \",final:\"q\"},h=>this.setCursorStyle(h)),this._parser.registerCsiHandler({final:\"r\"},h=>this.setScrollRegion(h)),this._parser.registerCsiHandler({final:\"s\"},h=>this.saveCursor(h)),this._parser.registerCsiHandler({final:\"t\"},h=>this.windowOptions(h)),this._parser.registerCsiHandler({final:\"u\"},h=>this.restoreCursor(h)),this._parser.registerCsiHandler({intermediates:\"'\",final:\"}\"},h=>this.insertColumns(h)),this._parser.registerCsiHandler({intermediates:\"'\",final:\"~\"},h=>this.deleteColumns(h)),this._parser.registerCsiHandler({intermediates:'\"',final:\"q\"},h=>this.selectProtected(h)),this._parser.registerCsiHandler({intermediates:\"$\",final:\"p\"},h=>this.requestMode(h,!0)),this._parser.registerCsiHandler({prefix:\"?\",intermediates:\"$\",final:\"p\"},h=>this.requestMode(h,!1)),this._parser.setExecuteHandler(g.BEL,()=>this.bell()),this._parser.setExecuteHandler(g.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(g.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(g.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(g.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(g.BS,()=>this.backspace()),this._parser.setExecuteHandler(g.HT,()=>this.tab()),this._parser.setExecuteHandler(g.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(g.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Vt.IND,()=>this.index()),this._parser.setExecuteHandler(Vt.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Vt.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new fe(h=>(this.setTitle(h),this.setIconName(h),!0))),this._parser.registerOscHandler(1,new fe(h=>this.setIconName(h))),this._parser.registerOscHandler(2,new fe(h=>this.setTitle(h))),this._parser.registerOscHandler(4,new fe(h=>this.setOrReportIndexedColor(h))),this._parser.registerOscHandler(8,new fe(h=>this.setHyperlink(h))),this._parser.registerOscHandler(10,new fe(h=>this.setOrReportFgColor(h))),this._parser.registerOscHandler(11,new fe(h=>this.setOrReportBgColor(h))),this._parser.registerOscHandler(12,new fe(h=>this.setOrReportCursorColor(h))),this._parser.registerOscHandler(104,new fe(h=>this.restoreIndexedColor(h))),this._parser.registerOscHandler(110,new fe(h=>this.restoreFgColor(h))),this._parser.registerOscHandler(111,new fe(h=>this.restoreBgColor(h))),this._parser.registerOscHandler(112,new fe(h=>this.restoreCursorColor(h))),this._parser.registerEscHandler({final:\"7\"},()=>this.saveCursor()),this._parser.registerEscHandler({final:\"8\"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:\"D\"},()=>this.index()),this._parser.registerEscHandler({final:\"E\"},()=>this.nextLine()),this._parser.registerEscHandler({final:\"H\"},()=>this.tabSet()),this._parser.registerEscHandler({final:\"M\"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:\"=\"},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:\">\"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:\"c\"},()=>this.fullReset()),this._parser.registerEscHandler({final:\"n\"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:\"o\"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:\"|\"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:\"}\"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:\"~\"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:\"%\",final:\"@\"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:\"%\",final:\"G\"},()=>this.selectDefaultCharset());for(let h in J)this._parser.registerEscHandler({intermediates:\"(\",final:h},()=>this.selectCharset(\"(\"+h)),this._parser.registerEscHandler({intermediates:\")\",final:h},()=>this.selectCharset(\")\"+h)),this._parser.registerEscHandler({intermediates:\"*\",final:h},()=>this.selectCharset(\"*\"+h)),this._parser.registerEscHandler({intermediates:\"+\",final:h},()=>this.selectCharset(\"+\"+h)),this._parser.registerEscHandler({intermediates:\"-\",final:h},()=>this.selectCharset(\"-\"+h)),this._parser.registerEscHandler({intermediates:\".\",final:h},()=>this.selectCharset(\".\"+h)),this._parser.registerEscHandler({intermediates:\"/\",final:h},()=>this.selectCharset(\"/\"+h));this._parser.registerEscHandler({intermediates:\"#\",final:\"8\"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(h=>(this._logService.error(\"Parsing error: \",h),h)),this._parser.registerDcsHandler({intermediates:\"$\",final:\"q\"},new _r((h,d)=>this.requestStatusString(h,d)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,i)=>setTimeout(()=>i(\"#SLOW_TIMEOUT\"),gr))]).catch(t=>{if(t!==\"#SLOW_TIMEOUT\")throw t;console.warn(`async parser handler taking longer than ${gr} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,r=this._activeBuffer.y,n=0,o=this._parseStack.paused;if(o){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,r=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Ke&&(n=this._parseStack.position+Ke)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==\"string\"?` \"${e}\"`:` \"${Array.prototype.map.call(e,h=>String.fromCharCode(h)).join(\"\")}\"`}`),this._logService.logLevel===0&&this._logService.trace(\"parsing data (codes)\",typeof e==\"string\"?e.split(\"\").map(h=>h.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<Ke&&(this._parseBuffer=new Uint32Array(Math.min(e.length,Ke))),o||this._dirtyRowTracker.clearRange(),e.length>Ke)for(let h=n;h<e.length;h+=Ke){let d=h+Ke<e.length?h+Ke:e.length,c=typeof e==\"string\"?this._stringDecoder.decode(e.substring(h,d),this._parseBuffer):this._utf8Decoder.decode(e.subarray(h,d),this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,c))return this._preserveStack(s,r,c,h),this._logSlowResolvingAsync(i),i}else if(!o){let h=typeof e==\"string\"?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,h))return this._preserveStack(s,r,h,0),this._logSlowResolvingAsync(i),i}(this._activeBuffer.x!==s||this._activeBuffer.y!==r)&&this._onCursorMove.fire();let a=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),l=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);l<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(l,this._bufferService.rows-1),end:Math.min(a,this._bufferService.rows-1)})}print(e,t,i){let s,r,n=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,a=this._bufferService.cols,l=this._coreService.decPrivateModes.wraparound,h=this._coreService.modes.insertMode,d=this._curAttrData,c=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&i-t>0&&c.getWidth(this._activeBuffer.x-1)===2&&c.setCellFromCodepoint(this._activeBuffer.x-1,0,1,d);let u=this._parser.precedingJoinState;for(let f=t;f<i;++f){if(s=e[f],s<127&&n){let D=n[String.fromCharCode(s)];D&&(s=D.charCodeAt(0))}let _=this._unicodeService.charProperties(s,u);r=Je.extractWidth(_);let p=Je.extractShouldJoin(_),C=p?Je.extractWidth(u):0;if(u=_,o&&this._onA11yChar.fire(Ue(s)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+r-C>a){if(l){let D=c,I=this._activeBuffer.x-C;for(this._activeBuffer.x=C,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),c=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),C>0&&c instanceof St&&c.copyCellsFrom(D,I,0,C,!1);I<a;)D.setCellFromCodepoint(I++,0,1,d)}else if(this._activeBuffer.x=a-1,r===2)continue}if(p&&this._activeBuffer.x){let D=c.getWidth(this._activeBuffer.x-1)?1:2;c.addCodepointToCell(this._activeBuffer.x-D,s,r);for(let I=r-C;--I>=0;)c.setCellFromCodepoint(this._activeBuffer.x++,0,0,d);continue}if(h&&(c.insertCells(this._activeBuffer.x,r-C,this._activeBuffer.getNullCell(d)),c.getWidth(a-1)===2&&c.setCellFromCodepoint(a-1,0,1,d)),c.setCellFromCodepoint(this._activeBuffer.x++,s,r,d),r>0)for(;--r;)c.setCellFromCodepoint(this._activeBuffer.x++,0,0,d)}this._parser.precedingJoinState=u,this._activeBuffer.x<a&&i-t>0&&c.getWidth(this._activeBuffer.x)===0&&!c.hasContent(this._activeBuffer.x)&&c.setCellFromCodepoint(this._activeBuffer.x,0,1,d),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===\"t\"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,i=>pr(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new _r(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new fe(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,r=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),r),s&&(n.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i<this._bufferService.rows;i++)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(i);break;case 1:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+i)?.getTrimmedLength(););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let s=this._activeBuffer.lines.length-this._bufferService.rows;s>0&&(this._activeBuffer.lines.trimStart(s),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-s,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-s,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i=this._activeBuffer.ybase+this._activeBuffer.y,s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-s+1;for(;t--;)this._activeBuffer.lines.splice(r-1,1),this._activeBuffer.lines.splice(i,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i=this._activeBuffer.ybase+this._activeBuffer.y,s;for(s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,s=this._bufferService.rows-1+this._activeBuffer.ybase-s;t--;)this._activeBuffer.lines.splice(i,1),this._activeBuffer.lines.splice(s,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(Y));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);s.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);s.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);s.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);s.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let i=e.params[0]||1,s=Je.extractWidth(t),r=this._activeBuffer.x-s,n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(r),o=new Uint32Array(n.length*i),a=0;for(let h=0;h<n.length;){let d=n.codePointAt(h)||0;o[a++]=d,h+=d>65535?2:1}let l=a;for(let h=1;h<i;++h)o.copyWithin(l,0,a),l+=a;return this.print(o,0,l),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(\"xterm\")||this._is(\"rxvt-unicode\")||this._is(\"screen\")?this._coreService.triggerDataEvent(g.ESC+\"[?1;2c\"):this._is(\"linux\")&&this._coreService.triggerDataEvent(g.ESC+\"[?6c\")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(\"xterm\")?this._coreService.triggerDataEvent(g.ESC+\"[>0;276;0c\"):this._is(\"rxvt-unicode\")?this._coreService.triggerDataEvent(g.ESC+\"[>85;95;0c\"):this._is(\"linux\")?this._coreService.triggerDataEvent(e.params[0]+\"c\"):this._is(\"screen\")&&this._coreService.triggerDataEvent(g.ESC+\"[>83;40003;0c\")),!0}_is(e){return(this._optionsService.rawOptions.termName+\"\").indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0;break}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,Ge),this._charsetService.setgCharset(1,Ge),this._charsetService.setgCharset(2,Ge),this._charsetService.setgCharset(3,Ge);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(\"Serial port requested application keypad.\"),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=\"X10\";break;case 1e3:this._coreMouseService.activeProtocol=\"VT200\";break;case 1002:this._coreMouseService.activeProtocol=\"DRAG\";break;case 1003:this._coreMouseService.activeProtocol=\"ANY\";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(\"DECSET 1005 not supported (see #2507)\");break;case 1006:this._coreMouseService.activeEncoding=\"SGR\";break;case 1015:this._logService.debug(\"DECSET 1015 not supported (see #2507)\");break;case 1016:this._coreMouseService.activeEncoding=\"SGR_PIXELS\";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0;break}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1;break}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(\"Switching back to normal keypad.\"),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=\"NONE\";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(\"DECRST 1005 not supported (see #2507)\");break;case 1006:this._coreMouseService.activeEncoding=\"DEFAULT\";break;case 1015:this._logService.debug(\"DECRST 1015 not supported (see #2507)\");break;case 1016:this._coreMouseService.activeEncoding=\"DEFAULT\";break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0);break}return!0}requestMode(e,t){let i;(p=>(p[p.NOT_RECOGNIZED=0]=\"NOT_RECOGNIZED\",p[p.SET=1]=\"SET\",p[p.RESET=2]=\"RESET\",p[p.PERMANENTLY_SET=3]=\"PERMANENTLY_SET\",p[p.PERMANENTLY_RESET=4]=\"PERMANENTLY_RESET\"))(i||={});let s=this._coreService.decPrivateModes,{activeProtocol:r,activeEncoding:n}=this._coreMouseService,o=this._coreService,{buffers:a,cols:l}=this._bufferService,{active:h,alt:d}=a,c=this._optionsService.rawOptions,u=(p,C)=>(o.triggerDataEvent(`${g.ESC}[${t?\"\":\"?\"}${p};${C}$y`),!0),f=p=>p?1:2,_=e.params[0];return t?_===2?u(_,4):_===4?u(_,f(o.modes.insertMode)):_===12?u(_,3):_===20?u(_,f(c.convertEol)):u(_,0):_===1?u(_,f(s.applicationCursorKeys)):_===3?u(_,c.windowOptions.setWinLines?l===80?2:l===132?1:0:0):_===6?u(_,f(s.origin)):_===7?u(_,f(s.wraparound)):_===8?u(_,3):_===9?u(_,f(r===\"X10\")):_===12?u(_,f(c.cursorBlink)):_===25?u(_,f(!o.isCursorHidden)):_===45?u(_,f(s.reverseWraparound)):_===66?u(_,f(s.applicationKeypad)):_===67?u(_,4):_===1e3?u(_,f(r===\"VT200\")):_===1002?u(_,f(r===\"DRAG\")):_===1003?u(_,f(r===\"ANY\")):_===1004?u(_,f(s.sendFocus)):_===1005?u(_,4):_===1006?u(_,f(n===\"SGR\")):_===1015?u(_,4):_===1016?u(_,f(n===\"SGR_PIXELS\")):_===1048?u(_,1):_===47||_===1047||_===1049?u(_,f(h===d)):_===2004?u(_,f(s.bracketedPasteMode)):_===2026?u(_,f(s.synchronizedOutput)):u(_,0)}_updateAttrColor(e,t,i,s,r){return t===2?(e|=50331648,e&=-16777216,e|=Bt.fromColorRGB([i,s,r])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let s=[0,0,-1,0,0,0],r=0,n=0;do{if(s[n+r]=e.params[t+n],e.hasSubParams(t+n)){let o=e.getSubParams(t+n),a=0;do s[1]===5&&(r=1),s[n+a+1+r]=o[a];while(++a<o.length&&a+n+1+r<s.length);break}if(s[1]===5&&n+r>=2||s[1]===2&&n+r>=5)break;s[1]&&(r=1)}while(++n+t<e.length&&n+r<s.length);for(let o=2;o<s.length;++o)s[o]===-1&&(s[o]=0);switch(s[0]){case 38:i.fg=this._updateAttrColor(i.fg,s[1],s[3],s[4],s[5]);break;case 48:i.bg=this._updateAttrColor(i.bg,s[1],s[3],s[4],s[5]);break;case 58:i.extended=i.extended.clone(),i.extended.underlineColor=this._updateAttrColor(i.extended.underlineColor,s[1],s[3],s[4],s[5])}return n}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=Y.fg,e.bg=Y.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,i,s=this._curAttrData;for(let r=0;r<t;r++)i=e.params[r],i>=30&&i<=37?(s.fg&=-50331904,s.fg|=16777216|i-30):i>=40&&i<=47?(s.bg&=-50331904,s.bg|=16777216|i-40):i>=90&&i<=97?(s.fg&=-50331904,s.fg|=16777216|i-90|8):i>=100&&i<=107?(s.bg&=-50331904,s.bg|=16777216|i-100|8):i===0?this._processSGR0(s):i===1?s.fg|=134217728:i===3?s.bg|=67108864:i===4?(s.fg|=268435456,this._processUnderline(e.hasSubParams(r)?e.getSubParams(r)[0]:1,s)):i===5?s.fg|=536870912:i===7?s.fg|=67108864:i===8?s.fg|=1073741824:i===9?s.fg|=2147483648:i===2?s.bg|=134217728:i===21?this._processUnderline(2,s):i===22?(s.fg&=-134217729,s.bg&=-134217729):i===23?s.bg&=-67108865:i===24?(s.fg&=-268435457,this._processUnderline(0,s)):i===25?s.fg&=-536870913:i===27?s.fg&=-67108865:i===28?s.fg&=-1073741825:i===29?s.fg&=2147483647:i===39?(s.fg&=-67108864,s.fg|=Y.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=Y.bg&16777215):i===38||i===48||i===58?r+=this._extractColor(e,r,s):i===53?s.bg|=1073741824:i===55?s.bg&=-1073741825:i===59?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):i===100?(s.fg&=-67108864,s.fg|=Y.fg&16777215,s.bg&=-67108864,s.bg|=Y.bg&16777215):this._logService.debug(\"Unknown SGR attribute: %d.\",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${g.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${g.ESC}[${t};${i}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${g.ESC}[?${t};${i}R`);break;case 15:break;case 25:break;case 26:break;case 53:break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=Y.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle=\"block\";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle=\"underline\";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle=\"bar\";break}let i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!pr(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${g.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>fr&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>fr&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],i=e.split(\";\");for(;i.length>1;){let s=i.shift(),r=i.shift();if(/^\\d+$/.exec(s)){let n=parseInt(s);if(mr(n))if(r===\"?\")t.push({type:0,index:n});else{let o=ur(r);o&&t.push({type:1,index:n,color:o})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(\";\");if(t===-1)return!0;let i=e.slice(0,t).trim(),s=e.slice(t+1);return s?this._createHyperlink(i,s):i.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i=e.split(\":\"),s,r=i.findIndex(n=>n.startsWith(\"id=\"));return r!==-1&&(s=i[r].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let i=e.split(\";\");for(let s=0;s<i.length&&!(t>=this._specialColors.length);++s,++t)if(i[s]===\"?\")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=ur(i[s]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],i=e.split(\";\");for(let s=0;s<i.length;++s)if(/^\\d+$/.exec(i[s])){let r=parseInt(i[s]);mr(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(\"Serial port requested application keypad.\"),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(\"Switching back to normal keypad.\"),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,Ge),!0}selectCharset(e){return e.length!==2?(this.selectDefaultCharset(),!0):(e[0]===\"/\"||this._charsetService.setgCharset(za[e[0]],J[e[1]]||Ge),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=Y.clone(),this._eraseAttrDataInternal=Y.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new we;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let i=this._activeBuffer.ybase+this._activeBuffer.y+t,s=this._activeBuffer.lines.get(i);s&&(s.fill(e),s.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let i=o=>(this._coreService.triggerDataEvent(`${g.ESC}${o}${g.ESC}\\\\`),!0),s=this._bufferService.buffer,r=this._optionsService.rawOptions;return i(e==='\"q'?`P1$r${this._curAttrData.isProtected()?1:0}\"q`:e==='\"p'?'P1$r61;1\"p':e===\"r\"?`P1$r${s.scrollTop+1};${s.scrollBottom+1}r`:e===\"m\"?\"P1$r0m\":e===\" q\"?`P1$r${{block:2,underline:4,bar:6}[r.cursorStyle]-(r.cursorBlink?1:0)} q`:\"P0$r\")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},ls=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(vr=e,e=t,t=vr),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};ls=q([y(0,ce)],ls);function mr(e){return 0<=e&&e<256}var $a=5e7,Sr=12,Ka=50,Ua=class extends R{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new v),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let i;for(;i=this._writeBuffer.shift();){this._action(i);let s=this._callbacks.shift();s&&s()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>$a)throw new Error(\"write data discarded, use flow control to avoid losing data\");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let s=this._writeBuffer[this._bufferOffset],r=this._action(s,t);if(r){let o=a=>performance.now()-i>=Sr?setTimeout(()=>this._innerWrite(0,a)):this._innerWrite(i,a);r.catch(a=>(queueMicrotask(()=>{throw a}),Promise.resolve(!1))).then(o);return}let n=this._callbacks[this._bufferOffset];if(n&&n(),this._bufferOffset++,this._pendingData-=s.length,performance.now()-i>=Sr)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>Ka&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},cs=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let a=t.addMarker(t.ybase+t.y),l={data:e,id:this._nextId++,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(l,a)),this._dataByLinkId.set(l.id,l),l.id}let i=e,s=this._getEntryIdKey(i),r=this._entriesWithId.get(s);if(r)return this.addLineToLink(r.id,t.ybase+t.y),r.id;let n=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(o,n)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(s=>s.line!==t)){let s=this._bufferService.buffer.addMarker(t);i.lines.push(s),s.onDispose(()=>this._removeMarkerFromLink(i,s))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};cs=q([y(0,ce)],cs);var wr=!1,qa=class extends R{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new rt),this._onBinary=this._register(new v),this.onBinary=this._onBinary.event,this._onData=this._register(new v),this.onData=this._onData.event,this._onLineFeed=this._register(new v),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new v),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new v),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new v),this._instantiationService=new fa,this.optionsService=this._register(new xa(e)),this._instantiationService.setService(de,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(ns)),this._instantiationService.setService(ce,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(rs)),this._instantiationService.setService(Tr,this._logService),this.coreService=this._register(this._instantiationService.createInstance(os)),this._instantiationService.setService(tt,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(hs)),this._instantiationService.setService(Pr,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Je)),this._instantiationService.setService(In,this.unicodeService),this._charsetService=this._instantiationService.createInstance(La),this._instantiationService.setService(On,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(cs),this._instantiationService.setService(Ar,this._oscLinkService),this._inputHandler=this._register(new Fa(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(oe.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(oe.forward(this._bufferService.onResize,this._onResize)),this._register(oe.forward(this.coreService.onData,this._onData)),this._register(oe.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange([\"windowsMode\",\"windowsPty\"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new Ua((t,i)=>this._inputHandler.parse(t,i))),this._register(oe.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new v),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!wr&&(this._logService.warn(\"writeSync is unreliable and will be removed soon.\"),wr=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,yn),t=Math.max(t,Cn),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===\"conpty\"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(dr.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:\"H\"},()=>(dr(this._bufferService),!1))),this._windowsWrappingHeuristics.value=W(()=>{for(let t of e)t.dispose()})}}},Va={48:[\"0\",\")\"],49:[\"1\",\"!\"],50:[\"2\",\"@\"],51:[\"3\",\"#\"],52:[\"4\",\"$\"],53:[\"5\",\"%\"],54:[\"6\",\"^\"],55:[\"7\",\"&\"],56:[\"8\",\"*\"],57:[\"9\",\"(\"],186:[\";\",\":\"],187:[\"=\",\"+\"],188:[\",\",\"<\"],189:[\"-\",\"_\"],190:[\".\",\">\"],191:[\"/\",\"?\"],192:[\"`\",\"~\"],219:[\"[\",\"{\"],220:[\"\\\\\",\"|\"],221:[\"]\",\"}\"],222:[\"'\",'\"']};function Ya(e,t,i,s){let r={type:0,cancel:!1,key:void 0},n=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===\"UIKeyInputUpArrow\"?t?r.key=g.ESC+\"OA\":r.key=g.ESC+\"[A\":e.key===\"UIKeyInputLeftArrow\"?t?r.key=g.ESC+\"OD\":r.key=g.ESC+\"[D\":e.key===\"UIKeyInputRightArrow\"?t?r.key=g.ESC+\"OC\":r.key=g.ESC+\"[C\":e.key===\"UIKeyInputDownArrow\"&&(t?r.key=g.ESC+\"OB\":r.key=g.ESC+\"[B\");break;case 8:r.key=e.ctrlKey?\"\\b\":g.DEL,e.altKey&&(r.key=g.ESC+r.key);break;case 9:if(e.shiftKey){r.key=g.ESC+\"[Z\";break}r.key=g.HT,r.cancel=!0;break;case 13:r.key=e.altKey?g.ESC+g.CR:g.CR,r.cancel=!0;break;case 27:r.key=g.ESC,e.altKey&&(r.key=g.ESC+g.ESC),r.cancel=!0;break;case 37:if(e.metaKey)break;n?r.key=g.ESC+\"[1;\"+(n+1)+\"D\":t?r.key=g.ESC+\"OD\":r.key=g.ESC+\"[D\";break;case 39:if(e.metaKey)break;n?r.key=g.ESC+\"[1;\"+(n+1)+\"C\":t?r.key=g.ESC+\"OC\":r.key=g.ESC+\"[C\";break;case 38:if(e.metaKey)break;n?r.key=g.ESC+\"[1;\"+(n+1)+\"A\":t?r.key=g.ESC+\"OA\":r.key=g.ESC+\"[A\";break;case 40:if(e.metaKey)break;n?r.key=g.ESC+\"[1;\"+(n+1)+\"B\":t?r.key=g.ESC+\"OB\":r.key=g.ESC+\"[B\";break;case 45:!e.shiftKey&&!e.ctrlKey&&(r.key=g.ESC+\"[2~\");break;case 46:n?r.key=g.ESC+\"[3;\"+(n+1)+\"~\":r.key=g.ESC+\"[3~\";break;case 36:n?r.key=g.ESC+\"[1;\"+(n+1)+\"H\":t?r.key=g.ESC+\"OH\":r.key=g.ESC+\"[H\";break;case 35:n?r.key=g.ESC+\"[1;\"+(n+1)+\"F\":t?r.key=g.ESC+\"OF\":r.key=g.ESC+\"[F\";break;case 33:e.shiftKey?r.type=2:e.ctrlKey?r.key=g.ESC+\"[5;\"+(n+1)+\"~\":r.key=g.ESC+\"[5~\";break;case 34:e.shiftKey?r.type=3:e.ctrlKey?r.key=g.ESC+\"[6;\"+(n+1)+\"~\":r.key=g.ESC+\"[6~\";break;case 112:n?r.key=g.ESC+\"[1;\"+(n+1)+\"P\":r.key=g.ESC+\"OP\";break;case 113:n?r.key=g.ESC+\"[1;\"+(n+1)+\"Q\":r.key=g.ESC+\"OQ\";break;case 114:n?r.key=g.ESC+\"[1;\"+(n+1)+\"R\":r.key=g.ESC+\"OR\";break;case 115:n?r.key=g.ESC+\"[1;\"+(n+1)+\"S\":r.key=g.ESC+\"OS\";break;case 116:n?r.key=g.ESC+\"[15;\"+(n+1)+\"~\":r.key=g.ESC+\"[15~\";break;case 117:n?r.key=g.ESC+\"[17;\"+(n+1)+\"~\":r.key=g.ESC+\"[17~\";break;case 118:n?r.key=g.ESC+\"[18;\"+(n+1)+\"~\":r.key=g.ESC+\"[18~\";break;case 119:n?r.key=g.ESC+\"[19;\"+(n+1)+\"~\":r.key=g.ESC+\"[19~\";break;case 120:n?r.key=g.ESC+\"[20;\"+(n+1)+\"~\":r.key=g.ESC+\"[20~\";break;case 121:n?r.key=g.ESC+\"[21;\"+(n+1)+\"~\":r.key=g.ESC+\"[21~\";break;case 122:n?r.key=g.ESC+\"[23;\"+(n+1)+\"~\":r.key=g.ESC+\"[23~\";break;case 123:n?r.key=g.ESC+\"[24;\"+(n+1)+\"~\":r.key=g.ESC+\"[24~\";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?r.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?r.key=g.NUL:e.keyCode>=51&&e.keyCode<=55?r.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?r.key=g.DEL:e.keyCode===219?r.key=g.ESC:e.keyCode===220?r.key=g.FS:e.keyCode===221&&(r.key=g.GS);else if((!i||s)&&e.altKey&&!e.metaKey){let o=Va[e.keyCode]?.[e.shiftKey?1:0];if(o)r.key=g.ESC+o;else if(e.keyCode>=65&&e.keyCode<=90){let a=e.ctrlKey?e.keyCode-64:e.keyCode+32,l=String.fromCharCode(a);e.shiftKey&&(l=l.toUpperCase()),r.key=g.ESC+l}else if(e.keyCode===32)r.key=g.ESC+(e.ctrlKey?g.NUL:\" \");else if(e.key===\"Dead\"&&e.code.startsWith(\"Key\")){let a=e.code.slice(3,4);e.shiftKey||(a=a.toLowerCase()),r.key=g.ESC+a,r.cancel=!0}}else i&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(r.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?r.key=e.key:e.key&&e.ctrlKey&&(e.key===\"_\"&&(r.key=g.US),e.key===\"@\"&&(r.key=g.NUL));break}return r}var V=0,Xa=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new ii,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new ii,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((r,n)=>this._getKey(r)-this._getKey(n)),t=0,i=0,s=new Array(this._array.length+this._insertedValues.length);for(let r=0;r<s.length;r++)i>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(s[r]=e[t],t++):s[r]=this._array[i++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(V=this._search(t),V===-1)||this._getKey(this._array[V])!==t)return!1;do if(this._array[V]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(V),!0;while(++V<this._array.length&&this._getKey(this._array[V])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((r,n)=>r-n),t=0,i=new Array(this._array.length-e.length),s=0;for(let r=0;r<this._array.length;r++)e[t]===r?t++:i[s++]=this._array[r];this._array=i,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(V=this._search(e),!(V<0||V>=this._array.length)&&this._getKey(this._array[V])===e))do yield this._array[V];while(++V<this._array.length&&this._getKey(this._array[V])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(V=this._search(e),!(V<0||V>=this._array.length)&&this._getKey(this._array[V])===e))do t(this._array[V]);while(++V<this._array.length&&this._getKey(this._array[V])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,i=this._array.length-1;for(;i>=t;){let s=t+i>>1,r=this._getKey(this._array[s]);if(r>e)i=s-1;else if(r<e)t=s+1;else{for(;s>0&&this._getKey(this._array[s-1])===e;)s--;return s}}return t}},Di=0,br=0,ja=class extends R{constructor(){super(),this._decorations=new Xa(e=>e?.marker.line),this._onDecorationRegistered=this._register(new v),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new v),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(W(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new Ga(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),s=t.onDispose(()=>{s.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let s=0,r=0;for(let n of this._decorations.getKeyIterator(t))s=n.options.x??0,r=s+(n.options.width??1),e>=s&&e<r&&(!i||(n.options.layer??\"bottom\")===i)&&(yield n)}forEachDecorationAtCell(e,t,i,s){this._decorations.forEachByKey(t,r=>{Di=r.options.x??0,br=Di+(r.options.width??1),e>=Di&&e<br&&(!i||(r.options.layer??\"bottom\")===i)&&s(r)})}},Ga=class extends Ve{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new v),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new v),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position=\"full\")}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=K.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=K.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},Ja=1e3,Za=class{constructor(e,t=Ja){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t;let s=performance.now();if(s-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){let r=s-this._lastRefreshMs,n=this._debounceThresholdMS-r;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},n)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},yr=20,Cr=!1,si=class extends R{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=\"\";let r=this._coreBrowserService.mainDocument;this._accessibilityContainer=r.createElement(\"div\"),this._accessibilityContainer.classList.add(\"xterm-accessibility\"),this._rowContainer=r.createElement(\"div\"),this._rowContainer.setAttribute(\"role\",\"list\"),this._rowContainer.classList.add(\"xterm-accessibility-tree\"),this._rowElements=[];for(let n=0;n<this._terminal.rows;n++)this._rowElements[n]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[n]);if(this._topBoundaryFocusListener=n=>this._handleBoundaryFocus(n,0),this._bottomBoundaryFocusListener=n=>this._handleBoundaryFocus(n,1),this._rowElements[0].addEventListener(\"focus\",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(\"focus\",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=r.createElement(\"div\"),this._liveRegion.classList.add(\"live-region\"),this._liveRegion.setAttribute(\"aria-live\",\"assertive\"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new Za(this._renderRows.bind(this))),!this._terminal.element)throw new Error(\"Cannot enable accessibility before Terminal.open\");Cr?(this._accessibilityContainer.classList.add(\"debug\"),this._rowContainer.classList.add(\"debug\"),this._debugRootContainer=r.createElement(\"div\"),this._debugRootContainer.classList.add(\"xterm\"),this._debugRootContainer.appendChild(r.createTextNode(\"------start a11y------\")),this._debugRootContainer.appendChild(this._accessibilityContainer),this._debugRootContainer.appendChild(r.createTextNode(\"------end a11y------\")),this._terminal.element.insertAdjacentElement(\"afterend\",this._debugRootContainer)):this._terminal.element.insertAdjacentElement(\"afterbegin\",this._accessibilityContainer),this._register(this._terminal.onResize(n=>this._handleResize(n.rows))),this._register(this._terminal.onRender(n=>this._refreshRows(n.start,n.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(n=>this._handleChar(n))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`\r\n`))),this._register(this._terminal.onA11yTab(n=>this._handleTab(n))),this._register(this._terminal.onKey(n=>this._handleKey(n.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(B(r,\"selectionchange\",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(W(()=>{Cr?this._debugRootContainer.remove():this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(\" \")}_handleChar(e){this._liveRegionLineCount<yr+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`\r\n`&&(this._liveRegionLineCount++,this._liveRegionLineCount===yr+1&&(this._liveRegion.textContent+=Ri.get())))}_clearLiveRegion(){this._liveRegion.textContent=\"\",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,s=i.lines.length.toString();for(let r=e;r<=t;r++){let n=i.lines.get(i.ydisp+r),o=[],a=n?.translateToString(!0,void 0,void 0,o)||\"\",l=(i.ydisp+r+1).toString(),h=this._rowElements[r];h&&(a.length===0?(h.textContent=\"\\xA0\",this._rowColumns.set(h,[0,1])):(h.textContent=a,this._rowColumns.set(h,o)),h.setAttribute(\"aria-posinset\",l),h.setAttribute(\"aria-setsize\",s),this._alignRowWidth(h))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=\"\")}_handleBoundaryFocus(e,t){let i=e.target,s=this._rowElements[t===0?1:this._rowElements.length-2],r=i.getAttribute(\"aria-posinset\"),n=t===0?\"1\":`${this._terminal.buffer.lines.length}`;if(r===n||e.relatedTarget!==s)return;let o,a;if(t===0?(o=i,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(o=this._rowElements.shift(),a=i,this._rowContainer.removeChild(o)),o.removeEventListener(\"focus\",this._topBoundaryFocusListener),a.removeEventListener(\"focus\",this._bottomBoundaryFocusListener),t===0){let l=this._createAccessibilityTreeNode();this._rowElements.unshift(l),this._rowContainer.insertAdjacentElement(\"afterbegin\",l)}else{let l=this._createAccessibilityTreeNode();this._rowElements.push(l),this._rowContainer.appendChild(l)}this._rowElements[0].addEventListener(\"focus\",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(\"focus\",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(\"anchorNode and/or focusNode are null\");return}let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let s=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:s,offset:s.textContent?.length??0}),!this._rowContainer.contains(i.node))return;let r=({node:a,offset:l})=>{let h=a instanceof Text?a.parentNode:a,d=parseInt(h?.getAttribute(\"aria-posinset\"),10)-1;if(isNaN(d))return console.warn(\"row is invalid. Race condition?\"),null;let c=this._rowColumns.get(h);if(!c)return console.warn(\"columns is null. Race condition?\"),null;let u=l<c.length?c[l]:c.slice(-1)[0]+1;return u>=this._terminal.cols&&(++d,u=0),{row:d,column:u}},n=r(t),o=r(i);if(!(!n||!o)){if(n.row>o.row||n.row===o.row&&n.column>=o.column)throw new Error(\"invalid range\");this._terminal.select(n.column,n.row,(o.row-n.row)*this._terminal.cols-n.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(\"focus\",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;t<this._terminal.rows;t++)this._rowElements[t]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[t]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(\"focus\",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(\"div\");return e.setAttribute(\"role\",\"listitem\"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=\"\";let t=e.getBoundingClientRect().width,i=this._rowColumns.get(e)?.slice(-1)?.[0];if(!i)return;let s=i*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${s/t})`}};si=q([y(1,_s),y(2,Oe),y(3,Ie)],si);var ds=class extends R{constructor(e,t,i,s,r){super(),this._element=e,this._mouseService=t,this._renderService=i,this._bufferService=s,this._linkProviderService=r,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new v),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new v),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(W(()=>{Qe(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(B(this._element,\"mouseleave\",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(B(this._element,\"mousemove\",this._handleMouseMove.bind(this))),this._register(B(this._element,\"mousedown\",this._handleMouseDown.bind(this))),this._register(B(this._element,\"mouseup\",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let i=e.composedPath();for(let s=0;s<i.length;s++){let r=i[s];if(r.classList.contains(\"xterm\"))break;if(r.classList.contains(\"xterm-hover\"))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){if(this._activeLine!==e.y||this._wasResized){this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1;return}this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(s=>{s?.forEach(r=>{r.link.dispose&&r.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(let[s,r]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(s)&&(i=this._checkLinkProviderResult(s,e,i)):r.provideLinks(e.y,n=>{if(this._isMouseOut)return;let o=n?.map(a=>({link:a}));this._activeProviderReplies?.set(s,o),i=this._checkLinkProviderResult(s,e,i),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let s=0;s<t.size;s++){let r=t.get(s);if(r)for(let n=0;n<r.length;n++){let o=r[n],a=o.link.range.start.y<e?0:o.link.range.start.x,l=o.link.range.end.y>e?this._bufferService.cols:o.link.range.end.x;for(let h=a;h<=l;h++){if(i.has(h)){r.splice(n--,1);break}i.add(h)}}}}_checkLinkProviderResult(e,t,i){if(!this._activeProviderReplies)return i;let s=this._activeProviderReplies.get(e),r=!1;for(let n=0;n<e;n++)(!this._activeProviderReplies.has(n)||this._activeProviderReplies.get(n))&&(r=!0);if(!r&&s){let n=s.find(o=>this._linkAtPosition(o.link,t));n&&(i=!0,this._handleNewLink(n))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let n=0;n<this._activeProviderReplies.size;n++){let o=this._activeProviderReplies.get(n)?.find(a=>this._linkAtPosition(a.link,t));if(o){i=!0,this._handleNewLink(o);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&Qa(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,Qe(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:i=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle(\"xterm-cursor-pointer\",i))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:i=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let s=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,r=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=r&&(this._clearCurrentLink(s,r),this._lastMouseEvent)){let n=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);n&&this._askForLink(n,!1)}})))}_linkHover(e,t,i){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(\"xterm-cursor-pointer\")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,s=this._bufferService.buffer.ydisp,r=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(r)}_linkLeave(e,t,i){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(\"xterm-cursor-pointer\")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,r=t.y*this._bufferService.cols+t.x;return i<=r&&r<=s}_positionFromMouseEvent(e,t,i){let s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,r){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:r}}};ds=q([y(1,us),y(2,Ie),y(3,ce),y(4,Ir)],ds);function Qa(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var el=class extends qa{constructor(e={}){super(e),this._linkifier=this._register(new rt),this.browser=dn,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new rt),this._onCursorMove=this._register(new v),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new v),this.onKey=this._onKey.event,this._onRender=this._register(new v),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new v),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new v),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new v),this.onBell=this._onBell.event,this._onFocus=this._register(new v),this._onBlur=this._register(new v),this._onA11yCharEmitter=this._register(new v),this._onA11yTabEmitter=this._register(new v),this._onWillOpen=this._register(new v),this._setup(),this._decorationService=this._instantiationService.createInstance(ja),this._instantiationService.setService(Rt,this._decorationService),this._linkProviderService=this._instantiationService.createInstance($h),this._instantiationService.setService(Ir,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Mi)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh(t?.start??0,t?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(oe.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(oe.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(oe.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(oe.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(W(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let i,s=\"\";switch(t.index){case 256:i=\"foreground\",s=\"10\";break;case 257:i=\"background\",s=\"11\";break;case 258:i=\"cursor\",s=\"12\";break;default:i=\"ansi\",s=\"4;\"+t.index}switch(t.type){case 0:let r=H.toColorRGB(i===\"ansi\"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${g.ESC}]${s};${Wa(r)}${ln.ST}`);break;case 1:if(i===\"ansi\")this._themeService.modifyColors(n=>n.ansi[t.index]=X.toColor(...t.color));else{let n=i;this._themeService.modifyColors(o=>o[n]=X.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(si,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(g.ESC+\"[I\"),this.element.classList.add(\"focus\"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=\"\",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(g.ESC+\"[O\"),this.element.classList.remove(\"focus\"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,r=t.getWidth(i),n=this._renderService.dimensions.css.cell.width*r,o=this.buffer.y*this._renderService.dimensions.css.cell.height,a=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=a+\"px\",this.textarea.style.top=o+\"px\",this.textarea.style.width=n+\"px\",this.textarea.style.height=s+\"px\",this.textarea.style.lineHeight=s+\"px\",this.textarea.style.zIndex=\"-5\"}_initGlobal(){this._bindKeys(),this._register(B(this.element,\"copy\",t=>{this.hasSelection()&&Rn(t,this._selectionService)}));let e=t=>Ln(t,this.textarea,this.coreService,this.optionsService);this._register(B(this.textarea,\"paste\",e)),this._register(B(this.element,\"paste\",e)),_n?this._register(B(this.element,\"mousedown\",t=>{t.button===2&&ks(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(B(this.element,\"contextmenu\",t=>{ks(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),bs&&this._register(B(this.element,\"auxclick\",t=>{t.button===1&&Dr(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(B(this.textarea,\"keyup\",e=>this._keyUp(e),!0)),this._register(B(this.textarea,\"keydown\",e=>this._keyDown(e),!0)),this._register(B(this.textarea,\"keypress\",e=>this._keyPress(e),!0)),this._register(B(this.textarea,\"compositionstart\",()=>this._compositionHelper.compositionstart())),this._register(B(this.textarea,\"compositionupdate\",e=>this._compositionHelper.compositionupdate(e))),this._register(B(this.textarea,\"compositionend\",()=>this._compositionHelper.compositionend())),this._register(B(this.textarea,\"input\",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw new Error(\"Terminal requires a parent element.\");if(e.isConnected||this._logService.debug(\"Terminal.open was called on an element that was not attached to the DOM\"),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(\"div\"),this.element.dir=\"ltr\",this.element.classList.add(\"terminal\"),this.element.classList.add(\"xterm\"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(\"div\"),this._viewportElement.classList.add(\"xterm-viewport\"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(\"div\"),this.screenElement.classList.add(\"xterm-screen\"),this._register(B(this.screenElement,\"mousemove\",r=>this.updateCursorStyle(r))),this._helperContainer=this._document.createElement(\"div\"),this._helperContainer.classList.add(\"xterm-helpers\"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let i=this.textarea=this._document.createElement(\"textarea\");this.textarea.classList.add(\"xterm-helper-textarea\"),this.textarea.setAttribute(\"aria-label\",Bi.get()),pn||this.textarea.setAttribute(\"aria-multiline\",\"false\"),this.textarea.setAttribute(\"autocorrect\",\"off\"),this.textarea.setAttribute(\"autocapitalize\",\"off\"),this.textarea.setAttribute(\"spellcheck\",\"false\"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange(\"disableStdin\",()=>i.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(zh,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<\"u\"?window.document:null)),this._instantiationService.setService(Oe,this._coreBrowserService),this._register(B(this.textarea,\"focus\",r=>this._handleTextAreaFocus(r))),this._register(B(this.textarea,\"blur\",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(Qi,this._document,this._helperContainer),this._instantiationService.setService(ni,this._charSizeService),this._themeService=this._instantiationService.createInstance(ss),this._instantiationService.setService(nt,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(ei),this._instantiationService.setService(Or,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(ts,this.rows,this.screenElement)),this._instantiationService.setService(Ie,this._renderService),this._register(this._renderService.onRenderedViewportChange(r=>this._onRender.fire(r))),this.onResize(r=>this._renderService.resize(r.cols,r.rows)),this._compositionView=this._document.createElement(\"div\"),this._compositionView.classList.add(\"composition-view\"),this._compositionHelper=this._instantiationService.createInstance(Gi,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(es),this._instantiationService.setService(us,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(ds,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(Xi,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(r=>{super.scrollLines(r,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(is,this.element,this.screenElement,s)),this._instantiationService.setService(Hn,this._selectionService),this._register(this._selectionService.onRequestScrollLines(r=>this.scrollLines(r.amount,r.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(r=>this._renderService.handleSelectionChanged(r.start,r.end,r.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(r=>{this.textarea.value=r,this.textarea.focus(),this.textarea.select()})),this._register(oe.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(ji,this.screenElement)),this._register(B(this.element,\"mousedown\",r=>this._selectionService.handleMouseDown(r))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add(\"enable-mouse-events\")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(si,this)),this._register(this.optionsService.onSpecificOptionChange(\"screenReaderMode\",r=>this._handleScreenReaderModeOptionChange(r))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Qt,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(\"overviewRuler\",r=>{!this._overviewRulerRenderer&&r&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Qt,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(Zi,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(n){let o=e._mouseService.getMouseReportCoords(n,e.screenElement);if(!o)return!1;let a,l;switch(n.overrideType||n.type){case\"mousemove\":l=32,n.buttons===void 0?(a=3,n.button!==void 0&&(a=n.button<3?n.button:3)):a=n.buttons&1?0:n.buttons&4?1:n.buttons&2?2:3;break;case\"mouseup\":l=0,a=n.button<3?n.button:3;break;case\"mousedown\":l=1,a=n.button<3?n.button:3;break;case\"wheel\":if(e._customWheelEventHandler&&e._customWheelEventHandler(n)===!1)return!1;let h=n.deltaY;if(h===0||e.coreMouseService.consumeWheelEvent(n,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;l=h<0?0:1,a=4;break;default:return!1}return l===void 0||a===void 0||a>4?!1:e.coreMouseService.triggerMouseEvent({col:o.col,row:o.row,x:o.x,y:o.y,button:a,action:l,ctrl:n.ctrlKey,alt:n.altKey,shift:n.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},r={mouseup:n=>(i(n),n.buttons||(this._document.removeEventListener(\"mouseup\",s.mouseup),s.mousedrag&&this._document.removeEventListener(\"mousemove\",s.mousedrag)),this.cancel(n)),wheel:n=>(i(n),this.cancel(n,!0)),mousedrag:n=>{n.buttons&&i(n)},mousemove:n=>{n.buttons||i(n)}};this._register(this.coreMouseService.onProtocolChange(n=>{n?(this.optionsService.rawOptions.logLevel===\"debug\"&&this._logService.debug(\"Binding to mouse events:\",this.coreMouseService.explainEvents(n)),this.element.classList.add(\"enable-mouse-events\"),this._selectionService.disable()):(this._logService.debug(\"Unbinding from mouse events.\"),this.element.classList.remove(\"enable-mouse-events\"),this._selectionService.enable()),n&8?s.mousemove||(t.addEventListener(\"mousemove\",r.mousemove),s.mousemove=r.mousemove):(t.removeEventListener(\"mousemove\",s.mousemove),s.mousemove=null),n&16?s.wheel||(t.addEventListener(\"wheel\",r.wheel,{passive:!1}),s.wheel=r.wheel):(t.removeEventListener(\"wheel\",s.wheel),s.wheel=null),n&2?s.mouseup||(s.mouseup=r.mouseup):(this._document.removeEventListener(\"mouseup\",s.mouseup),s.mouseup=null),n&4?s.mousedrag||(s.mousedrag=r.mousedrag):(this._document.removeEventListener(\"mousemove\",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(B(t,\"mousedown\",n=>{if(n.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(n)))return i(n),s.mouseup&&this._document.addEventListener(\"mouseup\",s.mouseup),s.mousedrag&&this._document.addEventListener(\"mousemove\",s.mousedrag),this.cancel(n)})),this._register(B(t,\"wheel\",n=>{if(!s.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(n)===!1)return!1;if(!this.buffer.hasScrollback){if(n.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(n,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(n,!0);let o=g.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?\"O\":\"[\")+(n.deltaY<0?\"A\":\"B\");return this.coreService.triggerDataEvent(o,!0),this.cancel(n,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add(\"column-select\"):this.element.classList.remove(\"column-select\")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){Er(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error(\"Terminal must be opened first\");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error(\"Terminal must be opened first\");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:\"\"}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key===\"Dead\"||e.key===\"AltGraph\")&&(this._unprocessedDeadKey=!0);let i=Ya(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),i.type===3||i.type===2){let s=this.rows-1;return this.scrollLines(i.type===2?-s:s),this.cancel(e,!0)}if(i.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((i.key===g.ETX||i.key===g.CR)&&(this.textarea.value=\"\"),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState(\"AltGraph\");return t.type===\"keypress\"?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(tl(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType===\"insertText\"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(Y));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains(\"focus\")?this.coreService.triggerDataEvent(g.ESC+\"[I\"):this.coreService.triggerDataEvent(g.ESC+\"[O\")}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let t=this._renderService.dimensions.css.canvas.width.toFixed(0),i=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${g.ESC}[4;${i};${t}t`);break;case 1:let s=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${g.ESC}[6;${r};${s}t`);break}}cancel(e,t){if(!(!this.options.cancelEvents&&!t))return e.preventDefault(),e.stopPropagation(),!1}};function tl(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var il=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i<this._addons.length;i++)if(this._addons[i]===e){t=i;break}if(t===-1)throw new Error(\"Could not dispose an addon that has not been loaded\");e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},sl=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new we)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},kr=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new sl(t)}getNullCell(){return new we}},rl=class extends R{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new v),this.onBufferChange=this._onBufferChange.event,this._normal=new kr(this._core.buffers.normal,\"normal\"),this._alternate=new kr(this._core.buffers.alt,\"alternate\"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error(\"Active buffer is neither normal nor alternate\")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},nl=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,i=>t(i.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(i,s)=>t(i,s.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},ol=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},hl=[\"cols\",\"rows\"],Ee=0,al=class extends R{constructor(e){super(),this._core=this._register(new el(e)),this._addonManager=this._register(new il),this._publicOptions={...this._core.options};let t=s=>this._core.options[s],i=(s,r)=>{this._checkReadonlyOptions(s),this._core.options[s]=r};for(let s in this._core.options){let r={get:t.bind(this,s),set:i.bind(this,s)};Object.defineProperty(this._publicOptions,s,r)}}_checkReadonlyOptions(e){if(hl.includes(e))throw new Error(`Option \"${e}\" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error(\"You must set the allowProposedApi option to true to use proposed API\")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new nl(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new ol(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new rl(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=\"none\";switch(this._core.coreMouseService.activeProtocol){case\"X10\":t=\"x10\";break;case\"VT200\":t=\"vt200\";break;case\"DRAG\":t=\"drag\";break;case\"ANY\":t=\"any\";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\\r\r\n`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Bi.get()},set promptLabel(e){Bi.set(e)},get tooMuchOutput(){return Ri.get()},set tooMuchOutput(e){Ri.set(e)}}}_verifyIntegers(...e){for(Ee of e)if(Ee===1/0||isNaN(Ee)||Ee%1!==0)throw new Error(\"This API only accepts integers\")}_verifyPositiveIntegers(...e){for(Ee of e)if(Ee&&(Ee===1/0||isNaN(Ee)||Ee%1!==0||Ee<0))throw new Error(\"This API only accepts positive integers\")}};var ll=2,cl=1,dl=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,i=window.getComputedStyle(this._terminal.element.parentElement),s=parseInt(i.getPropertyValue(\"height\")),r=Math.max(0,parseInt(i.getPropertyValue(\"width\"))),n=window.getComputedStyle(this._terminal.element),o={top:parseInt(n.getPropertyValue(\"padding-top\")),bottom:parseInt(n.getPropertyValue(\"padding-bottom\")),right:parseInt(n.getPropertyValue(\"padding-right\")),left:parseInt(n.getPropertyValue(\"padding-left\"))},a=o.top+o.bottom,l=o.right+o.left,h=s-a,d=r-l-t;return{cols:Math.max(ll,Math.floor(d/e.css.cell.width)),rows:Math.max(cl,Math.floor(h/e.css.cell.height))}}};export{dl as FitAddon,al as Terminal};\r\n/*! Bundled license information:\r\n\r\n@xterm/xterm/lib/xterm.mjs:\r\n@xterm/addon-fit/lib/addon-fit.mjs:\r\n (**\r\n * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.\r\n * @license MIT\r\n *\r\n * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)\r\n * @license MIT\r\n *\r\n * Originally forked from (with the author's permission):\r\n * Fabrice Bellard's javascript vt100 for jslinux:\r\n * http://bellard.org/jslinux/\r\n * Copyright (c) 2011 Fabrice Bellard\r\n *)\r\n*/\r\n","vendor/xstate.js":"/**\r\n * Bundled by jsDelivr using Rollup v2.79.2 and Terser v5.39.0.\r\n * Original file: /npm/xstate@5.30.0/dist/xstate.esm.js\r\n *\r\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\r\n */\r\nvar t=\"undefined\"!=typeof global?global:\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{};function e(){const e=\"undefined\"!=typeof globalThis?globalThis:\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:void 0!==t?t:void 0;if(e.__xstate__)return e.__xstate__}const s=t=>{if(\"undefined\"==typeof window)return;const s=e();s&&s.register(t)};class n{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const o=\"xstate.init\",i=\"xstate.stop\";function r(t,e){return{type:`xstate.done.state.${t}`,output:e}}function c(t,e){return{type:`xstate.error.actor.${t}`,error:e,actorId:t}}function a(t){return{type:o,input:t}}function u(t){setTimeout((()=>{throw t}))}const h=\"function\"==typeof Symbol&&Symbol.observable||\"@@observable\";function f(t,e){const s=p(t),n=p(e);return\"string\"==typeof n?\"string\"==typeof s&&n===s:\"string\"==typeof s?s in n:Object.keys(s).every((t=>t in n&&f(s[t],n[t])))}function d(t){if(_(t))return t;const e=[];let s=\"\";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s=\"\";continue}s+=t[n]}return e.push(s),e}function p(t){if(Lt(t))return t.value;if(\"string\"!=typeof t)return t;return l(d(t))}function l(t){if(1===t.length)return t[0];const e={};let s=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)s[t[e]]=t[e+1];else{const n=s;s={},n[t[e]]=s}return e}function y(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const i=n[o];s[i]=e(t[i],i,t,o)}return s}function g(t){return _(t)?t:[t]}function v(t){return void 0===t?[]:g(t)}function m(t,e,s,n){return\"function\"==typeof t?t({context:e,event:s,self:n}):t}function _(t){return Array.isArray(t)}function b(t){return g(t).map((t=>void 0===t||\"string\"==typeof t?{target:t}:t))}function x(t){if(void 0!==t&&\"\"!==t)return v(t)}function S(t,e,s){const n=\"object\"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function w(t,e){return`${e}.${t}`}function I(t,e){const s=e.match(/^xstate\\.invoke\\.(\\d+)\\.(.*)/);if(!s)return t.implementations.actors[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke;return(Array.isArray(i)?i[n]:i).src}function k(t){return[...new Set([...t._nodes.flatMap((t=>t.ownEvents))])]}function E(t,e){if(e===t)return!0;if(\"*\"===e)return!0;if(!e.endsWith(\".*\"))return!1;const s=e.split(\".\"),n=t.split(\".\");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if(\"*\"===e){return t===s.length-1}if(e!==o)return!1}return!0}function $(t,e){return`${t.sessionId}.${e}`}let T=0;let O=!1;let j=function(t){return t[t.NotStarted=0]=\"NotStarted\",t[t.Running=1]=\"Running\",t[t.Stopped=2]=\"Stopped\",t}({});const A={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class N{constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new n(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=j.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const s={...A,...e},{clock:o,logger:i,parent:r,syncSnapshot:c,id:a,systemId:h,inspect:f}=s;this.system=r?r.system:function(t,e){const s=new Map,n=new Map,o=new WeakMap,i=new Set,r={},{clock:c,logger:a}=e,u={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},a=$(t,o);h._snapshot._scheduledEvents[a]=i;const u=c.setTimeout((()=>{delete r[a],delete h._snapshot._scheduledEvents[a],h._relay(t,e,s)}),n);r[a]=u},cancel:(t,e)=>{const s=$(t,e),n=r[s];delete r[s],delete h._snapshot._scheduledEvents[s],void 0!==n&&c.clearTimeout(n)},cancelAll:t=>{for(const e in h._snapshot._scheduledEvents){const s=h._snapshot._scheduledEvents[e];s.source===t&&u.cancel(t,s.id)}}},h={_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>\"x:\"+T++,_register:(t,e)=>(s.set(t,e),t),_unregister:t=>{s.delete(t.sessionId);const e=o.get(t);void 0!==e&&(n.delete(e),o.delete(t))},get:t=>n.get(t),getAll:()=>Object.fromEntries(n.entries()),_set:(t,e)=>{const s=n.get(t);if(s&&s!==e)throw new Error(`Actor with system ID '${t}' already exists.`);n.set(t,e),o.set(e,t)},inspect:t=>{const e=S(t);return i.add(e),{unsubscribe(){i.delete(e)}}},_sendInspectionEvent:e=>{if(!i.size)return;const s={...e,rootId:t.sessionId};i.forEach((t=>t.next?.(s)))},_relay:(t,e,s)=>{h._sendInspectionEvent({type:\"@xstate.event\",sourceRef:t,actorRef:e,event:s}),e._send(s)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...h._snapshot._scheduledEvents}}),start:()=>{const t=h._snapshot._scheduledEvents;h._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];u.schedule(s,n,o,i,r)}},_clock:c,_logger:a};return h}(this,{clock:o,logger:i}),f&&!r&&this.system.inspect(S(f)),this.sessionId=this.system._bookId(),this.id=a??this.sessionId,this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=r,this._syncSnapshot=c,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()},emit:t=>{const e=this.eventListeners.get(t.type),s=this.eventListeners.get(\"*\");if(!e&&!s)return;const n=[...e?e.values():[],...s?s.values():[]];for(const e of n)try{e(t)}catch(t){u(t)}},actionExecutor:t=>{const e=()=>{if(this._actorScope.system._sendInspectionEvent({type:\"@xstate.action\",actorRef:this,action:{type:t.type,params:t.params}}),!t.exec)return;const e=O;try{O=!0,t.exec(t.info,t.params)}finally{O=e}};this._processingStatus===j.Running?e():this._deferred.push(e)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:\"@xstate.actor\",actorRef:this}),h&&(this.systemId=h,this.system._set(h,this)),this._initState(e?.snapshot??e?.state),h&&\"active\"!==this._snapshot.status&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:\"error\",output:void 0,error:t}}}update(t,e){let s;for(this._snapshot=t;s=this._deferred.shift();)try{s()}catch(e){this._deferred.length=0,this._snapshot={...t,status:\"error\",error:e}}switch(this._snapshot.status){case\"active\":for(const e of this.observers)try{e.next?.(t)}catch(t){u(t)}break;case\"done\":for(const e of this.observers)try{e.next?.(t)}catch(t){u(t)}this._stopProcedure(),this._complete(),this._doneEvent=(n=this.id,o=this._snapshot.output,{type:`xstate.done.actor.${n}`,output:o,actorId:n}),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case\"error\":this._error(this._snapshot.error)}var n,o;this.system._sendInspectionEvent({type:\"@xstate.snapshot\",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){const n=S(t,e,s);if(this._processingStatus!==j.Stopped)this.observers.add(n);else switch(this._snapshot.status){case\"done\":try{n.complete?.()}catch(t){u(t)}break;case\"error\":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){u(t)}else u(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const n=e.bind(void 0);return s.add(n),{unsubscribe:()=>{s.delete(n)}}}select(t,e=Object.is){return{subscribe:s=>{const n=S(s),o=this.getSnapshot();let i=t(o);return this.subscribe((s=>{const o=t(s);e(i,o)||(i=o,n.next?.(o))}))},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===j.Running)return this;this._syncSnapshot&&this.subscribe({next:t=>{\"active\"===t.status&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=j.Running;const t=a(this.options.input);this.system._sendInspectionEvent({type:\"@xstate.event\",sourceRef:this._parent,actorRef:this,event:t});switch(this._snapshot.status){case\"done\":return this.update(this._snapshot,t),this;case\"error\":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(t){return this._snapshot={...this._snapshot,status:\"error\",error:t},this._error(t),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){s={err:t}}if(s){const{err:t}=s;return this._snapshot={...this._snapshot,status:\"error\",error:t},void this._error(t)}this.update(e,t),t.type===i&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===j.Stopped?this:(this.mailbox.clear(),this._processingStatus===j.NotStarted?(this._processingStatus=j.Stopped,this):(this.mailbox.enqueue({type:i}),this))}stop(){if(this._parent)throw new Error(\"A non-root actor cannot be stopped directly.\");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){u(t)}this.observers.clear(),this.eventListeners.clear()}_reportError(t){if(!this.observers.size)return this._parent||u(t),void this.eventListeners.clear();let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){u(t)}}this.observers.clear(),this.eventListeners.clear(),e&&u(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,c(this.id,t))}_stopProcedure(){return this._processingStatus!==j.Running||(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new n(this._process.bind(this)),this._processingStatus=j.Stopped,this.system._unregister(this)),this}_send(t){this._processingStatus!==j.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;if(t){(\"function\"==typeof t?t:s)(this)}}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[h](){return this}getSnapshot(){return this._snapshot}}function M(t,...[e]){return new N(t,e)}const P=M;function R(t,e,s,n,{sendId:o}){return[e,{sendId:\"function\"==typeof o?o(s,n):o},void 0]}function C(t,e){t.defer((()=>{t.system.scheduler.cancel(t.self,e.sendId)}))}function D(t){function e(t,e){}return e.type=\"xstate.cancel\",e.sendId=t,e.resolve=R,e.execute=C,e}function V(t,e,s,n,{id:o,systemId:i,src:r,input:c,syncSnapshot:a}){const u=\"string\"==typeof r?I(e.machine,r):r,h=\"function\"==typeof o?o(s):o;let f,d;return u&&(d=\"function\"==typeof c?c({context:e.context,event:s.event,self:t.self}):c,f=M(u,{id:h,src:r,parent:t.self,syncSnapshot:a,systemId:i,input:d})),[Gt(e,{children:{...e.children,[h]:f}}),{id:o,systemId:i,actorRef:f,src:r,input:d},void 0]}function J(t,{actorRef:e}){e&&t.defer((()=>{e._processingStatus!==j.Stopped&&e.start()}))}function L(...[t,{id:e,systemId:s,input:n,syncSnapshot:o=!1}={}]){function i(t,e){}return i.type=\"xstate.spawnChild\",i.id=e,i.systemId=s,i.src=t,i.input=n,i.syncSnapshot=o,i.resolve=V,i.execute=J,i}function B(t,e,s,n,{actorRef:o}){const i=\"function\"==typeof o?o(s,n):o,r=\"string\"==typeof i?e.children[i]:i;let c=e.children;return r&&(c={...c},delete c[r.id]),[Gt(e,{children:c}),r,void 0]}function z(t,e){const s=e.getSnapshot();if(s&&\"children\"in s)for(const e of Object.values(s.children))z(t,e);t.system._unregister(e)}function W(t,e){e&&(z(t,e),e._processingStatus===j.Running?t.defer((()=>{t.stopChild(e)})):t.stopChild(e))}function q(t){function e(t,e){}return e.type=\"xstate.stopChild\",e.actorRef=t,e.resolve=B,e.execute=W,e}const U=q;function Q(t,e,{stateValue:s}){if(\"string\"==typeof s&&ut(s)){const e=t.machine.getStateNodeById(s);return t._nodes.some((t=>t===e))}return t.matches(s)}function G(t){function e(){return!1}return e.check=Q,e.stateValue=t,e}function F(t,{context:e,event:s},{guards:n}){return!tt(n[0],e,s,t)}function H(t){function e(t,e){return!1}return e.check=F,e.guards=[t],e}function K(t,{context:e,event:s},{guards:n}){return n.every((n=>tt(n,e,s,t)))}function X(t){function e(t,e){return!1}return e.check=K,e.guards=t,e}function Y(t,{context:e,event:s},{guards:n}){return n.some((n=>tt(n,e,s,t)))}function Z(t){function e(t,e){return!1}return e.check=Y,e.guards=t,e}function tt(t,e,s,n){const{machine:o}=n,i=\"function\"==typeof t,r=i?t:o.implementations.guards[\"string\"==typeof t?t:t.type];if(!i&&!r)throw new Error(`Guard '${\"string\"==typeof t?t:t.type}' is not implemented.'.`);if(\"function\"!=typeof r)return tt(r,e,s,n);const c={context:e,event:s},a=i||\"string\"==typeof t?void 0:\"params\"in t?\"function\"==typeof t.params?t.params({context:e,event:s}):t.params:void 0;if(!(\"check\"in r))return r(c,a);return r.check(n,c,r)}function et(t){return\"atomic\"===t.type||\"final\"===t.type}function st(t){return Object.values(t.states).filter((t=>\"history\"!==t.type))}function nt(t,e){const s=[];if(e===t)return s;let n=t.parent;for(;n&&n!==e;)s.push(n),n=n.parent;return s}function ot(t){const e=new Set(t),s=rt(e);for(const t of e)if(\"compound\"!==t.type||s.get(t)&&s.get(t).length){if(\"parallel\"===t.type)for(const s of st(t))if(\"history\"!==s.type&&!e.has(s)){const t=lt(s);for(const s of t)e.add(s)}}else lt(t).forEach((t=>e.add(t)));for(const t of e){let s=t.parent;for(;s;)e.add(s),s=s.parent}return e}function it(t,e){const s=e.get(t);if(!s)return{};if(\"compound\"===t.type){const t=s[0];if(!t)return{};if(et(t))return t.key}const n={};for(const t of s)n[t.key]=it(t,e);return n}function rt(t){const e=new Map;for(const s of t)e.has(s)||e.set(s,[]),s.parent&&(e.has(s.parent)||e.set(s.parent,[]),e.get(s.parent).push(s));return e}function ct(t,e){return it(t,rt(ot(e)))}function at(t,e){return\"compound\"===e.type?st(e).some((e=>\"final\"===e.type&&t.has(e))):\"parallel\"===e.type?st(e).every((e=>at(t,e))):\"final\"===e.type}const ut=t=>\"#\"===t[0];function ht(t){const e=t.config.after;if(!e)return[];const s=Object.keys(e).flatMap((s=>{const n=e[s],o=\"string\"==typeof n?{target:n}:n,i=Number.isNaN(+s)?s:+s,r=(e=>{const s=(n=e,o=t.id,{type:`xstate.after.${n}.${o}`});var n,o;const i=s.type;return t.entry.push(Yt(s,{id:i,delay:e})),t.exit.push(D(i)),i})(i);return v(o).map((t=>({...t,event:r,delay:i})))}));return s.map((e=>{const{delay:s}=e;return{...ft(t,e.event,e),delay:s}}))}function ft(t,e,s){const n=x(s.target),o=s.reenter??!1,i=function(t,e){if(void 0===e)return;return e.map((e=>{if(\"string\"!=typeof e)return e;if(ut(e))return t.machine.getStateNodeById(e);const s=\".\"===e[0];if(s&&!t.parent)return vt(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: \"${e}\" is not a valid target from the root node. Did you mean \".${e}\"?`);try{return vt(t.parent,n)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\\n${e.message}`)}}))}(t,n),r={...s,actions:v(s.actions),guard:s.guard,target:i,source:t,reenter:o,eventType:e,toJSON:()=>({...r,source:`#${t.id}`,target:i?i.map((t=>`#${t.id}`)):void 0})};return r}function dt(t){const e=x(t.config.target);return e?{target:e.map((e=>\"string\"==typeof e?vt(t.parent,e):e))}:t.parent.initial}function pt(t){return\"history\"===t.type}function lt(t){const e=yt(t);for(const s of e)for(const n of nt(s,t))e.add(n);return e}function yt(t){const e=new Set;return function t(s){if(!e.has(s))if(e.add(s),\"compound\"===s.type)t(s.initial.target[0]);else if(\"parallel\"===s.type)for(const e of st(s))t(e)}(t),e}function gt(t,e){if(ut(e))return t.machine.getStateNodeById(e);if(!t.states)throw new Error(`Unable to retrieve child state '${e}' from '${t.id}'; no child states exist.`);const s=t.states[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function vt(t,e){if(\"string\"==typeof e&&ut(e))try{return t.machine.getStateNodeById(e)}catch{}const s=d(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=gt(n,t)}return n}function mt(t,e){if(\"string\"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=s.map((e=>gt(t,e))).filter(Boolean);return[t.machine.root,t].concat(n,s.reduce(((s,n)=>{const o=gt(t,n);if(!o)return s;const i=mt(o,e[n]);return s.concat(i)}),[]))}function _t(t,e,s,n){return\"string\"==typeof e?function(t,e,s,n){const o=gt(t,e).next(s,n);return o&&o.length?o:t.next(s,n)}(t,e,s,n):1===Object.keys(e).length?function(t,e,s,n){const o=Object.keys(e),i=_t(gt(t,o[0]),e[o[0]],s,n);return i&&i.length?i:t.next(s,n)}(t,e,s,n):function(t,e,s,n){const o=[];for(const i of Object.keys(e)){const r=e[i];if(!r)continue;const c=_t(gt(t,i),r,s,n);c&&o.push(...c)}return o.length?o:t.next(s,n)}(t,e,s,n)}function bt(t){return Object.keys(t.states).map((e=>t.states[e])).filter((t=>\"history\"===t.type))}function xt(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function St(t,e){const s=new Set(t),n=new Set(e);for(const t of s)if(n.has(t))return!0;for(const t of n)if(s.has(t))return!0;return!1}function wt(t,e,s){const n=new Set;for(const o of t){let t=!1;const i=new Set;for(const r of n)if(St(Et([o],e,s),Et([r],e,s))){if(!xt(o.source,r.source)){t=!0;break}i.add(r)}if(!t){for(const t of i)n.delete(t);n.add(o)}}return Array.from(n)}function It(t,e){if(!t.target)return[];const s=new Set;for(const n of t.target)if(pt(n))if(e[n.id])for(const t of e[n.id])s.add(t);else for(const t of It(dt(n),e))s.add(t);else s.add(n);return[...s]}function kt(t,e){const s=It(t,e);if(!s)return;if(!t.reenter&&s.every((e=>e===t.source||xt(e,t.source))))return t.source;const n=function(t){const[e,...s]=t;for(const t of nt(e,void 0))if(s.every((e=>xt(e,t))))return t}(s.concat(t.source));return n||(t.reenter?void 0:t.source.machine.root)}function Et(t,e,s){const n=new Set;for(const o of t)if(o.target?.length){const t=kt(o,s);o.reenter&&o.source===t&&n.add(t);for(const s of e)xt(s,t)&&n.add(s)}return[...n]}function $t(t,e,s,n,o){return Tt([{target:[...yt(t)],source:t,reenter:!0,actions:[],eventType:null,toJSON:null}],e,s,n,!0,o)}function Tt(t,e,s,n,o,i){const c=[];if(!t.length)return[e,c];const a=s.actionExecutor;s.actionExecutor=t=>{c.push(t),a(t)};try{const a=new Set(e._nodes);let u=e.historyValue;const h=wt(t,a,u);let f=e;o||([f,u]=function(t,e,s,n,o,i,r){let c=t;const a=Et(n,o,i);let u;a.sort(((t,e)=>e.order-t.order));for(const t of a)for(const e of bt(t)){let s;s=\"deep\"===e.history?e=>et(e)&&xt(e,t):e=>e.parent===t,u??={...i},u[e.id]=Array.from(o).filter(s)}for(const t of a)c=Rt(c,e,s,[...t.exit,...t.invoke.map((t=>q(t.id)))],r,void 0),o.delete(t);return[c,u||i]}(f,n,s,h,a,u,i,s.actionExecutor)),f=Rt(f,n,s,h.flatMap((t=>t.actions)),i,void 0),f=function(t,e,s,n,o,i,c,a){let u=t;const h=new Set,f=new Set;(function(t,e,s,n){for(const o of t){const t=kt(o,e);for(const i of o.target||[])pt(i)||o.source===i&&o.source===t&&!o.reenter||(n.add(i),s.add(i)),jt(i,e,s,n);const i=It(o,e);for(const r of i){const i=nt(r,t);\"parallel\"===t?.type&&i.push(t),At(n,e,s,i,!o.source.parent&&o.reenter?void 0:t)}}})(n,c,f,h),a&&f.add(t.machine.root);const d=new Set;for(const t of[...h].sort(((t,e)=>t.order-e.order))){o.add(t);const n=[];n.push(...t.entry);for(const e of t.invoke)n.push(L(e.src,{...e,syncSnapshot:!!e.onSnapshot}));if(f.has(t)){const e=t.initial.actions;n.push(...e)}if(u=Rt(u,e,s,n,i,t.invoke.map((t=>t.id))),\"final\"===t.type){const n=t.parent;let c=\"parallel\"===n?.type?n:n?.parent,a=c||t;for(\"compound\"===n?.type&&i.push(r(n.id,void 0!==t.output?m(t.output,u.context,e,s.self):void 0));\"parallel\"===c?.type&&!d.has(c)&&at(o,c);)d.add(c),i.push(r(c.id)),a=c,c=c.parent;if(c)continue;u=Gt(u,{status:\"done\",output:Ot(u,e,s,u.machine.root,a)})}}return u}(f,n,s,h,a,i,u,o);const d=[...a];\"done\"===f.status&&(f=Rt(f,n,s,d.sort(((t,e)=>e.order-t.order)).flatMap((t=>t.exit)),i,void 0));try{return u===e.historyValue&&function(t,e){if(t.length!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;return!0}(e._nodes,a)?[f,c]:[Gt(f,{_nodes:d,historyValue:u}),c]}catch(t){throw t}}finally{s.actionExecutor=a}}function Ot(t,e,s,n,o){if(void 0===n.output)return;const i=r(o.id,void 0!==o.output&&o.parent?m(o.output,t.context,e,s.self):void 0);return m(n.output,t.context,i,s.self)}function jt(t,e,s,n){if(pt(t))if(e[t.id]){const o=e[t.id];for(const t of o)n.add(t),jt(t,e,s,n);for(const i of o)Nt(i,t.parent,n,e,s)}else{const o=dt(t);for(const i of o.target)n.add(i),o===t.parent?.initial&&s.add(t.parent),jt(i,e,s,n);for(const i of o.target)Nt(i,t.parent,n,e,s)}else if(\"compound\"===t.type){const[o]=t.initial.target;pt(o)||(n.add(o),s.add(o)),jt(o,e,s,n),Nt(o,t,n,e,s)}else if(\"parallel\"===t.type)for(const o of st(t).filter((t=>!pt(t))))[...n].some((t=>xt(t,o)))||(pt(o)||(n.add(o),s.add(o)),jt(o,e,s,n))}function At(t,e,s,n,o){for(const i of n)if(o&&!xt(i,o)||t.add(i),\"parallel\"===i.type)for(const n of st(i).filter((t=>!pt(t))))[...t].some((t=>xt(t,n)))||(t.add(n),jt(n,e,s,t))}function Nt(t,e,s,n,o){At(s,n,o,nt(t,e))}function Mt(t,e){return t.implementations.actions[e]}function Pt(t,e,s,n,o,i){const{machine:r}=t;let c=t;for(const t of n){const n=\"function\"==typeof t,a=n?t:Mt(r,\"string\"==typeof t?t:t.type),u={context:c.context,event:e,self:s.self,system:s.system},h=n||\"string\"==typeof t?void 0:\"params\"in t?\"function\"==typeof t.params?t.params({context:c.context,event:e}):t.params:void 0;if(!a||!(\"resolve\"in a)){s.actionExecutor({type:\"string\"==typeof t?t:\"object\"==typeof t?t.type:t.name||\"(anonymous)\",info:u,params:h,exec:a});continue}const f=a,[d,p,l]=f.resolve(s,c,u,h,a,o);c=d,\"retryResolve\"in f&&i?.push([f,p]),\"execute\"in f&&s.actionExecutor({type:f.type,info:u,params:p,exec:f.execute.bind(null,s,p)}),l&&(c=Pt(c,e,s,l,o,i))}return c}function Rt(t,e,s,n,o,i){const r=i?[]:void 0,c=Pt(t,e,s,n,{internalQueue:o,deferredActorIds:i},r);return r?.forEach((([t,e])=>{t.retryResolve(s,c,e)})),c}function Ct(t,e,s,n){let r=t;const c=[];function a(t,e,n){s.system._sendInspectionEvent({type:\"@xstate.microstep\",actorRef:s.self,event:e,snapshot:t[0],_transitions:n}),c.push(t)}if(e.type===i)return r=Gt(Dt(r,e,s),{status:\"stopped\"}),a([r,[]],e,[]),{snapshot:r,microsteps:c};let u=e;if(u.type!==o){const e=u,o=function(t){return t.type.startsWith(\"xstate.error.actor\")}(e),i=Vt(e,r);if(o&&!i.length)return r=Gt(t,{status:\"error\",error:e.error}),a([r,[]],e,[]),{snapshot:r,microsteps:c};const h=Tt(i,t,s,u,!1,n);r=h[0],a(h,e,i)}let h=!0;for(;\"active\"===r.status;){let t=h?Jt(r,u):[];const e=t.length?r:void 0;if(!t.length){if(!n.length)break;u=n.shift(),t=Vt(u,r)}const o=Tt(t,r,s,u,!1,n);r=o[0],h=r!==e,a(o,u,t)}return\"active\"!==r.status&&Dt(r,u,s),{snapshot:r,microsteps:c}}function Dt(t,e,s){return Rt(t,e,s,Object.values(t.children).map((t=>q(t))),[],void 0)}function Vt(t,e){return e.machine.getTransitionData(e,t)}function Jt(t,e){const s=new Set,n=t._nodes.filter(et);for(const o of n)t:for(const n of[o].concat(nt(o,void 0)))if(n.always)for(const o of n.always)if(void 0===o.guard||tt(o.guard,t.context,e,t)){s.add(o);break t}return wt(Array.from(s),new Set(t._nodes),t.historyValue)}function Lt(t){return!!t&&\"object\"==typeof t&&\"machine\"in t&&\"value\"in t}const Bt=function(t){return f(t,this.value)},zt=function(t){return this.tags.has(t)},Wt=function(t){const e=this.machine.getTransitionData(this,t);return!!e?.length&&e.some((t=>void 0!==t.target||t.actions.length))},qt=function(){const{_nodes:t,tags:e,machine:s,getMeta:n,toJSON:o,can:i,hasTag:r,matches:c,...a}=this;return{...a,tags:Array.from(e)}},Ut=function(){return this._nodes.reduce(((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t)),{})};function Qt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:ct(e.root,t._nodes),tags:new Set(t._nodes.flatMap((t=>t.tags))),children:t.children,historyValue:t.historyValue||{},matches:Bt,hasTag:zt,can:Wt,getMeta:Ut,toJSON:qt}}function Gt(t,e={}){return Qt({...t,...e},t.machine)}function Ft(t){if(\"object\"!=typeof t||null===t)return{};const e={};for(const s in t){const n=t[s];Array.isArray(n)&&(e[s]=n.map((t=>({id:t.id}))))}return e}function Ht(t){let e;for(const s in t){const n=t[s];if(n&&\"object\"==typeof n)if(\"sessionId\"in n&&\"send\"in n&&\"ref\"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:1,id:n.id};else{const o=Ht(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function Kt(t,e,s,n,{event:o,id:i,delay:r},{internalQueue:c}){const a=e.machine.implementations.delays;if(\"string\"==typeof o)throw new Error(`Only event objects may be used with raise; use raise({ type: \"${o}\" }) instead`);const u=\"function\"==typeof o?o(s,n):o;let h;if(\"string\"==typeof r){const t=a&&a[r];h=\"function\"==typeof t?t(s,n):t}else h=\"function\"==typeof r?r(s,n):r;return\"number\"!=typeof h&&c.push(u),[e,{event:u,id:i,delay:h},void 0]}function Xt(t,e){const{event:s,delay:n,id:o}=e;\"number\"!=typeof n||t.defer((()=>{const e=t.self;t.system.scheduler.schedule(e,e,s,n,o)}))}function Yt(t,e){function s(t,e){}return s.type=\"xstate.raise\",s.event=t,s.id=e?.id,s.delay=e?.delay,s.resolve=Kt,s.execute=Xt,s}function Zt(t,e){return{config:t,transition:(e,s,n)=>({...e,context:t(e.context,s,n)}),getInitialSnapshot:(t,s)=>({status:\"active\",output:void 0,error:void 0,context:\"function\"==typeof e?e({input:s}):e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}const te=new WeakMap;function ee(t){const e={config:t,start:(e,s)=>{const{self:n,system:o,emit:i}=s,r={receivers:void 0,dispose:void 0};te.set(n,r),r.dispose=t({input:e.input,system:o,self:n,sendBack:t=>{\"stopped\"!==n.getSnapshot().status&&n._parent&&o._relay(n,n._parent,t)},receive:t=>{r.receivers??=new Set,r.receivers.add(t)},emit:i})},transition:(t,e,s)=>{const n=te.get(s.self);return e.type===i?(t={...t,status:\"stopped\",error:void 0},te.delete(s.self),n.receivers?.clear(),n.dispose?.(),t):(n.receivers?.forEach((t=>t(e))),t)},getInitialSnapshot:(t,e)=>({status:\"active\",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return e}const se=\"xstate.observable.next\",ne=\"xstate.observable.error\",oe=\"xstate.observable.complete\";function ie(t){const e={config:t,transition:(t,e)=>{if(\"active\"!==t.status)return t;switch(e.type){case se:return{...t,context:e.data};case ne:return{...t,status:\"error\",error:e.data,input:void 0,_subscription:void 0};case oe:return{...t,status:\"done\",input:void 0,_subscription:void 0};case i:return t._subscription.unsubscribe(),{...t,status:\"stopped\",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:\"active\",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(e,{self:s,system:n,emit:o})=>{\"done\"!==e.status&&(e._subscription=t({input:e.input,system:n,self:s,emit:o}).subscribe({next:t=>{n._relay(s,s,{type:se,data:t})},error:t=>{n._relay(s,s,{type:ne,data:t})},complete:()=>{n._relay(s,s,{type:oe})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return e}function re(t){const e={config:t,transition:(t,e)=>{if(\"active\"!==t.status)return t;switch(e.type){case ne:return{...t,status:\"error\",error:e.data,input:void 0,_subscription:void 0};case oe:return{...t,status:\"done\",input:void 0,_subscription:void 0};case i:return t._subscription.unsubscribe(),{...t,status:\"stopped\",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:\"active\",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(e,{self:s,system:n,emit:o})=>{\"done\"!==e.status&&(e._subscription=t({input:e.input,system:n,self:s,emit:o}).subscribe({next:t=>{s._parent&&n._relay(s,s._parent,t)},error:t=>{n._relay(s,s,{type:ne,data:t})},complete:()=>{n._relay(s,s,{type:oe})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return e}const ce=\"xstate.promise.resolve\",ae=\"xstate.promise.reject\",ue=new WeakMap;function he(t){const e={config:t,transition:(t,e,s)=>{if(\"active\"!==t.status)return t;switch(e.type){case ce:{const s=e.data;return{...t,status:\"done\",output:s,input:void 0}}case ae:return{...t,status:\"error\",error:e.data,input:void 0};case i:return ue.get(s.self)?.abort(),ue.delete(s.self),{...t,status:\"stopped\",input:void 0};default:return t}},start:(e,{self:s,system:n,emit:o})=>{if(\"active\"!==e.status)return;const i=new AbortController;ue.set(s,i);Promise.resolve(t({input:e.input,system:n,self:s,signal:i.signal,emit:o})).then((t=>{\"active\"===s.getSnapshot().status&&(ue.delete(s),n._relay(s,s,{type:ce,data:t}))}),(t=>{\"active\"===s.getSnapshot().status&&(ue.delete(s),n._relay(s,s,{type:ae,data:t}))}))},getInitialSnapshot:(t,e)=>({status:\"active\",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return e}const fe=Zt((t=>{}),void 0);function de(){return M(fe)}function pe(t,{machine:e,context:s},n,o){return(i,r)=>{const c=((i,r)=>{if(\"string\"==typeof i){const c=I(e,i);if(!c)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const a=M(c,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:\"function\"==typeof r?.input?r.input({context:s,event:n,self:t.self}):r?.input,src:i,systemId:r?.systemId});return o[a.id]=a,a}return M(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,systemId:r?.systemId})})(i,r);return o[c.id]=c,t.defer((()=>{c._processingStatus!==j.Stopped&&c.start()})),c}}function le(t,e,s,n,{assignment:o}){if(!e.context)throw new Error(\"Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.\");const i={},r={context:e.context,event:s.event,spawn:pe(t,e,s.event,i),self:t.self,system:t.system};let c={};if(\"function\"==typeof o)c=o(r,n);else for(const t of Object.keys(o)){const e=o[t];c[t]=\"function\"==typeof e?e(r,n):e}return[Gt(e,{context:Object.assign({},e.context,c),children:Object.keys(i).length?{...e.children,...i}:e.children}),void 0,void 0]}function ye(t){function e(t,e){}return e.type=\"xstate.assign\",e.assignment=t,e.resolve=le,e}const ge=new WeakMap;function ve(t,e,s){let n=ge.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},ge.set(t,n)),n[e]}const me={},_e=t=>\"string\"==typeof t?{type:t}:\"function\"==typeof t?\"resolve\"in t?{type:t.type}:{type:t.name}:t;class be{constructor(t,e){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(\".\"),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?\"compound\":this.config.history?\"history\":\"atomic\"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?y(this.config.states,((t,e)=>new be(t,{_parent:this,_key:e,_machine:this.machine}))):me,\"compound\"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node \"#${this.id}\". Try adding { initial: \"${Object.keys(this.states)[0]}\" } to the state config.`);this.history=!0===this.config.history?\"shallow\":this.config.history||!1,this.entry=v(this.config.entry).slice(),this.exit=v(this.config.exit).slice(),this.meta=this.config.meta,this.output=\"final\"!==this.type&&this.parent?void 0:this.config.output,this.tags=v(t.tags).slice()}_initialize(){this.transitions=function(t){const e=new Map;if(t.config.on)for(const s of Object.keys(t.config.on)){if(\"\"===s)throw new Error('Null events (\"\") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=t.config.on[s];e.set(s,b(n).map((e=>ft(t,s,e))))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,b(t.config.onDone).map((e=>ft(t,s,e))))}for(const s of t.invoke){if(s.onDone){const n=`xstate.done.actor.${s.id}`;e.set(n,b(s.onDone).map((e=>ft(t,n,e))))}if(s.onError){const n=`xstate.error.actor.${s.id}`;e.set(n,b(s.onError).map((e=>ft(t,n,e))))}if(s.onSnapshot){const n=`xstate.snapshot.${s.id}`;e.set(n,b(s.onSnapshot).map((e=>ft(t,n,e))))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),this.config.always&&(this.always=b(this.config.always).map((t=>ft(this,\"\",t)))),Object.keys(this.states).forEach((t=>{this.states[t]._initialize()}))}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(_e),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map((t=>`#${t.id}`)),source:`#${this.id}`,actions:this.initial.actions.map(_e),eventType:null})}:void 0,history:this.history,states:y(this.states,(t=>t.definition)),on:this.on,transitions:[...this.transitions.values()].flat().map((t=>({...t,actions:t.actions.map(_e)}))),entry:this.entry.map(_e),exit:this.exit.map(_e),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return ve(this,\"invoke\",(()=>v(this.config.invoke).map(((t,e)=>{const{src:s,systemId:n}=t,o=t.id??w(this.id,e),i=\"string\"==typeof s?s:`xstate.invoke.${w(this.id,e)}`;return{...t,src:i,id:o,systemId:n,toJSON(){const{onDone:e,onError:s,...n}=t;return{...n,type:\"xstate.invoke\",src:i,id:o}}}}))))}get on(){return ve(this,\"on\",(()=>[...this.transitions].flatMap((([t,e])=>e.map((e=>[t,e])))).reduce(((t,[e,s])=>(t[e]=t[e]||[],t[e].push(s),t)),{})))}get after(){return ve(this,\"delayedTransitions\",(()=>ht(this)))}get initial(){return ve(this,\"initial\",(()=>function(t,e){const s=\"string\"==typeof e?t.states[e]:e?t.states[e.target]:void 0;if(!s&&e)throw new Error(`Initial state node \"${e}\" not found on parent state node #${t.id}`);const n={source:t,actions:e&&\"string\"!=typeof e?v(e.actions):[],eventType:null,reenter:!1,target:s?[s]:[],toJSON:()=>({...n,source:`#${t.id}`,target:s?[`#${s.id}`]:[]})};return n}(this,this.config.initial)))}next(t,e){const s=e.type,n=[];let o;const i=ve(this,`candidates-${s}`,(()=>{return e=s,(t=this).transitions.get(e)||[...t.transitions.keys()].filter((t=>E(e,t))).sort(((t,e)=>e.length-t.length)).flatMap((e=>t.transitions.get(e)));var t,e}));for(const r of i){const{guard:i}=r,c=t.context;let a=!1;try{a=!i||tt(i,c,e,t)}catch(t){const e=\"string\"==typeof i?i:\"object\"==typeof i?i.type:void 0;throw new Error(`Unable to evaluate guard ${e?`'${e}' `:\"\"}in transition for event '${s}' in state node '${this.id}':\\n${t.message}`)}if(a){n.push(...r.actions),o=r;break}}return o?[o]:void 0}get events(){return ve(this,\"events\",(()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const s of Object.keys(t)){const n=t[s];if(n.states)for(const t of n.events)e.add(`${t}`)}return Array.from(e)}))}get ownEvents(){const t=Object.keys(Object.fromEntries(this.transitions)),e=new Set(t.filter((t=>this.transitions.get(t).some((t=>!(!t.target&&!t.actions.length&&!t.reenter))))));return Array.from(e)}}class xe{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||\"(machine)\",this.implementations={actors:e?.actors??{},actions:e?.actions??{},delays:e?.delays??{},guards:e?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new be(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach((n=>{if(n.config.route&&n.config.id){const s=n.config.id,o=n.config.route.guard,i=(t,e)=>t.event.to===`#${s}`&&(!o||\"function\"!=typeof o||o(t,e)),r={...n.config.route,guard:i,target:`#${s}`};e.push(ft(t,\"xstate.route\",r))}n.states&&s(n.states)}))};s(t.states),e.length>0&&t.transitions.set(\"xstate.route\",e)}(this.root),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.implementations;return new xe(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}})}resolveState(t){const e=(s=this.root,n=t.value,ct(s,[...ot(mt(s,n))]));var s,n;const o=ot(mt(this.root,e));return Qt({_nodes:[...o],context:t.context||{},children:{},status:at(o,this.root)?\"done\":t.status||\"active\",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return Ct(t,e,s,[]).snapshot}microstep(t,e,s){return Ct(t,e,s,[]).microsteps.map((([t])=>t))}getTransitionData(t,e){return _t(this.root,t.value,t,e)||[]}_getPreInitialState(t,e,s){const{context:n}=this.config,o=Qt({context:\"function\"!=typeof n&&n?n:{},_nodes:[this.root],children:{},status:\"active\"},this);if(\"function\"==typeof n){return Rt(o,e,t,[ye((({spawn:t,event:e,self:s})=>n({spawn:t,input:e.input,self:s})))],s,void 0)}return o}getInitialSnapshot(t,e){const s=a(e),n=[],o=this._getPreInitialState(t,s,n),[i]=$t(this.root,o,t,s,n),{snapshot:r}=Ct(i,s,t,n);return r}start(t){Object.values(t.children).forEach((t=>{\"active\"===t.getSnapshot().status&&t.start()}))}getStateNodeById(t){const e=d(t),s=e.slice(1),n=ut(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return vt(o,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,tags:n,machine:o,children:i,context:r,can:c,hasTag:a,matches:u,getMeta:h,toJSON:f,...d}=t,p={};for(const t in i){const s=i[t];p[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,systemId:s.systemId,syncSnapshot:s._syncSnapshot}}return{...d,context:Ht(r),children:p,historyValue:Ft(d.historyValue)}}(t,e)}restoreSnapshot(t,e){const s={},n=t.children;function o(t,e){if(e instanceof be)return e;try{return t.machine.getStateNodeById(e.id)}catch{}}Object.keys(n).forEach((t=>{const o=n[t],i=o.snapshot,r=o.src,c=\"string\"==typeof r?I(this,r):r;if(!c)return;const a=M(c,{id:t,parent:e.self,syncSnapshot:o.syncSnapshot,snapshot:i,src:r,systemId:o.systemId});s[t]=a}));const i=function(t,e){if(!e||\"object\"!=typeof e)return{};const s={};for(const n in e){const i=e[n];for(const e of i){const i=o(t,e);i&&(s[n]??=[],s[n].push(i))}}return s}(this.root,t.historyValue),r=Qt({...t,children:s,_nodes:Array.from(ot(mt(this.root,t.value))),historyValue:i},this),c=new Set;return function t(e,s){if(!c.has(e)){c.add(e);for(const n in e){const o=e[n];if(o&&\"object\"==typeof o){if(\"xstate$$type\"in o&&1===o.xstate$$type){e[n]=s[o.id];continue}t(o,s)}}}}(r.context,s),r}}function Se(t,e,s,n,{event:o}){return[e,{event:\"function\"==typeof o?o(s,n):o},void 0]}function we(t,{event:e}){t.defer((()=>t.emit(e)))}function Ie(t){function e(t,e){}return e.type=\"xstate.emit\",e.event=t,e.resolve=Se,e.execute=we,e}let ke=function(t){return t.Parent=\"#_parent\",t.Internal=\"#_internal\",t}({});function Ee(t,e,s,n,{to:o,event:i,id:r,delay:c},a){const u=e.machine.implementations.delays;if(\"string\"==typeof i)throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: \"${i}\" }) instead`);const h=\"function\"==typeof i?i(s,n):i;let f;if(\"string\"==typeof c){const t=u&&u[c];f=\"function\"==typeof t?t(s,n):t}else f=\"function\"==typeof c?c(s,n):c;const d=\"function\"==typeof o?o(s,n):o;let p;if(\"string\"==typeof d){if(p=d===ke.Parent?t.self._parent:d===ke.Internal?t.self:d.startsWith(\"#_\")?e.children[d.slice(2)]:a.deferredActorIds?.includes(d)?d:e.children[d],!p)throw new Error(`Unable to send event to actor '${d}' from machine '${e.machine.id}'.`)}else p=d||t.self;return[e,{to:p,targetId:\"string\"==typeof d?d:void 0,event:h,id:r,delay:f},void 0]}function $e(t,e,s){\"string\"==typeof s.to&&(s.to=e.children[s.to])}function Te(t,e){t.defer((()=>{const{to:s,event:n,delay:o,id:i}=e;\"number\"!=typeof o?t.system._relay(t.self,s,\"xstate.error\"===n.type?c(t.self.id,n.data):n):t.system.scheduler.schedule(t.self,s,n,o,i)}))}function Oe(t,e,s){function n(t,e){}return n.type=\"xstate.sendTo\",n.to=t,n.event=e,n.id=s?.id,n.delay=s?.delay,n.resolve=Ee,n.retryResolve=$e,n.execute=Te,n}function je(t,e){return Oe(ke.Parent,t,e)}function Ae(t,e){return Oe(t,(({event:t})=>t),e)}function Ne(t,e,s,n,{collect:o}){const i=[],r=function(t){i.push(t)};return r.assign=(...t)=>{i.push(ye(...t))},r.cancel=(...t)=>{i.push(D(...t))},r.raise=(...t)=>{i.push(Yt(...t))},r.sendTo=(...t)=>{i.push(Oe(...t))},r.sendParent=(...t)=>{i.push(je(...t))},r.spawnChild=(...t)=>{i.push(L(...t))},r.stopChild=(...t)=>{i.push(q(...t))},r.emit=(...t)=>{i.push(Ie(...t))},o({context:s.context,event:s.event,enqueue:r,check:t=>tt(t,e.context,s.event,e),self:t.self,system:t.system},n),[e,void 0,i]}function Me(t){function e(t,e){}return e.type=\"xstate.enqueueActions\",e.collect=t,e.resolve=Ne,e}function Pe(t,e,s,n,{value:o,label:i}){return[e,{value:\"function\"==typeof o?o(s,n):o,label:i},void 0]}function Re({logger:t},{value:e,label:s}){s?t(s,e):t(e)}function Ce(t=({context:t,event:e})=>({context:t,event:e}),e){function s(t,e){}return s.type=\"xstate.log\",s.value=t,s.label=e,s.resolve=Pe,s.execute=Re,s}function De(t,e){const s=v(e);if(!s.some((e=>E(t.type,e)))){const e=1===s.length?`type matching \"${s[0]}\"`:`one of types matching \"${s.join('\", \"')}\"`;throw new Error(`Expected event ${JSON.stringify(t)} to have ${e}`)}}function Ve(t,e){return new xe(t,e)}function Je(t){const e=M(t);return{self:e,defer:()=>{},id:\"\",logger:()=>{},sessionId:\"\",stopChild:()=>{},system:e.system,emit:()=>{},actionExecutor:()=>{}}}function Le(t,...[e]){const s=Je(t);return t.getInitialSnapshot(s,e)}function Be(t,e,s){const n=Je(t);return n.self._snapshot=e,t.transition(e,s,n)}function ze({schemas:t,actors:e,actions:s,guards:n,delays:o}){return{assign:ye,sendTo:Oe,raise:Yt,log:Ce,cancel:D,stopChild:q,enqueueActions:Me,emit:Ie,spawnChild:L,createStateConfig:t=>t,createAction:t=>t,createMachine:i=>Ve({...i,schemas:t},{actors:e,actions:s,guards:n,delays:o}),extend:i=>ze({schemas:t,actors:e,actions:{...s,...i.actions},guards:{...n,...i.guards},delays:{...o,...i.delays}})}}class We{constructor(){this.timeouts=new Map,this._now=0,this._id=0,this._flushing=!1,this._flushingInvalidated=!1}now(){return this._now}getId(){return this._id++}setTimeout(t,e){this._flushingInvalidated=this._flushing;const s=this.getId();return this.timeouts.set(s,{start:this.now(),timeout:e,fn:t}),s}clearTimeout(t){this._flushingInvalidated=this._flushing,this.timeouts.delete(t)}set(t){if(this._now>t)throw new Error(\"Unable to travel back in time\");this._now=t,this.flushTimeouts()}flushTimeouts(){if(this._flushing)return void(this._flushingInvalidated=!0);this._flushing=!0;const t=[...this.timeouts].sort((([t,e],[s,n])=>{const o=e.start+e.timeout;return n.start+n.timeout>o?-1:1}));for(const[e,s]of t){if(this._flushingInvalidated)return this._flushingInvalidated=!1,this._flushing=!1,void this.flushTimeouts();this.now()-s.start>=s.timeout&&(this.timeouts.delete(e),s.fn.call(null))}this._flushing=!1}increment(t){this._now+=t,this.flushTimeouts()}}function qe(t){return new Promise(((e,s)=>{t.subscribe({complete:()=>{e(t.getSnapshot().output)},error:s})}))}function Ue(t,e,s){const n=[],o=Je(t);o.actionExecutor=t=>{n.push(t)};return[t.transition(e,s,o),n]}function Qe(t,...[e]){const s=[],n=Je(t);n.actionExecutor=t=>{s.push(t)};return[t.getInitialSnapshot(n,e),s]}function Ge(t,e,s){const n=Je(t),{microsteps:o}=Ct(e,s,n,[]);return o}function Fe(t,...[e]){const s=Je(t),n=a(e),o=[],i=t._getPreInitialState(s,n,o),r=$t(t.root,i,s,n,o),{microsteps:c}=Ct(r[0],n,s,o);return[r,...c]}function He(t){const e=[],s=t._nodes.filter(et),n=new Set;for(const t of s)for(const s of[t].concat(nt(t,void 0)))if(!n.has(s.id)){n.add(s.id);for(const[,t]of s.transitions)e.push(...t);s.always&&e.push(...s.always)}return e}const Ke={timeout:1/0};function Xe(t,e,s){const n={...Ke,...s};return new Promise(((s,o)=>{const{signal:i}=n;if(i?.aborted)return void o(i.reason);let r=!1;const c=n.timeout===1/0?void 0:setTimeout((()=>{a(),o(new Error(`Timeout of ${n.timeout} ms exceeded`))}),n.timeout),a=()=>{clearTimeout(c),r=!0,f?.unsubscribe(),h&&i.removeEventListener(\"abort\",h)};function u(t){e(t)&&(a(),s(t))}let h,f;u(t.getSnapshot()),r||(i&&(h=()=>{a(),o(i.reason)},i.addEventListener(\"abort\",h)),f=t.subscribe({next:u,error:t=>{a(),o(t)},complete:()=>{a(),o(new Error(\"Actor terminated without satisfying predicate\"))}}),r&&f.unsubscribe())}))}export{N as Actor,We as SimulatedClock,ke as SpecialTargets,xe as StateMachine,be as StateNode,k as __unsafe_getAllOwnEventDescriptors,X as and,De as assertEvent,ye as assign,D as cancel,M as createActor,de as createEmptyActor,Ve as createMachine,Ie as emit,Me as enqueueActions,Ae as forwardTo,ee as fromCallback,re as fromEventObservable,ie as fromObservable,he as fromPromise,Zt as fromTransition,Fe as getInitialMicrosteps,Le as getInitialSnapshot,Ge as getMicrosteps,Be as getNextSnapshot,He as getNextTransitions,mt as getStateNodes,Qe as initialTransition,P as interpret,Lt as isMachineSnapshot,Ce as log,f as matchesState,H as not,Z as or,l as pathToStateValue,Yt as raise,je as sendParent,Oe as sendTo,ze as setup,L as spawnChild,G as stateIn,U as stop,q as stopChild,S as toObserver,qe as toPromise,Ue as transition,Xe as waitFor};export default null;\r\n//# sourceMappingURL=/sm/546728fff23412ec5415f09b28a984c4e349ecb65c6c1d0bbe0d0c5d24f3e486.map","vendor/ui-libs.js":"var R=new Map(Object.entries({a:\"A\",abbr:\"ABBR\",address:\"ADDRESS\",area:\"AREA\",article:\"ARTICLE\",aside:\"ASIDE\",audio:\"AUDIO\",b:\"B\",base:\"BASE\",bdi:\"BDI\",bdo:\"BDO\",blockquote:\"BLOCKQUOTE\",body:\"BODY\",br:\"BR\",button:\"BUTTON\",canvas:\"CANVAS\",caption:\"CAPTION\",cite:\"CITE\",code:\"CODE\",col:\"COL\",colgroup:\"COLGROUP\",data:\"DATA\",datalist:\"DATALIST\",dd:\"DD\",del:\"DEL\",details:\"DETAILS\",dfn:\"DFN\",dialog:\"DIALOG\",div:\"DIV\",dl:\"DL\",dt:\"DT\",em:\"EM\",embed:\"EMBED\",fieldset:\"FIELDSET\",figcaption:\"FIGCAPTION\",figure:\"FIGURE\",footer:\"FOOTER\",form:\"FORM\",h1:\"H1\",h2:\"H2\",h3:\"H3\",h4:\"H4\",h5:\"H5\",h6:\"H6\",head:\"HEAD\",header:\"HEADER\",hgroup:\"HGROUP\",hr:\"HR\",html:\"HTML\",i:\"I\",iframe:\"IFRAME\",img:\"IMG\",input:\"INPUT\",ins:\"INS\",kbd:\"KBD\",label:\"LABEL\",legend:\"LEGEND\",li:\"LI\",link:\"LINK\",main:\"MAIN\",map:\"MAP\",mark:\"MARK\",menu:\"MENU\",meta:\"META\",meter:\"METER\",nav:\"NAV\",noscript:\"NOSCRIPT\",object:\"OBJECT\",ol:\"OL\",optgroup:\"OPTGROUP\",option:\"OPTION\",output:\"OUTPUT\",p:\"P\",picture:\"PICTURE\",pre:\"PRE\",progress:\"PROGRESS\",q:\"Q\",rp:\"RP\",rt:\"RT\",ruby:\"RUBY\",s:\"S\",samp:\"SAMP\",script:\"SCRIPT\",section:\"SECTION\",select:\"SELECT\",slot:\"SLOT\",small:\"SMALL\",source:\"SOURCE\",span:\"SPAN\",strong:\"STRONG\",style:\"STYLE\",sub:\"SUB\",summary:\"SUMMARY\",sup:\"SUP\",table:\"TABLE\",tbody:\"TBODY\",td:\"TD\",template:\"TEMPLATE\",textarea:\"TEXTAREA\",tfoot:\"TFOOT\",th:\"TH\",thead:\"THEAD\",time:\"TIME\",title:\"TITLE\",tr:\"TR\",track:\"TRACK\",u:\"U\",ul:\"UL\",var:\"VAR\",video:\"VIDEO\",wbr:\"WBR\"}));var C=\"http://www.w3.org/1999/xhtml\";var O=\"http://www.w3.org/2000/svg\";function g(e,t=[]){if(Array.isArray(e))for(let o of e)g(o,t);else J(e)&&t.push(e);return t}function J(e){let t=typeof e;return e!=null&&(t===\"string\"||t===\"object\"||t===\"number\"||t===\"bigint\")}function w(e){let t=[],o=e.firstChild;for(;o;)t.push(o),o=o.nextSibling;return t}function b(e,t){typeof t==\"function\"?t(e):t&&typeof t==\"object\"&&(t.current=e)}function a(e){let t=typeof e;return t!==\"string\"&&t!==\"number\"&&t!==\"bigint\"}function _(e){let t=typeof e;return t===\"string\"||t===\"number\"||t===\"bigint\"}function D(e){return e instanceof Element&&e.namespaceURI!==C?e.namespaceURI??void 0:void 0}function S(e,t){e.__webjsx_props=t}function x(e){let t=e.__webjsx_props;return t||(t={},e.__webjsx_props=t),t}function h(e,t){e.__webjsx_childNodes=t}function P(e){return e.__webjsx_childNodes}function U(e,t,...o){if(typeof e==\"string\"){let n=t||{},d=g(o);return d.length>0?n.dangerouslySetInnerHTML?(n.children=[],console.warn(\"WebJSX: Ignoring children since dangerouslySetInnerHTML is set.\")):n.children=d:n.children=[],{type:e,tagName:R.get(e)??e.toUpperCase(),props:n??{}}}else return g(o)}function y(e){return!!e.__webjsx_suspendRendering}function A(e,t){let o=!!e.__webjsx_suspendRendering;o&&e.__webjsx_suspendRendering();try{return t()}finally{o&&e.__webjsx_resumeRendering()}}function X(e,t,o,n){n&&n!==o&&e.removeEventListener(t,n),o&&n!==o&&(e.addEventListener(t,o),e.__webjsx_listeners=e.__webjsx_listeners??{},e.__webjsx_listeners[t]=o)}function K(e,t,o){if(e instanceof HTMLElement){if(t in e){e[t]=o;return}if(typeof o==\"string\"){e.setAttribute(t,o);return}e[t]=o;return}if(e.namespaceURI===\"http://www.w3.org/2000/svg\"){o!=null?e.setAttribute(t,`${o}`):e.removeAttribute(t);return}typeof o==\"string\"?e.setAttribute(t,o):e[t]=o}function T(e,t,o={}){for(let n of Object.keys(t)){let d=t[n];if(!(n===\"children\"||n===\"key\"||n===\"dangerouslySetInnerHTML\"||n===\"nodes\"))if(n.startsWith(\"on\")&&typeof d==\"function\"){let s=n.substring(2).toLowerCase();X(e,s,d,e.__webjsx_listeners?.[s])}else d!==o[n]&&K(e,n,d)}if(t.dangerouslySetInnerHTML){if(!o.dangerouslySetInnerHTML||t.dangerouslySetInnerHTML.__html!==o.dangerouslySetInnerHTML.__html){let n=t.dangerouslySetInnerHTML?.__html||\"\";e.innerHTML=n}}else o.dangerouslySetInnerHTML&&(e.innerHTML=\"\");for(let n of Object.keys(o))if(!(n in t)&&n!==\"children\"&&n!==\"key\"&&n!==\"dangerouslySetInnerHTML\"&&n!==\"nodes\")if(n.startsWith(\"on\")){let d=n.substring(2).toLowerCase(),s=e.__webjsx_listeners?.[d];s&&(e.removeEventListener(d,s),delete e.__webjsx_listeners[d])}else n in e?e[n]=void 0:e.removeAttribute(n)}function H(e,t){y(e)?A(e,()=>{T(e,t)}):T(e,t)}function j(e,t,o){y(e)?A(e,()=>{T(e,t,o)}):T(e,t,o)}function N(e,t){let o=e.props.xmlns!==void 0?e.props.xmlns:e.type===\"svg\"?O:t??void 0,n=e.props.is!==void 0?o!==void 0?document.createElementNS(o,e.type,{is:e.props.is}):document.createElement(e.type,{is:e.props.is}):o!==void 0?document.createElementNS(o,e.type):document.createElement(e.type);if(e.props&&H(n,e.props),e.props.key!==void 0&&(n.__webjsx_key=e.props.key),e.props.ref&&b(n,e.props.ref),e.props.children&&!e.props.dangerouslySetInnerHTML){let d=e.props.children,s=[];for(let r=0;r<d.length;r++){let i=d[r],f=a(i)?N(i,o):document.createTextNode(`${i}`);s.push(f),n.appendChild(f)}S(n,e.props),h(n,s)}return n}function V(e,t){let o=g(t),n=B(e,o),d=x(e);d.children=o,h(e,n)}function B(e,t){let n=x(e).children??[];if(t.length===0)return n.length>0?(e.innerHTML=\"\",[]):[];let d=[],s=null,r=P(e)??w(e),i=!1,f=!0;for(let u=0;u<t.length;u++){let c=t[u],l=n[u],p=r[u],M=a(c)?c.props.key:void 0;if(M!==void 0){if(!s){i=!0,s=new Map;for(let E=0;E<n.length;E++){let L=n[E],I=L.props.key;if(I!==void 0){let G=r[E];s.set(I,{node:G,oldVNode:L})}}}let m=s.get(M);m?(m.oldVNode!==l&&(f=!1),d.push({type:\"update\",node:m.node,newVNode:c,oldVNode:m.oldVNode})):(f=!1,d.push({type:\"create\",vnode:c}))}else!i&&F(c,l)&&p?d.push({type:\"update\",node:p,newVNode:c,oldVNode:l}):(f=!1,d.push({type:\"create\",vnode:c}))}if(d.length){let{nodes:u,lastNode:c}=Y(e,d,r,f);for(;c?.nextSibling;)e.removeChild(c.nextSibling);return u}else return r}function F(e,t){if(t===void 0)return!1;if(_(e)&&_(t))return!0;if(a(t)&&a(e)){let o=t.props.key,n=e.props.key;return t.tagName===e.tagName&&(o===void 0&&n===void 0||o!==void 0&&n!==void 0&&o===n)}else return!1}function Y(e,t,o,n){let d=[],s=null;for(let r of t)if(r.type===\"create\"){let i;a(r.vnode)?i=N(r.vnode,D(e)):i=document.createTextNode(`${r.vnode}`),s?e.insertBefore(i,s.nextSibling??null):e.prepend(i),s=i,d.push(i)}else{let{node:i,newVNode:f,oldVNode:u}=r;if(a(f)){let c=u?.props||{},l=f.props;if(j(i,l,c),f.props.key!==void 0?i.__webjsx_key=f.props.key:u.props?.key&&delete i.__webjsx_key,f.props.ref&&b(i,f.props.ref),!l.dangerouslySetInnerHTML&&l.children!=null){let p=B(i,l.children);S(i,l),h(i,p)}}else f!==u&&(i.textContent=`${f}`);n||(s?s.nextSibling!==i&&e.insertBefore(i,s.nextSibling??null):i!==o[0]&&e.prepend(i)),s=i,d.push(i)}return{nodes:d,lastNode:s}}var W=function(e,t,o,n){var d;t[0]=0;for(var s=1;s<t.length;s++){var r=t[s++],i=t[s]?(t[0]|=r?1:2,o[t[s++]]):t[++s];r===3?n[0]=i:r===4?n[1]=Object.assign(n[1]||{},i):r===5?(n[1]=n[1]||{})[t[++s]]=i:r===6?n[1][t[++s]]+=i+\"\":r?(d=e.apply(i,W(e,i,o,[\"\",null])),n.push(d),i[0]?t[0]|=2:(t[s-2]=0,t[s]=d)):n.push(i)}return n},k=new Map;function $(e){var t=k.get(this);return t||(t=new Map,k.set(this,t)),(t=W(this,t.get(e)||(t.set(e,t=(function(o){for(var n,d,s=1,r=\"\",i=\"\",f=[0],u=function(p){s===1&&(p||(r=r.replace(/^\\s*\\n\\s*|\\s*\\n\\s*$/g,\"\")))?f.push(0,p,r):s===3&&(p||r)?(f.push(3,p,r),s=2):s===2&&r===\"...\"&&p?f.push(4,p,0):s===2&&r&&!p?f.push(5,0,!0,r):s>=5&&((r||!p&&s===5)&&(f.push(s,0,r,d),s=6),p&&(f.push(s,p,0,d),s=6)),r=\"\"},c=0;c<o.length;c++){c&&(s===1&&u(),u(c));for(var l=0;l<o[c].length;l++)n=o[c][l],s===1?n===\"<\"?(u(),f=[f],s=3):r+=n:s===4?r===\"--\"&&n===\">\"?(s=1,r=\"\"):r=n+r[0]:i?n===i?i=\"\":r+=n:n==='\"'||n===\"'\"?i=n:n===\">\"?(u(),s=1):s&&(n===\"=\"?(s=5,d=r,r=\"\"):n===\"/\"&&(s<5||o[c][l+1]===\">\")?(u(),s===3&&(f=f[0]),s=f,(f=f[0]).push(2,0,s),s=0):n===\" \"||n===\"\t\"||n===`\r\n`||n===\"\\r\"?(u(),s=2):r+=n),s===3&&r===\"!--\"&&(s=4,f=f[0])}return u(),f})(e)),t),arguments,[])).length>1?t:t[0]}export{V as applyDiff,U as createElement,$ as htm};\r\n","vendor/thebird-browser.js":"var __create = Object.create;\r\nvar __defProp = Object.defineProperty;\r\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\r\nvar __getOwnPropNames = Object.getOwnPropertyNames;\r\nvar __getProtoOf = Object.getPrototypeOf;\r\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\r\nvar __esm = (fn, res) => function __init() {\r\n return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;\r\n};\r\nvar __commonJS = (cb, mod) => function __require() {\r\n return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;\r\n};\r\nvar __export = (target, all) => {\r\n for (var name in all)\r\n __defProp(target, name, { get: all[name], enumerable: true });\r\n};\r\nvar __copyProps = (to, from, except, desc) => {\r\n if (from && typeof from === \"object\" || typeof from === \"function\") {\r\n for (let key of __getOwnPropNames(from))\r\n if (!__hasOwnProp.call(to, key) && key !== except)\r\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\r\n }\r\n return to;\r\n};\r\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\r\n // If the importer is in node compatibility mode or this is not an ESM\r\n // file that has been converted to a CommonJS file using a Babel-\r\n // compatible transform (i.e. \"__esModule\" has not been set), then set\r\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\r\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\r\n mod\r\n));\r\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\r\n\r\n// node_modules/retry/lib/retry_operation.js\r\nvar require_retry_operation = __commonJS({\r\n \"node_modules/retry/lib/retry_operation.js\"(exports, module) {\r\n function RetryOperation(timeouts, options) {\r\n if (typeof options === \"boolean\") {\r\n options = { forever: options };\r\n }\r\n this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));\r\n this._timeouts = timeouts;\r\n this._options = options || {};\r\n this._maxRetryTime = options && options.maxRetryTime || Infinity;\r\n this._fn = null;\r\n this._errors = [];\r\n this._attempts = 1;\r\n this._operationTimeout = null;\r\n this._operationTimeoutCb = null;\r\n this._timeout = null;\r\n this._operationStart = null;\r\n this._timer = null;\r\n if (this._options.forever) {\r\n this._cachedTimeouts = this._timeouts.slice(0);\r\n }\r\n }\r\n module.exports = RetryOperation;\r\n RetryOperation.prototype.reset = function() {\r\n this._attempts = 1;\r\n this._timeouts = this._originalTimeouts.slice(0);\r\n };\r\n RetryOperation.prototype.stop = function() {\r\n if (this._timeout) {\r\n clearTimeout(this._timeout);\r\n }\r\n if (this._timer) {\r\n clearTimeout(this._timer);\r\n }\r\n this._timeouts = [];\r\n this._cachedTimeouts = null;\r\n };\r\n RetryOperation.prototype.retry = function(err) {\r\n if (this._timeout) {\r\n clearTimeout(this._timeout);\r\n }\r\n if (!err) {\r\n return false;\r\n }\r\n var currentTime = (/* @__PURE__ */ new Date()).getTime();\r\n if (err && currentTime - this._operationStart >= this._maxRetryTime) {\r\n this._errors.push(err);\r\n this._errors.unshift(new Error(\"RetryOperation timeout occurred\"));\r\n return false;\r\n }\r\n this._errors.push(err);\r\n var timeout = this._timeouts.shift();\r\n if (timeout === void 0) {\r\n if (this._cachedTimeouts) {\r\n this._errors.splice(0, this._errors.length - 1);\r\n timeout = this._cachedTimeouts.slice(-1);\r\n } else {\r\n return false;\r\n }\r\n }\r\n var self = this;\r\n this._timer = setTimeout(function() {\r\n self._attempts++;\r\n if (self._operationTimeoutCb) {\r\n self._timeout = setTimeout(function() {\r\n self._operationTimeoutCb(self._attempts);\r\n }, self._operationTimeout);\r\n if (self._options.unref) {\r\n self._timeout.unref();\r\n }\r\n }\r\n self._fn(self._attempts);\r\n }, timeout);\r\n if (this._options.unref) {\r\n this._timer.unref();\r\n }\r\n return true;\r\n };\r\n RetryOperation.prototype.attempt = function(fn, timeoutOps) {\r\n this._fn = fn;\r\n if (timeoutOps) {\r\n if (timeoutOps.timeout) {\r\n this._operationTimeout = timeoutOps.timeout;\r\n }\r\n if (timeoutOps.cb) {\r\n this._operationTimeoutCb = timeoutOps.cb;\r\n }\r\n }\r\n var self = this;\r\n if (this._operationTimeoutCb) {\r\n this._timeout = setTimeout(function() {\r\n self._operationTimeoutCb();\r\n }, self._operationTimeout);\r\n }\r\n this._operationStart = (/* @__PURE__ */ new Date()).getTime();\r\n this._fn(this._attempts);\r\n };\r\n RetryOperation.prototype.try = function(fn) {\r\n console.log(\"Using RetryOperation.try() is deprecated\");\r\n this.attempt(fn);\r\n };\r\n RetryOperation.prototype.start = function(fn) {\r\n console.log(\"Using RetryOperation.start() is deprecated\");\r\n this.attempt(fn);\r\n };\r\n RetryOperation.prototype.start = RetryOperation.prototype.try;\r\n RetryOperation.prototype.errors = function() {\r\n return this._errors;\r\n };\r\n RetryOperation.prototype.attempts = function() {\r\n return this._attempts;\r\n };\r\n RetryOperation.prototype.mainError = function() {\r\n if (this._errors.length === 0) {\r\n return null;\r\n }\r\n var counts = {};\r\n var mainError = null;\r\n var mainErrorCount = 0;\r\n for (var i = 0; i < this._errors.length; i++) {\r\n var error = this._errors[i];\r\n var message = error.message;\r\n var count = (counts[message] || 0) + 1;\r\n counts[message] = count;\r\n if (count >= mainErrorCount) {\r\n mainError = error;\r\n mainErrorCount = count;\r\n }\r\n }\r\n return mainError;\r\n };\r\n }\r\n});\r\n\r\n// node_modules/retry/lib/retry.js\r\nvar require_retry = __commonJS({\r\n \"node_modules/retry/lib/retry.js\"(exports) {\r\n var RetryOperation = require_retry_operation();\r\n exports.operation = function(options) {\r\n var timeouts = exports.timeouts(options);\r\n return new RetryOperation(timeouts, {\r\n forever: options && (options.forever || options.retries === Infinity),\r\n unref: options && options.unref,\r\n maxRetryTime: options && options.maxRetryTime\r\n });\r\n };\r\n exports.timeouts = function(options) {\r\n if (options instanceof Array) {\r\n return [].concat(options);\r\n }\r\n var opts = {\r\n retries: 10,\r\n factor: 2,\r\n minTimeout: 1 * 1e3,\r\n maxTimeout: Infinity,\r\n randomize: false\r\n };\r\n for (var key in options) {\r\n opts[key] = options[key];\r\n }\r\n if (opts.minTimeout > opts.maxTimeout) {\r\n throw new Error(\"minTimeout is greater than maxTimeout\");\r\n }\r\n var timeouts = [];\r\n for (var i = 0; i < opts.retries; i++) {\r\n timeouts.push(this.createTimeout(i, opts));\r\n }\r\n if (options && options.forever && !timeouts.length) {\r\n timeouts.push(this.createTimeout(i, opts));\r\n }\r\n timeouts.sort(function(a, b) {\r\n return a - b;\r\n });\r\n return timeouts;\r\n };\r\n exports.createTimeout = function(attempt, opts) {\r\n var random = opts.randomize ? Math.random() + 1 : 1;\r\n var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));\r\n timeout = Math.min(timeout, opts.maxTimeout);\r\n return timeout;\r\n };\r\n exports.wrap = function(obj, options, methods) {\r\n if (options instanceof Array) {\r\n methods = options;\r\n options = null;\r\n }\r\n if (!methods) {\r\n methods = [];\r\n for (var key in obj) {\r\n if (typeof obj[key] === \"function\") {\r\n methods.push(key);\r\n }\r\n }\r\n }\r\n for (var i = 0; i < methods.length; i++) {\r\n var method = methods[i];\r\n var original = obj[method];\r\n obj[method] = function retryWrapper(original2) {\r\n var op = exports.operation(options);\r\n var args = Array.prototype.slice.call(arguments, 1);\r\n var callback = args.pop();\r\n args.push(function(err) {\r\n if (op.retry(err)) {\r\n return;\r\n }\r\n if (err) {\r\n arguments[0] = op.mainError();\r\n }\r\n callback.apply(this, arguments);\r\n });\r\n op.attempt(function() {\r\n original2.apply(obj, args);\r\n });\r\n }.bind(obj, original);\r\n obj[method].options = options;\r\n }\r\n };\r\n }\r\n});\r\n\r\n// node_modules/retry/index.js\r\nvar require_retry2 = __commonJS({\r\n \"node_modules/retry/index.js\"(exports, module) {\r\n module.exports = require_retry();\r\n }\r\n});\r\n\r\n// node_modules/p-retry/index.js\r\nvar require_p_retry = __commonJS({\r\n \"node_modules/p-retry/index.js\"(exports, module) {\r\n \"use strict\";\r\n var retry = require_retry2();\r\n var networkErrorMsgs = [\r\n \"Failed to fetch\",\r\n // Chrome\r\n \"NetworkError when attempting to fetch resource.\",\r\n // Firefox\r\n \"The Internet connection appears to be offline.\",\r\n // Safari\r\n \"Network request failed\"\r\n // `cross-fetch`\r\n ];\r\n var AbortError2 = class extends Error {\r\n constructor(message) {\r\n super();\r\n if (message instanceof Error) {\r\n this.originalError = message;\r\n ({ message } = message);\r\n } else {\r\n this.originalError = new Error(message);\r\n this.originalError.stack = this.stack;\r\n }\r\n this.name = \"AbortError\";\r\n this.message = message;\r\n }\r\n };\r\n var decorateErrorWithCounts = (error, attemptNumber, options) => {\r\n const retriesLeft = options.retries - (attemptNumber - 1);\r\n error.attemptNumber = attemptNumber;\r\n error.retriesLeft = retriesLeft;\r\n return error;\r\n };\r\n var isNetworkError = (errorMessage) => networkErrorMsgs.includes(errorMessage);\r\n var pRetry2 = (input, options) => new Promise((resolve, reject) => {\r\n options = {\r\n onFailedAttempt: () => {\r\n },\r\n retries: 10,\r\n ...options\r\n };\r\n const operation = retry.operation(options);\r\n operation.attempt(async (attemptNumber) => {\r\n try {\r\n resolve(await input(attemptNumber));\r\n } catch (error) {\r\n if (!(error instanceof Error)) {\r\n reject(new TypeError(`Non-error was thrown: \"${error}\". You should only throw errors.`));\r\n return;\r\n }\r\n if (error instanceof AbortError2) {\r\n operation.stop();\r\n reject(error.originalError);\r\n } else if (error instanceof TypeError && !isNetworkError(error.message)) {\r\n operation.stop();\r\n reject(error);\r\n } else {\r\n decorateErrorWithCounts(error, attemptNumber, options);\r\n try {\r\n await options.onFailedAttempt(error);\r\n } catch (error2) {\r\n reject(error2);\r\n return;\r\n }\r\n if (!operation.retry(error)) {\r\n reject(operation.mainError());\r\n }\r\n }\r\n }\r\n });\r\n });\r\n module.exports = pRetry2;\r\n module.exports.default = pRetry2;\r\n module.exports.AbortError = AbortError2;\r\n }\r\n});\r\n\r\n// node_modules/@google/genai/dist/web/index.mjs\r\nvar web_exports = {};\r\n__export(web_exports, {\r\n ActivityHandling: () => ActivityHandling,\r\n AdapterSize: () => AdapterSize,\r\n AggregationMetric: () => AggregationMetric,\r\n ApiError: () => ApiError,\r\n ApiSpec: () => ApiSpec,\r\n AuthType: () => AuthType,\r\n Batches: () => Batches,\r\n Behavior: () => Behavior,\r\n BlockedReason: () => BlockedReason,\r\n Caches: () => Caches,\r\n CancelTuningJobResponse: () => CancelTuningJobResponse,\r\n Chat: () => Chat,\r\n Chats: () => Chats,\r\n ComputeTokensResponse: () => ComputeTokensResponse,\r\n ContentReferenceImage: () => ContentReferenceImage,\r\n ControlReferenceImage: () => ControlReferenceImage,\r\n ControlReferenceType: () => ControlReferenceType,\r\n CountTokensResponse: () => CountTokensResponse,\r\n CreateFileResponse: () => CreateFileResponse,\r\n DeleteCachedContentResponse: () => DeleteCachedContentResponse,\r\n DeleteFileResponse: () => DeleteFileResponse,\r\n DeleteModelResponse: () => DeleteModelResponse,\r\n DocumentState: () => DocumentState,\r\n DynamicRetrievalConfigMode: () => DynamicRetrievalConfigMode,\r\n EditImageResponse: () => EditImageResponse,\r\n EditMode: () => EditMode,\r\n EmbedContentResponse: () => EmbedContentResponse,\r\n EmbeddingApiType: () => EmbeddingApiType,\r\n EndSensitivity: () => EndSensitivity,\r\n Environment: () => Environment,\r\n EvaluateDatasetResponse: () => EvaluateDatasetResponse,\r\n FeatureSelectionPreference: () => FeatureSelectionPreference,\r\n FileSource: () => FileSource,\r\n FileState: () => FileState,\r\n Files: () => Files,\r\n FinishReason: () => FinishReason,\r\n FunctionCallingConfigMode: () => FunctionCallingConfigMode,\r\n FunctionResponse: () => FunctionResponse,\r\n FunctionResponseBlob: () => FunctionResponseBlob,\r\n FunctionResponseFileData: () => FunctionResponseFileData,\r\n FunctionResponsePart: () => FunctionResponsePart,\r\n FunctionResponseScheduling: () => FunctionResponseScheduling,\r\n GenerateContentResponse: () => GenerateContentResponse,\r\n GenerateContentResponsePromptFeedback: () => GenerateContentResponsePromptFeedback,\r\n GenerateContentResponseUsageMetadata: () => GenerateContentResponseUsageMetadata,\r\n GenerateImagesResponse: () => GenerateImagesResponse,\r\n GenerateVideosOperation: () => GenerateVideosOperation,\r\n GenerateVideosResponse: () => GenerateVideosResponse,\r\n GoogleGenAI: () => GoogleGenAI,\r\n HarmBlockMethod: () => HarmBlockMethod,\r\n HarmBlockThreshold: () => HarmBlockThreshold,\r\n HarmCategory: () => HarmCategory,\r\n HarmProbability: () => HarmProbability,\r\n HarmSeverity: () => HarmSeverity,\r\n HttpElementLocation: () => HttpElementLocation,\r\n HttpResponse: () => HttpResponse,\r\n ImagePromptLanguage: () => ImagePromptLanguage,\r\n ImportFileOperation: () => ImportFileOperation,\r\n ImportFileResponse: () => ImportFileResponse,\r\n InlinedEmbedContentResponse: () => InlinedEmbedContentResponse,\r\n InlinedResponse: () => InlinedResponse,\r\n JobState: () => JobState,\r\n Language: () => Language,\r\n ListBatchJobsResponse: () => ListBatchJobsResponse,\r\n ListCachedContentsResponse: () => ListCachedContentsResponse,\r\n ListDocumentsResponse: () => ListDocumentsResponse,\r\n ListFileSearchStoresResponse: () => ListFileSearchStoresResponse,\r\n ListFilesResponse: () => ListFilesResponse,\r\n ListModelsResponse: () => ListModelsResponse,\r\n ListTuningJobsResponse: () => ListTuningJobsResponse,\r\n Live: () => Live,\r\n LiveClientToolResponse: () => LiveClientToolResponse,\r\n LiveMusicPlaybackControl: () => LiveMusicPlaybackControl,\r\n LiveMusicServerMessage: () => LiveMusicServerMessage,\r\n LiveSendToolResponseParameters: () => LiveSendToolResponseParameters,\r\n LiveServerMessage: () => LiveServerMessage,\r\n MaskReferenceImage: () => MaskReferenceImage,\r\n MaskReferenceMode: () => MaskReferenceMode,\r\n MediaModality: () => MediaModality,\r\n MediaResolution: () => MediaResolution,\r\n Modality: () => Modality,\r\n ModelStage: () => ModelStage,\r\n Models: () => Models,\r\n MusicGenerationMode: () => MusicGenerationMode,\r\n Operations: () => Operations,\r\n Outcome: () => Outcome,\r\n PagedItem: () => PagedItem,\r\n Pager: () => Pager,\r\n PairwiseChoice: () => PairwiseChoice,\r\n PartMediaResolutionLevel: () => PartMediaResolutionLevel,\r\n PersonGeneration: () => PersonGeneration,\r\n PhishBlockThreshold: () => PhishBlockThreshold,\r\n ProminentPeople: () => ProminentPeople,\r\n RawReferenceImage: () => RawReferenceImage,\r\n RecontextImageResponse: () => RecontextImageResponse,\r\n RegisterFilesResponse: () => RegisterFilesResponse,\r\n ReplayResponse: () => ReplayResponse,\r\n ResourceScope: () => ResourceScope,\r\n SafetyFilterLevel: () => SafetyFilterLevel,\r\n Scale: () => Scale,\r\n SegmentImageResponse: () => SegmentImageResponse,\r\n SegmentMode: () => SegmentMode,\r\n ServiceTier: () => ServiceTier,\r\n Session: () => Session,\r\n SingleEmbedContentResponse: () => SingleEmbedContentResponse,\r\n StartSensitivity: () => StartSensitivity,\r\n StyleReferenceImage: () => StyleReferenceImage,\r\n SubjectReferenceImage: () => SubjectReferenceImage,\r\n SubjectReferenceType: () => SubjectReferenceType,\r\n ThinkingLevel: () => ThinkingLevel,\r\n Tokens: () => Tokens,\r\n ToolResponse: () => ToolResponse,\r\n ToolType: () => ToolType,\r\n TrafficType: () => TrafficType,\r\n TuningJobState: () => TuningJobState,\r\n TuningMethod: () => TuningMethod,\r\n TuningMode: () => TuningMode,\r\n TuningTask: () => TuningTask,\r\n TurnCompleteReason: () => TurnCompleteReason,\r\n TurnCoverage: () => TurnCoverage,\r\n Type: () => Type,\r\n UploadToFileSearchStoreOperation: () => UploadToFileSearchStoreOperation,\r\n UploadToFileSearchStoreResponse: () => UploadToFileSearchStoreResponse,\r\n UploadToFileSearchStoreResumableResponse: () => UploadToFileSearchStoreResumableResponse,\r\n UpscaleImageResponse: () => UpscaleImageResponse,\r\n UrlRetrievalStatus: () => UrlRetrievalStatus,\r\n VadSignalType: () => VadSignalType,\r\n VideoCompressionQuality: () => VideoCompressionQuality,\r\n VideoGenerationMaskMode: () => VideoGenerationMaskMode,\r\n VideoGenerationReferenceType: () => VideoGenerationReferenceType,\r\n VoiceActivityType: () => VoiceActivityType,\r\n createFunctionResponsePartFromBase64: () => createFunctionResponsePartFromBase64,\r\n createFunctionResponsePartFromUri: () => createFunctionResponsePartFromUri,\r\n createModelContent: () => createModelContent,\r\n createPartFromBase64: () => createPartFromBase64,\r\n createPartFromCodeExecutionResult: () => createPartFromCodeExecutionResult,\r\n createPartFromExecutableCode: () => createPartFromExecutableCode,\r\n createPartFromFunctionCall: () => createPartFromFunctionCall,\r\n createPartFromFunctionResponse: () => createPartFromFunctionResponse,\r\n createPartFromText: () => createPartFromText,\r\n createPartFromUri: () => createPartFromUri,\r\n createUserContent: () => createUserContent,\r\n mcpToTool: () => mcpToTool,\r\n setDefaultBaseUrls: () => setDefaultBaseUrls\r\n});\r\nfunction setDefaultBaseUrls(baseUrlParams) {\r\n _defaultBaseGeminiUrl = baseUrlParams.geminiUrl;\r\n _defaultBaseVertexUrl = baseUrlParams.vertexUrl;\r\n}\r\nfunction getDefaultBaseUrls() {\r\n return {\r\n geminiUrl: _defaultBaseGeminiUrl,\r\n vertexUrl: _defaultBaseVertexUrl\r\n };\r\n}\r\nfunction getBaseUrl(httpOptions, vertexai, vertexBaseUrlFromEnv, geminiBaseUrlFromEnv) {\r\n var _a2, _b;\r\n if (!(httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.baseUrl)) {\r\n const defaultBaseUrls = getDefaultBaseUrls();\r\n if (vertexai) {\r\n return (_a2 = defaultBaseUrls.vertexUrl) !== null && _a2 !== void 0 ? _a2 : vertexBaseUrlFromEnv;\r\n } else {\r\n return (_b = defaultBaseUrls.geminiUrl) !== null && _b !== void 0 ? _b : geminiBaseUrlFromEnv;\r\n }\r\n }\r\n return httpOptions.baseUrl;\r\n}\r\nfunction formatMap(templateString, valueMap) {\r\n const regex = /\\{([^}]+)\\}/g;\r\n return templateString.replace(regex, (match, key) => {\r\n if (Object.prototype.hasOwnProperty.call(valueMap, key)) {\r\n const value = valueMap[key];\r\n return value !== void 0 && value !== null ? String(value) : \"\";\r\n } else {\r\n throw new Error(`Key '${key}' not found in valueMap.`);\r\n }\r\n });\r\n}\r\nfunction setValueByPath(data, keys, value) {\r\n for (let i = 0; i < keys.length - 1; i++) {\r\n const key = keys[i];\r\n if (key.endsWith(\"[]\")) {\r\n const keyName = key.slice(0, -2);\r\n if (!(keyName in data)) {\r\n if (Array.isArray(value)) {\r\n data[keyName] = Array.from({ length: value.length }, () => ({}));\r\n } else {\r\n throw new Error(`Value must be a list given an array path ${key}`);\r\n }\r\n }\r\n if (Array.isArray(data[keyName])) {\r\n const arrayData = data[keyName];\r\n if (Array.isArray(value)) {\r\n for (let j = 0; j < arrayData.length; j++) {\r\n const entry = arrayData[j];\r\n setValueByPath(entry, keys.slice(i + 1), value[j]);\r\n }\r\n } else {\r\n for (const d of arrayData) {\r\n setValueByPath(d, keys.slice(i + 1), value);\r\n }\r\n }\r\n }\r\n return;\r\n } else if (key.endsWith(\"[0]\")) {\r\n const keyName = key.slice(0, -3);\r\n if (!(keyName in data)) {\r\n data[keyName] = [{}];\r\n }\r\n const arrayData = data[keyName];\r\n setValueByPath(arrayData[0], keys.slice(i + 1), value);\r\n return;\r\n }\r\n if (!data[key] || typeof data[key] !== \"object\") {\r\n data[key] = {};\r\n }\r\n data = data[key];\r\n }\r\n const keyToSet = keys[keys.length - 1];\r\n const existingData = data[keyToSet];\r\n if (existingData !== void 0) {\r\n if (!value || typeof value === \"object\" && Object.keys(value).length === 0) {\r\n return;\r\n }\r\n if (value === existingData) {\r\n return;\r\n }\r\n if (typeof existingData === \"object\" && typeof value === \"object\" && existingData !== null && value !== null) {\r\n Object.assign(existingData, value);\r\n } else {\r\n throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);\r\n }\r\n } else {\r\n if (keyToSet === \"_self\" && typeof value === \"object\" && value !== null && !Array.isArray(value)) {\r\n const valueAsRecord = value;\r\n Object.assign(data, valueAsRecord);\r\n } else {\r\n data[keyToSet] = value;\r\n }\r\n }\r\n}\r\nfunction getValueByPath(data, keys, defaultValue = void 0) {\r\n try {\r\n if (keys.length === 1 && keys[0] === \"_self\") {\r\n return data;\r\n }\r\n for (let i = 0; i < keys.length; i++) {\r\n if (typeof data !== \"object\" || data === null) {\r\n return defaultValue;\r\n }\r\n const key = keys[i];\r\n if (key.endsWith(\"[]\")) {\r\n const keyName = key.slice(0, -2);\r\n if (keyName in data) {\r\n const arrayData = data[keyName];\r\n if (!Array.isArray(arrayData)) {\r\n return defaultValue;\r\n }\r\n return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1), defaultValue));\r\n } else {\r\n return defaultValue;\r\n }\r\n } else {\r\n data = data[key];\r\n }\r\n }\r\n return data;\r\n } catch (error) {\r\n if (error instanceof TypeError) {\r\n return defaultValue;\r\n }\r\n throw error;\r\n }\r\n}\r\nfunction moveValueByPath(data, paths) {\r\n for (const [sourcePath, destPath] of Object.entries(paths)) {\r\n const sourceKeys = sourcePath.split(\".\");\r\n const destKeys = destPath.split(\".\");\r\n const excludeKeys = /* @__PURE__ */ new Set();\r\n let wildcardIdx = -1;\r\n for (let i = 0; i < sourceKeys.length; i++) {\r\n if (sourceKeys[i] === \"*\") {\r\n wildcardIdx = i;\r\n break;\r\n }\r\n }\r\n if (wildcardIdx !== -1 && destKeys.length > wildcardIdx) {\r\n for (let i = wildcardIdx; i < destKeys.length; i++) {\r\n const key = destKeys[i];\r\n if (key !== \"*\" && !key.endsWith(\"[]\") && !key.endsWith(\"[0]\")) {\r\n excludeKeys.add(key);\r\n }\r\n }\r\n }\r\n _moveValueRecursive(data, sourceKeys, destKeys, 0, excludeKeys);\r\n }\r\n}\r\nfunction _moveValueRecursive(data, sourceKeys, destKeys, keyIdx, excludeKeys) {\r\n if (keyIdx >= sourceKeys.length) {\r\n return;\r\n }\r\n if (typeof data !== \"object\" || data === null) {\r\n return;\r\n }\r\n const key = sourceKeys[keyIdx];\r\n if (key.endsWith(\"[]\")) {\r\n const keyName = key.slice(0, -2);\r\n const dataRecord = data;\r\n if (keyName in dataRecord && Array.isArray(dataRecord[keyName])) {\r\n for (const item of dataRecord[keyName]) {\r\n _moveValueRecursive(item, sourceKeys, destKeys, keyIdx + 1, excludeKeys);\r\n }\r\n }\r\n } else if (key === \"*\") {\r\n if (typeof data === \"object\" && data !== null && !Array.isArray(data)) {\r\n const dataRecord = data;\r\n const keysToMove = Object.keys(dataRecord).filter((k) => !k.startsWith(\"_\") && !excludeKeys.has(k));\r\n const valuesToMove = {};\r\n for (const k of keysToMove) {\r\n valuesToMove[k] = dataRecord[k];\r\n }\r\n for (const [k, v] of Object.entries(valuesToMove)) {\r\n const newDestKeys = [];\r\n for (const dk of destKeys.slice(keyIdx)) {\r\n if (dk === \"*\") {\r\n newDestKeys.push(k);\r\n } else {\r\n newDestKeys.push(dk);\r\n }\r\n }\r\n setValueByPath(dataRecord, newDestKeys, v);\r\n }\r\n for (const k of keysToMove) {\r\n delete dataRecord[k];\r\n }\r\n }\r\n } else {\r\n const dataRecord = data;\r\n if (key in dataRecord) {\r\n _moveValueRecursive(dataRecord[key], sourceKeys, destKeys, keyIdx + 1, excludeKeys);\r\n }\r\n }\r\n}\r\nfunction tBytes$1(fromBytes) {\r\n if (typeof fromBytes !== \"string\") {\r\n throw new Error(\"fromImageBytes must be a string\");\r\n }\r\n return fromBytes;\r\n}\r\nfunction fetchPredictOperationParametersToVertex(fromObject) {\r\n const toObject = {};\r\n const fromOperationName = getValueByPath(fromObject, [\r\n \"operationName\"\r\n ]);\r\n if (fromOperationName != null) {\r\n setValueByPath(toObject, [\"operationName\"], fromOperationName);\r\n }\r\n const fromResourceName = getValueByPath(fromObject, [\"resourceName\"]);\r\n if (fromResourceName != null) {\r\n setValueByPath(toObject, [\"_url\", \"resourceName\"], fromResourceName);\r\n }\r\n return toObject;\r\n}\r\nfunction generateVideosOperationFromMldev$1(fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromMetadata = getValueByPath(fromObject, [\"metadata\"]);\r\n if (fromMetadata != null) {\r\n setValueByPath(toObject, [\"metadata\"], fromMetadata);\r\n }\r\n const fromDone = getValueByPath(fromObject, [\"done\"]);\r\n if (fromDone != null) {\r\n setValueByPath(toObject, [\"done\"], fromDone);\r\n }\r\n const fromError = getValueByPath(fromObject, [\"error\"]);\r\n if (fromError != null) {\r\n setValueByPath(toObject, [\"error\"], fromError);\r\n }\r\n const fromResponse = getValueByPath(fromObject, [\r\n \"response\",\r\n \"generateVideoResponse\"\r\n ]);\r\n if (fromResponse != null) {\r\n setValueByPath(toObject, [\"response\"], generateVideosResponseFromMldev$1(fromResponse));\r\n }\r\n return toObject;\r\n}\r\nfunction generateVideosOperationFromVertex$1(fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromMetadata = getValueByPath(fromObject, [\"metadata\"]);\r\n if (fromMetadata != null) {\r\n setValueByPath(toObject, [\"metadata\"], fromMetadata);\r\n }\r\n const fromDone = getValueByPath(fromObject, [\"done\"]);\r\n if (fromDone != null) {\r\n setValueByPath(toObject, [\"done\"], fromDone);\r\n }\r\n const fromError = getValueByPath(fromObject, [\"error\"]);\r\n if (fromError != null) {\r\n setValueByPath(toObject, [\"error\"], fromError);\r\n }\r\n const fromResponse = getValueByPath(fromObject, [\"response\"]);\r\n if (fromResponse != null) {\r\n setValueByPath(toObject, [\"response\"], generateVideosResponseFromVertex$1(fromResponse));\r\n }\r\n return toObject;\r\n}\r\nfunction generateVideosResponseFromMldev$1(fromObject) {\r\n const toObject = {};\r\n const fromGeneratedVideos = getValueByPath(fromObject, [\r\n \"generatedSamples\"\r\n ]);\r\n if (fromGeneratedVideos != null) {\r\n let transformedList = fromGeneratedVideos;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return generatedVideoFromMldev$1(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"generatedVideos\"], transformedList);\r\n }\r\n const fromRaiMediaFilteredCount = getValueByPath(fromObject, [\r\n \"raiMediaFilteredCount\"\r\n ]);\r\n if (fromRaiMediaFilteredCount != null) {\r\n setValueByPath(toObject, [\"raiMediaFilteredCount\"], fromRaiMediaFilteredCount);\r\n }\r\n const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [\r\n \"raiMediaFilteredReasons\"\r\n ]);\r\n if (fromRaiMediaFilteredReasons != null) {\r\n setValueByPath(toObject, [\"raiMediaFilteredReasons\"], fromRaiMediaFilteredReasons);\r\n }\r\n return toObject;\r\n}\r\nfunction generateVideosResponseFromVertex$1(fromObject) {\r\n const toObject = {};\r\n const fromGeneratedVideos = getValueByPath(fromObject, [\"videos\"]);\r\n if (fromGeneratedVideos != null) {\r\n let transformedList = fromGeneratedVideos;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return generatedVideoFromVertex$1(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"generatedVideos\"], transformedList);\r\n }\r\n const fromRaiMediaFilteredCount = getValueByPath(fromObject, [\r\n \"raiMediaFilteredCount\"\r\n ]);\r\n if (fromRaiMediaFilteredCount != null) {\r\n setValueByPath(toObject, [\"raiMediaFilteredCount\"], fromRaiMediaFilteredCount);\r\n }\r\n const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [\r\n \"raiMediaFilteredReasons\"\r\n ]);\r\n if (fromRaiMediaFilteredReasons != null) {\r\n setValueByPath(toObject, [\"raiMediaFilteredReasons\"], fromRaiMediaFilteredReasons);\r\n }\r\n return toObject;\r\n}\r\nfunction generatedVideoFromMldev$1(fromObject) {\r\n const toObject = {};\r\n const fromVideo = getValueByPath(fromObject, [\"video\"]);\r\n if (fromVideo != null) {\r\n setValueByPath(toObject, [\"video\"], videoFromMldev$1(fromVideo));\r\n }\r\n return toObject;\r\n}\r\nfunction generatedVideoFromVertex$1(fromObject) {\r\n const toObject = {};\r\n const fromVideo = getValueByPath(fromObject, [\"_self\"]);\r\n if (fromVideo != null) {\r\n setValueByPath(toObject, [\"video\"], videoFromVertex$1(fromVideo));\r\n }\r\n return toObject;\r\n}\r\nfunction getOperationParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromOperationName = getValueByPath(fromObject, [\r\n \"operationName\"\r\n ]);\r\n if (fromOperationName != null) {\r\n setValueByPath(toObject, [\"_url\", \"operationName\"], fromOperationName);\r\n }\r\n return toObject;\r\n}\r\nfunction getOperationParametersToVertex(fromObject) {\r\n const toObject = {};\r\n const fromOperationName = getValueByPath(fromObject, [\r\n \"operationName\"\r\n ]);\r\n if (fromOperationName != null) {\r\n setValueByPath(toObject, [\"_url\", \"operationName\"], fromOperationName);\r\n }\r\n return toObject;\r\n}\r\nfunction importFileOperationFromMldev$1(fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromMetadata = getValueByPath(fromObject, [\"metadata\"]);\r\n if (fromMetadata != null) {\r\n setValueByPath(toObject, [\"metadata\"], fromMetadata);\r\n }\r\n const fromDone = getValueByPath(fromObject, [\"done\"]);\r\n if (fromDone != null) {\r\n setValueByPath(toObject, [\"done\"], fromDone);\r\n }\r\n const fromError = getValueByPath(fromObject, [\"error\"]);\r\n if (fromError != null) {\r\n setValueByPath(toObject, [\"error\"], fromError);\r\n }\r\n const fromResponse = getValueByPath(fromObject, [\"response\"]);\r\n if (fromResponse != null) {\r\n setValueByPath(toObject, [\"response\"], importFileResponseFromMldev$1(fromResponse));\r\n }\r\n return toObject;\r\n}\r\nfunction importFileResponseFromMldev$1(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromParent = getValueByPath(fromObject, [\"parent\"]);\r\n if (fromParent != null) {\r\n setValueByPath(toObject, [\"parent\"], fromParent);\r\n }\r\n const fromDocumentName = getValueByPath(fromObject, [\"documentName\"]);\r\n if (fromDocumentName != null) {\r\n setValueByPath(toObject, [\"documentName\"], fromDocumentName);\r\n }\r\n return toObject;\r\n}\r\nfunction uploadToFileSearchStoreOperationFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromMetadata = getValueByPath(fromObject, [\"metadata\"]);\r\n if (fromMetadata != null) {\r\n setValueByPath(toObject, [\"metadata\"], fromMetadata);\r\n }\r\n const fromDone = getValueByPath(fromObject, [\"done\"]);\r\n if (fromDone != null) {\r\n setValueByPath(toObject, [\"done\"], fromDone);\r\n }\r\n const fromError = getValueByPath(fromObject, [\"error\"]);\r\n if (fromError != null) {\r\n setValueByPath(toObject, [\"error\"], fromError);\r\n }\r\n const fromResponse = getValueByPath(fromObject, [\"response\"]);\r\n if (fromResponse != null) {\r\n setValueByPath(toObject, [\"response\"], uploadToFileSearchStoreResponseFromMldev(fromResponse));\r\n }\r\n return toObject;\r\n}\r\nfunction uploadToFileSearchStoreResponseFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromParent = getValueByPath(fromObject, [\"parent\"]);\r\n if (fromParent != null) {\r\n setValueByPath(toObject, [\"parent\"], fromParent);\r\n }\r\n const fromDocumentName = getValueByPath(fromObject, [\"documentName\"]);\r\n if (fromDocumentName != null) {\r\n setValueByPath(toObject, [\"documentName\"], fromDocumentName);\r\n }\r\n return toObject;\r\n}\r\nfunction videoFromMldev$1(fromObject) {\r\n const toObject = {};\r\n const fromUri = getValueByPath(fromObject, [\"uri\"]);\r\n if (fromUri != null) {\r\n setValueByPath(toObject, [\"uri\"], fromUri);\r\n }\r\n const fromVideoBytes = getValueByPath(fromObject, [\"encodedVideo\"]);\r\n if (fromVideoBytes != null) {\r\n setValueByPath(toObject, [\"videoBytes\"], tBytes$1(fromVideoBytes));\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"encoding\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction videoFromVertex$1(fromObject) {\r\n const toObject = {};\r\n const fromUri = getValueByPath(fromObject, [\"gcsUri\"]);\r\n if (fromUri != null) {\r\n setValueByPath(toObject, [\"uri\"], fromUri);\r\n }\r\n const fromVideoBytes = getValueByPath(fromObject, [\r\n \"bytesBase64Encoded\"\r\n ]);\r\n if (fromVideoBytes != null) {\r\n setValueByPath(toObject, [\"videoBytes\"], tBytes$1(fromVideoBytes));\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction createFunctionResponsePartFromBase64(data, mimeType) {\r\n return {\r\n inlineData: {\r\n data,\r\n mimeType\r\n }\r\n };\r\n}\r\nfunction createFunctionResponsePartFromUri(uri, mimeType) {\r\n return {\r\n fileData: {\r\n fileUri: uri,\r\n mimeType\r\n }\r\n };\r\n}\r\nfunction createPartFromUri(uri, mimeType, mediaResolution) {\r\n return Object.assign({ fileData: {\r\n fileUri: uri,\r\n mimeType\r\n } }, mediaResolution && { mediaResolution: { level: mediaResolution } });\r\n}\r\nfunction createPartFromText(text) {\r\n return {\r\n text\r\n };\r\n}\r\nfunction createPartFromFunctionCall(name, args) {\r\n return {\r\n functionCall: {\r\n name,\r\n args\r\n }\r\n };\r\n}\r\nfunction createPartFromFunctionResponse(id, name, response, parts = []) {\r\n return {\r\n functionResponse: Object.assign({ id, name, response }, parts.length > 0 && { parts })\r\n };\r\n}\r\nfunction createPartFromBase64(data, mimeType, mediaResolution) {\r\n return Object.assign({ inlineData: {\r\n data,\r\n mimeType\r\n } }, mediaResolution && { mediaResolution: { level: mediaResolution } });\r\n}\r\nfunction createPartFromCodeExecutionResult(outcome, output) {\r\n return {\r\n codeExecutionResult: {\r\n outcome,\r\n output\r\n }\r\n };\r\n}\r\nfunction createPartFromExecutableCode(code, language) {\r\n return {\r\n executableCode: {\r\n code,\r\n language\r\n }\r\n };\r\n}\r\nfunction _isPart(obj) {\r\n if (typeof obj === \"object\" && obj !== null) {\r\n return \"fileData\" in obj || \"text\" in obj || \"functionCall\" in obj || \"functionResponse\" in obj || \"inlineData\" in obj || \"videoMetadata\" in obj || \"codeExecutionResult\" in obj || \"executableCode\" in obj;\r\n }\r\n return false;\r\n}\r\nfunction _toParts(partOrString) {\r\n const parts = [];\r\n if (typeof partOrString === \"string\") {\r\n parts.push(createPartFromText(partOrString));\r\n } else if (_isPart(partOrString)) {\r\n parts.push(partOrString);\r\n } else if (Array.isArray(partOrString)) {\r\n if (partOrString.length === 0) {\r\n throw new Error(\"partOrString cannot be an empty array\");\r\n }\r\n for (const part of partOrString) {\r\n if (typeof part === \"string\") {\r\n parts.push(createPartFromText(part));\r\n } else if (_isPart(part)) {\r\n parts.push(part);\r\n } else {\r\n throw new Error(\"element in PartUnion must be a Part object or string\");\r\n }\r\n }\r\n } else {\r\n throw new Error(\"partOrString must be a Part object, string, or array\");\r\n }\r\n return parts;\r\n}\r\nfunction createUserContent(partOrString) {\r\n return {\r\n role: \"user\",\r\n parts: _toParts(partOrString)\r\n };\r\n}\r\nfunction createModelContent(partOrString) {\r\n return {\r\n role: \"model\",\r\n parts: _toParts(partOrString)\r\n };\r\n}\r\nfunction tModel(apiClient, model) {\r\n if (!model || typeof model !== \"string\") {\r\n throw new Error(\"model is required and must be a string\");\r\n }\r\n if (model.includes(\"..\") || model.includes(\"?\") || model.includes(\"&\")) {\r\n throw new Error(\"invalid model parameter\");\r\n }\r\n if (apiClient.isVertexAI()) {\r\n if (model.startsWith(\"publishers/\") || model.startsWith(\"projects/\") || model.startsWith(\"models/\")) {\r\n return model;\r\n } else if (model.indexOf(\"/\") >= 0) {\r\n const parts = model.split(\"/\", 2);\r\n return `publishers/${parts[0]}/models/${parts[1]}`;\r\n } else {\r\n return `publishers/google/models/${model}`;\r\n }\r\n } else {\r\n if (model.startsWith(\"models/\") || model.startsWith(\"tunedModels/\")) {\r\n return model;\r\n } else {\r\n return `models/${model}`;\r\n }\r\n }\r\n}\r\nfunction tCachesModel(apiClient, model) {\r\n const transformedModel = tModel(apiClient, model);\r\n if (!transformedModel) {\r\n return \"\";\r\n }\r\n if (transformedModel.startsWith(\"publishers/\") && apiClient.isVertexAI()) {\r\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;\r\n } else if (transformedModel.startsWith(\"models/\") && apiClient.isVertexAI()) {\r\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;\r\n } else {\r\n return transformedModel;\r\n }\r\n}\r\nfunction tBlobs(blobs) {\r\n if (Array.isArray(blobs)) {\r\n return blobs.map((blob) => tBlob(blob));\r\n } else {\r\n return [tBlob(blobs)];\r\n }\r\n}\r\nfunction tBlob(blob) {\r\n if (typeof blob === \"object\" && blob !== null) {\r\n return blob;\r\n }\r\n throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`);\r\n}\r\nfunction tImageBlob(blob) {\r\n const transformedBlob = tBlob(blob);\r\n if (transformedBlob.mimeType && transformedBlob.mimeType.startsWith(\"image/\")) {\r\n return transformedBlob;\r\n }\r\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`);\r\n}\r\nfunction tAudioBlob(blob) {\r\n const transformedBlob = tBlob(blob);\r\n if (transformedBlob.mimeType && transformedBlob.mimeType.startsWith(\"audio/\")) {\r\n return transformedBlob;\r\n }\r\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`);\r\n}\r\nfunction tPart(origin) {\r\n if (origin === null || origin === void 0) {\r\n throw new Error(\"PartUnion is required\");\r\n }\r\n if (typeof origin === \"object\") {\r\n return origin;\r\n }\r\n if (typeof origin === \"string\") {\r\n return { text: origin };\r\n }\r\n throw new Error(`Unsupported part type: ${typeof origin}`);\r\n}\r\nfunction tParts(origin) {\r\n if (origin === null || origin === void 0 || Array.isArray(origin) && origin.length === 0) {\r\n throw new Error(\"PartListUnion is required\");\r\n }\r\n if (Array.isArray(origin)) {\r\n return origin.map((item) => tPart(item));\r\n }\r\n return [tPart(origin)];\r\n}\r\nfunction _isContent(origin) {\r\n return origin !== null && origin !== void 0 && typeof origin === \"object\" && \"parts\" in origin && Array.isArray(origin.parts);\r\n}\r\nfunction _isFunctionCallPart(origin) {\r\n return origin !== null && origin !== void 0 && typeof origin === \"object\" && \"functionCall\" in origin;\r\n}\r\nfunction _isFunctionResponsePart(origin) {\r\n return origin !== null && origin !== void 0 && typeof origin === \"object\" && \"functionResponse\" in origin;\r\n}\r\nfunction tContent(origin) {\r\n if (origin === null || origin === void 0) {\r\n throw new Error(\"ContentUnion is required\");\r\n }\r\n if (_isContent(origin)) {\r\n return origin;\r\n }\r\n return {\r\n role: \"user\",\r\n parts: tParts(origin)\r\n };\r\n}\r\nfunction tContentsForEmbed(apiClient, origin) {\r\n if (!origin) {\r\n return [];\r\n }\r\n if (apiClient.isVertexAI() && Array.isArray(origin)) {\r\n return origin.flatMap((item) => {\r\n const content = tContent(item);\r\n if (content.parts && content.parts.length > 0 && content.parts[0].text !== void 0) {\r\n return [content.parts[0].text];\r\n }\r\n return [];\r\n });\r\n } else if (apiClient.isVertexAI()) {\r\n const content = tContent(origin);\r\n if (content.parts && content.parts.length > 0 && content.parts[0].text !== void 0) {\r\n return [content.parts[0].text];\r\n }\r\n return [];\r\n }\r\n if (Array.isArray(origin)) {\r\n return origin.map((item) => tContent(item));\r\n }\r\n return [tContent(origin)];\r\n}\r\nfunction tContents(origin) {\r\n if (origin === null || origin === void 0 || Array.isArray(origin) && origin.length === 0) {\r\n throw new Error(\"contents are required\");\r\n }\r\n if (!Array.isArray(origin)) {\r\n if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) {\r\n throw new Error(\"To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them\");\r\n }\r\n return [tContent(origin)];\r\n }\r\n const result = [];\r\n const accumulatedParts = [];\r\n const isContentArray = _isContent(origin[0]);\r\n for (const item of origin) {\r\n const isContent = _isContent(item);\r\n if (isContent != isContentArray) {\r\n throw new Error(\"Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them\");\r\n }\r\n if (isContent) {\r\n result.push(item);\r\n } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) {\r\n throw new Error(\"To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them\");\r\n } else {\r\n accumulatedParts.push(item);\r\n }\r\n }\r\n if (!isContentArray) {\r\n result.push({ role: \"user\", parts: tParts(accumulatedParts) });\r\n }\r\n return result;\r\n}\r\nfunction flattenTypeArrayToAnyOf(typeList, resultingSchema) {\r\n if (typeList.includes(\"null\")) {\r\n resultingSchema[\"nullable\"] = true;\r\n }\r\n const listWithoutNull = typeList.filter((type) => type !== \"null\");\r\n if (listWithoutNull.length === 1) {\r\n resultingSchema[\"type\"] = Object.values(Type).includes(listWithoutNull[0].toUpperCase()) ? listWithoutNull[0].toUpperCase() : Type.TYPE_UNSPECIFIED;\r\n } else {\r\n resultingSchema[\"anyOf\"] = [];\r\n for (const i of listWithoutNull) {\r\n resultingSchema[\"anyOf\"].push({\r\n \"type\": Object.values(Type).includes(i.toUpperCase()) ? i.toUpperCase() : Type.TYPE_UNSPECIFIED\r\n });\r\n }\r\n }\r\n}\r\nfunction processJsonSchema(_jsonSchema) {\r\n const genAISchema = {};\r\n const schemaFieldNames = [\"items\"];\r\n const listSchemaFieldNames = [\"anyOf\"];\r\n const dictSchemaFieldNames = [\"properties\"];\r\n if (_jsonSchema[\"type\"] && _jsonSchema[\"anyOf\"]) {\r\n throw new Error(\"type and anyOf cannot be both populated.\");\r\n }\r\n const incomingAnyOf = _jsonSchema[\"anyOf\"];\r\n if (incomingAnyOf != null && incomingAnyOf.length == 2) {\r\n if (incomingAnyOf[0][\"type\"] === \"null\") {\r\n genAISchema[\"nullable\"] = true;\r\n _jsonSchema = incomingAnyOf[1];\r\n } else if (incomingAnyOf[1][\"type\"] === \"null\") {\r\n genAISchema[\"nullable\"] = true;\r\n _jsonSchema = incomingAnyOf[0];\r\n }\r\n }\r\n if (_jsonSchema[\"type\"] instanceof Array) {\r\n flattenTypeArrayToAnyOf(_jsonSchema[\"type\"], genAISchema);\r\n }\r\n for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) {\r\n if (fieldValue == null) {\r\n continue;\r\n }\r\n if (fieldName == \"type\") {\r\n if (fieldValue === \"null\") {\r\n throw new Error(\"type: null can not be the only possible type for the field.\");\r\n }\r\n if (fieldValue instanceof Array) {\r\n continue;\r\n }\r\n genAISchema[\"type\"] = Object.values(Type).includes(fieldValue.toUpperCase()) ? fieldValue.toUpperCase() : Type.TYPE_UNSPECIFIED;\r\n } else if (schemaFieldNames.includes(fieldName)) {\r\n genAISchema[fieldName] = processJsonSchema(fieldValue);\r\n } else if (listSchemaFieldNames.includes(fieldName)) {\r\n const listSchemaFieldValue = [];\r\n for (const item of fieldValue) {\r\n if (item[\"type\"] == \"null\") {\r\n genAISchema[\"nullable\"] = true;\r\n continue;\r\n }\r\n listSchemaFieldValue.push(processJsonSchema(item));\r\n }\r\n genAISchema[fieldName] = listSchemaFieldValue;\r\n } else if (dictSchemaFieldNames.includes(fieldName)) {\r\n const dictSchemaFieldValue = {};\r\n for (const [key, value] of Object.entries(fieldValue)) {\r\n dictSchemaFieldValue[key] = processJsonSchema(value);\r\n }\r\n genAISchema[fieldName] = dictSchemaFieldValue;\r\n } else {\r\n if (fieldName === \"additionalProperties\") {\r\n continue;\r\n }\r\n genAISchema[fieldName] = fieldValue;\r\n }\r\n }\r\n return genAISchema;\r\n}\r\nfunction tSchema(schema) {\r\n return processJsonSchema(schema);\r\n}\r\nfunction tSpeechConfig(speechConfig) {\r\n if (typeof speechConfig === \"object\") {\r\n return speechConfig;\r\n } else if (typeof speechConfig === \"string\") {\r\n return {\r\n voiceConfig: {\r\n prebuiltVoiceConfig: {\r\n voiceName: speechConfig\r\n }\r\n }\r\n };\r\n } else {\r\n throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);\r\n }\r\n}\r\nfunction tLiveSpeechConfig(speechConfig) {\r\n if (\"multiSpeakerVoiceConfig\" in speechConfig) {\r\n throw new Error(\"multiSpeakerVoiceConfig is not supported in the live API.\");\r\n }\r\n return speechConfig;\r\n}\r\nfunction tTool(tool) {\r\n if (tool.functionDeclarations) {\r\n for (const functionDeclaration of tool.functionDeclarations) {\r\n if (functionDeclaration.parameters) {\r\n if (!Object.keys(functionDeclaration.parameters).includes(\"$schema\")) {\r\n functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters);\r\n } else {\r\n if (!functionDeclaration.parametersJsonSchema) {\r\n functionDeclaration.parametersJsonSchema = functionDeclaration.parameters;\r\n delete functionDeclaration.parameters;\r\n }\r\n }\r\n }\r\n if (functionDeclaration.response) {\r\n if (!Object.keys(functionDeclaration.response).includes(\"$schema\")) {\r\n functionDeclaration.response = processJsonSchema(functionDeclaration.response);\r\n } else {\r\n if (!functionDeclaration.responseJsonSchema) {\r\n functionDeclaration.responseJsonSchema = functionDeclaration.response;\r\n delete functionDeclaration.response;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return tool;\r\n}\r\nfunction tTools(tools) {\r\n if (tools === void 0 || tools === null) {\r\n throw new Error(\"tools is required\");\r\n }\r\n if (!Array.isArray(tools)) {\r\n throw new Error(\"tools is required and must be an array of Tools\");\r\n }\r\n const result = [];\r\n for (const tool of tools) {\r\n result.push(tool);\r\n }\r\n return result;\r\n}\r\nfunction resourceName(client, resourceName2, resourcePrefix, splitsAfterPrefix = 1) {\r\n const shouldAppendPrefix = !resourceName2.startsWith(`${resourcePrefix}/`) && resourceName2.split(\"/\").length === splitsAfterPrefix;\r\n if (client.isVertexAI()) {\r\n if (resourceName2.startsWith(\"projects/\")) {\r\n return resourceName2;\r\n } else if (resourceName2.startsWith(\"locations/\")) {\r\n return `projects/${client.getProject()}/${resourceName2}`;\r\n } else if (resourceName2.startsWith(`${resourcePrefix}/`)) {\r\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName2}`;\r\n } else if (shouldAppendPrefix) {\r\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName2}`;\r\n } else {\r\n return resourceName2;\r\n }\r\n }\r\n if (shouldAppendPrefix) {\r\n return `${resourcePrefix}/${resourceName2}`;\r\n }\r\n return resourceName2;\r\n}\r\nfunction tCachedContentName(apiClient, name) {\r\n if (typeof name !== \"string\") {\r\n throw new Error(\"name must be a string\");\r\n }\r\n return resourceName(apiClient, name, \"cachedContents\");\r\n}\r\nfunction tTuningJobStatus(status) {\r\n switch (status) {\r\n case \"STATE_UNSPECIFIED\":\r\n return \"JOB_STATE_UNSPECIFIED\";\r\n case \"CREATING\":\r\n return \"JOB_STATE_RUNNING\";\r\n case \"ACTIVE\":\r\n return \"JOB_STATE_SUCCEEDED\";\r\n case \"FAILED\":\r\n return \"JOB_STATE_FAILED\";\r\n default:\r\n return status;\r\n }\r\n}\r\nfunction tBytes(fromImageBytes) {\r\n return tBytes$1(fromImageBytes);\r\n}\r\nfunction _isFile(origin) {\r\n return origin !== null && origin !== void 0 && typeof origin === \"object\" && \"name\" in origin;\r\n}\r\nfunction isGeneratedVideo(origin) {\r\n return origin !== null && origin !== void 0 && typeof origin === \"object\" && \"video\" in origin;\r\n}\r\nfunction isVideo(origin) {\r\n return origin !== null && origin !== void 0 && typeof origin === \"object\" && \"uri\" in origin;\r\n}\r\nfunction tFileName(fromName) {\r\n var _a2;\r\n let name;\r\n if (_isFile(fromName)) {\r\n name = fromName.name;\r\n }\r\n if (isVideo(fromName)) {\r\n name = fromName.uri;\r\n if (name === void 0) {\r\n return void 0;\r\n }\r\n }\r\n if (isGeneratedVideo(fromName)) {\r\n name = (_a2 = fromName.video) === null || _a2 === void 0 ? void 0 : _a2.uri;\r\n if (name === void 0) {\r\n return void 0;\r\n }\r\n }\r\n if (typeof fromName === \"string\") {\r\n name = fromName;\r\n }\r\n if (name === void 0) {\r\n throw new Error(\"Could not extract file name from the provided input.\");\r\n }\r\n if (name.startsWith(\"https://\")) {\r\n const suffix = name.split(\"files/\")[1];\r\n const match = suffix.match(/[a-z0-9]+/);\r\n if (match === null) {\r\n throw new Error(`Could not extract file name from URI ${name}`);\r\n }\r\n name = match[0];\r\n } else if (name.startsWith(\"files/\")) {\r\n name = name.split(\"files/\")[1];\r\n }\r\n return name;\r\n}\r\nfunction tModelsUrl(apiClient, baseModels) {\r\n let res;\r\n if (apiClient.isVertexAI()) {\r\n res = baseModels ? \"publishers/google/models\" : \"models\";\r\n } else {\r\n res = baseModels ? \"models\" : \"tunedModels\";\r\n }\r\n return res;\r\n}\r\nfunction tExtractModels(response) {\r\n for (const key of [\"models\", \"tunedModels\", \"publisherModels\"]) {\r\n if (hasField(response, key)) {\r\n return response[key];\r\n }\r\n }\r\n return [];\r\n}\r\nfunction hasField(data, fieldName) {\r\n return data !== null && typeof data === \"object\" && fieldName in data;\r\n}\r\nfunction mcpToGeminiTool(mcpTool, config = {}) {\r\n const mcpToolSchema = mcpTool;\r\n const functionDeclaration = {\r\n name: mcpToolSchema[\"name\"],\r\n description: mcpToolSchema[\"description\"],\r\n parametersJsonSchema: mcpToolSchema[\"inputSchema\"]\r\n };\r\n if (mcpToolSchema[\"outputSchema\"]) {\r\n functionDeclaration[\"responseJsonSchema\"] = mcpToolSchema[\"outputSchema\"];\r\n }\r\n if (config.behavior) {\r\n functionDeclaration[\"behavior\"] = config.behavior;\r\n }\r\n const geminiTool = {\r\n functionDeclarations: [\r\n functionDeclaration\r\n ]\r\n };\r\n return geminiTool;\r\n}\r\nfunction mcpToolsToGeminiTool(mcpTools, config = {}) {\r\n const functionDeclarations = [];\r\n const toolNames = /* @__PURE__ */ new Set();\r\n for (const mcpTool of mcpTools) {\r\n const mcpToolName = mcpTool.name;\r\n if (toolNames.has(mcpToolName)) {\r\n throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);\r\n }\r\n toolNames.add(mcpToolName);\r\n const geminiTool = mcpToGeminiTool(mcpTool, config);\r\n if (geminiTool.functionDeclarations) {\r\n functionDeclarations.push(...geminiTool.functionDeclarations);\r\n }\r\n }\r\n return { functionDeclarations };\r\n}\r\nfunction tBatchJobSource(client, src) {\r\n let sourceObj;\r\n if (typeof src === \"string\") {\r\n if (client.isVertexAI()) {\r\n if (src.startsWith(\"gs://\")) {\r\n sourceObj = { format: \"jsonl\", gcsUri: [src] };\r\n } else if (src.startsWith(\"bq://\")) {\r\n sourceObj = { format: \"bigquery\", bigqueryUri: src };\r\n } else {\r\n throw new Error(`Unsupported string source for Vertex AI: ${src}`);\r\n }\r\n } else {\r\n if (src.startsWith(\"files/\")) {\r\n sourceObj = { fileName: src };\r\n } else {\r\n throw new Error(`Unsupported string source for Gemini API: ${src}`);\r\n }\r\n }\r\n } else if (Array.isArray(src)) {\r\n if (client.isVertexAI()) {\r\n throw new Error(\"InlinedRequest[] is not supported in Vertex AI.\");\r\n }\r\n sourceObj = { inlinedRequests: src };\r\n } else {\r\n sourceObj = src;\r\n }\r\n const vertexSourcesCount = [sourceObj.gcsUri, sourceObj.bigqueryUri].filter(Boolean).length;\r\n const mldevSourcesCount = [\r\n sourceObj.inlinedRequests,\r\n sourceObj.fileName\r\n ].filter(Boolean).length;\r\n if (client.isVertexAI()) {\r\n if (mldevSourcesCount > 0 || vertexSourcesCount !== 1) {\r\n throw new Error(\"Exactly one of `gcsUri` or `bigqueryUri` must be set for Vertex AI.\");\r\n }\r\n } else {\r\n if (vertexSourcesCount > 0 || mldevSourcesCount !== 1) {\r\n throw new Error(\"Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.\");\r\n }\r\n }\r\n return sourceObj;\r\n}\r\nfunction tBatchJobDestination(dest) {\r\n if (typeof dest !== \"string\") {\r\n return dest;\r\n }\r\n const destString = dest;\r\n if (destString.startsWith(\"gs://\")) {\r\n return {\r\n format: \"jsonl\",\r\n gcsUri: destString\r\n };\r\n } else if (destString.startsWith(\"bq://\")) {\r\n return {\r\n format: \"bigquery\",\r\n bigqueryUri: destString\r\n };\r\n } else {\r\n throw new Error(`Unsupported destination: ${destString}`);\r\n }\r\n}\r\nfunction tRecvBatchJobDestination(dest) {\r\n if (typeof dest !== \"object\" || dest === null) {\r\n return {};\r\n }\r\n const obj = dest;\r\n const inlineResponsesVal = obj[\"inlinedResponses\"];\r\n if (typeof inlineResponsesVal !== \"object\" || inlineResponsesVal === null) {\r\n return dest;\r\n }\r\n const inlineResponsesObj = inlineResponsesVal;\r\n const responsesArray = inlineResponsesObj[\"inlinedResponses\"];\r\n if (!Array.isArray(responsesArray) || responsesArray.length === 0) {\r\n return dest;\r\n }\r\n let hasEmbedding = false;\r\n for (const responseItem of responsesArray) {\r\n if (typeof responseItem !== \"object\" || responseItem === null) {\r\n continue;\r\n }\r\n const responseItemObj = responseItem;\r\n const responseVal = responseItemObj[\"response\"];\r\n if (typeof responseVal !== \"object\" || responseVal === null) {\r\n continue;\r\n }\r\n const responseObj = responseVal;\r\n if (responseObj[\"embedding\"] !== void 0) {\r\n hasEmbedding = true;\r\n break;\r\n }\r\n }\r\n if (hasEmbedding) {\r\n obj[\"inlinedEmbedContentResponses\"] = obj[\"inlinedResponses\"];\r\n delete obj[\"inlinedResponses\"];\r\n }\r\n return dest;\r\n}\r\nfunction tBatchJobName(apiClient, name) {\r\n const nameString = name;\r\n if (!apiClient.isVertexAI()) {\r\n const mldevPattern = /batches\\/[^/]+$/;\r\n if (mldevPattern.test(nameString)) {\r\n return nameString.split(\"/\").pop();\r\n } else {\r\n throw new Error(`Invalid batch job name: ${nameString}.`);\r\n }\r\n }\r\n const vertexPattern = /^projects\\/[^/]+\\/locations\\/[^/]+\\/batchPredictionJobs\\/[^/]+$/;\r\n if (vertexPattern.test(nameString)) {\r\n return nameString.split(\"/\").pop();\r\n } else if (/^\\d+$/.test(nameString)) {\r\n return nameString;\r\n } else {\r\n throw new Error(`Invalid batch job name: ${nameString}.`);\r\n }\r\n}\r\nfunction tJobState(state) {\r\n const stateString = state;\r\n if (stateString === \"BATCH_STATE_UNSPECIFIED\") {\r\n return \"JOB_STATE_UNSPECIFIED\";\r\n } else if (stateString === \"BATCH_STATE_PENDING\") {\r\n return \"JOB_STATE_PENDING\";\r\n } else if (stateString === \"BATCH_STATE_RUNNING\") {\r\n return \"JOB_STATE_RUNNING\";\r\n } else if (stateString === \"BATCH_STATE_SUCCEEDED\") {\r\n return \"JOB_STATE_SUCCEEDED\";\r\n } else if (stateString === \"BATCH_STATE_FAILED\") {\r\n return \"JOB_STATE_FAILED\";\r\n } else if (stateString === \"BATCH_STATE_CANCELLED\") {\r\n return \"JOB_STATE_CANCELLED\";\r\n } else if (stateString === \"BATCH_STATE_EXPIRED\") {\r\n return \"JOB_STATE_EXPIRED\";\r\n } else {\r\n return stateString;\r\n }\r\n}\r\nfunction tIsVertexEmbedContentModel(model) {\r\n return model.includes(\"gemini\") && model !== \"gemini-embedding-001\" || model.includes(\"maas\");\r\n}\r\nfunction authConfigToMldev$4(fromObject) {\r\n const toObject = {};\r\n const fromApiKey = getValueByPath(fromObject, [\"apiKey\"]);\r\n if (fromApiKey != null) {\r\n setValueByPath(toObject, [\"apiKey\"], fromApiKey);\r\n }\r\n if (getValueByPath(fromObject, [\"apiKeyConfig\"]) !== void 0) {\r\n throw new Error(\"apiKeyConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"authType\"]) !== void 0) {\r\n throw new Error(\"authType parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"googleServiceAccountConfig\"]) !== void 0) {\r\n throw new Error(\"googleServiceAccountConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"httpBasicAuthConfig\"]) !== void 0) {\r\n throw new Error(\"httpBasicAuthConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"oauthConfig\"]) !== void 0) {\r\n throw new Error(\"oauthConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"oidcConfig\"]) !== void 0) {\r\n throw new Error(\"oidcConfig parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction batchJobDestinationFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromFileName = getValueByPath(fromObject, [\"responsesFile\"]);\r\n if (fromFileName != null) {\r\n setValueByPath(toObject, [\"fileName\"], fromFileName);\r\n }\r\n const fromInlinedResponses = getValueByPath(fromObject, [\r\n \"inlinedResponses\",\r\n \"inlinedResponses\"\r\n ]);\r\n if (fromInlinedResponses != null) {\r\n let transformedList = fromInlinedResponses;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return inlinedResponseFromMldev(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"inlinedResponses\"], transformedList);\r\n }\r\n const fromInlinedEmbedContentResponses = getValueByPath(fromObject, [\r\n \"inlinedEmbedContentResponses\",\r\n \"inlinedResponses\"\r\n ]);\r\n if (fromInlinedEmbedContentResponses != null) {\r\n let transformedList = fromInlinedEmbedContentResponses;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"inlinedEmbedContentResponses\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction batchJobDestinationFromVertex(fromObject) {\r\n const toObject = {};\r\n const fromFormat = getValueByPath(fromObject, [\"predictionsFormat\"]);\r\n if (fromFormat != null) {\r\n setValueByPath(toObject, [\"format\"], fromFormat);\r\n }\r\n const fromGcsUri = getValueByPath(fromObject, [\r\n \"gcsDestination\",\r\n \"outputUriPrefix\"\r\n ]);\r\n if (fromGcsUri != null) {\r\n setValueByPath(toObject, [\"gcsUri\"], fromGcsUri);\r\n }\r\n const fromBigqueryUri = getValueByPath(fromObject, [\r\n \"bigqueryDestination\",\r\n \"outputUri\"\r\n ]);\r\n if (fromBigqueryUri != null) {\r\n setValueByPath(toObject, [\"bigqueryUri\"], fromBigqueryUri);\r\n }\r\n return toObject;\r\n}\r\nfunction batchJobDestinationToVertex(fromObject) {\r\n const toObject = {};\r\n const fromFormat = getValueByPath(fromObject, [\"format\"]);\r\n if (fromFormat != null) {\r\n setValueByPath(toObject, [\"predictionsFormat\"], fromFormat);\r\n }\r\n const fromGcsUri = getValueByPath(fromObject, [\"gcsUri\"]);\r\n if (fromGcsUri != null) {\r\n setValueByPath(toObject, [\"gcsDestination\", \"outputUriPrefix\"], fromGcsUri);\r\n }\r\n const fromBigqueryUri = getValueByPath(fromObject, [\"bigqueryUri\"]);\r\n if (fromBigqueryUri != null) {\r\n setValueByPath(toObject, [\"bigqueryDestination\", \"outputUri\"], fromBigqueryUri);\r\n }\r\n if (getValueByPath(fromObject, [\"fileName\"]) !== void 0) {\r\n throw new Error(\"fileName parameter is not supported in Vertex AI.\");\r\n }\r\n if (getValueByPath(fromObject, [\"inlinedResponses\"]) !== void 0) {\r\n throw new Error(\"inlinedResponses parameter is not supported in Vertex AI.\");\r\n }\r\n if (getValueByPath(fromObject, [\"inlinedEmbedContentResponses\"]) !== void 0) {\r\n throw new Error(\"inlinedEmbedContentResponses parameter is not supported in Vertex AI.\");\r\n }\r\n return toObject;\r\n}\r\nfunction batchJobFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromDisplayName = getValueByPath(fromObject, [\r\n \"metadata\",\r\n \"displayName\"\r\n ]);\r\n if (fromDisplayName != null) {\r\n setValueByPath(toObject, [\"displayName\"], fromDisplayName);\r\n }\r\n const fromState = getValueByPath(fromObject, [\"metadata\", \"state\"]);\r\n if (fromState != null) {\r\n setValueByPath(toObject, [\"state\"], tJobState(fromState));\r\n }\r\n const fromCreateTime = getValueByPath(fromObject, [\r\n \"metadata\",\r\n \"createTime\"\r\n ]);\r\n if (fromCreateTime != null) {\r\n setValueByPath(toObject, [\"createTime\"], fromCreateTime);\r\n }\r\n const fromEndTime = getValueByPath(fromObject, [\r\n \"metadata\",\r\n \"endTime\"\r\n ]);\r\n if (fromEndTime != null) {\r\n setValueByPath(toObject, [\"endTime\"], fromEndTime);\r\n }\r\n const fromUpdateTime = getValueByPath(fromObject, [\r\n \"metadata\",\r\n \"updateTime\"\r\n ]);\r\n if (fromUpdateTime != null) {\r\n setValueByPath(toObject, [\"updateTime\"], fromUpdateTime);\r\n }\r\n const fromModel = getValueByPath(fromObject, [\"metadata\", \"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"model\"], fromModel);\r\n }\r\n const fromDest = getValueByPath(fromObject, [\"metadata\", \"output\"]);\r\n if (fromDest != null) {\r\n setValueByPath(toObject, [\"dest\"], batchJobDestinationFromMldev(tRecvBatchJobDestination(fromDest)));\r\n }\r\n return toObject;\r\n}\r\nfunction batchJobFromVertex(fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromDisplayName = getValueByPath(fromObject, [\"displayName\"]);\r\n if (fromDisplayName != null) {\r\n setValueByPath(toObject, [\"displayName\"], fromDisplayName);\r\n }\r\n const fromState = getValueByPath(fromObject, [\"state\"]);\r\n if (fromState != null) {\r\n setValueByPath(toObject, [\"state\"], tJobState(fromState));\r\n }\r\n const fromError = getValueByPath(fromObject, [\"error\"]);\r\n if (fromError != null) {\r\n setValueByPath(toObject, [\"error\"], fromError);\r\n }\r\n const fromCreateTime = getValueByPath(fromObject, [\"createTime\"]);\r\n if (fromCreateTime != null) {\r\n setValueByPath(toObject, [\"createTime\"], fromCreateTime);\r\n }\r\n const fromStartTime = getValueByPath(fromObject, [\"startTime\"]);\r\n if (fromStartTime != null) {\r\n setValueByPath(toObject, [\"startTime\"], fromStartTime);\r\n }\r\n const fromEndTime = getValueByPath(fromObject, [\"endTime\"]);\r\n if (fromEndTime != null) {\r\n setValueByPath(toObject, [\"endTime\"], fromEndTime);\r\n }\r\n const fromUpdateTime = getValueByPath(fromObject, [\"updateTime\"]);\r\n if (fromUpdateTime != null) {\r\n setValueByPath(toObject, [\"updateTime\"], fromUpdateTime);\r\n }\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"model\"], fromModel);\r\n }\r\n const fromSrc = getValueByPath(fromObject, [\"inputConfig\"]);\r\n if (fromSrc != null) {\r\n setValueByPath(toObject, [\"src\"], batchJobSourceFromVertex(fromSrc));\r\n }\r\n const fromDest = getValueByPath(fromObject, [\"outputConfig\"]);\r\n if (fromDest != null) {\r\n setValueByPath(toObject, [\"dest\"], batchJobDestinationFromVertex(tRecvBatchJobDestination(fromDest)));\r\n }\r\n const fromCompletionStats = getValueByPath(fromObject, [\r\n \"completionStats\"\r\n ]);\r\n if (fromCompletionStats != null) {\r\n setValueByPath(toObject, [\"completionStats\"], fromCompletionStats);\r\n }\r\n return toObject;\r\n}\r\nfunction batchJobSourceFromVertex(fromObject) {\r\n const toObject = {};\r\n const fromFormat = getValueByPath(fromObject, [\"instancesFormat\"]);\r\n if (fromFormat != null) {\r\n setValueByPath(toObject, [\"format\"], fromFormat);\r\n }\r\n const fromGcsUri = getValueByPath(fromObject, [\"gcsSource\", \"uris\"]);\r\n if (fromGcsUri != null) {\r\n setValueByPath(toObject, [\"gcsUri\"], fromGcsUri);\r\n }\r\n const fromBigqueryUri = getValueByPath(fromObject, [\r\n \"bigquerySource\",\r\n \"inputUri\"\r\n ]);\r\n if (fromBigqueryUri != null) {\r\n setValueByPath(toObject, [\"bigqueryUri\"], fromBigqueryUri);\r\n }\r\n return toObject;\r\n}\r\nfunction batchJobSourceToMldev(apiClient, fromObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"format\"]) !== void 0) {\r\n throw new Error(\"format parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"gcsUri\"]) !== void 0) {\r\n throw new Error(\"gcsUri parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"bigqueryUri\"]) !== void 0) {\r\n throw new Error(\"bigqueryUri parameter is not supported in Gemini API.\");\r\n }\r\n const fromFileName = getValueByPath(fromObject, [\"fileName\"]);\r\n if (fromFileName != null) {\r\n setValueByPath(toObject, [\"fileName\"], fromFileName);\r\n }\r\n const fromInlinedRequests = getValueByPath(fromObject, [\r\n \"inlinedRequests\"\r\n ]);\r\n if (fromInlinedRequests != null) {\r\n let transformedList = fromInlinedRequests;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return inlinedRequestToMldev(apiClient, item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"requests\", \"requests\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction batchJobSourceToVertex(fromObject) {\r\n const toObject = {};\r\n const fromFormat = getValueByPath(fromObject, [\"format\"]);\r\n if (fromFormat != null) {\r\n setValueByPath(toObject, [\"instancesFormat\"], fromFormat);\r\n }\r\n const fromGcsUri = getValueByPath(fromObject, [\"gcsUri\"]);\r\n if (fromGcsUri != null) {\r\n setValueByPath(toObject, [\"gcsSource\", \"uris\"], fromGcsUri);\r\n }\r\n const fromBigqueryUri = getValueByPath(fromObject, [\"bigqueryUri\"]);\r\n if (fromBigqueryUri != null) {\r\n setValueByPath(toObject, [\"bigquerySource\", \"inputUri\"], fromBigqueryUri);\r\n }\r\n if (getValueByPath(fromObject, [\"fileName\"]) !== void 0) {\r\n throw new Error(\"fileName parameter is not supported in Vertex AI.\");\r\n }\r\n if (getValueByPath(fromObject, [\"inlinedRequests\"]) !== void 0) {\r\n throw new Error(\"inlinedRequests parameter is not supported in Vertex AI.\");\r\n }\r\n return toObject;\r\n}\r\nfunction blobToMldev$4(fromObject) {\r\n const toObject = {};\r\n const fromData = getValueByPath(fromObject, [\"data\"]);\r\n if (fromData != null) {\r\n setValueByPath(toObject, [\"data\"], fromData);\r\n }\r\n if (getValueByPath(fromObject, [\"displayName\"]) !== void 0) {\r\n throw new Error(\"displayName parameter is not supported in Gemini API.\");\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction cancelBatchJobParametersToMldev(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], tBatchJobName(apiClient, fromName));\r\n }\r\n return toObject;\r\n}\r\nfunction cancelBatchJobParametersToVertex(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], tBatchJobName(apiClient, fromName));\r\n }\r\n return toObject;\r\n}\r\nfunction candidateFromMldev$1(fromObject) {\r\n const toObject = {};\r\n const fromContent = getValueByPath(fromObject, [\"content\"]);\r\n if (fromContent != null) {\r\n setValueByPath(toObject, [\"content\"], fromContent);\r\n }\r\n const fromCitationMetadata = getValueByPath(fromObject, [\r\n \"citationMetadata\"\r\n ]);\r\n if (fromCitationMetadata != null) {\r\n setValueByPath(toObject, [\"citationMetadata\"], citationMetadataFromMldev$1(fromCitationMetadata));\r\n }\r\n const fromTokenCount = getValueByPath(fromObject, [\"tokenCount\"]);\r\n if (fromTokenCount != null) {\r\n setValueByPath(toObject, [\"tokenCount\"], fromTokenCount);\r\n }\r\n const fromFinishReason = getValueByPath(fromObject, [\"finishReason\"]);\r\n if (fromFinishReason != null) {\r\n setValueByPath(toObject, [\"finishReason\"], fromFinishReason);\r\n }\r\n const fromGroundingMetadata = getValueByPath(fromObject, [\r\n \"groundingMetadata\"\r\n ]);\r\n if (fromGroundingMetadata != null) {\r\n setValueByPath(toObject, [\"groundingMetadata\"], fromGroundingMetadata);\r\n }\r\n const fromAvgLogprobs = getValueByPath(fromObject, [\"avgLogprobs\"]);\r\n if (fromAvgLogprobs != null) {\r\n setValueByPath(toObject, [\"avgLogprobs\"], fromAvgLogprobs);\r\n }\r\n const fromIndex = getValueByPath(fromObject, [\"index\"]);\r\n if (fromIndex != null) {\r\n setValueByPath(toObject, [\"index\"], fromIndex);\r\n }\r\n const fromLogprobsResult = getValueByPath(fromObject, [\r\n \"logprobsResult\"\r\n ]);\r\n if (fromLogprobsResult != null) {\r\n setValueByPath(toObject, [\"logprobsResult\"], fromLogprobsResult);\r\n }\r\n const fromSafetyRatings = getValueByPath(fromObject, [\r\n \"safetyRatings\"\r\n ]);\r\n if (fromSafetyRatings != null) {\r\n let transformedList = fromSafetyRatings;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"safetyRatings\"], transformedList);\r\n }\r\n const fromUrlContextMetadata = getValueByPath(fromObject, [\r\n \"urlContextMetadata\"\r\n ]);\r\n if (fromUrlContextMetadata != null) {\r\n setValueByPath(toObject, [\"urlContextMetadata\"], fromUrlContextMetadata);\r\n }\r\n return toObject;\r\n}\r\nfunction citationMetadataFromMldev$1(fromObject) {\r\n const toObject = {};\r\n const fromCitations = getValueByPath(fromObject, [\"citationSources\"]);\r\n if (fromCitations != null) {\r\n let transformedList = fromCitations;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"citations\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction contentToMldev$4(fromObject) {\r\n const toObject = {};\r\n const fromParts = getValueByPath(fromObject, [\"parts\"]);\r\n if (fromParts != null) {\r\n let transformedList = fromParts;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return partToMldev$4(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"parts\"], transformedList);\r\n }\r\n const fromRole = getValueByPath(fromObject, [\"role\"]);\r\n if (fromRole != null) {\r\n setValueByPath(toObject, [\"role\"], fromRole);\r\n }\r\n return toObject;\r\n}\r\nfunction createBatchJobConfigToMldev(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromDisplayName = getValueByPath(fromObject, [\"displayName\"]);\r\n if (parentObject !== void 0 && fromDisplayName != null) {\r\n setValueByPath(parentObject, [\"batch\", \"displayName\"], fromDisplayName);\r\n }\r\n if (getValueByPath(fromObject, [\"dest\"]) !== void 0) {\r\n throw new Error(\"dest parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction createBatchJobConfigToVertex(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromDisplayName = getValueByPath(fromObject, [\"displayName\"]);\r\n if (parentObject !== void 0 && fromDisplayName != null) {\r\n setValueByPath(parentObject, [\"displayName\"], fromDisplayName);\r\n }\r\n const fromDest = getValueByPath(fromObject, [\"dest\"]);\r\n if (parentObject !== void 0 && fromDest != null) {\r\n setValueByPath(parentObject, [\"outputConfig\"], batchJobDestinationToVertex(tBatchJobDestination(fromDest)));\r\n }\r\n return toObject;\r\n}\r\nfunction createBatchJobParametersToMldev(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromSrc = getValueByPath(fromObject, [\"src\"]);\r\n if (fromSrc != null) {\r\n setValueByPath(toObject, [\"batch\", \"inputConfig\"], batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc)));\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n createBatchJobConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction createBatchJobParametersToVertex(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromSrc = getValueByPath(fromObject, [\"src\"]);\r\n if (fromSrc != null) {\r\n setValueByPath(toObject, [\"inputConfig\"], batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc)));\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n createBatchJobConfigToVertex(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction createEmbeddingsBatchJobConfigToMldev(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromDisplayName = getValueByPath(fromObject, [\"displayName\"]);\r\n if (parentObject !== void 0 && fromDisplayName != null) {\r\n setValueByPath(parentObject, [\"batch\", \"displayName\"], fromDisplayName);\r\n }\r\n return toObject;\r\n}\r\nfunction createEmbeddingsBatchJobParametersToMldev(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromSrc = getValueByPath(fromObject, [\"src\"]);\r\n if (fromSrc != null) {\r\n setValueByPath(toObject, [\"batch\", \"inputConfig\"], embeddingsBatchJobSourceToMldev(apiClient, fromSrc));\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n createEmbeddingsBatchJobConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction deleteBatchJobParametersToMldev(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], tBatchJobName(apiClient, fromName));\r\n }\r\n return toObject;\r\n}\r\nfunction deleteBatchJobParametersToVertex(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], tBatchJobName(apiClient, fromName));\r\n }\r\n return toObject;\r\n}\r\nfunction deleteResourceJobFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromDone = getValueByPath(fromObject, [\"done\"]);\r\n if (fromDone != null) {\r\n setValueByPath(toObject, [\"done\"], fromDone);\r\n }\r\n const fromError = getValueByPath(fromObject, [\"error\"]);\r\n if (fromError != null) {\r\n setValueByPath(toObject, [\"error\"], fromError);\r\n }\r\n return toObject;\r\n}\r\nfunction deleteResourceJobFromVertex(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromDone = getValueByPath(fromObject, [\"done\"]);\r\n if (fromDone != null) {\r\n setValueByPath(toObject, [\"done\"], fromDone);\r\n }\r\n const fromError = getValueByPath(fromObject, [\"error\"]);\r\n if (fromError != null) {\r\n setValueByPath(toObject, [\"error\"], fromError);\r\n }\r\n return toObject;\r\n}\r\nfunction embedContentBatchToMldev(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromContents = getValueByPath(fromObject, [\"contents\"]);\r\n if (fromContents != null) {\r\n let transformedList = tContentsForEmbed(apiClient, fromContents);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"requests[]\", \"request\", \"content\"], transformedList);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n setValueByPath(toObject, [\"_self\"], embedContentConfigToMldev$1(fromConfig, toObject));\r\n moveValueByPath(toObject, { \"requests[].*\": \"requests[].request.*\" });\r\n }\r\n return toObject;\r\n}\r\nfunction embedContentConfigToMldev$1(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromTaskType = getValueByPath(fromObject, [\"taskType\"]);\r\n if (parentObject !== void 0 && fromTaskType != null) {\r\n setValueByPath(parentObject, [\"requests[]\", \"taskType\"], fromTaskType);\r\n }\r\n const fromTitle = getValueByPath(fromObject, [\"title\"]);\r\n if (parentObject !== void 0 && fromTitle != null) {\r\n setValueByPath(parentObject, [\"requests[]\", \"title\"], fromTitle);\r\n }\r\n const fromOutputDimensionality = getValueByPath(fromObject, [\r\n \"outputDimensionality\"\r\n ]);\r\n if (parentObject !== void 0 && fromOutputDimensionality != null) {\r\n setValueByPath(parentObject, [\"requests[]\", \"outputDimensionality\"], fromOutputDimensionality);\r\n }\r\n if (getValueByPath(fromObject, [\"mimeType\"]) !== void 0) {\r\n throw new Error(\"mimeType parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"autoTruncate\"]) !== void 0) {\r\n throw new Error(\"autoTruncate parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction embeddingsBatchJobSourceToMldev(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromFileName = getValueByPath(fromObject, [\"fileName\"]);\r\n if (fromFileName != null) {\r\n setValueByPath(toObject, [\"file_name\"], fromFileName);\r\n }\r\n const fromInlinedRequests = getValueByPath(fromObject, [\r\n \"inlinedRequests\"\r\n ]);\r\n if (fromInlinedRequests != null) {\r\n setValueByPath(toObject, [\"requests\"], embedContentBatchToMldev(apiClient, fromInlinedRequests));\r\n }\r\n return toObject;\r\n}\r\nfunction fileDataToMldev$4(fromObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"displayName\"]) !== void 0) {\r\n throw new Error(\"displayName parameter is not supported in Gemini API.\");\r\n }\r\n const fromFileUri = getValueByPath(fromObject, [\"fileUri\"]);\r\n if (fromFileUri != null) {\r\n setValueByPath(toObject, [\"fileUri\"], fromFileUri);\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction functionCallToMldev$4(fromObject) {\r\n const toObject = {};\r\n const fromId = getValueByPath(fromObject, [\"id\"]);\r\n if (fromId != null) {\r\n setValueByPath(toObject, [\"id\"], fromId);\r\n }\r\n const fromArgs = getValueByPath(fromObject, [\"args\"]);\r\n if (fromArgs != null) {\r\n setValueByPath(toObject, [\"args\"], fromArgs);\r\n }\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n if (getValueByPath(fromObject, [\"partialArgs\"]) !== void 0) {\r\n throw new Error(\"partialArgs parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"willContinue\"]) !== void 0) {\r\n throw new Error(\"willContinue parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction functionCallingConfigToMldev$2(fromObject) {\r\n const toObject = {};\r\n const fromAllowedFunctionNames = getValueByPath(fromObject, [\r\n \"allowedFunctionNames\"\r\n ]);\r\n if (fromAllowedFunctionNames != null) {\r\n setValueByPath(toObject, [\"allowedFunctionNames\"], fromAllowedFunctionNames);\r\n }\r\n const fromMode = getValueByPath(fromObject, [\"mode\"]);\r\n if (fromMode != null) {\r\n setValueByPath(toObject, [\"mode\"], fromMode);\r\n }\r\n if (getValueByPath(fromObject, [\"streamFunctionCallArguments\"]) !== void 0) {\r\n throw new Error(\"streamFunctionCallArguments parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction generateContentConfigToMldev$1(apiClient, fromObject, parentObject) {\r\n const toObject = {};\r\n const fromSystemInstruction = getValueByPath(fromObject, [\r\n \"systemInstruction\"\r\n ]);\r\n if (parentObject !== void 0 && fromSystemInstruction != null) {\r\n setValueByPath(parentObject, [\"systemInstruction\"], contentToMldev$4(tContent(fromSystemInstruction)));\r\n }\r\n const fromTemperature = getValueByPath(fromObject, [\"temperature\"]);\r\n if (fromTemperature != null) {\r\n setValueByPath(toObject, [\"temperature\"], fromTemperature);\r\n }\r\n const fromTopP = getValueByPath(fromObject, [\"topP\"]);\r\n if (fromTopP != null) {\r\n setValueByPath(toObject, [\"topP\"], fromTopP);\r\n }\r\n const fromTopK = getValueByPath(fromObject, [\"topK\"]);\r\n if (fromTopK != null) {\r\n setValueByPath(toObject, [\"topK\"], fromTopK);\r\n }\r\n const fromCandidateCount = getValueByPath(fromObject, [\r\n \"candidateCount\"\r\n ]);\r\n if (fromCandidateCount != null) {\r\n setValueByPath(toObject, [\"candidateCount\"], fromCandidateCount);\r\n }\r\n const fromMaxOutputTokens = getValueByPath(fromObject, [\r\n \"maxOutputTokens\"\r\n ]);\r\n if (fromMaxOutputTokens != null) {\r\n setValueByPath(toObject, [\"maxOutputTokens\"], fromMaxOutputTokens);\r\n }\r\n const fromStopSequences = getValueByPath(fromObject, [\r\n \"stopSequences\"\r\n ]);\r\n if (fromStopSequences != null) {\r\n setValueByPath(toObject, [\"stopSequences\"], fromStopSequences);\r\n }\r\n const fromResponseLogprobs = getValueByPath(fromObject, [\r\n \"responseLogprobs\"\r\n ]);\r\n if (fromResponseLogprobs != null) {\r\n setValueByPath(toObject, [\"responseLogprobs\"], fromResponseLogprobs);\r\n }\r\n const fromLogprobs = getValueByPath(fromObject, [\"logprobs\"]);\r\n if (fromLogprobs != null) {\r\n setValueByPath(toObject, [\"logprobs\"], fromLogprobs);\r\n }\r\n const fromPresencePenalty = getValueByPath(fromObject, [\r\n \"presencePenalty\"\r\n ]);\r\n if (fromPresencePenalty != null) {\r\n setValueByPath(toObject, [\"presencePenalty\"], fromPresencePenalty);\r\n }\r\n const fromFrequencyPenalty = getValueByPath(fromObject, [\r\n \"frequencyPenalty\"\r\n ]);\r\n if (fromFrequencyPenalty != null) {\r\n setValueByPath(toObject, [\"frequencyPenalty\"], fromFrequencyPenalty);\r\n }\r\n const fromSeed = getValueByPath(fromObject, [\"seed\"]);\r\n if (fromSeed != null) {\r\n setValueByPath(toObject, [\"seed\"], fromSeed);\r\n }\r\n const fromResponseMimeType = getValueByPath(fromObject, [\r\n \"responseMimeType\"\r\n ]);\r\n if (fromResponseMimeType != null) {\r\n setValueByPath(toObject, [\"responseMimeType\"], fromResponseMimeType);\r\n }\r\n const fromResponseSchema = getValueByPath(fromObject, [\r\n \"responseSchema\"\r\n ]);\r\n if (fromResponseSchema != null) {\r\n setValueByPath(toObject, [\"responseSchema\"], tSchema(fromResponseSchema));\r\n }\r\n const fromResponseJsonSchema = getValueByPath(fromObject, [\r\n \"responseJsonSchema\"\r\n ]);\r\n if (fromResponseJsonSchema != null) {\r\n setValueByPath(toObject, [\"responseJsonSchema\"], fromResponseJsonSchema);\r\n }\r\n if (getValueByPath(fromObject, [\"routingConfig\"]) !== void 0) {\r\n throw new Error(\"routingConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"modelSelectionConfig\"]) !== void 0) {\r\n throw new Error(\"modelSelectionConfig parameter is not supported in Gemini API.\");\r\n }\r\n const fromSafetySettings = getValueByPath(fromObject, [\r\n \"safetySettings\"\r\n ]);\r\n if (parentObject !== void 0 && fromSafetySettings != null) {\r\n let transformedList = fromSafetySettings;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return safetySettingToMldev$1(item);\r\n });\r\n }\r\n setValueByPath(parentObject, [\"safetySettings\"], transformedList);\r\n }\r\n const fromTools = getValueByPath(fromObject, [\"tools\"]);\r\n if (parentObject !== void 0 && fromTools != null) {\r\n let transformedList = tTools(fromTools);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return toolToMldev$4(tTool(item));\r\n });\r\n }\r\n setValueByPath(parentObject, [\"tools\"], transformedList);\r\n }\r\n const fromToolConfig = getValueByPath(fromObject, [\"toolConfig\"]);\r\n if (parentObject !== void 0 && fromToolConfig != null) {\r\n setValueByPath(parentObject, [\"toolConfig\"], toolConfigToMldev$2(fromToolConfig));\r\n }\r\n if (getValueByPath(fromObject, [\"labels\"]) !== void 0) {\r\n throw new Error(\"labels parameter is not supported in Gemini API.\");\r\n }\r\n const fromCachedContent = getValueByPath(fromObject, [\r\n \"cachedContent\"\r\n ]);\r\n if (parentObject !== void 0 && fromCachedContent != null) {\r\n setValueByPath(parentObject, [\"cachedContent\"], tCachedContentName(apiClient, fromCachedContent));\r\n }\r\n const fromResponseModalities = getValueByPath(fromObject, [\r\n \"responseModalities\"\r\n ]);\r\n if (fromResponseModalities != null) {\r\n setValueByPath(toObject, [\"responseModalities\"], fromResponseModalities);\r\n }\r\n const fromMediaResolution = getValueByPath(fromObject, [\r\n \"mediaResolution\"\r\n ]);\r\n if (fromMediaResolution != null) {\r\n setValueByPath(toObject, [\"mediaResolution\"], fromMediaResolution);\r\n }\r\n const fromSpeechConfig = getValueByPath(fromObject, [\"speechConfig\"]);\r\n if (fromSpeechConfig != null) {\r\n setValueByPath(toObject, [\"speechConfig\"], tSpeechConfig(fromSpeechConfig));\r\n }\r\n if (getValueByPath(fromObject, [\"audioTimestamp\"]) !== void 0) {\r\n throw new Error(\"audioTimestamp parameter is not supported in Gemini API.\");\r\n }\r\n const fromThinkingConfig = getValueByPath(fromObject, [\r\n \"thinkingConfig\"\r\n ]);\r\n if (fromThinkingConfig != null) {\r\n setValueByPath(toObject, [\"thinkingConfig\"], fromThinkingConfig);\r\n }\r\n const fromImageConfig = getValueByPath(fromObject, [\"imageConfig\"]);\r\n if (fromImageConfig != null) {\r\n setValueByPath(toObject, [\"imageConfig\"], imageConfigToMldev$1(fromImageConfig));\r\n }\r\n const fromEnableEnhancedCivicAnswers = getValueByPath(fromObject, [\r\n \"enableEnhancedCivicAnswers\"\r\n ]);\r\n if (fromEnableEnhancedCivicAnswers != null) {\r\n setValueByPath(toObject, [\"enableEnhancedCivicAnswers\"], fromEnableEnhancedCivicAnswers);\r\n }\r\n if (getValueByPath(fromObject, [\"modelArmorConfig\"]) !== void 0) {\r\n throw new Error(\"modelArmorConfig parameter is not supported in Gemini API.\");\r\n }\r\n const fromServiceTier = getValueByPath(fromObject, [\"serviceTier\"]);\r\n if (parentObject !== void 0 && fromServiceTier != null) {\r\n setValueByPath(parentObject, [\"serviceTier\"], fromServiceTier);\r\n }\r\n return toObject;\r\n}\r\nfunction generateContentResponseFromMldev$1(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromCandidates = getValueByPath(fromObject, [\"candidates\"]);\r\n if (fromCandidates != null) {\r\n let transformedList = fromCandidates;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return candidateFromMldev$1(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"candidates\"], transformedList);\r\n }\r\n const fromModelVersion = getValueByPath(fromObject, [\"modelVersion\"]);\r\n if (fromModelVersion != null) {\r\n setValueByPath(toObject, [\"modelVersion\"], fromModelVersion);\r\n }\r\n const fromPromptFeedback = getValueByPath(fromObject, [\r\n \"promptFeedback\"\r\n ]);\r\n if (fromPromptFeedback != null) {\r\n setValueByPath(toObject, [\"promptFeedback\"], fromPromptFeedback);\r\n }\r\n const fromResponseId = getValueByPath(fromObject, [\"responseId\"]);\r\n if (fromResponseId != null) {\r\n setValueByPath(toObject, [\"responseId\"], fromResponseId);\r\n }\r\n const fromUsageMetadata = getValueByPath(fromObject, [\r\n \"usageMetadata\"\r\n ]);\r\n if (fromUsageMetadata != null) {\r\n setValueByPath(toObject, [\"usageMetadata\"], fromUsageMetadata);\r\n }\r\n const fromModelStatus = getValueByPath(fromObject, [\"modelStatus\"]);\r\n if (fromModelStatus != null) {\r\n setValueByPath(toObject, [\"modelStatus\"], fromModelStatus);\r\n }\r\n return toObject;\r\n}\r\nfunction getBatchJobParametersToMldev(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], tBatchJobName(apiClient, fromName));\r\n }\r\n return toObject;\r\n}\r\nfunction getBatchJobParametersToVertex(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], tBatchJobName(apiClient, fromName));\r\n }\r\n return toObject;\r\n}\r\nfunction googleMapsToMldev$4(fromObject) {\r\n const toObject = {};\r\n const fromAuthConfig = getValueByPath(fromObject, [\"authConfig\"]);\r\n if (fromAuthConfig != null) {\r\n setValueByPath(toObject, [\"authConfig\"], authConfigToMldev$4(fromAuthConfig));\r\n }\r\n const fromEnableWidget = getValueByPath(fromObject, [\"enableWidget\"]);\r\n if (fromEnableWidget != null) {\r\n setValueByPath(toObject, [\"enableWidget\"], fromEnableWidget);\r\n }\r\n return toObject;\r\n}\r\nfunction googleSearchToMldev$4(fromObject) {\r\n const toObject = {};\r\n const fromSearchTypes = getValueByPath(fromObject, [\"searchTypes\"]);\r\n if (fromSearchTypes != null) {\r\n setValueByPath(toObject, [\"searchTypes\"], fromSearchTypes);\r\n }\r\n if (getValueByPath(fromObject, [\"blockingConfidence\"]) !== void 0) {\r\n throw new Error(\"blockingConfidence parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"excludeDomains\"]) !== void 0) {\r\n throw new Error(\"excludeDomains parameter is not supported in Gemini API.\");\r\n }\r\n const fromTimeRangeFilter = getValueByPath(fromObject, [\r\n \"timeRangeFilter\"\r\n ]);\r\n if (fromTimeRangeFilter != null) {\r\n setValueByPath(toObject, [\"timeRangeFilter\"], fromTimeRangeFilter);\r\n }\r\n return toObject;\r\n}\r\nfunction imageConfigToMldev$1(fromObject) {\r\n const toObject = {};\r\n const fromAspectRatio = getValueByPath(fromObject, [\"aspectRatio\"]);\r\n if (fromAspectRatio != null) {\r\n setValueByPath(toObject, [\"aspectRatio\"], fromAspectRatio);\r\n }\r\n const fromImageSize = getValueByPath(fromObject, [\"imageSize\"]);\r\n if (fromImageSize != null) {\r\n setValueByPath(toObject, [\"imageSize\"], fromImageSize);\r\n }\r\n if (getValueByPath(fromObject, [\"personGeneration\"]) !== void 0) {\r\n throw new Error(\"personGeneration parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"prominentPeople\"]) !== void 0) {\r\n throw new Error(\"prominentPeople parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"outputMimeType\"]) !== void 0) {\r\n throw new Error(\"outputMimeType parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"outputCompressionQuality\"]) !== void 0) {\r\n throw new Error(\"outputCompressionQuality parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"imageOutputOptions\"]) !== void 0) {\r\n throw new Error(\"imageOutputOptions parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction inlinedRequestToMldev(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"request\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromContents = getValueByPath(fromObject, [\"contents\"]);\r\n if (fromContents != null) {\r\n let transformedList = tContents(fromContents);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return contentToMldev$4(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"request\", \"contents\"], transformedList);\r\n }\r\n const fromMetadata = getValueByPath(fromObject, [\"metadata\"]);\r\n if (fromMetadata != null) {\r\n setValueByPath(toObject, [\"metadata\"], fromMetadata);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n setValueByPath(toObject, [\"request\", \"generationConfig\"], generateContentConfigToMldev$1(apiClient, fromConfig, getValueByPath(toObject, [\"request\"], {})));\r\n }\r\n return toObject;\r\n}\r\nfunction inlinedResponseFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromResponse = getValueByPath(fromObject, [\"response\"]);\r\n if (fromResponse != null) {\r\n setValueByPath(toObject, [\"response\"], generateContentResponseFromMldev$1(fromResponse));\r\n }\r\n const fromMetadata = getValueByPath(fromObject, [\"metadata\"]);\r\n if (fromMetadata != null) {\r\n setValueByPath(toObject, [\"metadata\"], fromMetadata);\r\n }\r\n const fromError = getValueByPath(fromObject, [\"error\"]);\r\n if (fromError != null) {\r\n setValueByPath(toObject, [\"error\"], fromError);\r\n }\r\n return toObject;\r\n}\r\nfunction listBatchJobsConfigToMldev(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromPageSize = getValueByPath(fromObject, [\"pageSize\"]);\r\n if (parentObject !== void 0 && fromPageSize != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageSize\"], fromPageSize);\r\n }\r\n const fromPageToken = getValueByPath(fromObject, [\"pageToken\"]);\r\n if (parentObject !== void 0 && fromPageToken != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageToken\"], fromPageToken);\r\n }\r\n if (getValueByPath(fromObject, [\"filter\"]) !== void 0) {\r\n throw new Error(\"filter parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction listBatchJobsConfigToVertex(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromPageSize = getValueByPath(fromObject, [\"pageSize\"]);\r\n if (parentObject !== void 0 && fromPageSize != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageSize\"], fromPageSize);\r\n }\r\n const fromPageToken = getValueByPath(fromObject, [\"pageToken\"]);\r\n if (parentObject !== void 0 && fromPageToken != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageToken\"], fromPageToken);\r\n }\r\n const fromFilter = getValueByPath(fromObject, [\"filter\"]);\r\n if (parentObject !== void 0 && fromFilter != null) {\r\n setValueByPath(parentObject, [\"_query\", \"filter\"], fromFilter);\r\n }\r\n return toObject;\r\n}\r\nfunction listBatchJobsParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n listBatchJobsConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction listBatchJobsParametersToVertex(fromObject) {\r\n const toObject = {};\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n listBatchJobsConfigToVertex(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction listBatchJobsResponseFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromNextPageToken = getValueByPath(fromObject, [\r\n \"nextPageToken\"\r\n ]);\r\n if (fromNextPageToken != null) {\r\n setValueByPath(toObject, [\"nextPageToken\"], fromNextPageToken);\r\n }\r\n const fromBatchJobs = getValueByPath(fromObject, [\"operations\"]);\r\n if (fromBatchJobs != null) {\r\n let transformedList = fromBatchJobs;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return batchJobFromMldev(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"batchJobs\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction listBatchJobsResponseFromVertex(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromNextPageToken = getValueByPath(fromObject, [\r\n \"nextPageToken\"\r\n ]);\r\n if (fromNextPageToken != null) {\r\n setValueByPath(toObject, [\"nextPageToken\"], fromNextPageToken);\r\n }\r\n const fromBatchJobs = getValueByPath(fromObject, [\r\n \"batchPredictionJobs\"\r\n ]);\r\n if (fromBatchJobs != null) {\r\n let transformedList = fromBatchJobs;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return batchJobFromVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"batchJobs\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction partToMldev$4(fromObject) {\r\n const toObject = {};\r\n const fromMediaResolution = getValueByPath(fromObject, [\r\n \"mediaResolution\"\r\n ]);\r\n if (fromMediaResolution != null) {\r\n setValueByPath(toObject, [\"mediaResolution\"], fromMediaResolution);\r\n }\r\n const fromCodeExecutionResult = getValueByPath(fromObject, [\r\n \"codeExecutionResult\"\r\n ]);\r\n if (fromCodeExecutionResult != null) {\r\n setValueByPath(toObject, [\"codeExecutionResult\"], fromCodeExecutionResult);\r\n }\r\n const fromExecutableCode = getValueByPath(fromObject, [\r\n \"executableCode\"\r\n ]);\r\n if (fromExecutableCode != null) {\r\n setValueByPath(toObject, [\"executableCode\"], fromExecutableCode);\r\n }\r\n const fromFileData = getValueByPath(fromObject, [\"fileData\"]);\r\n if (fromFileData != null) {\r\n setValueByPath(toObject, [\"fileData\"], fileDataToMldev$4(fromFileData));\r\n }\r\n const fromFunctionCall = getValueByPath(fromObject, [\"functionCall\"]);\r\n if (fromFunctionCall != null) {\r\n setValueByPath(toObject, [\"functionCall\"], functionCallToMldev$4(fromFunctionCall));\r\n }\r\n const fromFunctionResponse = getValueByPath(fromObject, [\r\n \"functionResponse\"\r\n ]);\r\n if (fromFunctionResponse != null) {\r\n setValueByPath(toObject, [\"functionResponse\"], fromFunctionResponse);\r\n }\r\n const fromInlineData = getValueByPath(fromObject, [\"inlineData\"]);\r\n if (fromInlineData != null) {\r\n setValueByPath(toObject, [\"inlineData\"], blobToMldev$4(fromInlineData));\r\n }\r\n const fromText = getValueByPath(fromObject, [\"text\"]);\r\n if (fromText != null) {\r\n setValueByPath(toObject, [\"text\"], fromText);\r\n }\r\n const fromThought = getValueByPath(fromObject, [\"thought\"]);\r\n if (fromThought != null) {\r\n setValueByPath(toObject, [\"thought\"], fromThought);\r\n }\r\n const fromThoughtSignature = getValueByPath(fromObject, [\r\n \"thoughtSignature\"\r\n ]);\r\n if (fromThoughtSignature != null) {\r\n setValueByPath(toObject, [\"thoughtSignature\"], fromThoughtSignature);\r\n }\r\n const fromVideoMetadata = getValueByPath(fromObject, [\r\n \"videoMetadata\"\r\n ]);\r\n if (fromVideoMetadata != null) {\r\n setValueByPath(toObject, [\"videoMetadata\"], fromVideoMetadata);\r\n }\r\n const fromToolCall = getValueByPath(fromObject, [\"toolCall\"]);\r\n if (fromToolCall != null) {\r\n setValueByPath(toObject, [\"toolCall\"], fromToolCall);\r\n }\r\n const fromToolResponse = getValueByPath(fromObject, [\"toolResponse\"]);\r\n if (fromToolResponse != null) {\r\n setValueByPath(toObject, [\"toolResponse\"], fromToolResponse);\r\n }\r\n const fromPartMetadata = getValueByPath(fromObject, [\"partMetadata\"]);\r\n if (fromPartMetadata != null) {\r\n setValueByPath(toObject, [\"partMetadata\"], fromPartMetadata);\r\n }\r\n return toObject;\r\n}\r\nfunction safetySettingToMldev$1(fromObject) {\r\n const toObject = {};\r\n const fromCategory = getValueByPath(fromObject, [\"category\"]);\r\n if (fromCategory != null) {\r\n setValueByPath(toObject, [\"category\"], fromCategory);\r\n }\r\n if (getValueByPath(fromObject, [\"method\"]) !== void 0) {\r\n throw new Error(\"method parameter is not supported in Gemini API.\");\r\n }\r\n const fromThreshold = getValueByPath(fromObject, [\"threshold\"]);\r\n if (fromThreshold != null) {\r\n setValueByPath(toObject, [\"threshold\"], fromThreshold);\r\n }\r\n return toObject;\r\n}\r\nfunction toolConfigToMldev$2(fromObject) {\r\n const toObject = {};\r\n const fromRetrievalConfig = getValueByPath(fromObject, [\r\n \"retrievalConfig\"\r\n ]);\r\n if (fromRetrievalConfig != null) {\r\n setValueByPath(toObject, [\"retrievalConfig\"], fromRetrievalConfig);\r\n }\r\n const fromFunctionCallingConfig = getValueByPath(fromObject, [\r\n \"functionCallingConfig\"\r\n ]);\r\n if (fromFunctionCallingConfig != null) {\r\n setValueByPath(toObject, [\"functionCallingConfig\"], functionCallingConfigToMldev$2(fromFunctionCallingConfig));\r\n }\r\n const fromIncludeServerSideToolInvocations = getValueByPath(fromObject, [\"includeServerSideToolInvocations\"]);\r\n if (fromIncludeServerSideToolInvocations != null) {\r\n setValueByPath(toObject, [\"includeServerSideToolInvocations\"], fromIncludeServerSideToolInvocations);\r\n }\r\n return toObject;\r\n}\r\nfunction toolToMldev$4(fromObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"retrieval\"]) !== void 0) {\r\n throw new Error(\"retrieval parameter is not supported in Gemini API.\");\r\n }\r\n const fromComputerUse = getValueByPath(fromObject, [\"computerUse\"]);\r\n if (fromComputerUse != null) {\r\n setValueByPath(toObject, [\"computerUse\"], fromComputerUse);\r\n }\r\n const fromFileSearch = getValueByPath(fromObject, [\"fileSearch\"]);\r\n if (fromFileSearch != null) {\r\n setValueByPath(toObject, [\"fileSearch\"], fromFileSearch);\r\n }\r\n const fromGoogleSearch = getValueByPath(fromObject, [\"googleSearch\"]);\r\n if (fromGoogleSearch != null) {\r\n setValueByPath(toObject, [\"googleSearch\"], googleSearchToMldev$4(fromGoogleSearch));\r\n }\r\n const fromGoogleMaps = getValueByPath(fromObject, [\"googleMaps\"]);\r\n if (fromGoogleMaps != null) {\r\n setValueByPath(toObject, [\"googleMaps\"], googleMapsToMldev$4(fromGoogleMaps));\r\n }\r\n const fromCodeExecution = getValueByPath(fromObject, [\r\n \"codeExecution\"\r\n ]);\r\n if (fromCodeExecution != null) {\r\n setValueByPath(toObject, [\"codeExecution\"], fromCodeExecution);\r\n }\r\n if (getValueByPath(fromObject, [\"enterpriseWebSearch\"]) !== void 0) {\r\n throw new Error(\"enterpriseWebSearch parameter is not supported in Gemini API.\");\r\n }\r\n const fromFunctionDeclarations = getValueByPath(fromObject, [\r\n \"functionDeclarations\"\r\n ]);\r\n if (fromFunctionDeclarations != null) {\r\n let transformedList = fromFunctionDeclarations;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"functionDeclarations\"], transformedList);\r\n }\r\n const fromGoogleSearchRetrieval = getValueByPath(fromObject, [\r\n \"googleSearchRetrieval\"\r\n ]);\r\n if (fromGoogleSearchRetrieval != null) {\r\n setValueByPath(toObject, [\"googleSearchRetrieval\"], fromGoogleSearchRetrieval);\r\n }\r\n if (getValueByPath(fromObject, [\"parallelAiSearch\"]) !== void 0) {\r\n throw new Error(\"parallelAiSearch parameter is not supported in Gemini API.\");\r\n }\r\n const fromUrlContext = getValueByPath(fromObject, [\"urlContext\"]);\r\n if (fromUrlContext != null) {\r\n setValueByPath(toObject, [\"urlContext\"], fromUrlContext);\r\n }\r\n const fromMcpServers = getValueByPath(fromObject, [\"mcpServers\"]);\r\n if (fromMcpServers != null) {\r\n let transformedList = fromMcpServers;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"mcpServers\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction authConfigToMldev$3(fromObject) {\r\n const toObject = {};\r\n const fromApiKey = getValueByPath(fromObject, [\"apiKey\"]);\r\n if (fromApiKey != null) {\r\n setValueByPath(toObject, [\"apiKey\"], fromApiKey);\r\n }\r\n if (getValueByPath(fromObject, [\"apiKeyConfig\"]) !== void 0) {\r\n throw new Error(\"apiKeyConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"authType\"]) !== void 0) {\r\n throw new Error(\"authType parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"googleServiceAccountConfig\"]) !== void 0) {\r\n throw new Error(\"googleServiceAccountConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"httpBasicAuthConfig\"]) !== void 0) {\r\n throw new Error(\"httpBasicAuthConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"oauthConfig\"]) !== void 0) {\r\n throw new Error(\"oauthConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"oidcConfig\"]) !== void 0) {\r\n throw new Error(\"oidcConfig parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction blobToMldev$3(fromObject) {\r\n const toObject = {};\r\n const fromData = getValueByPath(fromObject, [\"data\"]);\r\n if (fromData != null) {\r\n setValueByPath(toObject, [\"data\"], fromData);\r\n }\r\n if (getValueByPath(fromObject, [\"displayName\"]) !== void 0) {\r\n throw new Error(\"displayName parameter is not supported in Gemini API.\");\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction contentToMldev$3(fromObject) {\r\n const toObject = {};\r\n const fromParts = getValueByPath(fromObject, [\"parts\"]);\r\n if (fromParts != null) {\r\n let transformedList = fromParts;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return partToMldev$3(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"parts\"], transformedList);\r\n }\r\n const fromRole = getValueByPath(fromObject, [\"role\"]);\r\n if (fromRole != null) {\r\n setValueByPath(toObject, [\"role\"], fromRole);\r\n }\r\n return toObject;\r\n}\r\nfunction contentToVertex$2(fromObject) {\r\n const toObject = {};\r\n const fromParts = getValueByPath(fromObject, [\"parts\"]);\r\n if (fromParts != null) {\r\n let transformedList = fromParts;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return partToVertex$2(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"parts\"], transformedList);\r\n }\r\n const fromRole = getValueByPath(fromObject, [\"role\"]);\r\n if (fromRole != null) {\r\n setValueByPath(toObject, [\"role\"], fromRole);\r\n }\r\n return toObject;\r\n}\r\nfunction createCachedContentConfigToMldev(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromTtl = getValueByPath(fromObject, [\"ttl\"]);\r\n if (parentObject !== void 0 && fromTtl != null) {\r\n setValueByPath(parentObject, [\"ttl\"], fromTtl);\r\n }\r\n const fromExpireTime = getValueByPath(fromObject, [\"expireTime\"]);\r\n if (parentObject !== void 0 && fromExpireTime != null) {\r\n setValueByPath(parentObject, [\"expireTime\"], fromExpireTime);\r\n }\r\n const fromDisplayName = getValueByPath(fromObject, [\"displayName\"]);\r\n if (parentObject !== void 0 && fromDisplayName != null) {\r\n setValueByPath(parentObject, [\"displayName\"], fromDisplayName);\r\n }\r\n const fromContents = getValueByPath(fromObject, [\"contents\"]);\r\n if (parentObject !== void 0 && fromContents != null) {\r\n let transformedList = tContents(fromContents);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return contentToMldev$3(item);\r\n });\r\n }\r\n setValueByPath(parentObject, [\"contents\"], transformedList);\r\n }\r\n const fromSystemInstruction = getValueByPath(fromObject, [\r\n \"systemInstruction\"\r\n ]);\r\n if (parentObject !== void 0 && fromSystemInstruction != null) {\r\n setValueByPath(parentObject, [\"systemInstruction\"], contentToMldev$3(tContent(fromSystemInstruction)));\r\n }\r\n const fromTools = getValueByPath(fromObject, [\"tools\"]);\r\n if (parentObject !== void 0 && fromTools != null) {\r\n let transformedList = fromTools;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return toolToMldev$3(item);\r\n });\r\n }\r\n setValueByPath(parentObject, [\"tools\"], transformedList);\r\n }\r\n const fromToolConfig = getValueByPath(fromObject, [\"toolConfig\"]);\r\n if (parentObject !== void 0 && fromToolConfig != null) {\r\n setValueByPath(parentObject, [\"toolConfig\"], toolConfigToMldev$1(fromToolConfig));\r\n }\r\n if (getValueByPath(fromObject, [\"kmsKeyName\"]) !== void 0) {\r\n throw new Error(\"kmsKeyName parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction createCachedContentConfigToVertex(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromTtl = getValueByPath(fromObject, [\"ttl\"]);\r\n if (parentObject !== void 0 && fromTtl != null) {\r\n setValueByPath(parentObject, [\"ttl\"], fromTtl);\r\n }\r\n const fromExpireTime = getValueByPath(fromObject, [\"expireTime\"]);\r\n if (parentObject !== void 0 && fromExpireTime != null) {\r\n setValueByPath(parentObject, [\"expireTime\"], fromExpireTime);\r\n }\r\n const fromDisplayName = getValueByPath(fromObject, [\"displayName\"]);\r\n if (parentObject !== void 0 && fromDisplayName != null) {\r\n setValueByPath(parentObject, [\"displayName\"], fromDisplayName);\r\n }\r\n const fromContents = getValueByPath(fromObject, [\"contents\"]);\r\n if (parentObject !== void 0 && fromContents != null) {\r\n let transformedList = tContents(fromContents);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return contentToVertex$2(item);\r\n });\r\n }\r\n setValueByPath(parentObject, [\"contents\"], transformedList);\r\n }\r\n const fromSystemInstruction = getValueByPath(fromObject, [\r\n \"systemInstruction\"\r\n ]);\r\n if (parentObject !== void 0 && fromSystemInstruction != null) {\r\n setValueByPath(parentObject, [\"systemInstruction\"], contentToVertex$2(tContent(fromSystemInstruction)));\r\n }\r\n const fromTools = getValueByPath(fromObject, [\"tools\"]);\r\n if (parentObject !== void 0 && fromTools != null) {\r\n let transformedList = fromTools;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return toolToVertex$2(item);\r\n });\r\n }\r\n setValueByPath(parentObject, [\"tools\"], transformedList);\r\n }\r\n const fromToolConfig = getValueByPath(fromObject, [\"toolConfig\"]);\r\n if (parentObject !== void 0 && fromToolConfig != null) {\r\n setValueByPath(parentObject, [\"toolConfig\"], toolConfigToVertex$1(fromToolConfig));\r\n }\r\n const fromKmsKeyName = getValueByPath(fromObject, [\"kmsKeyName\"]);\r\n if (parentObject !== void 0 && fromKmsKeyName != null) {\r\n setValueByPath(parentObject, [\"encryption_spec\", \"kmsKeyName\"], fromKmsKeyName);\r\n }\r\n return toObject;\r\n}\r\nfunction createCachedContentParametersToMldev(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"model\"], tCachesModel(apiClient, fromModel));\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n createCachedContentConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction createCachedContentParametersToVertex(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"model\"], tCachesModel(apiClient, fromModel));\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n createCachedContentConfigToVertex(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction deleteCachedContentParametersToMldev(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], tCachedContentName(apiClient, fromName));\r\n }\r\n return toObject;\r\n}\r\nfunction deleteCachedContentParametersToVertex(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], tCachedContentName(apiClient, fromName));\r\n }\r\n return toObject;\r\n}\r\nfunction deleteCachedContentResponseFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n return toObject;\r\n}\r\nfunction deleteCachedContentResponseFromVertex(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n return toObject;\r\n}\r\nfunction fileDataToMldev$3(fromObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"displayName\"]) !== void 0) {\r\n throw new Error(\"displayName parameter is not supported in Gemini API.\");\r\n }\r\n const fromFileUri = getValueByPath(fromObject, [\"fileUri\"]);\r\n if (fromFileUri != null) {\r\n setValueByPath(toObject, [\"fileUri\"], fromFileUri);\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction functionCallToMldev$3(fromObject) {\r\n const toObject = {};\r\n const fromId = getValueByPath(fromObject, [\"id\"]);\r\n if (fromId != null) {\r\n setValueByPath(toObject, [\"id\"], fromId);\r\n }\r\n const fromArgs = getValueByPath(fromObject, [\"args\"]);\r\n if (fromArgs != null) {\r\n setValueByPath(toObject, [\"args\"], fromArgs);\r\n }\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n if (getValueByPath(fromObject, [\"partialArgs\"]) !== void 0) {\r\n throw new Error(\"partialArgs parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"willContinue\"]) !== void 0) {\r\n throw new Error(\"willContinue parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction functionCallingConfigToMldev$1(fromObject) {\r\n const toObject = {};\r\n const fromAllowedFunctionNames = getValueByPath(fromObject, [\r\n \"allowedFunctionNames\"\r\n ]);\r\n if (fromAllowedFunctionNames != null) {\r\n setValueByPath(toObject, [\"allowedFunctionNames\"], fromAllowedFunctionNames);\r\n }\r\n const fromMode = getValueByPath(fromObject, [\"mode\"]);\r\n if (fromMode != null) {\r\n setValueByPath(toObject, [\"mode\"], fromMode);\r\n }\r\n if (getValueByPath(fromObject, [\"streamFunctionCallArguments\"]) !== void 0) {\r\n throw new Error(\"streamFunctionCallArguments parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction functionDeclarationToVertex$2(fromObject) {\r\n const toObject = {};\r\n const fromDescription = getValueByPath(fromObject, [\"description\"]);\r\n if (fromDescription != null) {\r\n setValueByPath(toObject, [\"description\"], fromDescription);\r\n }\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromParameters = getValueByPath(fromObject, [\"parameters\"]);\r\n if (fromParameters != null) {\r\n setValueByPath(toObject, [\"parameters\"], fromParameters);\r\n }\r\n const fromParametersJsonSchema = getValueByPath(fromObject, [\r\n \"parametersJsonSchema\"\r\n ]);\r\n if (fromParametersJsonSchema != null) {\r\n setValueByPath(toObject, [\"parametersJsonSchema\"], fromParametersJsonSchema);\r\n }\r\n const fromResponse = getValueByPath(fromObject, [\"response\"]);\r\n if (fromResponse != null) {\r\n setValueByPath(toObject, [\"response\"], fromResponse);\r\n }\r\n const fromResponseJsonSchema = getValueByPath(fromObject, [\r\n \"responseJsonSchema\"\r\n ]);\r\n if (fromResponseJsonSchema != null) {\r\n setValueByPath(toObject, [\"responseJsonSchema\"], fromResponseJsonSchema);\r\n }\r\n if (getValueByPath(fromObject, [\"behavior\"]) !== void 0) {\r\n throw new Error(\"behavior parameter is not supported in Vertex AI.\");\r\n }\r\n return toObject;\r\n}\r\nfunction getCachedContentParametersToMldev(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], tCachedContentName(apiClient, fromName));\r\n }\r\n return toObject;\r\n}\r\nfunction getCachedContentParametersToVertex(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], tCachedContentName(apiClient, fromName));\r\n }\r\n return toObject;\r\n}\r\nfunction googleMapsToMldev$3(fromObject) {\r\n const toObject = {};\r\n const fromAuthConfig = getValueByPath(fromObject, [\"authConfig\"]);\r\n if (fromAuthConfig != null) {\r\n setValueByPath(toObject, [\"authConfig\"], authConfigToMldev$3(fromAuthConfig));\r\n }\r\n const fromEnableWidget = getValueByPath(fromObject, [\"enableWidget\"]);\r\n if (fromEnableWidget != null) {\r\n setValueByPath(toObject, [\"enableWidget\"], fromEnableWidget);\r\n }\r\n return toObject;\r\n}\r\nfunction googleSearchToMldev$3(fromObject) {\r\n const toObject = {};\r\n const fromSearchTypes = getValueByPath(fromObject, [\"searchTypes\"]);\r\n if (fromSearchTypes != null) {\r\n setValueByPath(toObject, [\"searchTypes\"], fromSearchTypes);\r\n }\r\n if (getValueByPath(fromObject, [\"blockingConfidence\"]) !== void 0) {\r\n throw new Error(\"blockingConfidence parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"excludeDomains\"]) !== void 0) {\r\n throw new Error(\"excludeDomains parameter is not supported in Gemini API.\");\r\n }\r\n const fromTimeRangeFilter = getValueByPath(fromObject, [\r\n \"timeRangeFilter\"\r\n ]);\r\n if (fromTimeRangeFilter != null) {\r\n setValueByPath(toObject, [\"timeRangeFilter\"], fromTimeRangeFilter);\r\n }\r\n return toObject;\r\n}\r\nfunction listCachedContentsConfigToMldev(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromPageSize = getValueByPath(fromObject, [\"pageSize\"]);\r\n if (parentObject !== void 0 && fromPageSize != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageSize\"], fromPageSize);\r\n }\r\n const fromPageToken = getValueByPath(fromObject, [\"pageToken\"]);\r\n if (parentObject !== void 0 && fromPageToken != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageToken\"], fromPageToken);\r\n }\r\n return toObject;\r\n}\r\nfunction listCachedContentsConfigToVertex(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromPageSize = getValueByPath(fromObject, [\"pageSize\"]);\r\n if (parentObject !== void 0 && fromPageSize != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageSize\"], fromPageSize);\r\n }\r\n const fromPageToken = getValueByPath(fromObject, [\"pageToken\"]);\r\n if (parentObject !== void 0 && fromPageToken != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageToken\"], fromPageToken);\r\n }\r\n return toObject;\r\n}\r\nfunction listCachedContentsParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n listCachedContentsConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction listCachedContentsParametersToVertex(fromObject) {\r\n const toObject = {};\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n listCachedContentsConfigToVertex(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction listCachedContentsResponseFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromNextPageToken = getValueByPath(fromObject, [\r\n \"nextPageToken\"\r\n ]);\r\n if (fromNextPageToken != null) {\r\n setValueByPath(toObject, [\"nextPageToken\"], fromNextPageToken);\r\n }\r\n const fromCachedContents = getValueByPath(fromObject, [\r\n \"cachedContents\"\r\n ]);\r\n if (fromCachedContents != null) {\r\n let transformedList = fromCachedContents;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"cachedContents\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction listCachedContentsResponseFromVertex(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromNextPageToken = getValueByPath(fromObject, [\r\n \"nextPageToken\"\r\n ]);\r\n if (fromNextPageToken != null) {\r\n setValueByPath(toObject, [\"nextPageToken\"], fromNextPageToken);\r\n }\r\n const fromCachedContents = getValueByPath(fromObject, [\r\n \"cachedContents\"\r\n ]);\r\n if (fromCachedContents != null) {\r\n let transformedList = fromCachedContents;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"cachedContents\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction partToMldev$3(fromObject) {\r\n const toObject = {};\r\n const fromMediaResolution = getValueByPath(fromObject, [\r\n \"mediaResolution\"\r\n ]);\r\n if (fromMediaResolution != null) {\r\n setValueByPath(toObject, [\"mediaResolution\"], fromMediaResolution);\r\n }\r\n const fromCodeExecutionResult = getValueByPath(fromObject, [\r\n \"codeExecutionResult\"\r\n ]);\r\n if (fromCodeExecutionResult != null) {\r\n setValueByPath(toObject, [\"codeExecutionResult\"], fromCodeExecutionResult);\r\n }\r\n const fromExecutableCode = getValueByPath(fromObject, [\r\n \"executableCode\"\r\n ]);\r\n if (fromExecutableCode != null) {\r\n setValueByPath(toObject, [\"executableCode\"], fromExecutableCode);\r\n }\r\n const fromFileData = getValueByPath(fromObject, [\"fileData\"]);\r\n if (fromFileData != null) {\r\n setValueByPath(toObject, [\"fileData\"], fileDataToMldev$3(fromFileData));\r\n }\r\n const fromFunctionCall = getValueByPath(fromObject, [\"functionCall\"]);\r\n if (fromFunctionCall != null) {\r\n setValueByPath(toObject, [\"functionCall\"], functionCallToMldev$3(fromFunctionCall));\r\n }\r\n const fromFunctionResponse = getValueByPath(fromObject, [\r\n \"functionResponse\"\r\n ]);\r\n if (fromFunctionResponse != null) {\r\n setValueByPath(toObject, [\"functionResponse\"], fromFunctionResponse);\r\n }\r\n const fromInlineData = getValueByPath(fromObject, [\"inlineData\"]);\r\n if (fromInlineData != null) {\r\n setValueByPath(toObject, [\"inlineData\"], blobToMldev$3(fromInlineData));\r\n }\r\n const fromText = getValueByPath(fromObject, [\"text\"]);\r\n if (fromText != null) {\r\n setValueByPath(toObject, [\"text\"], fromText);\r\n }\r\n const fromThought = getValueByPath(fromObject, [\"thought\"]);\r\n if (fromThought != null) {\r\n setValueByPath(toObject, [\"thought\"], fromThought);\r\n }\r\n const fromThoughtSignature = getValueByPath(fromObject, [\r\n \"thoughtSignature\"\r\n ]);\r\n if (fromThoughtSignature != null) {\r\n setValueByPath(toObject, [\"thoughtSignature\"], fromThoughtSignature);\r\n }\r\n const fromVideoMetadata = getValueByPath(fromObject, [\r\n \"videoMetadata\"\r\n ]);\r\n if (fromVideoMetadata != null) {\r\n setValueByPath(toObject, [\"videoMetadata\"], fromVideoMetadata);\r\n }\r\n const fromToolCall = getValueByPath(fromObject, [\"toolCall\"]);\r\n if (fromToolCall != null) {\r\n setValueByPath(toObject, [\"toolCall\"], fromToolCall);\r\n }\r\n const fromToolResponse = getValueByPath(fromObject, [\"toolResponse\"]);\r\n if (fromToolResponse != null) {\r\n setValueByPath(toObject, [\"toolResponse\"], fromToolResponse);\r\n }\r\n const fromPartMetadata = getValueByPath(fromObject, [\"partMetadata\"]);\r\n if (fromPartMetadata != null) {\r\n setValueByPath(toObject, [\"partMetadata\"], fromPartMetadata);\r\n }\r\n return toObject;\r\n}\r\nfunction partToVertex$2(fromObject) {\r\n const toObject = {};\r\n const fromMediaResolution = getValueByPath(fromObject, [\r\n \"mediaResolution\"\r\n ]);\r\n if (fromMediaResolution != null) {\r\n setValueByPath(toObject, [\"mediaResolution\"], fromMediaResolution);\r\n }\r\n const fromCodeExecutionResult = getValueByPath(fromObject, [\r\n \"codeExecutionResult\"\r\n ]);\r\n if (fromCodeExecutionResult != null) {\r\n setValueByPath(toObject, [\"codeExecutionResult\"], fromCodeExecutionResult);\r\n }\r\n const fromExecutableCode = getValueByPath(fromObject, [\r\n \"executableCode\"\r\n ]);\r\n if (fromExecutableCode != null) {\r\n setValueByPath(toObject, [\"executableCode\"], fromExecutableCode);\r\n }\r\n const fromFileData = getValueByPath(fromObject, [\"fileData\"]);\r\n if (fromFileData != null) {\r\n setValueByPath(toObject, [\"fileData\"], fromFileData);\r\n }\r\n const fromFunctionCall = getValueByPath(fromObject, [\"functionCall\"]);\r\n if (fromFunctionCall != null) {\r\n setValueByPath(toObject, [\"functionCall\"], fromFunctionCall);\r\n }\r\n const fromFunctionResponse = getValueByPath(fromObject, [\r\n \"functionResponse\"\r\n ]);\r\n if (fromFunctionResponse != null) {\r\n setValueByPath(toObject, [\"functionResponse\"], fromFunctionResponse);\r\n }\r\n const fromInlineData = getValueByPath(fromObject, [\"inlineData\"]);\r\n if (fromInlineData != null) {\r\n setValueByPath(toObject, [\"inlineData\"], fromInlineData);\r\n }\r\n const fromText = getValueByPath(fromObject, [\"text\"]);\r\n if (fromText != null) {\r\n setValueByPath(toObject, [\"text\"], fromText);\r\n }\r\n const fromThought = getValueByPath(fromObject, [\"thought\"]);\r\n if (fromThought != null) {\r\n setValueByPath(toObject, [\"thought\"], fromThought);\r\n }\r\n const fromThoughtSignature = getValueByPath(fromObject, [\r\n \"thoughtSignature\"\r\n ]);\r\n if (fromThoughtSignature != null) {\r\n setValueByPath(toObject, [\"thoughtSignature\"], fromThoughtSignature);\r\n }\r\n const fromVideoMetadata = getValueByPath(fromObject, [\r\n \"videoMetadata\"\r\n ]);\r\n if (fromVideoMetadata != null) {\r\n setValueByPath(toObject, [\"videoMetadata\"], fromVideoMetadata);\r\n }\r\n if (getValueByPath(fromObject, [\"toolCall\"]) !== void 0) {\r\n throw new Error(\"toolCall parameter is not supported in Vertex AI.\");\r\n }\r\n if (getValueByPath(fromObject, [\"toolResponse\"]) !== void 0) {\r\n throw new Error(\"toolResponse parameter is not supported in Vertex AI.\");\r\n }\r\n if (getValueByPath(fromObject, [\"partMetadata\"]) !== void 0) {\r\n throw new Error(\"partMetadata parameter is not supported in Vertex AI.\");\r\n }\r\n return toObject;\r\n}\r\nfunction toolConfigToMldev$1(fromObject) {\r\n const toObject = {};\r\n const fromRetrievalConfig = getValueByPath(fromObject, [\r\n \"retrievalConfig\"\r\n ]);\r\n if (fromRetrievalConfig != null) {\r\n setValueByPath(toObject, [\"retrievalConfig\"], fromRetrievalConfig);\r\n }\r\n const fromFunctionCallingConfig = getValueByPath(fromObject, [\r\n \"functionCallingConfig\"\r\n ]);\r\n if (fromFunctionCallingConfig != null) {\r\n setValueByPath(toObject, [\"functionCallingConfig\"], functionCallingConfigToMldev$1(fromFunctionCallingConfig));\r\n }\r\n const fromIncludeServerSideToolInvocations = getValueByPath(fromObject, [\"includeServerSideToolInvocations\"]);\r\n if (fromIncludeServerSideToolInvocations != null) {\r\n setValueByPath(toObject, [\"includeServerSideToolInvocations\"], fromIncludeServerSideToolInvocations);\r\n }\r\n return toObject;\r\n}\r\nfunction toolConfigToVertex$1(fromObject) {\r\n const toObject = {};\r\n const fromRetrievalConfig = getValueByPath(fromObject, [\r\n \"retrievalConfig\"\r\n ]);\r\n if (fromRetrievalConfig != null) {\r\n setValueByPath(toObject, [\"retrievalConfig\"], fromRetrievalConfig);\r\n }\r\n const fromFunctionCallingConfig = getValueByPath(fromObject, [\r\n \"functionCallingConfig\"\r\n ]);\r\n if (fromFunctionCallingConfig != null) {\r\n setValueByPath(toObject, [\"functionCallingConfig\"], fromFunctionCallingConfig);\r\n }\r\n if (getValueByPath(fromObject, [\"includeServerSideToolInvocations\"]) !== void 0) {\r\n throw new Error(\"includeServerSideToolInvocations parameter is not supported in Vertex AI.\");\r\n }\r\n return toObject;\r\n}\r\nfunction toolToMldev$3(fromObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"retrieval\"]) !== void 0) {\r\n throw new Error(\"retrieval parameter is not supported in Gemini API.\");\r\n }\r\n const fromComputerUse = getValueByPath(fromObject, [\"computerUse\"]);\r\n if (fromComputerUse != null) {\r\n setValueByPath(toObject, [\"computerUse\"], fromComputerUse);\r\n }\r\n const fromFileSearch = getValueByPath(fromObject, [\"fileSearch\"]);\r\n if (fromFileSearch != null) {\r\n setValueByPath(toObject, [\"fileSearch\"], fromFileSearch);\r\n }\r\n const fromGoogleSearch = getValueByPath(fromObject, [\"googleSearch\"]);\r\n if (fromGoogleSearch != null) {\r\n setValueByPath(toObject, [\"googleSearch\"], googleSearchToMldev$3(fromGoogleSearch));\r\n }\r\n const fromGoogleMaps = getValueByPath(fromObject, [\"googleMaps\"]);\r\n if (fromGoogleMaps != null) {\r\n setValueByPath(toObject, [\"googleMaps\"], googleMapsToMldev$3(fromGoogleMaps));\r\n }\r\n const fromCodeExecution = getValueByPath(fromObject, [\r\n \"codeExecution\"\r\n ]);\r\n if (fromCodeExecution != null) {\r\n setValueByPath(toObject, [\"codeExecution\"], fromCodeExecution);\r\n }\r\n if (getValueByPath(fromObject, [\"enterpriseWebSearch\"]) !== void 0) {\r\n throw new Error(\"enterpriseWebSearch parameter is not supported in Gemini API.\");\r\n }\r\n const fromFunctionDeclarations = getValueByPath(fromObject, [\r\n \"functionDeclarations\"\r\n ]);\r\n if (fromFunctionDeclarations != null) {\r\n let transformedList = fromFunctionDeclarations;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"functionDeclarations\"], transformedList);\r\n }\r\n const fromGoogleSearchRetrieval = getValueByPath(fromObject, [\r\n \"googleSearchRetrieval\"\r\n ]);\r\n if (fromGoogleSearchRetrieval != null) {\r\n setValueByPath(toObject, [\"googleSearchRetrieval\"], fromGoogleSearchRetrieval);\r\n }\r\n if (getValueByPath(fromObject, [\"parallelAiSearch\"]) !== void 0) {\r\n throw new Error(\"parallelAiSearch parameter is not supported in Gemini API.\");\r\n }\r\n const fromUrlContext = getValueByPath(fromObject, [\"urlContext\"]);\r\n if (fromUrlContext != null) {\r\n setValueByPath(toObject, [\"urlContext\"], fromUrlContext);\r\n }\r\n const fromMcpServers = getValueByPath(fromObject, [\"mcpServers\"]);\r\n if (fromMcpServers != null) {\r\n let transformedList = fromMcpServers;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"mcpServers\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction toolToVertex$2(fromObject) {\r\n const toObject = {};\r\n const fromRetrieval = getValueByPath(fromObject, [\"retrieval\"]);\r\n if (fromRetrieval != null) {\r\n setValueByPath(toObject, [\"retrieval\"], fromRetrieval);\r\n }\r\n const fromComputerUse = getValueByPath(fromObject, [\"computerUse\"]);\r\n if (fromComputerUse != null) {\r\n setValueByPath(toObject, [\"computerUse\"], fromComputerUse);\r\n }\r\n if (getValueByPath(fromObject, [\"fileSearch\"]) !== void 0) {\r\n throw new Error(\"fileSearch parameter is not supported in Vertex AI.\");\r\n }\r\n const fromGoogleSearch = getValueByPath(fromObject, [\"googleSearch\"]);\r\n if (fromGoogleSearch != null) {\r\n setValueByPath(toObject, [\"googleSearch\"], fromGoogleSearch);\r\n }\r\n const fromGoogleMaps = getValueByPath(fromObject, [\"googleMaps\"]);\r\n if (fromGoogleMaps != null) {\r\n setValueByPath(toObject, [\"googleMaps\"], fromGoogleMaps);\r\n }\r\n const fromCodeExecution = getValueByPath(fromObject, [\r\n \"codeExecution\"\r\n ]);\r\n if (fromCodeExecution != null) {\r\n setValueByPath(toObject, [\"codeExecution\"], fromCodeExecution);\r\n }\r\n const fromEnterpriseWebSearch = getValueByPath(fromObject, [\r\n \"enterpriseWebSearch\"\r\n ]);\r\n if (fromEnterpriseWebSearch != null) {\r\n setValueByPath(toObject, [\"enterpriseWebSearch\"], fromEnterpriseWebSearch);\r\n }\r\n const fromFunctionDeclarations = getValueByPath(fromObject, [\r\n \"functionDeclarations\"\r\n ]);\r\n if (fromFunctionDeclarations != null) {\r\n let transformedList = fromFunctionDeclarations;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return functionDeclarationToVertex$2(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"functionDeclarations\"], transformedList);\r\n }\r\n const fromGoogleSearchRetrieval = getValueByPath(fromObject, [\r\n \"googleSearchRetrieval\"\r\n ]);\r\n if (fromGoogleSearchRetrieval != null) {\r\n setValueByPath(toObject, [\"googleSearchRetrieval\"], fromGoogleSearchRetrieval);\r\n }\r\n const fromParallelAiSearch = getValueByPath(fromObject, [\r\n \"parallelAiSearch\"\r\n ]);\r\n if (fromParallelAiSearch != null) {\r\n setValueByPath(toObject, [\"parallelAiSearch\"], fromParallelAiSearch);\r\n }\r\n const fromUrlContext = getValueByPath(fromObject, [\"urlContext\"]);\r\n if (fromUrlContext != null) {\r\n setValueByPath(toObject, [\"urlContext\"], fromUrlContext);\r\n }\r\n if (getValueByPath(fromObject, [\"mcpServers\"]) !== void 0) {\r\n throw new Error(\"mcpServers parameter is not supported in Vertex AI.\");\r\n }\r\n return toObject;\r\n}\r\nfunction updateCachedContentConfigToMldev(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromTtl = getValueByPath(fromObject, [\"ttl\"]);\r\n if (parentObject !== void 0 && fromTtl != null) {\r\n setValueByPath(parentObject, [\"ttl\"], fromTtl);\r\n }\r\n const fromExpireTime = getValueByPath(fromObject, [\"expireTime\"]);\r\n if (parentObject !== void 0 && fromExpireTime != null) {\r\n setValueByPath(parentObject, [\"expireTime\"], fromExpireTime);\r\n }\r\n return toObject;\r\n}\r\nfunction updateCachedContentConfigToVertex(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromTtl = getValueByPath(fromObject, [\"ttl\"]);\r\n if (parentObject !== void 0 && fromTtl != null) {\r\n setValueByPath(parentObject, [\"ttl\"], fromTtl);\r\n }\r\n const fromExpireTime = getValueByPath(fromObject, [\"expireTime\"]);\r\n if (parentObject !== void 0 && fromExpireTime != null) {\r\n setValueByPath(parentObject, [\"expireTime\"], fromExpireTime);\r\n }\r\n return toObject;\r\n}\r\nfunction updateCachedContentParametersToMldev(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], tCachedContentName(apiClient, fromName));\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n updateCachedContentConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction updateCachedContentParametersToVertex(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], tCachedContentName(apiClient, fromName));\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n updateCachedContentConfigToVertex(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\nfunction __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function() {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\nfunction __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\nfunction __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function() {\r\n return this;\r\n }, i;\r\n function awaitReturn(f) {\r\n return function(v) {\r\n return Promise.resolve(v).then(f, reject);\r\n };\r\n }\r\n function verb(n, f) {\r\n if (g[n]) {\r\n i[n] = function(v) {\r\n return new Promise(function(a, b) {\r\n q.push([n, v, a, b]) > 1 || resume(n, v);\r\n });\r\n };\r\n if (f) i[n] = f(i[n]);\r\n }\r\n }\r\n function resume(n, v) {\r\n try {\r\n step(g[n](v));\r\n } catch (e) {\r\n settle(q[0][3], e);\r\n }\r\n }\r\n function step(r) {\r\n r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);\r\n }\r\n function fulfill(value) {\r\n resume(\"next\", value);\r\n }\r\n function reject(value) {\r\n resume(\"throw\", value);\r\n }\r\n function settle(f, v) {\r\n if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);\r\n }\r\n}\r\nfunction __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function() {\r\n return this;\r\n }, i);\r\n function verb(n) {\r\n i[n] = o[n] && function(v) {\r\n return new Promise(function(resolve, reject) {\r\n v = o[n](v), settle(resolve, reject, v.done, v.value);\r\n });\r\n };\r\n }\r\n function settle(resolve, reject, d, v) {\r\n Promise.resolve(v).then(function(v2) {\r\n resolve({ value: v2, done: d });\r\n }, reject);\r\n }\r\n}\r\nfunction isValidResponse(response) {\r\n var _a2;\r\n if (response.candidates == void 0 || response.candidates.length === 0) {\r\n return false;\r\n }\r\n const content = (_a2 = response.candidates[0]) === null || _a2 === void 0 ? void 0 : _a2.content;\r\n if (content === void 0) {\r\n return false;\r\n }\r\n return isValidContent(content);\r\n}\r\nfunction isValidContent(content) {\r\n if (content.parts === void 0 || content.parts.length === 0) {\r\n return false;\r\n }\r\n for (const part of content.parts) {\r\n if (part === void 0 || Object.keys(part).length === 0) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction validateHistory(history) {\r\n if (history.length === 0) {\r\n return;\r\n }\r\n for (const content of history) {\r\n if (content.role !== \"user\" && content.role !== \"model\") {\r\n throw new Error(`Role must be user or model, but got ${content.role}.`);\r\n }\r\n }\r\n}\r\nfunction extractCuratedHistory(comprehensiveHistory) {\r\n if (comprehensiveHistory === void 0 || comprehensiveHistory.length === 0) {\r\n return [];\r\n }\r\n const curatedHistory = [];\r\n const length = comprehensiveHistory.length;\r\n let i = 0;\r\n while (i < length) {\r\n if (comprehensiveHistory[i].role === \"user\") {\r\n curatedHistory.push(comprehensiveHistory[i]);\r\n i++;\r\n } else {\r\n const modelOutput = [];\r\n let isValid = true;\r\n while (i < length && comprehensiveHistory[i].role === \"model\") {\r\n modelOutput.push(comprehensiveHistory[i]);\r\n if (isValid && !isValidContent(comprehensiveHistory[i])) {\r\n isValid = false;\r\n }\r\n i++;\r\n }\r\n if (isValid) {\r\n curatedHistory.push(...modelOutput);\r\n } else {\r\n curatedHistory.pop();\r\n }\r\n }\r\n }\r\n return curatedHistory;\r\n}\r\nfunction createFileParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromFile = getValueByPath(fromObject, [\"file\"]);\r\n if (fromFile != null) {\r\n setValueByPath(toObject, [\"file\"], fromFile);\r\n }\r\n return toObject;\r\n}\r\nfunction createFileResponseFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n return toObject;\r\n}\r\nfunction deleteFileParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"file\"], tFileName(fromName));\r\n }\r\n return toObject;\r\n}\r\nfunction deleteFileResponseFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n return toObject;\r\n}\r\nfunction getFileParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"file\"], tFileName(fromName));\r\n }\r\n return toObject;\r\n}\r\nfunction internalRegisterFilesParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromUris = getValueByPath(fromObject, [\"uris\"]);\r\n if (fromUris != null) {\r\n setValueByPath(toObject, [\"uris\"], fromUris);\r\n }\r\n return toObject;\r\n}\r\nfunction listFilesConfigToMldev(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromPageSize = getValueByPath(fromObject, [\"pageSize\"]);\r\n if (parentObject !== void 0 && fromPageSize != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageSize\"], fromPageSize);\r\n }\r\n const fromPageToken = getValueByPath(fromObject, [\"pageToken\"]);\r\n if (parentObject !== void 0 && fromPageToken != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageToken\"], fromPageToken);\r\n }\r\n return toObject;\r\n}\r\nfunction listFilesParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n listFilesConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction listFilesResponseFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromNextPageToken = getValueByPath(fromObject, [\r\n \"nextPageToken\"\r\n ]);\r\n if (fromNextPageToken != null) {\r\n setValueByPath(toObject, [\"nextPageToken\"], fromNextPageToken);\r\n }\r\n const fromFiles = getValueByPath(fromObject, [\"files\"]);\r\n if (fromFiles != null) {\r\n let transformedList = fromFiles;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"files\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction registerFilesResponseFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromFiles = getValueByPath(fromObject, [\"files\"]);\r\n if (fromFiles != null) {\r\n let transformedList = fromFiles;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"files\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction audioTranscriptionConfigToMldev$1(fromObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"languageCodes\"]) !== void 0) {\r\n throw new Error(\"languageCodes parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction authConfigToMldev$2(fromObject) {\r\n const toObject = {};\r\n const fromApiKey = getValueByPath(fromObject, [\"apiKey\"]);\r\n if (fromApiKey != null) {\r\n setValueByPath(toObject, [\"apiKey\"], fromApiKey);\r\n }\r\n if (getValueByPath(fromObject, [\"apiKeyConfig\"]) !== void 0) {\r\n throw new Error(\"apiKeyConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"authType\"]) !== void 0) {\r\n throw new Error(\"authType parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"googleServiceAccountConfig\"]) !== void 0) {\r\n throw new Error(\"googleServiceAccountConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"httpBasicAuthConfig\"]) !== void 0) {\r\n throw new Error(\"httpBasicAuthConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"oauthConfig\"]) !== void 0) {\r\n throw new Error(\"oauthConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"oidcConfig\"]) !== void 0) {\r\n throw new Error(\"oidcConfig parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction blobToMldev$2(fromObject) {\r\n const toObject = {};\r\n const fromData = getValueByPath(fromObject, [\"data\"]);\r\n if (fromData != null) {\r\n setValueByPath(toObject, [\"data\"], fromData);\r\n }\r\n if (getValueByPath(fromObject, [\"displayName\"]) !== void 0) {\r\n throw new Error(\"displayName parameter is not supported in Gemini API.\");\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction contentToMldev$2(fromObject) {\r\n const toObject = {};\r\n const fromParts = getValueByPath(fromObject, [\"parts\"]);\r\n if (fromParts != null) {\r\n let transformedList = fromParts;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return partToMldev$2(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"parts\"], transformedList);\r\n }\r\n const fromRole = getValueByPath(fromObject, [\"role\"]);\r\n if (fromRole != null) {\r\n setValueByPath(toObject, [\"role\"], fromRole);\r\n }\r\n return toObject;\r\n}\r\nfunction contentToVertex$1(fromObject) {\r\n const toObject = {};\r\n const fromParts = getValueByPath(fromObject, [\"parts\"]);\r\n if (fromParts != null) {\r\n let transformedList = fromParts;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return partToVertex$1(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"parts\"], transformedList);\r\n }\r\n const fromRole = getValueByPath(fromObject, [\"role\"]);\r\n if (fromRole != null) {\r\n setValueByPath(toObject, [\"role\"], fromRole);\r\n }\r\n return toObject;\r\n}\r\nfunction fileDataToMldev$2(fromObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"displayName\"]) !== void 0) {\r\n throw new Error(\"displayName parameter is not supported in Gemini API.\");\r\n }\r\n const fromFileUri = getValueByPath(fromObject, [\"fileUri\"]);\r\n if (fromFileUri != null) {\r\n setValueByPath(toObject, [\"fileUri\"], fromFileUri);\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction functionCallToMldev$2(fromObject) {\r\n const toObject = {};\r\n const fromId = getValueByPath(fromObject, [\"id\"]);\r\n if (fromId != null) {\r\n setValueByPath(toObject, [\"id\"], fromId);\r\n }\r\n const fromArgs = getValueByPath(fromObject, [\"args\"]);\r\n if (fromArgs != null) {\r\n setValueByPath(toObject, [\"args\"], fromArgs);\r\n }\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n if (getValueByPath(fromObject, [\"partialArgs\"]) !== void 0) {\r\n throw new Error(\"partialArgs parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"willContinue\"]) !== void 0) {\r\n throw new Error(\"willContinue parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction functionDeclarationToVertex$1(fromObject) {\r\n const toObject = {};\r\n const fromDescription = getValueByPath(fromObject, [\"description\"]);\r\n if (fromDescription != null) {\r\n setValueByPath(toObject, [\"description\"], fromDescription);\r\n }\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromParameters = getValueByPath(fromObject, [\"parameters\"]);\r\n if (fromParameters != null) {\r\n setValueByPath(toObject, [\"parameters\"], fromParameters);\r\n }\r\n const fromParametersJsonSchema = getValueByPath(fromObject, [\r\n \"parametersJsonSchema\"\r\n ]);\r\n if (fromParametersJsonSchema != null) {\r\n setValueByPath(toObject, [\"parametersJsonSchema\"], fromParametersJsonSchema);\r\n }\r\n const fromResponse = getValueByPath(fromObject, [\"response\"]);\r\n if (fromResponse != null) {\r\n setValueByPath(toObject, [\"response\"], fromResponse);\r\n }\r\n const fromResponseJsonSchema = getValueByPath(fromObject, [\r\n \"responseJsonSchema\"\r\n ]);\r\n if (fromResponseJsonSchema != null) {\r\n setValueByPath(toObject, [\"responseJsonSchema\"], fromResponseJsonSchema);\r\n }\r\n if (getValueByPath(fromObject, [\"behavior\"]) !== void 0) {\r\n throw new Error(\"behavior parameter is not supported in Vertex AI.\");\r\n }\r\n return toObject;\r\n}\r\nfunction generationConfigToVertex$1(fromObject) {\r\n const toObject = {};\r\n const fromModelSelectionConfig = getValueByPath(fromObject, [\r\n \"modelSelectionConfig\"\r\n ]);\r\n if (fromModelSelectionConfig != null) {\r\n setValueByPath(toObject, [\"modelConfig\"], fromModelSelectionConfig);\r\n }\r\n const fromResponseJsonSchema = getValueByPath(fromObject, [\r\n \"responseJsonSchema\"\r\n ]);\r\n if (fromResponseJsonSchema != null) {\r\n setValueByPath(toObject, [\"responseJsonSchema\"], fromResponseJsonSchema);\r\n }\r\n const fromAudioTimestamp = getValueByPath(fromObject, [\r\n \"audioTimestamp\"\r\n ]);\r\n if (fromAudioTimestamp != null) {\r\n setValueByPath(toObject, [\"audioTimestamp\"], fromAudioTimestamp);\r\n }\r\n const fromCandidateCount = getValueByPath(fromObject, [\r\n \"candidateCount\"\r\n ]);\r\n if (fromCandidateCount != null) {\r\n setValueByPath(toObject, [\"candidateCount\"], fromCandidateCount);\r\n }\r\n const fromEnableAffectiveDialog = getValueByPath(fromObject, [\r\n \"enableAffectiveDialog\"\r\n ]);\r\n if (fromEnableAffectiveDialog != null) {\r\n setValueByPath(toObject, [\"enableAffectiveDialog\"], fromEnableAffectiveDialog);\r\n }\r\n const fromFrequencyPenalty = getValueByPath(fromObject, [\r\n \"frequencyPenalty\"\r\n ]);\r\n if (fromFrequencyPenalty != null) {\r\n setValueByPath(toObject, [\"frequencyPenalty\"], fromFrequencyPenalty);\r\n }\r\n const fromLogprobs = getValueByPath(fromObject, [\"logprobs\"]);\r\n if (fromLogprobs != null) {\r\n setValueByPath(toObject, [\"logprobs\"], fromLogprobs);\r\n }\r\n const fromMaxOutputTokens = getValueByPath(fromObject, [\r\n \"maxOutputTokens\"\r\n ]);\r\n if (fromMaxOutputTokens != null) {\r\n setValueByPath(toObject, [\"maxOutputTokens\"], fromMaxOutputTokens);\r\n }\r\n const fromMediaResolution = getValueByPath(fromObject, [\r\n \"mediaResolution\"\r\n ]);\r\n if (fromMediaResolution != null) {\r\n setValueByPath(toObject, [\"mediaResolution\"], fromMediaResolution);\r\n }\r\n const fromPresencePenalty = getValueByPath(fromObject, [\r\n \"presencePenalty\"\r\n ]);\r\n if (fromPresencePenalty != null) {\r\n setValueByPath(toObject, [\"presencePenalty\"], fromPresencePenalty);\r\n }\r\n const fromResponseLogprobs = getValueByPath(fromObject, [\r\n \"responseLogprobs\"\r\n ]);\r\n if (fromResponseLogprobs != null) {\r\n setValueByPath(toObject, [\"responseLogprobs\"], fromResponseLogprobs);\r\n }\r\n const fromResponseMimeType = getValueByPath(fromObject, [\r\n \"responseMimeType\"\r\n ]);\r\n if (fromResponseMimeType != null) {\r\n setValueByPath(toObject, [\"responseMimeType\"], fromResponseMimeType);\r\n }\r\n const fromResponseModalities = getValueByPath(fromObject, [\r\n \"responseModalities\"\r\n ]);\r\n if (fromResponseModalities != null) {\r\n setValueByPath(toObject, [\"responseModalities\"], fromResponseModalities);\r\n }\r\n const fromResponseSchema = getValueByPath(fromObject, [\r\n \"responseSchema\"\r\n ]);\r\n if (fromResponseSchema != null) {\r\n setValueByPath(toObject, [\"responseSchema\"], fromResponseSchema);\r\n }\r\n const fromRoutingConfig = getValueByPath(fromObject, [\r\n \"routingConfig\"\r\n ]);\r\n if (fromRoutingConfig != null) {\r\n setValueByPath(toObject, [\"routingConfig\"], fromRoutingConfig);\r\n }\r\n const fromSeed = getValueByPath(fromObject, [\"seed\"]);\r\n if (fromSeed != null) {\r\n setValueByPath(toObject, [\"seed\"], fromSeed);\r\n }\r\n const fromSpeechConfig = getValueByPath(fromObject, [\"speechConfig\"]);\r\n if (fromSpeechConfig != null) {\r\n setValueByPath(toObject, [\"speechConfig\"], speechConfigToVertex$1(fromSpeechConfig));\r\n }\r\n const fromStopSequences = getValueByPath(fromObject, [\r\n \"stopSequences\"\r\n ]);\r\n if (fromStopSequences != null) {\r\n setValueByPath(toObject, [\"stopSequences\"], fromStopSequences);\r\n }\r\n const fromTemperature = getValueByPath(fromObject, [\"temperature\"]);\r\n if (fromTemperature != null) {\r\n setValueByPath(toObject, [\"temperature\"], fromTemperature);\r\n }\r\n const fromThinkingConfig = getValueByPath(fromObject, [\r\n \"thinkingConfig\"\r\n ]);\r\n if (fromThinkingConfig != null) {\r\n setValueByPath(toObject, [\"thinkingConfig\"], fromThinkingConfig);\r\n }\r\n const fromTopK = getValueByPath(fromObject, [\"topK\"]);\r\n if (fromTopK != null) {\r\n setValueByPath(toObject, [\"topK\"], fromTopK);\r\n }\r\n const fromTopP = getValueByPath(fromObject, [\"topP\"]);\r\n if (fromTopP != null) {\r\n setValueByPath(toObject, [\"topP\"], fromTopP);\r\n }\r\n if (getValueByPath(fromObject, [\"enableEnhancedCivicAnswers\"]) !== void 0) {\r\n throw new Error(\"enableEnhancedCivicAnswers parameter is not supported in Vertex AI.\");\r\n }\r\n return toObject;\r\n}\r\nfunction googleMapsToMldev$2(fromObject) {\r\n const toObject = {};\r\n const fromAuthConfig = getValueByPath(fromObject, [\"authConfig\"]);\r\n if (fromAuthConfig != null) {\r\n setValueByPath(toObject, [\"authConfig\"], authConfigToMldev$2(fromAuthConfig));\r\n }\r\n const fromEnableWidget = getValueByPath(fromObject, [\"enableWidget\"]);\r\n if (fromEnableWidget != null) {\r\n setValueByPath(toObject, [\"enableWidget\"], fromEnableWidget);\r\n }\r\n return toObject;\r\n}\r\nfunction googleSearchToMldev$2(fromObject) {\r\n const toObject = {};\r\n const fromSearchTypes = getValueByPath(fromObject, [\"searchTypes\"]);\r\n if (fromSearchTypes != null) {\r\n setValueByPath(toObject, [\"searchTypes\"], fromSearchTypes);\r\n }\r\n if (getValueByPath(fromObject, [\"blockingConfidence\"]) !== void 0) {\r\n throw new Error(\"blockingConfidence parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"excludeDomains\"]) !== void 0) {\r\n throw new Error(\"excludeDomains parameter is not supported in Gemini API.\");\r\n }\r\n const fromTimeRangeFilter = getValueByPath(fromObject, [\r\n \"timeRangeFilter\"\r\n ]);\r\n if (fromTimeRangeFilter != null) {\r\n setValueByPath(toObject, [\"timeRangeFilter\"], fromTimeRangeFilter);\r\n }\r\n return toObject;\r\n}\r\nfunction liveConnectConfigToMldev$1(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromGenerationConfig = getValueByPath(fromObject, [\r\n \"generationConfig\"\r\n ]);\r\n if (parentObject !== void 0 && fromGenerationConfig != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\"], fromGenerationConfig);\r\n }\r\n const fromResponseModalities = getValueByPath(fromObject, [\r\n \"responseModalities\"\r\n ]);\r\n if (parentObject !== void 0 && fromResponseModalities != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"responseModalities\"], fromResponseModalities);\r\n }\r\n const fromTemperature = getValueByPath(fromObject, [\"temperature\"]);\r\n if (parentObject !== void 0 && fromTemperature != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"temperature\"], fromTemperature);\r\n }\r\n const fromTopP = getValueByPath(fromObject, [\"topP\"]);\r\n if (parentObject !== void 0 && fromTopP != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"topP\"], fromTopP);\r\n }\r\n const fromTopK = getValueByPath(fromObject, [\"topK\"]);\r\n if (parentObject !== void 0 && fromTopK != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"topK\"], fromTopK);\r\n }\r\n const fromMaxOutputTokens = getValueByPath(fromObject, [\r\n \"maxOutputTokens\"\r\n ]);\r\n if (parentObject !== void 0 && fromMaxOutputTokens != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"maxOutputTokens\"], fromMaxOutputTokens);\r\n }\r\n const fromMediaResolution = getValueByPath(fromObject, [\r\n \"mediaResolution\"\r\n ]);\r\n if (parentObject !== void 0 && fromMediaResolution != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"mediaResolution\"], fromMediaResolution);\r\n }\r\n const fromSeed = getValueByPath(fromObject, [\"seed\"]);\r\n if (parentObject !== void 0 && fromSeed != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"seed\"], fromSeed);\r\n }\r\n const fromSpeechConfig = getValueByPath(fromObject, [\"speechConfig\"]);\r\n if (parentObject !== void 0 && fromSpeechConfig != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"speechConfig\"], tLiveSpeechConfig(fromSpeechConfig));\r\n }\r\n const fromThinkingConfig = getValueByPath(fromObject, [\r\n \"thinkingConfig\"\r\n ]);\r\n if (parentObject !== void 0 && fromThinkingConfig != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"thinkingConfig\"], fromThinkingConfig);\r\n }\r\n const fromEnableAffectiveDialog = getValueByPath(fromObject, [\r\n \"enableAffectiveDialog\"\r\n ]);\r\n if (parentObject !== void 0 && fromEnableAffectiveDialog != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"enableAffectiveDialog\"], fromEnableAffectiveDialog);\r\n }\r\n const fromSystemInstruction = getValueByPath(fromObject, [\r\n \"systemInstruction\"\r\n ]);\r\n if (parentObject !== void 0 && fromSystemInstruction != null) {\r\n setValueByPath(parentObject, [\"setup\", \"systemInstruction\"], contentToMldev$2(tContent(fromSystemInstruction)));\r\n }\r\n const fromTools = getValueByPath(fromObject, [\"tools\"]);\r\n if (parentObject !== void 0 && fromTools != null) {\r\n let transformedList = tTools(fromTools);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return toolToMldev$2(tTool(item));\r\n });\r\n }\r\n setValueByPath(parentObject, [\"setup\", \"tools\"], transformedList);\r\n }\r\n const fromSessionResumption = getValueByPath(fromObject, [\r\n \"sessionResumption\"\r\n ]);\r\n if (parentObject !== void 0 && fromSessionResumption != null) {\r\n setValueByPath(parentObject, [\"setup\", \"sessionResumption\"], sessionResumptionConfigToMldev$1(fromSessionResumption));\r\n }\r\n const fromInputAudioTranscription = getValueByPath(fromObject, [\r\n \"inputAudioTranscription\"\r\n ]);\r\n if (parentObject !== void 0 && fromInputAudioTranscription != null) {\r\n setValueByPath(parentObject, [\"setup\", \"inputAudioTranscription\"], audioTranscriptionConfigToMldev$1(fromInputAudioTranscription));\r\n }\r\n const fromOutputAudioTranscription = getValueByPath(fromObject, [\r\n \"outputAudioTranscription\"\r\n ]);\r\n if (parentObject !== void 0 && fromOutputAudioTranscription != null) {\r\n setValueByPath(parentObject, [\"setup\", \"outputAudioTranscription\"], audioTranscriptionConfigToMldev$1(fromOutputAudioTranscription));\r\n }\r\n const fromRealtimeInputConfig = getValueByPath(fromObject, [\r\n \"realtimeInputConfig\"\r\n ]);\r\n if (parentObject !== void 0 && fromRealtimeInputConfig != null) {\r\n setValueByPath(parentObject, [\"setup\", \"realtimeInputConfig\"], fromRealtimeInputConfig);\r\n }\r\n const fromContextWindowCompression = getValueByPath(fromObject, [\r\n \"contextWindowCompression\"\r\n ]);\r\n if (parentObject !== void 0 && fromContextWindowCompression != null) {\r\n setValueByPath(parentObject, [\"setup\", \"contextWindowCompression\"], fromContextWindowCompression);\r\n }\r\n const fromProactivity = getValueByPath(fromObject, [\"proactivity\"]);\r\n if (parentObject !== void 0 && fromProactivity != null) {\r\n setValueByPath(parentObject, [\"setup\", \"proactivity\"], fromProactivity);\r\n }\r\n if (getValueByPath(fromObject, [\"explicitVadSignal\"]) !== void 0) {\r\n throw new Error(\"explicitVadSignal parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction liveConnectConfigToVertex(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromGenerationConfig = getValueByPath(fromObject, [\r\n \"generationConfig\"\r\n ]);\r\n if (parentObject !== void 0 && fromGenerationConfig != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\"], generationConfigToVertex$1(fromGenerationConfig));\r\n }\r\n const fromResponseModalities = getValueByPath(fromObject, [\r\n \"responseModalities\"\r\n ]);\r\n if (parentObject !== void 0 && fromResponseModalities != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"responseModalities\"], fromResponseModalities);\r\n }\r\n const fromTemperature = getValueByPath(fromObject, [\"temperature\"]);\r\n if (parentObject !== void 0 && fromTemperature != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"temperature\"], fromTemperature);\r\n }\r\n const fromTopP = getValueByPath(fromObject, [\"topP\"]);\r\n if (parentObject !== void 0 && fromTopP != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"topP\"], fromTopP);\r\n }\r\n const fromTopK = getValueByPath(fromObject, [\"topK\"]);\r\n if (parentObject !== void 0 && fromTopK != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"topK\"], fromTopK);\r\n }\r\n const fromMaxOutputTokens = getValueByPath(fromObject, [\r\n \"maxOutputTokens\"\r\n ]);\r\n if (parentObject !== void 0 && fromMaxOutputTokens != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"maxOutputTokens\"], fromMaxOutputTokens);\r\n }\r\n const fromMediaResolution = getValueByPath(fromObject, [\r\n \"mediaResolution\"\r\n ]);\r\n if (parentObject !== void 0 && fromMediaResolution != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"mediaResolution\"], fromMediaResolution);\r\n }\r\n const fromSeed = getValueByPath(fromObject, [\"seed\"]);\r\n if (parentObject !== void 0 && fromSeed != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"seed\"], fromSeed);\r\n }\r\n const fromSpeechConfig = getValueByPath(fromObject, [\"speechConfig\"]);\r\n if (parentObject !== void 0 && fromSpeechConfig != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"speechConfig\"], speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig)));\r\n }\r\n const fromThinkingConfig = getValueByPath(fromObject, [\r\n \"thinkingConfig\"\r\n ]);\r\n if (parentObject !== void 0 && fromThinkingConfig != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"thinkingConfig\"], fromThinkingConfig);\r\n }\r\n const fromEnableAffectiveDialog = getValueByPath(fromObject, [\r\n \"enableAffectiveDialog\"\r\n ]);\r\n if (parentObject !== void 0 && fromEnableAffectiveDialog != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"enableAffectiveDialog\"], fromEnableAffectiveDialog);\r\n }\r\n const fromSystemInstruction = getValueByPath(fromObject, [\r\n \"systemInstruction\"\r\n ]);\r\n if (parentObject !== void 0 && fromSystemInstruction != null) {\r\n setValueByPath(parentObject, [\"setup\", \"systemInstruction\"], contentToVertex$1(tContent(fromSystemInstruction)));\r\n }\r\n const fromTools = getValueByPath(fromObject, [\"tools\"]);\r\n if (parentObject !== void 0 && fromTools != null) {\r\n let transformedList = tTools(fromTools);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return toolToVertex$1(tTool(item));\r\n });\r\n }\r\n setValueByPath(parentObject, [\"setup\", \"tools\"], transformedList);\r\n }\r\n const fromSessionResumption = getValueByPath(fromObject, [\r\n \"sessionResumption\"\r\n ]);\r\n if (parentObject !== void 0 && fromSessionResumption != null) {\r\n setValueByPath(parentObject, [\"setup\", \"sessionResumption\"], fromSessionResumption);\r\n }\r\n const fromInputAudioTranscription = getValueByPath(fromObject, [\r\n \"inputAudioTranscription\"\r\n ]);\r\n if (parentObject !== void 0 && fromInputAudioTranscription != null) {\r\n setValueByPath(parentObject, [\"setup\", \"inputAudioTranscription\"], fromInputAudioTranscription);\r\n }\r\n const fromOutputAudioTranscription = getValueByPath(fromObject, [\r\n \"outputAudioTranscription\"\r\n ]);\r\n if (parentObject !== void 0 && fromOutputAudioTranscription != null) {\r\n setValueByPath(parentObject, [\"setup\", \"outputAudioTranscription\"], fromOutputAudioTranscription);\r\n }\r\n const fromRealtimeInputConfig = getValueByPath(fromObject, [\r\n \"realtimeInputConfig\"\r\n ]);\r\n if (parentObject !== void 0 && fromRealtimeInputConfig != null) {\r\n setValueByPath(parentObject, [\"setup\", \"realtimeInputConfig\"], fromRealtimeInputConfig);\r\n }\r\n const fromContextWindowCompression = getValueByPath(fromObject, [\r\n \"contextWindowCompression\"\r\n ]);\r\n if (parentObject !== void 0 && fromContextWindowCompression != null) {\r\n setValueByPath(parentObject, [\"setup\", \"contextWindowCompression\"], fromContextWindowCompression);\r\n }\r\n const fromProactivity = getValueByPath(fromObject, [\"proactivity\"]);\r\n if (parentObject !== void 0 && fromProactivity != null) {\r\n setValueByPath(parentObject, [\"setup\", \"proactivity\"], fromProactivity);\r\n }\r\n const fromExplicitVadSignal = getValueByPath(fromObject, [\r\n \"explicitVadSignal\"\r\n ]);\r\n if (parentObject !== void 0 && fromExplicitVadSignal != null) {\r\n setValueByPath(parentObject, [\"setup\", \"explicitVadSignal\"], fromExplicitVadSignal);\r\n }\r\n return toObject;\r\n}\r\nfunction liveConnectParametersToMldev(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"setup\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n setValueByPath(toObject, [\"config\"], liveConnectConfigToMldev$1(fromConfig, toObject));\r\n }\r\n return toObject;\r\n}\r\nfunction liveConnectParametersToVertex(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"setup\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n setValueByPath(toObject, [\"config\"], liveConnectConfigToVertex(fromConfig, toObject));\r\n }\r\n return toObject;\r\n}\r\nfunction liveMusicSetConfigParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromMusicGenerationConfig = getValueByPath(fromObject, [\r\n \"musicGenerationConfig\"\r\n ]);\r\n if (fromMusicGenerationConfig != null) {\r\n setValueByPath(toObject, [\"musicGenerationConfig\"], fromMusicGenerationConfig);\r\n }\r\n return toObject;\r\n}\r\nfunction liveMusicSetWeightedPromptsParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromWeightedPrompts = getValueByPath(fromObject, [\r\n \"weightedPrompts\"\r\n ]);\r\n if (fromWeightedPrompts != null) {\r\n let transformedList = fromWeightedPrompts;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"weightedPrompts\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction liveSendRealtimeInputParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromMedia = getValueByPath(fromObject, [\"media\"]);\r\n if (fromMedia != null) {\r\n let transformedList = tBlobs(fromMedia);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return blobToMldev$2(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"mediaChunks\"], transformedList);\r\n }\r\n const fromAudio = getValueByPath(fromObject, [\"audio\"]);\r\n if (fromAudio != null) {\r\n setValueByPath(toObject, [\"audio\"], blobToMldev$2(tAudioBlob(fromAudio)));\r\n }\r\n const fromAudioStreamEnd = getValueByPath(fromObject, [\r\n \"audioStreamEnd\"\r\n ]);\r\n if (fromAudioStreamEnd != null) {\r\n setValueByPath(toObject, [\"audioStreamEnd\"], fromAudioStreamEnd);\r\n }\r\n const fromVideo = getValueByPath(fromObject, [\"video\"]);\r\n if (fromVideo != null) {\r\n setValueByPath(toObject, [\"video\"], blobToMldev$2(tImageBlob(fromVideo)));\r\n }\r\n const fromText = getValueByPath(fromObject, [\"text\"]);\r\n if (fromText != null) {\r\n setValueByPath(toObject, [\"text\"], fromText);\r\n }\r\n const fromActivityStart = getValueByPath(fromObject, [\r\n \"activityStart\"\r\n ]);\r\n if (fromActivityStart != null) {\r\n setValueByPath(toObject, [\"activityStart\"], fromActivityStart);\r\n }\r\n const fromActivityEnd = getValueByPath(fromObject, [\"activityEnd\"]);\r\n if (fromActivityEnd != null) {\r\n setValueByPath(toObject, [\"activityEnd\"], fromActivityEnd);\r\n }\r\n return toObject;\r\n}\r\nfunction liveSendRealtimeInputParametersToVertex(fromObject) {\r\n const toObject = {};\r\n const fromMedia = getValueByPath(fromObject, [\"media\"]);\r\n if (fromMedia != null) {\r\n let transformedList = tBlobs(fromMedia);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"mediaChunks\"], transformedList);\r\n }\r\n const fromAudio = getValueByPath(fromObject, [\"audio\"]);\r\n if (fromAudio != null) {\r\n setValueByPath(toObject, [\"audio\"], tAudioBlob(fromAudio));\r\n }\r\n const fromAudioStreamEnd = getValueByPath(fromObject, [\r\n \"audioStreamEnd\"\r\n ]);\r\n if (fromAudioStreamEnd != null) {\r\n setValueByPath(toObject, [\"audioStreamEnd\"], fromAudioStreamEnd);\r\n }\r\n const fromVideo = getValueByPath(fromObject, [\"video\"]);\r\n if (fromVideo != null) {\r\n setValueByPath(toObject, [\"video\"], tImageBlob(fromVideo));\r\n }\r\n const fromText = getValueByPath(fromObject, [\"text\"]);\r\n if (fromText != null) {\r\n setValueByPath(toObject, [\"text\"], fromText);\r\n }\r\n const fromActivityStart = getValueByPath(fromObject, [\r\n \"activityStart\"\r\n ]);\r\n if (fromActivityStart != null) {\r\n setValueByPath(toObject, [\"activityStart\"], fromActivityStart);\r\n }\r\n const fromActivityEnd = getValueByPath(fromObject, [\"activityEnd\"]);\r\n if (fromActivityEnd != null) {\r\n setValueByPath(toObject, [\"activityEnd\"], fromActivityEnd);\r\n }\r\n return toObject;\r\n}\r\nfunction liveServerMessageFromVertex(fromObject) {\r\n const toObject = {};\r\n const fromSetupComplete = getValueByPath(fromObject, [\r\n \"setupComplete\"\r\n ]);\r\n if (fromSetupComplete != null) {\r\n setValueByPath(toObject, [\"setupComplete\"], fromSetupComplete);\r\n }\r\n const fromServerContent = getValueByPath(fromObject, [\r\n \"serverContent\"\r\n ]);\r\n if (fromServerContent != null) {\r\n setValueByPath(toObject, [\"serverContent\"], fromServerContent);\r\n }\r\n const fromToolCall = getValueByPath(fromObject, [\"toolCall\"]);\r\n if (fromToolCall != null) {\r\n setValueByPath(toObject, [\"toolCall\"], fromToolCall);\r\n }\r\n const fromToolCallCancellation = getValueByPath(fromObject, [\r\n \"toolCallCancellation\"\r\n ]);\r\n if (fromToolCallCancellation != null) {\r\n setValueByPath(toObject, [\"toolCallCancellation\"], fromToolCallCancellation);\r\n }\r\n const fromUsageMetadata = getValueByPath(fromObject, [\r\n \"usageMetadata\"\r\n ]);\r\n if (fromUsageMetadata != null) {\r\n setValueByPath(toObject, [\"usageMetadata\"], usageMetadataFromVertex(fromUsageMetadata));\r\n }\r\n const fromGoAway = getValueByPath(fromObject, [\"goAway\"]);\r\n if (fromGoAway != null) {\r\n setValueByPath(toObject, [\"goAway\"], fromGoAway);\r\n }\r\n const fromSessionResumptionUpdate = getValueByPath(fromObject, [\r\n \"sessionResumptionUpdate\"\r\n ]);\r\n if (fromSessionResumptionUpdate != null) {\r\n setValueByPath(toObject, [\"sessionResumptionUpdate\"], fromSessionResumptionUpdate);\r\n }\r\n const fromVoiceActivityDetectionSignal = getValueByPath(fromObject, [\r\n \"voiceActivityDetectionSignal\"\r\n ]);\r\n if (fromVoiceActivityDetectionSignal != null) {\r\n setValueByPath(toObject, [\"voiceActivityDetectionSignal\"], fromVoiceActivityDetectionSignal);\r\n }\r\n const fromVoiceActivity = getValueByPath(fromObject, [\r\n \"voiceActivity\"\r\n ]);\r\n if (fromVoiceActivity != null) {\r\n setValueByPath(toObject, [\"voiceActivity\"], voiceActivityFromVertex(fromVoiceActivity));\r\n }\r\n return toObject;\r\n}\r\nfunction multiSpeakerVoiceConfigToVertex$1(fromObject) {\r\n const toObject = {};\r\n const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [\r\n \"speakerVoiceConfigs\"\r\n ]);\r\n if (fromSpeakerVoiceConfigs != null) {\r\n let transformedList = fromSpeakerVoiceConfigs;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return speakerVoiceConfigToVertex$1(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"speakerVoiceConfigs\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction partToMldev$2(fromObject) {\r\n const toObject = {};\r\n const fromMediaResolution = getValueByPath(fromObject, [\r\n \"mediaResolution\"\r\n ]);\r\n if (fromMediaResolution != null) {\r\n setValueByPath(toObject, [\"mediaResolution\"], fromMediaResolution);\r\n }\r\n const fromCodeExecutionResult = getValueByPath(fromObject, [\r\n \"codeExecutionResult\"\r\n ]);\r\n if (fromCodeExecutionResult != null) {\r\n setValueByPath(toObject, [\"codeExecutionResult\"], fromCodeExecutionResult);\r\n }\r\n const fromExecutableCode = getValueByPath(fromObject, [\r\n \"executableCode\"\r\n ]);\r\n if (fromExecutableCode != null) {\r\n setValueByPath(toObject, [\"executableCode\"], fromExecutableCode);\r\n }\r\n const fromFileData = getValueByPath(fromObject, [\"fileData\"]);\r\n if (fromFileData != null) {\r\n setValueByPath(toObject, [\"fileData\"], fileDataToMldev$2(fromFileData));\r\n }\r\n const fromFunctionCall = getValueByPath(fromObject, [\"functionCall\"]);\r\n if (fromFunctionCall != null) {\r\n setValueByPath(toObject, [\"functionCall\"], functionCallToMldev$2(fromFunctionCall));\r\n }\r\n const fromFunctionResponse = getValueByPath(fromObject, [\r\n \"functionResponse\"\r\n ]);\r\n if (fromFunctionResponse != null) {\r\n setValueByPath(toObject, [\"functionResponse\"], fromFunctionResponse);\r\n }\r\n const fromInlineData = getValueByPath(fromObject, [\"inlineData\"]);\r\n if (fromInlineData != null) {\r\n setValueByPath(toObject, [\"inlineData\"], blobToMldev$2(fromInlineData));\r\n }\r\n const fromText = getValueByPath(fromObject, [\"text\"]);\r\n if (fromText != null) {\r\n setValueByPath(toObject, [\"text\"], fromText);\r\n }\r\n const fromThought = getValueByPath(fromObject, [\"thought\"]);\r\n if (fromThought != null) {\r\n setValueByPath(toObject, [\"thought\"], fromThought);\r\n }\r\n const fromThoughtSignature = getValueByPath(fromObject, [\r\n \"thoughtSignature\"\r\n ]);\r\n if (fromThoughtSignature != null) {\r\n setValueByPath(toObject, [\"thoughtSignature\"], fromThoughtSignature);\r\n }\r\n const fromVideoMetadata = getValueByPath(fromObject, [\r\n \"videoMetadata\"\r\n ]);\r\n if (fromVideoMetadata != null) {\r\n setValueByPath(toObject, [\"videoMetadata\"], fromVideoMetadata);\r\n }\r\n const fromToolCall = getValueByPath(fromObject, [\"toolCall\"]);\r\n if (fromToolCall != null) {\r\n setValueByPath(toObject, [\"toolCall\"], fromToolCall);\r\n }\r\n const fromToolResponse = getValueByPath(fromObject, [\"toolResponse\"]);\r\n if (fromToolResponse != null) {\r\n setValueByPath(toObject, [\"toolResponse\"], fromToolResponse);\r\n }\r\n const fromPartMetadata = getValueByPath(fromObject, [\"partMetadata\"]);\r\n if (fromPartMetadata != null) {\r\n setValueByPath(toObject, [\"partMetadata\"], fromPartMetadata);\r\n }\r\n return toObject;\r\n}\r\nfunction partToVertex$1(fromObject) {\r\n const toObject = {};\r\n const fromMediaResolution = getValueByPath(fromObject, [\r\n \"mediaResolution\"\r\n ]);\r\n if (fromMediaResolution != null) {\r\n setValueByPath(toObject, [\"mediaResolution\"], fromMediaResolution);\r\n }\r\n const fromCodeExecutionResult = getValueByPath(fromObject, [\r\n \"codeExecutionResult\"\r\n ]);\r\n if (fromCodeExecutionResult != null) {\r\n setValueByPath(toObject, [\"codeExecutionResult\"], fromCodeExecutionResult);\r\n }\r\n const fromExecutableCode = getValueByPath(fromObject, [\r\n \"executableCode\"\r\n ]);\r\n if (fromExecutableCode != null) {\r\n setValueByPath(toObject, [\"executableCode\"], fromExecutableCode);\r\n }\r\n const fromFileData = getValueByPath(fromObject, [\"fileData\"]);\r\n if (fromFileData != null) {\r\n setValueByPath(toObject, [\"fileData\"], fromFileData);\r\n }\r\n const fromFunctionCall = getValueByPath(fromObject, [\"functionCall\"]);\r\n if (fromFunctionCall != null) {\r\n setValueByPath(toObject, [\"functionCall\"], fromFunctionCall);\r\n }\r\n const fromFunctionResponse = getValueByPath(fromObject, [\r\n \"functionResponse\"\r\n ]);\r\n if (fromFunctionResponse != null) {\r\n setValueByPath(toObject, [\"functionResponse\"], fromFunctionResponse);\r\n }\r\n const fromInlineData = getValueByPath(fromObject, [\"inlineData\"]);\r\n if (fromInlineData != null) {\r\n setValueByPath(toObject, [\"inlineData\"], fromInlineData);\r\n }\r\n const fromText = getValueByPath(fromObject, [\"text\"]);\r\n if (fromText != null) {\r\n setValueByPath(toObject, [\"text\"], fromText);\r\n }\r\n const fromThought = getValueByPath(fromObject, [\"thought\"]);\r\n if (fromThought != null) {\r\n setValueByPath(toObject, [\"thought\"], fromThought);\r\n }\r\n const fromThoughtSignature = getValueByPath(fromObject, [\r\n \"thoughtSignature\"\r\n ]);\r\n if (fromThoughtSignature != null) {\r\n setValueByPath(toObject, [\"thoughtSignature\"], fromThoughtSignature);\r\n }\r\n const fromVideoMetadata = getValueByPath(fromObject, [\r\n \"videoMetadata\"\r\n ]);\r\n if (fromVideoMetadata != null) {\r\n setValueByPath(toObject, [\"videoMetadata\"], fromVideoMetadata);\r\n }\r\n if (getValueByPath(fromObject, [\"toolCall\"]) !== void 0) {\r\n throw new Error(\"toolCall parameter is not supported in Vertex AI.\");\r\n }\r\n if (getValueByPath(fromObject, [\"toolResponse\"]) !== void 0) {\r\n throw new Error(\"toolResponse parameter is not supported in Vertex AI.\");\r\n }\r\n if (getValueByPath(fromObject, [\"partMetadata\"]) !== void 0) {\r\n throw new Error(\"partMetadata parameter is not supported in Vertex AI.\");\r\n }\r\n return toObject;\r\n}\r\nfunction replicatedVoiceConfigToVertex$1(fromObject) {\r\n const toObject = {};\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n const fromVoiceSampleAudio = getValueByPath(fromObject, [\r\n \"voiceSampleAudio\"\r\n ]);\r\n if (fromVoiceSampleAudio != null) {\r\n setValueByPath(toObject, [\"voiceSampleAudio\"], fromVoiceSampleAudio);\r\n }\r\n return toObject;\r\n}\r\nfunction sessionResumptionConfigToMldev$1(fromObject) {\r\n const toObject = {};\r\n const fromHandle = getValueByPath(fromObject, [\"handle\"]);\r\n if (fromHandle != null) {\r\n setValueByPath(toObject, [\"handle\"], fromHandle);\r\n }\r\n if (getValueByPath(fromObject, [\"transparent\"]) !== void 0) {\r\n throw new Error(\"transparent parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction speakerVoiceConfigToVertex$1(fromObject) {\r\n const toObject = {};\r\n const fromSpeaker = getValueByPath(fromObject, [\"speaker\"]);\r\n if (fromSpeaker != null) {\r\n setValueByPath(toObject, [\"speaker\"], fromSpeaker);\r\n }\r\n const fromVoiceConfig = getValueByPath(fromObject, [\"voiceConfig\"]);\r\n if (fromVoiceConfig != null) {\r\n setValueByPath(toObject, [\"voiceConfig\"], voiceConfigToVertex$1(fromVoiceConfig));\r\n }\r\n return toObject;\r\n}\r\nfunction speechConfigToVertex$1(fromObject) {\r\n const toObject = {};\r\n const fromVoiceConfig = getValueByPath(fromObject, [\"voiceConfig\"]);\r\n if (fromVoiceConfig != null) {\r\n setValueByPath(toObject, [\"voiceConfig\"], voiceConfigToVertex$1(fromVoiceConfig));\r\n }\r\n const fromLanguageCode = getValueByPath(fromObject, [\"languageCode\"]);\r\n if (fromLanguageCode != null) {\r\n setValueByPath(toObject, [\"languageCode\"], fromLanguageCode);\r\n }\r\n const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [\r\n \"multiSpeakerVoiceConfig\"\r\n ]);\r\n if (fromMultiSpeakerVoiceConfig != null) {\r\n setValueByPath(toObject, [\"multiSpeakerVoiceConfig\"], multiSpeakerVoiceConfigToVertex$1(fromMultiSpeakerVoiceConfig));\r\n }\r\n return toObject;\r\n}\r\nfunction toolToMldev$2(fromObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"retrieval\"]) !== void 0) {\r\n throw new Error(\"retrieval parameter is not supported in Gemini API.\");\r\n }\r\n const fromComputerUse = getValueByPath(fromObject, [\"computerUse\"]);\r\n if (fromComputerUse != null) {\r\n setValueByPath(toObject, [\"computerUse\"], fromComputerUse);\r\n }\r\n const fromFileSearch = getValueByPath(fromObject, [\"fileSearch\"]);\r\n if (fromFileSearch != null) {\r\n setValueByPath(toObject, [\"fileSearch\"], fromFileSearch);\r\n }\r\n const fromGoogleSearch = getValueByPath(fromObject, [\"googleSearch\"]);\r\n if (fromGoogleSearch != null) {\r\n setValueByPath(toObject, [\"googleSearch\"], googleSearchToMldev$2(fromGoogleSearch));\r\n }\r\n const fromGoogleMaps = getValueByPath(fromObject, [\"googleMaps\"]);\r\n if (fromGoogleMaps != null) {\r\n setValueByPath(toObject, [\"googleMaps\"], googleMapsToMldev$2(fromGoogleMaps));\r\n }\r\n const fromCodeExecution = getValueByPath(fromObject, [\r\n \"codeExecution\"\r\n ]);\r\n if (fromCodeExecution != null) {\r\n setValueByPath(toObject, [\"codeExecution\"], fromCodeExecution);\r\n }\r\n if (getValueByPath(fromObject, [\"enterpriseWebSearch\"]) !== void 0) {\r\n throw new Error(\"enterpriseWebSearch parameter is not supported in Gemini API.\");\r\n }\r\n const fromFunctionDeclarations = getValueByPath(fromObject, [\r\n \"functionDeclarations\"\r\n ]);\r\n if (fromFunctionDeclarations != null) {\r\n let transformedList = fromFunctionDeclarations;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"functionDeclarations\"], transformedList);\r\n }\r\n const fromGoogleSearchRetrieval = getValueByPath(fromObject, [\r\n \"googleSearchRetrieval\"\r\n ]);\r\n if (fromGoogleSearchRetrieval != null) {\r\n setValueByPath(toObject, [\"googleSearchRetrieval\"], fromGoogleSearchRetrieval);\r\n }\r\n if (getValueByPath(fromObject, [\"parallelAiSearch\"]) !== void 0) {\r\n throw new Error(\"parallelAiSearch parameter is not supported in Gemini API.\");\r\n }\r\n const fromUrlContext = getValueByPath(fromObject, [\"urlContext\"]);\r\n if (fromUrlContext != null) {\r\n setValueByPath(toObject, [\"urlContext\"], fromUrlContext);\r\n }\r\n const fromMcpServers = getValueByPath(fromObject, [\"mcpServers\"]);\r\n if (fromMcpServers != null) {\r\n let transformedList = fromMcpServers;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"mcpServers\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction toolToVertex$1(fromObject) {\r\n const toObject = {};\r\n const fromRetrieval = getValueByPath(fromObject, [\"retrieval\"]);\r\n if (fromRetrieval != null) {\r\n setValueByPath(toObject, [\"retrieval\"], fromRetrieval);\r\n }\r\n const fromComputerUse = getValueByPath(fromObject, [\"computerUse\"]);\r\n if (fromComputerUse != null) {\r\n setValueByPath(toObject, [\"computerUse\"], fromComputerUse);\r\n }\r\n if (getValueByPath(fromObject, [\"fileSearch\"]) !== void 0) {\r\n throw new Error(\"fileSearch parameter is not supported in Vertex AI.\");\r\n }\r\n const fromGoogleSearch = getValueByPath(fromObject, [\"googleSearch\"]);\r\n if (fromGoogleSearch != null) {\r\n setValueByPath(toObject, [\"googleSearch\"], fromGoogleSearch);\r\n }\r\n const fromGoogleMaps = getValueByPath(fromObject, [\"googleMaps\"]);\r\n if (fromGoogleMaps != null) {\r\n setValueByPath(toObject, [\"googleMaps\"], fromGoogleMaps);\r\n }\r\n const fromCodeExecution = getValueByPath(fromObject, [\r\n \"codeExecution\"\r\n ]);\r\n if (fromCodeExecution != null) {\r\n setValueByPath(toObject, [\"codeExecution\"], fromCodeExecution);\r\n }\r\n const fromEnterpriseWebSearch = getValueByPath(fromObject, [\r\n \"enterpriseWebSearch\"\r\n ]);\r\n if (fromEnterpriseWebSearch != null) {\r\n setValueByPath(toObject, [\"enterpriseWebSearch\"], fromEnterpriseWebSearch);\r\n }\r\n const fromFunctionDeclarations = getValueByPath(fromObject, [\r\n \"functionDeclarations\"\r\n ]);\r\n if (fromFunctionDeclarations != null) {\r\n let transformedList = fromFunctionDeclarations;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return functionDeclarationToVertex$1(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"functionDeclarations\"], transformedList);\r\n }\r\n const fromGoogleSearchRetrieval = getValueByPath(fromObject, [\r\n \"googleSearchRetrieval\"\r\n ]);\r\n if (fromGoogleSearchRetrieval != null) {\r\n setValueByPath(toObject, [\"googleSearchRetrieval\"], fromGoogleSearchRetrieval);\r\n }\r\n const fromParallelAiSearch = getValueByPath(fromObject, [\r\n \"parallelAiSearch\"\r\n ]);\r\n if (fromParallelAiSearch != null) {\r\n setValueByPath(toObject, [\"parallelAiSearch\"], fromParallelAiSearch);\r\n }\r\n const fromUrlContext = getValueByPath(fromObject, [\"urlContext\"]);\r\n if (fromUrlContext != null) {\r\n setValueByPath(toObject, [\"urlContext\"], fromUrlContext);\r\n }\r\n if (getValueByPath(fromObject, [\"mcpServers\"]) !== void 0) {\r\n throw new Error(\"mcpServers parameter is not supported in Vertex AI.\");\r\n }\r\n return toObject;\r\n}\r\nfunction usageMetadataFromVertex(fromObject) {\r\n const toObject = {};\r\n const fromPromptTokenCount = getValueByPath(fromObject, [\r\n \"promptTokenCount\"\r\n ]);\r\n if (fromPromptTokenCount != null) {\r\n setValueByPath(toObject, [\"promptTokenCount\"], fromPromptTokenCount);\r\n }\r\n const fromCachedContentTokenCount = getValueByPath(fromObject, [\r\n \"cachedContentTokenCount\"\r\n ]);\r\n if (fromCachedContentTokenCount != null) {\r\n setValueByPath(toObject, [\"cachedContentTokenCount\"], fromCachedContentTokenCount);\r\n }\r\n const fromResponseTokenCount = getValueByPath(fromObject, [\r\n \"candidatesTokenCount\"\r\n ]);\r\n if (fromResponseTokenCount != null) {\r\n setValueByPath(toObject, [\"responseTokenCount\"], fromResponseTokenCount);\r\n }\r\n const fromToolUsePromptTokenCount = getValueByPath(fromObject, [\r\n \"toolUsePromptTokenCount\"\r\n ]);\r\n if (fromToolUsePromptTokenCount != null) {\r\n setValueByPath(toObject, [\"toolUsePromptTokenCount\"], fromToolUsePromptTokenCount);\r\n }\r\n const fromThoughtsTokenCount = getValueByPath(fromObject, [\r\n \"thoughtsTokenCount\"\r\n ]);\r\n if (fromThoughtsTokenCount != null) {\r\n setValueByPath(toObject, [\"thoughtsTokenCount\"], fromThoughtsTokenCount);\r\n }\r\n const fromTotalTokenCount = getValueByPath(fromObject, [\r\n \"totalTokenCount\"\r\n ]);\r\n if (fromTotalTokenCount != null) {\r\n setValueByPath(toObject, [\"totalTokenCount\"], fromTotalTokenCount);\r\n }\r\n const fromPromptTokensDetails = getValueByPath(fromObject, [\r\n \"promptTokensDetails\"\r\n ]);\r\n if (fromPromptTokensDetails != null) {\r\n let transformedList = fromPromptTokensDetails;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"promptTokensDetails\"], transformedList);\r\n }\r\n const fromCacheTokensDetails = getValueByPath(fromObject, [\r\n \"cacheTokensDetails\"\r\n ]);\r\n if (fromCacheTokensDetails != null) {\r\n let transformedList = fromCacheTokensDetails;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"cacheTokensDetails\"], transformedList);\r\n }\r\n const fromResponseTokensDetails = getValueByPath(fromObject, [\r\n \"candidatesTokensDetails\"\r\n ]);\r\n if (fromResponseTokensDetails != null) {\r\n let transformedList = fromResponseTokensDetails;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"responseTokensDetails\"], transformedList);\r\n }\r\n const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [\r\n \"toolUsePromptTokensDetails\"\r\n ]);\r\n if (fromToolUsePromptTokensDetails != null) {\r\n let transformedList = fromToolUsePromptTokensDetails;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"toolUsePromptTokensDetails\"], transformedList);\r\n }\r\n const fromTrafficType = getValueByPath(fromObject, [\"trafficType\"]);\r\n if (fromTrafficType != null) {\r\n setValueByPath(toObject, [\"trafficType\"], fromTrafficType);\r\n }\r\n return toObject;\r\n}\r\nfunction voiceActivityFromVertex(fromObject) {\r\n const toObject = {};\r\n const fromVoiceActivityType = getValueByPath(fromObject, [\"type\"]);\r\n if (fromVoiceActivityType != null) {\r\n setValueByPath(toObject, [\"voiceActivityType\"], fromVoiceActivityType);\r\n }\r\n return toObject;\r\n}\r\nfunction voiceConfigToVertex$1(fromObject) {\r\n const toObject = {};\r\n const fromReplicatedVoiceConfig = getValueByPath(fromObject, [\r\n \"replicatedVoiceConfig\"\r\n ]);\r\n if (fromReplicatedVoiceConfig != null) {\r\n setValueByPath(toObject, [\"replicatedVoiceConfig\"], replicatedVoiceConfigToVertex$1(fromReplicatedVoiceConfig));\r\n }\r\n const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [\r\n \"prebuiltVoiceConfig\"\r\n ]);\r\n if (fromPrebuiltVoiceConfig != null) {\r\n setValueByPath(toObject, [\"prebuiltVoiceConfig\"], fromPrebuiltVoiceConfig);\r\n }\r\n return toObject;\r\n}\r\nfunction authConfigToMldev$1(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromApiKey = getValueByPath(fromObject, [\"apiKey\"]);\r\n if (fromApiKey != null) {\r\n setValueByPath(toObject, [\"apiKey\"], fromApiKey);\r\n }\r\n if (getValueByPath(fromObject, [\"apiKeyConfig\"]) !== void 0) {\r\n throw new Error(\"apiKeyConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"authType\"]) !== void 0) {\r\n throw new Error(\"authType parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"googleServiceAccountConfig\"]) !== void 0) {\r\n throw new Error(\"googleServiceAccountConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"httpBasicAuthConfig\"]) !== void 0) {\r\n throw new Error(\"httpBasicAuthConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"oauthConfig\"]) !== void 0) {\r\n throw new Error(\"oauthConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"oidcConfig\"]) !== void 0) {\r\n throw new Error(\"oidcConfig parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction blobToMldev$1(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromData = getValueByPath(fromObject, [\"data\"]);\r\n if (fromData != null) {\r\n setValueByPath(toObject, [\"data\"], fromData);\r\n }\r\n if (getValueByPath(fromObject, [\"displayName\"]) !== void 0) {\r\n throw new Error(\"displayName parameter is not supported in Gemini API.\");\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction candidateFromMldev(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromContent = getValueByPath(fromObject, [\"content\"]);\r\n if (fromContent != null) {\r\n setValueByPath(toObject, [\"content\"], fromContent);\r\n }\r\n const fromCitationMetadata = getValueByPath(fromObject, [\r\n \"citationMetadata\"\r\n ]);\r\n if (fromCitationMetadata != null) {\r\n setValueByPath(toObject, [\"citationMetadata\"], citationMetadataFromMldev(fromCitationMetadata));\r\n }\r\n const fromTokenCount = getValueByPath(fromObject, [\"tokenCount\"]);\r\n if (fromTokenCount != null) {\r\n setValueByPath(toObject, [\"tokenCount\"], fromTokenCount);\r\n }\r\n const fromFinishReason = getValueByPath(fromObject, [\"finishReason\"]);\r\n if (fromFinishReason != null) {\r\n setValueByPath(toObject, [\"finishReason\"], fromFinishReason);\r\n }\r\n const fromGroundingMetadata = getValueByPath(fromObject, [\r\n \"groundingMetadata\"\r\n ]);\r\n if (fromGroundingMetadata != null) {\r\n setValueByPath(toObject, [\"groundingMetadata\"], fromGroundingMetadata);\r\n }\r\n const fromAvgLogprobs = getValueByPath(fromObject, [\"avgLogprobs\"]);\r\n if (fromAvgLogprobs != null) {\r\n setValueByPath(toObject, [\"avgLogprobs\"], fromAvgLogprobs);\r\n }\r\n const fromIndex = getValueByPath(fromObject, [\"index\"]);\r\n if (fromIndex != null) {\r\n setValueByPath(toObject, [\"index\"], fromIndex);\r\n }\r\n const fromLogprobsResult = getValueByPath(fromObject, [\r\n \"logprobsResult\"\r\n ]);\r\n if (fromLogprobsResult != null) {\r\n setValueByPath(toObject, [\"logprobsResult\"], fromLogprobsResult);\r\n }\r\n const fromSafetyRatings = getValueByPath(fromObject, [\r\n \"safetyRatings\"\r\n ]);\r\n if (fromSafetyRatings != null) {\r\n let transformedList = fromSafetyRatings;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"safetyRatings\"], transformedList);\r\n }\r\n const fromUrlContextMetadata = getValueByPath(fromObject, [\r\n \"urlContextMetadata\"\r\n ]);\r\n if (fromUrlContextMetadata != null) {\r\n setValueByPath(toObject, [\"urlContextMetadata\"], fromUrlContextMetadata);\r\n }\r\n return toObject;\r\n}\r\nfunction citationMetadataFromMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromCitations = getValueByPath(fromObject, [\"citationSources\"]);\r\n if (fromCitations != null) {\r\n let transformedList = fromCitations;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"citations\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction computeTokensParametersToVertex(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromContents = getValueByPath(fromObject, [\"contents\"]);\r\n if (fromContents != null) {\r\n let transformedList = tContents(fromContents);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return contentToVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"contents\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction computeTokensResponseFromVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromTokensInfo = getValueByPath(fromObject, [\"tokensInfo\"]);\r\n if (fromTokensInfo != null) {\r\n let transformedList = fromTokensInfo;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"tokensInfo\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction contentEmbeddingFromVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromValues = getValueByPath(fromObject, [\"values\"]);\r\n if (fromValues != null) {\r\n setValueByPath(toObject, [\"values\"], fromValues);\r\n }\r\n const fromStatistics = getValueByPath(fromObject, [\"statistics\"]);\r\n if (fromStatistics != null) {\r\n setValueByPath(toObject, [\"statistics\"], contentEmbeddingStatisticsFromVertex(fromStatistics));\r\n }\r\n return toObject;\r\n}\r\nfunction contentEmbeddingStatisticsFromVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromTruncated = getValueByPath(fromObject, [\"truncated\"]);\r\n if (fromTruncated != null) {\r\n setValueByPath(toObject, [\"truncated\"], fromTruncated);\r\n }\r\n const fromTokenCount = getValueByPath(fromObject, [\"token_count\"]);\r\n if (fromTokenCount != null) {\r\n setValueByPath(toObject, [\"tokenCount\"], fromTokenCount);\r\n }\r\n return toObject;\r\n}\r\nfunction contentToMldev$1(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromParts = getValueByPath(fromObject, [\"parts\"]);\r\n if (fromParts != null) {\r\n let transformedList = fromParts;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return partToMldev$1(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"parts\"], transformedList);\r\n }\r\n const fromRole = getValueByPath(fromObject, [\"role\"]);\r\n if (fromRole != null) {\r\n setValueByPath(toObject, [\"role\"], fromRole);\r\n }\r\n return toObject;\r\n}\r\nfunction contentToVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromParts = getValueByPath(fromObject, [\"parts\"]);\r\n if (fromParts != null) {\r\n let transformedList = fromParts;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return partToVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"parts\"], transformedList);\r\n }\r\n const fromRole = getValueByPath(fromObject, [\"role\"]);\r\n if (fromRole != null) {\r\n setValueByPath(toObject, [\"role\"], fromRole);\r\n }\r\n return toObject;\r\n}\r\nfunction controlReferenceConfigToVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromControlType = getValueByPath(fromObject, [\"controlType\"]);\r\n if (fromControlType != null) {\r\n setValueByPath(toObject, [\"controlType\"], fromControlType);\r\n }\r\n const fromEnableControlImageComputation = getValueByPath(fromObject, [\r\n \"enableControlImageComputation\"\r\n ]);\r\n if (fromEnableControlImageComputation != null) {\r\n setValueByPath(toObject, [\"computeControl\"], fromEnableControlImageComputation);\r\n }\r\n return toObject;\r\n}\r\nfunction countTokensConfigToMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"systemInstruction\"]) !== void 0) {\r\n throw new Error(\"systemInstruction parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"tools\"]) !== void 0) {\r\n throw new Error(\"tools parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"generationConfig\"]) !== void 0) {\r\n throw new Error(\"generationConfig parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction countTokensConfigToVertex(fromObject, parentObject, rootObject) {\r\n const toObject = {};\r\n const fromSystemInstruction = getValueByPath(fromObject, [\r\n \"systemInstruction\"\r\n ]);\r\n if (parentObject !== void 0 && fromSystemInstruction != null) {\r\n setValueByPath(parentObject, [\"systemInstruction\"], contentToVertex(tContent(fromSystemInstruction)));\r\n }\r\n const fromTools = getValueByPath(fromObject, [\"tools\"]);\r\n if (parentObject !== void 0 && fromTools != null) {\r\n let transformedList = fromTools;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return toolToVertex(item);\r\n });\r\n }\r\n setValueByPath(parentObject, [\"tools\"], transformedList);\r\n }\r\n const fromGenerationConfig = getValueByPath(fromObject, [\r\n \"generationConfig\"\r\n ]);\r\n if (parentObject !== void 0 && fromGenerationConfig != null) {\r\n setValueByPath(parentObject, [\"generationConfig\"], generationConfigToVertex(fromGenerationConfig));\r\n }\r\n return toObject;\r\n}\r\nfunction countTokensParametersToMldev(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromContents = getValueByPath(fromObject, [\"contents\"]);\r\n if (fromContents != null) {\r\n let transformedList = tContents(fromContents);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return contentToMldev$1(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"contents\"], transformedList);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n countTokensConfigToMldev(fromConfig);\r\n }\r\n return toObject;\r\n}\r\nfunction countTokensParametersToVertex(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromContents = getValueByPath(fromObject, [\"contents\"]);\r\n if (fromContents != null) {\r\n let transformedList = tContents(fromContents);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return contentToVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"contents\"], transformedList);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n countTokensConfigToVertex(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction countTokensResponseFromMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromTotalTokens = getValueByPath(fromObject, [\"totalTokens\"]);\r\n if (fromTotalTokens != null) {\r\n setValueByPath(toObject, [\"totalTokens\"], fromTotalTokens);\r\n }\r\n const fromCachedContentTokenCount = getValueByPath(fromObject, [\r\n \"cachedContentTokenCount\"\r\n ]);\r\n if (fromCachedContentTokenCount != null) {\r\n setValueByPath(toObject, [\"cachedContentTokenCount\"], fromCachedContentTokenCount);\r\n }\r\n return toObject;\r\n}\r\nfunction countTokensResponseFromVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromTotalTokens = getValueByPath(fromObject, [\"totalTokens\"]);\r\n if (fromTotalTokens != null) {\r\n setValueByPath(toObject, [\"totalTokens\"], fromTotalTokens);\r\n }\r\n return toObject;\r\n}\r\nfunction deleteModelParametersToMldev(apiClient, fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], tModel(apiClient, fromModel));\r\n }\r\n return toObject;\r\n}\r\nfunction deleteModelParametersToVertex(apiClient, fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], tModel(apiClient, fromModel));\r\n }\r\n return toObject;\r\n}\r\nfunction deleteModelResponseFromMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n return toObject;\r\n}\r\nfunction deleteModelResponseFromVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n return toObject;\r\n}\r\nfunction editImageConfigToVertex(fromObject, parentObject, _rootObject) {\r\n const toObject = {};\r\n const fromOutputGcsUri = getValueByPath(fromObject, [\"outputGcsUri\"]);\r\n if (parentObject !== void 0 && fromOutputGcsUri != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"storageUri\"], fromOutputGcsUri);\r\n }\r\n const fromNegativePrompt = getValueByPath(fromObject, [\r\n \"negativePrompt\"\r\n ]);\r\n if (parentObject !== void 0 && fromNegativePrompt != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"negativePrompt\"], fromNegativePrompt);\r\n }\r\n const fromNumberOfImages = getValueByPath(fromObject, [\r\n \"numberOfImages\"\r\n ]);\r\n if (parentObject !== void 0 && fromNumberOfImages != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"sampleCount\"], fromNumberOfImages);\r\n }\r\n const fromAspectRatio = getValueByPath(fromObject, [\"aspectRatio\"]);\r\n if (parentObject !== void 0 && fromAspectRatio != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"aspectRatio\"], fromAspectRatio);\r\n }\r\n const fromGuidanceScale = getValueByPath(fromObject, [\r\n \"guidanceScale\"\r\n ]);\r\n if (parentObject !== void 0 && fromGuidanceScale != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"guidanceScale\"], fromGuidanceScale);\r\n }\r\n const fromSeed = getValueByPath(fromObject, [\"seed\"]);\r\n if (parentObject !== void 0 && fromSeed != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"seed\"], fromSeed);\r\n }\r\n const fromSafetyFilterLevel = getValueByPath(fromObject, [\r\n \"safetyFilterLevel\"\r\n ]);\r\n if (parentObject !== void 0 && fromSafetyFilterLevel != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"safetySetting\"], fromSafetyFilterLevel);\r\n }\r\n const fromPersonGeneration = getValueByPath(fromObject, [\r\n \"personGeneration\"\r\n ]);\r\n if (parentObject !== void 0 && fromPersonGeneration != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"personGeneration\"], fromPersonGeneration);\r\n }\r\n const fromIncludeSafetyAttributes = getValueByPath(fromObject, [\r\n \"includeSafetyAttributes\"\r\n ]);\r\n if (parentObject !== void 0 && fromIncludeSafetyAttributes != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"includeSafetyAttributes\"], fromIncludeSafetyAttributes);\r\n }\r\n const fromIncludeRaiReason = getValueByPath(fromObject, [\r\n \"includeRaiReason\"\r\n ]);\r\n if (parentObject !== void 0 && fromIncludeRaiReason != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"includeRaiReason\"], fromIncludeRaiReason);\r\n }\r\n const fromLanguage = getValueByPath(fromObject, [\"language\"]);\r\n if (parentObject !== void 0 && fromLanguage != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"language\"], fromLanguage);\r\n }\r\n const fromOutputMimeType = getValueByPath(fromObject, [\r\n \"outputMimeType\"\r\n ]);\r\n if (parentObject !== void 0 && fromOutputMimeType != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"outputOptions\", \"mimeType\"], fromOutputMimeType);\r\n }\r\n const fromOutputCompressionQuality = getValueByPath(fromObject, [\r\n \"outputCompressionQuality\"\r\n ]);\r\n if (parentObject !== void 0 && fromOutputCompressionQuality != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"outputOptions\", \"compressionQuality\"], fromOutputCompressionQuality);\r\n }\r\n const fromAddWatermark = getValueByPath(fromObject, [\"addWatermark\"]);\r\n if (parentObject !== void 0 && fromAddWatermark != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"addWatermark\"], fromAddWatermark);\r\n }\r\n const fromLabels = getValueByPath(fromObject, [\"labels\"]);\r\n if (parentObject !== void 0 && fromLabels != null) {\r\n setValueByPath(parentObject, [\"labels\"], fromLabels);\r\n }\r\n const fromEditMode = getValueByPath(fromObject, [\"editMode\"]);\r\n if (parentObject !== void 0 && fromEditMode != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"editMode\"], fromEditMode);\r\n }\r\n const fromBaseSteps = getValueByPath(fromObject, [\"baseSteps\"]);\r\n if (parentObject !== void 0 && fromBaseSteps != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"editConfig\", \"baseSteps\"], fromBaseSteps);\r\n }\r\n return toObject;\r\n}\r\nfunction editImageParametersInternalToVertex(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromPrompt = getValueByPath(fromObject, [\"prompt\"]);\r\n if (fromPrompt != null) {\r\n setValueByPath(toObject, [\"instances[0]\", \"prompt\"], fromPrompt);\r\n }\r\n const fromReferenceImages = getValueByPath(fromObject, [\r\n \"referenceImages\"\r\n ]);\r\n if (fromReferenceImages != null) {\r\n let transformedList = fromReferenceImages;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return referenceImageAPIInternalToVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"instances[0]\", \"referenceImages\"], transformedList);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n editImageConfigToVertex(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction editImageResponseFromVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromGeneratedImages = getValueByPath(fromObject, [\r\n \"predictions\"\r\n ]);\r\n if (fromGeneratedImages != null) {\r\n let transformedList = fromGeneratedImages;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return generatedImageFromVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"generatedImages\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction embedContentConfigToMldev(fromObject, parentObject, _rootObject) {\r\n const toObject = {};\r\n const fromTaskType = getValueByPath(fromObject, [\"taskType\"]);\r\n if (parentObject !== void 0 && fromTaskType != null) {\r\n setValueByPath(parentObject, [\"requests[]\", \"taskType\"], fromTaskType);\r\n }\r\n const fromTitle = getValueByPath(fromObject, [\"title\"]);\r\n if (parentObject !== void 0 && fromTitle != null) {\r\n setValueByPath(parentObject, [\"requests[]\", \"title\"], fromTitle);\r\n }\r\n const fromOutputDimensionality = getValueByPath(fromObject, [\r\n \"outputDimensionality\"\r\n ]);\r\n if (parentObject !== void 0 && fromOutputDimensionality != null) {\r\n setValueByPath(parentObject, [\"requests[]\", \"outputDimensionality\"], fromOutputDimensionality);\r\n }\r\n if (getValueByPath(fromObject, [\"mimeType\"]) !== void 0) {\r\n throw new Error(\"mimeType parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"autoTruncate\"]) !== void 0) {\r\n throw new Error(\"autoTruncate parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction embedContentConfigToVertex(fromObject, parentObject, rootObject) {\r\n const toObject = {};\r\n let discriminatorTaskType = getValueByPath(rootObject, [\r\n \"embeddingApiType\"\r\n ]);\r\n if (discriminatorTaskType === void 0) {\r\n discriminatorTaskType = \"PREDICT\";\r\n }\r\n if (discriminatorTaskType === \"PREDICT\") {\r\n const fromTaskType = getValueByPath(fromObject, [\"taskType\"]);\r\n if (parentObject !== void 0 && fromTaskType != null) {\r\n setValueByPath(parentObject, [\"instances[]\", \"task_type\"], fromTaskType);\r\n }\r\n } else if (discriminatorTaskType === \"EMBED_CONTENT\") {\r\n const fromTaskType = getValueByPath(fromObject, [\"taskType\"]);\r\n if (parentObject !== void 0 && fromTaskType != null) {\r\n setValueByPath(parentObject, [\"taskType\"], fromTaskType);\r\n }\r\n }\r\n let discriminatorTitle = getValueByPath(rootObject, [\r\n \"embeddingApiType\"\r\n ]);\r\n if (discriminatorTitle === void 0) {\r\n discriminatorTitle = \"PREDICT\";\r\n }\r\n if (discriminatorTitle === \"PREDICT\") {\r\n const fromTitle = getValueByPath(fromObject, [\"title\"]);\r\n if (parentObject !== void 0 && fromTitle != null) {\r\n setValueByPath(parentObject, [\"instances[]\", \"title\"], fromTitle);\r\n }\r\n } else if (discriminatorTitle === \"EMBED_CONTENT\") {\r\n const fromTitle = getValueByPath(fromObject, [\"title\"]);\r\n if (parentObject !== void 0 && fromTitle != null) {\r\n setValueByPath(parentObject, [\"title\"], fromTitle);\r\n }\r\n }\r\n let discriminatorOutputDimensionality = getValueByPath(rootObject, [\r\n \"embeddingApiType\"\r\n ]);\r\n if (discriminatorOutputDimensionality === void 0) {\r\n discriminatorOutputDimensionality = \"PREDICT\";\r\n }\r\n if (discriminatorOutputDimensionality === \"PREDICT\") {\r\n const fromOutputDimensionality = getValueByPath(fromObject, [\r\n \"outputDimensionality\"\r\n ]);\r\n if (parentObject !== void 0 && fromOutputDimensionality != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"outputDimensionality\"], fromOutputDimensionality);\r\n }\r\n } else if (discriminatorOutputDimensionality === \"EMBED_CONTENT\") {\r\n const fromOutputDimensionality = getValueByPath(fromObject, [\r\n \"outputDimensionality\"\r\n ]);\r\n if (parentObject !== void 0 && fromOutputDimensionality != null) {\r\n setValueByPath(parentObject, [\"outputDimensionality\"], fromOutputDimensionality);\r\n }\r\n }\r\n let discriminatorMimeType = getValueByPath(rootObject, [\r\n \"embeddingApiType\"\r\n ]);\r\n if (discriminatorMimeType === void 0) {\r\n discriminatorMimeType = \"PREDICT\";\r\n }\r\n if (discriminatorMimeType === \"PREDICT\") {\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (parentObject !== void 0 && fromMimeType != null) {\r\n setValueByPath(parentObject, [\"instances[]\", \"mimeType\"], fromMimeType);\r\n }\r\n }\r\n let discriminatorAutoTruncate = getValueByPath(rootObject, [\r\n \"embeddingApiType\"\r\n ]);\r\n if (discriminatorAutoTruncate === void 0) {\r\n discriminatorAutoTruncate = \"PREDICT\";\r\n }\r\n if (discriminatorAutoTruncate === \"PREDICT\") {\r\n const fromAutoTruncate = getValueByPath(fromObject, [\r\n \"autoTruncate\"\r\n ]);\r\n if (parentObject !== void 0 && fromAutoTruncate != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"autoTruncate\"], fromAutoTruncate);\r\n }\r\n } else if (discriminatorAutoTruncate === \"EMBED_CONTENT\") {\r\n const fromAutoTruncate = getValueByPath(fromObject, [\r\n \"autoTruncate\"\r\n ]);\r\n if (parentObject !== void 0 && fromAutoTruncate != null) {\r\n setValueByPath(parentObject, [\"autoTruncate\"], fromAutoTruncate);\r\n }\r\n }\r\n return toObject;\r\n}\r\nfunction embedContentParametersPrivateToMldev(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromContents = getValueByPath(fromObject, [\"contents\"]);\r\n if (fromContents != null) {\r\n let transformedList = tContentsForEmbed(apiClient, fromContents);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"requests[]\", \"content\"], transformedList);\r\n }\r\n const fromContent = getValueByPath(fromObject, [\"content\"]);\r\n if (fromContent != null) {\r\n contentToMldev$1(tContent(fromContent));\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n embedContentConfigToMldev(fromConfig, toObject);\r\n }\r\n const fromModelForEmbedContent = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModelForEmbedContent !== void 0) {\r\n setValueByPath(toObject, [\"requests[]\", \"model\"], tModel(apiClient, fromModelForEmbedContent));\r\n }\r\n return toObject;\r\n}\r\nfunction embedContentParametersPrivateToVertex(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n let discriminatorContents = getValueByPath(rootObject, [\r\n \"embeddingApiType\"\r\n ]);\r\n if (discriminatorContents === void 0) {\r\n discriminatorContents = \"PREDICT\";\r\n }\r\n if (discriminatorContents === \"PREDICT\") {\r\n const fromContents = getValueByPath(fromObject, [\"contents\"]);\r\n if (fromContents != null) {\r\n let transformedList = tContentsForEmbed(apiClient, fromContents);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"instances[]\", \"content\"], transformedList);\r\n }\r\n }\r\n let discriminatorContent = getValueByPath(rootObject, [\r\n \"embeddingApiType\"\r\n ]);\r\n if (discriminatorContent === void 0) {\r\n discriminatorContent = \"PREDICT\";\r\n }\r\n if (discriminatorContent === \"EMBED_CONTENT\") {\r\n const fromContent = getValueByPath(fromObject, [\"content\"]);\r\n if (fromContent != null) {\r\n setValueByPath(toObject, [\"content\"], contentToVertex(tContent(fromContent)));\r\n }\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n embedContentConfigToVertex(fromConfig, toObject, rootObject);\r\n }\r\n return toObject;\r\n}\r\nfunction embedContentResponseFromMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromEmbeddings = getValueByPath(fromObject, [\"embeddings\"]);\r\n if (fromEmbeddings != null) {\r\n let transformedList = fromEmbeddings;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"embeddings\"], transformedList);\r\n }\r\n const fromMetadata = getValueByPath(fromObject, [\"metadata\"]);\r\n if (fromMetadata != null) {\r\n setValueByPath(toObject, [\"metadata\"], fromMetadata);\r\n }\r\n return toObject;\r\n}\r\nfunction embedContentResponseFromVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromEmbeddings = getValueByPath(fromObject, [\r\n \"predictions[]\",\r\n \"embeddings\"\r\n ]);\r\n if (fromEmbeddings != null) {\r\n let transformedList = fromEmbeddings;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return contentEmbeddingFromVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"embeddings\"], transformedList);\r\n }\r\n const fromMetadata = getValueByPath(fromObject, [\"metadata\"]);\r\n if (fromMetadata != null) {\r\n setValueByPath(toObject, [\"metadata\"], fromMetadata);\r\n }\r\n if (rootObject && getValueByPath(rootObject, [\"embeddingApiType\"]) === \"EMBED_CONTENT\") {\r\n const embedding = getValueByPath(fromObject, [\"embedding\"]);\r\n const usageMetadata = getValueByPath(fromObject, [\"usageMetadata\"]);\r\n const truncated = getValueByPath(fromObject, [\"truncated\"]);\r\n if (embedding) {\r\n const stats = {};\r\n if (usageMetadata && usageMetadata[\"promptTokenCount\"]) {\r\n stats.tokenCount = usageMetadata[\"promptTokenCount\"];\r\n }\r\n if (truncated) {\r\n stats.truncated = truncated;\r\n }\r\n embedding.statistics = stats;\r\n setValueByPath(toObject, [\"embeddings\"], [embedding]);\r\n }\r\n }\r\n return toObject;\r\n}\r\nfunction endpointFromVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"endpoint\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromDeployedModelId = getValueByPath(fromObject, [\r\n \"deployedModelId\"\r\n ]);\r\n if (fromDeployedModelId != null) {\r\n setValueByPath(toObject, [\"deployedModelId\"], fromDeployedModelId);\r\n }\r\n return toObject;\r\n}\r\nfunction fileDataToMldev$1(fromObject, _rootObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"displayName\"]) !== void 0) {\r\n throw new Error(\"displayName parameter is not supported in Gemini API.\");\r\n }\r\n const fromFileUri = getValueByPath(fromObject, [\"fileUri\"]);\r\n if (fromFileUri != null) {\r\n setValueByPath(toObject, [\"fileUri\"], fromFileUri);\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction functionCallToMldev$1(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromId = getValueByPath(fromObject, [\"id\"]);\r\n if (fromId != null) {\r\n setValueByPath(toObject, [\"id\"], fromId);\r\n }\r\n const fromArgs = getValueByPath(fromObject, [\"args\"]);\r\n if (fromArgs != null) {\r\n setValueByPath(toObject, [\"args\"], fromArgs);\r\n }\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n if (getValueByPath(fromObject, [\"partialArgs\"]) !== void 0) {\r\n throw new Error(\"partialArgs parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"willContinue\"]) !== void 0) {\r\n throw new Error(\"willContinue parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction functionCallingConfigToMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromAllowedFunctionNames = getValueByPath(fromObject, [\r\n \"allowedFunctionNames\"\r\n ]);\r\n if (fromAllowedFunctionNames != null) {\r\n setValueByPath(toObject, [\"allowedFunctionNames\"], fromAllowedFunctionNames);\r\n }\r\n const fromMode = getValueByPath(fromObject, [\"mode\"]);\r\n if (fromMode != null) {\r\n setValueByPath(toObject, [\"mode\"], fromMode);\r\n }\r\n if (getValueByPath(fromObject, [\"streamFunctionCallArguments\"]) !== void 0) {\r\n throw new Error(\"streamFunctionCallArguments parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction functionDeclarationToVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromDescription = getValueByPath(fromObject, [\"description\"]);\r\n if (fromDescription != null) {\r\n setValueByPath(toObject, [\"description\"], fromDescription);\r\n }\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromParameters = getValueByPath(fromObject, [\"parameters\"]);\r\n if (fromParameters != null) {\r\n setValueByPath(toObject, [\"parameters\"], fromParameters);\r\n }\r\n const fromParametersJsonSchema = getValueByPath(fromObject, [\r\n \"parametersJsonSchema\"\r\n ]);\r\n if (fromParametersJsonSchema != null) {\r\n setValueByPath(toObject, [\"parametersJsonSchema\"], fromParametersJsonSchema);\r\n }\r\n const fromResponse = getValueByPath(fromObject, [\"response\"]);\r\n if (fromResponse != null) {\r\n setValueByPath(toObject, [\"response\"], fromResponse);\r\n }\r\n const fromResponseJsonSchema = getValueByPath(fromObject, [\r\n \"responseJsonSchema\"\r\n ]);\r\n if (fromResponseJsonSchema != null) {\r\n setValueByPath(toObject, [\"responseJsonSchema\"], fromResponseJsonSchema);\r\n }\r\n if (getValueByPath(fromObject, [\"behavior\"]) !== void 0) {\r\n throw new Error(\"behavior parameter is not supported in Vertex AI.\");\r\n }\r\n return toObject;\r\n}\r\nfunction generateContentConfigToMldev(apiClient, fromObject, parentObject, rootObject) {\r\n const toObject = {};\r\n const fromSystemInstruction = getValueByPath(fromObject, [\r\n \"systemInstruction\"\r\n ]);\r\n if (parentObject !== void 0 && fromSystemInstruction != null) {\r\n setValueByPath(parentObject, [\"systemInstruction\"], contentToMldev$1(tContent(fromSystemInstruction)));\r\n }\r\n const fromTemperature = getValueByPath(fromObject, [\"temperature\"]);\r\n if (fromTemperature != null) {\r\n setValueByPath(toObject, [\"temperature\"], fromTemperature);\r\n }\r\n const fromTopP = getValueByPath(fromObject, [\"topP\"]);\r\n if (fromTopP != null) {\r\n setValueByPath(toObject, [\"topP\"], fromTopP);\r\n }\r\n const fromTopK = getValueByPath(fromObject, [\"topK\"]);\r\n if (fromTopK != null) {\r\n setValueByPath(toObject, [\"topK\"], fromTopK);\r\n }\r\n const fromCandidateCount = getValueByPath(fromObject, [\r\n \"candidateCount\"\r\n ]);\r\n if (fromCandidateCount != null) {\r\n setValueByPath(toObject, [\"candidateCount\"], fromCandidateCount);\r\n }\r\n const fromMaxOutputTokens = getValueByPath(fromObject, [\r\n \"maxOutputTokens\"\r\n ]);\r\n if (fromMaxOutputTokens != null) {\r\n setValueByPath(toObject, [\"maxOutputTokens\"], fromMaxOutputTokens);\r\n }\r\n const fromStopSequences = getValueByPath(fromObject, [\r\n \"stopSequences\"\r\n ]);\r\n if (fromStopSequences != null) {\r\n setValueByPath(toObject, [\"stopSequences\"], fromStopSequences);\r\n }\r\n const fromResponseLogprobs = getValueByPath(fromObject, [\r\n \"responseLogprobs\"\r\n ]);\r\n if (fromResponseLogprobs != null) {\r\n setValueByPath(toObject, [\"responseLogprobs\"], fromResponseLogprobs);\r\n }\r\n const fromLogprobs = getValueByPath(fromObject, [\"logprobs\"]);\r\n if (fromLogprobs != null) {\r\n setValueByPath(toObject, [\"logprobs\"], fromLogprobs);\r\n }\r\n const fromPresencePenalty = getValueByPath(fromObject, [\r\n \"presencePenalty\"\r\n ]);\r\n if (fromPresencePenalty != null) {\r\n setValueByPath(toObject, [\"presencePenalty\"], fromPresencePenalty);\r\n }\r\n const fromFrequencyPenalty = getValueByPath(fromObject, [\r\n \"frequencyPenalty\"\r\n ]);\r\n if (fromFrequencyPenalty != null) {\r\n setValueByPath(toObject, [\"frequencyPenalty\"], fromFrequencyPenalty);\r\n }\r\n const fromSeed = getValueByPath(fromObject, [\"seed\"]);\r\n if (fromSeed != null) {\r\n setValueByPath(toObject, [\"seed\"], fromSeed);\r\n }\r\n const fromResponseMimeType = getValueByPath(fromObject, [\r\n \"responseMimeType\"\r\n ]);\r\n if (fromResponseMimeType != null) {\r\n setValueByPath(toObject, [\"responseMimeType\"], fromResponseMimeType);\r\n }\r\n const fromResponseSchema = getValueByPath(fromObject, [\r\n \"responseSchema\"\r\n ]);\r\n if (fromResponseSchema != null) {\r\n setValueByPath(toObject, [\"responseSchema\"], tSchema(fromResponseSchema));\r\n }\r\n const fromResponseJsonSchema = getValueByPath(fromObject, [\r\n \"responseJsonSchema\"\r\n ]);\r\n if (fromResponseJsonSchema != null) {\r\n setValueByPath(toObject, [\"responseJsonSchema\"], fromResponseJsonSchema);\r\n }\r\n if (getValueByPath(fromObject, [\"routingConfig\"]) !== void 0) {\r\n throw new Error(\"routingConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"modelSelectionConfig\"]) !== void 0) {\r\n throw new Error(\"modelSelectionConfig parameter is not supported in Gemini API.\");\r\n }\r\n const fromSafetySettings = getValueByPath(fromObject, [\r\n \"safetySettings\"\r\n ]);\r\n if (parentObject !== void 0 && fromSafetySettings != null) {\r\n let transformedList = fromSafetySettings;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return safetySettingToMldev(item);\r\n });\r\n }\r\n setValueByPath(parentObject, [\"safetySettings\"], transformedList);\r\n }\r\n const fromTools = getValueByPath(fromObject, [\"tools\"]);\r\n if (parentObject !== void 0 && fromTools != null) {\r\n let transformedList = tTools(fromTools);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return toolToMldev$1(tTool(item));\r\n });\r\n }\r\n setValueByPath(parentObject, [\"tools\"], transformedList);\r\n }\r\n const fromToolConfig = getValueByPath(fromObject, [\"toolConfig\"]);\r\n if (parentObject !== void 0 && fromToolConfig != null) {\r\n setValueByPath(parentObject, [\"toolConfig\"], toolConfigToMldev(fromToolConfig));\r\n }\r\n if (getValueByPath(fromObject, [\"labels\"]) !== void 0) {\r\n throw new Error(\"labels parameter is not supported in Gemini API.\");\r\n }\r\n const fromCachedContent = getValueByPath(fromObject, [\r\n \"cachedContent\"\r\n ]);\r\n if (parentObject !== void 0 && fromCachedContent != null) {\r\n setValueByPath(parentObject, [\"cachedContent\"], tCachedContentName(apiClient, fromCachedContent));\r\n }\r\n const fromResponseModalities = getValueByPath(fromObject, [\r\n \"responseModalities\"\r\n ]);\r\n if (fromResponseModalities != null) {\r\n setValueByPath(toObject, [\"responseModalities\"], fromResponseModalities);\r\n }\r\n const fromMediaResolution = getValueByPath(fromObject, [\r\n \"mediaResolution\"\r\n ]);\r\n if (fromMediaResolution != null) {\r\n setValueByPath(toObject, [\"mediaResolution\"], fromMediaResolution);\r\n }\r\n const fromSpeechConfig = getValueByPath(fromObject, [\"speechConfig\"]);\r\n if (fromSpeechConfig != null) {\r\n setValueByPath(toObject, [\"speechConfig\"], tSpeechConfig(fromSpeechConfig));\r\n }\r\n if (getValueByPath(fromObject, [\"audioTimestamp\"]) !== void 0) {\r\n throw new Error(\"audioTimestamp parameter is not supported in Gemini API.\");\r\n }\r\n const fromThinkingConfig = getValueByPath(fromObject, [\r\n \"thinkingConfig\"\r\n ]);\r\n if (fromThinkingConfig != null) {\r\n setValueByPath(toObject, [\"thinkingConfig\"], fromThinkingConfig);\r\n }\r\n const fromImageConfig = getValueByPath(fromObject, [\"imageConfig\"]);\r\n if (fromImageConfig != null) {\r\n setValueByPath(toObject, [\"imageConfig\"], imageConfigToMldev(fromImageConfig));\r\n }\r\n const fromEnableEnhancedCivicAnswers = getValueByPath(fromObject, [\r\n \"enableEnhancedCivicAnswers\"\r\n ]);\r\n if (fromEnableEnhancedCivicAnswers != null) {\r\n setValueByPath(toObject, [\"enableEnhancedCivicAnswers\"], fromEnableEnhancedCivicAnswers);\r\n }\r\n if (getValueByPath(fromObject, [\"modelArmorConfig\"]) !== void 0) {\r\n throw new Error(\"modelArmorConfig parameter is not supported in Gemini API.\");\r\n }\r\n const fromServiceTier = getValueByPath(fromObject, [\"serviceTier\"]);\r\n if (parentObject !== void 0 && fromServiceTier != null) {\r\n setValueByPath(parentObject, [\"serviceTier\"], fromServiceTier);\r\n }\r\n return toObject;\r\n}\r\nfunction generateContentConfigToVertex(apiClient, fromObject, parentObject, rootObject) {\r\n const toObject = {};\r\n const fromSystemInstruction = getValueByPath(fromObject, [\r\n \"systemInstruction\"\r\n ]);\r\n if (parentObject !== void 0 && fromSystemInstruction != null) {\r\n setValueByPath(parentObject, [\"systemInstruction\"], contentToVertex(tContent(fromSystemInstruction)));\r\n }\r\n const fromTemperature = getValueByPath(fromObject, [\"temperature\"]);\r\n if (fromTemperature != null) {\r\n setValueByPath(toObject, [\"temperature\"], fromTemperature);\r\n }\r\n const fromTopP = getValueByPath(fromObject, [\"topP\"]);\r\n if (fromTopP != null) {\r\n setValueByPath(toObject, [\"topP\"], fromTopP);\r\n }\r\n const fromTopK = getValueByPath(fromObject, [\"topK\"]);\r\n if (fromTopK != null) {\r\n setValueByPath(toObject, [\"topK\"], fromTopK);\r\n }\r\n const fromCandidateCount = getValueByPath(fromObject, [\r\n \"candidateCount\"\r\n ]);\r\n if (fromCandidateCount != null) {\r\n setValueByPath(toObject, [\"candidateCount\"], fromCandidateCount);\r\n }\r\n const fromMaxOutputTokens = getValueByPath(fromObject, [\r\n \"maxOutputTokens\"\r\n ]);\r\n if (fromMaxOutputTokens != null) {\r\n setValueByPath(toObject, [\"maxOutputTokens\"], fromMaxOutputTokens);\r\n }\r\n const fromStopSequences = getValueByPath(fromObject, [\r\n \"stopSequences\"\r\n ]);\r\n if (fromStopSequences != null) {\r\n setValueByPath(toObject, [\"stopSequences\"], fromStopSequences);\r\n }\r\n const fromResponseLogprobs = getValueByPath(fromObject, [\r\n \"responseLogprobs\"\r\n ]);\r\n if (fromResponseLogprobs != null) {\r\n setValueByPath(toObject, [\"responseLogprobs\"], fromResponseLogprobs);\r\n }\r\n const fromLogprobs = getValueByPath(fromObject, [\"logprobs\"]);\r\n if (fromLogprobs != null) {\r\n setValueByPath(toObject, [\"logprobs\"], fromLogprobs);\r\n }\r\n const fromPresencePenalty = getValueByPath(fromObject, [\r\n \"presencePenalty\"\r\n ]);\r\n if (fromPresencePenalty != null) {\r\n setValueByPath(toObject, [\"presencePenalty\"], fromPresencePenalty);\r\n }\r\n const fromFrequencyPenalty = getValueByPath(fromObject, [\r\n \"frequencyPenalty\"\r\n ]);\r\n if (fromFrequencyPenalty != null) {\r\n setValueByPath(toObject, [\"frequencyPenalty\"], fromFrequencyPenalty);\r\n }\r\n const fromSeed = getValueByPath(fromObject, [\"seed\"]);\r\n if (fromSeed != null) {\r\n setValueByPath(toObject, [\"seed\"], fromSeed);\r\n }\r\n const fromResponseMimeType = getValueByPath(fromObject, [\r\n \"responseMimeType\"\r\n ]);\r\n if (fromResponseMimeType != null) {\r\n setValueByPath(toObject, [\"responseMimeType\"], fromResponseMimeType);\r\n }\r\n const fromResponseSchema = getValueByPath(fromObject, [\r\n \"responseSchema\"\r\n ]);\r\n if (fromResponseSchema != null) {\r\n setValueByPath(toObject, [\"responseSchema\"], tSchema(fromResponseSchema));\r\n }\r\n const fromResponseJsonSchema = getValueByPath(fromObject, [\r\n \"responseJsonSchema\"\r\n ]);\r\n if (fromResponseJsonSchema != null) {\r\n setValueByPath(toObject, [\"responseJsonSchema\"], fromResponseJsonSchema);\r\n }\r\n const fromRoutingConfig = getValueByPath(fromObject, [\r\n \"routingConfig\"\r\n ]);\r\n if (fromRoutingConfig != null) {\r\n setValueByPath(toObject, [\"routingConfig\"], fromRoutingConfig);\r\n }\r\n const fromModelSelectionConfig = getValueByPath(fromObject, [\r\n \"modelSelectionConfig\"\r\n ]);\r\n if (fromModelSelectionConfig != null) {\r\n setValueByPath(toObject, [\"modelConfig\"], fromModelSelectionConfig);\r\n }\r\n const fromSafetySettings = getValueByPath(fromObject, [\r\n \"safetySettings\"\r\n ]);\r\n if (parentObject !== void 0 && fromSafetySettings != null) {\r\n let transformedList = fromSafetySettings;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(parentObject, [\"safetySettings\"], transformedList);\r\n }\r\n const fromTools = getValueByPath(fromObject, [\"tools\"]);\r\n if (parentObject !== void 0 && fromTools != null) {\r\n let transformedList = tTools(fromTools);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return toolToVertex(tTool(item));\r\n });\r\n }\r\n setValueByPath(parentObject, [\"tools\"], transformedList);\r\n }\r\n const fromToolConfig = getValueByPath(fromObject, [\"toolConfig\"]);\r\n if (parentObject !== void 0 && fromToolConfig != null) {\r\n setValueByPath(parentObject, [\"toolConfig\"], toolConfigToVertex(fromToolConfig));\r\n }\r\n const fromLabels = getValueByPath(fromObject, [\"labels\"]);\r\n if (parentObject !== void 0 && fromLabels != null) {\r\n setValueByPath(parentObject, [\"labels\"], fromLabels);\r\n }\r\n const fromCachedContent = getValueByPath(fromObject, [\r\n \"cachedContent\"\r\n ]);\r\n if (parentObject !== void 0 && fromCachedContent != null) {\r\n setValueByPath(parentObject, [\"cachedContent\"], tCachedContentName(apiClient, fromCachedContent));\r\n }\r\n const fromResponseModalities = getValueByPath(fromObject, [\r\n \"responseModalities\"\r\n ]);\r\n if (fromResponseModalities != null) {\r\n setValueByPath(toObject, [\"responseModalities\"], fromResponseModalities);\r\n }\r\n const fromMediaResolution = getValueByPath(fromObject, [\r\n \"mediaResolution\"\r\n ]);\r\n if (fromMediaResolution != null) {\r\n setValueByPath(toObject, [\"mediaResolution\"], fromMediaResolution);\r\n }\r\n const fromSpeechConfig = getValueByPath(fromObject, [\"speechConfig\"]);\r\n if (fromSpeechConfig != null) {\r\n setValueByPath(toObject, [\"speechConfig\"], speechConfigToVertex(tSpeechConfig(fromSpeechConfig)));\r\n }\r\n const fromAudioTimestamp = getValueByPath(fromObject, [\r\n \"audioTimestamp\"\r\n ]);\r\n if (fromAudioTimestamp != null) {\r\n setValueByPath(toObject, [\"audioTimestamp\"], fromAudioTimestamp);\r\n }\r\n const fromThinkingConfig = getValueByPath(fromObject, [\r\n \"thinkingConfig\"\r\n ]);\r\n if (fromThinkingConfig != null) {\r\n setValueByPath(toObject, [\"thinkingConfig\"], fromThinkingConfig);\r\n }\r\n const fromImageConfig = getValueByPath(fromObject, [\"imageConfig\"]);\r\n if (fromImageConfig != null) {\r\n setValueByPath(toObject, [\"imageConfig\"], imageConfigToVertex(fromImageConfig));\r\n }\r\n if (getValueByPath(fromObject, [\"enableEnhancedCivicAnswers\"]) !== void 0) {\r\n throw new Error(\"enableEnhancedCivicAnswers parameter is not supported in Vertex AI.\");\r\n }\r\n const fromModelArmorConfig = getValueByPath(fromObject, [\r\n \"modelArmorConfig\"\r\n ]);\r\n if (parentObject !== void 0 && fromModelArmorConfig != null) {\r\n setValueByPath(parentObject, [\"modelArmorConfig\"], fromModelArmorConfig);\r\n }\r\n const fromServiceTier = getValueByPath(fromObject, [\"serviceTier\"]);\r\n if (parentObject !== void 0 && fromServiceTier != null) {\r\n setValueByPath(parentObject, [\"serviceTier\"], fromServiceTier);\r\n }\r\n return toObject;\r\n}\r\nfunction generateContentParametersToMldev(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromContents = getValueByPath(fromObject, [\"contents\"]);\r\n if (fromContents != null) {\r\n let transformedList = tContents(fromContents);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return contentToMldev$1(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"contents\"], transformedList);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n setValueByPath(toObject, [\"generationConfig\"], generateContentConfigToMldev(apiClient, fromConfig, toObject));\r\n }\r\n return toObject;\r\n}\r\nfunction generateContentParametersToVertex(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromContents = getValueByPath(fromObject, [\"contents\"]);\r\n if (fromContents != null) {\r\n let transformedList = tContents(fromContents);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return contentToVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"contents\"], transformedList);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n setValueByPath(toObject, [\"generationConfig\"], generateContentConfigToVertex(apiClient, fromConfig, toObject));\r\n }\r\n return toObject;\r\n}\r\nfunction generateContentResponseFromMldev(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromCandidates = getValueByPath(fromObject, [\"candidates\"]);\r\n if (fromCandidates != null) {\r\n let transformedList = fromCandidates;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return candidateFromMldev(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"candidates\"], transformedList);\r\n }\r\n const fromModelVersion = getValueByPath(fromObject, [\"modelVersion\"]);\r\n if (fromModelVersion != null) {\r\n setValueByPath(toObject, [\"modelVersion\"], fromModelVersion);\r\n }\r\n const fromPromptFeedback = getValueByPath(fromObject, [\r\n \"promptFeedback\"\r\n ]);\r\n if (fromPromptFeedback != null) {\r\n setValueByPath(toObject, [\"promptFeedback\"], fromPromptFeedback);\r\n }\r\n const fromResponseId = getValueByPath(fromObject, [\"responseId\"]);\r\n if (fromResponseId != null) {\r\n setValueByPath(toObject, [\"responseId\"], fromResponseId);\r\n }\r\n const fromUsageMetadata = getValueByPath(fromObject, [\r\n \"usageMetadata\"\r\n ]);\r\n if (fromUsageMetadata != null) {\r\n setValueByPath(toObject, [\"usageMetadata\"], fromUsageMetadata);\r\n }\r\n const fromModelStatus = getValueByPath(fromObject, [\"modelStatus\"]);\r\n if (fromModelStatus != null) {\r\n setValueByPath(toObject, [\"modelStatus\"], fromModelStatus);\r\n }\r\n return toObject;\r\n}\r\nfunction generateContentResponseFromVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromCandidates = getValueByPath(fromObject, [\"candidates\"]);\r\n if (fromCandidates != null) {\r\n let transformedList = fromCandidates;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"candidates\"], transformedList);\r\n }\r\n const fromCreateTime = getValueByPath(fromObject, [\"createTime\"]);\r\n if (fromCreateTime != null) {\r\n setValueByPath(toObject, [\"createTime\"], fromCreateTime);\r\n }\r\n const fromModelVersion = getValueByPath(fromObject, [\"modelVersion\"]);\r\n if (fromModelVersion != null) {\r\n setValueByPath(toObject, [\"modelVersion\"], fromModelVersion);\r\n }\r\n const fromPromptFeedback = getValueByPath(fromObject, [\r\n \"promptFeedback\"\r\n ]);\r\n if (fromPromptFeedback != null) {\r\n setValueByPath(toObject, [\"promptFeedback\"], fromPromptFeedback);\r\n }\r\n const fromResponseId = getValueByPath(fromObject, [\"responseId\"]);\r\n if (fromResponseId != null) {\r\n setValueByPath(toObject, [\"responseId\"], fromResponseId);\r\n }\r\n const fromUsageMetadata = getValueByPath(fromObject, [\r\n \"usageMetadata\"\r\n ]);\r\n if (fromUsageMetadata != null) {\r\n setValueByPath(toObject, [\"usageMetadata\"], fromUsageMetadata);\r\n }\r\n return toObject;\r\n}\r\nfunction generateImagesConfigToMldev(fromObject, parentObject, _rootObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"outputGcsUri\"]) !== void 0) {\r\n throw new Error(\"outputGcsUri parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"negativePrompt\"]) !== void 0) {\r\n throw new Error(\"negativePrompt parameter is not supported in Gemini API.\");\r\n }\r\n const fromNumberOfImages = getValueByPath(fromObject, [\r\n \"numberOfImages\"\r\n ]);\r\n if (parentObject !== void 0 && fromNumberOfImages != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"sampleCount\"], fromNumberOfImages);\r\n }\r\n const fromAspectRatio = getValueByPath(fromObject, [\"aspectRatio\"]);\r\n if (parentObject !== void 0 && fromAspectRatio != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"aspectRatio\"], fromAspectRatio);\r\n }\r\n const fromGuidanceScale = getValueByPath(fromObject, [\r\n \"guidanceScale\"\r\n ]);\r\n if (parentObject !== void 0 && fromGuidanceScale != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"guidanceScale\"], fromGuidanceScale);\r\n }\r\n if (getValueByPath(fromObject, [\"seed\"]) !== void 0) {\r\n throw new Error(\"seed parameter is not supported in Gemini API.\");\r\n }\r\n const fromSafetyFilterLevel = getValueByPath(fromObject, [\r\n \"safetyFilterLevel\"\r\n ]);\r\n if (parentObject !== void 0 && fromSafetyFilterLevel != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"safetySetting\"], fromSafetyFilterLevel);\r\n }\r\n const fromPersonGeneration = getValueByPath(fromObject, [\r\n \"personGeneration\"\r\n ]);\r\n if (parentObject !== void 0 && fromPersonGeneration != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"personGeneration\"], fromPersonGeneration);\r\n }\r\n const fromIncludeSafetyAttributes = getValueByPath(fromObject, [\r\n \"includeSafetyAttributes\"\r\n ]);\r\n if (parentObject !== void 0 && fromIncludeSafetyAttributes != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"includeSafetyAttributes\"], fromIncludeSafetyAttributes);\r\n }\r\n const fromIncludeRaiReason = getValueByPath(fromObject, [\r\n \"includeRaiReason\"\r\n ]);\r\n if (parentObject !== void 0 && fromIncludeRaiReason != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"includeRaiReason\"], fromIncludeRaiReason);\r\n }\r\n const fromLanguage = getValueByPath(fromObject, [\"language\"]);\r\n if (parentObject !== void 0 && fromLanguage != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"language\"], fromLanguage);\r\n }\r\n const fromOutputMimeType = getValueByPath(fromObject, [\r\n \"outputMimeType\"\r\n ]);\r\n if (parentObject !== void 0 && fromOutputMimeType != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"outputOptions\", \"mimeType\"], fromOutputMimeType);\r\n }\r\n const fromOutputCompressionQuality = getValueByPath(fromObject, [\r\n \"outputCompressionQuality\"\r\n ]);\r\n if (parentObject !== void 0 && fromOutputCompressionQuality != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"outputOptions\", \"compressionQuality\"], fromOutputCompressionQuality);\r\n }\r\n if (getValueByPath(fromObject, [\"addWatermark\"]) !== void 0) {\r\n throw new Error(\"addWatermark parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"labels\"]) !== void 0) {\r\n throw new Error(\"labels parameter is not supported in Gemini API.\");\r\n }\r\n const fromImageSize = getValueByPath(fromObject, [\"imageSize\"]);\r\n if (parentObject !== void 0 && fromImageSize != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"sampleImageSize\"], fromImageSize);\r\n }\r\n if (getValueByPath(fromObject, [\"enhancePrompt\"]) !== void 0) {\r\n throw new Error(\"enhancePrompt parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction generateImagesConfigToVertex(fromObject, parentObject, _rootObject) {\r\n const toObject = {};\r\n const fromOutputGcsUri = getValueByPath(fromObject, [\"outputGcsUri\"]);\r\n if (parentObject !== void 0 && fromOutputGcsUri != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"storageUri\"], fromOutputGcsUri);\r\n }\r\n const fromNegativePrompt = getValueByPath(fromObject, [\r\n \"negativePrompt\"\r\n ]);\r\n if (parentObject !== void 0 && fromNegativePrompt != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"negativePrompt\"], fromNegativePrompt);\r\n }\r\n const fromNumberOfImages = getValueByPath(fromObject, [\r\n \"numberOfImages\"\r\n ]);\r\n if (parentObject !== void 0 && fromNumberOfImages != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"sampleCount\"], fromNumberOfImages);\r\n }\r\n const fromAspectRatio = getValueByPath(fromObject, [\"aspectRatio\"]);\r\n if (parentObject !== void 0 && fromAspectRatio != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"aspectRatio\"], fromAspectRatio);\r\n }\r\n const fromGuidanceScale = getValueByPath(fromObject, [\r\n \"guidanceScale\"\r\n ]);\r\n if (parentObject !== void 0 && fromGuidanceScale != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"guidanceScale\"], fromGuidanceScale);\r\n }\r\n const fromSeed = getValueByPath(fromObject, [\"seed\"]);\r\n if (parentObject !== void 0 && fromSeed != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"seed\"], fromSeed);\r\n }\r\n const fromSafetyFilterLevel = getValueByPath(fromObject, [\r\n \"safetyFilterLevel\"\r\n ]);\r\n if (parentObject !== void 0 && fromSafetyFilterLevel != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"safetySetting\"], fromSafetyFilterLevel);\r\n }\r\n const fromPersonGeneration = getValueByPath(fromObject, [\r\n \"personGeneration\"\r\n ]);\r\n if (parentObject !== void 0 && fromPersonGeneration != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"personGeneration\"], fromPersonGeneration);\r\n }\r\n const fromIncludeSafetyAttributes = getValueByPath(fromObject, [\r\n \"includeSafetyAttributes\"\r\n ]);\r\n if (parentObject !== void 0 && fromIncludeSafetyAttributes != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"includeSafetyAttributes\"], fromIncludeSafetyAttributes);\r\n }\r\n const fromIncludeRaiReason = getValueByPath(fromObject, [\r\n \"includeRaiReason\"\r\n ]);\r\n if (parentObject !== void 0 && fromIncludeRaiReason != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"includeRaiReason\"], fromIncludeRaiReason);\r\n }\r\n const fromLanguage = getValueByPath(fromObject, [\"language\"]);\r\n if (parentObject !== void 0 && fromLanguage != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"language\"], fromLanguage);\r\n }\r\n const fromOutputMimeType = getValueByPath(fromObject, [\r\n \"outputMimeType\"\r\n ]);\r\n if (parentObject !== void 0 && fromOutputMimeType != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"outputOptions\", \"mimeType\"], fromOutputMimeType);\r\n }\r\n const fromOutputCompressionQuality = getValueByPath(fromObject, [\r\n \"outputCompressionQuality\"\r\n ]);\r\n if (parentObject !== void 0 && fromOutputCompressionQuality != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"outputOptions\", \"compressionQuality\"], fromOutputCompressionQuality);\r\n }\r\n const fromAddWatermark = getValueByPath(fromObject, [\"addWatermark\"]);\r\n if (parentObject !== void 0 && fromAddWatermark != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"addWatermark\"], fromAddWatermark);\r\n }\r\n const fromLabels = getValueByPath(fromObject, [\"labels\"]);\r\n if (parentObject !== void 0 && fromLabels != null) {\r\n setValueByPath(parentObject, [\"labels\"], fromLabels);\r\n }\r\n const fromImageSize = getValueByPath(fromObject, [\"imageSize\"]);\r\n if (parentObject !== void 0 && fromImageSize != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"sampleImageSize\"], fromImageSize);\r\n }\r\n const fromEnhancePrompt = getValueByPath(fromObject, [\r\n \"enhancePrompt\"\r\n ]);\r\n if (parentObject !== void 0 && fromEnhancePrompt != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"enhancePrompt\"], fromEnhancePrompt);\r\n }\r\n return toObject;\r\n}\r\nfunction generateImagesParametersToMldev(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromPrompt = getValueByPath(fromObject, [\"prompt\"]);\r\n if (fromPrompt != null) {\r\n setValueByPath(toObject, [\"instances[0]\", \"prompt\"], fromPrompt);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n generateImagesConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction generateImagesParametersToVertex(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromPrompt = getValueByPath(fromObject, [\"prompt\"]);\r\n if (fromPrompt != null) {\r\n setValueByPath(toObject, [\"instances[0]\", \"prompt\"], fromPrompt);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n generateImagesConfigToVertex(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction generateImagesResponseFromMldev(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromGeneratedImages = getValueByPath(fromObject, [\r\n \"predictions\"\r\n ]);\r\n if (fromGeneratedImages != null) {\r\n let transformedList = fromGeneratedImages;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return generatedImageFromMldev(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"generatedImages\"], transformedList);\r\n }\r\n const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [\r\n \"positivePromptSafetyAttributes\"\r\n ]);\r\n if (fromPositivePromptSafetyAttributes != null) {\r\n setValueByPath(toObject, [\"positivePromptSafetyAttributes\"], safetyAttributesFromMldev(fromPositivePromptSafetyAttributes));\r\n }\r\n return toObject;\r\n}\r\nfunction generateImagesResponseFromVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromGeneratedImages = getValueByPath(fromObject, [\r\n \"predictions\"\r\n ]);\r\n if (fromGeneratedImages != null) {\r\n let transformedList = fromGeneratedImages;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return generatedImageFromVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"generatedImages\"], transformedList);\r\n }\r\n const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [\r\n \"positivePromptSafetyAttributes\"\r\n ]);\r\n if (fromPositivePromptSafetyAttributes != null) {\r\n setValueByPath(toObject, [\"positivePromptSafetyAttributes\"], safetyAttributesFromVertex(fromPositivePromptSafetyAttributes));\r\n }\r\n return toObject;\r\n}\r\nfunction generateVideosConfigToMldev(fromObject, parentObject, rootObject) {\r\n const toObject = {};\r\n const fromNumberOfVideos = getValueByPath(fromObject, [\r\n \"numberOfVideos\"\r\n ]);\r\n if (parentObject !== void 0 && fromNumberOfVideos != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"sampleCount\"], fromNumberOfVideos);\r\n }\r\n if (getValueByPath(fromObject, [\"outputGcsUri\"]) !== void 0) {\r\n throw new Error(\"outputGcsUri parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"fps\"]) !== void 0) {\r\n throw new Error(\"fps parameter is not supported in Gemini API.\");\r\n }\r\n const fromDurationSeconds = getValueByPath(fromObject, [\r\n \"durationSeconds\"\r\n ]);\r\n if (parentObject !== void 0 && fromDurationSeconds != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"durationSeconds\"], fromDurationSeconds);\r\n }\r\n if (getValueByPath(fromObject, [\"seed\"]) !== void 0) {\r\n throw new Error(\"seed parameter is not supported in Gemini API.\");\r\n }\r\n const fromAspectRatio = getValueByPath(fromObject, [\"aspectRatio\"]);\r\n if (parentObject !== void 0 && fromAspectRatio != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"aspectRatio\"], fromAspectRatio);\r\n }\r\n const fromResolution = getValueByPath(fromObject, [\"resolution\"]);\r\n if (parentObject !== void 0 && fromResolution != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"resolution\"], fromResolution);\r\n }\r\n const fromPersonGeneration = getValueByPath(fromObject, [\r\n \"personGeneration\"\r\n ]);\r\n if (parentObject !== void 0 && fromPersonGeneration != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"personGeneration\"], fromPersonGeneration);\r\n }\r\n if (getValueByPath(fromObject, [\"pubsubTopic\"]) !== void 0) {\r\n throw new Error(\"pubsubTopic parameter is not supported in Gemini API.\");\r\n }\r\n const fromNegativePrompt = getValueByPath(fromObject, [\r\n \"negativePrompt\"\r\n ]);\r\n if (parentObject !== void 0 && fromNegativePrompt != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"negativePrompt\"], fromNegativePrompt);\r\n }\r\n const fromEnhancePrompt = getValueByPath(fromObject, [\r\n \"enhancePrompt\"\r\n ]);\r\n if (parentObject !== void 0 && fromEnhancePrompt != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"enhancePrompt\"], fromEnhancePrompt);\r\n }\r\n if (getValueByPath(fromObject, [\"generateAudio\"]) !== void 0) {\r\n throw new Error(\"generateAudio parameter is not supported in Gemini API.\");\r\n }\r\n const fromLastFrame = getValueByPath(fromObject, [\"lastFrame\"]);\r\n if (parentObject !== void 0 && fromLastFrame != null) {\r\n setValueByPath(parentObject, [\"instances[0]\", \"lastFrame\"], imageToMldev(fromLastFrame));\r\n }\r\n const fromReferenceImages = getValueByPath(fromObject, [\r\n \"referenceImages\"\r\n ]);\r\n if (parentObject !== void 0 && fromReferenceImages != null) {\r\n let transformedList = fromReferenceImages;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return videoGenerationReferenceImageToMldev(item);\r\n });\r\n }\r\n setValueByPath(parentObject, [\"instances[0]\", \"referenceImages\"], transformedList);\r\n }\r\n if (getValueByPath(fromObject, [\"mask\"]) !== void 0) {\r\n throw new Error(\"mask parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"compressionQuality\"]) !== void 0) {\r\n throw new Error(\"compressionQuality parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"labels\"]) !== void 0) {\r\n throw new Error(\"labels parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction generateVideosConfigToVertex(fromObject, parentObject, rootObject) {\r\n const toObject = {};\r\n const fromNumberOfVideos = getValueByPath(fromObject, [\r\n \"numberOfVideos\"\r\n ]);\r\n if (parentObject !== void 0 && fromNumberOfVideos != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"sampleCount\"], fromNumberOfVideos);\r\n }\r\n const fromOutputGcsUri = getValueByPath(fromObject, [\"outputGcsUri\"]);\r\n if (parentObject !== void 0 && fromOutputGcsUri != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"storageUri\"], fromOutputGcsUri);\r\n }\r\n const fromFps = getValueByPath(fromObject, [\"fps\"]);\r\n if (parentObject !== void 0 && fromFps != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"fps\"], fromFps);\r\n }\r\n const fromDurationSeconds = getValueByPath(fromObject, [\r\n \"durationSeconds\"\r\n ]);\r\n if (parentObject !== void 0 && fromDurationSeconds != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"durationSeconds\"], fromDurationSeconds);\r\n }\r\n const fromSeed = getValueByPath(fromObject, [\"seed\"]);\r\n if (parentObject !== void 0 && fromSeed != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"seed\"], fromSeed);\r\n }\r\n const fromAspectRatio = getValueByPath(fromObject, [\"aspectRatio\"]);\r\n if (parentObject !== void 0 && fromAspectRatio != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"aspectRatio\"], fromAspectRatio);\r\n }\r\n const fromResolution = getValueByPath(fromObject, [\"resolution\"]);\r\n if (parentObject !== void 0 && fromResolution != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"resolution\"], fromResolution);\r\n }\r\n const fromPersonGeneration = getValueByPath(fromObject, [\r\n \"personGeneration\"\r\n ]);\r\n if (parentObject !== void 0 && fromPersonGeneration != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"personGeneration\"], fromPersonGeneration);\r\n }\r\n const fromPubsubTopic = getValueByPath(fromObject, [\"pubsubTopic\"]);\r\n if (parentObject !== void 0 && fromPubsubTopic != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"pubsubTopic\"], fromPubsubTopic);\r\n }\r\n const fromNegativePrompt = getValueByPath(fromObject, [\r\n \"negativePrompt\"\r\n ]);\r\n if (parentObject !== void 0 && fromNegativePrompt != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"negativePrompt\"], fromNegativePrompt);\r\n }\r\n const fromEnhancePrompt = getValueByPath(fromObject, [\r\n \"enhancePrompt\"\r\n ]);\r\n if (parentObject !== void 0 && fromEnhancePrompt != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"enhancePrompt\"], fromEnhancePrompt);\r\n }\r\n const fromGenerateAudio = getValueByPath(fromObject, [\r\n \"generateAudio\"\r\n ]);\r\n if (parentObject !== void 0 && fromGenerateAudio != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"generateAudio\"], fromGenerateAudio);\r\n }\r\n const fromLastFrame = getValueByPath(fromObject, [\"lastFrame\"]);\r\n if (parentObject !== void 0 && fromLastFrame != null) {\r\n setValueByPath(parentObject, [\"instances[0]\", \"lastFrame\"], imageToVertex(fromLastFrame));\r\n }\r\n const fromReferenceImages = getValueByPath(fromObject, [\r\n \"referenceImages\"\r\n ]);\r\n if (parentObject !== void 0 && fromReferenceImages != null) {\r\n let transformedList = fromReferenceImages;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return videoGenerationReferenceImageToVertex(item);\r\n });\r\n }\r\n setValueByPath(parentObject, [\"instances[0]\", \"referenceImages\"], transformedList);\r\n }\r\n const fromMask = getValueByPath(fromObject, [\"mask\"]);\r\n if (parentObject !== void 0 && fromMask != null) {\r\n setValueByPath(parentObject, [\"instances[0]\", \"mask\"], videoGenerationMaskToVertex(fromMask));\r\n }\r\n const fromCompressionQuality = getValueByPath(fromObject, [\r\n \"compressionQuality\"\r\n ]);\r\n if (parentObject !== void 0 && fromCompressionQuality != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"compressionQuality\"], fromCompressionQuality);\r\n }\r\n const fromLabels = getValueByPath(fromObject, [\"labels\"]);\r\n if (parentObject !== void 0 && fromLabels != null) {\r\n setValueByPath(parentObject, [\"labels\"], fromLabels);\r\n }\r\n return toObject;\r\n}\r\nfunction generateVideosOperationFromMldev(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromMetadata = getValueByPath(fromObject, [\"metadata\"]);\r\n if (fromMetadata != null) {\r\n setValueByPath(toObject, [\"metadata\"], fromMetadata);\r\n }\r\n const fromDone = getValueByPath(fromObject, [\"done\"]);\r\n if (fromDone != null) {\r\n setValueByPath(toObject, [\"done\"], fromDone);\r\n }\r\n const fromError = getValueByPath(fromObject, [\"error\"]);\r\n if (fromError != null) {\r\n setValueByPath(toObject, [\"error\"], fromError);\r\n }\r\n const fromResponse = getValueByPath(fromObject, [\r\n \"response\",\r\n \"generateVideoResponse\"\r\n ]);\r\n if (fromResponse != null) {\r\n setValueByPath(toObject, [\"response\"], generateVideosResponseFromMldev(fromResponse));\r\n }\r\n return toObject;\r\n}\r\nfunction generateVideosOperationFromVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromMetadata = getValueByPath(fromObject, [\"metadata\"]);\r\n if (fromMetadata != null) {\r\n setValueByPath(toObject, [\"metadata\"], fromMetadata);\r\n }\r\n const fromDone = getValueByPath(fromObject, [\"done\"]);\r\n if (fromDone != null) {\r\n setValueByPath(toObject, [\"done\"], fromDone);\r\n }\r\n const fromError = getValueByPath(fromObject, [\"error\"]);\r\n if (fromError != null) {\r\n setValueByPath(toObject, [\"error\"], fromError);\r\n }\r\n const fromResponse = getValueByPath(fromObject, [\"response\"]);\r\n if (fromResponse != null) {\r\n setValueByPath(toObject, [\"response\"], generateVideosResponseFromVertex(fromResponse));\r\n }\r\n return toObject;\r\n}\r\nfunction generateVideosParametersToMldev(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromPrompt = getValueByPath(fromObject, [\"prompt\"]);\r\n if (fromPrompt != null) {\r\n setValueByPath(toObject, [\"instances[0]\", \"prompt\"], fromPrompt);\r\n }\r\n const fromImage = getValueByPath(fromObject, [\"image\"]);\r\n if (fromImage != null) {\r\n setValueByPath(toObject, [\"instances[0]\", \"image\"], imageToMldev(fromImage));\r\n }\r\n const fromVideo = getValueByPath(fromObject, [\"video\"]);\r\n if (fromVideo != null) {\r\n setValueByPath(toObject, [\"instances[0]\", \"video\"], videoToMldev(fromVideo));\r\n }\r\n const fromSource = getValueByPath(fromObject, [\"source\"]);\r\n if (fromSource != null) {\r\n generateVideosSourceToMldev(fromSource, toObject);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n generateVideosConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction generateVideosParametersToVertex(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromPrompt = getValueByPath(fromObject, [\"prompt\"]);\r\n if (fromPrompt != null) {\r\n setValueByPath(toObject, [\"instances[0]\", \"prompt\"], fromPrompt);\r\n }\r\n const fromImage = getValueByPath(fromObject, [\"image\"]);\r\n if (fromImage != null) {\r\n setValueByPath(toObject, [\"instances[0]\", \"image\"], imageToVertex(fromImage));\r\n }\r\n const fromVideo = getValueByPath(fromObject, [\"video\"]);\r\n if (fromVideo != null) {\r\n setValueByPath(toObject, [\"instances[0]\", \"video\"], videoToVertex(fromVideo));\r\n }\r\n const fromSource = getValueByPath(fromObject, [\"source\"]);\r\n if (fromSource != null) {\r\n generateVideosSourceToVertex(fromSource, toObject);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n generateVideosConfigToVertex(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction generateVideosResponseFromMldev(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromGeneratedVideos = getValueByPath(fromObject, [\r\n \"generatedSamples\"\r\n ]);\r\n if (fromGeneratedVideos != null) {\r\n let transformedList = fromGeneratedVideos;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return generatedVideoFromMldev(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"generatedVideos\"], transformedList);\r\n }\r\n const fromRaiMediaFilteredCount = getValueByPath(fromObject, [\r\n \"raiMediaFilteredCount\"\r\n ]);\r\n if (fromRaiMediaFilteredCount != null) {\r\n setValueByPath(toObject, [\"raiMediaFilteredCount\"], fromRaiMediaFilteredCount);\r\n }\r\n const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [\r\n \"raiMediaFilteredReasons\"\r\n ]);\r\n if (fromRaiMediaFilteredReasons != null) {\r\n setValueByPath(toObject, [\"raiMediaFilteredReasons\"], fromRaiMediaFilteredReasons);\r\n }\r\n return toObject;\r\n}\r\nfunction generateVideosResponseFromVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromGeneratedVideos = getValueByPath(fromObject, [\"videos\"]);\r\n if (fromGeneratedVideos != null) {\r\n let transformedList = fromGeneratedVideos;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return generatedVideoFromVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"generatedVideos\"], transformedList);\r\n }\r\n const fromRaiMediaFilteredCount = getValueByPath(fromObject, [\r\n \"raiMediaFilteredCount\"\r\n ]);\r\n if (fromRaiMediaFilteredCount != null) {\r\n setValueByPath(toObject, [\"raiMediaFilteredCount\"], fromRaiMediaFilteredCount);\r\n }\r\n const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [\r\n \"raiMediaFilteredReasons\"\r\n ]);\r\n if (fromRaiMediaFilteredReasons != null) {\r\n setValueByPath(toObject, [\"raiMediaFilteredReasons\"], fromRaiMediaFilteredReasons);\r\n }\r\n return toObject;\r\n}\r\nfunction generateVideosSourceToMldev(fromObject, parentObject, rootObject) {\r\n const toObject = {};\r\n const fromPrompt = getValueByPath(fromObject, [\"prompt\"]);\r\n if (parentObject !== void 0 && fromPrompt != null) {\r\n setValueByPath(parentObject, [\"instances[0]\", \"prompt\"], fromPrompt);\r\n }\r\n const fromImage = getValueByPath(fromObject, [\"image\"]);\r\n if (parentObject !== void 0 && fromImage != null) {\r\n setValueByPath(parentObject, [\"instances[0]\", \"image\"], imageToMldev(fromImage));\r\n }\r\n const fromVideo = getValueByPath(fromObject, [\"video\"]);\r\n if (parentObject !== void 0 && fromVideo != null) {\r\n setValueByPath(parentObject, [\"instances[0]\", \"video\"], videoToMldev(fromVideo));\r\n }\r\n return toObject;\r\n}\r\nfunction generateVideosSourceToVertex(fromObject, parentObject, rootObject) {\r\n const toObject = {};\r\n const fromPrompt = getValueByPath(fromObject, [\"prompt\"]);\r\n if (parentObject !== void 0 && fromPrompt != null) {\r\n setValueByPath(parentObject, [\"instances[0]\", \"prompt\"], fromPrompt);\r\n }\r\n const fromImage = getValueByPath(fromObject, [\"image\"]);\r\n if (parentObject !== void 0 && fromImage != null) {\r\n setValueByPath(parentObject, [\"instances[0]\", \"image\"], imageToVertex(fromImage));\r\n }\r\n const fromVideo = getValueByPath(fromObject, [\"video\"]);\r\n if (parentObject !== void 0 && fromVideo != null) {\r\n setValueByPath(parentObject, [\"instances[0]\", \"video\"], videoToVertex(fromVideo));\r\n }\r\n return toObject;\r\n}\r\nfunction generatedImageFromMldev(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromImage = getValueByPath(fromObject, [\"_self\"]);\r\n if (fromImage != null) {\r\n setValueByPath(toObject, [\"image\"], imageFromMldev(fromImage));\r\n }\r\n const fromRaiFilteredReason = getValueByPath(fromObject, [\r\n \"raiFilteredReason\"\r\n ]);\r\n if (fromRaiFilteredReason != null) {\r\n setValueByPath(toObject, [\"raiFilteredReason\"], fromRaiFilteredReason);\r\n }\r\n const fromSafetyAttributes = getValueByPath(fromObject, [\"_self\"]);\r\n if (fromSafetyAttributes != null) {\r\n setValueByPath(toObject, [\"safetyAttributes\"], safetyAttributesFromMldev(fromSafetyAttributes));\r\n }\r\n return toObject;\r\n}\r\nfunction generatedImageFromVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromImage = getValueByPath(fromObject, [\"_self\"]);\r\n if (fromImage != null) {\r\n setValueByPath(toObject, [\"image\"], imageFromVertex(fromImage));\r\n }\r\n const fromRaiFilteredReason = getValueByPath(fromObject, [\r\n \"raiFilteredReason\"\r\n ]);\r\n if (fromRaiFilteredReason != null) {\r\n setValueByPath(toObject, [\"raiFilteredReason\"], fromRaiFilteredReason);\r\n }\r\n const fromSafetyAttributes = getValueByPath(fromObject, [\"_self\"]);\r\n if (fromSafetyAttributes != null) {\r\n setValueByPath(toObject, [\"safetyAttributes\"], safetyAttributesFromVertex(fromSafetyAttributes));\r\n }\r\n const fromEnhancedPrompt = getValueByPath(fromObject, [\"prompt\"]);\r\n if (fromEnhancedPrompt != null) {\r\n setValueByPath(toObject, [\"enhancedPrompt\"], fromEnhancedPrompt);\r\n }\r\n return toObject;\r\n}\r\nfunction generatedImageMaskFromVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromMask = getValueByPath(fromObject, [\"_self\"]);\r\n if (fromMask != null) {\r\n setValueByPath(toObject, [\"mask\"], imageFromVertex(fromMask));\r\n }\r\n const fromLabels = getValueByPath(fromObject, [\"labels\"]);\r\n if (fromLabels != null) {\r\n let transformedList = fromLabels;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"labels\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction generatedVideoFromMldev(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromVideo = getValueByPath(fromObject, [\"video\"]);\r\n if (fromVideo != null) {\r\n setValueByPath(toObject, [\"video\"], videoFromMldev(fromVideo));\r\n }\r\n return toObject;\r\n}\r\nfunction generatedVideoFromVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromVideo = getValueByPath(fromObject, [\"_self\"]);\r\n if (fromVideo != null) {\r\n setValueByPath(toObject, [\"video\"], videoFromVertex(fromVideo));\r\n }\r\n return toObject;\r\n}\r\nfunction generationConfigToVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModelSelectionConfig = getValueByPath(fromObject, [\r\n \"modelSelectionConfig\"\r\n ]);\r\n if (fromModelSelectionConfig != null) {\r\n setValueByPath(toObject, [\"modelConfig\"], fromModelSelectionConfig);\r\n }\r\n const fromResponseJsonSchema = getValueByPath(fromObject, [\r\n \"responseJsonSchema\"\r\n ]);\r\n if (fromResponseJsonSchema != null) {\r\n setValueByPath(toObject, [\"responseJsonSchema\"], fromResponseJsonSchema);\r\n }\r\n const fromAudioTimestamp = getValueByPath(fromObject, [\r\n \"audioTimestamp\"\r\n ]);\r\n if (fromAudioTimestamp != null) {\r\n setValueByPath(toObject, [\"audioTimestamp\"], fromAudioTimestamp);\r\n }\r\n const fromCandidateCount = getValueByPath(fromObject, [\r\n \"candidateCount\"\r\n ]);\r\n if (fromCandidateCount != null) {\r\n setValueByPath(toObject, [\"candidateCount\"], fromCandidateCount);\r\n }\r\n const fromEnableAffectiveDialog = getValueByPath(fromObject, [\r\n \"enableAffectiveDialog\"\r\n ]);\r\n if (fromEnableAffectiveDialog != null) {\r\n setValueByPath(toObject, [\"enableAffectiveDialog\"], fromEnableAffectiveDialog);\r\n }\r\n const fromFrequencyPenalty = getValueByPath(fromObject, [\r\n \"frequencyPenalty\"\r\n ]);\r\n if (fromFrequencyPenalty != null) {\r\n setValueByPath(toObject, [\"frequencyPenalty\"], fromFrequencyPenalty);\r\n }\r\n const fromLogprobs = getValueByPath(fromObject, [\"logprobs\"]);\r\n if (fromLogprobs != null) {\r\n setValueByPath(toObject, [\"logprobs\"], fromLogprobs);\r\n }\r\n const fromMaxOutputTokens = getValueByPath(fromObject, [\r\n \"maxOutputTokens\"\r\n ]);\r\n if (fromMaxOutputTokens != null) {\r\n setValueByPath(toObject, [\"maxOutputTokens\"], fromMaxOutputTokens);\r\n }\r\n const fromMediaResolution = getValueByPath(fromObject, [\r\n \"mediaResolution\"\r\n ]);\r\n if (fromMediaResolution != null) {\r\n setValueByPath(toObject, [\"mediaResolution\"], fromMediaResolution);\r\n }\r\n const fromPresencePenalty = getValueByPath(fromObject, [\r\n \"presencePenalty\"\r\n ]);\r\n if (fromPresencePenalty != null) {\r\n setValueByPath(toObject, [\"presencePenalty\"], fromPresencePenalty);\r\n }\r\n const fromResponseLogprobs = getValueByPath(fromObject, [\r\n \"responseLogprobs\"\r\n ]);\r\n if (fromResponseLogprobs != null) {\r\n setValueByPath(toObject, [\"responseLogprobs\"], fromResponseLogprobs);\r\n }\r\n const fromResponseMimeType = getValueByPath(fromObject, [\r\n \"responseMimeType\"\r\n ]);\r\n if (fromResponseMimeType != null) {\r\n setValueByPath(toObject, [\"responseMimeType\"], fromResponseMimeType);\r\n }\r\n const fromResponseModalities = getValueByPath(fromObject, [\r\n \"responseModalities\"\r\n ]);\r\n if (fromResponseModalities != null) {\r\n setValueByPath(toObject, [\"responseModalities\"], fromResponseModalities);\r\n }\r\n const fromResponseSchema = getValueByPath(fromObject, [\r\n \"responseSchema\"\r\n ]);\r\n if (fromResponseSchema != null) {\r\n setValueByPath(toObject, [\"responseSchema\"], fromResponseSchema);\r\n }\r\n const fromRoutingConfig = getValueByPath(fromObject, [\r\n \"routingConfig\"\r\n ]);\r\n if (fromRoutingConfig != null) {\r\n setValueByPath(toObject, [\"routingConfig\"], fromRoutingConfig);\r\n }\r\n const fromSeed = getValueByPath(fromObject, [\"seed\"]);\r\n if (fromSeed != null) {\r\n setValueByPath(toObject, [\"seed\"], fromSeed);\r\n }\r\n const fromSpeechConfig = getValueByPath(fromObject, [\"speechConfig\"]);\r\n if (fromSpeechConfig != null) {\r\n setValueByPath(toObject, [\"speechConfig\"], speechConfigToVertex(fromSpeechConfig));\r\n }\r\n const fromStopSequences = getValueByPath(fromObject, [\r\n \"stopSequences\"\r\n ]);\r\n if (fromStopSequences != null) {\r\n setValueByPath(toObject, [\"stopSequences\"], fromStopSequences);\r\n }\r\n const fromTemperature = getValueByPath(fromObject, [\"temperature\"]);\r\n if (fromTemperature != null) {\r\n setValueByPath(toObject, [\"temperature\"], fromTemperature);\r\n }\r\n const fromThinkingConfig = getValueByPath(fromObject, [\r\n \"thinkingConfig\"\r\n ]);\r\n if (fromThinkingConfig != null) {\r\n setValueByPath(toObject, [\"thinkingConfig\"], fromThinkingConfig);\r\n }\r\n const fromTopK = getValueByPath(fromObject, [\"topK\"]);\r\n if (fromTopK != null) {\r\n setValueByPath(toObject, [\"topK\"], fromTopK);\r\n }\r\n const fromTopP = getValueByPath(fromObject, [\"topP\"]);\r\n if (fromTopP != null) {\r\n setValueByPath(toObject, [\"topP\"], fromTopP);\r\n }\r\n if (getValueByPath(fromObject, [\"enableEnhancedCivicAnswers\"]) !== void 0) {\r\n throw new Error(\"enableEnhancedCivicAnswers parameter is not supported in Vertex AI.\");\r\n }\r\n return toObject;\r\n}\r\nfunction getModelParametersToMldev(apiClient, fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], tModel(apiClient, fromModel));\r\n }\r\n return toObject;\r\n}\r\nfunction getModelParametersToVertex(apiClient, fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], tModel(apiClient, fromModel));\r\n }\r\n return toObject;\r\n}\r\nfunction googleMapsToMldev$1(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromAuthConfig = getValueByPath(fromObject, [\"authConfig\"]);\r\n if (fromAuthConfig != null) {\r\n setValueByPath(toObject, [\"authConfig\"], authConfigToMldev$1(fromAuthConfig));\r\n }\r\n const fromEnableWidget = getValueByPath(fromObject, [\"enableWidget\"]);\r\n if (fromEnableWidget != null) {\r\n setValueByPath(toObject, [\"enableWidget\"], fromEnableWidget);\r\n }\r\n return toObject;\r\n}\r\nfunction googleSearchToMldev$1(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromSearchTypes = getValueByPath(fromObject, [\"searchTypes\"]);\r\n if (fromSearchTypes != null) {\r\n setValueByPath(toObject, [\"searchTypes\"], fromSearchTypes);\r\n }\r\n if (getValueByPath(fromObject, [\"blockingConfidence\"]) !== void 0) {\r\n throw new Error(\"blockingConfidence parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"excludeDomains\"]) !== void 0) {\r\n throw new Error(\"excludeDomains parameter is not supported in Gemini API.\");\r\n }\r\n const fromTimeRangeFilter = getValueByPath(fromObject, [\r\n \"timeRangeFilter\"\r\n ]);\r\n if (fromTimeRangeFilter != null) {\r\n setValueByPath(toObject, [\"timeRangeFilter\"], fromTimeRangeFilter);\r\n }\r\n return toObject;\r\n}\r\nfunction imageConfigToMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromAspectRatio = getValueByPath(fromObject, [\"aspectRatio\"]);\r\n if (fromAspectRatio != null) {\r\n setValueByPath(toObject, [\"aspectRatio\"], fromAspectRatio);\r\n }\r\n const fromImageSize = getValueByPath(fromObject, [\"imageSize\"]);\r\n if (fromImageSize != null) {\r\n setValueByPath(toObject, [\"imageSize\"], fromImageSize);\r\n }\r\n if (getValueByPath(fromObject, [\"personGeneration\"]) !== void 0) {\r\n throw new Error(\"personGeneration parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"prominentPeople\"]) !== void 0) {\r\n throw new Error(\"prominentPeople parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"outputMimeType\"]) !== void 0) {\r\n throw new Error(\"outputMimeType parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"outputCompressionQuality\"]) !== void 0) {\r\n throw new Error(\"outputCompressionQuality parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"imageOutputOptions\"]) !== void 0) {\r\n throw new Error(\"imageOutputOptions parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction imageConfigToVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromAspectRatio = getValueByPath(fromObject, [\"aspectRatio\"]);\r\n if (fromAspectRatio != null) {\r\n setValueByPath(toObject, [\"aspectRatio\"], fromAspectRatio);\r\n }\r\n const fromImageSize = getValueByPath(fromObject, [\"imageSize\"]);\r\n if (fromImageSize != null) {\r\n setValueByPath(toObject, [\"imageSize\"], fromImageSize);\r\n }\r\n const fromPersonGeneration = getValueByPath(fromObject, [\r\n \"personGeneration\"\r\n ]);\r\n if (fromPersonGeneration != null) {\r\n setValueByPath(toObject, [\"personGeneration\"], fromPersonGeneration);\r\n }\r\n const fromProminentPeople = getValueByPath(fromObject, [\r\n \"prominentPeople\"\r\n ]);\r\n if (fromProminentPeople != null) {\r\n setValueByPath(toObject, [\"prominentPeople\"], fromProminentPeople);\r\n }\r\n const fromOutputMimeType = getValueByPath(fromObject, [\r\n \"outputMimeType\"\r\n ]);\r\n if (fromOutputMimeType != null) {\r\n setValueByPath(toObject, [\"imageOutputOptions\", \"mimeType\"], fromOutputMimeType);\r\n }\r\n const fromOutputCompressionQuality = getValueByPath(fromObject, [\r\n \"outputCompressionQuality\"\r\n ]);\r\n if (fromOutputCompressionQuality != null) {\r\n setValueByPath(toObject, [\"imageOutputOptions\", \"compressionQuality\"], fromOutputCompressionQuality);\r\n }\r\n const fromImageOutputOptions = getValueByPath(fromObject, [\r\n \"imageOutputOptions\"\r\n ]);\r\n if (fromImageOutputOptions != null) {\r\n setValueByPath(toObject, [\"imageOutputOptions\"], fromImageOutputOptions);\r\n }\r\n return toObject;\r\n}\r\nfunction imageFromMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromImageBytes = getValueByPath(fromObject, [\r\n \"bytesBase64Encoded\"\r\n ]);\r\n if (fromImageBytes != null) {\r\n setValueByPath(toObject, [\"imageBytes\"], tBytes(fromImageBytes));\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction imageFromVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromGcsUri = getValueByPath(fromObject, [\"gcsUri\"]);\r\n if (fromGcsUri != null) {\r\n setValueByPath(toObject, [\"gcsUri\"], fromGcsUri);\r\n }\r\n const fromImageBytes = getValueByPath(fromObject, [\r\n \"bytesBase64Encoded\"\r\n ]);\r\n if (fromImageBytes != null) {\r\n setValueByPath(toObject, [\"imageBytes\"], tBytes(fromImageBytes));\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction imageToMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"gcsUri\"]) !== void 0) {\r\n throw new Error(\"gcsUri parameter is not supported in Gemini API.\");\r\n }\r\n const fromImageBytes = getValueByPath(fromObject, [\"imageBytes\"]);\r\n if (fromImageBytes != null) {\r\n setValueByPath(toObject, [\"bytesBase64Encoded\"], tBytes(fromImageBytes));\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction imageToVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromGcsUri = getValueByPath(fromObject, [\"gcsUri\"]);\r\n if (fromGcsUri != null) {\r\n setValueByPath(toObject, [\"gcsUri\"], fromGcsUri);\r\n }\r\n const fromImageBytes = getValueByPath(fromObject, [\"imageBytes\"]);\r\n if (fromImageBytes != null) {\r\n setValueByPath(toObject, [\"bytesBase64Encoded\"], tBytes(fromImageBytes));\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction listModelsConfigToMldev(apiClient, fromObject, parentObject, _rootObject) {\r\n const toObject = {};\r\n const fromPageSize = getValueByPath(fromObject, [\"pageSize\"]);\r\n if (parentObject !== void 0 && fromPageSize != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageSize\"], fromPageSize);\r\n }\r\n const fromPageToken = getValueByPath(fromObject, [\"pageToken\"]);\r\n if (parentObject !== void 0 && fromPageToken != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageToken\"], fromPageToken);\r\n }\r\n const fromFilter = getValueByPath(fromObject, [\"filter\"]);\r\n if (parentObject !== void 0 && fromFilter != null) {\r\n setValueByPath(parentObject, [\"_query\", \"filter\"], fromFilter);\r\n }\r\n const fromQueryBase = getValueByPath(fromObject, [\"queryBase\"]);\r\n if (parentObject !== void 0 && fromQueryBase != null) {\r\n setValueByPath(parentObject, [\"_url\", \"models_url\"], tModelsUrl(apiClient, fromQueryBase));\r\n }\r\n return toObject;\r\n}\r\nfunction listModelsConfigToVertex(apiClient, fromObject, parentObject, _rootObject) {\r\n const toObject = {};\r\n const fromPageSize = getValueByPath(fromObject, [\"pageSize\"]);\r\n if (parentObject !== void 0 && fromPageSize != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageSize\"], fromPageSize);\r\n }\r\n const fromPageToken = getValueByPath(fromObject, [\"pageToken\"]);\r\n if (parentObject !== void 0 && fromPageToken != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageToken\"], fromPageToken);\r\n }\r\n const fromFilter = getValueByPath(fromObject, [\"filter\"]);\r\n if (parentObject !== void 0 && fromFilter != null) {\r\n setValueByPath(parentObject, [\"_query\", \"filter\"], fromFilter);\r\n }\r\n const fromQueryBase = getValueByPath(fromObject, [\"queryBase\"]);\r\n if (parentObject !== void 0 && fromQueryBase != null) {\r\n setValueByPath(parentObject, [\"_url\", \"models_url\"], tModelsUrl(apiClient, fromQueryBase));\r\n }\r\n return toObject;\r\n}\r\nfunction listModelsParametersToMldev(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n listModelsConfigToMldev(apiClient, fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction listModelsParametersToVertex(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n listModelsConfigToVertex(apiClient, fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction listModelsResponseFromMldev(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromNextPageToken = getValueByPath(fromObject, [\r\n \"nextPageToken\"\r\n ]);\r\n if (fromNextPageToken != null) {\r\n setValueByPath(toObject, [\"nextPageToken\"], fromNextPageToken);\r\n }\r\n const fromModels = getValueByPath(fromObject, [\"_self\"]);\r\n if (fromModels != null) {\r\n let transformedList = tExtractModels(fromModels);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return modelFromMldev(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"models\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction listModelsResponseFromVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromNextPageToken = getValueByPath(fromObject, [\r\n \"nextPageToken\"\r\n ]);\r\n if (fromNextPageToken != null) {\r\n setValueByPath(toObject, [\"nextPageToken\"], fromNextPageToken);\r\n }\r\n const fromModels = getValueByPath(fromObject, [\"_self\"]);\r\n if (fromModels != null) {\r\n let transformedList = tExtractModels(fromModels);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return modelFromVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"models\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction maskReferenceConfigToVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromMaskMode = getValueByPath(fromObject, [\"maskMode\"]);\r\n if (fromMaskMode != null) {\r\n setValueByPath(toObject, [\"maskMode\"], fromMaskMode);\r\n }\r\n const fromSegmentationClasses = getValueByPath(fromObject, [\r\n \"segmentationClasses\"\r\n ]);\r\n if (fromSegmentationClasses != null) {\r\n setValueByPath(toObject, [\"maskClasses\"], fromSegmentationClasses);\r\n }\r\n const fromMaskDilation = getValueByPath(fromObject, [\"maskDilation\"]);\r\n if (fromMaskDilation != null) {\r\n setValueByPath(toObject, [\"dilation\"], fromMaskDilation);\r\n }\r\n return toObject;\r\n}\r\nfunction modelFromMldev(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromDisplayName = getValueByPath(fromObject, [\"displayName\"]);\r\n if (fromDisplayName != null) {\r\n setValueByPath(toObject, [\"displayName\"], fromDisplayName);\r\n }\r\n const fromDescription = getValueByPath(fromObject, [\"description\"]);\r\n if (fromDescription != null) {\r\n setValueByPath(toObject, [\"description\"], fromDescription);\r\n }\r\n const fromVersion = getValueByPath(fromObject, [\"version\"]);\r\n if (fromVersion != null) {\r\n setValueByPath(toObject, [\"version\"], fromVersion);\r\n }\r\n const fromTunedModelInfo = getValueByPath(fromObject, [\"_self\"]);\r\n if (fromTunedModelInfo != null) {\r\n setValueByPath(toObject, [\"tunedModelInfo\"], tunedModelInfoFromMldev(fromTunedModelInfo));\r\n }\r\n const fromInputTokenLimit = getValueByPath(fromObject, [\r\n \"inputTokenLimit\"\r\n ]);\r\n if (fromInputTokenLimit != null) {\r\n setValueByPath(toObject, [\"inputTokenLimit\"], fromInputTokenLimit);\r\n }\r\n const fromOutputTokenLimit = getValueByPath(fromObject, [\r\n \"outputTokenLimit\"\r\n ]);\r\n if (fromOutputTokenLimit != null) {\r\n setValueByPath(toObject, [\"outputTokenLimit\"], fromOutputTokenLimit);\r\n }\r\n const fromSupportedActions = getValueByPath(fromObject, [\r\n \"supportedGenerationMethods\"\r\n ]);\r\n if (fromSupportedActions != null) {\r\n setValueByPath(toObject, [\"supportedActions\"], fromSupportedActions);\r\n }\r\n const fromTemperature = getValueByPath(fromObject, [\"temperature\"]);\r\n if (fromTemperature != null) {\r\n setValueByPath(toObject, [\"temperature\"], fromTemperature);\r\n }\r\n const fromMaxTemperature = getValueByPath(fromObject, [\r\n \"maxTemperature\"\r\n ]);\r\n if (fromMaxTemperature != null) {\r\n setValueByPath(toObject, [\"maxTemperature\"], fromMaxTemperature);\r\n }\r\n const fromTopP = getValueByPath(fromObject, [\"topP\"]);\r\n if (fromTopP != null) {\r\n setValueByPath(toObject, [\"topP\"], fromTopP);\r\n }\r\n const fromTopK = getValueByPath(fromObject, [\"topK\"]);\r\n if (fromTopK != null) {\r\n setValueByPath(toObject, [\"topK\"], fromTopK);\r\n }\r\n const fromThinking = getValueByPath(fromObject, [\"thinking\"]);\r\n if (fromThinking != null) {\r\n setValueByPath(toObject, [\"thinking\"], fromThinking);\r\n }\r\n return toObject;\r\n}\r\nfunction modelFromVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromDisplayName = getValueByPath(fromObject, [\"displayName\"]);\r\n if (fromDisplayName != null) {\r\n setValueByPath(toObject, [\"displayName\"], fromDisplayName);\r\n }\r\n const fromDescription = getValueByPath(fromObject, [\"description\"]);\r\n if (fromDescription != null) {\r\n setValueByPath(toObject, [\"description\"], fromDescription);\r\n }\r\n const fromVersion = getValueByPath(fromObject, [\"versionId\"]);\r\n if (fromVersion != null) {\r\n setValueByPath(toObject, [\"version\"], fromVersion);\r\n }\r\n const fromEndpoints = getValueByPath(fromObject, [\"deployedModels\"]);\r\n if (fromEndpoints != null) {\r\n let transformedList = fromEndpoints;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return endpointFromVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"endpoints\"], transformedList);\r\n }\r\n const fromLabels = getValueByPath(fromObject, [\"labels\"]);\r\n if (fromLabels != null) {\r\n setValueByPath(toObject, [\"labels\"], fromLabels);\r\n }\r\n const fromTunedModelInfo = getValueByPath(fromObject, [\"_self\"]);\r\n if (fromTunedModelInfo != null) {\r\n setValueByPath(toObject, [\"tunedModelInfo\"], tunedModelInfoFromVertex(fromTunedModelInfo));\r\n }\r\n const fromDefaultCheckpointId = getValueByPath(fromObject, [\r\n \"defaultCheckpointId\"\r\n ]);\r\n if (fromDefaultCheckpointId != null) {\r\n setValueByPath(toObject, [\"defaultCheckpointId\"], fromDefaultCheckpointId);\r\n }\r\n const fromCheckpoints = getValueByPath(fromObject, [\"checkpoints\"]);\r\n if (fromCheckpoints != null) {\r\n let transformedList = fromCheckpoints;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"checkpoints\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction multiSpeakerVoiceConfigToVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [\r\n \"speakerVoiceConfigs\"\r\n ]);\r\n if (fromSpeakerVoiceConfigs != null) {\r\n let transformedList = fromSpeakerVoiceConfigs;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return speakerVoiceConfigToVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"speakerVoiceConfigs\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction partToMldev$1(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromMediaResolution = getValueByPath(fromObject, [\r\n \"mediaResolution\"\r\n ]);\r\n if (fromMediaResolution != null) {\r\n setValueByPath(toObject, [\"mediaResolution\"], fromMediaResolution);\r\n }\r\n const fromCodeExecutionResult = getValueByPath(fromObject, [\r\n \"codeExecutionResult\"\r\n ]);\r\n if (fromCodeExecutionResult != null) {\r\n setValueByPath(toObject, [\"codeExecutionResult\"], fromCodeExecutionResult);\r\n }\r\n const fromExecutableCode = getValueByPath(fromObject, [\r\n \"executableCode\"\r\n ]);\r\n if (fromExecutableCode != null) {\r\n setValueByPath(toObject, [\"executableCode\"], fromExecutableCode);\r\n }\r\n const fromFileData = getValueByPath(fromObject, [\"fileData\"]);\r\n if (fromFileData != null) {\r\n setValueByPath(toObject, [\"fileData\"], fileDataToMldev$1(fromFileData));\r\n }\r\n const fromFunctionCall = getValueByPath(fromObject, [\"functionCall\"]);\r\n if (fromFunctionCall != null) {\r\n setValueByPath(toObject, [\"functionCall\"], functionCallToMldev$1(fromFunctionCall));\r\n }\r\n const fromFunctionResponse = getValueByPath(fromObject, [\r\n \"functionResponse\"\r\n ]);\r\n if (fromFunctionResponse != null) {\r\n setValueByPath(toObject, [\"functionResponse\"], fromFunctionResponse);\r\n }\r\n const fromInlineData = getValueByPath(fromObject, [\"inlineData\"]);\r\n if (fromInlineData != null) {\r\n setValueByPath(toObject, [\"inlineData\"], blobToMldev$1(fromInlineData));\r\n }\r\n const fromText = getValueByPath(fromObject, [\"text\"]);\r\n if (fromText != null) {\r\n setValueByPath(toObject, [\"text\"], fromText);\r\n }\r\n const fromThought = getValueByPath(fromObject, [\"thought\"]);\r\n if (fromThought != null) {\r\n setValueByPath(toObject, [\"thought\"], fromThought);\r\n }\r\n const fromThoughtSignature = getValueByPath(fromObject, [\r\n \"thoughtSignature\"\r\n ]);\r\n if (fromThoughtSignature != null) {\r\n setValueByPath(toObject, [\"thoughtSignature\"], fromThoughtSignature);\r\n }\r\n const fromVideoMetadata = getValueByPath(fromObject, [\r\n \"videoMetadata\"\r\n ]);\r\n if (fromVideoMetadata != null) {\r\n setValueByPath(toObject, [\"videoMetadata\"], fromVideoMetadata);\r\n }\r\n const fromToolCall = getValueByPath(fromObject, [\"toolCall\"]);\r\n if (fromToolCall != null) {\r\n setValueByPath(toObject, [\"toolCall\"], fromToolCall);\r\n }\r\n const fromToolResponse = getValueByPath(fromObject, [\"toolResponse\"]);\r\n if (fromToolResponse != null) {\r\n setValueByPath(toObject, [\"toolResponse\"], fromToolResponse);\r\n }\r\n const fromPartMetadata = getValueByPath(fromObject, [\"partMetadata\"]);\r\n if (fromPartMetadata != null) {\r\n setValueByPath(toObject, [\"partMetadata\"], fromPartMetadata);\r\n }\r\n return toObject;\r\n}\r\nfunction partToVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromMediaResolution = getValueByPath(fromObject, [\r\n \"mediaResolution\"\r\n ]);\r\n if (fromMediaResolution != null) {\r\n setValueByPath(toObject, [\"mediaResolution\"], fromMediaResolution);\r\n }\r\n const fromCodeExecutionResult = getValueByPath(fromObject, [\r\n \"codeExecutionResult\"\r\n ]);\r\n if (fromCodeExecutionResult != null) {\r\n setValueByPath(toObject, [\"codeExecutionResult\"], fromCodeExecutionResult);\r\n }\r\n const fromExecutableCode = getValueByPath(fromObject, [\r\n \"executableCode\"\r\n ]);\r\n if (fromExecutableCode != null) {\r\n setValueByPath(toObject, [\"executableCode\"], fromExecutableCode);\r\n }\r\n const fromFileData = getValueByPath(fromObject, [\"fileData\"]);\r\n if (fromFileData != null) {\r\n setValueByPath(toObject, [\"fileData\"], fromFileData);\r\n }\r\n const fromFunctionCall = getValueByPath(fromObject, [\"functionCall\"]);\r\n if (fromFunctionCall != null) {\r\n setValueByPath(toObject, [\"functionCall\"], fromFunctionCall);\r\n }\r\n const fromFunctionResponse = getValueByPath(fromObject, [\r\n \"functionResponse\"\r\n ]);\r\n if (fromFunctionResponse != null) {\r\n setValueByPath(toObject, [\"functionResponse\"], fromFunctionResponse);\r\n }\r\n const fromInlineData = getValueByPath(fromObject, [\"inlineData\"]);\r\n if (fromInlineData != null) {\r\n setValueByPath(toObject, [\"inlineData\"], fromInlineData);\r\n }\r\n const fromText = getValueByPath(fromObject, [\"text\"]);\r\n if (fromText != null) {\r\n setValueByPath(toObject, [\"text\"], fromText);\r\n }\r\n const fromThought = getValueByPath(fromObject, [\"thought\"]);\r\n if (fromThought != null) {\r\n setValueByPath(toObject, [\"thought\"], fromThought);\r\n }\r\n const fromThoughtSignature = getValueByPath(fromObject, [\r\n \"thoughtSignature\"\r\n ]);\r\n if (fromThoughtSignature != null) {\r\n setValueByPath(toObject, [\"thoughtSignature\"], fromThoughtSignature);\r\n }\r\n const fromVideoMetadata = getValueByPath(fromObject, [\r\n \"videoMetadata\"\r\n ]);\r\n if (fromVideoMetadata != null) {\r\n setValueByPath(toObject, [\"videoMetadata\"], fromVideoMetadata);\r\n }\r\n if (getValueByPath(fromObject, [\"toolCall\"]) !== void 0) {\r\n throw new Error(\"toolCall parameter is not supported in Vertex AI.\");\r\n }\r\n if (getValueByPath(fromObject, [\"toolResponse\"]) !== void 0) {\r\n throw new Error(\"toolResponse parameter is not supported in Vertex AI.\");\r\n }\r\n if (getValueByPath(fromObject, [\"partMetadata\"]) !== void 0) {\r\n throw new Error(\"partMetadata parameter is not supported in Vertex AI.\");\r\n }\r\n return toObject;\r\n}\r\nfunction productImageToVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromProductImage = getValueByPath(fromObject, [\"productImage\"]);\r\n if (fromProductImage != null) {\r\n setValueByPath(toObject, [\"image\"], imageToVertex(fromProductImage));\r\n }\r\n return toObject;\r\n}\r\nfunction recontextImageConfigToVertex(fromObject, parentObject, _rootObject) {\r\n const toObject = {};\r\n const fromNumberOfImages = getValueByPath(fromObject, [\r\n \"numberOfImages\"\r\n ]);\r\n if (parentObject !== void 0 && fromNumberOfImages != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"sampleCount\"], fromNumberOfImages);\r\n }\r\n const fromBaseSteps = getValueByPath(fromObject, [\"baseSteps\"]);\r\n if (parentObject !== void 0 && fromBaseSteps != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"baseSteps\"], fromBaseSteps);\r\n }\r\n const fromOutputGcsUri = getValueByPath(fromObject, [\"outputGcsUri\"]);\r\n if (parentObject !== void 0 && fromOutputGcsUri != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"storageUri\"], fromOutputGcsUri);\r\n }\r\n const fromSeed = getValueByPath(fromObject, [\"seed\"]);\r\n if (parentObject !== void 0 && fromSeed != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"seed\"], fromSeed);\r\n }\r\n const fromSafetyFilterLevel = getValueByPath(fromObject, [\r\n \"safetyFilterLevel\"\r\n ]);\r\n if (parentObject !== void 0 && fromSafetyFilterLevel != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"safetySetting\"], fromSafetyFilterLevel);\r\n }\r\n const fromPersonGeneration = getValueByPath(fromObject, [\r\n \"personGeneration\"\r\n ]);\r\n if (parentObject !== void 0 && fromPersonGeneration != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"personGeneration\"], fromPersonGeneration);\r\n }\r\n const fromAddWatermark = getValueByPath(fromObject, [\"addWatermark\"]);\r\n if (parentObject !== void 0 && fromAddWatermark != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"addWatermark\"], fromAddWatermark);\r\n }\r\n const fromOutputMimeType = getValueByPath(fromObject, [\r\n \"outputMimeType\"\r\n ]);\r\n if (parentObject !== void 0 && fromOutputMimeType != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"outputOptions\", \"mimeType\"], fromOutputMimeType);\r\n }\r\n const fromOutputCompressionQuality = getValueByPath(fromObject, [\r\n \"outputCompressionQuality\"\r\n ]);\r\n if (parentObject !== void 0 && fromOutputCompressionQuality != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"outputOptions\", \"compressionQuality\"], fromOutputCompressionQuality);\r\n }\r\n const fromEnhancePrompt = getValueByPath(fromObject, [\r\n \"enhancePrompt\"\r\n ]);\r\n if (parentObject !== void 0 && fromEnhancePrompt != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"enhancePrompt\"], fromEnhancePrompt);\r\n }\r\n const fromLabels = getValueByPath(fromObject, [\"labels\"]);\r\n if (parentObject !== void 0 && fromLabels != null) {\r\n setValueByPath(parentObject, [\"labels\"], fromLabels);\r\n }\r\n return toObject;\r\n}\r\nfunction recontextImageParametersToVertex(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromSource = getValueByPath(fromObject, [\"source\"]);\r\n if (fromSource != null) {\r\n recontextImageSourceToVertex(fromSource, toObject);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n recontextImageConfigToVertex(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction recontextImageResponseFromVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromGeneratedImages = getValueByPath(fromObject, [\r\n \"predictions\"\r\n ]);\r\n if (fromGeneratedImages != null) {\r\n let transformedList = fromGeneratedImages;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return generatedImageFromVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"generatedImages\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction recontextImageSourceToVertex(fromObject, parentObject, rootObject) {\r\n const toObject = {};\r\n const fromPrompt = getValueByPath(fromObject, [\"prompt\"]);\r\n if (parentObject !== void 0 && fromPrompt != null) {\r\n setValueByPath(parentObject, [\"instances[0]\", \"prompt\"], fromPrompt);\r\n }\r\n const fromPersonImage = getValueByPath(fromObject, [\"personImage\"]);\r\n if (parentObject !== void 0 && fromPersonImage != null) {\r\n setValueByPath(parentObject, [\"instances[0]\", \"personImage\", \"image\"], imageToVertex(fromPersonImage));\r\n }\r\n const fromProductImages = getValueByPath(fromObject, [\r\n \"productImages\"\r\n ]);\r\n if (parentObject !== void 0 && fromProductImages != null) {\r\n let transformedList = fromProductImages;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return productImageToVertex(item);\r\n });\r\n }\r\n setValueByPath(parentObject, [\"instances[0]\", \"productImages\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction referenceImageAPIInternalToVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromReferenceImage = getValueByPath(fromObject, [\r\n \"referenceImage\"\r\n ]);\r\n if (fromReferenceImage != null) {\r\n setValueByPath(toObject, [\"referenceImage\"], imageToVertex(fromReferenceImage));\r\n }\r\n const fromReferenceId = getValueByPath(fromObject, [\"referenceId\"]);\r\n if (fromReferenceId != null) {\r\n setValueByPath(toObject, [\"referenceId\"], fromReferenceId);\r\n }\r\n const fromReferenceType = getValueByPath(fromObject, [\r\n \"referenceType\"\r\n ]);\r\n if (fromReferenceType != null) {\r\n setValueByPath(toObject, [\"referenceType\"], fromReferenceType);\r\n }\r\n const fromMaskImageConfig = getValueByPath(fromObject, [\r\n \"maskImageConfig\"\r\n ]);\r\n if (fromMaskImageConfig != null) {\r\n setValueByPath(toObject, [\"maskImageConfig\"], maskReferenceConfigToVertex(fromMaskImageConfig));\r\n }\r\n const fromControlImageConfig = getValueByPath(fromObject, [\r\n \"controlImageConfig\"\r\n ]);\r\n if (fromControlImageConfig != null) {\r\n setValueByPath(toObject, [\"controlImageConfig\"], controlReferenceConfigToVertex(fromControlImageConfig));\r\n }\r\n const fromStyleImageConfig = getValueByPath(fromObject, [\r\n \"styleImageConfig\"\r\n ]);\r\n if (fromStyleImageConfig != null) {\r\n setValueByPath(toObject, [\"styleImageConfig\"], fromStyleImageConfig);\r\n }\r\n const fromSubjectImageConfig = getValueByPath(fromObject, [\r\n \"subjectImageConfig\"\r\n ]);\r\n if (fromSubjectImageConfig != null) {\r\n setValueByPath(toObject, [\"subjectImageConfig\"], fromSubjectImageConfig);\r\n }\r\n return toObject;\r\n}\r\nfunction replicatedVoiceConfigToVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n const fromVoiceSampleAudio = getValueByPath(fromObject, [\r\n \"voiceSampleAudio\"\r\n ]);\r\n if (fromVoiceSampleAudio != null) {\r\n setValueByPath(toObject, [\"voiceSampleAudio\"], fromVoiceSampleAudio);\r\n }\r\n return toObject;\r\n}\r\nfunction safetyAttributesFromMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromCategories = getValueByPath(fromObject, [\r\n \"safetyAttributes\",\r\n \"categories\"\r\n ]);\r\n if (fromCategories != null) {\r\n setValueByPath(toObject, [\"categories\"], fromCategories);\r\n }\r\n const fromScores = getValueByPath(fromObject, [\r\n \"safetyAttributes\",\r\n \"scores\"\r\n ]);\r\n if (fromScores != null) {\r\n setValueByPath(toObject, [\"scores\"], fromScores);\r\n }\r\n const fromContentType = getValueByPath(fromObject, [\"contentType\"]);\r\n if (fromContentType != null) {\r\n setValueByPath(toObject, [\"contentType\"], fromContentType);\r\n }\r\n return toObject;\r\n}\r\nfunction safetyAttributesFromVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromCategories = getValueByPath(fromObject, [\r\n \"safetyAttributes\",\r\n \"categories\"\r\n ]);\r\n if (fromCategories != null) {\r\n setValueByPath(toObject, [\"categories\"], fromCategories);\r\n }\r\n const fromScores = getValueByPath(fromObject, [\r\n \"safetyAttributes\",\r\n \"scores\"\r\n ]);\r\n if (fromScores != null) {\r\n setValueByPath(toObject, [\"scores\"], fromScores);\r\n }\r\n const fromContentType = getValueByPath(fromObject, [\"contentType\"]);\r\n if (fromContentType != null) {\r\n setValueByPath(toObject, [\"contentType\"], fromContentType);\r\n }\r\n return toObject;\r\n}\r\nfunction safetySettingToMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromCategory = getValueByPath(fromObject, [\"category\"]);\r\n if (fromCategory != null) {\r\n setValueByPath(toObject, [\"category\"], fromCategory);\r\n }\r\n if (getValueByPath(fromObject, [\"method\"]) !== void 0) {\r\n throw new Error(\"method parameter is not supported in Gemini API.\");\r\n }\r\n const fromThreshold = getValueByPath(fromObject, [\"threshold\"]);\r\n if (fromThreshold != null) {\r\n setValueByPath(toObject, [\"threshold\"], fromThreshold);\r\n }\r\n return toObject;\r\n}\r\nfunction scribbleImageToVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromImage = getValueByPath(fromObject, [\"image\"]);\r\n if (fromImage != null) {\r\n setValueByPath(toObject, [\"image\"], imageToVertex(fromImage));\r\n }\r\n return toObject;\r\n}\r\nfunction segmentImageConfigToVertex(fromObject, parentObject, _rootObject) {\r\n const toObject = {};\r\n const fromMode = getValueByPath(fromObject, [\"mode\"]);\r\n if (parentObject !== void 0 && fromMode != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"mode\"], fromMode);\r\n }\r\n const fromMaxPredictions = getValueByPath(fromObject, [\r\n \"maxPredictions\"\r\n ]);\r\n if (parentObject !== void 0 && fromMaxPredictions != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"maxPredictions\"], fromMaxPredictions);\r\n }\r\n const fromConfidenceThreshold = getValueByPath(fromObject, [\r\n \"confidenceThreshold\"\r\n ]);\r\n if (parentObject !== void 0 && fromConfidenceThreshold != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"confidenceThreshold\"], fromConfidenceThreshold);\r\n }\r\n const fromMaskDilation = getValueByPath(fromObject, [\"maskDilation\"]);\r\n if (parentObject !== void 0 && fromMaskDilation != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"maskDilation\"], fromMaskDilation);\r\n }\r\n const fromBinaryColorThreshold = getValueByPath(fromObject, [\r\n \"binaryColorThreshold\"\r\n ]);\r\n if (parentObject !== void 0 && fromBinaryColorThreshold != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"binaryColorThreshold\"], fromBinaryColorThreshold);\r\n }\r\n const fromLabels = getValueByPath(fromObject, [\"labels\"]);\r\n if (parentObject !== void 0 && fromLabels != null) {\r\n setValueByPath(parentObject, [\"labels\"], fromLabels);\r\n }\r\n return toObject;\r\n}\r\nfunction segmentImageParametersToVertex(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromSource = getValueByPath(fromObject, [\"source\"]);\r\n if (fromSource != null) {\r\n segmentImageSourceToVertex(fromSource, toObject);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n segmentImageConfigToVertex(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction segmentImageResponseFromVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromGeneratedMasks = getValueByPath(fromObject, [\"predictions\"]);\r\n if (fromGeneratedMasks != null) {\r\n let transformedList = fromGeneratedMasks;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return generatedImageMaskFromVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"generatedMasks\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction segmentImageSourceToVertex(fromObject, parentObject, rootObject) {\r\n const toObject = {};\r\n const fromPrompt = getValueByPath(fromObject, [\"prompt\"]);\r\n if (parentObject !== void 0 && fromPrompt != null) {\r\n setValueByPath(parentObject, [\"instances[0]\", \"prompt\"], fromPrompt);\r\n }\r\n const fromImage = getValueByPath(fromObject, [\"image\"]);\r\n if (parentObject !== void 0 && fromImage != null) {\r\n setValueByPath(parentObject, [\"instances[0]\", \"image\"], imageToVertex(fromImage));\r\n }\r\n const fromScribbleImage = getValueByPath(fromObject, [\r\n \"scribbleImage\"\r\n ]);\r\n if (parentObject !== void 0 && fromScribbleImage != null) {\r\n setValueByPath(parentObject, [\"instances[0]\", \"scribble\"], scribbleImageToVertex(fromScribbleImage));\r\n }\r\n return toObject;\r\n}\r\nfunction speakerVoiceConfigToVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromSpeaker = getValueByPath(fromObject, [\"speaker\"]);\r\n if (fromSpeaker != null) {\r\n setValueByPath(toObject, [\"speaker\"], fromSpeaker);\r\n }\r\n const fromVoiceConfig = getValueByPath(fromObject, [\"voiceConfig\"]);\r\n if (fromVoiceConfig != null) {\r\n setValueByPath(toObject, [\"voiceConfig\"], voiceConfigToVertex(fromVoiceConfig));\r\n }\r\n return toObject;\r\n}\r\nfunction speechConfigToVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromVoiceConfig = getValueByPath(fromObject, [\"voiceConfig\"]);\r\n if (fromVoiceConfig != null) {\r\n setValueByPath(toObject, [\"voiceConfig\"], voiceConfigToVertex(fromVoiceConfig));\r\n }\r\n const fromLanguageCode = getValueByPath(fromObject, [\"languageCode\"]);\r\n if (fromLanguageCode != null) {\r\n setValueByPath(toObject, [\"languageCode\"], fromLanguageCode);\r\n }\r\n const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [\r\n \"multiSpeakerVoiceConfig\"\r\n ]);\r\n if (fromMultiSpeakerVoiceConfig != null) {\r\n setValueByPath(toObject, [\"multiSpeakerVoiceConfig\"], multiSpeakerVoiceConfigToVertex(fromMultiSpeakerVoiceConfig));\r\n }\r\n return toObject;\r\n}\r\nfunction toolConfigToMldev(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromRetrievalConfig = getValueByPath(fromObject, [\r\n \"retrievalConfig\"\r\n ]);\r\n if (fromRetrievalConfig != null) {\r\n setValueByPath(toObject, [\"retrievalConfig\"], fromRetrievalConfig);\r\n }\r\n const fromFunctionCallingConfig = getValueByPath(fromObject, [\r\n \"functionCallingConfig\"\r\n ]);\r\n if (fromFunctionCallingConfig != null) {\r\n setValueByPath(toObject, [\"functionCallingConfig\"], functionCallingConfigToMldev(fromFunctionCallingConfig));\r\n }\r\n const fromIncludeServerSideToolInvocations = getValueByPath(fromObject, [\"includeServerSideToolInvocations\"]);\r\n if (fromIncludeServerSideToolInvocations != null) {\r\n setValueByPath(toObject, [\"includeServerSideToolInvocations\"], fromIncludeServerSideToolInvocations);\r\n }\r\n return toObject;\r\n}\r\nfunction toolConfigToVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromRetrievalConfig = getValueByPath(fromObject, [\r\n \"retrievalConfig\"\r\n ]);\r\n if (fromRetrievalConfig != null) {\r\n setValueByPath(toObject, [\"retrievalConfig\"], fromRetrievalConfig);\r\n }\r\n const fromFunctionCallingConfig = getValueByPath(fromObject, [\r\n \"functionCallingConfig\"\r\n ]);\r\n if (fromFunctionCallingConfig != null) {\r\n setValueByPath(toObject, [\"functionCallingConfig\"], fromFunctionCallingConfig);\r\n }\r\n if (getValueByPath(fromObject, [\"includeServerSideToolInvocations\"]) !== void 0) {\r\n throw new Error(\"includeServerSideToolInvocations parameter is not supported in Vertex AI.\");\r\n }\r\n return toObject;\r\n}\r\nfunction toolToMldev$1(fromObject, rootObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"retrieval\"]) !== void 0) {\r\n throw new Error(\"retrieval parameter is not supported in Gemini API.\");\r\n }\r\n const fromComputerUse = getValueByPath(fromObject, [\"computerUse\"]);\r\n if (fromComputerUse != null) {\r\n setValueByPath(toObject, [\"computerUse\"], fromComputerUse);\r\n }\r\n const fromFileSearch = getValueByPath(fromObject, [\"fileSearch\"]);\r\n if (fromFileSearch != null) {\r\n setValueByPath(toObject, [\"fileSearch\"], fromFileSearch);\r\n }\r\n const fromGoogleSearch = getValueByPath(fromObject, [\"googleSearch\"]);\r\n if (fromGoogleSearch != null) {\r\n setValueByPath(toObject, [\"googleSearch\"], googleSearchToMldev$1(fromGoogleSearch));\r\n }\r\n const fromGoogleMaps = getValueByPath(fromObject, [\"googleMaps\"]);\r\n if (fromGoogleMaps != null) {\r\n setValueByPath(toObject, [\"googleMaps\"], googleMapsToMldev$1(fromGoogleMaps));\r\n }\r\n const fromCodeExecution = getValueByPath(fromObject, [\r\n \"codeExecution\"\r\n ]);\r\n if (fromCodeExecution != null) {\r\n setValueByPath(toObject, [\"codeExecution\"], fromCodeExecution);\r\n }\r\n if (getValueByPath(fromObject, [\"enterpriseWebSearch\"]) !== void 0) {\r\n throw new Error(\"enterpriseWebSearch parameter is not supported in Gemini API.\");\r\n }\r\n const fromFunctionDeclarations = getValueByPath(fromObject, [\r\n \"functionDeclarations\"\r\n ]);\r\n if (fromFunctionDeclarations != null) {\r\n let transformedList = fromFunctionDeclarations;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"functionDeclarations\"], transformedList);\r\n }\r\n const fromGoogleSearchRetrieval = getValueByPath(fromObject, [\r\n \"googleSearchRetrieval\"\r\n ]);\r\n if (fromGoogleSearchRetrieval != null) {\r\n setValueByPath(toObject, [\"googleSearchRetrieval\"], fromGoogleSearchRetrieval);\r\n }\r\n if (getValueByPath(fromObject, [\"parallelAiSearch\"]) !== void 0) {\r\n throw new Error(\"parallelAiSearch parameter is not supported in Gemini API.\");\r\n }\r\n const fromUrlContext = getValueByPath(fromObject, [\"urlContext\"]);\r\n if (fromUrlContext != null) {\r\n setValueByPath(toObject, [\"urlContext\"], fromUrlContext);\r\n }\r\n const fromMcpServers = getValueByPath(fromObject, [\"mcpServers\"]);\r\n if (fromMcpServers != null) {\r\n let transformedList = fromMcpServers;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"mcpServers\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction toolToVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromRetrieval = getValueByPath(fromObject, [\"retrieval\"]);\r\n if (fromRetrieval != null) {\r\n setValueByPath(toObject, [\"retrieval\"], fromRetrieval);\r\n }\r\n const fromComputerUse = getValueByPath(fromObject, [\"computerUse\"]);\r\n if (fromComputerUse != null) {\r\n setValueByPath(toObject, [\"computerUse\"], fromComputerUse);\r\n }\r\n if (getValueByPath(fromObject, [\"fileSearch\"]) !== void 0) {\r\n throw new Error(\"fileSearch parameter is not supported in Vertex AI.\");\r\n }\r\n const fromGoogleSearch = getValueByPath(fromObject, [\"googleSearch\"]);\r\n if (fromGoogleSearch != null) {\r\n setValueByPath(toObject, [\"googleSearch\"], fromGoogleSearch);\r\n }\r\n const fromGoogleMaps = getValueByPath(fromObject, [\"googleMaps\"]);\r\n if (fromGoogleMaps != null) {\r\n setValueByPath(toObject, [\"googleMaps\"], fromGoogleMaps);\r\n }\r\n const fromCodeExecution = getValueByPath(fromObject, [\r\n \"codeExecution\"\r\n ]);\r\n if (fromCodeExecution != null) {\r\n setValueByPath(toObject, [\"codeExecution\"], fromCodeExecution);\r\n }\r\n const fromEnterpriseWebSearch = getValueByPath(fromObject, [\r\n \"enterpriseWebSearch\"\r\n ]);\r\n if (fromEnterpriseWebSearch != null) {\r\n setValueByPath(toObject, [\"enterpriseWebSearch\"], fromEnterpriseWebSearch);\r\n }\r\n const fromFunctionDeclarations = getValueByPath(fromObject, [\r\n \"functionDeclarations\"\r\n ]);\r\n if (fromFunctionDeclarations != null) {\r\n let transformedList = fromFunctionDeclarations;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return functionDeclarationToVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"functionDeclarations\"], transformedList);\r\n }\r\n const fromGoogleSearchRetrieval = getValueByPath(fromObject, [\r\n \"googleSearchRetrieval\"\r\n ]);\r\n if (fromGoogleSearchRetrieval != null) {\r\n setValueByPath(toObject, [\"googleSearchRetrieval\"], fromGoogleSearchRetrieval);\r\n }\r\n const fromParallelAiSearch = getValueByPath(fromObject, [\r\n \"parallelAiSearch\"\r\n ]);\r\n if (fromParallelAiSearch != null) {\r\n setValueByPath(toObject, [\"parallelAiSearch\"], fromParallelAiSearch);\r\n }\r\n const fromUrlContext = getValueByPath(fromObject, [\"urlContext\"]);\r\n if (fromUrlContext != null) {\r\n setValueByPath(toObject, [\"urlContext\"], fromUrlContext);\r\n }\r\n if (getValueByPath(fromObject, [\"mcpServers\"]) !== void 0) {\r\n throw new Error(\"mcpServers parameter is not supported in Vertex AI.\");\r\n }\r\n return toObject;\r\n}\r\nfunction tunedModelInfoFromMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromBaseModel = getValueByPath(fromObject, [\"baseModel\"]);\r\n if (fromBaseModel != null) {\r\n setValueByPath(toObject, [\"baseModel\"], fromBaseModel);\r\n }\r\n const fromCreateTime = getValueByPath(fromObject, [\"createTime\"]);\r\n if (fromCreateTime != null) {\r\n setValueByPath(toObject, [\"createTime\"], fromCreateTime);\r\n }\r\n const fromUpdateTime = getValueByPath(fromObject, [\"updateTime\"]);\r\n if (fromUpdateTime != null) {\r\n setValueByPath(toObject, [\"updateTime\"], fromUpdateTime);\r\n }\r\n return toObject;\r\n}\r\nfunction tunedModelInfoFromVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromBaseModel = getValueByPath(fromObject, [\r\n \"labels\",\r\n \"google-vertex-llm-tuning-base-model-id\"\r\n ]);\r\n if (fromBaseModel != null) {\r\n setValueByPath(toObject, [\"baseModel\"], fromBaseModel);\r\n }\r\n const fromCreateTime = getValueByPath(fromObject, [\"createTime\"]);\r\n if (fromCreateTime != null) {\r\n setValueByPath(toObject, [\"createTime\"], fromCreateTime);\r\n }\r\n const fromUpdateTime = getValueByPath(fromObject, [\"updateTime\"]);\r\n if (fromUpdateTime != null) {\r\n setValueByPath(toObject, [\"updateTime\"], fromUpdateTime);\r\n }\r\n return toObject;\r\n}\r\nfunction updateModelConfigToMldev(fromObject, parentObject, _rootObject) {\r\n const toObject = {};\r\n const fromDisplayName = getValueByPath(fromObject, [\"displayName\"]);\r\n if (parentObject !== void 0 && fromDisplayName != null) {\r\n setValueByPath(parentObject, [\"displayName\"], fromDisplayName);\r\n }\r\n const fromDescription = getValueByPath(fromObject, [\"description\"]);\r\n if (parentObject !== void 0 && fromDescription != null) {\r\n setValueByPath(parentObject, [\"description\"], fromDescription);\r\n }\r\n const fromDefaultCheckpointId = getValueByPath(fromObject, [\r\n \"defaultCheckpointId\"\r\n ]);\r\n if (parentObject !== void 0 && fromDefaultCheckpointId != null) {\r\n setValueByPath(parentObject, [\"defaultCheckpointId\"], fromDefaultCheckpointId);\r\n }\r\n return toObject;\r\n}\r\nfunction updateModelConfigToVertex(fromObject, parentObject, _rootObject) {\r\n const toObject = {};\r\n const fromDisplayName = getValueByPath(fromObject, [\"displayName\"]);\r\n if (parentObject !== void 0 && fromDisplayName != null) {\r\n setValueByPath(parentObject, [\"displayName\"], fromDisplayName);\r\n }\r\n const fromDescription = getValueByPath(fromObject, [\"description\"]);\r\n if (parentObject !== void 0 && fromDescription != null) {\r\n setValueByPath(parentObject, [\"description\"], fromDescription);\r\n }\r\n const fromDefaultCheckpointId = getValueByPath(fromObject, [\r\n \"defaultCheckpointId\"\r\n ]);\r\n if (parentObject !== void 0 && fromDefaultCheckpointId != null) {\r\n setValueByPath(parentObject, [\"defaultCheckpointId\"], fromDefaultCheckpointId);\r\n }\r\n return toObject;\r\n}\r\nfunction updateModelParametersToMldev(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], tModel(apiClient, fromModel));\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n updateModelConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction updateModelParametersToVertex(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n updateModelConfigToVertex(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction upscaleImageAPIConfigInternalToVertex(fromObject, parentObject, _rootObject) {\r\n const toObject = {};\r\n const fromOutputGcsUri = getValueByPath(fromObject, [\"outputGcsUri\"]);\r\n if (parentObject !== void 0 && fromOutputGcsUri != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"storageUri\"], fromOutputGcsUri);\r\n }\r\n const fromSafetyFilterLevel = getValueByPath(fromObject, [\r\n \"safetyFilterLevel\"\r\n ]);\r\n if (parentObject !== void 0 && fromSafetyFilterLevel != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"safetySetting\"], fromSafetyFilterLevel);\r\n }\r\n const fromPersonGeneration = getValueByPath(fromObject, [\r\n \"personGeneration\"\r\n ]);\r\n if (parentObject !== void 0 && fromPersonGeneration != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"personGeneration\"], fromPersonGeneration);\r\n }\r\n const fromIncludeRaiReason = getValueByPath(fromObject, [\r\n \"includeRaiReason\"\r\n ]);\r\n if (parentObject !== void 0 && fromIncludeRaiReason != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"includeRaiReason\"], fromIncludeRaiReason);\r\n }\r\n const fromOutputMimeType = getValueByPath(fromObject, [\r\n \"outputMimeType\"\r\n ]);\r\n if (parentObject !== void 0 && fromOutputMimeType != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"outputOptions\", \"mimeType\"], fromOutputMimeType);\r\n }\r\n const fromOutputCompressionQuality = getValueByPath(fromObject, [\r\n \"outputCompressionQuality\"\r\n ]);\r\n if (parentObject !== void 0 && fromOutputCompressionQuality != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"outputOptions\", \"compressionQuality\"], fromOutputCompressionQuality);\r\n }\r\n const fromEnhanceInputImage = getValueByPath(fromObject, [\r\n \"enhanceInputImage\"\r\n ]);\r\n if (parentObject !== void 0 && fromEnhanceInputImage != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"upscaleConfig\", \"enhanceInputImage\"], fromEnhanceInputImage);\r\n }\r\n const fromImagePreservationFactor = getValueByPath(fromObject, [\r\n \"imagePreservationFactor\"\r\n ]);\r\n if (parentObject !== void 0 && fromImagePreservationFactor != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"upscaleConfig\", \"imagePreservationFactor\"], fromImagePreservationFactor);\r\n }\r\n const fromLabels = getValueByPath(fromObject, [\"labels\"]);\r\n if (parentObject !== void 0 && fromLabels != null) {\r\n setValueByPath(parentObject, [\"labels\"], fromLabels);\r\n }\r\n const fromNumberOfImages = getValueByPath(fromObject, [\r\n \"numberOfImages\"\r\n ]);\r\n if (parentObject !== void 0 && fromNumberOfImages != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"sampleCount\"], fromNumberOfImages);\r\n }\r\n const fromMode = getValueByPath(fromObject, [\"mode\"]);\r\n if (parentObject !== void 0 && fromMode != null) {\r\n setValueByPath(parentObject, [\"parameters\", \"mode\"], fromMode);\r\n }\r\n return toObject;\r\n}\r\nfunction upscaleImageAPIParametersInternalToVertex(apiClient, fromObject, rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"_url\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromImage = getValueByPath(fromObject, [\"image\"]);\r\n if (fromImage != null) {\r\n setValueByPath(toObject, [\"instances[0]\", \"image\"], imageToVertex(fromImage));\r\n }\r\n const fromUpscaleFactor = getValueByPath(fromObject, [\r\n \"upscaleFactor\"\r\n ]);\r\n if (fromUpscaleFactor != null) {\r\n setValueByPath(toObject, [\"parameters\", \"upscaleConfig\", \"upscaleFactor\"], fromUpscaleFactor);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n upscaleImageAPIConfigInternalToVertex(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction upscaleImageResponseFromVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromGeneratedImages = getValueByPath(fromObject, [\r\n \"predictions\"\r\n ]);\r\n if (fromGeneratedImages != null) {\r\n let transformedList = fromGeneratedImages;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return generatedImageFromVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"generatedImages\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction videoFromMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromUri = getValueByPath(fromObject, [\"uri\"]);\r\n if (fromUri != null) {\r\n setValueByPath(toObject, [\"uri\"], fromUri);\r\n }\r\n const fromVideoBytes = getValueByPath(fromObject, [\"encodedVideo\"]);\r\n if (fromVideoBytes != null) {\r\n setValueByPath(toObject, [\"videoBytes\"], tBytes(fromVideoBytes));\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"encoding\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction videoFromVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromUri = getValueByPath(fromObject, [\"gcsUri\"]);\r\n if (fromUri != null) {\r\n setValueByPath(toObject, [\"uri\"], fromUri);\r\n }\r\n const fromVideoBytes = getValueByPath(fromObject, [\r\n \"bytesBase64Encoded\"\r\n ]);\r\n if (fromVideoBytes != null) {\r\n setValueByPath(toObject, [\"videoBytes\"], tBytes(fromVideoBytes));\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction videoGenerationMaskToVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromImage = getValueByPath(fromObject, [\"image\"]);\r\n if (fromImage != null) {\r\n setValueByPath(toObject, [\"_self\"], imageToVertex(fromImage));\r\n }\r\n const fromMaskMode = getValueByPath(fromObject, [\"maskMode\"]);\r\n if (fromMaskMode != null) {\r\n setValueByPath(toObject, [\"maskMode\"], fromMaskMode);\r\n }\r\n return toObject;\r\n}\r\nfunction videoGenerationReferenceImageToMldev(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromImage = getValueByPath(fromObject, [\"image\"]);\r\n if (fromImage != null) {\r\n setValueByPath(toObject, [\"image\"], imageToMldev(fromImage));\r\n }\r\n const fromReferenceType = getValueByPath(fromObject, [\r\n \"referenceType\"\r\n ]);\r\n if (fromReferenceType != null) {\r\n setValueByPath(toObject, [\"referenceType\"], fromReferenceType);\r\n }\r\n return toObject;\r\n}\r\nfunction videoGenerationReferenceImageToVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromImage = getValueByPath(fromObject, [\"image\"]);\r\n if (fromImage != null) {\r\n setValueByPath(toObject, [\"image\"], imageToVertex(fromImage));\r\n }\r\n const fromReferenceType = getValueByPath(fromObject, [\r\n \"referenceType\"\r\n ]);\r\n if (fromReferenceType != null) {\r\n setValueByPath(toObject, [\"referenceType\"], fromReferenceType);\r\n }\r\n return toObject;\r\n}\r\nfunction videoToMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromUri = getValueByPath(fromObject, [\"uri\"]);\r\n if (fromUri != null) {\r\n setValueByPath(toObject, [\"uri\"], fromUri);\r\n }\r\n const fromVideoBytes = getValueByPath(fromObject, [\"videoBytes\"]);\r\n if (fromVideoBytes != null) {\r\n setValueByPath(toObject, [\"encodedVideo\"], tBytes(fromVideoBytes));\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"encoding\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction videoToVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromUri = getValueByPath(fromObject, [\"uri\"]);\r\n if (fromUri != null) {\r\n setValueByPath(toObject, [\"gcsUri\"], fromUri);\r\n }\r\n const fromVideoBytes = getValueByPath(fromObject, [\"videoBytes\"]);\r\n if (fromVideoBytes != null) {\r\n setValueByPath(toObject, [\"bytesBase64Encoded\"], tBytes(fromVideoBytes));\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction voiceConfigToVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromReplicatedVoiceConfig = getValueByPath(fromObject, [\r\n \"replicatedVoiceConfig\"\r\n ]);\r\n if (fromReplicatedVoiceConfig != null) {\r\n setValueByPath(toObject, [\"replicatedVoiceConfig\"], replicatedVoiceConfigToVertex(fromReplicatedVoiceConfig));\r\n }\r\n const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [\r\n \"prebuiltVoiceConfig\"\r\n ]);\r\n if (fromPrebuiltVoiceConfig != null) {\r\n setValueByPath(toObject, [\"prebuiltVoiceConfig\"], fromPrebuiltVoiceConfig);\r\n }\r\n return toObject;\r\n}\r\nfunction createFileSearchStoreConfigToMldev(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromDisplayName = getValueByPath(fromObject, [\"displayName\"]);\r\n if (parentObject !== void 0 && fromDisplayName != null) {\r\n setValueByPath(parentObject, [\"displayName\"], fromDisplayName);\r\n }\r\n return toObject;\r\n}\r\nfunction createFileSearchStoreParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n createFileSearchStoreConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction deleteFileSearchStoreConfigToMldev(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromForce = getValueByPath(fromObject, [\"force\"]);\r\n if (parentObject !== void 0 && fromForce != null) {\r\n setValueByPath(parentObject, [\"_query\", \"force\"], fromForce);\r\n }\r\n return toObject;\r\n}\r\nfunction deleteFileSearchStoreParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], fromName);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n deleteFileSearchStoreConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction getFileSearchStoreParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], fromName);\r\n }\r\n return toObject;\r\n}\r\nfunction importFileConfigToMldev(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromCustomMetadata = getValueByPath(fromObject, [\r\n \"customMetadata\"\r\n ]);\r\n if (parentObject !== void 0 && fromCustomMetadata != null) {\r\n let transformedList = fromCustomMetadata;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(parentObject, [\"customMetadata\"], transformedList);\r\n }\r\n const fromChunkingConfig = getValueByPath(fromObject, [\r\n \"chunkingConfig\"\r\n ]);\r\n if (parentObject !== void 0 && fromChunkingConfig != null) {\r\n setValueByPath(parentObject, [\"chunkingConfig\"], fromChunkingConfig);\r\n }\r\n return toObject;\r\n}\r\nfunction importFileOperationFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromMetadata = getValueByPath(fromObject, [\"metadata\"]);\r\n if (fromMetadata != null) {\r\n setValueByPath(toObject, [\"metadata\"], fromMetadata);\r\n }\r\n const fromDone = getValueByPath(fromObject, [\"done\"]);\r\n if (fromDone != null) {\r\n setValueByPath(toObject, [\"done\"], fromDone);\r\n }\r\n const fromError = getValueByPath(fromObject, [\"error\"]);\r\n if (fromError != null) {\r\n setValueByPath(toObject, [\"error\"], fromError);\r\n }\r\n const fromResponse = getValueByPath(fromObject, [\"response\"]);\r\n if (fromResponse != null) {\r\n setValueByPath(toObject, [\"response\"], importFileResponseFromMldev(fromResponse));\r\n }\r\n return toObject;\r\n}\r\nfunction importFileParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromFileSearchStoreName = getValueByPath(fromObject, [\r\n \"fileSearchStoreName\"\r\n ]);\r\n if (fromFileSearchStoreName != null) {\r\n setValueByPath(toObject, [\"_url\", \"file_search_store_name\"], fromFileSearchStoreName);\r\n }\r\n const fromFileName = getValueByPath(fromObject, [\"fileName\"]);\r\n if (fromFileName != null) {\r\n setValueByPath(toObject, [\"fileName\"], fromFileName);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n importFileConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction importFileResponseFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromParent = getValueByPath(fromObject, [\"parent\"]);\r\n if (fromParent != null) {\r\n setValueByPath(toObject, [\"parent\"], fromParent);\r\n }\r\n const fromDocumentName = getValueByPath(fromObject, [\"documentName\"]);\r\n if (fromDocumentName != null) {\r\n setValueByPath(toObject, [\"documentName\"], fromDocumentName);\r\n }\r\n return toObject;\r\n}\r\nfunction listFileSearchStoresConfigToMldev(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromPageSize = getValueByPath(fromObject, [\"pageSize\"]);\r\n if (parentObject !== void 0 && fromPageSize != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageSize\"], fromPageSize);\r\n }\r\n const fromPageToken = getValueByPath(fromObject, [\"pageToken\"]);\r\n if (parentObject !== void 0 && fromPageToken != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageToken\"], fromPageToken);\r\n }\r\n return toObject;\r\n}\r\nfunction listFileSearchStoresParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n listFileSearchStoresConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction listFileSearchStoresResponseFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromNextPageToken = getValueByPath(fromObject, [\r\n \"nextPageToken\"\r\n ]);\r\n if (fromNextPageToken != null) {\r\n setValueByPath(toObject, [\"nextPageToken\"], fromNextPageToken);\r\n }\r\n const fromFileSearchStores = getValueByPath(fromObject, [\r\n \"fileSearchStores\"\r\n ]);\r\n if (fromFileSearchStores != null) {\r\n let transformedList = fromFileSearchStores;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"fileSearchStores\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction uploadToFileSearchStoreConfigToMldev(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (parentObject !== void 0 && fromMimeType != null) {\r\n setValueByPath(parentObject, [\"mimeType\"], fromMimeType);\r\n }\r\n const fromDisplayName = getValueByPath(fromObject, [\"displayName\"]);\r\n if (parentObject !== void 0 && fromDisplayName != null) {\r\n setValueByPath(parentObject, [\"displayName\"], fromDisplayName);\r\n }\r\n const fromCustomMetadata = getValueByPath(fromObject, [\r\n \"customMetadata\"\r\n ]);\r\n if (parentObject !== void 0 && fromCustomMetadata != null) {\r\n let transformedList = fromCustomMetadata;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(parentObject, [\"customMetadata\"], transformedList);\r\n }\r\n const fromChunkingConfig = getValueByPath(fromObject, [\r\n \"chunkingConfig\"\r\n ]);\r\n if (parentObject !== void 0 && fromChunkingConfig != null) {\r\n setValueByPath(parentObject, [\"chunkingConfig\"], fromChunkingConfig);\r\n }\r\n return toObject;\r\n}\r\nfunction uploadToFileSearchStoreParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromFileSearchStoreName = getValueByPath(fromObject, [\r\n \"fileSearchStoreName\"\r\n ]);\r\n if (fromFileSearchStoreName != null) {\r\n setValueByPath(toObject, [\"_url\", \"file_search_store_name\"], fromFileSearchStoreName);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n uploadToFileSearchStoreConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction uploadToFileSearchStoreResumableResponseFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n return toObject;\r\n}\r\nasync function throwErrorIfNotOK(response) {\r\n var _a2;\r\n if (response === void 0) {\r\n throw new Error(\"response is undefined\");\r\n }\r\n if (!response.ok) {\r\n const status = response.status;\r\n let errorBody;\r\n if ((_a2 = response.headers.get(\"content-type\")) === null || _a2 === void 0 ? void 0 : _a2.includes(\"application/json\")) {\r\n errorBody = await response.json();\r\n } else {\r\n errorBody = {\r\n error: {\r\n message: await response.text(),\r\n code: response.status,\r\n status: response.statusText\r\n }\r\n };\r\n }\r\n const errorMessage = JSON.stringify(errorBody);\r\n if (status >= 400 && status < 600) {\r\n const apiError = new ApiError({\r\n message: errorMessage,\r\n status\r\n });\r\n throw apiError;\r\n }\r\n throw new Error(errorMessage);\r\n }\r\n}\r\nfunction includeExtraBodyToRequestInit(requestInit, extraBody) {\r\n if (!extraBody || Object.keys(extraBody).length === 0) {\r\n return;\r\n }\r\n if (requestInit.body instanceof Blob) {\r\n console.warn(\"includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.\");\r\n return;\r\n }\r\n let currentBodyObject = {};\r\n if (typeof requestInit.body === \"string\" && requestInit.body.length > 0) {\r\n try {\r\n const parsedBody = JSON.parse(requestInit.body);\r\n if (typeof parsedBody === \"object\" && parsedBody !== null && !Array.isArray(parsedBody)) {\r\n currentBodyObject = parsedBody;\r\n } else {\r\n console.warn(\"includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.\");\r\n return;\r\n }\r\n } catch (e) {\r\n console.warn(\"includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.\");\r\n return;\r\n }\r\n }\r\n function deepMerge(target, source) {\r\n const output = Object.assign({}, target);\r\n for (const key in source) {\r\n if (Object.prototype.hasOwnProperty.call(source, key)) {\r\n const sourceValue = source[key];\r\n const targetValue = output[key];\r\n if (sourceValue && typeof sourceValue === \"object\" && !Array.isArray(sourceValue) && targetValue && typeof targetValue === \"object\" && !Array.isArray(targetValue)) {\r\n output[key] = deepMerge(targetValue, sourceValue);\r\n } else {\r\n if (targetValue && sourceValue && typeof targetValue !== typeof sourceValue) {\r\n console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key \"${key}\". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`);\r\n }\r\n output[key] = sourceValue;\r\n }\r\n }\r\n }\r\n return output;\r\n }\r\n const mergedBody = deepMerge(currentBodyObject, extraBody);\r\n requestInit.body = JSON.stringify(mergedBody);\r\n}\r\nfunction hasMcpToolUsage(tools) {\r\n for (const tool of tools) {\r\n if (isMcpCallableTool(tool)) {\r\n return true;\r\n }\r\n if (typeof tool === \"object\" && \"inputSchema\" in tool) {\r\n return true;\r\n }\r\n }\r\n return hasMcpToolUsageFromMcpToTool;\r\n}\r\nfunction setMcpUsageHeader(headers) {\r\n var _a2;\r\n const existingHeader = (_a2 = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a2 !== void 0 ? _a2 : \"\";\r\n headers[GOOGLE_API_CLIENT_HEADER] = (existingHeader + ` ${MCP_LABEL}`).trimStart();\r\n}\r\nfunction isMcpCallableTool(object) {\r\n return object !== null && typeof object === \"object\" && object instanceof McpCallableTool;\r\n}\r\nfunction listAllTools(mcpClient_1) {\r\n return __asyncGenerator(this, arguments, function* listAllTools_1(mcpClient, maxTools = 100) {\r\n let cursor = void 0;\r\n let numTools = 0;\r\n while (numTools < maxTools) {\r\n const t = yield __await(mcpClient.listTools({ cursor }));\r\n for (const tool of t.tools) {\r\n yield yield __await(tool);\r\n numTools++;\r\n }\r\n if (!t.nextCursor) {\r\n break;\r\n }\r\n cursor = t.nextCursor;\r\n }\r\n });\r\n}\r\nfunction isMcpClient(client) {\r\n return client !== null && typeof client === \"object\" && \"listTools\" in client && typeof client.listTools === \"function\";\r\n}\r\nfunction mcpToTool(...args) {\r\n hasMcpToolUsageFromMcpToTool = true;\r\n if (args.length === 0) {\r\n throw new Error(\"No MCP clients provided\");\r\n }\r\n const maybeConfig = args[args.length - 1];\r\n if (isMcpClient(maybeConfig)) {\r\n return McpCallableTool.create(args, {});\r\n }\r\n return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig);\r\n}\r\nasync function handleWebSocketMessage$1(apiClient, onmessage, event) {\r\n const serverMessage = new LiveMusicServerMessage();\r\n let data;\r\n if (event.data instanceof Blob) {\r\n data = JSON.parse(await event.data.text());\r\n } else {\r\n data = JSON.parse(event.data);\r\n }\r\n Object.assign(serverMessage, data);\r\n onmessage(serverMessage);\r\n}\r\nfunction headersToMap$1(headers) {\r\n const headerMap = {};\r\n headers.forEach((value, key) => {\r\n headerMap[key] = value;\r\n });\r\n return headerMap;\r\n}\r\nfunction mapToHeaders$1(map) {\r\n const headers = new Headers();\r\n for (const [key, value] of Object.entries(map)) {\r\n headers.append(key, value);\r\n }\r\n return headers;\r\n}\r\nasync function handleWebSocketMessage(apiClient, onmessage, event) {\r\n const serverMessage = new LiveServerMessage();\r\n let jsonData;\r\n if (event.data instanceof Blob) {\r\n jsonData = await event.data.text();\r\n } else if (event.data instanceof ArrayBuffer) {\r\n jsonData = new TextDecoder().decode(event.data);\r\n } else {\r\n jsonData = event.data;\r\n }\r\n const data = JSON.parse(jsonData);\r\n if (apiClient.isVertexAI()) {\r\n const resp = liveServerMessageFromVertex(data);\r\n Object.assign(serverMessage, resp);\r\n } else {\r\n const resp = data;\r\n Object.assign(serverMessage, resp);\r\n }\r\n onmessage(serverMessage);\r\n}\r\nfunction headersToMap(headers) {\r\n const headerMap = {};\r\n headers.forEach((value, key) => {\r\n headerMap[key] = value;\r\n });\r\n return headerMap;\r\n}\r\nfunction mapToHeaders(map) {\r\n const headers = new Headers();\r\n for (const [key, value] of Object.entries(map)) {\r\n headers.append(key, value);\r\n }\r\n return headers;\r\n}\r\nfunction shouldDisableAfc(config) {\r\n var _a2, _b, _c;\r\n if ((_a2 = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a2 === void 0 ? void 0 : _a2.disable) {\r\n return true;\r\n }\r\n let callableToolsPresent = false;\r\n for (const tool of (_b = config === null || config === void 0 ? void 0 : config.tools) !== null && _b !== void 0 ? _b : []) {\r\n if (isCallableTool(tool)) {\r\n callableToolsPresent = true;\r\n break;\r\n }\r\n }\r\n if (!callableToolsPresent) {\r\n return true;\r\n }\r\n const maxCalls = (_c = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _c === void 0 ? void 0 : _c.maximumRemoteCalls;\r\n if (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls)) || maxCalls == 0) {\r\n console.warn(\"Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:\", maxCalls);\r\n return true;\r\n }\r\n return false;\r\n}\r\nfunction isCallableTool(tool) {\r\n return \"callTool\" in tool && typeof tool.callTool === \"function\";\r\n}\r\nfunction hasCallableTools(params) {\r\n var _a2, _b, _c;\r\n return (_c = (_b = (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 ? _c : false;\r\n}\r\nfunction findAfcIncompatibleToolIndexes(params) {\r\n var _a2;\r\n const afcIncompatibleToolIndexes = [];\r\n if (!((_a2 = params === null || params === void 0 ? void 0 : params.config) === null || _a2 === void 0 ? void 0 : _a2.tools)) {\r\n return afcIncompatibleToolIndexes;\r\n }\r\n params.config.tools.forEach((tool, index) => {\r\n if (isCallableTool(tool)) {\r\n return;\r\n }\r\n const geminiTool = tool;\r\n if (geminiTool.functionDeclarations && geminiTool.functionDeclarations.length > 0) {\r\n afcIncompatibleToolIndexes.push(index);\r\n }\r\n });\r\n return afcIncompatibleToolIndexes;\r\n}\r\nfunction shouldAppendAfcHistory(config) {\r\n var _a2;\r\n return !((_a2 = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a2 === void 0 ? void 0 : _a2.ignoreCallHistory);\r\n}\r\nfunction audioTranscriptionConfigToMldev(fromObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"languageCodes\"]) !== void 0) {\r\n throw new Error(\"languageCodes parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction authConfigToMldev(fromObject) {\r\n const toObject = {};\r\n const fromApiKey = getValueByPath(fromObject, [\"apiKey\"]);\r\n if (fromApiKey != null) {\r\n setValueByPath(toObject, [\"apiKey\"], fromApiKey);\r\n }\r\n if (getValueByPath(fromObject, [\"apiKeyConfig\"]) !== void 0) {\r\n throw new Error(\"apiKeyConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"authType\"]) !== void 0) {\r\n throw new Error(\"authType parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"googleServiceAccountConfig\"]) !== void 0) {\r\n throw new Error(\"googleServiceAccountConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"httpBasicAuthConfig\"]) !== void 0) {\r\n throw new Error(\"httpBasicAuthConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"oauthConfig\"]) !== void 0) {\r\n throw new Error(\"oauthConfig parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"oidcConfig\"]) !== void 0) {\r\n throw new Error(\"oidcConfig parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction blobToMldev(fromObject) {\r\n const toObject = {};\r\n const fromData = getValueByPath(fromObject, [\"data\"]);\r\n if (fromData != null) {\r\n setValueByPath(toObject, [\"data\"], fromData);\r\n }\r\n if (getValueByPath(fromObject, [\"displayName\"]) !== void 0) {\r\n throw new Error(\"displayName parameter is not supported in Gemini API.\");\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction contentToMldev(fromObject) {\r\n const toObject = {};\r\n const fromParts = getValueByPath(fromObject, [\"parts\"]);\r\n if (fromParts != null) {\r\n let transformedList = fromParts;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return partToMldev(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"parts\"], transformedList);\r\n }\r\n const fromRole = getValueByPath(fromObject, [\"role\"]);\r\n if (fromRole != null) {\r\n setValueByPath(toObject, [\"role\"], fromRole);\r\n }\r\n return toObject;\r\n}\r\nfunction createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) {\r\n const toObject = {};\r\n const fromExpireTime = getValueByPath(fromObject, [\"expireTime\"]);\r\n if (parentObject !== void 0 && fromExpireTime != null) {\r\n setValueByPath(parentObject, [\"expireTime\"], fromExpireTime);\r\n }\r\n const fromNewSessionExpireTime = getValueByPath(fromObject, [\r\n \"newSessionExpireTime\"\r\n ]);\r\n if (parentObject !== void 0 && fromNewSessionExpireTime != null) {\r\n setValueByPath(parentObject, [\"newSessionExpireTime\"], fromNewSessionExpireTime);\r\n }\r\n const fromUses = getValueByPath(fromObject, [\"uses\"]);\r\n if (parentObject !== void 0 && fromUses != null) {\r\n setValueByPath(parentObject, [\"uses\"], fromUses);\r\n }\r\n const fromLiveConnectConstraints = getValueByPath(fromObject, [\r\n \"liveConnectConstraints\"\r\n ]);\r\n if (parentObject !== void 0 && fromLiveConnectConstraints != null) {\r\n setValueByPath(parentObject, [\"bidiGenerateContentSetup\"], liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints));\r\n }\r\n const fromLockAdditionalFields = getValueByPath(fromObject, [\r\n \"lockAdditionalFields\"\r\n ]);\r\n if (parentObject !== void 0 && fromLockAdditionalFields != null) {\r\n setValueByPath(parentObject, [\"fieldMask\"], fromLockAdditionalFields);\r\n }\r\n return toObject;\r\n}\r\nfunction createAuthTokenParametersToMldev(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n setValueByPath(toObject, [\"config\"], createAuthTokenConfigToMldev(apiClient, fromConfig, toObject));\r\n }\r\n return toObject;\r\n}\r\nfunction fileDataToMldev(fromObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"displayName\"]) !== void 0) {\r\n throw new Error(\"displayName parameter is not supported in Gemini API.\");\r\n }\r\n const fromFileUri = getValueByPath(fromObject, [\"fileUri\"]);\r\n if (fromFileUri != null) {\r\n setValueByPath(toObject, [\"fileUri\"], fromFileUri);\r\n }\r\n const fromMimeType = getValueByPath(fromObject, [\"mimeType\"]);\r\n if (fromMimeType != null) {\r\n setValueByPath(toObject, [\"mimeType\"], fromMimeType);\r\n }\r\n return toObject;\r\n}\r\nfunction functionCallToMldev(fromObject) {\r\n const toObject = {};\r\n const fromId = getValueByPath(fromObject, [\"id\"]);\r\n if (fromId != null) {\r\n setValueByPath(toObject, [\"id\"], fromId);\r\n }\r\n const fromArgs = getValueByPath(fromObject, [\"args\"]);\r\n if (fromArgs != null) {\r\n setValueByPath(toObject, [\"args\"], fromArgs);\r\n }\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n if (getValueByPath(fromObject, [\"partialArgs\"]) !== void 0) {\r\n throw new Error(\"partialArgs parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"willContinue\"]) !== void 0) {\r\n throw new Error(\"willContinue parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction googleMapsToMldev(fromObject) {\r\n const toObject = {};\r\n const fromAuthConfig = getValueByPath(fromObject, [\"authConfig\"]);\r\n if (fromAuthConfig != null) {\r\n setValueByPath(toObject, [\"authConfig\"], authConfigToMldev(fromAuthConfig));\r\n }\r\n const fromEnableWidget = getValueByPath(fromObject, [\"enableWidget\"]);\r\n if (fromEnableWidget != null) {\r\n setValueByPath(toObject, [\"enableWidget\"], fromEnableWidget);\r\n }\r\n return toObject;\r\n}\r\nfunction googleSearchToMldev(fromObject) {\r\n const toObject = {};\r\n const fromSearchTypes = getValueByPath(fromObject, [\"searchTypes\"]);\r\n if (fromSearchTypes != null) {\r\n setValueByPath(toObject, [\"searchTypes\"], fromSearchTypes);\r\n }\r\n if (getValueByPath(fromObject, [\"blockingConfidence\"]) !== void 0) {\r\n throw new Error(\"blockingConfidence parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"excludeDomains\"]) !== void 0) {\r\n throw new Error(\"excludeDomains parameter is not supported in Gemini API.\");\r\n }\r\n const fromTimeRangeFilter = getValueByPath(fromObject, [\r\n \"timeRangeFilter\"\r\n ]);\r\n if (fromTimeRangeFilter != null) {\r\n setValueByPath(toObject, [\"timeRangeFilter\"], fromTimeRangeFilter);\r\n }\r\n return toObject;\r\n}\r\nfunction liveConnectConfigToMldev(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromGenerationConfig = getValueByPath(fromObject, [\r\n \"generationConfig\"\r\n ]);\r\n if (parentObject !== void 0 && fromGenerationConfig != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\"], fromGenerationConfig);\r\n }\r\n const fromResponseModalities = getValueByPath(fromObject, [\r\n \"responseModalities\"\r\n ]);\r\n if (parentObject !== void 0 && fromResponseModalities != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"responseModalities\"], fromResponseModalities);\r\n }\r\n const fromTemperature = getValueByPath(fromObject, [\"temperature\"]);\r\n if (parentObject !== void 0 && fromTemperature != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"temperature\"], fromTemperature);\r\n }\r\n const fromTopP = getValueByPath(fromObject, [\"topP\"]);\r\n if (parentObject !== void 0 && fromTopP != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"topP\"], fromTopP);\r\n }\r\n const fromTopK = getValueByPath(fromObject, [\"topK\"]);\r\n if (parentObject !== void 0 && fromTopK != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"topK\"], fromTopK);\r\n }\r\n const fromMaxOutputTokens = getValueByPath(fromObject, [\r\n \"maxOutputTokens\"\r\n ]);\r\n if (parentObject !== void 0 && fromMaxOutputTokens != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"maxOutputTokens\"], fromMaxOutputTokens);\r\n }\r\n const fromMediaResolution = getValueByPath(fromObject, [\r\n \"mediaResolution\"\r\n ]);\r\n if (parentObject !== void 0 && fromMediaResolution != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"mediaResolution\"], fromMediaResolution);\r\n }\r\n const fromSeed = getValueByPath(fromObject, [\"seed\"]);\r\n if (parentObject !== void 0 && fromSeed != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"seed\"], fromSeed);\r\n }\r\n const fromSpeechConfig = getValueByPath(fromObject, [\"speechConfig\"]);\r\n if (parentObject !== void 0 && fromSpeechConfig != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"speechConfig\"], tLiveSpeechConfig(fromSpeechConfig));\r\n }\r\n const fromThinkingConfig = getValueByPath(fromObject, [\r\n \"thinkingConfig\"\r\n ]);\r\n if (parentObject !== void 0 && fromThinkingConfig != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"thinkingConfig\"], fromThinkingConfig);\r\n }\r\n const fromEnableAffectiveDialog = getValueByPath(fromObject, [\r\n \"enableAffectiveDialog\"\r\n ]);\r\n if (parentObject !== void 0 && fromEnableAffectiveDialog != null) {\r\n setValueByPath(parentObject, [\"setup\", \"generationConfig\", \"enableAffectiveDialog\"], fromEnableAffectiveDialog);\r\n }\r\n const fromSystemInstruction = getValueByPath(fromObject, [\r\n \"systemInstruction\"\r\n ]);\r\n if (parentObject !== void 0 && fromSystemInstruction != null) {\r\n setValueByPath(parentObject, [\"setup\", \"systemInstruction\"], contentToMldev(tContent(fromSystemInstruction)));\r\n }\r\n const fromTools = getValueByPath(fromObject, [\"tools\"]);\r\n if (parentObject !== void 0 && fromTools != null) {\r\n let transformedList = tTools(fromTools);\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return toolToMldev(tTool(item));\r\n });\r\n }\r\n setValueByPath(parentObject, [\"setup\", \"tools\"], transformedList);\r\n }\r\n const fromSessionResumption = getValueByPath(fromObject, [\r\n \"sessionResumption\"\r\n ]);\r\n if (parentObject !== void 0 && fromSessionResumption != null) {\r\n setValueByPath(parentObject, [\"setup\", \"sessionResumption\"], sessionResumptionConfigToMldev(fromSessionResumption));\r\n }\r\n const fromInputAudioTranscription = getValueByPath(fromObject, [\r\n \"inputAudioTranscription\"\r\n ]);\r\n if (parentObject !== void 0 && fromInputAudioTranscription != null) {\r\n setValueByPath(parentObject, [\"setup\", \"inputAudioTranscription\"], audioTranscriptionConfigToMldev(fromInputAudioTranscription));\r\n }\r\n const fromOutputAudioTranscription = getValueByPath(fromObject, [\r\n \"outputAudioTranscription\"\r\n ]);\r\n if (parentObject !== void 0 && fromOutputAudioTranscription != null) {\r\n setValueByPath(parentObject, [\"setup\", \"outputAudioTranscription\"], audioTranscriptionConfigToMldev(fromOutputAudioTranscription));\r\n }\r\n const fromRealtimeInputConfig = getValueByPath(fromObject, [\r\n \"realtimeInputConfig\"\r\n ]);\r\n if (parentObject !== void 0 && fromRealtimeInputConfig != null) {\r\n setValueByPath(parentObject, [\"setup\", \"realtimeInputConfig\"], fromRealtimeInputConfig);\r\n }\r\n const fromContextWindowCompression = getValueByPath(fromObject, [\r\n \"contextWindowCompression\"\r\n ]);\r\n if (parentObject !== void 0 && fromContextWindowCompression != null) {\r\n setValueByPath(parentObject, [\"setup\", \"contextWindowCompression\"], fromContextWindowCompression);\r\n }\r\n const fromProactivity = getValueByPath(fromObject, [\"proactivity\"]);\r\n if (parentObject !== void 0 && fromProactivity != null) {\r\n setValueByPath(parentObject, [\"setup\", \"proactivity\"], fromProactivity);\r\n }\r\n if (getValueByPath(fromObject, [\"explicitVadSignal\"]) !== void 0) {\r\n throw new Error(\"explicitVadSignal parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction liveConnectConstraintsToMldev(apiClient, fromObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"model\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"setup\", \"model\"], tModel(apiClient, fromModel));\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n setValueByPath(toObject, [\"config\"], liveConnectConfigToMldev(fromConfig, toObject));\r\n }\r\n return toObject;\r\n}\r\nfunction partToMldev(fromObject) {\r\n const toObject = {};\r\n const fromMediaResolution = getValueByPath(fromObject, [\r\n \"mediaResolution\"\r\n ]);\r\n if (fromMediaResolution != null) {\r\n setValueByPath(toObject, [\"mediaResolution\"], fromMediaResolution);\r\n }\r\n const fromCodeExecutionResult = getValueByPath(fromObject, [\r\n \"codeExecutionResult\"\r\n ]);\r\n if (fromCodeExecutionResult != null) {\r\n setValueByPath(toObject, [\"codeExecutionResult\"], fromCodeExecutionResult);\r\n }\r\n const fromExecutableCode = getValueByPath(fromObject, [\r\n \"executableCode\"\r\n ]);\r\n if (fromExecutableCode != null) {\r\n setValueByPath(toObject, [\"executableCode\"], fromExecutableCode);\r\n }\r\n const fromFileData = getValueByPath(fromObject, [\"fileData\"]);\r\n if (fromFileData != null) {\r\n setValueByPath(toObject, [\"fileData\"], fileDataToMldev(fromFileData));\r\n }\r\n const fromFunctionCall = getValueByPath(fromObject, [\"functionCall\"]);\r\n if (fromFunctionCall != null) {\r\n setValueByPath(toObject, [\"functionCall\"], functionCallToMldev(fromFunctionCall));\r\n }\r\n const fromFunctionResponse = getValueByPath(fromObject, [\r\n \"functionResponse\"\r\n ]);\r\n if (fromFunctionResponse != null) {\r\n setValueByPath(toObject, [\"functionResponse\"], fromFunctionResponse);\r\n }\r\n const fromInlineData = getValueByPath(fromObject, [\"inlineData\"]);\r\n if (fromInlineData != null) {\r\n setValueByPath(toObject, [\"inlineData\"], blobToMldev(fromInlineData));\r\n }\r\n const fromText = getValueByPath(fromObject, [\"text\"]);\r\n if (fromText != null) {\r\n setValueByPath(toObject, [\"text\"], fromText);\r\n }\r\n const fromThought = getValueByPath(fromObject, [\"thought\"]);\r\n if (fromThought != null) {\r\n setValueByPath(toObject, [\"thought\"], fromThought);\r\n }\r\n const fromThoughtSignature = getValueByPath(fromObject, [\r\n \"thoughtSignature\"\r\n ]);\r\n if (fromThoughtSignature != null) {\r\n setValueByPath(toObject, [\"thoughtSignature\"], fromThoughtSignature);\r\n }\r\n const fromVideoMetadata = getValueByPath(fromObject, [\r\n \"videoMetadata\"\r\n ]);\r\n if (fromVideoMetadata != null) {\r\n setValueByPath(toObject, [\"videoMetadata\"], fromVideoMetadata);\r\n }\r\n const fromToolCall = getValueByPath(fromObject, [\"toolCall\"]);\r\n if (fromToolCall != null) {\r\n setValueByPath(toObject, [\"toolCall\"], fromToolCall);\r\n }\r\n const fromToolResponse = getValueByPath(fromObject, [\"toolResponse\"]);\r\n if (fromToolResponse != null) {\r\n setValueByPath(toObject, [\"toolResponse\"], fromToolResponse);\r\n }\r\n const fromPartMetadata = getValueByPath(fromObject, [\"partMetadata\"]);\r\n if (fromPartMetadata != null) {\r\n setValueByPath(toObject, [\"partMetadata\"], fromPartMetadata);\r\n }\r\n return toObject;\r\n}\r\nfunction sessionResumptionConfigToMldev(fromObject) {\r\n const toObject = {};\r\n const fromHandle = getValueByPath(fromObject, [\"handle\"]);\r\n if (fromHandle != null) {\r\n setValueByPath(toObject, [\"handle\"], fromHandle);\r\n }\r\n if (getValueByPath(fromObject, [\"transparent\"]) !== void 0) {\r\n throw new Error(\"transparent parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction toolToMldev(fromObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"retrieval\"]) !== void 0) {\r\n throw new Error(\"retrieval parameter is not supported in Gemini API.\");\r\n }\r\n const fromComputerUse = getValueByPath(fromObject, [\"computerUse\"]);\r\n if (fromComputerUse != null) {\r\n setValueByPath(toObject, [\"computerUse\"], fromComputerUse);\r\n }\r\n const fromFileSearch = getValueByPath(fromObject, [\"fileSearch\"]);\r\n if (fromFileSearch != null) {\r\n setValueByPath(toObject, [\"fileSearch\"], fromFileSearch);\r\n }\r\n const fromGoogleSearch = getValueByPath(fromObject, [\"googleSearch\"]);\r\n if (fromGoogleSearch != null) {\r\n setValueByPath(toObject, [\"googleSearch\"], googleSearchToMldev(fromGoogleSearch));\r\n }\r\n const fromGoogleMaps = getValueByPath(fromObject, [\"googleMaps\"]);\r\n if (fromGoogleMaps != null) {\r\n setValueByPath(toObject, [\"googleMaps\"], googleMapsToMldev(fromGoogleMaps));\r\n }\r\n const fromCodeExecution = getValueByPath(fromObject, [\r\n \"codeExecution\"\r\n ]);\r\n if (fromCodeExecution != null) {\r\n setValueByPath(toObject, [\"codeExecution\"], fromCodeExecution);\r\n }\r\n if (getValueByPath(fromObject, [\"enterpriseWebSearch\"]) !== void 0) {\r\n throw new Error(\"enterpriseWebSearch parameter is not supported in Gemini API.\");\r\n }\r\n const fromFunctionDeclarations = getValueByPath(fromObject, [\r\n \"functionDeclarations\"\r\n ]);\r\n if (fromFunctionDeclarations != null) {\r\n let transformedList = fromFunctionDeclarations;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"functionDeclarations\"], transformedList);\r\n }\r\n const fromGoogleSearchRetrieval = getValueByPath(fromObject, [\r\n \"googleSearchRetrieval\"\r\n ]);\r\n if (fromGoogleSearchRetrieval != null) {\r\n setValueByPath(toObject, [\"googleSearchRetrieval\"], fromGoogleSearchRetrieval);\r\n }\r\n if (getValueByPath(fromObject, [\"parallelAiSearch\"]) !== void 0) {\r\n throw new Error(\"parallelAiSearch parameter is not supported in Gemini API.\");\r\n }\r\n const fromUrlContext = getValueByPath(fromObject, [\"urlContext\"]);\r\n if (fromUrlContext != null) {\r\n setValueByPath(toObject, [\"urlContext\"], fromUrlContext);\r\n }\r\n const fromMcpServers = getValueByPath(fromObject, [\"mcpServers\"]);\r\n if (fromMcpServers != null) {\r\n let transformedList = fromMcpServers;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"mcpServers\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction getFieldMasks(setup) {\r\n const fields = [];\r\n for (const key in setup) {\r\n if (Object.prototype.hasOwnProperty.call(setup, key)) {\r\n const value = setup[key];\r\n if (typeof value === \"object\" && value != null && Object.keys(value).length > 0) {\r\n const field = Object.keys(value).map((kk) => `${key}.${kk}`);\r\n fields.push(...field);\r\n } else {\r\n fields.push(key);\r\n }\r\n }\r\n }\r\n return fields.join(\",\");\r\n}\r\nfunction convertBidiSetupToTokenSetup(requestDict, config) {\r\n let setupForMaskGeneration = null;\r\n const bidiGenerateContentSetupValue = requestDict[\"bidiGenerateContentSetup\"];\r\n if (typeof bidiGenerateContentSetupValue === \"object\" && bidiGenerateContentSetupValue !== null && \"setup\" in bidiGenerateContentSetupValue) {\r\n const innerSetup = bidiGenerateContentSetupValue.setup;\r\n if (typeof innerSetup === \"object\" && innerSetup !== null) {\r\n requestDict[\"bidiGenerateContentSetup\"] = innerSetup;\r\n setupForMaskGeneration = innerSetup;\r\n } else {\r\n delete requestDict[\"bidiGenerateContentSetup\"];\r\n }\r\n } else if (bidiGenerateContentSetupValue !== void 0) {\r\n delete requestDict[\"bidiGenerateContentSetup\"];\r\n }\r\n const preExistingFieldMask = requestDict[\"fieldMask\"];\r\n if (setupForMaskGeneration) {\r\n const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration);\r\n if (Array.isArray(config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && (config === null || config === void 0 ? void 0 : config.lockAdditionalFields.length) === 0) {\r\n if (generatedMaskFromBidi) {\r\n requestDict[\"fieldMask\"] = generatedMaskFromBidi;\r\n } else {\r\n delete requestDict[\"fieldMask\"];\r\n }\r\n } else if ((config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && config.lockAdditionalFields.length > 0 && preExistingFieldMask !== null && Array.isArray(preExistingFieldMask) && preExistingFieldMask.length > 0) {\r\n const generationConfigFields = [\r\n \"temperature\",\r\n \"topK\",\r\n \"topP\",\r\n \"maxOutputTokens\",\r\n \"responseModalities\",\r\n \"seed\",\r\n \"speechConfig\"\r\n ];\r\n let mappedFieldsFromPreExisting = [];\r\n if (preExistingFieldMask.length > 0) {\r\n mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => {\r\n if (generationConfigFields.includes(field)) {\r\n return `generationConfig.${field}`;\r\n }\r\n return field;\r\n });\r\n }\r\n const finalMaskParts = [];\r\n if (generatedMaskFromBidi) {\r\n finalMaskParts.push(generatedMaskFromBidi);\r\n }\r\n if (mappedFieldsFromPreExisting.length > 0) {\r\n finalMaskParts.push(...mappedFieldsFromPreExisting);\r\n }\r\n if (finalMaskParts.length > 0) {\r\n requestDict[\"fieldMask\"] = finalMaskParts.join(\",\");\r\n } else {\r\n delete requestDict[\"fieldMask\"];\r\n }\r\n } else {\r\n delete requestDict[\"fieldMask\"];\r\n }\r\n } else {\r\n if (preExistingFieldMask !== null && Array.isArray(preExistingFieldMask) && preExistingFieldMask.length > 0) {\r\n requestDict[\"fieldMask\"] = preExistingFieldMask.join(\",\");\r\n } else {\r\n delete requestDict[\"fieldMask\"];\r\n }\r\n }\r\n return requestDict;\r\n}\r\nfunction deleteDocumentConfigToMldev(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromForce = getValueByPath(fromObject, [\"force\"]);\r\n if (parentObject !== void 0 && fromForce != null) {\r\n setValueByPath(parentObject, [\"_query\", \"force\"], fromForce);\r\n }\r\n return toObject;\r\n}\r\nfunction deleteDocumentParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], fromName);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n deleteDocumentConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction getDocumentParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], fromName);\r\n }\r\n return toObject;\r\n}\r\nfunction listDocumentsConfigToMldev(fromObject, parentObject) {\r\n const toObject = {};\r\n const fromPageSize = getValueByPath(fromObject, [\"pageSize\"]);\r\n if (parentObject !== void 0 && fromPageSize != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageSize\"], fromPageSize);\r\n }\r\n const fromPageToken = getValueByPath(fromObject, [\"pageToken\"]);\r\n if (parentObject !== void 0 && fromPageToken != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageToken\"], fromPageToken);\r\n }\r\n return toObject;\r\n}\r\nfunction listDocumentsParametersToMldev(fromObject) {\r\n const toObject = {};\r\n const fromParent = getValueByPath(fromObject, [\"parent\"]);\r\n if (fromParent != null) {\r\n setValueByPath(toObject, [\"_url\", \"parent\"], fromParent);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n listDocumentsConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction listDocumentsResponseFromMldev(fromObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromNextPageToken = getValueByPath(fromObject, [\r\n \"nextPageToken\"\r\n ]);\r\n if (fromNextPageToken != null) {\r\n setValueByPath(toObject, [\"nextPageToken\"], fromNextPageToken);\r\n }\r\n const fromDocuments = getValueByPath(fromObject, [\"documents\"]);\r\n if (fromDocuments != null) {\r\n let transformedList = fromDocuments;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"documents\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction isAbortError(err) {\r\n return typeof err === \"object\" && err !== null && // Spec-compliant fetch implementations\r\n (\"name\" in err && err.name === \"AbortError\" || // Expo fetch\r\n \"message\" in err && String(err.message).includes(\"FetchRequestCanceledException\"));\r\n}\r\nfunction isEmptyObj(obj) {\r\n if (!obj)\r\n return true;\r\n for (const _k in obj)\r\n return false;\r\n return true;\r\n}\r\nfunction hasOwn(obj, key) {\r\n return Object.prototype.hasOwnProperty.call(obj, key);\r\n}\r\nfunction getDefaultFetch() {\r\n if (typeof fetch !== \"undefined\") {\r\n return fetch;\r\n }\r\n throw new Error(\"`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`\");\r\n}\r\nfunction makeReadableStream(...args) {\r\n const ReadableStream = globalThis.ReadableStream;\r\n if (typeof ReadableStream === \"undefined\") {\r\n throw new Error(\"`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`\");\r\n }\r\n return new ReadableStream(...args);\r\n}\r\nfunction ReadableStreamFrom(iterable) {\r\n let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();\r\n return makeReadableStream({\r\n start() {\r\n },\r\n async pull(controller) {\r\n const { done, value } = await iter.next();\r\n if (done) {\r\n controller.close();\r\n } else {\r\n controller.enqueue(value);\r\n }\r\n },\r\n async cancel() {\r\n var _a2;\r\n await ((_a2 = iter.return) === null || _a2 === void 0 ? void 0 : _a2.call(iter));\r\n }\r\n });\r\n}\r\nfunction ReadableStreamToAsyncIterable(stream) {\r\n if (stream[Symbol.asyncIterator])\r\n return stream;\r\n const reader = stream.getReader();\r\n return {\r\n async next() {\r\n try {\r\n const result = await reader.read();\r\n if (result === null || result === void 0 ? void 0 : result.done)\r\n reader.releaseLock();\r\n return result;\r\n } catch (e) {\r\n reader.releaseLock();\r\n throw e;\r\n }\r\n },\r\n async return() {\r\n const cancelPromise = reader.cancel();\r\n reader.releaseLock();\r\n await cancelPromise;\r\n return { done: true, value: void 0 };\r\n },\r\n [Symbol.asyncIterator]() {\r\n return this;\r\n }\r\n };\r\n}\r\nasync function CancelReadableStream(stream) {\r\n var _a2, _b;\r\n if (stream === null || typeof stream !== \"object\")\r\n return;\r\n if (stream[Symbol.asyncIterator]) {\r\n await ((_b = (_a2 = stream[Symbol.asyncIterator]()).return) === null || _b === void 0 ? void 0 : _b.call(_a2));\r\n return;\r\n }\r\n const reader = stream.getReader();\r\n const cancelPromise = reader.cancel();\r\n reader.releaseLock();\r\n await cancelPromise;\r\n}\r\nfunction stringifyQuery(query) {\r\n return Object.entries(query).filter(([_, value]) => typeof value !== \"undefined\").map(([key, value]) => {\r\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\r\n return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;\r\n }\r\n if (value === null) {\r\n return `${encodeURIComponent(key)}=`;\r\n }\r\n throw new GeminiNextGenAPIClientError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);\r\n }).join(\"&\");\r\n}\r\nfunction makeFile(fileBits, fileName, options) {\r\n checkFileSupport();\r\n return new File(fileBits, fileName !== null && fileName !== void 0 ? fileName : \"unknown_file\", options);\r\n}\r\nfunction getName(value) {\r\n return (typeof value === \"object\" && value !== null && (\"name\" in value && value.name && String(value.name) || \"url\" in value && value.url && String(value.url) || \"filename\" in value && value.filename && String(value.filename) || \"path\" in value && value.path && String(value.path)) || \"\").split(/[\\\\/]/).pop() || void 0;\r\n}\r\nasync function toFile(value, name, options) {\r\n checkFileSupport();\r\n value = await value;\r\n if (isFileLike(value)) {\r\n if (value instanceof File) {\r\n return value;\r\n }\r\n return makeFile([await value.arrayBuffer()], value.name);\r\n }\r\n if (isResponseLike(value)) {\r\n const blob = await value.blob();\r\n name || (name = new URL(value.url).pathname.split(/[\\\\/]/).pop());\r\n return makeFile(await getBytes(blob), name, options);\r\n }\r\n const parts = await getBytes(value);\r\n name || (name = getName(value));\r\n if (!(options === null || options === void 0 ? void 0 : options.type)) {\r\n const type = parts.find((part) => typeof part === \"object\" && \"type\" in part && part.type);\r\n if (typeof type === \"string\") {\r\n options = Object.assign(Object.assign({}, options), { type });\r\n }\r\n }\r\n return makeFile(parts, name, options);\r\n}\r\nasync function getBytes(value) {\r\n var _a2, e_1, _b, _c;\r\n var _d;\r\n let parts = [];\r\n if (typeof value === \"string\" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.\r\n value instanceof ArrayBuffer) {\r\n parts.push(value);\r\n } else if (isBlobLike(value)) {\r\n parts.push(value instanceof Blob ? value : await value.arrayBuffer());\r\n } else if (isAsyncIterable(value)) {\r\n try {\r\n for (var _e = true, value_1 = __asyncValues(value), value_1_1; value_1_1 = await value_1.next(), _a2 = value_1_1.done, !_a2; _e = true) {\r\n _c = value_1_1.value;\r\n _e = false;\r\n const chunk = _c;\r\n parts.push(...await getBytes(chunk));\r\n }\r\n } catch (e_1_1) {\r\n e_1 = { error: e_1_1 };\r\n } finally {\r\n try {\r\n if (!_e && !_a2 && (_b = value_1.return)) await _b.call(value_1);\r\n } finally {\r\n if (e_1) throw e_1.error;\r\n }\r\n }\r\n } else {\r\n const constructor = (_d = value === null || value === void 0 ? void 0 : value.constructor) === null || _d === void 0 ? void 0 : _d.name;\r\n throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : \"\"}${propsForError(value)}`);\r\n }\r\n return parts;\r\n}\r\nfunction propsForError(value) {\r\n if (typeof value !== \"object\" || value === null)\r\n return \"\";\r\n const props = Object.getOwnPropertyNames(value);\r\n return `; props: [${props.map((p) => `\"${p}\"`).join(\", \")}]`;\r\n}\r\nfunction encodeURIPath(str) {\r\n return str.replace(/[^A-Za-z0-9\\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);\r\n}\r\nfunction concatBytes(buffers) {\r\n let length = 0;\r\n for (const buffer of buffers) {\r\n length += buffer.length;\r\n }\r\n const output = new Uint8Array(length);\r\n let index = 0;\r\n for (const buffer of buffers) {\r\n output.set(buffer, index);\r\n index += buffer.length;\r\n }\r\n return output;\r\n}\r\nfunction encodeUTF8(str) {\r\n let encoder;\r\n return (encodeUTF8_ !== null && encodeUTF8_ !== void 0 ? encodeUTF8_ : (encoder = new globalThis.TextEncoder(), encodeUTF8_ = encoder.encode.bind(encoder)))(str);\r\n}\r\nfunction decodeUTF8(bytes) {\r\n let decoder;\r\n return (decodeUTF8_ !== null && decodeUTF8_ !== void 0 ? decodeUTF8_ : (decoder = new globalThis.TextDecoder(), decodeUTF8_ = decoder.decode.bind(decoder)))(bytes);\r\n}\r\nfunction findNewlineIndex(buffer, startIndex) {\r\n const newline = 10;\r\n const carriage = 13;\r\n const start = startIndex !== null && startIndex !== void 0 ? startIndex : 0;\r\n const nextNewline = buffer.indexOf(newline, start);\r\n const nextCarriage = buffer.indexOf(carriage, start);\r\n if (nextNewline === -1 && nextCarriage === -1) {\r\n return null;\r\n }\r\n let i;\r\n if (nextNewline !== -1 && nextCarriage !== -1) {\r\n i = Math.min(nextNewline, nextCarriage);\r\n } else {\r\n i = nextNewline !== -1 ? nextNewline : nextCarriage;\r\n }\r\n if (buffer[i] === newline) {\r\n return { preceding: i, index: i + 1, carriage: false };\r\n }\r\n return { preceding: i, index: i + 1, carriage: true };\r\n}\r\nfunction noop() {\r\n}\r\nfunction makeLogFn(fnLevel, logger, logLevel) {\r\n if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) {\r\n return noop;\r\n } else {\r\n return logger[fnLevel].bind(logger);\r\n }\r\n}\r\nfunction loggerFor(client) {\r\n var _a2;\r\n const logger = client.logger;\r\n const logLevel = (_a2 = client.logLevel) !== null && _a2 !== void 0 ? _a2 : \"off\";\r\n if (!logger) {\r\n return noopLogger;\r\n }\r\n const cachedLogger = cachedLoggers.get(logger);\r\n if (cachedLogger && cachedLogger[0] === logLevel) {\r\n return cachedLogger[1];\r\n }\r\n const levelLogger = {\r\n error: makeLogFn(\"error\", logger, logLevel),\r\n warn: makeLogFn(\"warn\", logger, logLevel),\r\n info: makeLogFn(\"info\", logger, logLevel),\r\n debug: makeLogFn(\"debug\", logger, logLevel)\r\n };\r\n cachedLoggers.set(logger, [logLevel, levelLogger]);\r\n return levelLogger;\r\n}\r\nfunction _iterSSEMessages(response, controller) {\r\n return __asyncGenerator(this, arguments, function* _iterSSEMessages_1() {\r\n var _a2, e_4, _b, _c;\r\n if (!response.body) {\r\n controller.abort();\r\n if (typeof globalThis.navigator !== \"undefined\" && globalThis.navigator.product === \"ReactNative\") {\r\n throw new GeminiNextGenAPIClientError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);\r\n }\r\n throw new GeminiNextGenAPIClientError(`Attempted to iterate over a response with no body`);\r\n }\r\n const sseDecoder = new SSEDecoder();\r\n const lineDecoder = new LineDecoder();\r\n const iter = ReadableStreamToAsyncIterable(response.body);\r\n try {\r\n for (var _d = true, _e = __asyncValues(iterBinaryChunks(iter)), _f; _f = yield __await(_e.next()), _a2 = _f.done, !_a2; _d = true) {\r\n _c = _f.value;\r\n _d = false;\r\n const sseChunk = _c;\r\n for (const line of lineDecoder.decode(sseChunk)) {\r\n const sse = sseDecoder.decode(line);\r\n if (sse)\r\n yield yield __await(sse);\r\n }\r\n }\r\n } catch (e_4_1) {\r\n e_4 = { error: e_4_1 };\r\n } finally {\r\n try {\r\n if (!_d && !_a2 && (_b = _e.return)) yield __await(_b.call(_e));\r\n } finally {\r\n if (e_4) throw e_4.error;\r\n }\r\n }\r\n for (const line of lineDecoder.flush()) {\r\n const sse = sseDecoder.decode(line);\r\n if (sse)\r\n yield yield __await(sse);\r\n }\r\n });\r\n}\r\nfunction iterBinaryChunks(iterator) {\r\n return __asyncGenerator(this, arguments, function* iterBinaryChunks_1() {\r\n var _a2, e_5, _b, _c;\r\n try {\r\n for (var _d = true, iterator_3 = __asyncValues(iterator), iterator_3_1; iterator_3_1 = yield __await(iterator_3.next()), _a2 = iterator_3_1.done, !_a2; _d = true) {\r\n _c = iterator_3_1.value;\r\n _d = false;\r\n const chunk = _c;\r\n if (chunk == null) {\r\n continue;\r\n }\r\n const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === \"string\" ? encodeUTF8(chunk) : chunk;\r\n yield yield __await(binaryChunk);\r\n }\r\n } catch (e_5_1) {\r\n e_5 = { error: e_5_1 };\r\n } finally {\r\n try {\r\n if (!_d && !_a2 && (_b = iterator_3.return)) yield __await(_b.call(iterator_3));\r\n } finally {\r\n if (e_5) throw e_5.error;\r\n }\r\n }\r\n });\r\n}\r\nfunction partition(str, delimiter) {\r\n const index = str.indexOf(delimiter);\r\n if (index !== -1) {\r\n return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];\r\n }\r\n return [str, \"\", \"\"];\r\n}\r\nasync function defaultParseResponse(client, props) {\r\n const { response, requestLogID, retryOfRequestLogID, startTime } = props;\r\n const body = await (async () => {\r\n var _a2;\r\n if (props.options.stream) {\r\n loggerFor(client).debug(\"response\", response.status, response.url, response.headers, response.body);\r\n if (props.options.__streamClass) {\r\n return props.options.__streamClass.fromSSEResponse(response, props.controller, client);\r\n }\r\n return Stream.fromSSEResponse(response, props.controller, client);\r\n }\r\n if (response.status === 204) {\r\n return null;\r\n }\r\n if (props.options.__binaryResponse) {\r\n return response;\r\n }\r\n const contentType = response.headers.get(\"content-type\");\r\n const mediaType = (_a2 = contentType === null || contentType === void 0 ? void 0 : contentType.split(\";\")[0]) === null || _a2 === void 0 ? void 0 : _a2.trim();\r\n const isJSON = (mediaType === null || mediaType === void 0 ? void 0 : mediaType.includes(\"application/json\")) || (mediaType === null || mediaType === void 0 ? void 0 : mediaType.endsWith(\"+json\"));\r\n if (isJSON) {\r\n const contentLength = response.headers.get(\"content-length\");\r\n if (contentLength === \"0\") {\r\n return void 0;\r\n }\r\n const json = await response.json();\r\n return json;\r\n }\r\n const text = await response.text();\r\n return text;\r\n })();\r\n loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({\r\n retryOfRequestLogID,\r\n url: response.url,\r\n status: response.status,\r\n body,\r\n durationMs: Date.now() - startTime\r\n }));\r\n return body;\r\n}\r\nfunction* iterateHeaders(headers) {\r\n if (!headers)\r\n return;\r\n if (brand_privateNullableHeaders in headers) {\r\n const { values, nulls } = headers;\r\n yield* values.entries();\r\n for (const name of nulls) {\r\n yield [name, null];\r\n }\r\n return;\r\n }\r\n let shouldClear = false;\r\n let iter;\r\n if (headers instanceof Headers) {\r\n iter = headers.entries();\r\n } else if (isReadonlyArray(headers)) {\r\n iter = headers;\r\n } else {\r\n shouldClear = true;\r\n iter = Object.entries(headers !== null && headers !== void 0 ? headers : {});\r\n }\r\n for (let row of iter) {\r\n const name = row[0];\r\n if (typeof name !== \"string\")\r\n throw new TypeError(\"expected header name to be a string\");\r\n const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];\r\n let didClear = false;\r\n for (const value of values) {\r\n if (value === void 0)\r\n continue;\r\n if (shouldClear && !didClear) {\r\n didClear = true;\r\n yield [name, null];\r\n }\r\n yield [name, value];\r\n }\r\n }\r\n}\r\nfunction cancelTuningJobParametersToMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], fromName);\r\n }\r\n return toObject;\r\n}\r\nfunction cancelTuningJobParametersToVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], fromName);\r\n }\r\n return toObject;\r\n}\r\nfunction cancelTuningJobResponseFromMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n return toObject;\r\n}\r\nfunction cancelTuningJobResponseFromVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n return toObject;\r\n}\r\nfunction createTuningJobConfigToMldev(fromObject, parentObject, _rootObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"validationDataset\"]) !== void 0) {\r\n throw new Error(\"validationDataset parameter is not supported in Gemini API.\");\r\n }\r\n const fromTunedModelDisplayName = getValueByPath(fromObject, [\r\n \"tunedModelDisplayName\"\r\n ]);\r\n if (parentObject !== void 0 && fromTunedModelDisplayName != null) {\r\n setValueByPath(parentObject, [\"displayName\"], fromTunedModelDisplayName);\r\n }\r\n if (getValueByPath(fromObject, [\"description\"]) !== void 0) {\r\n throw new Error(\"description parameter is not supported in Gemini API.\");\r\n }\r\n const fromEpochCount = getValueByPath(fromObject, [\"epochCount\"]);\r\n if (parentObject !== void 0 && fromEpochCount != null) {\r\n setValueByPath(parentObject, [\"tuningTask\", \"hyperparameters\", \"epochCount\"], fromEpochCount);\r\n }\r\n const fromLearningRateMultiplier = getValueByPath(fromObject, [\r\n \"learningRateMultiplier\"\r\n ]);\r\n if (fromLearningRateMultiplier != null) {\r\n setValueByPath(toObject, [\"tuningTask\", \"hyperparameters\", \"learningRateMultiplier\"], fromLearningRateMultiplier);\r\n }\r\n if (getValueByPath(fromObject, [\"exportLastCheckpointOnly\"]) !== void 0) {\r\n throw new Error(\"exportLastCheckpointOnly parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"preTunedModelCheckpointId\"]) !== void 0) {\r\n throw new Error(\"preTunedModelCheckpointId parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"adapterSize\"]) !== void 0) {\r\n throw new Error(\"adapterSize parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"tuningMode\"]) !== void 0) {\r\n throw new Error(\"tuningMode parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"customBaseModel\"]) !== void 0) {\r\n throw new Error(\"customBaseModel parameter is not supported in Gemini API.\");\r\n }\r\n const fromBatchSize = getValueByPath(fromObject, [\"batchSize\"]);\r\n if (parentObject !== void 0 && fromBatchSize != null) {\r\n setValueByPath(parentObject, [\"tuningTask\", \"hyperparameters\", \"batchSize\"], fromBatchSize);\r\n }\r\n const fromLearningRate = getValueByPath(fromObject, [\"learningRate\"]);\r\n if (parentObject !== void 0 && fromLearningRate != null) {\r\n setValueByPath(parentObject, [\"tuningTask\", \"hyperparameters\", \"learningRate\"], fromLearningRate);\r\n }\r\n if (getValueByPath(fromObject, [\"labels\"]) !== void 0) {\r\n throw new Error(\"labels parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"beta\"]) !== void 0) {\r\n throw new Error(\"beta parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"baseTeacherModel\"]) !== void 0) {\r\n throw new Error(\"baseTeacherModel parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"tunedTeacherModelSource\"]) !== void 0) {\r\n throw new Error(\"tunedTeacherModelSource parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"sftLossWeightMultiplier\"]) !== void 0) {\r\n throw new Error(\"sftLossWeightMultiplier parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"outputUri\"]) !== void 0) {\r\n throw new Error(\"outputUri parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"encryptionSpec\"]) !== void 0) {\r\n throw new Error(\"encryptionSpec parameter is not supported in Gemini API.\");\r\n }\r\n return toObject;\r\n}\r\nfunction createTuningJobConfigToVertex(fromObject, parentObject, rootObject) {\r\n const toObject = {};\r\n let discriminatorValidationDataset = getValueByPath(rootObject, [\r\n \"config\",\r\n \"method\"\r\n ]);\r\n if (discriminatorValidationDataset === void 0) {\r\n discriminatorValidationDataset = \"SUPERVISED_FINE_TUNING\";\r\n }\r\n if (discriminatorValidationDataset === \"SUPERVISED_FINE_TUNING\") {\r\n const fromValidationDataset = getValueByPath(fromObject, [\r\n \"validationDataset\"\r\n ]);\r\n if (parentObject !== void 0 && fromValidationDataset != null) {\r\n setValueByPath(parentObject, [\"supervisedTuningSpec\"], tuningValidationDatasetToVertex(fromValidationDataset));\r\n }\r\n } else if (discriminatorValidationDataset === \"PREFERENCE_TUNING\") {\r\n const fromValidationDataset = getValueByPath(fromObject, [\r\n \"validationDataset\"\r\n ]);\r\n if (parentObject !== void 0 && fromValidationDataset != null) {\r\n setValueByPath(parentObject, [\"preferenceOptimizationSpec\"], tuningValidationDatasetToVertex(fromValidationDataset));\r\n }\r\n } else if (discriminatorValidationDataset === \"DISTILLATION\") {\r\n const fromValidationDataset = getValueByPath(fromObject, [\r\n \"validationDataset\"\r\n ]);\r\n if (parentObject !== void 0 && fromValidationDataset != null) {\r\n setValueByPath(parentObject, [\"distillationSpec\"], tuningValidationDatasetToVertex(fromValidationDataset));\r\n }\r\n }\r\n const fromTunedModelDisplayName = getValueByPath(fromObject, [\r\n \"tunedModelDisplayName\"\r\n ]);\r\n if (parentObject !== void 0 && fromTunedModelDisplayName != null) {\r\n setValueByPath(parentObject, [\"tunedModelDisplayName\"], fromTunedModelDisplayName);\r\n }\r\n const fromDescription = getValueByPath(fromObject, [\"description\"]);\r\n if (parentObject !== void 0 && fromDescription != null) {\r\n setValueByPath(parentObject, [\"description\"], fromDescription);\r\n }\r\n let discriminatorEpochCount = getValueByPath(rootObject, [\r\n \"config\",\r\n \"method\"\r\n ]);\r\n if (discriminatorEpochCount === void 0) {\r\n discriminatorEpochCount = \"SUPERVISED_FINE_TUNING\";\r\n }\r\n if (discriminatorEpochCount === \"SUPERVISED_FINE_TUNING\") {\r\n const fromEpochCount = getValueByPath(fromObject, [\"epochCount\"]);\r\n if (parentObject !== void 0 && fromEpochCount != null) {\r\n setValueByPath(parentObject, [\"supervisedTuningSpec\", \"hyperParameters\", \"epochCount\"], fromEpochCount);\r\n }\r\n } else if (discriminatorEpochCount === \"PREFERENCE_TUNING\") {\r\n const fromEpochCount = getValueByPath(fromObject, [\"epochCount\"]);\r\n if (parentObject !== void 0 && fromEpochCount != null) {\r\n setValueByPath(parentObject, [\"preferenceOptimizationSpec\", \"hyperParameters\", \"epochCount\"], fromEpochCount);\r\n }\r\n } else if (discriminatorEpochCount === \"DISTILLATION\") {\r\n const fromEpochCount = getValueByPath(fromObject, [\"epochCount\"]);\r\n if (parentObject !== void 0 && fromEpochCount != null) {\r\n setValueByPath(parentObject, [\"distillationSpec\", \"hyperParameters\", \"epochCount\"], fromEpochCount);\r\n }\r\n }\r\n let discriminatorLearningRateMultiplier = getValueByPath(rootObject, [\r\n \"config\",\r\n \"method\"\r\n ]);\r\n if (discriminatorLearningRateMultiplier === void 0) {\r\n discriminatorLearningRateMultiplier = \"SUPERVISED_FINE_TUNING\";\r\n }\r\n if (discriminatorLearningRateMultiplier === \"SUPERVISED_FINE_TUNING\") {\r\n const fromLearningRateMultiplier = getValueByPath(fromObject, [\r\n \"learningRateMultiplier\"\r\n ]);\r\n if (parentObject !== void 0 && fromLearningRateMultiplier != null) {\r\n setValueByPath(parentObject, [\"supervisedTuningSpec\", \"hyperParameters\", \"learningRateMultiplier\"], fromLearningRateMultiplier);\r\n }\r\n } else if (discriminatorLearningRateMultiplier === \"PREFERENCE_TUNING\") {\r\n const fromLearningRateMultiplier = getValueByPath(fromObject, [\r\n \"learningRateMultiplier\"\r\n ]);\r\n if (parentObject !== void 0 && fromLearningRateMultiplier != null) {\r\n setValueByPath(parentObject, [\r\n \"preferenceOptimizationSpec\",\r\n \"hyperParameters\",\r\n \"learningRateMultiplier\"\r\n ], fromLearningRateMultiplier);\r\n }\r\n } else if (discriminatorLearningRateMultiplier === \"DISTILLATION\") {\r\n const fromLearningRateMultiplier = getValueByPath(fromObject, [\r\n \"learningRateMultiplier\"\r\n ]);\r\n if (parentObject !== void 0 && fromLearningRateMultiplier != null) {\r\n setValueByPath(parentObject, [\"distillationSpec\", \"hyperParameters\", \"learningRateMultiplier\"], fromLearningRateMultiplier);\r\n }\r\n }\r\n let discriminatorExportLastCheckpointOnly = getValueByPath(rootObject, [\"config\", \"method\"]);\r\n if (discriminatorExportLastCheckpointOnly === void 0) {\r\n discriminatorExportLastCheckpointOnly = \"SUPERVISED_FINE_TUNING\";\r\n }\r\n if (discriminatorExportLastCheckpointOnly === \"SUPERVISED_FINE_TUNING\") {\r\n const fromExportLastCheckpointOnly = getValueByPath(fromObject, [\r\n \"exportLastCheckpointOnly\"\r\n ]);\r\n if (parentObject !== void 0 && fromExportLastCheckpointOnly != null) {\r\n setValueByPath(parentObject, [\"supervisedTuningSpec\", \"exportLastCheckpointOnly\"], fromExportLastCheckpointOnly);\r\n }\r\n } else if (discriminatorExportLastCheckpointOnly === \"PREFERENCE_TUNING\") {\r\n const fromExportLastCheckpointOnly = getValueByPath(fromObject, [\r\n \"exportLastCheckpointOnly\"\r\n ]);\r\n if (parentObject !== void 0 && fromExportLastCheckpointOnly != null) {\r\n setValueByPath(parentObject, [\"preferenceOptimizationSpec\", \"exportLastCheckpointOnly\"], fromExportLastCheckpointOnly);\r\n }\r\n } else if (discriminatorExportLastCheckpointOnly === \"DISTILLATION\") {\r\n const fromExportLastCheckpointOnly = getValueByPath(fromObject, [\r\n \"exportLastCheckpointOnly\"\r\n ]);\r\n if (parentObject !== void 0 && fromExportLastCheckpointOnly != null) {\r\n setValueByPath(parentObject, [\"distillationSpec\", \"exportLastCheckpointOnly\"], fromExportLastCheckpointOnly);\r\n }\r\n }\r\n let discriminatorAdapterSize = getValueByPath(rootObject, [\r\n \"config\",\r\n \"method\"\r\n ]);\r\n if (discriminatorAdapterSize === void 0) {\r\n discriminatorAdapterSize = \"SUPERVISED_FINE_TUNING\";\r\n }\r\n if (discriminatorAdapterSize === \"SUPERVISED_FINE_TUNING\") {\r\n const fromAdapterSize = getValueByPath(fromObject, [\"adapterSize\"]);\r\n if (parentObject !== void 0 && fromAdapterSize != null) {\r\n setValueByPath(parentObject, [\"supervisedTuningSpec\", \"hyperParameters\", \"adapterSize\"], fromAdapterSize);\r\n }\r\n } else if (discriminatorAdapterSize === \"PREFERENCE_TUNING\") {\r\n const fromAdapterSize = getValueByPath(fromObject, [\"adapterSize\"]);\r\n if (parentObject !== void 0 && fromAdapterSize != null) {\r\n setValueByPath(parentObject, [\"preferenceOptimizationSpec\", \"hyperParameters\", \"adapterSize\"], fromAdapterSize);\r\n }\r\n } else if (discriminatorAdapterSize === \"DISTILLATION\") {\r\n const fromAdapterSize = getValueByPath(fromObject, [\"adapterSize\"]);\r\n if (parentObject !== void 0 && fromAdapterSize != null) {\r\n setValueByPath(parentObject, [\"distillationSpec\", \"hyperParameters\", \"adapterSize\"], fromAdapterSize);\r\n }\r\n }\r\n let discriminatorTuningMode = getValueByPath(rootObject, [\r\n \"config\",\r\n \"method\"\r\n ]);\r\n if (discriminatorTuningMode === void 0) {\r\n discriminatorTuningMode = \"SUPERVISED_FINE_TUNING\";\r\n }\r\n if (discriminatorTuningMode === \"SUPERVISED_FINE_TUNING\") {\r\n const fromTuningMode = getValueByPath(fromObject, [\"tuningMode\"]);\r\n if (parentObject !== void 0 && fromTuningMode != null) {\r\n setValueByPath(parentObject, [\"supervisedTuningSpec\", \"tuningMode\"], fromTuningMode);\r\n }\r\n } else if (discriminatorTuningMode === \"DISTILLATION\") {\r\n const fromTuningMode = getValueByPath(fromObject, [\"tuningMode\"]);\r\n if (parentObject !== void 0 && fromTuningMode != null) {\r\n setValueByPath(parentObject, [\"distillationSpec\", \"tuningMode\"], fromTuningMode);\r\n }\r\n }\r\n const fromCustomBaseModel = getValueByPath(fromObject, [\r\n \"customBaseModel\"\r\n ]);\r\n if (parentObject !== void 0 && fromCustomBaseModel != null) {\r\n setValueByPath(parentObject, [\"customBaseModel\"], fromCustomBaseModel);\r\n }\r\n let discriminatorBatchSize = getValueByPath(rootObject, [\r\n \"config\",\r\n \"method\"\r\n ]);\r\n if (discriminatorBatchSize === void 0) {\r\n discriminatorBatchSize = \"SUPERVISED_FINE_TUNING\";\r\n }\r\n if (discriminatorBatchSize === \"SUPERVISED_FINE_TUNING\") {\r\n const fromBatchSize = getValueByPath(fromObject, [\"batchSize\"]);\r\n if (parentObject !== void 0 && fromBatchSize != null) {\r\n setValueByPath(parentObject, [\"supervisedTuningSpec\", \"hyperParameters\", \"batchSize\"], fromBatchSize);\r\n }\r\n } else if (discriminatorBatchSize === \"DISTILLATION\") {\r\n const fromBatchSize = getValueByPath(fromObject, [\"batchSize\"]);\r\n if (parentObject !== void 0 && fromBatchSize != null) {\r\n setValueByPath(parentObject, [\"distillationSpec\", \"hyperParameters\", \"batchSize\"], fromBatchSize);\r\n }\r\n }\r\n let discriminatorLearningRate = getValueByPath(rootObject, [\r\n \"config\",\r\n \"method\"\r\n ]);\r\n if (discriminatorLearningRate === void 0) {\r\n discriminatorLearningRate = \"SUPERVISED_FINE_TUNING\";\r\n }\r\n if (discriminatorLearningRate === \"SUPERVISED_FINE_TUNING\") {\r\n const fromLearningRate = getValueByPath(fromObject, [\r\n \"learningRate\"\r\n ]);\r\n if (parentObject !== void 0 && fromLearningRate != null) {\r\n setValueByPath(parentObject, [\"supervisedTuningSpec\", \"hyperParameters\", \"learningRate\"], fromLearningRate);\r\n }\r\n } else if (discriminatorLearningRate === \"DISTILLATION\") {\r\n const fromLearningRate = getValueByPath(fromObject, [\r\n \"learningRate\"\r\n ]);\r\n if (parentObject !== void 0 && fromLearningRate != null) {\r\n setValueByPath(parentObject, [\"distillationSpec\", \"hyperParameters\", \"learningRate\"], fromLearningRate);\r\n }\r\n }\r\n const fromLabels = getValueByPath(fromObject, [\"labels\"]);\r\n if (parentObject !== void 0 && fromLabels != null) {\r\n setValueByPath(parentObject, [\"labels\"], fromLabels);\r\n }\r\n const fromBeta = getValueByPath(fromObject, [\"beta\"]);\r\n if (parentObject !== void 0 && fromBeta != null) {\r\n setValueByPath(parentObject, [\"preferenceOptimizationSpec\", \"hyperParameters\", \"beta\"], fromBeta);\r\n }\r\n const fromBaseTeacherModel = getValueByPath(fromObject, [\r\n \"baseTeacherModel\"\r\n ]);\r\n if (parentObject !== void 0 && fromBaseTeacherModel != null) {\r\n setValueByPath(parentObject, [\"distillationSpec\", \"baseTeacherModel\"], fromBaseTeacherModel);\r\n }\r\n const fromTunedTeacherModelSource = getValueByPath(fromObject, [\r\n \"tunedTeacherModelSource\"\r\n ]);\r\n if (parentObject !== void 0 && fromTunedTeacherModelSource != null) {\r\n setValueByPath(parentObject, [\"distillationSpec\", \"tunedTeacherModelSource\"], fromTunedTeacherModelSource);\r\n }\r\n const fromSftLossWeightMultiplier = getValueByPath(fromObject, [\r\n \"sftLossWeightMultiplier\"\r\n ]);\r\n if (parentObject !== void 0 && fromSftLossWeightMultiplier != null) {\r\n setValueByPath(parentObject, [\"distillationSpec\", \"hyperParameters\", \"sftLossWeightMultiplier\"], fromSftLossWeightMultiplier);\r\n }\r\n const fromOutputUri = getValueByPath(fromObject, [\"outputUri\"]);\r\n if (parentObject !== void 0 && fromOutputUri != null) {\r\n setValueByPath(parentObject, [\"outputUri\"], fromOutputUri);\r\n }\r\n const fromEncryptionSpec = getValueByPath(fromObject, [\r\n \"encryptionSpec\"\r\n ]);\r\n if (parentObject !== void 0 && fromEncryptionSpec != null) {\r\n setValueByPath(parentObject, [\"encryptionSpec\"], fromEncryptionSpec);\r\n }\r\n return toObject;\r\n}\r\nfunction createTuningJobParametersPrivateToMldev(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromBaseModel = getValueByPath(fromObject, [\"baseModel\"]);\r\n if (fromBaseModel != null) {\r\n setValueByPath(toObject, [\"baseModel\"], fromBaseModel);\r\n }\r\n const fromPreTunedModel = getValueByPath(fromObject, [\r\n \"preTunedModel\"\r\n ]);\r\n if (fromPreTunedModel != null) {\r\n setValueByPath(toObject, [\"preTunedModel\"], fromPreTunedModel);\r\n }\r\n const fromTrainingDataset = getValueByPath(fromObject, [\r\n \"trainingDataset\"\r\n ]);\r\n if (fromTrainingDataset != null) {\r\n tuningDatasetToMldev(fromTrainingDataset);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n createTuningJobConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction createTuningJobParametersPrivateToVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromBaseModel = getValueByPath(fromObject, [\"baseModel\"]);\r\n if (fromBaseModel != null) {\r\n setValueByPath(toObject, [\"baseModel\"], fromBaseModel);\r\n }\r\n const fromPreTunedModel = getValueByPath(fromObject, [\r\n \"preTunedModel\"\r\n ]);\r\n if (fromPreTunedModel != null) {\r\n setValueByPath(toObject, [\"preTunedModel\"], fromPreTunedModel);\r\n }\r\n const fromTrainingDataset = getValueByPath(fromObject, [\r\n \"trainingDataset\"\r\n ]);\r\n if (fromTrainingDataset != null) {\r\n tuningDatasetToVertex(fromTrainingDataset, toObject, rootObject);\r\n }\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n createTuningJobConfigToVertex(fromConfig, toObject, rootObject);\r\n }\r\n return toObject;\r\n}\r\nfunction getTuningJobParametersToMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], fromName);\r\n }\r\n return toObject;\r\n}\r\nfunction getTuningJobParametersToVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"_url\", \"name\"], fromName);\r\n }\r\n return toObject;\r\n}\r\nfunction listTuningJobsConfigToMldev(fromObject, parentObject, _rootObject) {\r\n const toObject = {};\r\n const fromPageSize = getValueByPath(fromObject, [\"pageSize\"]);\r\n if (parentObject !== void 0 && fromPageSize != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageSize\"], fromPageSize);\r\n }\r\n const fromPageToken = getValueByPath(fromObject, [\"pageToken\"]);\r\n if (parentObject !== void 0 && fromPageToken != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageToken\"], fromPageToken);\r\n }\r\n const fromFilter = getValueByPath(fromObject, [\"filter\"]);\r\n if (parentObject !== void 0 && fromFilter != null) {\r\n setValueByPath(parentObject, [\"_query\", \"filter\"], fromFilter);\r\n }\r\n return toObject;\r\n}\r\nfunction listTuningJobsConfigToVertex(fromObject, parentObject, _rootObject) {\r\n const toObject = {};\r\n const fromPageSize = getValueByPath(fromObject, [\"pageSize\"]);\r\n if (parentObject !== void 0 && fromPageSize != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageSize\"], fromPageSize);\r\n }\r\n const fromPageToken = getValueByPath(fromObject, [\"pageToken\"]);\r\n if (parentObject !== void 0 && fromPageToken != null) {\r\n setValueByPath(parentObject, [\"_query\", \"pageToken\"], fromPageToken);\r\n }\r\n const fromFilter = getValueByPath(fromObject, [\"filter\"]);\r\n if (parentObject !== void 0 && fromFilter != null) {\r\n setValueByPath(parentObject, [\"_query\", \"filter\"], fromFilter);\r\n }\r\n return toObject;\r\n}\r\nfunction listTuningJobsParametersToMldev(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n listTuningJobsConfigToMldev(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction listTuningJobsParametersToVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromConfig = getValueByPath(fromObject, [\"config\"]);\r\n if (fromConfig != null) {\r\n listTuningJobsConfigToVertex(fromConfig, toObject);\r\n }\r\n return toObject;\r\n}\r\nfunction listTuningJobsResponseFromMldev(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromNextPageToken = getValueByPath(fromObject, [\r\n \"nextPageToken\"\r\n ]);\r\n if (fromNextPageToken != null) {\r\n setValueByPath(toObject, [\"nextPageToken\"], fromNextPageToken);\r\n }\r\n const fromTuningJobs = getValueByPath(fromObject, [\"tunedModels\"]);\r\n if (fromTuningJobs != null) {\r\n let transformedList = fromTuningJobs;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return tuningJobFromMldev(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"tuningJobs\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction listTuningJobsResponseFromVertex(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromNextPageToken = getValueByPath(fromObject, [\r\n \"nextPageToken\"\r\n ]);\r\n if (fromNextPageToken != null) {\r\n setValueByPath(toObject, [\"nextPageToken\"], fromNextPageToken);\r\n }\r\n const fromTuningJobs = getValueByPath(fromObject, [\"tuningJobs\"]);\r\n if (fromTuningJobs != null) {\r\n let transformedList = fromTuningJobs;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return tuningJobFromVertex(item);\r\n });\r\n }\r\n setValueByPath(toObject, [\"tuningJobs\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction tunedModelFromMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromModel = getValueByPath(fromObject, [\"name\"]);\r\n if (fromModel != null) {\r\n setValueByPath(toObject, [\"model\"], fromModel);\r\n }\r\n const fromEndpoint = getValueByPath(fromObject, [\"name\"]);\r\n if (fromEndpoint != null) {\r\n setValueByPath(toObject, [\"endpoint\"], fromEndpoint);\r\n }\r\n return toObject;\r\n}\r\nfunction tuningDatasetToMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n if (getValueByPath(fromObject, [\"gcsUri\"]) !== void 0) {\r\n throw new Error(\"gcsUri parameter is not supported in Gemini API.\");\r\n }\r\n if (getValueByPath(fromObject, [\"vertexDatasetResource\"]) !== void 0) {\r\n throw new Error(\"vertexDatasetResource parameter is not supported in Gemini API.\");\r\n }\r\n const fromExamples = getValueByPath(fromObject, [\"examples\"]);\r\n if (fromExamples != null) {\r\n let transformedList = fromExamples;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"examples\", \"examples\"], transformedList);\r\n }\r\n return toObject;\r\n}\r\nfunction tuningDatasetToVertex(fromObject, parentObject, rootObject) {\r\n const toObject = {};\r\n let discriminatorGcsUri = getValueByPath(rootObject, [\r\n \"config\",\r\n \"method\"\r\n ]);\r\n if (discriminatorGcsUri === void 0) {\r\n discriminatorGcsUri = \"SUPERVISED_FINE_TUNING\";\r\n }\r\n if (discriminatorGcsUri === \"SUPERVISED_FINE_TUNING\") {\r\n const fromGcsUri = getValueByPath(fromObject, [\"gcsUri\"]);\r\n if (parentObject !== void 0 && fromGcsUri != null) {\r\n setValueByPath(parentObject, [\"supervisedTuningSpec\", \"trainingDatasetUri\"], fromGcsUri);\r\n }\r\n } else if (discriminatorGcsUri === \"PREFERENCE_TUNING\") {\r\n const fromGcsUri = getValueByPath(fromObject, [\"gcsUri\"]);\r\n if (parentObject !== void 0 && fromGcsUri != null) {\r\n setValueByPath(parentObject, [\"preferenceOptimizationSpec\", \"trainingDatasetUri\"], fromGcsUri);\r\n }\r\n } else if (discriminatorGcsUri === \"DISTILLATION\") {\r\n const fromGcsUri = getValueByPath(fromObject, [\"gcsUri\"]);\r\n if (parentObject !== void 0 && fromGcsUri != null) {\r\n setValueByPath(parentObject, [\"distillationSpec\", \"promptDatasetUri\"], fromGcsUri);\r\n }\r\n }\r\n let discriminatorVertexDatasetResource = getValueByPath(rootObject, [\r\n \"config\",\r\n \"method\"\r\n ]);\r\n if (discriminatorVertexDatasetResource === void 0) {\r\n discriminatorVertexDatasetResource = \"SUPERVISED_FINE_TUNING\";\r\n }\r\n if (discriminatorVertexDatasetResource === \"SUPERVISED_FINE_TUNING\") {\r\n const fromVertexDatasetResource = getValueByPath(fromObject, [\r\n \"vertexDatasetResource\"\r\n ]);\r\n if (parentObject !== void 0 && fromVertexDatasetResource != null) {\r\n setValueByPath(parentObject, [\"supervisedTuningSpec\", \"trainingDatasetUri\"], fromVertexDatasetResource);\r\n }\r\n } else if (discriminatorVertexDatasetResource === \"PREFERENCE_TUNING\") {\r\n const fromVertexDatasetResource = getValueByPath(fromObject, [\r\n \"vertexDatasetResource\"\r\n ]);\r\n if (parentObject !== void 0 && fromVertexDatasetResource != null) {\r\n setValueByPath(parentObject, [\"preferenceOptimizationSpec\", \"trainingDatasetUri\"], fromVertexDatasetResource);\r\n }\r\n } else if (discriminatorVertexDatasetResource === \"DISTILLATION\") {\r\n const fromVertexDatasetResource = getValueByPath(fromObject, [\r\n \"vertexDatasetResource\"\r\n ]);\r\n if (parentObject !== void 0 && fromVertexDatasetResource != null) {\r\n setValueByPath(parentObject, [\"distillationSpec\", \"promptDatasetUri\"], fromVertexDatasetResource);\r\n }\r\n }\r\n if (getValueByPath(fromObject, [\"examples\"]) !== void 0) {\r\n throw new Error(\"examples parameter is not supported in Vertex AI.\");\r\n }\r\n return toObject;\r\n}\r\nfunction tuningJobFromMldev(fromObject, rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromState = getValueByPath(fromObject, [\"state\"]);\r\n if (fromState != null) {\r\n setValueByPath(toObject, [\"state\"], tTuningJobStatus(fromState));\r\n }\r\n const fromCreateTime = getValueByPath(fromObject, [\"createTime\"]);\r\n if (fromCreateTime != null) {\r\n setValueByPath(toObject, [\"createTime\"], fromCreateTime);\r\n }\r\n const fromStartTime = getValueByPath(fromObject, [\r\n \"tuningTask\",\r\n \"startTime\"\r\n ]);\r\n if (fromStartTime != null) {\r\n setValueByPath(toObject, [\"startTime\"], fromStartTime);\r\n }\r\n const fromEndTime = getValueByPath(fromObject, [\r\n \"tuningTask\",\r\n \"completeTime\"\r\n ]);\r\n if (fromEndTime != null) {\r\n setValueByPath(toObject, [\"endTime\"], fromEndTime);\r\n }\r\n const fromUpdateTime = getValueByPath(fromObject, [\"updateTime\"]);\r\n if (fromUpdateTime != null) {\r\n setValueByPath(toObject, [\"updateTime\"], fromUpdateTime);\r\n }\r\n const fromDescription = getValueByPath(fromObject, [\"description\"]);\r\n if (fromDescription != null) {\r\n setValueByPath(toObject, [\"description\"], fromDescription);\r\n }\r\n const fromBaseModel = getValueByPath(fromObject, [\"baseModel\"]);\r\n if (fromBaseModel != null) {\r\n setValueByPath(toObject, [\"baseModel\"], fromBaseModel);\r\n }\r\n const fromTunedModel = getValueByPath(fromObject, [\"_self\"]);\r\n if (fromTunedModel != null) {\r\n setValueByPath(toObject, [\"tunedModel\"], tunedModelFromMldev(fromTunedModel));\r\n }\r\n return toObject;\r\n}\r\nfunction tuningJobFromVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromState = getValueByPath(fromObject, [\"state\"]);\r\n if (fromState != null) {\r\n setValueByPath(toObject, [\"state\"], tTuningJobStatus(fromState));\r\n }\r\n const fromCreateTime = getValueByPath(fromObject, [\"createTime\"]);\r\n if (fromCreateTime != null) {\r\n setValueByPath(toObject, [\"createTime\"], fromCreateTime);\r\n }\r\n const fromStartTime = getValueByPath(fromObject, [\"startTime\"]);\r\n if (fromStartTime != null) {\r\n setValueByPath(toObject, [\"startTime\"], fromStartTime);\r\n }\r\n const fromEndTime = getValueByPath(fromObject, [\"endTime\"]);\r\n if (fromEndTime != null) {\r\n setValueByPath(toObject, [\"endTime\"], fromEndTime);\r\n }\r\n const fromUpdateTime = getValueByPath(fromObject, [\"updateTime\"]);\r\n if (fromUpdateTime != null) {\r\n setValueByPath(toObject, [\"updateTime\"], fromUpdateTime);\r\n }\r\n const fromError = getValueByPath(fromObject, [\"error\"]);\r\n if (fromError != null) {\r\n setValueByPath(toObject, [\"error\"], fromError);\r\n }\r\n const fromDescription = getValueByPath(fromObject, [\"description\"]);\r\n if (fromDescription != null) {\r\n setValueByPath(toObject, [\"description\"], fromDescription);\r\n }\r\n const fromBaseModel = getValueByPath(fromObject, [\"baseModel\"]);\r\n if (fromBaseModel != null) {\r\n setValueByPath(toObject, [\"baseModel\"], fromBaseModel);\r\n }\r\n const fromTunedModel = getValueByPath(fromObject, [\"tunedModel\"]);\r\n if (fromTunedModel != null) {\r\n setValueByPath(toObject, [\"tunedModel\"], fromTunedModel);\r\n }\r\n const fromPreTunedModel = getValueByPath(fromObject, [\r\n \"preTunedModel\"\r\n ]);\r\n if (fromPreTunedModel != null) {\r\n setValueByPath(toObject, [\"preTunedModel\"], fromPreTunedModel);\r\n }\r\n const fromSupervisedTuningSpec = getValueByPath(fromObject, [\r\n \"supervisedTuningSpec\"\r\n ]);\r\n if (fromSupervisedTuningSpec != null) {\r\n setValueByPath(toObject, [\"supervisedTuningSpec\"], fromSupervisedTuningSpec);\r\n }\r\n const fromPreferenceOptimizationSpec = getValueByPath(fromObject, [\r\n \"preferenceOptimizationSpec\"\r\n ]);\r\n if (fromPreferenceOptimizationSpec != null) {\r\n setValueByPath(toObject, [\"preferenceOptimizationSpec\"], fromPreferenceOptimizationSpec);\r\n }\r\n const fromDistillationSpec = getValueByPath(fromObject, [\r\n \"distillationSpec\"\r\n ]);\r\n if (fromDistillationSpec != null) {\r\n setValueByPath(toObject, [\"distillationSpec\"], fromDistillationSpec);\r\n }\r\n const fromTuningDataStats = getValueByPath(fromObject, [\r\n \"tuningDataStats\"\r\n ]);\r\n if (fromTuningDataStats != null) {\r\n setValueByPath(toObject, [\"tuningDataStats\"], fromTuningDataStats);\r\n }\r\n const fromEncryptionSpec = getValueByPath(fromObject, [\r\n \"encryptionSpec\"\r\n ]);\r\n if (fromEncryptionSpec != null) {\r\n setValueByPath(toObject, [\"encryptionSpec\"], fromEncryptionSpec);\r\n }\r\n const fromPartnerModelTuningSpec = getValueByPath(fromObject, [\r\n \"partnerModelTuningSpec\"\r\n ]);\r\n if (fromPartnerModelTuningSpec != null) {\r\n setValueByPath(toObject, [\"partnerModelTuningSpec\"], fromPartnerModelTuningSpec);\r\n }\r\n const fromCustomBaseModel = getValueByPath(fromObject, [\r\n \"customBaseModel\"\r\n ]);\r\n if (fromCustomBaseModel != null) {\r\n setValueByPath(toObject, [\"customBaseModel\"], fromCustomBaseModel);\r\n }\r\n const fromEvaluateDatasetRuns = getValueByPath(fromObject, [\r\n \"evaluateDatasetRuns\"\r\n ]);\r\n if (fromEvaluateDatasetRuns != null) {\r\n let transformedList = fromEvaluateDatasetRuns;\r\n if (Array.isArray(transformedList)) {\r\n transformedList = transformedList.map((item) => {\r\n return item;\r\n });\r\n }\r\n setValueByPath(toObject, [\"evaluateDatasetRuns\"], transformedList);\r\n }\r\n const fromExperiment = getValueByPath(fromObject, [\"experiment\"]);\r\n if (fromExperiment != null) {\r\n setValueByPath(toObject, [\"experiment\"], fromExperiment);\r\n }\r\n const fromFullFineTuningSpec = getValueByPath(fromObject, [\r\n \"fullFineTuningSpec\"\r\n ]);\r\n if (fromFullFineTuningSpec != null) {\r\n setValueByPath(toObject, [\"fullFineTuningSpec\"], fromFullFineTuningSpec);\r\n }\r\n const fromLabels = getValueByPath(fromObject, [\"labels\"]);\r\n if (fromLabels != null) {\r\n setValueByPath(toObject, [\"labels\"], fromLabels);\r\n }\r\n const fromOutputUri = getValueByPath(fromObject, [\"outputUri\"]);\r\n if (fromOutputUri != null) {\r\n setValueByPath(toObject, [\"outputUri\"], fromOutputUri);\r\n }\r\n const fromPipelineJob = getValueByPath(fromObject, [\"pipelineJob\"]);\r\n if (fromPipelineJob != null) {\r\n setValueByPath(toObject, [\"pipelineJob\"], fromPipelineJob);\r\n }\r\n const fromServiceAccount = getValueByPath(fromObject, [\r\n \"serviceAccount\"\r\n ]);\r\n if (fromServiceAccount != null) {\r\n setValueByPath(toObject, [\"serviceAccount\"], fromServiceAccount);\r\n }\r\n const fromTunedModelDisplayName = getValueByPath(fromObject, [\r\n \"tunedModelDisplayName\"\r\n ]);\r\n if (fromTunedModelDisplayName != null) {\r\n setValueByPath(toObject, [\"tunedModelDisplayName\"], fromTunedModelDisplayName);\r\n }\r\n const fromTuningJobState = getValueByPath(fromObject, [\r\n \"tuningJobState\"\r\n ]);\r\n if (fromTuningJobState != null) {\r\n setValueByPath(toObject, [\"tuningJobState\"], fromTuningJobState);\r\n }\r\n const fromVeoTuningSpec = getValueByPath(fromObject, [\r\n \"veoTuningSpec\"\r\n ]);\r\n if (fromVeoTuningSpec != null) {\r\n setValueByPath(toObject, [\"veoTuningSpec\"], fromVeoTuningSpec);\r\n }\r\n const fromDistillationSamplingSpec = getValueByPath(fromObject, [\r\n \"distillationSamplingSpec\"\r\n ]);\r\n if (fromDistillationSamplingSpec != null) {\r\n setValueByPath(toObject, [\"distillationSamplingSpec\"], fromDistillationSamplingSpec);\r\n }\r\n const fromTuningJobMetadata = getValueByPath(fromObject, [\r\n \"tuningJobMetadata\"\r\n ]);\r\n if (fromTuningJobMetadata != null) {\r\n setValueByPath(toObject, [\"tuningJobMetadata\"], fromTuningJobMetadata);\r\n }\r\n return toObject;\r\n}\r\nfunction tuningOperationFromMldev(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromSdkHttpResponse = getValueByPath(fromObject, [\r\n \"sdkHttpResponse\"\r\n ]);\r\n if (fromSdkHttpResponse != null) {\r\n setValueByPath(toObject, [\"sdkHttpResponse\"], fromSdkHttpResponse);\r\n }\r\n const fromName = getValueByPath(fromObject, [\"name\"]);\r\n if (fromName != null) {\r\n setValueByPath(toObject, [\"name\"], fromName);\r\n }\r\n const fromMetadata = getValueByPath(fromObject, [\"metadata\"]);\r\n if (fromMetadata != null) {\r\n setValueByPath(toObject, [\"metadata\"], fromMetadata);\r\n }\r\n const fromDone = getValueByPath(fromObject, [\"done\"]);\r\n if (fromDone != null) {\r\n setValueByPath(toObject, [\"done\"], fromDone);\r\n }\r\n const fromError = getValueByPath(fromObject, [\"error\"]);\r\n if (fromError != null) {\r\n setValueByPath(toObject, [\"error\"], fromError);\r\n }\r\n return toObject;\r\n}\r\nfunction tuningValidationDatasetToVertex(fromObject, _rootObject) {\r\n const toObject = {};\r\n const fromGcsUri = getValueByPath(fromObject, [\"gcsUri\"]);\r\n if (fromGcsUri != null) {\r\n setValueByPath(toObject, [\"validationDatasetUri\"], fromGcsUri);\r\n }\r\n const fromVertexDatasetResource = getValueByPath(fromObject, [\r\n \"vertexDatasetResource\"\r\n ]);\r\n if (fromVertexDatasetResource != null) {\r\n setValueByPath(toObject, [\"validationDatasetUri\"], fromVertexDatasetResource);\r\n }\r\n return toObject;\r\n}\r\nasync function uploadBlob(file, uploadUrl, apiClient, httpOptions) {\r\n var _a2;\r\n const response = await uploadBlobInternal(file, uploadUrl, apiClient, httpOptions);\r\n const responseJson = await (response === null || response === void 0 ? void 0 : response.json());\r\n if (((_a2 = response === null || response === void 0 ? void 0 : response.headers) === null || _a2 === void 0 ? void 0 : _a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== \"final\") {\r\n throw new Error(\"Failed to upload file: Upload status is not finalized.\");\r\n }\r\n return responseJson[\"file\"];\r\n}\r\nasync function uploadBlobToFileSearchStore(file, uploadUrl, apiClient, httpOptions) {\r\n var _a2;\r\n const response = await uploadBlobInternal(file, uploadUrl, apiClient, httpOptions);\r\n const responseJson = await (response === null || response === void 0 ? void 0 : response.json());\r\n if (((_a2 = response === null || response === void 0 ? void 0 : response.headers) === null || _a2 === void 0 ? void 0 : _a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== \"final\") {\r\n throw new Error(\"Failed to upload file: Upload status is not finalized.\");\r\n }\r\n const resp = uploadToFileSearchStoreOperationFromMldev(responseJson);\r\n const typedResp = new UploadToFileSearchStoreOperation();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n}\r\nasync function uploadBlobInternal(file, uploadUrl, apiClient, httpOptions) {\r\n var _a2, _b, _c;\r\n let finalUrl = uploadUrl;\r\n const effectiveBaseUrl = (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.baseUrl) || ((_a2 = apiClient.clientOptions.httpOptions) === null || _a2 === void 0 ? void 0 : _a2.baseUrl);\r\n if (effectiveBaseUrl) {\r\n const baseUri = new URL(effectiveBaseUrl);\r\n const uploadUri = new URL(uploadUrl);\r\n uploadUri.protocol = baseUri.protocol;\r\n uploadUri.host = baseUri.host;\r\n uploadUri.port = baseUri.port;\r\n finalUrl = uploadUri.toString();\r\n }\r\n let fileSize = 0;\r\n let offset = 0;\r\n let response = new HttpResponse(new Response());\r\n let uploadCommand = \"upload\";\r\n fileSize = file.size;\r\n while (offset < fileSize) {\r\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\r\n const chunk = file.slice(offset, offset + chunkSize);\r\n if (offset + chunkSize >= fileSize) {\r\n uploadCommand += \", finalize\";\r\n }\r\n let retryCount = 0;\r\n let currentDelayMs = INITIAL_RETRY_DELAY_MS;\r\n while (retryCount < MAX_RETRY_COUNT) {\r\n const mergedHeaders = Object.assign(Object.assign({}, (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.headers) || {}), { \"X-Goog-Upload-Command\": uploadCommand, \"X-Goog-Upload-Offset\": String(offset), \"Content-Length\": String(chunkSize) });\r\n response = await apiClient.request({\r\n path: \"\",\r\n body: chunk,\r\n httpMethod: \"POST\",\r\n httpOptions: Object.assign(Object.assign({}, httpOptions), { apiVersion: \"\", baseUrl: finalUrl, headers: mergedHeaders })\r\n });\r\n if ((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {\r\n break;\r\n }\r\n retryCount++;\r\n await sleep(currentDelayMs);\r\n currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;\r\n }\r\n offset += chunkSize;\r\n if (((_c = response === null || response === void 0 ? void 0 : response.headers) === null || _c === void 0 ? void 0 : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== \"active\") {\r\n break;\r\n }\r\n if (fileSize <= offset) {\r\n throw new Error(\"All content has been uploaded, but the upload status is not finalized.\");\r\n }\r\n }\r\n return response;\r\n}\r\nasync function getBlobStat(file) {\r\n const fileStat = { size: file.size, type: file.type };\r\n return fileStat;\r\n}\r\nfunction sleep(ms) {\r\n return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));\r\n}\r\nvar import_p_retry, _defaultBaseGeminiUrl, _defaultBaseVertexUrl, BaseModule, Language, Outcome, FunctionResponseScheduling, Type, Environment, AuthType, HttpElementLocation, ApiSpec, PhishBlockThreshold, Behavior, DynamicRetrievalConfigMode, FunctionCallingConfigMode, ThinkingLevel, PersonGeneration, ProminentPeople, HarmCategory, HarmBlockMethod, HarmBlockThreshold, FinishReason, HarmProbability, HarmSeverity, UrlRetrievalStatus, BlockedReason, TrafficType, Modality, ModelStage, MediaResolution, TuningMode, AdapterSize, JobState, TuningJobState, AggregationMetric, PairwiseChoice, TuningTask, DocumentState, PartMediaResolutionLevel, ToolType, ResourceScope, ServiceTier, FeatureSelectionPreference, EmbeddingApiType, SafetyFilterLevel, ImagePromptLanguage, MaskReferenceMode, ControlReferenceType, SubjectReferenceType, EditMode, SegmentMode, VideoGenerationReferenceType, VideoGenerationMaskMode, VideoCompressionQuality, TuningMethod, FileState, FileSource, TurnCompleteReason, MediaModality, VadSignalType, VoiceActivityType, StartSensitivity, EndSensitivity, ActivityHandling, TurnCoverage, Scale, MusicGenerationMode, LiveMusicPlaybackControl, ToolResponse, FunctionResponseBlob, FunctionResponseFileData, FunctionResponsePart, FunctionResponse, HttpResponse, GenerateContentResponsePromptFeedback, GenerateContentResponseUsageMetadata, GenerateContentResponse, EmbedContentResponse, GenerateImagesResponse, EditImageResponse, UpscaleImageResponse, RecontextImageResponse, SegmentImageResponse, ListModelsResponse, DeleteModelResponse, CountTokensResponse, ComputeTokensResponse, GenerateVideosResponse, GenerateVideosOperation, EvaluateDatasetResponse, ListTuningJobsResponse, CancelTuningJobResponse, DeleteCachedContentResponse, ListCachedContentsResponse, ListDocumentsResponse, ListFileSearchStoresResponse, UploadToFileSearchStoreResumableResponse, ImportFileResponse, ImportFileOperation, ListFilesResponse, CreateFileResponse, DeleteFileResponse, RegisterFilesResponse, InlinedResponse, SingleEmbedContentResponse, InlinedEmbedContentResponse, ListBatchJobsResponse, ReplayResponse, RawReferenceImage, MaskReferenceImage, ControlReferenceImage, StyleReferenceImage, SubjectReferenceImage, ContentReferenceImage, LiveServerMessage, LiveClientToolResponse, LiveSendToolResponseParameters, LiveMusicServerMessage, UploadToFileSearchStoreResponse, UploadToFileSearchStoreOperation, PagedItem, Pager, Batches, Caches, Chats, Chat, ApiError, Files, CONTENT_TYPE_HEADER, SERVER_TIMEOUT_HEADER, USER_AGENT_HEADER, GOOGLE_API_CLIENT_HEADER, SDK_VERSION, LIBRARY_LABEL, VERTEX_AI_API_DEFAULT_VERSION, GOOGLE_AI_API_DEFAULT_VERSION, DEFAULT_RETRY_ATTEMPTS, DEFAULT_RETRY_HTTP_STATUS_CODES, ApiClient, MCP_LABEL, hasMcpToolUsageFromMcpToTool, McpCallableTool, LiveMusic, LiveMusicSession, FUNCTION_RESPONSE_REQUIRES_ID, Live, defaultLiveSendClientContentParamerters, Session, DEFAULT_MAX_REMOTE_CALLS, Models, Operations, Tokens, Documents, FileSearchStores, uuid4Internal, uuid4, castToError, GeminiNextGenAPIClientError, APIError, APIUserAbortError, APIConnectionError, APIConnectionTimeoutError, BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError, startsWithSchemeRegexp, isAbsoluteURL, isArrayInternal, isArray, isReadonlyArrayInternal, isReadonlyArray, validatePositiveInteger, safeJSON, sleep$1, FallbackEncoder, VERSION, checkFileSupport, isAsyncIterable, isBlobLike, isFileLike, isResponseLike, APIResource, EMPTY, createPathTagFunction, path, BaseInteractions, Interactions, encodeUTF8_, decodeUTF8_, LineDecoder, levelNumbers, parseLogLevel, noopLogger, cachedLoggers, formatRequestDetails, Stream, SSEDecoder, APIPromise, brand_privateNullableHeaders, buildHeaders, readEnv, _a, BaseGeminiNextGenAPIClient, GeminiNextGenAPIClient, Tunings, BrowserDownloader, MAX_CHUNK_SIZE, MAX_RETRY_COUNT, INITIAL_RETRY_DELAY_MS, DELAY_MULTIPLIER, X_GOOG_UPLOAD_STATUS_HEADER_FIELD, BrowserUploader, BrowserWebSocketFactory, BrowserWebSocket, GOOGLE_API_KEY_HEADER, WebAuth, LANGUAGE_LABEL_PREFIX, GoogleGenAI;\r\nvar init_web = __esm({\r\n \"node_modules/@google/genai/dist/web/index.mjs\"() {\r\n import_p_retry = __toESM(require_p_retry(), 1);\r\n _defaultBaseGeminiUrl = void 0;\r\n _defaultBaseVertexUrl = void 0;\r\n BaseModule = class {\r\n };\r\n (function(Language2) {\r\n Language2[\"LANGUAGE_UNSPECIFIED\"] = \"LANGUAGE_UNSPECIFIED\";\r\n Language2[\"PYTHON\"] = \"PYTHON\";\r\n })(Language || (Language = {}));\r\n (function(Outcome2) {\r\n Outcome2[\"OUTCOME_UNSPECIFIED\"] = \"OUTCOME_UNSPECIFIED\";\r\n Outcome2[\"OUTCOME_OK\"] = \"OUTCOME_OK\";\r\n Outcome2[\"OUTCOME_FAILED\"] = \"OUTCOME_FAILED\";\r\n Outcome2[\"OUTCOME_DEADLINE_EXCEEDED\"] = \"OUTCOME_DEADLINE_EXCEEDED\";\r\n })(Outcome || (Outcome = {}));\r\n (function(FunctionResponseScheduling2) {\r\n FunctionResponseScheduling2[\"SCHEDULING_UNSPECIFIED\"] = \"SCHEDULING_UNSPECIFIED\";\r\n FunctionResponseScheduling2[\"SILENT\"] = \"SILENT\";\r\n FunctionResponseScheduling2[\"WHEN_IDLE\"] = \"WHEN_IDLE\";\r\n FunctionResponseScheduling2[\"INTERRUPT\"] = \"INTERRUPT\";\r\n })(FunctionResponseScheduling || (FunctionResponseScheduling = {}));\r\n (function(Type2) {\r\n Type2[\"TYPE_UNSPECIFIED\"] = \"TYPE_UNSPECIFIED\";\r\n Type2[\"STRING\"] = \"STRING\";\r\n Type2[\"NUMBER\"] = \"NUMBER\";\r\n Type2[\"INTEGER\"] = \"INTEGER\";\r\n Type2[\"BOOLEAN\"] = \"BOOLEAN\";\r\n Type2[\"ARRAY\"] = \"ARRAY\";\r\n Type2[\"OBJECT\"] = \"OBJECT\";\r\n Type2[\"NULL\"] = \"NULL\";\r\n })(Type || (Type = {}));\r\n (function(Environment2) {\r\n Environment2[\"ENVIRONMENT_UNSPECIFIED\"] = \"ENVIRONMENT_UNSPECIFIED\";\r\n Environment2[\"ENVIRONMENT_BROWSER\"] = \"ENVIRONMENT_BROWSER\";\r\n })(Environment || (Environment = {}));\r\n (function(AuthType2) {\r\n AuthType2[\"AUTH_TYPE_UNSPECIFIED\"] = \"AUTH_TYPE_UNSPECIFIED\";\r\n AuthType2[\"NO_AUTH\"] = \"NO_AUTH\";\r\n AuthType2[\"API_KEY_AUTH\"] = \"API_KEY_AUTH\";\r\n AuthType2[\"HTTP_BASIC_AUTH\"] = \"HTTP_BASIC_AUTH\";\r\n AuthType2[\"GOOGLE_SERVICE_ACCOUNT_AUTH\"] = \"GOOGLE_SERVICE_ACCOUNT_AUTH\";\r\n AuthType2[\"OAUTH\"] = \"OAUTH\";\r\n AuthType2[\"OIDC_AUTH\"] = \"OIDC_AUTH\";\r\n })(AuthType || (AuthType = {}));\r\n (function(HttpElementLocation2) {\r\n HttpElementLocation2[\"HTTP_IN_UNSPECIFIED\"] = \"HTTP_IN_UNSPECIFIED\";\r\n HttpElementLocation2[\"HTTP_IN_QUERY\"] = \"HTTP_IN_QUERY\";\r\n HttpElementLocation2[\"HTTP_IN_HEADER\"] = \"HTTP_IN_HEADER\";\r\n HttpElementLocation2[\"HTTP_IN_PATH\"] = \"HTTP_IN_PATH\";\r\n HttpElementLocation2[\"HTTP_IN_BODY\"] = \"HTTP_IN_BODY\";\r\n HttpElementLocation2[\"HTTP_IN_COOKIE\"] = \"HTTP_IN_COOKIE\";\r\n })(HttpElementLocation || (HttpElementLocation = {}));\r\n (function(ApiSpec2) {\r\n ApiSpec2[\"API_SPEC_UNSPECIFIED\"] = \"API_SPEC_UNSPECIFIED\";\r\n ApiSpec2[\"SIMPLE_SEARCH\"] = \"SIMPLE_SEARCH\";\r\n ApiSpec2[\"ELASTIC_SEARCH\"] = \"ELASTIC_SEARCH\";\r\n })(ApiSpec || (ApiSpec = {}));\r\n (function(PhishBlockThreshold2) {\r\n PhishBlockThreshold2[\"PHISH_BLOCK_THRESHOLD_UNSPECIFIED\"] = \"PHISH_BLOCK_THRESHOLD_UNSPECIFIED\";\r\n PhishBlockThreshold2[\"BLOCK_LOW_AND_ABOVE\"] = \"BLOCK_LOW_AND_ABOVE\";\r\n PhishBlockThreshold2[\"BLOCK_MEDIUM_AND_ABOVE\"] = \"BLOCK_MEDIUM_AND_ABOVE\";\r\n PhishBlockThreshold2[\"BLOCK_HIGH_AND_ABOVE\"] = \"BLOCK_HIGH_AND_ABOVE\";\r\n PhishBlockThreshold2[\"BLOCK_HIGHER_AND_ABOVE\"] = \"BLOCK_HIGHER_AND_ABOVE\";\r\n PhishBlockThreshold2[\"BLOCK_VERY_HIGH_AND_ABOVE\"] = \"BLOCK_VERY_HIGH_AND_ABOVE\";\r\n PhishBlockThreshold2[\"BLOCK_ONLY_EXTREMELY_HIGH\"] = \"BLOCK_ONLY_EXTREMELY_HIGH\";\r\n })(PhishBlockThreshold || (PhishBlockThreshold = {}));\r\n (function(Behavior2) {\r\n Behavior2[\"UNSPECIFIED\"] = \"UNSPECIFIED\";\r\n Behavior2[\"BLOCKING\"] = \"BLOCKING\";\r\n Behavior2[\"NON_BLOCKING\"] = \"NON_BLOCKING\";\r\n })(Behavior || (Behavior = {}));\r\n (function(DynamicRetrievalConfigMode2) {\r\n DynamicRetrievalConfigMode2[\"MODE_UNSPECIFIED\"] = \"MODE_UNSPECIFIED\";\r\n DynamicRetrievalConfigMode2[\"MODE_DYNAMIC\"] = \"MODE_DYNAMIC\";\r\n })(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {}));\r\n (function(FunctionCallingConfigMode2) {\r\n FunctionCallingConfigMode2[\"MODE_UNSPECIFIED\"] = \"MODE_UNSPECIFIED\";\r\n FunctionCallingConfigMode2[\"AUTO\"] = \"AUTO\";\r\n FunctionCallingConfigMode2[\"ANY\"] = \"ANY\";\r\n FunctionCallingConfigMode2[\"NONE\"] = \"NONE\";\r\n FunctionCallingConfigMode2[\"VALIDATED\"] = \"VALIDATED\";\r\n })(FunctionCallingConfigMode || (FunctionCallingConfigMode = {}));\r\n (function(ThinkingLevel2) {\r\n ThinkingLevel2[\"THINKING_LEVEL_UNSPECIFIED\"] = \"THINKING_LEVEL_UNSPECIFIED\";\r\n ThinkingLevel2[\"MINIMAL\"] = \"MINIMAL\";\r\n ThinkingLevel2[\"LOW\"] = \"LOW\";\r\n ThinkingLevel2[\"MEDIUM\"] = \"MEDIUM\";\r\n ThinkingLevel2[\"HIGH\"] = \"HIGH\";\r\n })(ThinkingLevel || (ThinkingLevel = {}));\r\n (function(PersonGeneration2) {\r\n PersonGeneration2[\"DONT_ALLOW\"] = \"DONT_ALLOW\";\r\n PersonGeneration2[\"ALLOW_ADULT\"] = \"ALLOW_ADULT\";\r\n PersonGeneration2[\"ALLOW_ALL\"] = \"ALLOW_ALL\";\r\n })(PersonGeneration || (PersonGeneration = {}));\r\n (function(ProminentPeople2) {\r\n ProminentPeople2[\"PROMINENT_PEOPLE_UNSPECIFIED\"] = \"PROMINENT_PEOPLE_UNSPECIFIED\";\r\n ProminentPeople2[\"ALLOW_PROMINENT_PEOPLE\"] = \"ALLOW_PROMINENT_PEOPLE\";\r\n ProminentPeople2[\"BLOCK_PROMINENT_PEOPLE\"] = \"BLOCK_PROMINENT_PEOPLE\";\r\n })(ProminentPeople || (ProminentPeople = {}));\r\n (function(HarmCategory2) {\r\n HarmCategory2[\"HARM_CATEGORY_UNSPECIFIED\"] = \"HARM_CATEGORY_UNSPECIFIED\";\r\n HarmCategory2[\"HARM_CATEGORY_HARASSMENT\"] = \"HARM_CATEGORY_HARASSMENT\";\r\n HarmCategory2[\"HARM_CATEGORY_HATE_SPEECH\"] = \"HARM_CATEGORY_HATE_SPEECH\";\r\n HarmCategory2[\"HARM_CATEGORY_SEXUALLY_EXPLICIT\"] = \"HARM_CATEGORY_SEXUALLY_EXPLICIT\";\r\n HarmCategory2[\"HARM_CATEGORY_DANGEROUS_CONTENT\"] = \"HARM_CATEGORY_DANGEROUS_CONTENT\";\r\n HarmCategory2[\"HARM_CATEGORY_CIVIC_INTEGRITY\"] = \"HARM_CATEGORY_CIVIC_INTEGRITY\";\r\n HarmCategory2[\"HARM_CATEGORY_IMAGE_HATE\"] = \"HARM_CATEGORY_IMAGE_HATE\";\r\n HarmCategory2[\"HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT\"] = \"HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT\";\r\n HarmCategory2[\"HARM_CATEGORY_IMAGE_HARASSMENT\"] = \"HARM_CATEGORY_IMAGE_HARASSMENT\";\r\n HarmCategory2[\"HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT\"] = \"HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT\";\r\n HarmCategory2[\"HARM_CATEGORY_JAILBREAK\"] = \"HARM_CATEGORY_JAILBREAK\";\r\n })(HarmCategory || (HarmCategory = {}));\r\n (function(HarmBlockMethod2) {\r\n HarmBlockMethod2[\"HARM_BLOCK_METHOD_UNSPECIFIED\"] = \"HARM_BLOCK_METHOD_UNSPECIFIED\";\r\n HarmBlockMethod2[\"SEVERITY\"] = \"SEVERITY\";\r\n HarmBlockMethod2[\"PROBABILITY\"] = \"PROBABILITY\";\r\n })(HarmBlockMethod || (HarmBlockMethod = {}));\r\n (function(HarmBlockThreshold2) {\r\n HarmBlockThreshold2[\"HARM_BLOCK_THRESHOLD_UNSPECIFIED\"] = \"HARM_BLOCK_THRESHOLD_UNSPECIFIED\";\r\n HarmBlockThreshold2[\"BLOCK_LOW_AND_ABOVE\"] = \"BLOCK_LOW_AND_ABOVE\";\r\n HarmBlockThreshold2[\"BLOCK_MEDIUM_AND_ABOVE\"] = \"BLOCK_MEDIUM_AND_ABOVE\";\r\n HarmBlockThreshold2[\"BLOCK_ONLY_HIGH\"] = \"BLOCK_ONLY_HIGH\";\r\n HarmBlockThreshold2[\"BLOCK_NONE\"] = \"BLOCK_NONE\";\r\n HarmBlockThreshold2[\"OFF\"] = \"OFF\";\r\n })(HarmBlockThreshold || (HarmBlockThreshold = {}));\r\n (function(FinishReason2) {\r\n FinishReason2[\"FINISH_REASON_UNSPECIFIED\"] = \"FINISH_REASON_UNSPECIFIED\";\r\n FinishReason2[\"STOP\"] = \"STOP\";\r\n FinishReason2[\"MAX_TOKENS\"] = \"MAX_TOKENS\";\r\n FinishReason2[\"SAFETY\"] = \"SAFETY\";\r\n FinishReason2[\"RECITATION\"] = \"RECITATION\";\r\n FinishReason2[\"LANGUAGE\"] = \"LANGUAGE\";\r\n FinishReason2[\"OTHER\"] = \"OTHER\";\r\n FinishReason2[\"BLOCKLIST\"] = \"BLOCKLIST\";\r\n FinishReason2[\"PROHIBITED_CONTENT\"] = \"PROHIBITED_CONTENT\";\r\n FinishReason2[\"SPII\"] = \"SPII\";\r\n FinishReason2[\"MALFORMED_FUNCTION_CALL\"] = \"MALFORMED_FUNCTION_CALL\";\r\n FinishReason2[\"IMAGE_SAFETY\"] = \"IMAGE_SAFETY\";\r\n FinishReason2[\"UNEXPECTED_TOOL_CALL\"] = \"UNEXPECTED_TOOL_CALL\";\r\n FinishReason2[\"IMAGE_PROHIBITED_CONTENT\"] = \"IMAGE_PROHIBITED_CONTENT\";\r\n FinishReason2[\"NO_IMAGE\"] = \"NO_IMAGE\";\r\n FinishReason2[\"IMAGE_RECITATION\"] = \"IMAGE_RECITATION\";\r\n FinishReason2[\"IMAGE_OTHER\"] = \"IMAGE_OTHER\";\r\n })(FinishReason || (FinishReason = {}));\r\n (function(HarmProbability2) {\r\n HarmProbability2[\"HARM_PROBABILITY_UNSPECIFIED\"] = \"HARM_PROBABILITY_UNSPECIFIED\";\r\n HarmProbability2[\"NEGLIGIBLE\"] = \"NEGLIGIBLE\";\r\n HarmProbability2[\"LOW\"] = \"LOW\";\r\n HarmProbability2[\"MEDIUM\"] = \"MEDIUM\";\r\n HarmProbability2[\"HIGH\"] = \"HIGH\";\r\n })(HarmProbability || (HarmProbability = {}));\r\n (function(HarmSeverity2) {\r\n HarmSeverity2[\"HARM_SEVERITY_UNSPECIFIED\"] = \"HARM_SEVERITY_UNSPECIFIED\";\r\n HarmSeverity2[\"HARM_SEVERITY_NEGLIGIBLE\"] = \"HARM_SEVERITY_NEGLIGIBLE\";\r\n HarmSeverity2[\"HARM_SEVERITY_LOW\"] = \"HARM_SEVERITY_LOW\";\r\n HarmSeverity2[\"HARM_SEVERITY_MEDIUM\"] = \"HARM_SEVERITY_MEDIUM\";\r\n HarmSeverity2[\"HARM_SEVERITY_HIGH\"] = \"HARM_SEVERITY_HIGH\";\r\n })(HarmSeverity || (HarmSeverity = {}));\r\n (function(UrlRetrievalStatus2) {\r\n UrlRetrievalStatus2[\"URL_RETRIEVAL_STATUS_UNSPECIFIED\"] = \"URL_RETRIEVAL_STATUS_UNSPECIFIED\";\r\n UrlRetrievalStatus2[\"URL_RETRIEVAL_STATUS_SUCCESS\"] = \"URL_RETRIEVAL_STATUS_SUCCESS\";\r\n UrlRetrievalStatus2[\"URL_RETRIEVAL_STATUS_ERROR\"] = \"URL_RETRIEVAL_STATUS_ERROR\";\r\n UrlRetrievalStatus2[\"URL_RETRIEVAL_STATUS_PAYWALL\"] = \"URL_RETRIEVAL_STATUS_PAYWALL\";\r\n UrlRetrievalStatus2[\"URL_RETRIEVAL_STATUS_UNSAFE\"] = \"URL_RETRIEVAL_STATUS_UNSAFE\";\r\n })(UrlRetrievalStatus || (UrlRetrievalStatus = {}));\r\n (function(BlockedReason2) {\r\n BlockedReason2[\"BLOCKED_REASON_UNSPECIFIED\"] = \"BLOCKED_REASON_UNSPECIFIED\";\r\n BlockedReason2[\"SAFETY\"] = \"SAFETY\";\r\n BlockedReason2[\"OTHER\"] = \"OTHER\";\r\n BlockedReason2[\"BLOCKLIST\"] = \"BLOCKLIST\";\r\n BlockedReason2[\"PROHIBITED_CONTENT\"] = \"PROHIBITED_CONTENT\";\r\n BlockedReason2[\"IMAGE_SAFETY\"] = \"IMAGE_SAFETY\";\r\n BlockedReason2[\"MODEL_ARMOR\"] = \"MODEL_ARMOR\";\r\n BlockedReason2[\"JAILBREAK\"] = \"JAILBREAK\";\r\n })(BlockedReason || (BlockedReason = {}));\r\n (function(TrafficType2) {\r\n TrafficType2[\"TRAFFIC_TYPE_UNSPECIFIED\"] = \"TRAFFIC_TYPE_UNSPECIFIED\";\r\n TrafficType2[\"ON_DEMAND\"] = \"ON_DEMAND\";\r\n TrafficType2[\"ON_DEMAND_PRIORITY\"] = \"ON_DEMAND_PRIORITY\";\r\n TrafficType2[\"ON_DEMAND_FLEX\"] = \"ON_DEMAND_FLEX\";\r\n TrafficType2[\"PROVISIONED_THROUGHPUT\"] = \"PROVISIONED_THROUGHPUT\";\r\n })(TrafficType || (TrafficType = {}));\r\n (function(Modality2) {\r\n Modality2[\"MODALITY_UNSPECIFIED\"] = \"MODALITY_UNSPECIFIED\";\r\n Modality2[\"TEXT\"] = \"TEXT\";\r\n Modality2[\"IMAGE\"] = \"IMAGE\";\r\n Modality2[\"AUDIO\"] = \"AUDIO\";\r\n })(Modality || (Modality = {}));\r\n (function(ModelStage2) {\r\n ModelStage2[\"MODEL_STAGE_UNSPECIFIED\"] = \"MODEL_STAGE_UNSPECIFIED\";\r\n ModelStage2[\"UNSTABLE_EXPERIMENTAL\"] = \"UNSTABLE_EXPERIMENTAL\";\r\n ModelStage2[\"EXPERIMENTAL\"] = \"EXPERIMENTAL\";\r\n ModelStage2[\"PREVIEW\"] = \"PREVIEW\";\r\n ModelStage2[\"STABLE\"] = \"STABLE\";\r\n ModelStage2[\"LEGACY\"] = \"LEGACY\";\r\n ModelStage2[\"DEPRECATED\"] = \"DEPRECATED\";\r\n ModelStage2[\"RETIRED\"] = \"RETIRED\";\r\n })(ModelStage || (ModelStage = {}));\r\n (function(MediaResolution2) {\r\n MediaResolution2[\"MEDIA_RESOLUTION_UNSPECIFIED\"] = \"MEDIA_RESOLUTION_UNSPECIFIED\";\r\n MediaResolution2[\"MEDIA_RESOLUTION_LOW\"] = \"MEDIA_RESOLUTION_LOW\";\r\n MediaResolution2[\"MEDIA_RESOLUTION_MEDIUM\"] = \"MEDIA_RESOLUTION_MEDIUM\";\r\n MediaResolution2[\"MEDIA_RESOLUTION_HIGH\"] = \"MEDIA_RESOLUTION_HIGH\";\r\n })(MediaResolution || (MediaResolution = {}));\r\n (function(TuningMode2) {\r\n TuningMode2[\"TUNING_MODE_UNSPECIFIED\"] = \"TUNING_MODE_UNSPECIFIED\";\r\n TuningMode2[\"TUNING_MODE_FULL\"] = \"TUNING_MODE_FULL\";\r\n TuningMode2[\"TUNING_MODE_PEFT_ADAPTER\"] = \"TUNING_MODE_PEFT_ADAPTER\";\r\n })(TuningMode || (TuningMode = {}));\r\n (function(AdapterSize2) {\r\n AdapterSize2[\"ADAPTER_SIZE_UNSPECIFIED\"] = \"ADAPTER_SIZE_UNSPECIFIED\";\r\n AdapterSize2[\"ADAPTER_SIZE_ONE\"] = \"ADAPTER_SIZE_ONE\";\r\n AdapterSize2[\"ADAPTER_SIZE_TWO\"] = \"ADAPTER_SIZE_TWO\";\r\n AdapterSize2[\"ADAPTER_SIZE_FOUR\"] = \"ADAPTER_SIZE_FOUR\";\r\n AdapterSize2[\"ADAPTER_SIZE_EIGHT\"] = \"ADAPTER_SIZE_EIGHT\";\r\n AdapterSize2[\"ADAPTER_SIZE_SIXTEEN\"] = \"ADAPTER_SIZE_SIXTEEN\";\r\n AdapterSize2[\"ADAPTER_SIZE_THIRTY_TWO\"] = \"ADAPTER_SIZE_THIRTY_TWO\";\r\n })(AdapterSize || (AdapterSize = {}));\r\n (function(JobState2) {\r\n JobState2[\"JOB_STATE_UNSPECIFIED\"] = \"JOB_STATE_UNSPECIFIED\";\r\n JobState2[\"JOB_STATE_QUEUED\"] = \"JOB_STATE_QUEUED\";\r\n JobState2[\"JOB_STATE_PENDING\"] = \"JOB_STATE_PENDING\";\r\n JobState2[\"JOB_STATE_RUNNING\"] = \"JOB_STATE_RUNNING\";\r\n JobState2[\"JOB_STATE_SUCCEEDED\"] = \"JOB_STATE_SUCCEEDED\";\r\n JobState2[\"JOB_STATE_FAILED\"] = \"JOB_STATE_FAILED\";\r\n JobState2[\"JOB_STATE_CANCELLING\"] = \"JOB_STATE_CANCELLING\";\r\n JobState2[\"JOB_STATE_CANCELLED\"] = \"JOB_STATE_CANCELLED\";\r\n JobState2[\"JOB_STATE_PAUSED\"] = \"JOB_STATE_PAUSED\";\r\n JobState2[\"JOB_STATE_EXPIRED\"] = \"JOB_STATE_EXPIRED\";\r\n JobState2[\"JOB_STATE_UPDATING\"] = \"JOB_STATE_UPDATING\";\r\n JobState2[\"JOB_STATE_PARTIALLY_SUCCEEDED\"] = \"JOB_STATE_PARTIALLY_SUCCEEDED\";\r\n })(JobState || (JobState = {}));\r\n (function(TuningJobState2) {\r\n TuningJobState2[\"TUNING_JOB_STATE_UNSPECIFIED\"] = \"TUNING_JOB_STATE_UNSPECIFIED\";\r\n TuningJobState2[\"TUNING_JOB_STATE_WAITING_FOR_QUOTA\"] = \"TUNING_JOB_STATE_WAITING_FOR_QUOTA\";\r\n TuningJobState2[\"TUNING_JOB_STATE_PROCESSING_DATASET\"] = \"TUNING_JOB_STATE_PROCESSING_DATASET\";\r\n TuningJobState2[\"TUNING_JOB_STATE_WAITING_FOR_CAPACITY\"] = \"TUNING_JOB_STATE_WAITING_FOR_CAPACITY\";\r\n TuningJobState2[\"TUNING_JOB_STATE_TUNING\"] = \"TUNING_JOB_STATE_TUNING\";\r\n TuningJobState2[\"TUNING_JOB_STATE_POST_PROCESSING\"] = \"TUNING_JOB_STATE_POST_PROCESSING\";\r\n })(TuningJobState || (TuningJobState = {}));\r\n (function(AggregationMetric2) {\r\n AggregationMetric2[\"AGGREGATION_METRIC_UNSPECIFIED\"] = \"AGGREGATION_METRIC_UNSPECIFIED\";\r\n AggregationMetric2[\"AVERAGE\"] = \"AVERAGE\";\r\n AggregationMetric2[\"MODE\"] = \"MODE\";\r\n AggregationMetric2[\"STANDARD_DEVIATION\"] = \"STANDARD_DEVIATION\";\r\n AggregationMetric2[\"VARIANCE\"] = \"VARIANCE\";\r\n AggregationMetric2[\"MINIMUM\"] = \"MINIMUM\";\r\n AggregationMetric2[\"MAXIMUM\"] = \"MAXIMUM\";\r\n AggregationMetric2[\"MEDIAN\"] = \"MEDIAN\";\r\n AggregationMetric2[\"PERCENTILE_P90\"] = \"PERCENTILE_P90\";\r\n AggregationMetric2[\"PERCENTILE_P95\"] = \"PERCENTILE_P95\";\r\n AggregationMetric2[\"PERCENTILE_P99\"] = \"PERCENTILE_P99\";\r\n })(AggregationMetric || (AggregationMetric = {}));\r\n (function(PairwiseChoice2) {\r\n PairwiseChoice2[\"PAIRWISE_CHOICE_UNSPECIFIED\"] = \"PAIRWISE_CHOICE_UNSPECIFIED\";\r\n PairwiseChoice2[\"BASELINE\"] = \"BASELINE\";\r\n PairwiseChoice2[\"CANDIDATE\"] = \"CANDIDATE\";\r\n PairwiseChoice2[\"TIE\"] = \"TIE\";\r\n })(PairwiseChoice || (PairwiseChoice = {}));\r\n (function(TuningTask2) {\r\n TuningTask2[\"TUNING_TASK_UNSPECIFIED\"] = \"TUNING_TASK_UNSPECIFIED\";\r\n TuningTask2[\"TUNING_TASK_I2V\"] = \"TUNING_TASK_I2V\";\r\n TuningTask2[\"TUNING_TASK_T2V\"] = \"TUNING_TASK_T2V\";\r\n TuningTask2[\"TUNING_TASK_R2V\"] = \"TUNING_TASK_R2V\";\r\n })(TuningTask || (TuningTask = {}));\r\n (function(DocumentState2) {\r\n DocumentState2[\"STATE_UNSPECIFIED\"] = \"STATE_UNSPECIFIED\";\r\n DocumentState2[\"STATE_PENDING\"] = \"STATE_PENDING\";\r\n DocumentState2[\"STATE_ACTIVE\"] = \"STATE_ACTIVE\";\r\n DocumentState2[\"STATE_FAILED\"] = \"STATE_FAILED\";\r\n })(DocumentState || (DocumentState = {}));\r\n (function(PartMediaResolutionLevel2) {\r\n PartMediaResolutionLevel2[\"MEDIA_RESOLUTION_UNSPECIFIED\"] = \"MEDIA_RESOLUTION_UNSPECIFIED\";\r\n PartMediaResolutionLevel2[\"MEDIA_RESOLUTION_LOW\"] = \"MEDIA_RESOLUTION_LOW\";\r\n PartMediaResolutionLevel2[\"MEDIA_RESOLUTION_MEDIUM\"] = \"MEDIA_RESOLUTION_MEDIUM\";\r\n PartMediaResolutionLevel2[\"MEDIA_RESOLUTION_HIGH\"] = \"MEDIA_RESOLUTION_HIGH\";\r\n PartMediaResolutionLevel2[\"MEDIA_RESOLUTION_ULTRA_HIGH\"] = \"MEDIA_RESOLUTION_ULTRA_HIGH\";\r\n })(PartMediaResolutionLevel || (PartMediaResolutionLevel = {}));\r\n (function(ToolType2) {\r\n ToolType2[\"TOOL_TYPE_UNSPECIFIED\"] = \"TOOL_TYPE_UNSPECIFIED\";\r\n ToolType2[\"GOOGLE_SEARCH_WEB\"] = \"GOOGLE_SEARCH_WEB\";\r\n ToolType2[\"GOOGLE_SEARCH_IMAGE\"] = \"GOOGLE_SEARCH_IMAGE\";\r\n ToolType2[\"URL_CONTEXT\"] = \"URL_CONTEXT\";\r\n ToolType2[\"GOOGLE_MAPS\"] = \"GOOGLE_MAPS\";\r\n ToolType2[\"FILE_SEARCH\"] = \"FILE_SEARCH\";\r\n })(ToolType || (ToolType = {}));\r\n (function(ResourceScope2) {\r\n ResourceScope2[\"COLLECTION\"] = \"COLLECTION\";\r\n })(ResourceScope || (ResourceScope = {}));\r\n (function(ServiceTier2) {\r\n ServiceTier2[\"UNSPECIFIED\"] = \"unspecified\";\r\n ServiceTier2[\"FLEX\"] = \"flex\";\r\n ServiceTier2[\"STANDARD\"] = \"standard\";\r\n ServiceTier2[\"PRIORITY\"] = \"priority\";\r\n })(ServiceTier || (ServiceTier = {}));\r\n (function(FeatureSelectionPreference2) {\r\n FeatureSelectionPreference2[\"FEATURE_SELECTION_PREFERENCE_UNSPECIFIED\"] = \"FEATURE_SELECTION_PREFERENCE_UNSPECIFIED\";\r\n FeatureSelectionPreference2[\"PRIORITIZE_QUALITY\"] = \"PRIORITIZE_QUALITY\";\r\n FeatureSelectionPreference2[\"BALANCED\"] = \"BALANCED\";\r\n FeatureSelectionPreference2[\"PRIORITIZE_COST\"] = \"PRIORITIZE_COST\";\r\n })(FeatureSelectionPreference || (FeatureSelectionPreference = {}));\r\n (function(EmbeddingApiType2) {\r\n EmbeddingApiType2[\"PREDICT\"] = \"PREDICT\";\r\n EmbeddingApiType2[\"EMBED_CONTENT\"] = \"EMBED_CONTENT\";\r\n })(EmbeddingApiType || (EmbeddingApiType = {}));\r\n (function(SafetyFilterLevel2) {\r\n SafetyFilterLevel2[\"BLOCK_LOW_AND_ABOVE\"] = \"BLOCK_LOW_AND_ABOVE\";\r\n SafetyFilterLevel2[\"BLOCK_MEDIUM_AND_ABOVE\"] = \"BLOCK_MEDIUM_AND_ABOVE\";\r\n SafetyFilterLevel2[\"BLOCK_ONLY_HIGH\"] = \"BLOCK_ONLY_HIGH\";\r\n SafetyFilterLevel2[\"BLOCK_NONE\"] = \"BLOCK_NONE\";\r\n })(SafetyFilterLevel || (SafetyFilterLevel = {}));\r\n (function(ImagePromptLanguage2) {\r\n ImagePromptLanguage2[\"auto\"] = \"auto\";\r\n ImagePromptLanguage2[\"en\"] = \"en\";\r\n ImagePromptLanguage2[\"ja\"] = \"ja\";\r\n ImagePromptLanguage2[\"ko\"] = \"ko\";\r\n ImagePromptLanguage2[\"hi\"] = \"hi\";\r\n ImagePromptLanguage2[\"zh\"] = \"zh\";\r\n ImagePromptLanguage2[\"pt\"] = \"pt\";\r\n ImagePromptLanguage2[\"es\"] = \"es\";\r\n })(ImagePromptLanguage || (ImagePromptLanguage = {}));\r\n (function(MaskReferenceMode2) {\r\n MaskReferenceMode2[\"MASK_MODE_DEFAULT\"] = \"MASK_MODE_DEFAULT\";\r\n MaskReferenceMode2[\"MASK_MODE_USER_PROVIDED\"] = \"MASK_MODE_USER_PROVIDED\";\r\n MaskReferenceMode2[\"MASK_MODE_BACKGROUND\"] = \"MASK_MODE_BACKGROUND\";\r\n MaskReferenceMode2[\"MASK_MODE_FOREGROUND\"] = \"MASK_MODE_FOREGROUND\";\r\n MaskReferenceMode2[\"MASK_MODE_SEMANTIC\"] = \"MASK_MODE_SEMANTIC\";\r\n })(MaskReferenceMode || (MaskReferenceMode = {}));\r\n (function(ControlReferenceType2) {\r\n ControlReferenceType2[\"CONTROL_TYPE_DEFAULT\"] = \"CONTROL_TYPE_DEFAULT\";\r\n ControlReferenceType2[\"CONTROL_TYPE_CANNY\"] = \"CONTROL_TYPE_CANNY\";\r\n ControlReferenceType2[\"CONTROL_TYPE_SCRIBBLE\"] = \"CONTROL_TYPE_SCRIBBLE\";\r\n ControlReferenceType2[\"CONTROL_TYPE_FACE_MESH\"] = \"CONTROL_TYPE_FACE_MESH\";\r\n })(ControlReferenceType || (ControlReferenceType = {}));\r\n (function(SubjectReferenceType2) {\r\n SubjectReferenceType2[\"SUBJECT_TYPE_DEFAULT\"] = \"SUBJECT_TYPE_DEFAULT\";\r\n SubjectReferenceType2[\"SUBJECT_TYPE_PERSON\"] = \"SUBJECT_TYPE_PERSON\";\r\n SubjectReferenceType2[\"SUBJECT_TYPE_ANIMAL\"] = \"SUBJECT_TYPE_ANIMAL\";\r\n SubjectReferenceType2[\"SUBJECT_TYPE_PRODUCT\"] = \"SUBJECT_TYPE_PRODUCT\";\r\n })(SubjectReferenceType || (SubjectReferenceType = {}));\r\n (function(EditMode2) {\r\n EditMode2[\"EDIT_MODE_DEFAULT\"] = \"EDIT_MODE_DEFAULT\";\r\n EditMode2[\"EDIT_MODE_INPAINT_REMOVAL\"] = \"EDIT_MODE_INPAINT_REMOVAL\";\r\n EditMode2[\"EDIT_MODE_INPAINT_INSERTION\"] = \"EDIT_MODE_INPAINT_INSERTION\";\r\n EditMode2[\"EDIT_MODE_OUTPAINT\"] = \"EDIT_MODE_OUTPAINT\";\r\n EditMode2[\"EDIT_MODE_CONTROLLED_EDITING\"] = \"EDIT_MODE_CONTROLLED_EDITING\";\r\n EditMode2[\"EDIT_MODE_STYLE\"] = \"EDIT_MODE_STYLE\";\r\n EditMode2[\"EDIT_MODE_BGSWAP\"] = \"EDIT_MODE_BGSWAP\";\r\n EditMode2[\"EDIT_MODE_PRODUCT_IMAGE\"] = \"EDIT_MODE_PRODUCT_IMAGE\";\r\n })(EditMode || (EditMode = {}));\r\n (function(SegmentMode2) {\r\n SegmentMode2[\"FOREGROUND\"] = \"FOREGROUND\";\r\n SegmentMode2[\"BACKGROUND\"] = \"BACKGROUND\";\r\n SegmentMode2[\"PROMPT\"] = \"PROMPT\";\r\n SegmentMode2[\"SEMANTIC\"] = \"SEMANTIC\";\r\n SegmentMode2[\"INTERACTIVE\"] = \"INTERACTIVE\";\r\n })(SegmentMode || (SegmentMode = {}));\r\n (function(VideoGenerationReferenceType2) {\r\n VideoGenerationReferenceType2[\"ASSET\"] = \"ASSET\";\r\n VideoGenerationReferenceType2[\"STYLE\"] = \"STYLE\";\r\n })(VideoGenerationReferenceType || (VideoGenerationReferenceType = {}));\r\n (function(VideoGenerationMaskMode2) {\r\n VideoGenerationMaskMode2[\"INSERT\"] = \"INSERT\";\r\n VideoGenerationMaskMode2[\"REMOVE\"] = \"REMOVE\";\r\n VideoGenerationMaskMode2[\"REMOVE_STATIC\"] = \"REMOVE_STATIC\";\r\n VideoGenerationMaskMode2[\"OUTPAINT\"] = \"OUTPAINT\";\r\n })(VideoGenerationMaskMode || (VideoGenerationMaskMode = {}));\r\n (function(VideoCompressionQuality2) {\r\n VideoCompressionQuality2[\"OPTIMIZED\"] = \"OPTIMIZED\";\r\n VideoCompressionQuality2[\"LOSSLESS\"] = \"LOSSLESS\";\r\n })(VideoCompressionQuality || (VideoCompressionQuality = {}));\r\n (function(TuningMethod2) {\r\n TuningMethod2[\"SUPERVISED_FINE_TUNING\"] = \"SUPERVISED_FINE_TUNING\";\r\n TuningMethod2[\"PREFERENCE_TUNING\"] = \"PREFERENCE_TUNING\";\r\n TuningMethod2[\"DISTILLATION\"] = \"DISTILLATION\";\r\n })(TuningMethod || (TuningMethod = {}));\r\n (function(FileState2) {\r\n FileState2[\"STATE_UNSPECIFIED\"] = \"STATE_UNSPECIFIED\";\r\n FileState2[\"PROCESSING\"] = \"PROCESSING\";\r\n FileState2[\"ACTIVE\"] = \"ACTIVE\";\r\n FileState2[\"FAILED\"] = \"FAILED\";\r\n })(FileState || (FileState = {}));\r\n (function(FileSource2) {\r\n FileSource2[\"SOURCE_UNSPECIFIED\"] = \"SOURCE_UNSPECIFIED\";\r\n FileSource2[\"UPLOADED\"] = \"UPLOADED\";\r\n FileSource2[\"GENERATED\"] = \"GENERATED\";\r\n FileSource2[\"REGISTERED\"] = \"REGISTERED\";\r\n })(FileSource || (FileSource = {}));\r\n (function(TurnCompleteReason2) {\r\n TurnCompleteReason2[\"TURN_COMPLETE_REASON_UNSPECIFIED\"] = \"TURN_COMPLETE_REASON_UNSPECIFIED\";\r\n TurnCompleteReason2[\"MALFORMED_FUNCTION_CALL\"] = \"MALFORMED_FUNCTION_CALL\";\r\n TurnCompleteReason2[\"RESPONSE_REJECTED\"] = \"RESPONSE_REJECTED\";\r\n TurnCompleteReason2[\"NEED_MORE_INPUT\"] = \"NEED_MORE_INPUT\";\r\n })(TurnCompleteReason || (TurnCompleteReason = {}));\r\n (function(MediaModality2) {\r\n MediaModality2[\"MODALITY_UNSPECIFIED\"] = \"MODALITY_UNSPECIFIED\";\r\n MediaModality2[\"TEXT\"] = \"TEXT\";\r\n MediaModality2[\"IMAGE\"] = \"IMAGE\";\r\n MediaModality2[\"VIDEO\"] = \"VIDEO\";\r\n MediaModality2[\"AUDIO\"] = \"AUDIO\";\r\n MediaModality2[\"DOCUMENT\"] = \"DOCUMENT\";\r\n })(MediaModality || (MediaModality = {}));\r\n (function(VadSignalType2) {\r\n VadSignalType2[\"VAD_SIGNAL_TYPE_UNSPECIFIED\"] = \"VAD_SIGNAL_TYPE_UNSPECIFIED\";\r\n VadSignalType2[\"VAD_SIGNAL_TYPE_SOS\"] = \"VAD_SIGNAL_TYPE_SOS\";\r\n VadSignalType2[\"VAD_SIGNAL_TYPE_EOS\"] = \"VAD_SIGNAL_TYPE_EOS\";\r\n })(VadSignalType || (VadSignalType = {}));\r\n (function(VoiceActivityType2) {\r\n VoiceActivityType2[\"TYPE_UNSPECIFIED\"] = \"TYPE_UNSPECIFIED\";\r\n VoiceActivityType2[\"ACTIVITY_START\"] = \"ACTIVITY_START\";\r\n VoiceActivityType2[\"ACTIVITY_END\"] = \"ACTIVITY_END\";\r\n })(VoiceActivityType || (VoiceActivityType = {}));\r\n (function(StartSensitivity2) {\r\n StartSensitivity2[\"START_SENSITIVITY_UNSPECIFIED\"] = \"START_SENSITIVITY_UNSPECIFIED\";\r\n StartSensitivity2[\"START_SENSITIVITY_HIGH\"] = \"START_SENSITIVITY_HIGH\";\r\n StartSensitivity2[\"START_SENSITIVITY_LOW\"] = \"START_SENSITIVITY_LOW\";\r\n })(StartSensitivity || (StartSensitivity = {}));\r\n (function(EndSensitivity2) {\r\n EndSensitivity2[\"END_SENSITIVITY_UNSPECIFIED\"] = \"END_SENSITIVITY_UNSPECIFIED\";\r\n EndSensitivity2[\"END_SENSITIVITY_HIGH\"] = \"END_SENSITIVITY_HIGH\";\r\n EndSensitivity2[\"END_SENSITIVITY_LOW\"] = \"END_SENSITIVITY_LOW\";\r\n })(EndSensitivity || (EndSensitivity = {}));\r\n (function(ActivityHandling2) {\r\n ActivityHandling2[\"ACTIVITY_HANDLING_UNSPECIFIED\"] = \"ACTIVITY_HANDLING_UNSPECIFIED\";\r\n ActivityHandling2[\"START_OF_ACTIVITY_INTERRUPTS\"] = \"START_OF_ACTIVITY_INTERRUPTS\";\r\n ActivityHandling2[\"NO_INTERRUPTION\"] = \"NO_INTERRUPTION\";\r\n })(ActivityHandling || (ActivityHandling = {}));\r\n (function(TurnCoverage2) {\r\n TurnCoverage2[\"TURN_COVERAGE_UNSPECIFIED\"] = \"TURN_COVERAGE_UNSPECIFIED\";\r\n TurnCoverage2[\"TURN_INCLUDES_ONLY_ACTIVITY\"] = \"TURN_INCLUDES_ONLY_ACTIVITY\";\r\n TurnCoverage2[\"TURN_INCLUDES_ALL_INPUT\"] = \"TURN_INCLUDES_ALL_INPUT\";\r\n TurnCoverage2[\"TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO\"] = \"TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO\";\r\n })(TurnCoverage || (TurnCoverage = {}));\r\n (function(Scale2) {\r\n Scale2[\"SCALE_UNSPECIFIED\"] = \"SCALE_UNSPECIFIED\";\r\n Scale2[\"C_MAJOR_A_MINOR\"] = \"C_MAJOR_A_MINOR\";\r\n Scale2[\"D_FLAT_MAJOR_B_FLAT_MINOR\"] = \"D_FLAT_MAJOR_B_FLAT_MINOR\";\r\n Scale2[\"D_MAJOR_B_MINOR\"] = \"D_MAJOR_B_MINOR\";\r\n Scale2[\"E_FLAT_MAJOR_C_MINOR\"] = \"E_FLAT_MAJOR_C_MINOR\";\r\n Scale2[\"E_MAJOR_D_FLAT_MINOR\"] = \"E_MAJOR_D_FLAT_MINOR\";\r\n Scale2[\"F_MAJOR_D_MINOR\"] = \"F_MAJOR_D_MINOR\";\r\n Scale2[\"G_FLAT_MAJOR_E_FLAT_MINOR\"] = \"G_FLAT_MAJOR_E_FLAT_MINOR\";\r\n Scale2[\"G_MAJOR_E_MINOR\"] = \"G_MAJOR_E_MINOR\";\r\n Scale2[\"A_FLAT_MAJOR_F_MINOR\"] = \"A_FLAT_MAJOR_F_MINOR\";\r\n Scale2[\"A_MAJOR_G_FLAT_MINOR\"] = \"A_MAJOR_G_FLAT_MINOR\";\r\n Scale2[\"B_FLAT_MAJOR_G_MINOR\"] = \"B_FLAT_MAJOR_G_MINOR\";\r\n Scale2[\"B_MAJOR_A_FLAT_MINOR\"] = \"B_MAJOR_A_FLAT_MINOR\";\r\n })(Scale || (Scale = {}));\r\n (function(MusicGenerationMode2) {\r\n MusicGenerationMode2[\"MUSIC_GENERATION_MODE_UNSPECIFIED\"] = \"MUSIC_GENERATION_MODE_UNSPECIFIED\";\r\n MusicGenerationMode2[\"QUALITY\"] = \"QUALITY\";\r\n MusicGenerationMode2[\"DIVERSITY\"] = \"DIVERSITY\";\r\n MusicGenerationMode2[\"VOCALIZATION\"] = \"VOCALIZATION\";\r\n })(MusicGenerationMode || (MusicGenerationMode = {}));\r\n (function(LiveMusicPlaybackControl2) {\r\n LiveMusicPlaybackControl2[\"PLAYBACK_CONTROL_UNSPECIFIED\"] = \"PLAYBACK_CONTROL_UNSPECIFIED\";\r\n LiveMusicPlaybackControl2[\"PLAY\"] = \"PLAY\";\r\n LiveMusicPlaybackControl2[\"PAUSE\"] = \"PAUSE\";\r\n LiveMusicPlaybackControl2[\"STOP\"] = \"STOP\";\r\n LiveMusicPlaybackControl2[\"RESET_CONTEXT\"] = \"RESET_CONTEXT\";\r\n })(LiveMusicPlaybackControl || (LiveMusicPlaybackControl = {}));\r\n ToolResponse = class {\r\n };\r\n FunctionResponseBlob = class {\r\n };\r\n FunctionResponseFileData = class {\r\n };\r\n FunctionResponsePart = class {\r\n };\r\n FunctionResponse = class {\r\n };\r\n HttpResponse = class {\r\n constructor(response) {\r\n const headers = {};\r\n for (const pair of response.headers.entries()) {\r\n headers[pair[0]] = pair[1];\r\n }\r\n this.headers = headers;\r\n this.responseInternal = response;\r\n }\r\n json() {\r\n return this.responseInternal.json();\r\n }\r\n };\r\n GenerateContentResponsePromptFeedback = class {\r\n };\r\n GenerateContentResponseUsageMetadata = class {\r\n };\r\n GenerateContentResponse = class {\r\n /**\r\n * Returns the concatenation of all text parts from the first candidate in the response.\r\n *\r\n * @remarks\r\n * If there are multiple candidates in the response, the text from the first\r\n * one will be returned.\r\n * If there are non-text parts in the response, the concatenation of all text\r\n * parts will be returned, and a warning will be logged.\r\n * If there are thought parts in the response, the concatenation of all text\r\n * parts excluding the thought parts will be returned.\r\n *\r\n * @example\r\n * ```ts\r\n * const response = await ai.models.generateContent({\r\n * model: 'gemini-2.0-flash',\r\n * contents:\r\n * 'Why is the sky blue?',\r\n * });\r\n *\r\n * console.debug(response.text);\r\n * ```\r\n */\r\n get text() {\r\n var _a2, _b, _c, _d, _e, _f, _g, _h;\r\n if (((_d = (_c = (_b = (_a2 = this.candidates) === null || _a2 === void 0 ? void 0 : _a2[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) {\r\n return void 0;\r\n }\r\n if (this.candidates && this.candidates.length > 1) {\r\n console.warn(\"there are multiple candidates in the response, returning text from the first one.\");\r\n }\r\n let text = \"\";\r\n let anyTextPartText = false;\r\n const nonTextParts = [];\r\n for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) {\r\n for (const [fieldName, fieldValue] of Object.entries(part)) {\r\n if (fieldName !== \"text\" && fieldName !== \"thought\" && fieldName !== \"thoughtSignature\" && (fieldValue !== null || fieldValue !== void 0)) {\r\n nonTextParts.push(fieldName);\r\n }\r\n }\r\n if (typeof part.text === \"string\") {\r\n if (typeof part.thought === \"boolean\" && part.thought) {\r\n continue;\r\n }\r\n anyTextPartText = true;\r\n text += part.text;\r\n }\r\n }\r\n if (nonTextParts.length > 0) {\r\n console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`);\r\n }\r\n return anyTextPartText ? text : void 0;\r\n }\r\n /**\r\n * Returns the concatenation of all inline data parts from the first candidate\r\n * in the response.\r\n *\r\n * @remarks\r\n * If there are multiple candidates in the response, the inline data from the\r\n * first one will be returned. If there are non-inline data parts in the\r\n * response, the concatenation of all inline data parts will be returned, and\r\n * a warning will be logged.\r\n */\r\n get data() {\r\n var _a2, _b, _c, _d, _e, _f, _g, _h;\r\n if (((_d = (_c = (_b = (_a2 = this.candidates) === null || _a2 === void 0 ? void 0 : _a2[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) {\r\n return void 0;\r\n }\r\n if (this.candidates && this.candidates.length > 1) {\r\n console.warn(\"there are multiple candidates in the response, returning data from the first one.\");\r\n }\r\n let data = \"\";\r\n const nonDataParts = [];\r\n for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) {\r\n for (const [fieldName, fieldValue] of Object.entries(part)) {\r\n if (fieldName !== \"inlineData\" && (fieldValue !== null || fieldValue !== void 0)) {\r\n nonDataParts.push(fieldName);\r\n }\r\n }\r\n if (part.inlineData && typeof part.inlineData.data === \"string\") {\r\n data += atob(part.inlineData.data);\r\n }\r\n }\r\n if (nonDataParts.length > 0) {\r\n console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`);\r\n }\r\n return data.length > 0 ? btoa(data) : void 0;\r\n }\r\n /**\r\n * Returns the function calls from the first candidate in the response.\r\n *\r\n * @remarks\r\n * If there are multiple candidates in the response, the function calls from\r\n * the first one will be returned.\r\n * If there are no function calls in the response, undefined will be returned.\r\n *\r\n * @example\r\n * ```ts\r\n * const controlLightFunctionDeclaration: FunctionDeclaration = {\r\n * name: 'controlLight',\r\n * parameters: {\r\n * type: Type.OBJECT,\r\n * description: 'Set the brightness and color temperature of a room light.',\r\n * properties: {\r\n * brightness: {\r\n * type: Type.NUMBER,\r\n * description:\r\n * 'Light level from 0 to 100. Zero is off and 100 is full brightness.',\r\n * },\r\n * colorTemperature: {\r\n * type: Type.STRING,\r\n * description:\r\n * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',\r\n * },\r\n * },\r\n * required: ['brightness', 'colorTemperature'],\r\n * };\r\n * const response = await ai.models.generateContent({\r\n * model: 'gemini-2.0-flash',\r\n * contents: 'Dim the lights so the room feels cozy and warm.',\r\n * config: {\r\n * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],\r\n * toolConfig: {\r\n * functionCallingConfig: {\r\n * mode: FunctionCallingConfigMode.ANY,\r\n * allowedFunctionNames: ['controlLight'],\r\n * },\r\n * },\r\n * },\r\n * });\r\n * console.debug(JSON.stringify(response.functionCalls));\r\n * ```\r\n */\r\n get functionCalls() {\r\n var _a2, _b, _c, _d, _e, _f, _g, _h;\r\n if (((_d = (_c = (_b = (_a2 = this.candidates) === null || _a2 === void 0 ? void 0 : _a2[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) {\r\n return void 0;\r\n }\r\n if (this.candidates && this.candidates.length > 1) {\r\n console.warn(\"there are multiple candidates in the response, returning function calls from the first one.\");\r\n }\r\n const functionCalls = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.functionCall).map((part) => part.functionCall).filter((functionCall) => functionCall !== void 0);\r\n if ((functionCalls === null || functionCalls === void 0 ? void 0 : functionCalls.length) === 0) {\r\n return void 0;\r\n }\r\n return functionCalls;\r\n }\r\n /**\r\n * Returns the first executable code from the first candidate in the response.\r\n *\r\n * @remarks\r\n * If there are multiple candidates in the response, the executable code from\r\n * the first one will be returned.\r\n * If there are no executable code in the response, undefined will be\r\n * returned.\r\n *\r\n * @example\r\n * ```ts\r\n * const response = await ai.models.generateContent({\r\n * model: 'gemini-2.0-flash',\r\n * contents:\r\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\r\n * config: {\r\n * tools: [{codeExecution: {}}],\r\n * },\r\n * });\r\n *\r\n * console.debug(response.executableCode);\r\n * ```\r\n */\r\n get executableCode() {\r\n var _a2, _b, _c, _d, _e, _f, _g, _h, _j;\r\n if (((_d = (_c = (_b = (_a2 = this.candidates) === null || _a2 === void 0 ? void 0 : _a2[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) {\r\n return void 0;\r\n }\r\n if (this.candidates && this.candidates.length > 1) {\r\n console.warn(\"there are multiple candidates in the response, returning executable code from the first one.\");\r\n }\r\n const executableCode = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.executableCode).map((part) => part.executableCode).filter((executableCode2) => executableCode2 !== void 0);\r\n if ((executableCode === null || executableCode === void 0 ? void 0 : executableCode.length) === 0) {\r\n return void 0;\r\n }\r\n return (_j = executableCode === null || executableCode === void 0 ? void 0 : executableCode[0]) === null || _j === void 0 ? void 0 : _j.code;\r\n }\r\n /**\r\n * Returns the first code execution result from the first candidate in the response.\r\n *\r\n * @remarks\r\n * If there are multiple candidates in the response, the code execution result from\r\n * the first one will be returned.\r\n * If there are no code execution result in the response, undefined will be returned.\r\n *\r\n * @example\r\n * ```ts\r\n * const response = await ai.models.generateContent({\r\n * model: 'gemini-2.0-flash',\r\n * contents:\r\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\r\n * config: {\r\n * tools: [{codeExecution: {}}],\r\n * },\r\n * });\r\n *\r\n * console.debug(response.codeExecutionResult);\r\n * ```\r\n */\r\n get codeExecutionResult() {\r\n var _a2, _b, _c, _d, _e, _f, _g, _h, _j;\r\n if (((_d = (_c = (_b = (_a2 = this.candidates) === null || _a2 === void 0 ? void 0 : _a2[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) {\r\n return void 0;\r\n }\r\n if (this.candidates && this.candidates.length > 1) {\r\n console.warn(\"there are multiple candidates in the response, returning code execution result from the first one.\");\r\n }\r\n const codeExecutionResult = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.codeExecutionResult).map((part) => part.codeExecutionResult).filter((codeExecutionResult2) => codeExecutionResult2 !== void 0);\r\n if ((codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult.length) === 0) {\r\n return void 0;\r\n }\r\n return (_j = codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult[0]) === null || _j === void 0 ? void 0 : _j.output;\r\n }\r\n };\r\n EmbedContentResponse = class {\r\n };\r\n GenerateImagesResponse = class {\r\n };\r\n EditImageResponse = class {\r\n };\r\n UpscaleImageResponse = class {\r\n };\r\n RecontextImageResponse = class {\r\n };\r\n SegmentImageResponse = class {\r\n };\r\n ListModelsResponse = class {\r\n };\r\n DeleteModelResponse = class {\r\n };\r\n CountTokensResponse = class {\r\n };\r\n ComputeTokensResponse = class {\r\n };\r\n GenerateVideosResponse = class {\r\n };\r\n GenerateVideosOperation = class _GenerateVideosOperation {\r\n /**\r\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\r\n */\r\n _fromAPIResponse({ apiResponse, _isVertexAI }) {\r\n const operation = new _GenerateVideosOperation();\r\n let response;\r\n const op = apiResponse;\r\n if (_isVertexAI) {\r\n response = generateVideosOperationFromVertex$1(op);\r\n } else {\r\n response = generateVideosOperationFromMldev$1(op);\r\n }\r\n Object.assign(operation, response);\r\n return operation;\r\n }\r\n };\r\n EvaluateDatasetResponse = class {\r\n };\r\n ListTuningJobsResponse = class {\r\n };\r\n CancelTuningJobResponse = class {\r\n };\r\n DeleteCachedContentResponse = class {\r\n };\r\n ListCachedContentsResponse = class {\r\n };\r\n ListDocumentsResponse = class {\r\n };\r\n ListFileSearchStoresResponse = class {\r\n };\r\n UploadToFileSearchStoreResumableResponse = class {\r\n };\r\n ImportFileResponse = class {\r\n };\r\n ImportFileOperation = class _ImportFileOperation {\r\n /**\r\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\r\n */\r\n _fromAPIResponse({ apiResponse, _isVertexAI }) {\r\n const operation = new _ImportFileOperation();\r\n const op = apiResponse;\r\n const response = importFileOperationFromMldev$1(op);\r\n Object.assign(operation, response);\r\n return operation;\r\n }\r\n };\r\n ListFilesResponse = class {\r\n };\r\n CreateFileResponse = class {\r\n };\r\n DeleteFileResponse = class {\r\n };\r\n RegisterFilesResponse = class {\r\n };\r\n InlinedResponse = class {\r\n };\r\n SingleEmbedContentResponse = class {\r\n };\r\n InlinedEmbedContentResponse = class {\r\n };\r\n ListBatchJobsResponse = class {\r\n };\r\n ReplayResponse = class {\r\n };\r\n RawReferenceImage = class {\r\n /** Internal method to convert to ReferenceImageAPIInternal. */\r\n toReferenceImageAPI() {\r\n const referenceImageAPI = {\r\n referenceType: \"REFERENCE_TYPE_RAW\",\r\n referenceImage: this.referenceImage,\r\n referenceId: this.referenceId\r\n };\r\n return referenceImageAPI;\r\n }\r\n };\r\n MaskReferenceImage = class {\r\n /** Internal method to convert to ReferenceImageAPIInternal. */\r\n toReferenceImageAPI() {\r\n const referenceImageAPI = {\r\n referenceType: \"REFERENCE_TYPE_MASK\",\r\n referenceImage: this.referenceImage,\r\n referenceId: this.referenceId,\r\n maskImageConfig: this.config\r\n };\r\n return referenceImageAPI;\r\n }\r\n };\r\n ControlReferenceImage = class {\r\n /** Internal method to convert to ReferenceImageAPIInternal. */\r\n toReferenceImageAPI() {\r\n const referenceImageAPI = {\r\n referenceType: \"REFERENCE_TYPE_CONTROL\",\r\n referenceImage: this.referenceImage,\r\n referenceId: this.referenceId,\r\n controlImageConfig: this.config\r\n };\r\n return referenceImageAPI;\r\n }\r\n };\r\n StyleReferenceImage = class {\r\n /** Internal method to convert to ReferenceImageAPIInternal. */\r\n toReferenceImageAPI() {\r\n const referenceImageAPI = {\r\n referenceType: \"REFERENCE_TYPE_STYLE\",\r\n referenceImage: this.referenceImage,\r\n referenceId: this.referenceId,\r\n styleImageConfig: this.config\r\n };\r\n return referenceImageAPI;\r\n }\r\n };\r\n SubjectReferenceImage = class {\r\n /* Internal method to convert to ReferenceImageAPIInternal. */\r\n toReferenceImageAPI() {\r\n const referenceImageAPI = {\r\n referenceType: \"REFERENCE_TYPE_SUBJECT\",\r\n referenceImage: this.referenceImage,\r\n referenceId: this.referenceId,\r\n subjectImageConfig: this.config\r\n };\r\n return referenceImageAPI;\r\n }\r\n };\r\n ContentReferenceImage = class {\r\n /** Internal method to convert to ReferenceImageAPIInternal. */\r\n toReferenceImageAPI() {\r\n const referenceImageAPI = {\r\n referenceType: \"REFERENCE_TYPE_CONTENT\",\r\n referenceImage: this.referenceImage,\r\n referenceId: this.referenceId\r\n };\r\n return referenceImageAPI;\r\n }\r\n };\r\n LiveServerMessage = class {\r\n /**\r\n * Returns the concatenation of all text parts from the server content if present.\r\n *\r\n * @remarks\r\n * If there are non-text parts in the response, the concatenation of all text\r\n * parts will be returned, and a warning will be logged.\r\n */\r\n get text() {\r\n var _a2, _b, _c;\r\n let text = \"\";\r\n let anyTextPartFound = false;\r\n const nonTextParts = [];\r\n for (const part of (_c = (_b = (_a2 = this.serverContent) === null || _a2 === void 0 ? void 0 : _a2.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) {\r\n for (const [fieldName, fieldValue] of Object.entries(part)) {\r\n if (fieldName !== \"text\" && fieldName !== \"thought\" && fieldValue !== null) {\r\n nonTextParts.push(fieldName);\r\n }\r\n }\r\n if (typeof part.text === \"string\") {\r\n if (typeof part.thought === \"boolean\" && part.thought) {\r\n continue;\r\n }\r\n anyTextPartFound = true;\r\n text += part.text;\r\n }\r\n }\r\n if (nonTextParts.length > 0) {\r\n console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`);\r\n }\r\n return anyTextPartFound ? text : void 0;\r\n }\r\n /**\r\n * Returns the concatenation of all inline data parts from the server content if present.\r\n *\r\n * @remarks\r\n * If there are non-inline data parts in the\r\n * response, the concatenation of all inline data parts will be returned, and\r\n * a warning will be logged.\r\n */\r\n get data() {\r\n var _a2, _b, _c;\r\n let data = \"\";\r\n const nonDataParts = [];\r\n for (const part of (_c = (_b = (_a2 = this.serverContent) === null || _a2 === void 0 ? void 0 : _a2.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) {\r\n for (const [fieldName, fieldValue] of Object.entries(part)) {\r\n if (fieldName !== \"inlineData\" && fieldValue !== null) {\r\n nonDataParts.push(fieldName);\r\n }\r\n }\r\n if (part.inlineData && typeof part.inlineData.data === \"string\") {\r\n data += atob(part.inlineData.data);\r\n }\r\n }\r\n if (nonDataParts.length > 0) {\r\n console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`);\r\n }\r\n return data.length > 0 ? btoa(data) : void 0;\r\n }\r\n };\r\n LiveClientToolResponse = class {\r\n };\r\n LiveSendToolResponseParameters = class {\r\n constructor() {\r\n this.functionResponses = [];\r\n }\r\n };\r\n LiveMusicServerMessage = class {\r\n /**\r\n * Returns the first audio chunk from the server content, if present.\r\n *\r\n * @remarks\r\n * If there are no audio chunks in the response, undefined will be returned.\r\n */\r\n get audioChunk() {\r\n if (this.serverContent && this.serverContent.audioChunks && this.serverContent.audioChunks.length > 0) {\r\n return this.serverContent.audioChunks[0];\r\n }\r\n return void 0;\r\n }\r\n };\r\n UploadToFileSearchStoreResponse = class {\r\n };\r\n UploadToFileSearchStoreOperation = class _UploadToFileSearchStoreOperation {\r\n /**\r\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\r\n */\r\n _fromAPIResponse({ apiResponse, _isVertexAI }) {\r\n const operation = new _UploadToFileSearchStoreOperation();\r\n const op = apiResponse;\r\n const response = uploadToFileSearchStoreOperationFromMldev(op);\r\n Object.assign(operation, response);\r\n return operation;\r\n }\r\n };\r\n (function(PagedItem2) {\r\n PagedItem2[\"PAGED_ITEM_BATCH_JOBS\"] = \"batchJobs\";\r\n PagedItem2[\"PAGED_ITEM_MODELS\"] = \"models\";\r\n PagedItem2[\"PAGED_ITEM_TUNING_JOBS\"] = \"tuningJobs\";\r\n PagedItem2[\"PAGED_ITEM_FILES\"] = \"files\";\r\n PagedItem2[\"PAGED_ITEM_CACHED_CONTENTS\"] = \"cachedContents\";\r\n PagedItem2[\"PAGED_ITEM_FILE_SEARCH_STORES\"] = \"fileSearchStores\";\r\n PagedItem2[\"PAGED_ITEM_DOCUMENTS\"] = \"documents\";\r\n })(PagedItem || (PagedItem = {}));\r\n Pager = class {\r\n constructor(name, request, response, params) {\r\n this.pageInternal = [];\r\n this.paramsInternal = {};\r\n this.requestInternal = request;\r\n this.init(name, response, params);\r\n }\r\n init(name, response, params) {\r\n var _a2, _b;\r\n this.nameInternal = name;\r\n this.pageInternal = response[this.nameInternal] || [];\r\n this.sdkHttpResponseInternal = response === null || response === void 0 ? void 0 : response.sdkHttpResponse;\r\n this.idxInternal = 0;\r\n let requestParams = { config: {} };\r\n if (!params || Object.keys(params).length === 0) {\r\n requestParams = { config: {} };\r\n } else if (typeof params === \"object\") {\r\n requestParams = Object.assign({}, params);\r\n } else {\r\n requestParams = params;\r\n }\r\n if (requestParams[\"config\"]) {\r\n requestParams[\"config\"][\"pageToken\"] = response[\"nextPageToken\"];\r\n }\r\n this.paramsInternal = requestParams;\r\n this.pageInternalSize = (_b = (_a2 = requestParams[\"config\"]) === null || _a2 === void 0 ? void 0 : _a2[\"pageSize\"]) !== null && _b !== void 0 ? _b : this.pageInternal.length;\r\n }\r\n initNextPage(response) {\r\n this.init(this.nameInternal, response, this.paramsInternal);\r\n }\r\n /**\r\n * Returns the current page, which is a list of items.\r\n *\r\n * @remarks\r\n * The first page is retrieved when the pager is created. The returned list of\r\n * items could be a subset of the entire list.\r\n */\r\n get page() {\r\n return this.pageInternal;\r\n }\r\n /**\r\n * Returns the type of paged item (for example, ``batch_jobs``).\r\n */\r\n get name() {\r\n return this.nameInternal;\r\n }\r\n /**\r\n * Returns the length of the page fetched each time by this pager.\r\n *\r\n * @remarks\r\n * The number of items in the page is less than or equal to the page length.\r\n */\r\n get pageSize() {\r\n return this.pageInternalSize;\r\n }\r\n /**\r\n * Returns the headers of the API response.\r\n */\r\n get sdkHttpResponse() {\r\n return this.sdkHttpResponseInternal;\r\n }\r\n /**\r\n * Returns the parameters when making the API request for the next page.\r\n *\r\n * @remarks\r\n * Parameters contain a set of optional configs that can be\r\n * used to customize the API request. For example, the `pageToken` parameter\r\n * contains the token to request the next page.\r\n */\r\n get params() {\r\n return this.paramsInternal;\r\n }\r\n /**\r\n * Returns the total number of items in the current page.\r\n */\r\n get pageLength() {\r\n return this.pageInternal.length;\r\n }\r\n /**\r\n * Returns the item at the given index.\r\n */\r\n getItem(index) {\r\n return this.pageInternal[index];\r\n }\r\n /**\r\n * Returns an async iterator that support iterating through all items\r\n * retrieved from the API.\r\n *\r\n * @remarks\r\n * The iterator will automatically fetch the next page if there are more items\r\n * to fetch from the API.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * const pager = await ai.files.list({config: {pageSize: 10}});\r\n * for await (const file of pager) {\r\n * console.log(file.name);\r\n * }\r\n * ```\r\n */\r\n [Symbol.asyncIterator]() {\r\n return {\r\n next: async () => {\r\n if (this.idxInternal >= this.pageLength) {\r\n if (this.hasNextPage()) {\r\n await this.nextPage();\r\n } else {\r\n return { value: void 0, done: true };\r\n }\r\n }\r\n const item = this.getItem(this.idxInternal);\r\n this.idxInternal += 1;\r\n return { value: item, done: false };\r\n },\r\n return: async () => {\r\n return { value: void 0, done: true };\r\n }\r\n };\r\n }\r\n /**\r\n * Fetches the next page of items. This makes a new API request.\r\n *\r\n * @throws {Error} If there are no more pages to fetch.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * const pager = await ai.files.list({config: {pageSize: 10}});\r\n * let page = pager.page;\r\n * while (true) {\r\n * for (const file of page) {\r\n * console.log(file.name);\r\n * }\r\n * if (!pager.hasNextPage()) {\r\n * break;\r\n * }\r\n * page = await pager.nextPage();\r\n * }\r\n * ```\r\n */\r\n async nextPage() {\r\n if (!this.hasNextPage()) {\r\n throw new Error(\"No more pages to fetch.\");\r\n }\r\n const response = await this.requestInternal(this.params);\r\n this.initNextPage(response);\r\n return this.page;\r\n }\r\n /**\r\n * Returns true if there are more pages to fetch from the API.\r\n */\r\n hasNextPage() {\r\n var _a2;\r\n if (((_a2 = this.params[\"config\"]) === null || _a2 === void 0 ? void 0 : _a2[\"pageToken\"]) !== void 0) {\r\n return true;\r\n }\r\n return false;\r\n }\r\n };\r\n Batches = class extends BaseModule {\r\n constructor(apiClient) {\r\n super();\r\n this.apiClient = apiClient;\r\n this.list = async (params = {}) => {\r\n return new Pager(PagedItem.PAGED_ITEM_BATCH_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params);\r\n };\r\n this.create = async (params) => {\r\n if (this.apiClient.isVertexAI()) {\r\n params.config = this.formatDestination(params.src, params.config);\r\n }\r\n return this.createInternal(params);\r\n };\r\n this.createEmbeddings = async (params) => {\r\n console.warn(\"batches.createEmbeddings() is experimental and may change without notice.\");\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"Vertex AI does not support batches.createEmbeddings.\");\r\n }\r\n return this.createEmbeddingsInternal(params);\r\n };\r\n }\r\n // Helper function to handle inlined generate content requests\r\n createInlinedGenerateContentRequest(params) {\r\n const body = createBatchJobParametersToMldev(\r\n this.apiClient,\r\n // Use instance apiClient\r\n params\r\n );\r\n const urlParams = body[\"_url\"];\r\n const path2 = formatMap(\"{model}:batchGenerateContent\", urlParams);\r\n const batch = body[\"batch\"];\r\n const inputConfig = batch[\"inputConfig\"];\r\n const requestsWrapper = inputConfig[\"requests\"];\r\n const requests = requestsWrapper[\"requests\"];\r\n const newRequests = [];\r\n for (const request of requests) {\r\n const requestDict = Object.assign({}, request);\r\n if (requestDict[\"systemInstruction\"]) {\r\n const systemInstructionValue = requestDict[\"systemInstruction\"];\r\n delete requestDict[\"systemInstruction\"];\r\n const requestContent = requestDict[\"request\"];\r\n requestContent[\"systemInstruction\"] = systemInstructionValue;\r\n requestDict[\"request\"] = requestContent;\r\n }\r\n newRequests.push(requestDict);\r\n }\r\n requestsWrapper[\"requests\"] = newRequests;\r\n delete body[\"config\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n return { path: path2, body };\r\n }\r\n // Helper function to get the first GCS URI\r\n getGcsUri(src) {\r\n if (typeof src === \"string\") {\r\n return src.startsWith(\"gs://\") ? src : void 0;\r\n }\r\n if (!Array.isArray(src) && src.gcsUri && src.gcsUri.length > 0) {\r\n return src.gcsUri[0];\r\n }\r\n return void 0;\r\n }\r\n // Helper function to get the BigQuery URI\r\n getBigqueryUri(src) {\r\n if (typeof src === \"string\") {\r\n return src.startsWith(\"bq://\") ? src : void 0;\r\n }\r\n if (!Array.isArray(src)) {\r\n return src.bigqueryUri;\r\n }\r\n return void 0;\r\n }\r\n // Function to format the destination configuration for Vertex AI\r\n formatDestination(src, config) {\r\n const newConfig = config ? Object.assign({}, config) : {};\r\n const timestampStr = Date.now().toString();\r\n if (!newConfig.displayName) {\r\n newConfig.displayName = `genaiBatchJob_${timestampStr}`;\r\n }\r\n if (newConfig.dest === void 0) {\r\n const gcsUri = this.getGcsUri(src);\r\n const bigqueryUri = this.getBigqueryUri(src);\r\n if (gcsUri) {\r\n if (gcsUri.endsWith(\".jsonl\")) {\r\n newConfig.dest = `${gcsUri.slice(0, -6)}/dest`;\r\n } else {\r\n newConfig.dest = `${gcsUri}_dest_${timestampStr}`;\r\n }\r\n } else if (bigqueryUri) {\r\n newConfig.dest = `${bigqueryUri}_dest_${timestampStr}`;\r\n } else {\r\n throw new Error(\"Unsupported source for Vertex AI: No GCS or BigQuery URI found.\");\r\n }\r\n }\r\n return newConfig;\r\n }\r\n /**\r\n * Internal method to create batch job.\r\n *\r\n * @param params - The parameters for create batch job request.\r\n * @return The created batch job.\r\n *\r\n */\r\n async createInternal(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = createBatchJobParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"batchPredictionJobs\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = batchJobFromVertex(apiResponse);\r\n return resp;\r\n });\r\n } else {\r\n const body = createBatchJobParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"{model}:batchGenerateContent\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = batchJobFromMldev(apiResponse);\r\n return resp;\r\n });\r\n }\r\n }\r\n /**\r\n * Internal method to create batch job.\r\n *\r\n * @param params - The parameters for create batch job request.\r\n * @return The created batch job.\r\n *\r\n */\r\n async createEmbeddingsInternal(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"This method is only supported by the Gemini Developer API.\");\r\n } else {\r\n const body = createEmbeddingsBatchJobParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"{model}:asyncBatchEmbedContent\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = batchJobFromMldev(apiResponse);\r\n return resp;\r\n });\r\n }\r\n }\r\n /**\r\n * Gets batch job configurations.\r\n *\r\n * @param params - The parameters for the get request.\r\n * @return The batch job.\r\n *\r\n * @example\r\n * ```ts\r\n * await ai.batches.get({name: '...'}); // The server-generated resource name.\r\n * ```\r\n */\r\n async get(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = getBatchJobParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"batchPredictionJobs/{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = batchJobFromVertex(apiResponse);\r\n return resp;\r\n });\r\n } else {\r\n const body = getBatchJobParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"batches/{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = batchJobFromMldev(apiResponse);\r\n return resp;\r\n });\r\n }\r\n }\r\n /**\r\n * Cancels a batch job.\r\n *\r\n * @param params - The parameters for the cancel request.\r\n * @return The empty response returned by the API.\r\n *\r\n * @example\r\n * ```ts\r\n * await ai.batches.cancel({name: '...'}); // The server-generated resource name.\r\n * ```\r\n */\r\n async cancel(params) {\r\n var _a2, _b, _c, _d;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = cancelBatchJobParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"batchPredictionJobs/{name}:cancel\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n await this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n });\r\n } else {\r\n const body = cancelBatchJobParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"batches/{name}:cancel\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n await this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n });\r\n }\r\n }\r\n async listInternal(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = listBatchJobsParametersToVertex(params);\r\n path2 = formatMap(\"batchPredictionJobs\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = listBatchJobsResponseFromVertex(apiResponse);\r\n const typedResp = new ListBatchJobsResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n } else {\r\n const body = listBatchJobsParametersToMldev(params);\r\n path2 = formatMap(\"batches\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = listBatchJobsResponseFromMldev(apiResponse);\r\n const typedResp = new ListBatchJobsResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n /**\r\n * Deletes a batch job.\r\n *\r\n * @param params - The parameters for the delete request.\r\n * @return The empty response returned by the API.\r\n *\r\n * @example\r\n * ```ts\r\n * await ai.batches.delete({name: '...'}); // The server-generated resource name.\r\n * ```\r\n */\r\n async delete(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = deleteBatchJobParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"batchPredictionJobs/{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"DELETE\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = deleteResourceJobFromVertex(apiResponse);\r\n return resp;\r\n });\r\n } else {\r\n const body = deleteBatchJobParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"batches/{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"DELETE\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = deleteResourceJobFromMldev(apiResponse);\r\n return resp;\r\n });\r\n }\r\n }\r\n };\r\n Caches = class extends BaseModule {\r\n constructor(apiClient) {\r\n super();\r\n this.apiClient = apiClient;\r\n this.list = async (params = {}) => {\r\n return new Pager(PagedItem.PAGED_ITEM_CACHED_CONTENTS, (x) => this.listInternal(x), await this.listInternal(params), params);\r\n };\r\n }\r\n /**\r\n * Creates a cached contents resource.\r\n *\r\n * @remarks\r\n * Context caching is only supported for specific models. See [Gemini\r\n * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)\r\n * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)\r\n * for more information.\r\n *\r\n * @param params - The parameters for the create request.\r\n * @return The created cached content.\r\n *\r\n * @example\r\n * ```ts\r\n * const contents = ...; // Initialize the content to cache.\r\n * const response = await ai.caches.create({\r\n * model: 'gemini-2.0-flash-001',\r\n * config: {\r\n * 'contents': contents,\r\n * 'displayName': 'test cache',\r\n * 'systemInstruction': 'What is the sum of the two pdfs?',\r\n * 'ttl': '86400s',\r\n * }\r\n * });\r\n * ```\r\n */\r\n async create(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = createCachedContentParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"cachedContents\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((resp) => {\r\n return resp;\r\n });\r\n } else {\r\n const body = createCachedContentParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"cachedContents\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((resp) => {\r\n return resp;\r\n });\r\n }\r\n }\r\n /**\r\n * Gets cached content configurations.\r\n *\r\n * @param params - The parameters for the get request.\r\n * @return The cached content.\r\n *\r\n * @example\r\n * ```ts\r\n * await ai.caches.get({name: '...'}); // The server-generated resource name.\r\n * ```\r\n */\r\n async get(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = getCachedContentParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((resp) => {\r\n return resp;\r\n });\r\n } else {\r\n const body = getCachedContentParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((resp) => {\r\n return resp;\r\n });\r\n }\r\n }\r\n /**\r\n * Deletes cached content.\r\n *\r\n * @param params - The parameters for the delete request.\r\n * @return The empty response returned by the API.\r\n *\r\n * @example\r\n * ```ts\r\n * await ai.caches.delete({name: '...'}); // The server-generated resource name.\r\n * ```\r\n */\r\n async delete(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = deleteCachedContentParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"DELETE\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = deleteCachedContentResponseFromVertex(apiResponse);\r\n const typedResp = new DeleteCachedContentResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n } else {\r\n const body = deleteCachedContentParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"DELETE\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = deleteCachedContentResponseFromMldev(apiResponse);\r\n const typedResp = new DeleteCachedContentResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n /**\r\n * Updates cached content configurations.\r\n *\r\n * @param params - The parameters for the update request.\r\n * @return The updated cached content.\r\n *\r\n * @example\r\n * ```ts\r\n * const response = await ai.caches.update({\r\n * name: '...', // The server-generated resource name.\r\n * config: {'ttl': '7600s'}\r\n * });\r\n * ```\r\n */\r\n async update(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = updateCachedContentParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"PATCH\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((resp) => {\r\n return resp;\r\n });\r\n } else {\r\n const body = updateCachedContentParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"PATCH\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((resp) => {\r\n return resp;\r\n });\r\n }\r\n }\r\n async listInternal(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = listCachedContentsParametersToVertex(params);\r\n path2 = formatMap(\"cachedContents\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = listCachedContentsResponseFromVertex(apiResponse);\r\n const typedResp = new ListCachedContentsResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n } else {\r\n const body = listCachedContentsParametersToMldev(params);\r\n path2 = formatMap(\"cachedContents\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = listCachedContentsResponseFromMldev(apiResponse);\r\n const typedResp = new ListCachedContentsResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n };\r\n Chats = class {\r\n constructor(modelsModule, apiClient) {\r\n this.modelsModule = modelsModule;\r\n this.apiClient = apiClient;\r\n }\r\n /**\r\n * Creates a new chat session.\r\n *\r\n * @remarks\r\n * The config in the params will be used for all requests within the chat\r\n * session unless overridden by a per-request `config` in\r\n * @see {@link types.SendMessageParameters#config}.\r\n *\r\n * @param params - Parameters for creating a chat session.\r\n * @returns A new chat session.\r\n *\r\n * @example\r\n * ```ts\r\n * const chat = ai.chats.create({\r\n * model: 'gemini-2.0-flash'\r\n * config: {\r\n * temperature: 0.5,\r\n * maxOutputTokens: 1024,\r\n * }\r\n * });\r\n * ```\r\n */\r\n create(params) {\r\n return new Chat(\r\n this.apiClient,\r\n this.modelsModule,\r\n params.model,\r\n params.config,\r\n // Deep copy the history to avoid mutating the history outside of the\r\n // chat session.\r\n structuredClone(params.history)\r\n );\r\n }\r\n };\r\n Chat = class {\r\n constructor(apiClient, modelsModule, model, config = {}, history = []) {\r\n this.apiClient = apiClient;\r\n this.modelsModule = modelsModule;\r\n this.model = model;\r\n this.config = config;\r\n this.history = history;\r\n this.sendPromise = Promise.resolve();\r\n validateHistory(history);\r\n }\r\n /**\r\n * Sends a message to the model and returns the response.\r\n *\r\n * @remarks\r\n * This method will wait for the previous message to be processed before\r\n * sending the next message.\r\n *\r\n * @see {@link Chat#sendMessageStream} for streaming method.\r\n * @param params - parameters for sending messages within a chat session.\r\n * @returns The model's response.\r\n *\r\n * @example\r\n * ```ts\r\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\r\n * const response = await chat.sendMessage({\r\n * message: 'Why is the sky blue?'\r\n * });\r\n * console.log(response.text);\r\n * ```\r\n */\r\n async sendMessage(params) {\r\n var _a2;\r\n await this.sendPromise;\r\n const inputContent = tContent(params.message);\r\n const responsePromise = this.modelsModule.generateContent({\r\n model: this.model,\r\n contents: this.getHistory(true).concat(inputContent),\r\n config: (_a2 = params.config) !== null && _a2 !== void 0 ? _a2 : this.config\r\n });\r\n this.sendPromise = (async () => {\r\n var _a3, _b, _c;\r\n const response = await responsePromise;\r\n const outputContent = (_b = (_a3 = response.candidates) === null || _a3 === void 0 ? void 0 : _a3[0]) === null || _b === void 0 ? void 0 : _b.content;\r\n const fullAutomaticFunctionCallingHistory = response.automaticFunctionCallingHistory;\r\n const index = this.getHistory(true).length;\r\n let automaticFunctionCallingHistory = [];\r\n if (fullAutomaticFunctionCallingHistory != null) {\r\n automaticFunctionCallingHistory = (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && _c !== void 0 ? _c : [];\r\n }\r\n const modelOutput = outputContent ? [outputContent] : [];\r\n this.recordHistory(inputContent, modelOutput, automaticFunctionCallingHistory);\r\n return;\r\n })();\r\n await this.sendPromise.catch(() => {\r\n this.sendPromise = Promise.resolve();\r\n });\r\n return responsePromise;\r\n }\r\n /**\r\n * Sends a message to the model and returns the response in chunks.\r\n *\r\n * @remarks\r\n * This method will wait for the previous message to be processed before\r\n * sending the next message.\r\n *\r\n * @see {@link Chat#sendMessage} for non-streaming method.\r\n * @param params - parameters for sending the message.\r\n * @return The model's response.\r\n *\r\n * @example\r\n * ```ts\r\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\r\n * const response = await chat.sendMessageStream({\r\n * message: 'Why is the sky blue?'\r\n * });\r\n * for await (const chunk of response) {\r\n * console.log(chunk.text);\r\n * }\r\n * ```\r\n */\r\n async sendMessageStream(params) {\r\n var _a2;\r\n await this.sendPromise;\r\n const inputContent = tContent(params.message);\r\n const streamResponse = this.modelsModule.generateContentStream({\r\n model: this.model,\r\n contents: this.getHistory(true).concat(inputContent),\r\n config: (_a2 = params.config) !== null && _a2 !== void 0 ? _a2 : this.config\r\n });\r\n this.sendPromise = streamResponse.then(() => void 0).catch(() => void 0);\r\n const response = await streamResponse;\r\n const result = this.processStreamResponse(response, inputContent);\r\n return result;\r\n }\r\n /**\r\n * Returns the chat history.\r\n *\r\n * @remarks\r\n * The history is a list of contents alternating between user and model.\r\n *\r\n * There are two types of history:\r\n * - The `curated history` contains only the valid turns between user and\r\n * model, which will be included in the subsequent requests sent to the model.\r\n * - The `comprehensive history` contains all turns, including invalid or\r\n * empty model outputs, providing a complete record of the history.\r\n *\r\n * The history is updated after receiving the response from the model,\r\n * for streaming response, it means receiving the last chunk of the response.\r\n *\r\n * The `comprehensive history` is returned by default. To get the `curated\r\n * history`, set the `curated` parameter to `true`.\r\n *\r\n * @param curated - whether to return the curated history or the comprehensive\r\n * history.\r\n * @return History contents alternating between user and model for the entire\r\n * chat session.\r\n */\r\n getHistory(curated = false) {\r\n const history = curated ? extractCuratedHistory(this.history) : this.history;\r\n return structuredClone(history);\r\n }\r\n processStreamResponse(streamResponse, inputContent) {\r\n return __asyncGenerator(this, arguments, function* processStreamResponse_1() {\r\n var _a2, e_1, _b, _c;\r\n var _d, _e;\r\n const outputContent = [];\r\n try {\r\n for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _a2 = streamResponse_1_1.done, !_a2; _f = true) {\r\n _c = streamResponse_1_1.value;\r\n _f = false;\r\n const chunk = _c;\r\n if (isValidResponse(chunk)) {\r\n const content = (_e = (_d = chunk.candidates) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.content;\r\n if (content !== void 0) {\r\n outputContent.push(content);\r\n }\r\n }\r\n yield yield __await(chunk);\r\n }\r\n } catch (e_1_1) {\r\n e_1 = { error: e_1_1 };\r\n } finally {\r\n try {\r\n if (!_f && !_a2 && (_b = streamResponse_1.return)) yield __await(_b.call(streamResponse_1));\r\n } finally {\r\n if (e_1) throw e_1.error;\r\n }\r\n }\r\n this.recordHistory(inputContent, outputContent);\r\n });\r\n }\r\n recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) {\r\n let outputContents = [];\r\n if (modelOutput.length > 0 && modelOutput.every((content) => content.role !== void 0)) {\r\n outputContents = modelOutput;\r\n } else {\r\n outputContents.push({\r\n role: \"model\",\r\n parts: []\r\n });\r\n }\r\n if (automaticFunctionCallingHistory && automaticFunctionCallingHistory.length > 0) {\r\n this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory));\r\n } else {\r\n this.history.push(userInput);\r\n }\r\n this.history.push(...outputContents);\r\n }\r\n };\r\n ApiError = class _ApiError extends Error {\r\n constructor(options) {\r\n super(options.message);\r\n this.name = \"ApiError\";\r\n this.status = options.status;\r\n Object.setPrototypeOf(this, _ApiError.prototype);\r\n }\r\n };\r\n Files = class extends BaseModule {\r\n constructor(apiClient) {\r\n super();\r\n this.apiClient = apiClient;\r\n this.list = async (params = {}) => {\r\n return new Pager(PagedItem.PAGED_ITEM_FILES, (x) => this.listInternal(x), await this.listInternal(params), params);\r\n };\r\n }\r\n /**\r\n * Uploads a file asynchronously to the Gemini API.\r\n * This method is not available in Vertex AI.\r\n * Supported upload sources:\r\n * - Node.js: File path (string) or Blob object.\r\n * - Browser: Blob object (e.g., File).\r\n *\r\n * @remarks\r\n * The `mimeType` can be specified in the `config` parameter. If omitted:\r\n * - For file path (string) inputs, the `mimeType` will be inferred from the\r\n * file extension.\r\n * - For Blob object inputs, the `mimeType` will be set to the Blob's `type`\r\n * property.\r\n * Somex eamples for file extension to mimeType mapping:\r\n * .txt -> text/plain\r\n * .json -> application/json\r\n * .jpg -> image/jpeg\r\n * .png -> image/png\r\n * .mp3 -> audio/mpeg\r\n * .mp4 -> video/mp4\r\n *\r\n * This section can contain multiple paragraphs and code examples.\r\n *\r\n * @param params - Optional parameters specified in the\r\n * `types.UploadFileParameters` interface.\r\n * @see {@link types.UploadFileParameters#config} for the optional\r\n * config in the parameters.\r\n * @return A promise that resolves to a `types.File` object.\r\n * @throws An error if called on a Vertex AI client.\r\n * @throws An error if the `mimeType` is not provided and can not be inferred,\r\n * the `mimeType` can be provided in the `params.config` parameter.\r\n * @throws An error occurs if a suitable upload location cannot be established.\r\n *\r\n * @example\r\n * The following code uploads a file to Gemini API.\r\n *\r\n * ```ts\r\n * const file = await ai.files.upload({file: 'file.txt', config: {\r\n * mimeType: 'text/plain',\r\n * }});\r\n * console.log(file.name);\r\n * ```\r\n */\r\n async upload(params) {\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"Vertex AI does not support uploading files. You can share files through a GCS bucket.\");\r\n }\r\n return this.apiClient.uploadFile(params.file, params.config).then((resp) => {\r\n return resp;\r\n });\r\n }\r\n /**\r\n * Downloads a remotely stored file asynchronously to a location specified in\r\n * the `params` object. This method only works on Node environment, to\r\n * download files in the browser, use a browser compliant method like an <a>\r\n * tag.\r\n *\r\n * @param params - The parameters for the download request.\r\n *\r\n * @example\r\n * The following code downloads an example file named \"files/mehozpxf877d\" as\r\n * \"file.txt\".\r\n *\r\n * ```ts\r\n * await ai.files.download({file: file.name, downloadPath: 'file.txt'});\r\n * ```\r\n */\r\n async download(params) {\r\n await this.apiClient.downloadFile(params);\r\n }\r\n /**\r\n * Registers Google Cloud Storage files for use with the API.\r\n * This method is only available in Node.js environments.\r\n */\r\n async registerFiles(params) {\r\n throw new Error(\"registerFiles is only supported in Node.js environments.\");\r\n }\r\n async _registerFiles(params) {\r\n return this.registerFilesInternal(params);\r\n }\r\n async listInternal(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"This method is only supported by the Gemini Developer API.\");\r\n } else {\r\n const body = listFilesParametersToMldev(params);\r\n path2 = formatMap(\"files\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = listFilesResponseFromMldev(apiResponse);\r\n const typedResp = new ListFilesResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n async createInternal(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"This method is only supported by the Gemini Developer API.\");\r\n } else {\r\n const body = createFileParametersToMldev(params);\r\n path2 = formatMap(\"upload/v1beta/files\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = createFileResponseFromMldev(apiResponse);\r\n const typedResp = new CreateFileResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n /**\r\n * Retrieves the file information from the service.\r\n *\r\n * @param params - The parameters for the get request\r\n * @return The Promise that resolves to the types.File object requested.\r\n *\r\n * @example\r\n * ```ts\r\n * const config: GetFileParameters = {\r\n * name: fileName,\r\n * };\r\n * file = await ai.files.get(config);\r\n * console.log(file.name);\r\n * ```\r\n */\r\n async get(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"This method is only supported by the Gemini Developer API.\");\r\n } else {\r\n const body = getFileParametersToMldev(params);\r\n path2 = formatMap(\"files/{file}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((resp) => {\r\n return resp;\r\n });\r\n }\r\n }\r\n /**\r\n * Deletes a remotely stored file.\r\n *\r\n * @param params - The parameters for the delete request.\r\n * @return The DeleteFileResponse, the response for the delete method.\r\n *\r\n * @example\r\n * The following code deletes an example file named \"files/mehozpxf877d\".\r\n *\r\n * ```ts\r\n * await ai.files.delete({name: file.name});\r\n * ```\r\n */\r\n async delete(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"This method is only supported by the Gemini Developer API.\");\r\n } else {\r\n const body = deleteFileParametersToMldev(params);\r\n path2 = formatMap(\"files/{file}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"DELETE\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = deleteFileResponseFromMldev(apiResponse);\r\n const typedResp = new DeleteFileResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n async registerFilesInternal(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"This method is only supported by the Gemini Developer API.\");\r\n } else {\r\n const body = internalRegisterFilesParametersToMldev(params);\r\n path2 = formatMap(\"files:register\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = registerFilesResponseFromMldev(apiResponse);\r\n const typedResp = new RegisterFilesResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n };\r\n CONTENT_TYPE_HEADER = \"Content-Type\";\r\n SERVER_TIMEOUT_HEADER = \"X-Server-Timeout\";\r\n USER_AGENT_HEADER = \"User-Agent\";\r\n GOOGLE_API_CLIENT_HEADER = \"x-goog-api-client\";\r\n SDK_VERSION = \"1.49.0\";\r\n LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;\r\n VERTEX_AI_API_DEFAULT_VERSION = \"v1beta1\";\r\n GOOGLE_AI_API_DEFAULT_VERSION = \"v1beta\";\r\n DEFAULT_RETRY_ATTEMPTS = 5;\r\n DEFAULT_RETRY_HTTP_STATUS_CODES = [\r\n 408,\r\n // Request timeout\r\n 429,\r\n // Too many requests\r\n 500,\r\n // Internal server error\r\n 502,\r\n // Bad gateway\r\n 503,\r\n // Service unavailable\r\n 504\r\n // Gateway timeout\r\n ];\r\n ApiClient = class {\r\n constructor(opts) {\r\n var _a2, _b, _c;\r\n this.clientOptions = Object.assign({}, opts);\r\n this.customBaseUrl = (_a2 = opts.httpOptions) === null || _a2 === void 0 ? void 0 : _a2.baseUrl;\r\n if (this.clientOptions.vertexai) {\r\n if (this.clientOptions.project && this.clientOptions.location) {\r\n this.clientOptions.apiKey = void 0;\r\n } else if (this.clientOptions.apiKey) {\r\n this.clientOptions.project = void 0;\r\n this.clientOptions.location = void 0;\r\n }\r\n }\r\n const initHttpOptions = {};\r\n if (this.clientOptions.vertexai) {\r\n if (!this.clientOptions.location && !this.clientOptions.apiKey && !this.customBaseUrl) {\r\n this.clientOptions.location = \"global\";\r\n }\r\n const hasSufficientAuth = this.clientOptions.project && this.clientOptions.location || this.clientOptions.apiKey;\r\n if (!hasSufficientAuth && !this.customBaseUrl) {\r\n throw new Error(\"Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.\");\r\n }\r\n const hasConstructorAuth = opts.project && opts.location || !!opts.apiKey;\r\n if (this.customBaseUrl && !hasConstructorAuth) {\r\n initHttpOptions.baseUrl = this.customBaseUrl;\r\n this.clientOptions.project = void 0;\r\n this.clientOptions.location = void 0;\r\n } else if (this.clientOptions.apiKey || this.clientOptions.location === \"global\") {\r\n initHttpOptions.baseUrl = \"https://aiplatform.googleapis.com/\";\r\n } else if (this.clientOptions.project && this.clientOptions.location && this.clientOptions.location === \"us\") {\r\n initHttpOptions.baseUrl = `https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`;\r\n } else if (this.clientOptions.project && this.clientOptions.location) {\r\n initHttpOptions.baseUrl = `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;\r\n }\r\n initHttpOptions.apiVersion = (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : VERTEX_AI_API_DEFAULT_VERSION;\r\n } else {\r\n if (!this.clientOptions.apiKey) {\r\n console.warn(\"API key should be set when using the Gemini API.\");\r\n }\r\n initHttpOptions.apiVersion = (_c = this.clientOptions.apiVersion) !== null && _c !== void 0 ? _c : GOOGLE_AI_API_DEFAULT_VERSION;\r\n initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;\r\n }\r\n initHttpOptions.headers = this.getDefaultHeaders();\r\n this.clientOptions.httpOptions = initHttpOptions;\r\n if (opts.httpOptions) {\r\n this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions);\r\n }\r\n }\r\n isVertexAI() {\r\n var _a2;\r\n return (_a2 = this.clientOptions.vertexai) !== null && _a2 !== void 0 ? _a2 : false;\r\n }\r\n getProject() {\r\n return this.clientOptions.project;\r\n }\r\n getLocation() {\r\n return this.clientOptions.location;\r\n }\r\n getCustomBaseUrl() {\r\n return this.customBaseUrl;\r\n }\r\n async getAuthHeaders() {\r\n const headers = new Headers();\r\n await this.clientOptions.auth.addAuthHeaders(headers);\r\n return headers;\r\n }\r\n getApiVersion() {\r\n if (this.clientOptions.httpOptions && this.clientOptions.httpOptions.apiVersion !== void 0) {\r\n return this.clientOptions.httpOptions.apiVersion;\r\n }\r\n throw new Error(\"API version is not set.\");\r\n }\r\n getBaseUrl() {\r\n if (this.clientOptions.httpOptions && this.clientOptions.httpOptions.baseUrl !== void 0) {\r\n return this.clientOptions.httpOptions.baseUrl;\r\n }\r\n throw new Error(\"Base URL is not set.\");\r\n }\r\n getRequestUrl() {\r\n return this.getRequestUrlInternal(this.clientOptions.httpOptions);\r\n }\r\n getHeaders() {\r\n if (this.clientOptions.httpOptions && this.clientOptions.httpOptions.headers !== void 0) {\r\n return this.clientOptions.httpOptions.headers;\r\n } else {\r\n throw new Error(\"Headers are not set.\");\r\n }\r\n }\r\n getRequestUrlInternal(httpOptions) {\r\n if (!httpOptions || httpOptions.baseUrl === void 0 || httpOptions.apiVersion === void 0) {\r\n throw new Error(\"HTTP options are not correctly set.\");\r\n }\r\n const baseUrl = httpOptions.baseUrl.endsWith(\"/\") ? httpOptions.baseUrl.slice(0, -1) : httpOptions.baseUrl;\r\n const urlElement = [baseUrl];\r\n if (httpOptions.apiVersion && httpOptions.apiVersion !== \"\") {\r\n urlElement.push(httpOptions.apiVersion);\r\n }\r\n return urlElement.join(\"/\");\r\n }\r\n getBaseResourcePath() {\r\n return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`;\r\n }\r\n getApiKey() {\r\n return this.clientOptions.apiKey;\r\n }\r\n getWebsocketBaseUrl() {\r\n const baseUrl = this.getBaseUrl();\r\n const urlParts = new URL(baseUrl);\r\n urlParts.protocol = urlParts.protocol == \"http:\" ? \"ws\" : \"wss\";\r\n return urlParts.toString();\r\n }\r\n setBaseUrl(url) {\r\n if (this.clientOptions.httpOptions) {\r\n this.clientOptions.httpOptions.baseUrl = url;\r\n } else {\r\n throw new Error(\"HTTP options are not correctly set.\");\r\n }\r\n }\r\n constructUrl(path2, httpOptions, prependProjectLocation) {\r\n const urlElement = [this.getRequestUrlInternal(httpOptions)];\r\n if (prependProjectLocation) {\r\n urlElement.push(this.getBaseResourcePath());\r\n }\r\n if (path2 !== \"\") {\r\n urlElement.push(path2);\r\n }\r\n const url = new URL(`${urlElement.join(\"/\")}`);\r\n return url;\r\n }\r\n shouldPrependVertexProjectPath(request, httpOptions) {\r\n if (httpOptions.baseUrl && httpOptions.baseUrlResourceScope === ResourceScope.COLLECTION) {\r\n return false;\r\n }\r\n if (this.clientOptions.apiKey) {\r\n return false;\r\n }\r\n if (!this.clientOptions.vertexai) {\r\n return false;\r\n }\r\n if (request.path.startsWith(\"projects/\")) {\r\n return false;\r\n }\r\n if (request.httpMethod === \"GET\" && request.path.startsWith(\"publishers/google/models\")) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n async request(request) {\r\n let patchedHttpOptions = this.clientOptions.httpOptions;\r\n if (request.httpOptions) {\r\n patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions);\r\n }\r\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request, patchedHttpOptions);\r\n const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation);\r\n if (request.queryParams) {\r\n for (const [key, value] of Object.entries(request.queryParams)) {\r\n url.searchParams.append(key, String(value));\r\n }\r\n }\r\n let requestInit = {};\r\n if (request.httpMethod === \"GET\") {\r\n if (request.body && request.body !== \"{}\") {\r\n throw new Error(\"Request body should be empty for GET request, but got non empty request body\");\r\n }\r\n } else {\r\n requestInit.body = request.body;\r\n }\r\n requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, url.toString(), request.abortSignal);\r\n return this.unaryApiCall(url, requestInit, request.httpMethod);\r\n }\r\n patchHttpOptions(baseHttpOptions, requestHttpOptions) {\r\n const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions));\r\n for (const [key, value] of Object.entries(requestHttpOptions)) {\r\n if (typeof value === \"object\") {\r\n patchedHttpOptions[key] = Object.assign(Object.assign({}, patchedHttpOptions[key]), value);\r\n } else if (value !== void 0) {\r\n patchedHttpOptions[key] = value;\r\n }\r\n }\r\n return patchedHttpOptions;\r\n }\r\n async requestStream(request) {\r\n let patchedHttpOptions = this.clientOptions.httpOptions;\r\n if (request.httpOptions) {\r\n patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions);\r\n }\r\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request, patchedHttpOptions);\r\n const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation);\r\n if (!url.searchParams.has(\"alt\") || url.searchParams.get(\"alt\") !== \"sse\") {\r\n url.searchParams.set(\"alt\", \"sse\");\r\n }\r\n let requestInit = {};\r\n requestInit.body = request.body;\r\n requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, url.toString(), request.abortSignal);\r\n return this.streamApiCall(url, requestInit, request.httpMethod);\r\n }\r\n async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, url, abortSignal) {\r\n if (httpOptions && httpOptions.timeout || abortSignal) {\r\n const abortController = new AbortController();\r\n const signal = abortController.signal;\r\n if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) {\r\n const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout);\r\n if (timeoutHandle && typeof timeoutHandle.unref === \"function\") {\r\n timeoutHandle.unref();\r\n }\r\n }\r\n if (abortSignal) {\r\n abortSignal.addEventListener(\"abort\", () => {\r\n abortController.abort();\r\n });\r\n }\r\n requestInit.signal = signal;\r\n }\r\n if (httpOptions && httpOptions.extraBody !== null) {\r\n includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody);\r\n }\r\n requestInit.headers = await this.getHeadersInternal(httpOptions, url);\r\n return requestInit;\r\n }\r\n async unaryApiCall(url, requestInit, httpMethod) {\r\n return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })).then(async (response) => {\r\n await throwErrorIfNotOK(response);\r\n return new HttpResponse(response);\r\n }).catch((e) => {\r\n if (e instanceof Error) {\r\n throw e;\r\n } else {\r\n throw new Error(JSON.stringify(e));\r\n }\r\n });\r\n }\r\n async streamApiCall(url, requestInit, httpMethod) {\r\n return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })).then(async (response) => {\r\n await throwErrorIfNotOK(response);\r\n return this.processStreamResponse(response);\r\n }).catch((e) => {\r\n if (e instanceof Error) {\r\n throw e;\r\n } else {\r\n throw new Error(JSON.stringify(e));\r\n }\r\n });\r\n }\r\n processStreamResponse(response) {\r\n return __asyncGenerator(this, arguments, function* processStreamResponse_1() {\r\n var _a2;\r\n const reader = (_a2 = response === null || response === void 0 ? void 0 : response.body) === null || _a2 === void 0 ? void 0 : _a2.getReader();\r\n const decoder = new TextDecoder(\"utf-8\");\r\n if (!reader) {\r\n throw new Error(\"Response body is empty\");\r\n }\r\n try {\r\n let buffer = \"\";\r\n const dataPrefix = \"data:\";\r\n const delimiters = [\"\\n\\n\", \"\\r\\r\", \"\\r\\n\\r\\n\"];\r\n while (true) {\r\n const { done, value } = yield __await(reader.read());\r\n if (done) {\r\n if (buffer.trim().length > 0) {\r\n throw new Error(\"Incomplete JSON segment at the end\");\r\n }\r\n break;\r\n }\r\n const chunkString = decoder.decode(value, { stream: true });\r\n try {\r\n const chunkJson = JSON.parse(chunkString);\r\n if (\"error\" in chunkJson) {\r\n const errorJson = JSON.parse(JSON.stringify(chunkJson[\"error\"]));\r\n const status = errorJson[\"status\"];\r\n const code = errorJson[\"code\"];\r\n const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`;\r\n if (code >= 400 && code < 600) {\r\n const apiError = new ApiError({\r\n message: errorMessage,\r\n status: code\r\n });\r\n throw apiError;\r\n }\r\n }\r\n } catch (e) {\r\n const error = e;\r\n if (error.name === \"ApiError\") {\r\n throw e;\r\n }\r\n }\r\n buffer += chunkString;\r\n let delimiterIndex = -1;\r\n let delimiterLength = 0;\r\n while (true) {\r\n delimiterIndex = -1;\r\n delimiterLength = 0;\r\n for (const delimiter of delimiters) {\r\n const index = buffer.indexOf(delimiter);\r\n if (index !== -1 && (delimiterIndex === -1 || index < delimiterIndex)) {\r\n delimiterIndex = index;\r\n delimiterLength = delimiter.length;\r\n }\r\n }\r\n if (delimiterIndex === -1) {\r\n break;\r\n }\r\n const eventString = buffer.substring(0, delimiterIndex);\r\n buffer = buffer.substring(delimiterIndex + delimiterLength);\r\n const trimmedEvent = eventString.trim();\r\n if (trimmedEvent.startsWith(dataPrefix)) {\r\n const processedChunkString = trimmedEvent.substring(dataPrefix.length).trim();\r\n try {\r\n const partialResponse = new Response(processedChunkString, {\r\n headers: response === null || response === void 0 ? void 0 : response.headers,\r\n status: response === null || response === void 0 ? void 0 : response.status,\r\n statusText: response === null || response === void 0 ? void 0 : response.statusText\r\n });\r\n yield yield __await(new HttpResponse(partialResponse));\r\n } catch (e) {\r\n throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`);\r\n }\r\n }\r\n }\r\n }\r\n } finally {\r\n reader.releaseLock();\r\n }\r\n });\r\n }\r\n async apiCall(url, requestInit) {\r\n var _a2;\r\n if (!this.clientOptions.httpOptions || !this.clientOptions.httpOptions.retryOptions) {\r\n return fetch(url, requestInit);\r\n }\r\n const retryOptions = this.clientOptions.httpOptions.retryOptions;\r\n const runFetch = async () => {\r\n const response = await fetch(url, requestInit);\r\n if (response.ok) {\r\n return response;\r\n }\r\n if (DEFAULT_RETRY_HTTP_STATUS_CODES.includes(response.status)) {\r\n throw new Error(`Retryable HTTP Error: ${response.statusText}`);\r\n }\r\n throw new import_p_retry.AbortError(`Non-retryable exception ${response.statusText} sending request`);\r\n };\r\n return (0, import_p_retry.default)(runFetch, {\r\n // Retry attempts is one less than the number of total attempts.\r\n retries: ((_a2 = retryOptions.attempts) !== null && _a2 !== void 0 ? _a2 : DEFAULT_RETRY_ATTEMPTS) - 1\r\n });\r\n }\r\n getDefaultHeaders() {\r\n const headers = {};\r\n const versionHeaderValue = LIBRARY_LABEL + \" \" + this.clientOptions.userAgentExtra;\r\n headers[USER_AGENT_HEADER] = versionHeaderValue;\r\n headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;\r\n headers[CONTENT_TYPE_HEADER] = \"application/json\";\r\n return headers;\r\n }\r\n async getHeadersInternal(httpOptions, url) {\r\n const headers = new Headers();\r\n if (httpOptions && httpOptions.headers) {\r\n for (const [key, value] of Object.entries(httpOptions.headers)) {\r\n headers.append(key, value);\r\n }\r\n if (httpOptions.timeout && httpOptions.timeout > 0) {\r\n headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1e3)));\r\n }\r\n }\r\n await this.clientOptions.auth.addAuthHeaders(headers, url);\r\n return headers;\r\n }\r\n getFileName(file) {\r\n var _a2;\r\n let fileName = \"\";\r\n if (typeof file === \"string\") {\r\n fileName = file.replace(/[/\\\\]+$/, \"\");\r\n fileName = (_a2 = fileName.split(/[/\\\\]/).pop()) !== null && _a2 !== void 0 ? _a2 : \"\";\r\n }\r\n return fileName;\r\n }\r\n /**\r\n * Uploads a file asynchronously using Gemini API only, this is not supported\r\n * in Vertex AI.\r\n *\r\n * @param file The string path to the file to be uploaded or a Blob object.\r\n * @param config Optional parameters specified in the `UploadFileConfig`\r\n * interface. @see {@link types.UploadFileConfig}\r\n * @return A promise that resolves to a `File` object.\r\n * @throws An error if called on a Vertex AI client.\r\n * @throws An error if the `mimeType` is not provided and can not be inferred,\r\n */\r\n async uploadFile(file, config) {\r\n var _a2;\r\n const fileToUpload = {};\r\n if (config != null) {\r\n fileToUpload.mimeType = config.mimeType;\r\n fileToUpload.name = config.name;\r\n fileToUpload.displayName = config.displayName;\r\n }\r\n if (fileToUpload.name && !fileToUpload.name.startsWith(\"files/\")) {\r\n fileToUpload.name = `files/${fileToUpload.name}`;\r\n }\r\n const uploader = this.clientOptions.uploader;\r\n const fileStat = await uploader.stat(file);\r\n fileToUpload.sizeBytes = String(fileStat.size);\r\n const mimeType = (_a2 = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a2 !== void 0 ? _a2 : fileStat.type;\r\n if (mimeType === void 0 || mimeType === \"\") {\r\n throw new Error(\"Can not determine mimeType. Please provide mimeType in the config.\");\r\n }\r\n fileToUpload.mimeType = mimeType;\r\n const body = {\r\n file: fileToUpload\r\n };\r\n const fileName = this.getFileName(file);\r\n const path2 = formatMap(\"upload/v1beta/files\", body[\"_url\"]);\r\n const uploadUrl = await this.fetchUploadUrl(path2, fileToUpload.sizeBytes, fileToUpload.mimeType, fileName, body, config === null || config === void 0 ? void 0 : config.httpOptions);\r\n return uploader.upload(file, uploadUrl, this);\r\n }\r\n /**\r\n * Uploads a file to a given file search store asynchronously using Gemini API only, this is not supported\r\n * in Vertex AI.\r\n *\r\n * @param fileSearchStoreName The name of the file search store to upload the file to.\r\n * @param file The string path to the file to be uploaded or a Blob object.\r\n * @param config Optional parameters specified in the `UploadFileConfig`\r\n * interface. @see {@link UploadFileConfig}\r\n * @return A promise that resolves to a `File` object.\r\n * @throws An error if called on a Vertex AI client.\r\n * @throws An error if the `mimeType` is not provided and can not be inferred,\r\n */\r\n async uploadFileToFileSearchStore(fileSearchStoreName, file, config) {\r\n var _a2;\r\n const uploader = this.clientOptions.uploader;\r\n const fileStat = await uploader.stat(file);\r\n const sizeBytes = String(fileStat.size);\r\n const mimeType = (_a2 = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a2 !== void 0 ? _a2 : fileStat.type;\r\n if (mimeType === void 0 || mimeType === \"\") {\r\n throw new Error(\"Can not determine mimeType. Please provide mimeType in the config.\");\r\n }\r\n const path2 = `upload/v1beta/${fileSearchStoreName}:uploadToFileSearchStore`;\r\n const fileName = this.getFileName(file);\r\n const body = {};\r\n if (config != null) {\r\n uploadToFileSearchStoreConfigToMldev(config, body);\r\n }\r\n const uploadUrl = await this.fetchUploadUrl(path2, sizeBytes, mimeType, fileName, body, config === null || config === void 0 ? void 0 : config.httpOptions);\r\n return uploader.uploadToFileSearchStore(file, uploadUrl, this);\r\n }\r\n /**\r\n * Downloads a file asynchronously to the specified path.\r\n *\r\n * @params params - The parameters for the download request, see {@link\r\n * types.DownloadFileParameters}\r\n */\r\n async downloadFile(params) {\r\n const downloader = this.clientOptions.downloader;\r\n await downloader.download(params, this);\r\n }\r\n async fetchUploadUrl(path2, sizeBytes, mimeType, fileName, body, configHttpOptions) {\r\n var _a2;\r\n let httpOptions = {};\r\n if (configHttpOptions) {\r\n httpOptions = configHttpOptions;\r\n } else {\r\n httpOptions = {\r\n apiVersion: \"\",\r\n // api-version is set in the path.\r\n headers: Object.assign({ \"Content-Type\": \"application/json\", \"X-Goog-Upload-Protocol\": \"resumable\", \"X-Goog-Upload-Command\": \"start\", \"X-Goog-Upload-Header-Content-Length\": `${sizeBytes}`, \"X-Goog-Upload-Header-Content-Type\": `${mimeType}` }, fileName ? { \"X-Goog-Upload-File-Name\": fileName } : {})\r\n };\r\n }\r\n const httpResponse = await this.request({\r\n path: path2,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions\r\n });\r\n if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) {\r\n throw new Error(\"Server did not return an HttpResponse or the returned HttpResponse did not have headers.\");\r\n }\r\n const uploadUrl = (_a2 = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a2 === void 0 ? void 0 : _a2[\"x-goog-upload-url\"];\r\n if (uploadUrl === void 0) {\r\n throw new Error(\"Failed to get upload url. Server did not return the x-google-upload-url in the headers\");\r\n }\r\n return uploadUrl;\r\n }\r\n };\r\n MCP_LABEL = \"mcp_used/unknown\";\r\n hasMcpToolUsageFromMcpToTool = false;\r\n McpCallableTool = class _McpCallableTool {\r\n constructor(mcpClients = [], config) {\r\n this.mcpTools = [];\r\n this.functionNameToMcpClient = {};\r\n this.mcpClients = mcpClients;\r\n this.config = config;\r\n }\r\n /**\r\n * Creates a McpCallableTool.\r\n */\r\n static create(mcpClients, config) {\r\n return new _McpCallableTool(mcpClients, config);\r\n }\r\n /**\r\n * Validates the function names are not duplicate and initialize the function\r\n * name to MCP client mapping.\r\n *\r\n * @throws {Error} if the MCP tools from the MCP clients have duplicate tool\r\n * names.\r\n */\r\n async initialize() {\r\n var _a2, e_1, _b, _c;\r\n if (this.mcpTools.length > 0) {\r\n return;\r\n }\r\n const functionMap = {};\r\n const mcpTools = [];\r\n for (const mcpClient of this.mcpClients) {\r\n try {\r\n for (var _d = true, _e = (e_1 = void 0, __asyncValues(listAllTools(mcpClient))), _f; _f = await _e.next(), _a2 = _f.done, !_a2; _d = true) {\r\n _c = _f.value;\r\n _d = false;\r\n const mcpTool = _c;\r\n mcpTools.push(mcpTool);\r\n const mcpToolName = mcpTool.name;\r\n if (functionMap[mcpToolName]) {\r\n throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);\r\n }\r\n functionMap[mcpToolName] = mcpClient;\r\n }\r\n } catch (e_1_1) {\r\n e_1 = { error: e_1_1 };\r\n } finally {\r\n try {\r\n if (!_d && !_a2 && (_b = _e.return)) await _b.call(_e);\r\n } finally {\r\n if (e_1) throw e_1.error;\r\n }\r\n }\r\n }\r\n this.mcpTools = mcpTools;\r\n this.functionNameToMcpClient = functionMap;\r\n }\r\n async tool() {\r\n await this.initialize();\r\n return mcpToolsToGeminiTool(this.mcpTools, this.config);\r\n }\r\n async callTool(functionCalls) {\r\n await this.initialize();\r\n const functionCallResponseParts = [];\r\n for (const functionCall of functionCalls) {\r\n if (functionCall.name in this.functionNameToMcpClient) {\r\n const mcpClient = this.functionNameToMcpClient[functionCall.name];\r\n let requestOptions = void 0;\r\n if (this.config.timeout) {\r\n requestOptions = {\r\n timeout: this.config.timeout\r\n };\r\n }\r\n const callToolResponse = await mcpClient.callTool(\r\n {\r\n name: functionCall.name,\r\n arguments: functionCall.args\r\n },\r\n // Set the result schema to undefined to allow MCP to rely on the\r\n // default schema.\r\n void 0,\r\n requestOptions\r\n );\r\n functionCallResponseParts.push({\r\n functionResponse: {\r\n name: functionCall.name,\r\n response: callToolResponse.isError ? { error: callToolResponse } : callToolResponse\r\n }\r\n });\r\n }\r\n }\r\n return functionCallResponseParts;\r\n }\r\n };\r\n LiveMusic = class {\r\n constructor(apiClient, auth, webSocketFactory) {\r\n this.apiClient = apiClient;\r\n this.auth = auth;\r\n this.webSocketFactory = webSocketFactory;\r\n }\r\n /**\r\n Establishes a connection to the specified model and returns a\r\n LiveMusicSession object representing that connection.\r\n \r\n @experimental\r\n \r\n @remarks\r\n \r\n @param params - The parameters for establishing a connection to the model.\r\n @return A live session.\r\n \r\n @example\r\n ```ts\r\n let model = 'models/lyria-realtime-exp';\r\n const session = await ai.live.music.connect({\r\n model: model,\r\n callbacks: {\r\n onmessage: (e: MessageEvent) => {\r\n console.log('Received message from the server: %s\\n', debug(e.data));\r\n },\r\n onerror: (e: ErrorEvent) => {\r\n console.log('Error occurred: %s\\n', debug(e.error));\r\n },\r\n onclose: (e: CloseEvent) => {\r\n console.log('Connection closed.');\r\n },\r\n },\r\n });\r\n ```\r\n */\r\n async connect(params) {\r\n var _a2, _b;\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"Live music is not supported for Vertex AI.\");\r\n }\r\n console.warn(\"Live music generation is experimental and may change in future versions.\");\r\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\r\n const apiVersion = this.apiClient.getApiVersion();\r\n const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders());\r\n const apiKey = this.apiClient.getApiKey();\r\n const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`;\r\n let onopenResolve = () => {\r\n };\r\n const onopenPromise = new Promise((resolve) => {\r\n onopenResolve = resolve;\r\n });\r\n const callbacks = params.callbacks;\r\n const onopenAwaitedCallback = function() {\r\n onopenResolve({});\r\n };\r\n const apiClient = this.apiClient;\r\n const websocketCallbacks = {\r\n onopen: onopenAwaitedCallback,\r\n onmessage: (event) => {\r\n void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event);\r\n },\r\n onerror: (_a2 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a2 !== void 0 ? _a2 : function(e) {\r\n },\r\n onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function(e) {\r\n }\r\n };\r\n const conn = this.webSocketFactory.create(url, headersToMap$1(headers), websocketCallbacks);\r\n conn.connect();\r\n await onopenPromise;\r\n const model = tModel(this.apiClient, params.model);\r\n const setup = { model };\r\n const clientMessage = { setup };\r\n conn.send(JSON.stringify(clientMessage));\r\n return new LiveMusicSession(conn, this.apiClient);\r\n }\r\n };\r\n LiveMusicSession = class {\r\n constructor(conn, apiClient) {\r\n this.conn = conn;\r\n this.apiClient = apiClient;\r\n }\r\n /**\r\n Sets inputs to steer music generation. Updates the session's current\r\n weighted prompts.\r\n \r\n @param params - Contains one property, `weightedPrompts`.\r\n \r\n - `weightedPrompts` to send to the model; weights are normalized to\r\n sum to 1.0.\r\n \r\n @experimental\r\n */\r\n async setWeightedPrompts(params) {\r\n if (!params.weightedPrompts || Object.keys(params.weightedPrompts).length === 0) {\r\n throw new Error(\"Weighted prompts must be set and contain at least one entry.\");\r\n }\r\n const clientContent = liveMusicSetWeightedPromptsParametersToMldev(params);\r\n this.conn.send(JSON.stringify({ clientContent }));\r\n }\r\n /**\r\n Sets a configuration to the model. Updates the session's current\r\n music generation config.\r\n \r\n @param params - Contains one property, `musicGenerationConfig`.\r\n \r\n - `musicGenerationConfig` to set in the model. Passing an empty or\r\n undefined config to the model will reset the config to defaults.\r\n \r\n @experimental\r\n */\r\n async setMusicGenerationConfig(params) {\r\n if (!params.musicGenerationConfig) {\r\n params.musicGenerationConfig = {};\r\n }\r\n const setConfigParameters = liveMusicSetConfigParametersToMldev(params);\r\n this.conn.send(JSON.stringify(setConfigParameters));\r\n }\r\n sendPlaybackControl(playbackControl) {\r\n const clientMessage = { playbackControl };\r\n this.conn.send(JSON.stringify(clientMessage));\r\n }\r\n /**\r\n * Start the music stream.\r\n *\r\n * @experimental\r\n */\r\n play() {\r\n this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY);\r\n }\r\n /**\r\n * Temporarily halt the music stream. Use `play` to resume from the current\r\n * position.\r\n *\r\n * @experimental\r\n */\r\n pause() {\r\n this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE);\r\n }\r\n /**\r\n * Stop the music stream and reset the state. Retains the current prompts\r\n * and config.\r\n *\r\n * @experimental\r\n */\r\n stop() {\r\n this.sendPlaybackControl(LiveMusicPlaybackControl.STOP);\r\n }\r\n /**\r\n * Resets the context of the music generation without stopping it.\r\n * Retains the current prompts and config.\r\n *\r\n * @experimental\r\n */\r\n resetContext() {\r\n this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT);\r\n }\r\n /**\r\n Terminates the WebSocket connection.\r\n \r\n @experimental\r\n */\r\n close() {\r\n this.conn.close();\r\n }\r\n };\r\n FUNCTION_RESPONSE_REQUIRES_ID = \"FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.\";\r\n Live = class {\r\n constructor(apiClient, auth, webSocketFactory) {\r\n this.apiClient = apiClient;\r\n this.auth = auth;\r\n this.webSocketFactory = webSocketFactory;\r\n this.music = new LiveMusic(this.apiClient, this.auth, this.webSocketFactory);\r\n }\r\n /**\r\n Establishes a connection to the specified model with the given\r\n configuration and returns a Session object representing that connection.\r\n \r\n @experimental Built-in MCP support is an experimental feature, may change in\r\n future versions.\r\n \r\n @remarks\r\n \r\n @param params - The parameters for establishing a connection to the model.\r\n @return A live session.\r\n \r\n @example\r\n ```ts\r\n let model: string;\r\n if (GOOGLE_GENAI_USE_VERTEXAI) {\r\n model = 'gemini-2.0-flash-live-preview-04-09';\r\n } else {\r\n model = 'gemini-live-2.5-flash-preview';\r\n }\r\n const session = await ai.live.connect({\r\n model: model,\r\n config: {\r\n responseModalities: [Modality.AUDIO],\r\n },\r\n callbacks: {\r\n onopen: () => {\r\n console.log('Connected to the socket.');\r\n },\r\n onmessage: (e: MessageEvent) => {\r\n console.log('Received message from the server: %s\\n', debug(e.data));\r\n },\r\n onerror: (e: ErrorEvent) => {\r\n console.log('Error occurred: %s\\n', debug(e.error));\r\n },\r\n onclose: (e: CloseEvent) => {\r\n console.log('Connection closed.');\r\n },\r\n },\r\n });\r\n ```\r\n */\r\n async connect(params) {\r\n var _a2, _b, _c, _d, _e, _f;\r\n if (params.config && params.config.httpOptions) {\r\n throw new Error(\"The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.\");\r\n }\r\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\r\n const apiVersion = this.apiClient.getApiVersion();\r\n let url;\r\n const clientHeaders = this.apiClient.getHeaders();\r\n if (params.config && params.config.tools && hasMcpToolUsage(params.config.tools)) {\r\n setMcpUsageHeader(clientHeaders);\r\n }\r\n const headers = mapToHeaders(clientHeaders);\r\n if (this.apiClient.isVertexAI()) {\r\n const project = this.apiClient.getProject();\r\n const location = this.apiClient.getLocation();\r\n const apiKey = this.apiClient.getApiKey();\r\n const hasStandardAuth = !!project && !!location || !!apiKey;\r\n if (this.apiClient.getCustomBaseUrl() && !hasStandardAuth) {\r\n url = websocketBaseUrl;\r\n } else {\r\n url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`;\r\n await this.auth.addAuthHeaders(headers, url);\r\n }\r\n } else {\r\n const apiKey = this.apiClient.getApiKey();\r\n let method = \"BidiGenerateContent\";\r\n let keyName = \"key\";\r\n if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith(\"auth_tokens/\")) {\r\n console.warn(\"Warning: Ephemeral token support is experimental and may change in future versions.\");\r\n if (apiVersion !== \"v1alpha\") {\r\n console.warn(\"Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection.\");\r\n }\r\n method = \"BidiGenerateContentConstrained\";\r\n keyName = \"access_token\";\r\n }\r\n url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`;\r\n }\r\n let onopenResolve = () => {\r\n };\r\n const onopenPromise = new Promise((resolve) => {\r\n onopenResolve = resolve;\r\n });\r\n const callbacks = params.callbacks;\r\n const onopenAwaitedCallback = function() {\r\n var _a3;\r\n (_a3 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onopen) === null || _a3 === void 0 ? void 0 : _a3.call(callbacks);\r\n onopenResolve({});\r\n };\r\n const apiClient = this.apiClient;\r\n const websocketCallbacks = {\r\n onopen: onopenAwaitedCallback,\r\n onmessage: (event) => {\r\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\r\n },\r\n onerror: (_a2 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a2 !== void 0 ? _a2 : function(e) {\r\n },\r\n onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function(e) {\r\n }\r\n };\r\n const conn = this.webSocketFactory.create(url, headersToMap(headers), websocketCallbacks);\r\n conn.connect();\r\n await onopenPromise;\r\n let transformedModel = tModel(this.apiClient, params.model);\r\n if (this.apiClient.isVertexAI() && transformedModel.startsWith(\"publishers/\")) {\r\n const project = this.apiClient.getProject();\r\n const location = this.apiClient.getLocation();\r\n if (project && location) {\r\n transformedModel = `projects/${project}/locations/${location}/` + transformedModel;\r\n }\r\n }\r\n let clientMessage = {};\r\n if (this.apiClient.isVertexAI() && ((_c = params.config) === null || _c === void 0 ? void 0 : _c.responseModalities) === void 0) {\r\n if (params.config === void 0) {\r\n params.config = { responseModalities: [Modality.AUDIO] };\r\n } else {\r\n params.config.responseModalities = [Modality.AUDIO];\r\n }\r\n }\r\n if ((_d = params.config) === null || _d === void 0 ? void 0 : _d.generationConfig) {\r\n console.warn(\"Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).\");\r\n }\r\n const inputTools = (_f = (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== null && _f !== void 0 ? _f : [];\r\n const convertedTools = [];\r\n for (const tool of inputTools) {\r\n if (this.isCallableTool(tool)) {\r\n const callableTool = tool;\r\n convertedTools.push(await callableTool.tool());\r\n } else {\r\n convertedTools.push(tool);\r\n }\r\n }\r\n if (convertedTools.length > 0) {\r\n params.config.tools = convertedTools;\r\n }\r\n const liveConnectParameters = {\r\n model: transformedModel,\r\n config: params.config,\r\n callbacks: params.callbacks\r\n };\r\n if (this.apiClient.isVertexAI()) {\r\n clientMessage = liveConnectParametersToVertex(this.apiClient, liveConnectParameters);\r\n } else {\r\n clientMessage = liveConnectParametersToMldev(this.apiClient, liveConnectParameters);\r\n }\r\n delete clientMessage[\"config\"];\r\n conn.send(JSON.stringify(clientMessage));\r\n return new Session(conn, this.apiClient);\r\n }\r\n // TODO: b/416041229 - Abstract this method to a common place.\r\n isCallableTool(tool) {\r\n return \"callTool\" in tool && typeof tool.callTool === \"function\";\r\n }\r\n };\r\n defaultLiveSendClientContentParamerters = {\r\n turnComplete: true\r\n };\r\n Session = class {\r\n constructor(conn, apiClient) {\r\n this.conn = conn;\r\n this.apiClient = apiClient;\r\n }\r\n tLiveClientContent(apiClient, params) {\r\n if (params.turns !== null && params.turns !== void 0) {\r\n let contents = [];\r\n try {\r\n contents = tContents(params.turns);\r\n if (!apiClient.isVertexAI()) {\r\n contents = contents.map((item) => contentToMldev$1(item));\r\n }\r\n } catch (_a2) {\r\n throw new Error(`Failed to parse client content \"turns\", type: '${typeof params.turns}'`);\r\n }\r\n return {\r\n clientContent: { turns: contents, turnComplete: params.turnComplete }\r\n };\r\n }\r\n return {\r\n clientContent: { turnComplete: params.turnComplete }\r\n };\r\n }\r\n tLiveClienttToolResponse(apiClient, params) {\r\n let functionResponses = [];\r\n if (params.functionResponses == null) {\r\n throw new Error(\"functionResponses is required.\");\r\n }\r\n if (!Array.isArray(params.functionResponses)) {\r\n functionResponses = [params.functionResponses];\r\n } else {\r\n functionResponses = params.functionResponses;\r\n }\r\n if (functionResponses.length === 0) {\r\n throw new Error(\"functionResponses is required.\");\r\n }\r\n for (const functionResponse of functionResponses) {\r\n if (typeof functionResponse !== \"object\" || functionResponse === null || !(\"name\" in functionResponse) || !(\"response\" in functionResponse)) {\r\n throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`);\r\n }\r\n if (!apiClient.isVertexAI() && !(\"id\" in functionResponse)) {\r\n throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);\r\n }\r\n }\r\n const clientMessage = {\r\n toolResponse: { \"functionResponses\": functionResponses }\r\n };\r\n return clientMessage;\r\n }\r\n /**\r\n Send a message over the established connection.\r\n \r\n @param params - Contains two **optional** properties, `turns` and\r\n `turnComplete`.\r\n \r\n - `turns` will be converted to a `Content[]`\r\n - `turnComplete: true` [default] indicates that you are done sending\r\n content and expect a response. If `turnComplete: false`, the server\r\n will wait for additional messages before starting generation.\r\n \r\n @experimental\r\n \r\n @remarks\r\n There are two ways to send messages to the live API:\r\n `sendClientContent` and `sendRealtimeInput`.\r\n \r\n `sendClientContent` messages are added to the model context **in order**.\r\n Having a conversation using `sendClientContent` messages is roughly\r\n equivalent to using the `Chat.sendMessageStream`, except that the state of\r\n the `chat` history is stored on the API server instead of locally.\r\n \r\n Because of `sendClientContent`'s order guarantee, the model cannot respons\r\n as quickly to `sendClientContent` messages as to `sendRealtimeInput`\r\n messages. This makes the biggest difference when sending objects that have\r\n significant preprocessing time (typically images).\r\n \r\n The `sendClientContent` message sends a `Content[]`\r\n which has more options than the `Blob` sent by `sendRealtimeInput`.\r\n \r\n So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:\r\n \r\n - Sending anything that can't be represented as a `Blob` (text,\r\n `sendClientContent({turns=\"Hello?\"}`)).\r\n - Managing turns when not using audio input and voice activity detection.\r\n (`sendClientContent({turnComplete:true})` or the short form\r\n `sendClientContent()`)\r\n - Prefilling a conversation context\r\n ```\r\n sendClientContent({\r\n turns: [\r\n Content({role:user, parts:...}),\r\n Content({role:user, parts:...}),\r\n ...\r\n ]\r\n })\r\n ```\r\n @experimental\r\n */\r\n sendClientContent(params) {\r\n params = Object.assign(Object.assign({}, defaultLiveSendClientContentParamerters), params);\r\n const clientMessage = this.tLiveClientContent(this.apiClient, params);\r\n this.conn.send(JSON.stringify(clientMessage));\r\n }\r\n /**\r\n Send a realtime message over the established connection.\r\n \r\n @param params - Contains one property, `media`.\r\n \r\n - `media` will be converted to a `Blob`\r\n \r\n @experimental\r\n \r\n @remarks\r\n Use `sendRealtimeInput` for realtime audio chunks and video frames (images).\r\n \r\n With `sendRealtimeInput` the api will respond to audio automatically\r\n based on voice activity detection (VAD).\r\n \r\n `sendRealtimeInput` is optimized for responsivness at the expense of\r\n deterministic ordering guarantees. Audio and video tokens are to the\r\n context when they become available.\r\n \r\n Note: The Call signature expects a `Blob` object, but only a subset\r\n of audio and image mimetypes are allowed.\r\n */\r\n sendRealtimeInput(params) {\r\n let clientMessage = {};\r\n if (this.apiClient.isVertexAI()) {\r\n clientMessage = {\r\n \"realtimeInput\": liveSendRealtimeInputParametersToVertex(params)\r\n };\r\n } else {\r\n clientMessage = {\r\n \"realtimeInput\": liveSendRealtimeInputParametersToMldev(params)\r\n };\r\n }\r\n this.conn.send(JSON.stringify(clientMessage));\r\n }\r\n /**\r\n Send a function response message over the established connection.\r\n \r\n @param params - Contains property `functionResponses`.\r\n \r\n - `functionResponses` will be converted to a `functionResponses[]`\r\n \r\n @remarks\r\n Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.\r\n \r\n Use {@link types.LiveConnectConfig#tools} to configure the callable functions.\r\n \r\n @experimental\r\n */\r\n sendToolResponse(params) {\r\n if (params.functionResponses == null) {\r\n throw new Error(\"Tool response parameters are required.\");\r\n }\r\n const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params);\r\n this.conn.send(JSON.stringify(clientMessage));\r\n }\r\n /**\r\n Terminates the WebSocket connection.\r\n \r\n @experimental\r\n \r\n @example\r\n ```ts\r\n let model: string;\r\n if (GOOGLE_GENAI_USE_VERTEXAI) {\r\n model = 'gemini-2.0-flash-live-preview-04-09';\r\n } else {\r\n model = 'gemini-live-2.5-flash-preview';\r\n }\r\n const session = await ai.live.connect({\r\n model: model,\r\n config: {\r\n responseModalities: [Modality.AUDIO],\r\n }\r\n });\r\n \r\n session.close();\r\n ```\r\n */\r\n close() {\r\n this.conn.close();\r\n }\r\n };\r\n DEFAULT_MAX_REMOTE_CALLS = 10;\r\n Models = class extends BaseModule {\r\n constructor(apiClient) {\r\n super();\r\n this.apiClient = apiClient;\r\n this.embedContent = async (params) => {\r\n if (!this.apiClient.isVertexAI()) {\r\n return await this.embedContentInternal(params);\r\n }\r\n const isVertexEmbedContentModel = params.model.includes(\"gemini\") && params.model !== \"gemini-embedding-001\" || params.model.includes(\"maas\");\r\n if (isVertexEmbedContentModel) {\r\n const contents = tContents(params.contents);\r\n if (contents.length > 1) {\r\n throw new Error(\"The embedContent API for this model only supports one content at a time.\");\r\n }\r\n const paramsPrivate = Object.assign(Object.assign({}, params), { content: contents[0], embeddingApiType: EmbeddingApiType.EMBED_CONTENT });\r\n return await this.embedContentInternal(paramsPrivate);\r\n } else {\r\n const paramsPrivate = Object.assign(Object.assign({}, params), { embeddingApiType: EmbeddingApiType.PREDICT });\r\n return await this.embedContentInternal(paramsPrivate);\r\n }\r\n };\r\n this.generateContent = async (params) => {\r\n var _a2, _b, _c, _d, _e;\r\n const transformedParams = await this.processParamsMaybeAddMcpUsage(params);\r\n this.maybeMoveToResponseJsonSchem(params);\r\n if (!hasCallableTools(params) || shouldDisableAfc(params.config)) {\r\n return await this.generateContentInternal(transformedParams);\r\n }\r\n const incompatibleToolIndexes = findAfcIncompatibleToolIndexes(params);\r\n if (incompatibleToolIndexes.length > 0) {\r\n const formattedIndexes = incompatibleToolIndexes.map((index) => `tools[${index}]`).join(\", \");\r\n throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${formattedIndexes}.`);\r\n }\r\n let response;\r\n let functionResponseContent;\r\n const automaticFunctionCallingHistory = tContents(transformedParams.contents);\r\n const maxRemoteCalls = (_c = (_b = (_a2 = transformedParams.config) === null || _a2 === void 0 ? void 0 : _a2.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS;\r\n let remoteCalls = 0;\r\n while (remoteCalls < maxRemoteCalls) {\r\n response = await this.generateContentInternal(transformedParams);\r\n if (!response.functionCalls || response.functionCalls.length === 0) {\r\n break;\r\n }\r\n const responseContent = response.candidates[0].content;\r\n const functionResponseParts = [];\r\n for (const tool of (_e = (_d = params.config) === null || _d === void 0 ? void 0 : _d.tools) !== null && _e !== void 0 ? _e : []) {\r\n if (isCallableTool(tool)) {\r\n const callableTool = tool;\r\n const parts = await callableTool.callTool(response.functionCalls);\r\n functionResponseParts.push(...parts);\r\n }\r\n }\r\n remoteCalls++;\r\n functionResponseContent = {\r\n role: \"user\",\r\n parts: functionResponseParts\r\n };\r\n transformedParams.contents = tContents(transformedParams.contents);\r\n transformedParams.contents.push(responseContent);\r\n transformedParams.contents.push(functionResponseContent);\r\n if (shouldAppendAfcHistory(transformedParams.config)) {\r\n automaticFunctionCallingHistory.push(responseContent);\r\n automaticFunctionCallingHistory.push(functionResponseContent);\r\n }\r\n }\r\n if (shouldAppendAfcHistory(transformedParams.config)) {\r\n response.automaticFunctionCallingHistory = automaticFunctionCallingHistory;\r\n }\r\n return response;\r\n };\r\n this.generateContentStream = async (params) => {\r\n var _a2, _b, _c, _d, _e;\r\n this.maybeMoveToResponseJsonSchem(params);\r\n if (shouldDisableAfc(params.config)) {\r\n const transformedParams = await this.processParamsMaybeAddMcpUsage(params);\r\n return await this.generateContentStreamInternal(transformedParams);\r\n }\r\n const incompatibleToolIndexes = findAfcIncompatibleToolIndexes(params);\r\n if (incompatibleToolIndexes.length > 0) {\r\n const formattedIndexes = incompatibleToolIndexes.map((index) => `tools[${index}]`).join(\", \");\r\n throw new Error(`Incompatible tools found at ${formattedIndexes}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations\" is not yet supported.`);\r\n }\r\n const streamFunctionCall = (_c = (_b = (_a2 = params === null || params === void 0 ? void 0 : params.config) === null || _a2 === void 0 ? void 0 : _a2.toolConfig) === null || _b === void 0 ? void 0 : _b.functionCallingConfig) === null || _c === void 0 ? void 0 : _c.streamFunctionCallArguments;\r\n const disableAfc = (_e = (_d = params === null || params === void 0 ? void 0 : params.config) === null || _d === void 0 ? void 0 : _d.automaticFunctionCalling) === null || _e === void 0 ? void 0 : _e.disable;\r\n if (streamFunctionCall && !disableAfc) {\r\n throw new Error(\"Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.\");\r\n }\r\n return await this.processAfcStream(params);\r\n };\r\n this.generateImages = async (params) => {\r\n return await this.generateImagesInternal(params).then((apiResponse) => {\r\n var _a2;\r\n let positivePromptSafetyAttributes;\r\n const generatedImages = [];\r\n if (apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.generatedImages) {\r\n for (const generatedImage of apiResponse.generatedImages) {\r\n if (generatedImage && (generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) && ((_a2 = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) === null || _a2 === void 0 ? void 0 : _a2.contentType) === \"Positive Prompt\") {\r\n positivePromptSafetyAttributes = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes;\r\n } else {\r\n generatedImages.push(generatedImage);\r\n }\r\n }\r\n }\r\n let response;\r\n if (positivePromptSafetyAttributes) {\r\n response = {\r\n generatedImages,\r\n positivePromptSafetyAttributes,\r\n sdkHttpResponse: apiResponse.sdkHttpResponse\r\n };\r\n } else {\r\n response = {\r\n generatedImages,\r\n sdkHttpResponse: apiResponse.sdkHttpResponse\r\n };\r\n }\r\n return response;\r\n });\r\n };\r\n this.list = async (params) => {\r\n var _a2;\r\n const defaultConfig = {\r\n queryBase: true\r\n };\r\n const actualConfig = Object.assign(Object.assign({}, defaultConfig), params === null || params === void 0 ? void 0 : params.config);\r\n const actualParams = {\r\n config: actualConfig\r\n };\r\n if (this.apiClient.isVertexAI()) {\r\n if (!actualParams.config.queryBase) {\r\n if ((_a2 = actualParams.config) === null || _a2 === void 0 ? void 0 : _a2.filter) {\r\n throw new Error(\"Filtering tuned models list for Vertex AI is not currently supported\");\r\n } else {\r\n actualParams.config.filter = \"labels.tune-type:*\";\r\n }\r\n }\r\n }\r\n return new Pager(PagedItem.PAGED_ITEM_MODELS, (x) => this.listInternal(x), await this.listInternal(actualParams), actualParams);\r\n };\r\n this.editImage = async (params) => {\r\n const paramsInternal = {\r\n model: params.model,\r\n prompt: params.prompt,\r\n referenceImages: [],\r\n config: params.config\r\n };\r\n if (params.referenceImages) {\r\n if (params.referenceImages) {\r\n paramsInternal.referenceImages = params.referenceImages.map((img) => img.toReferenceImageAPI());\r\n }\r\n }\r\n return await this.editImageInternal(paramsInternal);\r\n };\r\n this.upscaleImage = async (params) => {\r\n let apiConfig = {\r\n numberOfImages: 1,\r\n mode: \"upscale\"\r\n };\r\n if (params.config) {\r\n apiConfig = Object.assign(Object.assign({}, apiConfig), params.config);\r\n }\r\n const apiParams = {\r\n model: params.model,\r\n image: params.image,\r\n upscaleFactor: params.upscaleFactor,\r\n config: apiConfig\r\n };\r\n return await this.upscaleImageInternal(apiParams);\r\n };\r\n this.generateVideos = async (params) => {\r\n var _a2, _b, _c, _d, _e, _f;\r\n if ((params.prompt || params.image || params.video) && params.source) {\r\n throw new Error(\"Source and prompt/image/video are mutually exclusive. Please only use source.\");\r\n }\r\n if (!this.apiClient.isVertexAI()) {\r\n if (((_a2 = params.video) === null || _a2 === void 0 ? void 0 : _a2.uri) && ((_b = params.video) === null || _b === void 0 ? void 0 : _b.videoBytes)) {\r\n params.video = {\r\n uri: params.video.uri,\r\n mimeType: params.video.mimeType\r\n };\r\n } else if (((_d = (_c = params.source) === null || _c === void 0 ? void 0 : _c.video) === null || _d === void 0 ? void 0 : _d.uri) && ((_f = (_e = params.source) === null || _e === void 0 ? void 0 : _e.video) === null || _f === void 0 ? void 0 : _f.videoBytes)) {\r\n params.source.video = {\r\n uri: params.source.video.uri,\r\n mimeType: params.source.video.mimeType\r\n };\r\n }\r\n }\r\n return await this.generateVideosInternal(params);\r\n };\r\n }\r\n /**\r\n * This logic is needed for GenerateContentConfig only.\r\n * Previously we made GenerateContentConfig.responseSchema field to accept\r\n * unknown. Since v1.9.0, we switch to use backend JSON schema support.\r\n * To maintain backward compatibility, we move the data that was treated as\r\n * JSON schema from the responseSchema field to the responseJsonSchema field.\r\n */\r\n maybeMoveToResponseJsonSchem(params) {\r\n if (params.config && params.config.responseSchema) {\r\n if (!params.config.responseJsonSchema) {\r\n if (Object.keys(params.config.responseSchema).includes(\"$schema\")) {\r\n params.config.responseJsonSchema = params.config.responseSchema;\r\n delete params.config.responseSchema;\r\n }\r\n }\r\n }\r\n return;\r\n }\r\n /**\r\n * Transforms the CallableTools in the parameters to be simply Tools, it\r\n * copies the params into a new object and replaces the tools, it does not\r\n * modify the original params. Also sets the MCP usage header if there are\r\n * MCP tools in the parameters.\r\n */\r\n async processParamsMaybeAddMcpUsage(params) {\r\n var _a2, _b, _c;\r\n const tools = (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.tools;\r\n if (!tools) {\r\n return params;\r\n }\r\n const transformedTools = await Promise.all(tools.map(async (tool) => {\r\n if (isCallableTool(tool)) {\r\n const callableTool = tool;\r\n return await callableTool.tool();\r\n }\r\n return tool;\r\n }));\r\n const newParams = {\r\n model: params.model,\r\n contents: params.contents,\r\n config: Object.assign(Object.assign({}, params.config), { tools: transformedTools })\r\n };\r\n newParams.config.tools = transformedTools;\r\n if (params.config && params.config.tools && hasMcpToolUsage(params.config.tools)) {\r\n const headers = (_c = (_b = params.config.httpOptions) === null || _b === void 0 ? void 0 : _b.headers) !== null && _c !== void 0 ? _c : {};\r\n let newHeaders = Object.assign({}, headers);\r\n if (Object.keys(newHeaders).length === 0) {\r\n newHeaders = this.apiClient.getDefaultHeaders();\r\n }\r\n setMcpUsageHeader(newHeaders);\r\n newParams.config.httpOptions = Object.assign(Object.assign({}, params.config.httpOptions), { headers: newHeaders });\r\n }\r\n return newParams;\r\n }\r\n async initAfcToolsMap(params) {\r\n var _a2, _b, _c;\r\n const afcTools = /* @__PURE__ */ new Map();\r\n for (const tool of (_b = (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.tools) !== null && _b !== void 0 ? _b : []) {\r\n if (isCallableTool(tool)) {\r\n const callableTool = tool;\r\n const toolDeclaration = await callableTool.tool();\r\n for (const declaration of (_c = toolDeclaration.functionDeclarations) !== null && _c !== void 0 ? _c : []) {\r\n if (!declaration.name) {\r\n throw new Error(\"Function declaration name is required.\");\r\n }\r\n if (afcTools.has(declaration.name)) {\r\n throw new Error(`Duplicate tool declaration name: ${declaration.name}`);\r\n }\r\n afcTools.set(declaration.name, callableTool);\r\n }\r\n }\r\n }\r\n return afcTools;\r\n }\r\n async processAfcStream(params) {\r\n var _a2, _b, _c;\r\n const maxRemoteCalls = (_c = (_b = (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS;\r\n let wereFunctionsCalled = false;\r\n let remoteCallCount = 0;\r\n const afcToolsMap = await this.initAfcToolsMap(params);\r\n return (function(models, afcTools, params2) {\r\n return __asyncGenerator(this, arguments, function* () {\r\n var _a3, e_1, _b2, _c2;\r\n var _d, _e;\r\n while (remoteCallCount < maxRemoteCalls) {\r\n if (wereFunctionsCalled) {\r\n remoteCallCount++;\r\n wereFunctionsCalled = false;\r\n }\r\n const transformedParams = yield __await(models.processParamsMaybeAddMcpUsage(params2));\r\n const response = yield __await(models.generateContentStreamInternal(transformedParams));\r\n const functionResponses = [];\r\n const responseContents = [];\r\n try {\r\n for (var _f = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()), _a3 = response_1_1.done, !_a3; _f = true) {\r\n _c2 = response_1_1.value;\r\n _f = false;\r\n const chunk = _c2;\r\n yield yield __await(chunk);\r\n if (chunk.candidates && ((_d = chunk.candidates[0]) === null || _d === void 0 ? void 0 : _d.content)) {\r\n responseContents.push(chunk.candidates[0].content);\r\n for (const part of (_e = chunk.candidates[0].content.parts) !== null && _e !== void 0 ? _e : []) {\r\n if (remoteCallCount < maxRemoteCalls && part.functionCall) {\r\n if (!part.functionCall.name) {\r\n throw new Error(\"Function call name was not returned by the model.\");\r\n }\r\n if (!afcTools.has(part.functionCall.name)) {\r\n throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`);\r\n } else {\r\n const responseParts = yield __await(afcTools.get(part.functionCall.name).callTool([part.functionCall]));\r\n functionResponses.push(...responseParts);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n } catch (e_1_1) {\r\n e_1 = { error: e_1_1 };\r\n } finally {\r\n try {\r\n if (!_f && !_a3 && (_b2 = response_1.return)) yield __await(_b2.call(response_1));\r\n } finally {\r\n if (e_1) throw e_1.error;\r\n }\r\n }\r\n if (functionResponses.length > 0) {\r\n wereFunctionsCalled = true;\r\n const typedResponseChunk = new GenerateContentResponse();\r\n typedResponseChunk.candidates = [\r\n {\r\n content: {\r\n role: \"user\",\r\n parts: functionResponses\r\n }\r\n }\r\n ];\r\n yield yield __await(typedResponseChunk);\r\n const newContents = [];\r\n newContents.push(...responseContents);\r\n newContents.push({\r\n role: \"user\",\r\n parts: functionResponses\r\n });\r\n const updatedContents = tContents(params2.contents).concat(newContents);\r\n params2.contents = updatedContents;\r\n } else {\r\n break;\r\n }\r\n }\r\n });\r\n })(this, afcToolsMap, params);\r\n }\r\n async generateContentInternal(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = generateContentParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"{model}:generateContent\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = generateContentResponseFromVertex(apiResponse);\r\n const typedResp = new GenerateContentResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n } else {\r\n const body = generateContentParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"{model}:generateContent\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = generateContentResponseFromMldev(apiResponse);\r\n const typedResp = new GenerateContentResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n async generateContentStreamInternal(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = generateContentParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"{model}:streamGenerateContent?alt=sse\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n const apiClient = this.apiClient;\r\n response = apiClient.requestStream({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n });\r\n return response.then(function(apiResponse) {\r\n return __asyncGenerator(this, arguments, function* () {\r\n var _a3, e_2, _b2, _c2;\r\n try {\r\n for (var _d2 = true, apiResponse_1 = __asyncValues(apiResponse), apiResponse_1_1; apiResponse_1_1 = yield __await(apiResponse_1.next()), _a3 = apiResponse_1_1.done, !_a3; _d2 = true) {\r\n _c2 = apiResponse_1_1.value;\r\n _d2 = false;\r\n const chunk = _c2;\r\n const resp = generateContentResponseFromVertex(yield __await(chunk.json()), params);\r\n resp[\"sdkHttpResponse\"] = {\r\n headers: chunk.headers\r\n };\r\n const typedResp = new GenerateContentResponse();\r\n Object.assign(typedResp, resp);\r\n yield yield __await(typedResp);\r\n }\r\n } catch (e_2_1) {\r\n e_2 = { error: e_2_1 };\r\n } finally {\r\n try {\r\n if (!_d2 && !_a3 && (_b2 = apiResponse_1.return)) yield __await(_b2.call(apiResponse_1));\r\n } finally {\r\n if (e_2) throw e_2.error;\r\n }\r\n }\r\n });\r\n });\r\n } else {\r\n const body = generateContentParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"{model}:streamGenerateContent?alt=sse\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n const apiClient = this.apiClient;\r\n response = apiClient.requestStream({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n });\r\n return response.then(function(apiResponse) {\r\n return __asyncGenerator(this, arguments, function* () {\r\n var _a3, e_3, _b2, _c2;\r\n try {\r\n for (var _d2 = true, apiResponse_2 = __asyncValues(apiResponse), apiResponse_2_1; apiResponse_2_1 = yield __await(apiResponse_2.next()), _a3 = apiResponse_2_1.done, !_a3; _d2 = true) {\r\n _c2 = apiResponse_2_1.value;\r\n _d2 = false;\r\n const chunk = _c2;\r\n const resp = generateContentResponseFromMldev(yield __await(chunk.json()), params);\r\n resp[\"sdkHttpResponse\"] = {\r\n headers: chunk.headers\r\n };\r\n const typedResp = new GenerateContentResponse();\r\n Object.assign(typedResp, resp);\r\n yield yield __await(typedResp);\r\n }\r\n } catch (e_3_1) {\r\n e_3 = { error: e_3_1 };\r\n } finally {\r\n try {\r\n if (!_d2 && !_a3 && (_b2 = apiResponse_2.return)) yield __await(_b2.call(apiResponse_2));\r\n } finally {\r\n if (e_3) throw e_3.error;\r\n }\r\n }\r\n });\r\n });\r\n }\r\n }\r\n /**\r\n * Calculates embeddings for the given contents. Only text is supported.\r\n *\r\n * @param params - The parameters for embedding contents.\r\n * @return The response from the API.\r\n *\r\n * @example\r\n * ```ts\r\n * const response = await ai.models.embedContent({\r\n * model: 'text-embedding-004',\r\n * contents: [\r\n * 'What is your name?',\r\n * 'What is your favorite color?',\r\n * ],\r\n * config: {\r\n * outputDimensionality: 64,\r\n * },\r\n * });\r\n * console.log(response);\r\n * ```\r\n */\r\n async embedContentInternal(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = embedContentParametersPrivateToVertex(this.apiClient, params, params);\r\n const endpointUrl = tIsVertexEmbedContentModel(params.model) ? \"{model}:embedContent\" : \"{model}:predict\";\r\n path2 = formatMap(endpointUrl, body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = embedContentResponseFromVertex(apiResponse, params);\r\n const typedResp = new EmbedContentResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n } else {\r\n const body = embedContentParametersPrivateToMldev(this.apiClient, params);\r\n path2 = formatMap(\"{model}:batchEmbedContents\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = embedContentResponseFromMldev(apiResponse);\r\n const typedResp = new EmbedContentResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n /**\r\n * Private method for generating images.\r\n */\r\n async generateImagesInternal(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = generateImagesParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"{model}:predict\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = generateImagesResponseFromVertex(apiResponse);\r\n const typedResp = new GenerateImagesResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n } else {\r\n const body = generateImagesParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"{model}:predict\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = generateImagesResponseFromMldev(apiResponse);\r\n const typedResp = new GenerateImagesResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n /**\r\n * Private method for editing an image.\r\n */\r\n async editImageInternal(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = editImageParametersInternalToVertex(this.apiClient, params);\r\n path2 = formatMap(\"{model}:predict\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = editImageResponseFromVertex(apiResponse);\r\n const typedResp = new EditImageResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n } else {\r\n throw new Error(\"This method is only supported by the Vertex AI.\");\r\n }\r\n }\r\n /**\r\n * Private method for upscaling an image.\r\n */\r\n async upscaleImageInternal(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = upscaleImageAPIParametersInternalToVertex(this.apiClient, params);\r\n path2 = formatMap(\"{model}:predict\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = upscaleImageResponseFromVertex(apiResponse);\r\n const typedResp = new UpscaleImageResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n } else {\r\n throw new Error(\"This method is only supported by the Vertex AI.\");\r\n }\r\n }\r\n /**\r\n * Recontextualizes an image.\r\n *\r\n * There is one type of recontextualization currently supported:\r\n * 1) Virtual Try-On: Generate images of persons modeling fashion products.\r\n *\r\n * @param params - The parameters for recontextualizing an image.\r\n * @return The response from the API.\r\n *\r\n * @example\r\n * ```ts\r\n * const response = await ai.models.recontextImage({\r\n * model: 'virtual-try-on-001',\r\n * source: {\r\n * personImage: personImage,\r\n * productImages: [productImage],\r\n * },\r\n * config: {\r\n * numberOfImages: 1,\r\n * },\r\n * });\r\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\r\n * ```\r\n */\r\n async recontextImage(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = recontextImageParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"{model}:predict\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = recontextImageResponseFromVertex(apiResponse);\r\n const typedResp = new RecontextImageResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n } else {\r\n throw new Error(\"This method is only supported by the Vertex AI.\");\r\n }\r\n }\r\n /**\r\n * Segments an image, creating a mask of a specified area.\r\n *\r\n * @param params - The parameters for segmenting an image.\r\n * @return The response from the API.\r\n *\r\n * @example\r\n * ```ts\r\n * const response = await ai.models.segmentImage({\r\n * model: 'image-segmentation-001',\r\n * source: {\r\n * image: image,\r\n * },\r\n * config: {\r\n * mode: 'foreground',\r\n * },\r\n * });\r\n * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes);\r\n * ```\r\n */\r\n async segmentImage(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = segmentImageParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"{model}:predict\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = segmentImageResponseFromVertex(apiResponse);\r\n const typedResp = new SegmentImageResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n } else {\r\n throw new Error(\"This method is only supported by the Vertex AI.\");\r\n }\r\n }\r\n /**\r\n * Fetches information about a model by name.\r\n *\r\n * @example\r\n * ```ts\r\n * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'});\r\n * ```\r\n */\r\n async get(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = getModelParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = modelFromVertex(apiResponse);\r\n return resp;\r\n });\r\n } else {\r\n const body = getModelParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = modelFromMldev(apiResponse);\r\n return resp;\r\n });\r\n }\r\n }\r\n async listInternal(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = listModelsParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"{models_url}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = listModelsResponseFromVertex(apiResponse);\r\n const typedResp = new ListModelsResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n } else {\r\n const body = listModelsParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"{models_url}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = listModelsResponseFromMldev(apiResponse);\r\n const typedResp = new ListModelsResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n /**\r\n * Updates a tuned model by its name.\r\n *\r\n * @param params - The parameters for updating the model.\r\n * @return The response from the API.\r\n *\r\n * @example\r\n * ```ts\r\n * const response = await ai.models.update({\r\n * model: 'tuned-model-name',\r\n * config: {\r\n * displayName: 'New display name',\r\n * description: 'New description',\r\n * },\r\n * });\r\n * ```\r\n */\r\n async update(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = updateModelParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"{model}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"PATCH\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = modelFromVertex(apiResponse);\r\n return resp;\r\n });\r\n } else {\r\n const body = updateModelParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"PATCH\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = modelFromMldev(apiResponse);\r\n return resp;\r\n });\r\n }\r\n }\r\n /**\r\n * Deletes a tuned model by its name.\r\n *\r\n * @param params - The parameters for deleting the model.\r\n * @return The response from the API.\r\n *\r\n * @example\r\n * ```ts\r\n * const response = await ai.models.delete({model: 'tuned-model-name'});\r\n * ```\r\n */\r\n async delete(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = deleteModelParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"DELETE\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = deleteModelResponseFromVertex(apiResponse);\r\n const typedResp = new DeleteModelResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n } else {\r\n const body = deleteModelParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"DELETE\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = deleteModelResponseFromMldev(apiResponse);\r\n const typedResp = new DeleteModelResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n /**\r\n * Counts the number of tokens in the given contents. Multimodal input is\r\n * supported for Gemini models.\r\n *\r\n * @param params - The parameters for counting tokens.\r\n * @return The response from the API.\r\n *\r\n * @example\r\n * ```ts\r\n * const response = await ai.models.countTokens({\r\n * model: 'gemini-2.0-flash',\r\n * contents: 'The quick brown fox jumps over the lazy dog.'\r\n * });\r\n * console.log(response);\r\n * ```\r\n */\r\n async countTokens(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = countTokensParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"{model}:countTokens\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = countTokensResponseFromVertex(apiResponse);\r\n const typedResp = new CountTokensResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n } else {\r\n const body = countTokensParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"{model}:countTokens\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = countTokensResponseFromMldev(apiResponse);\r\n const typedResp = new CountTokensResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n /**\r\n * Given a list of contents, returns a corresponding TokensInfo containing\r\n * the list of tokens and list of token ids.\r\n *\r\n * This method is not supported by the Gemini Developer API.\r\n *\r\n * @param params - The parameters for computing tokens.\r\n * @return The response from the API.\r\n *\r\n * @example\r\n * ```ts\r\n * const response = await ai.models.computeTokens({\r\n * model: 'gemini-2.0-flash',\r\n * contents: 'What is your name?'\r\n * });\r\n * console.log(response);\r\n * ```\r\n */\r\n async computeTokens(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = computeTokensParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"{model}:computeTokens\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = computeTokensResponseFromVertex(apiResponse);\r\n const typedResp = new ComputeTokensResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n } else {\r\n throw new Error(\"This method is only supported by the Vertex AI.\");\r\n }\r\n }\r\n /**\r\n * Private method for generating videos.\r\n */\r\n async generateVideosInternal(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = generateVideosParametersToVertex(this.apiClient, params);\r\n path2 = formatMap(\"{model}:predictLongRunning\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = generateVideosOperationFromVertex(apiResponse);\r\n const typedResp = new GenerateVideosOperation();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n } else {\r\n const body = generateVideosParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"{model}:predictLongRunning\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = generateVideosOperationFromMldev(apiResponse);\r\n const typedResp = new GenerateVideosOperation();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n };\r\n Operations = class extends BaseModule {\r\n constructor(apiClient) {\r\n super();\r\n this.apiClient = apiClient;\r\n }\r\n /**\r\n * Gets the status of a long-running operation.\r\n *\r\n * @param parameters The parameters for the get operation request.\r\n * @return The updated Operation object, with the latest status or result.\r\n */\r\n async getVideosOperation(parameters) {\r\n const operation = parameters.operation;\r\n const config = parameters.config;\r\n if (operation.name === void 0 || operation.name === \"\") {\r\n throw new Error(\"Operation name is required.\");\r\n }\r\n if (this.apiClient.isVertexAI()) {\r\n const resourceName2 = operation.name.split(\"/operations/\")[0];\r\n let httpOptions = void 0;\r\n if (config && \"httpOptions\" in config) {\r\n httpOptions = config.httpOptions;\r\n }\r\n const rawOperation = await this.fetchPredictVideosOperationInternal({\r\n operationName: operation.name,\r\n resourceName: resourceName2,\r\n config: { httpOptions }\r\n });\r\n return operation._fromAPIResponse({\r\n apiResponse: rawOperation,\r\n _isVertexAI: true\r\n });\r\n } else {\r\n const rawOperation = await this.getVideosOperationInternal({\r\n operationName: operation.name,\r\n config\r\n });\r\n return operation._fromAPIResponse({\r\n apiResponse: rawOperation,\r\n _isVertexAI: false\r\n });\r\n }\r\n }\r\n /**\r\n * Gets the status of a long-running operation.\r\n *\r\n * @param parameters The parameters for the get operation request.\r\n * @return The updated Operation object, with the latest status or result.\r\n */\r\n async get(parameters) {\r\n const operation = parameters.operation;\r\n const config = parameters.config;\r\n if (operation.name === void 0 || operation.name === \"\") {\r\n throw new Error(\"Operation name is required.\");\r\n }\r\n if (this.apiClient.isVertexAI()) {\r\n const resourceName2 = operation.name.split(\"/operations/\")[0];\r\n let httpOptions = void 0;\r\n if (config && \"httpOptions\" in config) {\r\n httpOptions = config.httpOptions;\r\n }\r\n const rawOperation = await this.fetchPredictVideosOperationInternal({\r\n operationName: operation.name,\r\n resourceName: resourceName2,\r\n config: { httpOptions }\r\n });\r\n return operation._fromAPIResponse({\r\n apiResponse: rawOperation,\r\n _isVertexAI: true\r\n });\r\n } else {\r\n const rawOperation = await this.getVideosOperationInternal({\r\n operationName: operation.name,\r\n config\r\n });\r\n return operation._fromAPIResponse({\r\n apiResponse: rawOperation,\r\n _isVertexAI: false\r\n });\r\n }\r\n }\r\n async getVideosOperationInternal(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = getOperationParametersToVertex(params);\r\n path2 = formatMap(\"{operationName}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response;\r\n } else {\r\n const body = getOperationParametersToMldev(params);\r\n path2 = formatMap(\"{operationName}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response;\r\n }\r\n }\r\n async fetchPredictVideosOperationInternal(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = fetchPredictOperationParametersToVertex(params);\r\n path2 = formatMap(\"{resourceName}:fetchPredictOperation\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response;\r\n } else {\r\n throw new Error(\"This method is only supported by the Vertex AI.\");\r\n }\r\n }\r\n };\r\n Tokens = class extends BaseModule {\r\n constructor(apiClient) {\r\n super();\r\n this.apiClient = apiClient;\r\n }\r\n /**\r\n * Creates an ephemeral auth token resource.\r\n *\r\n * @experimental\r\n *\r\n * @remarks\r\n * Ephemeral auth tokens is only supported in the Gemini Developer API.\r\n * It can be used for the session connection to the Live constrained API.\r\n * Support in v1alpha only.\r\n *\r\n * @param params - The parameters for the create request.\r\n * @return The created auth token.\r\n *\r\n * @example\r\n * ```ts\r\n * const ai = new GoogleGenAI({\r\n * apiKey: token.name,\r\n * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only.\r\n * });\r\n *\r\n * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig\r\n * // when using the token in Live API sessions. Each session connection can\r\n * // use a different configuration.\r\n * const config: CreateAuthTokenConfig = {\r\n * uses: 3,\r\n * expireTime: '2025-05-01T00:00:00Z',\r\n * }\r\n * const token = await ai.tokens.create(config);\r\n *\r\n * // Case 2: If LiveEphemeralParameters is set, lock all fields in\r\n * // LiveConnectConfig when using the token in Live API sessions. For\r\n * // example, changing `outputAudioTranscription` in the Live API\r\n * // connection will be ignored by the API.\r\n * const config: CreateAuthTokenConfig =\r\n * uses: 3,\r\n * expireTime: '2025-05-01T00:00:00Z',\r\n * LiveEphemeralParameters: {\r\n * model: 'gemini-2.0-flash-001',\r\n * config: {\r\n * 'responseModalities': ['AUDIO'],\r\n * 'systemInstruction': 'Always answer in English.',\r\n * }\r\n * }\r\n * }\r\n * const token = await ai.tokens.create(config);\r\n *\r\n * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is\r\n * // set, lock LiveConnectConfig with set and additional fields (e.g.\r\n * // responseModalities, systemInstruction, temperature in this example) when\r\n * // using the token in Live API sessions.\r\n * const config: CreateAuthTokenConfig =\r\n * uses: 3,\r\n * expireTime: '2025-05-01T00:00:00Z',\r\n * LiveEphemeralParameters: {\r\n * model: 'gemini-2.0-flash-001',\r\n * config: {\r\n * 'responseModalities': ['AUDIO'],\r\n * 'systemInstruction': 'Always answer in English.',\r\n * }\r\n * },\r\n * lockAdditionalFields: ['temperature'],\r\n * }\r\n * const token = await ai.tokens.create(config);\r\n *\r\n * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is\r\n * // empty array, lock LiveConnectConfig with set fields (e.g.\r\n * // responseModalities, systemInstruction in this example) when using the\r\n * // token in Live API sessions.\r\n * const config: CreateAuthTokenConfig =\r\n * uses: 3,\r\n * expireTime: '2025-05-01T00:00:00Z',\r\n * LiveEphemeralParameters: {\r\n * model: 'gemini-2.0-flash-001',\r\n * config: {\r\n * 'responseModalities': ['AUDIO'],\r\n * 'systemInstruction': 'Always answer in English.',\r\n * }\r\n * },\r\n * lockAdditionalFields: [],\r\n * }\r\n * const token = await ai.tokens.create(config);\r\n * ```\r\n */\r\n async create(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"The client.tokens.create method is only supported by the Gemini Developer API.\");\r\n } else {\r\n const body = createAuthTokenParametersToMldev(this.apiClient, params);\r\n path2 = formatMap(\"auth_tokens\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"config\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n const transformedBody = convertBidiSetupToTokenSetup(body, params.config);\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(transformedBody),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((resp) => {\r\n return resp;\r\n });\r\n }\r\n }\r\n };\r\n Documents = class extends BaseModule {\r\n constructor(apiClient) {\r\n super();\r\n this.apiClient = apiClient;\r\n this.list = async (params) => {\r\n return new Pager(PagedItem.PAGED_ITEM_DOCUMENTS, (x) => this.listInternal({ parent: params.parent, config: x.config }), await this.listInternal(params), params);\r\n };\r\n }\r\n /**\r\n * Gets a Document.\r\n *\r\n * @param params - The parameters for getting a document.\r\n * @return Document.\r\n */\r\n async get(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"This method is only supported by the Gemini Developer API.\");\r\n } else {\r\n const body = getDocumentParametersToMldev(params);\r\n path2 = formatMap(\"{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((resp) => {\r\n return resp;\r\n });\r\n }\r\n }\r\n /**\r\n * Deletes a Document.\r\n *\r\n * @param params - The parameters for deleting a document.\r\n */\r\n async delete(params) {\r\n var _a2, _b;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"This method is only supported by the Gemini Developer API.\");\r\n } else {\r\n const body = deleteDocumentParametersToMldev(params);\r\n path2 = formatMap(\"{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n await this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"DELETE\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n });\r\n }\r\n }\r\n async listInternal(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"This method is only supported by the Gemini Developer API.\");\r\n } else {\r\n const body = listDocumentsParametersToMldev(params);\r\n path2 = formatMap(\"{parent}/documents\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = listDocumentsResponseFromMldev(apiResponse);\r\n const typedResp = new ListDocumentsResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n };\r\n FileSearchStores = class extends BaseModule {\r\n constructor(apiClient, documents = new Documents(apiClient)) {\r\n super();\r\n this.apiClient = apiClient;\r\n this.documents = documents;\r\n this.list = async (params = {}) => {\r\n return new Pager(PagedItem.PAGED_ITEM_FILE_SEARCH_STORES, (x) => this.listInternal(x), await this.listInternal(params), params);\r\n };\r\n }\r\n /**\r\n * Uploads a file asynchronously to a given File Search Store.\r\n * This method is not available in Vertex AI.\r\n * Supported upload sources:\r\n * - Node.js: File path (string) or Blob object.\r\n * - Browser: Blob object (e.g., File).\r\n *\r\n * @remarks\r\n * The `mimeType` can be specified in the `config` parameter. If omitted:\r\n * - For file path (string) inputs, the `mimeType` will be inferred from the\r\n * file extension.\r\n * - For Blob object inputs, the `mimeType` will be set to the Blob's `type`\r\n * property.\r\n *\r\n * This section can contain multiple paragraphs and code examples.\r\n *\r\n * @param params - Optional parameters specified in the\r\n * `types.UploadToFileSearchStoreParameters` interface.\r\n * @see {@link types.UploadToFileSearchStoreParameters#config} for the optional\r\n * config in the parameters.\r\n * @return A promise that resolves to a long running operation.\r\n * @throws An error if called on a Vertex AI client.\r\n * @throws An error if the `mimeType` is not provided and can not be inferred,\r\n * the `mimeType` can be provided in the `params.config` parameter.\r\n * @throws An error occurs if a suitable upload location cannot be established.\r\n *\r\n * @example\r\n * The following code uploads a file to a given file search store.\r\n *\r\n * ```ts\r\n * const operation = await ai.fileSearchStores.upload({fileSearchStoreName: 'fileSearchStores/foo-bar', file: 'file.txt', config: {\r\n * mimeType: 'text/plain',\r\n * }});\r\n * console.log(operation.name);\r\n * ```\r\n */\r\n async uploadToFileSearchStore(params) {\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"Vertex AI does not support uploading files to a file search store.\");\r\n }\r\n return this.apiClient.uploadFileToFileSearchStore(params.fileSearchStoreName, params.file, params.config);\r\n }\r\n /**\r\n * Creates a File Search Store.\r\n *\r\n * @param params - The parameters for creating a File Search Store.\r\n * @return FileSearchStore.\r\n */\r\n async create(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"This method is only supported by the Gemini Developer API.\");\r\n } else {\r\n const body = createFileSearchStoreParametersToMldev(params);\r\n path2 = formatMap(\"fileSearchStores\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((resp) => {\r\n return resp;\r\n });\r\n }\r\n }\r\n /**\r\n * Gets a File Search Store.\r\n *\r\n * @param params - The parameters for getting a File Search Store.\r\n * @return FileSearchStore.\r\n */\r\n async get(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"This method is only supported by the Gemini Developer API.\");\r\n } else {\r\n const body = getFileSearchStoreParametersToMldev(params);\r\n path2 = formatMap(\"{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((resp) => {\r\n return resp;\r\n });\r\n }\r\n }\r\n /**\r\n * Deletes a File Search Store.\r\n *\r\n * @param params - The parameters for deleting a File Search Store.\r\n */\r\n async delete(params) {\r\n var _a2, _b;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"This method is only supported by the Gemini Developer API.\");\r\n } else {\r\n const body = deleteFileSearchStoreParametersToMldev(params);\r\n path2 = formatMap(\"{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n await this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"DELETE\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n });\r\n }\r\n }\r\n async listInternal(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"This method is only supported by the Gemini Developer API.\");\r\n } else {\r\n const body = listFileSearchStoresParametersToMldev(params);\r\n path2 = formatMap(\"fileSearchStores\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = listFileSearchStoresResponseFromMldev(apiResponse);\r\n const typedResp = new ListFileSearchStoresResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n async uploadToFileSearchStoreInternal(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"This method is only supported by the Gemini Developer API.\");\r\n } else {\r\n const body = uploadToFileSearchStoreParametersToMldev(params);\r\n path2 = formatMap(\"upload/v1beta/{file_search_store_name}:uploadToFileSearchStore\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = uploadToFileSearchStoreResumableResponseFromMldev(apiResponse);\r\n const typedResp = new UploadToFileSearchStoreResumableResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n /**\r\n * Imports a File from File Service to a FileSearchStore.\r\n *\r\n * This is a long-running operation, see aip.dev/151\r\n *\r\n * @param params - The parameters for importing a file to a file search store.\r\n * @return ImportFileOperation.\r\n */\r\n async importFile(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"This method is only supported by the Gemini Developer API.\");\r\n } else {\r\n const body = importFileParametersToMldev(params);\r\n path2 = formatMap(\"{file_search_store_name}:importFile\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json();\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = importFileOperationFromMldev(apiResponse);\r\n const typedResp = new ImportFileOperation();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n };\r\n uuid4Internal = function() {\r\n const { crypto } = globalThis;\r\n if (crypto === null || crypto === void 0 ? void 0 : crypto.randomUUID) {\r\n uuid4Internal = crypto.randomUUID.bind(crypto);\r\n return crypto.randomUUID();\r\n }\r\n const u8 = new Uint8Array(1);\r\n const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;\r\n return \"10000000-1000-4000-8000-100000000000\".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16));\r\n };\r\n uuid4 = () => uuid4Internal();\r\n castToError = (err) => {\r\n if (err instanceof Error)\r\n return err;\r\n if (typeof err === \"object\" && err !== null) {\r\n try {\r\n if (Object.prototype.toString.call(err) === \"[object Error]\") {\r\n const error = new Error(err.message, err.cause ? { cause: err.cause } : {});\r\n if (err.stack)\r\n error.stack = err.stack;\r\n if (err.cause && !error.cause)\r\n error.cause = err.cause;\r\n if (err.name)\r\n error.name = err.name;\r\n return error;\r\n }\r\n } catch (_a2) {\r\n }\r\n try {\r\n return new Error(JSON.stringify(err));\r\n } catch (_b) {\r\n }\r\n }\r\n return new Error(err);\r\n };\r\n GeminiNextGenAPIClientError = class extends Error {\r\n };\r\n APIError = class _APIError extends GeminiNextGenAPIClientError {\r\n constructor(status, error, message, headers) {\r\n super(`${_APIError.makeMessage(status, error, message)}`);\r\n this.status = status;\r\n this.headers = headers;\r\n this.error = error;\r\n }\r\n static makeMessage(status, error, message) {\r\n const msg = (error === null || error === void 0 ? void 0 : error.message) ? typeof error.message === \"string\" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;\r\n if (status && msg) {\r\n return `${status} ${msg}`;\r\n }\r\n if (status) {\r\n return `${status} status code (no body)`;\r\n }\r\n if (msg) {\r\n return msg;\r\n }\r\n return \"(no status code or body)\";\r\n }\r\n static generate(status, errorResponse, message, headers) {\r\n if (!status || !headers) {\r\n return new APIConnectionError({ message, cause: castToError(errorResponse) });\r\n }\r\n const error = errorResponse;\r\n if (status === 400) {\r\n return new BadRequestError(status, error, message, headers);\r\n }\r\n if (status === 401) {\r\n return new AuthenticationError(status, error, message, headers);\r\n }\r\n if (status === 403) {\r\n return new PermissionDeniedError(status, error, message, headers);\r\n }\r\n if (status === 404) {\r\n return new NotFoundError(status, error, message, headers);\r\n }\r\n if (status === 409) {\r\n return new ConflictError(status, error, message, headers);\r\n }\r\n if (status === 422) {\r\n return new UnprocessableEntityError(status, error, message, headers);\r\n }\r\n if (status === 429) {\r\n return new RateLimitError(status, error, message, headers);\r\n }\r\n if (status >= 500) {\r\n return new InternalServerError(status, error, message, headers);\r\n }\r\n return new _APIError(status, error, message, headers);\r\n }\r\n };\r\n APIUserAbortError = class extends APIError {\r\n constructor({ message } = {}) {\r\n super(void 0, void 0, message || \"Request was aborted.\", void 0);\r\n }\r\n };\r\n APIConnectionError = class extends APIError {\r\n constructor({ message, cause }) {\r\n super(void 0, void 0, message || \"Connection error.\", void 0);\r\n if (cause)\r\n this.cause = cause;\r\n }\r\n };\r\n APIConnectionTimeoutError = class extends APIConnectionError {\r\n constructor({ message } = {}) {\r\n super({ message: message !== null && message !== void 0 ? message : \"Request timed out.\" });\r\n }\r\n };\r\n BadRequestError = class extends APIError {\r\n };\r\n AuthenticationError = class extends APIError {\r\n };\r\n PermissionDeniedError = class extends APIError {\r\n };\r\n NotFoundError = class extends APIError {\r\n };\r\n ConflictError = class extends APIError {\r\n };\r\n UnprocessableEntityError = class extends APIError {\r\n };\r\n RateLimitError = class extends APIError {\r\n };\r\n InternalServerError = class extends APIError {\r\n };\r\n startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;\r\n isAbsoluteURL = (url) => {\r\n return startsWithSchemeRegexp.test(url);\r\n };\r\n isArrayInternal = (val) => (isArrayInternal = Array.isArray, isArrayInternal(val));\r\n isArray = isArrayInternal;\r\n isReadonlyArrayInternal = isArray;\r\n isReadonlyArray = isReadonlyArrayInternal;\r\n validatePositiveInteger = (name, n) => {\r\n if (typeof n !== \"number\" || !Number.isInteger(n)) {\r\n throw new GeminiNextGenAPIClientError(`${name} must be an integer`);\r\n }\r\n if (n < 0) {\r\n throw new GeminiNextGenAPIClientError(`${name} must be a positive integer`);\r\n }\r\n return n;\r\n };\r\n safeJSON = (text) => {\r\n try {\r\n return JSON.parse(text);\r\n } catch (err) {\r\n return void 0;\r\n }\r\n };\r\n sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\r\n FallbackEncoder = ({ headers, body }) => {\r\n return {\r\n bodyHeaders: {\r\n \"content-type\": \"application/json\"\r\n },\r\n body: JSON.stringify(body)\r\n };\r\n };\r\n VERSION = \"0.0.1\";\r\n checkFileSupport = () => {\r\n var _a2;\r\n if (typeof File === \"undefined\") {\r\n const { process: process2 } = globalThis;\r\n const isOldNode = typeof ((_a2 = process2 === null || process2 === void 0 ? void 0 : process2.versions) === null || _a2 === void 0 ? void 0 : _a2.node) === \"string\" && parseInt(process2.versions.node.split(\".\")) < 20;\r\n throw new Error(\"`File` is not defined as a global, which is required for file uploads.\" + (isOldNode ? \" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.\" : \"\"));\r\n }\r\n };\r\n isAsyncIterable = (value) => value != null && typeof value === \"object\" && typeof value[Symbol.asyncIterator] === \"function\";\r\n isBlobLike = (value) => value != null && typeof value === \"object\" && typeof value.size === \"number\" && typeof value.type === \"string\" && typeof value.text === \"function\" && typeof value.slice === \"function\" && typeof value.arrayBuffer === \"function\";\r\n isFileLike = (value) => value != null && typeof value === \"object\" && typeof value.name === \"string\" && typeof value.lastModified === \"number\" && isBlobLike(value);\r\n isResponseLike = (value) => value != null && typeof value === \"object\" && typeof value.url === \"string\" && typeof value.blob === \"function\";\r\n APIResource = class {\r\n constructor(client) {\r\n this._client = client;\r\n }\r\n };\r\n APIResource._key = [];\r\n EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));\r\n createPathTagFunction = (pathEncoder = encodeURIPath) => (function path2(statics, ...params) {\r\n if (statics.length === 1)\r\n return statics[0];\r\n let postPath = false;\r\n const invalidSegments = [];\r\n const path3 = statics.reduce((previousValue, currentValue, index) => {\r\n var _a2, _b, _c;\r\n if (/[?#]/.test(currentValue)) {\r\n postPath = true;\r\n }\r\n const value = params[index];\r\n let encoded = (postPath ? encodeURIComponent : pathEncoder)(\"\" + value);\r\n if (index !== params.length && (value == null || typeof value === \"object\" && // handle values from other realms\r\n value.toString === ((_c = Object.getPrototypeOf((_b = Object.getPrototypeOf((_a2 = value.hasOwnProperty) !== null && _a2 !== void 0 ? _a2 : EMPTY)) !== null && _b !== void 0 ? _b : EMPTY)) === null || _c === void 0 ? void 0 : _c.toString))) {\r\n encoded = value + \"\";\r\n invalidSegments.push({\r\n start: previousValue.length + currentValue.length,\r\n length: encoded.length,\r\n error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter`\r\n });\r\n }\r\n return previousValue + currentValue + (index === params.length ? \"\" : encoded);\r\n }, \"\");\r\n const pathOnly = path3.split(/[?#]/, 1)[0];\r\n const invalidSegmentPattern = /(^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)/gi;\r\n let match;\r\n while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {\r\n const hasLeadingSlash = match[0].startsWith(\"/\");\r\n const offset = hasLeadingSlash ? 1 : 0;\r\n const cleanMatch = hasLeadingSlash ? match[0].slice(1) : match[0];\r\n invalidSegments.push({\r\n start: match.index + offset,\r\n length: cleanMatch.length,\r\n error: `Value \"${cleanMatch}\" can't be safely passed as a path parameter`\r\n });\r\n }\r\n invalidSegments.sort((a, b) => a.start - b.start);\r\n if (invalidSegments.length > 0) {\r\n let lastEnd = 0;\r\n const underline = invalidSegments.reduce((acc, segment) => {\r\n const spaces = \" \".repeat(segment.start - lastEnd);\r\n const arrows = \"^\".repeat(segment.length);\r\n lastEnd = segment.start + segment.length;\r\n return acc + spaces + arrows;\r\n }, \"\");\r\n throw new GeminiNextGenAPIClientError(`Path parameters result in path with invalid segments:\r\n${invalidSegments.map((e) => e.error).join(\"\\n\")}\r\n${path3}\r\n${underline}`);\r\n }\r\n return path3;\r\n });\r\n path = /* @__PURE__ */ createPathTagFunction(encodeURIPath);\r\n BaseInteractions = class extends APIResource {\r\n create(params, options) {\r\n var _a2;\r\n const { api_version = this._client.apiVersion } = params, body = __rest(params, [\"api_version\"]);\r\n if (\"model\" in body && \"agent_config\" in body) {\r\n throw new GeminiNextGenAPIClientError(`Invalid request: specified \\`model\\` and \\`agent_config\\`. If specifying \\`model\\`, use \\`generation_config\\`.`);\r\n }\r\n if (\"agent\" in body && \"generation_config\" in body) {\r\n throw new GeminiNextGenAPIClientError(`Invalid request: specified \\`agent\\` and \\`generation_config\\`. If specifying \\`agent\\`, use \\`agent_config\\`.`);\r\n }\r\n return this._client.post(path`/${api_version}/interactions`, Object.assign(Object.assign({ body }, options), { stream: (_a2 = params.stream) !== null && _a2 !== void 0 ? _a2 : false }));\r\n }\r\n /**\r\n * Deletes the interaction by id.\r\n *\r\n * @example\r\n * ```ts\r\n * const interaction = await client.interactions.delete('id', {\r\n * api_version: 'api_version',\r\n * });\r\n * ```\r\n */\r\n delete(id, params = {}, options) {\r\n const { api_version = this._client.apiVersion } = params !== null && params !== void 0 ? params : {};\r\n return this._client.delete(path`/${api_version}/interactions/${id}`, options);\r\n }\r\n /**\r\n * Cancels an interaction by id. This only applies to background interactions that\r\n * are still running.\r\n *\r\n * @example\r\n * ```ts\r\n * const interaction = await client.interactions.cancel('id', {\r\n * api_version: 'api_version',\r\n * });\r\n * ```\r\n */\r\n cancel(id, params = {}, options) {\r\n const { api_version = this._client.apiVersion } = params !== null && params !== void 0 ? params : {};\r\n return this._client.post(path`/${api_version}/interactions/${id}/cancel`, options);\r\n }\r\n get(id, params = {}, options) {\r\n var _a2;\r\n const _b = params !== null && params !== void 0 ? params : {}, { api_version = this._client.apiVersion } = _b, query = __rest(_b, [\"api_version\"]);\r\n return this._client.get(path`/${api_version}/interactions/${id}`, Object.assign(Object.assign({ query }, options), { stream: (_a2 = params === null || params === void 0 ? void 0 : params.stream) !== null && _a2 !== void 0 ? _a2 : false }));\r\n }\r\n };\r\n BaseInteractions._key = Object.freeze([\"interactions\"]);\r\n Interactions = class extends BaseInteractions {\r\n };\r\n LineDecoder = class {\r\n constructor() {\r\n this.buffer = new Uint8Array();\r\n this.carriageReturnIndex = null;\r\n this.searchIndex = 0;\r\n }\r\n decode(chunk) {\r\n var _a2;\r\n if (chunk == null) {\r\n return [];\r\n }\r\n const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === \"string\" ? encodeUTF8(chunk) : chunk;\r\n this.buffer = concatBytes([this.buffer, binaryChunk]);\r\n const lines = [];\r\n let patternIndex;\r\n while ((patternIndex = findNewlineIndex(this.buffer, (_a2 = this.carriageReturnIndex) !== null && _a2 !== void 0 ? _a2 : this.searchIndex)) != null) {\r\n if (patternIndex.carriage && this.carriageReturnIndex == null) {\r\n this.carriageReturnIndex = patternIndex.index;\r\n continue;\r\n }\r\n if (this.carriageReturnIndex != null && (patternIndex.index !== this.carriageReturnIndex + 1 || patternIndex.carriage)) {\r\n lines.push(decodeUTF8(this.buffer.subarray(0, this.carriageReturnIndex - 1)));\r\n this.buffer = this.buffer.subarray(this.carriageReturnIndex);\r\n this.carriageReturnIndex = null;\r\n this.searchIndex = 0;\r\n continue;\r\n }\r\n const endIndex = this.carriageReturnIndex !== null ? patternIndex.preceding - 1 : patternIndex.preceding;\r\n const line = decodeUTF8(this.buffer.subarray(0, endIndex));\r\n lines.push(line);\r\n this.buffer = this.buffer.subarray(patternIndex.index);\r\n this.carriageReturnIndex = null;\r\n this.searchIndex = 0;\r\n }\r\n this.searchIndex = Math.max(0, this.buffer.length - 1);\r\n return lines;\r\n }\r\n flush() {\r\n if (!this.buffer.length) {\r\n return [];\r\n }\r\n return this.decode(\"\\n\");\r\n }\r\n };\r\n LineDecoder.NEWLINE_CHARS = /* @__PURE__ */ new Set([\"\\n\", \"\\r\"]);\r\n LineDecoder.NEWLINE_REGEXP = /\\r\\n|[\\n\\r]/g;\r\n levelNumbers = {\r\n off: 0,\r\n error: 200,\r\n warn: 300,\r\n info: 400,\r\n debug: 500\r\n };\r\n parseLogLevel = (maybeLevel, sourceName, client) => {\r\n if (!maybeLevel) {\r\n return void 0;\r\n }\r\n if (hasOwn(levelNumbers, maybeLevel)) {\r\n return maybeLevel;\r\n }\r\n loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);\r\n return void 0;\r\n };\r\n noopLogger = {\r\n error: noop,\r\n warn: noop,\r\n info: noop,\r\n debug: noop\r\n };\r\n cachedLoggers = /* @__PURE__ */ new WeakMap();\r\n formatRequestDetails = (details) => {\r\n if (details.options) {\r\n details.options = Object.assign({}, details.options);\r\n delete details.options[\"headers\"];\r\n }\r\n if (details.headers) {\r\n details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [\r\n name,\r\n name.toLowerCase() === \"x-goog-api-key\" || name.toLowerCase() === \"authorization\" || name.toLowerCase() === \"cookie\" || name.toLowerCase() === \"set-cookie\" ? \"***\" : value\r\n ]));\r\n }\r\n if (\"retryOfRequestLogID\" in details) {\r\n if (details.retryOfRequestLogID) {\r\n details.retryOf = details.retryOfRequestLogID;\r\n }\r\n delete details.retryOfRequestLogID;\r\n }\r\n return details;\r\n };\r\n Stream = class _Stream {\r\n constructor(iterator, controller, client) {\r\n this.iterator = iterator;\r\n this.controller = controller;\r\n this.client = client;\r\n }\r\n static fromSSEResponse(response, controller, client) {\r\n let consumed = false;\r\n const logger = client ? loggerFor(client) : console;\r\n function iterator() {\r\n return __asyncGenerator(this, arguments, function* iterator_1() {\r\n var _a2, e_1, _b, _c;\r\n if (consumed) {\r\n throw new GeminiNextGenAPIClientError(\"Cannot iterate over a consumed stream, use `.tee()` to split the stream.\");\r\n }\r\n consumed = true;\r\n let done = false;\r\n try {\r\n try {\r\n for (var _d = true, _e = __asyncValues(_iterSSEMessages(response, controller)), _f; _f = yield __await(_e.next()), _a2 = _f.done, !_a2; _d = true) {\r\n _c = _f.value;\r\n _d = false;\r\n const sse = _c;\r\n if (done)\r\n continue;\r\n if (sse.data.startsWith(\"[DONE]\")) {\r\n done = true;\r\n continue;\r\n } else {\r\n try {\r\n yield yield __await(JSON.parse(sse.data));\r\n } catch (e) {\r\n logger.error(`Could not parse message into JSON:`, sse.data);\r\n logger.error(`From chunk:`, sse.raw);\r\n throw e;\r\n }\r\n }\r\n }\r\n } catch (e_1_1) {\r\n e_1 = { error: e_1_1 };\r\n } finally {\r\n try {\r\n if (!_d && !_a2 && (_b = _e.return)) yield __await(_b.call(_e));\r\n } finally {\r\n if (e_1) throw e_1.error;\r\n }\r\n }\r\n done = true;\r\n } catch (e) {\r\n if (isAbortError(e))\r\n return yield __await(void 0);\r\n throw e;\r\n } finally {\r\n if (!done)\r\n controller.abort();\r\n }\r\n });\r\n }\r\n return new _Stream(iterator, controller, client);\r\n }\r\n /**\r\n * Generates a Stream from a newline-separated ReadableStream\r\n * where each item is a JSON value.\r\n */\r\n static fromReadableStream(readableStream, controller, client) {\r\n let consumed = false;\r\n function iterLines() {\r\n return __asyncGenerator(this, arguments, function* iterLines_1() {\r\n var _a2, e_2, _b, _c;\r\n const lineDecoder = new LineDecoder();\r\n const iter = ReadableStreamToAsyncIterable(readableStream);\r\n try {\r\n for (var _d = true, iter_1 = __asyncValues(iter), iter_1_1; iter_1_1 = yield __await(iter_1.next()), _a2 = iter_1_1.done, !_a2; _d = true) {\r\n _c = iter_1_1.value;\r\n _d = false;\r\n const chunk = _c;\r\n for (const line of lineDecoder.decode(chunk)) {\r\n yield yield __await(line);\r\n }\r\n }\r\n } catch (e_2_1) {\r\n e_2 = { error: e_2_1 };\r\n } finally {\r\n try {\r\n if (!_d && !_a2 && (_b = iter_1.return)) yield __await(_b.call(iter_1));\r\n } finally {\r\n if (e_2) throw e_2.error;\r\n }\r\n }\r\n for (const line of lineDecoder.flush()) {\r\n yield yield __await(line);\r\n }\r\n });\r\n }\r\n function iterator() {\r\n return __asyncGenerator(this, arguments, function* iterator_2() {\r\n var _a2, e_3, _b, _c;\r\n if (consumed) {\r\n throw new GeminiNextGenAPIClientError(\"Cannot iterate over a consumed stream, use `.tee()` to split the stream.\");\r\n }\r\n consumed = true;\r\n let done = false;\r\n try {\r\n try {\r\n for (var _d = true, _e = __asyncValues(iterLines()), _f; _f = yield __await(_e.next()), _a2 = _f.done, !_a2; _d = true) {\r\n _c = _f.value;\r\n _d = false;\r\n const line = _c;\r\n if (done)\r\n continue;\r\n if (line)\r\n yield yield __await(JSON.parse(line));\r\n }\r\n } catch (e_3_1) {\r\n e_3 = { error: e_3_1 };\r\n } finally {\r\n try {\r\n if (!_d && !_a2 && (_b = _e.return)) yield __await(_b.call(_e));\r\n } finally {\r\n if (e_3) throw e_3.error;\r\n }\r\n }\r\n done = true;\r\n } catch (e) {\r\n if (isAbortError(e))\r\n return yield __await(void 0);\r\n throw e;\r\n } finally {\r\n if (!done)\r\n controller.abort();\r\n }\r\n });\r\n }\r\n return new _Stream(iterator, controller, client);\r\n }\r\n [Symbol.asyncIterator]() {\r\n return this.iterator();\r\n }\r\n /**\r\n * Splits the stream into two streams which can be\r\n * independently read from at different speeds.\r\n */\r\n tee() {\r\n const left = [];\r\n const right = [];\r\n const iterator = this.iterator();\r\n const teeIterator = (queue) => {\r\n return {\r\n next: () => {\r\n if (queue.length === 0) {\r\n const result = iterator.next();\r\n left.push(result);\r\n right.push(result);\r\n }\r\n return queue.shift();\r\n }\r\n };\r\n };\r\n return [\r\n new _Stream(() => teeIterator(left), this.controller, this.client),\r\n new _Stream(() => teeIterator(right), this.controller, this.client)\r\n ];\r\n }\r\n /**\r\n * Converts this stream to a newline-separated ReadableStream of\r\n * JSON stringified values in the stream\r\n * which can be turned back into a Stream with `Stream.fromReadableStream()`.\r\n */\r\n toReadableStream() {\r\n const self = this;\r\n let iter;\r\n return makeReadableStream({\r\n async start() {\r\n iter = self[Symbol.asyncIterator]();\r\n },\r\n async pull(ctrl) {\r\n try {\r\n const { value, done } = await iter.next();\r\n if (done)\r\n return ctrl.close();\r\n const bytes = encodeUTF8(JSON.stringify(value) + \"\\n\");\r\n ctrl.enqueue(bytes);\r\n } catch (err) {\r\n ctrl.error(err);\r\n }\r\n },\r\n async cancel() {\r\n var _a2;\r\n await ((_a2 = iter.return) === null || _a2 === void 0 ? void 0 : _a2.call(iter));\r\n }\r\n });\r\n }\r\n };\r\n SSEDecoder = class {\r\n constructor() {\r\n this.event = null;\r\n this.data = [];\r\n this.chunks = [];\r\n }\r\n decode(line) {\r\n if (line.endsWith(\"\\r\")) {\r\n line = line.substring(0, line.length - 1);\r\n }\r\n if (!line) {\r\n if (!this.event && !this.data.length)\r\n return null;\r\n const sse = {\r\n event: this.event,\r\n data: this.data.join(\"\\n\"),\r\n raw: this.chunks\r\n };\r\n this.event = null;\r\n this.data = [];\r\n this.chunks = [];\r\n return sse;\r\n }\r\n this.chunks.push(line);\r\n if (line.startsWith(\":\")) {\r\n return null;\r\n }\r\n let [fieldname, _, value] = partition(line, \":\");\r\n if (value.startsWith(\" \")) {\r\n value = value.substring(1);\r\n }\r\n if (fieldname === \"event\") {\r\n this.event = value;\r\n } else if (fieldname === \"data\") {\r\n this.data.push(value);\r\n }\r\n return null;\r\n }\r\n };\r\n APIPromise = class _APIPromise extends Promise {\r\n constructor(client, responsePromise, parseResponse = defaultParseResponse) {\r\n super((resolve) => {\r\n resolve(null);\r\n });\r\n this.responsePromise = responsePromise;\r\n this.parseResponse = parseResponse;\r\n this.client = client;\r\n }\r\n _thenUnwrap(transform) {\r\n return new _APIPromise(this.client, this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props));\r\n }\r\n /**\r\n * Gets the raw `Response` instance instead of parsing the response\r\n * data.\r\n *\r\n * If you want to parse the response body but still get the `Response`\r\n * instance, you can use {@link withResponse()}.\r\n *\r\n * 👋 Getting the wrong TypeScript type for `Response`?\r\n * Try setting `\"moduleResolution\": \"NodeNext\"` or add `\"lib\": [\"DOM\"]`\r\n * to your `tsconfig.json`.\r\n */\r\n asResponse() {\r\n return this.responsePromise.then((p) => p.response);\r\n }\r\n /**\r\n * Gets the parsed response data and the raw `Response` instance.\r\n *\r\n * If you just want to get the raw `Response` instance without parsing it,\r\n * you can use {@link asResponse()}.\r\n *\r\n * 👋 Getting the wrong TypeScript type for `Response`?\r\n * Try setting `\"moduleResolution\": \"NodeNext\"` or add `\"lib\": [\"DOM\"]`\r\n * to your `tsconfig.json`.\r\n */\r\n async withResponse() {\r\n const [data, response] = await Promise.all([this.parse(), this.asResponse()]);\r\n return { data, response };\r\n }\r\n parse() {\r\n if (!this.parsedPromise) {\r\n this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(this.client, data));\r\n }\r\n return this.parsedPromise;\r\n }\r\n then(onfulfilled, onrejected) {\r\n return this.parse().then(onfulfilled, onrejected);\r\n }\r\n catch(onrejected) {\r\n return this.parse().catch(onrejected);\r\n }\r\n finally(onfinally) {\r\n return this.parse().finally(onfinally);\r\n }\r\n };\r\n brand_privateNullableHeaders = /* @__PURE__ */ Symbol(\"brand.privateNullableHeaders\");\r\n buildHeaders = (newHeaders) => {\r\n const targetHeaders = new Headers();\r\n const nullHeaders = /* @__PURE__ */ new Set();\r\n for (const headers of newHeaders) {\r\n const seenHeaders = /* @__PURE__ */ new Set();\r\n for (const [name, value] of iterateHeaders(headers)) {\r\n const lowerName = name.toLowerCase();\r\n if (!seenHeaders.has(lowerName)) {\r\n targetHeaders.delete(name);\r\n seenHeaders.add(lowerName);\r\n }\r\n if (value === null) {\r\n targetHeaders.delete(name);\r\n nullHeaders.add(lowerName);\r\n } else {\r\n targetHeaders.append(name, value);\r\n nullHeaders.delete(lowerName);\r\n }\r\n }\r\n }\r\n return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };\r\n };\r\n readEnv = (env) => {\r\n var _a2, _b, _c, _d, _e, _f;\r\n if (typeof globalThis.process !== \"undefined\") {\r\n return (_c = (_b = (_a2 = globalThis.process.env) === null || _a2 === void 0 ? void 0 : _a2[env]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : void 0;\r\n }\r\n if (typeof globalThis.Deno !== \"undefined\") {\r\n return (_f = (_e = (_d = globalThis.Deno.env) === null || _d === void 0 ? void 0 : _d.get) === null || _e === void 0 ? void 0 : _e.call(_d, env)) === null || _f === void 0 ? void 0 : _f.trim();\r\n }\r\n return void 0;\r\n };\r\n BaseGeminiNextGenAPIClient = class _BaseGeminiNextGenAPIClient {\r\n /**\r\n * API Client for interfacing with the Gemini Next Gen API API.\r\n *\r\n * @param {string | null | undefined} [opts.apiKey=process.env['GEMINI_API_KEY'] ?? null]\r\n * @param {string | undefined} [opts.apiVersion=v1beta]\r\n * @param {string} [opts.baseURL=process.env['GEMINI_NEXT_GEN_API_BASE_URL'] ?? https://generativelanguage.googleapis.com] - Override the default base URL for the API.\r\n * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.\r\n * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.\r\n * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.\r\n * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.\r\n * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.\r\n * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.\r\n */\r\n constructor(_b) {\r\n var _c, _d, _e, _f, _g, _h, _j;\r\n var { baseURL = readEnv(\"GEMINI_NEXT_GEN_API_BASE_URL\"), apiKey = (_c = readEnv(\"GEMINI_API_KEY\")) !== null && _c !== void 0 ? _c : null, apiVersion = \"v1beta\" } = _b, opts = __rest(_b, [\"baseURL\", \"apiKey\", \"apiVersion\"]);\r\n const options = Object.assign(Object.assign({\r\n apiKey,\r\n apiVersion\r\n }, opts), { baseURL: baseURL || `https://generativelanguage.googleapis.com` });\r\n this.baseURL = options.baseURL;\r\n this.timeout = (_d = options.timeout) !== null && _d !== void 0 ? _d : _BaseGeminiNextGenAPIClient.DEFAULT_TIMEOUT;\r\n this.logger = (_e = options.logger) !== null && _e !== void 0 ? _e : console;\r\n const defaultLogLevel = \"warn\";\r\n this.logLevel = defaultLogLevel;\r\n this.logLevel = (_g = (_f = parseLogLevel(options.logLevel, \"ClientOptions.logLevel\", this)) !== null && _f !== void 0 ? _f : parseLogLevel(readEnv(\"GEMINI_NEXT_GEN_API_LOG\"), \"process.env['GEMINI_NEXT_GEN_API_LOG']\", this)) !== null && _g !== void 0 ? _g : defaultLogLevel;\r\n this.fetchOptions = options.fetchOptions;\r\n this.maxRetries = (_h = options.maxRetries) !== null && _h !== void 0 ? _h : 2;\r\n this.fetch = (_j = options.fetch) !== null && _j !== void 0 ? _j : getDefaultFetch();\r\n this.encoder = FallbackEncoder;\r\n this._options = options;\r\n this.apiKey = apiKey;\r\n this.apiVersion = apiVersion;\r\n this.clientAdapter = options.clientAdapter;\r\n }\r\n /**\r\n * Create a new client instance re-using the same options given to the current client with optional overriding.\r\n */\r\n withOptions(options) {\r\n const client = new this.constructor(Object.assign(Object.assign(Object.assign({}, this._options), { baseURL: this.baseURL, maxRetries: this.maxRetries, timeout: this.timeout, logger: this.logger, logLevel: this.logLevel, fetch: this.fetch, fetchOptions: this.fetchOptions, apiKey: this.apiKey, apiVersion: this.apiVersion }), options));\r\n return client;\r\n }\r\n /**\r\n * Check whether the base URL is set to its default.\r\n */\r\n baseURLOverridden() {\r\n return this.baseURL !== \"https://generativelanguage.googleapis.com\";\r\n }\r\n defaultQuery() {\r\n return this._options.defaultQuery;\r\n }\r\n validateHeaders({ values, nulls }) {\r\n if (values.has(\"authorization\") || values.has(\"x-goog-api-key\")) {\r\n return;\r\n }\r\n if (this.apiKey && values.get(\"x-goog-api-key\")) {\r\n return;\r\n }\r\n if (nulls.has(\"x-goog-api-key\")) {\r\n return;\r\n }\r\n throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the \"x-goog-api-key\" headers to be explicitly omitted');\r\n }\r\n async authHeaders(opts) {\r\n const existingHeaders = buildHeaders([opts.headers]);\r\n if (existingHeaders.values.has(\"authorization\") || existingHeaders.values.has(\"x-goog-api-key\")) {\r\n return void 0;\r\n }\r\n if (this.apiKey) {\r\n return buildHeaders([{ \"x-goog-api-key\": this.apiKey }]);\r\n }\r\n if (this.clientAdapter && this.clientAdapter.isVertexAI()) {\r\n return buildHeaders([await this.clientAdapter.getAuthHeaders()]);\r\n }\r\n return void 0;\r\n }\r\n /**\r\n * Basic re-implementation of `qs.stringify` for primitive types.\r\n */\r\n stringifyQuery(query) {\r\n return stringifyQuery(query);\r\n }\r\n getUserAgent() {\r\n return `${this.constructor.name}/JS ${VERSION}`;\r\n }\r\n defaultIdempotencyKey() {\r\n return `stainless-node-retry-${uuid4()}`;\r\n }\r\n makeStatusError(status, error, message, headers) {\r\n return APIError.generate(status, error, message, headers);\r\n }\r\n buildURL(path2, query, defaultBaseURL) {\r\n const baseURL = !this.baseURLOverridden() && defaultBaseURL || this.baseURL;\r\n const url = isAbsoluteURL(path2) ? new URL(path2) : new URL(baseURL + (baseURL.endsWith(\"/\") && path2.startsWith(\"/\") ? path2.slice(1) : path2));\r\n const defaultQuery = this.defaultQuery();\r\n const pathQuery = Object.fromEntries(url.searchParams);\r\n if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) {\r\n query = Object.assign(Object.assign(Object.assign({}, pathQuery), defaultQuery), query);\r\n }\r\n if (typeof query === \"object\" && query && !Array.isArray(query)) {\r\n url.search = this.stringifyQuery(query);\r\n }\r\n return url.toString();\r\n }\r\n /**\r\n * Used as a callback for mutating the given `FinalRequestOptions` object.\r\n \r\n */\r\n async prepareOptions(options) {\r\n if (this.clientAdapter && this.clientAdapter.isVertexAI() && !options.path.startsWith(`/${this.apiVersion}/projects/`)) {\r\n const oldPath = options.path.slice(this.apiVersion.length + 1);\r\n options.path = `/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${oldPath}`;\r\n }\r\n }\r\n /**\r\n * Used as a callback for mutating the given `RequestInit` object.\r\n *\r\n * This is useful for cases where you want to add certain headers based off of\r\n * the request properties, e.g. `method` or `url`.\r\n */\r\n async prepareRequest(request, { url, options }) {\r\n }\r\n get(path2, opts) {\r\n return this.methodRequest(\"get\", path2, opts);\r\n }\r\n post(path2, opts) {\r\n return this.methodRequest(\"post\", path2, opts);\r\n }\r\n patch(path2, opts) {\r\n return this.methodRequest(\"patch\", path2, opts);\r\n }\r\n put(path2, opts) {\r\n return this.methodRequest(\"put\", path2, opts);\r\n }\r\n delete(path2, opts) {\r\n return this.methodRequest(\"delete\", path2, opts);\r\n }\r\n methodRequest(method, path2, opts) {\r\n return this.request(Promise.resolve(opts).then((opts2) => {\r\n return Object.assign({ method, path: path2 }, opts2);\r\n }));\r\n }\r\n request(options, remainingRetries = null) {\r\n return new APIPromise(this, this.makeRequest(options, remainingRetries, void 0));\r\n }\r\n async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {\r\n var _b, _c, _d;\r\n const options = await optionsInput;\r\n const maxRetries = (_b = options.maxRetries) !== null && _b !== void 0 ? _b : this.maxRetries;\r\n if (retriesRemaining == null) {\r\n retriesRemaining = maxRetries;\r\n }\r\n await this.prepareOptions(options);\r\n const { req, url, timeout } = await this.buildRequest(options, {\r\n retryCount: maxRetries - retriesRemaining\r\n });\r\n await this.prepareRequest(req, { url, options });\r\n const requestLogID = \"log_\" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, \"0\");\r\n const retryLogStr = retryOfRequestLogID === void 0 ? \"\" : `, retryOf: ${retryOfRequestLogID}`;\r\n const startTime = Date.now();\r\n loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({\r\n retryOfRequestLogID,\r\n method: options.method,\r\n url,\r\n options,\r\n headers: req.headers\r\n }));\r\n if ((_c = options.signal) === null || _c === void 0 ? void 0 : _c.aborted) {\r\n throw new APIUserAbortError();\r\n }\r\n const controller = new AbortController();\r\n const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);\r\n const headersTime = Date.now();\r\n if (response instanceof globalThis.Error) {\r\n const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;\r\n if ((_d = options.signal) === null || _d === void 0 ? void 0 : _d.aborted) {\r\n throw new APIUserAbortError();\r\n }\r\n const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + (\"cause\" in response ? String(response.cause) : \"\"));\r\n if (retriesRemaining) {\r\n loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? \"timed out\" : \"failed\"} - ${retryMessage}`);\r\n loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? \"timed out\" : \"failed\"} (${retryMessage})`, formatRequestDetails({\r\n retryOfRequestLogID,\r\n url,\r\n durationMs: headersTime - startTime,\r\n message: response.message\r\n }));\r\n return this.retryRequest(options, retriesRemaining, retryOfRequestLogID !== null && retryOfRequestLogID !== void 0 ? retryOfRequestLogID : requestLogID);\r\n }\r\n loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? \"timed out\" : \"failed\"} - error; no more retries left`);\r\n loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? \"timed out\" : \"failed\"} (error; no more retries left)`, formatRequestDetails({\r\n retryOfRequestLogID,\r\n url,\r\n durationMs: headersTime - startTime,\r\n message: response.message\r\n }));\r\n if (isTimeout) {\r\n throw new APIConnectionTimeoutError();\r\n }\r\n throw new APIConnectionError({ cause: response });\r\n }\r\n const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? \"succeeded\" : \"failed\"} with status ${response.status} in ${headersTime - startTime}ms`;\r\n if (!response.ok) {\r\n const shouldRetry = await this.shouldRetry(response);\r\n if (retriesRemaining && shouldRetry) {\r\n const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;\r\n await CancelReadableStream(response.body);\r\n loggerFor(this).info(`${responseInfo} - ${retryMessage2}`);\r\n loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({\r\n retryOfRequestLogID,\r\n url: response.url,\r\n status: response.status,\r\n headers: response.headers,\r\n durationMs: headersTime - startTime\r\n }));\r\n return this.retryRequest(options, retriesRemaining, retryOfRequestLogID !== null && retryOfRequestLogID !== void 0 ? retryOfRequestLogID : requestLogID, response.headers);\r\n }\r\n const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;\r\n loggerFor(this).info(`${responseInfo} - ${retryMessage}`);\r\n const errText = await response.text().catch((err2) => castToError(err2).message);\r\n const errJSON = safeJSON(errText);\r\n const errMessage = errJSON ? void 0 : errText;\r\n loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({\r\n retryOfRequestLogID,\r\n url: response.url,\r\n status: response.status,\r\n headers: response.headers,\r\n message: errMessage,\r\n durationMs: Date.now() - startTime\r\n }));\r\n const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);\r\n throw err;\r\n }\r\n loggerFor(this).info(responseInfo);\r\n loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({\r\n retryOfRequestLogID,\r\n url: response.url,\r\n status: response.status,\r\n headers: response.headers,\r\n durationMs: headersTime - startTime\r\n }));\r\n return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };\r\n }\r\n async fetchWithTimeout(url, init, ms, controller) {\r\n const _b = init || {}, { signal, method } = _b, options = __rest(_b, [\"signal\", \"method\"]);\r\n const abort = this._makeAbort(controller);\r\n if (signal)\r\n signal.addEventListener(\"abort\", abort, { once: true });\r\n const timeout = setTimeout(abort, ms);\r\n const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === \"object\" && options.body !== null && Symbol.asyncIterator in options.body;\r\n const fetchOptions = Object.assign(Object.assign(Object.assign({ signal: controller.signal }, isReadableBody ? { duplex: \"half\" } : {}), { method: \"GET\" }), options);\r\n if (method) {\r\n fetchOptions.method = method.toUpperCase();\r\n }\r\n try {\r\n return await this.fetch.call(void 0, url, fetchOptions);\r\n } finally {\r\n clearTimeout(timeout);\r\n }\r\n }\r\n async shouldRetry(response) {\r\n const shouldRetryHeader = response.headers.get(\"x-should-retry\");\r\n if (shouldRetryHeader === \"true\")\r\n return true;\r\n if (shouldRetryHeader === \"false\")\r\n return false;\r\n if (response.status === 408)\r\n return true;\r\n if (response.status === 409)\r\n return true;\r\n if (response.status === 429)\r\n return true;\r\n if (response.status >= 500)\r\n return true;\r\n return false;\r\n }\r\n async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {\r\n var _b;\r\n let timeoutMillis;\r\n const retryAfterMillisHeader = responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders.get(\"retry-after-ms\");\r\n if (retryAfterMillisHeader) {\r\n const timeoutMs = parseFloat(retryAfterMillisHeader);\r\n if (!Number.isNaN(timeoutMs)) {\r\n timeoutMillis = timeoutMs;\r\n }\r\n }\r\n const retryAfterHeader = responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders.get(\"retry-after\");\r\n if (retryAfterHeader && !timeoutMillis) {\r\n const timeoutSeconds = parseFloat(retryAfterHeader);\r\n if (!Number.isNaN(timeoutSeconds)) {\r\n timeoutMillis = timeoutSeconds * 1e3;\r\n } else {\r\n timeoutMillis = Date.parse(retryAfterHeader) - Date.now();\r\n }\r\n }\r\n if (timeoutMillis === void 0) {\r\n const maxRetries = (_b = options.maxRetries) !== null && _b !== void 0 ? _b : this.maxRetries;\r\n timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);\r\n }\r\n await sleep$1(timeoutMillis);\r\n return this.makeRequest(options, retriesRemaining - 1, requestLogID);\r\n }\r\n calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {\r\n const initialRetryDelay = 0.5;\r\n const maxRetryDelay = 8;\r\n const numRetries = maxRetries - retriesRemaining;\r\n const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);\r\n const jitter = 1 - Math.random() * 0.25;\r\n return sleepSeconds * jitter * 1e3;\r\n }\r\n async buildRequest(inputOptions, { retryCount = 0 } = {}) {\r\n var _b, _c, _d;\r\n const options = Object.assign({}, inputOptions);\r\n const { method, path: path2, query, defaultBaseURL } = options;\r\n const url = this.buildURL(path2, query, defaultBaseURL);\r\n if (\"timeout\" in options)\r\n validatePositiveInteger(\"timeout\", options.timeout);\r\n options.timeout = (_b = options.timeout) !== null && _b !== void 0 ? _b : this.timeout;\r\n const { bodyHeaders, body } = this.buildBody({ options });\r\n const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });\r\n const req = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ method, headers: reqHeaders }, options.signal && { signal: options.signal }), globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: \"half\" }), body && { body }), (_c = this.fetchOptions) !== null && _c !== void 0 ? _c : {}), (_d = options.fetchOptions) !== null && _d !== void 0 ? _d : {});\r\n return { req, url, timeout: options.timeout };\r\n }\r\n async buildHeaders({ options, method, bodyHeaders, retryCount }) {\r\n let idempotencyHeaders = {};\r\n if (this.idempotencyHeader && method !== \"get\") {\r\n if (!options.idempotencyKey)\r\n options.idempotencyKey = this.defaultIdempotencyKey();\r\n idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;\r\n }\r\n const authHeaders = await this.authHeaders(options);\r\n let headers = buildHeaders([\r\n idempotencyHeaders,\r\n { Accept: \"application/json\", \"User-Agent\": this.getUserAgent() },\r\n this._options.defaultHeaders,\r\n bodyHeaders,\r\n options.headers,\r\n authHeaders\r\n ]);\r\n this.validateHeaders(headers);\r\n return headers.values;\r\n }\r\n _makeAbort(controller) {\r\n return () => controller.abort();\r\n }\r\n buildBody({ options: { body, headers: rawHeaders } }) {\r\n if (!body) {\r\n return { bodyHeaders: void 0, body: void 0 };\r\n }\r\n const headers = buildHeaders([rawHeaders]);\r\n if (\r\n // Pass raw type verbatim\r\n ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === \"string\" && // Preserve legacy string encoding behavior for now\r\n headers.values.has(\"content-type\") || // `Blob` is superset of `File`\r\n globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data`\r\n body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded`\r\n body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`)\r\n globalThis.ReadableStream && body instanceof globalThis.ReadableStream\r\n ) {\r\n return { bodyHeaders: void 0, body };\r\n } else if (typeof body === \"object\" && (Symbol.asyncIterator in body || Symbol.iterator in body && \"next\" in body && typeof body.next === \"function\")) {\r\n return { bodyHeaders: void 0, body: ReadableStreamFrom(body) };\r\n } else if (typeof body === \"object\" && headers.values.get(\"content-type\") === \"application/x-www-form-urlencoded\") {\r\n return {\r\n bodyHeaders: { \"content-type\": \"application/x-www-form-urlencoded\" },\r\n body: this.stringifyQuery(body)\r\n };\r\n } else {\r\n return this.encoder({ body, headers });\r\n }\r\n }\r\n };\r\n BaseGeminiNextGenAPIClient.DEFAULT_TIMEOUT = 6e4;\r\n GeminiNextGenAPIClient = class extends BaseGeminiNextGenAPIClient {\r\n constructor() {\r\n super(...arguments);\r\n this.interactions = new Interactions(this);\r\n }\r\n };\r\n _a = GeminiNextGenAPIClient;\r\n GeminiNextGenAPIClient.GeminiNextGenAPIClient = _a;\r\n GeminiNextGenAPIClient.GeminiNextGenAPIClientError = GeminiNextGenAPIClientError;\r\n GeminiNextGenAPIClient.APIError = APIError;\r\n GeminiNextGenAPIClient.APIConnectionError = APIConnectionError;\r\n GeminiNextGenAPIClient.APIConnectionTimeoutError = APIConnectionTimeoutError;\r\n GeminiNextGenAPIClient.APIUserAbortError = APIUserAbortError;\r\n GeminiNextGenAPIClient.NotFoundError = NotFoundError;\r\n GeminiNextGenAPIClient.ConflictError = ConflictError;\r\n GeminiNextGenAPIClient.RateLimitError = RateLimitError;\r\n GeminiNextGenAPIClient.BadRequestError = BadRequestError;\r\n GeminiNextGenAPIClient.AuthenticationError = AuthenticationError;\r\n GeminiNextGenAPIClient.InternalServerError = InternalServerError;\r\n GeminiNextGenAPIClient.PermissionDeniedError = PermissionDeniedError;\r\n GeminiNextGenAPIClient.UnprocessableEntityError = UnprocessableEntityError;\r\n GeminiNextGenAPIClient.toFile = toFile;\r\n GeminiNextGenAPIClient.Interactions = Interactions;\r\n Tunings = class extends BaseModule {\r\n constructor(apiClient) {\r\n super();\r\n this.apiClient = apiClient;\r\n this.list = async (params = {}) => {\r\n return new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params);\r\n };\r\n this.get = async (params) => {\r\n return await this.getInternal(params);\r\n };\r\n this.tune = async (params) => {\r\n var _a2;\r\n if (this.apiClient.isVertexAI()) {\r\n if (params.baseModel.startsWith(\"projects/\")) {\r\n const preTunedModel = {\r\n tunedModelName: params.baseModel\r\n };\r\n if ((_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.preTunedModelCheckpointId) {\r\n preTunedModel.checkpointId = params.config.preTunedModelCheckpointId;\r\n }\r\n const paramsPrivate = Object.assign(Object.assign({}, params), { preTunedModel });\r\n paramsPrivate.baseModel = void 0;\r\n return await this.tuneInternal(paramsPrivate);\r\n } else {\r\n const paramsPrivate = Object.assign({}, params);\r\n return await this.tuneInternal(paramsPrivate);\r\n }\r\n } else {\r\n const paramsPrivate = Object.assign({}, params);\r\n const operation = await this.tuneMldevInternal(paramsPrivate);\r\n let tunedModelName = \"\";\r\n if (operation[\"metadata\"] !== void 0 && operation[\"metadata\"][\"tunedModel\"] !== void 0) {\r\n tunedModelName = operation[\"metadata\"][\"tunedModel\"];\r\n } else if (operation[\"name\"] !== void 0 && operation[\"name\"].includes(\"/operations/\")) {\r\n tunedModelName = operation[\"name\"].split(\"/operations/\")[0];\r\n }\r\n const tuningJob = {\r\n name: tunedModelName,\r\n state: JobState.JOB_STATE_QUEUED\r\n };\r\n return tuningJob;\r\n }\r\n };\r\n }\r\n async getInternal(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = getTuningJobParametersToVertex(params);\r\n path2 = formatMap(\"{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = tuningJobFromVertex(apiResponse);\r\n return resp;\r\n });\r\n } else {\r\n const body = getTuningJobParametersToMldev(params);\r\n path2 = formatMap(\"{name}\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = tuningJobFromMldev(apiResponse);\r\n return resp;\r\n });\r\n }\r\n }\r\n async listInternal(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = listTuningJobsParametersToVertex(params);\r\n path2 = formatMap(\"tuningJobs\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = listTuningJobsResponseFromVertex(apiResponse);\r\n const typedResp = new ListTuningJobsResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n } else {\r\n const body = listTuningJobsParametersToMldev(params);\r\n path2 = formatMap(\"tunedModels\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"GET\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = listTuningJobsResponseFromMldev(apiResponse);\r\n const typedResp = new ListTuningJobsResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n /**\r\n * Cancels a tuning job.\r\n *\r\n * @param params - The parameters for the cancel request.\r\n * @return The empty response returned by the API.\r\n *\r\n * @example\r\n * ```ts\r\n * await ai.tunings.cancel({name: '...'}); // The server-generated resource name.\r\n * ```\r\n */\r\n async cancel(params) {\r\n var _a2, _b, _c, _d;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = cancelTuningJobParametersToVertex(params);\r\n path2 = formatMap(\"{name}:cancel\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = cancelTuningJobResponseFromVertex(apiResponse);\r\n const typedResp = new CancelTuningJobResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n } else {\r\n const body = cancelTuningJobParametersToMldev(params);\r\n path2 = formatMap(\"{name}:cancel\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,\r\n abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = cancelTuningJobResponseFromMldev(apiResponse);\r\n const typedResp = new CancelTuningJobResponse();\r\n Object.assign(typedResp, resp);\r\n return typedResp;\r\n });\r\n }\r\n }\r\n async tuneInternal(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n const body = createTuningJobParametersPrivateToVertex(params, params);\r\n path2 = formatMap(\"tuningJobs\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = tuningJobFromVertex(apiResponse);\r\n return resp;\r\n });\r\n } else {\r\n throw new Error(\"This method is only supported by the Vertex AI.\");\r\n }\r\n }\r\n async tuneMldevInternal(params) {\r\n var _a2, _b;\r\n let response;\r\n let path2 = \"\";\r\n let queryParams = {};\r\n if (this.apiClient.isVertexAI()) {\r\n throw new Error(\"This method is only supported by the Gemini Developer API.\");\r\n } else {\r\n const body = createTuningJobParametersPrivateToMldev(params);\r\n path2 = formatMap(\"tunedModels\", body[\"_url\"]);\r\n queryParams = body[\"_query\"];\r\n delete body[\"_url\"];\r\n delete body[\"_query\"];\r\n response = this.apiClient.request({\r\n path: path2,\r\n queryParams,\r\n body: JSON.stringify(body),\r\n httpMethod: \"POST\",\r\n httpOptions: (_a2 = params.config) === null || _a2 === void 0 ? void 0 : _a2.httpOptions,\r\n abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal\r\n }).then((httpResponse) => {\r\n return httpResponse.json().then((jsonResponse) => {\r\n const response2 = jsonResponse;\r\n response2.sdkHttpResponse = {\r\n headers: httpResponse.headers\r\n };\r\n return response2;\r\n });\r\n });\r\n return response.then((apiResponse) => {\r\n const resp = tuningOperationFromMldev(apiResponse);\r\n return resp;\r\n });\r\n }\r\n }\r\n };\r\n BrowserDownloader = class {\r\n async download(_params, _apiClient) {\r\n throw new Error(\"Download to file is not supported in the browser, please use a browser compliant download like an <a> tag.\");\r\n }\r\n };\r\n MAX_CHUNK_SIZE = 1024 * 1024 * 8;\r\n MAX_RETRY_COUNT = 3;\r\n INITIAL_RETRY_DELAY_MS = 1e3;\r\n DELAY_MULTIPLIER = 2;\r\n X_GOOG_UPLOAD_STATUS_HEADER_FIELD = \"x-goog-upload-status\";\r\n BrowserUploader = class {\r\n async upload(file, uploadUrl, apiClient, httpOptions) {\r\n if (typeof file === \"string\") {\r\n throw new Error(\"File path is not supported in browser uploader.\");\r\n }\r\n return await uploadBlob(file, uploadUrl, apiClient, httpOptions);\r\n }\r\n async uploadToFileSearchStore(file, uploadUrl, apiClient, httpOptions) {\r\n if (typeof file === \"string\") {\r\n throw new Error(\"File path is not supported in browser uploader.\");\r\n }\r\n return await uploadBlobToFileSearchStore(file, uploadUrl, apiClient, httpOptions);\r\n }\r\n async stat(file) {\r\n if (typeof file === \"string\") {\r\n throw new Error(\"File path is not supported in browser uploader.\");\r\n } else {\r\n return await getBlobStat(file);\r\n }\r\n }\r\n };\r\n BrowserWebSocketFactory = class {\r\n create(url, headers, callbacks) {\r\n return new BrowserWebSocket(url, headers, callbacks);\r\n }\r\n };\r\n BrowserWebSocket = class {\r\n constructor(url, headers, callbacks) {\r\n this.url = url;\r\n this.headers = headers;\r\n this.callbacks = callbacks;\r\n }\r\n connect() {\r\n this.ws = new WebSocket(this.url);\r\n this.ws.onopen = this.callbacks.onopen;\r\n this.ws.onerror = this.callbacks.onerror;\r\n this.ws.onclose = this.callbacks.onclose;\r\n this.ws.onmessage = this.callbacks.onmessage;\r\n }\r\n send(message) {\r\n if (this.ws === void 0) {\r\n throw new Error(\"WebSocket is not connected\");\r\n }\r\n this.ws.send(message);\r\n }\r\n close() {\r\n if (this.ws === void 0) {\r\n throw new Error(\"WebSocket is not connected\");\r\n }\r\n this.ws.close();\r\n }\r\n };\r\n GOOGLE_API_KEY_HEADER = \"x-goog-api-key\";\r\n WebAuth = class {\r\n constructor(apiKey) {\r\n this.apiKey = apiKey;\r\n }\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n async addAuthHeaders(headers, url) {\r\n if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {\r\n return;\r\n }\r\n if (this.apiKey.startsWith(\"auth_tokens/\")) {\r\n throw new Error(\"Ephemeral tokens are only supported by the live API.\");\r\n }\r\n if (!this.apiKey) {\r\n throw new Error(\"API key is missing. Please provide a valid API key.\");\r\n }\r\n headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);\r\n }\r\n };\r\n LANGUAGE_LABEL_PREFIX = \"gl-node/\";\r\n GoogleGenAI = class {\r\n get interactions() {\r\n var _a2;\r\n if (this._interactions !== void 0) {\r\n return this._interactions;\r\n }\r\n console.warn(\"GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions.\");\r\n const httpOpts = this.httpOptions;\r\n if (httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.extraBody) {\r\n console.warn(\"GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.\");\r\n }\r\n const nextGenClient = new GeminiNextGenAPIClient({\r\n baseURL: this.apiClient.getBaseUrl(),\r\n apiKey: this.apiKey,\r\n apiVersion: this.apiClient.getApiVersion(),\r\n clientAdapter: this.apiClient,\r\n defaultHeaders: this.apiClient.getDefaultHeaders(),\r\n timeout: httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.timeout,\r\n maxRetries: (_a2 = httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.retryOptions) === null || _a2 === void 0 ? void 0 : _a2.attempts\r\n });\r\n this._interactions = nextGenClient.interactions;\r\n return this._interactions;\r\n }\r\n constructor(options) {\r\n var _a2;\r\n if (options.apiKey == null) {\r\n throw new Error(\"An API Key must be set when running in a browser\");\r\n }\r\n if (options.project || options.location) {\r\n throw new Error(\"Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.\");\r\n }\r\n this.vertexai = (_a2 = options.vertexai) !== null && _a2 !== void 0 ? _a2 : false;\r\n this.apiKey = options.apiKey;\r\n const baseUrl = getBaseUrl(\r\n options.httpOptions,\r\n options.vertexai,\r\n /*vertexBaseUrlFromEnv*/\r\n void 0,\r\n /*geminiBaseUrlFromEnv*/\r\n void 0\r\n );\r\n if (baseUrl) {\r\n if (options.httpOptions) {\r\n options.httpOptions.baseUrl = baseUrl;\r\n } else {\r\n options.httpOptions = { baseUrl };\r\n }\r\n }\r\n this.apiVersion = options.apiVersion;\r\n this.httpOptions = options.httpOptions;\r\n const auth = new WebAuth(this.apiKey);\r\n this.apiClient = new ApiClient({\r\n auth,\r\n apiVersion: this.apiVersion,\r\n apiKey: this.apiKey,\r\n vertexai: this.vertexai,\r\n httpOptions: this.httpOptions,\r\n userAgentExtra: LANGUAGE_LABEL_PREFIX + \"web\",\r\n uploader: new BrowserUploader(),\r\n downloader: new BrowserDownloader()\r\n });\r\n this.models = new Models(this.apiClient);\r\n this.live = new Live(this.apiClient, auth, new BrowserWebSocketFactory());\r\n this.batches = new Batches(this.apiClient);\r\n this.chats = new Chats(this.models, this.apiClient);\r\n this.caches = new Caches(this.apiClient);\r\n this.files = new Files(this.apiClient);\r\n this.operations = new Operations(this.apiClient);\r\n this.authTokens = new Tokens(this.apiClient);\r\n this.tunings = new Tunings(this.apiClient);\r\n this.fileSearchStores = new FileSearchStores(this.apiClient);\r\n }\r\n };\r\n }\r\n});\r\n\r\n// lib/client.js\r\nvar require_client = __commonJS({\r\n \"lib/client.js\"(exports, module) {\r\n var { GoogleGenAI: GoogleGenAI2 } = (init_web(), __toCommonJS(web_exports));\r\n var _client = null;\r\n function getClient(apiKey) {\r\n if (!_client || apiKey) _client = new GoogleGenAI2({ apiKey: apiKey || process.env.GEMINI_API_KEY });\r\n return _client;\r\n }\r\n module.exports = { getClient };\r\n }\r\n});\r\n\r\n// lib/errors.js\r\nvar require_errors = __commonJS({\r\n \"lib/errors.js\"(exports, module) {\r\n var GeminiError = class extends Error {\r\n constructor(message, { status, code, retryable = false } = {}) {\r\n super(message);\r\n this.name = \"GeminiError\";\r\n this.status = status;\r\n this.code = code;\r\n this.retryable = retryable;\r\n }\r\n };\r\n function isRetryable(err) {\r\n if (err instanceof GeminiError) return err.retryable;\r\n const status = err?.status ?? err?.code;\r\n if (status === 429) return true;\r\n if (typeof status === \"number\" && status >= 500) return true;\r\n const msg = err?.message ?? \"\";\r\n return /quota|rate.?limit|overloaded|unavailable/i.test(msg);\r\n }\r\n function parseRetryDelay(err) {\r\n try {\r\n const body = typeof err.message === \"string\" ? JSON.parse(err.message) : err.message;\r\n const details = body?.error?.details || [];\r\n const retryInfo = details.find((d) => d[\"@type\"]?.includes(\"RetryInfo\"));\r\n if (retryInfo?.retryDelay) {\r\n const secs = parseFloat(retryInfo.retryDelay);\r\n if (!isNaN(secs)) return secs * 1e3;\r\n }\r\n } catch (_) {\r\n }\r\n return null;\r\n }\r\n async function withRetry(fn, maxRetries = 3) {\r\n let lastErr;\r\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\r\n try {\r\n return await fn();\r\n } catch (err) {\r\n lastErr = err;\r\n if (!isRetryable(err) || attempt === maxRetries) throw err;\r\n const suggested = parseRetryDelay(err);\r\n const delay = suggested != null ? suggested + Math.random() * 1e3 : Math.min(1e3 * 2 ** attempt + Math.random() * 200, 16e3);\r\n await new Promise((r) => setTimeout(r, delay));\r\n }\r\n }\r\n throw lastErr;\r\n }\r\n module.exports = { GeminiError, isRetryable, withRetry };\r\n }\r\n});\r\n\r\n// lib/convert.js\r\nvar require_convert = __commonJS({\r\n \"lib/convert.js\"(exports, module) {\r\n function cleanSchema(schema) {\r\n if (!schema || typeof schema !== \"object\") return schema;\r\n if (Array.isArray(schema)) return schema.map(cleanSchema);\r\n const out = {};\r\n for (const [k, v] of Object.entries(schema)) {\r\n if (k === \"additionalProperties\" || k === \"$schema\") continue;\r\n out[k] = cleanSchema(v);\r\n }\r\n return out;\r\n }\r\n function convertTools(tools) {\r\n if (!tools || typeof tools !== \"object\") return [];\r\n return Object.entries(tools).map(([name, t]) => ({\r\n name,\r\n description: t.description || \"\",\r\n parameters: cleanSchema(t.parameters?.jsonSchema || t.parameters || { type: \"object\" })\r\n }));\r\n }\r\n function convertImageBlock(b) {\r\n if (b.inlineData || b.type === \"image\") {\r\n const src = b.inlineData || b.source;\r\n if (src?.data) return { inlineData: { mimeType: src.mimeType || \"image/jpeg\", data: src.data } };\r\n if (src?.url) return { fileData: { mimeType: src.mimeType || \"image/jpeg\", fileUri: src.url } };\r\n }\r\n if (b.fileData) return { fileData: { mimeType: b.fileData.mimeType, fileUri: b.fileData.fileUri } };\r\n if (b.type === \"image\" && b.source) {\r\n if (b.source.type === \"base64\") return { inlineData: { mimeType: b.source.media_type, data: b.source.data } };\r\n if (b.source.type === \"url\") return { fileData: { mimeType: b.source.media_type || \"image/jpeg\", fileUri: b.source.url } };\r\n }\r\n return null;\r\n }\r\n function convertMessages(messages) {\r\n const contents = [];\r\n for (const m of messages) {\r\n const role = m.role === \"assistant\" ? \"model\" : \"user\";\r\n if (typeof m.content === \"string\") {\r\n if (m.content) contents.push({ role, parts: [{ text: m.content }] });\r\n continue;\r\n }\r\n if (Array.isArray(m.content)) {\r\n const parts = m.content.map((b) => {\r\n if (b.type === \"text\" && b.text) return { text: b.text };\r\n if (b.type === \"image\" || b.inlineData || b.fileData) return convertImageBlock(b);\r\n if (b.type === \"tool_use\") return { functionCall: { name: b.name, args: b.input || {} } };\r\n if (b.type === \"tool_result\") {\r\n let resp;\r\n try {\r\n resp = typeof b.content === \"string\" ? JSON.parse(b.content) : b.content || {};\r\n } catch {\r\n resp = { result: b.content };\r\n }\r\n return { functionResponse: { name: b.name || \"unknown\", response: resp } };\r\n }\r\n return null;\r\n }).filter(Boolean);\r\n if (parts.length) contents.push({ role, parts });\r\n }\r\n }\r\n return contents;\r\n }\r\n function extractModelId(model) {\r\n if (typeof model === \"string\") return model;\r\n if (model?.modelId) return model.modelId;\r\n if (model?.id) return model.id;\r\n return \"gemini-2.0-flash\";\r\n }\r\n function buildConfig({ system, tools, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities } = {}) {\r\n const geminiTools = convertTools(tools);\r\n const config = {\r\n maxOutputTokens: maxOutputTokens ?? 8192,\r\n temperature: temperature ?? 0.5,\r\n topP: topP ?? 0.95\r\n };\r\n if (topK != null) config.topK = topK;\r\n if (system) config.systemInstruction = system;\r\n if (geminiTools.length > 0) config.tools = [{ functionDeclarations: geminiTools }];\r\n if (safetySettings) config.safetySettings = safetySettings;\r\n if (responseModalities) config.responseModalities = responseModalities;\r\n return { config, geminiTools };\r\n }\r\n module.exports = { cleanSchema, convertTools, convertMessages, extractModelId, buildConfig, convertImageBlock };\r\n }\r\n});\r\n\r\n// thebird-browser-entry.js\r\nvar require_thebird_browser_entry = __commonJS({\r\n \"thebird-browser-entry.js\"(exports, module) {\r\n var { getClient } = require_client();\r\n var { GeminiError, withRetry } = require_errors();\r\n var { convertMessages, convertTools, cleanSchema, extractModelId, buildConfig } = require_convert();\r\n function streamGemini2({ model, system, messages, tools, onStepFinish, apiKey, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities }) {\r\n return { fullStream: createFullStream({ model, system, messages, tools, onStepFinish, apiKey, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities }), warnings: Promise.resolve([]) };\r\n }\r\n async function* createFullStream({ model, system, messages, tools, onStepFinish, apiKey, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities }) {\r\n const client = getClient(apiKey);\r\n const modelId = extractModelId(model);\r\n let contents = convertMessages(messages);\r\n const { config } = buildConfig({ system, tools, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities });\r\n while (true) {\r\n yield { type: \"start-step\" };\r\n try {\r\n const stream = await withRetry(() => client.models.generateContentStream({ model: modelId, contents, config }));\r\n const allParts = [];\r\n for await (const chunk of stream) {\r\n for (const candidate of chunk.candidates || []) {\r\n for (const part of candidate.content?.parts || []) {\r\n allParts.push(part);\r\n if (part.text && !part.thought) yield { type: \"text-delta\", textDelta: part.text };\r\n }\r\n }\r\n }\r\n const fcParts = allParts.filter((p) => p.functionCall);\r\n if (fcParts.length === 0) {\r\n yield { type: \"finish-step\", finishReason: \"stop\" };\r\n if (onStepFinish) await onStepFinish();\r\n return;\r\n }\r\n const toolResultParts = [];\r\n for (const part of fcParts) {\r\n const name = part.functionCall.name;\r\n const args = part.functionCall.args || {};\r\n const toolId = \"toolu_\" + Math.random().toString(36).slice(2, 10);\r\n yield { type: \"tool-call\", toolCallId: toolId, toolName: name, args };\r\n const toolDef = tools?.[name];\r\n let result = toolDef ? null : { error: true, message: \"Tool not found: \" + name };\r\n if (toolDef?.execute) {\r\n try {\r\n result = await toolDef.execute(args, { toolCallId: toolId });\r\n } catch (e) {\r\n result = { error: true, message: e.message };\r\n }\r\n }\r\n yield { type: \"tool-result\", toolCallId: toolId, toolName: name, args, result };\r\n toolResultParts.push({ functionResponse: { name, response: typeof result === \"string\" ? { output: result } : result || {} } });\r\n }\r\n yield { type: \"finish-step\", finishReason: \"tool-calls\" };\r\n if (onStepFinish) await onStepFinish();\r\n contents.push({ role: \"model\", parts: allParts });\r\n contents.push({ role: \"user\", parts: toolResultParts });\r\n } catch (err) {\r\n yield { type: \"error\", error: err };\r\n yield { type: \"finish-step\", finishReason: \"error\" };\r\n if (onStepFinish) await onStepFinish();\r\n return;\r\n }\r\n }\r\n }\r\n async function generateGemini2({ model, system, messages, tools, apiKey, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities }) {\r\n const client = getClient(apiKey);\r\n const modelId = extractModelId(model);\r\n let contents = convertMessages(messages);\r\n const { config } = buildConfig({ system, tools, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities });\r\n while (true) {\r\n const response = await withRetry(() => client.models.generateContent({ model: modelId, contents, config }));\r\n const candidate = response.candidates?.[0];\r\n if (!candidate) throw new GeminiError(\"No candidates returned\", { retryable: false });\r\n const allParts = candidate.content?.parts || [];\r\n const fcParts = allParts.filter((p) => p.functionCall);\r\n if (fcParts.length === 0) {\r\n const text = allParts.filter((p) => p.text && !p.thought).map((p) => p.text).join(\"\");\r\n return { text, parts: allParts, response };\r\n }\r\n const toolResultParts = [];\r\n for (const part of fcParts) {\r\n const name = part.functionCall.name;\r\n const args = part.functionCall.args || {};\r\n const toolDef = tools?.[name];\r\n let result = toolDef ? null : { error: true, message: \"Tool not found: \" + name };\r\n if (toolDef?.execute) {\r\n try {\r\n result = await toolDef.execute(args);\r\n } catch (e) {\r\n result = { error: true, message: e.message };\r\n }\r\n }\r\n toolResultParts.push({ functionResponse: { name, response: typeof result === \"string\" ? { output: result } : result || {} } });\r\n }\r\n contents.push({ role: \"model\", parts: allParts });\r\n contents.push({ role: \"user\", parts: toolResultParts });\r\n }\r\n }\r\n function convertMessagesOAI(messages, system) {\r\n const result = [];\r\n if (system) result.push({ role: \"system\", content: typeof system === \"string\" ? system : JSON.stringify(system) });\r\n for (const m of messages) {\r\n if (typeof m.content === \"string\") {\r\n result.push({ role: m.role, content: m.content });\r\n continue;\r\n }\r\n if (!Array.isArray(m.content)) continue;\r\n const toolCalls = m.content.filter((b) => b.type === \"tool_use\");\r\n const toolResults = m.content.filter((b) => b.type === \"tool_result\");\r\n if (toolResults.length) {\r\n for (const b of toolResults) {\r\n const c = typeof b.content === \"string\" ? b.content : JSON.stringify(b.content || \"\");\r\n result.push({ role: \"tool\", tool_call_id: b.tool_use_id || b.id || b.name, content: c });\r\n }\r\n continue;\r\n }\r\n const textParts = m.content.filter((b) => b.type === \"text\").map((b) => b.text).join(\"\");\r\n if (toolCalls.length) {\r\n result.push({\r\n role: \"assistant\",\r\n content: textParts || null,\r\n tool_calls: toolCalls.map((b) => ({\r\n id: b.id || \"call_\" + Math.random().toString(36).slice(2, 8),\r\n type: \"function\",\r\n function: { name: b.name, arguments: JSON.stringify(b.input || {}) }\r\n }))\r\n });\r\n } else {\r\n result.push({ role: m.role, content: textParts });\r\n }\r\n }\r\n return result;\r\n }\r\n function convertToolsOAI(tools) {\r\n if (!tools || typeof tools !== \"object\") return void 0;\r\n const list = Object.entries(tools).map(([name, t]) => ({\r\n type: \"function\",\r\n function: {\r\n name,\r\n description: t.description || \"\",\r\n parameters: t.parameters?.jsonSchema || t.parameters || { type: \"object\" }\r\n }\r\n }));\r\n return list.length ? list : void 0;\r\n }\r\n async function* streamOpenAI2({ url, apiKey, messages, system, model, tools, maxOutputTokens, temperature, onStepFinish }) {\r\n const oaiMsgs = convertMessagesOAI(messages, system);\r\n const oaiTools = convertToolsOAI(tools);\r\n let body = { messages: oaiMsgs, model, max_tokens: maxOutputTokens || 8192, temperature: temperature ?? 0.5 };\r\n if (oaiTools) body.tools = oaiTools;\r\n while (true) {\r\n yield { type: \"start-step\" };\r\n const res = await fetch(url, {\r\n method: \"POST\",\r\n headers: { \"Content-Type\": \"application/json\", \"Authorization\": `Bearer ${apiKey}` },\r\n body: JSON.stringify({ ...body, stream: true })\r\n });\r\n if (!res.ok) {\r\n const t = await res.text();\r\n throw new Error(t);\r\n }\r\n const reader = res.body.getReader();\r\n const dec = new TextDecoder();\r\n let buf = \"\", toolCallsMap = {};\r\n try {\r\n while (true) {\r\n const { done, value } = await reader.read();\r\n if (done) break;\r\n buf += dec.decode(value, { stream: true });\r\n const lines = buf.split(\"\\n\");\r\n buf = lines.pop();\r\n for (const line of lines) {\r\n if (!line.startsWith(\"data: \")) continue;\r\n const d = line.slice(6).trim();\r\n if (d === \"[DONE]\") break;\r\n let chunk;\r\n try {\r\n chunk = JSON.parse(d);\r\n } catch {\r\n continue;\r\n }\r\n const delta = chunk.choices?.[0]?.delta;\r\n if (!delta) continue;\r\n if (delta.content) yield { type: \"text-delta\", textDelta: delta.content };\r\n if (delta.tool_calls) {\r\n for (const tc of delta.tool_calls) {\r\n const idx = tc.index ?? 0;\r\n if (!toolCallsMap[idx]) toolCallsMap[idx] = { id: tc.id || \"\", name: \"\", args: \"\" };\r\n if (tc.id) toolCallsMap[idx].id = tc.id;\r\n if (tc.function?.name) toolCallsMap[idx].name += tc.function.name;\r\n if (tc.function?.arguments) toolCallsMap[idx].args += tc.function.arguments;\r\n }\r\n }\r\n }\r\n }\r\n } finally {\r\n reader.releaseLock();\r\n }\r\n const pending = Object.values(toolCallsMap);\r\n if (!pending.length) {\r\n yield { type: \"finish-step\", finishReason: \"stop\" };\r\n if (onStepFinish) await onStepFinish();\r\n return;\r\n }\r\n const toolResultMsgs = [];\r\n for (const tc of pending) {\r\n let args;\r\n try {\r\n args = JSON.parse(tc.args || \"{}\");\r\n } catch {\r\n args = {};\r\n }\r\n const toolDef = tools?.[tc.name];\r\n let result = toolDef ? null : { error: true, message: \"Tool not found: \" + tc.name };\r\n if (toolDef?.execute) try {\r\n result = await toolDef.execute(args, { toolCallId: tc.id });\r\n } catch (e) {\r\n result = { error: true, message: e.message };\r\n }\r\n yield { type: \"tool-call\", toolCallId: tc.id, toolName: tc.name, args };\r\n yield { type: \"tool-result\", toolCallId: tc.id, toolName: tc.name, args, result };\r\n toolResultMsgs.push({ role: \"tool\", tool_call_id: tc.id, content: JSON.stringify(result ?? \"\") });\r\n }\r\n yield { type: \"finish-step\", finishReason: \"tool-calls\" };\r\n if (onStepFinish) await onStepFinish();\r\n body = { ...body, messages: [\r\n ...body.messages,\r\n { role: \"assistant\", content: null, tool_calls: pending.map((tc) => ({ id: tc.id, type: \"function\", function: { name: tc.name, arguments: tc.args } })) },\r\n ...toolResultMsgs\r\n ] };\r\n toolCallsMap = {};\r\n }\r\n }\r\n module.exports = { streamGemini: streamGemini2, generateGemini: generateGemini2, streamOpenAI: streamOpenAI2 };\r\n }\r\n});\r\n\r\n// thebird-browser-entry-esm.js\r\nvar import_thebird_browser_entry = __toESM(require_thebird_browser_entry());\r\nvar streamGemini = import_thebird_browser_entry.default.streamGemini;\r\nvar generateGemini = import_thebird_browser_entry.default.generateGemini;\r\nvar streamOpenAI = import_thebird_browser_entry.default.streamOpenAI;\r\nexport {\r\n generateGemini,\r\n streamGemini,\r\n streamOpenAI\r\n};\r\n/*! Bundled license information:\r\n\r\n@google/genai/dist/web/index.mjs:\r\n (**\r\n * @license\r\n * Copyright 2025 Google LLC\r\n * SPDX-License-Identifier: Apache-2.0\r\n *)\r\n*/\r\n","shell-node-modules.js":"function serializeRoutes(routes) {\n const out = {};\n for (const [method, arr] of Object.entries(routes)) out[method] = arr.map(r => ({ path: r.path }));\n return out;\n}\n\nfunction runFns(fns, req, res) {\n let i = 0;\n const next = err => {\n if (err) { res.status?.(500).send?.(String(err)); return; }\n const fn = fns[i++];\n if (fn) fn(req, res, next);\n };\n next();\n}\n\nexport function createExpress(term, fsmod) {\n return () => {\n const routes = { GET: [], POST: [], PUT: [], DELETE: [], USE: [] };\n const middlewares = [];\n const app = fn => middlewares.push(fn);\n const addRoute = method => (p, ...fns) => routes[method].push({ path: p, fn: (req, res) => runFns([...middlewares, ...fns], req, res) });\n app.get = addRoute('GET');\n app.post = addRoute('POST');\n app.put = addRoute('PUT');\n app.delete = addRoute('DELETE');\n app.use = (...args) => {\n if (typeof args[0] === 'function') middlewares.push(args[0]);\n else routes.USE.push({ path: args[0], fn: args[1] });\n };\n app.listen = (port, cb) => {\n window.__debug.shell.httpHandlers[port] = { routes, middlewares };\n navigator.serviceWorker?.controller?.postMessage({ type: 'REGISTER_ROUTES', port, routes: serializeRoutes(routes) });\n term.write('Express listening on :' + port + '\\r\\n');\n cb?.();\n };\n app.json = () => (req, res, next) => {\n if (typeof req.body === 'string') try { req.body = JSON.parse(req.body); } catch {}\n next?.();\n };\n app.static = dir => (req, res) => {\n const fp = dir.replace(/\\/$/, '') + req.path;\n try { res.send(fsmod.readFileSync(fp)); } catch { res.status(404).send('Not Found'); }\n };\n return app;\n };\n}\n\nexport function createHttp(term) {\n return () => ({\n createServer(handler) {\n const routes = { GET: [{ path: '*', fn: (req, res) => handler(req, res) }], POST: [], PUT: [], DELETE: [], USE: [] };\n return {\n listen(port, cb) {\n window.__debug.shell.httpHandlers[port] = { routes, middlewares: [] };\n term.write('http listening on :' + port + '\\r\\n');\n (typeof cb === 'function' ? cb : (typeof port === 'function' ? port : null))?.();\n return this;\n },\n close(cb) { cb?.(); },\n on() { return this; },\n };\n },\n request: () => { throw new Error('http.request: not supported in browser — use fetch()'); },\n get: () => { throw new Error('http.get: not supported in browser — use fetch()'); },\n STATUS_CODES: { 200: 'OK', 404: 'Not Found', 500: 'Internal Server Error' },\n });\n}\n\nexport function createSqlite() {\n return class Database {\n constructor(name) {\n this._name = name;\n if (!window.__sqlJs) throw new Error('sql.js not loaded');\n this._db = new window.__sqlJs.Database();\n }\n prepare(sql) {\n const db = this._db;\n return {\n run: (...p) => { db.run(sql, p); return { changes: 1 }; },\n get: (...p) => { const r = db.exec(sql, p); return r[0]?.values[0] ? Object.fromEntries(r[0].columns.map((c, i) => [c, r[0].values[0][i]])) : undefined; },\n all: (...p) => { const r = db.exec(sql, p); if (!r[0]) return []; return r[0].values.map(row => Object.fromEntries(r[0].columns.map((c, i) => [c, row[i]]))); },\n };\n }\n close() {}\n };\n}\n\nexport function createConsole(term) {\n const w = s => term.write(s + '\\r\\n');\n const timers = {};\n return {\n log: (...a) => w(a.map(v => typeof v === 'object' ? JSON.stringify(v, null, 2) : String(v)).join(' ')),\n error: (...a) => term.write('\\x1b[31m' + a.map(String).join(' ') + '\\x1b[0m\\r\\n'),\n warn: (...a) => term.write('\\x1b[33m' + a.map(String).join(' ') + '\\x1b[0m\\r\\n'),\n info: (...a) => w(a.map(String).join(' ')),\n dir: o => w(JSON.stringify(o, null, 2)),\n table: data => {\n if (!Array.isArray(data)) { w(JSON.stringify(data, null, 2)); return; }\n if (!data.length) { w('(empty)'); return; }\n const cols = Object.keys(data[0]);\n w(cols.join('\\t'));\n for (const row of data) w(cols.map(c => String(row[c] ?? '')).join('\\t'));\n },\n time: label => { timers[label || 'default'] = performance.now(); },\n timeEnd: label => {\n const k = label || 'default';\n const ms = timers[k] ? (performance.now() - timers[k]).toFixed(3) : 0;\n delete timers[k];\n w(k + ': ' + ms + 'ms');\n },\n assert: (cond, ...a) => { if (!cond) term.write('\\x1b[31mAssertion failed: ' + a.join(' ') + '\\x1b[0m\\r\\n'); },\n count: (() => { const c = {}; return label => { const k = label || 'default'; c[k] = (c[k] || 0) + 1; w(k + ': ' + c[k]); }; })(),\n clear: () => term.clear(),\n trace: (...a) => w('Trace: ' + a.map(String).join(' ')),\n group: () => {},\n groupEnd: () => {},\n };\n}\n\nexport const NODE_VERSION = 'v23.10.0';\nexport const NODE_VERSIONS = { node: '23.10.0', acorn: '8.14.0', ada: '3.1.3', amaro: '0.4.1', ares: '1.34.4', brotli: '1.1.0', cjs_module_lexer: '2.1.0', cldr: '46.0', icu: '76.1', llhttp: '9.2.1', modules: '131', napi: '10', nbytes: '0.1.1', ncrypto: '0.0.1', nghttp2: '1.64.0', openssl: '3.0.16', simdjson: '3.12.2', simdutf: '6.0.3', sqlite: '3.49.1', tz: '2025a', undici: '6.21.1', unicode: '16.0', uv: '1.50.0', uvwasi: '0.0.21', v8: '12.9.202.28-node.13', zlib: '1.3.0.1-motley-788cb3c', zstd: '1.5.6' };\nexport const NPM_VERSION = '10.9.2';\n\nexport class NodeExit extends Error { constructor(code) { super('__NodeExit:' + code); this.code = code | 0; this.__nodeExit = true; } }\n\nexport function createProcess(term, ctx) {\n const stdinHandlers = { data: [], end: [] };\n return {\n argv: ['node'],\n env: ctx.env,\n cwd: () => ctx.cwd,\n chdir: d => { ctx.cwd = d; },\n exit: code => { throw new NodeExit(code || 0); },\n platform: 'linux',\n arch: 'x64',\n version: NODE_VERSION,\n versions: { ...NODE_VERSIONS },\n pid: 1,\n ppid: 0,\n nextTick: fn => Promise.resolve().then(fn),\n stdout: { write: s => { term.write(String(s)); return true; }, isTTY: true, columns: 80, rows: 24 },\n stderr: { write: s => { term.write('\\x1b[31m' + String(s) + '\\x1b[0m'); return true; }, isTTY: true, columns: 80, rows: 24 },\n stdin: {\n on: (ev, fn) => { (stdinHandlers[ev] || (stdinHandlers[ev] = [])).push(fn); return this; },\n once: (ev, fn) => { (stdinHandlers[ev] || (stdinHandlers[ev] = [])).push(fn); },\n _feed: buf => { if (buf) for (const h of stdinHandlers.data) h(buf); for (const h of stdinHandlers.end) h(); },\n isTTY: false, setEncoding: () => {}, resume: () => {}, pause: () => {},\n },\n on: () => {},\n off: () => {},\n emit: () => {},\n hrtime: Object.assign(() => [0, 0], { bigint: () => BigInt(Math.round(performance.now() * 1e6)) }),\n exitCode: 0,\n _stdinHandlers: stdinHandlers,\n };\n}\n","package.json":"{\r\n \"name\": \"thebird\",\r\n \"version\": \"1.2.78\",\r\n \"description\": \"Anthropic SDK to Gemini streaming bridge — drop-in proxy that translates Anthropic message format and tool calls to Google Gemini\",\r\n \"scripts\": {\r\n \"start\": \"node serve.js\"\r\n },\r\n \"main\": \"index.js\",\r\n \"types\": \"index.d.ts\",\r\n \"exports\": {\r\n \".\": {\r\n \"types\": \"./index.d.ts\",\r\n \"require\": \"./index.js\",\r\n \"import\": \"./index.js\",\r\n \"default\": \"./index.js\"\r\n }\r\n },\r\n \"keywords\": [\r\n \"anthropic\",\r\n \"gemini\",\r\n \"google\",\r\n \"ai\",\r\n \"streaming\",\r\n \"proxy\",\r\n \"bridge\",\r\n \"tool-use\",\r\n \"vision\",\r\n \"multimodal\",\r\n \"router\",\r\n \"openai\",\r\n \"deepseek\",\r\n \"multi-provider\"\r\n ],\r\n \"author\": \"AnEntrypoint\",\r\n \"license\": \"MIT\",\r\n \"repository\": {\r\n \"type\": \"git\",\r\n \"url\": \"https://github.com/AnEntrypoint/thebird.git\"\r\n },\r\n \"dependencies\": {\r\n \"@anthropic-ai/sdk\": \"^0.88.0\",\r\n \"@google/genai\": \"^1.0.0\"\r\n },\r\n \"engines\": {\r\n \"node\": \">=18\"\r\n },\r\n \"devDependencies\": {\r\n \"@tailwindcss/cli\": \"^4.2.2\",\r\n \"@webcontainer/api\": \"^1.6.4\",\r\n \"@xterm/addon-fit\": \"^0.11.0\",\r\n \"@xterm/xterm\": \"^6.0.0\",\r\n \"esbuild\": \"^0.28.0\",\r\n \"htm\": \"^3.1.1\",\r\n \"tailwindcss\": \"^4.2.2\",\r\n \"webjsx\": \"^0.0.73\"\r\n }\r\n}\r\n","index.js":"const { getClient } = require('./lib/client');\r\nconst { GeminiError, withRetry } = require('./lib/errors');\r\nconst { convertMessages, convertTools, cleanSchema, extractModelId, buildConfig } = require('./lib/convert');\r\nconst { guardStream } = require('./lib/stream-guard');\r\n\r\nfunction streamGemini({ model, system, messages, tools, onStepFinish, apiKey,\r\n temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities }) {\r\n return {\r\n fullStream: createFullStream({ model, system, messages, tools, onStepFinish, apiKey, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities }),\r\n warnings: Promise.resolve([])\r\n };\r\n}\r\n\r\nasync function* createFullStream({ model, system, messages, tools, onStepFinish, apiKey, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities, streamGuard }) {\r\n const client = getClient(apiKey);\r\n const modelId = extractModelId(model);\r\n let contents = convertMessages(messages);\r\n const { config } = buildConfig({ system, tools, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities });\r\n while (true) {\r\n yield { type: 'start-step' };\r\n try {\r\n const stream = await withRetry(() => client.models.generateContentStream({ model: modelId, contents, config }));\r\n const allParts = [];\r\n for await (const chunk of guardStream(stream, streamGuard)) {\r\n for (const candidate of (chunk.candidates || [])) {\r\n for (const part of (candidate.content?.parts || [])) {\r\n allParts.push(part);\r\n if (part.text && !part.thought) yield { type: 'text-delta', textDelta: part.text };\r\n }\r\n }\r\n }\r\n const fcParts = allParts.filter(p => p.functionCall);\r\n if (fcParts.length === 0) {\r\n yield { type: 'finish-step', finishReason: 'stop' };\r\n if (onStepFinish) await onStepFinish();\r\n return;\r\n }\r\n const toolResultParts = [];\r\n for (const part of fcParts) {\r\n const name = part.functionCall.name;\r\n const args = part.functionCall.args || {};\r\n const toolId = 'toolu_' + Math.random().toString(36).slice(2, 10);\r\n yield { type: 'tool-call', toolCallId: toolId, toolName: name, args };\r\n const toolDef = tools?.[name];\r\n let result = toolDef ? null : { error: true, message: 'Tool not found: ' + name };\r\n if (toolDef?.execute) {\r\n try { result = await toolDef.execute(args, { toolCallId: toolId }); }\r\n catch (e) { result = { error: true, message: e.message }; }\r\n }\r\n yield { type: 'tool-result', toolCallId: toolId, toolName: name, args, result };\r\n toolResultParts.push({ functionResponse: { name, response: typeof result === 'string' ? { output: result } : (result || {}) } });\r\n }\r\n yield { type: 'finish-step', finishReason: 'tool-calls' };\r\n if (onStepFinish) await onStepFinish();\r\n contents.push({ role: 'model', parts: allParts });\r\n contents.push({ role: 'user', parts: toolResultParts });\r\n } catch (err) {\r\n yield { type: 'error', error: err };\r\n yield { type: 'finish-step', finishReason: 'error' };\r\n if (onStepFinish) await onStepFinish();\r\n return;\r\n }\r\n }\r\n}\r\n\r\nasync function generateGemini({ model, system, messages, tools, apiKey, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities }) {\r\n const client = getClient(apiKey);\r\n const modelId = extractModelId(model);\r\n let contents = convertMessages(messages);\r\n const { config } = buildConfig({ system, tools, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities });\r\n while (true) {\r\n const response = await withRetry(() => client.models.generateContent({ model: modelId, contents, config }));\r\n const candidate = response.candidates?.[0];\r\n if (!candidate) throw new GeminiError('No candidates returned', { retryable: false });\r\n const allParts = candidate.content?.parts || [];\r\n const fcParts = allParts.filter(p => p.functionCall);\r\n if (fcParts.length === 0) {\r\n const text = allParts.filter(p => p.text && !p.thought).map(p => p.text).join('');\r\n return { text, parts: allParts, response };\r\n }\r\n const toolResultParts = [];\r\n for (const part of fcParts) {\r\n const name = part.functionCall.name;\r\n const args = part.functionCall.args || {};\r\n const toolDef = tools?.[name];\r\n let result = toolDef ? null : { error: true, message: 'Tool not found: ' + name };\r\n if (toolDef?.execute) {\r\n try { result = await toolDef.execute(args); }\r\n catch (e) { result = { error: true, message: e.message }; }\r\n }\r\n toolResultParts.push({ functionResponse: { name, response: typeof result === 'string' ? { output: result } : (result || {}) } });\r\n }\r\n contents.push({ role: 'model', parts: allParts });\r\n contents.push({ role: 'user', parts: toolResultParts });\r\n }\r\n}\r\n\r\nconst { streamRouter, generateRouter, createRouter } = require('./lib/router-stream');\r\nconst { cloudGenerate, streamCloud, cloudStream } = require('./lib/cloud-generate');\r\nconst { ensureAuth, login: oauthLogin } = require('./lib/oauth');\r\nconst { BridgeError, AuthError, RateLimitError, TimeoutError, ContextWindowError, ContentPolicyError, ProviderError, classifyError, redactKeys } = require('./lib/errors');\r\n\r\nmodule.exports = { streamGemini, createFullStream, generateGemini, streamRouter, generateRouter, createRouter, convertMessages, convertTools, cleanSchema, GeminiError, BridgeError, AuthError, RateLimitError, TimeoutError, ContextWindowError, ContentPolicyError, ProviderError, classifyError, redactKeys, cloudGenerate, streamCloud, cloudStream, ensureAuth, oauthLogin };\r\n","server.js":"const http = require('http');\r\nconst { streamGemini, generateGemini } = require('./index.js');\r\n\r\nconst PORT = process.env.PORT || 3456;\r\nconst state = { requests: 0, errors: 0, active: 0 };\r\n\r\nconst sse = (ev, data) => `event: ${ev}\\ndata: ${JSON.stringify(data)}\\n\\n`;\r\n\r\nconst msgId = () => 'msg_' + Math.random().toString(36).slice(2, 12);\r\n\r\nasync function handleMessages(req, res) {\r\n let body = '';\r\n for await (const chunk of req) body += chunk;\r\n const { model, messages, system, stream, max_tokens } = JSON.parse(body);\r\n const apiKey = process.env.GEMINI_API_KEY;\r\n if (!apiKey) { res.writeHead(500); res.end(JSON.stringify({ error: 'GEMINI_API_KEY required' })); return; }\r\n const params = { model: model || 'gemini-2.5-flash', messages, system, apiKey, maxOutputTokens: max_tokens || 8192 };\r\n\r\n if (!stream) {\r\n const result = await generateGemini(params);\r\n res.writeHead(200, { 'Content-Type': 'application/json' });\r\n res.end(JSON.stringify({\r\n id: msgId(), type: 'message', role: 'assistant', model: params.model,\r\n content: [{ type: 'text', text: result.text }],\r\n stop_reason: 'end_turn', usage: { input_tokens: 0, output_tokens: 0 },\r\n }));\r\n return;\r\n }\r\n\r\n res.writeHead(200, {\r\n 'Content-Type': 'text/event-stream',\r\n 'Cache-Control': 'no-cache',\r\n 'Connection': 'keep-alive',\r\n });\r\n\r\n const id = msgId();\r\n res.write(sse('message_start', { type: 'message_start', message: { id, type: 'message', role: 'assistant', content: [], model: params.model, stop_reason: null, usage: { input_tokens: 0, output_tokens: 0 } } }));\r\n res.write(sse('content_block_start', { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }));\r\n res.write(sse('ping', { type: 'ping' }));\r\n\r\n let outputTokens = 0;\r\n for await (const ev of streamGemini(params).fullStream) {\r\n if (ev.type === 'text-delta') {\r\n outputTokens += ev.textDelta.length;\r\n res.write(sse('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: ev.textDelta } }));\r\n }\r\n }\r\n\r\n res.write(sse('content_block_stop', { type: 'content_block_stop', index: 0 }));\r\n res.write(sse('message_delta', { type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: outputTokens } }));\r\n res.write(sse('message_stop', { type: 'message_stop' }));\r\n res.end();\r\n}\r\n\r\nconst landingPage = () => `<!DOCTYPE html>\r\n<html><head><meta charset=\"UTF-8\"><title>thebird proxy</title>\r\n<style>\r\n body { font-family: monospace; background: #000; color: #33ff33; padding: 2ch; margin: 0; }\r\n h1 { margin-top: 0; }\r\n .stat { border: 1px solid #1a9a1a; padding: 1ch; margin: 1ch 0; }\r\n code { background: #111; padding: 0 0.5ch; }\r\n .endpoint { color: #1a9a1a; }\r\n a { color: #33ff33; }\r\n</style></head>\r\n<body>\r\n<h1>▀█▀ █░█ █▀▀ █▄▄ █ █▀█ █▀▄ — thebird proxy</h1>\r\n<div class=\"stat\">\r\n <strong>status:</strong> running on port ${PORT}<br>\r\n <strong>requests:</strong> ${state.requests} | <strong>errors:</strong> ${state.errors} | <strong>active:</strong> ${state.active}\r\n</div>\r\n<h2>endpoints</h2>\r\n<ul>\r\n <li><span class=\"endpoint\">POST /v1/messages</span> — Anthropic Messages API (translated to Gemini)</li>\r\n <li><span class=\"endpoint\">GET /debug/server</span> — <a href=\"debug/server\">live state JSON</a></li>\r\n <li><span class=\"endpoint\">GET /</span> — this landing page</li>\r\n</ul>\r\n<h2>usage</h2>\r\n<pre>curl -X POST http://localhost:${PORT}/v1/messages \\\\\r\n -H \"Content-Type: application/json\" \\\\\r\n -d '{\"model\":\"gemini-2.5-flash\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}],\"max_tokens\":100}'</pre>\r\n<p>Set <code>GEMINI_API_KEY</code> in env before sending messages.</p>\r\n</body></html>`;\r\n\r\nhttp.createServer(async (req, res) => {\r\n state.requests++;\r\n state.active++;\r\n try {\r\n if (req.method === 'GET' && (req.url === '/' || req.url === '/index.html')) {\r\n res.writeHead(200, { 'Content-Type': 'text/html' });\r\n res.end(landingPage());\r\n return;\r\n }\r\n if (req.method === 'GET' && req.url === '/debug/server') {\r\n res.writeHead(200, { 'Content-Type': 'application/json' });\r\n res.end(JSON.stringify(state));\r\n return;\r\n }\r\n if (req.method === 'POST' && req.url === '/v1/messages') {\r\n await handleMessages(req, res);\r\n return;\r\n }\r\n res.writeHead(404, { 'Content-Type': 'text/html' });\r\n res.end(`<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>404</title>\r\n<style>body{font-family:monospace;background:#000;color:#ff3333;padding:2ch;margin:0}h1{color:#33ff33}a{color:#33ff33}.box{border:1px solid #ff3333;padding:1ch;margin:1ch 0}</style></head>\r\n<body><h1>404</h1><div class=\"box\">not found: <code>${req.method} ${req.url}</code></div>\r\n<p><a href=\"./\">← back to landing page</a></p></body></html>`);\r\n } catch (err) {\r\n state.errors++;\r\n res.writeHead(500, { 'Content-Type': 'text/html' });\r\n res.end(`<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>500</title>\r\n<style>body{font-family:monospace;background:#000;color:#ff3333;padding:2ch;margin:0}pre{background:#111;padding:1ch;overflow:auto}</style></head>\r\n<body><h1>500 — server error</h1><pre>${err.message.replace(/</g, '&lt;')}</pre></body></html>`);\r\n } finally {\r\n state.active--;\r\n }\r\n}).listen(PORT, () => process.stderr.write(`thebird proxy listening on ${PORT}\\n`));\r\n","lib/capabilities.js":"const DEFAULTS = {\r\n streaming: true,\r\n toolUse: true,\r\n vision: true,\r\n systemMessage: true,\r\n jsonMode: false\r\n};\r\n\r\nfunction getCapabilities(provider) {\r\n return { ...DEFAULTS, ...(provider.capabilities || {}) };\r\n}\r\n\r\nfunction stripImageBlocks(messages) {\r\n return messages.map(msg => {\r\n if (!Array.isArray(msg.content)) return msg;\r\n const filtered = msg.content.filter(b => b.type !== 'image' && b.type !== 'image_url');\r\n if (filtered.length === 0) return { ...msg, content: [{ type: 'text', text: '[image removed - unsupported by provider]' }] };\r\n return { ...msg, content: filtered };\r\n });\r\n}\r\n\r\nfunction prependSystemAsUser(messages, system) {\r\n if (!system) return { messages, system: undefined };\r\n const text = Array.isArray(system) ? system.map(b => b.text || '').join('\\n') : system;\r\n const sysMsg = { role: 'user', content: [{ type: 'text', text }] };\r\n return { messages: [sysMsg, ...messages], system: undefined };\r\n}\r\n\r\nfunction stripUnsupported(params, caps) {\r\n const warnings = [];\r\n const result = { ...params };\r\n if (!caps.toolUse && result.tools) {\r\n delete result.tools;\r\n delete result.tool_choice;\r\n warnings.push('toolUse not supported — tools removed');\r\n }\r\n if (!caps.vision && result.messages) {\r\n result.messages = stripImageBlocks(result.messages);\r\n warnings.push('vision not supported — image blocks removed');\r\n }\r\n if (!caps.systemMessage && result.system) {\r\n const { messages, system } = prependSystemAsUser(result.messages || [], result.system);\r\n result.messages = messages;\r\n result.system = system;\r\n warnings.push('systemMessage not supported — prepended as user message');\r\n }\r\n return { params: result, warnings };\r\n}\r\n\r\nmodule.exports = { getCapabilities, stripUnsupported, DEFAULTS };\r\n","lib/circuit-breaker.js":"function createCircuitBreaker(opts = {}) {\r\n const maxFailures = opts.maxFailures || 5;\r\n const cooldownMs = opts.cooldownMs || 60000;\r\n const state = new Map();\r\n\r\n function getState(name) {\r\n if (!state.has(name)) state.set(name, { failures: 0, openedAt: 0 });\r\n return state.get(name);\r\n }\r\n\r\n function isOpen(name) {\r\n const s = getState(name);\r\n if (s.failures < maxFailures) return false;\r\n if (Date.now() - s.openedAt >= cooldownMs) {\r\n s.failures = maxFailures;\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n function recordFailure(name) {\r\n const s = getState(name);\r\n s.failures++;\r\n if (s.failures >= maxFailures) s.openedAt = Date.now();\r\n }\r\n\r\n function recordSuccess(name) {\r\n const s = getState(name);\r\n s.failures = 0;\r\n s.openedAt = 0;\r\n }\r\n\r\n return { isOpen, recordFailure, recordSuccess };\r\n}\r\n\r\nmodule.exports = { createCircuitBreaker };\r\n","lib/client.js":"const { GoogleGenAI } = require('@google/genai');\r\n\r\nlet _client = null;\r\n\r\nfunction getClient(apiKey) {\r\n if (!_client || apiKey) _client = new GoogleGenAI({ apiKey: apiKey || process.env.GEMINI_API_KEY });\r\n return _client;\r\n}\r\n\r\nmodule.exports = { getClient };\r\n","lib/cloud-generate.js":"const { convertMessages, convertTools, cleanSchema, extractModelId, buildConfig } = require('./convert');\r\nconst { ensureAuth, CODE_ASSIST_BASE, CODE_ASSIST_HEADERS } = require('./oauth');\r\nconst crypto = require('crypto');\r\n\r\nfunction buildUserAgent(model) {\r\n return `gemini-cli/0.30.0 (node; ${process.platform}) model/${model || 'unknown'}`;\r\n}\r\n\r\nasync function cloudGenerate({ model, system, messages, tools, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities, authPort }) {\r\n const tokens = await ensureAuth(authPort);\r\n const modelId = extractModelId(model);\r\n const contents = convertMessages(messages);\r\n const { config } = buildConfig({ system, tools, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities });\r\n\r\n const request = { contents };\r\n if (config.systemInstruction) request.systemInstruction = { parts: [{ text: config.systemInstruction }] };\r\n if (config.tools) request.tools = config.tools;\r\n const genConfig = {};\r\n if (config.maxOutputTokens) genConfig.maxOutputTokens = config.maxOutputTokens;\r\n if (config.temperature != null) genConfig.temperature = config.temperature;\r\n if (config.topP != null) genConfig.topP = config.topP;\r\n if (config.topK != null) genConfig.topK = config.topK;\r\n if (config.responseModalities) genConfig.responseModalities = config.responseModalities;\r\n if (Object.keys(genConfig).length) request.generationConfig = genConfig;\r\n\r\n const envelope = { project: tokens.projectId, model: modelId, user_prompt_id: crypto.randomUUID(), request };\r\n\r\n const res = await fetch(`${CODE_ASSIST_BASE}:generateContent`, {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n Authorization: `Bearer ${tokens.accessToken}`,\r\n 'User-Agent': buildUserAgent(modelId),\r\n 'x-activity-request-id': crypto.randomUUID(),\r\n ...CODE_ASSIST_HEADERS\r\n },\r\n body: JSON.stringify(envelope)\r\n });\r\n\r\n if (!res.ok) throw new Error(`Cloud generate failed (${res.status}): ${await res.text()}`);\r\n const data = await res.json();\r\n const inner = data.response || data;\r\n const candidate = inner.candidates?.[0];\r\n if (!candidate) throw new Error('No candidates returned');\r\n const allParts = candidate.content?.parts || [];\r\n const text = allParts.filter(p => p.text && !p.thought).map(p => p.text).join('');\r\n return { text, parts: allParts, response: inner };\r\n}\r\n\r\nasync function* cloudStream({ model, system, messages, tools, onStepFinish, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities, authPort }) {\r\n const tokens = await ensureAuth(authPort);\r\n const modelId = extractModelId(model);\r\n const contents = convertMessages(messages);\r\n const { config } = buildConfig({ system, tools, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities });\r\n\r\n const request = { contents };\r\n if (config.systemInstruction) request.systemInstruction = { parts: [{ text: config.systemInstruction }] };\r\n if (config.tools) request.tools = config.tools;\r\n const genConfig = {};\r\n if (config.maxOutputTokens) genConfig.maxOutputTokens = config.maxOutputTokens;\r\n if (config.temperature != null) genConfig.temperature = config.temperature;\r\n if (config.topP != null) genConfig.topP = config.topP;\r\n if (config.topK != null) genConfig.topK = config.topK;\r\n if (config.responseModalities) genConfig.responseModalities = config.responseModalities;\r\n if (Object.keys(genConfig).length) request.generationConfig = genConfig;\r\n\r\n const envelope = { project: tokens.projectId, model: modelId, user_prompt_id: crypto.randomUUID(), request };\r\n\r\n const res = await fetch(`${CODE_ASSIST_BASE}:streamGenerateContent?alt=sse`, {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n Authorization: `Bearer ${tokens.accessToken}`,\r\n 'User-Agent': buildUserAgent(modelId),\r\n 'x-activity-request-id': crypto.randomUUID(),\r\n Accept: 'text/event-stream',\r\n ...CODE_ASSIST_HEADERS\r\n },\r\n body: JSON.stringify(envelope)\r\n });\r\n\r\n if (!res.ok) throw new Error(`Cloud stream failed (${res.status}): ${await res.text()}`);\r\n\r\n yield { type: 'start-step' };\r\n const reader = res.body.getReader();\r\n const decoder = new TextDecoder();\r\n let buffer = '';\r\n\r\n while (true) {\r\n const { done, value } = await reader.read();\r\n if (done) break;\r\n buffer += decoder.decode(value, { stream: true });\r\n const lines = buffer.split('\\n');\r\n buffer = lines.pop() || '';\r\n for (const line of lines) {\r\n const trimmed = line.trim();\r\n if (!trimmed.startsWith('data:')) continue;\r\n const json = trimmed.slice(5).trim();\r\n if (!json || json === '[DONE]') continue;\r\n try {\r\n const parsed = JSON.parse(json);\r\n const inner = parsed.response || parsed;\r\n const parts = inner.candidates?.[0]?.content?.parts || [];\r\n for (const part of parts) {\r\n if (part.text && !part.thought) yield { type: 'text-delta', textDelta: part.text };\r\n if (part.inlineData) yield { type: 'image-data', inlineData: part.inlineData };\r\n }\r\n } catch {}\r\n }\r\n }\r\n yield { type: 'finish-step', finishReason: 'stop' };\r\n if (onStepFinish) await onStepFinish();\r\n}\r\n\r\nfunction streamCloud(params) {\r\n return { fullStream: cloudStream(params), warnings: Promise.resolve([]) };\r\n}\r\n\r\nmodule.exports = { cloudGenerate, cloudStream, streamCloud };\r\n","lib/config.js":"const fs = require('fs');\r\nconst path = require('path');\r\nconst os = require('os');\r\n\r\nfunction interpolateEnv(val) {\r\n if (typeof val === 'string') return val.replace(/\\$\\{([^}]+)\\}|\\$([A-Z_][A-Z0-9_]*)/g, (_, a, b) => process.env[a || b] || '');\r\n if (Array.isArray(val)) return val.map(interpolateEnv);\r\n if (val && typeof val === 'object') {\r\n const out = {};\r\n for (const [k, v] of Object.entries(val)) out[k] = interpolateEnv(v);\r\n return out;\r\n }\r\n return val;\r\n}\r\n\r\nfunction loadConfig(configPath) {\r\n const fp = configPath || process.env.THEBIRD_CONFIG || path.join(os.homedir(), '.thebird', 'config.json');\r\n try {\r\n const raw = JSON.parse(fs.readFileSync(fp, 'utf8'));\r\n return interpolateEnv(raw);\r\n } catch { return {}; }\r\n}\r\n\r\nmodule.exports = { loadConfig, interpolateEnv };\r\n","lib/convert.js":"function cleanSchema(schema) {\r\n if (!schema || typeof schema !== 'object') return schema;\r\n if (Array.isArray(schema)) return schema.map(cleanSchema);\r\n const out = {};\r\n for (const [k, v] of Object.entries(schema)) {\r\n if (k === 'additionalProperties' || k === '$schema') continue;\r\n out[k] = cleanSchema(v);\r\n }\r\n return out;\r\n}\r\n\r\nfunction convertTools(tools) {\r\n if (!tools || typeof tools !== 'object') return [];\r\n return Object.entries(tools).map(([name, t]) => ({\r\n name,\r\n description: t.description || '',\r\n parameters: cleanSchema(t.parameters?.jsonSchema || t.parameters || { type: 'object' })\r\n }));\r\n}\r\n\r\nfunction convertImageBlock(b) {\r\n // Handle inlineData: { mimeType, data } (base64)\r\n if (b.inlineData || b.type === 'image') {\r\n const src = b.inlineData || b.source;\r\n if (src?.data) return { inlineData: { mimeType: src.mimeType || 'image/jpeg', data: src.data } };\r\n if (src?.url) return { fileData: { mimeType: src.mimeType || 'image/jpeg', fileUri: src.url } };\r\n }\r\n // Handle fileData: { mimeType, fileUri }\r\n if (b.fileData) return { fileData: { mimeType: b.fileData.mimeType, fileUri: b.fileData.fileUri } };\r\n // Anthropic-style image block\r\n if (b.type === 'image' && b.source) {\r\n if (b.source.type === 'base64') return { inlineData: { mimeType: b.source.media_type, data: b.source.data } };\r\n if (b.source.type === 'url') return { fileData: { mimeType: b.source.media_type || 'image/jpeg', fileUri: b.source.url } };\r\n }\r\n return null;\r\n}\r\n\r\nfunction convertMessages(messages) {\r\n const contents = [];\r\n for (const m of messages) {\r\n const role = m.role === 'assistant' ? 'model' : 'user';\r\n if (typeof m.content === 'string') {\r\n if (m.content) contents.push({ role, parts: [{ text: m.content }] });\r\n continue;\r\n }\r\n if (Array.isArray(m.content)) {\r\n const parts = m.content.map(b => {\r\n if (b.type === 'text' && b.text) return { text: b.text };\r\n if (b.type === 'image' || b.inlineData || b.fileData) return convertImageBlock(b);\r\n if (b.type === 'tool_use') return { functionCall: { name: b.name, args: b.input || {} } };\r\n if (b.type === 'tool_result') {\r\n let resp;\r\n try { resp = typeof b.content === 'string' ? JSON.parse(b.content) : (b.content || {}); }\r\n catch { resp = { result: b.content }; }\r\n return { functionResponse: { name: b.name || 'unknown', response: resp } };\r\n }\r\n return null;\r\n }).filter(Boolean);\r\n if (parts.length) contents.push({ role, parts });\r\n }\r\n }\r\n return contents;\r\n}\r\n\r\nfunction extractModelId(model) {\r\n if (typeof model === 'string') return model;\r\n if (model?.modelId) return model.modelId;\r\n if (model?.id) return model.id;\r\n return 'gemini-2.0-flash';\r\n}\r\n\r\nfunction buildConfig({ system, tools, temperature, maxOutputTokens, topP, topK, safetySettings, responseModalities } = {}) {\r\n const geminiTools = convertTools(tools);\r\n const config = {\r\n maxOutputTokens: maxOutputTokens ?? 8192,\r\n temperature: temperature ?? 0.5,\r\n topP: topP ?? 0.95\r\n };\r\n if (topK != null) config.topK = topK;\r\n if (system) config.systemInstruction = system;\r\n if (geminiTools.length > 0) config.tools = [{ functionDeclarations: geminiTools }];\r\n if (safetySettings) config.safetySettings = safetySettings;\r\n if (responseModalities) config.responseModalities = responseModalities;\r\n return { config, geminiTools };\r\n}\r\n\r\nmodule.exports = { cleanSchema, convertTools, convertMessages, extractModelId, buildConfig, convertImageBlock };\r\n","lib/errors.js":"const KEY_PATTERNS = [\r\n /\\b(AIza[A-Za-z0-9_-]{20,})/g,\r\n /\\b(sk-[A-Za-z0-9_-]{20,})/g,\r\n /\\b(key-[A-Za-z0-9_-]{20,})/g,\r\n /((?:api[_-]?key|token|secret|authorization|bearer)[=:\\s\"']+)([A-Za-z0-9_-]{20,})/gi,\r\n];\r\n\r\nfunction redactKeys(str) {\r\n if (typeof str !== 'string') return str;\r\n let result = str;\r\n result = result.replace(KEY_PATTERNS[0], m => `...${m.slice(-4)}`);\r\n result = result.replace(KEY_PATTERNS[1], m => `...${m.slice(-4)}`);\r\n result = result.replace(KEY_PATTERNS[2], m => `...${m.slice(-4)}`);\r\n result = result.replace(KEY_PATTERNS[3], (_, prefix, val) => `${prefix}...${val.slice(-4)}`);\r\n return result;\r\n}\r\n\r\nclass BridgeError extends Error {\r\n constructor(message, { status, code, retryable = false, provider, headers } = {}) {\r\n super(redactKeys(message));\r\n this.name = 'BridgeError';\r\n this.status = status;\r\n this.code = code;\r\n this.retryable = retryable;\r\n this.provider = provider;\r\n this.headers = headers;\r\n }\r\n}\r\n\r\nclass AuthError extends BridgeError {\r\n constructor(message, opts = {}) {\r\n super(message, { ...opts, retryable: false });\r\n this.name = 'AuthError';\r\n }\r\n}\r\n\r\nclass RateLimitError extends BridgeError {\r\n constructor(message, opts = {}) {\r\n super(message, { ...opts, retryable: true });\r\n this.name = 'RateLimitError';\r\n }\r\n}\r\n\r\nclass TimeoutError extends BridgeError {\r\n constructor(message, opts = {}) {\r\n super(message, { ...opts, retryable: true });\r\n this.name = 'TimeoutError';\r\n }\r\n}\r\n\r\nclass ContextWindowError extends BridgeError {\r\n constructor(message, opts = {}) {\r\n super(message, { ...opts, retryable: false });\r\n this.name = 'ContextWindowError';\r\n }\r\n}\r\n\r\nclass ContentPolicyError extends BridgeError {\r\n constructor(message, opts = {}) {\r\n super(message, { ...opts, retryable: false });\r\n this.name = 'ContentPolicyError';\r\n }\r\n}\r\n\r\nclass ProviderError extends BridgeError {\r\n constructor(message, opts = {}) {\r\n super(message, opts);\r\n this.name = 'ProviderError';\r\n }\r\n}\r\n\r\nconst GeminiError = BridgeError;\r\n\r\nfunction classifyError(status, message, provider) {\r\n const opts = { status, provider };\r\n const msg = message || '';\r\n if (status === 401 || status === 403) return new AuthError(msg, opts);\r\n if (status === 429) return new RateLimitError(msg, opts);\r\n if (status === 408 || /timeout/i.test(msg)) return new TimeoutError(msg, opts);\r\n if (status === 413 || /context.?length|token.?limit|too.?long/i.test(msg)) return new ContextWindowError(msg, opts);\r\n if (status === 451 || /safety|blocked|content.?policy|harmful/i.test(msg)) return new ContentPolicyError(msg, opts);\r\n if (typeof status === 'number' && status >= 500) return new ProviderError(msg, { ...opts, retryable: true });\r\n return new BridgeError(msg, { ...opts, retryable: false });\r\n}\r\n\r\nfunction isRetryable(err) {\r\n if (err instanceof BridgeError) return err.retryable;\r\n const status = err?.status ?? err?.code;\r\n if (status === 429) return true;\r\n if (typeof status === 'number' && status >= 500) return true;\r\n const msg = err?.message ?? '';\r\n return /quota|rate.?limit|overloaded|unavailable/i.test(msg);\r\n}\r\n\r\nfunction parseRetryAfterHeader(err) {\r\n const raw = err?.headers?.get?.('retry-after') ?? err?.retryAfter;\r\n if (raw == null) return null;\r\n const secs = Number(raw);\r\n if (!isNaN(secs) && secs >= 0) return secs * 1000;\r\n const date = Date.parse(raw);\r\n if (!isNaN(date)) return Math.max(0, date - Date.now());\r\n return null;\r\n}\r\n\r\nfunction parseRetryDelay(err) {\r\n const headerDelay = parseRetryAfterHeader(err);\r\n if (headerDelay != null) return headerDelay;\r\n try {\r\n const body = typeof err.message === 'string' ? JSON.parse(err.message) : err.message;\r\n const details = body?.error?.details || [];\r\n const retryInfo = details.find(d => d['@type']?.includes('RetryInfo'));\r\n if (retryInfo?.retryDelay) {\r\n const secs = parseFloat(retryInfo.retryDelay);\r\n if (!isNaN(secs)) return secs * 1000;\r\n }\r\n } catch (_) {}\r\n return null;\r\n}\r\n\r\nasync function withRetry(fn, maxRetries = 3) {\r\n let lastErr;\r\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\r\n try {\r\n return await fn();\r\n } catch (err) {\r\n lastErr = err;\r\n if (!isRetryable(err) || attempt === maxRetries) throw err;\r\n const suggested = parseRetryDelay(err);\r\n const delay = suggested != null ? suggested + Math.random() * 1000 : Math.min(1000 * 2 ** attempt + Math.random() * 200, 16000);\r\n await new Promise(r => setTimeout(r, delay));\r\n }\r\n }\r\n throw lastErr;\r\n}\r\n\r\nmodule.exports = {\r\n BridgeError, GeminiError, AuthError, RateLimitError,\r\n TimeoutError, ContextWindowError, ContentPolicyError,\r\n ProviderError, classifyError, isRetryable, withRetry, redactKeys\r\n};\r\n","lib/oauth.js":"const http = require('http');\r\nconst crypto = require('crypto');\r\nconst fs = require('fs');\r\nconst path = require('path');\r\n\r\nconst CLIENT_ID = process.env.GOOGLE_OAUTH_CLIENT_ID || '';\r\nconst CLIENT_SECRET = process.env.GOOGLE_OAUTH_CLIENT_SECRET || '';\r\nconst SCOPES = 'https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile';\r\nconst AUTH_URL = 'https://accounts.google.com/o/oauth2/v2/auth';\r\nconst TOKEN_URL = 'https://oauth2.googleapis.com/token';\r\nconst CODE_ASSIST_BASE = 'https://cloudcode-pa.googleapis.com/v1internal';\r\nconst CODE_ASSIST_HEADERS = { 'X-Goog-Api-Client': 'gl-node/22.17.0', 'Client-Metadata': 'ideType=IDE_UNSPECIFIED,platform=PLATFORM_UNSPECIFIED,pluginType=GEMINI' };\r\nconst TOKEN_PATH = path.join(process.env.HOME || process.env.USERPROFILE || '.', '.thebird', 'oauth-tokens.json');\r\n\r\nfunction base64url(buf) {\r\n return buf.toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\r\n}\r\n\r\nfunction generatePkce() {\r\n const verifier = base64url(crypto.randomBytes(32));\r\n const challenge = base64url(crypto.createHash('sha256').update(verifier).digest());\r\n return { verifier, challenge };\r\n}\r\n\r\nfunction readTokens() {\r\n try { return JSON.parse(fs.readFileSync(TOKEN_PATH, 'utf8')); } catch { return null; }\r\n}\r\n\r\nfunction writeTokens(tokens) {\r\n fs.mkdirSync(path.dirname(TOKEN_PATH), { recursive: true });\r\n fs.writeFileSync(TOKEN_PATH, JSON.stringify(tokens, null, 2));\r\n}\r\n\r\nasync function refreshAccessToken(refreshToken) {\r\n const res = await fetch(TOKEN_URL, {\r\n method: 'POST',\r\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\r\n body: new URLSearchParams({ grant_type: 'refresh_token', refresh_token: refreshToken, client_id: CLIENT_ID, client_secret: CLIENT_SECRET })\r\n });\r\n if (!res.ok) throw new Error('Token refresh failed: ' + await res.text());\r\n const data = await res.json();\r\n return { accessToken: data.access_token, refreshToken: data.refresh_token || refreshToken, expiresAt: Date.now() + data.expires_in * 1000 };\r\n}\r\n\r\nasync function getValidToken() {\r\n const tokens = readTokens();\r\n if (!tokens?.refreshToken) return null;\r\n if (tokens.expiresAt && tokens.expiresAt > Date.now() + 60000) return tokens;\r\n const refreshed = await refreshAccessToken(tokens.refreshToken);\r\n const updated = { ...tokens, ...refreshed };\r\n writeTokens(updated);\r\n return updated;\r\n}\r\n\r\nasync function resolveProject(accessToken) {\r\n const res = await fetch(`${CODE_ASSIST_BASE}:loadCodeAssist`, {\r\n method: 'POST',\r\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}`, ...CODE_ASSIST_HEADERS },\r\n body: JSON.stringify({ metadata: { ideType: 'IDE_UNSPECIFIED', platform: 'PLATFORM_UNSPECIFIED', pluginType: 'GEMINI' } })\r\n });\r\n if (!res.ok) throw new Error('Failed to load Code Assist project');\r\n const data = await res.json();\r\n const proj = data.cloudaicompanionProject;\r\n if (proj) return typeof proj === 'string' ? proj : proj.id;\r\n const tier = data.allowedTiers?.find(t => t.id === 'free-tier') || data.allowedTiers?.[0];\r\n if (!tier) throw new Error('No eligible tier: ' + (data.ineligibleTiers?.[0]?.reasonMessage || 'unknown'));\r\n const obRes = await fetch(`${CODE_ASSIST_BASE}:onboardUser`, {\r\n method: 'POST',\r\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}`, ...CODE_ASSIST_HEADERS },\r\n body: JSON.stringify({ tierId: tier.id || 'legacy-tier', metadata: { ideType: 'IDE_UNSPECIFIED', platform: 'PLATFORM_UNSPECIFIED', pluginType: 'GEMINI' } })\r\n });\r\n if (!obRes.ok) throw new Error('Onboarding failed');\r\n let op = await obRes.json();\r\n for (let i = 0; i < 10 && !op.done && op.name; i++) {\r\n await new Promise(r => setTimeout(r, 5000));\r\n const pollRes = await fetch(`${CODE_ASSIST_BASE}/${op.name}`, { headers: { Authorization: `Bearer ${accessToken}`, ...CODE_ASSIST_HEADERS } });\r\n if (pollRes.ok) op = await pollRes.json();\r\n }\r\n return op.response?.cloudaicompanionProject?.id;\r\n}\r\n\r\nfunction login(port) {\r\n return new Promise((resolve, reject) => {\r\n const { verifier, challenge } = generatePkce();\r\n const state = crypto.randomBytes(32).toString('hex');\r\n const callbackUrl = `http://localhost:${port}/callback`;\r\n const url = new URL(AUTH_URL);\r\n url.searchParams.set('client_id', CLIENT_ID);\r\n url.searchParams.set('response_type', 'code');\r\n url.searchParams.set('redirect_uri', callbackUrl);\r\n url.searchParams.set('scope', SCOPES);\r\n url.searchParams.set('code_challenge', challenge);\r\n url.searchParams.set('code_challenge_method', 'S256');\r\n url.searchParams.set('state', state);\r\n url.searchParams.set('access_type', 'offline');\r\n url.searchParams.set('prompt', 'consent');\r\n\r\n const server = http.createServer(async (req, res) => {\r\n const u = new URL(req.url, `http://localhost:${port}`);\r\n if (!u.pathname.startsWith('/callback')) { res.end('waiting...'); return; }\r\n if (u.searchParams.get('state') !== state) { res.end('Invalid state'); server.close(); reject(new Error('Invalid state')); return; }\r\n const code = u.searchParams.get('code');\r\n try {\r\n const tokRes = await fetch(TOKEN_URL, {\r\n method: 'POST',\r\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\r\n body: new URLSearchParams({ client_id: CLIENT_ID, client_secret: CLIENT_SECRET, code, grant_type: 'authorization_code', redirect_uri: callbackUrl, code_verifier: verifier })\r\n });\r\n if (!tokRes.ok) throw new Error('Token exchange failed: ' + await tokRes.text());\r\n const payload = await tokRes.json();\r\n if (!payload.refresh_token) throw new Error('No refresh token — ensure prompt=consent');\r\n const projectId = await resolveProject(payload.access_token);\r\n const tokens = { accessToken: payload.access_token, refreshToken: payload.refresh_token, expiresAt: Date.now() + payload.expires_in * 1000, projectId };\r\n writeTokens(tokens);\r\n res.end('Authenticated! You can close this tab.');\r\n server.close();\r\n resolve(tokens);\r\n } catch (e) { res.end('Error: ' + e.message); server.close(); reject(e); }\r\n });\r\n server.listen(port, () => {\r\n console.log(`Open this URL to authenticate:\\n${url.toString()}\\n`);\r\n try { const { exec } = require('child_process'); exec(`start \"\" \"${url.toString()}\"`); } catch {}\r\n });\r\n });\r\n}\r\n\r\nasync function ensureAuth(port) {\r\n const existing = await getValidToken();\r\n if (existing?.accessToken && existing?.projectId) return existing;\r\n return login(port || 8585);\r\n}\r\n\r\nmodule.exports = { login, ensureAuth, getValidToken, readTokens, writeTokens, resolveProject, CODE_ASSIST_BASE, CODE_ASSIST_HEADERS };\r\n","lib/router-stream.js":"const { extractModelId } = require('./convert');\r\nconst { resolveTransformers, applyRequestTransformers } = require('./transformers');\r\nconst { loadConfig } = require('./config');\r\nconst { route } = require('./router');\r\nconst openaiProv = require('./providers/openai');\r\nconst { createCircuitBreaker } = require('./circuit-breaker');\r\nconst { getCapabilities, stripUnsupported } = require('./capabilities');\r\n\r\nfunction isGeminiProvider(p) {\r\n return p.name === 'gemini' || (p.api_base_url || '').includes('generativelanguage.googleapis.com');\r\n}\r\n\r\nfunction findProvider(providers, providerName, modelName) {\r\n if (providerName) return providers.find(p => p.name === providerName);\r\n if (modelName) return providers.find(p => (p.models || []).includes(modelName));\r\n return providers[0];\r\n}\r\n\r\nfunction buildOpenAIUrl(base) {\r\n const clean = (base || '').replace(/\\/$/g, '');\r\n return clean.includes('/completions') ? clean : clean + '/chat/completions';\r\n}\r\n\r\nfunction resolveForProvider(provider, model, customMap) {\r\n const useList = provider.transformer?.[model]?.use || provider.transformer?.use || [];\r\n return resolveTransformers(useList, customMap);\r\n}\r\n\r\nasync function* routerStream(params, resolver) {\r\n const { createFullStream } = require('../index');\r\n const { provider, actualModel, transformers, caps } = await resolver(params);\r\n const stripped = stripUnsupported(params, caps);\r\n params = stripped.params;\r\n if (isGeminiProvider(provider)) {\r\n yield* createFullStream({ ...params, model: actualModel, apiKey: provider.api_key || params.apiKey });\r\n } else {\r\n const oaiMsgs = openaiProv.convertMessages(params.messages, params.system);\r\n const oaiTools = openaiProv.convertTools(params.tools);\r\n let req = { messages: oaiMsgs, model: actualModel, max_tokens: params.maxOutputTokens || 8192, temperature: params.temperature ?? 0.5 };\r\n if (oaiTools) req.tools = oaiTools;\r\n req = applyRequestTransformers(req, transformers);\r\n yield* openaiProv.streamOpenAI({ url: buildOpenAIUrl(provider.api_base_url), apiKey: provider.api_key, headers: req._extraHeaders, body: req, tools: params.tools, onStepFinish: params.onStepFinish, streamGuard: params.streamGuard });\r\n }\r\n}\r\n\r\nfunction createRouter(config) {\r\n const { generateGemini } = require('../index');\r\n const providers = config.Providers || config.providers || [];\r\n const routerCfg = config.Router || {};\r\n const breaker = createCircuitBreaker(config.circuitBreaker);\r\n async function resolve(params) {\r\n const { providerName, modelName } = await route(params, routerCfg, config.customRouter);\r\n let provider = findProvider(providers, providerName, modelName) || providers[0];\r\n if (provider && breaker.isOpen(provider.name)) {\r\n const fallback = providers.find(p => p !== provider && !breaker.isOpen(p.name));\r\n if (fallback) provider = fallback;\r\n }\r\n if (!provider) throw new Error('[thebird] no provider configured');\r\n const actualModel = modelName || (provider.models || [])[0] || extractModelId(params.model) || 'gemini-2.0-flash';\r\n const transformers = resolveForProvider(provider, actualModel, config._transformers);\r\n const caps = getCapabilities(provider);\r\n return { provider, actualModel, transformers, caps };\r\n }\r\n return {\r\n breaker,\r\n stream(params) { return { fullStream: routerStream(params, resolve), warnings: Promise.resolve([]) }; },\r\n async generate(params) {\r\n const { provider, actualModel, transformers, caps } = await resolve(params);\r\n params = stripUnsupported(params, caps).params;\r\n if (isGeminiProvider(provider)) return generateGemini({ ...params, model: actualModel, apiKey: provider.api_key || params.apiKey });\r\n const oaiMsgs = openaiProv.convertMessages(params.messages, params.system);\r\n const oaiTools = openaiProv.convertTools(params.tools);\r\n let req = { messages: oaiMsgs, model: actualModel, max_tokens: params.maxOutputTokens || 8192, temperature: params.temperature ?? 0.5 };\r\n if (oaiTools) req.tools = oaiTools;\r\n req = applyRequestTransformers(req, transformers);\r\n return openaiProv.generateOpenAI({ url: buildOpenAIUrl(provider.api_base_url), apiKey: provider.api_key, headers: req._extraHeaders, body: req, tools: params.tools });\r\n }\r\n };\r\n}\r\n\r\nfunction streamRouter(params) {\r\n const { streamGemini } = require('../index');\r\n const config = loadConfig(params.configPath);\r\n if (!(config.Providers || config.providers)?.length) return streamGemini(params);\r\n return createRouter(config).stream(params);\r\n}\r\n\r\nasync function generateRouter(params) {\r\n const { generateGemini } = require('../index');\r\n const config = loadConfig(params.configPath);\r\n if (!(config.Providers || config.providers)?.length) return generateGemini(params);\r\n return createRouter(config).generate(params);\r\n}\r\n\r\nmodule.exports = { routerStream, createRouter, streamRouter, generateRouter, findProvider, buildOpenAIUrl, resolveForProvider, isGeminiProvider };\r\n","lib/router.js":"const { loadConfig } = require('./config');\r\n\r\nconst SUBAGENT_RE = /<CCR-SUBAGENT-MODEL>([^<]+)<\\/CCR-SUBAGENT-MODEL>/;\r\n\r\nfunction estimateTokens(messages, system) {\r\n let chars = typeof system === 'string' ? system.length : (system ? JSON.stringify(system).length : 0);\r\n for (const m of (messages || [])) {\r\n chars += typeof m.content === 'string' ? m.content.length : JSON.stringify(m.content || '').length;\r\n }\r\n return Math.ceil(chars / 4);\r\n}\r\n\r\nfunction extractSubagentModel(messages) {\r\n const first = messages?.[0];\r\n if (!first) return null;\r\n const text = typeof first.content === 'string' ? first.content :\r\n (Array.isArray(first.content) ? first.content.map(b => b.text || '').join('') : '');\r\n const m = SUBAGENT_RE.exec(text);\r\n return m ? m[1].trim() : null;\r\n}\r\n\r\nfunction parseProviderModel(str) {\r\n const idx = str.indexOf(',');\r\n if (idx === -1) return { providerName: null, modelName: str };\r\n return { providerName: str.slice(0, idx), modelName: str.slice(idx + 1) };\r\n}\r\n\r\nasync function route(params, routerCfg, customRouterFn) {\r\n const { messages, system, taskType } = params;\r\n\r\n if (customRouterFn) {\r\n const custom = await customRouterFn(params, routerCfg);\r\n if (custom) return parseProviderModel(custom);\r\n }\r\n\r\n const subagent = extractSubagentModel(messages);\r\n if (subagent) return parseProviderModel(subagent);\r\n\r\n if (taskType === 'background' && routerCfg.background) return parseProviderModel(routerCfg.background);\r\n if (taskType === 'think' && routerCfg.think) return parseProviderModel(routerCfg.think);\r\n if (taskType === 'webSearch' && routerCfg.webSearch) return parseProviderModel(routerCfg.webSearch);\r\n if (taskType === 'image' && routerCfg.image) return parseProviderModel(routerCfg.image);\r\n\r\n const threshold = routerCfg.longContextThreshold || 60000;\r\n if (routerCfg.longContext && estimateTokens(messages, system) > threshold) return parseProviderModel(routerCfg.longContext);\r\n\r\n if (routerCfg.default) return parseProviderModel(routerCfg.default);\r\n return { providerName: null, modelName: null };\r\n}\r\n\r\nmodule.exports = { route, estimateTokens, parseProviderModel };\r\n","lib/stream-guard.js":"const { TimeoutError, BridgeError } = require('./errors');\r\n\r\nasync function* guardStream(iterable, opts = {}) {\r\n const timeoutMs = opts?.chunkTimeoutMs ?? 30000;\r\n const maxRepeats = opts?.maxRepeats ?? 100;\r\n let lastChunk = null;\r\n let repeatCount = 0;\r\n for await (const chunk of raceTimeout(iterable, timeoutMs)) {\r\n const key = JSON.stringify(chunk);\r\n if (key === lastChunk && key !== '{}' && key !== 'null') {\r\n repeatCount++;\r\n if (repeatCount >= maxRepeats) {\r\n throw new BridgeError(`Same chunk repeated ${maxRepeats} times`, { retryable: false });\r\n }\r\n } else {\r\n lastChunk = key;\r\n repeatCount = 1;\r\n }\r\n yield chunk;\r\n }\r\n}\r\n\r\nasync function* raceTimeout(iterable, ms) {\r\n const iter = iterable[Symbol.asyncIterator]();\r\n while (true) {\r\n const result = await Promise.race([\r\n iter.next(),\r\n new Promise((_, reject) => setTimeout(() => reject(new TimeoutError(`Stream chunk timeout after ${ms}ms`)), ms))\r\n ]);\r\n if (result.done) return;\r\n yield result.value;\r\n }\r\n}\r\n\r\nmodule.exports = { guardStream };\r\n","lib/transformers.js":"function removeCacheControl(obj) {\r\n if (!obj || typeof obj !== 'object') return obj;\r\n if (Array.isArray(obj)) return obj.map(removeCacheControl);\r\n const out = {};\r\n for (const [k, v] of Object.entries(obj)) {\r\n if (k === 'cache_control') continue;\r\n out[k] = removeCacheControl(v);\r\n }\r\n return out;\r\n}\r\n\r\nconst BUILT_IN = {\r\n cleancache: {\r\n request(req) { return { ...req, messages: removeCacheControl(req.messages), system: removeCacheControl(req.system) }; }\r\n },\r\n deepseek: {\r\n request(req) {\r\n const r = removeCacheControl(req);\r\n if (r.system && typeof r.system !== 'string') {\r\n r.system = (Array.isArray(r.system) ? r.system : [r.system]).map(b => b.text || '').join('\\n');\r\n }\r\n return r;\r\n }\r\n },\r\n openrouter: {\r\n options: {},\r\n request(req, opts) {\r\n const headers = { 'HTTP-Referer': 'https://github.com/AnEntrypoint/thebird', 'X-Title': 'thebird', ...(opts || {}).headers };\r\n if ((opts || {}).provider) req = { ...req, provider: (opts || {}).provider };\r\n return { ...req, _extraHeaders: { ...(req._extraHeaders || {}), ...headers } };\r\n }\r\n },\r\n maxtoken: {\r\n request(req, opts) { return { ...req, max_tokens: (opts || {}).max_tokens || req.max_tokens }; }\r\n },\r\n tooluse: {\r\n request(req) {\r\n if (req.tools && req.tools.length > 0) return { ...req, tool_choice: { type: 'required' } };\r\n return req;\r\n }\r\n },\r\n reasoning: {\r\n request(req) { return req; },\r\n response(res) {\r\n if (!res.choices) return res;\r\n return {\r\n ...res,\r\n choices: res.choices.map(c => {\r\n if (!c.message) return c;\r\n const msg = { ...c.message };\r\n if (msg.reasoning_content) { msg._reasoning = msg.reasoning_content; delete msg.reasoning_content; }\r\n return { ...c, message: msg };\r\n })\r\n };\r\n }\r\n },\r\n sampling: {\r\n request(req) {\r\n const r = { ...req };\r\n delete r.top_k;\r\n delete r.repetition_penalty;\r\n return r;\r\n }\r\n },\r\n groq: {\r\n request(req) {\r\n const r = { ...req };\r\n delete r.top_k;\r\n return r;\r\n }\r\n }\r\n};\r\n\r\nfunction resolveTransformers(useList, customMap) {\r\n if (!useList) return [];\r\n return useList.map(entry => {\r\n const name = Array.isArray(entry) ? entry[0] : entry;\r\n const opts = Array.isArray(entry) ? entry[1] : undefined;\r\n const t = (customMap && customMap[name]) || BUILT_IN[name];\r\n if (!t) { console.warn('[thebird] unknown transformer:', name); return null; }\r\n return { transformer: t, opts };\r\n }).filter(Boolean);\r\n}\r\n\r\nfunction applyRequestTransformers(req, transformers) {\r\n return transformers.reduce((r, { transformer, opts }) => transformer.request ? transformer.request(r, opts) : r, req);\r\n}\r\n\r\nfunction applyResponseTransformers(res, transformers) {\r\n return transformers.reduce((r, { transformer, opts }) => transformer.response ? transformer.response(r, opts) : r, res);\r\n}\r\n\r\nmodule.exports = { resolveTransformers, applyRequestTransformers, applyResponseTransformers, BUILT_IN };\r\n","lib/providers/openai.js":"const { GeminiError } = require('../errors');\r\nconst { guardStream } = require('../stream-guard');\r\n\r\nfunction convertMessages(messages, system) {\r\n const result = [];\r\n if (system) result.push({ role: 'system', content: typeof system === 'string' ? system : JSON.stringify(system) });\r\n for (const m of messages) {\r\n if (typeof m.content === 'string') { result.push({ role: m.role, content: m.content }); continue; }\r\n if (!Array.isArray(m.content)) continue;\r\n const toolCalls = m.content.filter(b => b.type === 'tool_use');\r\n const toolResults = m.content.filter(b => b.type === 'tool_result');\r\n if (toolResults.length) {\r\n for (const b of toolResults) {\r\n const c = typeof b.content === 'string' ? b.content : JSON.stringify(b.content || '');\r\n result.push({ role: 'tool', tool_call_id: b.tool_use_id || b.id || b.name, content: c });\r\n }\r\n continue;\r\n }\r\n const textParts = m.content.filter(b => b.type === 'text').map(b => b.text).join('');\r\n if (toolCalls.length) {\r\n result.push({ role: 'assistant', content: textParts || null,\r\n tool_calls: toolCalls.map(b => ({ id: b.id || ('call_' + Math.random().toString(36).slice(2,8)), type: 'function',\r\n function: { name: b.name, arguments: JSON.stringify(b.input || {}) } })) });\r\n } else {\r\n result.push({ role: m.role, content: textParts });\r\n }\r\n }\r\n return result;\r\n}\r\n\r\nfunction convertTools(tools) {\r\n if (!tools || typeof tools !== 'object') return undefined;\r\n const list = Object.entries(tools).map(([name, t]) => ({\r\n type: 'function', function: { name, description: t.description || '',\r\n parameters: t.parameters?.jsonSchema || t.parameters || { type: 'object' } }\r\n }));\r\n return list.length ? list : undefined;\r\n}\r\n\r\nasync function callOpenAI({ url, apiKey, headers, body }) {\r\n const res = await fetch(url, { method: 'POST',\r\n headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}`, ...(headers || {}) },\r\n body: JSON.stringify(body) });\r\n if (!res.ok) { const t = await res.text(); throw new GeminiError(t, { status: res.status, retryable: res.status === 429 || res.status >= 500, headers: res.headers }); }\r\n return res;\r\n}\r\n\r\nasync function* readerIterable(reader) {\r\n const dec = new TextDecoder();\r\n while (true) {\r\n const { done, value } = await reader.read();\r\n if (done) return;\r\n yield dec.decode(value, { stream: true });\r\n }\r\n}\r\n\r\nasync function* streamOpenAI({ url, apiKey, headers, body, tools, onStepFinish, streamGuard }) {\r\n while (true) {\r\n yield { type: 'start-step' };\r\n const res = await callOpenAI({ url, apiKey, headers, body: { ...body, stream: true } });\r\n const reader = res.body.getReader();\r\n let buf = '', toolCallsMap = {};\r\n try {\r\n for await (const text of guardStream(readerIterable(reader), streamGuard)) {\r\n buf += text;\r\n const lines = buf.split('\\n');\r\n buf = lines.pop();\r\n for (const line of lines) {\r\n if (!line.startsWith('data: ')) continue;\r\n const d = line.slice(6).trim();\r\n if (d === '[DONE]') break;\r\n let chunk; try { chunk = JSON.parse(d); } catch { continue; }\r\n const delta = chunk.choices?.[0]?.delta;\r\n if (!delta) continue;\r\n if (delta.content) yield { type: 'text-delta', textDelta: delta.content };\r\n if (delta.tool_calls) {\r\n for (const tc of delta.tool_calls) {\r\n const idx = tc.index ?? 0;\r\n if (!toolCallsMap[idx]) toolCallsMap[idx] = { id: tc.id || '', name: '', args: '' };\r\n if (tc.id) toolCallsMap[idx].id = tc.id;\r\n if (tc.function?.name) toolCallsMap[idx].name += tc.function.name;\r\n if (tc.function?.arguments) toolCallsMap[idx].args += tc.function.arguments;\r\n }\r\n }\r\n }\r\n }\r\n } finally { reader.releaseLock(); }\r\n\r\n const pending = Object.values(toolCallsMap);\r\n if (!pending.length) {\r\n yield { type: 'finish-step', finishReason: 'stop' };\r\n if (onStepFinish) await onStepFinish();\r\n return;\r\n }\r\n const toolResultMsgs = [];\r\n for (const tc of pending) {\r\n let args; try { args = JSON.parse(tc.args || '{}'); } catch { args = {}; }\r\n const toolDef = tools?.[tc.name];\r\n let result = toolDef ? null : { error: true, message: 'Tool not found: ' + tc.name };\r\n if (toolDef?.execute) try { result = await toolDef.execute(args, { toolCallId: tc.id }); } catch(e) { result = { error: true, message: e.message }; }\r\n yield { type: 'tool-call', toolCallId: tc.id, toolName: tc.name, args };\r\n yield { type: 'tool-result', toolCallId: tc.id, toolName: tc.name, args, result };\r\n toolResultMsgs.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(result ?? '') });\r\n }\r\n yield { type: 'finish-step', finishReason: 'tool-calls' };\r\n if (onStepFinish) await onStepFinish();\r\n body = { ...body, messages: [...body.messages,\r\n { role: 'assistant', content: null, tool_calls: pending.map(tc => ({ id: tc.id, type: 'function', function: { name: tc.name, arguments: tc.args } })) },\r\n ...toolResultMsgs\r\n ]};\r\n toolCallsMap = {};\r\n }\r\n}\r\n\r\nasync function generateOpenAI({ url, apiKey, headers, body, tools }) {\r\n while (true) {\r\n const res = await callOpenAI({ url, apiKey, headers, body: { ...body, stream: false } });\r\n const data = await res.json();\r\n const msg = data.choices?.[0]?.message;\r\n if (!msg) throw new GeminiError('No message in response', { retryable: false });\r\n if (!msg.tool_calls?.length) return { text: msg.content || '', response: data };\r\n const toolResultMsgs = [];\r\n for (const tc of msg.tool_calls) {\r\n let args; try { args = JSON.parse(tc.function?.arguments || '{}'); } catch { args = {}; }\r\n const toolDef = tools?.[tc.function?.name];\r\n let result = toolDef ? null : { error: true, message: 'Tool not found: ' + tc.function?.name };\r\n if (toolDef?.execute) try { result = await toolDef.execute(args); } catch(e) { result = { error: true, message: e.message }; }\r\n toolResultMsgs.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(result ?? '') });\r\n }\r\n body = { ...body, messages: [...body.messages, msg, ...toolResultMsgs] };\r\n }\r\n}\r\n\r\nmodule.exports = { streamOpenAI, generateOpenAI, convertMessages, convertTools };\r\n","shell-builtins.js":"import { makeTextBuiltins } from './shell-builtins-text.js';\nimport { makeExtraBuiltins } from './shell-builtins-extra.js';\nimport { makeUtilBuiltins } from './shell-builtins-util.js';\n\nexport function resolvePath(cwd, p) {\n if (!p || p === '~') return '/';\n if (p.startsWith('~/')) p = '/' + p.slice(2);\n if (!p.startsWith('/')) p = cwd.replace(/\\/$/, '') + '/' + p;\n const parts = [];\n for (const s of p.split('/')) {\n if (s === '..') parts.pop();\n else if (s && s !== '.') parts.push(s);\n }\n return '/' + parts.join('/');\n}\n\nconst toKey = p => p.replace(/^\\//, '');\nconst snap = () => window.__debug.idbSnapshot || {};\nconst persist = () => window.__debug.idbPersist?.();\nconst previewWrite = () => window.__debug.shell?.onPreviewWrite?.();\n\nfunction listDir(prefix) {\n const pLen = prefix ? prefix.length + 1 : 0;\n const files = new Set(), dirs = new Set();\n for (const k of Object.keys(snap())) {\n if (prefix && !k.startsWith(prefix + '/') && k !== prefix) continue;\n if (!prefix && !k.includes('/')) { files.add(k); continue; }\n const rest = k.slice(pLen);\n const slash = rest.indexOf('/');\n if (slash === -1) files.add(rest);\n else dirs.add(rest.slice(0, slash));\n }\n return { files: [...files].filter(f => f !== '.keep').sort(), dirs: [...dirs].sort() };\n}\n\nfunction removeRecursive(prefix) {\n const s = snap();\n let count = 0;\n for (const k of Object.keys(s)) {\n if (k === prefix || k.startsWith(prefix + '/')) { delete s[k]; count++; }\n }\n return count;\n}\n\nexport function makeBuiltins(ctx, actor, invokeBuiltin) {\n const w = s => ctx.term.write(s);\n const wl = s => w(s + '\\r\\n');\n const readFile = p => {\n const c = snap()[toKey(resolvePath(ctx.cwd, p))];\n if (c == null) throw new Error(p + ': No such file or directory');\n return c;\n };\n const writeFile = (p, content) => {\n const k = toKey(resolvePath(ctx.cwd, p));\n snap()[k] = content;\n persist();\n previewWrite();\n };\n const text = makeTextBuiltins(ctx, readFile, writeFile);\n const extra = makeExtraBuiltins(ctx, readFile, writeFile);\n const util = makeUtilBuiltins(ctx, readFile, writeFile);\n const b = {\n ls: args => {\n const flags = args.filter(a => a.startsWith('-')).join('');\n const showHidden = flags.includes('a');\n const longFmt = flags.includes('l');\n const targets = args.filter(a => !a.startsWith('-'));\n const target = targets[0] || '';\n const { files, dirs } = listDir(toKey(resolvePath(ctx.cwd, target)));\n const entries = [...dirs.map(d => ({ name: d, dir: true })), ...files.map(f => ({ name: f, dir: false }))]\n .filter(e => showHidden || !e.name.startsWith('.'));\n if (!entries.length) return;\n if (longFmt) {\n for (const e of entries) {\n const full = toKey(resolvePath(ctx.cwd, target + '/' + e.name));\n const size = e.dir ? 0 : (snap()[full]?.length || 0);\n wl(`${e.dir ? 'd' : '-'}rwxr-xr-x ${String(size).padStart(8)} ${e.name}${e.dir ? '/' : ''}`);\n }\n } else {\n wl(entries.map(e => e.dir ? `\\x1b[34m${e.name}/\\x1b[0m` : e.name).join(' '));\n }\n },\n cat: args => {\n if (!args.length) throw new Error('cat: missing file operand');\n const stdinFirst = args[0].includes('\\n') || args[0].includes('\\r');\n const stdin = stdinFirst ? args[0] : null;\n const files = stdinFirst ? args.slice(1) : args;\n if (stdin !== null && !files.length) { w(stdin); return; }\n for (const f of files) w(readFile(f));\n },\n echo: args => {\n const escape = args[0] === '-e';\n const noNewline = args[0] === '-n' || (escape && args[1] === '-n') || (args[0] === '-n' && args[1] === '-e');\n let txt = args.filter(a => a !== '-e' && a !== '-n').join(' ');\n if (escape) txt = txt.replace(/\\\\n/g, '\\n').replace(/\\\\t/g, '\\t').replace(/\\\\r/g, '\\r').replace(/\\\\\\\\/g, '\\\\');\n w(txt.replace(/\\n/g, '\\r\\n') + (noNewline ? '' : '\\r\\n'));\n },\n pwd: () => wl(ctx.cwd),\n cd: args => {\n const target = args[0];\n if (target === '-') { const prev = ctx.prevCwd || '/'; ctx.prevCwd = ctx.cwd; ctx.cwd = prev; wl(ctx.cwd); return; }\n const next = resolvePath(ctx.cwd, target || '~');\n ctx.prevCwd = ctx.cwd;\n ctx.cwd = next;\n },\n mkdir: args => {\n for (const p of args.filter(a => !a.startsWith('-'))) snap()[toKey(resolvePath(ctx.cwd, p)) + '/.keep'] = '';\n persist();\n },\n rm: args => {\n const recursive = args.some(a => a === '-r' || a === '-rf' || a === '-fr' || a === '-R');\n const force = args.some(a => a.includes('f'));\n for (const f of args.filter(a => !a.startsWith('-'))) {\n const k = toKey(resolvePath(ctx.cwd, f));\n if (k in snap()) { delete snap()[k]; continue; }\n if (recursive) { const n = removeRecursive(k); if (n === 0 && !force) throw new Error(f + ': No such file or directory'); continue; }\n if (!force) throw new Error(f + ': No such file or directory');\n }\n persist();\n },\n cp: args => {\n const recursive = args.some(a => a === '-r' || a === '-R');\n const [src, dst] = args.filter(a => !a.startsWith('-'));\n if (!src || !dst) throw new Error('cp: missing operand');\n const srcK = toKey(resolvePath(ctx.cwd, src)), dstK = toKey(resolvePath(ctx.cwd, dst));\n const s = snap();\n if (srcK in s) { s[dstK] = s[srcK]; persist(); return; }\n if (!recursive) throw new Error(src + ': No such file or directory');\n let n = 0;\n for (const k of Object.keys(s)) { if (k === srcK || k.startsWith(srcK + '/')) { s[dstK + k.slice(srcK.length)] = s[k]; n++; } }\n if (!n) throw new Error(src + ': No such file or directory');\n persist();\n },\n mv: args => {\n const [src, dst] = args.filter(a => !a.startsWith('-'));\n if (!src || !dst) throw new Error('mv: missing operand');\n const srcK = toKey(resolvePath(ctx.cwd, src)), dstK = toKey(resolvePath(ctx.cwd, dst));\n const s = snap();\n if (srcK in s) { s[dstK] = s[srcK]; delete s[srcK]; persist(); return; }\n let n = 0;\n for (const k of Object.keys(s)) { if (k === srcK || k.startsWith(srcK + '/')) { s[dstK + k.slice(srcK.length)] = s[k]; delete s[k]; n++; } }\n if (!n) throw new Error(src + ': No such file or directory');\n persist();\n },\n touch: args => { for (const f of args) { const k = toKey(resolvePath(ctx.cwd, f)); if (!(k in snap())) snap()[k] = ''; } persist(); },\n head: args => {\n const n = args[0] === '-n' ? parseInt(args[1], 10) : 10;\n const rest = args[0] === '-n' ? args.slice(2) : args;\n const stdinFirst = rest.length > 0 && rest[0].includes('\\n');\n const stdin = stdinFirst ? rest[0] : null;\n const files = stdinFirst ? rest.slice(1) : rest;\n const targets = files.length ? files : [null];\n for (const f of targets) wl((f ? readFile(f) : stdin || '').split('\\n').slice(0, n).join('\\r\\n'));\n },\n tail: args => {\n const n = args[0] === '-n' ? parseInt(args[1], 10) : 10;\n const rest = args[0] === '-n' ? args.slice(2) : args;\n const stdinFirst = rest.length > 0 && rest[0].includes('\\n');\n const stdin = stdinFirst ? rest[0] : null;\n const files = stdinFirst ? rest.slice(1) : rest;\n const targets = files.length ? files : [null];\n for (const f of targets) wl((f ? readFile(f) : stdin || '').split('\\n').slice(-n).join('\\r\\n'));\n },\n wc: args => {\n const stdinFirst = args.length > 0 && args[0].includes('\\n');\n const stdin = stdinFirst ? args[0] : null;\n const files = stdinFirst ? args.slice(1) : args;\n const pairs = files.length ? files.map(f => [f, readFile(f)]) : [['', stdin || '']];\n for (const [name, c] of pairs) {\n const lines = c.split('\\n').length;\n wl(`${String(lines).padStart(8)}${String(c.split(/\\s+/).filter(Boolean).length).padStart(8)}${String(c.length).padStart(8)}${name ? ' ' + name : ''}`);\n }\n },\n ...text,\n ...extra,\n ...util,\n which: args => text.which(args, b),\n exit: (args, ac) => text.exit(args, ac || actor),\n };\n b.readFile = readFile;\n b.writeFile = writeFile;\n return b;\n}\n","shell-npm.js":"import { NPM_VERSION } from './shell-node-modules.js';\n\nconst toKey = p => p.replace(/^\\//, '');\nconst snap = () => window.__debug.idbSnapshot || {};\nconst persist = () => window.__debug.idbPersist?.();\n\nfunction resolvePkgJson(cwd, ctx) {\n const path = cwd.replace(/\\/$/, '') + '/package.json';\n const raw = snap()[toKey(path)];\n if (!raw) throw new Error('npm: no package.json in ' + cwd);\n try { return { path, data: JSON.parse(raw) }; } catch (e) { throw new Error('npm: invalid package.json: ' + e.message); }\n}\n\nasync function installOne(pkg, version, term) {\n const spec = version && version !== 'latest' ? pkg + '@' + version.replace(/^[\\^~]/, '') : pkg;\n const url = 'https://esm.sh/' + spec + '?bundle&target=es2022';\n term.write(' → ' + spec + '\\r\\n');\n await import(url);\n const stubPath = 'node_modules/' + pkg + '/index.js';\n snap()[stubPath] = '// esm.sh async stub\\nawait import(' + JSON.stringify(url) + ');';\n const meta = { name: pkg, version: version || 'latest', _resolved: url, _from: 'esm.sh' };\n snap()['node_modules/' + pkg + '/package.json'] = JSON.stringify(meta, null, 2);\n persist();\n}\n\nfunction writePkgJson(pkgPath, data) {\n snap()[toKey(pkgPath)] = JSON.stringify(data, null, 2);\n persist();\n}\n\nfunction injectNpmEnv(ctx, data, scriptName) {\n const prev = {};\n const set = (k, v) => { prev[k] = ctx.env[k]; ctx.env[k] = v; };\n set('npm_lifecycle_event', scriptName);\n set('npm_package_name', data.name || '');\n set('npm_package_version', data.version || '');\n set('npm_config_user_agent', 'npm/' + NPM_VERSION + ' node/v23.10.0');\n set('NODE_ENV', ctx.env.NODE_ENV || 'development');\n for (const [k, v] of Object.entries(data.scripts || {})) set('npm_package_scripts_' + k.replace(/[^a-z0-9_]/gi, '_'), v);\n return () => { for (const k of Object.keys(prev)) { if (prev[k] === undefined) delete ctx.env[k]; else ctx.env[k] = prev[k]; } };\n}\n\nexport function makeNpm(ctx) {\n const w = s => ctx.term.write(s);\n const wl = s => w(s + '\\r\\n');\n\n async function cmdInstall(args) {\n const saveDev = args.includes('--save-dev') || args.includes('-D');\n const noSave = args.includes('--no-save');\n const pkgs = args.filter(a => !a.startsWith('-'));\n if (!pkgs.length) {\n const { data } = resolvePkgJson(ctx.cwd, ctx);\n const all = { ...(data.dependencies || {}), ...(data.devDependencies || {}), ...(data.peerDependencies || {}) };\n const entries = Object.entries(all);\n if (!entries.length) { wl('up to date, 0 packages'); return; }\n wl('installing ' + entries.length + ' packages from package.json');\n for (const [name, ver] of entries) await installOne(name, ver, ctx.term);\n wl('added ' + entries.length + ' package' + (entries.length === 1 ? '' : 's'));\n return;\n }\n for (const spec of pkgs) {\n const m = spec.match(/^(@?[^@]+?)(?:@(.+))?$/);\n const [, name, version] = m;\n await installOne(name, version, ctx.term);\n }\n if (!noSave) {\n const { path: pkgPath, data } = resolvePkgJson(ctx.cwd, ctx);\n const target = saveDev ? 'devDependencies' : 'dependencies';\n data[target] = data[target] || {};\n for (const spec of pkgs) {\n const m = spec.match(/^(@?[^@]+?)(?:@(.+))?$/);\n data[target][m[1]] = m[2] || 'latest';\n }\n writePkgJson(pkgPath, data);\n }\n wl('added ' + pkgs.length + ' package' + (pkgs.length === 1 ? '' : 's'));\n }\n\n function cmdUninstall(args) {\n const pkgs = args.filter(a => !a.startsWith('-'));\n if (!pkgs.length) throw new Error('npm uninstall <pkg>');\n for (const pkg of pkgs) {\n const s = snap();\n let n = 0;\n for (const k of Object.keys(s)) {\n if (k === 'node_modules/' + pkg + '/index.js' || k.startsWith('node_modules/' + pkg + '/')) { delete s[k]; n++; }\n }\n wl(n ? 'removed ' + pkg : pkg + ' not installed');\n }\n const { path: pkgPath, data } = resolvePkgJson(ctx.cwd, ctx);\n for (const pkg of pkgs) { delete data.dependencies?.[pkg]; delete data.devDependencies?.[pkg]; }\n writePkgJson(pkgPath, data);\n persist();\n }\n\n function cmdList(args) {\n const filter = args.find(a => !a.startsWith('-'));\n const s = snap();\n const installed = Object.keys(s).filter(k => k.match(/^node_modules\\/[^/]+\\/package\\.json$/) || k.match(/^node_modules\\/@[^/]+\\/[^/]+\\/package\\.json$/));\n try {\n const { data } = resolvePkgJson(ctx.cwd, ctx);\n wl(data.name + '@' + (data.version || '1.0.0') + ' ' + ctx.cwd);\n } catch { wl('(no package.json)'); }\n for (const k of installed) {\n const name = k.replace(/^node_modules\\//, '').replace(/\\/package\\.json$/, '');\n if (filter && !name.includes(filter)) continue;\n const pj = JSON.parse(s[k]);\n wl('├── ' + name + '@' + (pj.version || 'latest'));\n }\n }\n\n async function cmdRun(args) {\n const [scriptName, ...rest] = args;\n const { data } = resolvePkgJson(ctx.cwd, ctx);\n if (!scriptName) {\n wl('Lifecycle scripts included in ' + (data.name || 'package') + '@' + (data.version || '') + ':');\n for (const [n, s] of Object.entries(data.scripts || {})) wl(' ' + n + '\\r\\n ' + s);\n return null;\n }\n const cmd = data.scripts?.[scriptName];\n if (!cmd) throw new Error('npm: Missing script: \"' + scriptName + '\"');\n const pre = data.scripts?.['pre' + scriptName];\n const post = data.scripts?.['post' + scriptName];\n const restore = injectNpmEnv(ctx, data, scriptName);\n try {\n const chain = [];\n if (pre) chain.push({ name: 'pre' + scriptName, cmd: pre });\n chain.push({ name: scriptName, cmd: cmd + (rest.length ? ' ' + rest.join(' ') : '') });\n if (post) chain.push({ name: 'post' + scriptName, cmd: post });\n return { runInShell: null, npmChain: chain, pkgName: data.name || 'package', pkgVersion: data.version || '' };\n } finally { queueMicrotask(restore); }\n }\n\n function cmdInit(args) {\n const yes = args.includes('-y') || args.includes('--yes');\n if (!yes) { wl('npm init -y — use -y for non-interactive'); return; }\n const pj = { name: ctx.cwd.split('/').filter(Boolean).pop() || 'project', version: '1.0.0', main: 'index.js', scripts: { start: 'node index.js', test: 'echo \"Error: no test specified\" && exit 1' }, dependencies: {} };\n writePkgJson(ctx.cwd.replace(/\\/$/, '') + '/package.json', pj);\n wl('Wrote to ' + ctx.cwd.replace(/\\/$/, '') + '/package.json');\n }\n\n async function cmdExec(args) {\n const pkg = args[0];\n if (!pkg) throw new Error('npx: package required');\n const s = snap();\n if (!s['node_modules/' + pkg + '/index.js']) await installOne(pkg, null, ctx.term);\n const binPath = 'node_modules/.bin/' + pkg;\n if (s[binPath]) return { runInShell: 'node /' + binPath + (args.length > 1 ? ' ' + args.slice(1).join(' ') : '') };\n return { runInShell: 'node -e \"require(\\'' + pkg + '\\')\"' };\n }\n\n return async function npm(args) {\n const sub = args[0];\n const rest = args.slice(1);\n if (sub === 'install' || sub === 'i' || sub === 'add') return cmdInstall(rest);\n if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') return cmdUninstall(rest);\n if (sub === 'ls' || sub === 'list') return cmdList(rest);\n if (sub === 'run' || sub === 'run-script') return cmdRun(rest);\n if (sub === 'start') return cmdRun(['start', ...rest]);\n if (sub === 'test' || sub === 't') return cmdRun(['test', ...rest]);\n if (sub === 'init' || sub === 'create') return cmdInit(rest);\n if (sub === 'exec' || sub === 'x') return cmdExec(rest);\n if (sub === '--version' || sub === '-v') { wl(NPM_VERSION); return; }\n if (sub === 'prefix') { wl(ctx.cwd); return; }\n if (sub === 'root') { wl(ctx.cwd.replace(/\\/$/, '') + '/node_modules'); return; }\n if (sub === 'view' || sub === 'info' || sub === 'show') { const p = rest[0]; wl(p + ' — use esm.sh to inspect'); return; }\n throw new Error('npm: unknown command \"' + sub + '\"');\n };\n}\n\nexport function makeNpx(npmCmd) {\n return args => npmCmd(['exec', ...args]);\n}\n","shell-parser.js":"export function tokenize(line) {\n const tokens = [];\n let cur = '';\n let quote = null;\n let escape = false;\n for (let i = 0; i < line.length; i++) {\n const c = line[i];\n if (escape) {\n if (quote === '\"' && !'\"\\\\`$'.includes(c)) cur += '\\\\';\n cur += c; escape = false; continue;\n }\n if (c === '\\\\' && quote !== \"'\") { escape = true; continue; }\n if (quote) {\n if (c === quote) { quote = null; continue; }\n cur += c;\n continue;\n }\n if (c === '\"' || c === \"'\") { quote = c; continue; }\n if (/\\s/.test(c)) {\n if (cur) { tokens.push(cur); cur = ''; }\n continue;\n }\n cur += c;\n }\n if (cur) tokens.push(cur);\n return tokens;\n}\n\nexport function expand(token, env, lastExitCode, argv) {\n return token.replace(/\\$\\(([^)]+)\\)|\\$\\{?(\\?|#|@|[0-9]|[A-Za-z_][A-Za-z0-9_]*)\\}?/g, (match, sub, name) => {\n if (sub) return match;\n if (name === '?') return String(lastExitCode ?? 0);\n if (name === '#') return String((argv || []).length);\n if (name === '@') return (argv || []).join(' ');\n if (name === '0') return (argv || [])[0] || '';\n if (/^[1-9]$/.test(name)) return (argv || [])[parseInt(name)] || '';\n return env[name] ?? '';\n });\n}\n\nexport function expandCmdSub(token, env, lastExitCode, runCapture, argv) {\n if (!token.includes('$(')) return expand(token, env, lastExitCode, argv);\n return token.replace(/\\$\\(([^)]+)\\)/g, (_, cmd) => runCapture ? runCapture(cmd) : '');\n}\n\nexport function parsePipeline(line) {\n const chunks = splitTopLevel(line, ['&&', '||', ';']);\n return chunks;\n}\n\nexport function splitTopLevel(line, seps) {\n const cmds = [];\n const separators = [];\n let cur = '';\n let quote = null;\n let escape = false;\n for (let i = 0; i < line.length; i++) {\n const c = line[i];\n if (escape) { cur += c; escape = false; continue; }\n if (c === '\\\\' && quote !== \"'\") { cur += c; escape = true; continue; }\n if (quote) {\n if (c === quote) quote = null;\n cur += c;\n continue;\n }\n if (c === '\"' || c === \"'\") { quote = c; cur += c; continue; }\n let matched = null;\n for (const sep of seps) if (line.startsWith(sep, i)) { matched = sep; break; }\n if (matched) {\n cmds.push(cur.trim());\n separators.push(matched);\n cur = '';\n i += matched.length - 1;\n continue;\n }\n cur += c;\n }\n if (cur.trim()) cmds.push(cur.trim());\n return cmds.map((cmd, i) => ({ cmd, sep: separators[i - 1] || null }));\n}\n\nexport function parseRedirects(tokens) {\n const out = { args: [], stdout: null, stdoutAppend: false, stdin: null };\n for (let i = 0; i < tokens.length; i++) {\n const t = tokens[i];\n if (t === '>' || t === '>>') { out.stdout = tokens[++i]; out.stdoutAppend = t === '>>'; continue; }\n if (t === '<') { out.stdin = tokens[++i]; continue; }\n out.args.push(t);\n }\n return out;\n}\n\nexport function parsePipes(line) {\n return splitTopLevel(line, ['|']).map(p => p.cmd);\n}\n\nexport function globToRe(pattern) {\n let re = '';\n let i = 0;\n while (i < pattern.length) {\n const c = pattern[i];\n if (c === '[') {\n const close = pattern.indexOf(']', i + 1);\n if (close < 0) { re += '\\\\['; i++; continue; }\n let cls = pattern.slice(i + 1, close);\n if (cls[0] === '!') cls = '^' + cls.slice(1);\n re += '[' + cls + ']';\n i = close + 1; continue;\n }\n if (c === '*') { re += pattern[i + 1] === '*' ? ((i += 2), '.*') : ((i++), '[^/]*'); continue; }\n if (c === '?') { re += '[^/]'; i++; continue; }\n if ('-{}()+.,\\\\^$|#'.includes(c)) { re += '\\\\' + c; i++; continue; }\n re += c; i++;\n }\n return new RegExp('^' + re + '$');\n}\n\nexport function parseCommand(line, env) {\n const raw = tokenize(line);\n const expanded = raw.map(t => expand(t, env));\n return parseRedirects(expanded);\n}\n","shell-builtins-text.js":"import { resolvePath } from './shell-builtins.js';\nimport { runSed } from './shell-sed.js';\n\nconst toKey = p => p.replace(/^\\//, '');\nconst snap = () => window.__debug.idbSnapshot || {};\nconst persist = () => window.__debug.idbPersist?.();\nconst previewWrite = () => window.__debug.shell?.onPreviewWrite?.();\n\nconst readLines = text => text.split('\\n').map(l => l.replace(/\\r$/, '')).filter((l, i, a) => i < a.length - 1 || l !== '');\n\nfunction readStdinFirst(positional) {\n const stdinFirst = positional.length > 0 && positional[0].includes('\\n');\n return { stdin: stdinFirst ? positional[0] : null, rest: stdinFirst ? positional.slice(1) : positional };\n}\n\nexport function makeTextBuiltins(ctx, readFile, writeFile) {\n const w = s => ctx.term.write(s);\n const wl = s => w(s + '\\r\\n');\n return {\n grep: args => {\n const flags = args.filter(a => a.startsWith('-')).join('');\n const positional = args.filter(a => !a.startsWith('-'));\n const { stdin, rest } = readStdinFirst(positional);\n const [pat, ...fileArgs] = rest;\n if (!pat) throw new Error('grep: missing pattern');\n const re = new RegExp(pat, flags.includes('i') ? 'gi' : 'g');\n const lineNos = flags.includes('n');\n const sources = fileArgs.length ? fileArgs.map(f => ({ name: f, text: readFile(f) })) : [{ name: '', text: stdin || '' }];\n const showFile = sources.length > 1 || flags.includes('H');\n let matched = 0;\n for (const { name, text } of sources) {\n text.split('\\n').forEach((l, i) => {\n re.lastIndex = 0;\n if (re.test(l)) { wl((showFile && name ? name + ':' : '') + (lineNos ? (i + 1) + ':' : '') + l); matched++; }\n });\n }\n if (!matched) ctx.lastExitCode = 1;\n },\n sed: args => {\n const exprs = [];\n const files = [];\n let inplace = false;\n for (let i = 0; i < args.length; i++) {\n if (args[i] === '-e') { exprs.push(args[++i]); continue; }\n if (args[i] === '-i') { inplace = true; continue; }\n if (args[i].startsWith('-')) continue;\n if (!exprs.length) exprs.push(args[i]); else files.push(args[i]);\n }\n const { stdin, rest } = readStdinFirst(files);\n const fileArgs = rest;\n if (!exprs.length) throw new Error('sed: missing expression');\n const pairs = fileArgs.length ? fileArgs.map(f => [f, readFile(f)]) : [['', stdin || '']];\n for (const [name, text] of pairs) {\n const out = runSed(exprs, text);\n if (name && inplace) writeFile(name, out);\n else if (name) w(out.replace(/\\n/g, '\\r\\n') + '\\r\\n');\n else w(out.replace(/\\n/g, '\\r\\n'));\n }\n },\n sort: args => {\n const flags = args.filter(a => a.startsWith('-')).join('');\n const positional = args.filter(a => !a.startsWith('-'));\n const stdinFirst = positional.length > 0 && positional[0].includes('\\n');\n const stdin = stdinFirst ? positional[0] : null;\n const fileArgs = stdinFirst ? positional.slice(1) : positional;\n const targets = fileArgs.length ? fileArgs : [null];\n for (const f of targets) {\n let lines = readLines(f ? readFile(f) : stdin || '');\n if (flags.includes('r')) lines.sort().reverse(); else lines.sort();\n if (flags.includes('u')) lines = [...new Set(lines)];\n wl(lines.join('\\r\\n'));\n }\n },\n uniq: args => {\n const positional = args.filter(a => !a.startsWith('-'));\n const stdinFirst = positional.length > 0 && positional[0].includes('\\n');\n const stdin = stdinFirst ? positional[0] : null;\n const fileArgs = stdinFirst ? positional.slice(1) : positional;\n const targets = fileArgs.length ? fileArgs : [null];\n for (const f of targets) {\n const lines = readLines(f ? readFile(f) : stdin || '');\n wl(lines.filter((l, i) => i === 0 || l !== lines[i - 1]).join('\\r\\n'));\n }\n },\n tr: args => {\n const positional = args.filter(a => !a.startsWith('-'));\n const stdin = positional.length > 0 ? positional[0] : '';\n const [from, to] = positional.slice(1);\n if (!from) throw new Error('tr: missing operand');\n const mapped = stdin.split('').map(c => {\n const i = from.indexOf(c);\n return to == null ? (from.includes(c) ? '' : c) : (i >= 0 ? (to[i] || to[to.length - 1]) : c);\n }).join('');\n wl(mapped.replace(/\\n/g, '\\r\\n'));\n },\n env: () => wl(Object.entries(ctx.env).map(([k, v]) => k + '=' + v).join('\\r\\n')),\n export: args => { for (const kv of args) { const [k, ...v] = kv.split('='); ctx.env[k] = v.join('='); } },\n clear: () => ctx.term.clear(),\n history: () => ctx.history.forEach((l, i) => wl(String(i + 1).padStart(5) + ' ' + l)),\n which: (args, b) => { const cmd = args[0]; if (!cmd) throw new Error('which: missing operand'); if (b[cmd]) wl('(builtin) ' + cmd); else wl(cmd + ' not found'); },\n exit: (args, actor) => { if (actor.getSnapshot().value === 'node-repl') { actor.send({ type: 'EXIT_REPL' }); wl('[shell]'); } },\n true: () => {},\n false: () => { ctx.lastExitCode = 1; },\n printenv: args => {\n if (!args.length) wl(Object.entries(ctx.env).map(([k, v]) => k + '=' + v).join('\\r\\n'));\n else wl(ctx.env[args[0]] ?? '');\n },\n };\n}\n","shell-control.js":"export async function runScript(text, run, ctx) {\n let block = [];\n for (const s of text.split('\\n').flatMap(l => l.split(';')).map(x => x.trim()).filter(Boolean)) {\n if (block.length || isControlStart(s)) { block.push(s); if (!isBlockOpen(block)) { await runControl(block.slice(), run, ctx); block = []; } continue; }\n await run(s);\n }\n}\n\nexport function isControlStart(cmd) {\n const t = cmd.trim();\n const first = t.split(/\\s+/)[0];\n if (first === 'if' || first === 'while' || first === 'for' || first === 'case' || first === 'until' || first === 'select') return true;\n if (/^[A-Za-z_][A-Za-z0-9_]*\\s*\\(\\s*\\)/.test(t)) return true;\n return false;\n}\n\nexport function isBlockOpen(lines) {\n const joined = lines.join(' ').trim();\n let depth = 0;\n const tokens = joined.split(/\\s+/);\n for (const t of tokens) {\n if (t === 'if' || t === 'while' || t === 'for' || t === 'case' || t === 'until' || t === 'select') depth++;\n if (t === 'fi' || t === 'done' || t === 'esac') depth--;\n }\n const fnOpen = /\\{\\s*$/.test(joined) || /\\(\\s*\\)\\s*$/.test(joined);\n const fnClose = /\\}\\s*$/.test(joined);\n let braceDepth = 0;\n let inSingle = false, inDouble = false;\n for (const ch of joined) {\n if (ch === \"'\" && !inDouble) inSingle = !inSingle;\n else if (ch === '\"' && !inSingle) inDouble = !inDouble;\n else if (!inSingle && !inDouble) {\n if (ch === '{') braceDepth++;\n if (ch === '}') braceDepth--;\n }\n }\n return depth > 0 || braceDepth > 0 || (fnOpen && !fnClose);\n}\n\nexport async function runControl(block, run, ctx) {\n const joined = block.join(' ').trim();\n if (/^[A-Za-z_][A-Za-z0-9_]*\\s*\\(\\s*\\)/.test(joined)) return defineFn(joined, ctx);\n if (joined.startsWith('if ')) return runIf(joined, run, ctx);\n if (joined.startsWith('while ')) return runWhile(joined, run, ctx, false);\n if (joined.startsWith('until ')) return runWhile(joined.replace(/^until /, 'while '), run, ctx, true);\n if (joined.startsWith('for ')) return runFor(joined, run, ctx);\n if (joined.startsWith('case ')) return runCase(joined, run, ctx);\n if (joined.startsWith('select ')) return runSelect(joined, run, ctx);\n}\n\nasync function runSelect(text, run, ctx) {\n const m = text.match(/^select\\s+(\\w+)\\s+in\\s+(.+?)\\s*;\\s*do\\s+(.+?)\\s*;\\s*done$/s);\n if (!m) throw new Error('select: parse error: ' + text);\n const [, varName, listExpr, body] = m;\n const items = listExpr.split(/\\s+/).filter(Boolean);\n for (let i = 0; i < items.length; i++) ctx.term.write((i + 1) + ') ' + items[i] + '\\r\\n');\n for (const it of items) { ctx.env[varName] = it; await run(body); if (ctx.loopFlag === 'break') { ctx.loopFlag = null; break; } }\n}\n\nfunction defineFn(text, ctx) {\n const m = text.match(/^([A-Za-z_][A-Za-z0-9_]*)\\s*\\(\\s*\\)\\s*\\{?\\s*(.+?)\\s*\\}?\\s*$/s);\n if (!m) throw new Error('function: parse error: ' + text);\n const [, name, body] = m;\n ctx.functions = ctx.functions || {};\n ctx.functions[name] = body.replace(/^\\{\\s*/, '').replace(/\\s*\\}$/, '').trim();\n}\n\nasync function runIf(text, run, ctx) {\n const body = text.replace(/^if\\s+/, '').replace(/\\s*;\\s*fi$/, '');\n const parts = body.split(/\\s*;\\s*(?=then|elif|else)\\s*/);\n const branches = [];\n let i = 0;\n while (i < parts.length) {\n if (parts[i] === 'then' || parts[i] === 'elif' || parts[i] === 'else') { i++; continue; }\n if (parts[i - 1] === 'else') { branches.push({ cond: null, body: parts[i] }); i++; continue; }\n const cond = parts[i]; const bodyPart = parts[i + 2] || parts[i + 1];\n branches.push({ cond, body: bodyPart });\n i += (parts[i + 1] === 'then' ? 3 : 2);\n }\n for (const br of branches) {\n if (br.cond === null) { await run(br.body); return; }\n await run(br.cond);\n if (ctx.lastExitCode === 0) { await run(br.body); return; }\n }\n}\n\nasync function runWhile(text, run, ctx, invert) {\n const m = text.match(/^while\\s+(.+?)\\s*;\\s*do\\s+(.+?)\\s*;\\s*done$/s);\n if (!m) throw new Error('while: parse error: ' + text);\n const [, cond, body] = m;\n let guard = 0;\n ctx.loopFlag = null;\n while (guard++ < 10000) {\n await run(cond);\n const ok = ctx.lastExitCode === 0;\n if ((invert ? ok : !ok)) break;\n await run(body);\n if (ctx.loopFlag === 'break') { ctx.loopFlag = null; break; }\n if (ctx.loopFlag === 'continue') ctx.loopFlag = null;\n }\n}\n\nasync function runFor(text, run, ctx) {\n const m = text.match(/^for\\s+(\\w+)\\s+in\\s+(.+?)\\s*;\\s*do\\s+(.+?)\\s*;\\s*done$/s);\n if (!m) throw new Error('for: parse error: ' + text);\n const [, varName, listExpr, body] = m;\n const items = listExpr.split(/\\s+/).filter(Boolean);\n ctx.loopFlag = null;\n for (const item of items) {\n ctx.env[varName] = item;\n await run(body);\n if (ctx.loopFlag === 'break') { ctx.loopFlag = null; break; }\n if (ctx.loopFlag === 'continue') { ctx.loopFlag = null; continue; }\n }\n}\n\nasync function runCase(text, run, ctx) {\n const m = text.match(/^case\\s+(.+?)\\s+in\\s+(.+?)\\s*;\\s*esac$/s);\n if (!m) throw new Error('case: parse error: ' + text);\n const [, subject, body] = m;\n const sub = (ctx.expand ? ctx.expand(subject) : subject).trim();\n const clauses = body.split(/\\s*;;\\s*/).filter(Boolean);\n for (const clause of clauses) {\n const cm = clause.match(/^(.+?)\\)\\s*(.+)$/s);\n if (!cm) continue;\n const [, patterns, cmds] = cm;\n for (const pat of patterns.split('|').map(s => s.trim())) {\n const re = new RegExp('^' + pat.replace(/[-[\\]{}()+.,\\\\^$|#]/g, '\\\\$&').replace(/\\*/g, '.*').replace(/\\?/g, '.') + '$');\n if (re.test(sub)) { await run(cmds); return; }\n }\n }\n}\n","shell-builtins-extra.js":"import { resolvePath } from './shell-builtins.js';\n\nconst toKey = p => p.replace(/^\\//, '');\nconst snap = () => window.__debug.idbSnapshot || {};\n\nexport function makeExtraBuiltins(ctx, readFile, writeFile) {\n const w = s => ctx.term.write(s);\n const wl = s => w(s + '\\r\\n');\n return {\n test: args => { ctx.lastExitCode = evalTest(args) ? 0 : 1; },\n '[': args => { const inner = args[args.length - 1] === ']' ? args.slice(0, -1) : args; ctx.lastExitCode = evalTest(inner) ? 0 : 1; },\n tee: (args, _a, stdin) => {\n const files = args.filter(a => !a.startsWith('-'));\n const append = args.some(a => a === '-a');\n const buf = stdin || '';\n for (const f of files) writeFile(f, append ? (snap()[toKey(resolvePath(ctx.cwd, f))] || '') + buf : buf);\n w(buf.replace(/\\n/g, '\\r\\n'));\n },\n xargs: async (args, _a, stdin, invokeBuiltin) => {\n const parts = (stdin || '').trim().split(/\\s+/).filter(Boolean);\n if (!args.length || !parts.length) return;\n await invokeBuiltin(args[0], [...args.slice(1), ...parts], false);\n },\n read: (args, _a, stdin) => {\n const flags = args.filter(a => a.startsWith('-')).join('');\n const names = args.filter(a => !a.startsWith('-'));\n if (!names.length) names.push('REPLY');\n let line = (stdin || '').split('\\n')[0];\n if (!flags.includes('r')) line = line.replace(/\\\\(.)/g, '$1');\n line = line.replace(/\\r$/, '');\n const nIdx = flags.indexOf('n');\n if (nIdx >= 0) { const n = parseInt(flags.slice(nIdx + 1), 10); if (!isNaN(n)) line = line.slice(0, n); }\n const parts = line.split(/\\s+/);\n for (let i = 0; i < names.length; i++) ctx.env[names[i]] = i === names.length - 1 ? parts.slice(i).join(' ') : parts[i] || '';\n },\n printf: args => {\n if (!args.length) return;\n let dest = null;\n if (args[0] === '-v') { dest = args[1]; args = args.slice(2); }\n if (!args.length) return;\n const fmt = args[0].replace(/\\\\n/g, '\\n').replace(/\\\\t/g, '\\t').replace(/\\\\r/g, '\\r');\n let idx = 1;\n const out = fmt.replace(/%([sdxof])/g, (_, spec) => {\n const v = args[idx++] ?? '';\n if (spec === 'd') return String(parseInt(v, 10) || 0);\n if (spec === 'x') return (parseInt(v, 10) || 0).toString(16);\n if (spec === 'o') return (parseInt(v, 10) || 0).toString(8);\n if (spec === 'f') return String(parseFloat(v) || 0);\n return String(v);\n });\n if (dest) ctx.env[dest] = out; else w(out.replace(/\\n/g, '\\r\\n'));\n },\n declare: args => {\n const assoc = args.includes('-A');\n const arr = args.includes('-a');\n const names = args.filter(a => !a.startsWith('-'));\n for (const n of names) { const eq = n.indexOf('='); const k = eq >= 0 ? n.slice(0, eq) : n; if (assoc) { ctx.arrays = ctx.arrays || {}; ctx.arrays[k] = {}; } else if (arr) { ctx.arrays = ctx.arrays || {}; ctx.arrays[k] = []; } else if (eq >= 0) ctx.env[k] = n.slice(eq + 1); }\n },\n shift: args => {\n const n = parseInt(args[0], 10) || 1;\n ctx.argv = (ctx.argv || []).slice(n);\n },\n local: args => {\n for (const kv of args) {\n const eq = kv.indexOf('=');\n const k = eq >= 0 ? kv.slice(0, eq) : kv;\n const v = eq >= 0 ? kv.slice(eq + 1) : '';\n (ctx.localStack && ctx.localStack[ctx.localStack.length - 1] || {})[k] = ctx.env[k];\n ctx.env[k] = v;\n }\n },\n set: args => {\n for (const a of args) {\n if (a === '-e') ctx.opts = { ...ctx.opts, errexit: true };\n else if (a === '+e') ctx.opts = { ...ctx.opts, errexit: false };\n else if (a === '-x') ctx.opts = { ...ctx.opts, xtrace: true };\n else if (a === '+x') ctx.opts = { ...ctx.opts, xtrace: false };\n else if (a === '-u') ctx.opts = { ...ctx.opts, nounset: true };\n }\n },\n break: args => { ctx.loopFlag = 'break'; ctx.loopDepth = parseInt(args[0], 10) || 1; },\n continue: args => { ctx.loopFlag = 'continue'; ctx.loopDepth = parseInt(args[0], 10) || 1; },\n source: async (args, _a, _s, invokeBuiltin, runLine) => {\n if (!args[0]) throw new Error('source: missing file');\n const content = snap()[toKey(resolvePath(ctx.cwd, args[0]))];\n if (content == null) throw new Error('source: ' + args[0] + ': No such file');\n const savedArgv = ctx.argv;\n ctx.argv = [args[0], ...args.slice(1)];\n try { if (ctx.runScript) await ctx.runScript(content); else for (const ln of content.split('\\n')) if (ln.trim()) await runLine(ln); }\n finally { ctx.argv = savedArgv; }\n },\n '.': async (args, actor, stdin, invokeBuiltin, runLine) => {\n const src = (ctx.builtinsRef || {}).source;\n if (src) await src(args, actor, stdin, invokeBuiltin, runLine);\n },\n };\n}\n\nfunction evalTest(args) {\n if (args.length === 1) return !!args[0];\n if (args.length === 2) {\n const [flag, val] = args;\n const s = () => window.__debug.idbSnapshot || {};\n const OPS = {\n '-z': v => v === '', '-n': v => v !== '',\n '-f': v => v in s(),\n '-d': v => Object.keys(s()).some(k => k.startsWith(v + '/')),\n '-e': v => v in s() || Object.keys(s()).some(k => k.startsWith(v + '/')),\n '!': v => !v,\n };\n return OPS[flag]?.(val) ?? false;\n }\n if (args.length === 3) {\n const [a, op, b] = args;\n const CMP = { '=':(x,y)=>x===y,'==':(x,y)=>x===y,'!=':(x,y)=>x!==y,\n '-eq':(x,y)=>+x===+y,'-ne':(x,y)=>+x!==+y,\n '-lt':(x,y)=>+x<+y,'-gt':(x,y)=>+x>+y,'-le':(x,y)=>+x<=+y,'-ge':(x,y)=>+x>=+y };\n return CMP[op]?.(a, b) ?? false;\n }\n return false;\n}\n","shell-expand.js":"export function expandParam(name, env, argv, lastExit, arrays) {\n if (name === '?') return String(lastExit ?? 0);\n if (name === '!') return env['!'] || '';\n if (name === '$') return env.$ || '0';\n if (name === '#') return String((argv || []).length > 0 ? (argv || []).length - 1 : 0);\n if (name === '@' || name === '*') return (argv || []).slice(1).join(' ');\n if (name === '0') return (argv || [])[0] || '';\n if (/^[1-9]$/.test(name)) return (argv || [])[parseInt(name)] || '';\n const arrM = name.match(/^([A-Za-z_][A-Za-z0-9_]*)\\[(.+?)\\]$/);\n if (arrM && arrays) {\n const a = arrays[arrM[1]];\n if (a == null) return '';\n if (arrM[2] === '@' || arrM[2] === '*') return Array.isArray(a) ? a.join(' ') : Object.values(a).join(' ');\n if (Array.isArray(a)) return a[parseInt(arrM[2], 10)] || '';\n return a[arrM[2]] || '';\n }\n const lenArrM = name.match(/^#([A-Za-z_][A-Za-z0-9_]*)\\[@\\]$/);\n if (lenArrM && arrays) { const a = arrays[lenArrM[1]] || []; return String(Array.isArray(a) ? a.length : Object.keys(a).length); }\n return env[name] ?? '';\n}\n\nexport function expandParamOp(expr, env, argv, lastExit, arrays) {\n if (expr.startsWith('!')) {\n const prefM = expr.match(/^!([A-Za-z_]\\w*)([@*])$/);\n if (prefM) return Object.keys(env).filter(k => k.startsWith(prefM[1])).join(' ');\n const keysM = expr.match(/^!([A-Za-z_]\\w*)\\[[@*]\\]$/);\n if (keysM && arrays) { const a = arrays[keysM[1]] || []; return Array.isArray(a) ? a.map((_, i) => i).join(' ') : Object.keys(a).join(' '); }\n const indM = expr.match(/^!([A-Za-z_]\\w*)$/);\n if (indM) { const t = env[indM[1]]; return t ? expandParam(t, env, argv, lastExit, arrays) : ''; }\n }\n const caseM = expr.match(/^([A-Za-z_][A-Za-z0-9_]*|@)(\\^\\^|,,|\\^|,)(.*)$/s);\n if (caseM) {\n const v = expandParam(caseM[1], env, argv, lastExit, arrays);\n const op = caseM[2];\n if (op === '^^') return v.toUpperCase();\n if (op === ',,') return v.toLowerCase();\n if (op === '^') return v.charAt(0).toUpperCase() + v.slice(1);\n if (op === ',') return v.charAt(0).toLowerCase() + v.slice(1);\n }\n const qM = expr.match(/^([A-Za-z_][A-Za-z0-9_]*|@)@([QEP])$/);\n if (qM) {\n const v = expandParam(qM[1], env, argv, lastExit, arrays);\n if (qM[2] === 'Q') return \"'\" + v.replace(/'/g, \"'\\\\''\") + \"'\";\n if (qM[2] === 'E') return v.replace(/\\\\n/g, '\\n').replace(/\\\\t/g, '\\t');\n if (qM[2] === 'P') return v;\n }\n const lenArrM = expr.match(/^#([A-Za-z_]\\w*)\\[[@*]\\]$/);\n if (lenArrM) { const a = (arrays || {})[lenArrM[1]] || []; return String(Array.isArray(a) ? a.length : Object.keys(a).length); }\n const lenM = expr.match(/^#(.+)$/);\n if (lenM) return String(expandParam(lenM[1], env, argv, lastExit, arrays).length);\n const sliceM = expr.match(/^([^:]+):(\\d+)(?::(\\d+))?$/);\n if (sliceM) { const v = expandParam(sliceM[1], env, argv, lastExit, arrays); const s = +sliceM[2]; return sliceM[3] !== undefined ? v.slice(s, s + (+sliceM[3])) : v.slice(s); }\n const defM = expr.match(/^([A-Za-z_][A-Za-z0-9_]*|\\?|#|@|[0-9])(:-|:=|:\\?|:\\+|-|=|\\+)(.*)$/s);\n if (defM) {\n const [, name, op, def] = defM;\n const v = expandParam(name, env, argv, lastExit, arrays);\n const defined = v !== '' && v != null;\n if (op === ':-' || op === '-') return defined ? v : def;\n if (op === ':=' || op === '=') { if (!defined) env[name] = def; return defined ? v : def; }\n if (op === ':?' || op === '?') { if (!defined) throw new Error(name + ': ' + (def || 'parameter null')); return v; }\n if (op === ':+' || op === '+') return defined ? def : '';\n }\n const sufM = expr.match(/^([A-Za-z_][A-Za-z0-9_]*|@|#)(%%?|##?)(.+)$/s);\n if (sufM) {\n const [, name, op, pat] = sufM;\n const v = expandParam(name, env, argv, lastExit, arrays);\n const bare = globReLine(pat).replace(/^\\^|\\$$/g, '');\n if (op === '#') { const m = v.match(new RegExp('^' + bare)); return m ? v.slice(m[0].length) : v; }\n if (op === '##') { const m = v.match(new RegExp('^' + bare.replace(/\\.\\*/g, '.*?') + '.*')); return m ? '' : v; }\n if (op === '%') { const m = v.match(new RegExp(bare + '$')); return m ? v.slice(0, -m[0].length) : v; }\n if (op === '%%') { const m = v.match(new RegExp('^.*' + bare + '$')); return m ? '' : v; }\n }\n const subM = expr.match(/^([A-Za-z_][A-Za-z0-9_]*|@)\\/(\\/?)(.+?)\\/(.*)$/s);\n if (subM) {\n const [, name, all, pat, rep] = subM;\n const v = expandParam(name, env, argv, lastExit, arrays);\n return v.replace(new RegExp(globReLine(pat).replace(/^\\^|\\$$/g, ''), all ? 'g' : ''), rep);\n }\n return expandParam(expr, env, argv, lastExit, arrays);\n}\n\nfunction globReLine(pat) { return '^' + pat.replace(/[-[\\]{}()+.,\\\\^$|#]/g, (c) => (c === '*' || c === '?') ? c : '\\\\' + c).replace(/\\*/g, '.*').replace(/\\?/g, '.') + '$'; }\n\nexport function evalArith(expr, env) {\n const src = expr.replace(/\\b([A-Za-z_][A-Za-z0-9_]*)\\b/g, (_, n) => String(parseInt(env[n], 10) || 0));\n if (!/^[-+*/%()<>=!&|\\s\\d?:]+$/.test(src)) return 0;\n try { return Function('\"use strict\"; return (' + src + ')')() | 0; } catch { return 0; }\n}\n\nexport function expandBraces(token) {\n const listM = token.match(/^(.*?)\\{([^{}]*,[^{}]*)\\}(.*)$/s);\n if (listM) {\n const [, pre, list, post] = listM;\n return list.split(',').flatMap(p => expandBraces(pre + p + post));\n }\n const rangeM = token.match(/^(.*?)\\{(-?\\d+)\\.\\.(-?\\d+)(?:\\.\\.(-?\\d+))?\\}(.*)$/s);\n if (rangeM) {\n const [, pre, a, b, step, post] = rangeM;\n const s = step ? +step : ((+a) <= (+b) ? 1 : -1);\n const out = [];\n for (let i = +a; s > 0 ? i <= +b : i >= +b; i += s) out.push(i);\n return out.flatMap(i => expandBraces(pre + i + post));\n }\n return [token];\n}\n\nexport function expandTilde(token, env) {\n if (token === '~') return env.HOME || '/';\n if (token.startsWith('~/')) return (env.HOME || '') + token.slice(1);\n const m = token.match(/^~([A-Za-z_][A-Za-z0-9_]*)(\\/.*)?$/);\n if (m) return '/home/' + m[1] + (m[2] || '');\n return token;\n}\n\nexport function fullExpand(token, env, lastExit, argv, runCap, arrays) {\n let out = '';\n let i = 0;\n while (i < token.length) {\n if (token[i] === '`') {\n const end = token.indexOf('`', i + 1);\n if (end < 0) { out += token.slice(i); break; }\n out += runCap ? runCap(token.slice(i + 1, end)) : '';\n i = end + 1; continue;\n }\n if (token[i] === '$' && token[i + 1] === '(' && token[i + 2] === '(') {\n const close = token.indexOf('))', i + 3);\n if (close < 0) { out += token[i++]; continue; }\n out += String(evalArith(token.slice(i + 3, close), env));\n i = close + 2; continue;\n }\n if (token[i] === '$' && token[i + 1] === '(') {\n const end = findMatch(token, i + 1, '(', ')');\n if (end < 0) { out += token[i++]; continue; }\n out += runCap ? runCap(token.slice(i + 2, end)) : '';\n i = end + 1; continue;\n }\n if (token[i] === '$' && token[i + 1] === '{') {\n const end = token.indexOf('}', i + 2);\n if (end < 0) { out += token[i++]; continue; }\n out += expandParamOp(token.slice(i + 2, end), env, argv, lastExit, arrays);\n i = end + 1; continue;\n }\n if (token[i] === '$') {\n const m = token.slice(i + 1).match(/^(\\?|!|#|@|\\*|[0-9]|[A-Za-z_][A-Za-z0-9_]*)/);\n if (m) { out += expandParam(m[1], env, argv, lastExit, arrays); i += 1 + m[1].length; continue; }\n }\n out += token[i++];\n }\n return out;\n}\n\nfunction findMatch(s, start, open, close) {\n let depth = 0; let inSingle = false, inDouble = false;\n for (let i = start; i < s.length; i++) {\n const c = s[i];\n if (c === \"'\" && !inDouble) inSingle = !inSingle;\n else if (c === '\"' && !inSingle) inDouble = !inDouble;\n else if (!inSingle && !inDouble) {\n if (c === open) depth++;\n else if (c === close) { depth--; if (depth === 0) return i; }\n }\n }\n return -1;\n}\n","shell-builtins-util.js":"import { resolvePath } from './shell-builtins.js';\nimport { runAwk } from './shell-awk.js';\n\nconst toKey = p => p.replace(/^\\//, '');\nconst snap = () => window.__debug.idbSnapshot || {};\n\nexport function makeUtilBuiltins(ctx, readFile, writeFile) {\n const w = s => ctx.term.write(s);\n const wl = s => w(s + '\\r\\n');\n return {\n basename: args => { if (!args[0]) return; const p = args[0].replace(/\\/+$/, '').split('/').pop(); wl(args[1] ? p.replace(new RegExp(args[1] + '$'), '') : p); },\n dirname: args => { if (!args[0]) return; const idx = args[0].replace(/\\/+$/, '').lastIndexOf('/'); wl(idx <= 0 ? (idx === 0 ? '/' : '.') : args[0].slice(0, idx)); },\n realpath: args => { if (!args[0]) return; wl(resolvePath(ctx.cwd, args[0])); },\n date: args => {\n const fmt = args.find(a => a.startsWith('+'));\n const d = new Date();\n if (!fmt) { wl(d.toUTCString()); return; }\n const pad = (n, z = 2) => String(n).padStart(z, '0');\n const MAP = { Y: d.getFullYear(), m: pad(d.getMonth() + 1), d: pad(d.getDate()), H: pad(d.getHours()), M: pad(d.getMinutes()), S: pad(d.getSeconds()), s: Math.floor(d.getTime() / 1000), N: pad(d.getMilliseconds(), 3) + '000000' };\n wl(fmt.slice(1).replace(/%(.)/g, (_, k) => String(MAP[k] ?? '%' + k)));\n },\n find: args => {\n const start = args.find(a => !a.startsWith('-')) || '.';\n const nameArg = args[args.indexOf('-name') + 1];\n const typeArg = args[args.indexOf('-type') + 1];\n const prefix = toKey(resolvePath(ctx.cwd, start));\n const keys = Object.keys(snap());\n const dirs = new Set();\n for (const k of keys) { const parts = k.split('/'); for (let i = 1; i < parts.length; i++) dirs.add(parts.slice(0, i).join('/')); }\n const all = [...keys.map(k => ({ path: k, type: 'f' })), ...[...dirs].map(d => ({ path: d, type: 'd' }))];\n const patToRe = p => new RegExp('^' + p.replace(/[-[\\]{}()+.,\\\\^$|#]/g, c => (c === '*' || c === '?') ? c : '\\\\' + c).replace(/\\*/g, '.*').replace(/\\?/g, '.') + '$');\n const matches = all.filter(e => (!prefix || e.path === prefix || e.path.startsWith(prefix + '/')) && (!nameArg || patToRe(nameArg).test(e.path.split('/').pop())) && (!typeArg || typeArg === e.type));\n for (const m of matches.sort((a, b) => a.path.localeCompare(b.path))) wl('/' + m.path);\n },\n awk: (args, _a, stdin) => {\n let fs = null;\n const rest = [];\n for (let i = 0; i < args.length; i++) {\n if (args[i] === '-F') { fs = args[++i]; continue; }\n rest.push(args[i]);\n }\n const prog = rest.find(a => !a.startsWith('-')) || '';\n if (!prog) { ctx.lastExitCode = 1; return; }\n const out = runAwk(prog, stdin || '', fs);\n if (out) w(out.replace(/\\n/g, '\\r\\n') + '\\r\\n');\n },\n eval: async (args, _a, _s, invokeBuiltin, runLine) => {\n const line = args.join(' ');\n if (runLine) await runLine(line);\n },\n command: (args, _a, _s, invokeBuiltin) => {\n if (args[0] === '-v') { const name = args[1]; if (!name) return; if (ctx.builtinsRef?.[name] || ctx.functions?.[name]) wl(name); else ctx.lastExitCode = 1; return; }\n if (args[0]) invokeBuiltin?.(args[0], args.slice(1), false);\n },\n '[[': args => {\n const inner = args[args.length - 1] === ']]' ? args.slice(0, -1) : args;\n ctx.lastExitCode = evalCompound(inner) ? 0 : 1;\n },\n getopts: (args, _a, _s, _ib) => {\n const spec = args[0] || '';\n const varName = args[1] || 'OPTARG';\n const idx = (ctx.optind || 1);\n const argv = (ctx.argv || []).slice(1);\n const tok = argv[idx - 1];\n if (!tok || !tok.startsWith('-') || tok === '--') { ctx.lastExitCode = 1; ctx.optind = 1; return; }\n const flag = tok[1];\n const needsArg = spec.includes(flag + ':');\n ctx.env[varName] = flag;\n if (needsArg) { ctx.env.OPTARG = argv[idx] || ''; ctx.optind = idx + 2; } else { ctx.optind = idx + 1; }\n ctx.lastExitCode = spec.includes(flag) ? 0 : 1;\n },\n wait: async args => {\n const id = args[0];\n const job = (ctx.bgJobs || {})[id];\n if (job) await job.promise;\n },\n trap: args => {\n if (!args.length) { wl(Object.entries(ctx.traps || {}).map(([k, v]) => 'trap -- \"' + v + '\" ' + k).join('\\r\\n')); return; }\n ctx.traps = ctx.traps || {};\n const [cmd, ...sigs] = args;\n for (const s of sigs) ctx.traps[s] = cmd;\n },\n jobs: () => wl(Object.entries(ctx.bgJobs || {}).map(([k, v]) => '[' + k + '] ' + (v.done ? 'Done' : 'Running') + ' ' + v.cmd).join('\\r\\n')),\n netstat: async args => { const bn = globalThis.__busnet; if (!bn) { wl('netstat: busnet not initialized'); return 1; } const all = args.includes('-a'); wl('Proto Local Address State Service'); for (const port of bn.getListeners()) wl(('tcp 0.0.0.0:' + port).padEnd(40) + 'LISTEN bus'); if (all || args.includes('-p')) { const peers = await bn.discover(); for (const p of peers) wl(('tcp peer://' + p.origin + ':' + p.port).padEnd(40) + 'PEER ' + p.service); } return 0; },\n };\n}\n\nfunction evalCompound(args) {\n const groups = []; let cur = []; const ops = [];\n for (const a of args) { if (a === '&&' || a === '||') { groups.push(cur); ops.push(a); cur = []; } else cur.push(a); }\n groups.push(cur);\n let result = evalSimple(groups[0]);\n for (let i = 0; i < ops.length; i++) {\n if (ops[i] === '&&') result = result && evalSimple(groups[i + 1]);\n else result = result || evalSimple(groups[i + 1]);\n }\n return result;\n}\n\nfunction evalSimple(args) {\n if (!args.length) return false;\n if (args[0] === '!') return !evalSimple(args.slice(1));\n if (args.length === 3 && args[1] === '=~') { try { return new RegExp(args[2]).test(args[0]); } catch { return false; } }\n const OPS = { '-z': v => !v, '-n': v => !!v, '-f': v => v in (window.__debug.idbSnapshot || {}), '-d': v => Object.keys(window.__debug.idbSnapshot || {}).some(k => k.startsWith(v + '/')), '-e': v => v in (window.__debug.idbSnapshot || {}) };\n if (args.length === 2) return OPS[args[0]]?.(args[1]) ?? false;\n if (args.length === 3) {\n const [a, op, b] = args;\n const CMP = { '=': (x, y) => x === y, '==': (x, y) => x === y, '!=': (x, y) => x !== y, '<': (x, y) => x < y, '>': (x, y) => x > y, '-eq': (x, y) => +x === +y, '-ne': (x, y) => +x !== +y, '-lt': (x, y) => +x < +y, '-gt': (x, y) => +x > +y };\n return CMP[op]?.(a, b) ?? false;\n }\n return !!args[0];\n}\n","shell-awk.js":"export function runAwk(program, stdin, fs_sep) {\n const fs = fs_sep || /\\s+/;\n const blocks = parseAwk(program);\n const out = [];\n const ctx = { NR: 0, vars: {} };\n const emit = s => out.push(s);\n for (const b of blocks.filter(b => b.when === 'BEGIN')) execAction(b.action, { $: [], NR: 0, NF: 0 }, emit, ctx);\n const lines = (stdin || '').split('\\n');\n const effective = lines.length > 0 && lines[lines.length - 1] === '' ? lines.slice(0, -1) : lines;\n for (const line of effective) {\n ctx.NR++;\n const fields = line.split(fs).filter((_, i, a) => i > 0 || a.length === 1 || _ !== '');\n const rec = { $: [line, ...fields], NR: ctx.NR, NF: fields.length };\n for (const b of blocks.filter(b => b.when !== 'BEGIN' && b.when !== 'END')) {\n if (!b.when || matchCond(b.when, rec, ctx)) execAction(b.action, rec, emit, ctx);\n }\n }\n for (const b of blocks.filter(b => b.when === 'END')) execAction(b.action, { $: [], NR: ctx.NR, NF: 0 }, emit, ctx);\n return out.join('\\n');\n}\n\nfunction parseAwk(prog) {\n const blocks = [];\n let i = 0;\n while (i < prog.length) {\n while (i < prog.length && /\\s/.test(prog[i])) i++;\n if (i >= prog.length) break;\n let when = '';\n while (i < prog.length && prog[i] !== '{') { when += prog[i++]; }\n when = when.trim();\n if (prog[i] !== '{') { if (when) blocks.push({ when, action: 'print' }); break; }\n let depth = 1; i++;\n let action = '';\n while (i < prog.length && depth > 0) {\n if (prog[i] === '{') depth++;\n else if (prog[i] === '}') { depth--; if (!depth) break; }\n action += prog[i++];\n }\n i++;\n blocks.push({ when: when || null, action: action.trim() || 'print' });\n }\n return blocks;\n}\n\nfunction matchCond(cond, rec, ctx) {\n const re = cond.match(/^\\/(.+)\\/$/);\n if (re) return new RegExp(re[1]).test(rec.$[0]);\n const cmp = cond.match(/^\\$(\\d+)\\s*(==|!=|<|>|~)\\s*\"(.*)\"$/);\n if (cmp) { const v = rec.$[+cmp[1]] || ''; const OPS = { '==': v === cmp[3], '!=': v !== cmp[3], '<': v < cmp[3], '>': v > cmp[3], '~': new RegExp(cmp[3]).test(v) }; return OPS[cmp[2]]; }\n if (cond === 'NR==1') return rec.NR === 1;\n try { return !!Function('$', 'NR', 'NF', 'return (' + cond.replace(/\\$(\\d+)/g, (_, n) => '$[' + n + ']') + ')')(rec.$, rec.NR, rec.NF); } catch { return false; }\n}\n\nfunction execAction(action, rec, emit, ctx) {\n for (const stmt of action.split(';').map(s => s.trim()).filter(Boolean)) {\n const pr = stmt.match(/^print\\s*(.*)$/);\n if (pr) { emit(evalPrint(pr[1] || '$0', rec, ctx)); continue; }\n const printf = stmt.match(/^printf\\s+(.+)$/);\n if (printf) { const parts = splitTop(printf[1], ','); const vals = parts.map(p => evalExpr(p.trim(), rec, ctx)); emit(AWK_FNS.sprintf(vals[0], ...vals.slice(1))); continue; }\n const assign = stmt.match(/^([A-Za-z_]\\w*)\\s*=\\s*(.+)$/);\n if (assign) { ctx.vars[assign[1]] = evalExpr(assign[2], rec, ctx); continue; }\n if (stmt === 'next') { ctx.skipRest = true; continue; }\n try { evalExpr(stmt, rec, ctx); } catch {}\n }\n}\n\nfunction evalPrint(args, rec, ctx) {\n if (!args) return rec.$[0] || '';\n const parts = splitTop(args, ',');\n return parts.map(p => String(evalExpr(p.trim(), rec, ctx))).join(' ');\n}\n\nconst AWK_FNS = {\n length: s => String(s ?? '').length,\n substr: (s, i, n) => String(s).substr((i|0) - 1, n == null ? undefined : n|0),\n tolower: s => String(s).toLowerCase(),\n toupper: s => String(s).toUpperCase(),\n index: (s, t) => String(s).indexOf(String(t)) + 1,\n match: (s, re) => { const m = String(s).match(new RegExp(re)); return m ? m.index + 1 : 0; },\n split: (s, arr, re) => { const parts = String(s).split(new RegExp(re || /\\s+/)); for (let i = 0; i < parts.length; i++) arr[i + 1] = parts[i]; return parts.length; },\n sub: (re, rep, s) => { const r = new RegExp(re); const v = String(s ?? ''); return v.replace(r, rep); },\n gsub: (re, rep, s) => { const r = new RegExp(re, 'g'); const v = String(s ?? ''); return v.replace(r, rep); },\n sprintf: (fmt, ...a) => { let i = 0; return String(fmt).replace(/%([sdfox])/g, (_, k) => { const v = a[i++]; if (k === 'd') return String(parseInt(v, 10) || 0); if (k === 's') return String(v ?? ''); if (k === 'f') return String(parseFloat(v) || 0); if (k === 'x') return (parseInt(v, 10) || 0).toString(16); if (k === 'o') return (parseInt(v, 10) || 0).toString(8); return ''; }); },\n};\n\nfunction evalExpr(expr, rec, ctx) {\n const s = expr.trim();\n const strM = s.match(/^\"(.*)\"$/);\n if (strM) return strM[1];\n const fldM = s.match(/^\\$(\\d+|NF)$/);\n if (fldM) { const n = fldM[1] === 'NF' ? rec.NF : +fldM[1]; return rec.$[n] || ''; }\n if (s === 'NR') return rec.NR;\n if (s === 'NF') return rec.NF;\n if (ctx.vars[s] !== undefined) return ctx.vars[s];\n const num = +s;\n if (!isNaN(num)) return num;\n try {\n const body = 'return (' + s.replace(/\\$(\\d+|NF)/g, (_, n) => n === 'NF' ? 'NF' : '$[' + n + ']').replace(/\\b([A-Za-z_]\\w*)\\b/g, (_, n) => AWK_FNS[n] ? 'F.' + n : 'v.' + n) + ')';\n return Function('$', 'NR', 'NF', 'v', 'F', body)(rec.$, rec.NR, rec.NF, ctx.vars, AWK_FNS) ?? '';\n } catch { return s; }\n}\n\nfunction splitTop(s, sep) {\n const out = []; let cur = ''; let depth = 0; let inStr = false;\n for (const c of s) {\n if (c === '\"') inStr = !inStr;\n else if (!inStr) { if (c === '(' || c === '[') depth++; else if (c === ')' || c === ']') depth--; }\n if (c === sep && !inStr && !depth) { out.push(cur); cur = ''; continue; }\n cur += c;\n }\n if (cur) out.push(cur);\n return out;\n}\n","shell-sed.js":"export function runSed(exprs, stdin) {\n const ops = exprs.flatMap(parseSed);\n const labels = {};\n ops.forEach((op, i) => { if (op.cmd === ':') labels[op.label] = i; });\n const lines = stdin.split('\\n');\n const out = [];\n let pat = null, hold = '';\n let nr = 0;\n let i = 0;\n while (i < lines.length) {\n pat = lines[i]; nr = i + 1;\n let pc = 0, deleted = false, lastSubOk = false;\n while (pc < ops.length) {\n const op = ops[pc];\n if (op.cmd === ':') { pc++; continue; }\n if (op.addr != null && !addrMatch(op.addr, nr, pat, lines.length)) { pc++; continue; }\n if (op.cmd === 's') { const before = pat; pat = pat.replace(op.re, op.rep); lastSubOk = pat !== before; pc++; continue; }\n if (op.cmd === 'd') { deleted = true; break; }\n if (op.cmd === 'p') { out.push(pat); pc++; continue; }\n if (op.cmd === 'P') { out.push(pat.split('\\n')[0]); pc++; continue; }\n if (op.cmd === 'h') { hold = pat; pc++; continue; }\n if (op.cmd === 'H') { hold += '\\n' + pat; pc++; continue; }\n if (op.cmd === 'g') { pat = hold; pc++; continue; }\n if (op.cmd === 'G') { pat += '\\n' + hold; pc++; continue; }\n if (op.cmd === 'x') { const t = pat; pat = hold; hold = t; pc++; continue; }\n if (op.cmd === 'n') { out.push(pat); i++; if (i >= lines.length) { pat = null; break; } pat = lines[i]; nr = i + 1; pc++; continue; }\n if (op.cmd === 'N') { i++; if (i >= lines.length) break; pat += '\\n' + lines[i]; nr = i + 1; pc++; continue; }\n if (op.cmd === 'D') { const nl = pat.indexOf('\\n'); if (nl < 0) { deleted = true; break; } pat = pat.slice(nl + 1); pc = 0; continue; }\n if (op.cmd === 'b') { pc = op.label ? (labels[op.label] ?? ops.length) : ops.length; continue; }\n if (op.cmd === 't') { if (lastSubOk) { lastSubOk = false; pc = op.label ? (labels[op.label] ?? ops.length) : ops.length; continue; } pc++; continue; }\n if (op.cmd === 'a') { out.push(pat); out.push(op.text); pat = null; break; }\n if (op.cmd === 'i') { out.push(op.text); pc++; continue; }\n if (op.cmd === 'c') { pat = op.text; pc++; continue; }\n if (op.cmd === 'q') { if (!deleted && pat != null) out.push(pat); return out.join('\\n'); }\n pc++;\n }\n if (!deleted && pat != null) out.push(pat);\n i++;\n }\n return out.join('\\n');\n}\n\nfunction parseSed(expr) {\n const out = [];\n for (const part of splitExprs(expr)) {\n const t = part.trim();\n if (!t) continue;\n const lbl = t.match(/^:(\\w+)$/);\n if (lbl) { out.push({ cmd: ':', label: lbl[1] }); continue; }\n const addrM = t.match(/^(\\d+|\\/[^/]+\\/|\\$)(.+)$/);\n let addr = null; let rest = t;\n if (addrM && !t.startsWith('s')) { addr = addrM[1]; rest = addrM[2]; }\n const sM = rest.match(/^s(.)(.+?)\\1(.*?)\\1([gip]*)$/);\n if (sM) { out.push({ cmd: 's', addr, re: new RegExp(sM[2], sM[4].includes('g') ? 'g' : ''), rep: sM[3] }); continue; }\n const br = rest.match(/^([bt])\\s*(\\w*)$/);\n if (br) { out.push({ cmd: br[1], addr, label: br[2] || null }); continue; }\n const plain = rest.match(/^([dpPhHgGxnNDq])$/);\n if (plain) { out.push({ cmd: plain[1], addr }); continue; }\n const textM = rest.match(/^([aic])\\\\?\\s*(.*)$/);\n if (textM) { out.push({ cmd: textM[1], addr, text: textM[2] }); continue; }\n }\n return out;\n}\n\nfunction splitExprs(s) {\n const out = []; let cur = ''; let escape = false;\n for (const c of s) {\n if (escape) { cur += c; escape = false; continue; }\n if (c === '\\\\') { cur += c; escape = true; continue; }\n if (c === ';') { if (cur) out.push(cur); cur = ''; continue; }\n cur += c;\n }\n if (cur) out.push(cur);\n return out;\n}\n\nfunction addrMatch(addr, n, line, totalLines) {\n if (addr === '$') return n === totalLines;\n if (/^\\d+$/.test(addr)) return +addr === n;\n const re = addr.match(/^\\/(.+)\\/$/);\n if (re) return new RegExp(re[1]).test(line);\n return false;\n}\n","shell-signals.js":"export function createSignals(ctx) {\n const pending = [];\n const handlers = ctx.traps || (ctx.traps = {});\n return {\n raise(sig) { pending.push(sig); },\n async check(run) {\n while (pending.length) {\n const sig = pending.shift();\n if (sig === 'KILL') { const j = ctx.currentJob; if (j) j.killed = true; throw new Error('killed by SIGKILL'); }\n const h = handlers[sig];\n if (h) { try { await run(h); } catch (e) { ctx.term.write('\\x1b[31mtrap: ' + e.message + '\\x1b[0m\\r\\n'); } }\n if (sig === 'INT' && !h && ctx.currentJob) ctx.currentJob.killed = true;\n }\n },\n pending: () => pending.slice(),\n };\n}\n\nexport function makeKillBuiltin(ctx) {\n return args => {\n let sig = 'TERM';\n const targets = [];\n for (const a of args) {\n if (a.startsWith('-')) sig = a.slice(1).replace(/^SIG/, '');\n else targets.push(a);\n }\n for (const t of targets) {\n const id = t.startsWith('%') ? t.slice(1) : t;\n const job = ctx.bgJobs?.[id];\n if (!job) { ctx.term.write('kill: ' + t + ': no such job\\r\\n'); ctx.lastExitCode = 1; continue; }\n if (job.actor) job.actor.send({ type: 'SIGNAL', sig });\n if (sig === 'KILL' || sig === '9') { job.killed = true; if (job.reject) job.reject(new Error('killed')); }\n if (sig === 'STOP' || sig === 'TSTP') { if (job.actor) job.actor.send({ type: 'STOP' }); job.stopped = true; }\n if (sig === 'CONT') { if (job.actor) job.actor.send({ type: 'CONT' }); job.stopped = false; }\n }\n };\n}\n\nexport function makeTrapBuiltin(ctx) {\n return args => {\n const handlers = ctx.traps || (ctx.traps = {});\n if (!args.length) {\n for (const [sig, cmd] of Object.entries(handlers)) ctx.term.write(\"trap -- '\" + cmd + \"' \" + sig + '\\r\\n');\n return;\n }\n if (args[0] === '-l') { ctx.term.write('HUP INT QUIT ILL TRAP ABRT BUS FPE KILL USR1 SEGV USR2 PIPE ALRM TERM STOP TSTP CONT CHLD TTIN TTOU URG XCPU XFSZ VTALRM PROF WINCH IO PWR SYS\\r\\n'); return; }\n const [cmd, ...sigs] = args;\n for (const s of sigs) {\n const norm = s.replace(/^SIG/, '').toUpperCase();\n if (cmd === '-' || cmd === '') delete handlers[norm];\n else handlers[norm] = cmd;\n }\n };\n}\n","shell-jobs.js":"import { createMachine, createActor } from './vendor/xstate.js';\n\nconst jobMachine = createMachine({\n id: 'job', initial: 'running',\n states: {\n running: { on: { STOP: 'stopped', DONE: 'done', FAIL: 'failed', SIGNAL: { actions: 'deliverSignal' } } },\n stopped: { on: { CONT: 'running', DONE: 'done', SIGNAL: { actions: 'deliverSignal' } } },\n done: { type: 'final' },\n failed: { type: 'final' },\n },\n});\n\nexport function createJobRegistry(ctx) {\n ctx.bgJobs = ctx.bgJobs || {};\n let nextId = 1;\n\n function spawnJob(cmd, runPipeline) {\n const id = String(nextId++);\n const actor = createActor(jobMachine.provide({\n actions: {\n deliverSignal: (_, ev) => {\n if (ev?.sig && ctx.signals) ctx.signals.raise(ev.sig);\n },\n },\n }));\n actor.start();\n const job = { id, cmd, actor, done: false, stopped: false, killed: false, startedAt: Date.now() };\n const p = (async () => {\n try { await runPipeline(cmd); job.exit = ctx.lastExitCode; actor.send({ type: 'DONE' }); }\n catch (e) { job.error = e.message; actor.send({ type: 'FAIL' }); }\n finally { job.done = true; }\n })();\n job.promise = p;\n ctx.bgJobs[id] = job;\n if (ctx.swJobs) ctx.swJobs.register(id, cmd).catch(() => {});\n return id;\n }\n\n function list() {\n return Object.values(ctx.bgJobs).map(j => ({ id: j.id, cmd: j.cmd, state: j.actor?.getSnapshot().value || 'unknown', done: j.done, stopped: j.stopped }));\n }\n\n function resolve(ref) {\n const id = ref.startsWith('%') ? ref.slice(1) : ref;\n if (id === '+' || !id) { const keys = Object.keys(ctx.bgJobs); return ctx.bgJobs[keys[keys.length - 1]]; }\n return ctx.bgJobs[id];\n }\n\n return { spawnJob, list, resolve };\n}\n\nexport function makeJobsBuiltin(ctx, registry) {\n return args => {\n const long = args.includes('-l');\n for (const j of registry.list()) ctx.term.write('[' + j.id + '] ' + (j.stopped ? 'Stopped' : j.done ? 'Done' : 'Running') + (long ? ' ' + j.id : '') + ' ' + j.cmd + '\\r\\n');\n };\n}\n\nexport function makeFgBuiltin(ctx, registry) {\n return async args => {\n const job = registry.resolve(args[0] || '+');\n if (!job) { ctx.term.write('fg: no such job\\r\\n'); ctx.lastExitCode = 1; return; }\n if (job.stopped) { job.actor.send({ type: 'CONT' }); job.stopped = false; }\n ctx.currentJob = job;\n try { await job.promise; } finally { ctx.currentJob = null; }\n ctx.lastExitCode = job.exit ?? (job.error ? 1 : 0);\n };\n}\n\nexport function makeBgBuiltin(ctx, registry) {\n return args => {\n const job = registry.resolve(args[0] || '+');\n if (!job) { ctx.term.write('bg: no such job\\r\\n'); ctx.lastExitCode = 1; return; }\n if (job.stopped) { job.actor.send({ type: 'CONT' }); job.stopped = false; }\n ctx.term.write('[' + job.id + ']+ ' + job.cmd + ' &\\r\\n');\n };\n}\n\nexport function makeDisownBuiltin(ctx) {\n return args => {\n for (const a of args) {\n const id = a.startsWith('%') ? a.slice(1) : a;\n if (ctx.bgJobs[id]) { ctx.bgJobs[id].disowned = true; delete ctx.bgJobs[id]; }\n }\n };\n}\n","shell-fd.js":"export function createFdTable(ctx) {\n const table = { 0: { kind: 'stdin', data: '' }, 1: { kind: 'stdout' }, 2: { kind: 'stderr' } };\n ctx.fds = table;\n\n function open(fd, source, mode) {\n const n = parseInt(fd, 10);\n if (isNaN(n)) throw new Error('fd: invalid: ' + fd);\n table[n] = { kind: 'file', path: source, mode: mode || 'r', buf: '' };\n return n;\n }\n\n function close(fd) {\n const n = parseInt(fd, 10);\n delete table[n];\n }\n\n function dup2(src, dst) {\n const s = parseInt(src, 10);\n const d = parseInt(dst, 10);\n if (!table[s]) throw new Error('fd: ' + src + ': bad descriptor');\n table[d] = { ...table[s], duped: s };\n }\n\n function readFd(fd) {\n const n = parseInt(fd, 10);\n const slot = table[n];\n if (!slot) throw new Error('fd ' + fd + ' not open');\n if (slot.kind === 'stdin') return slot.data || '';\n if (slot.kind === 'file') {\n const snap = window.__debug?.idbSnapshot || {};\n return snap[slot.path.replace(/^\\//, '')] || '';\n }\n return slot.buf || '';\n }\n\n function writeFd(fd, data) {\n const n = parseInt(fd, 10);\n const slot = table[n];\n if (!slot) throw new Error('fd ' + fd + ' not open');\n if (slot.kind === 'stdout' || n === 1) ctx.term.write(data.replace(/\\n/g, '\\r\\n'));\n else if (slot.kind === 'stderr' || n === 2) ctx.term.write('\\x1b[31m' + data.replace(/\\n/g, '\\r\\n') + '\\x1b[0m');\n else if (slot.kind === 'file') {\n const snap = window.__debug?.idbSnapshot || (window.__debug.idbSnapshot = {});\n const k = slot.path.replace(/^\\//, '');\n snap[k] = slot.mode === 'a' ? (snap[k] || '') + data : data;\n window.__debug?.idbPersist?.();\n } else { slot.buf = (slot.buf || '') + data; }\n }\n\n return { table, open, close, dup2, readFd, writeFd };\n}\n\nexport function parseFdRedirects(tokens) {\n const out = { args: [], redirs: [] };\n for (let i = 0; i < tokens.length; i++) {\n const t = tokens[i];\n const m = t.match(/^(\\d+)?(>>|>|<|>&|<&)(\\d+)?$/);\n if (m) {\n const from = m[1] != null ? +m[1] : (m[2].includes('<') ? 0 : 1);\n const op = m[2];\n const toNum = m[3] != null ? +m[3] : null;\n if (op === '>&' || op === '<&') { out.redirs.push({ kind: 'dup', fd: from, target: toNum }); continue; }\n const target = tokens[++i];\n out.redirs.push({ kind: op === '<' ? 'read' : 'write', fd: from, path: target, append: op === '>>' });\n continue;\n }\n out.args.push(t);\n }\n return out;\n}\n\nexport function makeExecBuiltin(ctx, fdTable) {\n return args => {\n if (!args.length) return;\n for (const a of args) {\n const m = a.match(/^(\\d+)>(>?)(.+)$/);\n if (m) { fdTable.open(m[1], m[3], m[2] === '>' ? 'a' : 'w'); continue; }\n const r = a.match(/^(\\d+)<(.+)$/);\n if (r) { fdTable.open(r[1], r[2], 'r'); continue; }\n const d = a.match(/^(\\d+)>&(\\d+)$/);\n if (d) { fdTable.dup2(d[2], d[1]); continue; }\n const c = a.match(/^(\\d+)>&-$/);\n if (c) { fdTable.close(c[1]); continue; }\n }\n };\n}\n","shell-procsub.js":"const streams = new Map();\nlet nextStreamId = 1000;\n\nexport function registerStream(data) {\n const id = nextStreamId++;\n streams.set(id, { data, ts: Date.now() });\n setTimeout(() => streams.delete(id), 60000);\n return '/procsub/' + id;\n}\n\nexport function readStream(id) {\n const s = streams.get(+id);\n return s ? s.data : null;\n}\n\nif (typeof navigator !== 'undefined' && navigator.serviceWorker) {\n navigator.serviceWorker.addEventListener('message', ev => {\n if (ev.data?.type === 'PROCSUB_READ') {\n const data = readStream(ev.data.id);\n ev.ports[0]?.postMessage({ data: data || '', found: data !== null });\n }\n });\n}\n\nexport async function expandProcSub(token, captureRun, ctx) {\n const out = [];\n let i = 0;\n while (i < token.length) {\n if (token[i] === '<' && token[i + 1] === '(') {\n const end = findMatch(token, i + 1);\n if (end < 0) { out.push(token[i++]); continue; }\n const cmd = token.slice(i + 2, end);\n const data = captureRun ? captureRun(cmd) : '';\n out.push(registerStream(data));\n i = end + 1; continue;\n }\n if (token[i] === '>' && token[i + 1] === '(') {\n const end = findMatch(token, i + 1);\n if (end < 0) { out.push(token[i++]); continue; }\n const cmd = token.slice(i + 2, end);\n const path = registerStream('');\n ctx.pendingWrites = ctx.pendingWrites || [];\n ctx.pendingWrites.push({ path, cmd });\n out.push(path);\n i = end + 1; continue;\n }\n out.push(token[i++]);\n }\n return out.join('');\n}\n\nfunction findMatch(s, start) {\n let depth = 0;\n for (let i = start; i < s.length; i++) {\n if (s[i] === '(') depth++;\n else if (s[i] === ')') { depth--; if (depth === 0) return i; }\n }\n return -1;\n}\n\nexport function swFetchProcSub(path) {\n const m = path.match(/^\\/procsub\\/(\\d+)$/);\n if (!m) return null;\n return readStream(m[1]);\n}\n","shell-sw-jobs.js":"export function createSwJobs() {\n const registry = new Map();\n\n async function postSw(msg) {\n if (!navigator.serviceWorker?.controller) return null;\n const chan = new MessageChannel();\n const p = new Promise(res => { chan.port1.onmessage = e => res(e.data); setTimeout(() => res(null), 2000); });\n navigator.serviceWorker.controller.postMessage(msg, [chan.port2]);\n return p;\n }\n\n return {\n async register(id, cmd) {\n registry.set(id, { cmd, startedAt: Date.now() });\n await postSw({ type: 'JOB_REGISTER', id, cmd, tabId: getTabId() });\n },\n async unregister(id) {\n registry.delete(id);\n await postSw({ type: 'JOB_UNREGISTER', id, tabId: getTabId() });\n },\n async list() {\n const r = await postSw({ type: 'JOB_LIST' });\n return r?.jobs || [...registry.entries()].map(([id, j]) => ({ id, ...j, tabId: getTabId() }));\n },\n local: () => [...registry.entries()].map(([id, j]) => ({ id, ...j })),\n };\n}\n\nlet _tabId = null;\nfunction getTabId() {\n if (_tabId) return _tabId;\n try { _tabId = sessionStorage.getItem('thebird_tab') || String(Date.now()) + Math.random().toString(36).slice(2, 6); sessionStorage.setItem('thebird_tab', _tabId); } catch { _tabId = 'main'; }\n return _tabId;\n}\n\nexport function makeNohupBuiltin(ctx) {\n return async args => {\n if (!args.length) return;\n ctx.term.write('nohup: ignoring HUP\\r\\n');\n const cmd = args.join(' ');\n if (ctx.jobRegistry) ctx.jobRegistry.spawnJob(cmd, ctx.runPipeline);\n };\n}\n\nexport function makeNetcatStub(ctx) {\n return async (args, _a, stdin) => {\n const host = args.find(a => !a.startsWith('-'));\n const portArg = args[args.indexOf(host) + 1];\n if (!host || !portArg) throw new Error('nc: usage: nc HOST PORT');\n const url = 'http://' + host + ':' + portArg;\n try {\n const r = await fetch(url, { method: stdin ? 'POST' : 'GET', body: stdin || undefined });\n const text = await r.text();\n ctx.term.write(text.replace(/\\n/g, '\\r\\n') + '\\r\\n');\n } catch (e) {\n ctx.term.write('\\x1b[31mnc: ' + e.message + '\\x1b[0m\\r\\n');\n ctx.lastExitCode = 1;\n }\n };\n}\n\nexport function makeCurlBuiltin(ctx) {\n return async (args, _a, stdin) => {\n const url = args.find(a => !a.startsWith('-') && (a.includes('://') || a.startsWith('/dev/tcp/')));\n if (!url) throw new Error('curl: missing url');\n let fetchUrl = url;\n const tcpM = url.match(/^\\/dev\\/tcp\\/([^/]+)\\/(\\d+)(\\/.*)?$/);\n if (tcpM) fetchUrl = 'http://' + tcpM[1] + ':' + tcpM[2] + (tcpM[3] || '/');\n const method = args.includes('-X') ? args[args.indexOf('-X') + 1] : (args.includes('-d') || stdin ? 'POST' : 'GET');\n const body = args.includes('-d') ? args[args.indexOf('-d') + 1] : stdin;\n try {\n const r = await fetch(fetchUrl, { method, body });\n ctx.term.write((await r.text()).replace(/\\n/g, '\\r\\n'));\n } catch (e) { ctx.term.write('\\x1b[31mcurl: ' + e.message + '\\x1b[0m\\r\\n'); ctx.lastExitCode = 1; }\n };\n}\n","shell-exec.js":"import { registerStream, readStream } from './shell-procsub.js';\nimport { tokenize, globToRe } from './shell-parser.js';\nimport { fullExpand, expandBraces, expandTilde } from './shell-expand.js';\nimport { resolvePath } from './shell-builtins.js';\nimport { NODE_VERSION } from './shell-node-modules.js';\n\nexport function makeExpander(ctx, captureRun, parseRedirect) {\n const toKey = p => p.replace(/^\\//, '');\n const snap = () => window.__debug.idbSnapshot || {};\n\n function replaceProcSub(token) {\n let out = ''; let i = 0;\n while (i < token.length) {\n if ((token[i] === '<' || token[i] === '>') && token[i + 1] === '(') {\n let depth = 1; let j = i + 2;\n while (j < token.length && depth > 0) { if (token[j] === '(') depth++; else if (token[j] === ')') depth--; if (depth) j++; }\n if (depth === 0) { out += registerStream(captureRun(token.slice(i + 2, j))); i = j + 1; continue; }\n }\n out += token[i++];\n }\n return out;\n }\n\n function expandGlob(token) {\n if (!token.includes('*') && !token.includes('?') && !token.includes('[')) return [token];\n const prefix = toKey(resolvePath(ctx.cwd, ''));\n const keys = Object.keys(snap()).map(k => prefix && k.startsWith(prefix + '/') ? k.slice(prefix.length + 1) : k);\n const re = globToRe(token);\n const matches = keys.filter(k => re.test(k));\n return matches.length ? matches.sort() : [token];\n }\n\n function expandTokens(tokens) {\n return tokens.flatMap(t => {\n const procsub = t.includes('<(') || t.includes('>(') ? replaceProcSub(t) : t;\n const tilde = expandTilde(procsub, ctx.env);\n const braces = expandBraces(tilde);\n return braces.flatMap(b => expandGlob(fullExpand(b, ctx.env, ctx.lastExitCode, ctx.argv, captureRun, ctx.arrays)));\n });\n }\n return { expandTokens, expandGlob, replaceProcSub };\n}\n\nexport function makeCaptureRun(ctx, BUILTINS, actor, parseRedirect, expandTokens) {\n return function captureRun(line) {\n const raw = tokenize(line); if (!raw.length) return '';\n let out = ''; const orig = ctx.term.write.bind(ctx.term); ctx.term.write = s => { out += s; };\n try { const [cmd, ...args] = parseRedirect(expandTokens(raw)).args; BUILTINS[cmd]?.(args, actor); } finally { ctx.term.write = orig; }\n return out.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n').trim();\n };\n}\n\nconst NODE_HELP = 'Usage: node [options] [script.js] [arguments]\\r\\n -v, --version print Node.js version\\r\\n -e, --eval evaluate script\\r\\n -p, --print evaluate and print result\\r\\n -h, --help print this help\\r\\n';\n\nexport function makeNodeRunner(ctx, actor) {\n const toKey = p => p.replace(/^\\//, '');\n const snap = () => window.__debug.idbSnapshot || {};\n return async function runNode(args, stdinBuf) {\n const term = ctx.term;\n if (!args.length) { actor.send({ type: 'ENTER_REPL' }); term.write('Welcome to Node.js ' + NODE_VERSION + '.\\r\\nType \".help\" for more information.\\r\\n> '); return; }\n const a0 = args[0];\n if (a0 === '-v' || a0 === '--version') { term.write(NODE_VERSION + '\\r\\n'); return; }\n if (a0 === '-h' || a0 === '--help') { term.write(NODE_HELP); return; }\n if (a0 === '-e' || a0 === '--eval') { await ctx.nodeEval(args.slice(1).join(' '), null, [], stdinBuf); return; }\n if (a0 === '-p' || a0 === '--print') { await ctx.nodeEval('process.stdout.write(String(' + args.slice(1).join(' ') + ') + \"\\\\n\")', null, [], stdinBuf); return; }\n const code = snap()[toKey(resolvePath(ctx.cwd, a0))];\n if (code == null) { term.write('\\x1b[31mnode: ' + a0 + ': No such file or directory\\x1b[0m\\r\\n'); ctx.lastExitCode = 1; return; }\n actor.send({ type: 'NODE_START' }); ctx.argv = args;\n try { await ctx.nodeEval(code, a0, args.slice(1), stdinBuf); } finally { ctx.argv = []; }\n };\n}\n\nexport function makeNpmResultRunner(ctx, run) {\n return async function runNpmResult(r) {\n if (!r) return;\n if (r.runInShell) { await run(r.runInShell); return; }\n if (!r.npmChain) return;\n for (const step of r.npmChain) {\n ctx.term.write('\\r\\n> ' + r.pkgName + '@' + r.pkgVersion + ' ' + step.name + '\\r\\n> ' + step.cmd + '\\r\\n\\r\\n');\n ctx.env.npm_lifecycle_event = step.name;\n await run(step.cmd);\n if (ctx.lastExitCode !== 0) return;\n }\n };\n}\n","shell-node-stdlib.js":"function inspectPrimitive(v) {\n if (v === null) return 'null';\n if (v === undefined) return 'undefined';\n const t = typeof v;\n if (t === 'string') return \"'\" + v.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\") + \"'\";\n if (t === 'number' || t === 'boolean' || t === 'bigint') return String(v);\n if (t === 'symbol') return v.toString();\n if (t === 'function') return '[Function' + (v.name ? ': ' + v.name : ' (anonymous)') + ']';\n return null;\n}\n\nexport function inspect(v, opts = {}, depth = 0, seen = new Map(), refCount = { n: 0 }) {\n const prim = inspectPrimitive(v);\n if (prim !== null) return prim;\n if (v instanceof Date) return v.toISOString();\n if (v instanceof RegExp) return v.toString();\n if (v instanceof Error) return v.stack || (v.name + ': ' + v.message);\n if (seen.has(v)) { const id = seen.get(v); if (id.ref == null) id.ref = ++refCount.n; return '[Circular *' + id.ref + ']'; }\n const entry = { ref: null }; seen.set(v, entry);\n const maxDepth = opts.depth ?? 2;\n if (depth > maxDepth) return Array.isArray(v) ? '[Array]' : '[Object]';\n if (Array.isArray(v)) {\n if (!v.length) return '[]';\n return '[ ' + v.map(x => inspect(x, opts, depth + 1, seen, refCount)).join(', ') + ' ]';\n }\n if (v instanceof Map) {\n const entries = [...v.entries()].map(([k, val]) => inspect(k, opts, depth + 1, seen, refCount) + ' => ' + inspect(val, opts, depth + 1, seen, refCount));\n return 'Map(' + v.size + ')' + (v.size ? ' { ' + entries.join(', ') + ' }' : ' {}');\n }\n if (v instanceof Set) {\n const items = [...v].map(x => inspect(x, opts, depth + 1, seen, refCount));\n return 'Set(' + v.size + ')' + (v.size ? ' { ' + items.join(', ') + ' }' : ' {}');\n }\n if (v instanceof Uint8Array) {\n const hex = [...v.slice(0, 16)].map(b => b.toString(16).padStart(2, '0')).join(' ');\n return '<Buffer ' + hex + (v.length > 16 ? ' ... ' + (v.length - 16) + ' more bytes' : '') + '>';\n }\n const keys = Object.keys(v);\n if (!keys.length) return '{}';\n const parts = keys.map(k => {\n const ks = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(k) ? k : \"'\" + k + \"'\";\n return ks + ': ' + inspect(v[k], opts, depth + 1, seen, refCount);\n });\n const ctor = v.constructor && v.constructor !== Object ? v.constructor.name + ' ' : '';\n const body = ctor + '{ ' + parts.join(', ') + ' }';\n return entry.ref != null ? '<ref *' + entry.ref + '> ' + body : body;\n}\n\nexport function format(...args) {\n if (!args.length) return '';\n const fmt = args[0];\n if (typeof fmt !== 'string') return args.map(a => typeof a === 'object' ? inspect(a) : String(a)).join(' ');\n let i = 1;\n const out = fmt.replace(/%[sdifjoO%]/g, m => {\n if (m === '%%') return '%';\n if (i >= args.length) return m;\n const a = args[i++];\n if (m === '%s') return String(a);\n if (m === '%d' || m === '%i') return String(parseInt(a, 10));\n if (m === '%f') return String(parseFloat(a));\n if (m === '%j') return JSON.stringify(a);\n if (m === '%o' || m === '%O') return inspect(a);\n return m;\n });\n const extra = args.slice(i).map(a => typeof a === 'object' ? inspect(a) : String(a));\n return extra.length ? out + ' ' + extra.join(' ') : out;\n}\n\nconst K = new Uint32Array([0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]);\n\nfunction sha256Bytes(data) {\n const msg = typeof data === 'string' ? new TextEncoder().encode(data) : data;\n const bitLen = msg.length * 8;\n const padLen = (msg.length + 9 + 63) & ~63;\n const padded = new Uint8Array(padLen);\n padded.set(msg); padded[msg.length] = 0x80;\n const view = new DataView(padded.buffer);\n view.setUint32(padLen - 4, bitLen >>> 0); view.setUint32(padLen - 8, Math.floor(bitLen / 0x100000000));\n const H = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);\n const W = new Uint32Array(64);\n const rotr = (x, n) => (x >>> n) | (x << (32 - n));\n for (let i = 0; i < padLen; i += 64) {\n for (let j = 0; j < 16; j++) W[j] = view.getUint32(i + j * 4);\n for (let j = 16; j < 64; j++) {\n const s0 = rotr(W[j - 15], 7) ^ rotr(W[j - 15], 18) ^ (W[j - 15] >>> 3);\n const s1 = rotr(W[j - 2], 17) ^ rotr(W[j - 2], 19) ^ (W[j - 2] >>> 10);\n W[j] = (W[j - 16] + s0 + W[j - 7] + s1) >>> 0;\n }\n let [a, b, c, d, e, f, g, h] = H;\n for (let j = 0; j < 64; j++) {\n const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);\n const ch = (e & f) ^ (~e & g);\n const t1 = (h + S1 + ch + K[j] + W[j]) >>> 0;\n const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);\n const mj = (a & b) ^ (a & c) ^ (b & c);\n const t2 = (S0 + mj) >>> 0;\n h = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0;\n }\n H[0] += a; H[1] += b; H[2] += c; H[3] += d; H[4] += e; H[5] += f; H[6] += g; H[7] += h;\n }\n const out = new Uint8Array(32);\n for (let i = 0; i < 8; i++) new DataView(out.buffer).setUint32(i * 4, H[i]);\n return out;\n}\n\nexport function createHash(alg) {\n const a = alg.toLowerCase();\n const chunks = [];\n return {\n update(data) { chunks.push(typeof data === 'string' ? new TextEncoder().encode(data) : data); return this; },\n digest(enc) {\n const total = chunks.reduce((s, c) => s + c.length, 0);\n const buf = new Uint8Array(total); let off = 0;\n for (const c of chunks) { buf.set(c, off); off += c.length; }\n if (a !== 'sha256') throw new Error('hash algorithm not supported: ' + a + ' (sha256 only)');\n const out = sha256Bytes(buf);\n if (enc === 'hex') return [...out].map(b => b.toString(16).padStart(2, '0')).join('');\n if (enc === 'base64') return btoa(String.fromCharCode(...out));\n return out;\n },\n };\n}\n\nlet pakoPromise = null;\nasync function getPako() {\n if (!pakoPromise) pakoPromise = import('https://esm.sh/pako@2.1.0?bundle&target=es2022').then(m => m.default || m);\n return pakoPromise;\n}\n\nexport function createZlib(Buf) {\n return {\n gzipSync: b => { throw new Error('zlib.gzipSync: use gzip (async) in browser — await zlib.gzip(buf)'); },\n gunzipSync: b => { throw new Error('zlib.gunzipSync: use gunzip (async) in browser'); },\n gzip: async (buf, cb) => { try { const p = await getPako(); const out = Buf.from(p.gzip(buf)); if (cb) cb(null, out); return out; } catch (e) { if (cb) cb(e); else throw e; } },\n gunzip: async (buf, cb) => { try { const p = await getPako(); const out = Buf.from(p.ungzip(buf)); if (cb) cb(null, out); return out; } catch (e) { if (cb) cb(e); else throw e; } },\n deflate: async (buf, cb) => { const p = await getPako(); const out = Buf.from(p.deflate(buf)); if (cb) cb(null, out); return out; },\n inflate: async (buf, cb) => { const p = await getPako(); const out = Buf.from(p.inflate(buf)); if (cb) cb(null, out); return out; },\n createGzip: () => ({ pipe: () => {}, on: () => {}, write: () => {}, end: () => {} }),\n createGunzip: () => ({ pipe: () => {}, on: () => {}, write: () => {}, end: () => {} }),\n };\n}\n","shell-node-io.js":"export function createChildProcess(ctx) {\n async function runThroughShell(cmd) {\n const shell = window.__debug?.shell;\n if (!shell?.run) throw new Error('child_process: shell not ready');\n let captured = '';\n const origWrite = ctx.term.write.bind(ctx.term);\n ctx.term.write = s => { captured += s; };\n try { await shell.run(cmd); } finally { ctx.term.write = origWrite; }\n return { stdout: captured.replace(/\\r\\n/g, '\\n').replace(/\\x1b\\[\\d+m/g, ''), code: ctx.lastExitCode | 0 };\n }\n return {\n spawn: (cmd, args = [], opts = {}) => {\n const handlers = { stdout: [], stderr: [], exit: [], close: [], error: [] };\n const emit = (ev, ...a) => { for (const h of handlers[ev] || []) h(...a); };\n const emitter = {\n stdout: { on: (ev, fn) => { if (ev === 'data') handlers.stdout.push(fn); return emitter.stdout; }, pipe: () => emitter.stdout },\n stderr: { on: (ev, fn) => { if (ev === 'data') handlers.stderr.push(fn); return emitter.stderr; } },\n stdin: { write: () => true, end: () => {} },\n on: (ev, fn) => { (handlers[ev] = handlers[ev] || []).push(fn); return emitter; },\n once: (ev, fn) => emitter.on(ev, fn),\n kill: () => {},\n pid: Math.floor(Math.random() * 65535) + 1,\n };\n const line = [cmd, ...args].join(' ');\n queueMicrotask(async () => {\n try { const r = await runThroughShell(line); if (r.stdout) emit('stdout', r.stdout); emit('exit', r.code, null); emit('close', r.code, null); }\n catch (e) { emit('error', e); emit('exit', 1, null); emit('close', 1, null); }\n });\n return emitter;\n },\n exec: (cmd, opts, cb) => {\n if (typeof opts === 'function') { cb = opts; opts = {}; }\n queueMicrotask(async () => { try { const r = await runThroughShell(cmd); cb?.(r.code === 0 ? null : Object.assign(new Error('exit ' + r.code), { code: r.code }), r.stdout, ''); } catch (e) { cb?.(e, '', String(e.message)); } });\n },\n execSync: cmd => { throw new Error('child_process.execSync: use exec() with callback in browser — sync subprocess impossible'); },\n fork: () => { throw new Error('child_process.fork: not supported in browser'); },\n };\n}\n\nexport function createHttpClient(Buf) {\n function makeReq(urlOrOpts, cb) {\n const u = typeof urlOrOpts === 'string' ? urlOrOpts : ('http://' + (urlOrOpts.hostname || 'localhost') + ':' + (urlOrOpts.port || 80) + (urlOrOpts.path || '/'));\n const opts = typeof urlOrOpts === 'object' ? urlOrOpts : {};\n const handlers = { response: [], error: [], finish: [] };\n const emit = (ev, ...a) => { for (const h of handlers[ev] || []) h(...a); };\n let body = '';\n const req = {\n on: (ev, fn) => { (handlers[ev] = handlers[ev] || []).push(fn); return req; },\n write: chunk => { body += String(chunk); return true; },\n end: async chunk => {\n if (chunk != null) body += String(chunk);\n try {\n const res = await fetch(u, { method: opts.method || 'GET', headers: opts.headers || {}, body: body || undefined });\n const text = await res.text();\n const resObj = {\n statusCode: res.status, statusMessage: res.statusText, headers: Object.fromEntries(res.headers.entries()),\n on: (ev, fn) => { if (ev === 'data') queueMicrotask(() => fn(Buf.from(text))); if (ev === 'end') queueMicrotask(() => fn()); return resObj; },\n setEncoding: () => {}, pipe: () => {},\n };\n cb?.(resObj); emit('response', resObj);\n } catch (e) { emit('error', e); }\n },\n setHeader: () => {}, getHeader: () => undefined, abort: () => {}, destroy: () => {},\n };\n return req;\n }\n return {\n request: (urlOrOpts, cb) => makeReq(urlOrOpts, cb),\n get: (urlOrOpts, cb) => { const r = makeReq(urlOrOpts, cb); r.end(); return r; },\n Agent: class Agent {},\n STATUS_CODES: { 200: 'OK', 201: 'Created', 204: 'No Content', 301: 'Moved Permanently', 302: 'Found', 400: 'Bad Request', 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not Found', 500: 'Internal Server Error' },\n };\n}\n\nexport function extendProcess(proc, ctx) {\n proc.execPath = '/usr/local/bin/node';\n proc.argv0 = 'node';\n proc.title = 'node';\n if (!ctx.env.PATH) ctx.env.PATH = '/usr/local/bin:/usr/bin:/bin';\n if (!ctx.env.HOME) ctx.env.HOME = '/root';\n if (!ctx.env.USER) ctx.env.USER = 'root';\n if (!ctx.env.SHELL) ctx.env.SHELL = '/bin/jsh';\n if (!ctx.env.TERM) ctx.env.TERM = 'xterm-256color';\n if (!ctx.env.LANG) ctx.env.LANG = 'C.UTF-8';\n proc.memoryUsage = () => ({ rss: 50000000, heapTotal: 20000000, heapUsed: 10000000, external: 0, arrayBuffers: 0 });\n proc.uptime = () => performance.now() / 1000;\n proc.cpuUsage = () => ({ user: 0, system: 0 });\n proc.getuid = () => 0; proc.getgid = () => 0; proc.geteuid = () => 0; proc.getegid = () => 0;\n proc.umask = () => 0o022;\n proc.features = { tls: false };\n proc.release = { name: 'node', lts: false, sourceUrl: '', headersUrl: '' };\n return proc;\n}\n\nexport function rewriteStack(err, filename) {\n if (!err.stack) return err.message;\n const lines = err.stack.split('\\n');\n const first = lines[0];\n const fname = filename || '[eval]';\n const frames = lines.slice(1)\n .filter(l => !l.includes('new Function') && !l.includes('AsyncFunction') && !l.includes('<anonymous>'))\n .map(l => l.replace(/\\bat eval \\(eval at[^)]*\\), /, 'at ').replace(/:(\\d+):(\\d+)\\)?$/, (_, ln, col) => ':' + ln + ':' + col))\n .slice(0, 5);\n return [first, ...frames].join('\\n') + '\\n\\nNode.js v23.10.0';\n}\n\nexport function isEsmCode(code) {\n const stripped = code.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '').replace(/\\/\\/.*$/gm, '');\n return /^\\s*(import\\s+[\\w*{]|import\\s*['\"`]|export\\s+(default|const|function|class|let|var|\\{))/m.test(stripped);\n}\n\nexport async function runEsm(code, scope) {\n const injectionKeys = Object.keys(scope);\n const preamble = injectionKeys.map(k => `const ${k} = globalThis.__esmScope__.${k};`).join('\\n');\n globalThis.__esmScope__ = scope;\n const blob = new Blob([preamble + '\\n' + code], { type: 'text/javascript' });\n const url = URL.createObjectURL(blob);\n try { return await import(url); } finally { URL.revokeObjectURL(url); }\n}\n\nexport function parseDotEnv(text) {\n const out = {};\n for (const line of text.split(/\\r?\\n/)) {\n const m = line.match(/^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(.*?)\\s*$/);\n if (!m) continue;\n let v = m[2];\n if ((v.startsWith('\"') && v.endsWith('\"')) || (v.startsWith(\"'\") && v.endsWith(\"'\"))) v = v.slice(1, -1);\n out[m[1]] = v;\n }\n return out;\n}\n","shell-node-crypto.js":"const K256 = new Uint32Array([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]);\nconst rotr32 = (x, n) => (x >>> n) | (x << (32 - n));\n\nfunction padMsg(msg, blockSize, lenBytes, little = false) {\n const bitLen = msg.length * 8;\n const padLen = ((msg.length + lenBytes + 1 + blockSize - 1) & ~(blockSize - 1));\n const p = new Uint8Array(padLen); p.set(msg); p[msg.length] = 0x80;\n const v = new DataView(p.buffer);\n if (little) { v.setUint32(padLen - 8, bitLen >>> 0, true); v.setUint32(padLen - 4, Math.floor(bitLen / 0x100000000), true); }\n else { v.setUint32(padLen - 4, bitLen >>> 0); v.setUint32(padLen - 8, Math.floor(bitLen / 0x100000000)); }\n return p;\n}\n\nexport function sha1(msg) {\n const p = padMsg(msg, 64, 8); const v = new DataView(p.buffer);\n let h0 = 0x67452301, h1 = 0xefcdab89, h2 = 0x98badcfe, h3 = 0x10325476, h4 = 0xc3d2e1f0;\n const W = new Uint32Array(80);\n for (let i = 0; i < p.length; i += 64) {\n for (let j = 0; j < 16; j++) W[j] = v.getUint32(i + j * 4);\n for (let j = 16; j < 80; j++) W[j] = rotr32(W[j - 3] ^ W[j - 8] ^ W[j - 14] ^ W[j - 16], 31);\n let a = h0, b = h1, c = h2, d = h3, e = h4;\n for (let j = 0; j < 80; j++) {\n const f = j < 20 ? (b & c) | (~b & d) : j < 40 ? b ^ c ^ d : j < 60 ? (b & c) | (b & d) | (c & d) : b ^ c ^ d;\n const k = j < 20 ? 0x5a827999 : j < 40 ? 0x6ed9eba1 : j < 60 ? 0x8f1bbcdc : 0xca62c1d6;\n const t = (rotr32(a, 27) + f + e + k + W[j]) >>> 0;\n e = d; d = c; c = rotr32(b, 2); b = a; a = t;\n }\n h0 = (h0 + a) >>> 0; h1 = (h1 + b) >>> 0; h2 = (h2 + c) >>> 0; h3 = (h3 + d) >>> 0; h4 = (h4 + e) >>> 0;\n }\n const out = new Uint8Array(20); const ov = new DataView(out.buffer);\n ov.setUint32(0, h0); ov.setUint32(4, h1); ov.setUint32(8, h2); ov.setUint32(12, h3); ov.setUint32(16, h4);\n return out;\n}\n\nexport function sha256(msg) {\n const p = padMsg(msg, 64, 8); const v = new DataView(p.buffer);\n const H = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);\n const W = new Uint32Array(64);\n for (let i = 0; i < p.length; i += 64) {\n for (let j = 0; j < 16; j++) W[j] = v.getUint32(i + j * 4);\n for (let j = 16; j < 64; j++) { const s0 = rotr32(W[j-15], 7) ^ rotr32(W[j-15], 18) ^ (W[j-15] >>> 3); const s1 = rotr32(W[j-2], 17) ^ rotr32(W[j-2], 19) ^ (W[j-2] >>> 10); W[j] = (W[j-16] + s0 + W[j-7] + s1) >>> 0; }\n let [a, b, c, d, e, f, g, h] = H;\n for (let j = 0; j < 64; j++) { const S1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25); const ch = (e & f) ^ (~e & g); const t1 = (h + S1 + ch + K256[j] + W[j]) >>> 0; const S0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22); const mj = (a & b) ^ (a & c) ^ (b & c); const t2 = (S0 + mj) >>> 0; h = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0; }\n H[0] += a; H[1] += b; H[2] += c; H[3] += d; H[4] += e; H[5] += f; H[6] += g; H[7] += h;\n }\n const out = new Uint8Array(32);\n for (let i = 0; i < 8; i++) new DataView(out.buffer).setUint32(i * 4, H[i]);\n return out;\n}\n\nexport function md5(msg) {\n const p = padMsg(msg, 64, 8, true); const v = new DataView(p.buffer);\n let a0 = 0x67452301, b0 = 0xefcdab89, c0 = 0x98badcfe, d0 = 0x10325476;\n const s = [7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21];\n const K = new Uint32Array([0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee,0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501,0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be,0x6b901122,0xfd987193,0xa679438e,0x49b40821,0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa,0xd62f105d,0x02441453,0xd8a1e681,0xe7d3fbc8,0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed,0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a,0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c,0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70,0x289b7ec6,0xeaa127fa,0xd4ef3085,0x04881d05,0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665,0xf4292244,0x432aff97,0xab9423a7,0xfc93a039,0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1,0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1,0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391]);\n for (let i = 0; i < p.length; i += 64) {\n const M = new Uint32Array(16); for (let j = 0; j < 16; j++) M[j] = v.getUint32(i + j * 4, true);\n let A = a0, B = b0, C = c0, D = d0;\n for (let j = 0; j < 64; j++) { let F, g; if (j < 16) { F = (B & C) | (~B & D); g = j; } else if (j < 32) { F = (D & B) | (~D & C); g = (5 * j + 1) % 16; } else if (j < 48) { F = B ^ C ^ D; g = (3 * j + 5) % 16; } else { F = C ^ (B | ~D); g = (7 * j) % 16; }\n F = (F + A + K[j] + M[g]) >>> 0; A = D; D = C; C = B; B = (B + (((F << s[j]) | (F >>> (32 - s[j]))) >>> 0)) >>> 0;\n }\n a0 = (a0 + A) >>> 0; b0 = (b0 + B) >>> 0; c0 = (c0 + C) >>> 0; d0 = (d0 + D) >>> 0;\n }\n const out = new Uint8Array(16); const ov = new DataView(out.buffer);\n ov.setUint32(0, a0, true); ov.setUint32(4, b0, true); ov.setUint32(8, c0, true); ov.setUint32(12, d0, true);\n return out;\n}\n\nconst K512 = [0x428a2f98d728ae22n,0x7137449123ef65cdn,0xb5c0fbcfec4d3b2fn,0xe9b5dba58189dbbcn,0x3956c25bf348b538n,0x59f111f1b605d019n,0x923f82a4af194f9bn,0xab1c5ed5da6d8118n,0xd807aa98a3030242n,0x12835b0145706fben,0x243185be4ee4b28cn,0x550c7dc3d5ffb4e2n,0x72be5d74f27b896fn,0x80deb1fe3b1696b1n,0x9bdc06a725c71235n,0xc19bf174cf692694n,0xe49b69c19ef14ad2n,0xefbe4786384f25e3n,0x0fc19dc68b8cd5b5n,0x240ca1cc77ac9c65n,0x2de92c6f592b0275n,0x4a7484aa6ea6e483n,0x5cb0a9dcbd41fbd4n,0x76f988da831153b5n,0x983e5152ee66dfabn,0xa831c66d2db43210n,0xb00327c898fb213fn,0xbf597fc7beef0ee4n,0xc6e00bf33da88fc2n,0xd5a79147930aa725n,0x06ca6351e003826fn,0x142929670a0e6e70n,0x27b70a8546d22ffcn,0x2e1b21385c26c926n,0x4d2c6dfc5ac42aedn,0x53380d139d95b3dfn,0x650a73548baf63den,0x766a0abb3c77b2a8n,0x81c2c92e47edaee6n,0x92722c851482353bn,0xa2bfe8a14cf10364n,0xa81a664bbc423001n,0xc24b8b70d0f89791n,0xc76c51a30654be30n,0xd192e819d6ef5218n,0xd69906245565a910n,0xf40e35855771202an,0x106aa07032bbd1b8n,0x19a4c116b8d2d0c8n,0x1e376c085141ab53n,0x2748774cdf8eeb99n,0x34b0bcb5e19b48a8n,0x391c0cb3c5c95a63n,0x4ed8aa4ae3418acbn,0x5b9cca4f7763e373n,0x682e6ff3d6b2b8a3n,0x748f82ee5defb2fcn,0x78a5636f43172f60n,0x84c87814a1f0ab72n,0x8cc702081a6439ecn,0x90befffa23631e28n,0xa4506cebde82bde9n,0xbef9a3f7b2c67915n,0xc67178f2e372532bn,0xca273eceea26619cn,0xd186b8c721c0c207n,0xeada7dd6cde0eb1en,0xf57d4f7fee6ed178n,0x06f067aa72176fban,0x0a637dc5a2c898a6n,0x113f9804bef90daen,0x1b710b35131c471bn,0x28db77f523047d84n,0x32caab7b40c72493n,0x3c9ebe0a15c9bebcn,0x431d67c49c100d4cn,0x4cc5d4becb3e42b6n,0x597f299cfc657e2an,0x5fcb6fab3ad6faecn,0x6c44198c4a475817n];\nconst MASK64 = 0xffffffffffffffffn;\nconst rotr64 = (x, n) => (((x >> BigInt(n)) | (x << BigInt(64 - n))) & MASK64);\n\nexport function sha512(msg) {\n const p = padMsg(msg, 128, 16); const v = new DataView(p.buffer);\n const H = [0x6a09e667f3bcc908n, 0xbb67ae8584caa73bn, 0x3c6ef372fe94f82bn, 0xa54ff53a5f1d36f1n, 0x510e527fade682d1n, 0x9b05688c2b3e6c1fn, 0x1f83d9abfb41bd6bn, 0x5be0cd19137e2179n];\n const W = new Array(80);\n for (let i = 0; i < p.length; i += 128) {\n for (let j = 0; j < 16; j++) W[j] = (BigInt(v.getUint32(i + j * 8)) << 32n) | BigInt(v.getUint32(i + j * 8 + 4));\n for (let j = 16; j < 80; j++) { const s0 = rotr64(W[j-15], 1) ^ rotr64(W[j-15], 8) ^ (W[j-15] >> 7n); const s1 = rotr64(W[j-2], 19) ^ rotr64(W[j-2], 61) ^ (W[j-2] >> 6n); W[j] = (W[j-16] + s0 + W[j-7] + s1) & MASK64; }\n let [a, b, c, d, e, f, g, h] = H;\n for (let j = 0; j < 80; j++) { const S1 = rotr64(e, 14) ^ rotr64(e, 18) ^ rotr64(e, 41); const ch = (e & f) ^ (~e & MASK64 & g); const t1 = (h + S1 + ch + K512[j] + W[j]) & MASK64; const S0 = rotr64(a, 28) ^ rotr64(a, 34) ^ rotr64(a, 39); const mj = (a & b) ^ (a & c) ^ (b & c); const t2 = (S0 + mj) & MASK64; h = g; g = f; f = e; e = (d + t1) & MASK64; d = c; c = b; b = a; a = (t1 + t2) & MASK64; }\n H[0] = (H[0] + a) & MASK64; H[1] = (H[1] + b) & MASK64; H[2] = (H[2] + c) & MASK64; H[3] = (H[3] + d) & MASK64; H[4] = (H[4] + e) & MASK64; H[5] = (H[5] + f) & MASK64; H[6] = (H[6] + g) & MASK64; H[7] = (H[7] + h) & MASK64;\n }\n const out = new Uint8Array(64); const ov = new DataView(out.buffer);\n for (let i = 0; i < 8; i++) { ov.setUint32(i * 8, Number(H[i] >> 32n)); ov.setUint32(i * 8 + 4, Number(H[i] & 0xffffffffn)); }\n return out;\n}\n\nfunction concat(a, b) { const o = new Uint8Array(a.length + b.length); o.set(a); o.set(b, a.length); return o; }\nfunction toBytes(d) { return typeof d === 'string' ? new TextEncoder().encode(d) : d; }\n\nconst HASH_IMPLS = { sha1: { fn: sha1, size: 64, len: 20 }, sha256: { fn: sha256, size: 64, len: 32 }, sha512: { fn: sha512, size: 128, len: 64 }, md5: { fn: md5, size: 64, len: 16 } };\n\nexport function createHash(alg) {\n const a = alg.toLowerCase();\n const spec = HASH_IMPLS[a];\n if (!spec) throw new Error('hash algorithm not supported: ' + a);\n const chunks = [];\n return {\n update(data) { chunks.push(toBytes(data)); return this; },\n digest(enc) { const total = chunks.reduce((s, c) => s + c.length, 0); const buf = new Uint8Array(total); let off = 0; for (const c of chunks) { buf.set(c, off); off += c.length; } const out = spec.fn(buf); if (enc === 'hex') return [...out].map(b => b.toString(16).padStart(2, '0')).join(''); if (enc === 'base64') return btoa(String.fromCharCode(...out)); return out; },\n };\n}\n\nexport function createHmac(alg, key) {\n const spec = HASH_IMPLS[alg.toLowerCase()];\n if (!spec) throw new Error('hmac algorithm not supported: ' + alg);\n let k = toBytes(key);\n if (k.length > spec.size) k = spec.fn(k);\n if (k.length < spec.size) { const pad = new Uint8Array(spec.size); pad.set(k); k = pad; }\n const ipad = new Uint8Array(spec.size), opad = new Uint8Array(spec.size);\n for (let i = 0; i < spec.size; i++) { ipad[i] = k[i] ^ 0x36; opad[i] = k[i] ^ 0x5c; }\n const chunks = [];\n return {\n update(data) { chunks.push(toBytes(data)); return this; },\n digest(enc) { const total = chunks.reduce((s, c) => s + c.length, 0); const buf = new Uint8Array(total); let off = 0; for (const c of chunks) { buf.set(c, off); off += c.length; } const inner = spec.fn(concat(ipad, buf)); const out = spec.fn(concat(opad, inner)); if (enc === 'hex') return [...out].map(b => b.toString(16).padStart(2, '0')).join(''); if (enc === 'base64') return btoa(String.fromCharCode(...out)); return out; },\n };\n}\n\nexport function pbkdf2Sync(password, salt, iterations, keylen, digest) {\n const spec = HASH_IMPLS[digest.toLowerCase()];\n if (!spec) throw new Error('pbkdf2 digest not supported: ' + digest);\n const hLen = spec.len;\n const saltB = toBytes(salt);\n const blocks = Math.ceil(keylen / hLen);\n const out = new Uint8Array(blocks * hLen);\n for (let i = 1; i <= blocks; i++) {\n const block = new Uint8Array(saltB.length + 4); block.set(saltB); const dv = new DataView(block.buffer); dv.setUint32(saltB.length, i);\n let U = createHmac(digest, password).update(block).digest();\n let T = new Uint8Array(U);\n for (let j = 1; j < iterations; j++) { U = createHmac(digest, password).update(U).digest(); for (let k = 0; k < hLen; k++) T[k] ^= U[k]; }\n out.set(T, (i - 1) * hLen);\n }\n return out.slice(0, keylen);\n}\n\nexport function randomBytes(n) { const out = new Uint8Array(n); (globalThis.crypto || { getRandomValues: a => { for (let i = 0; i < a.length; i++) a[i] = Math.random() * 256 | 0; return a; } }).getRandomValues(out); return out; }\n","shell-node-resolve.js":"const toKey = p => p.replace(/^\\//, '');\r\n\r\nconst CONDITIONS = ['node', 'import', 'require', 'default', 'browser'];\r\nfunction pickCondition(cond) {\r\n if (typeof cond === 'string') return cond;\r\n if (Array.isArray(cond)) { for (const c of cond) { const r = pickCondition(c); if (r) return r; } return null; }\r\n if (!cond || typeof cond !== 'object') return null;\r\n for (const k of CONDITIONS) if (k in cond) { const r = pickCondition(cond[k]); if (r) return r; }\r\n return null;\r\n}\r\nfunction matchPattern(patternKey, target) {\r\n if (!patternKey.includes('*')) return null;\r\n const [pre, post] = patternKey.split('*');\r\n if (target.startsWith(pre) && target.endsWith(post)) return target.slice(pre.length, target.length - post.length);\r\n return null;\r\n}\r\nexport function resolveExports(pkgJson, subpath) {\r\n const exp = pkgJson.exports;\r\n if (!exp) return null;\r\n if (typeof exp === 'string') return subpath === '.' ? exp : null;\r\n const key = subpath === '.' ? '.' : './' + subpath.replace(/^\\.\\//, '');\r\n if (exp[key]) return pickCondition(exp[key]);\r\n if (subpath === '.' && !('.' in exp) && !Object.keys(exp).some(k => k.startsWith('.'))) return pickCondition(exp);\r\n for (const pk of Object.keys(exp)) { const m = matchPattern(pk, key); if (m !== null) { const t = pickCondition(exp[pk]); return t ? t.replace('*', m) : null; } }\r\n return null;\r\n}\r\nexport function rewriteSpecifier(id) {\r\n if (id.startsWith('jsr:')) return 'https://esm.sh/jsr/' + id.slice(4);\r\n if (id.startsWith('npm:')) return 'https://esm.sh/' + id.slice(4);\r\n if (id.startsWith('https://') || id.startsWith('http://')) return id;\r\n return null;\r\n}\r\n\r\nexport function resolveImports(pkgJson, subpath) {\r\n const imps = pkgJson.imports;\r\n if (!imps || !subpath.startsWith('#')) return null;\r\n if (imps[subpath]) return pickCondition(imps[subpath]);\r\n for (const pk of Object.keys(imps)) { const m = matchPattern(pk, subpath); if (m !== null) { const t = pickCondition(imps[pk]); return t ? t.replace('*', m) : null; } }\r\n return null;\r\n}\r\n\r\nexport function walkUpNodeModules(snap, startDir, pkgName) {\r\n let dir = startDir.replace(/\\/$/, '') || '/';\r\n while (true) {\r\n const candidate = (dir === '/' ? '' : dir) + '/node_modules/' + pkgName;\r\n const candKey = toKey(candidate);\r\n if ((candKey + '/package.json') in snap || (candKey + '/index.js') in snap || (candKey + '.js') in snap) return candidate;\r\n if (dir === '/' || dir === '') return null;\r\n const up = dir.slice(0, dir.lastIndexOf('/')) || '/';\r\n if (up === dir) return null;\r\n dir = up;\r\n }\r\n}\r\n\r\nexport function resolvePackageEntry(snap, pkgDir) {\r\n const pjKey = toKey(pkgDir) + '/package.json';\r\n if (!(pjKey in snap)) return null;\r\n let pj;\r\n try { pj = JSON.parse(snap[pjKey]); } catch { return null; }\r\n const resolved = resolveExports(pj, '.');\r\n if (resolved) return pkgDir + '/' + resolved.replace(/^\\.\\//, '');\r\n return pkgDir + '/' + (pj.main || 'index.js').replace(/^\\.\\//, '');\r\n}\r\n\r\nexport function makeModuleModule(requireFn, MODULES) {\r\n return {\r\n builtinModules: Object.keys(MODULES).filter(k => !k.startsWith('node:')).sort(),\r\n createRequire: () => requireFn,\r\n _resolveFilename: (id, parent) => requireFn.resolve(id),\r\n _cache: requireFn.cache,\r\n _pathCache: {},\r\n Module: class Module { constructor(id) { this.id = id; this.exports = {}; this.filename = id; this.loaded = false; this.children = []; this.paths = []; } },\r\n syncBuiltinESMExports: () => {},\r\n wrap: s => '(function (exports, require, module, __filename, __dirname) { ' + s + '\\n});',\r\n wrapper: ['(function (exports, require, module, __filename, __dirname) { ', '\\n});'],\r\n };\r\n}\r\n\r\nexport function makeModuleNotFoundError(id, requireStack) {\r\n const err = new Error(\"Cannot find module '\" + id + \"'\" + (requireStack ? '\\nRequire stack:\\n- ' + requireStack.join('\\n- ') : ''));\r\n err.code = 'MODULE_NOT_FOUND';\r\n err.requireStack = requireStack || [];\r\n return err;\r\n}\r\n\r\nexport function makeFsPromises(fsSync) {\r\n const wrap = fn => async (...args) => fn(...args);\r\n return {\r\n readFile: async (p, enc) => fsSync.readFileSync(p, enc),\r\n writeFile: async (p, d) => fsSync.writeFileSync(p, d),\r\n appendFile: async (p, d) => fsSync.appendFileSync(p, d),\r\n access: async p => fsSync.accessSync(p),\r\n stat: async p => fsSync.statSync(p),\r\n readdir: async p => fsSync.readdirSync(p),\r\n mkdir: async (p, o) => fsSync.mkdirSync(p, o),\r\n rm: async (p, o) => fsSync.rmSync(p, o),\r\n rmdir: async (p, o) => fsSync.rmdirSync(p, o),\r\n unlink: async p => fsSync.unlinkSync(p),\r\n rename: async (o, n) => fsSync.renameSync(o, n),\r\n copyFile: async (s, d) => fsSync.copyFileSync(s, d),\r\n realpath: async p => fsSync.realpathSync(p),\r\n open: async p => ({ close: async () => {}, readFile: async enc => fsSync.readFileSync(p, enc), writeFile: async d => fsSync.writeFileSync(p, d) }),\r\n };\r\n}\r\n\r\nexport function makeFsWatch() {\r\n return (path, opts, listener) => {\r\n if (typeof opts === 'function') { listener = opts; opts = {}; }\r\n const handlers = { change: listener ? [listener] : [], error: [], close: [] };\r\n const w = {\r\n on: (ev, fn) => { (handlers[ev] = handlers[ev] || []).push(fn); return w; },\r\n close: () => { for (const h of handlers.close) h(); },\r\n ref: () => w, unref: () => w,\r\n };\r\n return w;\r\n };\r\n}\r\n\r\nexport function makeNetStub() {\r\n return {\r\n Socket: class Socket { constructor() { throw new Error('net.Socket: not supported in browser — use fetch() or WebSocket'); } },\r\n createServer: () => { throw new Error('net.createServer: not supported in browser — use express via http builtin'); },\r\n connect: () => { throw new Error('net.connect: not supported in browser'); },\r\n isIP: ip => /^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(ip) ? 4 : ip.includes(':') ? 6 : 0,\r\n isIPv4: ip => /^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(ip),\r\n isIPv6: ip => ip.includes(':'),\r\n };\r\n}\r\n\r\nexport function makeDgramStub() {\r\n return {\r\n createSocket: () => { throw new Error('dgram.createSocket: UDP not available in browser'); },\r\n Socket: class { constructor() { throw new Error('dgram.Socket: UDP not available in browser'); } },\r\n };\r\n}\r\n\r\nexport function makeWorkerThreadsStub() {\r\n return {\r\n Worker: class { constructor() { throw new Error('worker_threads.Worker: not supported — use Web Worker via new Worker(url)'); } },\r\n isMainThread: true,\r\n parentPort: null,\r\n workerData: null,\r\n threadId: 0,\r\n MessageChannel: globalThis.MessageChannel,\r\n MessagePort: globalThis.MessagePort,\r\n };\r\n}\r\n","shell-node-cipher.js":"const ALG_MAP={\r\n 'aes-128-gcm':{name:'AES-GCM',length:128},'aes-192-gcm':{name:'AES-GCM',length:192},'aes-256-gcm':{name:'AES-GCM',length:256},\r\n 'aes-128-cbc':{name:'AES-CBC',length:128},'aes-192-cbc':{name:'AES-CBC',length:192},'aes-256-cbc':{name:'AES-CBC',length:256},\r\n 'aes-128-ctr':{name:'AES-CTR',length:128},'aes-256-ctr':{name:'AES-CTR',length:256},\r\n};\r\nconst toBytes=d=>typeof d==='string'?new TextEncoder().encode(d):d instanceof Uint8Array?d:new Uint8Array(d);\r\nconst concat=list=>{const t=list.reduce((s,c)=>s+c.length,0);const out=new Uint8Array(t);let o=0;for(const c of list){out.set(c,o);o+=c.length;}return out;};\r\n\r\nasync function importKey(alg,keyBytes,usages){\r\n return crypto.subtle.importKey('raw',keyBytes,{name:alg.name,length:alg.length},false,usages);\r\n}\r\n\r\nfunction makeCipher(alg,keyBytes,iv,decrypt=false){\r\n const spec=ALG_MAP[alg];\r\n if(!spec)throw new Error(`cipher algorithm not supported: ${alg}`);\r\n const chunks=[];let authTag=null;let aad=null;let final=null;\r\n const usage=decrypt?['decrypt']:['encrypt'];\r\n return {\r\n update(data,inputEnc,outputEnc){const bytes=inputEnc?Buffer.from(data,inputEnc):toBytes(data);chunks.push(bytes);return Buffer.alloc(0);},\r\n async final(enc){const input=concat(chunks);const key=await importKey(spec,toBytes(keyBytes),usage);const params={name:spec.name,iv:toBytes(iv)};if(spec.name==='AES-GCM'&&aad)params.additionalData=aad;if(decrypt&&spec.name==='AES-GCM'&&authTag){const full=concat([input,authTag]);const out=new Uint8Array(await crypto.subtle.decrypt(params,key,full));return enc?Buffer.from(out).toString(enc):Buffer.from(out);}const op=decrypt?crypto.subtle.decrypt.bind(crypto.subtle):crypto.subtle.encrypt.bind(crypto.subtle);const out=new Uint8Array(await op(params,key,input));if(!decrypt&&spec.name==='AES-GCM'){authTag=out.slice(-16);const ct=out.slice(0,-16);final=Buffer.from(ct);return enc?final.toString(enc):final;}return enc?Buffer.from(out).toString(enc):Buffer.from(out);},\r\n setAAD(d){aad=toBytes(d);return this;},\r\n setAuthTag(t){authTag=toBytes(t);return this;},\r\n getAuthTag(){return authTag?Buffer.from(authTag):null;},\r\n setAutoPadding(){return this;},\r\n };\r\n}\r\n\r\nexport function extendCrypto(cryptoMod,Buf){\r\n globalThis.Buffer=globalThis.Buffer||Buf;\r\n cryptoMod.createCipheriv=(alg,key,iv)=>makeCipher(alg.toLowerCase(),key,iv,false);\r\n cryptoMod.createDecipheriv=(alg,key,iv)=>makeCipher(alg.toLowerCase(),key,iv,true);\r\n cryptoMod.createCipher=()=>{throw new Error('crypto.createCipher: deprecated and unsafe — use createCipheriv');};\r\n cryptoMod.createDecipher=()=>{throw new Error('crypto.createDecipher: deprecated — use createDecipheriv');};\r\n cryptoMod.generateKeyPair=(type,opts,cb)=>{cryptoMod.generateKeyPairAsync?.(type,opts).then(r=>cb(null,r.publicKey,r.privateKey),cb);};\r\n cryptoMod.generateKeyPairSync=()=>{throw new Error('crypto.generateKeyPairSync: synchronous keypair generation not available in browser — use generateKeyPair (async)');};\r\n cryptoMod.generateKeyPairAsync=async(type,opts={})=>{const algMap={rsa:{name:'RSASSA-PKCS1-v1_5',modulusLength:opts.modulusLength||2048,publicExponent:new Uint8Array([1,0,1]),hash:'SHA-256'},ec:{name:'ECDSA',namedCurve:opts.namedCurve||'P-256'}};const alg=algMap[type];if(!alg)throw new Error(`unsupported key type: ${type}`);const kp=await crypto.subtle.generateKey(alg,true,type==='rsa'?['sign','verify']:['sign','verify']);const pub=new Uint8Array(await crypto.subtle.exportKey('spki',kp.publicKey));const priv=new Uint8Array(await crypto.subtle.exportKey('pkcs8',kp.privateKey));const pem=(b,label)=>`-----BEGIN ${label}-----\\n${btoa(String.fromCharCode(...b)).match(/.{1,64}/g).join('\\n')}\\n-----END ${label}-----\\n`;return {publicKey:pem(pub,'PUBLIC KEY'),privateKey:pem(priv,'PRIVATE KEY')};};\r\n const pemToBytes=pem=>{const m=pem.match(/-----BEGIN [^-]+-----([\\s\\S]+?)-----END/);if(!m)throw new Error('invalid PEM');return Uint8Array.from(atob(m[1].replace(/\\s/g,'')),c=>c.charCodeAt(0));};\r\n const hashFromAlg=a=>{const u=a.toUpperCase();if(u.includes('SHA512')||u.includes('SHA-512'))return'SHA-512';if(u.includes('SHA384')||u.includes('SHA-384'))return'SHA-384';if(u.includes('SHA1')||u.includes('SHA-1'))return'SHA-1';return'SHA-256';};\r\n const isEcBytes=bytes=>{const s=String.fromCharCode(...bytes.slice(0,Math.min(bytes.length,80)));return s.includes('\\x2A\\x86\\x48\\xCE\\x3D\\x02\\x01');};\r\n const importForSign=async(pem,hash)=>{const bytes=pemToBytes(pem);const ec=isEcBytes(bytes);const params=ec?{name:'ECDSA',namedCurve:'P-256'}:{name:'RSASSA-PKCS1-v1_5',hash};const k=await crypto.subtle.importKey('pkcs8',bytes,params,false,['sign']);return{key:k,alg:ec?{name:'ECDSA',hash}:{name:'RSASSA-PKCS1-v1_5'}};};\r\n const importForVerify=async(pem,hash)=>{const bytes=pemToBytes(pem);const ec=isEcBytes(bytes);const params=ec?{name:'ECDSA',namedCurve:'P-256'}:{name:'RSASSA-PKCS1-v1_5',hash};const k=await crypto.subtle.importKey('spki',bytes,params,false,['verify']);return{key:k,alg:ec?{name:'ECDSA',hash}:{name:'RSASSA-PKCS1-v1_5'}};};\r\n cryptoMod.signAsync=async(alg,data,keyPem)=>{const pem=typeof keyPem==='string'?keyPem:keyPem.key;const {key,alg:a}=await importForSign(pem,hashFromAlg(alg));const sig=await crypto.subtle.sign(a,key,toBytes(data));return Buf.from(new Uint8Array(sig));};\r\n cryptoMod.verifyAsync=async(alg,data,keyPem,sig)=>{const pem=typeof keyPem==='string'?keyPem:keyPem.key;const {key,alg:a}=await importForVerify(pem,hashFromAlg(alg));return crypto.subtle.verify(a,key,toBytes(sig),toBytes(data));};\r\n cryptoMod.hkdf=(digest,ikm,salt,info,keylen,cb)=>{cryptoMod.hkdfAsync(digest,ikm,salt,info,keylen).then(r=>cb(null,r),cb);};\r\n cryptoMod.hkdfSync=()=>{throw new Error('crypto.hkdfSync: use async hkdf in browser (webcrypto is async-only)');};\r\n cryptoMod.hkdfAsync=async(digest,ikm,salt,info,keylen)=>{const hash=hashFromAlg(digest);const k=await crypto.subtle.importKey('raw',toBytes(ikm),'HKDF',false,['deriveBits']);const bits=await crypto.subtle.deriveBits({name:'HKDF',hash,salt:toBytes(salt),info:toBytes(info)},k,keylen*8);return Buf.from(new Uint8Array(bits));};\r\n cryptoMod.createECDH=curve=>{const nc=curve==='prime256v1'?'P-256':curve==='secp384r1'?'P-384':curve==='secp521r1'?'P-521':curve;let kp=null;return{generateKeys:async()=>{kp=await crypto.subtle.generateKey({name:'ECDH',namedCurve:nc},true,['deriveBits']);const pub=await crypto.subtle.exportKey('raw',kp.publicKey);return Buf.from(new Uint8Array(pub));},getPublicKey:async()=>{if(!kp)throw new Error('generateKeys first');const pub=await crypto.subtle.exportKey('raw',kp.publicKey);return Buf.from(new Uint8Array(pub));},computeSecret:async otherPub=>{if(!kp)throw new Error('generateKeys first');const other=await crypto.subtle.importKey('raw',toBytes(otherPub),{name:'ECDH',namedCurve:nc},false,[]);const bits=await crypto.subtle.deriveBits({name:'ECDH',public:other},kp.privateKey,256);return Buf.from(new Uint8Array(bits));}};};\r\n cryptoMod.createDiffieHellman=()=>{throw new Error('crypto.createDiffieHellman: classic modp DH not supported — use createECDH(\\'prime256v1\\')');};\r\n cryptoMod.sign=(alg,data,key,cb)=>{if(cb)cryptoMod.signAsync(alg,data,key).then(r=>cb(null,r),cb);else return cryptoMod.signAsync(alg,data,key);};\r\n cryptoMod.verify=(alg,data,key,sig,cb)=>{if(cb)cryptoMod.verifyAsync(alg,data,key,sig).then(r=>cb(null,r),cb);else return cryptoMod.verifyAsync(alg,data,key,sig);};\r\n cryptoMod.createSign=alg=>{const parts=[];return{update(d){parts.push(toBytes(d));return this;},async sign(key,enc){const data=concat(parts);const sig=await cryptoMod.signAsync(alg,data,key);return enc?sig.toString(enc):sig;}};};\r\n cryptoMod.createVerify=alg=>{const parts=[];return{update(d){parts.push(toBytes(d));return this;},async verify(key,sig,enc){const data=concat(parts);const sigBytes=typeof sig==='string'?Buf.from(sig,enc):sig;return cryptoMod.verifyAsync(alg,data,key,sigBytes);}};};\r\n cryptoMod.getCiphers=()=>Object.keys(ALG_MAP);\r\n cryptoMod.getHashes=()=>['sha1','sha256','sha512','md5'];\r\n cryptoMod.getCurves=()=>['P-256','P-384','P-521'];\r\n cryptoMod.timingSafeEqual=(a,b)=>{if(a.length!==b.length)return false;let r=0;for(let i=0;i<a.length;i++)r|=a[i]^b[i];return r===0;};\r\n cryptoMod.diffieHellman=()=>{throw new Error('crypto.diffieHellman: use webcrypto ECDH')};\r\n cryptoMod.scrypt=(pw,salt,len,opts,cb)=>{if(typeof opts==='function'){cb=opts;opts={};}queueMicrotask(()=>{try{const k=cryptoMod.pbkdf2Sync(pw,salt,16384,len,'sha256');cb(null,Buf.from(k));}catch(e){cb(e);}});};\r\n cryptoMod.scryptSync=(pw,salt,len)=>Buf.from(cryptoMod.pbkdf2Sync(pw,salt,16384,len,'sha256'));\r\n return cryptoMod;\r\n}\r\n","shell-node-keyobject.js":"const pemLabel=pem=>{const m=pem.match(/-----BEGIN ([^-]+)-----/);return m?m[1]:null;};\r\nconst pemToBytes=pem=>{const m=pem.match(/-----BEGIN [^-]+-----([\\s\\S]+?)-----END/);if(!m)throw new Error('invalid PEM');return Uint8Array.from(atob(m[1].replace(/\\s/g,'')),c=>c.charCodeAt(0));};\r\nconst bytesToPem=(bytes,label)=>`-----BEGIN ${label}-----\\n${btoa(String.fromCharCode(...bytes)).match(/.{1,64}/g).join('\\n')}\\n-----END ${label}-----\\n`;\r\n\r\nexport function makeKeyObject(pem,type){\r\n const label=pemLabel(pem);\r\n const inferredType=type||(label==='PRIVATE KEY'||label==='RSA PRIVATE KEY'||label==='EC PRIVATE KEY'?'private':label==='PUBLIC KEY'?'public':'secret');\r\n const bytes=pemToBytes(pem);\r\n const asymType=(()=>{const s=String.fromCharCode(...bytes.slice(0,Math.min(bytes.length,80)));if(s.includes('\\x2A\\x86\\x48\\xCE\\x3D\\x02\\x01'))return'ec';if(s.includes('\\x2A\\x86\\x48\\x86\\xF7\\x0D\\x01\\x01\\x01'))return'rsa';return'unknown';})();\r\n return{\r\n type:inferredType,\r\n asymmetricKeyType:asymType,\r\n export({format='pem',type:expType}={}){\r\n if(format==='pem'){const l=inferredType==='private'?'PRIVATE KEY':'PUBLIC KEY';return bytesToPem(bytes,l);}\r\n if(format==='der')return bytes;\r\n if(format==='jwk')throw new Error('KeyObject.export jwk: use webcrypto exportKey(\\'jwk\\') directly');\r\n throw new Error('unsupported format: '+format);\r\n },\r\n toCryptoKey(){throw new Error('KeyObject.toCryptoKey: import via webcrypto.importKey instead');}\r\n };\r\n}\r\n\r\nlet x509Mod=null;let x509Promise=null;\r\nasync function getX509(){\r\n if(!x509Promise)x509Promise=import('https://esm.sh/@peculiar/x509@1.9.7/es2022/x509.mjs').then(m=>m.default||m);\r\n return x509Promise;\r\n}\r\nexport async function preloadX509(){x509Mod=await getX509();return x509Mod;}\r\n\r\nexport class X509Certificate{\r\n constructor(pem){\r\n this._pem=typeof pem==='string'?pem:'-----BEGIN CERTIFICATE-----\\n'+btoa(String.fromCharCode(...pem)).match(/.{1,64}/g).join('\\n')+'\\n-----END CERTIFICATE-----\\n';\r\n if(x509Mod){this._parsed=new x509Mod.X509Certificate(this._pem);}else{this._parsed=null;}\r\n }\r\n async _parse(){\r\n if(this._parsed)return this._parsed;\r\n const x509=await getX509();x509Mod=x509;\r\n this._parsed=new x509.X509Certificate(this._pem);\r\n return this._parsed;\r\n }\r\n async fingerprint256Async(){const p=await this._parse();const hash=await crypto.subtle.digest('SHA-256',p.rawData);return [...new Uint8Array(hash)].map(b=>b.toString(16).padStart(2,'0').toUpperCase()).join(':');}\r\n _need(){if(!this._parsed)throw new Error('X509Certificate: call await crypto.preloadX509() once before sync access, or await cert._parse()');return this._parsed;}\r\n get subject(){return this._need().subject;}\r\n get issuer(){return this._need().issuer;}\r\n get validFrom(){return this._need().notBefore.toISOString();}\r\n get validTo(){return this._need().notAfter.toISOString();}\r\n get serialNumber(){return this._need().serialNumber;}\r\n get raw(){return new Uint8Array(this._need().rawData);}\r\n toString(){return this._pem;}\r\n}\r\n\r\nexport function extendKeys(cryptoMod){\r\n cryptoMod.createPrivateKey=input=>{const pem=typeof input==='string'?input:input.key;return makeKeyObject(pem,'private');};\r\n cryptoMod.createPublicKey=input=>{const pem=typeof input==='string'?input:input.key;return makeKeyObject(pem,'public');};\r\n cryptoMod.createSecretKey=buf=>({type:'secret',symmetricKeySize:buf.length,export:()=>buf});\r\n cryptoMod.X509Certificate=X509Certificate;\r\n cryptoMod.KeyObject={from:pem=>makeKeyObject(pem)};\r\n cryptoMod.preloadX509=preloadX509;\r\n return cryptoMod;\r\n}\r\n","shell-node-advanced.js":"export function makeStreamingZlib(streamMod,Buf,fflate){\r\n const Transform=streamMod.Transform;\r\n const mkT=(Klass,errMsg)=>()=>{let inst=null;const chunks=[];const out=new Transform({transform(c,e,cb){try{if(!inst)inst=new fflate[Klass]((chunk,fin)=>{out.push(Buf.from(chunk));});inst.push(c instanceof Uint8Array?c:new TextEncoder().encode(String(c)),false);cb();}catch(e){cb(e);}},flush(cb){try{if(inst)inst.push(new Uint8Array(0),true);cb();}catch(e){cb(e);}}});return out;};\r\n return{\r\n createGzip:mkT('Gzip'),\r\n createGunzip:mkT('Gunzip'),\r\n createDeflate:mkT('Deflate'),\r\n createInflate:mkT('Inflate'),\r\n createDeflateRaw:mkT('Deflate'),\r\n createInflateRaw:mkT('Inflate'),\r\n createBrotliCompress:()=>{throw new Error('brotli: not in webcrypto/CompressionStream — use gzip instead');},\r\n createBrotliDecompress:()=>{throw new Error('brotli: not supported in browser');},\r\n brotliCompressSync:()=>{throw new Error('brotli: not supported — use gzipSync');},\r\n brotliDecompressSync:()=>{throw new Error('brotli: not supported');},\r\n };\r\n}\r\n\r\nexport function makeVmModule(){\r\n const contexts=new WeakMap();\r\n const registry=typeof FinalizationRegistry!=='undefined'?new FinalizationRegistry(iframe=>{try{iframe.remove();}catch{}}):{register(){}};\r\n const hasDom=typeof document!=='undefined';\r\n const cloneAcross=v=>{if(v==null||typeof v!=='object'&&typeof v!=='function')return v;if(typeof v==='function')return v;try{return structuredClone(v);}catch{return v;}};\r\n const mkIframe=ctx=>{if(!hasDom)return{iframe:null,win:globalThis};const f=document.createElement('iframe');f.style.display='none';f.setAttribute('sandbox','allow-scripts allow-same-origin');document.body.appendChild(f);const win=f.contentWindow;if(ctx)for(const k of Object.keys(ctx))win[k]=cloneAcross(ctx[k]);registry.register(ctx||{},f);return{iframe:f,win};};\r\n const syncBack=(ctx,win)=>{for(const k of Object.keys(ctx))if(k in win)ctx[k]=cloneAcross(win[k]);for(const k of Object.keys(win))if(!(k in ctx)&&!['window','self','document','location','navigator','parent','top','frames','opener','localStorage','sessionStorage'].includes(k))ctx[k]=cloneAcross(win[k]);};\r\n return{\r\n runInThisContext:code=>(0,eval)(code),\r\n runInNewContext:(code,ctx={})=>{const{win}=mkIframe(ctx);const r=win.eval?win.eval(code):(0,eval)(code);if(win.eval)syncBack(ctx,win);return cloneAcross(r);},\r\n runInContext:(code,ctxObj)=>{const ref=contexts.get(ctxObj);if(!ref)throw new Error('vm.runInContext: context not created via createContext');const r=ref.win.eval(code);syncBack(ctxObj,ref.win);return cloneAcross(r);},\r\n createContext:(ctx={})=>{const ref=mkIframe(ctx);contexts.set(ctx,ref);return ctx;},\r\n isContext:ctx=>contexts.has(ctx),\r\n Script:class Script{constructor(code){this.code=code;}runInThisContext(){return(0,eval)(this.code);}runInNewContext(ctx={}){const{win}=mkIframe(ctx);const r=win.eval?win.eval(this.code):(0,eval)(this.code);if(win.eval)syncBack(ctx,win);return cloneAcross(r);}runInContext(ctx){const ref=contexts.get(ctx);if(!ref)throw new Error('Script.runInContext: createContext first');const r=ref.win.eval(this.code);syncBack(ctx,ref.win);return cloneAcross(r);}},\r\n compileFunction:(code,params=[])=>new Function(...params,code),\r\n };\r\n}\r\n\r\nexport function makeModuleRegister(MODULES,snap,pathmod){\r\n const hooks=[];\r\n return{\r\n register(specifier,parentURL){hooks.push({specifier,parentURL:parentURL||'file:///'});return{addEventListener(){}};},\r\n _runResolve:async(specifier,context)=>{let result={url:specifier,shortCircuit:false};for(const h of hooks){try{const m=await import(h.specifier);if(m.resolve){const nextResolve=async(s,c)=>({url:s,shortCircuit:true});const r=await m.resolve(specifier,context,nextResolve);if(r&&r.shortCircuit){result=r;break;}if(r)result=r;}}catch{}}return result;},\r\n _runLoad:async(url,context)=>{let result={format:'module',source:null,shortCircuit:false};for(const h of hooks){try{const m=await import(h.specifier);if(m.load){const nextLoad=async(u,c)=>({format:'module',source:null,shortCircuit:true});const r=await m.load(url,context,nextLoad);if(r&&r.shortCircuit){result=r;break;}if(r)result=r;}}catch{}}return result;},\r\n _hooks:hooks,\r\n };\r\n}\r\n\r\nexport function makeHttp2(){\r\n const mkStream=()=>{const handlers={};const on=(e,f)=>{(handlers[e]=handlers[e]||[]).push(f);return stream;};const emit=(e,...a)=>{for(const f of handlers[e]||[])f(...a);};const stream={on,once:on,emit,close(){emit('close');},end(){emit('end');},write(){},pipe:d=>d,setEncoding(){return stream;}};return{stream,emit};};\r\n return{\r\n connect(authority){\r\n const h={};let closed=false;\r\n const session={\r\n on:(e,f)=>{(h[e]=h[e]||[]).push(f);return session;},\r\n once:(e,f)=>session.on(e,f),\r\n emit:(e,...a)=>{for(const f of h[e]||[])f(...a);},\r\n close(){closed=true;session.emit('close');},\r\n destroy(){closed=true;session.emit('close');},\r\n request(headers){\r\n const {stream,emit}=mkStream();\r\n const method=headers[':method']||'GET';\r\n const path=headers[':path']||'/';\r\n const url=authority.toString().replace(/\\/$/,'')+path;\r\n const fetchHeaders={};for(const[k,v]of Object.entries(headers))if(!k.startsWith(':'))fetchHeaders[k]=v;\r\n fetch(url,{method,headers:fetchHeaders}).then(async r=>{const respHeaders={':status':r.status};r.headers.forEach((v,k)=>{respHeaders[k]=v;});emit('response',respHeaders,0);const reader=r.body?.getReader();if(reader)for(;;){const{value,done}=await reader.read();if(done)break;emit('data',new Uint8Array(value));}emit('end');emit('close');}).catch(e=>emit('error',e));\r\n return stream;\r\n },\r\n };\r\n queueMicrotask(()=>session.emit('connect',session));\r\n return session;\r\n },\r\n constants:{NGHTTP2_REFUSED_STREAM:0xb,HTTP2_HEADER_METHOD:':method',HTTP2_HEADER_PATH:':path',HTTP2_HEADER_STATUS:':status'},\r\n };\r\n}\r\n\r\nlet wasiPromise=null;\r\nasync function getWasi(){if(!wasiPromise)wasiPromise=import('https://esm.sh/@bjorn3/browser_wasi_shim@0.3.0/es2022/browser_wasi_shim.mjs').then(m=>m.default||m);return wasiPromise;}\r\n\r\nexport function makeWasi(){\r\n return{\r\n WASI:class WASI{\r\n constructor(opts={}){this._opts=opts;this._lib=null;this.wasiImport={};}\r\n async _load(){if(!this._lib){this._lib=await getWasi();const args=this._opts.args||[];const env=Object.entries(this._opts.env||{}).map(([k,v])=>`${k}=${v}`);const fds=[new this._lib.OpenFile(new this._lib.File([])),new this._lib.OpenFile(new this._lib.File([])),new this._lib.OpenFile(new this._lib.File([]))];this._wasi=new this._lib.WASI(args,env,fds);this.wasiImport=this._wasi.wasiImport;}return this._wasi;}\r\n async start(instance){await this._load();return this._wasi.start(instance);}\r\n async initialize(instance){await this._load();return this._wasi.initialize(instance);}\r\n }\r\n };\r\n}\r\n","shell-node-observe.js":"export function makeDebugRegistry(){\n const reg={modules:{},streamsOpen:new Set(),workersActive:new Set(),cryptoOps:0,requireCount:0,zlibBytes:{in:0,out:0},http2Sessions:0,vmContexts:0,activeRequires:[]};\n if(typeof window!=='undefined'){window.__debug=window.__debug||{};window.__debug.node=reg;}\n return reg;\n}\n\nexport function makeDiagnosticsChannel(){\n const channels=new Map();\n const ch=name=>{if(!channels.has(name))channels.set(name,{name,subs:new Set(),subscribe(fn){this.subs.add(fn);return this;},unsubscribe(fn){this.subs.delete(fn);return this;},publish(msg){for(const fn of this.subs)try{fn(msg,name);}catch{}},hasSubscribers(){return this.subs.size>0;}});return channels.get(name);};\n return{\n channel:ch,\n subscribe(name,fn){ch(name).subscribe(fn);},\n unsubscribe(name,fn){ch(name).unsubscribe(fn);},\n hasSubscribers(name){return ch(name).hasSubscribers();},\n tracingChannel(name){const start=ch(name+':start');const end=ch(name+':end');const asyncStart=ch(name+':asyncStart');const asyncEnd=ch(name+':asyncEnd');const error=ch(name+':error');return{start,end,asyncStart,asyncEnd,error,traceSync(fn,ctx){start.publish(ctx);try{const r=fn.call(ctx);end.publish({...ctx,result:r});return r;}catch(e){error.publish({...ctx,error:e});throw e;}},async tracePromise(fn,ctx){start.publish(ctx);try{const r=await fn.call(ctx);asyncEnd.publish({...ctx,result:r});return r;}catch(e){error.publish({...ctx,error:e});throw e;}}};},\n };\n}\n\nexport function makeTraceEvents(reg){\n const events=[];\n reg.traceEvents=events;\n const tracings=[];\n return{\n createTracing({categories=[]}={}){const t={categories,enabled:false,enable(){this.enabled=true;tracings.push(this);},disable(){this.enabled=false;const i=tracings.indexOf(this);if(i>=0)tracings.splice(i,1);}};return t;},\n getEnabledCategories(){const out=new Set();for(const t of tracings)if(t.enabled)for(const c of t.categories)out.add(c);return[...out];},\n _emit(cat,name,data){if(events.length>=10000)events.shift();events.push({cat,name,data,ts:performance.now()});},\n };\n}\n\nexport function makeBufferPool(Buf,poolSize=8192){\n let pool=new Uint8Array(poolSize);\n let offset=0;\n Buf.poolSize=poolSize;\n const origAllocUnsafe=Buf.allocUnsafe;\n Buf.allocUnsafe=size=>{if(size>=poolSize>>>1)return origAllocUnsafe(size);if(offset+size>poolSize){pool=new Uint8Array(poolSize);offset=0;}const slice=Buf.from(pool.buffer,pool.byteOffset+offset,size);offset+=size;offset=(offset+7)&~7;return slice;};\n Buf.allocUnsafeSlow=size=>origAllocUnsafe(size);\n return Buf;\n}\n\nexport function makeProcessBindings(util){\n const bindings={util:{isDate:v=>v instanceof Date,isRegExp:v=>v instanceof RegExp,isMap:v=>v instanceof Map,isSet:v=>v instanceof Set,isPromise:v=>v instanceof Promise,isNativeError:v=>v instanceof Error,isArrayBuffer:v=>v instanceof ArrayBuffer,isTypedArray:v=>ArrayBuffer.isView(v)&&!(v instanceof DataView),getHiddenValue:()=>undefined,setHiddenValue:()=>{}}};\n return name=>{if(bindings[name])return bindings[name];throw new Error(`process.binding('${name}'): internal binding not exposed`);};\n}\n\nexport function makePerfMemory(perf){\n const getMemory=()=>{const m=performance.memory||{usedJSHeapSize:0,totalJSHeapSize:0,jsHeapSizeLimit:1073741824};return{rss:m.totalJSHeapSize||50000000,heapTotal:m.totalJSHeapSize||10000000,heapUsed:m.usedJSHeapSize||5000000,external:0,arrayBuffers:0};};\n perf.measureUserAgentSpecificMemory=performance.measureUserAgentSpecificMemory?.bind(performance)||(async()=>({bytes:getMemory().heapUsed,breakdown:[]}));\n return getMemory;\n}\n\nexport function makeFetchPool(){\n return class Agent{\n constructor(opts={}){this.maxSockets=opts.maxSockets||Infinity;this.keepAlive=opts.keepAlive!==false;this._queue=[];this._active=0;this._controllers=new Set();}\n _acquire(){if(this._active<this.maxSockets){this._active++;return Promise.resolve();}return new Promise(r=>this._queue.push(r));}\n _release(){this._active--;const next=this._queue.shift();if(next){this._active++;next();}}\n async fetch(url,opts={}){await this._acquire();const ctrl=new AbortController();this._controllers.add(ctrl);const signal=opts.signal?AbortSignal.any?.([opts.signal,ctrl.signal])||opts.signal:ctrl.signal;try{return await fetch(url,{...opts,signal});}finally{this._controllers.delete(ctrl);this._release();}}\n destroy(){for(const c of this._controllers)c.abort();this._controllers.clear();}\n };\n}\n\nexport function installPrepareStackTraceHook(){\n if(Error._psHooked)return;Error._psHooked=true;\n const origGetStack=Object.getOwnPropertyDescriptor(Error.prototype,'stack');\n const parseFrame=l=>{const m=l.match(/at\\s+(?:(.+?)\\s+\\()?(.+?):(\\d+):(\\d+)\\)?/);return m?{getFileName:()=>m[2],getLineNumber:()=>+m[3],getColumnNumber:()=>+m[4],getFunctionName:()=>m[1]||null,isNative:()=>false,isEval:()=>false,toString:()=>l.trim()}:{getFileName:()=>null,getLineNumber:()=>0,getColumnNumber:()=>0,getFunctionName:()=>null,isNative:()=>false,toString:()=>l.trim()};};\n if(!('prepareStackTrace'in Error))Error.prepareStackTrace=null;\n Object.defineProperty(Error.prototype,'stack',{configurable:true,get(){const raw=origGetStack?.get?.call(this)||'';if(typeof Error.prepareStackTrace==='function'){const lines=raw.split('\\n').slice(1).filter(l=>l.trim().startsWith('at '));const frames=lines.map(parseFrame);try{return Error.prepareStackTrace(this,frames);}catch{return raw;}}return raw;},set(v){Object.defineProperty(this,'stack',{value:v,writable:true,configurable:true});}});\n}\n\nexport function installCaptureStackTrace(){\n if(Error.captureStackTrace)return;\n Error.captureStackTrace=(target,ctor)=>{const e=new Error();const lines=(e.stack||'').split('\\n');target.stack=(ctor?.name?ctor.name:'Error')+(target.message?': '+target.message:'')+'\\n'+lines.slice(2).join('\\n');};\n}\n\nexport function makeFsWatchReal(getSnap){\n const watchers=[];\n let lastSnap=null;\n const tick=()=>{const cur=getSnap();if(!lastSnap){lastSnap={...cur};return;}const curKeys=new Set(Object.keys(cur));const prevKeys=new Set(Object.keys(lastSnap));const changed=[];for(const k of curKeys)if(!prevKeys.has(k)||cur[k]!==lastSnap[k])changed.push({type:prevKeys.has(k)?'change':'rename',path:k});for(const k of prevKeys)if(!curKeys.has(k))changed.push({type:'rename',path:k});for(const {type,path} of changed)for(const w of watchers)if(path===w.path||(w.recursive&&path.startsWith(w.path+'/')))for(const h of w.handlers.change)h(type,path.split('/').pop());lastSnap={...cur};};\n setInterval(tick,500);\n return (path,opts={},listener)=>{if(typeof opts==='function'){listener=opts;opts={};}const normalized=path.replace(/^\\/+/,'').replace(/\\/$/,'');const handlers={change:listener?[listener]:[],error:[],close:[]};const w={path:normalized,recursive:!!opts.recursive,handlers,on:(ev,fn)=>{(handlers[ev]=handlers[ev]||[]).push(fn);return w;},close:()=>{const i=watchers.indexOf(w);if(i>=0)watchers.splice(i,1);for(const h of handlers.close)h();},ref:()=>w,unref:()=>w};watchers.push(w);return w;};\n}\n","shell-node-runtime.js":"export function makeWorkerThreads(snap,Buf){\n class Worker{\n constructor(scriptPath,opts={}){\n const src=snap()[scriptPath.replace(/^\\.?\\//,'')]||scriptPath;\n const preamble=`const workerData=${JSON.stringify(opts.workerData||null)};const parentPort={postMessage:(m,t)=>self.postMessage(m,t),on:(ev,fn)=>{if(ev==='message')self.addEventListener('message',e=>fn(e.data));if(ev==='close')self.addEventListener('close',fn);},close:()=>self.close()};`;\n const blob=new Blob([preamble+'\\n'+src],{type:'application/javascript'});\n this._url=URL.createObjectURL(blob);\n this._worker=new globalThis.Worker(this._url,{type:'module'});\n this._handlers={message:[],error:[],exit:[],online:[]};\n this._worker.addEventListener('message',e=>{for(const f of this._handlers.message)f(e.data);});\n this._worker.addEventListener('error',e=>{for(const f of this._handlers.error)f(e);});\n queueMicrotask(()=>{for(const f of this._handlers.online)f();});\n this.threadId=Math.floor(Math.random()*1e9);\n }\n on(ev,fn){(this._handlers[ev]=this._handlers[ev]||[]).push(fn);return this;}\n once(ev,fn){const w=(...a)=>{this.off(ev,w);fn(...a);};return this.on(ev,w);}\n off(ev,fn){this._handlers[ev]=(this._handlers[ev]||[]).filter(x=>x!==fn);return this;}\n postMessage(msg,transfer){this._worker.postMessage(msg,transfer);}\n terminate(){this._worker.terminate();URL.revokeObjectURL(this._url);for(const f of this._handlers.exit)f(0);return Promise.resolve(0);}\n ref(){return this;}\n unref(){return this;}\n }\n return{\n Worker,\n isMainThread:true,\n parentPort:null,\n workerData:null,\n threadId:0,\n MessageChannel:globalThis.MessageChannel,\n MessagePort:globalThis.MessagePort,\n BroadcastChannel:globalThis.BroadcastChannel,\n SHARE_ENV:Symbol('SHARE_ENV'),\n setEnvironmentData(){},\n getEnvironmentData(){},\n markAsUntransferable(){},\n moveMessagePortToContext(){throw new Error('moveMessagePortToContext: not supported');},\n resourceLimits:{maxOldGenerationSizeMb:0,maxYoungGenerationSizeMb:0,codeRangeSizeMb:0,stackSizeMb:0},\n };\n}\n\nexport function makeChildProcessReal(Buf,streamMod){\n const getWc=()=>globalThis.__webcontainer||window.__webcontainer||null;\n const mkProc=async(cmd,args,opts={})=>{const wc=getWc();if(!wc)throw new Error('child_process: WebContainer not available — spawn requires window.__webcontainer');const p=await wc.spawn(cmd,args||[],{cwd:opts.cwd,env:opts.env});const handlers={exit:[],close:[],error:[]};const stdout=new streamMod.Readable();const stderr=new streamMod.Readable();p.output.pipeTo(new WritableStream({write(chunk){stdout.push(Buf.from(chunk));}}));const exitPromise=p.exit.then(code=>{stdout.push(null);stderr.push(null);for(const f of handlers.exit)f(code);for(const f of handlers.close)f(code);return code;});return{pid:Math.floor(Math.random()*1e6),stdout,stderr,stdin:{write:d=>p.input.getWriter().write(d),end:()=>{}},on(ev,fn){(handlers[ev]=handlers[ev]||[]).push(fn);return this;},kill(){p.kill?.();},exitPromise};};\n return{\n exec(cmd,opts,cb){if(typeof opts==='function'){cb=opts;opts={};}const parts=cmd.split(/\\s+/);mkProc(parts[0],parts.slice(1),opts).then(p=>{const chunks=[];p.stdout.on('data',c=>chunks.push(c));p.exitPromise.then(code=>{const out=Buf.concat(chunks).toString();if(cb)code===0?cb(null,out,''):cb(Object.assign(new Error('exit '+code),{code}),out,'');});},e=>cb&&cb(e));},\n spawn(cmd,args,opts){let proc=null;const emitter={on(){return this;},_pending:true};mkProc(cmd,args,opts).then(p=>{proc=p;Object.assign(emitter,p);},e=>{for(const f of emitter._errorHandlers||[])f(e);});return new Proxy(emitter,{get(t,k){return proc?proc[k]:t[k];}});},\n execFile(f,args,opts,cb){if(typeof opts==='function'){cb=opts;opts={};}return this.exec([f,...(args||[])].join(' '),opts,cb);},\n execSync(){throw new Error('child_process.execSync: synchronous subprocess not available in browser');},\n spawnSync(){throw new Error('child_process.spawnSync: synchronous subprocess not available');},\n fork(){throw new Error('child_process.fork: not supported — use Worker');},\n };\n}\n\nexport function makeRepl(ctx,term,nodeEval){\n const history=[];\n let buffer='';\n let lastResult=undefined;\n const commands={\n '.clear':()=>{buffer='';term.write('\\r\\n');},\n '.exit':()=>{throw Object.assign(new Error('repl exit'),{__nodeExit:true,code:0});},\n '.help':()=>{term.write('Commands: .clear .exit .help .load .save .editor\\r\\n');},\n '.load':async path=>{const snap=window.__debug?.idbSnapshot||{};const content=snap[path.replace(/^\\/+/,'')];if(!content)throw new Error('file not found: '+path);return nodeEval(content);},\n '.save':path=>{const snap=window.__debug?.idbSnapshot||{};window.__debug.idbSnapshot={...snap,[path.replace(/^\\/+/,'')]:history.join('\\n')};term.write('saved\\r\\n');},\n '.editor':()=>{term.write('(type ^D to execute, ^C to cancel)\\r\\n');buffer='__editor__';},\n };\n const isIncomplete=code=>{let depth=0,inStr=null,inTmpl=false,prev='';for(let i=0;i<code.length;i++){const c=code[i];if(inStr){if(c==='\\\\'){i++;continue;}if(c===inStr)inStr=null;continue;}if(inTmpl){if(c==='\\\\'){i++;continue;}if(c==='`')inTmpl=false;else if(c==='$'&&code[i+1]==='{'){depth++;i++;}continue;}if(c===\"'\"||c==='\"')inStr=c;else if(c==='`')inTmpl=true;else if(c==='('||c==='['||c==='{')depth++;else if(c===')'||c===']'||c==='}')depth--;prev=c;}return depth>0||inStr!==null||inTmpl;};\n return{\n commands,\n isIncomplete,\n async eval(line){\n const trimmed=line.trim();\n if(trimmed.startsWith('.')){const[cmd,...rest]=trimmed.split(/\\s+/);if(commands[cmd])return commands[cmd](rest.join(' '));}\n buffer=buffer?buffer+'\\n'+line:line;\n if(isIncomplete(buffer))return{continuation:true};\n const code=buffer;buffer='';\n history.unshift(code);if(history.length>1000)history.pop();\n const src='const _=arguments[0];'+(code.startsWith('var ')||code.startsWith('let ')||code.startsWith('const ')||code.includes(';')||code.includes('\\n')?code:'return ('+code+');');\n try{const fn=new Function(src);const r=fn(lastResult);if(r!==undefined)lastResult=r;return{result:r};}catch(e){return{error:e};}\n },\n getHistory(){return history;},\n get lastResult(){return lastResult;},\n };\n}\n","shell-node-extras.js":"export function extendBuffer(Buf) {\r\n const proto = Buf.prototype;\r\n proto.readBigUInt64BE = function(o=0){return (BigInt(this.readUInt32BE(o))<<32n)|BigInt(this.readUInt32BE(o+4));};\r\n proto.readBigUInt64LE = function(o=0){return (BigInt(this.readUInt32LE(o)))|(BigInt(this.readUInt32LE(o+4))<<32n);};\r\n proto.readUInt32LE = function(o=0){return (this[o]|(this[o+1]<<8)|(this[o+2]<<16)|(this[o+3]*0x1000000))>>>0;};\r\n proto.readDoubleBE = function(o=0){return new DataView(this.buffer,this.byteOffset+o,8).getFloat64(0,false);};\r\n proto.readDoubleLE = function(o=0){return new DataView(this.buffer,this.byteOffset+o,8).getFloat64(0,true);};\r\n proto.readFloatBE = function(o=0){return new DataView(this.buffer,this.byteOffset+o,4).getFloat32(0,false);};\r\n proto.readFloatLE = function(o=0){return new DataView(this.buffer,this.byteOffset+o,4).getFloat32(0,true);};\r\n proto.writeUInt16BE = function(v,o=0){this[o]=(v>>8)&0xff;this[o+1]=v&0xff;return o+2;};\r\n proto.writeUInt16LE = function(v,o=0){this[o]=v&0xff;this[o+1]=(v>>8)&0xff;return o+2;};\r\n proto.writeUInt32BE = function(v,o=0){this[o]=(v>>>24)&0xff;this[o+1]=(v>>>16)&0xff;this[o+2]=(v>>>8)&0xff;this[o+3]=v&0xff;return o+4;};\r\n proto.swap16 = function(){for(let i=0;i<this.length;i+=2){const t=this[i];this[i]=this[i+1];this[i+1]=t;}return this;};\r\n proto.swap32 = function(){for(let i=0;i<this.length;i+=4){[this[i],this[i+3]]=[this[i+3],this[i]];[this[i+1],this[i+2]]=[this[i+2],this[i+1]];}return this;};\r\n proto.swap64 = function(){for(let i=0;i<this.length;i+=8){for(let j=0;j<4;j++){const t=this[i+j];this[i+j]=this[i+7-j];this[i+7-j]=t;}}return this;};\r\n Buf.copyBytesFrom = (view,off=0,len)=>Buf.from(view.buffer,view.byteOffset+off,len??view.byteLength-off);\r\n return Buf;\r\n}\r\n\r\nconst WIN = /^[A-Za-z]:[\\\\/]/;\r\nfunction win32Mod(){\r\n const sep='\\\\';\r\n const norm=p=>{const abs=WIN.test(p);const parts=[];for(const s of p.replace(/\\//g,'\\\\').split('\\\\')){if(s==='..')parts.pop();else if(s&&s!=='.')parts.push(s);}return (abs?p.slice(0,3):'')+parts.slice(abs?1:0).join('\\\\');};\r\n return {sep,delimiter:';',normalize:norm,join:(...a)=>norm(a.join('\\\\')),resolve:(...a)=>{let r='';for(const p of a)r=WIN.test(p)?p:r+'\\\\'+p;return norm(r);},dirname:p=>{const i=p.replace(/\\//g,'\\\\').lastIndexOf('\\\\');return i<=0?'.':p.slice(0,i);},basename:(p,ext)=>{const b=p.replace(/\\//g,'\\\\').split('\\\\').pop()||'';return ext&&b.endsWith(ext)?b.slice(0,-ext.length):b;},extname:p=>{const b=p.split(/[\\\\/]/).pop()||'';const i=b.lastIndexOf('.');return i>0?b.slice(i):'';},isAbsolute:p=>WIN.test(p)||p.startsWith('\\\\'),relative:(f,t)=>t.replace(f+'\\\\',''),parse:p=>({root:WIN.test(p)?p.slice(0,3):'',dir:p.slice(0,p.lastIndexOf('\\\\'))||'',base:p.split('\\\\').pop()||'',ext:'',name:''})};\r\n}\r\nexport function extendPath(posix){\r\n posix.delimiter=':';\r\n posix.posix=posix;\r\n posix.win32=win32Mod();\r\n return posix;\r\n}\r\n\r\nexport function createUrlExt(){\r\n const pathToFileURL=p=>{const u=new URL('file://');u.pathname=p.startsWith('/')?p:'/'+p;return u;};\r\n const fileURLToPath=u=>{const url=typeof u==='string'?new URL(u):u;if(url.protocol!=='file:')throw new TypeError('only file: supported');return decodeURIComponent(url.pathname);};\r\n return {URL,URLSearchParams,parse:s=>{const u=new URL(s);return{protocol:u.protocol,host:u.host,hostname:u.hostname,port:u.port,pathname:u.pathname,search:u.search,query:u.search.slice(1),hash:u.hash,href:u.href};},format:o=>{if(o instanceof URL)return o.href;const u=new URL('http://x');for(const[k,v]of Object.entries(o)){try{u[k]=v;}catch{}}return u.href;},resolve:(f,t)=>new URL(t,f).href,pathToFileURL,fileURLToPath,domainToASCII:s=>s,domainToUnicode:s=>s};\r\n}\r\n\r\nexport function makeStringDecoder(){\r\n class StringDecoder{\r\n constructor(enc='utf8'){this.encoding=enc;this._td=new TextDecoder(enc==='utf8'?'utf-8':enc,{fatal:false});this._buf=null;}\r\n write(b){return this._td.decode(b,{stream:true});}\r\n end(b){return this._td.decode(b||new Uint8Array(0),{stream:false});}\r\n }\r\n return {StringDecoder};\r\n}\r\n\r\nexport function makeReadline(term,proc){\r\n return {\r\n createInterface:({input,output,prompt='> ',terminal:useTerm}={})=>{\r\n const handlers={line:[],close:[],history:[]};\r\n const useXterm=useTerm!==false&&term&&(!input||input===proc?.stdin);\r\n let buf='';\r\n const rl={\r\n on:(ev,fn)=>{(handlers[ev]=handlers[ev]||[]).push(fn);return rl;},\r\n once:(ev,fn)=>rl.on(ev,(...a)=>{rl.off(ev,fn);fn(...a);}),\r\n off:(ev,fn)=>{handlers[ev]=(handlers[ev]||[]).filter(f=>f!==fn);return rl;},\r\n write:s=>(output||term)?.write?.(s),\r\n prompt:()=>(output||term)?.write?.(prompt),\r\n question:(q,cb)=>{(output||term)?.write?.(q);return new Promise(resolve=>{const handler=l=>{rl.off('line',handler);resolve(l);cb?.(l);};handlers.line.push(handler);});},\r\n close:()=>{for(const h of handlers.close)h();},\r\n setPrompt:p=>{prompt=p;},\r\n pause:()=>rl,resume:()=>rl,\r\n [Symbol.asyncIterator](){return{next(){return new Promise(r=>{handlers.line.push(function on(l){handlers.line=handlers.line.filter(f=>f!==on);r({value:l,done:false});});});}};}\r\n };\r\n if(useXterm){\r\n const sink=d=>{if(d==='\\r'||d==='\\n'){const l=buf;buf='';term.write('\\r\\n');for(const h of handlers.line)h(l);}else if(d==='\\x7f'){if(buf.length){buf=buf.slice(0,-1);term.write('\\b \\b');}}else if(d>=' '){buf+=d;term.write(d);}};\r\n if(proc?.stdin?.on)proc.stdin.on('data',sink);\r\n }else if(input?._onLine)input._onLine(l=>{for(const h of handlers.line)h(l);});\r\n return rl;\r\n },\r\n cursorTo:(s,x,y)=>{if(s?.write)s.write(`\\x1b[${(y||0)+1};${(x||0)+1}H`);},\r\n clearLine:s=>s?.write?.('\\x1b[2K'),\r\n clearScreenDown:s=>s?.write?.('\\x1b[J'),\r\n moveCursor:(s,dx,dy)=>{if(s?.write){if(dx>0)s.write(`\\x1b[${dx}C`);else if(dx<0)s.write(`\\x1b[${-dx}D`);if(dy>0)s.write(`\\x1b[${dy}B`);else if(dy<0)s.write(`\\x1b[${-dy}A`);}},\r\n emitKeypressEvents:(stream,rl)=>{if(!stream?.on)return;stream.on('data',d=>{const name=d==='\\r'?'return':d==='\\x1b[A'?'up':d==='\\x1b[B'?'down':d==='\\x7f'?'backspace':d.length===1?d:'';stream.emit?.('keypress',d,{name,ctrl:false,meta:false,shift:false,sequence:d});});},\r\n };\r\n}\r\n\r\nexport function makeTimersMod(){\r\n return {setTimeout,setInterval,setImmediate:fn=>setTimeout(fn,0),clearTimeout,clearInterval,clearImmediate:clearTimeout,promises:{setTimeout:ms=>new Promise(r=>setTimeout(r,ms)),setImmediate:()=>Promise.resolve(),setInterval:async function*(ms){while(1){await new Promise(r=>setTimeout(r,ms));yield;}}}};\r\n}\r\n\r\nexport function makePerfHooks(){\r\n return {performance:globalThis.performance,PerformanceObserver:class{observe(){}disconnect(){}},monitorEventLoopDelay:()=>({enable(){},disable(){},reset(){},min:0,max:0,mean:0,stddev:0,percentile:()=>0}),constants:{NODE_PERFORMANCE_GC_MAJOR:2}};\r\n}\r\n\r\nexport function makeV8Mod(){\r\n return {getHeapStatistics:()=>({total_heap_size:20000000,used_heap_size:10000000,heap_size_limit:2000000000,total_available_size:1990000000}),getHeapSpaceStatistics:()=>[],serialize:o=>new TextEncoder().encode(JSON.stringify(o)),deserialize:b=>JSON.parse(new TextDecoder().decode(b)),cachedDataVersionTag:()=>0,setFlagsFromString:()=>{}};\r\n}\r\n\r\nexport function makeAsyncHooks(){\r\n return {createHook:()=>({enable(){return this;},disable(){return this;}}),executionAsyncId:()=>1,triggerAsyncId:()=>0,executionAsyncResource:()=>({}),AsyncLocalStorage:class{constructor(){this._s=null;}run(s,fn,...a){const p=this._s;this._s=s;try{return fn(...a);}finally{this._s=p;}}getStore(){return this._s;}enterWith(s){this._s=s;}disable(){this._s=null;}exit(fn,...a){const p=this._s;this._s=null;try{return fn(...a);}finally{this._s=p;}}},AsyncResource:class{constructor(){}runInAsyncScope(fn,t,...a){return fn.apply(t,a);}}};\r\n}\r\n\r\nexport function makeStubs(ctx){\r\n const stub=name=>({__stub:name,toString:()=>`[${name} stub]`});\r\n return {\r\n inspector:{open:()=>{},close:()=>{},url:()=>undefined,waitForDebugger:()=>{},Session:class{connect(){}post(){}}},\r\n cluster:{isPrimary:true,isMaster:true,isWorker:false,workers:{},fork:()=>{throw new Error('cluster.fork: not supported in browser')},on:()=>{},emit:()=>{}},\r\n sea:{isSea:()=>false,getAsset:()=>{throw new Error('sea.getAsset: no SEA blob')},getRawAsset:()=>{throw new Error('sea.getRawAsset: no SEA blob')}},\r\n test_runner:{test:(n,fn)=>Promise.resolve(fn?.()),describe:(n,fn)=>fn?.(),it:(n,fn)=>Promise.resolve(fn?.()),before:fn=>fn?.(),after:fn=>fn?.(),beforeEach:()=>{},afterEach:()=>{},run:()=>({})},\r\n readline_promises:{createInterface:()=>({close(){},question:q=>Promise.resolve('')})},\r\n punycode:{encode:s=>s,decode:s=>s,toASCII:s=>s,toUnicode:s=>s,ucs2:{encode:a=>String.fromCodePoint(...a),decode:s=>[...s].map(c=>c.codePointAt(0))}},\r\n tty:{isatty:()=>true,ReadStream:class{isTTY=true;},WriteStream:class{isTTY=true;columns=80;rows=24;}},\r\n domain:{create:()=>({run:fn=>fn(),add(){},remove(){},dispose(){},on(){},emit(){}})},\r\n diagnostics_channel:{channel:name=>({hasSubscribers:false,publish(){},subscribe(){},unsubscribe(){}}),hasSubscribers:()=>false},\r\n string_decoder:makeStringDecoder(),\r\n tls:{connect:()=>{throw new Error('tls.connect: use fetch() for HTTPS in browser');},createServer:()=>{throw new Error('tls.createServer: not supported in browser');},DEFAULT_CIPHERS:'',DEFAULT_MIN_VERSION:'TLSv1.2',DEFAULT_MAX_VERSION:'TLSv1.3'},\r\n };\r\n}\r\n\r\nexport function makeErrorCodes(){\r\n const codes={ERR_MODULE_NOT_FOUND:'Cannot find module',ERR_INVALID_ARG_TYPE:'Invalid argument type',ERR_INVALID_ARG_VALUE:'Invalid argument value',ERR_OUT_OF_RANGE:'Value out of range',ERR_UNHANDLED_ERROR:'Unhandled error',ERR_ASSERTION:'Assertion failed',ERR_UNSUPPORTED_DIR_IMPORT:'Directory import not supported',ERR_PACKAGE_PATH_NOT_EXPORTED:'Package path not exported',ERR_REQUIRE_ESM:'Cannot require() ESM module',ERR_UNKNOWN_FILE_EXTENSION:'Unknown file extension',ERR_UNKNOWN_BUILTIN_MODULE:'Unknown builtin module',ERR_INVALID_URL:'Invalid URL',ERR_STREAM_DESTROYED:'Stream destroyed',ERR_STREAM_WRITE_AFTER_END:'Write after end',ERR_STREAM_PREMATURE_CLOSE:'Premature close'};\r\n const make=(code,msg)=>{const e=new Error(msg||codes[code]);e.code=code;return e;};\r\n return {codes,make};\r\n}\r\n\r\nexport function extendProcessExtras(proc,ctx){\r\n proc.stdout.columns=80;proc.stdout.rows=24;proc.stdout.isTTY=true;proc.stdout.getColorDepth=()=>8;proc.stdout.hasColors=()=>true;\r\n proc.stderr.columns=80;proc.stderr.rows=24;proc.stderr.isTTY=true;\r\n proc.stdin.isTTY=true;\r\n proc.resourceUsage=()=>({userCPUTime:0,systemCPUTime:0,maxRSS:50000,sharedMemorySize:0,unsharedDataSize:0,unsharedStackSize:0,minorPageFault:0,majorPageFault:0,swappedOut:0,fsRead:0,fsWrite:0,ipcSent:0,ipcReceived:0,signalsCount:0,voluntaryContextSwitches:0,involuntaryContextSwitches:0});\r\n proc.binding=name=>{throw new Error(`process.binding('${name}'): internal bindings not available`);};\r\n proc.allowedNodeEnvironmentFlags=new Set(['--experimental-vm-modules','--no-warnings','--loader','--import','--require','-r','--enable-source-maps','--inspect','--inspect-brk','--trace-warnings','--unhandled-rejections','--preserve-symlinks','--no-deprecation','--throw-deprecation']);\r\n const nodeOpts=(ctx.env.NODE_OPTIONS||'').split(/\\s+/).filter(Boolean);\r\n proc.execArgv=nodeOpts;\r\n proc.sourceMapsEnabled=nodeOpts.includes('--enable-source-maps');\r\n proc.features={inspector:false,debug:false,uv:false,ipv6:true,tls_alpn:false,tls_sni:false,tls_ocsp:false,tls:false,cached_builtins:true};\r\n proc.report={getReport:()=>({}),writeReport:()=>'report.json'};\r\n proc.availableMemory=()=>1073741824;\r\n proc.constrainedMemory=()=>0;\r\n proc.loadEnvFile=p=>{};\r\n proc.noDeprecation=false;proc.throwDeprecation=false;proc.traceDeprecation=false;\r\n proc.sourceMapsEnabled=false;\r\n proc.channel=undefined;proc.connected=false;\r\n const sigH={};\r\n const origOn=proc.on?.bind(proc);\r\n proc.on=(ev,fn)=>{if(['SIGINT','SIGTERM','SIGHUP','exit','beforeExit','uncaughtException','unhandledRejection','warning','message'].includes(ev)){(sigH[ev]=sigH[ev]||[]).push(fn);}origOn?.(ev,fn);return proc;};\r\n proc._emitSignal=(ev,...a)=>{for(const h of sigH[ev]||[])h(...a);};\r\n proc.kill=()=>true;\r\n return proc;\r\n}\r\n\r\nexport function makeStreamConsumers(){\r\n const toArr=async it=>{const a=[];for await(const c of it)a.push(c);return a;};\r\n return {text:async s=>{const a=await toArr(s);return a.map(c=>typeof c==='string'?c:new TextDecoder().decode(c)).join('');},json:async s=>JSON.parse(await (await import('./shell-node-extras.js')).makeStreamConsumers().text(s)),arrayBuffer:async s=>{const a=await toArr(s);const b=Buffer.concat(a.map(c=>c instanceof Uint8Array?c:new TextEncoder().encode(c)));return b.buffer;},buffer:async s=>{const a=await toArr(s);return Buffer.concat(a.map(c=>c instanceof Uint8Array?c:new TextEncoder().encode(c)));}};\r\n}\r\n","shell-node-streams.js":"function makeEmitter(){\n const h={};\n return {\n on(e,f){(h[e]=h[e]||[]).push(f);return this;},\n once(e,f){const w=(...a)=>{this.off(e,w);f(...a);};return this.on(e,w);},\n off(e,f){h[e]=(h[e]||[]).filter(x=>x!==f);return this;},\n removeListener(e,f){return this.off(e,f);},\n removeAllListeners(e){if(e)delete h[e];else for(const k of Object.keys(h))delete h[k];return this;},\n emit(e,...a){for(const f of(h[e]||[]).slice())f(...a);return(h[e]||[]).length>0;},\n listenerCount(e){return(h[e]||[]).length;},\n _h:h,\n };\n}\n\nclass Readable{\n constructor(opts={}){\n Object.assign(this,makeEmitter());\n this._q=[];this._ended=false;this._flowing=null;this._paused=false;this._destroyed=false;\n this.readable=true;this.readableHighWaterMark=opts.highWaterMark??16384;this.readableEnded=false;this.readableObjectMode=!!opts.objectMode;\n this._read=opts.read||(()=>{});this._encoding=null;\n }\n push(chunk){if(chunk===null){this._ended=true;queueMicrotask(()=>this._drain());return false;}this._q.push(chunk);queueMicrotask(()=>this._drain());return this._q.length<this.readableHighWaterMark;}\n read(n){if(!this._q.length)return null;return n?this._q.shift():this._q.shift();}\n _drain(){if(this._paused||this._destroyed)return;while(this._q.length){const c=this._q.shift();const data=this._encoding&&c instanceof Uint8Array?new TextDecoder(this._encoding).decode(c):c;this.emit('data',data);}if(this._ended&&!this.readableEnded){this.readableEnded=true;this.emit('end');}}\n pause(){this._paused=true;return this;}\n resume(){this._paused=false;queueMicrotask(()=>this._drain());return this;}\n pipe(dest){this.on('data',c=>{if(dest.write(c)===false)this.pause();});this.on('end',()=>dest.end?.());dest.on?.('drain',()=>this.resume());return dest;}\n unpipe(){return this;}\n setEncoding(enc){this._encoding=enc;return this;}\n destroy(e){this._destroyed=true;if(e)this.emit('error',e);this.emit('close');return this;}\n [Symbol.asyncIterator](){const self=this;return{async next(){if(self._q.length)return{value:self._q.shift(),done:false};if(self._ended)return{value:undefined,done:true};return new Promise(r=>{const onData=c=>{self.off('data',onData);self.off('end',onEnd);r({value:c,done:false});};const onEnd=()=>{self.off('data',onData);r({value:undefined,done:true});};self.on('data',onData);self.once('end',onEnd);});}};}\n}\n\nclass Writable{\n constructor(opts={}){\n Object.assign(this,makeEmitter());\n this._write=opts.write||((c,e,cb)=>cb());this.writable=true;this.writableEnded=false;this.writableFinished=false;this.writableHighWaterMark=opts.highWaterMark??16384;this._pending=0;\n }\n write(chunk,enc,cb){if(typeof enc==='function'){cb=enc;enc=null;}if(this.writableEnded){const e=Object.assign(new Error('write after end'),{code:'ERR_STREAM_WRITE_AFTER_END'});queueMicrotask(()=>cb?.(e));return false;}this._pending++;this._write(chunk,enc,err=>{this._pending--;cb?.(err);if(this._pending===0)this.emit('drain');});return this._pending<this.writableHighWaterMark;}\n end(chunk,enc,cb){if(chunk!=null)this.write(chunk,enc);this.writableEnded=true;queueMicrotask(()=>{this.writableFinished=true;this.emit('finish');this.emit('close');cb?.();});return this;}\n destroy(e){if(e)this.emit('error',e);this.emit('close');return this;}\n}\n\nclass Duplex extends Readable{constructor(opts={}){super(opts);Object.assign(this,new Writable(opts));this._write=opts.write||((c,e,cb)=>cb());}write(...a){return Writable.prototype.write.call(this,...a);}end(...a){return Writable.prototype.end.call(this,...a);}}\n\nclass Transform extends Duplex{\n constructor(opts={}){super(opts);this._transform=opts.transform||((c,e,cb)=>cb(null,c));this._flush=opts.flush||(cb=>cb());this._write=(c,e,cb)=>{this._transform(c,e,(err,out)=>{if(err)return cb(err);if(out!=null)this.push(out);cb();});};const origEnd=this.end.bind(this);this.end=(...a)=>{this._flush((err,out)=>{if(out!=null)this.push(out);this.push(null);});return origEnd(...a);};}\n}\n\nclass PassThrough extends Transform{constructor(opts){super({...opts,transform:(c,e,cb)=>cb(null,c)});}}\n\nfunction pipeline(...args){const cb=typeof args[args.length-1]==='function'?args.pop():null;const streams=args;let done=false;const fin=e=>{if(done)return;done=true;cb?.(e);};for(let i=0;i<streams.length-1;i++){const src=streams[i],dst=streams[i+1];src.on('error',fin);src.pipe(dst);}streams[streams.length-1].on('finish',()=>fin(null));streams[streams.length-1].on('error',fin);return streams[streams.length-1];}\n\nfunction finished(stream,cb){const onFin=()=>cb();const onErr=e=>cb(e);stream.on?.('finish',onFin);stream.on?.('end',onFin);stream.on?.('error',onErr);return()=>{stream.off?.('finish',onFin);stream.off?.('end',onFin);stream.off?.('error',onErr);};}\n\nexport function makeStream(){\n const mod={Readable,Writable,Duplex,Transform,PassThrough,pipeline,finished,promises:{pipeline:(...a)=>new Promise((res,rej)=>pipeline(...a,e=>e?rej(e):res())),finished:s=>new Promise((res,rej)=>finished(s,e=>e?rej(e):res()))}};\n Readable.from=iter=>{const r=new Readable();(async()=>{try{for await(const c of iter)r.push(c);r.push(null);}catch(e){r.destroy(e);}})();return r;};\n return mod;\n}\n\nexport function extendFsStreams(fs,Buf){\n fs.createReadStream=(path,opts={})=>{const r=new Readable();queueMicrotask(()=>{try{const data=fs.readFileSync(path);const buf=typeof data==='string'?Buf.from(data):data;const start=opts.start||0;const end=opts.end??buf.length;r.push(buf.slice(start,end));r.push(null);}catch(e){r.destroy(e);}});return r;};\n fs.createWriteStream=(path,opts={})=>{const chunks=[];const w=new Writable({write:(c,e,cb)=>{chunks.push(typeof c==='string'?Buf.from(c):c);cb();}});w.on('finish',()=>{try{fs.writeFileSync(path,Buf.concat(chunks));}catch(e){w.emit('error',e);}});return w;};\n return fs;\n}\n","shell-node-firefox.js":"export function detectBrowser(){\n const ua=(typeof navigator!=='undefined'?navigator.userAgent:'')||'';\n const vendor=/Firefox\\//.test(ua)?'firefox':/Edg\\//.test(ua)?'edge':/Chrome\\//.test(ua)?'chromium':/Safari\\//.test(ua)?'webkit':'unknown';\n const m=ua.match(/(Firefox|Chrome|Edg|Safari|Version)\\/([\\d.]+)/);\n const version=m?m[2]:'0';\n const g=globalThis;\n const caps={\n opfs:!!(g.navigator?.storage?.getDirectory),\n sharedArrayBuffer:typeof SharedArrayBuffer!=='undefined'&&g.crossOriginIsolated===true,\n performanceMemory:!!(g.performance?.memory),\n compressionStream:typeof g.CompressionStream!=='undefined',\n webTransport:typeof g.WebTransport!=='undefined',\n webRTCDataChannel:typeof g.RTCPeerConnection!=='undefined',\n webCodecs:typeof g.VideoEncoder!=='undefined',\n storageBuckets:!!(g.navigator?.storageBuckets),\n fileSystemObserver:typeof g.FileSystemObserver!=='undefined',\n measureMemory:typeof g.performance?.measureUserAgentSpecificMemory==='function',\n broadcastChannel:typeof g.BroadcastChannel!=='undefined',\n };\n return{vendor,version,ua,capabilities:caps};\n}\n\nexport function registerPolyfill(reg,name,backing,reason){\n reg.polyfills=reg.polyfills||{};\n reg.polyfills[name]={active:true,backing,reason,activatedAt:Date.now()};\n}\n\nexport function makeCompressionStreamZlib(streamMod,Buf){\n if(typeof CompressionStream==='undefined')return null;\n const mk=(name,Ctor)=>()=>{const t=new Ctor(name);const reader=t.readable.getReader();const writer=t.writable.getWriter();const out=new streamMod.Transform({transform(c,e,cb){writer.write(c instanceof Uint8Array?c:new TextEncoder().encode(String(c))).then(()=>cb(),cb);},flush(cb){writer.close().then(async()=>{for(;;){const{value,done}=await reader.read();if(done)break;out.push(Buf.from(value));}cb();},cb);}});return out;};\n return{\n createGzip:mk('gzip',CompressionStream),\n createGunzip:mk('gzip',DecompressionStream),\n createDeflate:mk('deflate',CompressionStream),\n createInflate:mk('deflate',DecompressionStream),\n createDeflateRaw:mk('deflate-raw',CompressionStream),\n createInflateRaw:mk('deflate-raw',DecompressionStream),\n };\n}\n\nexport function makeWebCodecs(){\n const g=globalThis;\n if(typeof g.VideoEncoder==='undefined')return null;\n return{VideoEncoder:g.VideoEncoder,VideoDecoder:g.VideoDecoder,AudioEncoder:g.AudioEncoder,AudioDecoder:g.AudioDecoder,ImageDecoder:g.ImageDecoder,EncodedVideoChunk:g.EncodedVideoChunk,EncodedAudioChunk:g.EncodedAudioChunk,VideoFrame:g.VideoFrame,AudioData:g.AudioData};\n}\n\nexport function makeWebPush(){\n return{\n async subscribe(applicationServerKey,opts={}){\n if(!navigator.serviceWorker)throw new Error('web-push: serviceWorker not available');\n const reg=await navigator.serviceWorker.ready;\n return reg.pushManager.subscribe({userVisibleOnly:opts.userVisibleOnly!==false,applicationServerKey});\n },\n async getSubscription(){\n const reg=await navigator.serviceWorker?.ready;\n return reg?reg.pushManager.getSubscription():null;\n },\n async unsubscribe(){\n const sub=await this.getSubscription();\n return sub?sub.unsubscribe():false;\n }\n };\n}\n\nexport function makeStorageHelpers(){\n const g=globalThis;\n return{\n async estimate(){if(!g.navigator?.storage?.estimate)return{usage:0,quota:0,usageDetails:{}};return g.navigator.storage.estimate();},\n async persist(){if(!g.navigator?.storage?.persist)return false;return g.navigator.storage.persist();},\n async persisted(){if(!g.navigator?.storage?.persisted)return false;return g.navigator.storage.persisted();},\n buckets:g.navigator?.storageBuckets||null,\n };\n}\n\nexport function makeFsObserver(getSnap,fsWatchers){\n const g=globalThis;\n if(typeof g.FileSystemObserver==='undefined')return null;\n return async (opfsRoot)=>{\n const obs=new g.FileSystemObserver(records=>{\n for(const r of records){\n const path=r.relativePathComponents.join('/');\n for(const w of fsWatchers)if(path===w.path||(w.recursive&&path.startsWith(w.path+'/')))for(const h of w.handlers.change)h(r.type,path.split('/').pop());\n }\n });\n if(opfsRoot)await obs.observe(opfsRoot,{recursive:true});\n return obs;\n };\n}\n\nexport function wrapWorkerForFirefox(opts={}){\n const ua=typeof navigator!=='undefined'?navigator.userAgent:'';\n const isOldFirefox=/Firefox\\/(\\d+)/.test(ua)&&parseInt(ua.match(/Firefox\\/(\\d+)/)[1])<128;\n if(!isOldFirefox||opts.type!=='module')return opts;\n return{...opts,type:'classic'};\n}\n","shell-node-opfs.js":"const WORKER_SRC=`\nself.addEventListener('message',async e=>{\n const {id,op,path,data,flags}=e.data;\n try{\n const root=await navigator.storage.getDirectory();\n const parts=path.replace(/^\\\\/+/,'').split('/');\n const fname=parts.pop();\n let dir=root;\n for(const p of parts){if(!p)continue;try{dir=await dir.getDirectoryHandle(p,{create:op==='write'||op==='mkdir'});}catch(err){if(op==='read'||op==='stat'||op==='delete'){self.postMessage({id,error:'ENOENT: '+path});return;}throw err;}}\n if(op==='mkdir'){await dir.getDirectoryHandle(fname,{create:true});self.postMessage({id,ok:true});return;}\n if(op==='read'){const h=await dir.getFileHandle(fname);const f=await h.getFile();const buf=new Uint8Array(await f.arrayBuffer());self.postMessage({id,data:buf},[buf.buffer]);return;}\n if(op==='write'){const h=await dir.getFileHandle(fname,{create:true});const sync=await h.createSyncAccessHandle();const bytes=data instanceof Uint8Array?data:new TextEncoder().encode(String(data));sync.truncate(0);sync.write(bytes,{at:0});sync.flush();sync.close();self.postMessage({id,ok:true});return;}\n if(op==='stat'){const h=await dir.getFileHandle(fname).catch(()=>dir.getDirectoryHandle(fname));const f=await h.getFile?.();self.postMessage({id,size:f?.size||0,mtime:f?.lastModified||0,isFile:!!f,isDirectory:!f});return;}\n if(op==='delete'){await dir.removeEntry(fname,{recursive:flags?.recursive||false});self.postMessage({id,ok:true});return;}\n if(op==='list'){const out=[];for await(const [name,h] of dir.entries())out.push({name,kind:h.kind});self.postMessage({id,entries:out});return;}\n self.postMessage({id,error:'unknown op: '+op});\n }catch(err){self.postMessage({id,error:err.message});}\n});\n`;\n\nexport function makeOpfsBackend(Buf){\n if(typeof navigator==='undefined'||!navigator.storage?.getDirectory)return null;\n const blob=new Blob([WORKER_SRC],{type:'application/javascript'});\n const url=URL.createObjectURL(blob);\n const worker=new Worker(url);\n const pending=new Map();let nextId=1;\n worker.addEventListener('message',e=>{const {id,...rest}=e.data;const p=pending.get(id);if(!p)return;pending.delete(id);if(rest.error)p.reject(new Error(rest.error));else p.resolve(rest);});\n const call=(op,path,data,flags)=>new Promise((resolve,reject)=>{const id=nextId++;pending.set(id,{resolve,reject});worker.postMessage({id,op,path,data,flags});});\n return{\n readFile:async(path,enc)=>{const r=await call('read',path);return enc?new TextDecoder(enc==='utf-8'?'utf-8':enc).decode(r.data):Buf.from(r.data);},\n writeFile:async(path,data)=>{await call('write',path,data);},\n mkdir:async path=>{await call('mkdir',path);},\n rm:async(path,opts)=>{await call('delete',path,null,opts);},\n stat:async path=>call('stat',path),\n list:async path=>{const r=await call('list',path);return r.entries;},\n _worker:worker,\n _url:url,\n };\n}\n\nexport function wireOpfsIntoFs(fs,opfs,reg){\n if(!opfs)return fs;\n const orig={readFileSync:fs.readFileSync,writeFileSync:fs.writeFileSync,existsSync:fs.existsSync,statSync:fs.statSync,mkdirSync:fs.mkdirSync,rmSync:fs.rmSync,unlinkSync:fs.unlinkSync};\n fs.promises=fs.promises||{};\n fs.promises.readFile=async(p,enc)=>opfs.readFile(p,enc).catch(()=>orig.readFileSync(p,enc));\n fs.promises.writeFile=async(p,d)=>{await opfs.writeFile(p,d).catch(()=>orig.writeFileSync(p,d));};\n fs.promises.mkdir=async(p,o)=>{await opfs.mkdir(p).catch(()=>orig.mkdirSync(p,o));};\n fs.promises.rm=async(p,o)=>{await opfs.rm(p,o).catch(()=>orig.rmSync(p,o));};\n fs.promises.stat=async p=>opfs.stat(p).catch(()=>orig.statSync(p));\n fs.promises.readdir=async p=>opfs.list(p).then(es=>es.map(e=>e.name)).catch(()=>fs.readdirSync(p));\n reg.polyfills=reg.polyfills||{};\n reg.polyfills.opfs={active:true,backing:'native',reason:'OPFS available'};\n return fs;\n}\n","shell-node-brotli.js":"let brotliMod=null;let brotliPromise=null;\n\nasync function loadBrotli(){\n if(!brotliPromise)brotliPromise=import('https://esm.sh/brotli-wasm@3.0.1/es2022/brotli-wasm.mjs').then(async m=>{const lib=m.default||m;if(lib.then)return await lib;if(lib.compress&&lib.decompress)return lib;return lib;});\n return brotliPromise;\n}\n\nexport async function preloadBrotli(){brotliMod=await loadBrotli();return brotliMod;}\n\nexport function makeBrotli(streamMod,Buf){\n const need=()=>{if(!brotliMod)throw new Error('brotli: call preloadBrotli() once before sync brotli calls (auto-preloaded on node entry)');return brotliMod;};\n const toBytes=d=>d instanceof Uint8Array?d:new TextEncoder().encode(String(d));\n const encodeErr=fn=>{try{return fn();}catch(e){throw new Error('brotli: '+e.message);}};\n return{\n brotliCompressSync:b=>Buf.from(encodeErr(()=>need().compress(toBytes(b)))),\n brotliDecompressSync:b=>Buf.from(encodeErr(()=>need().decompress(toBytes(b)))),\n brotliCompress:async(b,cb)=>{try{await loadBrotli();const out=Buf.from(need().compress(toBytes(b)));if(cb)cb(null,out);return out;}catch(e){if(cb)cb(e);else throw e;}},\n brotliDecompress:async(b,cb)=>{try{await loadBrotli();const out=Buf.from(need().decompress(toBytes(b)));if(cb)cb(null,out);return out;}catch(e){if(cb)cb(e);else throw e;}},\n createBrotliCompress:()=>{const chunks=[];return new streamMod.Transform({transform(c,e,cb){chunks.push(toBytes(c));cb();},flush(cb){try{const all=new Uint8Array(chunks.reduce((s,c)=>s+c.length,0));let off=0;for(const c of chunks){all.set(c,off);off+=c.length;}this.push(Buf.from(need().compress(all)));cb();}catch(e){cb(e);}}});},\n createBrotliDecompress:()=>{const chunks=[];return new streamMod.Transform({transform(c,e,cb){chunks.push(toBytes(c));cb();},flush(cb){try{const all=new Uint8Array(chunks.reduce((s,c)=>s+c.length,0));let off=0;for(const c of chunks){all.set(c,off);off+=c.length;}this.push(Buf.from(need().decompress(all)));cb();}catch(e){cb(e);}}});},\n };\n}\n","shell-node-srcmap.js":"let smMod=null;let smPromise=null;const consumers=new Map();const CAP=5;\n\nasync function loadSm(){\n if(!smPromise)smPromise=import('https://esm.sh/source-map-js@1.2.1/es2022/source-map-js.mjs').then(m=>m.default||m);\n return smPromise;\n}\n\nexport async function preloadSourceMap(){smMod=await loadSm();return smMod;}\n\nasync function consumerFor(url,snapFn){\n if(consumers.has(url))return consumers.get(url);\n if(consumers.size>50){const first=consumers.keys().next().value;consumers.delete(first);}\n if(!smMod)await loadSm();\n let src='';\n try{\n if(url.startsWith('data:application/json;base64,'))src=atob(url.slice(29));\n else if(url.startsWith('data:application/json,'))src=decodeURIComponent(url.slice(22));\n else if(url.startsWith('http'))src=await (await fetch(url)).text();\n else{const snap=snapFn();const key=url.replace(/^file:\\/\\/\\/?/,'').replace(/^\\//,'');src=snap[key]||snap[key+'.map']||'';}\n }catch{return null;}\n if(!src)return null;\n try{const raw=JSON.parse(src);const c=new smMod.SourceMapConsumer(raw);consumers.set(url,c);return c;}catch{return null;}\n}\n\nfunction extractMapUrl(source){\n if(!source)return null;\n const m=source.match(/\\/\\/[#@]\\s*sourceMappingURL=(\\S+)/);\n return m?m[1]:null;\n}\n\nexport function installSourceMapStacks(snapFn){\n if(Error._smHooked)return;Error._smHooked=true;\n const origFormatter=Error.prepareStackTrace;\n Error.prepareStackTrace=(err,frames)=>{\n if(!smMod)return origFormatter?origFormatter(err,frames):err.toString()+'\\n'+frames.map(f=>' at '+f.toString()).join('\\n');\n let depth=0;\n const mapped=frames.map(f=>{\n if(depth>=CAP)return f;\n const file=f.getFileName?.();if(!file)return f;\n const snap=snapFn();const src=snap[file.replace(/^file:\\/\\/\\/?/,'').replace(/^\\//,'')]||'';\n const mapUrl=extractMapUrl(src);if(!mapUrl)return f;\n depth++;\n const c=consumers.get(mapUrl);if(!c)return f;\n const line=f.getLineNumber?.(),col=f.getColumnNumber?.();if(!line)return f;\n try{const orig=c.originalPositionFor({line,column:col||0});if(!orig.source)return f;return{...f,getFileName:()=>orig.source,getLineNumber:()=>orig.line,getColumnNumber:()=>orig.column,getFunctionName:()=>orig.name||f.getFunctionName?.(),toString:()=>` at ${orig.name||'<anonymous>'} (${orig.source}:${orig.line}:${orig.column})`};}catch{return f;}\n });\n return origFormatter?origFormatter(err,mapped):err.toString()+'\\n'+mapped.map(f=>' at '+(f.toString?.()||f)).join('\\n');\n };\n Promise.resolve().then(async()=>{await loadSm();const snap=snapFn();for(const [key,src] of Object.entries(snap)){const mapUrl=extractMapUrl(src);if(mapUrl)await consumerFor(mapUrl,snapFn);}});\n}\n\nexport function clearSourceMapCache(){consumers.clear();}\n","shell-node-net.js":"const relayUrl=()=>{const g=globalThis;return g.__plugkit_tcp_relay||g.window?.__plugkit_tcp_relay||null;};\nconst udpRelayUrl=()=>{const g=globalThis;return g.__plugkit_udp_relay||g.window?.__plugkit_udp_relay||null;};\n\nexport function makeNet(Buf){\n class Socket{\n constructor(){this._h={};this._ws=null;this.bufferedAmount=0;this.writable=true;this.readable=true;this.remoteAddress=null;this.remotePort=null;this.destroyed=false;}\n _emit(ev,...a){for(const f of this._h[ev]||[])f(...a);}\n on(ev,fn){(this._h[ev]=this._h[ev]||[]).push(fn);return this;}\n once(ev,fn){const w=(...a)=>{this.off(ev,w);fn(...a);};return this.on(ev,w);}\n off(ev,fn){this._h[ev]=(this._h[ev]||[]).filter(x=>x!==fn);return this;}\n connect(opts,listener){const{port,host='127.0.0.1',tls=false}=typeof opts==='object'?opts:{port:opts,host:arguments[1]};const relay=relayUrl();if(!relay)throw new Error('net.Socket.connect: set window.__plugkit_tcp_relay to a WSS URL that tunnels TCP — not configured');this.remoteAddress=host;this.remotePort=port;const url=`${relay}${relay.includes('?')?'&':'?'}host=${encodeURIComponent(host)}&port=${port}${tls?'&tls=1':''}`;this._ws=new WebSocket(url);this._ws.binaryType='arraybuffer';this._ws.onopen=()=>{this._emit('connect');listener&&listener();};this._ws.onmessage=e=>{this._emit('data',Buf.from(e.data instanceof ArrayBuffer?new Uint8Array(e.data):new TextEncoder().encode(String(e.data))));};this._ws.onclose=()=>{this.destroyed=true;this._emit('end');this._emit('close');};this._ws.onerror=e=>this._emit('error',e);return this;}\n write(chunk,enc,cb){if(!this._ws||this._ws.readyState!==1){if(cb)cb(new Error('not connected'));return false;}const b=chunk instanceof Uint8Array?chunk:new TextEncoder().encode(String(chunk));this._ws.send(b);this.bufferedAmount=this._ws.bufferedAmount;if(cb)cb();return this.bufferedAmount<65536;}\n end(chunk){if(chunk)this.write(chunk);if(this._ws)this._ws.close();}\n destroy(err){this.destroyed=true;if(err)this._emit('error',err);if(this._ws)this._ws.close();}\n setEncoding(){return this;}\n setKeepAlive(){return this;}\n setNoDelay(){return this;}\n setTimeout(){return this;}\n pipe(dest){this.on('data',c=>{if(dest.write(c)===false)this._ws.send('__BACKPRESSURE__');});this.on('end',()=>dest.end?.());return dest;}\n }\n return{\n Socket,\n createConnection(...args){const s=new Socket();s.connect(...args);return s;},\n connect(...args){return this.createConnection(...args);},\n createServer(onConn){const bn=globalThis.__busnet;if(!bn)throw new Error('net.createServer: busnet not initialized');const handlers={connection:onConn?[onConn]:[]};let bnHandle=null;return{listen(port,host,cb){if(typeof host==='function'){cb=host;host=null;}bnHandle=bn.listen(port,'tcp',c=>{for(const h of handlers.connection)h(c);});cb?.();return this;},close(cb){bnHandle?.close();cb?.();},on(ev,fn){(handlers[ev]=handlers[ev]||[]).push(fn);return this;},address(){return bnHandle?{address:'127.0.0.1',family:'IPv4',port:bnHandle.port}:null;},unref(){return this;},ref(){return this;}};},\n isIP:ip=>/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(ip)?4:ip.includes(':')?6:0,\n isIPv4:ip=>/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(ip),\n isIPv6:ip=>ip.includes(':'),\n };\n}\n\nexport function makeTls(netMod,Buf){\n class TLSSocket extends netMod.Socket{\n constructor(){super();this.authorized=true;this.encrypted=true;}\n }\n return{\n TLSSocket,\n connect(opts,listener){const s=new TLSSocket();const port=typeof opts==='object'?opts.port:opts;const host=typeof opts==='object'?opts.host:arguments[1];s.connect({port,host,tls:true},listener);return s;},\n createServer(){throw new Error('tls.createServer: server sockets not supported');},\n DEFAULT_ECDH_CURVE:'auto',\n DEFAULT_MAX_VERSION:'TLSv1.3',\n DEFAULT_MIN_VERSION:'TLSv1.2',\n CLIENT_RENEG_LIMIT:3,\n rootCertificates:[],\n checkServerIdentity:()=>undefined,\n createSecureContext:()=>({}),\n };\n}\n\nexport function makeDgram(Buf){\n class Dgram{\n constructor(type='udp4'){this.type=type;this._h={};this._ws=null;this._addr=null;}\n on(ev,fn){(this._h[ev]=this._h[ev]||[]).push(fn);return this;}\n _emit(ev,...a){for(const f of this._h[ev]||[])f(...a);}\n bind(port,addr,cb){this._addr={port:port||0,address:addr||'0.0.0.0'};queueMicrotask(()=>{this._emit('listening');cb&&cb();});const relay=udpRelayUrl();if(!relay)return;this._ws=new WebSocket(relay);this._ws.binaryType='arraybuffer';this._ws.onmessage=e=>{const view=new DataView(e.data);const srcPortLen=view.getUint16(0);const portBytes=new Uint8Array(e.data,2,srcPortLen);const addrStr=new TextDecoder().decode(portBytes);const[ah,ap]=addrStr.split(':');const payload=new Uint8Array(e.data,2+srcPortLen);this._emit('message',Buf.from(payload),{address:ah,port:+ap,family:'IPv4',size:payload.length});};return this;}\n send(msg,offset,length,port,addr,cb){if(typeof offset==='number'&&typeof length==='number'){msg=msg.slice(offset,offset+length);}else{cb=addr;addr=port;port=length;}const relay=udpRelayUrl();if(!relay){if(cb)cb(new Error('dgram: set window.__plugkit_udp_relay'));return;}if(!this._ws){this._ws=new WebSocket(relay);this._ws.binaryType='arraybuffer';}const send=()=>{const target=`${addr}:${port}`;const tb=new TextEncoder().encode(target);const buf=new Uint8Array(2+tb.length+msg.length);new DataView(buf.buffer).setUint16(0,tb.length);buf.set(tb,2);buf.set(msg instanceof Uint8Array?msg:new TextEncoder().encode(String(msg)),2+tb.length);this._ws.send(buf);cb&&cb(null);};if(this._ws.readyState===1)send();else this._ws.addEventListener('open',send,{once:true});}\n address(){return this._addr||{address:'0.0.0.0',port:0,family:'IPv4'};}\n close(cb){if(this._ws)this._ws.close();this._emit('close');cb&&cb();}\n addMembership(){}\n dropMembership(){}\n setBroadcast(){}\n setTTL(){}\n setMulticastTTL(){}\n ref(){return this;}\n unref(){return this;}\n }\n return{\n Socket:Dgram,\n createSocket(type,cb){const s=new Dgram(typeof type==='object'?type.type:type);if(typeof cb==='function')s.on('message',cb);return s;},\n };\n}\n","shell-node-inspector.js":"export function makeInspector(debugReg){\n let opened=false;let url=null;let port=null;const sessions=new Set();\n const targets=()=>[{description:'thebird browser runtime',devtoolsFrontendUrl:'',id:'thebird-1',title:'thebird',type:'node',url:'file://thebird',webSocketDebuggerUrl:url}];\n const handlers={};\n const post=(sess,msg)=>{try{sess.send(JSON.stringify(msg));}catch{}};\n const installServer=u=>{\n if(typeof globalThis.addEventListener!=='function')return;\n globalThis.addEventListener('message',e=>{if(e.data?.type!=='cdp:connect')return;const chan=e.data.channel;const sess={send:m=>globalThis.postMessage({type:'cdp:msg',channel:chan,msg:m},'*')};sessions.add(sess);});\n };\n const dispatch=(sess,raw)=>{\n let msg;try{msg=JSON.parse(raw);}catch{return;}\n const {id,method,params}=msg;\n const send=result=>post(sess,{id,result});\n const err=code=>post(sess,{id,error:{code,message:'not implemented'}});\n const map={\n 'Runtime.enable':()=>send({}),\n 'Runtime.evaluate':()=>{try{const r=(0,eval)(params.expression);send({result:{type:typeof r,value:r,description:String(r)}});}catch(e){send({exceptionDetails:{exception:{type:'object',className:'Error',description:e.stack}}});}},\n 'Debugger.enable':()=>send({debuggerId:'thebird-dbg-1'}),\n 'Debugger.getScriptSource':()=>send({scriptSource:''}),\n 'Profiler.enable':()=>send({}),\n 'Profiler.start':()=>send({}),\n 'Profiler.stop':()=>send({profile:{nodes:[],startTime:0,endTime:0,samples:[],timeDeltas:[]}}),\n 'HeapProfiler.enable':()=>send({}),\n 'HeapProfiler.takeHeapSnapshot':()=>send({}),\n };\n const h=map[method];h?h():err(-32601);\n };\n return{\n open(p=9229,host='127.0.0.1',wait=false){if(opened)return;opened=true;port=p;url=`ws://${host}:${p}/${crypto.randomUUID()}`;installServer(url);debugReg.polyfills=debugReg.polyfills||{};debugReg.polyfills.inspector={active:true,backing:'postMessage-CDP',reason:'real WS debugger unavailable in sandbox'};debugReg.inspector={url,port,targets:targets(),sessions};if(wait)throw new Error('inspector.waitForDebugger: sync block not supported — use openAsync()');return{url};},\n async openAsync(p=9229,host='127.0.0.1'){return this.open(p,host,false);},\n close(){opened=false;url=null;sessions.clear();},\n url:()=>url,\n waitForDebugger(){throw new Error('inspector.waitForDebugger: synchronous block not supported in browser — attach before starting work');},\n Session:class Session{constructor(){this._h={};}connect(){return this;}post(method,params,cb){queueMicrotask(()=>dispatch({send:m=>{const p=JSON.parse(m);cb&&cb(p.error||null,p.result);}},JSON.stringify({id:1,method,params})));}on(ev,fn){(this._h[ev]=this._h[ev]||[]).push(fn);return this;}disconnect(){return this;}},\n console:{context:{}},\n _dispatch:dispatch,\n _targets:targets,\n };\n}\n","shell-node-profiler.js":"export function makeV8Profiler(debugReg){\n const samples=[];let observer=null;let running=false;let startT=0;\n const startObserver=()=>{if(observer||typeof PerformanceObserver==='undefined')return;try{observer=new PerformanceObserver(list=>{for(const e of list.getEntries())if(running)samples.push({name:e.name,ts:e.startTime,dur:e.duration,entryType:e.entryType});});observer.observe({entryTypes:['measure','longtask','function']});}catch{}};\n const stopObserver=()=>{if(observer){observer.disconnect();observer=null;}};\n return{\n CPUProfile:class CPUProfile{\n constructor(){this.nodes=[];this.samples=[];this.timeDeltas=[];this.startTime=0;this.endTime=0;this.title='';}\n startProfiling(title){this.title=title||'';samples.length=0;startT=performance.now();running=true;startObserver();}\n stopProfiling(){running=false;stopObserver();const end=performance.now();this.startTime=startT*1000;this.endTime=end*1000;this.nodes=samples.map((s,i)=>({id:i+1,callFrame:{functionName:s.name||'(anonymous)',scriptId:'0',url:'',lineNumber:0,columnNumber:0},hitCount:1,children:[]}));this.samples=samples.map((_,i)=>i+1);this.timeDeltas=samples.map(s=>Math.round(s.dur*1000));return this;}\n },\n startProfiling(){const p=new this.CPUProfile();p.startProfiling();return p;},\n stopProfiling(p){return p?p.stopProfiling():null;},\n getHeapStatistics(){const m=performance.memory||{usedJSHeapSize:5e6,totalJSHeapSize:10e6,jsHeapSizeLimit:1e9};return{total_heap_size:m.totalJSHeapSize,total_heap_size_executable:0,total_physical_size:m.totalJSHeapSize,total_available_size:m.jsHeapSizeLimit-m.usedJSHeapSize,used_heap_size:m.usedJSHeapSize,heap_size_limit:m.jsHeapSizeLimit,malloced_memory:0,peak_malloced_memory:0,does_zap_garbage:0,number_of_native_contexts:1,number_of_detached_contexts:0};},\n getHeapSpaceStatistics(){return[{space_name:'new_space',space_size:1e6,space_used_size:5e5,space_available_size:5e5,physical_space_size:1e6}];},\n getHeapCodeStatistics(){return{code_and_metadata_size:0,bytecode_and_metadata_size:0,external_script_source_size:0};},\n cachedDataVersionTag:()=>0,\n setFlagsFromString(){},\n startupSnapshot:{isBuildingSnapshot:()=>false,addSerializeCallback(){},addDeserializeCallback(){}},\n };\n}\n\nexport function makeHeapSnapshot(){\n const NODE_FIELDS=['type','name','id','self_size','edge_count','trace_node_id','detachedness'];\n const NODE_TYPES=[['hidden','array','string','object','code','closure','regexp','number','native','synthetic','concatenated string','sliced string','symbol','bigint','object shape'],'string','number','number','number','number','number'];\n const EDGE_FIELDS=['type','name_or_index','to_node'];\n const EDGE_TYPES=[['context','element','property','internal','hidden','shortcut','weak'],'string_or_number','node'];\n const META={node_fields:NODE_FIELDS,node_types:NODE_TYPES,edge_fields:EDGE_FIELDS,edge_types:EDGE_TYPES,trace_function_info_fields:[],trace_node_fields:[],sample_fields:[],location_fields:[]};\n const walk=(root,maxNodes=5000)=>{\n const visited=new WeakMap();const strings=[''];const stringIdx=new Map([['',0]]);\n const addStr=s=>{if(stringIdx.has(s))return stringIdx.get(s);const i=strings.length;strings.push(s);stringIdx.set(s,i);return i;};\n const nodes=[];const edges=[];const queue=[[root,'root']];\n while(queue.length&&nodes.length<maxNodes){\n const [obj,name]=queue.shift();\n if(visited.has(obj))continue;\n const id=nodes.length+1;visited.set(obj,id);\n const t=obj===null?9:typeof obj==='string'?2:typeof obj==='number'?7:typeof obj==='bigint'?13:typeof obj==='symbol'?12:Array.isArray(obj)?1:typeof obj==='function'?5:3;\n let childEdges=0;\n if(obj&&typeof obj==='object'){try{for(const k of Object.keys(obj).slice(0,32)){queue.push([obj[k],k]);childEdges++;}}catch{}}\n nodes.push([t,addStr(name),id,typeof obj==='string'?obj.length:64,childEdges,0,0]);\n }\n let cursor=0;\n for(const n of nodes){const childCount=n[4];for(let i=0;i<childCount;i++){edges.push([2,cursor+i+1,(cursor+i+1)*NODE_FIELDS.length]);}cursor+=childCount;}\n return{snapshot:{meta:META,node_count:nodes.length,edge_count:edges.length,trace_function_count:0},nodes:nodes.flat(),edges:edges.flat(),trace_function_infos:[],trace_tree:[],samples:[],locations:[],strings};\n };\n return{\n writeHeapSnapshot(filename){const snap=walk(globalThis);const json=JSON.stringify(snap);if(typeof filename==='string'&&globalThis.window?.__debug?.idbSnapshot){globalThis.window.__debug.idbSnapshot[filename.replace(/^\\/+/,'')]=json;}return filename;},\n getHeapSnapshot(){const snap=walk(globalThis);return{read(){return JSON.stringify(snap);}};},\n };\n}\n","shell-node-cluster.js":"const CHANNEL='plugkit-cluster';\nconst isWorkerUrl=()=>typeof location!=='undefined'&&location.hash==='#cluster-worker';\n\nexport function makeCluster(){\n if(typeof BroadcastChannel==='undefined')return null;\n const bc=new BroadcastChannel(CHANNEL);\n const workers=new Map();let nextId=1;\n const isMaster=!isWorkerUrl();\n const handlers={message:[],exit:[],online:[],listening:[],disconnect:[]};\n const onBC=e=>{const{from,to,type,data,id}=e.data||{};if(isMaster){if(to==='master'){const w=workers.get(from);if(!w)return;if(type==='ready'){w.state='online';for(const f of handlers.online)f(w);for(const f of w._h.online||[])f();}if(type==='message'){for(const f of handlers.message)f(w,data);for(const f of w._h.message||[])f(data);}if(type==='exit'){w.state='dead';for(const f of handlers.exit)f(w,data?.code||0);for(const f of w._h.exit||[])f(data?.code||0);workers.delete(from);}}}else{if(to==='worker'||to==='all'){if(type==='message')for(const f of workerHandlers.message)f(data);}}};\n bc.addEventListener('message',onBC);\n const workerHandlers={message:[]};\n const cluster={\n isMaster,\n isPrimary:isMaster,\n isWorker:!isMaster,\n workers:{},\n SCHED_RR:1,SCHED_NONE:0,\n schedulingPolicy:1,\n settings:{},\n setupMaster:opts=>Object.assign(cluster.settings,opts||{}),\n setupPrimary:opts=>Object.assign(cluster.settings,opts||{}),\n fork(env){if(!isMaster)throw new Error('cluster.fork: only master can fork');const id=nextId++;const w={id,state:'starting',_h:{},process:{pid:id,send:(msg)=>{bc.postMessage({from:'master',to:id,type:'message',data:msg});return true;},kill:()=>{bc.postMessage({from:'master',to:id,type:'kill'});}},send(msg){return this.process.send(msg);},on(ev,fn){(this._h[ev]=this._h[ev]||[]).push(fn);return this;},disconnect(){bc.postMessage({from:'master',to:id,type:'disconnect'});},kill(){this.process.kill();}};workers.set(id,w);cluster.workers[id]=w;const url=(cluster.settings.exec||location.href.split('#')[0])+'#cluster-worker';try{window.open(url,'_blank','noopener');}catch{}return w;},\n disconnect(cb){for(const w of workers.values())w.disconnect();cb&&cb();},\n on(ev,fn){(handlers[ev]=handlers[ev]||[]).push(fn);return cluster;},\n worker:isMaster?null:{id:0,process:{send:msg=>{bc.postMessage({from:0,to:'master',type:'message',data:msg});return true;},on(ev,fn){if(ev==='message')workerHandlers.message.push(fn);}}},\n _bc:bc,\n _workerSend:msg=>bc.postMessage({from:0,to:'master',type:'message',data:msg}),\n _workerReady:()=>bc.postMessage({from:0,to:'master',type:'ready'}),\n };\n if(!isMaster)queueMicrotask(()=>cluster._workerReady());\n return cluster;\n}\n","shell-runtime.js":"export function detectRuntime(){\n const g=globalThis;\n let runtime='browser',version='0';\n if(g.Deno?.version){runtime='deno';version=g.Deno.version.deno;}\n else if(g.Bun?.version){runtime='bun';version=g.Bun.version;}\n else if(g.process?.versions?.bun){runtime='bun';version=g.process.versions.bun;}\n else if(g.process?.versions?.node){runtime='node';version=g.process.versions.node;}\n const features={\n jsr:runtime==='deno'||runtime==='bun'||runtime==='browser',\n npmSpecifier:runtime==='deno'||runtime==='bun'||runtime==='browser',\n bunServe:typeof g.Bun?.serve==='function'||runtime==='browser',\n denoPermissions:runtime==='deno',\n typeStrip:runtime==='bun'||runtime==='deno'||runtime==='browser',\n workspaceRoot:true,\n shebangDispatch:true,\n };\n return{runtime,version,features};\n}\n\nexport function registerRuntime(reg,rt){\n reg.runtime={active:rt.runtime,version:rt.version,features:rt.features,available:['node','deno','bun','browser'],history:[]};\n return reg;\n}\n\nexport function logRuntimeSwitch(reg,from,to,reason){\n if(!reg?.runtime)return;\n reg.runtime.history.push({ts:Date.now(),from,to,reason});\n if(reg.runtime.history.length>50)reg.runtime.history.shift();\n reg.runtime.active=to;\n}\n\nexport function switchRuntime(shebang){\n if(!shebang)return'node';\n if(shebang.includes('deno'))return'deno';\n if(shebang.includes('bun'))return'bun';\n return'node';\n}\n","shell-deno.js":"export function makeDenoGlobal(fs,proc,cpMod,httpHandlers,Buf){\n const enc=new TextEncoder(),dec=new TextDecoder();\n const readFile=async p=>fs.existsSync(p)?(typeof fs.readFileSync(p)==='string'?enc.encode(fs.readFileSync(p)):fs.readFileSync(p)):(()=>{const e=new Error('NotFound: '+p);e.code='ENOENT';throw e;})();\n return{\n version:{deno:'2.0.0',v8:'12.9.202',typescript:'5.6.0'},\n build:{target:'x86_64-unknown-linux-gnu',arch:'x86_64',os:'linux',vendor:'unknown'},\n pid:proc.pid||1,ppid:0,hostname:()=>'thebird',\n cwd:()=>proc.cwd?.()||'/',\n chdir:p=>proc.chdir?.(p),\n exit:code=>proc.exit(code||0),\n env:{get:k=>proc.env[k],set:(k,v)=>{proc.env[k]=v;},delete:k=>{delete proc.env[k];},has:k=>k in proc.env,toObject:()=>({...proc.env})},\n args:(proc.argv||[]).slice(2),\n execPath:()=>'/usr/local/bin/deno',\n readTextFile:async p=>{const d=await readFile(p);return typeof d==='string'?d:dec.decode(d);},\n readTextFileSync:p=>fs.readFileSync(p,'utf8'),\n readFile,\n readFileSync:p=>{const d=fs.readFileSync(p);return typeof d==='string'?enc.encode(d):d;},\n writeTextFile:async(p,d)=>fs.writeFileSync(p,d),\n writeTextFileSync:(p,d)=>fs.writeFileSync(p,d),\n writeFile:async(p,d)=>fs.writeFileSync(p,d),\n writeFileSync:(p,d)=>fs.writeFileSync(p,d),\n mkdir:async(p,opts)=>fs.mkdirSync(p,opts),\n mkdirSync:(p,opts)=>fs.mkdirSync(p,opts),\n remove:async(p,opts)=>{if(opts?.recursive)fs.rmSync(p,{recursive:true});else fs.unlinkSync(p);},\n removeSync:(p,opts)=>{if(opts?.recursive)fs.rmSync(p,{recursive:true});else fs.unlinkSync(p);},\n rename:async(o,n)=>fs.renameSync(o,n),\n renameSync:(o,n)=>fs.renameSync(o,n),\n stat:async p=>fs.statSync(p),\n statSync:p=>fs.statSync(p),\n lstat:async p=>fs.lstatSync?.(p)||fs.statSync(p),\n lstatSync:p=>fs.lstatSync?.(p)||fs.statSync(p),\n symlink:async(t,l)=>fs.symlinkSync?.(t,l),\n symlinkSync:(t,l)=>fs.symlinkSync?.(t,l),\n realPath:async p=>fs.realpathSync?.(p)||p,\n realPathSync:p=>fs.realpathSync?.(p)||p,\n readDir:async function*(p){for(const name of fs.readdirSync(p))yield{name,isFile:true,isDirectory:false,isSymlink:false};},\n readDirSync:function*(p){for(const name of fs.readdirSync(p))yield{name,isFile:true,isDirectory:false,isSymlink:false};},\n makeTempDir:async opts=>fs.mkdtempSync?.((opts?.prefix||'/tmp/deno-'))||'/tmp/deno-'+Math.random().toString(36).slice(2,8),\n makeTempFile:async opts=>{const p=(opts?.prefix||'/tmp/')+'deno-'+Math.random().toString(36).slice(2,8);fs.writeFileSync(p,'');return p;},\n serve(opts,handler){const h=typeof opts==='function'?opts:handler||opts.fetch;const port=opts.port||8000;httpHandlers[port]={routes:{GET:[{path:'/',fn:async(req,res)=>{const r=await h(new Request('http://localhost:'+port+req.url,{method:req.method,headers:req.headers}));res.statusCode=r.status;r.headers.forEach((v,k)=>res.setHeader(k,v));res.end(await r.text());}}]}};return{shutdown:async()=>{delete httpHandlers[port];},finished:Promise.resolve()};},\n Command:class{constructor(cmd,opts={}){this.cmd=cmd;this.opts=opts;}async output(){return new Promise((resolve,reject)=>{cpMod.exec([this.cmd,...(this.opts.args||[])].join(' '),{cwd:this.opts.cwd,env:this.opts.env},(err,stdout,stderr)=>{if(err)return reject(err);resolve({code:0,success:true,stdout:enc.encode(stdout),stderr:enc.encode(stderr)});});});}spawn(){return this;}},\n permissions:{query:async d=>({state:'granted',onchange:null,partial:false}),request:async d=>({state:'granted'}),revoke:async d=>({state:'prompt'})},\n errors:{NotFound:class extends Error{constructor(m){super(m);this.name='NotFound';}},PermissionDenied:class extends Error{constructor(m){super(m);this.name='PermissionDenied';}},AlreadyExists:class extends Error{constructor(m){super(m);this.name='AlreadyExists';}}},\n inspect:v=>JSON.stringify(v,null,2),\n noColor:false,isatty:()=>true,\n addSignalListener(sig,fn){proc.on(sig,fn);},removeSignalListener(sig,fn){proc.off?.(sig,fn);},\n stdin:{readable:new ReadableStream({start(c){proc.stdin?.on?.('data',d=>c.enqueue(typeof d==='string'?new TextEncoder().encode(d):d));proc.stdin?.on?.('end',()=>c.close());}}),readSync(){return 0;},read:async buf=>0,rid:0,isTerminal:()=>!!proc.stdin?.isTTY},\n stdout:{writable:new WritableStream({write(c){proc.stdout.write(typeof c==='string'?c:new TextDecoder().decode(c));}}),writeSync:d=>{proc.stdout.write(typeof d==='string'?d:new TextDecoder().decode(d));return d.length;},write:async d=>d.length,rid:1,isTerminal:()=>!!proc.stdout?.isTTY},\n stderr:{writable:new WritableStream({write(c){proc.stderr.write(typeof c==='string'?c:new TextDecoder().decode(c));}}),writeSync:d=>{proc.stderr.write(typeof d==='string'?d:new TextDecoder().decode(d));return d.length;},write:async d=>d.length,rid:2,isTerminal:()=>!!proc.stderr?.isTTY},\n memoryUsage:()=>proc.memoryUsage(),\n resources:()=>({}),close:rid=>{},\n refTimer:t=>t?.ref?.(),unrefTimer:t=>t?.unref?.(),\n };\n}\n","shell-bun.js":"export function makeBunGlobal(fs,proc,cpMod,httpHandlers,Buf,streamMod,cryptoMod){\n const enc=new TextEncoder(),dec=new TextDecoder();\n const fileHandle=p=>({\n async text(){return fs.readFileSync(p,'utf8');},\n async arrayBuffer(){const d=fs.readFileSync(p);const u=typeof d==='string'?enc.encode(d):d;return u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);},\n async json(){return JSON.parse(fs.readFileSync(p,'utf8'));},\n async bytes(){const d=fs.readFileSync(p);return typeof d==='string'?enc.encode(d):d;},\n stream(){const s=new streamMod.Readable();s.push(fs.readFileSync(p));s.push(null);return s;},\n get size(){return fs.statSync(p).size;},\n get type(){return 'application/octet-stream';},\n get name(){return p.split('/').pop();},\n exists:()=>fs.existsSync(p),\n writer(){return{write:d=>fs.writeFileSync(p,d),end(){}};},\n slice(start,end){return fileHandle(p);},\n });\n const shell=strings=>{const cmd=typeof strings==='string'?strings:strings.raw.join(' ');return new Promise((resolve,reject)=>{cpMod.exec(cmd,{},(err,stdout,stderr)=>{resolve({stdout:enc.encode(stdout),stderr:enc.encode(stderr||''),exitCode:err?.code||0,text:()=>stdout,json:()=>JSON.parse(stdout),lines(){return stdout.split('\\n');}});});});};\n shell.cwd=()=>proc.cwd?.();shell.env=proc.env;shell.nothrow=()=>shell;\n return{\n version:'1.1.38',revision:'browser',env:proc.env,argv:proc.argv||['bun'],main:proc.argv?.[1]||'',\n file:fileHandle,\n write(dest,input){const p=typeof dest==='string'?dest:dest.name;fs.writeFileSync(p,typeof input==='string'?input:input instanceof Uint8Array?input:input.toString?.()||String(input));return Promise.resolve(typeof input==='string'?input.length:input.byteLength||0);},\n serve(opts){const port=opts.port||3000;const handler=opts.fetch;httpHandlers[port]={routes:{GET:[{path:'/',fn:async(req,res)=>{const r=await handler(new Request('http://localhost:'+port+req.url,{method:req.method,headers:req.headers,body:req.body}));res.statusCode=r.status;r.headers.forEach((v,k)=>res.setHeader(k,v));const body=await r.text();res.end(body);}}]}};return{port,stop:()=>{delete httpHandlers[port];},hostname:'localhost',development:false,pendingRequests:0};},\n listen:function(opts){return this.serve(opts);},\n spawn(opts){const cmd=Array.isArray(opts.cmd)?opts.cmd.join(' '):opts.cmd;return new Promise((resolve,reject)=>{cpMod.exec(cmd,{cwd:opts.cwd,env:opts.env},(err,stdout,stderr)=>{resolve({exited:Promise.resolve(err?.code||0),exitCode:err?.code||0,pid:1,stdout:{text:()=>stdout},stderr:{text:()=>stderr},kill(){}});});});},\n spawnSync(opts){throw new Error('Bun.spawnSync: synchronous subprocess not available in browser — use Bun.spawn');},\n $:shell,\n sleep:ms=>new Promise(r=>setTimeout(r,ms)),sleepSync:()=>{throw new Error('Bun.sleepSync: sync sleep blocks event loop — use await Bun.sleep');},\n hash:{wyhash:s=>{let h=5381n;for(const c of String(s))h=((h<<5n)+h)^BigInt(c.charCodeAt(0));return h&0xffffffffffffffffn;}},\n password:{hash:async p=>cryptoMod.pbkdf2Sync?String.fromCharCode(...cryptoMod.pbkdf2Sync(p,'bun-salt',10000,32,'sha256')):p,verify:async(p,h)=>true},\n gzipSync:b=>require('zlib').gzipSync?.(b)||b,gunzipSync:b=>require('zlib').gunzipSync?.(b)||b,\n inspect:v=>JSON.stringify(v,null,2),\n nanoseconds:()=>BigInt(Math.floor(performance.now()*1e6)),\n which:cmd=>null,\n pathToFileURL:p=>new URL('file://'+p),fileURLToPath:u=>String(u).replace(/^file:\\/\\//,''),\n enableANSIColors:true,isMainThread:true,\n deepEquals:(a,b)=>JSON.stringify(a)===JSON.stringify(b),\n stringWidth:s=>String(s).length,\n resolveSync:(id,root)=>id,resolve:async(id,root)=>id,\n TOML:{parse:s=>{const o={};for(const line of s.split('\\n')){const m=line.match(/^(\\w+)\\s*=\\s*(.+)$/);if(m)o[m[1]]=m[2].replace(/^[\"']|[\"']$/g,'');}return o;},stringify:o=>Object.entries(o).map(([k,v])=>`${k} = ${typeof v==='string'?'\"'+v+'\"':v}`).join('\\n')},\n color:(c,t)=>`<${c}>${t}</${c}>`,\n stdin:{stream(){const s=new streamMod.Readable();proc.stdin?.on?.('data',d=>s.push(d));proc.stdin?.on?.('end',()=>s.push(null));return s;},async text(){return new Promise(r=>{let b='';proc.stdin?.on?.('data',d=>b+=d);proc.stdin?.on?.('end',()=>r(b));});}},\n stdout:{writer(){return{write:d=>proc.stdout.write(d),end(){}};}},\n stderr:{writer(){return{write:d=>proc.stderr.write(d),end(){}};}},\n };\n}\n","shell-pm.js":"const LOCKFILES={bun:['bun.lock','bun.lockb'],pnpm:['pnpm-lock.yaml'],yarn:['yarn.lock'],npm:['package-lock.json']};\n\nfunction stripJsonc(s){return s.replace(/\\/\\*[\\s\\S]*?\\*\\//g,'').replace(/(^|[^:])\\/\\/.*$/gm,'$1');}\n\nexport function detectPm(snap,cwd=''){\n const base=cwd.replace(/^\\//,'').replace(/\\/$/,'');\n const pj=snap[(base?base+'/':'')+'package.json'];\n if(pj){try{const p=JSON.parse(pj);if(p.packageManager){const m=p.packageManager.match(/^(\\w+)@([\\d.]+)/);if(m)return{pm:m[1],version:m[2],source:'packageManager'};}}catch{}}\n for(const[pm,files] of Object.entries(LOCKFILES))for(const f of files)if(((base?base+'/':'')+f) in snap)return{pm,version:'latest',source:'lockfile:'+f};\n return{pm:'npm',version:'latest',source:'default'};\n}\n\nexport function parseBunfig(src){const o={};for(const line of src.split('\\n')){const m=line.match(/^\\s*(\\w+)\\s*=\\s*(.+)$/);if(m)o[m[1]]=m[2].trim().replace(/^[\"']|[\"']$/g,'');}return o;}\n\nexport function parseDenoJson(src){try{return JSON.parse(stripJsonc(src));}catch{return{};}}\n\nexport function makePmDispatcher(term,fs,persist,ctx){\n const snap=()=>globalThis.window?.__debug?.idbSnapshot||{};\n const log=(pm,cmd,args)=>{const reg=globalThis.window?.__debug?.node;if(!reg)return;reg.pm=reg.pm||{history:[]};reg.pm.history.push({ts:Date.now(),pm,cmd,args,cwd:ctx.cwd});if(reg.pm.history.length>200)reg.pm.history.shift();reg.pm.lastPm=pm;};\n const pkgPath=()=>{const d=ctx.cwd.replace(/^\\//,'').replace(/\\/$/,'');return(d?d+'/':'')+'package.json';};\n const readPj=()=>{const p=snap()[pkgPath()];return p?JSON.parse(p):{name:'pkg',version:'0.0.0',dependencies:{}};};\n const writePj=o=>{snap()[pkgPath()]=JSON.stringify(o,null,2);persist();};\n const writeLock=(pm,deps)=>{const base=ctx.cwd.replace(/^\\//,'').replace(/\\/$/,'');const key=(base?base+'/':'')+(LOCKFILES[pm]?.[0]||'package-lock.json');snap()[key]=JSON.stringify({name:pm,version:1,dependencies:deps},null,2);persist();};\n const cmds={\n async add(pm,args){const pj=readPj();pj.dependencies=pj.dependencies||{};const dev=args.includes('-D')||args.includes('--save-dev')||args.includes('--dev');const pkgs=args.filter(a=>!a.startsWith('-'));for(const spec of pkgs){const m=spec.match(/^(@?[^@]+)(?:@(.+))?$/);const name=m?.[1]||spec;const ver=m?.[2]||'latest';if(dev){pj.devDependencies=pj.devDependencies||{};pj.devDependencies[name]=ver;}else pj.dependencies[name]=ver;term.write(`${pm} added ${name}@${ver}\\r\\n`);}writePj(pj);writeLock(pm,pj.dependencies);return 0;},\n async remove(pm,args){const pj=readPj();const pkgs=args.filter(a=>!a.startsWith('-'));for(const name of pkgs){delete pj.dependencies?.[name];delete pj.devDependencies?.[name];term.write(`${pm} removed ${name}\\r\\n`);}writePj(pj);writeLock(pm,pj.dependencies||{});return 0;},\n async install(pm,args){const pj=readPj();const deps={...(pj.dependencies||{}),...(pj.devDependencies||{})};term.write(`${pm} install — ${Object.keys(deps).length} packages resolved via esm.sh\\r\\n`);writeLock(pm,pj.dependencies||{});return 0;},\n async run(pm,args){const script=args[0];const pj=readPj();const s=pj.scripts?.[script];if(!s){term.write(`${pm} run: no script '${script}'\\r\\n`);return 1;}return ctx.exec?.(s)||0;},\n async task(pm,args){const script=args[0];const base=ctx.cwd.replace(/^\\//,'').replace(/\\/$/,'');const dj=snap()[(base?base+'/':'')+'deno.json']||snap()[(base?base+'/':'')+'deno.jsonc'];if(!dj)return 1;const cfg=parseDenoJson(dj);const s=cfg.tasks?.[script];if(!s){term.write(`deno task: no task '${script}'\\r\\n`);return 1;}return ctx.exec?.(s)||0;},\n async ls(pm,args){const pj=readPj();const deps={...(pj.dependencies||{}),...(pj.devDependencies||{})};for(const[n,v] of Object.entries(deps))term.write(` ${n}@${v}\\r\\n`);return 0;},\n async init(pm,args){writePj({name:'pkg',version:'0.1.0',type:'module',scripts:{test:'echo test'}});term.write(`${pm} init — package.json created\\r\\n`);return 0;},\n };\n cmds.i=cmds.install;cmds.uninstall=cmds.remove;cmds.rm=cmds.remove;\n return async(pm,subcmd,args=[])=>{log(pm,subcmd,args);const fn=cmds[subcmd];if(!fn){term.write(`${pm}: unknown subcommand '${subcmd}'\\r\\n`);return 1;}return fn(pm,args);};\n}\n\nexport function makeCorepackStub(term){\n return async(args)=>{term.write(`corepack: ${args.join(' ')} — no-op in browser (all PMs built-in)\\r\\n`);return 0;};\n}\n","shell-ts.js":"let stripPromise=null;\nasync function getStripper(){\n if(!stripPromise)stripPromise=import('https://esm.sh/sucrase@3.35.0/es2022/sucrase.mjs').then(m=>m.default||m).catch(()=>null);\n return stripPromise;\n}\n\nconst typeDeclRE=/(^|\\n)\\s*(type|interface)\\s+\\w+[^\\n]*(?:\\n\\s+[^\\n]+)*\\n?/g;\nconst asAnyRE=/\\s+as\\s+[\\w.<>|&[\\]]+/g;\nconst genericRE=/<[A-Z]\\w*(?:\\s*(?:extends|,)[^>]*)?>/g;\nconst varAnnotRE=/(\\b(?:const|let|var)\\s+\\w+)\\s*:\\s*[^=,;)\\n]+/g;\nconst paramAnnotRE=/(\\b\\w+)\\s*:\\s*[\\w.<>|&[\\]{} ]+?(?=\\s*[,)=])/g;\nconst retTypeRE=/\\)\\s*:\\s*[\\w.<>|&[\\]{} ]+?(?=\\s*[{=]|$)/gm;\n\nexport function stripTypesSync(src){\n let out=src.replace(typeDeclRE,'\\n').replace(asAnyRE,'').replace(genericRE,'');\n out=out.replace(varAnnotRE,'$1').replace(retTypeRE,')');\n return out;\n}\n\nexport async function stripTypes(src,opts={}){\n try{const s=await getStripper();if(s?.transform){const r=s.transform(src,{transforms:['typescript',...(opts.jsx?['jsx']:[])],jsxRuntime:'automatic'});return r.code;}}catch{}\n return stripTypesSync(src);\n}\n\nexport function isTsFile(filename){return/\\.(ts|tsx|mts|cts)$/i.test(filename);}\n\nexport function preprocessSource(filename,src){\n if(!isTsFile(filename))return Promise.resolve(src);\n return stripTypes(src,{jsx:/\\.tsx$/.test(filename)});\n}\n","shell-posix.js":"const SYMLOOP_MAX=40;\nconst S_IFREG=0o100000,S_IFDIR=0o040000,S_IFLNK=0o120000,S_IFIFO=0o010000,S_IFMT=0o170000;\nconst isMeta=v=>v!==null&&typeof v==='object'&&!ArrayBuffer.isView(v)&&(v.__symlink||v.__fifo||('data' in v&&'mode' in v));\nconst unwrapData=v=>isMeta(v)?v.data:v;\nconst toKey=p=>p.replace(/^\\//,'');\nlet nextIno=1;const inodes=new Map();\n\nexport function installPosixFs(fs,Buf,ctx){\n const snap=()=>globalThis.window?.__debug?.idbSnapshot||{};\n const persist=()=>globalThis.window?.__debug?.idbPersist?.();\n const newIno=()=>++nextIno;\n const ensureInode=(key,s)=>{let e=s[key];if(!isMeta(e)){s[key]={data:e==null?'':e,mode:0o100644,ino:newIno(),nlink:1,uid:0,gid:0,atime:Date.now(),mtime:Date.now(),ctime:Date.now(),birthtime:Date.now()};e=s[key];}return e;};\n\n const resolveLink=(p,depth=0)=>{\n if(depth>SYMLOOP_MAX){const e=new Error('ELOOP: '+p);e.code='ELOOP';throw e;}\n const key=toKey(p);const entry=snap()[key];\n if(isMeta(entry)&&entry.__symlink){const tgt=entry.__symlink.startsWith('/')?entry.__symlink:p.replace(/[^/]+$/,'')+entry.__symlink;return resolveLink(tgt,depth+1);}\n return p;\n };\n\n const origRead=fs.readFileSync,origWrite=fs.writeFileSync,origStat=fs.statSync,origExists=fs.existsSync,origRm=fs.unlinkSync;\n fs.readFileSync=(p,enc)=>{const real=resolveLink(p);const entry=snap()[toKey(real)];if(entry==null){const e=new Error('ENOENT: '+p);e.code='ENOENT';throw e;}const data=unwrapData(entry);return enc?(typeof data==='string'?data:new TextDecoder(enc==='utf-8'?'utf-8':enc).decode(data)):(typeof data==='string'?data:Buf.from(data));};\n fs.writeFileSync=(p,data,opts)=>{const real=resolveLink(p);const s=snap();const key=toKey(real);const mode=S_IFREG|((typeof opts?.mode==='number'?opts.mode:0o666)&~(ctx.umask||0o022));const existing=s[key];if(isMeta(existing)&&!existing.__symlink){existing.data=data;existing.mtime=Date.now();existing.ctime=Date.now();}else if(isMeta(existing)){existing.data=data;}else{s[key]={data,mode,ino:newIno(),nlink:1,uid:0,gid:0,atime:Date.now(),mtime:Date.now(),ctime:Date.now(),birthtime:Date.now()};}persist();};\n fs.existsSync=p=>{try{const real=resolveLink(p);const key=toKey(real);const s=snap();return key in s||Object.keys(s).some(k=>k.startsWith(key+'/'));}catch{return false;}};\n fs.statSync=p=>{const real=resolveLink(p);const s=snap();const key=toKey(real);const entry=s[key];const hasDirChildren=Object.keys(s).some(k=>k.startsWith(key+'/'));if(entry==null){if(hasDirChildren)return makeStats({mode:S_IFDIR|0o755,ino:newIno(),size:0});const e=new Error('ENOENT: '+p);e.code='ENOENT';throw e;}if(isMeta(entry)){const m=entry.mode||S_IFREG|0o644;return makeStats({...entry,mode:m,size:typeof entry.data==='string'?entry.data.length:entry.data?.byteLength||0});}return makeStats({mode:S_IFREG|0o644,ino:newIno(),size:typeof entry==='string'?entry.length:entry?.byteLength||0});};\n fs.lstatSync=p=>{const s=snap();const entry=s[toKey(p)];if(entry==null){if(!origExists(p)){const e=new Error('ENOENT: '+p);e.code='ENOENT';throw e;}return makeStats({mode:S_IFDIR|0o755,ino:newIno(),size:0});}if(isMeta(entry)&&entry.__symlink)return makeStats({mode:S_IFLNK|0o777,ino:newIno(),size:entry.__symlink.length});return fs.statSync(p);};\n fs.readlinkSync=p=>{const entry=snap()[toKey(p)];if(!isMeta(entry)||!entry.__symlink){const e=new Error('EINVAL: '+p);e.code='EINVAL';throw e;}return entry.__symlink;};\n fs.symlinkSync=(target,path)=>{snap()[toKey(path)]={__symlink:target,mode:S_IFLNK|0o777,ino:newIno()};persist();};\n fs.linkSync=(src,dst)=>{const s=snap();const entry=ensureInode(toKey(resolveLink(src)),s);s[toKey(dst)]={...entry,nlink:(entry.nlink||1)+1};entry.nlink=(entry.nlink||1)+1;persist();};\n fs.unlinkSync=p=>{const key=toKey(p);const s=snap();const entry=s[key];if(entry==null){const e=new Error('ENOENT: '+p);e.code='ENOENT';throw e;}delete s[key];persist();};\n fs.chmodSync=(p,mode)=>{const real=resolveLink(p);const entry=ensureInode(toKey(real),snap());entry.mode=(entry.mode&S_IFMT)|(mode&0o7777);entry.ctime=Date.now();persist();};\n fs.realpathSync=p=>resolveLink(p);\n fs.realpathSync.native=fs.realpathSync;\n fs.cpSync=(src,dst,opts={})=>{const sKey=toKey(src),dKey=toKey(dst);const s=snap();const entry=s[sKey];if(entry!=null){s[dKey]=isMeta(entry)?{...entry,ino:newIno(),nlink:1}:entry;}if(opts.recursive){for(const k of Object.keys(s))if(k.startsWith(sKey+'/')){const rel=k.slice(sKey.length);const sub=s[k];s[dKey+rel]=isMeta(sub)?{...sub,ino:newIno(),nlink:1}:sub;}}persist();};\n fs.constants=fs.constants||{};Object.assign(fs.constants,{S_IFREG,S_IFDIR,S_IFLNK,S_IFIFO,S_IFMT,S_IXUSR:0o100,S_IWUSR:0o200,S_IRUSR:0o400,O_RDONLY:0,O_WRONLY:1,O_RDWR:2,O_CREAT:64,O_EXCL:128,O_TRUNC:512,O_APPEND:1024});\n return fs;\n}\n\nfunction makeStats(o){\n const mode=o.mode||0o100644;\n return{\n dev:1,ino:o.ino||0,mode,nlink:o.nlink||1,uid:o.uid||0,gid:o.gid||0,rdev:0,size:o.size||0,blksize:4096,blocks:Math.ceil((o.size||0)/512),\n atimeMs:o.atime||Date.now(),mtimeMs:o.mtime||Date.now(),ctimeMs:o.ctime||Date.now(),birthtimeMs:o.birthtime||Date.now(),\n atime:new Date(o.atime||Date.now()),mtime:new Date(o.mtime||Date.now()),ctime:new Date(o.ctime||Date.now()),birthtime:new Date(o.birthtime||Date.now()),\n isFile(){return(mode&S_IFMT)===S_IFREG;},\n isDirectory(){return(mode&S_IFMT)===S_IFDIR;},\n isSymbolicLink(){return(mode&S_IFMT)===S_IFLNK;},\n isFIFO(){return(mode&S_IFMT)===S_IFIFO;},\n isBlockDevice(){return false;},isCharacterDevice(){return false;},isSocket(){return false;},\n };\n}\n\nexport function installFds(fs,Buf){\n const fdTable=new Map();let nextFd=3;\n fs.openSync=(p,flags='r',mode=0o644)=>{const f=nextFd++;const exists=fs.existsSync(p);if(flags.includes('x')&&exists){const e=new Error('EEXIST: '+p);e.code='EEXIST';throw e;}if((flags.includes('w')||flags.includes('a'))&&!exists)fs.writeFileSync(p,'');if(flags.includes('w')&&exists)fs.writeFileSync(p,'');fdTable.set(f,{path:p,flags,position:flags.includes('a')?(fs.statSync(p).size):0,mode});return f;};\n fs.closeSync=fd=>{fdTable.delete(fd);};\n fs.readSync=(fd,buf,offset,length,position)=>{const e=fdTable.get(fd);if(!e)throw Object.assign(new Error('EBADF'),{code:'EBADF'});const data=fs.readFileSync(e.path);const bytes=typeof data==='string'?new TextEncoder().encode(data):data;const pos=position==null?e.position:position;const n=Math.min(length,bytes.length-pos);for(let i=0;i<n;i++)buf[offset+i]=bytes[pos+i];if(position==null)e.position+=n;return n;};\n fs.writeSync=(fd,buf,offset,length,position)=>{const e=fdTable.get(fd);if(!e)throw Object.assign(new Error('EBADF'),{code:'EBADF'});const existing=fs.existsSync(e.path)?fs.readFileSync(e.path):'';const existingBytes=typeof existing==='string'?new TextEncoder().encode(existing):existing;const pos=position==null?e.position:position;const slice=buf.slice(offset||0,(offset||0)+(length||buf.length));const out=new Uint8Array(Math.max(existingBytes.length,pos+slice.length));out.set(existingBytes);out.set(slice,pos);fs.writeFileSync(e.path,Buf.from(out));if(position==null)e.position=pos+slice.length;return slice.length;};\n fs.fstatSync=fd=>{const e=fdTable.get(fd);return fs.statSync(e.path);};\n fs.fsyncSync=()=>{};fs.ftruncateSync=(fd,len=0)=>{const e=fdTable.get(fd);const cur=fs.readFileSync(e.path);const bytes=typeof cur==='string'?new TextEncoder().encode(cur):cur;fs.writeFileSync(e.path,Buf.from(bytes.slice(0,len)));};\n return fs;\n}\n\nexport function installTmpAndMisc(fs,Buf,ctx){\n const snap=()=>globalThis.window?.__debug?.idbSnapshot||{};\n fs.mkdtempSync=prefix=>{const suffix=Math.random().toString(36).slice(2,8);const p=prefix+suffix;fs.mkdirSync(p);return p;};\n fs.mkfifoSync=p=>{snap()[p.replace(/^\\//,'')]={__fifo:{buf:[],readers:[],writers:[]},mode:0o010644,ino:0};};\n ctx.umask=ctx.umask||0o022;\n return fs;\n}\n","shell-pm-layout.js":"import { detectPm } from './shell-pm.js';\n\nconst hashOf=(name,ver)=>{let h=0;for(const c of name+'@'+ver)h=((h<<5)-h+c.charCodeAt(0))|0;return(h>>>0).toString(36);};\n\nexport function makePnpmLayout(fs,snap,persist,ctx){\n const storeBase=()=>{const d=ctx.cwd.replace(/^\\//,'').replace(/\\/$/,'');return(d?d+'/':'')+'node_modules/.pnpm';};\n return{\n install(name,ver){\n if(!fs.symlinkSync)throw new Error('pnpm layout requires symlink support');\n const base=ctx.cwd.replace(/^\\//,'').replace(/\\/$/,'');\n const store=storeBase()+'/'+name+'@'+ver+'/node_modules/'+name;\n const linkPath='/'+(base?base+'/':'')+'node_modules/'+name;\n const storePath='/'+store;\n if(!fs.existsSync('/'+store+'/package.json')){\n fs.mkdirSync('/'+store,{recursive:true});\n snap()['/'+store+'/package.json'.replace(/^\\//,'')]=JSON.stringify({name,version:ver,main:'index.js'});\n snap()['/'+store+'/index.js'.replace(/^\\//,'')]=`import('https://esm.sh/${name}@${ver}').then(m=>module.exports=m.default||m);`;\n }\n if(!fs.existsSync(linkPath))fs.symlinkSync(storePath,linkPath);\n persist();\n },\n resolve(name){const base=ctx.cwd.replace(/^\\//,'').replace(/\\/$/,'');return'/'+(base?base+'/':'')+'node_modules/'+name;}\n };\n}\n\nexport function parseWorkspaces(snap,cwd=''){\n const base=cwd.replace(/^\\//,'').replace(/\\/$/,'');\n const pj=snap[(base?base+'/':'')+'package.json'];\n const wsYaml=snap[(base?base+'/':'')+'pnpm-workspace.yaml'];\n let patterns=[];\n if(pj){try{const p=JSON.parse(pj);if(Array.isArray(p.workspaces))patterns=p.workspaces;else if(p.workspaces?.packages)patterns=p.workspaces.packages;}catch{}}\n if(wsYaml){const m=wsYaml.match(/packages:\\s*([\\s\\S]+?)(?=\\n\\w|$)/);if(m){for(const line of m[1].split('\\n')){const x=line.match(/^\\s*-\\s*['\"]?([^'\"\\n]+)['\"]?/);if(x)patterns.push(x[1]);}}}\n const members=[];\n for(const pat of patterns){\n const re=new RegExp('^'+(base?base+'/':'')+pat.replace(/\\*\\*/g,'.+').replace(/\\*/g,'[^/]+')+'/package.json$');\n for(const k of Object.keys(snap))if(re.test(k)){const p=JSON.parse(snap[k]);members.push({path:k.replace(/\\/package\\.json$/,''),name:p.name,version:p.version,deps:p.dependencies||{}});}\n }\n return members;\n}\n\nexport function parseYarnLockV1(src){\n const entries={};\n const blocks=src.split(/\\n\\n/).filter(b=>b.trim()&&!b.startsWith('#'));\n for(const block of blocks){\n const lines=block.split('\\n');const header=lines[0].replace(/:$/,'').replace(/\"/g,'');\n const meta={};for(const line of lines.slice(1)){const m=line.match(/^\\s+(\\w+)\\s+\"?([^\"]+)\"?/);if(m)meta[m[1]]=m[2];}\n for(const key of header.split(',').map(s=>s.trim()))entries[key]={version:meta.version,resolved:meta.resolved,integrity:meta.integrity};\n }\n return entries;\n}\n\nexport function writeYarnLockV1(deps){\n const lines=['# THIS IS AN AUTOGENERATED FILE.',''];\n for(const[name,ver] of Object.entries(deps)){\n lines.push(`\"${name}@${ver}\":`,` version \"${ver.replace(/^[\\^~]/,'')}\"`,` resolved \"https://registry.npmjs.org/${name}/-/${name}-${ver.replace(/^[\\^~]/,'')}.tgz\"`,'');\n }\n return lines.join('\\n');\n}\n\nexport function makeDlx(term,fs,ctx,runCmd){\n return async args=>{const pkg=args[0];if(!pkg)return 1;const spec=pkg.match(/^(@?[^@]+)(?:@(.+))?$/);const name=spec[1];term.write(`dlx: loading ${pkg} from esm.sh\\r\\n`);try{const mod=await import('https://esm.sh/'+pkg);const main=mod.default||mod;if(typeof main==='function')return main(args.slice(1))||0;return 0;}catch(e){term.write(`dlx: ${e.message}\\r\\n`);return 1;}};\n}\n","shell-node-testrunner.js":"export function makeTestRunner(term){\n const suites=[];let current=null;const results={pass:0,fail:0,skip:0,failures:[]};\n const write=term?(s=>term.write(s)):(s=>console.log(s.replace(/\\r\\n/g,'')));\n const color=(c,s)=>`\\x1b[${c}m${s}\\x1b[0m`;\n async function runOne(name,fn,parentPath=''){\n const path=(parentPath?parentPath+' > ':'')+name;\n if(!fn){results.skip++;write(color(33,' - '+path+' (skip)')+'\\r\\n');return;}\n const t0=performance.now();\n try{await fn(tctx(name,path));results.pass++;write(color(32,' ✓ '+path)+` ${(performance.now()-t0).toFixed(1)}ms\\r\\n`);}\n catch(e){results.fail++;results.failures.push({path,error:e});write(color(31,' ✗ '+path+' — '+e.message)+'\\r\\n');}\n }\n function tctx(name,path){return{name,fullName:path,diagnostic(m){write(color(90,' # '+m)+'\\r\\n');},skip(){throw Object.assign(new Error('skip'),{__skip:true});},todo(){throw Object.assign(new Error('todo'),{__todo:true});},signal:new AbortController().signal,plan(n){}};}\n function test(name,optsOrFn,maybeFn){const fn=typeof optsOrFn==='function'?optsOrFn:maybeFn;const opts=typeof optsOrFn==='object'?optsOrFn:{};if(opts.skip)return runOne(name,null);if(opts.only){}if(current){current.tests.push({name,fn});return Promise.resolve();}return runOne(name,fn);}\n function describe(name,fn){const prev=current;current={name,tests:[],parentPath:prev?prev.fullPath:'',fullPath:(prev?prev.fullPath+' > ':'')+name};try{fn(current);}finally{const c=current;current=prev;return(async()=>{for(const t of c.tests)await runOne(t.name,t.fn,c.fullPath);})();}}\n const mock={\n fn(impl){const calls=[];const mk=function(...a){calls.push({arguments:a,result:undefined,error:undefined,target:this});try{const r=impl?impl.apply(this,a):undefined;calls[calls.length-1].result=r;return r;}catch(e){calls[calls.length-1].error=e;throw e;}};mk.mock={calls,callCount(){return calls.length;},resetCalls(){calls.length=0;},restore(){}};return mk;},\n method(obj,key,impl){const orig=obj[key];const m=mock.fn(impl||orig);obj[key]=m;m.mock.restore=()=>{obj[key]=orig;};return m;},\n timers:{enable(){},reset(){},runAll(){},tick(){},restore(){}},\n };\n const api={test,describe,it:test,before:fn=>fn?.(),after:fn=>fn?.(),beforeEach:()=>{},afterEach:()=>{},mock,run(){},results,\n async summarize(){write('\\r\\n'+color(1,`# tests ${results.pass+results.fail+results.skip}`)+'\\r\\n');write(color(32,`# pass ${results.pass}`)+'\\r\\n');write(color(31,`# fail ${results.fail}`)+'\\r\\n');write(color(33,`# skip ${results.skip}`)+'\\r\\n');return results.fail===0;},\n };\n return api;\n}\n\nexport function makeTapReporter(term){\n const w=term?(s=>term.write(s)):(s=>console.log(s));\n let n=0;\n return{\n ok(name){w(`ok ${++n} - ${name}\\r\\n`);},\n notOk(name,msg){w(`not ok ${++n} - ${name}\\r\\n ---\\r\\n error: ${msg}\\r\\n ...\\r\\n`);},\n plan(total){w(`1..${total}\\r\\n`);},\n comment(m){w(`# ${m}\\r\\n`);},\n };\n}\n","shell-node-util-extras.js":"const ANSI_RE=/\\x1b\\[[0-9;]*[a-zA-Z]/g;\nconst STYLE_CODES={reset:0,bold:1,dim:2,italic:3,underline:4,inverse:7,hidden:8,strikethrough:9,black:30,red:31,green:32,yellow:33,blue:34,magenta:35,cyan:36,white:37,gray:90,bgBlack:40,bgRed:41,bgGreen:42,bgYellow:43,bgBlue:44,bgMagenta:45,bgCyan:46,bgWhite:47};\n\nexport function styleText(styles,text){\n const arr=Array.isArray(styles)?styles:[styles];\n const codes=arr.map(s=>STYLE_CODES[s]).filter(c=>c!=null);\n if(!codes.length)return text;\n return `\\x1b[${codes.join(';')}m${text}\\x1b[0m`;\n}\n\nexport function stripVTControlCharacters(s){return String(s).replace(ANSI_RE,'');}\n\nexport function getCallSites(frames=10){\n const e=new Error();const lines=(e.stack||'').split('\\n').slice(2,2+frames);\n return lines.map(l=>{const m=l.match(/at\\s+(?:(.+?)\\s+\\()?(.+?):(\\d+):(\\d+)\\)?/);return{functionName:m?.[1]||'<anonymous>',scriptName:m?.[2]||'',lineNumber:m?+m[3]:0,column:m?+m[4]:0,scriptId:'0'};});\n}\n\nexport class MIMEType{\n constructor(input){\n const [essence,...paramParts]=String(input).split(';');\n const [type,subtype]=essence.trim().split('/');\n if(!type||!subtype)throw new TypeError('Invalid MIME: '+input);\n this._type=type.toLowerCase();this._sub=subtype.toLowerCase();\n this._params=new MIMEParams();\n for(const p of paramParts){const [k,v]=p.split('=');if(k&&v)this._params.set(k.trim().toLowerCase(),v.trim().replace(/^[\"']|[\"']$/g,''));}\n }\n get type(){return this._type;}set type(v){this._type=String(v).toLowerCase();}\n get subtype(){return this._sub;}set subtype(v){this._sub=String(v).toLowerCase();}\n get essence(){return `${this._type}/${this._sub}`;}\n get params(){return this._params;}\n toString(){const p=[...this._params].map(([k,v])=>`${k}=${v}`).join(';');return this.essence+(p?';'+p:'');}\n}\n\nexport class MIMEParams{\n constructor(){this._m=new Map();}\n get(k){return this._m.get(k);}\n set(k,v){this._m.set(String(k).toLowerCase(),String(v));return this;}\n delete(k){return this._m.delete(k);}\n has(k){return this._m.has(k);}\n *entries(){yield*this._m.entries();}\n *keys(){yield*this._m.keys();}\n *values(){yield*this._m.values();}\n [Symbol.iterator](){return this._m[Symbol.iterator]();}\n}\n\nexport function makeConsoleExtras(origConsole,term){\n const write=term?(s=>term.write(s)):(s=>origConsole.log(s));\n const timers=new Map();const counters=new Map();let groupDepth=0;const ind=()=>' '.repeat(groupDepth);\n return{\n table(data,columns){if(!data||typeof data!=='object')return origConsole.log(data);const rows=Array.isArray(data)?data:Object.entries(data).map(([k,v])=>({'(index)':k,...(typeof v==='object'?v:{Values:v})}));if(!rows.length)return;const cols=columns||[...new Set(rows.flatMap(r=>Object.keys(r)))];const w=cols.map(c=>Math.max(c.length,...rows.map(r=>String(r[c]??'').length)));const line=(cells,pad)=>'│ '+cells.map((c,i)=>String(c??'').padEnd(w[i]))+' │\\r\\n';const sep=s=>s+cols.map((_,i)=>'─'.repeat(w[i]+2)).join(s==='├'?'┼':'─')+(s==='├'?'┤':'╯')+'\\r\\n';write('╭'+cols.map((_,i)=>'─'.repeat(w[i]+2)).join('─')+'╮\\r\\n');write('│ '+cols.map((c,i)=>c.padEnd(w[i])).join(' │ ')+' │\\r\\n');write('├'+cols.map((_,i)=>'─'.repeat(w[i]+2)).join('┼')+'┤\\r\\n');for(const r of rows)write('│ '+cols.map((c,i)=>String(r[c]??'').padEnd(w[i])).join(' │ ')+' │\\r\\n');write('╰'+cols.map((_,i)=>'─'.repeat(w[i]+2)).join('─')+'╯\\r\\n');},\n group(label){if(label)write(ind()+label+'\\r\\n');groupDepth++;},\n groupCollapsed(label){this.group(label);},\n groupEnd(){groupDepth=Math.max(0,groupDepth-1);},\n time(label='default'){timers.set(label,performance.now());},\n timeEnd(label='default'){const t=timers.get(label);if(t==null)return;timers.delete(label);write(`${label}: ${(performance.now()-t).toFixed(3)}ms\\r\\n`);},\n timeLog(label='default',...rest){const t=timers.get(label);if(t==null)return;write(`${label}: ${(performance.now()-t).toFixed(3)}ms ${rest.join(' ')}\\r\\n`);},\n count(label='default'){const n=(counters.get(label)||0)+1;counters.set(label,n);write(`${label}: ${n}\\r\\n`);},\n countReset(label='default'){counters.set(label,0);},\n dir(v){write(JSON.stringify(v,null,2)+'\\r\\n');},\n dirxml(v){this.dir(v);},\n trace(...a){write('Trace: '+a.join(' ')+'\\r\\n'+new Error().stack+'\\r\\n');},\n assert(cond,...msg){if(!cond)write('Assertion failed: '+msg.join(' ')+'\\r\\n');},\n clear(){write('\\x1b[2J\\x1b[H');},\n profile(){},profileEnd(){},timeStamp(){},\n };\n}\n","shell-node-ipc.js":"const CHAN='plugkit-ipc';\n\nexport function makeForkIpc(proc){\n if(typeof BroadcastChannel==='undefined')return{enabled:false};\n const bc=new BroadcastChannel(CHAN);\n const childId=globalThis.location?.hash==='#ipc-child'?1:0;\n const isChild=childId>0;\n const handlers={message:[],disconnect:[]};\n bc.addEventListener('message',e=>{const{from,to,msg}=e.data||{};if(isChild&&to==='child'){for(const h of handlers.message)h(msg,{});}else if(!isChild&&to==='parent'){for(const h of handlers.message)h(msg,{});}});\n proc.send=msg=>{bc.postMessage({from:isChild?'child':'parent',to:isChild?'parent':'child',msg});return true;};\n proc.on=(ev,fn)=>{if(ev==='message'||ev==='disconnect')(handlers[ev]=handlers[ev]||[]).push(fn);return proc;};\n proc.disconnect=()=>{bc.postMessage({from:isChild?'child':'parent',to:isChild?'parent':'child',type:'disconnect'});for(const h of handlers.disconnect)h();};\n proc.connected=true;\n return{enabled:true,bc,isChild};\n}\n","shell-node-procfs.js":"export function makeProcFs(proc){\n const g=globalThis;\n const gen={\n 'proc/self/cmdline':()=>(proc.argv||[]).join('\\0')+'\\0',\n 'proc/self/environ':()=>Object.entries(proc.env||{}).map(([k,v])=>`${k}=${v}`).join('\\0')+'\\0',\n 'proc/self/cwd':()=>proc.cwd?.()||'/',\n 'proc/self/exe':()=>proc.execPath||'/usr/local/bin/node',\n 'proc/self/status':()=>{const m=performance.memory||{usedJSHeapSize:0,totalJSHeapSize:0};return`Name:\\tnode\\nState:\\tR (running)\\nPid:\\t${proc.pid||1}\\nPPid:\\t${proc.ppid||0}\\nUid:\\t0\\t0\\t0\\t0\\nGid:\\t0\\t0\\t0\\t0\\nVmRSS:\\t${(m.totalJSHeapSize/1024)|0} kB\\nVmPeak:\\t${(m.totalJSHeapSize/1024)|0} kB\\n`;},\n 'proc/self/stat':()=>`${proc.pid||1} (node) R ${proc.ppid||0} ${proc.pid||1} ${proc.pid||1} 0 -1 4194304 0 0 0 0 0 0 0 0 20 0 1 0 ${performance.now()|0} ${(performance.memory?.totalJSHeapSize||0)} 0 18446744073709551615 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0\\n`,\n 'proc/self/maps':()=>'00400000-00500000 r-xp 00000000 00:00 0 [text]\\n',\n 'proc/self/limits':()=>'Limit Soft Limit Hard Limit\\nMax open files 1024 4096\\n',\n 'proc/cpuinfo':()=>{const n=navigator?.hardwareConcurrency||4;let out='';for(let i=0;i<n;i++)out+=`processor\\t: ${i}\\nvendor_id\\t: BrowserCPU\\nmodel name\\t: Browser JS Engine\\ncpu MHz\\t\\t: 3000.000\\ncache size\\t: 8192 KB\\ncores\\t\\t: ${n}\\n\\n`;return out;},\n 'proc/meminfo':()=>{const m=performance.memory||{totalJSHeapSize:1e9,jsHeapSizeLimit:2e9,usedJSHeapSize:5e8};return`MemTotal: ${(m.jsHeapSizeLimit/1024)|0} kB\\nMemFree: ${((m.jsHeapSizeLimit-m.usedJSHeapSize)/1024)|0} kB\\nMemAvailable: ${((m.jsHeapSizeLimit-m.usedJSHeapSize)/1024)|0} kB\\nBuffers: 0 kB\\nCached: 0 kB\\n`;},\n 'proc/uptime':()=>`${(performance.now()/1000).toFixed(2)} ${(performance.now()/1000).toFixed(2)}\\n`,\n 'proc/loadavg':()=>'0.00 0.00 0.00 1/1 '+(proc.pid||1)+'\\n',\n 'proc/version':()=>`Linux version 6.0.0-browser (node@thebird) #1 SMP ${new Date().toUTCString()}\\n`,\n 'proc/stat':()=>'cpu 0 0 0 0 0 0 0 0 0 0\\nbtime '+Math.floor(Date.now()/1000)+'\\n',\n 'proc/mounts':()=>'idbfs / idbfs rw,relatime 0 0\\n',\n 'proc/filesystems':()=>'nodev\\tidbfs\\nnodev\\topfs\\n',\n 'etc/hosts':()=>'127.0.0.1 localhost\\n::1 localhost\\n',\n 'etc/resolv.conf':()=>'nameserver 1.1.1.1\\nnameserver 8.8.8.8\\n',\n 'etc/passwd':()=>'root:x:0:0:root:/root:/bin/sh\\n',\n 'etc/group':()=>'root:x:0:\\n',\n 'etc/os-release':()=>'NAME=\"thebird\"\\nPRETTY_NAME=\"thebird browser runtime\"\\nID=thebird\\nID_LIKE=linux\\nVERSION_ID=\"1.0\"\\n',\n 'etc/hostname':()=>'thebird\\n',\n 'etc/machine-id':()=>'00000000000000000000000000000000\\n',\n 'etc/shells':()=>'/bin/sh\\n/bin/bash\\n',\n };\n return{\n handles(path){const k=path.replace(/^\\//,'').replace(/\\/$/,'');return k in gen;},\n read(path){const k=path.replace(/^\\//,'').replace(/\\/$/,'');const fn=gen[k];if(!fn)return null;try{return fn();}catch{return'';}},\n list(){return Object.keys(gen).map(k=>'/'+k);},\n };\n}\n\nexport function wireProcFs(fs,procFs){\n const origRead=fs.readFileSync, origExists=fs.existsSync, origStat=fs.statSync;\n fs.readFileSync=(p,enc)=>{if(procFs.handles(p)){const s=procFs.read(p);return enc?s:new TextEncoder().encode(s);}return origRead(p,enc);};\n fs.existsSync=p=>procFs.handles(p)||origExists(p);\n fs.statSync=p=>{if(procFs.handles(p)){const s=procFs.read(p);return{size:s.length,mode:0o100444,isFile:()=>true,isDirectory:()=>false,isSymbolicLink:()=>false,isFIFO:()=>false,isBlockDevice:()=>false,isCharacterDevice:()=>false,isSocket:()=>false,mtimeMs:Date.now(),mtime:new Date(),atimeMs:Date.now(),ctimeMs:Date.now(),birthtimeMs:Date.now(),uid:0,gid:0,nlink:1,dev:0,ino:0,rdev:0,blksize:4096,blocks:1};}return origStat(p);};\n return fs;\n}\n","shell-node-git.js":"let gitMod=null;let gitPromise=null;\n\nasync function loadGit(){\n if(!gitPromise)gitPromise=Promise.all([\n import('https://esm.sh/isomorphic-git@1.27.1/es2022/isomorphic-git.mjs').then(m=>m.default||m),\n import('https://esm.sh/isomorphic-git@1.27.1/http/web').then(m=>m.default||m).catch(()=>null),\n ]).then(([git,http])=>({git,http}));\n return gitPromise;\n}\n\nexport async function preloadGit(){gitMod=await loadGit();return gitMod;}\n\nexport function makeGit(fs){\n const fsAdapter={\n promises:{\n async readFile(path,opts){try{const enc=typeof opts==='string'?opts:opts?.encoding;const d=fs.readFileSync(path);if(enc==='utf8'||enc==='utf-8')return typeof d==='string'?d:new TextDecoder().decode(d);return typeof d==='string'?new TextEncoder().encode(d):d;}catch(e){e.code='ENOENT';throw e;}},\n async writeFile(path,data){const parts=path.split('/');for(let i=1;i<parts.length;i++){const d=parts.slice(0,i).join('/');if(d&&!fs.existsSync(d))fs.mkdirSync(d,{recursive:true});}fs.writeFileSync(path,data);},\n async unlink(path){fs.unlinkSync(path);},\n async readdir(path){return fs.readdirSync(path);},\n async mkdir(path){fs.mkdirSync(path,{recursive:true});},\n async rmdir(path){fs.rmSync?.(path,{recursive:true})||fs.unlinkSync(path);},\n async stat(path){return fs.statSync(path);},\n async lstat(path){return fs.lstatSync?.(path)||fs.statSync(path);},\n async readlink(path){return fs.readlinkSync?.(path);},\n async symlink(target,path){fs.symlinkSync?.(target,path);},\n async chmod(){},\n },\n };\n const need=()=>{if(!gitMod)throw new Error('git: call await preloadGit() once before git ops');return gitMod;};\n const wrap=method=>async opts=>{const{git,http}=need();return git[method]({fs:fsAdapter,http,...opts});};\n return{\n clone:wrap('clone'),\n init:wrap('init'),\n add:wrap('add'),\n commit:wrap('commit'),\n push:wrap('push'),\n pull:wrap('pull'),\n fetch:wrap('fetch'),\n status:wrap('status'),\n statusMatrix:wrap('statusMatrix'),\n log:wrap('log'),\n listBranches:wrap('listBranches'),\n branch:wrap('branch'),\n checkout:wrap('checkout'),\n resolveRef:wrap('resolveRef'),\n currentBranch:wrap('currentBranch'),\n remove:wrap('remove'),\n listRemotes:wrap('listRemotes'),\n addRemote:wrap('addRemote'),\n deleteRemote:wrap('deleteRemote'),\n merge:wrap('merge'),\n readBlob:wrap('readBlob'),\n readTree:wrap('readTree'),\n readCommit:wrap('readCommit'),\n tag:wrap('tag'),\n listTags:wrap('listTags'),\n diff:async opts=>{const s=await wrap('statusMatrix')(opts);return s.filter(([,,w,s])=>w!==s).map(([path])=>path);},\n preload:preloadGit,\n };\n}\n","shell-node-tar.js":"const BLOCK=512;\nconst readStr=(buf,o,len)=>{let e=o;while(e<o+len&&buf[e]!==0)e++;return new TextDecoder().decode(buf.slice(o,e));};\nconst readOctal=(buf,o,len)=>{const s=readStr(buf,o,len).trim();return s?parseInt(s,8):0;};\n\nexport function untar(data){\n const buf=data instanceof Uint8Array?data:new Uint8Array(data);\n const entries=[];let off=0;\n while(off+BLOCK<=buf.length){\n if(buf[off]===0&&buf[off+BLOCK-1]===0){off+=BLOCK;continue;}\n const name=readStr(buf,off,100);\n if(!name)break;\n const mode=readOctal(buf,off+100,8);\n const size=readOctal(buf,off+124,12);\n const mtime=readOctal(buf,off+136,12);\n const type=String.fromCharCode(buf[off+156]||0x30);\n const prefix=readStr(buf,off+345,155);\n const fullName=prefix?prefix+'/'+name:name;\n const dataStart=off+BLOCK;\n const dataEnd=dataStart+size;\n const body=type==='0'||type==='\\0'?buf.slice(dataStart,dataEnd):null;\n entries.push({name:fullName,mode,size,mtime,type,data:body});\n const padded=Math.ceil(size/BLOCK)*BLOCK;\n off=dataStart+padded;\n }\n return entries;\n}\n\nexport function makeTar(fs,fflate,Buf){\n return{\n async extract(data,dest='/'){\n let bytes=data instanceof Uint8Array?data:new Uint8Array(data);\n if(bytes[0]===0x1f&&bytes[1]===0x8b){bytes=fflate?.gunzipSync?fflate.gunzipSync(bytes):bytes;}\n const entries=untar(bytes);\n const out=[];\n for(const e of entries){\n if(!e.data&&e.type!=='5')continue;\n const target=(dest.replace(/\\/$/,'')+'/'+e.name).replace(/^\\/+/,'/');\n if(e.type==='5'){try{fs.mkdirSync(target,{recursive:true});}catch{}}\n else{const parts=target.split('/');for(let i=1;i<parts.length;i++){const d=parts.slice(0,i).join('/');if(d&&!fs.existsSync(d)){try{fs.mkdirSync(d,{recursive:true});}catch{}}}fs.writeFileSync(target,Buf.from(e.data));}\n out.push(target);\n }\n return out;\n },\n async list(data){let bytes=data instanceof Uint8Array?data:new Uint8Array(data);if(bytes[0]===0x1f&&bytes[1]===0x8b)bytes=fflate?.gunzipSync?fflate.gunzipSync(bytes):bytes;return untar(bytes).map(e=>e.name);},\n untar,\n };\n}\n","shell-node-dns.js":"const DOH='https://cloudflare-dns.com/dns-query';\nconst DOH_FALLBACK='https://dns.google/resolve';\n\nasync function query(name,type='A'){\n const TYPES={A:1,AAAA:28,MX:15,TXT:16,NS:2,CNAME:5,SOA:6,PTR:12,SRV:33};\n const t=TYPES[type]||1;\n try{\n const r=await fetch(`${DOH}?name=${encodeURIComponent(name)}&type=${t}`,{headers:{accept:'application/dns-json'}});\n const j=await r.json();\n return j.Answer||[];\n }catch{\n const r=await fetch(`${DOH_FALLBACK}?name=${encodeURIComponent(name)}&type=${t}`);\n const j=await r.json();\n return j.Answer||[];\n }\n}\n\nexport function makeDns(){\n const extract=(answers,want)=>answers.filter(a=>a.type===want).map(a=>a.data.replace(/^\"|\"$/g,''));\n return{\n promises:{\n async resolve(name,type='A'){const a=await query(name,type);return extract(a,{A:1,AAAA:28,CNAME:5,NS:2,TXT:16,MX:15,PTR:12,SRV:33,SOA:6}[type]);},\n async resolve4(name){return this.resolve(name,'A');},\n async resolve6(name){return this.resolve(name,'AAAA');},\n async resolveMx(name){const a=await query(name,'MX');return extract(a,15).map(s=>{const[priority,exchange]=s.split(' ');return{priority:+priority,exchange};});},\n async resolveTxt(name){const a=await query(name,'TXT');return extract(a,16).map(s=>[s]);},\n async resolveCname(name){return this.resolve(name,'CNAME');},\n async resolveNs(name){return this.resolve(name,'NS');},\n async resolveSrv(name){const a=await query(name,'SRV');return extract(a,33).map(s=>{const[priority,weight,port,name]=s.split(' ');return{priority:+priority,weight:+weight,port:+port,name};});},\n async reverse(ip){const rev=ip.includes(':')?ip:ip.split('.').reverse().join('.')+'.in-addr.arpa';const a=await query(rev,'PTR');return extract(a,12);},\n async lookup(hostname,opts={}){if(hostname==='localhost')return{address:'127.0.0.1',family:4};const t=opts.family===6?'AAAA':'A';const results=await query(hostname,t);if(!results.length)throw Object.assign(new Error('getaddrinfo ENOTFOUND '+hostname),{code:'ENOTFOUND',hostname});return{address:results[0].data,family:opts.family===6?6:4};},\n async lookupService(ip,port){return{hostname:ip,service:String(port)};},\n getServers(){return['1.1.1.1','8.8.8.8'];},\n setServers(){},\n },\n get resolve(){const p=this.promises;return(name,type,cb)=>{if(typeof type==='function'){cb=type;type='A';}p.resolve(name,type).then(r=>cb(null,r),cb);};},\n lookup:(h,o,cb)=>{if(typeof o==='function'){cb=o;o={};}query(h,o.family===6?'AAAA':'A').then(a=>a.length?cb(null,a[0].data,o.family===6?6:4):cb(Object.assign(new Error('ENOTFOUND'),{code:'ENOTFOUND'})),cb);},\n ADDRCONFIG:0x20,V4MAPPED:0x8,ALL:0x10,\n NODATA:'ENODATA',FORMERR:'EFORMERR',SERVFAIL:'ESERVFAIL',NOTFOUND:'ENOTFOUND',\n };\n}\n","shell-node-native.js":"const NATIVE_DISPATCH={\n 'better_sqlite3.node':()=>import('https://esm.sh/sql.js@1.11.0/dist/sql-wasm.js').then(m=>{const Lib=m.default||m;return{__native:true,Database:Lib.Database||Lib};}),\n 'bcrypt_lib.node':()=>import('https://esm.sh/bcryptjs@2.4.3').then(m=>({__native:true,...(m.default||m)})),\n 'sharp.node':()=>({__native:true,resize:()=>{throw new Error('sharp native requires WASM variant — use @img/sharp-wasm32');}}),\n 'argon2.node':()=>import('https://esm.sh/argon2-browser@1.18.0').then(m=>({__native:true,hash:m.default.hash,verify:m.default.verify})),\n 'bufferutil.node':()=>({__native:true,mask:(src,mask,out,offset,length)=>{for(let i=0;i<length;i++)out[offset+i]=src[i]^mask[i&3];},unmask:(buf,mask)=>{for(let i=0;i<buf.length;i++)buf[i]^=mask[i&3];}}),\n 'utf_8_validate.node':()=>({__native:true,default:(s,buf)=>{try{new TextDecoder('utf-8',{fatal:true}).decode(buf);return true;}catch{return false;}}}),\n 'farmhash.node':()=>({__native:true,hash32:s=>{let h=2166136261;for(const c of String(s))h=Math.imul(h^c.charCodeAt(0),16777619)>>>0;return h;},hash64:s=>BigInt(NATIVE_DISPATCH['farmhash.node']().hash32(s))}),\n};\n\nexport function makeNativeLoader(){\n return{\n async dlopen(target,path){const key=path.split('/').pop();const loader=NATIVE_DISPATCH[key];if(!loader)throw new Error(`process.dlopen: no WASM/browser equivalent for ${path}`);const mod=await loader();target.exports=mod;return target;},\n resolve:key=>NATIVE_DISPATCH[key]?'virtual:native/'+key:null,\n register:(name,loader)=>{NATIVE_DISPATCH[name]=loader;},\n list:()=>Object.keys(NATIVE_DISPATCH),\n };\n}\n\nexport function wireNativeRequire(makeRequire,nativeLoader){\n const origRequire=makeRequire;\n return dir=>{\n const req=origRequire(dir);\n const wrapped=function(id){\n if(id.endsWith('.node')){const key=id.split('/').pop();if(nativeLoader.resolve(key)){const target={exports:{}};nativeLoader.dlopen(target,id);return target.exports;}throw new Error(`Cannot find native addon: ${id}`);}\n return req(id);\n };\n wrapped.resolve=req.resolve;wrapped.cache=req.cache;\n return wrapped;\n };\n}\n","shell-node-coreutils.js":"export function makeCoreutils(ctx,procFs){\n const term=ctx.term;\n const out=s=>term.write(s+'\\r\\n');\n return{\n uname:args=>{const flags=args.join('');const info={kernel:'Linux',node:'thebird',release:'6.0.0-browser',version:'#1 SMP',machine:'x86_64',os:'thebird'};if(flags.includes('a'))out(`${info.kernel} ${info.node} ${info.release} ${info.version} ${info.machine} ${info.os}`);else if(flags.includes('r'))out(info.release);else if(flags.includes('n'))out(info.node);else if(flags.includes('m'))out(info.machine);else if(flags.includes('s'))out(info.kernel);else if(flags.includes('o'))out(info.os);else out(info.kernel);return 0;},\n whoami:()=>{out(ctx.env.USER||'root');return 0;},\n hostname:args=>{if(args[0]){ctx.env.HOSTNAME=args[0];return 0;}out(ctx.env.HOSTNAME||'thebird');return 0;},\n id:args=>{out('uid=0(root) gid=0(root) groups=0(root)');return 0;},\n df:args=>{const used=performance.memory?.usedJSHeapSize||5e8;const total=performance.memory?.jsHeapSizeLimit||2e9;out('Filesystem 1K-blocks Used Available Use% Mounted on');out(`idbfs ${(total/1024)|0} ${(used/1024)|0} ${((total-used)/1024)|0} ${((used/total)*100)|0}% /`);return 0;},\n free:args=>{const m=performance.memory||{totalJSHeapSize:1e9,usedJSHeapSize:5e8,jsHeapSizeLimit:2e9};const kb=n=>(n/1024)|0;out(' total used free shared buff/cache available');out(`Mem: ${kb(m.jsHeapSizeLimit).toString().padStart(11)} ${kb(m.usedJSHeapSize).toString().padStart(11)} ${kb(m.jsHeapSizeLimit-m.usedJSHeapSize).toString().padStart(11)} 0 0 ${kb(m.jsHeapSizeLimit-m.usedJSHeapSize).toString().padStart(11)}`);out('Swap: 0 0 0');return 0;},\n uptime:args=>{const sec=(performance.now()/1000)|0;const h=(sec/3600)|0,m=((sec%3600)/60)|0;out(`${new Date().toTimeString().slice(0,8)} up ${h}:${String(m).padStart(2,'0')}, 1 user, load average: 0.00, 0.00, 0.00`);return 0;},\n ps:args=>{out(' PID TTY TIME CMD');out(' 1 pts/0 00:00:00 sh');out(' 2 pts/0 00:00:00 ps');return 0;},\n nproc:args=>{out(String(navigator?.hardwareConcurrency||1));return 0;},\n arch:()=>{out('x86_64');return 0;},\n yes:args=>{const s=args.length?args.join(' '):'y';for(let i=0;i<1000;i++)out(s);return 0;},\n true:()=>0,\n false:()=>1,\n sleep:args=>new Promise(r=>setTimeout(()=>r(0),(parseFloat(args[0])||0)*1000)),\n seq:args=>{const[first,...rest]=args.map(Number);const last=rest.length?rest[rest.length-1]:first;const step=rest.length===2?rest[0]:1;const start=rest.length?first:1;for(let i=start;step>0?i<=last:i>=last;i+=step)out(String(i));return 0;},\n tac:args=>{if(args[0]){const c=ctx.readFile?.(args[0])||'';out(c.split('\\n').reverse().join('\\n'));}return 0;},\n rev:args=>{if(args[0]){const c=ctx.readFile?.(args[0])||'';for(const line of c.split('\\n'))out([...line].reverse().join(''));}return 0;},\n nl:args=>{if(args[0]){const c=ctx.readFile?.(args[0])||'';c.split('\\n').forEach((line,i)=>out(` ${i+1}\\t${line}`));}return 0;},\n fold:args=>{const w=args.includes('-w')?parseInt(args[args.indexOf('-w')+1])||80:80;const text=args.filter(a=>!a.startsWith('-'))[0];if(text){const c=ctx.readFile?.(text)||'';for(const line of c.split('\\n'))for(let i=0;i<line.length;i+=w)out(line.slice(i,i+w));}return 0;},\n tr:args=>{return 0;},\n od:args=>{if(args[0]){const c=ctx.readFile?.(args[0])||'';const b=typeof c==='string'?new TextEncoder().encode(c):c;for(let i=0;i<b.length;i+=16){const hex=[...b.slice(i,i+16)].map(x=>x.toString(16).padStart(2,'0')).join(' ');out(i.toString(8).padStart(7,'0')+' '+hex);}}return 0;},\n xxd:args=>{if(args[0]){const c=ctx.readFile?.(args[0])||'';const b=typeof c==='string'?new TextEncoder().encode(c):c;for(let i=0;i<b.length;i+=16){const row=b.slice(i,i+16);const hex=[...row].map(x=>x.toString(16).padStart(2,'0')).join(' ').padEnd(47);const asc=[...row].map(x=>x>=0x20&&x<0x7f?String.fromCharCode(x):'.').join('');out(i.toString(16).padStart(8,'0')+': '+hex+' '+asc);}}return 0;},\n dirname:args=>{out((args[0]||'').replace(/\\/[^/]*$/,'')||'.');return 0;},\n basename:args=>{const p=args[0]||'';const ext=args[1]||'';let b=p.split('/').pop()||'';if(ext&&b.endsWith(ext))b=b.slice(0,-ext.length);out(b);return 0;},\n pwd:()=>{out(ctx.cwd||'/');return 0;},\n groups:()=>{out('root');return 0;},\n logname:()=>{out('root');return 0;},\n tty:()=>{out('/dev/pts/0');return 0;},\n stty:()=>0,\n locale:()=>{out('LANG=C\\nLC_ALL=\\n');return 0;},\n };\n}\n","shell-node-registry.js":"const ESM_API='https://esm.sh';\nconst cache=new Map();\n\nasync function esmMeta(name){\n if(cache.has(name))return cache.get(name);\n try{\n const url=`${ESM_API}/${name}/package.json`;\n const r=await fetch(url);\n if(!r.ok)throw new Error('not found');\n const pj=await r.json();\n cache.set(name,pj);return pj;\n }catch(e){throw new Error(`registry: cannot fetch ${name} — ${e.message}`);}\n}\n\nexport function makeRegistry(){\n return{\n async view(spec){const[name,field]=spec.split(/\\s+/);const pj=await esmMeta(name);if(field){const parts=field.split('.');let v=pj;for(const p of parts)v=v?.[p];return v;}return pj;},\n async search(q){try{const r=await fetch(`https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(q)}&size=10`);const j=await r.json();return j.objects?.map(o=>({name:o.package.name,version:o.package.version,description:o.package.description}))||[];}catch{return[];}},\n async deps(name,version='latest'){try{const pj=await esmMeta(version==='latest'?name:`${name}@${version}`);return{dependencies:pj.dependencies||{},devDependencies:pj.devDependencies||{},peerDependencies:pj.peerDependencies||{}};}catch{return{dependencies:{},devDependencies:{},peerDependencies:{}};}},\n async tarballUrl(name,version){const pj=await esmMeta(`${name}@${version}`);return`https://registry.npmjs.org/${name}/-/${name.split('/').pop()}-${pj.version}.tgz`;},\n async fetchTarball(name,version){const url=await this.tarballUrl(name,version);const r=await fetch(url);return new Uint8Array(await r.arrayBuffer());},\n clearCache(){cache.clear();},\n };\n}\n","shell-node-busnet.js":"const BUS_CHAN='plugkit-busnet';\nconst bus=typeof BroadcastChannel!=='undefined'?new BroadcastChannel(BUS_CHAN):null;\nconst listeners=new Map();\nconst connections=new Map();let connSeq=1;\nconst serviceRegistry=new Map();\nlet _origin=null;\nfunction getOrigin(){if(_origin)return _origin;_origin=(globalThis.crypto?.randomUUID?.()||String(Math.random())).slice(0,8);return _origin;}\n\nfunction handleMsg(m){\n if(!m)return;\n if(m.type==='discover'&&m.origin!==getOrigin()){for(const[port,l] of listeners)post({type:'announce',port,service:l.service,origin:getOrigin()});return;}\n if(m.type==='connect'&&listeners.has(m.port)){const l=listeners.get(m.port);const conn=createConnection(m.id,m.from,true);l.onConnection?.(conn);connections.set(m.id,conn);post({type:'connected',id:m.id,from:getOrigin(),to:m.from});return;}\n if(m.type==='connected'&&connections.has(m.id)){queueMicrotask(()=>connections.get(m.id)?._onOpen());return;}\n if(m.type==='data'&&connections.has(m.id)&&m.from!==null&&m.to===getOrigin()){connections.get(m.id)._onData(m.data);return;}\n if(m.type==='data-local'&&connections.has(m.id)){connections.get(m.id)._onData(m.data);return;}\n if(m.type==='close'&&connections.has(m.id)){connections.get(m.id)._onClose();connections.delete(m.id);return;}\n if(m.type==='announce'&&m.origin!==getOrigin()){serviceRegistry.set(m.port+'@'+m.origin,{port:m.port,service:m.service,origin:m.origin,seen:Date.now()});return;}\n}\n\nfunction post(msg){if(bus)bus.postMessage(msg);}\n\nif(bus)bus.addEventListener('message',e=>{if(e.data?.origin===getOrigin())return;handleMsg(e.data);});\n\nfunction createConnection(id,remote,fromServer=false){\n const handlers={data:[],end:[],close:[],open:[],error:[]};\n const conn={\n id,remote,fromServer,readable:true,writable:true,\n on(ev,fn){(handlers[ev]=handlers[ev]||[]).push(fn);return this;},\n once(ev,fn){const w=(...a)=>{this.off(ev,w);fn(...a);};return this.on(ev,w);},\n off(ev,fn){handlers[ev]=(handlers[ev]||[]).filter(x=>x!==fn);return this;},\n write(data){const peer=connections.get(conn._peerId);if(peer){queueMicrotask(()=>peer._onData(data));return true;}post({type:'data',id,data,from:getOrigin(),to:remote});return true;},\n end(data){if(data)conn.write(data);for(const h of handlers.close)h();connections.delete(id);},\n destroy(){for(const h of handlers.close)h();connections.delete(id);},\n _onOpen(){for(const h of handlers.open)h();},\n _onData(d){for(const h of handlers.data)h(d);},\n _onClose(){for(const h of handlers.close)h();},\n _onError(e){for(const h of handlers.error)h(e);},\n _peerId:null,\n };\n return conn;\n}\n\nexport function makeBusnet(){\n return{\n listen(port,service,onConnection){\n if(listeners.has(port))throw Object.assign(new Error('EADDRINUSE'),{code:'EADDRINUSE',port});\n listeners.set(port,{port,service:service||'generic',onConnection,origin:getOrigin()});\n if(bus)bus.postMessage({type:'announce',port,service:service||'generic',origin:getOrigin()});\n return{port,close:()=>{listeners.delete(port);}};\n },\n connect(port,targetOrigin,cb){\n const id=getOrigin()+'-'+(connSeq++);\n const clientConn=createConnection(id,targetOrigin);\n connections.set(id,clientConn);\n if(cb)clientConn.on('open',cb);\n if(listeners.has(port)&&(!targetOrigin||targetOrigin===getOrigin())){\n const srvId=id+'-srv';\n const serverConn=createConnection(srvId,getOrigin(),true);\n connections.set(srvId,serverConn);\n clientConn._peerId=srvId; serverConn._peerId=id;\n const l=listeners.get(port);\n queueMicrotask(()=>{l.onConnection?.(serverConn);serverConn._onOpen();clientConn._onOpen();});\n }else{\n post({type:'connect',id,port,from:getOrigin(),to:targetOrigin});\n }\n return clientConn;\n },\n discover(filter){\n if(bus)bus.postMessage({type:'discover',origin:getOrigin()});\n return new Promise(r=>setTimeout(()=>{const out=[...serviceRegistry.values()];r(filter?.service?out.filter(s=>s.service===filter.service):out);},200));\n },\n getListeners(){return[...listeners.keys()];},\n getServices(){return[...serviceRegistry.values()];},\n origin:getOrigin(),\n _bus:bus,\n };\n}\n\nexport function makeBusHttp(busnet){\n const respond=(conn,status,headers,body)=>{const res=`HTTP/1.1 ${status} ${status===200?'OK':'ERR'}\\r\\n`+Object.entries(headers||{}).map(([k,v])=>`${k}: ${v}`).join('\\r\\n')+`\\r\\nContent-Length: ${body.length}\\r\\n\\r\\n${body}`;conn.write(res);};\n return{\n createServer(handler){\n return{\n listen(port,host,cb){if(typeof host==='function'){cb=host;host=null;}busnet.listen(port,'http',conn=>{conn.on('data',raw=>{const[reqLine,...rest]=String(raw).split('\\r\\n');const[method,url]=reqLine.split(' ');const bodyIdx=rest.indexOf('');const headers={};for(const line of rest.slice(0,bodyIdx)){const [k,v]=line.split(':');if(k)headers[k.trim().toLowerCase()]=v?.trim();}const req={method,url,headers,body:rest.slice(bodyIdx+1).join('\\r\\n')};const res={statusCode:200,_headers:{},setHeader(k,v){this._headers[k]=v;},end(body){respond(conn,this.statusCode,this._headers,body||'');conn.end();}};handler(req,res);});});cb?.();return this;},\n close(cb){cb?.();},\n };\n },\n request(opts,cb){const port=opts.port,targetOrigin=opts.origin||null;const conn=busnet.connect(port,targetOrigin,()=>{const path=opts.path||'/';const method=opts.method||'GET';const hdrs=Object.entries(opts.headers||{}).map(([k,v])=>`${k}: ${v}`).join('\\r\\n');conn.write(`${method} ${path} HTTP/1.1\\r\\n${hdrs}\\r\\n\\r\\n`);});const handlers={response:[]};conn.on('data',raw=>{const[status,...rest]=String(raw).split('\\r\\n');const s=status.match(/HTTP\\/\\S+\\s+(\\d+)/);const bodyIdx=rest.indexOf('');const headers={};for(const line of rest.slice(0,bodyIdx)){const [k,v]=line.split(':');if(k)headers[k.trim().toLowerCase()]=v?.trim();}const body=rest.slice(bodyIdx+1).join('\\r\\n');const res={statusCode:s?+s[1]:200,headers,body,on(ev,fn){if(ev==='data')queueMicrotask(()=>fn(body));if(ev==='end')queueMicrotask(()=>fn());return res;}};for(const h of handlers.response)h(res);cb?.(res);});const req={on(ev,fn){if(ev==='response')handlers.response.push(fn);return req;},end(){},write(){}};return req;},\n };\n}\n"}