@coasys/ad4m-connect 0.12.1-dev → 0.13.0-postmessage-ws-proxy.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/PostMessageWebSocket.d.ts +26 -0
- package/dist/components/icons/CheckCircleIcon.d.ts +1 -0
- package/dist/components/icons/MapPinIcon.d.ts +1 -0
- package/dist/components/icons/TickIcon.d.ts +1 -0
- package/dist/components/icons/index.d.ts +1 -0
- package/dist/components/shared/Ad4mLogo.d.ts +1 -0
- package/dist/components/shared/AppLogo.d.ts +1 -0
- package/dist/components/shared/Header.d.ts +1 -0
- package/dist/components/shared/Logo.d.ts +1 -0
- package/dist/components/states/ErrorState.d.ts +6 -0
- package/dist/components/views/ConnectionOverview.d.ts +22 -0
- package/dist/components/views/HostBrowser.d.ts +0 -1
- package/dist/components/views/HostDetail.d.ts +2 -1
- package/dist/components/views/Hosting.d.ts +22 -0
- package/dist/components/views/LocalAuthentication.d.ts +2 -1
- package/dist/components/views/LoggedInDashboard.d.ts +20 -2
- package/dist/components/views/MultiUserAuth.d.ts +26 -0
- package/dist/components/views/RemoteAuthentication.d.ts +3 -1
- package/dist/components/views/RemoteConnection.d.ts +19 -0
- package/dist/components/views/RequestCapability.d.ts +16 -0
- package/dist/components/views/ScanQRCode.d.ts +14 -0
- package/dist/components/views/Settings.d.ts +19 -0
- package/dist/components/views/Start.d.ts +19 -0
- package/dist/components/views/old/Hosting.d.ts +22 -0
- package/dist/components/views/old/MultiUserAuth.d.ts +26 -0
- package/dist/components/views/old/RemoteConnection.d.ts +19 -0
- package/dist/components/views/old/RequestCapability.d.ts +16 -0
- package/dist/components/views/old/ScanQRCode.d.ts +14 -0
- package/dist/components/views/old/Settings.d.ts +19 -0
- package/dist/components/views/old/Start.d.ts +19 -0
- package/dist/core.d.ts +10 -6
- package/dist/core.js +11323 -1582
- package/dist/core.js.map +7 -0
- package/dist/index.js +14040 -1931
- package/dist/index.js.map +7 -0
- package/dist/old/components/InvalidToken.d.ts +0 -0
- package/dist/old/components/VerifyCode.d.ts +0 -0
- package/dist/old/core.d.ts +0 -0
- package/dist/old/electron.d.ts +0 -0
- package/dist/old/state/ConnectState.d.ts +0 -0
- package/dist/old/state/index.d.ts +0 -0
- package/dist/old/utils.d.ts +0 -0
- package/dist/old/views/Hosting.d.ts +0 -0
- package/dist/old/views/MultiUserAuth.d.ts +0 -0
- package/dist/old/views/RemoteConnection.d.ts +0 -0
- package/dist/old/views/RequestCapability.d.ts +0 -0
- package/dist/old/views/ScanQRCode.d.ts +0 -0
- package/dist/old/views/Settings.d.ts +0 -0
- package/dist/old/views/Start.d.ts +0 -0
- package/dist/old/web.d.ts +0 -0
- package/dist/services/hostIndex.d.ts +2 -2
- package/dist/state/ConnectState.d.ts +101 -0
- package/dist/state/index.d.ts +2 -0
- package/dist/types.d.ts +13 -0
- package/dist/utils.d.ts +4 -1
- package/dist/utils.js +99 -1
- package/dist/utils.js.map +7 -0
- package/dist/web.d.ts +4 -0
- package/dist/web.js +12736 -1864
- package/dist/web.js.map +7 -0
- package/package.json +9 -7
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/utils.ts", "../src/PostMessageWebSocket.ts", "../../core/lib/index.js", "../../node_modules/.pnpm/auto-bind@5.0.1/node_modules/auto-bind/index.js", "../src/services/hostIndex.ts", "../src/core.ts", "../../node_modules/.pnpm/@lit+reactive-element@1.6.3/node_modules/@lit/reactive-element/src/css-tag.ts", "../../node_modules/.pnpm/@lit+reactive-element@1.6.3/node_modules/@lit/reactive-element/src/reactive-element.ts", "../../node_modules/.pnpm/lit-html@2.8.0/node_modules/lit-html/src/lit-html.ts", "../../node_modules/.pnpm/lit-element@3.3.3/node_modules/lit-element/src/lit-element.ts", "../../node_modules/.pnpm/@lit+reactive-element@1.6.3/node_modules/@lit/reactive-element/src/decorators/custom-element.ts", "../../node_modules/.pnpm/@lit+reactive-element@1.6.3/node_modules/@lit/reactive-element/src/decorators/property.ts", "../../node_modules/.pnpm/@lit+reactive-element@1.6.3/node_modules/@lit/reactive-element/src/decorators/state.ts", "../../node_modules/.pnpm/@lit+reactive-element@1.6.3/node_modules/@lit/reactive-element/src/decorators/query-assigned-elements.ts", "../src/components/icons/Ad4mLogo.ts", "../src/components/icons/LocalIcon.ts", "../src/components/icons/RemoteIcon.ts", "../src/components/icons/DownloadIcon.ts", "../src/components/icons/CheckIcon.ts", "../src/components/icons/CrossIcon.ts", "../src/components/icons/RefreshIcon.ts", "../src/components/icons/ArrowLeftRightIcon.ts", "../src/components/icons/ArrowLeftIcon.ts", "../src/components/icons/GlobeIcon.ts", "../src/components/icons/CreditIcon.ts", "../src/components/icons/WalletIcon.ts", "../src/components/icons/MapPinIcon.ts", "../src/styles/shared-styles.ts", "../src/components/views/ConnectionOptions.ts", "../src/components/views/LocalAuthentication.ts", "../src/components/views/RemoteAuthentication.ts", "../src/components/views/CurrentState.ts", "../src/components/shared/avatar.ts", "../src/components/views/HostBrowser.ts", "../src/components/views/HostDetail.ts", "../src/components/views/LoggedInDashboard.ts", "../src/web.ts", "../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["//@ts-ignore\nimport { version } from \"../../package.json\";\n\nexport function isEmbedded(): boolean {\n return typeof window !== 'undefined' && window.self !== window.top;\n}\n\nfunction localStorageSupported(): boolean {\n try {\n localStorage.setItem(\"test\", \"\");\n localStorage.removeItem(\"test\");\n } catch (e) {\n return false;\n }\n return true;\n}\n\nexport function setLocal(key: string, value: string): void {\n if (localStorageSupported()) localStorage.setItem(`${version}/${key}`, value);\n}\n\nexport function getLocal(key: string): string | null {\n if (localStorageSupported()) return localStorage.getItem(`${version}/${key}`);\n return null;\n}\n\nexport function removeLocal(key: string): void {\n if (localStorageSupported()) localStorage.removeItem(`${version}/${key}`);\n}\n\n/** Convert a WebSocket URL to an HTTP base URL. */\nexport function wsUrlToHttpBase(wsUrl: string): string {\n return wsUrl.replace(/^ws(s?):\\/\\//, (_, s) => `http${s}://`);\n}\n\n/** Check that the AD4M executor is reachable at the given HTTP base URL. */\nexport async function checkConnection(baseUrl: string, timeout = 10000): Promise<void> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout);\n try {\n const res = await fetch(`${baseUrl}/health`, { signal: controller.signal });\n if (!res.ok) throw new Error(`Health check returned ${res.status}`);\n const body = await res.json();\n if (body?.status !== 'ok') throw new Error('Not an AD4M executor');\n } catch (e: any) {\n if (e.name === 'AbortError') throw new Error('Connection timed out');\n throw e;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Extract up to 2 initials from a name (first letter of first two words) */\nexport function getInitials(name: string): string {\n const clean = name.trim();\n if (!clean) return \"\";\n const words = clean.split(/\\s+/);\n if (words.length >= 2) return (words[0][0] + words[1][0]).toUpperCase();\n return clean.slice(0, 2).toUpperCase();\n}\n\n/** Deterministic hue (0-359) from a string \u2014 same input always yields same color */\nexport function getHue(str: string): number {\n let hash = 0;\n for (let i = 0; i < str.length; i++) hash = str.charCodeAt(i) + ((hash << 5) - hash);\n return ((hash % 360) + 360) % 360;\n}\n\n", "/**\n * A WebSocket-compatible class that proxies all communication through\n * window.parent via postMessage instead of opening a real WebSocket.\n *\n * Used in embedded mode when the host/parent application sends AD4M_CONFIG\n * with proxy: true. The host opens a real WebSocket to the AD4M daemon and\n * forwards raw frames bidirectionally via the AD4M_PROXY_WS_* protocol.\n *\n * The constructor URL is intentionally ignored \u2014 the connection target is\n * determined by the host, not the embedded app.\n */\nexport class PostMessageWebSocket {\n static readonly CONNECTING = 0\n static readonly OPEN = 1\n static readonly CLOSING = 2\n static readonly CLOSED = 3\n\n readyState: number = 0 // CONNECTING\n\n onopen: ((e: Event) => void) | null = null\n onmessage: ((e: MessageEvent) => void) | null = null\n onerror: ((e: Event) => void) | null = null\n onclose: ((e: CloseEvent) => void) | null = null\n\n private readonly _messageHandler: (e: MessageEvent) => void\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n constructor(_url: string) {\n this._messageHandler = (e: MessageEvent) => {\n if (e.source !== window.parent) return\n\n const msg = e.data\n if (!msg || typeof msg.type !== 'string') return\n\n if (msg.type === 'AD4M_PROXY_WS_OPEN') {\n this.readyState = 1\n this.onopen?.(new Event('open'))\n return\n }\n if (msg.type === 'AD4M_PROXY_WS_MESSAGE') {\n this.onmessage?.(new MessageEvent('message', { data: msg.data }))\n return\n }\n if (msg.type === 'AD4M_PROXY_WS_ERROR') {\n this.onerror?.(new Event('error'))\n return\n }\n if (msg.type === 'AD4M_PROXY_WS_CLOSED') {\n this.readyState = 3\n this.onclose?.(\n new CloseEvent('close', {\n code: typeof msg.code === 'number' ? msg.code : 1000,\n reason: typeof msg.reason === 'string' ? msg.reason : '',\n wasClean: true,\n })\n )\n window.removeEventListener('message', this._messageHandler)\n }\n }\n\n window.addEventListener('message', this._messageHandler)\n window.parent.postMessage({ type: 'AD4M_PROXY_WS_CONNECT' }, '*')\n }\n\n send(data: string): void {\n window.parent.postMessage({ type: 'AD4M_PROXY_WS_SEND', data }, '*')\n }\n\n close(code?: number, reason?: string): void {\n this.readyState = 2 // CLOSING\n window.parent.postMessage({ type: 'AD4M_PROXY_WS_CLOSE', code, reason }, '*')\n window.removeEventListener('message', this._messageHandler)\n }\n}\n", "/** Error thrown by ApiClient when an RPC call fails. */\nclass RpcError extends Error {\n constructor(status, body) {\n super(`RPC error ${status}: ${body}`);\n this.name = \"RpcError\";\n this.status = status;\n this.body = body;\n }\n}\n/** Default RPC call timeout in milliseconds (30 seconds). */\nconst DEFAULT_TIMEOUT_MS = 30000;\n/** Maximum reconnect delay in ms. */\nconst MAX_RECONNECT_DELAY_MS = 30000;\n/** Initial reconnect delay in ms. */\nconst INITIAL_RECONNECT_DELAY_MS = 500;\n/** Counter for generating unique request IDs. */\nlet _idCounter = 0;\nfunction nextId() {\n return String(++_idCounter);\n}\nclass ApiClient {\n constructor(baseUrl, token, webSocketImpl) {\n // \u2500\u2500 WebSocket RPC core \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n this._ws = null;\n this._wsCallbacks = new Set();\n this._pendingCalls = new Map();\n this._wsReady = null;\n this._wsReadyResolve = null;\n this._wsReconnectTimer = null;\n this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;\n this._wsClosed = false;\n this._wsPingTimer = null;\n this.baseUrl = baseUrl;\n this.token = token;\n this._webSocketImpl = webSocketImpl;\n }\n getBaseUrl() { return this.baseUrl; }\n getToken() { return this.token; }\n setToken(token) {\n this.token = token;\n }\n _getWsUrl() {\n const wsBase = this.baseUrl\n .replace(/^http:\\/\\//, 'ws://')\n .replace(/^https:\\/\\//, 'wss://');\n const tokenParam = this.token ? `token=${encodeURIComponent(this.token)}` : '';\n const path = '/api/v1/ws';\n return tokenParam ? `${wsBase}${path}?${tokenParam}` : `${wsBase}${path}`;\n }\n _ensureWs() {\n if (this._ws && (this._ws.readyState === 1 /* OPEN */ || this._ws.readyState === 0 /* CONNECTING */)) {\n return;\n }\n // Prevent duplicate connections from concurrent callers\n if (this._wsReady)\n return;\n this._wsClosed = false;\n this._wsReady = new Promise((resolve) => {\n this._wsReadyResolve = resolve;\n });\n const url = this._getWsUrl();\n const WsImpl = this._webSocketImpl ?? WebSocket;\n const ws = new WsImpl(url);\n this._ws = ws;\n ws.onopen = () => {\n this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;\n if (this._wsReadyResolve) {\n this._wsReadyResolve();\n this._wsReadyResolve = null;\n }\n this._startPing();\n };\n ws.onmessage = (event) => {\n let parsed;\n try {\n parsed = JSON.parse(event.data);\n }\n catch (e) {\n console.error('Error parsing WebSocket data:', e);\n return;\n }\n // Ignore pong messages\n if (parsed.type === 'pong')\n return;\n // Check if this is a response to a pending RPC call (has an id field)\n const id = parsed.id;\n if (id && this._pendingCalls.has(id)) {\n const pending = this._pendingCalls.get(id);\n this._pendingCalls.delete(id);\n clearTimeout(pending.timer);\n if (parsed.error) {\n const err = parsed.error;\n pending.reject(new RpcError(err.code ?? 500, err.message ?? 'Unknown error'));\n }\n else {\n pending.resolve(parsed.result);\n }\n return;\n }\n // Server-push event (no id, or id not in pending) \u2192 route to subscribers\n for (const cb of this._wsCallbacks)\n cb(parsed);\n };\n ws.onerror = (e) => {\n console.error('WebSocket error:', e);\n };\n ws.onclose = () => {\n this._stopPing();\n this._ws = null;\n // Reset the readiness promise so future calls reconnect\n this._wsReady = null;\n // Reject all pending calls\n const hadPendingCalls = this._pendingCalls.size > 0;\n for (const [id, pending] of this._pendingCalls) {\n clearTimeout(pending.timer);\n pending.reject(new RpcError(503, 'WebSocket connection closed'));\n }\n this._pendingCalls.clear();\n if (!this._wsClosed && (this._wsCallbacks.size > 0 || hadPendingCalls)) {\n this._scheduleReconnect();\n }\n };\n }\n _startPing() {\n this._stopPing();\n this._wsPingTimer = setInterval(() => {\n if (this._ws && this._ws.readyState === 1 /* OPEN */) {\n this._ws.send(JSON.stringify({ type: 'ping' }));\n }\n }, 30000);\n }\n _stopPing() {\n if (this._wsPingTimer) {\n clearInterval(this._wsPingTimer);\n this._wsPingTimer = null;\n }\n }\n _scheduleReconnect() {\n if (this._wsReconnectTimer)\n return;\n const delay = this._wsReconnectDelay;\n this._wsReconnectDelay = Math.min(this._wsReconnectDelay * 2, MAX_RECONNECT_DELAY_MS);\n this._wsReconnectTimer = setTimeout(() => {\n this._wsReconnectTimer = null;\n if (!this._wsClosed) {\n this._ensureWs();\n }\n }, delay);\n }\n /** Ensure WS is connected and ready. Lazy \u2014 connects on first use. */\n async _ready() {\n this._ensureWs();\n if (this._wsReady)\n await this._wsReady;\n }\n // \u2500\u2500 RPC call method \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /**\n * Send an RPC call over the WebSocket connection.\n * @param type - The operation type (e.g. 'agent.get', 'perspective.all')\n * @param params - Optional parameters to include in the message\n * @returns Promise that resolves with the result from the server\n */\n async call(type, params) {\n await this._ready();\n const id = nextId();\n // Put params under a \"params\" key to avoid collision with\n // protocol fields \"id\" and \"type\" (e.g. params might contain\n // { id: modelId } or { type: \"db\" }).\n const message = { id, type, params: params || {} };\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingCalls.delete(id);\n reject(new RpcError(408, `RPC call '${type}' timed out after ${DEFAULT_TIMEOUT_MS}ms`));\n }, DEFAULT_TIMEOUT_MS);\n this._pendingCalls.set(id, {\n resolve: resolve,\n reject,\n timer,\n });\n if (this._ws && this._ws.readyState === 1 /* OPEN */) {\n this._ws.send(JSON.stringify(message));\n }\n else {\n this._pendingCalls.delete(id);\n clearTimeout(timer);\n reject(new RpcError(503, 'WebSocket not connected'));\n }\n });\n }\n // \u2500\u2500 Event subscriptions (same interface as before) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n subscribe(callback) {\n this._wsCallbacks.add(callback);\n this._ensureWs();\n return () => {\n this._wsCallbacks.delete(callback);\n if (this._wsCallbacks.size === 0 && this._pendingCalls.size === 0) {\n this._closeWs();\n }\n };\n }\n /** Wait until the WebSocket connection is established. */\n async waitForSubscription() {\n await this._ready();\n }\n // \u2500\u2500 Explicit connection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** Explicitly connect the WebSocket (optional \u2014 connection is lazy). */\n connect() {\n this._ensureWs();\n }\n _closeWs() {\n this._stopPing();\n if (this._wsReconnectTimer) {\n clearTimeout(this._wsReconnectTimer);\n this._wsReconnectTimer = null;\n }\n if (this._ws) {\n this._wsClosed = true;\n this._ws.close();\n this._ws = null;\n this._wsReady = null;\n }\n }\n /** Close all open WebSocket connections and reject pending calls. */\n closeAll() {\n // Reject pending calls\n for (const [id, pending] of this._pendingCalls) {\n clearTimeout(pending.timer);\n pending.reject(new RpcError(503, 'Client closed'));\n }\n this._pendingCalls.clear();\n this._closeWs();\n this._wsCallbacks.clear();\n }\n}\n\nclass ExpressionProof {\n constructor(sig, k) {\n this.key = k;\n this.signature = sig;\n }\n}\nclass ExpressionProofInput {\n}\n//Note having any as return type here fixes compilation errors but we lose the ExpressionClass type in resulting .d.ts files\nfunction ExpressionGeneric(DataTypeClass) {\n class ExpressionClass {\n constructor(author, timestamp, data, proof) {\n this.author = author;\n this.timestamp = timestamp;\n this.data = data;\n this.proof = proof;\n }\n }\n return ExpressionClass;\n}\nfunction ExpressionGenericInput(DataTypeClass) {\n class ExpressionClass {\n }\n return ExpressionClass;\n}\nclass Expression extends ExpressionGeneric() {\n}\nclass ExpressionRendered extends ExpressionGeneric() {\n}\nfunction isExpression(e) {\n return e && e.author && e.timestamp && e.data;\n}\n\n/** A Perspective represents subjective meaning, encoded through\n* associations between expressions, a.k.a. Links, that is a graph\n* over the objective Expressions of any subset of Languages.\n*\n* This type represents the clean onotological concept of a Perspective.\n* An instance of this class can be regarded as an immutable snapshot of\n* a mutable perspective.\n*\n* The types PerspectiveProxy and PerspectiveHandle are used when dealing\n* with an instantiated mutable perspective as is done through most of\n* the AD4M API.\n*/\nclass Perspective {\n constructor(links) {\n if (links) {\n this.links = links;\n }\n else {\n this.links = [];\n }\n }\n /** Convenience function for filtering links just like with PerspectiveProxy */\n get(query) {\n if (!query || !query.source && !query.predicate && !query.target) {\n return this.links;\n }\n if (query.source) {\n let result = JSON.parse(JSON.stringify(this.links));\n // @ts-ignore\n if (query.target)\n result = result.filter(l => l.data.target === query.target);\n // @ts-ignore\n if (query.predicate)\n result = result.filter(l => l.data.predicate === query.predicate);\n //@ts-ignore\n if (query.fromDate)\n result = result.filter(l => new Date(l.timestamp) >= query.fromDate);\n //@ts-ignore\n if (query.untilDate)\n result = result.filter(l => new Date(l.timestamp) <= query.untilDate);\n // console.debug(\"result\", result)\n if (query.limit)\n result = result.slice(0, query.limit);\n return result;\n }\n // console.debug(\"getLinks 3\")\n if (query.target) {\n //@ts-ignore\n let result = JSON.parse(JSON.stringify(this.links));\n // @ts-ignore\n if (query.predicate)\n result = result.filter(l => l.data.predicate === query.predicate);\n //@ts-ignore\n if (query.fromDate)\n result = result.filter(l => new Date(l.timestamp) >= query.fromDate);\n //@ts-ignore\n if (query.untilDate)\n result = result.filter(l => new Date(l.timestamp) <= query.untilDate);\n if (query.limit)\n result = result.slice(0, query.limit);\n return result;\n }\n // console.debug(\"getLinks 4\")\n //@ts-ignore\n let result = JSON.parse(JSON.stringify(this.links));\n result = result.filter(link => link.data.predicate === query.predicate);\n if (query.limit)\n result = result.slice(0, query.limit);\n return result;\n }\n /** Convenience function to get the target of the first link that matches the given query\n * This makes sense when the query is expected to return only one link\n * and the target of that link is what you are looking for.\n */\n getSingleTarget(query) {\n delete query.target;\n const foundLinks = this.get(query);\n if (foundLinks.length)\n return foundLinks[0].data.target;\n else\n return null;\n }\n}\nclass PerspectiveInput {\n}\nclass PerspectiveUnsignedInput {\n constructor(links) {\n if (links)\n this.links = links;\n else\n this.links = [];\n }\n static fromLink(link) {\n let obj = new PerspectiveUnsignedInput();\n obj.links.push(link);\n return obj;\n }\n}\nclass PerspectiveExpression extends ExpressionGeneric() {\n}\n\n/** AD4M's representation of an Agent\n *\n * AD4M Agents are build around DIDs, which are used to identify and authenticate the Agent.\n * Conceptually, an Agent is regarded as something that can speak and that can listen.\n *\n * Agents speak by creating Expressions in AD4M Languages which are signed by the Agent's DID key,\n * And they also speak (broadcast) by putting semantic statements into their public \"Agent Perspective\".\n * They listen (can receive messages) through their \"direct message Language\".\n *\n * These three aspects are represented by the three fields of this class.\n *\n * This class is used as format for the Expressions in the Agent language.\n * Since AD4M treats DID URIs as addresses for the Agent Language,\n * DIDs are resolved to Expressions that are objects of this class.\n * Thus, this is how agents see (other) agents.\n */\nclass Agent {\n constructor(did, perspective) {\n this.did = did;\n if (perspective) {\n this.perspective = perspective;\n }\n else {\n this.perspective = new Perspective();\n }\n }\n}\nclass AgentExpression extends ExpressionGeneric() {\n}\nclass EntanglementProof {\n constructor(did, didSigningKeyId, deviceKeyType, deviceKey, deviceKeySignedByDid, didSignedByDeviceKey) {\n this.did = did;\n this.didSigningKeyId = didSigningKeyId;\n this.deviceKeyType = deviceKeyType;\n this.deviceKey = deviceKey;\n this.deviceKeySignedByDid = deviceKeySignedByDid;\n this.didSignedByDeviceKey = didSignedByDeviceKey;\n }\n}\nclass EntanglementProofInput {\n constructor(did, didSigningKeyId, deviceKeyType, deviceKey, deviceKeySignedByDid, didSignedByDeviceKey) {\n this.did = did;\n this.didSigningKeyId = didSigningKeyId;\n this.deviceKeyType = deviceKeyType;\n this.deviceKey = deviceKey;\n this.deviceKeySignedByDid = deviceKeySignedByDid;\n this.didSignedByDeviceKey = didSignedByDeviceKey;\n }\n}\nclass AgentSignature {\n constructor(signature, publicKey) {\n this.signature = signature;\n this.publicKey = publicKey;\n }\n}\nclass Resource {\n constructor(domain, pointers) {\n this.domain = domain;\n this.pointers = pointers;\n }\n}\nclass Capability {\n constructor(withF, can) {\n this.with = withF;\n this.can = can;\n }\n}\nclass AuthInfo {\n constructor(appName, appDesc, appUrl, capabilities, appIconPath) {\n this.appName = appName;\n this.appDesc = appDesc;\n this.appIconPath = appIconPath;\n this.appUrl = appUrl;\n this.capabilities = capabilities;\n }\n}\nclass Apps {\n constructor(requestId, auth, token, revoked) {\n this.requestId = requestId;\n this.auth = auth;\n this.token = token;\n this.revoked = revoked;\n }\n}\nclass ResourceInput {\n constructor(domain, pointers) {\n this.domain = domain;\n this.pointers = pointers;\n }\n}\nclass CapabilityInput {\n constructor(withF, can) {\n this.with = withF;\n this.can = can;\n }\n}\nclass AuthInfoInput {\n constructor(appName, appDesc, appDomain, appUrl, appIconPath, capabilities) {\n this.appName = appName;\n this.appDesc = appDesc;\n this.appUrl = appUrl;\n this.appDomain = appDomain;\n this.capabilities = capabilities;\n this.appIconPath = appIconPath;\n }\n}\nclass UserCreationResult {\n constructor(did, success, error) {\n this.did = did;\n this.success = success;\n this.error = error;\n }\n}\n\nclass SentMessage {\n}\nclass RuntimeInfo {\n}\nclass ExceptionInfo {\n}\nclass NotificationInput {\n}\nclass Notification {\n}\nclass TriggeredNotification {\n}\nclass ImportStats {\n}\nclass ImportResult {\n}\nclass UserStatistics {\n}\nclass VerificationRequestResult {\n}\nclass HostingUserInfo {\n constructor(email, remainingCredits, hotWalletAddress, freeAccess = false) {\n this.email = email;\n this.remainingCredits = remainingCredits;\n this.hotWalletAddress = hotWalletAddress;\n this.freeAccess = freeAccess;\n }\n}\nclass PaymentRequestResult {\n constructor(success, message) {\n this.success = success;\n this.message = message;\n }\n}\nclass ComputeLogEntry {\n constructor(id, userEmail, timestamp, operation, cost, creditsAfter, summary) {\n this.id = id;\n this.userEmail = userEmail;\n this.timestamp = timestamp;\n this.operation = operation;\n this.cost = cost;\n this.creditsAfter = creditsAfter;\n this.summary = summary;\n }\n}\n\nclass AgentStatus {\n constructor(obj) {\n if (obj) {\n //@ts-ignore\n this.isInitialized = obj.isInitialized;\n if (!this.isInitialized) {\n this.isInitialized = false;\n }\n //@ts-ignore\n this.isUnlocked = obj.isUnlocked;\n if (!this.isUnlocked) {\n this.isUnlocked = false;\n }\n //@ts-ignore\n this.did = obj.did;\n //@ts-ignore\n this.didDocument = obj.didDocument;\n //@ts-ignore\n this.error = obj.error;\n }\n else {\n this.isInitialized = false;\n this.isUnlocked = false;\n }\n }\n}\n\nvar __classPrivateFieldSet$c = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$c = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _NeighbourhoodProxy_client, _NeighbourhoodProxy_pID;\nclass NeighbourhoodProxy {\n constructor(client, pID) {\n _NeighbourhoodProxy_client.set(this, void 0);\n _NeighbourhoodProxy_pID.set(this, void 0);\n __classPrivateFieldSet$c(this, _NeighbourhoodProxy_client, client, \"f\");\n __classPrivateFieldSet$c(this, _NeighbourhoodProxy_pID, pID, \"f\");\n }\n async otherAgents() {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").otherAgents(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"));\n }\n async hasTelepresenceAdapter() {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").hasTelepresenceAdapter(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"));\n }\n async onlineAgents() {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").onlineAgents(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"));\n }\n async setOnlineStatus(status) {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").setOnlineStatus(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"), status);\n }\n async setOnlineStatusU(status) {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").setOnlineStatusU(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"), status);\n }\n async sendSignal(remoteAgentDid, payload) {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").sendSignal(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"), remoteAgentDid, payload);\n }\n async sendSignalU(remoteAgentDid, payload) {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").sendSignalU(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"), remoteAgentDid, payload);\n }\n async sendBroadcast(payload, loopback = false) {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").sendBroadcast(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"), payload, loopback);\n }\n async sendBroadcastU(payload, loopback = false) {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").sendBroadcastU(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"), payload, loopback);\n }\n async addSignalHandler(handler) {\n await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").addSignalHandler(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"), handler);\n }\n removeSignalHandler(handler) {\n __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").removeSignalHandler(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"), handler);\n }\n}\n_NeighbourhoodProxy_client = new WeakMap(), _NeighbourhoodProxy_pID = new WeakMap();\n\nclass Link {\n constructor(obj) {\n this.source = obj.source ? obj.source : '';\n this.target = obj.target ? obj.target : '';\n this.predicate = obj.predicate ? obj.predicate : '';\n }\n}\nclass LinkMutations {\n}\nclass LinkExpressionMutations {\n constructor(additions, removals) {\n this.additions = additions;\n this.removals = removals;\n }\n}\nclass LinkInput {\n}\nclass LinkExpression extends ExpressionGeneric() {\n hash() {\n const mash = JSON.stringify(this.data, Object.keys(this.data).sort()) +\n JSON.stringify(this.author) + this.timestamp;\n let hash = 0, i, chr;\n for (i = 0; i < mash.length; i++) {\n chr = mash.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0; // Convert to 32bit integer\n }\n return hash;\n }\n}\nclass LinkExpressionInput extends ExpressionGenericInput() {\n}\nfunction linkEqual(l1, l2) {\n return l1.author == l2.author &&\n l1.timestamp == l2.timestamp &&\n l1.data.source == l2.data.source &&\n l1.data.predicate == l2.data.predicate &&\n l1.data.target == l2.data.target;\n}\nfunction isLink(l) {\n return l && l.source && l.target;\n}\nclass LinkExpressionUpdated {\n constructor(oldLink, newLink) {\n this.oldLink = oldLink;\n this.newLink = newLink;\n }\n}\n\nclass LinkQuery {\n constructor(obj) {\n if (obj) {\n // @ts-ignore\n this.source = obj.source;\n // @ts-ignore\n this.predicate = obj.predicate;\n // @ts-ignore\n this.target = obj.target;\n // @ts-ignore\n if (obj.fromDate) {\n // @ts-ignore\n this.fromDate = obj.fromDate;\n }\n // @ts-ignore\n if (obj.untilDate) {\n // @ts-ignore\n this.untilDate = obj.untilDate;\n }\n // @ts-ignore\n if (obj.limit) {\n // @ts-ignore\n this.limit = obj.limit;\n }\n }\n }\n isMatch(l) {\n if (this.source)\n if (this.source !== l.source)\n return false;\n if (this.predicate)\n if (this.predicate !== l.predicate)\n return false;\n if (this.target)\n if (this.target !== l.target)\n return false;\n return true;\n }\n}\n\nvar __classPrivateFieldSet$b = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$b = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _Literal_literal, _Literal_url;\nfunction encodeRFC3986URIComponent(str) {\n return encodeURIComponent(str)\n .replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);\n}\nclass Literal {\n constructor() {\n _Literal_literal.set(this, void 0);\n _Literal_url.set(this, void 0);\n }\n static fromUrl(url) {\n if (!url || !url.startsWith(\"literal:\"))\n throw new Error(\"Can't create Literal from non-literal URL\");\n if (url.startsWith(\"literal://\"))\n throw new Error(\"literal:// format is no longer supported. Use literal: instead.\");\n const l = new Literal();\n __classPrivateFieldSet$b(l, _Literal_url, url, \"f\");\n return l;\n }\n static from(literal) {\n const l = new Literal();\n __classPrivateFieldSet$b(l, _Literal_literal, literal, \"f\");\n return l;\n }\n toUrl() {\n if (__classPrivateFieldGet$b(this, _Literal_url, \"f\") && !__classPrivateFieldGet$b(this, _Literal_literal, \"f\"))\n return __classPrivateFieldGet$b(this, _Literal_url, \"f\");\n if (!__classPrivateFieldGet$b(this, _Literal_url, \"f\") && (__classPrivateFieldGet$b(this, _Literal_literal, \"f\") === undefined || __classPrivateFieldGet$b(this, _Literal_literal, \"f\") === \"\" || __classPrivateFieldGet$b(this, _Literal_literal, \"f\") === null))\n throw new Error(\"Can't turn empty Literal into URL\");\n let encoded;\n switch (typeof __classPrivateFieldGet$b(this, _Literal_literal, \"f\")) {\n case 'string':\n encoded = `string:${encodeRFC3986URIComponent(__classPrivateFieldGet$b(this, _Literal_literal, \"f\"))}`;\n break;\n case 'number':\n encoded = `number:${encodeRFC3986URIComponent(__classPrivateFieldGet$b(this, _Literal_literal, \"f\"))}`;\n break;\n case 'boolean':\n encoded = `boolean:${encodeRFC3986URIComponent(__classPrivateFieldGet$b(this, _Literal_literal, \"f\"))}`;\n break;\n case 'object':\n encoded = `json:${encodeRFC3986URIComponent(JSON.stringify(__classPrivateFieldGet$b(this, _Literal_literal, \"f\")))}`;\n break;\n }\n return `literal:${encoded}`;\n }\n get() {\n if (__classPrivateFieldGet$b(this, _Literal_literal, \"f\"))\n return __classPrivateFieldGet$b(this, _Literal_literal, \"f\");\n if (!__classPrivateFieldGet$b(this, _Literal_url, \"f\"))\n throw new Error(\"Can't render empty Literal\");\n if (!__classPrivateFieldGet$b(this, _Literal_url, \"f\").startsWith(\"literal:\"))\n throw new Error(\"Can't render Literal from non-literal URL\");\n const body = __classPrivateFieldGet$b(this, _Literal_url, \"f\").substring(8);\n if (body.startsWith(\"string:\")) {\n return decodeURIComponent(body.substring(7));\n }\n if (body.startsWith(\"number:\")) {\n const numberString = body.substring(7);\n return parseFloat(numberString);\n }\n if (body.startsWith(\"json:\")) {\n const json = body.substring(5);\n return JSON.parse(decodeURIComponent(json));\n }\n throw new Error(`Can't parse unknown literal: ${body}`);\n }\n}\n_Literal_literal = new WeakMap(), _Literal_url = new WeakMap();\n\nfunction capitalize(str) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n// e.g. \"name\" -> \"setName\"\nfunction propertyNameToSetterName(property) {\n return `set${capitalize(property)}`;\n}\n/**\n * Generate a random identifier string of the given length (lowercase alpha).\n */\nfunction makeRandomId(length) {\n let result = '';\n const characters = 'abcdefghijklmnopqrstuvwxyz';\n const charactersLength = characters.length;\n for (let i = 0; i < length; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n}\nfunction stringifyObjectLiteral(obj) {\n if (Array.isArray(obj)) {\n //@ts-ignore\n return `[${obj.map(stringifyObjectLiteral).join(\", \")}]`;\n }\n const keys = Object.keys(obj);\n const stringifiedPairs = [];\n for (const key of keys) {\n const valueString = JSON.stringify(obj[key]);\n const keyValuePairString = `${key}: ${valueString}`;\n stringifiedPairs.push(keyValuePairString);\n }\n return `{${stringifiedPairs.join(', ')}}`;\n}\n\n/**\n * SDNA (Social DNA) Prolog code generation.\n *\n * Builds subject-class Prolog facts from a model's property and relation\n * metadata. The heavy lifting used to live inside the `@Model` decorator\n * closure \u2014 it is extracted here so decorators.ts stays focused on\n * decorator registration logic.\n */\n/**\n * Build SDNA (Social DNA) Prolog code for a model class.\n *\n * @param subjectName - The model's registered name (from `@Model({ name })`)\n * @param obj - `target.prototype` \u2014 used to inspect prototype methods\n * (e.g. setter stubs, `subjectConstructor`, `isSubjectInstance`)\n * @param properties - Merged property metadata (from `getPropertiesMetadata`)\n * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)\n */\nfunction buildSDNA(subjectName, obj, properties, allRelationsMeta) {\n let sdna = \"\";\n let uuid = makeRandomId(8);\n sdna += `subject_class(\"${subjectName}\", ${uuid}).\\n`;\n let classRemoverActions = [];\n let constructorActions = [];\n if (obj.subjectConstructor && obj.subjectConstructor.length) {\n constructorActions = constructorActions.concat(obj.subjectConstructor);\n }\n let instanceConditions = [];\n if (obj.isSubjectInstance && obj.isSubjectInstance.length) {\n instanceConditions = instanceConditions.concat(obj.isSubjectInstance);\n }\n let propertiesCode = [];\n for (let property in properties) {\n let propertyCode = `property(${uuid}, \"${property}\").\\n`;\n let { through, initial, required, resolveLanguage, writable, flag, prologGetter, prologSetter, local } = properties[property];\n if (resolveLanguage) {\n propertyCode += `property_resolve(${uuid}, \"${property}\").\\n`;\n propertyCode += `property_resolve_language(${uuid}, \"${property}\", \"${resolveLanguage}\").\\n`;\n }\n if (prologGetter) {\n propertyCode += `property_getter(${uuid}, Base, \"${property}\", Value) :- ${prologGetter}.\\n`;\n }\n else if (through) {\n propertyCode += `property_getter(${uuid}, Base, \"${property}\", Value) :- triple(Base, \"${through}\", Value).\\n`;\n if (required) {\n if (flag) {\n instanceConditions.push(`triple(Base, \"${through}\", \"${initial}\")`);\n }\n else {\n instanceConditions.push(`triple(Base, \"${through}\", _)`);\n }\n }\n }\n if (prologSetter) {\n propertyCode += `property_setter(${uuid}, \"${property}\", Actions) :- ${prologSetter}.\\n`;\n }\n else if (writable && through) {\n let setter = obj[propertyNameToSetterName(property)];\n if (typeof setter === \"function\") {\n let action = [{\n action: \"setSingleTarget\",\n source: \"this\",\n predicate: through,\n target: \"value\",\n ...(local && { local: true })\n }];\n propertyCode += `property_setter(${uuid}, \"${property}\", '${stringifyObjectLiteral(action)}').\\n`;\n }\n }\n propertiesCode.push(propertyCode);\n // Auto-derive effectiveInitial for required, writable, non-flag properties\n // so constructor/destructor always handle the property link.\n // Optional properties (required: false) are excluded \u2014 they should\n // remain unset (undefined) until explicitly assigned.\n const effectiveInitial = initial\n ?? (required && writable && !flag && through ? \"literal:string:\" : undefined);\n if (effectiveInitial) {\n constructorActions.push({\n action: \"addLink\",\n source: \"this\",\n predicate: through,\n target: effectiveInitial,\n });\n classRemoverActions.push({\n action: \"removeLink\",\n source: \"this\",\n predicate: through,\n target: \"*\",\n });\n }\n }\n let relationsCode = [];\n const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));\n for (let relation in relations) {\n let relationCode = `collection(${uuid}, \"${relation}\").\\n`;\n let { predicate: through, local } = relations[relation];\n if (through) {\n relationCode += `collection_getter(${uuid}, Base, \"${relation}\", List) :- findall(C, triple(Base, \"${through}\", C), List).\\n`;\n let relationAdderAction = [{\n action: \"addLink\",\n source: \"this\",\n predicate: through,\n target: \"value\",\n ...(local && { local: true })\n }];\n let relationRemoverAction = [{\n action: \"removeLink\",\n source: \"this\",\n predicate: through,\n target: \"value\",\n }];\n let relationSetterAction = [{\n action: \"collectionSetter\",\n source: \"this\",\n predicate: through,\n target: \"value\",\n ...(local && { local: true })\n }];\n relationCode += `collection_adder(${uuid}, \"${relation}\", '${stringifyObjectLiteral(relationAdderAction)}').\\n`;\n relationCode += `collection_remover(${uuid}, \"${relation}\", '${stringifyObjectLiteral(relationRemoverAction)}').\\n`;\n relationCode += `collection_setter(${uuid}, \"${relation}\", '${stringifyObjectLiteral(relationSetterAction)}').\\n`;\n }\n relationsCode.push(relationCode);\n }\n let subjectContructorJSONString = stringifyObjectLiteral(constructorActions);\n sdna += `constructor(${uuid}, '${subjectContructorJSONString}').\\n`;\n if (instanceConditions.length > 0) {\n let instanceConditionProlog = instanceConditions.join(\", \");\n sdna += `instance(${uuid}, Base) :- ${instanceConditionProlog}.\\n`;\n sdna += \"\\n\";\n }\n sdna += `destructor(${uuid}, '${stringifyObjectLiteral(classRemoverActions)}').\\n`;\n sdna += \"\\n\";\n sdna += propertiesCode.join(\"\\n\");\n sdna += \"\\n\";\n sdna += relationsCode.join(\"\\n\");\n return {\n sdna,\n name: subjectName\n };\n}\n\n/**\n * Extract namespace from a URI\n * Examples:\n * - \"recipe://name\" -> \"recipe://\"\n * - \"https://example.com/vocab#term\" -> \"https://example.com/vocab#\"\n * - \"https://example.com/vocab/term\" -> \"https://example.com/vocab/\"\n * - \"recipe:Recipe\" -> \"recipe:\"\n */\nfunction extractNamespace(uri) {\n // Handle hash fragments first (highest priority)\n const hashIndex = uri.lastIndexOf('#');\n if (hashIndex !== -1) {\n return uri.substring(0, hashIndex + 1);\n }\n // Handle protocol-style URIs with paths\n const protocolMatch = uri.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\\/\\/)(.*)$/);\n if (protocolMatch) {\n const afterScheme = protocolMatch[2];\n const lastSlash = afterScheme.lastIndexOf('/');\n if (lastSlash !== -1) {\n // Has path segments - namespace includes up to last slash\n return protocolMatch[1] + afterScheme.substring(0, lastSlash + 1);\n }\n // Simple protocol URI without path (e.g., \"recipe://name\")\n return protocolMatch[1];\n }\n // Handle colon-separated (namespace:localName)\n const colonMatch = uri.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:)/);\n if (colonMatch) {\n return colonMatch[1];\n }\n // Fallback: no clear namespace\n return '';\n}\n/**\n * Escape special characters for Turtle string literals\n * Handles backslashes, quotes, newlines, and other control characters\n */\nfunction escapeTurtleString(value) {\n return value\n .replace(/\\\\/g, '\\\\\\\\') // Backslash must be first\n .replace(/\"/g, '\\\\\"') // Double quotes\n .replace(/\\n/g, '\\\\n') // Newlines\n .replace(/\\r/g, '\\\\r') // Carriage returns\n .replace(/\\t/g, '\\\\t') // Tabs\n .replace(/\\b/g, '\\\\b') // Backspace\n .replace(/\\f/g, '\\\\f'); // Form feed\n}\n/**\n * Extract local name from a URI\n * Examples:\n * - \"recipe://name\" -> \"name\"\n * - \"https://example.com/vocab#term\" -> \"term\"\n * - \"https://example.com/vocab/term\" -> \"term\"\n * - \"recipe:Recipe\" -> \"Recipe\"\n */\nfunction extractLocalName(uri) {\n // Handle hash fragments\n const hashIndex = uri.lastIndexOf('#');\n if (hashIndex !== -1) {\n return uri.substring(hashIndex + 1);\n }\n // Handle slash-based namespaces\n const lastSlash = uri.lastIndexOf('/');\n if (lastSlash !== -1 && lastSlash < uri.length - 1) {\n return uri.substring(lastSlash + 1);\n }\n // Handle colon-separated\n const colonMatch = uri.match(/^[a-zA-Z][a-zA-Z0-9+.-]*:(.+)$/);\n if (colonMatch) {\n return colonMatch[1];\n }\n // Fallback: entire URI\n return uri;\n}\n/**\n * SHACL Node Shape\n * Defines constraints for instances of a class\n */\nclass SHACLShape {\n /**\n * Create a new SHACL Shape\n * @param targetClassOrShapeUri - If one argument: the target class (shape URI auto-derived as {class}Shape)\n * If two arguments: first is shape URI, second is target class\n * @param targetClass - Optional target class when first arg is shape URI\n */\n constructor(targetClassOrShapeUri, targetClass) {\n if (targetClass !== undefined) {\n // Two arguments: explicit shape URI and target class\n this.nodeShapeUri = targetClassOrShapeUri;\n this.targetClass = targetClass;\n }\n else {\n // One argument: derive shape URI from target class\n this.targetClass = targetClassOrShapeUri;\n // Derive shape URI by appending \"Shape\" to the local name\n const namespace = extractNamespace(targetClassOrShapeUri);\n const localName = extractLocalName(targetClassOrShapeUri);\n this.nodeShapeUri = `${namespace}${localName}Shape`;\n }\n this.properties = [];\n this.parentShapes = [];\n }\n /**\n * Add a parent shape reference (sh:node) for model inheritance.\n * When a @Model class extends another @Model, the child shape\n * references the parent shape so SHACL validators can walk the\n * class hierarchy.\n */\n addParentShape(parentShapeUri) {\n if (!this.parentShapes.includes(parentShapeUri)) {\n this.parentShapes.push(parentShapeUri);\n }\n }\n /**\n * Add a property constraint to this shape\n */\n addProperty(prop) {\n this.properties.push(prop);\n }\n /**\n * Set constructor actions for this shape\n */\n setConstructorActions(actions) {\n this.constructor_actions = actions;\n }\n /**\n * Set destructor actions for this shape\n */\n setDestructorActions(actions) {\n this.destructor_actions = actions;\n }\n /**\n * Serialize shape to Turtle (RDF) format\n */\n toTurtle() {\n let turtle = `@prefix sh: <http://www.w3.org/ns/shacl#> .\\n`;\n turtle += `@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\\n`;\n turtle += `@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\\n`;\n turtle += `@prefix ad4m: <ad4m://> .\\n\\n`;\n turtle += `<${this.nodeShapeUri}>\\n`;\n turtle += ` a sh:NodeShape ;\\n`;\n if (this.targetClass) {\n turtle += ` sh:targetClass <${this.targetClass}> ;\\n`;\n }\n // Emit sh:node references for parent shapes (model inheritance)\n for (const parentUri of this.parentShapes) {\n turtle += ` sh:node <${parentUri}> ;\\n`;\n }\n // Add property shapes\n for (let i = 0; i < this.properties.length; i++) {\n const prop = this.properties[i];\n const isLast = i === this.properties.length - 1;\n turtle += ` sh:property [\\n`;\n turtle += ` sh:path <${prop.path}> ;\\n`;\n if (prop.datatype) {\n turtle += ` sh:datatype <${prop.datatype}> ;\\n`;\n }\n if (prop.nodeKind) {\n turtle += ` sh:nodeKind sh:${prop.nodeKind} ;\\n`;\n }\n if (prop.minCount !== undefined) {\n turtle += ` sh:minCount ${prop.minCount} ;\\n`;\n }\n if (prop.maxCount !== undefined) {\n turtle += ` sh:maxCount ${prop.maxCount} ;\\n`;\n }\n if (prop.pattern) {\n turtle += ` sh:pattern \"${escapeTurtleString(prop.pattern)}\" ;\\n`;\n }\n if (prop.minInclusive !== undefined) {\n turtle += ` sh:minInclusive ${prop.minInclusive} ;\\n`;\n }\n if (prop.maxInclusive !== undefined) {\n turtle += ` sh:maxInclusive ${prop.maxInclusive} ;\\n`;\n }\n if (prop.hasValue) {\n turtle += ` sh:hasValue \"${escapeTurtleString(prop.hasValue)}\" ;\\n`;\n }\n // AD4M-specific metadata\n if (prop.local !== undefined) {\n turtle += ` ad4m:local ${prop.local} ;\\n`;\n }\n if (prop.writable !== undefined) {\n turtle += ` ad4m:writable ${prop.writable} ;\\n`;\n }\n // Remove trailing semicolon and close bracket\n turtle = turtle.slice(0, -2) + '\\n';\n turtle += isLast ? ` ] .\\n` : ` ] ;\\n`;\n }\n return turtle;\n }\n /**\n * Serialize shape to AD4M Links (RDF triples)\n * Stores the shape as a graph of links in a Perspective\n */\n toLinks() {\n const links = [];\n // Shape type declaration\n links.push({\n source: this.nodeShapeUri,\n predicate: \"rdf://type\",\n target: \"sh://NodeShape\"\n });\n // Target class\n if (this.targetClass) {\n links.push({\n source: this.nodeShapeUri,\n predicate: \"sh://targetClass\",\n target: this.targetClass\n });\n }\n // Constructor actions \u2014 always emit, even for an empty array.\n // An empty `[]` tells the executor the shape is valid but has no\n // required initial links (all-optional model with no @Flag).\n if (this.constructor_actions) {\n links.push({\n source: this.nodeShapeUri,\n predicate: \"ad4m://constructor\",\n target: `literal:string:${JSON.stringify(this.constructor_actions)}`\n });\n }\n // Destructor actions \u2014 same rationale as constructor.\n if (this.destructor_actions) {\n links.push({\n source: this.nodeShapeUri,\n predicate: \"ad4m://destructor\",\n target: `literal:string:${JSON.stringify(this.destructor_actions)}`\n });\n }\n // Property shapes (each gets a named URI: {namespace}/{ClassName}.{propertyName})\n for (let i = 0; i < this.properties.length; i++) {\n const prop = this.properties[i];\n // Generate named property shape URI\n let propShapeId;\n if (prop.name && this.targetClass) {\n // Extract namespace from targetClass\n const namespace = extractNamespace(this.targetClass);\n const className = extractLocalName(this.targetClass);\n // Use format: {namespace}{ClassName}.{propertyName}\n propShapeId = `${namespace}${className}.${prop.name}`;\n }\n else {\n // Fallback to blank node if name is missing\n propShapeId = `_:propShape${i}`;\n }\n // Link shape to property shape\n links.push({\n source: this.nodeShapeUri,\n predicate: \"sh://property\",\n target: propShapeId\n });\n // Property path\n links.push({\n source: propShapeId,\n predicate: \"sh://path\",\n target: prop.path\n });\n // Constraints\n if (prop.datatype) {\n links.push({\n source: propShapeId,\n predicate: \"sh://datatype\",\n target: prop.datatype\n });\n }\n if (prop.nodeKind) {\n links.push({\n source: propShapeId,\n predicate: \"sh://nodeKind\",\n target: `sh://${prop.nodeKind}`\n });\n }\n if (prop.minCount !== undefined) {\n links.push({\n source: propShapeId,\n predicate: \"sh://minCount\",\n target: `literal:${prop.minCount}^^xsd:integer`\n });\n }\n if (prop.maxCount !== undefined) {\n links.push({\n source: propShapeId,\n predicate: \"sh://maxCount\",\n target: `literal:${prop.maxCount}^^xsd:integer`\n });\n }\n if (prop.pattern) {\n links.push({\n source: propShapeId,\n predicate: \"sh://pattern\",\n target: `literal:${prop.pattern}`\n });\n }\n if (prop.minInclusive !== undefined) {\n links.push({\n source: propShapeId,\n predicate: \"sh://minInclusive\",\n target: `literal:${prop.minInclusive}`\n });\n }\n if (prop.maxInclusive !== undefined) {\n links.push({\n source: propShapeId,\n predicate: \"sh://maxInclusive\",\n target: `literal:${prop.maxInclusive}`\n });\n }\n if (prop.hasValue) {\n links.push({\n source: propShapeId,\n predicate: \"sh://hasValue\",\n target: `literal:${prop.hasValue}`\n });\n }\n // AD4M-specific metadata\n if (prop.local !== undefined) {\n links.push({\n source: propShapeId,\n predicate: \"ad4m://local\",\n target: `literal:${prop.local}`\n });\n }\n if (prop.writable !== undefined) {\n links.push({\n source: propShapeId,\n predicate: \"ad4m://writable\",\n target: `literal:${prop.writable}`\n });\n }\n if (prop.resolveLanguage) {\n links.push({\n source: propShapeId,\n predicate: \"ad4m://resolveLanguage\",\n target: `literal:string:${prop.resolveLanguage}`\n });\n }\n // AD4M-specific actions\n if (prop.setter && prop.setter.length > 0) {\n links.push({\n source: propShapeId,\n predicate: \"ad4m://setter\",\n target: `literal:string:${JSON.stringify(prop.setter)}`\n });\n }\n if (prop.adder && prop.adder.length > 0) {\n links.push({\n source: propShapeId,\n predicate: \"ad4m://adder\",\n target: `literal:string:${JSON.stringify(prop.adder)}`\n });\n }\n if (prop.remover && prop.remover.length > 0) {\n links.push({\n source: propShapeId,\n predicate: \"ad4m://remover\",\n target: `literal:string:${JSON.stringify(prop.remover)}`\n });\n }\n if (prop.getter) {\n links.push({\n source: propShapeId,\n predicate: \"ad4m://getter\",\n target: `literal:string:${prop.getter}`\n });\n }\n if (prop.conformanceConditions && prop.conformanceConditions.length > 0) {\n links.push({\n source: propShapeId,\n predicate: \"ad4m://conformanceConditions\",\n target: `literal:string:${JSON.stringify(prop.conformanceConditions)}`\n });\n }\n if (prop.class) {\n links.push({\n source: propShapeId,\n predicate: \"sh://class\",\n target: prop.class\n });\n }\n if (prop.in && prop.in.length > 0) {\n links.push({\n source: propShapeId,\n predicate: \"sh://in\",\n target: `literal:string:${JSON.stringify(prop.in)}`\n });\n }\n }\n return links;\n }\n /**\n * Reconstruct shape from AD4M Links\n */\n static fromLinks(links, shapeUri) {\n // Find target class\n const targetClassLink = links.find(l => l.source === shapeUri && l.predicate === \"sh://targetClass\");\n const shape = new SHACLShape(shapeUri, targetClassLink?.target);\n // Find constructor actions\n const constructorLink = links.find(l => l.source === shapeUri && l.predicate === \"ad4m://constructor\");\n if (constructorLink) {\n try {\n const jsonStr = constructorLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n shape.constructor_actions = JSON.parse(jsonStr);\n }\n catch (e) {\n // Ignore parse errors\n }\n }\n // Find destructor actions\n const destructorLink = links.find(l => l.source === shapeUri && l.predicate === \"ad4m://destructor\");\n if (destructorLink) {\n try {\n const jsonStr = destructorLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n shape.destructor_actions = JSON.parse(jsonStr);\n }\n catch (e) {\n // Ignore parse errors\n }\n }\n // Find all property shapes\n const propShapeLinks = links.filter(l => l.source === shapeUri && l.predicate === \"sh://property\");\n for (const propLink of propShapeLinks) {\n const propShapeId = propLink.target;\n // Reconstruct property from its links\n const pathLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://path\");\n if (!pathLink)\n continue;\n // Extract property name from propShapeId if it's a named URI\n // Format: {namespace}{ClassName}.{propertyName}\n let propertyName;\n if (!propShapeId.startsWith('_:')) {\n const lastDotIndex = propShapeId.lastIndexOf('.');\n if (lastDotIndex !== -1) {\n propertyName = propShapeId.substring(lastDotIndex + 1);\n }\n }\n const prop = {\n name: propertyName,\n path: pathLink.target\n };\n // Extract constraints\n const datatypeLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://datatype\");\n if (datatypeLink)\n prop.datatype = datatypeLink.target;\n const nodeKindLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://nodeKind\");\n if (nodeKindLink) {\n prop.nodeKind = nodeKindLink.target.replace('sh://', '');\n }\n const minCountLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://minCount\");\n if (minCountLink) {\n // Handle both formats: literal:5^^xsd:integer and literal:number:5\n let val = minCountLink.target.replace(/^literal:\\/\\/|^literal:/, '').replace(/\\^\\^.*$/, '');\n if (val.startsWith('number:'))\n val = val.substring(7);\n prop.minCount = parseInt(val);\n }\n const maxCountLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://maxCount\");\n if (maxCountLink) {\n // Handle both formats: literal:5^^xsd:integer and literal:number:5\n let val = maxCountLink.target.replace(/^literal:\\/\\/|^literal:/, '').replace(/\\^\\^.*$/, '');\n if (val.startsWith('number:'))\n val = val.substring(7);\n prop.maxCount = parseInt(val);\n }\n const patternLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://pattern\");\n if (patternLink) {\n prop.pattern = patternLink.target.replace(/^literal:\\/\\/|^literal:/, '');\n }\n const minInclusiveLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://minInclusive\");\n if (minInclusiveLink) {\n // Handle both formats: literal:5 and literal:number:5\n let val = minInclusiveLink.target.replace(/^literal:\\/\\/|^literal:/, '');\n if (val.startsWith('number:'))\n val = val.substring(7);\n prop.minInclusive = parseFloat(val);\n }\n const maxInclusiveLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://maxInclusive\");\n if (maxInclusiveLink) {\n // Handle both formats: literal:5 and literal:number:5\n let val = maxInclusiveLink.target.replace(/^literal:\\/\\/|^literal:/, '');\n if (val.startsWith('number:'))\n val = val.substring(7);\n prop.maxInclusive = parseFloat(val);\n }\n const hasValueLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://hasValue\");\n if (hasValueLink) {\n prop.hasValue = hasValueLink.target.replace(/^literal:\\/\\/|^literal:/, '');\n }\n // AD4M-specific\n const localLink = links.find(l => l.source === propShapeId && l.predicate === \"ad4m://local\");\n if (localLink) {\n // Handle both formats: literal:true and literal:boolean:true\n let val = localLink.target.replace(/^literal:\\/\\/|^literal:/, '');\n if (val.startsWith('boolean:'))\n val = val.substring(8);\n prop.local = val === 'true';\n }\n const writableLink = links.find(l => l.source === propShapeId && l.predicate === \"ad4m://writable\");\n if (writableLink) {\n // Handle both formats: literal:true and literal:boolean:true\n let val = writableLink.target.replace(/^literal:\\/\\/|^literal:/, '');\n if (val.startsWith('boolean:'))\n val = val.substring(8);\n prop.writable = val === 'true';\n }\n const resolveLangLink = links.find(l => l.source === propShapeId && l.predicate === \"ad4m://resolveLanguage\");\n if (resolveLangLink) {\n prop.resolveLanguage = resolveLangLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n }\n // Parse action arrays\n const setterLink = links.find(l => l.source === propShapeId && l.predicate === \"ad4m://setter\");\n if (setterLink) {\n try {\n const jsonStr = setterLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n prop.setter = JSON.parse(jsonStr);\n }\n catch (e) {\n // Ignore parse errors\n }\n }\n const adderLink = links.find(l => l.source === propShapeId && l.predicate === \"ad4m://adder\");\n if (adderLink) {\n try {\n const jsonStr = adderLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n prop.adder = JSON.parse(jsonStr);\n }\n catch (e) {\n // Ignore parse errors\n }\n }\n const removerLink = links.find(l => l.source === propShapeId && l.predicate === \"ad4m://remover\");\n if (removerLink) {\n try {\n const jsonStr = removerLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n prop.remover = JSON.parse(jsonStr);\n }\n catch (e) {\n // Ignore parse errors\n }\n }\n const getterLink = links.find(l => l.source === propShapeId && l.predicate === \"ad4m://getter\");\n if (getterLink) {\n prop.getter = getterLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n }\n const conditionsLink = links.find(l => l.source === propShapeId && l.predicate === \"ad4m://conformanceConditions\");\n if (conditionsLink) {\n try {\n const jsonStr = conditionsLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n prop.conformanceConditions = JSON.parse(jsonStr);\n }\n catch (e) {\n // Ignore parse errors\n }\n }\n const classLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://class\");\n if (classLink) {\n prop.class = classLink.target;\n }\n const inLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://in\");\n if (inLink) {\n try {\n const jsonStr = inLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n prop.in = JSON.parse(jsonStr);\n }\n catch (e) {\n // Ignore parse errors\n }\n }\n shape.addProperty(prop);\n }\n return shape;\n }\n /**\n * Convert the shape to a JSON-serializable object.\n * Useful for passing to addSdna() as shaclJson parameter.\n *\n * @returns JSON-serializable object representing the shape\n */\n toJSON() {\n return {\n node_shape_uri: this.nodeShapeUri,\n target_class: this.targetClass,\n parent_shapes: this.parentShapes.length > 0 ? this.parentShapes : undefined,\n properties: this.properties.map(p => ({\n path: p.path,\n name: p.name,\n datatype: p.datatype,\n node_kind: p.nodeKind,\n min_count: p.minCount,\n max_count: p.maxCount,\n min_inclusive: p.minInclusive,\n max_inclusive: p.maxInclusive,\n pattern: p.pattern,\n has_value: p.hasValue,\n local: p.local,\n writable: p.writable,\n resolve_language: p.resolveLanguage,\n setter: p.setter,\n adder: p.adder,\n remover: p.remover,\n getter: p.getter,\n conformance_conditions: p.conformanceConditions,\n class: p.class,\n in: p.in,\n })),\n constructor_actions: this.constructor_actions,\n destructor_actions: this.destructor_actions,\n };\n }\n /**\n * Create a shape from a JSON object (inverse of toJSON)\n */\n static fromJSON(json) {\n const shape = json.node_shape_uri\n ? new SHACLShape(json.node_shape_uri, json.target_class)\n : new SHACLShape(json.target_class);\n for (const p of json.properties || []) {\n shape.addProperty({\n path: p.path,\n name: p.name,\n datatype: p.datatype,\n nodeKind: p.node_kind,\n minCount: p.min_count,\n maxCount: p.max_count,\n minInclusive: p.min_inclusive,\n maxInclusive: p.max_inclusive,\n pattern: p.pattern,\n hasValue: p.has_value,\n local: p.local,\n writable: p.writable,\n resolveLanguage: p.resolve_language,\n setter: p.setter,\n adder: p.adder,\n remover: p.remover,\n getter: p.getter,\n conformanceConditions: p.conformance_conditions,\n class: p.class,\n in: p.in,\n });\n }\n if (json.constructor_actions) {\n shape.constructor_actions = json.constructor_actions;\n }\n if (json.destructor_actions) {\n shape.destructor_actions = json.destructor_actions;\n }\n if (json.parent_shapes) {\n for (const ps of json.parent_shapes) {\n shape.addParentShape(ps);\n }\n }\n return shape;\n }\n}\n\nfunction formatList(list) {\n if (!list?.length) {\n return \"\";\n }\n if (list.length === 1) {\n return list.toString();\n }\n if (list.length === 2) {\n return list.join(' and ');\n }\n return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);\n}\nfunction capSentence(cap) {\n const can = cap.can.includes(\"*\") ? [\"READ\", \"WRITE\", \"UPDATE\"] : cap.can;\n const domain = cap.with.domain === \"*\" ? \"\" : cap.with.domain;\n const pointers = cap.with.pointers.includes(\"*\")\n ? [\"all AD4M data\"]\n : cap.with.pointers;\n return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;\n}\n/**\n * Escapes a string value for safe use in query strings.\n *\n * @description\n * Prevents SQL injection by properly escaping special characters in string values\n * that will be interpolated into query strings. This handles the most common\n * special characters that could break SQL queries or enable injection attacks.\n *\n * Single quotes, backslashes, and other special characters are escaped using\n * backslash notation, which is the standard escaping mechanism for query.\n *\n * @param value - The string value to escape\n * @returns The escaped string safe for query interpolation (without surrounding quotes)\n *\n * @example\n * ```typescript\n * const userInput = \"user's input with 'quotes'\";\n * const escaped = escapeQueryString(userInput);\n * const query = `SELECT * FROM link WHERE uri = '${escaped}'`;\n * // Results in: SELECT * FROM link WHERE uri = 'user\\'s input with \\'quotes\\''\n * ```\n */\nfunction escapeQueryString(value) {\n return value\n .replace(/\\\\/g, '\\\\\\\\') // Backslash -> \\\\\n .replace(/'/g, \"\\\\'\") // Single quote -> \\'\n .replace(/\"/g, '\\\\\"') // Double quote -> \\\"\n .replace(/\\n/g, '\\\\n') // Newline -> \\n\n .replace(/\\r/g, '\\\\r') // Carriage return -> \\r\n .replace(/\\t/g, '\\\\t'); // Tab -> \\t\n}\n\n/**\n * Shared query compilation utilities.\n *\n * These functions are used by both the runtime query builder (`Ad4mModel`) and\n * the compile-time SHACL generator (`decorators.ts`).\n *\n * All output uses native SPARQL syntax.\n */\n/**\n * Format a JavaScript value for embedding in a query expression.\n *\n * - Strings are single-quoted with backslash / quote / newline escaping\n * - Numbers and booleans are passed through as-is\n * - Arrays are recursed\n */\nfunction formatQueryValue(value) {\n if (typeof value === 'string') {\n // Escape backslashes first, then single quotes and other special characters\n const escaped = value\n .replace(/\\\\/g, '\\\\\\\\') // Backslash -> \\\\\n .replace(/'/g, \"\\\\'\") // Single quote -> \\'\n .replace(/\"/g, '\\\\\"') // Double quote -> \\\"\n .replace(/\\n/g, '\\\\n') // Newline -> \\n\n .replace(/\\r/g, '\\\\r') // Carriage return -> \\r\n .replace(/\\t/g, '\\\\t'); // Tab -> \\t\n return `'${escaped}'`;\n }\n else if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n else if (Array.isArray(value)) {\n return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;\n }\n else {\n return String(value);\n }\n}\n/**\n * Compile a single Where condition for a property into a SPARQL triple pattern\n * that can be embedded in a getter's WHERE clause.\n *\n * The generated pattern operates on `?target` \u2014 e.g.:\n * `?target <pred> <value> .`\n * `FILTER EXISTS { ?target <pred> ?_v0 }`\n *\n * @param predicate - The predicate URI for the property\n * @param condition - The Where condition value\n * @param opts - Optional settings (e.g. `resolveLanguage`)\n * @returns A single SPARQL condition string\n */\nfunction buildWhereCondition(predicate, condition, opts) {\n const escapedPredicate = escapeQueryString(predicate);\n // For literal-resolved properties, we match against the raw IRI (which is a literal: URI)\n // For language-resolved properties, we match against the plain URI\n // For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>\n // For language-resolved properties, values are plain URIs\n const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';\n const varSuffix = opts?.varIndex ?? 0;\n function formatValue(v) {\n if (typeof v === 'string') {\n return isLiteral\n ? `<literal:string:${escapeQueryString(v)}>`\n : `<${escapeQueryString(v)}>`;\n }\n // Numbers/booleans \u2014 also stored as literal:string: in AD4M\n return `<literal:string:${v}>`;\n }\n /**\n * For literal properties, generate a FILTER-based match that handles both\n * the raw value and the literal-encoded value. This mirrors the Rust\n * `build_projection_where_patterns` approach which uses:\n * FILTER(STR(?var) = \"value\" || STR(?var) = \"literal:string:encodedValue\")\n * This is more robust than exact IRI matching because it handles edge cases\n * where the stored format might vary.\n */\n function formatLiteralFilter(varName, v) {\n const raw = escapeQueryString(String(v));\n const encoded = encodeURIComponent(String(v))\n .replace(/!/g, '%21')\n .replace(/'/g, '%27')\n .replace(/\\(/g, '%28')\n .replace(/\\)/g, '%29')\n .replace(/\\*/g, '%2A');\n if (typeof v === 'string') {\n return `FILTER(STR(${varName}) = \"${raw}\" || STR(${varName}) = \"literal:string:${encoded}\")`;\n }\n else if (typeof v === 'number') {\n return `FILTER(STR(${varName}) = \"${v}\" || STR(${varName}) = \"literal:number:${v}\")`;\n }\n else if (typeof v === 'boolean') {\n return `FILTER(STR(${varName}) = \"${v}\" || STR(${varName}) = \"literal:boolean:${v}\")`;\n }\n return `FILTER(STR(${varName}) = \"${raw}\")`;\n }\n if (Array.isArray(condition)) {\n // Array values \u2192 FILTER IN\n if (isLiteral) {\n const varName = `?_wc${varSuffix}`;\n const inValues = condition.flatMap(v => {\n const raw = escapeQueryString(String(v));\n const encoded = encodeURIComponent(String(v))\n .replace(/!/g, '%21').replace(/'/g, '%27')\n .replace(/\\(/g, '%28').replace(/\\)/g, '%29').replace(/\\*/g, '%2A');\n return [`\"${raw}\"`, `\"literal:string:${encoded}\"`];\n }).join(', ');\n return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;\n }\n const formattedValues = condition.map(formatValue).join(', ');\n return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;\n }\n else if (typeof condition === 'object' && condition !== null) {\n // Operator object\n const ops = condition;\n const parts = [];\n if (ops.not !== undefined) {\n if (Array.isArray(ops.not)) {\n const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');\n // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,\n // so O(N\u00B2) behavior is bounded by the number of values for this property.\n parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);\n }\n else {\n // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,\n // so O(N\u00B2) behavior is bounded by the number of values for this property.\n parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);\n }\n }\n // Comparison operators \u2014 ensure property exists\n const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||\n ops.lt !== undefined || ops.lte !== undefined ||\n ops.between !== undefined || ops.contains !== undefined;\n if (hasComparisonOps) {\n parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);\n }\n return parts.join(' ');\n }\n else {\n // Simple equality\n if (isLiteral) {\n // Use FILTER matching (mirrors Rust build_projection_where_patterns)\n // to handle both raw values and literal-encoded IRIs robustly.\n const varName = `?_wc${varSuffix}`;\n return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;\n }\n return `?target <${escapedPredicate}> ${formatValue(condition)} .`;\n }\n}\n/**\n * Compile a full `Where` clause to an array of SPARQL condition strings.\n *\n * When `metadata` is provided, property names are resolved to predicates\n * using the model's property metadata. When `metadata` is `null`, property\n * names are treated as raw predicate URIs.\n *\n * Only handles **regular properties** \u2014 special fields (`id`, `author`,\n * `timestamp`) and relation fields are skipped (they are only relevant at\n * runtime query time, not for compile-time getter generation).\n */\nfunction compileWhereClause(where, metadata) {\n const conditions = [];\n for (const [propertyName, condition] of Object.entries(where)) {\n // Skip special fields that don't apply at compile time\n if (['id', 'author', 'timestamp'].includes(propertyName))\n continue;\n let predicate;\n let resolveLanguage;\n if (metadata) {\n const propMeta = metadata.properties[propertyName];\n if (propMeta) {\n predicate = propMeta.predicate;\n resolveLanguage = propMeta.resolveLanguage;\n }\n else {\n // Property not found in metadata \u2014 treat name as raw predicate URI\n predicate = propertyName;\n }\n }\n else {\n // No metadata \u2014 treat name as raw predicate URI\n predicate = propertyName;\n }\n const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });\n if (cond) {\n conditions.push(cond);\n }\n }\n return conditions;\n}\n\n/**\n * SHACL shape generation for AD4M model classes.\n *\n * Builds a W3C SHACL `SHACLShape` (with AD4M-specific action extensions)\n * from a model's property and relation metadata. The heavy lifting used\n * to live inside the `@Model` decorator closure \u2014 it is extracted here so\n * decorators.ts stays focused on decorator registration logic.\n */\n/**\n * Build a SHACL shape for a model class.\n *\n * @param subjectName - The model's registered name (from `@Model({ name })`)\n * @param target - The class constructor (used for prototype access,\n * inheritance chain, and relation target resolution)\n * @param properties - Merged property metadata (from `getPropertiesMetadata`)\n * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)\n * @param conformanceFilterFn - Injected conformance-filter builder\n * (avoids circular dependency back into decorators.ts)\n */\nfunction buildSHACL(subjectName, target, properties, allRelationsMeta, conformanceFilterFn) {\n const obj = target.prototype;\n // \u2500\u2500 Determine namespace from first property or relation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n let namespace = \"ad4m://\";\n const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));\n // Try properties first\n if (Object.keys(properties).length > 0) {\n const firstProp = properties[Object.keys(properties)[0]];\n if (firstProp.through) {\n const match = firstProp.through.match(/^([^:]+:\\/\\/)/);\n if (match) {\n namespace = match[1];\n }\n }\n }\n // Fall back to relations if no properties\n else if (Object.keys(relations).length > 0) {\n const firstRel = relations[Object.keys(relations)[0]];\n if (firstRel.predicate) {\n const match = firstRel.predicate.match(/^([^:]+:\\/\\/)/);\n if (match) {\n namespace = match[1];\n }\n }\n }\n // \u2500\u2500 Create SHACL shape \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const shapeUri = `${namespace}${subjectName}Shape`;\n const targetClass = `${namespace}${subjectName}`;\n const shape = new SHACLShape(shapeUri, targetClass);\n // Detect @Model inheritance \u2014 if the parent class also has\n // generateSHACL it is itself a @Model and we reference its shape\n // via sh:node so SHACL validators can walk the hierarchy.\n const parentCtor = Object.getPrototypeOf(target);\n if (parentCtor && typeof parentCtor.generateSHACL === 'function') {\n const parentSHACL = parentCtor.generateSHACL();\n if (parentSHACL?.shape?.nodeShapeUri) {\n shape.addParentShape(parentSHACL.shape.nodeShapeUri);\n }\n }\n // \u2500\u2500 Constructor / Destructor actions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n let constructorActions = [];\n if (obj.subjectConstructor && obj.subjectConstructor.length) {\n constructorActions = constructorActions.concat(obj.subjectConstructor);\n }\n let destructorActions = [];\n // \u2500\u2500 Convert properties to SHACL property shapes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n for (const propName in properties) {\n const propMeta = properties[propName];\n if (!propMeta.through)\n continue; // Skip properties without predicates\n const propShape = {\n name: propName,\n path: propMeta.through,\n };\n // Determine datatype from initial value or resolveLanguage\n if (propMeta.resolveLanguage === \"literal\") {\n propShape.datatype = \"xsd://string\";\n }\n else if (propMeta.initial) {\n const initialType = typeof obj[propName];\n if (initialType === \"number\") {\n propShape.datatype = \"xsd://integer\";\n }\n else if (initialType === \"boolean\") {\n propShape.datatype = \"xsd://boolean\";\n }\n else if (initialType === \"string\") {\n propShape.datatype = \"xsd://string\";\n }\n }\n // Cardinality constraints\n if (propMeta.required) {\n propShape.minCount = 1;\n }\n // Single-valued properties get maxCount 1\n propShape.maxCount = 1;\n // Flag properties have fixed value\n if (propMeta.flag && propMeta.initial) {\n propShape.hasValue = propMeta.initial;\n }\n // sh:in \u2014 allowed values (enum constraint)\n if (propMeta.options && propMeta.options.length > 0) {\n propShape.in = propMeta.options;\n }\n // AD4M-specific metadata\n if (propMeta.local !== undefined) {\n propShape.local = propMeta.local;\n }\n if (propMeta.writable !== undefined) {\n propShape.writable = propMeta.writable;\n }\n if (propMeta.resolveLanguage) {\n propShape.resolveLanguage = propMeta.resolveLanguage;\n }\n // \u2500\u2500 Setter actions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (propMeta.prologSetter) {\n console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +\n `The property will be created without setter actions. Consider using standard writable properties or provide explicit SHACL JSON.`);\n }\n else if (propMeta.writable && propMeta.through) {\n let setter = obj[propertyNameToSetterName(propName)];\n if (typeof setter === \"function\") {\n propShape.setter = [{\n action: \"setSingleTarget\",\n source: \"this\",\n predicate: propMeta.through,\n target: \"value\",\n ...(propMeta.local && { local: true })\n }];\n }\n }\n // \u2500\u2500 Constructor / Destructor entries \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const effectiveInitial = propMeta.initial\n ?? (propMeta.required && propMeta.writable && !propMeta.flag && propMeta.through\n ? \"literal:string:\" : undefined);\n if (effectiveInitial) {\n constructorActions.push({\n action: \"addLink\",\n source: \"this\",\n predicate: propMeta.through,\n target: effectiveInitial,\n });\n destructorActions.push({\n action: \"removeLink\",\n source: \"this\",\n predicate: propMeta.through,\n target: \"*\",\n });\n }\n shape.addProperty(propShape);\n }\n // \u2500\u2500 Convert relations to SHACL property shapes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n for (const relName in relations) {\n const relMeta = relations[relName];\n if (!relMeta.predicate)\n continue;\n const relShape = {\n name: relName,\n path: relMeta.predicate,\n };\n // Relations typically contain IRIs\n relShape.nodeKind = 'IRI';\n // AD4M-specific metadata\n if (relMeta.local !== undefined) {\n relShape.local = relMeta.local;\n }\n // Adder action\n relShape.adder = [{\n action: \"addLink\",\n source: \"this\",\n predicate: relMeta.predicate,\n target: \"value\",\n ...(relMeta.local && { local: true })\n }];\n // Remover action\n relShape.remover = [{\n action: \"removeLink\",\n source: \"this\",\n predicate: relMeta.predicate,\n target: \"value\",\n ...(relMeta.local && { local: true })\n }];\n // \u2500\u2500 Build Getter (conformance filter) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Priority chain:\n // 1. Explicit getter string \u2192 use verbatim\n // 2. `where` clause \u2192 compile DSL to SPARQL getter\n // 3. target + filter !== false \u2192 auto-derive from shape\n if (relMeta.getter) {\n relShape.getter = relMeta.getter;\n }\n else if (relMeta.where) {\n try {\n const TargetClass = relMeta.target?.();\n const targetMetadata = TargetClass\n ? TargetClass.getModelMetadata?.() ?? null\n : null;\n const conditions = compileWhereClause(relMeta.where, targetMetadata);\n if (conditions.length > 0) {\n const escapedPredicate = escapeQueryString(relMeta.predicate);\n relShape.getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;\n }\n }\n catch (e) {\n // Target metadata may not be available yet\n }\n }\n else if (relMeta.target && relMeta.filter !== false) {\n // Lazy conformance filter: store deferred reference,\n // resolve on first access via a getter on relShape\n const targetThunk = relMeta.target;\n const predicate = relMeta.predicate;\n let resolved = false;\n let cachedGetter;\n let cachedConditions;\n const resolveFilter = () => {\n if (resolved)\n return;\n resolved = true;\n try {\n const TargetClass = targetThunk();\n const filter = conformanceFilterFn(predicate, TargetClass);\n if (filter) {\n cachedGetter = filter.getter;\n cachedConditions = filter.conformanceConditions;\n }\n }\n catch (e) {\n // Target class may not be available yet\n }\n };\n // Define lazy getters that resolve on first access\n Object.defineProperty(relShape, 'getter', {\n get() { resolveFilter(); return cachedGetter; },\n set(v) { resolved = true; cachedGetter = v; },\n enumerable: true,\n configurable: true,\n });\n Object.defineProperty(relShape, 'conformanceConditions', {\n get() { resolveFilter(); return cachedConditions; },\n set(v) { resolved = true; cachedConditions = v; },\n enumerable: true,\n configurable: true,\n });\n }\n // \u2500\u2500 sh:class \u2014 target shape reference \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (relMeta.target) {\n try {\n const TargetClass = relMeta.target();\n const targetSHACL = TargetClass.generateSHACL?.();\n if (targetSHACL?.shape?.nodeShapeUri) {\n relShape.class = targetSHACL.shape.nodeShapeUri;\n }\n }\n catch (e) {\n // Target class may not be available yet\n }\n }\n shape.addProperty(relShape);\n }\n // Always set constructor and destructor actions on the shape, even\n // when empty. An empty array serialises to `literal:string:[]`\n // which the Rust executor parses as a valid (no-op) command list,\n // avoiding \"No SHACL constructor found\" errors for models whose\n // properties are all optional and have no @Flag.\n shape.setConstructorActions(constructorActions);\n shape.setDestructorActions(destructorActions);\n return {\n shape,\n name: subjectName\n };\n}\n\n/** Registry of property metadata keyed by constructor \u2192 { propName \u2192 metadata } */\nconst propertyRegistry = new WeakMap();\n/** Registry of relation metadata keyed by constructor \u2192 { propName \u2192 metadata } */\nconst relationRegistry = new WeakMap();\n/** Memoisation cache for getPropertiesMetadata \u2014 avoids repeated prototype-chain walks */\nconst propertiesMetadataCache = new WeakMap();\n/** Memoisation cache for getRelationsMetadata \u2014 avoids repeated prototype-chain walks */\nconst relationsMetadataCache = new WeakMap();\n/** Memoisation cache for generateSHACL \u2014 avoids recomputing SHACL shapes */\nconst shaclCache = new WeakMap();\n/**\n * Retrieve property metadata for a given class constructor.\n * Walks the prototype chain so subclass decorators compose with parent decorators.\n * Results are memoised per class constructor.\n */\nfunction getPropertiesMetadata(ctor) {\n const cached = propertiesMetadataCache.get(ctor);\n if (cached)\n return cached;\n const result = {};\n const chain = [];\n let current = ctor;\n while (current && current !== Object) {\n chain.unshift(current); // parent-first order\n current = Object.getPrototypeOf(current);\n }\n for (const c of chain) {\n const meta = propertyRegistry.get(c);\n if (meta)\n Object.assign(result, meta);\n }\n propertiesMetadataCache.set(ctor, result);\n return result;\n}\n/**\n * Retrieve relation metadata for a given class constructor.\n * Walks the prototype chain so subclass decorators compose with parent decorators.\n * Results are memoised per class constructor.\n */\nfunction getRelationsMetadata(ctor) {\n const cached = relationsMetadataCache.get(ctor);\n if (cached)\n return cached;\n const result = {};\n const chain = [];\n let current = ctor;\n while (current && current !== Object) {\n chain.unshift(current);\n current = Object.getPrototypeOf(current);\n }\n for (const c of chain) {\n const meta = relationRegistry.get(c);\n if (meta)\n Object.assign(result, meta);\n }\n relationsMetadataCache.set(ctor, result);\n return result;\n}\n/**\n * Get or compute memoised SHACL for a class. Used by @Model decorator.\n */\nfunction getMemoizedSHACL(target, compute) {\n const cached = shaclCache.get(target);\n if (cached)\n return cached;\n const result = compute();\n shaclCache.set(target, result);\n return result;\n}\n/**\n * Programmatically register property metadata for a given constructor.\n * Used by `fromJSONSchema()` and other dynamic model builders.\n */\nfunction setPropertyRegistryEntry(ctor, propName, meta) {\n if (!propertyRegistry.has(ctor))\n propertyRegistry.set(ctor, {});\n propertyRegistry.get(ctor)[propName] = meta;\n}\n/**\n * Programmatically register relation metadata for a given constructor.\n * Used by `fromJSONSchema()` and other dynamic model builders.\n */\nfunction setRelationRegistryEntry(ctor, relName, meta) {\n if (!relationRegistry.has(ctor))\n relationRegistry.set(ctor, {});\n relationRegistry.get(ctor)[relName] = meta;\n}\n/**\n * Build a conformance filter for a relation whose target model is known.\n *\n * Inspects the target class's property metadata to derive:\n * - `conformanceConditions`: Structured, DB-agnostic conditions (flag & required checks)\n * - `getter`: Pre-computed graph traversal expression that traverses outgoing links and filters\n * target nodes to only those conforming to the target shape.\n *\n * @param relationPredicate - The relation's predicate URI (e.g. \"flux://entry_type\")\n * @param targetClass - The target model class (resolved from the target() thunk)\n * @returns `{ getter, conformanceConditions }` or `undefined` if no conditions could be derived\n */\nfunction buildConformanceFilter(relationPredicate, targetClass) {\n try {\n const targetProps = getPropertiesMetadata(targetClass);\n const conditions = [];\n const sparqlConditions = [];\n let varIdx = 0;\n // 1. Flags \u2014 check predicate + value\n for (const [_propName, propMeta] of Object.entries(targetProps)) {\n if (propMeta.flag && propMeta.initial && propMeta.through) {\n conditions.push({\n type: 'flag',\n predicate: propMeta.through,\n value: propMeta.initial,\n });\n sparqlConditions.push(`?target <${escapeQueryString(propMeta.through)}> <${escapeQueryString(propMeta.initial)}> .`);\n }\n }\n // 2. Required (non-flag) properties \u2014 check predicate exists\n // Skip properties with custom getters (they don't follow the standard link pattern)\n for (const [_propName, propMeta] of Object.entries(targetProps)) {\n if (propMeta.required && !propMeta.flag && !propMeta.getter && propMeta.through) {\n conditions.push({\n type: 'required',\n predicate: propMeta.through,\n });\n sparqlConditions.push(`?target <${escapeQueryString(propMeta.through)}> ?_v${varIdx++} .`);\n }\n }\n if (conditions.length === 0) {\n return undefined;\n }\n const getter = `SELECT ?target WHERE { <Base> <${escapeQueryString(relationPredicate)}> ?target . ${sparqlConditions.join(' ')} }`;\n return { getter, conformanceConditions: conditions };\n }\n catch (e) {\n // Target class may not have property metadata\n return undefined;\n }\n}\n/**\n * Internal core implementation for registering property metadata on the prototype.\n * All property decorators (@Property, @Optional, @ReadOnly) and relation decorators\n * that create properties delegate to this function.\n * @internal\n */\nfunction applyPropertyMetadata(opts) {\n return function (target, key) {\n // Map readOnly \u2192 internal writable for SDNA/SHACL compatibility\n const writable = opts.readOnly ? false : (opts.through ? true : false);\n if (opts.required && !opts.initial) {\n throw new Error(\"SubjectProperty requires an 'initial' option if 'required' is true\");\n }\n if (!opts.through && !opts.prologGetter && !opts.getter) {\n throw new Error(\"SubjectProperty requires either 'through' or 'prologGetter' or 'getter' option\");\n }\n // Write to WeakMap registry (keyed by constructor)\n const ctor = target.constructor;\n if (!propertyRegistry.has(ctor))\n propertyRegistry.set(ctor, {});\n propertyRegistry.get(ctor)[key] = { ...opts, writable };\n if (writable) {\n const value = key;\n target[`set${capitalize(value)}`] = () => { };\n }\n Object.defineProperty(target, key, { configurable: true, writable: true });\n };\n}\n/**\n * Convenience decorator for defining optional (not required) properties.\n *\n * @category Decorators\n *\n * @description\n * Equivalent to `@Property` but defaults `required` to `false` and does not\n * apply `resolveLanguage` or `initial` defaults. Use this when a property\n * may or may not have a value, and you want full control over its configuration.\n *\n * @example\n * ```typescript\n * class Recipe extends Ad4mModel {\n * @Optional({ through: \"recipe://description\" })\n * description?: string;\n * }\n * ```\n *\n * @param {PropertyOptions} opts - Property configuration (same options as @Property)\n */\nfunction Optional(opts) {\n return applyPropertyMetadata({\n ...opts,\n required: opts.required ?? false,\n readOnly: opts.readOnly ?? false,\n });\n}\n/**\n * Decorator for defining flags on model classes.\n *\n * @category Decorators\n *\n * @description\n * A specialized property decorator for defining immutable type flags or markers on model instances.\n * Flags are always required properties with a fixed value that cannot be changed after creation.\n *\n * Common uses for flags:\n * - Type discrimination between different kinds of models\n * - Marking models with specific capabilities or features\n * - Versioning or compatibility markers\n *\n * Note: Use of Flag is discouraged unless you specifically need type-based filtering or\n * discrimination between different kinds of models. For most cases, regular properties\n * with @Property or @Optional are more appropriate.\n *\n * @example\n * ```typescript\n * class Message extends Ad4mModel {\n * // Type flag to identify message models\n * @Flag({\n * through: \"ad4m://type\",\n * value: \"ad4m://message\"\n * })\n * type: string = \"\";\n *\n * // Version flag for compatibility\n * @Flag({\n * through: \"ad4m://version\",\n * value: \"1.0.0\"\n * })\n * version: string = \"\";\n *\n * // Feature flag\n * @Flag({\n * through: \"message://feature\",\n * value: \"message://encrypted\"\n * })\n * feature: string = \"\";\n * }\n *\n * // Later you can query for specific types:\n * const messages = await Message.query(perspective)\n * .where({ type: \"ad4m://message\" })\n * .run();\n * ```\n *\n * @param {FlagOptions} opts - Flag configuration\n * @param {string} opts.through - The predicate URI for the flag\n * @param {string} opts.value - The fixed value for the flag\n */\nfunction Flag(opts) {\n return function (target, key) {\n if (!opts.through && !opts.value) {\n throw new Error(\"SubjectFlag requires a 'through' and 'value' option\");\n }\n if (!opts.through) {\n throw new Error(\"SubjectFlag requires a 'through' option\");\n }\n if (!opts.value) {\n throw new Error(\"SubjectFlag requires a 'value' option\");\n }\n const entry = {\n through: opts.through,\n required: true,\n initial: opts.value,\n flag: true,\n readOnly: true,\n writable: false,\n };\n // Write to WeakMap registry\n const ctor = target.constructor;\n if (!propertyRegistry.has(ctor))\n propertyRegistry.set(ctor, {});\n propertyRegistry.get(ctor)[key] = entry;\n // @ts-ignore\n target[key] = opts.value;\n Object.defineProperty(target, key, { configurable: true, writable: true });\n };\n}\n/**\n * Decorator for defining model classes in AD4M.\n *\n * @category Decorators\n *\n * @description\n * The root decorator that must be applied to any class that represents a model in AD4M.\n * It registers the class as a Social DNA (SDNA) subject class and provides the infrastructure\n * for storing and retrieving instances.\n *\n * This decorator:\n * - Registers the class with a unique name in the AD4M system\n * - Generates the necessary SDNA code for the model's properties and relations\n * - Enables the use of other model decorators (@Property, @HasMany, etc.)\n * - Provides static query methods through the Ad4mModel base class\n *\n * @example\n * ```typescript\n * @Model({ name: \"Recipe\" })\n * class Recipe extends Ad4mModel {\n * @Property({\n * through: \"recipe://name\",\n * resolveLanguage: \"literal\"\n * })\n * name: string = \"\";\n *\n * @HasMany({ through: \"recipe://ingredient\" })\n * ingredients: string[] = [];\n *\n * // Static query methods from Ad4mModel:\n * static async findByName(perspective: PerspectiveProxy, name: string) {\n * return Recipe.query(perspective)\n * .where({ name })\n * .run();\n * }\n * }\n *\n * // Using the model:\n * const recipe = new Recipe(perspective);\n * recipe.name = \"Chocolate Cake\";\n * await recipe.save();\n *\n * // Querying instances:\n * const recipes = await Recipe.query(perspective)\n * .where({ name: \"Chocolate Cake\" })\n * .run();\n *\n * // Using with PerspectiveProxy:\n * await perspective.ensureSDNASubjectClass(Recipe);\n * ```\n *\n * @param {ModelConfig} opts - Model configuration\n * @param {string} opts.name - Unique name for the model class in AD4M\n */\nfunction Model$1(opts) {\n return function (target) {\n target.prototype.className = opts.name;\n target.className = opts.name;\n target.generateSDNA = function () {\n return buildSDNA(opts.name, target.prototype, getPropertiesMetadata(target), getRelationsMetadata(target));\n };\n target.generateSHACL = function () {\n return getMemoizedSHACL(target, () => buildSHACL(opts.name, target, getPropertiesMetadata(target), getRelationsMetadata(target), buildConformanceFilter));\n };\n Object.defineProperty(target, 'type', { configurable: true });\n };\n}\n/**\n * The primary property decorator for AD4M model classes.\n *\n * @category Decorators\n *\n * @description\n * The core property decorator with smart defaults. All other property decorators\n * (@Optional, @ReadOnly) are thin wrappers that adjust these defaults.\n *\n * Smart defaults (all overridable):\n * - `required` \u2192 `false`\n * - `readOnly` \u2192 `false`\n * - `resolveLanguage` \u2192 `\"literal\"`\n * - `initial` \u2192 `undefined` (no link created until a value is explicitly set)\n *\n * Properties are optional by default. When a model instance is created without\n * providing a value for an optional property, no link is added to the graph.\n * Set `required: true` explicitly when a property must always be present (this\n * also adds a `\"literal:string:uninitialized\"` sentinel as the initial value\n * so that the SDNA constructor creates a placeholder link).\n *\n * @example\n * ```typescript\n * class User extends Ad4mModel {\n * // Optional property (default) \u2014 no link created until a value is set\n * @Property({\n * through: \"user://name\"\n * })\n * name: string = \"\";\n *\n * // Explicitly required property with sentinel initial value\n * @Property({\n * through: \"user://status\",\n * required: true\n * })\n * status: string = \"\";\n *\n * // Required property with custom initial value\n * @Property({\n * through: \"user://role\",\n * required: true,\n * initial: \"user://member\"\n * })\n * role: string = \"\";\n *\n * // Optional property with literal resolution\n * @Property({\n * through: \"user://bio\",\n * resolveLanguage: \"literal\"\n * })\n * bio: string = \"\";\n * }\n * ```\n *\n * @param {PropertyOptions} opts - Property configuration\n * @param {string} opts.through - The predicate URI for the property\n * @param {boolean} [opts.required=false] - Whether the property is required (adds query filters and sentinel initial value)\n * @param {string} [opts.initial] - Initial value (defaults to \"literal:string:uninitialized\" when required)\n * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. \"literal\")\n * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value\n * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value\n * @param {boolean} [opts.local] - Whether the property should only be stored locally\n */\nfunction Property(opts) {\n const required = opts.required ?? false;\n return applyPropertyMetadata({\n ...opts,\n required,\n readOnly: opts.readOnly ?? false,\n resolveLanguage: opts.resolveLanguage ?? \"literal\",\n initial: opts.initial ?? (required ? \"literal:string:uninitialized\" : undefined),\n });\n}\n/**\n * Decorator for defining read-only properties on model classes.\n *\n * @category Decorators\n *\n * @description\n * A convenience decorator that defines a read-only property.\n * Equivalent to `@Property` with `readOnly: true`.\n *\n * Read-only properties are ideal for:\n * - Computed or derived values\n * - Properties that should never change after creation\n * - Properties that are set by the system\n * - Properties that represent immutable data\n *\n * @example\n * ```typescript\n * class Post extends Ad4mModel {\n * // Read-only property with custom getter for computed value\n * @ReadOnly({\n * through: \"post://likes\",\n * getter: `findall(User, triple(Base, \"post://liked_by\", User), Users), length(Users, Value)`\n * })\n * likeCount: number = 0;\n *\n * // Read-only property for creation timestamp\n * @ReadOnly({\n * through: \"post://created_at\",\n * initial: new Date().toISOString()\n * })\n * createdAt: string = \"\";\n *\n * // Read-only property that resolves to a Literal\n * @ReadOnly({\n * through: \"post://author\",\n * resolveLanguage: \"literal\"\n * })\n * author: string = \"\";\n *\n * // Read-only property for system-managed data\n * @ReadOnly({\n * through: \"post://version\",\n * initial: \"1.0.0\"\n * })\n * version: string = \"\";\n * }\n * ```\n *\n * @param {PropertyOptions} opts - Property configuration\n * @param {string} opts.through - The predicate URI for the property\n * @param {string} [opts.initial] - Initial value (if property should have one)\n * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. \"literal\")\n * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value\n * @param {boolean} [opts.local] - Whether the property should only be stored locally\n */\nfunction ReadOnly(opts) {\n return Property({\n ...opts,\n readOnly: true,\n });\n}\n/**\n * Resolve overloaded relation decorator arguments.\n * Supports two calling conventions:\n * @HasMany({ through: \"...\", target: () => X }) \u2014 single options object\n * @HasMany(() => X, { through: \"...\" }) \u2014 target thunk + options\n * @internal\n */\nfunction resolveRelationArgs(first, second) {\n const opts = typeof first === 'function'\n ? { ...(second || {}), target: first }\n : first;\n // getter is mutually exclusive with through, target, and where\n if (opts.getter) {\n if (opts.through) {\n throw new Error('Relation decorator: `getter` and `through` are mutually exclusive. ' +\n 'Use `getter` alone for custom read-only relations, or `through` ' +\n '(with optional `target`) for standard link-based relations.');\n }\n if (opts.target) {\n throw new Error('Relation decorator: `getter` and `target` are mutually exclusive. ' +\n '`target` auto-generates a conformance getter from the model shape; ' +\n 'providing both is contradictory.');\n }\n if (opts.where) {\n throw new Error('Relation decorator: `where` and `getter` are mutually exclusive. ' +\n 'Use `where` for DSL-based filtering, or `getter` for raw getter expression.');\n }\n return opts;\n }\n // Default predicate when not provided\n if (!opts.through) {\n opts.through = 'ad4m://has_child';\n }\n // where validation\n if (opts.where) {\n if (opts.filter === false) {\n throw new Error('Relation decorator: `where` and `filter: false` are contradictory. ' +\n '`where` adds filtering constraints; `filter: false` disables filtering.');\n }\n }\n return opts;\n}\nfunction HasMany(first, second) {\n const opts = resolveRelationArgs(first, second);\n return function (target, key) {\n // --- relation registry ---\n const ctor = target.constructor;\n if (!relationRegistry.has(ctor))\n relationRegistry.set(ctor, {});\n const map = relationRegistry.get(ctor);\n map[key] = {\n predicate: opts.through,\n target: opts.target,\n kind: 'hasMany',\n local: opts.local,\n ...(opts.getter && { getter: opts.getter }),\n ...(opts.filter !== undefined && { filter: opts.filter }),\n ...(opts.where && { where: opts.where }),\n };\n const relKey = key;\n // Only add mutation methods when a predicate is available\n // (getter-only relations are read-only)\n if (opts.through) {\n target[`add${capitalize(relKey)}`] = async function (arg, batchId) {\n return this.addRelationValue(relKey, arg, batchId);\n };\n target[`remove${capitalize(relKey)}`] = async function (arg, batchId) {\n return this.removeRelationValue(relKey, arg, batchId);\n };\n target[`set${capitalize(relKey)}`] = async function (arg, batchId) {\n return this.setRelationValues(relKey, arg, batchId);\n };\n }\n Object.defineProperty(target, relKey, { configurable: true, writable: true });\n };\n}\nfunction HasOne(first, second) {\n const opts = resolveRelationArgs(first, second);\n return function (target, key) {\n const ctor = target.constructor;\n if (!relationRegistry.has(ctor))\n relationRegistry.set(ctor, {});\n const map = relationRegistry.get(ctor);\n map[key] = {\n predicate: opts.through,\n target: opts.target,\n kind: 'hasOne',\n maxCount: 1,\n local: opts.local,\n ...(opts.filter !== undefined && { filter: opts.filter }),\n ...(opts.where && { where: opts.where }),\n };\n const relKey = key;\n if (opts.through) {\n // Register as a writable property\n applyPropertyMetadata({\n through: opts.through,\n readOnly: false,\n local: opts.local,\n })(target, key);\n // Add prototype methods for add/remove/set (mirroring @HasMany)\n target[`add${capitalize(relKey)}`] = async function (arg) {\n return this.addRelationValue(relKey, arg);\n };\n target[`remove${capitalize(relKey)}`] = async function (arg) {\n return this.removeRelationValue(relKey, arg);\n };\n target[`set${capitalize(relKey)}`] = async function (arg) {\n return this.setRelationValues(relKey, arg);\n };\n }\n else {\n Object.defineProperty(target, relKey, { configurable: true, writable: true });\n }\n };\n}\nfunction BelongsToOne(first, second) {\n const opts = resolveRelationArgs(first, second);\n return function (target, key) {\n const ctor = target.constructor;\n if (!relationRegistry.has(ctor))\n relationRegistry.set(ctor, {});\n const map = relationRegistry.get(ctor);\n map[key] = {\n predicate: opts.through,\n target: opts.target,\n kind: 'belongsToOne',\n maxCount: 1,\n local: opts.local,\n ...(opts.filter !== undefined && { filter: opts.filter }),\n ...(opts.where && { where: opts.where }),\n };\n if (opts.through) {\n // Read-only property (the owning side manages the link)\n applyPropertyMetadata({\n through: opts.through,\n readOnly: true,\n local: opts.local,\n })(target, key);\n }\n else {\n Object.defineProperty(target, key, { configurable: true, writable: true });\n }\n };\n}\nfunction BelongsToMany(first, second) {\n const opts = resolveRelationArgs(first, second);\n return function (target, key) {\n const ctor = target.constructor;\n if (!relationRegistry.has(ctor))\n relationRegistry.set(ctor, {});\n const map = relationRegistry.get(ctor);\n map[key] = {\n predicate: opts.through,\n target: opts.target,\n kind: 'belongsToMany',\n local: opts.local,\n ...(opts.getter && { getter: opts.getter }),\n ...(opts.filter !== undefined && { filter: opts.filter }),\n ...(opts.where && { where: opts.where }),\n };\n // @BelongsToMany is the inverse/read-only side \u2014 do NOT generate add*/remove*/set*\n // prototype methods. Mutation must go through the owning side's @HasMany decorator.\n const relKey = key;\n Object.defineProperty(target, relKey, { configurable: true, writable: true });\n };\n}\n\n/**\n * Query Result TTL Cache\n *\n * Short-lived cache (200ms TTL) for SPARQL query results.\n * Prevents redundant queries during rapid render cycles where\n * multiple components issue the same query within milliseconds.\n *\n * Key: `perspectiveUUID + queryText`\n */\nconst cache = new Map();\nconst DEFAULT_TTL_MS = 200;\nfunction makeKey(perspectiveUUID, queryText) {\n return `${perspectiveUUID}:${queryText}`;\n}\n/**\n * Get a cached query result if it exists and hasn't expired.\n */\nfunction getCachedResult(perspectiveUUID, queryText) {\n const key = makeKey(perspectiveUUID, queryText);\n const entry = cache.get(key);\n if (!entry)\n return undefined;\n if (Date.now() > entry.expiry) {\n cache.delete(key);\n return undefined;\n }\n return entry.result;\n}\n/**\n * Store a query result in the cache with TTL.\n */\nfunction setCachedResult(perspectiveUUID, queryText, result, ttlMs = DEFAULT_TTL_MS) {\n // Lazy eviction of expired entries\n const now = Date.now();\n for (const [key, entry] of cache) {\n if (now > entry.expiry) {\n cache.delete(key);\n }\n }\n const cacheKey = makeKey(perspectiveUUID, queryText);\n cache.set(cacheKey, { result, expiry: now + ttlMs });\n}\n/**\n * Invalidate all cache entries for a given perspective.\n * Called after write operations to ensure stale data isn't served.\n */\nfunction invalidatePerspectiveCache(perspectiveUUID) {\n const prefix = perspectiveUUID + ':';\n for (const [key] of cache) {\n if (key.startsWith(prefix)) {\n cache.delete(key);\n }\n }\n}\n/**\n * Clear all cache entries (useful for testing).\n */\nfunction clearQueryCache() {\n cache.clear();\n}\n/**\n * Get the current size of the cache (useful for testing).\n */\nfunction queryCacheSize() {\n return cache.size;\n}\n\n/**\n * SHACL Flow - represents a state machine for AD4M expressions\n *\n * Flows define:\n * - Which expressions can enter the flow (flowable condition)\n * - What states exist and how to detect them (via link patterns)\n * - How to transition between states (via actions)\n *\n * @example\n * ```typescript\n * const todoFlow = new SHACLFlow('todo://TODO', 'todo://');\n *\n * // Any expression can become a TODO\n * todoFlow.flowable = 'any';\n *\n * // Define states\n * todoFlow.addState({\n * name: 'ready',\n * value: 0,\n * stateCheck: { predicate: 'todo://state', target: 'todo://ready' }\n * });\n * todoFlow.addState({\n * name: 'doing',\n * value: 0.5,\n * stateCheck: { predicate: 'todo://state', target: 'todo://doing' }\n * });\n * todoFlow.addState({\n * name: 'done',\n * value: 1,\n * stateCheck: { predicate: 'todo://state', target: 'todo://done' }\n * });\n *\n * // Define start action\n * todoFlow.startAction = [{\n * action: 'addLink',\n * source: 'this',\n * predicate: 'todo://state',\n * target: 'todo://ready'\n * }];\n *\n * // Define transitions\n * todoFlow.addTransition({\n * actionName: 'Start',\n * fromState: 'ready',\n * toState: 'doing',\n * actions: [\n * { action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://doing' },\n * { action: 'removeLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }\n * ]\n * });\n *\n * // Store in perspective\n * await perspective.addFlow('TODO', todoFlow);\n * ```\n */\nclass SHACLFlow {\n /**\n * Create a new SHACL Flow\n * @param name - Flow name (e.g., \"TODO\")\n * @param namespace - Namespace for URIs (e.g., \"todo://\")\n */\n constructor(name, namespace) {\n /** Condition for which expressions can start this flow */\n this.flowable = \"any\";\n /** Actions to execute when starting the flow */\n this.startAction = [];\n /** States in this flow */\n this._states = [];\n /** Transitions between states */\n this._transitions = [];\n this.name = name;\n this.namespace = namespace;\n }\n /** Get all states */\n get states() {\n return [...this._states];\n }\n /** Get all transitions */\n get transitions() {\n return [...this._transitions];\n }\n /**\n * Add a state to the flow\n * @param state - State definition\n */\n addState(state) {\n this._states.push(state);\n }\n /**\n * Add a transition to the flow\n * @param transition - Transition definition\n */\n addTransition(transition) {\n this._transitions.push(transition);\n }\n /**\n * Get the flow shape URI\n */\n get flowUri() {\n return `${this.namespace}${this.name}Flow`;\n }\n /**\n * Get a state URI\n */\n stateUri(stateName) {\n return `${this.namespace}${this.name}.${stateName}`;\n }\n /**\n * Get a transition URI\n */\n transitionUri(fromState, toState) {\n return `${this.namespace}${this.name}.${fromState}To${toState}`;\n }\n /**\n * Serialize the flow to AD4M links\n * These links can be stored in a perspective and queried via SPARQL\n *\n * @returns Array of Link objects representing the flow\n */\n toLinks() {\n const links = [];\n const flowUri = this.flowUri;\n // Flow type\n links.push({\n source: flowUri,\n predicate: \"rdf://type\",\n target: \"ad4m://Flow\"\n });\n // Flow name\n links.push({\n source: flowUri,\n predicate: \"ad4m://flowName\",\n target: Literal.from(this.name).toUrl()\n });\n // Flowable condition\n if (this.flowable === \"any\") {\n links.push({\n source: flowUri,\n predicate: \"ad4m://flowable\",\n target: \"ad4m://any\"\n });\n }\n else {\n links.push({\n source: flowUri,\n predicate: \"ad4m://flowable\",\n target: `literal:string:${encodeURIComponent(JSON.stringify(this.flowable))}`\n });\n }\n // Start action\n if (this.startAction.length > 0) {\n links.push({\n source: flowUri,\n predicate: \"ad4m://startAction\",\n target: `literal:string:${encodeURIComponent(JSON.stringify(this.startAction))}`\n });\n }\n // States\n for (const state of this._states) {\n const stateUri = this.stateUri(state.name);\n // Link flow to state\n links.push({\n source: flowUri,\n predicate: \"ad4m://hasState\",\n target: stateUri\n });\n // State type\n links.push({\n source: stateUri,\n predicate: \"rdf://type\",\n target: \"ad4m://FlowState\"\n });\n // State name\n links.push({\n source: stateUri,\n predicate: \"ad4m://stateName\",\n target: Literal.from(state.name).toUrl()\n });\n // State value\n links.push({\n source: stateUri,\n predicate: \"ad4m://stateValue\",\n target: Literal.from(state.value).toUrl()\n });\n // State check pattern\n links.push({\n source: stateUri,\n predicate: \"ad4m://stateCheck\",\n target: `literal:string:${encodeURIComponent(JSON.stringify(state.stateCheck))}`\n });\n }\n // Transitions\n for (const transition of this._transitions) {\n const transitionUri = this.transitionUri(transition.fromState, transition.toState);\n const fromStateUri = this.stateUri(transition.fromState);\n const toStateUri = this.stateUri(transition.toState);\n // Link flow to transition\n links.push({\n source: flowUri,\n predicate: \"ad4m://hasTransition\",\n target: transitionUri\n });\n // Transition type\n links.push({\n source: transitionUri,\n predicate: \"rdf://type\",\n target: \"ad4m://FlowTransition\"\n });\n // Action name\n links.push({\n source: transitionUri,\n predicate: \"ad4m://actionName\",\n target: Literal.from(transition.actionName).toUrl()\n });\n // From state\n links.push({\n source: transitionUri,\n predicate: \"ad4m://fromState\",\n target: fromStateUri\n });\n // To state\n links.push({\n source: transitionUri,\n predicate: \"ad4m://toState\",\n target: toStateUri\n });\n // Transition actions\n links.push({\n source: transitionUri,\n predicate: \"ad4m://transitionActions\",\n target: `literal:string:${encodeURIComponent(JSON.stringify(transition.actions))}`\n });\n }\n return links;\n }\n /**\n * Reconstruct a SHACLFlow from links\n *\n * @param links - Array of links containing the flow definition\n * @param flowUri - The URI of the flow to reconstruct\n * @returns Reconstructed SHACLFlow\n */\n static fromLinks(links, flowUri) {\n // Extract namespace and name from flowUri\n // Format: {namespace}{Name}Flow\n const flowSuffix = \"Flow\";\n if (!flowUri.endsWith(flowSuffix)) {\n throw new Error(`Invalid flow URI: ${flowUri} (must end with 'Flow')`);\n }\n const withoutSuffix = flowUri.slice(0, -flowSuffix.length);\n const lastSlashOrColon = Math.max(withoutSuffix.lastIndexOf('/'), withoutSuffix.lastIndexOf(':'));\n const namespace = withoutSuffix.slice(0, lastSlashOrColon + 1);\n const name = withoutSuffix.slice(lastSlashOrColon + 1);\n const flow = new SHACLFlow(name, namespace);\n // Find flowable condition\n const flowableLink = links.find(l => l.source === flowUri && l.predicate === \"ad4m://flowable\");\n if (flowableLink) {\n if (flowableLink.target === \"ad4m://any\") {\n flow.flowable = \"any\";\n }\n else {\n try {\n const jsonStr = flowableLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n flow.flowable = JSON.parse(decodeURIComponent(jsonStr));\n }\n catch {\n flow.flowable = \"any\";\n }\n }\n }\n // Find start action\n const startActionLink = links.find(l => l.source === flowUri && l.predicate === \"ad4m://startAction\");\n if (startActionLink) {\n try {\n const jsonStr = startActionLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n flow.startAction = JSON.parse(decodeURIComponent(jsonStr));\n }\n catch {\n // Ignore parse errors\n }\n }\n // Find states\n const stateLinks = links.filter(l => l.source === flowUri && l.predicate === \"ad4m://hasState\");\n // Build a map from state URI to state name for later lookup\n const stateUriToName = new Map();\n for (const stateLink of stateLinks) {\n const stateUri = stateLink.target;\n // Get state name\n const nameLink = links.find(l => l.source === stateUri && l.predicate === \"ad4m://stateName\");\n const stateName = nameLink ? Literal.fromUrl(nameLink.target).get() : \"\";\n // Store mapping for transition lookup\n stateUriToName.set(stateUri, stateName);\n // Get state value\n const valueLink = links.find(l => l.source === stateUri && l.predicate === \"ad4m://stateValue\");\n const stateValue = valueLink ? Literal.fromUrl(valueLink.target).get() : 0;\n // Get state check\n const checkLink = links.find(l => l.source === stateUri && l.predicate === \"ad4m://stateCheck\");\n let stateCheck = { predicate: \"\", target: \"\" };\n if (checkLink) {\n try {\n const jsonStr = checkLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n stateCheck = JSON.parse(decodeURIComponent(jsonStr));\n }\n catch {\n // Ignore parse errors\n }\n }\n flow.addState({ name: stateName, value: stateValue, stateCheck });\n }\n // Find transitions\n const transitionLinks = links.filter(l => l.source === flowUri && l.predicate === \"ad4m://hasTransition\");\n for (const transitionLink of transitionLinks) {\n const transitionUri = transitionLink.target;\n // Get action name\n const actionNameLink = links.find(l => l.source === transitionUri && l.predicate === \"ad4m://actionName\");\n const actionName = actionNameLink ? Literal.fromUrl(actionNameLink.target).get() : \"\";\n // Get from state\n const fromStateLink = links.find(l => l.source === transitionUri && l.predicate === \"ad4m://fromState\");\n const fromStateUri = fromStateLink?.target || \"\";\n const fromState = stateUriToName.get(fromStateUri) || \"\";\n // Get to state\n const toStateLink = links.find(l => l.source === transitionUri && l.predicate === \"ad4m://toState\");\n const toStateUri = toStateLink?.target || \"\";\n const toState = stateUriToName.get(toStateUri) || \"\";\n // Get actions\n const actionsLink = links.find(l => l.source === transitionUri && l.predicate === \"ad4m://transitionActions\");\n let actions = [];\n if (actionsLink) {\n try {\n const jsonStr = actionsLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n actions = JSON.parse(decodeURIComponent(jsonStr));\n }\n catch {\n // Ignore parse errors\n }\n }\n flow.addTransition({ actionName, fromState, toState, actions });\n }\n return flow;\n }\n /**\n * Convert to JSON representation\n */\n toJSON() {\n return {\n name: this.name,\n namespace: this.namespace,\n flowable: this.flowable,\n startAction: this.startAction,\n states: this._states,\n transitions: this._transitions\n };\n }\n /**\n * Create from JSON representation\n */\n static fromJSON(json) {\n const flow = new SHACLFlow(json.name, json.namespace);\n flow.flowable = json.flowable || \"any\";\n flow.startAction = json.startAction || [];\n for (const state of json.states || []) {\n flow.addState(state);\n }\n for (const transition of json.transitions || []) {\n flow.addTransition(transition);\n }\n return flow;\n }\n}\n\nvar __classPrivateFieldSet$a = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$a = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, _PerspectiveProxy_ensuredSubjectClasses;\n/** Extract namespace prefix from a URI (everything up to and including the last / or #) */\nfunction extractNamespaceFromUri(uri) {\n const hashIdx = uri.lastIndexOf('#');\n if (hashIdx >= 0)\n return uri.substring(0, hashIdx + 1);\n const slashIdx = uri.lastIndexOf('/');\n if (slashIdx >= 0)\n return uri.substring(0, slashIdx + 1);\n const colonIdx = uri.lastIndexOf(':');\n if (colonIdx >= 0)\n return uri.substring(0, colonIdx + 1);\n return uri;\n}\n/** Proxy object for a subscribed Prolog query that provides real-time updates\n *\n * This class handles:\n * - Keeping the subscription alive by sending periodic keepalive signals\n * - Managing callbacks for result updates\n * - Subscribing to query updates via WebSocket subscriptions\n * - Maintaining the latest query result\n * - Ensuring subscription is fully initialized before allowing access\n * - Cleaning up resources when disposed\n *\n * The subscription will remain active as long as keepalive signals are sent.\n * Make sure to call dispose() when you're done with the subscription to clean up\n * resources, stop keepalive signals, and notify the backend to remove the subscription.\n *\n * The subscription goes through an initialization process where it waits for the first\n * result to come through the subscription channel. You can await the `initialized`\n * promise to ensure the subscription is ready. The initialization will timeout after\n * 30 seconds if no result is received.\n *\n * Example usage:\n * ```typescript\n * const subscription = await perspective.subscribeInfer(\"my_query(X)\");\n * // At this point the subscription is already initialized since subscribeInfer waits\n *\n * // Set up callback for future updates\n * const removeCallback = subscription.onResult(result => {\n * console.log(\"New result:\", result);\n * });\n *\n * // Later: clean up subscription and notify backend\n * subscription.dispose();\n * ```\n */\nclass QuerySubscriptionProxy {\n /** Creates a new query subscription\n * @param uuid - The UUID of the perspective\n * @param query - The Prolog query to subscribe to\n * @param client - The PerspectiveClient instance to use for communication\n */\n constructor(uuid, query, client) {\n _QuerySubscriptionProxy_instances.add(this);\n _QuerySubscriptionProxy_uuid.set(this, void 0);\n _QuerySubscriptionProxy_subscriptionId.set(this, void 0);\n _QuerySubscriptionProxy_client.set(this, void 0);\n _QuerySubscriptionProxy_callbacks.set(this, void 0);\n _QuerySubscriptionProxy_keepaliveTimer.set(this, void 0);\n _QuerySubscriptionProxy_unsubscribe.set(this, void 0);\n _QuerySubscriptionProxy_latestResult.set(this, void 0);\n _QuerySubscriptionProxy_disposed.set(this, false);\n _QuerySubscriptionProxy_initialized.set(this, void 0);\n _QuerySubscriptionProxy_initResolve.set(this, void 0);\n _QuerySubscriptionProxy_initReject.set(this, void 0);\n _QuerySubscriptionProxy_initTimeoutId.set(this, void 0);\n _QuerySubscriptionProxy_query.set(this, void 0);\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_uuid, uuid, \"f\");\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_query, query, \"f\");\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_client, client, \"f\");\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_callbacks, new Set(), \"f\");\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, null, \"f\");\n // Create the promise once and store its resolve/reject\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, resolve, \"f\");\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, reject, \"f\");\n }), \"f\");\n }\n async subscribe() {\n // Clean up previous subscription attempt if retrying\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, \"f\")) {\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, \"f\").call(this);\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, undefined, \"f\");\n }\n // Clear any existing timeout\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, \"f\")) {\n clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, \"f\"));\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, \"f\");\n }\n // Clear any existing keepalive timer to prevent accumulation\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, \"f\")) {\n clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, \"f\"));\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, undefined, \"f\");\n }\n try {\n // Initialize the query subscription\n let initialResult;\n initialResult = await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, \"f\").subscribeQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, \"f\"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, \"f\"));\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_subscriptionId, initialResult.subscriptionId, \"f\");\n // Process the initial result immediately for fast UX.\n // The subscribeQuery() RPC call already returns the initial result,\n // so treat that as successful initialization instead of waiting for a\n // follow-up WebSocket update that may never arrive until the query changes.\n if (initialResult.result !== undefined) {\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, initialResult.result, \"f\");\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, \"m\", _QuerySubscriptionProxy_notifyCallbacks).call(this, initialResult.result);\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, \"f\")) {\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, \"f\").call(this, true);\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, \"f\");\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, \"f\");\n }\n }\n else {\n console.warn('\u26A0\uFE0F No initial result returned from subscribeQuery!');\n // Only keep the initialization timeout when the backend did not\n // provide an initial result up front.\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, setTimeout(() => {\n console.error('Subscription initialization timed out after 30 seconds. Resubscribing...');\n // Recursively retry subscription, catching any errors\n this.subscribe().catch(error => {\n console.error('Error during subscription retry after timeout:', error);\n });\n }, 30000), \"f\");\n }\n // Subscribe to query updates\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, \"f\").subscribeToQueryUpdates(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, \"f\"), (updateResult) => {\n // Clear timeout on first message\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, \"f\")) {\n clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, \"f\"));\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, \"f\");\n }\n // Resolve the initialization promise (only resolves once)\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, \"f\")) {\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, \"f\").call(this, true);\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, \"f\"); // Prevent double-resolve\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, \"f\");\n }\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, updateResult, \"f\");\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, \"m\", _QuerySubscriptionProxy_notifyCallbacks).call(this, updateResult);\n }), \"f\");\n }\n catch (error) {\n console.error('Error setting up subscription:', error);\n // Reject the promise if this is the first attempt\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initReject, \"f\")) {\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initReject, \"f\").call(this, error);\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, \"f\");\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, \"f\");\n }\n throw error; // Re-throw so caller knows it failed\n }\n // Start keepalive loop using platform-agnostic setTimeout\n const keepaliveLoop = async () => {\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, \"f\"))\n return;\n try {\n await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, \"f\").keepAliveQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, \"f\"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, \"f\"));\n }\n catch (e) {\n console.error('Error in keepalive:', e);\n // try to reinitialize the subscription\n console.log('Reinitializing subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, \"f\"));\n try {\n await this.subscribe();\n console.log('Subscription reinitialized');\n }\n catch (resubscribeError) {\n console.error('Error during resubscription from keepalive:', resubscribeError);\n // Don't schedule another keepalive on resubscribe failure\n return;\n }\n }\n // Schedule next keepalive if not disposed\n if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, \"f\")) {\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), \"f\");\n }\n };\n // Start the first keepalive loop\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), \"f\");\n }\n /** Get the subscription ID for this query subscription\n *\n * This is a unique identifier assigned when the subscription was created.\n * It can be used to reference this specific subscription, for example when\n * sending keepalive signals.\n *\n * @returns The subscription ID string\n */\n get id() {\n return __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, \"f\");\n }\n /** Promise that resolves when the subscription has received its first result\n * through the subscription channel. This ensures the subscription is fully\n * set up before allowing access to results or updates.\n *\n * If no result is received within 30 seconds, the subscription will automatically\n * retry. The promise will remain pending until a subscription message successfully\n * arrives, or until a fatal error occurs during subscription setup.\n *\n * Note: You typically don't need to await this directly since the subscription\n * creation methods (like subscribeInfer) already wait for initialization.\n */\n get initialized() {\n return __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initialized, \"f\");\n }\n /** Get the latest query result\n *\n * This returns the most recent result from the query, which could be either:\n * - The initial result from when the subscription was created\n * - The latest update received through the subscription\n *\n * @returns The latest query result as a string (usually a JSON array of bindings)\n */\n get result() {\n return __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_latestResult, \"f\");\n }\n /** Add a callback that will be called whenever new results arrive\n *\n * The callback will be called immediately with the current result,\n * and then again each time the query results change.\n *\n * @param callback - Function that takes a result string and processes it\n * @returns A function that can be called to remove this callback\n *\n * Example:\n * ```typescript\n * const removeCallback = subscription.onResult(result => {\n * const bindings = JSON.parse(result);\n * console.log(\"New bindings:\", bindings);\n * });\n *\n * // Later: stop receiving updates\n * removeCallback();\n * ```\n */\n onResult(callback) {\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, \"f\").add(callback);\n return () => __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, \"f\").delete(callback);\n }\n /** Clean up the subscription and stop keepalive signals\n *\n * This method:\n * 1. Stops the keepalive timer\n * 2. Unsubscribes from subscription updates\n * 3. Clears all registered callbacks\n * 4. Cleans up any pending initialization timeout\n *\n * After calling this method, the subscription is no longer active and\n * will not receive any more updates. The instance should be discarded.\n */\n dispose() {\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_disposed, true, \"f\");\n clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, \"f\"));\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, \"f\")) {\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, \"f\").call(this);\n }\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, \"f\").clear();\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, \"f\")) {\n clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, \"f\"));\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, \"f\");\n }\n // Tell the backend to dispose of the subscription\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, \"f\")) {\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, \"f\").disposeQuerySubscription(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, \"f\"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, \"f\"))\n .catch(e => console.error('Error disposing query subscription:', e));\n }\n }\n}\n_QuerySubscriptionProxy_uuid = new WeakMap(), _QuerySubscriptionProxy_subscriptionId = new WeakMap(), _QuerySubscriptionProxy_client = new WeakMap(), _QuerySubscriptionProxy_callbacks = new WeakMap(), _QuerySubscriptionProxy_keepaliveTimer = new WeakMap(), _QuerySubscriptionProxy_unsubscribe = new WeakMap(), _QuerySubscriptionProxy_latestResult = new WeakMap(), _QuerySubscriptionProxy_disposed = new WeakMap(), _QuerySubscriptionProxy_initialized = new WeakMap(), _QuerySubscriptionProxy_initResolve = new WeakMap(), _QuerySubscriptionProxy_initReject = new WeakMap(), _QuerySubscriptionProxy_initTimeoutId = new WeakMap(), _QuerySubscriptionProxy_query = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {\n for (const callback of __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, \"f\")) {\n try {\n callback(result);\n }\n catch (e) {\n console.error('Error in query subscription callback:', e);\n }\n }\n};\n/**\n * PerspectiveProxy provides a high-level interface for working with AD4M Perspectives - agent-centric semantic graphs\n * that store and organize links between expressions.\n *\n * A Perspective is fundamentally a collection of links (subject-predicate-object triples) that represent an agent's view\n * of their digital world. Through PerspectiveProxy, you can:\n * - Add, remove, and query links\n * - Work with Social DNA (subject classes and flows)\n * - Subscribe to real-time updates\n * - Share perspectives as Neighbourhoods\n * - Execute Prolog queries for complex graph patterns\n *\n *\n * @example\n * ```typescript\n * // Create and work with links\n * const perspective = await ad4m.perspective.add(\"My Space\");\n * await perspective.add({\n * source: \"did:key:alice\",\n * predicate: \"knows\",\n * target: \"did:key:bob\"\n * });\n *\n * // Query links\n * const friends = await perspective.get({\n * source: \"did:key:alice\",\n * predicate: \"knows\"\n * });\n *\n * // Use Social DNA\n * await perspective.addSdna(todoClass, \"subject_class\");\n * const todo = await perspective.createSubject(\"Todo\", \"expression://123\");\n *\n * // Subscribe to changes\n * perspective.addListener(\"link-added\", (link) => {\n * console.log(\"New link added:\", link);\n * });\n * ```\n */\nclass PerspectiveProxy {\n /** @internal Exposed for ModelQueryBuilder subscription management */\n get client() { return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\"); }\n /**\n * Creates a new PerspectiveProxy instance.\n * Note: Don't create this directly, use ad4m.perspective.add() instead.\n */\n constructor(handle, ad4m) {\n _PerspectiveProxy_handle.set(this, void 0);\n _PerspectiveProxy_client.set(this, void 0);\n _PerspectiveProxy_perspectiveLinkAddedCallbacks.set(this, void 0);\n _PerspectiveProxy_perspectiveLinkRemovedCallbacks.set(this, void 0);\n _PerspectiveProxy_perspectiveLinkUpdatedCallbacks.set(this, void 0);\n _PerspectiveProxy_perspectiveSyncStateChangeCallbacks.set(this, void 0);\n _PerspectiveProxy_ensuredSubjectClasses.set(this, new Set()\n /**\n * Creates a new PerspectiveProxy instance.\n * Note: Don't create this directly, use ad4m.perspective.add() instead.\n */\n );\n __classPrivateFieldSet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, [], \"f\");\n __classPrivateFieldSet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, [], \"f\");\n __classPrivateFieldSet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, [], \"f\");\n __classPrivateFieldSet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, [], \"f\");\n __classPrivateFieldSet$a(this, _PerspectiveProxy_handle, handle, \"f\");\n __classPrivateFieldSet$a(this, _PerspectiveProxy_client, ad4m, \"f\");\n this.uuid = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid;\n this.name = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").name;\n this.owners = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").owners;\n this.sharedUrl = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").sharedUrl;\n this.neighbourhood = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").neighbourhood;\n this.state = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").state;\n __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addPerspectiveLinkAddedListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, \"f\"));\n __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addPerspectiveLinkRemovedListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, \"f\"));\n __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addPerspectiveLinkUpdatedListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, \"f\"));\n __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addPerspectiveSyncStateChangeListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, \"f\"));\n }\n /** Update the proxy's internal handle and public fields in-place.\n * Keeps the same object reference so all holders see the update. */\n updateHandle(handle) {\n if (handle.uuid !== __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid) {\n throw new Error(`PerspectiveProxy.updateHandle: UUID mismatch \u2014 proxy is bound to \"${__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid}\" but received handle with UUID \"${handle.uuid}\". ` +\n `This would silently diverge from listeners registered under the original UUID.`);\n }\n __classPrivateFieldSet$a(this, _PerspectiveProxy_handle, handle, \"f\");\n this.uuid = handle.uuid;\n this.name = handle.name;\n this.owners = handle.owners;\n this.sharedUrl = handle.sharedUrl;\n this.neighbourhood = handle.neighbourhood;\n this.state = handle.state;\n }\n /**\n * Escapes special regex characters in a string to prevent ReDoS attacks\n * and regex injection when building dynamic regular expressions.\n *\n * @param str - The string to escape\n * @returns The escaped string safe for use in RegExp constructor\n *\n * @private\n */\n escapeRegExp(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n }\n /**\n * Executes a set of actions on an expression with optional parameters.\n * Used internally by Social DNA flows and subject class operations.\n *\n * Actions are specified as an array of commands that modify links in the perspective.\n * Each action is an object with the following format:\n * ```typescript\n * {\n * action: \"addLink\" | \"removeLink\" | \"setSingleTarget\" | \"collectionSetter\",\n * source: string, // Usually \"this\" to reference the current expression\n * predicate: string, // The predicate URI\n * target: string // The target value or \"value\" for parameters\n * }\n * ```\n *\n * Available commands:\n * - `addLink`: Creates a new link\n * - `removeLink`: Removes an existing link\n * - `setSingleTarget`: Removes all existing links with the same source/predicate and adds a new one\n * - `collectionSetter`: Special command for setting relation properties\n *\n * When used with parameters, the special value \"value\" in the target field will be\n * replaced with the actual parameter value.\n *\n * @example\n * ```typescript\n * // Add a state link and remove an old one\n * await perspective.executeAction([\n * {\n * action: \"addLink\",\n * source: \"this\",\n * predicate: \"todo://state\",\n * target: \"todo://doing\"\n * },\n * {\n * action: \"removeLink\",\n * source: \"this\",\n * predicate: \"todo://state\",\n * target: \"todo://ready\"\n * }\n * ], \"expression://123\");\n *\n * // Set a property using a parameter\n * await perspective.executeAction([\n * {\n * action: \"setSingleTarget\",\n * source: \"this\",\n * predicate: \"todo://title\",\n * target: \"value\"\n * }\n * ], \"expression://123\", [\n * { name: \"title\", value: \"New Title\" }\n * ]);\n * ```\n *\n * @param actions - Array of action objects to execute\n * @param expression - Target expression address (replaces \"this\" in actions)\n * @param parameters - Optional parameters that replace \"value\" in actions\n * @param batchId - Optional batch ID to group this operation with others\n */\n async executeAction(actions, expression, parameters, batchId) {\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").executeCommands(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);\n invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n return result;\n }\n /**\n * Retrieves links from the perspective that match the given query.\n *\n * @param query - Query parameters to filter links\n * @returns Array of matching LinkExpressions\n *\n * @example\n * ```typescript\n * // Get all links where Alice knows someone\n * const links = await perspective.get({\n * source: \"did:key:alice\",\n * predicate: \"knows\"\n * });\n *\n * // Get all comments on a post\n * const comments = await perspective.get({\n * source: \"post://123\",\n * predicate: \"comment\"\n * });\n * ```\n */\n async get(query) {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").queryLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, query);\n }\n /**\n * Executes a Prolog query against the perspective's knowledge base.\n * This is a powerful way to find complex patterns in the graph.\n *\n * @param query - Prolog query string\n * @returns Query results or false if no results\n *\n * @example\n * ```typescript\n * // Find friends of friends\n * const results = await perspective.infer(`\n * triple(A, \"knows\", B),\n * triple(B, \"knows\", C),\n * A \\= C\n * `);\n *\n * // Find all active todos\n * const todos = await perspective.infer(`\n * instance(Todo, \"Todo\"),\n * property_getter(\"Todo\", Todo, \"state\", \"active\")\n * `);\n * ```\n */\n async infer(query) {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").queryProlog(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, query);\n }\n /**\n * Executes a SPARQL query against the perspective's link cache.\n * This allows powerful SQL-like queries on the link data stored in SPARQL.\n *\n * **Security Note:** Only read-only queries (SELECT, RETURN, etc.) are permitted.\n * Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are\n * blocked for security reasons. Use the perspective's add/remove methods to modify links.\n *\n * @param query - SPARQL query string (read-only operations only)\n * @returns Query results as parsed JSON\n *\n * Executes a SPARQL query against the perspective's RDF (Oxigraph) store.\n *\n * @param query - SPARQL query string\n * @returns Query results as parsed JSON\n */\n async querySparql(query) {\n const cached = getCachedResult(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, query);\n if (cached !== undefined)\n return cached;\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").querySparql(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, query);\n setCachedResult(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, query, result);\n return result;\n }\n /**\n * Execute a model query \u2014 the executor-side replacement for SPARQL query building + JS hydration.\n *\n * @param className - The model class name (e.g. \"Recipe\")\n * @param queryJson - Structured query as JSON string\n * @param shapeJson - Optional shape metadata JSON from the model class\n * @returns Object with `instances` array and `totalCount`\n */\n async modelQuery(className, queryJson, shapeJson) {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, className, queryJson, shapeJson);\n }\n /**\n * Evaluate property getters for a batch of instances in a single RPC call.\n * Returns a map of `{ instanceId: { prop: value, ... } }`.\n *\n * Use this instead of `Ad4mModel.evaluateGetters()` for lazy-loading\n * getter-backed properties on visible items (e.g. `replyingTo` on messages).\n *\n * @param className - The model class name (e.g. \"Message\")\n * @param instanceIds - Array of instance base expression URIs\n * @param shapeJson - Shape metadata JSON from the model class\n * @param propertyNames - Optional subset of property names to evaluate\n * @returns Map of instance ID \u2192 evaluated property values\n */\n async evaluateGetters(className, instanceIds, shapeJson, propertyNames) {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").evaluateGetters(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, className, instanceIds, shapeJson, propertyNames);\n }\n /**\n * Subscribe to model query changes. Builds trigger SPARQL from the model shape\n * internally in Rust, registers a subscription, runs the initial query, and\n * pushes updated results when relevant links change.\n *\n * The subscription reuses the same GraphQL subscription channel as subscribeQuery().\n * Use keepAliveQuery() / disposeQuerySubscription() with the returned subscriptionId.\n *\n * @param className - The model class name\n * @param queryJson - JSON-serialized query parameters (same as modelQuery)\n * @param shapeJson - Optional shape metadata JSON from the model class\n * @returns Object with `subscriptionId` and initial `result`\n */\n async modelSubscribe(className, queryJson, shapeJson) {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").modelSubscribe(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, className, queryJson, shapeJson);\n }\n /**\n * Adds a new link to the perspective.\n *\n * @param link - The link to add\n * @param status - Whether the link should be shared in a Neighbourhood\n * @param batchId - Optional batch ID to group this operation with others\n * @returns The created LinkExpression\n *\n * @example\n * ```typescript\n * // Add a simple relationship\n * await perspective.add({\n * source: \"did:key:alice\",\n * predicate: \"follows\",\n * target: \"did:key:bob\"\n * });\n *\n * // Add a local-only link\n * await perspective.add({\n * source: \"note://123\",\n * predicate: \"tag\",\n * target: \"private\"\n * }, \"local\");\n * ```\n */\n async add(link, status = 'shared', batchId) {\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, link, status, batchId);\n invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n return result;\n }\n /**\n * Adds multiple links to the perspective in a single operation.\n * More efficient than adding links one by one.\n *\n * @param links - Array of links to add\n * @param status - Whether the links should be shared\n * @param batchId - Optional batch ID to group this operation with others\n * @returns Array of created LinkExpressions\n */\n async addLinks(links, status = 'shared', batchId) {\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, links, status, batchId);\n invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n return result;\n }\n /**\n * Removes multiple links from the perspective.\n *\n * @param links - Array of links to remove\n * @param batchId - Optional batch ID to group this operation with others\n * @returns Array of removed LinkExpressions\n */\n async removeLinks(links, batchId) {\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").removeLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, links, batchId);\n invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n return result;\n }\n /**\n * Applies a set of link mutations (adds and removes) in a single operation.\n * Useful for atomic updates to the perspective.\n *\n * @param mutations - Object containing links to add and remove\n * @param status - Whether new links should be shared\n * @returns Object containing results of the mutations\n */\n async linkMutations(mutations, status = 'shared') {\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").linkMutations(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, mutations, status);\n invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n return result;\n }\n /**\n * Adds a pre-signed LinkExpression to the perspective.\n *\n * @param link - The signed LinkExpression to add\n * @param status - Whether the link should be shared\n * @param batchId - Optional batch ID to group this operation with others\n * @returns The added LinkExpression\n */\n async addLinkExpression(link, status = 'shared', batchId) {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addLinkExpression(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, link, status, batchId);\n }\n /**\n * Updates an existing link with new data.\n *\n * @param oldLink - The existing link to update\n * @param newLink - The new link data\n * @param batchId - Optional batch ID to group this operation with others\n */\n async update(oldLink, newLink, batchId) {\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").updateLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, oldLink, newLink, batchId);\n invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n return result;\n }\n /**\n * Removes a link from the perspective.\n *\n * @param link - The link to remove\n * @param batchId - Optional batch ID to group this operation with others\n */\n async remove(link, batchId) {\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").removeLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, link, batchId);\n invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n return result;\n }\n /** Creates a new batch for grouping operations */\n async createBatch() {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").createBatch(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n }\n /** Commits a batch of operations */\n async commitBatch(batchId) {\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").commitBatch(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, batchId);\n invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n return result;\n }\n /**\n * Retrieves and renders an Expression referenced in this perspective.\n *\n * @param expressionURI - URI of the Expression to retrieve\n * @returns The rendered Expression\n */\n async getExpression(expressionURI) {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").getExpression(expressionURI);\n }\n /**\n * Creates a new Expression in the specified Language.\n *\n * @param content - Content for the new Expression\n * @param languageAddress - Address of the Language to use\n * @returns URI of the created Expression\n */\n async createExpression(content, languageAddress) {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").createExpression(content, languageAddress);\n }\n /**\n * Subscribes to link changes in the perspective.\n *\n * @param type - Type of change to listen for\n * @param cb - Callback function\n *\n * @example\n * ```typescript\n * // Listen for new links\n * perspective.addListener(\"link-added\", (link) => {\n * console.log(\"New link:\", link);\n * });\n *\n * // Listen for removed links\n * perspective.addListener(\"link-removed\", (link) => {\n * console.log(\"Link removed:\", link);\n * });\n * ```\n */\n async addListener(type, cb) {\n if (type === 'link-added') {\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, \"f\").push(cb);\n }\n else if (type === 'link-removed') {\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, \"f\").push(cb);\n }\n else if (type === 'link-updated') {\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, \"f\").push(cb);\n }\n }\n /**\n * Subscribes to sync state changes if this perspective is shared.\n *\n * @param cb - Callback function\n *\n * @example\n * ```typescript\n * perspective.addSyncStateChangeListener((state) => {\n * console.log(\"Sync state:\", state);\n * });\n * ```\n */\n async addSyncStateChangeListener(cb) {\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, \"f\").push(cb);\n }\n /**\n * Unsubscribes from link changes.\n *\n * @param type - Type of change to stop listening for\n * @param cb - The callback function to remove\n */\n async removeListener(type, cb) {\n if (type === 'link-added') {\n const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, \"f\").indexOf(cb);\n if (index >= 0)\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, \"f\").splice(index, 1);\n }\n else if (type === 'link-removed') {\n const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, \"f\").indexOf(cb);\n if (index >= 0)\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, \"f\").splice(index, 1);\n }\n else if (type === 'link-updated') {\n const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, \"f\").indexOf(cb);\n if (index >= 0)\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, \"f\").splice(index, 1);\n }\n }\n /** Clean up all subscriptions registered by this proxy.\n * Call this when the proxy is no longer needed to prevent subscription leaks.\n * After calling dispose(), the proxy should not be used. */\n dispose() {\n __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").removeAllListeners(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, \"f\").length = 0;\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, \"f\").length = 0;\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, \"f\").length = 0;\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, \"f\").length = 0;\n }\n /**\n * Creates a snapshot of the current perspective state.\n * Useful for backup or sharing.\n *\n * @returns Perspective object containing all links\n */\n async snapshot() {\n return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").snapshotByUUID(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n }\n /**\n * Loads a perspective snapshot, replacing current content.\n *\n * @param snapshot - Perspective snapshot to load\n */\n async loadSnapshot(snapshot) {\n //Clean the input data from __typename\n const cleanedSnapshot = JSON.parse(JSON.stringify(snapshot));\n delete cleanedSnapshot.__typename;\n cleanedSnapshot.links.forEach(link => {\n delete link.data.__typename;\n });\n for (const link of cleanedSnapshot.links) {\n await this.addLinkExpression(link);\n }\n }\n /**\n * Gets a single target value matching a query.\n * Useful when you expect only one result.\n *\n * @param query - Query to find the target\n * @returns Target value or void if not found\n *\n * @example\n * ```typescript\n * // Get a user's name\n * const name = await perspective.getSingleTarget({\n * source: \"did:key:alice\",\n * predicate: \"name\"\n * });\n * ```\n */\n async getSingleTarget(query) {\n delete query.target;\n const foundLinks = await this.get(query);\n if (foundLinks.length)\n return foundLinks[0].data.target;\n else\n return null;\n }\n /**\n * Sets a single target value, removing any existing targets.\n *\n * @param link - Link defining the new target\n * @param status - Whether the link should be shared\n *\n * @example\n * ```typescript\n * // Set a user's status\n * await perspective.setSingleTarget({\n * source: \"did:key:alice\",\n * predicate: \"status\",\n * target: \"online\"\n * });\n * ```\n */\n async setSingleTarget(link, status = 'shared') {\n const query = new LinkQuery({ source: link.source, predicate: link.predicate });\n const foundLinks = await this.get(query);\n const removals = [];\n for (const l of foundLinks) {\n delete l.__typename;\n delete l.data.__typename;\n delete l.proof.__typename;\n removals.push(l);\n }\n const additions = [link];\n await this.linkMutations({ additions, removals }, status);\n }\n /** Returns all the Social DNA flows defined in this perspective */\n async sdnaFlows() {\n // Query for all flow registration links\n const flowLinks = await this.get(new LinkQuery({\n source: \"ad4m://self\",\n predicate: \"ad4m://has_flow\"\n }));\n return flowLinks.map(l => {\n try {\n return Literal.fromUrl(l.data.target).get();\n }\n catch {\n return l.data.target;\n }\n });\n }\n /** Returns all Social DNA flows that can be started from the given expression */\n async availableFlows(exprAddr) {\n const allFlowNames = await this.sdnaFlows();\n const available = [];\n for (const name of allFlowNames) {\n const flow = await this.getFlow(name);\n if (!flow)\n continue;\n if (flow.flowable === \"any\") {\n available.push(name);\n }\n else {\n // Check if the expression matches the flowable link pattern\n const pattern = flow.flowable;\n const source = pattern.source || exprAddr;\n const links = await this.get(new LinkQuery({\n source,\n predicate: pattern.predicate,\n target: pattern.target\n }));\n if (links.length > 0) {\n available.push(name);\n }\n }\n }\n return available;\n }\n /** Starts the Social DNA flow @param flowName on the expression @param exprAddr */\n async startFlow(flowName, exprAddr) {\n const flow = await this.getFlow(flowName);\n if (!flow)\n throw `Flow \"${flowName}\" not found`;\n if (flow.startAction.length === 0)\n throw `Flow \"${flowName}\" has no start action`;\n await this.executeAction(flow.startAction, exprAddr, undefined);\n }\n /** Returns all expressions in the given state of given Social DNA flow */\n async expressionsInFlowState(flowName, flowState) {\n const flow = await this.getFlow(flowName);\n if (!flow)\n return [];\n // Find the state with the matching value\n const state = flow.states.find(s => s.value === flowState);\n if (!state)\n return [];\n // Query for expressions matching this state's check pattern\n const pattern = state.stateCheck;\n const links = await this.get(new LinkQuery({\n predicate: pattern.predicate,\n target: pattern.target\n }));\n // Return the sources (expression addresses) - use source if pattern has no explicit source\n return links.map(l => pattern.source ? l.data.target : l.data.source);\n }\n /** Returns the given expression's flow state with regard to given Social DNA flow */\n async flowState(flowName, exprAddr) {\n const flow = await this.getFlow(flowName);\n if (!flow)\n throw `Flow \"${flowName}\" not found`;\n // Check each state to find which one the expression is in\n for (const state of flow.states) {\n const pattern = state.stateCheck;\n const source = pattern.source || exprAddr;\n const links = await this.get(new LinkQuery({\n source,\n predicate: pattern.predicate,\n target: pattern.target\n }));\n if (links.length > 0)\n return state.value;\n }\n throw `Expression \"${exprAddr}\" is not in any state of flow \"${flowName}\"`;\n }\n /** Returns available action names, with regard to Social DNA flow and expression's flow state */\n async flowActions(flowName, exprAddr) {\n const flow = await this.getFlow(flowName);\n if (!flow)\n return [];\n // Determine current state\n let currentStateName = null;\n for (const state of flow.states) {\n const pattern = state.stateCheck;\n const source = pattern.source || exprAddr;\n const links = await this.get(new LinkQuery({\n source,\n predicate: pattern.predicate,\n target: pattern.target\n }));\n if (links.length > 0) {\n currentStateName = state.name;\n break;\n }\n }\n if (!currentStateName)\n return [];\n // Return transitions available from current state\n return flow.transitions\n .filter(t => t.fromState === currentStateName)\n .map(t => t.actionName);\n }\n /** Runs given Social DNA flow action */\n async runFlowAction(flowName, exprAddr, actionName) {\n const flow = await this.getFlow(flowName);\n if (!flow)\n throw `Flow \"${flowName}\" not found`;\n const transition = flow.transitions.find(t => t.actionName === actionName);\n if (!transition)\n throw `Action \"${actionName}\" not found in flow \"${flowName}\"`;\n await this.executeAction(transition.actions, exprAddr, undefined);\n }\n /** Returns the perspective's Social DNA code\n * This will return all SDNA code elements in an array.\n */\n async getSdna() {\n // First, find all the name literals that are linked from ad4m://self with SDNA predicates\n const sdnaPredicates = [\n \"ad4m://has_subject_class\",\n \"ad4m://has_flow\",\n \"ad4m://has_custom_sdna\"\n ];\n const allSdnaCode = [];\n for (const predicate of sdnaPredicates) {\n // Find name literals linked from ad4m://self with this predicate\n const nameLinks = await this.get(new LinkQuery({\n source: \"ad4m://self\",\n predicate: predicate\n }));\n // For each name literal found, get the actual SDNA code\n for (const nameLink of nameLinks) {\n const nameLiteral = nameLink.data.target;\n // Now find the SDNA code linked from this name with predicate \"ad4m://sdna\"\n const sdnaLinks = await this.get(new LinkQuery({\n source: nameLiteral,\n predicate: \"ad4m://sdna\"\n }));\n // Extract the SDNA code from each link\n for (const sdnaLink of sdnaLinks) {\n const code = Literal.fromUrl(sdnaLink.data.target).get();\n if (typeof code === 'string') {\n allSdnaCode.push(code);\n }\n }\n }\n }\n return allSdnaCode;\n }\n /** Returns the Social DNA code for a specific class\n * This will return the SDNA code for the specified class, or null if not found.\n */\n async getSdnaForClass(className) {\n // First, find the name literal for this class that is linked from ad4m://self\n const nameLiteral = Literal.from(className);\n const links = await this.get(new LinkQuery({\n source: \"ad4m://self\",\n target: nameLiteral.toUrl(),\n predicate: \"ad4m://has_subject_class\"\n }));\n if (links.length === 0) {\n return null;\n }\n // Now find the SDNA code linked from this name with predicate \"ad4m://sdna\"\n const sdnaLinks = await this.get(new LinkQuery({\n source: nameLiteral.toUrl(),\n predicate: \"ad4m://sdna\"\n }));\n if (sdnaLinks.length === 0) {\n return null;\n }\n // Extract the SDNA code from the first link\n const code = Literal.fromUrl(sdnaLinks[0].data.target).get();\n return typeof code === 'string' ? code : null;\n }\n /**\n * Adds Social DNA code to the perspective.\n *\n * **Recommended:** Use {@link addShacl} instead, which accepts the `SHACLShape` type directly.\n * This method is primarily for the RPC API layer and legacy Prolog code.\n *\n * @param name - Unique name for this SDNA definition\n * @param sdnaCode - Prolog SDNA code (legacy, can be empty string if shaclJson provided)\n * @param sdnaType - Type of SDNA: \"subject_class\", \"flow\", or \"custom\"\n * @param shaclJson - SHACL JSON string (use addShacl() for type-safe alternative)\n *\n * @example\n * // Recommended: Use addShacl() with SHACLShape type\n * const shape = new SHACLShape('recipe://Recipe');\n * shape.addProperty({ name: 'title', path: 'recipe://title', datatype: 'xsd:string' });\n * await perspective.addShacl('Recipe', shape);\n *\n * // Legacy: Prolog code is auto-converted to SHACL\n * await perspective.addSdna('Recipe', prologCode, 'subject_class');\n */\n async addSdna(name, sdnaCode, sdnaType, shaclJson) {\n return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addSdna(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, name, sdnaCode, sdnaType, shaclJson);\n }\n /**\n * Batch variant of addSdna \u2014 registers multiple SDNA entries in a single RPC call.\n * Acquires the Rust-side mutex once for the entire batch.\n */\n async addSdnaAll(entries) {\n return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addSdnaBatch(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, entries);\n }\n /**\n * Batch-registers multiple model classes as SHACL subject classes in a single RPC call.\n * Skips classes already registered on this perspective instance.\n */\n async ensureSubjectClasses(jsClasses) {\n const entries = [];\n for (const jsClass of jsClasses) {\n const className = jsClass.className || jsClass.prototype?.className || jsClass.name;\n if (__classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, \"f\").has(className))\n continue;\n if (!jsClass.generateSHACL) {\n throw new Error(`Class ${jsClass.name} must have generateSHACL(). Use @Model decorator.`);\n }\n const { shape } = jsClass.generateSHACL();\n entries.push({\n name: className,\n sdnaType: 'subject_class',\n shaclJson: JSON.stringify(shape.toJSON()),\n });\n }\n if (entries.length === 0)\n return;\n await this.addSdnaAll(entries);\n for (const entry of entries) {\n __classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, \"f\").add(entry.name);\n }\n }\n /**\n * Adds a subject class to the perspective.\n * Alias for addSdna() with sdnaType='subject_class'.\n */\n async addSubjectClass(name, shaclJson) {\n return this.addSdna(name, '', 'subject_class', shaclJson);\n }\n /**\n * **Recommended way to add SDNA schemas.**\n *\n * Store a SHACL shape in this Perspective using the type-safe `SHACLShape` class.\n * The shape is serialized as RDF triples (links) for native AD4M storage and querying.\n *\n * @param name - Unique name for this schema (e.g., 'Recipe', 'Task')\n * @param shape - SHACLShape instance defining the schema\n *\n * @example\n * import { SHACLShape } from '@coasys/ad4m';\n *\n * const shape = new SHACLShape('recipe://Recipe');\n * shape.addProperty({\n * name: 'title',\n * path: 'recipe://title',\n * datatype: 'xsd:string',\n * minCount: 1\n * });\n * shape.addProperty({\n * name: 'ingredients',\n * path: 'recipe://has_ingredient',\n * // No maxCount = relation\n * });\n *\n * await perspective.addShacl('Recipe', shape);\n */\n async addShacl(name, shape) {\n // Serialize shape to links\n const shapeLinks = shape.toLinks();\n // Create name -> shape mapping links\n const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);\n const allLinks = [\n ...shapeLinks.map(l => new Link({\n source: l.source,\n predicate: l.predicate,\n target: l.target\n })),\n new Link({\n source: \"ad4m://self\",\n predicate: \"ad4m://has_shacl\",\n target: nameMapping.toUrl()\n }),\n new Link({\n source: nameMapping.toUrl(),\n predicate: \"ad4m://shacl_shape_uri\",\n target: shape.nodeShapeUri\n })\n ];\n // Batch add all links at once\n await this.addLinks(allLinks);\n }\n /**\n * Retrieve a SHACL shape by name from this Perspective\n */\n async getShacl(name) {\n // Find the shape URI from the name mapping\n const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);\n const shapeUriLinks = await this.get(new LinkQuery({\n source: nameMapping.toUrl(),\n predicate: \"ad4m://shacl_shape_uri\"\n }));\n if (shapeUriLinks.length === 0) {\n return null;\n }\n const shapeUri = shapeUriLinks[0].data.target;\n // First get property shape URIs so we can query everything in one go\n const propertyLinks = await this.get(new LinkQuery({\n source: shapeUri,\n predicate: \"sh://property\"\n }));\n // Fetch all links from the shape and its property shapes\n const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];\n const allLinks = [];\n for (const uri of sourceUris) {\n const links = await this.get(new LinkQuery({ source: uri }));\n for (const l of links) {\n allLinks.push({\n source: l.data.source,\n predicate: l.data.predicate,\n target: l.data.target\n });\n }\n }\n const shapeLinks = allLinks;\n return SHACLShape.fromLinks(shapeLinks, shapeUri);\n }\n /**\n * Get all SHACL shapes stored in this Perspective\n */\n async getAllShacl() {\n const nameLinks = await this.get(new LinkQuery({\n source: \"ad4m://self\",\n predicate: \"ad4m://has_shacl\"\n }));\n const shapes = [];\n for (const nameLink of nameLinks) {\n const nameUrl = nameLink.data.target;\n const name = Literal.fromUrl(nameUrl).get();\n const shapeName = name.replace('shacl://', '');\n const shape = await this.getShacl(shapeName);\n if (shape) {\n shapes.push({ name: shapeName, shape });\n }\n }\n return shapes;\n }\n /**\n * **Recommended way to add Flow definitions.**\n *\n * Store a SHACL Flow (state machine) in this Perspective using the type-safe `SHACLFlow` class.\n * The flow is serialized as RDF triples (links) for native AD4M storage and querying.\n *\n * @param name - Flow name (e.g., 'TODO', 'Approval')\n * @param flow - SHACLFlow instance defining the state machine\n *\n * @example\n * ```typescript\n * import { SHACLFlow } from '@coasys/ad4m';\n *\n * const todoFlow = new SHACLFlow('TODO', 'todo://');\n * todoFlow.flowable = 'any';\n *\n * // Define states\n * todoFlow.addState({ name: 'ready', value: 0, stateCheck: { predicate: 'todo://state', target: 'todo://ready' }});\n * todoFlow.addState({ name: 'done', value: 1, stateCheck: { predicate: 'todo://state', target: 'todo://done' }});\n *\n * // Define start action\n * todoFlow.startAction = [{ action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }];\n *\n * // Define transitions\n * todoFlow.addTransition({\n * actionName: 'Complete',\n * fromState: 'ready',\n * toState: 'done',\n * actions: [\n * { action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://done' },\n * { action: 'removeLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }\n * ]\n * });\n *\n * await perspective.addFlow('TODO', todoFlow);\n * ```\n */\n async addFlow(name, flow) {\n // Serialize flow to links\n const flowLinks = flow.toLinks();\n // Create registration and mapping links\n const flowNameLiteral = Literal.from(name).toUrl();\n const allLinks = [\n ...flowLinks.map(l => new Link({\n source: l.source,\n predicate: l.predicate,\n target: l.target\n })),\n new Link({\n source: \"ad4m://self\",\n predicate: \"ad4m://has_flow\",\n target: flowNameLiteral\n }),\n new Link({\n source: flowNameLiteral,\n predicate: \"ad4m://flow_uri\",\n target: flow.flowUri\n })\n ];\n // Batch add all links at once\n await this.addLinks(allLinks);\n }\n /**\n * Retrieve a Flow definition by name from this Perspective\n *\n * @param name - Flow name to retrieve\n * @returns The SHACLFlow or null if not found\n */\n async getFlow(name) {\n const flowNameLiteral = Literal.from(name).toUrl();\n // Find flow URI from name mapping\n const flowUriLinks = await this.get(new LinkQuery({\n source: flowNameLiteral,\n predicate: \"ad4m://flow_uri\"\n }));\n if (flowUriLinks.length === 0) {\n return null;\n }\n const flowUri = flowUriLinks[0].data.target;\n // Compute alternate prefix for state/transition URIs\n const alternatePrefix = flowUri.endsWith('Flow')\n ? flowUri.slice(0, -4) + '.'\n : flowUri + '.';\n // Fetch flow links using SPARQL to match flowUri source OR alternatePrefix sources\n const sparqlQuery = `SELECT ?s ?p ?o WHERE {\n ?s ?p ?o .\n FILTER(?s = <${flowUri}> || STRSTARTS(STR(?s), \"${alternatePrefix}\"))\n }`;\n const sparqlResult = await this.querySparql(sparqlQuery);\n const flowLinks = (sparqlResult || []).map((r) => ({\n source: r.s,\n predicate: r.p,\n target: r.o\n }));\n return SHACLFlow.fromLinks(flowLinks, flowUri);\n }\n /** Returns all the Subject classes defined in this perspectives SDNA\n *\n * Uses SHACL-based lookup (Prolog-free implementation).\n */\n async subjectClasses() {\n try {\n // Query SHACL class links directly \u2014 no need for a separate RPC endpoint\n const classLinks = await this.get(new LinkQuery({\n predicate: \"rdf://type\",\n target: \"ad4m://SubjectClass\"\n }));\n const classNames = classLinks\n .map(l => {\n const source = l.data.source;\n // Extract class name from URI like \"recipe://Recipe\" or \"flux://Channel\"\n const parts = source.split(\"://\");\n const lastPart = parts[parts.length - 1];\n return lastPart.split('/').pop() || '';\n })\n .filter(name => name.length > 0);\n // Deduplicate\n return [...new Set(classNames)];\n }\n catch (e) {\n console.warn('subjectClasses: SHACL lookup failed:', e);\n return [];\n }\n }\n async stringOrTemplateObjectToSubjectClassName(subjectClass) {\n if (typeof subjectClass === \"string\")\n return subjectClass;\n else {\n let subjectClasses = await this.subjectClassesByTemplate(subjectClass);\n if (subjectClasses[0]) {\n return subjectClasses[0];\n }\n else {\n //@ts-ignore\n return subjectClass.className;\n }\n }\n }\n /**\n * Creates a new subject instance of the given subject class\n *\n * @param subjectClass Either a string with the name of the subject class, or an object\n * with the properties of the subject class.\n * @param exprAddr The address of the expression to be turned into a subject instance\n * @param initialValues Optional initial values for properties. If provided, these will be\n * merged with constructor actions for better performance.\n * @param batchId Optional batch ID for grouping operations. If provided, returns the expression address\n * instead of the subject proxy since the subject won't exist until the batch is committed.\n * @returns A proxy object for the created subject, or just the expression address if in batch mode\n */\n async createSubject(subjectClass, exprAddr, initialValues, batchId) {\n let className;\n if (typeof subjectClass === \"string\") {\n className = subjectClass;\n await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").createSubject(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, JSON.stringify({\n className,\n initialValues\n }), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);\n }\n else {\n const obj = subjectClass;\n const resolvedClassName = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className\n || await this.findClassByProperties(obj);\n if (!resolvedClassName) {\n throw new Error(\"Could not resolve subject class name from object. Use a decorated class or pass a className string.\");\n }\n await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").createSubject(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, JSON.stringify({\n className: resolvedClassName,\n initialValues\n }), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);\n }\n // Skip subject proxy creation when in batch mode since the subject won't exist until batch is committed\n if (batchId) {\n return exprAddr;\n }\n // Return the expression address directly \u2014 callers should use Ad4mModel or\n // getSubjectData() to interact with the created instance.\n return exprAddr;\n }\n async getSubjectData(subjectClass, exprAddr) {\n if (typeof subjectClass === \"string\") {\n return JSON.parse(await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").getSubjectData(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, JSON.stringify({ className: subjectClass }), exprAddr));\n }\n const obj = subjectClass;\n const resolvedClassName = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className\n || await this.findClassByProperties(obj);\n if (!resolvedClassName) {\n throw new Error(\"Could not resolve subject class name from object. Use a decorated class or pass a className string.\");\n }\n return JSON.parse(await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").getSubjectData(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, JSON.stringify({ className: resolvedClassName }), exprAddr));\n }\n /**\n * Gets actions from SHACL links for a given predicate (e.g., ad4m://constructor, ad4m://destructor).\n * Returns the parsed action array if found, or null if not found.\n */\n async getActionsFromSHACL(className, predicate) {\n // Use regex to match exact class name followed by \"Shape\" at end of URI\n // This prevents \"RecipeShape\" from matching \"MyRecipeShape\"\n const escaped = this.escapeRegExp(className);\n const shapePattern = new RegExp(`[/:#]${escaped}Shape$`);\n const links = await this.get(new LinkQuery({ predicate }));\n for (const link of links) {\n if (shapePattern.test(link.data.source)) {\n // Parse actions from literal:string:{json}\n const prefix = \"literal:string:\";\n if (link.data.target.startsWith(prefix)) {\n const jsonStr = link.data.target.slice(prefix.length);\n // Decode URL-encoded JSON if needed, with fallback for raw % characters\n let decoded = jsonStr;\n try {\n decoded = decodeURIComponent(jsonStr);\n }\n catch { }\n try {\n return JSON.parse(decoded);\n }\n catch (e) {\n console.warn(`Failed to parse SHACL actions JSON for ${className}:`, e);\n return null;\n }\n }\n }\n }\n return null;\n }\n /** Removes a subject instance by running its (SDNA defined) destructor,\n * which means removing links around the given expression address\n *\n * @param subjectClass Either a string with the name of the subject class, or an object\n * with the properties of the subject class. In the latter case, the first subject class\n * that matches the given properties will be used.\n * @param exprAddr The address of the expression to be turned into a subject instance\n * @param batchId Optional batch ID for grouping operations. If provided, the removal will be part of the batch\n * and won't be executed until the batch is committed.\n */\n async removeSubject(subjectClass, exprAddr, batchId) {\n let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);\n // Get destructor actions from SHACL links (Prolog-free)\n let actions = await this.getActionsFromSHACL(className, \"ad4m://destructor\");\n if (!actions) {\n throw `No destructor found for subject class: ${className}. Make sure the class was registered with SHACL.`;\n }\n await this.executeAction(actions, exprAddr, undefined, batchId);\n }\n /** Checks if the given expression is a subject instance of the given subject class\n * @param expression The expression to be checked\n * @param subjectClass Either a string with the name of the subject class, or an object\n * with the properties of the subject class. In the latter case, the first subject class\n * that matches the given properties will be used.\n */\n async isSubjectInstance(expression, subjectClass) {\n let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);\n // Get metadata from SHACL links\n const metadata = await this.getSubjectClassMetadata(className);\n if (!metadata) {\n console.warn(`isSubjectInstance: No SHACL metadata found for class ${className}`);\n return false;\n }\n // If no required triples, any expression with links is an instance\n if (metadata.requiredTriples.length === 0) {\n const links = await this.get(new LinkQuery({ source: expression }));\n return links.length > 0;\n }\n // Build a single SPARQL ASK query with all required triple patterns\n const patterns = metadata.requiredTriples.map((t, i) => {\n const target = t.target ? `<${t.target}>` : `?t${i}`;\n return `<${expression}> <${t.predicate}> ${target} .`;\n }).join('\\n ');\n const result = await this.querySparql(`ASK WHERE {\\n ${patterns}\\n}`);\n return result === true;\n }\n /**\n * Gets subject class metadata from SHACL links using SHACLShape.fromLinks().\n * Retrieves the SHACL shape and extracts metadata for instance queries.\n */\n async getSubjectClassMetadata(className) {\n try {\n // Use getShacl() to retrieve the shape via SHACLShape.fromLinks()\n const shape = await this.getShacl(className);\n if (!shape) {\n console.warn(`No SHACL metadata found for ${className}`);\n return null;\n }\n const requiredPredicates = [];\n const requiredTriples = [];\n const properties = new Map();\n const relations = new Map();\n // Build property/relation maps and track writable predicates from shape properties\n const writablePredicates = new Set();\n for (const prop of shape.properties) {\n if (!prop.path || !prop.name)\n continue;\n if (prop.writable) {\n writablePredicates.add(prop.path);\n }\n const isRelation = prop.adder && prop.adder.length > 0;\n if (isRelation) {\n relations.set(prop.name, { predicate: prop.path });\n }\n else {\n properties.set(prop.name, {\n predicate: prop.path,\n resolveLanguage: prop.resolveLanguage\n });\n }\n }\n // Extract required predicates/triples from constructor actions\n if (shape.constructor_actions) {\n for (const action of shape.constructor_actions) {\n if (action.predicate) {\n requiredPredicates.push(action.predicate);\n const isWritableProperty = writablePredicates.has(action.predicate);\n if (action.target && action.target !== 'value' && !isWritableProperty) {\n requiredTriples.push({ predicate: action.predicate, target: action.target });\n }\n else {\n requiredTriples.push({ predicate: action.predicate });\n }\n }\n }\n }\n return { requiredPredicates, requiredTriples, properties, relations };\n }\n catch (e) {\n console.error(`Error getting SHACL metadata for ${className}:`, e);\n return null;\n }\n }\n /**\n * Generates a SPARQL query to find instances based on class metadata.\n */\n /**\n * Finds all instances matching subject class metadata by querying links.\n * Returns base URIs of matching instances.\n */\n async findInstancesByMetadata(metadata) {\n if (metadata.requiredTriples.length === 0) {\n // No required triples - return all unique sources that have any link\n const allLinks = await this.get(new LinkQuery({}));\n const sources = new Set(allLinks.map(l => l.data.source));\n return Array.from(sources).map(s => ({ base: s }));\n }\n // Build a single SPARQL SELECT with all required triple patterns joined\n const patterns = metadata.requiredTriples.map((t, i) => {\n const target = t.target ? `<${t.target}>` : `?t${i}`;\n return `?base <${t.predicate}> ${target} .`;\n }).join('\\n ');\n const results = await this.querySparql(`SELECT DISTINCT ?base WHERE {\\n ${patterns}\\n}`);\n if (!Array.isArray(results))\n return [];\n return results.map((row) => ({ base: row.base }));\n }\n /** Returns all subject instances of the given subject class as proxy objects.\n * @param subjectClass Either a string with the name of the subject class, or an object\n * with the properties of the subject class. In the latter case, all subject classes\n * that match the given properties will be used.\n */\n async getAllSubjectInstances(subjectClass) {\n let classes = [];\n let isClassConstructor = typeof subjectClass === \"function\";\n if (typeof subjectClass === \"string\") {\n classes = [subjectClass];\n }\n else if (isClassConstructor) {\n // It's an Ad4mModel class constructor\n //@ts-ignore\n classes = [subjectClass.name];\n }\n else {\n classes = await this.subjectClassesByTemplate(subjectClass);\n }\n let instances = [];\n for (let className of classes) {\n //console.log(`getAllSubjectInstances: Processing class ${className}`);\n // Query SDNA for metadata, then query SPARQL for instances\n const metadata = await this.getSubjectClassMetadata(className);\n //console.log(`getAllSubjectInstances: Got metadata for ${className}:`, metadata);\n if (metadata) {\n const results = await this.findInstancesByMetadata(metadata);\n // console.log(`getAllSubjectInstances: SPARQL returned ${results?.length || 0} results`);\n for (const result of results || []) {\n //console.log(`getAllSubjectInstances: Creating subject for base ${result.base}`);\n try {\n let instance;\n if (isClassConstructor) {\n // Create an instance of the actual Ad4mModel class\n //@ts-ignore\n instance = new subjectClass(this, result.base);\n // Load the instance data from links\n await instance.get();\n }\n else {\n // Return plain data for string-based lookups\n const data = await this.getSubjectData(className, result.base);\n instance = { id: result.base, ...data };\n }\n instances.push(instance);\n //console.log(`getAllSubjectInstances: Successfully created subject for ${result.base}`);\n }\n catch (e) {\n //console.warn(`Failed to create subject for ${result.base}:`, e);\n }\n }\n }\n }\n //console.log(`getAllSubjectInstances: Returning ${instances.length} instances`);\n return instances;\n }\n /**\n * Find a subject class by matching an object's properties/relations against SHACL shapes.\n * Queries SHACL links client-side to find a class whose properties contain all required ones.\n * @returns The matching class name, or null if no match found.\n */\n async findClassByProperties(obj) {\n // Extract properties and relations from the object\n let properties = [];\n let relations = [];\n const proto = Object.getPrototypeOf(obj);\n const ctor = proto?.constructor;\n const registryProps = ctor ? getPropertiesMetadata(ctor) : {};\n if (Object.keys(registryProps).length > 0) {\n properties = Object.keys(registryProps);\n }\n else {\n properties = Object.keys(obj).filter(key => !Array.isArray(obj[key]));\n }\n const registryRelations = ctor\n ? Object.fromEntries(Object.entries(getRelationsMetadata(ctor)).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'))\n : {};\n if (Object.keys(registryRelations).length > 0) {\n relations = Object.keys(registryRelations).filter(key => key !== 'isSubjectInstance');\n }\n else {\n relations = Object.keys(obj).filter(key => Array.isArray(obj[key]) && key !== 'isSubjectInstance');\n }\n if (properties.length === 0 && relations.length === 0) {\n return null;\n }\n // Single SPARQL query to get all class shapes with their properties and collections\n const results = await this.querySparql(`\n SELECT ?shape ?predicate ?target WHERE {\n { ?shape <rdf://type> <ad4m://SubjectClass> . BIND(<rdf://type> AS ?predicate) BIND(<ad4m://SubjectClass> AS ?target) }\n UNION\n { ?shape <sh://property> ?target . BIND(<sh://property> AS ?predicate) }\n UNION\n { ?shape <sh://collection> ?target . BIND(<sh://collection> AS ?predicate) }\n }\n `);\n if (!Array.isArray(results) || results.length === 0)\n return null;\n // Build a map of className -> { properties, relations }\n const classShapes = new Map();\n // First pass: find all subject classes\n for (const r of results) {\n if (r.predicate === 'rdf://type' && r.target === 'ad4m://SubjectClass') {\n const source = r.shape;\n const sepIdx = source.indexOf('://');\n if (sepIdx < 0)\n continue;\n const className = source.substring(sepIdx + 3).split('/').pop();\n if (!className)\n continue;\n classShapes.set(className, { shapeUri: source, properties: [], relations: [] });\n }\n }\n // Second pass: collect properties and relations for each class\n for (const r of results) {\n if (r.predicate === 'sh://property' || r.predicate === 'sh://collection') {\n // Match shape source to class (e.g., \"recipe://RecipeShape\" -> \"Recipe\")\n for (const [className, shape] of classShapes) {\n if (r.shape.endsWith(`${className}Shape`)) {\n const dotIdx = r.target.lastIndexOf('.');\n if (dotIdx < 0)\n continue;\n const name = r.target.substring(dotIdx + 1);\n if (r.predicate === 'sh://property') {\n shape.properties.push(name);\n }\n else {\n shape.relations.push(name);\n }\n }\n }\n }\n }\n // Find a class that has all required properties and relations\n for (const [className, shape] of classShapes) {\n const hasAllProps = properties.every(p => shape.properties.includes(p));\n const hasAllRels = relations.every(c => shape.relations.includes(c));\n if (hasAllProps && hasAllRels) {\n return className;\n }\n }\n return null;\n }\n /** Returns all subject classes that match the given template object.\n * This function looks at the properties of the template object and\n * its setters and relations to create a Prolog query that finds\n * all subject classes that would be converted to a proxy object\n * with exactly the same properties and relations.\n *\n * Since there could be multiple subject classes that match the given\n * criteria, this function returns a list of class names.\n *\n * @param obj The template object\n */\n async subjectClassesByTemplate(obj) {\n // className lookup first: the @Model decorator sets a precise className on the prototype,\n // so this is always more specific than property-set matching.\n // Property matching alone has a superset-ambiguity problem: if DerivedModel adds\n // properties to BaseModel, then DerivedModel's shape is a superset of BaseModel's\n // property list, so findClassByProperties could wrongly return DerivedModel for a\n // BaseModel instance (causing the derived SDNA constructor to fire and inject extra\n // links into what should be a plain base instance).\n try {\n // @ts-ignore - className is added dynamically by decorators\n const className = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className;\n if (className) {\n const existingClasses = await this.subjectClasses();\n if (existingClasses.includes(className)) {\n return [className];\n }\n }\n }\n catch (e) {\n console.warn('subjectClassesByTemplate: className lookup failed:', e);\n }\n // Fall back to SHACL-based property matching for undecorated / dynamic objects\n try {\n const match = await this.findClassByProperties(obj);\n if (match) {\n return [match];\n }\n }\n catch (e) {\n console.warn('subjectClassesByTemplate: property matching failed:', e);\n }\n return [];\n }\n /** Takes a JS class (its constructor) and assumes that it was decorated by\n * the @subjectClass etc. decorators. It then tests if there is a subject class\n * already present in the perspective's SDNA that matches the given class.\n * If there is no such class, it gets the JS class's SDNA by calling its\n * static generateSDNA() function and adds it to the perspective's SDNA.\n */\n async ensureSDNASubjectClass(jsClass) {\n return this.ensureSubjectClass(jsClass);\n }\n /** Takes a JS class (its constructor) and ensures the SHACL subject class exists. */\n async ensureSubjectClass(jsClass) {\n // Get the class name from the JS class\n const className = jsClass.className || jsClass.prototype?.className || jsClass.name;\n // Skip if already registered for this perspective instance\n if (__classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, \"f\").has(className))\n return;\n // Note: Duplicate checking is handled on the Rust side in add_sdna\n // Generate SHACL SDNA (Prolog-free)\n if (!jsClass.generateSHACL) {\n throw new Error(`Class ${jsClass.name} must have generateSHACL(). Use @Model decorator.`);\n }\n // Get SHACL shape (W3C standard + AD4M action definitions)\n const { shape } = jsClass.generateSHACL();\n // Serialize SHACL shape to JSON for Rust backend using SHACLShape.toJSON()\n const shaclJson = JSON.stringify(shape.toJSON());\n // Pass SHACL JSON to backend (Prolog-free)\n // Backend stores SHACL links directly\n await this.addSdna(className, '', 'subject_class', shaclJson);\n // Mark as registered for this perspective instance\n __classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, \"f\").add(className);\n }\n /** Clear the per-instance ensured subject class cache.\n * Call this after wiping a perspective's links so that\n * subsequent register() calls re-add SHACL definitions. */\n clearEnsuredSubjectClasses() {\n __classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, \"f\").clear();\n }\n /**\n * Returns a list of all class names that have been registered as SHACL\n * subject classes in this perspective (via `ensureSDNASubjectClass` or `addSdna`).\n *\n * @returns Array of class name strings (e.g. `[\"Channel\", \"Message\", \"Task\"]`)\n */\n async listRegisteredClasses() {\n const results = await this.querySparql(`SELECT DISTINCT ?class WHERE { ?class <rdf://type> <ad4m://SubjectClass> . }`);\n if (!Array.isArray(results))\n return [];\n return results.map((row) => {\n const uri = row.class || '';\n // Extract class name from URI like \"recipe://Recipe\" or \"flux://Channel\"\n const hashIdx = uri.lastIndexOf('#');\n if (hashIdx >= 0)\n return uri.substring(hashIdx + 1);\n const slashIdx = uri.lastIndexOf('/');\n if (slashIdx >= 0)\n return uri.substring(slashIdx + 1);\n return uri;\n }).filter(Boolean);\n }\n /**\n * Returns the SHACL shape metadata for a registered class, including\n * property names, predicates, datatypes, and cardinality constraints.\n *\n * @param className - The name of the registered class\n * @returns Shape metadata or `null` if the class is not registered\n */\n async getClassShape(className) {\n // Find the shape URI for this class\n const safeName = className.replace(/['\"\\\\]/g, '');\n const shapeResults = await this.querySparql(`SELECT ?shapeUri ?targetClass WHERE {\n ?targetClass <rdf://type> <ad4m://SubjectClass> .\n ?targetClass <ad4m://shape> ?shapeUri .\n FILTER(STRENDS(STR(?targetClass), \"/${safeName}\") || STRENDS(STR(?targetClass), \"#${safeName}\"))\n } LIMIT 1`);\n if (!Array.isArray(shapeResults) || shapeResults.length === 0)\n return null;\n const shapeUri = shapeResults[0].shapeUri;\n shapeResults[0].targetClass;\n // Query all properties for this shape, including sh:in\n const propResults = await this.querySparql(`SELECT ?propShape ?path ?datatype ?minCount ?maxCount ?writable ?propType ?shIn WHERE {\n <${shapeUri}> <sh://property> ?propShape .\n ?propShape <sh://path> ?path .\n ?propShape <rdf://type> ?propType .\n OPTIONAL { ?propShape <sh://datatype> ?datatype }\n OPTIONAL { ?propShape <sh://minCount> ?minCount }\n OPTIONAL { ?propShape <sh://maxCount> ?maxCount }\n OPTIONAL { ?propShape <ad4m://writable> ?writable }\n OPTIONAL { ?propShape <sh://in> ?shIn }\n }`);\n const properties = (Array.isArray(propResults) ? propResults : []).map((row) => {\n // Extract property name from shape URI like \"recipe://Recipe.name\"\n const propUri = row.propShape || '';\n const dotIdx = propUri.lastIndexOf('.');\n const name = dotIdx >= 0 ? propUri.substring(dotIdx + 1) : propUri;\n const minCount = parseInt(row.minCount || '0', 10);\n const isCollection = row.propType === 'ad4m://CollectionShape';\n const writable = row.writable === 'true' || row.writable === 'literal:true';\n // Parse sh:in values if present\n let options;\n if (row.shIn) {\n try {\n let raw = row.shIn;\n // Strip literal: prefix if present, and URI-decode for robustness\n if (raw.startsWith('literal:string:')) {\n raw = decodeURIComponent(raw.substring('literal:string:'.length));\n }\n options = JSON.parse(raw);\n }\n catch { /* ignore parse errors */ }\n }\n return {\n name,\n predicate: row.path || '',\n datatype: row.datatype || undefined,\n required: minCount > 0,\n collection: isCollection,\n writable,\n ...(options && options.length > 0 ? { options } : {}),\n };\n });\n return { className: safeName, shapeUri, properties };\n }\n /**\n * Detects which registered subject classes a given instance conforms to,\n * based on its stored triples matching the class shapes' required properties.\n *\n * @param baseExpression - The instance's base expression / subject URI\n * @returns Array of class names the instance matches\n */\n async getInstanceClasses(baseExpression) {\n const safeId = baseExpression.replace(/['\"\\\\]/g, '');\n // Get all registered classes and their required conformance properties\n const results = await this.querySparql(`SELECT DISTINCT ?class WHERE {\n ?class <rdf://type> <ad4m://SubjectClass> .\n ?class <ad4m://shape> ?shape .\n ?shape <sh://property> ?propShape .\n ?propShape <sh://minCount> ?mc .\n FILTER(?mc >= 1)\n ?propShape <sh://path> ?path .\n <${safeId}> ?path ?_val .\n }`);\n if (!Array.isArray(results))\n return [];\n return results.map((row) => {\n const uri = row.class || '';\n const hashIdx = uri.lastIndexOf('#');\n if (hashIdx >= 0)\n return uri.substring(hashIdx + 1);\n const slashIdx = uri.lastIndexOf('/');\n if (slashIdx >= 0)\n return uri.substring(slashIdx + 1);\n return uri;\n }).filter(Boolean);\n }\n /**\n * Returns all named options (sh:in values) for a registered class, grouped by property.\n *\n * @param className - The name of the registered class\n * @returns Record mapping property name \u2192 array of { value, label } options\n */\n async getNamedOptions(className) {\n const shape = await this.getClassShape(className);\n if (!shape)\n return {};\n const result = {};\n for (const prop of shape.properties) {\n if (prop.options && prop.options.length > 0) {\n result[prop.name] = prop.options;\n }\n }\n return result;\n }\n /**\n * Adds a named option (sh:in value) to a property of a registered class.\n * This appends to the existing sh:in list stored on the property shape.\n *\n * @param className - The registered class name\n * @param propertyName - The property to add the option to\n * @param value - The RDF value for the option\n * @param label - Optional human-readable label\n */\n async addNamedOption(className, propertyName, value, label) {\n const shape = await this.getClassShape(className);\n if (!shape)\n throw new Error(`Class \"${className}\" not found`);\n const prop = shape.properties.find(p => p.name === propertyName);\n if (!prop)\n throw new Error(`Property \"${propertyName}\" not found on class \"${className}\"`);\n // Build the property shape URI\n const ns = extractNamespaceFromUri(shape.shapeUri);\n const propShapeId = `${ns}${className}.${propertyName}`;\n // Get existing options\n const existing = prop.options || [];\n // Don't add duplicates\n if (existing.some(o => o.value === value))\n return;\n const updated = [...existing, { value, ...(label ? { label } : {}) }];\n // Remove old sh:in link if exists by querying for it\n const oldLinks = await this.get(new LinkQuery({ source: propShapeId, predicate: \"sh://in\" }));\n for (const oldLink of oldLinks) {\n await this.remove(oldLink);\n }\n // Add new sh:in link\n await this.add(new Link({\n source: propShapeId,\n predicate: \"sh://in\",\n target: `literal:string:${JSON.stringify(updated)}`\n }));\n }\n getNeighbourhoodProxy() {\n return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").getNeighbourhoodProxy(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n }\n /**\n * Returns a proxy object for working with AI capabilities.\n *\n * @returns AIClient instance\n *\n * @example\n * ```typescript\n * // Use AI to analyze perspective content\n * const summary = await perspective.ai.summarize();\n *\n * // Generate new content\n * const suggestion = await perspective.ai.suggest(\"next action\");\n * ```\n */\n get ai() {\n return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").aiClient;\n }\n /**\n * Creates a subscription for a Prolog query that updates in real-time.\n *\n * This method:\n * 1. Creates the subscription on the Rust side\n * 2. Sets up the subscription callback\n * 3. Waits for the initial result to come through the subscription channel\n * 4. Returns a fully initialized QuerySubscriptionProxy\n *\n * The returned subscription is guaranteed to be ready to receive updates,\n * as this method waits for the initialization process to complete.\n *\n * The subscription will be automatically cleaned up on both frontend and backend\n * when dispose() is called. Make sure to call dispose() when you're done to\n * prevent memory leaks and ensure proper cleanup of resources.\n *\n * @param query - Prolog query string\n * @returns Initialized QuerySubscriptionProxy instance\n *\n * @example\n * ```typescript\n * // Subscribe to active todos\n * const subscription = await perspective.subscribeInfer(`\n * instance(Todo, \"Todo\"),\n * property_getter(\"Todo\", Todo, \"state\", \"active\")\n * `);\n *\n * // Subscription is already initialized here\n * console.log(\"Initial result:\", subscription.result);\n *\n * // Set up callback for future updates\n * subscription.onResult((todos) => {\n * console.log(\"Active todos:\", todos);\n * });\n *\n * // Clean up subscription when done\n * subscription.dispose();\n * ```\n */\n async subscribeInfer(query) {\n const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\"));\n // Start the subscription on the Rust side first to get the real subscription ID\n await subscriptionProxy.subscribe();\n // Wait for the initial result\n await subscriptionProxy.initialized;\n return subscriptionProxy;\n }\n /**\n * Creates a subscription for a SPARQL query that updates in real-time.\n *\n * This method:\n * 1. Creates the subscription on the Rust side\n * 2. Sets up the subscription callback\n * 3. Waits for the initial result to come through the subscription channel\n * 4. Returns a fully initialized QuerySubscriptionProxy\n *\n * The returned subscription is guaranteed to be ready to receive updates,\n * as this method waits for the initialization process to complete.\n *\n * The subscription will be automatically cleaned up on both frontend and backend\n * when dispose() is called. Make sure to call dispose() when you're done to\n * prevent memory leaks and ensure proper cleanup of resources.\n *\n /** Subscribe to a query with live updates via the SPARQL subscription endpoint.\n * @param query - Query string\n * @returns Initialized QuerySubscriptionProxy instance\n */\n async subscribeQuery(query) {\n const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\"));\n // Start the subscription on the Rust side first to get the real subscription ID\n await subscriptionProxy.subscribe();\n // Wait for the initial result\n await subscriptionProxy.initialized;\n return subscriptionProxy;\n }\n}\n_PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveProxy_ensuredSubjectClasses = new WeakMap();\n\nvar __classPrivateFieldSet$9 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$9 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _PerspectiveClient_apiClient, _PerspectiveClient_perspectiveAddedCallbacks, _PerspectiveClient_perspectiveUpdatedCallbacks, _PerspectiveClient_perspectiveRemovedCallbacks, _PerspectiveClient_perspectiveSyncStateChangeCallbacks, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient, _PerspectiveClient_unsubscribers, _PerspectiveClient_linkUnsubscribers, _PerspectiveClient_querySubscriptionUnsubscribers;\nfunction normalizeQueryResult(raw, errorContext) {\n let finalResult = raw;\n if (typeof finalResult === 'string') {\n try {\n finalResult = JSON.parse(finalResult);\n }\n catch (e) {\n console.error(errorContext, e);\n }\n }\n return finalResult;\n}\nclass PerspectiveClient {\n constructor(baseUrl, token, subscribe = true, sharedApiClient) {\n _PerspectiveClient_apiClient.set(this, void 0);\n _PerspectiveClient_perspectiveAddedCallbacks.set(this, void 0);\n _PerspectiveClient_perspectiveUpdatedCallbacks.set(this, void 0);\n _PerspectiveClient_perspectiveRemovedCallbacks.set(this, void 0);\n _PerspectiveClient_perspectiveSyncStateChangeCallbacks.set(this, void 0);\n _PerspectiveClient_expressionClient.set(this, void 0);\n _PerspectiveClient_neighbourhoodClient.set(this, void 0);\n _PerspectiveClient_aiClient.set(this, void 0);\n _PerspectiveClient_unsubscribers.set(this, void 0);\n _PerspectiveClient_linkUnsubscribers.set(this, void 0);\n _PerspectiveClient_querySubscriptionUnsubscribers.set(this, void 0);\n __classPrivateFieldSet$9(this, _PerspectiveClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), \"f\");\n __classPrivateFieldSet$9(this, _PerspectiveClient_perspectiveAddedCallbacks, [], \"f\");\n __classPrivateFieldSet$9(this, _PerspectiveClient_perspectiveUpdatedCallbacks, [], \"f\");\n __classPrivateFieldSet$9(this, _PerspectiveClient_perspectiveRemovedCallbacks, [], \"f\");\n __classPrivateFieldSet$9(this, _PerspectiveClient_perspectiveSyncStateChangeCallbacks, [], \"f\");\n __classPrivateFieldSet$9(this, _PerspectiveClient_unsubscribers, [], \"f\");\n __classPrivateFieldSet$9(this, _PerspectiveClient_linkUnsubscribers, new Map(), \"f\");\n __classPrivateFieldSet$9(this, _PerspectiveClient_querySubscriptionUnsubscribers, new Map(), \"f\");\n if (subscribe) {\n this.subscribePerspectiveAdded();\n this.subscribePerspectiveUpdated();\n this.subscribePerspectiveRemoved();\n }\n }\n setExpressionClient(client) {\n __classPrivateFieldSet$9(this, _PerspectiveClient_expressionClient, client, \"f\");\n }\n setNeighbourhoodClient(client) {\n __classPrivateFieldSet$9(this, _PerspectiveClient_neighbourhoodClient, client, \"f\");\n }\n setAIClient(client) {\n __classPrivateFieldSet$9(this, _PerspectiveClient_aiClient, client, \"f\");\n }\n get aiClient() {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_aiClient, \"f\");\n }\n async all() {\n const perspectives = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.all');\n return perspectives.map(handle => new PerspectiveProxy(handle, this));\n }\n async byUUID(uuid) {\n try {\n const perspective = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.get', { uuid });\n if (!perspective)\n return null;\n return new PerspectiveProxy(perspective, this);\n }\n catch (e) {\n if (e instanceof RpcError && e.status === 404)\n return null;\n throw e;\n }\n }\n async snapshotByUUID(uuid) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.snapshot', { uuid });\n }\n async publishSnapshotByUUID(uuid) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.publishSnapshot', { uuid });\n }\n async queryLinks(uuid, query) {\n const params = { uuid };\n if (query.source)\n params.source = query.source;\n if (query.predicate)\n params.predicate = query.predicate;\n if (query.target)\n params.target = query.target;\n if (query.fromDate)\n params.fromDate = query.fromDate instanceof Date ? query.fromDate.toISOString() : String(query.fromDate);\n if (query.untilDate)\n params.untilDate = query.untilDate instanceof Date ? query.untilDate.toISOString() : String(query.untilDate);\n if (query.limit !== undefined)\n params.limit = query.limit;\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.queryLinks', params);\n }\n async queryProlog(uuid, query) {\n const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.queryProlog', { uuid, query });\n return JSON.parse(result);\n }\n async querySparql(uuid, query) {\n const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.querySparql', { uuid, engine: 'sparql', query });\n return JSON.parse(result);\n }\n async subscribeQuery(uuid, query) {\n const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.subscribeQuery', { uuid, query });\n const { subscriptionId, result } = response;\n const parsed = normalizeQueryResult(result, 'Error parsing subscribeQuery result:');\n return { subscriptionId, result: parsed };\n }\n async perspectiveKeepAliveQuery(uuid, subscriptionId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.keepAliveQuery', { uuid, subscriptionId });\n }\n async perspectiveDisposeQuerySubscription(uuid, subscriptionId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.disposeQuery', { uuid, subscriptionId });\n }\n subscribeToQueryUpdates(subscriptionId, onData) {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").subscribe((data) => {\n const event = data;\n if (event.type !== 'query-subscription-update')\n return;\n const eventSubscriptionId = event.subscriptionId || event.subscription_id;\n if (eventSubscriptionId !== subscriptionId)\n return;\n const parsed = normalizeQueryResult(event.result, 'Error parsing query subscription:');\n onData(parsed);\n });\n __classPrivateFieldGet$9(this, _PerspectiveClient_querySubscriptionUnsubscribers, \"f\").set(subscriptionId, unsub);\n return unsub;\n }\n async keepAliveQuery(uuid, subscriptionId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.keepAliveQuery', { uuid, subscriptionId });\n }\n async disposeQuerySubscription(uuid, subscriptionId) {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_querySubscriptionUnsubscribers, \"f\").get(subscriptionId);\n if (unsub) {\n unsub();\n __classPrivateFieldGet$9(this, _PerspectiveClient_querySubscriptionUnsubscribers, \"f\").delete(subscriptionId);\n }\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.disposeQuery', { uuid, subscriptionId });\n }\n async modelQuery(uuid, className, queryJson, shapeJson) {\n const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });\n return JSON.parse(resultJson);\n }\n async evaluateGetters(uuid, className, instanceIds, shapeJson, propertyNames) {\n const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.evaluateGetters', {\n uuid,\n class_name: className,\n instance_ids: instanceIds,\n shape_json: shapeJson,\n ...(propertyNames && { property_names: propertyNames }),\n });\n return JSON.parse(resultJson);\n }\n async modelSubscribe(uuid, className, queryJson, shapeJson) {\n const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });\n return {\n subscriptionId: response.subscription_id,\n result: JSON.parse(response.result)\n };\n }\n async add(name) {\n const handle = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.create', { name });\n return new PerspectiveProxy(handle, this);\n }\n async update(uuid, name) {\n const handle = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.update', { uuid, name });\n return new PerspectiveProxy(handle, this);\n }\n async remove(uuid) {\n const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.remove', { uuid });\n return { perspectiveRemove: result };\n }\n async addLink(uuid, link, status = 'shared', batchId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.addLink', { uuid, link, status, batchId });\n }\n async addLinks(uuid, links, status = 'shared', batchId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.addLinks', { uuid, links, status, batchId });\n }\n async removeLinks(uuid, links, batchId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.removeLinks', { uuid, links, batchId });\n }\n async linkMutations(uuid, mutations, status) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.linkMutations', { uuid, mutations, status });\n }\n async addLinkExpression(uuid, link, status = 'shared', batchId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.addLinkExpression', { uuid, link, status, batchId });\n }\n async updateLink(uuid, oldLink, newLink, batchId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.updateLink', { uuid, oldLink, newLink, batchId });\n }\n async removeLink(uuid, link, batchId) {\n delete link.__typename;\n delete link.data.__typename;\n delete link.proof.__typename;\n delete link.status;\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.removeLink', { uuid, link, batchId });\n }\n async addSdna(uuid, name, sdnaCode, sdnaType, shaclJson) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.addSdna', { uuid, name, sdnaCode: sdnaCode || \"\", sdnaType, shaclJson });\n }\n async addSdnaBatch(uuid, entries) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.addSdna', { uuid, entries: entries.map(e => ({ ...e, sdnaCode: e.sdnaCode || \"\" })) });\n }\n async executeCommands(uuid, commands, expression, parameters, batchId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.executeCommands', { uuid, commands, expression, parameters, batchId });\n }\n async createSubject(uuid, subjectClass, expressionAddress, initialValues, batchId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.createSubject', { uuid, subjectClass, expressionAddress, initialValues, batchId });\n }\n async getSubjectData(uuid, subjectClass, expressionAddress) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.getSubjectData', { uuid, subjectClass, expressionAddress });\n }\n // ExpressionClient functions, needed for Subjects:\n async getExpression(expressionURI) {\n return await __classPrivateFieldGet$9(this, _PerspectiveClient_expressionClient, \"f\").get(expressionURI);\n }\n async createExpression(content, languageAddress) {\n return await __classPrivateFieldGet$9(this, _PerspectiveClient_expressionClient, \"f\").create(content, languageAddress);\n }\n // Subscriptions:\n addPerspectiveAddedListener(cb) {\n __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveAddedCallbacks, \"f\").push(cb);\n }\n subscribePerspectiveAdded() {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'perspective-added') {\n __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveAddedCallbacks, \"f\").forEach(cb => cb(data.perspective));\n }\n });\n __classPrivateFieldGet$9(this, _PerspectiveClient_unsubscribers, \"f\").push(unsub);\n }\n addPerspectiveUpdatedListener(cb) {\n __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveUpdatedCallbacks, \"f\").push(cb);\n }\n subscribePerspectiveUpdated() {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'perspective-updated') {\n __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveUpdatedCallbacks, \"f\").forEach(cb => cb(data.perspective));\n }\n });\n __classPrivateFieldGet$9(this, _PerspectiveClient_unsubscribers, \"f\").push(unsub);\n }\n addPerspectiveSyncedListener(cb) {\n __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveSyncStateChangeCallbacks, \"f\").push(cb);\n }\n async addPerspectiveSyncStateChangeListener(uuid, cb) {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'sync-state-change' && data.uuid === uuid) {\n cb.forEach(c => c(data.state));\n }\n });\n __classPrivateFieldGet$9(this, _PerspectiveClient_unsubscribers, \"f\").push(unsub);\n await new Promise(resolve => setTimeout(resolve, 500));\n }\n addPerspectiveRemovedListener(cb) {\n __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveRemovedCallbacks, \"f\").push(cb);\n }\n subscribePerspectiveRemoved() {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'perspective-removed') {\n __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveRemovedCallbacks, \"f\").forEach(cb => cb(data.uuid));\n }\n });\n __classPrivateFieldGet$9(this, _PerspectiveClient_unsubscribers, \"f\").push(unsub);\n }\n async addPerspectiveLinkAddedListener(uuid, cb) {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'link-added' && data.perspectiveUuid === uuid) {\n cb.forEach(c => c(data.link));\n }\n });\n let existing = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, \"f\").get(uuid) || [];\n existing.push(unsub);\n __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, \"f\").set(uuid, existing);\n await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").waitForSubscription();\n }\n async addPerspectiveLinkRemovedListener(uuid, cb) {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'link-removed' && data.perspectiveUuid === uuid) {\n const link = data.link;\n if (!link.status) {\n delete link.status;\n }\n cb.forEach(c => c(link));\n }\n });\n let existing = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, \"f\").get(uuid) || [];\n existing.push(unsub);\n __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, \"f\").set(uuid, existing);\n await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").waitForSubscription();\n }\n async addPerspectiveLinkUpdatedListener(uuid, cb) {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'link-updated' && data.perspectiveUuid === uuid) {\n const newLink = data.newLink;\n const oldLink = data.oldLink;\n if (!newLink.status) {\n delete newLink.status;\n }\n if (!oldLink.status) {\n delete oldLink.status;\n }\n cb.forEach(c => c(data));\n }\n });\n let existing = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, \"f\").get(uuid) || [];\n existing.push(unsub);\n __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, \"f\").set(uuid, existing);\n await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").waitForSubscription();\n }\n /** Unsubscribe all link/sync-state listeners registered for the given perspective UUID.\n * Called by PerspectiveProxy.dispose() to prevent subscription leaks. */\n removeAllListeners(uuid) {\n const unsubs = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, \"f\").get(uuid);\n if (unsubs) {\n for (const fn of unsubs) {\n try {\n fn();\n }\n catch { }\n }\n __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, \"f\").delete(uuid);\n }\n }\n getNeighbourhoodProxy(uuid) {\n return new NeighbourhoodProxy(__classPrivateFieldGet$9(this, _PerspectiveClient_neighbourhoodClient, \"f\"), uuid);\n }\n async createBatch(uuid) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.createBatch', { uuid });\n }\n async commitBatch(uuid, batchId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.commitBatch', { uuid, batchId });\n }\n}\n_PerspectiveClient_apiClient = new WeakMap(), _PerspectiveClient_perspectiveAddedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveUpdatedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveRemovedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap(), _PerspectiveClient_unsubscribers = new WeakMap(), _PerspectiveClient_linkUnsubscribers = new WeakMap(), _PerspectiveClient_querySubscriptionUnsubscribers = new WeakMap();\n\n/**\n * PersistentCache \u2014 two-tier persistent key-value cache abstraction.\n *\n * Provides an IndexedDB-backed implementation for browsers and a no-op\n * NullCache fallback for Node.js / environments without IndexedDB.\n *\n * Design goals:\n * - Lazy open: IDB connection is deferred until first access\n * - Fire-and-forget writes: put() resolves immediately (best-effort persistence)\n * - Graceful degradation: all IDB errors resolve (never reject), so callers\n * never need try/catch around cache operations\n * - Tree-shakeable: import only what you need\n */\nvar __classPrivateFieldSet$8 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$8 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _IDBCache_instances, _IDBCache_dbName, _IDBCache_storeName, _IDBCache_dbPromise, _IDBCache_version, _IDBCache_open;\n// \u2500\u2500 IndexedDB Implementation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nclass IDBCache {\n constructor(dbName, storeName) {\n _IDBCache_instances.add(this);\n _IDBCache_dbName.set(this, void 0);\n _IDBCache_storeName.set(this, void 0);\n _IDBCache_dbPromise.set(this, null);\n _IDBCache_version.set(this, 1);\n __classPrivateFieldSet$8(this, _IDBCache_dbName, dbName, \"f\");\n __classPrivateFieldSet$8(this, _IDBCache_storeName, storeName, \"f\");\n }\n async get(key) {\n try {\n const db = await __classPrivateFieldGet$8(this, _IDBCache_instances, \"m\", _IDBCache_open).call(this);\n return new Promise((resolve) => {\n const tx = db.transaction(__classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\"), 'readonly');\n const store = tx.objectStore(__classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\"));\n const req = store.get(key);\n req.onsuccess = () => resolve(req.result ?? undefined);\n req.onerror = () => resolve(undefined);\n });\n }\n catch {\n return undefined;\n }\n }\n async put(key, value) {\n try {\n const db = await __classPrivateFieldGet$8(this, _IDBCache_instances, \"m\", _IDBCache_open).call(this);\n return new Promise((resolve) => {\n const tx = db.transaction(__classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\"), 'readwrite');\n const store = tx.objectStore(__classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\"));\n store.put(value, key);\n tx.oncomplete = () => resolve();\n tx.onerror = () => resolve(); // fire-and-forget\n });\n }\n catch {\n // degrade gracefully\n }\n }\n async delete(key) {\n try {\n const db = await __classPrivateFieldGet$8(this, _IDBCache_instances, \"m\", _IDBCache_open).call(this);\n return new Promise((resolve) => {\n const tx = db.transaction(__classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\"), 'readwrite');\n const store = tx.objectStore(__classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\"));\n store.delete(key);\n tx.oncomplete = () => resolve();\n tx.onerror = () => resolve();\n });\n }\n catch {\n // degrade gracefully\n }\n }\n async clear() {\n try {\n const db = await __classPrivateFieldGet$8(this, _IDBCache_instances, \"m\", _IDBCache_open).call(this);\n return new Promise((resolve) => {\n const tx = db.transaction(__classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\"), 'readwrite');\n const store = tx.objectStore(__classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\"));\n store.clear();\n tx.oncomplete = () => resolve();\n tx.onerror = () => resolve();\n });\n }\n catch {\n // degrade gracefully\n }\n }\n}\n_IDBCache_dbName = new WeakMap(), _IDBCache_storeName = new WeakMap(), _IDBCache_dbPromise = new WeakMap(), _IDBCache_version = new WeakMap(), _IDBCache_instances = new WeakSet(), _IDBCache_open = function _IDBCache_open() {\n if (!__classPrivateFieldGet$8(this, _IDBCache_dbPromise, \"f\")) {\n __classPrivateFieldSet$8(this, _IDBCache_dbPromise, new Promise((resolve, reject) => {\n const storeName = __classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\");\n const req = indexedDB.open(__classPrivateFieldGet$8(this, _IDBCache_dbName, \"f\"), __classPrivateFieldGet$8(this, _IDBCache_version, \"f\"));\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains(storeName)) {\n db.createObjectStore(storeName);\n }\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n }), \"f\");\n }\n return __classPrivateFieldGet$8(this, _IDBCache_dbPromise, \"f\");\n};\n// \u2500\u2500 NullCache (no-op fallback for Node.js) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nclass NullCache {\n async get(_key) { return undefined; }\n async put(_key, _value) { }\n async delete(_key) { }\n async clear() { }\n}\n// \u2500\u2500 Factory \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n/**\n * Create a PersistentCache backed by IndexedDB (browser) or NullCache (Node.js).\n *\n * @param dbName - IndexedDB database name\n * @param storeName - IndexedDB object store name\n */\nfunction createPersistentCache(dbName, storeName) {\n try {\n if (typeof indexedDB !== 'undefined') {\n return new IDBCache(dbName, storeName);\n }\n }\n catch {\n // indexedDB access threw (e.g. in a worker with restricted globals)\n }\n return new NullCache();\n}\n\nvar __classPrivateFieldSet$7 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$7 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _AgentClient_apiClient, _AgentClient_baseUrl, _AgentClient_token, _AgentClient_appsChangedCallback, _AgentClient_updatedCallbacks, _AgentClient_agentStatusChangedCallbacks, _AgentClient_hostingUserInfoChangedCallbacks, _AgentClient_computeLogUpdatedCallbacks, _AgentClient_unsubscribers, _AgentClient_memCache, _AgentClient_persistent, _AgentClient_selfDid;\nclass AgentClient {\n constructor(baseUrl, token, subscribe = true, sharedApiClient) {\n _AgentClient_apiClient.set(this, void 0);\n _AgentClient_baseUrl.set(this, void 0);\n _AgentClient_token.set(this, void 0);\n _AgentClient_appsChangedCallback.set(this, void 0);\n _AgentClient_updatedCallbacks.set(this, void 0);\n _AgentClient_agentStatusChangedCallbacks.set(this, void 0);\n _AgentClient_hostingUserInfoChangedCallbacks.set(this, void 0);\n _AgentClient_computeLogUpdatedCallbacks.set(this, void 0);\n _AgentClient_unsubscribers.set(this, void 0);\n // \u2500\u2500 byDID cache \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // L1: in-memory promise cache with timestamps for TTL\n _AgentClient_memCache.set(this, new Map());\n // L2: persistent cache (IndexedDB in browser, NullCache in Node)\n _AgentClient_persistent.set(this, void 0);\n // Self-DID for event-driven invalidation (no TTL for own profile)\n _AgentClient_selfDid.set(this, null);\n __classPrivateFieldSet$7(this, _AgentClient_baseUrl, baseUrl, \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_token, token, \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_updatedCallbacks, [], \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_agentStatusChangedCallbacks, [], \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_appsChangedCallback, [], \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_hostingUserInfoChangedCallbacks, [], \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_computeLogUpdatedCallbacks, [], \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_unsubscribers, [], \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_persistent, createPersistentCache('ad4m-agent-cache', 'agents'), \"f\");\n if (subscribe) {\n this.subscribeAgentUpdated();\n this.subscribeAgentStatusChanged();\n this.subscribeAppsChanged();\n }\n }\n async me() {\n const agent = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.get');\n let agentObject = new Agent(agent.did, agent.perspective);\n agentObject.directMessageLanguage = agent.directMessageLanguage;\n // Auto-set selfDid so event-driven cache invalidation works\n // without requiring apps to call setSelfDid() manually\n if (agentObject.did && !__classPrivateFieldGet$7(this, _AgentClient_selfDid, \"f\")) {\n __classPrivateFieldSet$7(this, _AgentClient_selfDid, agentObject.did, \"f\");\n }\n return agentObject;\n }\n async status() {\n const agentStatus = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.status');\n return new AgentStatus(agentStatus);\n }\n async generate(passphrase) {\n const result = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.generate', { passphrase });\n return new AgentStatus(result);\n }\n async import(args) {\n const result = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.import', { ...args });\n return new AgentStatus(result);\n }\n async lock(passphrase) {\n const result = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.lock', { passphrase });\n return new AgentStatus(result);\n }\n async unlock(passphrase, holochain = true) {\n const result = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.unlock', { passphrase, holochain });\n return new AgentStatus(result);\n }\n async byDID(did) {\n const now = Date.now();\n const cached = __classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").get(did);\n if (cached) {\n const isSelf = did === __classPrivateFieldGet$7(this, _AgentClient_selfDid, \"f\");\n // Self-DID: L1 always valid (event-driven invalidation)\n // Remote DID: L1 valid within TTL\n if (isSelf || (now - cached.ts) < AgentClient.REMOTE_AGENT_TTL_MS) {\n return cached.promise;\n }\n }\n // Deduplicate: store the promise immediately so concurrent calls share one RPC\n const promise = (async () => {\n // L2: check persistent cache before network\n const persisted = await __classPrivateFieldGet$7(this, _AgentClient_persistent, \"f\").get(did);\n if (persisted) {\n return persisted;\n }\n // L3: network fetch\n const result = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.byDid', { did });\n __classPrivateFieldGet$7(this, _AgentClient_persistent, \"f\").put(did, result); // fire-and-forget write to L2\n return result;\n })();\n __classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").set(did, { promise, ts: now });\n // Clean up on failure so next call retries\n promise.catch(() => {\n if (__classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").get(did)?.promise === promise) {\n __classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").delete(did);\n }\n });\n return promise;\n }\n /**\n * Set the current agent's own DID.\n * The self-DID receives event-driven invalidation and is never TTL-expired.\n */\n setSelfDid(did) {\n __classPrivateFieldSet$7(this, _AgentClient_selfDid, did, \"f\");\n }\n /**\n * Invalidate a specific DID's cache entry in both L1 and L2.\n */\n invalidateByDid(did) {\n __classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").delete(did);\n __classPrivateFieldGet$7(this, _AgentClient_persistent, \"f\").delete(did); // fire-and-forget\n }\n /**\n * Clear the entire L1 (memory) byDID cache.\n * L2 (IndexedDB) is preserved \u2014 agent data remains valid across sessions.\n */\n clearByDidCache() {\n __classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").clear();\n }\n async updatePublicPerspective(perspective) {\n const cleanedPerspective = JSON.parse(JSON.stringify(perspective));\n delete cleanedPerspective.__typename;\n cleanedPerspective.links.forEach((link) => {\n delete link.__typename;\n delete link.data.__typename;\n delete link.proof.__typename;\n delete link.status;\n });\n const a = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.updateProfile', { publicPerspective: cleanedPerspective });\n const agent = new Agent(a.did, a.perspective);\n agent.directMessageLanguage = a.directMessageLanguage;\n // Immediately update byDID cache so subsequent byDID() calls\n // return fresh data without waiting for the subscription event\n if (agent.did) {\n __classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").set(agent.did, { promise: Promise.resolve(agent), ts: Date.now() });\n __classPrivateFieldGet$7(this, _AgentClient_persistent, \"f\").put(agent.did, agent); // fire-and-forget\n }\n return agent;\n }\n async mutatePublicPerspective(mutations) {\n const perspectiveClient = new PerspectiveClient(__classPrivateFieldGet$7(this, _AgentClient_baseUrl, \"f\"), __classPrivateFieldGet$7(this, _AgentClient_token, \"f\"));\n const proxyPerspective = await perspectiveClient.add(\"Agent Perspective Proxy\");\n const agentMe = await this.me();\n if (agentMe.perspective) {\n await proxyPerspective.loadSnapshot(agentMe.perspective);\n }\n for (const addition of mutations.additions) {\n await proxyPerspective.add(addition);\n }\n for (const removal of mutations.removals) {\n await proxyPerspective.remove(removal);\n }\n const snapshot = await proxyPerspective.snapshot();\n const agent = await this.updatePublicPerspective(snapshot);\n await perspectiveClient.remove(proxyPerspective.uuid);\n return agent;\n }\n async updateDirectMessageLanguage(directMessageLanguage) {\n const a = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.updateProfile', { dmLanguage: directMessageLanguage });\n const agent = new Agent(a.did, a.perspective);\n agent.directMessageLanguage = a.directMessageLanguage;\n // Immediately update byDID cache so subsequent byDID() calls\n // return fresh data without waiting for the subscription event\n if (agent.did) {\n __classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").set(agent.did, { promise: Promise.resolve(agent), ts: Date.now() });\n __classPrivateFieldGet$7(this, _AgentClient_persistent, \"f\").put(agent.did, agent); // fire-and-forget\n }\n return agent;\n }\n async addEntanglementProofs(proofs) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.addEntanglementProofs', { proofs });\n }\n async deleteEntanglementProofs(proofs) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.deleteEntanglementProofs', { proofs });\n }\n async getEntanglementProofs() {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.getEntanglementProofs');\n }\n async entanglementProofPreFlight(deviceKey, deviceKeyType) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.entanglementProofPreflight', { deviceKey, deviceKeyType });\n }\n addUpdatedListener(listener) {\n __classPrivateFieldGet$7(this, _AgentClient_updatedCallbacks, \"f\").push(listener);\n }\n addAppChangedListener(listener) {\n __classPrivateFieldGet$7(this, _AgentClient_appsChangedCallback, \"f\").push(listener);\n }\n subscribeAgentUpdated() {\n const unsub = __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'agent-updated') {\n const agent = (data.agent || data);\n // Update L1 and L2 cache from the event payload\n if (agent.did) {\n __classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").set(agent.did, {\n promise: Promise.resolve(agent),\n ts: Date.now(),\n });\n __classPrivateFieldGet$7(this, _AgentClient_persistent, \"f\").put(agent.did, agent); // fire-and-forget\n }\n __classPrivateFieldGet$7(this, _AgentClient_updatedCallbacks, \"f\").forEach((cb) => cb(agent));\n }\n });\n __classPrivateFieldGet$7(this, _AgentClient_unsubscribers, \"f\").push(unsub);\n }\n subscribeAppsChanged() {\n const unsub = __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'apps-changed') {\n __classPrivateFieldGet$7(this, _AgentClient_appsChangedCallback, \"f\").forEach((cb) => cb());\n }\n });\n __classPrivateFieldGet$7(this, _AgentClient_unsubscribers, \"f\").push(unsub);\n }\n addAgentStatusChangedListener(listener) {\n __classPrivateFieldGet$7(this, _AgentClient_agentStatusChangedCallbacks, \"f\").push(listener);\n }\n subscribeAgentStatusChanged() {\n const unsub = __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'agent-status-changed') {\n __classPrivateFieldGet$7(this, _AgentClient_agentStatusChangedCallbacks, \"f\").forEach((cb) => cb((data.agent || data)));\n }\n });\n __classPrivateFieldGet$7(this, _AgentClient_unsubscribers, \"f\").push(unsub);\n }\n addHostingUserInfoChangedListener(listener) {\n __classPrivateFieldGet$7(this, _AgentClient_hostingUserInfoChangedCallbacks, \"f\").push(listener);\n }\n subscribeHostingUserInfoChanged() {\n const unsub = __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'hosting-user-info-changed') {\n __classPrivateFieldGet$7(this, _AgentClient_hostingUserInfoChangedCallbacks, \"f\").forEach((cb) => cb((data.info || data)));\n }\n });\n __classPrivateFieldGet$7(this, _AgentClient_unsubscribers, \"f\").push(unsub);\n }\n addComputeLogUpdatedListener(listener) {\n __classPrivateFieldGet$7(this, _AgentClient_computeLogUpdatedCallbacks, \"f\").push(listener);\n }\n subscribeComputeLogUpdated() {\n const unsub = __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'compute-log-updated') {\n __classPrivateFieldGet$7(this, _AgentClient_computeLogUpdatedCallbacks, \"f\").forEach((cb) => cb((data.entry || data)));\n }\n });\n __classPrivateFieldGet$7(this, _AgentClient_unsubscribers, \"f\").push(unsub);\n }\n async requestCapability(authInfo) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.requestCapability', { authInfo });\n }\n async permitCapability(auth) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.permitCapability', { auth });\n }\n async generateJwt(requestId, rand) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.generateJwt', { requestId, rand });\n }\n async getApps() {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.getApps');\n }\n async removeApp(requestId) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.removeApp', { id: requestId });\n }\n async revokeToken(requestId) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.revokeToken', { token: requestId });\n }\n async isLocked() {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.isLocked');\n }\n async signMessage(message) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.sign', { message });\n }\n // Multi-user methods\n async createUser(email, password, appInfo) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('user.create', { email, password, appInfo });\n }\n async loginUser(email, password) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('user.login', { email, password });\n }\n async requestLoginVerification(email, appInfo) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('user.requestVerification', { email, appInfo });\n }\n async verifyEmailCode(email, code, verificationType) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('user.verifyEmail', { email, code, verificationType });\n }\n // Hosting methods\n async hostingUserInfo() {\n const resp = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('hosting.info');\n const info = resp?.userInfo || resp;\n return new HostingUserInfo(info.email || '', info.freeAccess ? 'unlimited' : String(info.credits ?? info.remainingCredits ?? '0'), info.hotWalletAddress || undefined, !!info.freeAccess);\n }\n async computeLog(since, limit, userEmail) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('runtime.computeLog', { since, limit, userEmail });\n }\n async setHotWalletAddress(address) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('hosting.setHotWallet', { address });\n }\n async requestPayment(amountHOT) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('hosting.requestPayment', { amountHOT });\n }\n}\n_AgentClient_apiClient = new WeakMap(), _AgentClient_baseUrl = new WeakMap(), _AgentClient_token = new WeakMap(), _AgentClient_appsChangedCallback = new WeakMap(), _AgentClient_updatedCallbacks = new WeakMap(), _AgentClient_agentStatusChangedCallbacks = new WeakMap(), _AgentClient_hostingUserInfoChangedCallbacks = new WeakMap(), _AgentClient_computeLogUpdatedCallbacks = new WeakMap(), _AgentClient_unsubscribers = new WeakMap(), _AgentClient_memCache = new WeakMap(), _AgentClient_persistent = new WeakMap(), _AgentClient_selfDid = new WeakMap();\n/** TTL for remote (non-self) agent profiles in L1 cache (ms). */\nAgentClient.REMOTE_AGENT_TTL_MS = 5 * 60000; // 5 minutes\n\nvar __classPrivateFieldSet$6 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$6 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _LanguageClient_apiClient;\nclass LanguageClient {\n constructor(baseUrl, token, sharedApiClient) {\n _LanguageClient_apiClient.set(this, void 0);\n __classPrivateFieldSet$6(this, _LanguageClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), \"f\");\n }\n async byAddress(address) {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.get', { address });\n }\n async byFilter(filter) {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.all', { filter });\n }\n async all() {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.all');\n }\n async writeSettings(languageAddress, settings) {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.writeSettings', { address: languageAddress, settings });\n }\n async applyTemplateAndPublish(sourceLanguageHash, templateData) {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.applyTemplate', { sourceLanguageHash, templateData });\n }\n async publish(languagePath, languageMeta) {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.publish', { languagePath, languageMeta });\n }\n async meta(address) {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.meta', { address });\n }\n async source(address) {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.source', { address });\n }\n async remove(address) {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.remove', { address });\n }\n}\n_LanguageClient_apiClient = new WeakMap();\n\nvar __classPrivateFieldSet$5 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$5 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _NeighbourhoodClient_apiClient, _NeighbourhoodClient_signalHandlers, _NeighbourhoodClient_signalUnsubscribers;\nclass NeighbourhoodClient {\n constructor(baseUrl, token, sharedApiClient) {\n _NeighbourhoodClient_apiClient.set(this, void 0);\n _NeighbourhoodClient_signalHandlers.set(this, new Map());\n _NeighbourhoodClient_signalUnsubscribers.set(this, new Map());\n __classPrivateFieldSet$5(this, _NeighbourhoodClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), \"f\");\n }\n async publishFromPerspective(perspectiveUUID, linkLanguage, meta) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.publish', {\n perspectiveUUID, linkLanguage, meta\n });\n }\n async joinFromUrl(url) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.join', { url });\n }\n async otherAgents(perspectiveUUID) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.otherAgents', { uuid: perspectiveUUID });\n }\n async hasTelepresenceAdapter(perspectiveUUID) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.hasTelepresence', { uuid: perspectiveUUID });\n }\n async onlineAgents(perspectiveUUID) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.onlineAgents', { uuid: perspectiveUUID });\n }\n async setOnlineStatus(perspectiveUUID, status) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.setOnlineStatus', { uuid: perspectiveUUID, status });\n }\n async setOnlineStatusU(perspectiveUUID, status) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.setOnlineStatus', { uuid: perspectiveUUID, status, signed: false });\n }\n async sendSignal(perspectiveUUID, remoteAgentDid, payload) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.sendSignal', {\n uuid: perspectiveUUID, remoteAgentDid, payload\n });\n }\n async sendSignalU(perspectiveUUID, remoteAgentDid, payload) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.sendSignal', {\n uuid: perspectiveUUID, remoteAgentDid, payload, signed: false\n });\n }\n async sendBroadcast(perspectiveUUID, payload, loopback = false) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.sendBroadcast', {\n uuid: perspectiveUUID, payload, loopback\n });\n }\n async sendBroadcastU(perspectiveUUID, payload, loopback = false) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.sendBroadcast', {\n uuid: perspectiveUUID, payload, loopback, signed: false\n });\n }\n dispatchSignal(perspectiveUUID, signal) {\n const handlers = __classPrivateFieldGet$5(this, _NeighbourhoodClient_signalHandlers, \"f\").get(perspectiveUUID);\n if (handlers) {\n for (const handler of handlers) {\n try {\n handler(signal);\n }\n catch (e) {\n console.error(\"Error in signal handler:\", e);\n }\n }\n }\n }\n async subscribeToSignals(perspectiveUUID) {\n const unsub = __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'signal') {\n this.dispatchSignal(perspectiveUUID, data.signal);\n }\n });\n __classPrivateFieldGet$5(this, _NeighbourhoodClient_signalUnsubscribers, \"f\").set(perspectiveUUID, unsub);\n }\n async addSignalHandler(perspectiveUUID, handler) {\n let handlersForPerspective = __classPrivateFieldGet$5(this, _NeighbourhoodClient_signalHandlers, \"f\").get(perspectiveUUID);\n if (!handlersForPerspective) {\n handlersForPerspective = [];\n __classPrivateFieldGet$5(this, _NeighbourhoodClient_signalHandlers, \"f\").set(perspectiveUUID, handlersForPerspective);\n handlersForPerspective.push(handler);\n await this.subscribeToSignals(perspectiveUUID);\n }\n else {\n handlersForPerspective.push(handler);\n }\n }\n removeSignalHandler(perspectiveUUID, handler) {\n const handlersForPerspective = __classPrivateFieldGet$5(this, _NeighbourhoodClient_signalHandlers, \"f\").get(perspectiveUUID);\n if (handlersForPerspective) {\n const index = handlersForPerspective.indexOf(handler);\n if (index > -1) {\n handlersForPerspective.splice(index, 1);\n }\n if (handlersForPerspective.length === 0) {\n __classPrivateFieldGet$5(this, _NeighbourhoodClient_signalHandlers, \"f\").delete(perspectiveUUID);\n const unsub = __classPrivateFieldGet$5(this, _NeighbourhoodClient_signalUnsubscribers, \"f\").get(perspectiveUUID);\n if (unsub) {\n unsub();\n __classPrivateFieldGet$5(this, _NeighbourhoodClient_signalUnsubscribers, \"f\").delete(perspectiveUUID);\n }\n }\n }\n }\n}\n_NeighbourhoodClient_apiClient = new WeakMap(), _NeighbourhoodClient_signalHandlers = new WeakMap(), _NeighbourhoodClient_signalUnsubscribers = new WeakMap();\n\nvar __classPrivateFieldSet$4 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$4 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _RuntimeClient_apiClient, _RuntimeClient_messageReceivedCallbacks, _RuntimeClient_exceptionOccurredCallbacks, _RuntimeClient_notificationTriggeredCallbacks, _RuntimeClient_notificationRequestedCallbacks, _RuntimeClient_unsubscribers;\nfunction normalizeExceptionType(type) {\n if (typeof type !== 'string' || type === type.toUpperCase()) {\n return type;\n }\n return type\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/([A-Z])([A-Z][a-z])/g, '$1_$2')\n .toUpperCase();\n}\nclass RuntimeClient {\n constructor(baseUrl, token, subscribe = true, sharedApiClient) {\n _RuntimeClient_apiClient.set(this, void 0);\n _RuntimeClient_messageReceivedCallbacks.set(this, void 0);\n _RuntimeClient_exceptionOccurredCallbacks.set(this, void 0);\n _RuntimeClient_notificationTriggeredCallbacks.set(this, void 0);\n _RuntimeClient_notificationRequestedCallbacks.set(this, void 0);\n _RuntimeClient_unsubscribers.set(this, void 0);\n __classPrivateFieldSet$4(this, _RuntimeClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), \"f\");\n __classPrivateFieldSet$4(this, _RuntimeClient_messageReceivedCallbacks, [], \"f\");\n __classPrivateFieldSet$4(this, _RuntimeClient_exceptionOccurredCallbacks, [], \"f\");\n __classPrivateFieldSet$4(this, _RuntimeClient_notificationTriggeredCallbacks, [], \"f\");\n __classPrivateFieldSet$4(this, _RuntimeClient_notificationRequestedCallbacks, [], \"f\");\n __classPrivateFieldSet$4(this, _RuntimeClient_unsubscribers, [], \"f\");\n if (subscribe) {\n this.subscribeMessageReceived();\n this.subscribeExceptionOccurred();\n this.subscribeNotificationTriggered();\n }\n }\n async info() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.info');\n }\n async tlsDomain() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.tlsDomain');\n }\n async quit() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.quit');\n }\n async openLink(url) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.openLink', { url });\n }\n async addTrustedAgents(agents) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('agent.addTrustedAgents', { agents });\n }\n async deleteTrustedAgents(agents) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('agent.deleteTrustedAgents', { agents });\n }\n async getTrustedAgents() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('agent.getTrustedAgents');\n }\n async addKnownLinkLanguageTemplates(addresses) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.addLinkLanguageTemplates', { addresses });\n }\n async removeKnownLinkLanguageTemplates(addresses) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.removeLinkLanguageTemplates', { addresses });\n }\n async knownLinkLanguageTemplates() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.linkLanguageTemplates');\n }\n async addFriends(dids) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.addFriends', { dids });\n }\n async removeFriends(dids) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.removeFriends', { dids });\n }\n async friends() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.friends');\n }\n async hcAgentInfos() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.hcAgentInfos');\n }\n async getNetworkMetrics() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.networkMetrics');\n }\n async restartHolochain() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.restartHolochain');\n }\n async hcAddAgentInfos(agentInfos) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.addHcAgentInfos', { agentInfos });\n }\n async verifyStringSignedByDid(did, didSigningKeyId, data, signedData) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.verifySignature', { did, didSigningKeyId, data, signedData });\n }\n async setStatus(perspective) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.setStatus', { status: perspective });\n }\n async friendStatus(did) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.friendStatus', { did });\n }\n async friendSendMessage(did, message) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.sendFriendMessage', { did, message });\n }\n async messageInbox(filter) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.inbox', { filter });\n }\n async messageOutbox(filter) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.outbox', { filter });\n }\n async requestInstallNotification(notification) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.createNotification', { ...notification });\n }\n async grantNotification(id) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.grantNotification', { id, granted: true });\n }\n async exportDb(filePath) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.exportData', { type: \"db\", filePath });\n }\n async importDb(filePath) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.importData', { type: \"db\", filePath });\n }\n async notifications() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.notifications');\n }\n async updateNotification(id, notification) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.updateNotification', { ...notification, id });\n }\n async removeNotification(id) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.deleteNotification', { id });\n }\n async exportPerspective(uuid, filePath) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.exportData', { type: \"perspective\", perspectiveUuid: uuid, filePath });\n }\n async importPerspective(filePath) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.importData', { type: \"perspective\", filePath });\n }\n async multiUserEnabled() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.multiUserEnabled');\n }\n async setMultiUserEnabled(enabled) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.setMultiUserEnabled', { enabled });\n }\n async freeHostingEnabled() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.freeHostingEnabled');\n }\n async setFreeHostingEnabled(enabled) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.setFreeHostingEnabled', { enabled });\n }\n async listUsers() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.list');\n }\n async userWalletAddress(email) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.wallet', { email });\n }\n async emailTestModeEnable() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.emailTest', { action: 'enable' });\n }\n async emailTestModeDisable() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.emailTest', { action: 'disable' });\n }\n async emailTestGetCode(email) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.emailTest', { action: 'get-code', email });\n }\n async emailTestClearCodes() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.emailTest', { action: 'clear-codes' });\n }\n async emailTestSetExpiry(email, verificationType, expiresAt) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.emailTest', { action: 'set-expiry', email, verificationType, expiresAt });\n }\n // ---- Unyt / mHOT methods ----\n async unytAgentKey() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.unytAgentKey');\n }\n async unytHotAgentPubkey() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.unytHotAgentPubkey');\n }\n async unytWalletBalance() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.unytWalletBalance');\n }\n async unytWalletHistory(page, perPage) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.unytWalletHistory', { page, perPage });\n }\n async unytVersionInfo() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.unytVersionInfo');\n }\n async unytSetMembraneProof(proof) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.unytSetMembraneProof', { proof });\n }\n async unytReinstallDna() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.unytReinstallDna');\n }\n async unytSendHot(recipient, amount) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.unytSendHot', { recipient, amount });\n }\n async setUserCredits(email, amount) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.credits', { email, amount });\n }\n async setUserFreeAccess(email, enabled) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.freeAccess', { email, enabled });\n }\n async setHostRates(ratesJson) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.setHostRates', { ratesJson });\n }\n async getHostRates() {\n const result = await __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.getHostRates');\n try {\n return JSON.parse(result);\n }\n catch {\n return [];\n }\n }\n addNotificationTriggeredCallback(cb) {\n __classPrivateFieldGet$4(this, _RuntimeClient_notificationTriggeredCallbacks, \"f\").push(cb);\n }\n subscribeNotificationTriggered() {\n const unsub = __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'notification-triggered') {\n __classPrivateFieldGet$4(this, _RuntimeClient_notificationTriggeredCallbacks, \"f\").forEach(cb => cb(data.notification));\n }\n });\n __classPrivateFieldGet$4(this, _RuntimeClient_unsubscribers, \"f\").push(unsub);\n }\n addMessageCallback(cb) {\n __classPrivateFieldGet$4(this, _RuntimeClient_messageReceivedCallbacks, \"f\").push(cb);\n }\n subscribeMessageReceived() {\n const unsub = __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'message-received') {\n __classPrivateFieldGet$4(this, _RuntimeClient_messageReceivedCallbacks, \"f\").forEach(cb => cb(data.message));\n }\n });\n __classPrivateFieldGet$4(this, _RuntimeClient_unsubscribers, \"f\").push(unsub);\n }\n addExceptionCallback(cb) {\n __classPrivateFieldGet$4(this, _RuntimeClient_exceptionOccurredCallbacks, \"f\").push(cb);\n }\n subscribeExceptionOccurred() {\n const unsub = __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'exception-occurred' && data.exception) {\n const exception = data.exception;\n const normalizedException = {\n ...exception,\n type: normalizeExceptionType(exception.type),\n };\n __classPrivateFieldGet$4(this, _RuntimeClient_exceptionOccurredCallbacks, \"f\").forEach(cb => cb(normalizedException));\n }\n });\n __classPrivateFieldGet$4(this, _RuntimeClient_unsubscribers, \"f\").push(unsub);\n }\n}\n_RuntimeClient_apiClient = new WeakMap(), _RuntimeClient_messageReceivedCallbacks = new WeakMap(), _RuntimeClient_exceptionOccurredCallbacks = new WeakMap(), _RuntimeClient_notificationTriggeredCallbacks = new WeakMap(), _RuntimeClient_notificationRequestedCallbacks = new WeakMap(), _RuntimeClient_unsubscribers = new WeakMap();\n\nvar __classPrivateFieldSet$3 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$3 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _ExpressionClient_instances, _ExpressionClient_apiClient, _ExpressionClient_memCache, _ExpressionClient_inflight, _ExpressionClient_totalMemBytes, _ExpressionClient_persistent, _ExpressionClient_memCacheResult;\nclass ExpressionClient {\n constructor(baseUrl, token, sharedApiClient) {\n _ExpressionClient_instances.add(this);\n _ExpressionClient_apiClient.set(this, void 0);\n // L1: in-memory LRU cache (hot path, sub-ms)\n _ExpressionClient_memCache.set(this, new Map());\n _ExpressionClient_inflight.set(this, new Map());\n _ExpressionClient_totalMemBytes.set(this, 0);\n // L2: persistent cache (IndexedDB in browser, NullCache in Node)\n _ExpressionClient_persistent.set(this, void 0);\n __classPrivateFieldSet$3(this, _ExpressionClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), \"f\");\n __classPrivateFieldSet$3(this, _ExpressionClient_persistent, createPersistentCache('ad4m-expression-cache', 'expressions'), \"f\");\n }\n async get(url, alwaysGet = false) {\n // Existing literal fast-path\n if (!alwaysGet) {\n try {\n let literalValue = Literal.fromUrl(url).get();\n if (typeof literalValue === 'object' && literalValue !== null) {\n if ('author' in literalValue && 'timestamp' in literalValue && 'data' in literalValue && 'proof' in literalValue) {\n return literalValue;\n }\n }\n }\n catch (e) { }\n }\n // L1: memory hit\n if (!alwaysGet) {\n const memHit = __classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").get(url);\n if (memHit)\n return memHit.data;\n }\n // Deduplicate in-flight requests\n if (!alwaysGet) {\n const existing = __classPrivateFieldGet$3(this, _ExpressionClient_inflight, \"f\").get(url);\n if (existing)\n return existing;\n }\n // L2 check + L3 network\n const promise = (async () => {\n if (!alwaysGet) {\n const persisted = await __classPrivateFieldGet$3(this, _ExpressionClient_persistent, \"f\").get(url);\n if (persisted) {\n __classPrivateFieldGet$3(this, _ExpressionClient_instances, \"m\", _ExpressionClient_memCacheResult).call(this, url, persisted); // promote to L1\n return persisted;\n }\n }\n // L3: network fetch\n const result = await __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, \"f\").call('expression.get', { url });\n __classPrivateFieldGet$3(this, _ExpressionClient_instances, \"m\", _ExpressionClient_memCacheResult).call(this, url, result);\n __classPrivateFieldGet$3(this, _ExpressionClient_persistent, \"f\").put(url, result); // fire-and-forget write to L2\n return result;\n })();\n __classPrivateFieldGet$3(this, _ExpressionClient_inflight, \"f\").set(url, promise);\n try {\n return await promise;\n }\n finally {\n __classPrivateFieldGet$3(this, _ExpressionClient_inflight, \"f\").delete(url);\n }\n }\n async getMany(urls) {\n // Check L1 first\n const results = urls.map(u => __classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").get(u)?.data ?? null);\n let uncachedIndices = results\n .map((r, i) => r === null ? i : -1)\n .filter(i => i >= 0);\n if (uncachedIndices.length === 0)\n return results;\n // Check L2 for remaining misses\n const l2Results = await Promise.all(uncachedIndices.map(i => __classPrivateFieldGet$3(this, _ExpressionClient_persistent, \"f\").get(urls[i])));\n const stillMissing = [];\n for (let j = 0; j < uncachedIndices.length; j++) {\n const idx = uncachedIndices[j];\n if (l2Results[j]) {\n results[idx] = l2Results[j];\n __classPrivateFieldGet$3(this, _ExpressionClient_instances, \"m\", _ExpressionClient_memCacheResult).call(this, urls[idx], l2Results[j]); // promote to L1\n }\n else {\n stillMissing.push(idx);\n }\n }\n if (stillMissing.length === 0)\n return results;\n // L3: fetch only truly uncached URLs\n const uncachedUrls = stillMissing.map(i => urls[i]);\n const fetched = await __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, \"f\").call('expression.getMany', { urls: uncachedUrls });\n for (let i = 0; i < stillMissing.length; i++) {\n const idx = stillMissing[i];\n results[idx] = fetched[i];\n if (fetched[i]) {\n __classPrivateFieldGet$3(this, _ExpressionClient_instances, \"m\", _ExpressionClient_memCacheResult).call(this, uncachedUrls[i], fetched[i]);\n __classPrivateFieldGet$3(this, _ExpressionClient_persistent, \"f\").put(uncachedUrls[i], fetched[i]); // fire-and-forget\n }\n }\n return results;\n }\n /**\n * Clear both L1 (memory) and L2 (persistent) expression caches.\n */\n clearCache() {\n __classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").clear();\n __classPrivateFieldGet$3(this, _ExpressionClient_inflight, \"f\").clear();\n __classPrivateFieldSet$3(this, _ExpressionClient_totalMemBytes, 0, \"f\");\n __classPrivateFieldGet$3(this, _ExpressionClient_persistent, \"f\").clear(); // fire-and-forget\n }\n async getRaw(url) {\n return __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, \"f\").call('expression.get', { url, raw: true });\n }\n async create(content, languageAddress) {\n const serialized = JSON.stringify(content);\n return __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, \"f\").call('expression.create', { content: serialized, languageAddress });\n }\n async interactions(url) {\n return __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, \"f\").call('expression.interactions', { url });\n }\n async interact(url, interactionCall) {\n const result = await __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, \"f\").call('expression.interact', { url, interactionCall });\n // Interactions can mutate the expression \u2014 invalidate cache so next get() fetches fresh\n __classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").delete(url);\n __classPrivateFieldGet$3(this, _ExpressionClient_inflight, \"f\").delete(url);\n __classPrivateFieldGet$3(this, _ExpressionClient_persistent, \"f\").delete(url); // fire-and-forget\n return result;\n }\n}\n_ExpressionClient_apiClient = new WeakMap(), _ExpressionClient_memCache = new WeakMap(), _ExpressionClient_inflight = new WeakMap(), _ExpressionClient_totalMemBytes = new WeakMap(), _ExpressionClient_persistent = new WeakMap(), _ExpressionClient_instances = new WeakSet(), _ExpressionClient_memCacheResult = function _ExpressionClient_memCacheResult(url, data) {\n const size = JSON.stringify(data).length;\n // Evict oldest entries if we'd exceed limits\n while (__classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").size >= ExpressionClient.MAX_MEM_ENTRIES ||\n __classPrivateFieldGet$3(this, _ExpressionClient_totalMemBytes, \"f\") + size > ExpressionClient.MAX_MEM_BYTES) {\n const oldest = __classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").keys().next().value;\n if (!oldest)\n break;\n const entry = __classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").get(oldest);\n __classPrivateFieldSet$3(this, _ExpressionClient_totalMemBytes, __classPrivateFieldGet$3(this, _ExpressionClient_totalMemBytes, \"f\") - entry.size, \"f\");\n __classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").delete(oldest);\n }\n __classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").set(url, { data, size });\n __classPrivateFieldSet$3(this, _ExpressionClient_totalMemBytes, __classPrivateFieldGet$3(this, _ExpressionClient_totalMemBytes, \"f\") + size, \"f\");\n};\n/** Maximum number of entries in the L1 memory cache. */\nExpressionClient.MAX_MEM_ENTRIES = 200;\n/** Maximum total size (in bytes) of L1 memory cache values. */\nExpressionClient.MAX_MEM_BYTES = 5 * 1024 * 1024; // 5 MB\n\nvar base64Js = {};\n\nbase64Js.byteLength = byteLength;\nbase64Js.toByteArray = toByteArray;\nbase64Js.fromByteArray = fromByteArray;\n\nvar lookup = [];\nvar revLookup = [];\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i];\n revLookup[code.charCodeAt(i)] = i;\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62;\nrevLookup['_'.charCodeAt(0)] = 63;\n\nfunction getLens (b64) {\n var len = b64.length;\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=');\n if (validLen === -1) validLen = len;\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4);\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64);\n var validLen = lens[0];\n var placeHoldersLen = lens[1];\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp;\n var lens = getLens(b64);\n var validLen = lens[0];\n var placeHoldersLen = lens[1];\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));\n\n var curByte = 0;\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen;\n\n var i;\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)];\n arr[curByte++] = (tmp >> 16) & 0xFF;\n arr[curByte++] = (tmp >> 8) & 0xFF;\n arr[curByte++] = tmp & 0xFF;\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4);\n arr[curByte++] = tmp & 0xFF;\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2);\n arr[curByte++] = (tmp >> 8) & 0xFF;\n arr[curByte++] = tmp & 0xFF;\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp;\n var output = [];\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF);\n output.push(tripletToBase64(tmp));\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp;\n var len = uint8.length;\n var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes\n var parts = [];\n var maxChunkLength = 16383; // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1];\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n );\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1];\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n );\n }\n\n return parts.join('')\n}\n\n/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n//const Z_FILTERED = 1;\n//const Z_HUFFMAN_ONLY = 2;\n//const Z_RLE = 3;\nconst Z_FIXED$1 = 4;\n//const Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nconst Z_BINARY = 0;\nconst Z_TEXT = 1;\n//const Z_ASCII = 1; // = Z_TEXT\nconst Z_UNKNOWN$1 = 2;\n\n/*============================================================================*/\n\n\nfunction zero$1(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n// From zutil.h\n\nconst STORED_BLOCK = 0;\nconst STATIC_TREES = 1;\nconst DYN_TREES = 2;\n/* The three kinds of block type */\n\nconst MIN_MATCH$1 = 3;\nconst MAX_MATCH$1 = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nconst LENGTH_CODES$1 = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nconst LITERALS$1 = 256;\n/* number of literal bytes 0..255 */\n\nconst L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nconst D_CODES$1 = 30;\n/* number of distance codes */\n\nconst BL_CODES$1 = 19;\n/* number of codes used to transfer the bit lengths */\n\nconst HEAP_SIZE$1 = 2 * L_CODES$1 + 1;\n/* maximum heap size */\n\nconst MAX_BITS$1 = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nconst MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nconst END_BLOCK = 256;\n/* end of block literal code */\n\nconst REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nconst REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nconst REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nconst extra_lbits = /* extra bits for each length code */\n new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);\n\nconst extra_dbits = /* extra bits for each distance code */\n new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);\n\nconst extra_blbits = /* extra bits for each bit length code */\n new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);\n\nconst bl_order =\n new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nconst DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nconst static_ltree = new Array((L_CODES$1 + 2) * 2);\nzero$1(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nconst static_dtree = new Array(D_CODES$1 * 2);\nzero$1(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nconst _dist_code = new Array(DIST_CODE_LEN);\nzero$1(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nconst _length_code = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1);\nzero$1(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nconst base_length = new Array(LENGTH_CODES$1);\nzero$1(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nconst base_dist = new Array(D_CODES$1);\nzero$1(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nlet static_l_desc;\nlet static_d_desc;\nlet static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nconst d_code = (dist) => {\n\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n};\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nconst put_short = (s, w) => {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = (w) & 0xff;\n s.pending_buf[s.pending++] = (w >>> 8) & 0xff;\n};\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nconst send_bits = (s, value, length) => {\n\n if (s.bi_valid > (Buf_size - length)) {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> (Buf_size - s.bi_valid);\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n s.bi_valid += length;\n }\n};\n\n\nconst send_code = (s, c, tree) => {\n\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n};\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nconst bi_reverse = (code, len) => {\n\n let res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nconst bi_flush = (s) => {\n\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n};\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nconst gen_bitlen = (s, desc) => {\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n\n const tree = desc.dyn_tree;\n const max_code = desc.max_code;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const extra = desc.stat_desc.extra_bits;\n const base = desc.stat_desc.extra_base;\n const max_length = desc.stat_desc.max_length;\n let h; /* heap index */\n let n, m; /* iterate over the tree elements */\n let bits; /* bit length */\n let xbits; /* extra bits */\n let f; /* frequency */\n let overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS$1; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE$1; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) { continue; } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) { return; }\n\n // Tracev((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) { bits--; }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) { continue; }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Tracev((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n};\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nconst gen_codes = (tree, max_code, bl_count) => {\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n\n const next_code = new Array(MAX_BITS$1 + 1); /* next code value for each bit length */\n let code = 0; /* running code value */\n let bits; /* bit index */\n let n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS$1; bits++) {\n code = (code + bl_count[bits - 1]) << 1;\n next_code[bits] = code;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,\n // \"inconsistent bit counts\");\n //Tracev((stderr,\"\\ngen_codes: max_code %d \", max_code));\n\n for (n = 0; n <= max_code; n++) {\n let len = tree[n * 2 + 1]/*.Len*/;\n if (len === 0) { continue; }\n /* Now reverse the bits */\n tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);\n\n //Tracecv(tree != static_ltree, (stderr,\"\\nn %3d %c l %2d c %4x (%x) \",\n // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));\n }\n};\n\n\n/* ===========================================================================\n * Initialize the various 'constant' tables.\n */\nconst tr_static_init = () => {\n\n let n; /* iterates over tree elements */\n let bits; /* bit counter */\n let length; /* length value */\n let code; /* code value */\n let dist; /* distance index */\n const bl_count = new Array(MAX_BITS$1 + 1);\n /* number of codes at each bit length for an optimal tree */\n\n // do check in _tr_init()\n //if (static_init_done) return;\n\n /* For some embedded targets, global variables are not initialized: */\n/*#ifdef NO_INIT_GLOBAL_POINTERS\n static_l_desc.static_tree = static_ltree;\n static_l_desc.extra_bits = extra_lbits;\n static_d_desc.static_tree = static_dtree;\n static_d_desc.extra_bits = extra_dbits;\n static_bl_desc.extra_bits = extra_blbits;\n#endif*/\n\n /* Initialize the mapping length (0..255) -> length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES$1 - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < (1 << extra_lbits[code]); n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < (1 << extra_dbits[code]); n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES$1; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS$1; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES$1 + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES$1; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS$1 + 1, L_CODES$1, MAX_BITS$1);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES$1, MAX_BITS$1);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES$1, MAX_BL_BITS);\n\n //static_init_done = true;\n};\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nconst init_block = (s) => {\n\n let n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES$1; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < D_CODES$1; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < BL_CODES$1; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.sym_next = s.matches = 0;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nconst bi_windup = (s) =>\n{\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n};\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nconst smaller = (tree, n, m, depth) => {\n\n const _n2 = n * 2;\n const _m2 = m * 2;\n return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));\n};\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nconst pqdownheap = (s, tree, k) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n\n const v = s.heap[k];\n let j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) { break; }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n};\n\n\n// inlined manually\n// const SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nconst compress_block = (s, ltree, dtree) => {\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n\n let dist; /* distance of matched string */\n let lc; /* match length or unmatched char (if dist == 0) */\n let sx = 0; /* running index in sym_buf */\n let code; /* the code to send */\n let extra; /* number of extra bits to send */\n\n if (s.sym_next !== 0) {\n do {\n dist = s.pending_buf[s.sym_buf + sx++] & 0xff;\n dist += (s.pending_buf[s.sym_buf + sx++] & 0xff) << 8;\n lc = s.pending_buf[s.sym_buf + sx++];\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS$1 + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and sym_buf is ok: */\n //Assert(s->pending < s->lit_bufsize + sx, \"pendingBuf overflow\");\n\n } while (sx < s.sym_next);\n }\n\n send_code(s, END_BLOCK, ltree);\n};\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nconst build_tree = (s, desc) => {\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n\n const tree = desc.dyn_tree;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const elems = desc.stat_desc.elems;\n let n, m; /* iterate over heap elements */\n let max_code = -1; /* largest code with non zero frequency */\n let node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE$1;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n};\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nconst scan_tree = (s, tree, max_code) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nconst send_tree = (s, tree, max_code) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nconst build_bl_tree = (s) => {\n\n let max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES$1 - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n};\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nconst send_all_trees = (s, lcodes, dcodes, blcodes) => {\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n\n let rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n};\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"block list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"allow list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nconst detect_data_type = (s) => {\n /* block_mask is the bit mask of block-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n let block_mask = 0xf3ffc07f;\n let n;\n\n /* Check for non-textual (\"block-listed\") bytes. */\n for (n = 0; n <= 31; n++, block_mask >>>= 1) {\n if ((block_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"allow-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS$1; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"block-listed\" or \"allow-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n};\n\n\nlet static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nconst _tr_init$1 = (s) =>\n{\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n};\n\n\n/* ===========================================================================\n * Send a stored block\n */\nconst _tr_stored_block$1 = (s, buf, stored_len, last) => {\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n bi_windup(s); /* align on byte boundary */\n put_short(s, stored_len);\n put_short(s, ~stored_len);\n if (stored_len) {\n s.pending_buf.set(s.window.subarray(buf, buf + stored_len), s.pending);\n }\n s.pending += stored_len;\n};\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nconst _tr_align$1 = (s) => {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n};\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and write out the encoded block.\n */\nconst _tr_flush_block$1 = (s, buf, stored_len, last) => {\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n\n let opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n let max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN$1) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = (s.opt_len + 3 + 7) >>> 3;\n static_lenb = (s.static_len + 3 + 7) >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->sym_next / 3));\n\n if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block$1(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED$1 || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n};\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nconst _tr_tally$1 = (s, dist, lc) => {\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n\n s.pending_buf[s.sym_buf + s.sym_next++] = dist;\n s.pending_buf[s.sym_buf + s.sym_next++] = dist >> 8;\n s.pending_buf[s.sym_buf + s.sym_next++] = lc;\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS$1 + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n return (s.sym_next === s.sym_end);\n};\n\nvar _tr_init_1 = _tr_init$1;\nvar _tr_stored_block_1 = _tr_stored_block$1;\nvar _tr_flush_block_1 = _tr_flush_block$1;\nvar _tr_tally_1 = _tr_tally$1;\nvar _tr_align_1 = _tr_align$1;\n\nvar trees = {\n\t_tr_init: _tr_init_1,\n\t_tr_stored_block: _tr_stored_block_1,\n\t_tr_flush_block: _tr_flush_block_1,\n\t_tr_tally: _tr_tally_1,\n\t_tr_align: _tr_align_1\n};\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst adler32 = (adler, buf, len, pos) => {\n let s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n};\n\n\nvar adler32_1 = adler32;\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nconst makeTable = () => {\n let c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n};\n\n// Create table on load. Just 255 signed longs. Not a problem.\nconst crcTable = new Uint32Array(makeTable());\n\n\nconst crc32 = (crc, buf, len, pos) => {\n const t = crcTable;\n const end = pos + len;\n\n crc ^= -1;\n\n for (let i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n};\n\n\nvar crc32_1 = crc32;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar messages = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar constants$2 = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align } = trees;\n\n\n\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$2, Z_PARTIAL_FLUSH, Z_FULL_FLUSH: Z_FULL_FLUSH$1, Z_FINISH: Z_FINISH$3, Z_BLOCK: Z_BLOCK$1,\n Z_OK: Z_OK$3, Z_STREAM_END: Z_STREAM_END$3, Z_STREAM_ERROR: Z_STREAM_ERROR$2, Z_DATA_ERROR: Z_DATA_ERROR$2, Z_BUF_ERROR: Z_BUF_ERROR$1,\n Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1,\n Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1,\n Z_UNKNOWN,\n Z_DEFLATED: Z_DEFLATED$2\n} = constants$2;\n\n/*============================================================================*/\n\n\nconst MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nconst MAX_WBITS$1 = 15;\n/* 32K LZ77 window */\nconst DEF_MEM_LEVEL = 8;\n\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\nconst D_CODES = 30;\n/* number of distance codes */\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\nconst MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);\n\nconst PRESET_DICT = 0x20;\n\nconst INIT_STATE = 42; /* zlib header -> BUSY_STATE */\n//#ifdef GZIP\nconst GZIP_STATE = 57; /* gzip header -> BUSY_STATE | EXTRA_STATE */\n//#endif\nconst EXTRA_STATE = 69; /* gzip extra block -> NAME_STATE */\nconst NAME_STATE = 73; /* gzip file name -> COMMENT_STATE */\nconst COMMENT_STATE = 91; /* gzip comment -> HCRC_STATE */\nconst HCRC_STATE = 103; /* gzip header CRC -> BUSY_STATE */\nconst BUSY_STATE = 113; /* deflate -> FINISH_STATE */\nconst FINISH_STATE = 666; /* stream complete */\n\nconst BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nconst BS_BLOCK_DONE = 2; /* block flush performed */\nconst BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nconst BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nconst OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nconst err = (strm, errorCode) => {\n strm.msg = messages[errorCode];\n return errorCode;\n};\n\nconst rank = (f) => {\n return ((f) * 2) - ((f) > 4 ? 9 : 0);\n};\n\nconst zero = (buf) => {\n let len = buf.length; while (--len >= 0) { buf[len] = 0; }\n};\n\n/* ===========================================================================\n * Slide the hash table when sliding the window down (could be avoided with 32\n * bit values at the expense of memory usage). We slide even when level == 0 to\n * keep the hash table consistent if we switch back to level > 0 later.\n */\nconst slide_hash = (s) => {\n let n, m;\n let p;\n let wsize = s.w_size;\n\n n = s.hash_size;\n p = n;\n do {\n m = s.head[--p];\n s.head[p] = (m >= wsize ? m - wsize : 0);\n } while (--n);\n n = wsize;\n//#ifndef FASTEST\n p = n;\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= wsize ? m - wsize : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n//#endif\n};\n\n/* eslint-disable new-cap */\nlet HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask;\n// This hash causes less collisions, https://github.com/nodeca/pako/issues/135\n// But breaks binary compatibility\n//let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;\nlet HASH = HASH_ZLIB;\n\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output, except for\n * some deflate_stored() output, goes through this function so some\n * applications may wish to modify it to avoid allocating a large\n * strm->next_out buffer and copying into it. (See also read_buf()).\n */\nconst flush_pending = (strm) => {\n const s = strm.state;\n\n //_tr_flush_bits(s);\n let len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n};\n\n\nconst flush_block_only = (s, last) => {\n _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n};\n\n\nconst put_byte = (s, b) => {\n s.pending_buf[s.pending++] = b;\n};\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nconst putShortMSB = (s, b) => {\n\n // put_byte(s, (Byte)(b >> 8));\n// put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n};\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nconst read_buf = (strm, buf, start, size) => {\n\n let len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32_1(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32_1(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n};\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nconst longest_match = (s, cur_match) => {\n\n let chain_length = s.max_chain_length; /* max hash chain length */\n let scan = s.strstart; /* current string */\n let match; /* matched string */\n let len; /* length of current match */\n let best_len = s.prev_length; /* best match length so far */\n let nice_match = s.nice_match; /* stop if match long enough */\n const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n const _win = s.window; // shortcut\n\n const wmask = s.w_mask;\n const prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n const strend = s.strstart + MAX_MATCH;\n let scan_end1 = _win[scan + best_len - 1];\n let scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n};\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nconst fill_window = (s) => {\n\n const _w_size = s.w_size;\n let n, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n s.window.set(s.window.subarray(_w_size, _w_size + _w_size - more), 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n slide_hash(s);\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + 1]);\n//#if MIN_MATCH != 3\n// Call update_hash() MIN_MATCH-3 more times\n//#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n// if (s.high_water < s.window_size) {\n// const curr = s.strstart + s.lookahead;\n// let init = 0;\n//\n// if (s.high_water < curr) {\n// /* Previous high water mark below current data -- zero WIN_INIT\n// * bytes or up to end of window, whichever is less.\n// */\n// init = s.window_size - curr;\n// if (init > WIN_INIT)\n// init = WIN_INIT;\n// zmemzero(s->window + curr, (unsigned)init);\n// s->high_water = curr + init;\n// }\n// else if (s->high_water < (ulg)curr + WIN_INIT) {\n// /* High water mark at or above current data, but below current data\n// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n// * to end of window, whichever is less.\n// */\n// init = (ulg)curr + WIN_INIT - s->high_water;\n// if (init > s->window_size - s->high_water)\n// init = s->window_size - s->high_water;\n// zmemzero(s->window + s->high_water, (unsigned)init);\n// s->high_water += init;\n// }\n// }\n//\n// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n// \"not enough room for search\");\n};\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n *\n * In case deflateParams() is used to later switch to a non-zero compression\n * level, s->matches (otherwise unused when storing) keeps track of the number\n * of hash table slides to perform. If s->matches is 1, then one hash table\n * slide will be done when switching. If s->matches is 2, the maximum value\n * allowed here, then the hash table will be cleared, since two or more slides\n * is the same as a clear.\n *\n * deflate_stored() is written to minimize the number of times an input byte is\n * copied. It is most efficient with large input and output buffers, which\n * maximizes the opportunites to have a single copy from next_in to next_out.\n */\nconst deflate_stored = (s, flush) => {\n\n /* Smallest worthy block size when not flushing or finishing. By default\n * this is 32K. This can be as small as 507 bytes for memLevel == 1. For\n * large input and output buffers, the stored block size will be larger.\n */\n let min_block = s.pending_buf_size - 5 > s.w_size ? s.w_size : s.pending_buf_size - 5;\n\n /* Copy as many min_block or larger stored blocks directly to next_out as\n * possible. If flushing, copy the remaining available input to next_out as\n * stored blocks, if there is enough space.\n */\n let len, left, have, last = 0;\n let used = s.strm.avail_in;\n do {\n /* Set len to the maximum size block that we can copy directly with the\n * available input data and output space. Set left to how much of that\n * would be copied from what's left in the window.\n */\n len = 65535/* MAX_STORED */; /* maximum deflate stored block length */\n have = (s.bi_valid + 42) >> 3; /* number of header bytes */\n if (s.strm.avail_out < have) { /* need room for header */\n break;\n }\n /* maximum stored block length that will fit in avail_out: */\n have = s.strm.avail_out - have;\n left = s.strstart - s.block_start; /* bytes left in window */\n if (len > left + s.strm.avail_in) {\n len = left + s.strm.avail_in; /* limit len to the input */\n }\n if (len > have) {\n len = have; /* limit len to the output */\n }\n\n /* If the stored block would be less than min_block in length, or if\n * unable to copy all of the available input when flushing, then try\n * copying to the window and the pending buffer instead. Also don't\n * write an empty block when flushing -- deflate() does that.\n */\n if (len < min_block && ((len === 0 && flush !== Z_FINISH$3) ||\n flush === Z_NO_FLUSH$2 ||\n len !== left + s.strm.avail_in)) {\n break;\n }\n\n /* Make a dummy stored block in pending to get the header bytes,\n * including any pending bits. This also updates the debugging counts.\n */\n last = flush === Z_FINISH$3 && len === left + s.strm.avail_in ? 1 : 0;\n _tr_stored_block(s, 0, 0, last);\n\n /* Replace the lengths in the dummy stored block with len. */\n s.pending_buf[s.pending - 4] = len;\n s.pending_buf[s.pending - 3] = len >> 8;\n s.pending_buf[s.pending - 2] = ~len;\n s.pending_buf[s.pending - 1] = ~len >> 8;\n\n /* Write the stored block header bytes. */\n flush_pending(s.strm);\n\n//#ifdef ZLIB_DEBUG\n// /* Update debugging counts for the data about to be copied. */\n// s->compressed_len += len << 3;\n// s->bits_sent += len << 3;\n//#endif\n\n /* Copy uncompressed bytes from the window to next_out. */\n if (left) {\n if (left > len) {\n left = len;\n }\n //zmemcpy(s->strm->next_out, s->window + s->block_start, left);\n s.strm.output.set(s.window.subarray(s.block_start, s.block_start + left), s.strm.next_out);\n s.strm.next_out += left;\n s.strm.avail_out -= left;\n s.strm.total_out += left;\n s.block_start += left;\n len -= left;\n }\n\n /* Copy uncompressed bytes directly from next_in to next_out, updating\n * the check value.\n */\n if (len) {\n read_buf(s.strm, s.strm.output, s.strm.next_out, len);\n s.strm.next_out += len;\n s.strm.avail_out -= len;\n s.strm.total_out += len;\n }\n } while (last === 0);\n\n /* Update the sliding window with the last s->w_size bytes of the copied\n * data, or append all of the copied data to the existing window if less\n * than s->w_size bytes were copied. Also update the number of bytes to\n * insert in the hash tables, in the event that deflateParams() switches to\n * a non-zero compression level.\n */\n used -= s.strm.avail_in; /* number of input bytes directly copied */\n if (used) {\n /* If any input was used, then no unused input remains in the window,\n * therefore s->block_start == s->strstart.\n */\n if (used >= s.w_size) { /* supplant the previous history */\n s.matches = 2; /* clear hash */\n //zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);\n s.window.set(s.strm.input.subarray(s.strm.next_in - s.w_size, s.strm.next_in), 0);\n s.strstart = s.w_size;\n s.insert = s.strstart;\n }\n else {\n if (s.window_size - s.strstart <= used) {\n /* Slide the window down. */\n s.strstart -= s.w_size;\n //zmemcpy(s->window, s->window + s->w_size, s->strstart);\n s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);\n if (s.matches < 2) {\n s.matches++; /* add a pending slide_hash() */\n }\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n }\n //zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);\n s.window.set(s.strm.input.subarray(s.strm.next_in - used, s.strm.next_in), s.strstart);\n s.strstart += used;\n s.insert += used > s.w_size - s.insert ? s.w_size - s.insert : used;\n }\n s.block_start = s.strstart;\n }\n if (s.high_water < s.strstart) {\n s.high_water = s.strstart;\n }\n\n /* If the last block was written to next_out, then done. */\n if (last) {\n return BS_FINISH_DONE;\n }\n\n /* If flushing and all input has been consumed, then done. */\n if (flush !== Z_NO_FLUSH$2 && flush !== Z_FINISH$3 &&\n s.strm.avail_in === 0 && s.strstart === s.block_start) {\n return BS_BLOCK_DONE;\n }\n\n /* Fill the window with any remaining input. */\n have = s.window_size - s.strstart;\n if (s.strm.avail_in > have && s.block_start >= s.w_size) {\n /* Slide the window down. */\n s.block_start -= s.w_size;\n s.strstart -= s.w_size;\n //zmemcpy(s->window, s->window + s->w_size, s->strstart);\n s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);\n if (s.matches < 2) {\n s.matches++; /* add a pending slide_hash() */\n }\n have += s.w_size; /* more space now */\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n }\n if (have > s.strm.avail_in) {\n have = s.strm.avail_in;\n }\n if (have) {\n read_buf(s.strm, s.window, s.strstart, have);\n s.strstart += have;\n s.insert += have > s.w_size - s.insert ? s.w_size - s.insert : have;\n }\n if (s.high_water < s.strstart) {\n s.high_water = s.strstart;\n }\n\n /* There was not enough avail_out to write a complete worthy or flushed\n * stored block to next_out. Write a stored block to pending instead, if we\n * have enough input for a worthy block, or if flushing and there is enough\n * room for the remaining input as a stored block in the pending buffer.\n */\n have = (s.bi_valid + 42) >> 3; /* number of header bytes */\n /* maximum stored block length that will fit in pending: */\n have = s.pending_buf_size - have > 65535/* MAX_STORED */ ? 65535/* MAX_STORED */ : s.pending_buf_size - have;\n min_block = have > s.w_size ? s.w_size : have;\n left = s.strstart - s.block_start;\n if (left >= min_block ||\n ((left || flush === Z_FINISH$3) && flush !== Z_NO_FLUSH$2 &&\n s.strm.avail_in === 0 && left <= have)) {\n len = left > have ? have : left;\n last = flush === Z_FINISH$3 && s.strm.avail_in === 0 &&\n len === left ? 1 : 0;\n _tr_stored_block(s, s.block_start, len, last);\n s.block_start += len;\n flush_pending(s.strm);\n }\n\n /* We've done all we can with the available input and output. */\n return last ? BS_FINISH_STARTED : BS_NEED_MORE;\n};\n\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nconst deflate_fast = (s, flush) => {\n\n let hash_head; /* head of the hash chain */\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else\n {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]);\n\n//#if MIN_MATCH != 3\n// Call UPDATE_HASH() MIN_MATCH-3 more times\n//#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nconst deflate_slow = (s, flush) => {\n\n let hash_head; /* head of hash chain */\n let bflush; /* set if current block must be flushed */\n\n let max_insert;\n\n /* Process the input block. */\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n};\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nconst deflate_rle = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n let prev; /* byte at distance one to match */\n let scan, strend; /* scan goes up to strend for length of run */\n\n const _win = s.window;\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nconst deflate_huff = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nfunction Config(good_length, max_lazy, nice_length, max_chain, func) {\n\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n}\n\nconst configuration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nconst lm_init = (s) => {\n\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n s.ins_h = 0;\n};\n\n\nfunction DeflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED$2; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new Uint16Array(HEAP_SIZE * 2);\n this.dyn_dtree = new Uint16Array((2 * D_CODES + 1) * 2);\n this.bl_tree = new Uint16Array((2 * BL_CODES + 1) * 2);\n zero(this.dyn_ltree);\n zero(this.dyn_dtree);\n zero(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new Uint16Array(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new Uint16Array(2 * L_CODES + 1); /* heap used to build the Huffman trees */\n zero(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new Uint16Array(2 * L_CODES + 1); //uch depth[2*L_CODES+1];\n zero(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.sym_buf = 0; /* buffer for distances and literals/lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.sym_next = 0; /* running index in sym_buf */\n this.sym_end = 0; /* symbol table full when sym_next reaches this */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n}\n\n\n/* =========================================================================\n * Check for a valid deflate stream state. Return 0 if ok, 1 if not.\n */\nconst deflateStateCheck = (strm) => {\n\n if (!strm) {\n return 1;\n }\n const s = strm.state;\n if (!s || s.strm !== strm || (s.status !== INIT_STATE &&\n//#ifdef GZIP\n s.status !== GZIP_STATE &&\n//#endif\n s.status !== EXTRA_STATE &&\n s.status !== NAME_STATE &&\n s.status !== COMMENT_STATE &&\n s.status !== HCRC_STATE &&\n s.status !== BUSY_STATE &&\n s.status !== FINISH_STATE)) {\n return 1;\n }\n return 0;\n};\n\n\nconst deflateResetKeep = (strm) => {\n\n if (deflateStateCheck(strm)) {\n return err(strm, Z_STREAM_ERROR$2);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n\n const s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status =\n//#ifdef GZIP\n s.wrap === 2 ? GZIP_STATE :\n//#endif\n s.wrap ? INIT_STATE : BUSY_STATE;\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = -2;\n _tr_init(s);\n return Z_OK$3;\n};\n\n\nconst deflateReset = (strm) => {\n\n const ret = deflateResetKeep(strm);\n if (ret === Z_OK$3) {\n lm_init(strm.state);\n }\n return ret;\n};\n\n\nconst deflateSetHeader = (strm, head) => {\n\n if (deflateStateCheck(strm) || strm.state.wrap !== 2) {\n return Z_STREAM_ERROR$2;\n }\n strm.state.gzhead = head;\n return Z_OK$3;\n};\n\n\nconst deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {\n\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR$2;\n }\n let wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION$1) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED$2 ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED || (windowBits === 8 && wrap !== 1)) {\n return err(strm, Z_STREAM_ERROR$2);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n const s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n s.status = INIT_STATE; /* to pass state test in deflateReset() */\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n\n s.window = new Uint8Array(s.w_size * 2);\n s.head = new Uint16Array(s.hash_size);\n s.prev = new Uint16Array(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n /* We overlay pending_buf and sym_buf. This works since the average size\n * for length/distance pairs over any compressed block is assured to be 31\n * bits or less.\n *\n * Analysis: The longest fixed codes are a length code of 8 bits plus 5\n * extra bits, for lengths 131 to 257. The longest fixed distance codes are\n * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest\n * possible fixed-codes length/distance pair is then 31 bits total.\n *\n * sym_buf starts one-fourth of the way into pending_buf. So there are\n * three bytes in sym_buf for every four bytes in pending_buf. Each symbol\n * in sym_buf is three bytes -- two for the distance and one for the\n * literal/length. As each symbol is consumed, the pointer to the next\n * sym_buf value to read moves forward three bytes. From that symbol, up to\n * 31 bits are written to pending_buf. The closest the written pending_buf\n * bits gets to the next sym_buf symbol to read is just before the last\n * code is written. At that time, 31*(n-2) bits have been written, just\n * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at\n * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1\n * symbols are written.) The closest the writing gets to what is unread is\n * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and\n * can range from 128 to 32768.\n *\n * Therefore, at a minimum, there are 142 bits of space between what is\n * written and what is read in the overlain buffers, so the symbols cannot\n * be overwritten by the compressed data. That space is actually 139 bits,\n * due to the three-bit fixed-code block header.\n *\n * That covers the case where either Z_FIXED is specified, forcing fixed\n * codes, or when the use of fixed codes is chosen, because that choice\n * results in a smaller compressed block than dynamic codes. That latter\n * condition then assures that the above analysis also covers all dynamic\n * blocks. A dynamic-code block will only be chosen to be emitted if it has\n * fewer bits than a fixed-code block would for the same set of symbols.\n * Therefore its average symbol length is assured to be less than 31. So\n * the compressed data for a dynamic block also cannot overwrite the\n * symbols from which it is being constructed.\n */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n s.pending_buf = new Uint8Array(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->sym_buf = s->pending_buf + s->lit_bufsize;\n s.sym_buf = s.lit_bufsize;\n\n //s->sym_end = (s->lit_bufsize - 1) * 3;\n s.sym_end = (s.lit_bufsize - 1) * 3;\n /* We avoid equality with lit_bufsize*3 because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n};\n\nconst deflateInit = (strm, level) => {\n\n return deflateInit2(strm, level, Z_DEFLATED$2, MAX_WBITS$1, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY$1);\n};\n\n\n/* ========================================================================= */\nconst deflate$2 = (strm, flush) => {\n\n if (deflateStateCheck(strm) || flush > Z_BLOCK$1 || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR$2) : Z_STREAM_ERROR$2;\n }\n\n const s = strm.state;\n\n if (!strm.output ||\n (strm.avail_in !== 0 && !strm.input) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH$3)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR$1 : Z_STREAM_ERROR$2);\n }\n\n const old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK$3;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH$3) {\n return err(strm, Z_BUF_ERROR$1);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR$1);\n }\n\n /* Write the header */\n if (s.status === INIT_STATE && s.wrap === 0) {\n s.status = BUSY_STATE;\n }\n if (s.status === INIT_STATE) {\n /* zlib header */\n let header = (Z_DEFLATED$2 + ((s.w_bits - 8) << 4)) << 8;\n let level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n//#ifdef GZIP\n if (s.status === GZIP_STATE) {\n /* gzip header */\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let left = (s.gzhead.extra.length & 0xffff) - s.gzindex;\n while (s.pending + left > s.pending_buf_size) {\n let copy = s.pending_buf_size - s.pending;\n // zmemcpy(s.pending_buf + s.pending,\n // s.gzhead.extra + s.gzindex, copy);\n s.pending_buf.set(s.gzhead.extra.subarray(s.gzindex, s.gzindex + copy), s.pending);\n s.pending = s.pending_buf_size;\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex += copy;\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n left -= copy;\n }\n // JS specific: s.gzhead.extra may be TypedArray or Array for backward compatibility\n // TypedArray.slice and TypedArray.from don't exist in IE10-IE11\n let gzhead_extra = new Uint8Array(s.gzhead.extra);\n // zmemcpy(s->pending_buf + s->pending,\n // s->gzhead->extra + s->gzindex, left);\n s.pending_buf.set(gzhead_extra.subarray(s.gzindex, s.gzindex + left), s.pending);\n s.pending += left;\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex = 0;\n }\n s.status = NAME_STATE;\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let val;\n do {\n if (s.pending === s.pending_buf_size) {\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex = 0;\n }\n s.status = COMMENT_STATE;\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let val;\n do {\n if (s.pending === s.pending_buf_size) {\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n }\n s.status = HCRC_STATE;\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n }\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n//#endif\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH$2 && s.status !== FINISH_STATE)) {\n let bstate = s.level === 0 ? deflate_stored(s, flush) :\n s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :\n s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush);\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK$3;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n _tr_align(s);\n }\n else if (flush !== Z_BLOCK$1) { /* FULL_FLUSH or SYNC_FLUSH */\n\n _tr_stored_block(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH$1) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK$3;\n }\n }\n }\n\n if (flush !== Z_FINISH$3) { return Z_OK$3; }\n if (s.wrap <= 0) { return Z_STREAM_END$3; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else\n {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK$3 : Z_STREAM_END$3;\n};\n\n\nconst deflateEnd = (strm) => {\n\n if (deflateStateCheck(strm)) {\n return Z_STREAM_ERROR$2;\n }\n\n const status = strm.state.status;\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR$2) : Z_OK$3;\n};\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nconst deflateSetDictionary = (strm, dictionary) => {\n\n let dictLength = dictionary.length;\n\n if (deflateStateCheck(strm)) {\n return Z_STREAM_ERROR$2;\n }\n\n const s = strm.state;\n const wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR$2;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n let tmpDict = new Uint8Array(s.w_size);\n tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n const avail = strm.avail_in;\n const next = strm.next_in;\n const input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH) {\n let str = s.strstart;\n let n = s.lookahead - (MIN_MATCH - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK$3;\n};\n\n\nvar deflateInit_1 = deflateInit;\nvar deflateInit2_1 = deflateInit2;\nvar deflateReset_1 = deflateReset;\nvar deflateResetKeep_1 = deflateResetKeep;\nvar deflateSetHeader_1 = deflateSetHeader;\nvar deflate_2$1 = deflate$2;\nvar deflateEnd_1 = deflateEnd;\nvar deflateSetDictionary_1 = deflateSetDictionary;\nvar deflateInfo = 'pako deflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.deflateBound = deflateBound;\nmodule.exports.deflateCopy = deflateCopy;\nmodule.exports.deflateGetDictionary = deflateGetDictionary;\nmodule.exports.deflateParams = deflateParams;\nmodule.exports.deflatePending = deflatePending;\nmodule.exports.deflatePrime = deflatePrime;\nmodule.exports.deflateTune = deflateTune;\n*/\n\nvar deflate_1$2 = {\n\tdeflateInit: deflateInit_1,\n\tdeflateInit2: deflateInit2_1,\n\tdeflateReset: deflateReset_1,\n\tdeflateResetKeep: deflateResetKeep_1,\n\tdeflateSetHeader: deflateSetHeader_1,\n\tdeflate: deflate_2$1,\n\tdeflateEnd: deflateEnd_1,\n\tdeflateSetDictionary: deflateSetDictionary_1,\n\tdeflateInfo: deflateInfo\n};\n\nconst _has = (obj, key) => {\n return Object.prototype.hasOwnProperty.call(obj, key);\n};\n\nvar assign = function (obj /*from1, from2, from3, ...*/) {\n const sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n const source = sources.shift();\n if (!source) { continue; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be non-object');\n }\n\n for (const p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n};\n\n\n// Join array of chunks to single array.\nvar flattenChunks = (chunks) => {\n // calculate data length\n let len = 0;\n\n for (let i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n const result = new Uint8Array(len);\n\n for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {\n let chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n};\n\nvar common = {\n\tassign: assign,\n\tflattenChunks: flattenChunks\n};\n\n// String encode/decode helpers\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nlet STR_APPLY_UIA_OK = true;\n\ntry { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nconst _utf8len = new Uint8Array(256);\nfor (let q = 0; q < 256; q++) {\n _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nvar string2buf = (str) => {\n if (typeof TextEncoder === 'function' && TextEncoder.prototype.encode) {\n return new TextEncoder().encode(str);\n }\n\n let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new Uint8Array(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper\nconst buf2binstring = (buf, len) => {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if (buf.subarray && STR_APPLY_UIA_OK) {\n return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));\n }\n }\n\n let result = '';\n for (let i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n};\n\n\n// convert array to string\nvar buf2string = (buf, max) => {\n const len = max || buf.length;\n\n if (typeof TextDecoder === 'function' && TextDecoder.prototype.decode) {\n return new TextDecoder().decode(buf.subarray(0, max));\n }\n\n let i, out;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n const utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n let c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n let c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nvar utf8border = (buf, max) => {\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n let pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\nvar strings = {\n\tstring2buf: string2buf,\n\tbuf2string: buf2string,\n\tutf8border: utf8border\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nvar zstream = ZStream;\n\nconst toString$1 = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$1, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH: Z_FINISH$2,\n Z_OK: Z_OK$2, Z_STREAM_END: Z_STREAM_END$2,\n Z_DEFAULT_COMPRESSION,\n Z_DEFAULT_STRATEGY,\n Z_DEFLATED: Z_DEFLATED$1\n} = constants$2;\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\nfunction Deflate$1(options) {\n this.options = common.assign({\n level: Z_DEFAULT_COMPRESSION,\n method: Z_DEFLATED$1,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY\n }, options || {});\n\n let opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = deflate_1$2.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK$2) {\n throw new Error(messages[status]);\n }\n\n if (opt.header) {\n deflate_1$2.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n let dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = deflate_1$2.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK$2) {\n throw new Error(messages[status]);\n }\n\n this._dict_set = true;\n }\n}\n\n/**\n * Deflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must\n * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending\n * buffers and call [[Deflate#onEnd]].\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nDeflate$1.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n let status, _flush_mode;\n\n if (this.ended) { return false; }\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH$2 : Z_NO_FLUSH$1;\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (toString$1.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n // Make sure avail_out > 6 to avoid repeating markers\n if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH) && strm.avail_out <= 6) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n status = deflate_1$2.deflate(strm, _flush_mode);\n\n // Ended => flush and finish\n if (status === Z_STREAM_END$2) {\n if (strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n }\n status = deflate_1$2.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK$2;\n }\n\n // Flush if out buffer full\n if (strm.avail_out === 0) {\n this.onData(strm.output);\n continue;\n }\n\n // Flush if requested and has data\n if (_flush_mode > 0 && strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array): output data.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nDeflate$1.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nDeflate$1.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK$2) {\n this.result = common.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * deflate(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate$1(input, options) {\n const deflator = new Deflate$1(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw deflator.msg || messages[deflator.err]; }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw$1(input, options) {\n options = options || {};\n options.raw = true;\n return deflate$1(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip$1(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate$1(input, options);\n}\n\n\nvar Deflate_1$1 = Deflate$1;\nvar deflate_2 = deflate$1;\nvar deflateRaw_1$1 = deflateRaw$1;\nvar gzip_1$1 = gzip$1;\nvar constants$1 = constants$2;\n\nvar deflate_1$1 = {\n\tDeflate: Deflate_1$1,\n\tdeflate: deflate_2,\n\tdeflateRaw: deflateRaw_1$1,\n\tgzip: gzip_1$1,\n\tconstants: constants$1\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nconst BAD$1 = 16209; /* got a data error -- remain here until reset */\nconst TYPE$1 = 16191; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nvar inffast = function inflate_fast(strm, start) {\n let _in; /* local strm.input */\n let last; /* have enough input while in < last */\n let _out; /* local strm.output */\n let beg; /* inflate()'s initial strm.output */\n let end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n let dmax; /* maximum distance from zlib header */\n//#endif\n let wsize; /* window size or zero if not using window */\n let whave; /* valid bytes in the window */\n let wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n let s_window; /* allocated sliding window, if wsize != 0 */\n let hold; /* local strm.hold */\n let bits; /* local strm.bits */\n let lcode; /* local strm.lencode */\n let dcode; /* local strm.distcode */\n let lmask; /* mask for first level of length codes */\n let dmask; /* mask for first level of distance codes */\n let here; /* retrieved table entry */\n let op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n let len; /* match length, unused bytes */\n let dist; /* match distance */\n let from; /* where to copy match from */\n let from_source;\n\n\n let input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n const state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD$1;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE$1;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD$1;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst MAXBITS = 15;\nconst ENOUGH_LENS$1 = 852;\nconst ENOUGH_DISTS$1 = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst CODES$1 = 0;\nconst LENS$1 = 1;\nconst DISTS$1 = 2;\n\nconst lbase = new Uint16Array([ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n]);\n\nconst lext = new Uint8Array([ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n]);\n\nconst dbase = new Uint16Array([ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n]);\n\nconst dext = new Uint8Array([ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n]);\n\nconst inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) =>\n{\n const bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n let len = 0; /* a code's length in bits */\n let sym = 0; /* index of code symbols */\n let min = 0, max = 0; /* minimum and maximum code lengths */\n let root = 0; /* number of index bits for root table */\n let curr = 0; /* number of index bits for current table */\n let drop = 0; /* code bits to drop for sub-table */\n let left = 0; /* number of prefix codes available */\n let used = 0; /* code entries in table used */\n let huff = 0; /* Huffman code */\n let incr; /* for incrementing code, index */\n let fill; /* index for replicating entries */\n let low; /* low bits for current root entry */\n let mask; /* mask for low root bits */\n let next; /* next available space in table */\n let base = null; /* base value table to use */\n// let shoextra; /* extra bits table to use */\n let match; /* use base and extra for symbol >= match */\n const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n let extra = null;\n\n let here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES$1 || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES$1) {\n base = extra = work; /* dummy value--not used */\n match = 20;\n\n } else if (type === LENS$1) {\n base = lbase;\n extra = lext;\n match = 257;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n match = 0;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS$1 && used > ENOUGH_LENS$1) ||\n (type === DISTS$1 && used > ENOUGH_DISTS$1)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] + 1 < match) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] >= match) {\n here_op = extra[work[sym] - match];\n here_val = base[work[sym] - match];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS$1 && used > ENOUGH_LENS$1) ||\n (type === DISTS$1 && used > ENOUGH_DISTS$1)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n\nvar inftrees = inflate_table;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n\n\n\n\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_FINISH: Z_FINISH$1, Z_BLOCK, Z_TREES,\n Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1, Z_NEED_DICT: Z_NEED_DICT$1, Z_STREAM_ERROR: Z_STREAM_ERROR$1, Z_DATA_ERROR: Z_DATA_ERROR$1, Z_MEM_ERROR: Z_MEM_ERROR$1, Z_BUF_ERROR,\n Z_DEFLATED\n} = constants$2;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nconst HEAD = 16180; /* i: waiting for magic header */\nconst FLAGS = 16181; /* i: waiting for method and flags (gzip) */\nconst TIME = 16182; /* i: waiting for modification time (gzip) */\nconst OS = 16183; /* i: waiting for extra flags and operating system (gzip) */\nconst EXLEN = 16184; /* i: waiting for extra length (gzip) */\nconst EXTRA = 16185; /* i: waiting for extra bytes (gzip) */\nconst NAME = 16186; /* i: waiting for end of file name (gzip) */\nconst COMMENT = 16187; /* i: waiting for end of comment (gzip) */\nconst HCRC = 16188; /* i: waiting for header crc (gzip) */\nconst DICTID = 16189; /* i: waiting for dictionary check value */\nconst DICT = 16190; /* waiting for inflateSetDictionary() call */\nconst TYPE = 16191; /* i: waiting for type bits, including last-flag bit */\nconst TYPEDO = 16192; /* i: same, but skip check to exit inflate on new block */\nconst STORED = 16193; /* i: waiting for stored size (length and complement) */\nconst COPY_ = 16194; /* i/o: same as COPY below, but only first time in */\nconst COPY = 16195; /* i/o: waiting for input or output to copy stored block */\nconst TABLE = 16196; /* i: waiting for dynamic block table lengths */\nconst LENLENS = 16197; /* i: waiting for code length code lengths */\nconst CODELENS = 16198; /* i: waiting for length/lit and distance code lengths */\nconst LEN_ = 16199; /* i: same as LEN below, but only first time in */\nconst LEN = 16200; /* i: waiting for length/lit/eob code */\nconst LENEXT = 16201; /* i: waiting for length extra bits */\nconst DIST = 16202; /* i: waiting for distance code */\nconst DISTEXT = 16203; /* i: waiting for distance extra bits */\nconst MATCH = 16204; /* o: waiting for output space to copy string */\nconst LIT = 16205; /* o: waiting for output space to write literal */\nconst CHECK = 16206; /* i: waiting for 32-bit check value */\nconst LENGTH = 16207; /* i: waiting for 32-bit length (gzip) */\nconst DONE = 16208; /* finished check, done -- remain here until reset */\nconst BAD = 16209; /* got a data error -- remain here until reset */\nconst MEM = 16210; /* got an inflate() memory error -- remain here until reset */\nconst SYNC = 16211; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_WBITS = MAX_WBITS;\n\n\nconst zswap32 = (q) => {\n\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n};\n\n\nfunction InflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip,\n bit 2 true to validate check value */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib), or\n -1 if raw or no header yet */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new Uint16Array(320); /* temporary storage for code lengths */\n this.work = new Uint16Array(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new Int32Array(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\n\nconst inflateStateCheck = (strm) => {\n\n if (!strm) {\n return 1;\n }\n const state = strm.state;\n if (!state || state.strm !== strm ||\n state.mode < HEAD || state.mode > SYNC) {\n return 1;\n }\n return 0;\n};\n\n\nconst inflateResetKeep = (strm) => {\n\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.flags = -1;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS);\n state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK$1;\n};\n\n\nconst inflateReset = (strm) => {\n\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n};\n\n\nconst inflateReset2 = (strm, windowBits) => {\n let wrap;\n\n /* get the state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 5;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR$1;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n};\n\n\nconst inflateInit2 = (strm, windowBits) => {\n\n if (!strm) { return Z_STREAM_ERROR$1; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n const state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.strm = strm;\n state.window = null/*Z_NULL*/;\n state.mode = HEAD; /* to pass state test in inflateReset2() */\n const ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK$1) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n};\n\n\nconst inflateInit = (strm) => {\n\n return inflateInit2(strm, DEF_WBITS);\n};\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nlet virgin = true;\n\nlet lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\n\nconst fixedtables = (state) => {\n\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n lenfix = new Int32Array(512);\n distfix = new Int32Array(32);\n\n /* literal/length table */\n let sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inftrees(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inftrees(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n};\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nconst updatewindow = (strm, src, end, copy) => {\n\n let dist;\n const state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new Uint8Array(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n state.window.set(src.subarray(end - state.wsize, end), 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n state.window.set(src.subarray(end - copy, end), 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n};\n\n\nconst inflate$2 = (strm, flush) => {\n\n let state;\n let input, output; // input/output buffers\n let next; /* next input INDEX */\n let put; /* next output INDEX */\n let have, left; /* available input and output */\n let hold; /* bit buffer */\n let bits; /* bits in bit buffer */\n let _in, _out; /* save starting available input and output */\n let copy; /* number of stored or match bytes to copy */\n let from; /* where to copy match bytes from */\n let from_source;\n let here = 0; /* current decoding table entry */\n let here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //let last; /* parent table entry */\n let last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n let len; /* length to copy for repeats, bits to drop */\n let ret; /* return code */\n const hbuf = new Uint8Array(4); /* buffer for gzip header crc calculation */\n let opts;\n\n let n; // temporary variable for NEED_BITS\n\n const order = /* permutation of code lengths */\n new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]);\n\n\n if (inflateStateCheck(strm) || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR$1;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK$1;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n if (state.wbits === 0) {\n state.wbits = 15;\n }\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n if (len > 15 || len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n\n // !!! pako patch. Force use `options.windowBits` if passed.\n // Required to always use max window size by default.\n state.dmax = 1 << state.wbits;\n //state.dmax = 1 << len;\n\n state.flags = 0; /* indicate zlib header */\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32_1(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Uint8Array(state.head.extra_len);\n }\n state.head.extra.set(\n input.subarray(\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n next + copy\n ),\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 4) && hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT$1;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n output.set(input.subarray(next, next + copy), put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inftrees(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inftrees(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inftrees(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inffast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if ((state.wrap & 4) && _out) {\n strm.adler = state.check =\n /*UPDATE_CHECK(state.check, put - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.wrap & 4) && (state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 4) && hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END$1;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR$1;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR$1;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR$1;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH$1))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if ((state.wrap & 4) && _out) {\n strm.adler = state.check = /*UPDATE_CHECK(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH$1) && ret === Z_OK$1) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n};\n\n\nconst inflateEnd = (strm) => {\n\n if (inflateStateCheck(strm)) {\n return Z_STREAM_ERROR$1;\n }\n\n let state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK$1;\n};\n\n\nconst inflateGetHeader = (strm, head) => {\n\n /* check state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK$1;\n};\n\n\nconst inflateSetDictionary = (strm, dictionary) => {\n const dictLength = dictionary.length;\n\n let state;\n let dictid;\n let ret;\n\n /* check state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR$1;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32_1(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR$1;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR$1;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK$1;\n};\n\n\nvar inflateReset_1 = inflateReset;\nvar inflateReset2_1 = inflateReset2;\nvar inflateResetKeep_1 = inflateResetKeep;\nvar inflateInit_1 = inflateInit;\nvar inflateInit2_1 = inflateInit2;\nvar inflate_2$1 = inflate$2;\nvar inflateEnd_1 = inflateEnd;\nvar inflateGetHeader_1 = inflateGetHeader;\nvar inflateSetDictionary_1 = inflateSetDictionary;\nvar inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.inflateCodesUsed = inflateCodesUsed;\nmodule.exports.inflateCopy = inflateCopy;\nmodule.exports.inflateGetDictionary = inflateGetDictionary;\nmodule.exports.inflateMark = inflateMark;\nmodule.exports.inflatePrime = inflatePrime;\nmodule.exports.inflateSync = inflateSync;\nmodule.exports.inflateSyncPoint = inflateSyncPoint;\nmodule.exports.inflateUndermine = inflateUndermine;\nmodule.exports.inflateValidate = inflateValidate;\n*/\n\nvar inflate_1$2 = {\n\tinflateReset: inflateReset_1,\n\tinflateReset2: inflateReset2_1,\n\tinflateResetKeep: inflateResetKeep_1,\n\tinflateInit: inflateInit_1,\n\tinflateInit2: inflateInit2_1,\n\tinflate: inflate_2$1,\n\tinflateEnd: inflateEnd_1,\n\tinflateGetHeader: inflateGetHeader_1,\n\tinflateSetDictionary: inflateSetDictionary_1,\n\tinflateInfo: inflateInfo\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nvar gzheader = GZheader;\n\nconst toString = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH, Z_FINISH,\n Z_OK, Z_STREAM_END, Z_NEED_DICT, Z_STREAM_ERROR, Z_DATA_ERROR, Z_MEM_ERROR\n} = constants$2;\n\n/* ===========================================================================*/\n\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate$1(options) {\n this.options = common.assign({\n chunkSize: 1024 * 64,\n windowBits: 15,\n to: ''\n }, options || {});\n\n const opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = inflate_1$2.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== Z_OK) {\n throw new Error(messages[status]);\n }\n\n this.header = new gzheader();\n\n inflate_1$2.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = inflate_1$2.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== Z_OK) {\n throw new Error(messages[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer): input data\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE\n * flush modes. See constants. Skipped or `false` means Z_NO_FLUSH,\n * `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. If end of stream detected,\n * [[Inflate#onEnd]] will be called.\n *\n * `flush_mode` is not needed for normal operation, because end of stream\n * detected automatically. You may try to use it for advanced things, but\n * this functionality was not tested.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate$1.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n const dictionary = this.options.dictionary;\n let status, _flush_mode, last_avail_out;\n\n if (this.ended) return false;\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH : Z_NO_FLUSH;\n\n // Convert data if needed\n if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = inflate_1$2.inflate(strm, _flush_mode);\n\n if (status === Z_NEED_DICT && dictionary) {\n status = inflate_1$2.inflateSetDictionary(strm, dictionary);\n\n if (status === Z_OK) {\n status = inflate_1$2.inflate(strm, _flush_mode);\n } else if (status === Z_DATA_ERROR) {\n // Replace code with more verbose\n status = Z_NEED_DICT;\n }\n }\n\n // Skip snyc markers if more data follows and not raw mode\n while (strm.avail_in > 0 &&\n status === Z_STREAM_END &&\n strm.state.wrap > 0 &&\n data[strm.next_in] !== 0)\n {\n inflate_1$2.inflateReset(strm);\n status = inflate_1$2.inflate(strm, _flush_mode);\n }\n\n switch (status) {\n case Z_STREAM_ERROR:\n case Z_DATA_ERROR:\n case Z_NEED_DICT:\n case Z_MEM_ERROR:\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n // Remember real `avail_out` value, because we may patch out buffer content\n // to align utf8 strings boundaries.\n last_avail_out = strm.avail_out;\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === Z_STREAM_END) {\n\n if (this.options.to === 'string') {\n\n let next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n let tail = strm.next_out - next_out_utf8;\n let utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail & realign counters\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0);\n\n this.onData(utf8str);\n\n } else {\n this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out));\n }\n }\n }\n\n // Must repeat iteration if out buffer is full\n if (status === Z_OK && last_avail_out === 0) continue;\n\n // Finalize if end of stream reached.\n if (status === Z_STREAM_END) {\n status = inflate_1$2.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return true;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|String): output data. When string output requested,\n * each chunk will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate$1.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate$1.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK) {\n if (this.options.to === 'string') {\n this.result = this.chunks.join('');\n } else {\n this.result = common.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako');\n * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9]));\n * let output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err) {\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate$1(input, options) {\n const inflator = new Inflate$1(options);\n\n inflator.push(input);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) throw inflator.msg || messages[inflator.err];\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw$1(input, options) {\n options = options || {};\n options.raw = true;\n return inflate$1(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nvar Inflate_1$1 = Inflate$1;\nvar inflate_2 = inflate$1;\nvar inflateRaw_1$1 = inflateRaw$1;\nvar ungzip$1 = inflate$1;\nvar constants = constants$2;\n\nvar inflate_1$1 = {\n\tInflate: Inflate_1$1,\n\tinflate: inflate_2,\n\tinflateRaw: inflateRaw_1$1,\n\tungzip: ungzip$1,\n\tconstants: constants\n};\n\nconst { Deflate, deflate, deflateRaw, gzip } = deflate_1$1;\n\nconst { Inflate, inflate, inflateRaw, ungzip } = inflate_1$1;\n\n\n\nvar Deflate_1 = Deflate;\nvar deflate_1 = deflate;\nvar deflateRaw_1 = deflateRaw;\nvar gzip_1 = gzip;\nvar Inflate_1 = Inflate;\nvar inflate_1 = inflate;\nvar inflateRaw_1 = inflateRaw;\nvar ungzip_1 = ungzip;\nvar constants_1 = constants$2;\n\nvar pako = {\n\tDeflate: Deflate_1,\n\tdeflate: deflate_1,\n\tdeflateRaw: deflateRaw_1,\n\tgzip: gzip_1,\n\tInflate: Inflate_1,\n\tinflate: inflate_1,\n\tinflateRaw: inflateRaw_1,\n\tungzip: ungzip_1,\n\tconstants: constants_1\n};\n\nclass AIPromptExamplesInput {\n constructor(input, output) {\n this.input = input;\n this.output = output;\n }\n}\nclass AIPromptExamples {\n constructor(input, output) {\n this.input = input;\n this.output = output;\n }\n}\nclass AITaskInput {\n constructor(name, model_id, system_prompt, prompt_examples, metaData) {\n this.name = name;\n this.modelId = model_id;\n this.systemPrompt = system_prompt;\n this.promptExamples = prompt_examples;\n this.metaData = metaData;\n }\n}\nclass AITask {\n constructor(name, model_id, task_id, system_prompt, prompt_examples, metaData, created_at, updated_at) {\n this.name = name;\n this.modelId = model_id;\n this.taskId = task_id;\n this.systemPrompt = system_prompt;\n this.promptExamples = prompt_examples;\n this.metaData = metaData;\n this.createdAt = created_at;\n this.updatedAt = updated_at;\n }\n}\nclass AIModelLoadingStatus {\n constructor(model, status, progress, downloaded, loaded) {\n this.model = model;\n this.status = status;\n this.progress = progress;\n this.downloaded = downloaded;\n this.loaded = loaded;\n }\n}\n\nvar __classPrivateFieldSet$2 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$2 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _AIClient_apiClient, _AIClient_transcriptionUnsubscribers, _AIClient_pendingStreamIds;\nclass AIClient {\n constructor(baseUrl, token, subscribe = true, sharedApiClient) {\n _AIClient_apiClient.set(this, void 0);\n _AIClient_transcriptionUnsubscribers.set(this, new Map());\n _AIClient_pendingStreamIds.set(this, new Set());\n __classPrivateFieldSet$2(this, _AIClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), \"f\");\n }\n serializeModelInput(model) {\n const payload = { ...model };\n if ('modelType' in payload) {\n payload.type = payload.modelType;\n delete payload.modelType;\n }\n return payload;\n }\n async getModels() {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.models');\n }\n async addModel(model) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.addModel', { model: this.serializeModelInput(model) });\n }\n async updateModel(modelId, model) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.updateModel', { id: modelId, model: this.serializeModelInput(model) });\n }\n async removeModel(modelId) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.removeModel', { id: modelId });\n }\n async setDefaultModel(modelType, modelId) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.setDefaultModel', { id: modelId, modelType });\n }\n async getDefaultModel(modelType) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.getDefaultModel', { modelType });\n }\n async tasks() {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.tasks');\n }\n async addTask(name, modelId, systemPrompt, promptExamples, metaData) {\n const task = new AITaskInput(name, modelId, systemPrompt, promptExamples, metaData);\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.addTask', { task });\n }\n async removeTask(taskId) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.removeTask', { id: taskId });\n }\n async updateTask(taskId, task) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.updateTask', {\n id: taskId,\n task: {\n name: task.name,\n modelId: task.modelId,\n systemPrompt: task.systemPrompt,\n promptExamples: task.promptExamples\n }\n });\n }\n async modelLoadingStatus(model) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.modelLoadingStatus', { model });\n }\n async prompt(taskId, prompt) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.prompt', { taskId, prompt });\n }\n async embed(modelId, text) {\n const aiEmbed = await __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.embed', { modelId, text });\n const compressed = base64Js.toByteArray(aiEmbed);\n const decompressed = JSON.parse(pako.inflate(compressed, { to: 'string' }));\n return decompressed;\n }\n async openTranscriptionStream(modelId, streamCallback, params) {\n const streamId = await __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.transcriptionOpen', { modelId, params });\n const unsub = __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'transcription-text' && data.streamId === streamId && data.text) {\n streamCallback(data.text);\n }\n });\n __classPrivateFieldGet$2(this, _AIClient_transcriptionUnsubscribers, \"f\").set(streamId, unsub);\n return streamId;\n }\n async closeTranscriptionStream(streamId) {\n __classPrivateFieldGet$2(this, _AIClient_pendingStreamIds, \"f\").delete(streamId);\n await __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.transcriptionClose', { streamId });\n const unsub = __classPrivateFieldGet$2(this, _AIClient_transcriptionUnsubscribers, \"f\").get(streamId);\n if (unsub) {\n unsub();\n __classPrivateFieldGet$2(this, _AIClient_transcriptionUnsubscribers, \"f\").delete(streamId);\n }\n }\n /**\n * Feed an audio utterance to one or more transcription streams.\n * Sends raw binary Float32Array as application/octet-stream.\n * NOTE: This method still uses HTTP fetch because binary audio data\n * cannot be efficiently sent over the JSON-based WebSocket RPC protocol.\n * Transcription results are delivered via the WS event channel.\n */\n async feedTranscriptionStream(streamIds, audio) {\n const ids = Array.isArray(streamIds) ? streamIds : [streamIds];\n // Ensure we have a typed array for binary transport\n const typedAudio = audio instanceof Float32Array\n ? audio\n : new Float32Array(audio);\n if (ids.length === 0 || typedAudio.length === 0) {\n return;\n }\n const baseUrl = __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").getBaseUrl();\n const token = __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").getToken();\n // Use slice to get only the relevant portion of the underlying ArrayBuffer\n // (Float32Array may be a view over a larger buffer)\n const bodyBuffer = typedAudio.buffer.slice(typedAudio.byteOffset, typedAudio.byteOffset + typedAudio.byteLength);\n const response = await fetch(`${baseUrl}/api/v1/ai/transcription/feed`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/octet-stream',\n 'X-Stream-Ids': ids.join(','),\n ...(token ? { 'Authorization': `Bearer ${token}` } : {}),\n },\n body: bodyBuffer,\n });\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(`[AIClient] feed failed: ${response.status} ${response.statusText} ${text}`);\n }\n }\n}\n_AIClient_apiClient = new WeakMap(), _AIClient_transcriptionUnsubscribers = new WeakMap(), _AIClient_pendingStreamIds = new WeakMap();\n\n/**\n * Shared query helpers used by both the Prolog and SPARQL query pipelines.\n */\n/**\n * Resolves the predicate for a parent query.\n *\n * Uses TS discriminated union narrowing:\n * - Raw form (`{ id, predicate }`) \u2192 predicate used as-is\n * - Model form (`{ model, id, field? }`) \u2192 lookup from relation metadata\n * - With `field`: direct key lookup\n * - Without `field`: scan for a relation whose `target()` matches `childCtor`\n */\nfunction resolveParentPredicate(parent, childCtor) {\n // Raw form \u2014 explicit predicate\n if ('predicate' in parent)\n return parent.predicate;\n // Model form \u2014 resolve from relation metadata\n const { model } = parent;\n const relMeta = getRelationsMetadata(model);\n // Direct lookup by field name when provided\n if (parent.field) {\n const entry = relMeta[parent.field];\n if (!entry) {\n throw new Error(`parent(): field \"${parent.field}\" is not a registered relation on ${model.name}`);\n }\n return entry.predicate;\n }\n // Fallback: scan for a relation whose target matches the child class\n for (const [, entry] of Object.entries(relMeta)) {\n if (entry.target && entry.target() === childCtor) {\n return entry.predicate;\n }\n }\n throw new Error(`parent(): could not resolve predicate \u2014 no relation on ${model.name} targets ${childCtor.name || 'the queried class'}`);\n}\n\n/**\n * JSON Schema \u2192 Ad4mModel class builder and related utilities.\n *\n * Contains:\n * - JSON Schema type definitions (JSONSchemaProperty, JSONSchema, JSONSchemaToModelOptions)\n * - Schema type helpers (normalizeNamespaceString, isArrayType, etc.)\n * - Predicate / namespace resolution helpers\n * - `buildModelFromJSONSchema()` \u2014 core implementation of `Ad4mModel.fromJSONSchema()`\n *\n * @module\n */\n// \u2500\u2500\u2500 Schema Type Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nfunction normalizeNamespaceString(namespace) {\n if (!namespace)\n return '';\n if (namespace.includes('://')) {\n const [scheme, rest] = namespace.split('://');\n const path = (rest || '').replace(/\\/+$/, '');\n return `${scheme}://${path}`;\n }\n else {\n return namespace.replace(/\\/+$/, '');\n }\n}\nfunction normalizeSchemaType(type) {\n if (!type)\n return undefined;\n if (typeof type === \"string\")\n return type;\n if (Array.isArray(type) && type.length > 0) {\n const nonNull = type.find((t) => t !== \"null\");\n return nonNull || type[0];\n }\n return undefined;\n}\nfunction isSchemaType(schema, expectedType) {\n return normalizeSchemaType(schema.type) === expectedType;\n}\nfunction isArrayType(schema) {\n return isSchemaType(schema, \"array\");\n}\nfunction isObjectType(schema) {\n return isSchemaType(schema, \"object\");\n}\nfunction isNumericType(schema) {\n const normalized = normalizeSchemaType(schema.type);\n return normalized === \"number\" || normalized === \"integer\";\n}\n// \u2500\u2500\u2500 Predicate / Namespace Resolution \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n/**\n * Determines the namespace for predicates using cascading precedence:\n * 1. Explicit namespace in options\n * 2. x-ad4m metadata in schema\n * 3. Infer from schema title\n * 4. Try to extract from $id\n * 5. Error if nothing works\n */\nfunction determineNamespace(schema, options) {\n // 1. Explicit namespace in options (highest precedence)\n if (options.namespace) {\n return options.namespace;\n }\n // 2. x-ad4m metadata in schema\n if (schema[\"x-ad4m\"]?.namespace) {\n return schema[\"x-ad4m\"].namespace;\n }\n // 3. Infer from schema title\n if (schema.title) {\n return `${schema.title.toLowerCase()}://`;\n }\n // 4. Try to extract from $id if it's a URL\n if (schema.$id) {\n try {\n const url = new URL(schema.$id);\n const pathParts = url.pathname.split('/').filter(p => p);\n if (pathParts.length > 0) {\n const lastPart = pathParts[pathParts.length - 1];\n const baseName = lastPart.replace(/\\.schema\\.json$/, '').replace(/\\.json$/, '');\n return `${baseName.toLowerCase()}://`;\n }\n }\n catch {\n // If $id is not a valid URL, continue to error\n }\n }\n // 5. Error if no namespace can be determined\n throw new Error(`Cannot infer namespace for JSON Schema. Please provide one of:\n - options.namespace\n - schema[\"x-ad4m\"].namespace \n - schema.title\n - valid schema.$id`);\n}\n/**\n * Determines the predicate for a specific property using cascading precedence:\n * 1. Explicit property mapping\n * 2. x-ad4m metadata in property schema\n * 3. Predicate template\n * 4. Custom predicate generator\n * 5. Default: namespace + property name\n */\nfunction determinePredicate(schema, propertyName, propertySchema, namespace, options) {\n // 1. Explicit property mapping (highest precedence)\n if (options.propertyMapping?.[propertyName]) {\n return options.propertyMapping[propertyName];\n }\n // 2. x-ad4m metadata in property schema\n if (propertySchema[\"x-ad4m\"]?.through) {\n return propertySchema[\"x-ad4m\"].through;\n }\n // 3. Generate from namespace + property name\n if (options.predicateTemplate) {\n const normalizedNs = normalizeNamespaceString(namespace);\n const [scheme, rest] = normalizedNs.includes('://') ? normalizedNs.split('://') : ['', normalizedNs];\n const nsNoScheme = rest || '';\n return options.predicateTemplate\n .replace('${namespace}', nsNoScheme)\n .replace('${scheme}', scheme)\n .replace('${ns}', nsNoScheme)\n .replace('${title}', schema.title || '')\n .replace('${property}', propertyName);\n }\n // 4. Custom predicate generator\n if (options.predicateGenerator) {\n return options.predicateGenerator(schema.title || '', propertyName);\n }\n // 5. Default: namespace + property name\n const normalizedNs = normalizeNamespaceString(namespace);\n if (normalizedNs.includes('://')) {\n // For namespaces like \"product://\", append property directly\n return `${normalizedNs}${propertyName}`;\n }\n else {\n return `${normalizedNs}://${propertyName}`;\n }\n}\n/**\n * Gets property-specific options using cascading precedence:\n * 1. Property-specific options\n * 2. x-ad4m metadata in property\n * 3. Global option\n * 4. Default value\n */\nfunction getPropertyOption(propertyName, propertySchema, options, optionName, defaultValue) {\n // 1. Property-specific options\n if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {\n return options.propertyOptions[propertyName][optionName];\n }\n // 2. x-ad4m metadata in property\n if (propertySchema[\"x-ad4m\"]?.[optionName] !== undefined) {\n return propertySchema[\"x-ad4m\"][optionName];\n }\n // 3. Global option\n if (options[optionName] !== undefined) {\n return options[optionName];\n }\n // 4. Default value\n return defaultValue;\n}\n/**\n * Gets default value for a JSON Schema type.\n */\nfunction getDefaultValueForType(type) {\n switch (type) {\n case 'string': return '';\n case 'number': return 0;\n case 'integer': return 0;\n case 'boolean': return false;\n case 'array': return [];\n case 'object': return {};\n default: return '';\n }\n}\n// \u2500\u2500\u2500 buildModelFromJSONSchema \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n/**\n * Core implementation of `Ad4mModel.fromJSONSchema()`.\n *\n * Creates a dynamic Ad4mModel subclass from a JSON Schema definition,\n * wiring up property / relation metadata, setters, and the `@Model` decorator.\n *\n * @param BaseClass - The Ad4mModel class (or subclass) to extend\n * @param schema - JSON Schema definition\n * @param options - Configuration options\n * @returns Generated Ad4mModel subclass\n */\nfunction buildModelFromJSONSchema(BaseClass, schema, options) {\n // Disallow top-level \"author\" property since Ad4mModel provides it implicitly via link authorship\n if (schema?.properties && Object.prototype.hasOwnProperty.call(schema.properties, \"author\")) {\n throw new Error('JSON Schema must not define a top-level \"author\" property because Ad4mModel already exposes it. Please rename the property (e.g., \"writer\").');\n }\n // Determine namespace with cascading precedence\n const namespace = determineNamespace(schema, options);\n // Create the dynamic class\n const DynamicModelClass = class extends BaseClass {\n };\n // Set up class metadata\n if (!options.name || options.name.trim() === '') {\n throw new Error(\"options.name is required and cannot be empty\");\n }\n DynamicModelClass.className = options.name;\n DynamicModelClass.prototype.className = options.name;\n // Generate properties and relations metadata\n const properties = {};\n const relations = {};\n if (schema.properties) {\n for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {\n const predicate = determinePredicate(schema, propertyName, propertySchema, namespace, options);\n const isRequired = schema.required?.includes(propertyName) || false;\n const propertyType = normalizeSchemaType(propertySchema.type);\n const isArray = isArrayType(propertySchema);\n if (isArray) {\n // Handle arrays as relations\n // Store the singular form as the relation key since SDNA generation expects singular\n relations[propertyName] = {\n through: predicate,\n local: getPropertyOption(propertyName, propertySchema, options, 'local')\n };\n // Define the property on prototype\n Object.defineProperty(DynamicModelClass.prototype, propertyName, {\n configurable: true,\n writable: true,\n value: []\n });\n // Add relation methods\n const adderName = `add${capitalize(propertyName)}`;\n const removerName = `remove${capitalize(propertyName)}`;\n const setterName = `set${capitalize(propertyName)}`;\n DynamicModelClass.prototype[adderName] = function () {\n // Placeholder function for SDNA generation\n };\n DynamicModelClass.prototype[removerName] = function () {\n // Placeholder function for SDNA generation\n };\n DynamicModelClass.prototype[setterName] = function () {\n // Placeholder function for SDNA generation\n };\n }\n else {\n // Handle regular properties\n let resolveLanguage = getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');\n // If no specific resolveLanguage for this property, use the global one\n if (!resolveLanguage && options.resolveLanguage) {\n resolveLanguage = options.resolveLanguage;\n }\n const local = getPropertyOption(propertyName, propertySchema, options, 'local');\n // Determine readOnly: check PropertyOptions first, then x-ad4m.writable (inverted) for JSON Schema wire format\n let readOnly = getPropertyOption(propertyName, propertySchema, options, 'readOnly');\n if (readOnly === undefined) {\n const xWritable = propertySchema[\"x-ad4m\"]?.writable;\n readOnly = xWritable !== undefined ? !xWritable : false;\n }\n const writable = !readOnly;\n let initial = getPropertyOption(propertyName, propertySchema, options, 'initial');\n // Handle nested objects by serializing to JSON\n if (isObjectType(propertySchema) && !resolveLanguage) {\n resolveLanguage = 'literal';\n console.warn(`Property \"${propertyName}\" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);\n }\n // Ensure numeric properties use literal language for correct typing\n if ((resolveLanguage === undefined || resolveLanguage === null) && isNumericType(propertySchema)) {\n resolveLanguage = 'literal';\n }\n // Default resolveLanguage to 'literal' for all remaining property types,\n // matching the @Property decorator behaviour. Without this, string values\n // stored as literal: URLs are returned unparsed.\n if (resolveLanguage === undefined || resolveLanguage === null) {\n resolveLanguage = 'literal';\n }\n // If property is required, ensure it has an initial value\n if (isRequired && !initial) {\n if (isObjectType(propertySchema)) {\n initial = 'literal:json:{}';\n }\n else {\n initial = \"ad4m://undefined\";\n }\n }\n properties[propertyName] = {\n through: predicate,\n required: isRequired,\n writable: writable,\n ...(resolveLanguage && { resolveLanguage }),\n ...(local !== undefined && { local }),\n ...(initial && { initial })\n };\n // Define the property on prototype\n Object.defineProperty(DynamicModelClass.prototype, propertyName, {\n configurable: true,\n writable: true,\n value: getDefaultValueForType(propertyType)\n });\n // Add setter function if writable\n if (writable) {\n const setterName = propertyNameToSetterName(propertyName);\n DynamicModelClass.prototype[setterName] = function () {\n // This is a placeholder function that the SDNA generation looks for\n // The actual setter logic is handled by the Ad4mModel base class\n };\n }\n }\n }\n }\n // No auto-flag generation \u2014 models with all-optional properties use\n // open-world structural matching. Consumers who need type discrimination\n // should add an explicit @Flag to their model definition.\n // Attach metadata to WeakMap registries\n for (const [propName, propMeta] of Object.entries(properties)) {\n setPropertyRegistryEntry(DynamicModelClass, propName, propMeta);\n }\n for (const [relName, relMeta] of Object.entries(relations)) {\n setRelationRegistryEntry(DynamicModelClass, relName, {\n predicate: relMeta.through || \"\",\n kind: 'hasMany',\n ...(relMeta.getter !== undefined && { getter: relMeta.getter }),\n ...(relMeta.local !== undefined && { local: relMeta.local }),\n });\n }\n // Store the JSON schema and options on the prototype for potential fallback use by getModelMetadata()\n DynamicModelClass.prototype.__jsonSchema = schema;\n DynamicModelClass.prototype.__jsonSchemaOptions = options;\n // Apply the Model decorator to set up the generateSDNA method\n const ModelDecorator = Model$1({ name: options.name });\n ModelDecorator(DynamicModelClass);\n return DynamicModelClass;\n}\n\n/**\n * SPARQL query building utilities for Ad4mModel.\n *\n * Uses the RDF 1.2 reifier storage model where each AD4M link is stored as:\n * 1. Direct triple: <source> <predicate> <target> . (default graph)\n * 2. Reifier: <link:HASH> <http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies> <<( source predicate target )>> .\n * 3. Metadata: <link:HASH> ad4m://ontology/* \"value\" . (default graph)\n *\n * All AD4M URIs (source, predicate, target) become RDF IRIs.\n *\n * @module\n */\n/**\n * Check whether a `where` clause contains filters that cannot be pushed down\n * to SPARQL and must be evaluated in JS after hydration.\n *\n * JS-only filters include:\n * - Literal-stored properties (equality, comparison, contains, etc.)\n * - Reverse relations (belongsToOne / belongsToMany)\n * - author / timestamp filters (skipped by buildSPARQLWhereFilters)\n *\n * When JS-only filters exist, SPARQL-level LIMIT/OFFSET must NOT be applied\n * because the database would cap the candidate set before JS filters run,\n * potentially discarding matches beyond the LIMIT.\n */\nfunction hasJsOnlyWhereFilters(metadata, allRelationsMetadata, where) {\n if (!where)\n return false;\n for (const [propertyName, condition] of Object.entries(where)) {\n if (propertyName === \"base\" || propertyName === \"id\")\n continue;\n // author/timestamp filters are handled in JS\n if (propertyName === \"author\" || propertyName === \"timestamp\")\n return true;\n const propMeta = metadata.properties[propertyName];\n if (!propMeta)\n continue;\n // Reverse relations are JS-only\n const relMeta = allRelationsMetadata[propertyName];\n if (relMeta && (relMeta.kind === 'belongsToOne' || relMeta.kind === 'belongsToMany')) {\n return true;\n }\n // Literal-stored properties: equality/IN/NOT can be pushed to SPARQL via\n // <ad4m://fn/parse_literal>(), but comparison operators (gt/lt/gte/lte/between/contains)\n // must remain JS-only because parse_literal returns strings.\n if (isLiteralStoredProperty(propMeta)) {\n if (typeof condition === 'object' && condition !== null && !Array.isArray(condition)) {\n const ops = condition;\n const hasCompOps = ops.gt !== undefined || ops.gte !== undefined ||\n ops.lt !== undefined || ops.lte !== undefined ||\n ops.between !== undefined || ops.contains !== undefined;\n if (hasCompOps)\n return true;\n // NOT with simple value can be pushed to SPARQL \u2014 not JS-only\n }\n // Simple equality and IN filters can be pushed to SPARQL \u2014 not JS-only\n }\n }\n return false;\n}\n/**\n * Determine if a property stores values as literal: IRIs (needs parse_literal for comparisons).\n * Properties with resolveLanguage === \"literal\" AND properties without resolveLanguage\n * both store values as literal: URIs. Only properties with a non-literal resolveLanguage\n * (e.g. file storage) or flag properties store raw URIs.\n */\nfunction isLiteralStoredProperty(propMeta) {\n if (propMeta.flag)\n return false;\n // If resolveLanguage is set to something other than \"literal\", it's a language expression URI\n if (propMeta.resolveLanguage && propMeta.resolveLanguage !== \"literal\")\n return false;\n // Everything else (resolveLanguage === \"literal\" or undefined) stores as literal: URIs\n return true;\n}\n/**\n * Escape a string for use as a SPARQL string literal.\n */\nfunction escapeSPARQL(value) {\n return value\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, \"\\\\n\")\n .replace(/\\r/g, \"\\\\r\")\n .replace(/\\t/g, \"\\\\t\")\n .replace(/\\0/g, \"\")\n .replace(/\\f/g, \"\\\\u000C\");\n}\n/**\n * Format a value as a SPARQL string literal (double-quoted).\n */\nfunction formatSPARQLValue(value) {\n if (typeof value === \"string\") {\n return `\"${escapeSPARQL(value)}\"`;\n }\n return `\"${String(value)}\"`;\n}\n/**\n * Format an AD4M URI as an RDF IRI for use in SPARQL triple patterns.\n * All AD4M link source/predicate/target values become IRIs in angle brackets.\n * The Rust SPARQL service transparently transforms these to valid IRI format.\n *\n * Rejects characters that would break or inject into a SPARQL IRI token,\n * matching the Rust-side `validate_iri()` function.\n */\nfunction iri(value) {\n if (/[<>{}\" ]/.test(value)) {\n throw new Error(`Invalid IRI component: '${value}'`);\n }\n return `<${value}>`;\n}\n/**\n * Map a user-facing property name to the SPARQL variable alias used in the query.\n *\n * Properties appear in the query as:\n * - Required properties: `?cfTarget_${name}`\n * - Where-clause joins: `?wTarget_${name}`\n * - Initial-value fallback: `?cfInitTarget_${name}`\n *\n * For ORDER BY, we prefer the conformance variable (always present for required props),\n * then the where-target variable.\n */\nfunction mapPropertyToSPARQLVar(propertyName, metadata) {\n const propMeta = metadata.properties[propertyName];\n if (propMeta) {\n if (propMeta.required && !propMeta.getter && !(propMeta.flag && propMeta.initial)) {\n return `?cfTarget_${propertyName}`;\n }\n if (propMeta.initial && !propMeta.flag) {\n return `?cfInitTarget_${propertyName}`;\n }\n }\n // Fallback: where-clause variable or raw name\n return `?wTarget_${propertyName}`;\n}\n/**\n * Build a SPARQL query that returns all links belonging to instances of\n * the given model class, optionally filtered by `where` conditions.\n *\n * Uses direct triple patterns: ?source ?predicate ?target\n * with named graph storage and metadata keyed by graph IRI.\n */\nfunction buildSPARQLQuery(metadata, allRelationsMetadata, query, modelClass) {\n const joinPatterns = [];\n const filterExpressions = [];\n // Parent filter \u2014 direct triple pattern\n if (query.parent) {\n const parentPredicate = resolveParentPredicate(query.parent, modelClass);\n joinPatterns.push(`\n ${iri(query.parent.id)} ${iri(parentPredicate)} ?source .`);\n }\n // Required property JOIN patterns \u2014 direct triple patterns\n let hasConformance = false;\n for (const [, propMeta] of Object.entries(metadata.properties)) {\n if (propMeta.required) {\n if (propMeta.getter)\n continue;\n hasConformance = true;\n if (propMeta.flag && propMeta.initial) {\n joinPatterns.push(`\n ?source ${iri(propMeta.predicate)} ${iri(propMeta.initial)} .`);\n }\n else {\n joinPatterns.push(`\n ?source ${iri(propMeta.predicate)} ?cfTarget_${propMeta.name} .`);\n }\n }\n }\n // Fallback: initial-value JOIN patterns\n if (!hasConformance) {\n for (const [, propMeta] of Object.entries(metadata.properties)) {\n if (propMeta.initial) {\n hasConformance = true;\n if (propMeta.flag) {\n joinPatterns.push(`\n ?source ${iri(propMeta.predicate)} ${iri(propMeta.initial)} .`);\n }\n else {\n joinPatterns.push(`\n ?source ${iri(propMeta.predicate)} ?cfInitTarget_${propMeta.name} .`);\n }\n break;\n }\n }\n }\n // Fallback: open-world structural matching\n // Use a subquery with DISTINCT to avoid row multiplication when the main\n // ?source ?predicate ?target pattern cross-joins with multiple structural matches.\n if (!hasConformance && joinPatterns.length === 0) {\n const knownPredicates = [];\n for (const [, propMeta] of Object.entries(metadata.properties)) {\n if (propMeta.predicate) {\n knownPredicates.push(iri(propMeta.predicate));\n }\n }\n if (metadata.relations) {\n for (const [, relMeta] of Object.entries(metadata.relations)) {\n if (relMeta.predicate) {\n knownPredicates.push(iri(relMeta.predicate));\n }\n }\n }\n if (knownPredicates.length > 0) {\n joinPatterns.push(`\n { SELECT DISTINCT ?source WHERE { ?source ?cf_structPred ?cf_structTarget . FILTER(?cf_structPred IN (${knownPredicates.join(\", \")})) } }`);\n }\n }\n // Build WHERE clause filters from user query\n const { joins: userJoins, filters: userFilters } = buildSPARQLWhereFilters(metadata, allRelationsMetadata, query.where);\n joinPatterns.push(...userJoins);\n filterExpressions.push(...userFilters);\n // Main triple pattern \u2014 fetches all links for matched sources\n // Direct triple in default graph + RDF 1.2 reifier for link metadata\n // FILTER(isIRI(?source)) excludes non-IRI subjects\n const joinClause = joinPatterns.join(\"\\n\");\n const filterClause = filterExpressions.length > 0\n ? `FILTER(\\n ${filterExpressions.join(\" &&\\n \")}\\n )`\n : \"\";\n // Determine if SPARQL-level pagination is safe.\n // When JS-only where filters exist, we must NOT limit at the SPARQL level\n // because the database would cap candidates before JS filters run.\n const canPaginateInSPARQL = !hasJsOnlyWhereFilters(metadata, allRelationsMetadata, query.where)\n && (query.limit !== undefined || query.offset !== undefined);\n // Build a pagination subquery that constrains ?source to only the page\n // of interest. This avoids fetching all links for all matching instances.\n const paginationSubquery = canPaginateInSPARQL\n ? buildPaginationSubquery(joinPatterns, filterExpressions, metadata, query)\n : '';\n if (paginationSubquery) {\n // Use the pagination subquery to constrain ?source, then fetch all links\n // for those sources only.\n return `\n\n SELECT ?source ?predicate ?target ?author ?timestamp WHERE {\n ${paginationSubquery}${joinClause}\n ?source ?predicate ?target .\n ?_reifier <http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies> <<( ?source ?predicate ?target )>> .\n FILTER(isIRI(?source) && isIRI(?predicate))\n ?_reifier <ad4m://ontology/author> ?author .\n ?_reifier <ad4m://ontology/timestamp> ?timestamp .\n ${filterClause}\n }\n `.trim();\n }\n return `\n\n SELECT ?source ?predicate ?target ?author ?timestamp WHERE {${joinClause}\n ?source ?predicate ?target .\n ?_reifier <http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies> <<( ?source ?predicate ?target )>> .\n FILTER(isIRI(?source) && isIRI(?predicate))\n ?_reifier <ad4m://ontology/author> ?author .\n ?_reifier <ad4m://ontology/timestamp> ?timestamp .\n ${filterClause}\n }\n `.trim();\n}\n/**\n * Build an inner subquery that selects DISTINCT ?source URIs with\n * ORDER BY, LIMIT, and OFFSET applied at the instance level.\n *\n * Because the outer SELECT returns multiple rows per instance (one per link),\n * we cannot apply LIMIT/OFFSET there. Instead this subquery constrains\n * ?source to only the instances on the requested page.\n *\n * @internal \u2014 used by buildSPARQLQuery when SPARQL-level pagination is safe.\n */\nfunction buildPaginationSubquery(joinPatterns, filterExpressions, metadata, query) {\n const innerJoin = joinPatterns.join('\\n');\n const innerFilter = filterExpressions.length > 0\n ? `FILTER(\\n ${filterExpressions.join(' &&\\n ')}\\n )`\n : '';\n // Build ORDER BY clause from query.order\n let orderByClause = '';\n const orderJoinPatterns = [];\n if (query.order) {\n const orderTerms = Object.entries(query.order).map(([prop, dir]) => {\n const sparqlVar = mapPropertyToSPARQLVar(prop, metadata);\n // Check if this order property's variable is already bound by existing\n // join patterns. If not, add an OPTIONAL join so ORDER BY is deterministic.\n const varAlreadyBound = innerJoin.includes(sparqlVar);\n if (!varAlreadyBound) {\n const propMeta = metadata.properties[prop];\n if (propMeta && propMeta.predicate && !propMeta.getter) {\n orderJoinPatterns.push(`\\n OPTIONAL { ?source <${propMeta.predicate}> ${sparqlVar} . }`);\n }\n }\n return dir === 'DESC' ? `DESC(${sparqlVar})` : `ASC(${sparqlVar})`;\n });\n if (orderTerms.length > 0) {\n orderByClause = `ORDER BY ${orderTerms.join(' ')}`;\n }\n }\n // No default ordering \u2014 when no explicit order is specified, results come in\n // natural (insertion) order.\n const tsSelect = '';\n const tsPattern = '';\n const limitClause = query.limit !== undefined ? `LIMIT ${query.limit}` : '';\n const offsetClause = query.offset !== undefined && query.offset > 0 ? `OFFSET ${query.offset}` : '';\n return `\n { SELECT DISTINCT ?source${tsSelect} WHERE {${innerJoin}${orderJoinPatterns.join('')}${tsPattern}\n FILTER(isIRI(?source))\n ${innerFilter}\n } ${orderByClause} ${limitClause} ${offsetClause} }\\n`;\n}\n/**\n * Build SPARQL FILTER expressions from user `where` conditions.\n * Uses direct triple patterns instead of link-node reification.\n */\nfunction buildSPARQLWhereFilters(metadata, _allRelationsMetadata, where) {\n if (!where)\n return { joins: [], filters: [] };\n const joins = [];\n const filters = [];\n for (const [propertyName, condition] of Object.entries(where)) {\n // 'base' maps to ?source\n if (propertyName === \"base\" || propertyName === \"id\") {\n if (Array.isArray(condition)) {\n const formatted = condition.map(v => iri(v)).join(\", \");\n filters.push(`?source IN (${formatted})`);\n }\n else if (typeof condition === \"object\" && condition !== null) {\n const ops = condition;\n if (ops.not !== undefined) {\n if (Array.isArray(ops.not)) {\n const formatted = ops.not.map(v => iri(v)).join(\", \");\n filters.push(`!(?source IN (${formatted}))`);\n }\n else {\n filters.push(`?source != ${iri(ops.not)}`);\n }\n }\n }\n else {\n filters.push(`?source = ${iri(String(condition))}`);\n }\n continue;\n }\n if (propertyName === \"author\" || propertyName === \"timestamp\") {\n continue;\n }\n const propMeta = metadata.properties[propertyName];\n if (!propMeta)\n continue;\n // Skip reverse relations (belongsToOne / belongsToMany) \u2014 these are registered as\n // read-only properties but the link direction is reversed (target\u2192source, not source\u2192target).\n // Adding a forward join pattern would match nothing. These are filtered in JS post-filter.\n const relMeta = _allRelationsMetadata[propertyName];\n if (relMeta && (relMeta.kind === 'belongsToOne' || relMeta.kind === 'belongsToMany')) {\n continue;\n }\n // Determine if this property stores values as literal: IRIs\n const useParseLiteral = isLiteralStoredProperty(propMeta);\n // For literal-stored properties, push equality/IN/NOT filters to SPARQL using\n // <ad4m://fn/parse_literal>() which extracts the raw value from literal: IRIs.\n // The correct SPARQL syntax is <ad4m://fn/parse_literal>(?var) \u2014 NOT fn::parse_literal\n // (which was SurrealDB syntax that Oxigraph rejects at parse time).\n // Comparison operators (gt/lt/gte/lte/between/contains) remain JS-only because\n // parse_literal returns strings and numeric/date comparisons would be unreliable.\n // JS post-filter in instancesFromQueryResult remains as a safety net for all cases.\n if (useParseLiteral) {\n if (typeof condition === \"object\" && condition !== null && !Array.isArray(condition)) {\n const ops = condition;\n const hasCompOps = ops.gt !== undefined || ops.gte !== undefined ||\n ops.lt !== undefined || ops.lte !== undefined ||\n ops.between !== undefined || ops.contains !== undefined;\n if (hasCompOps) {\n // Comparison operators: join only, filter in JS\n joins.push(`\n ?source ${iri(propMeta.predicate)} ?wTarget_cmp_${propertyName} .`);\n }\n if (ops.not !== undefined) {\n // NOT filter: push down to SPARQL\n joins.push(`\n ?source ${iri(propMeta.predicate)} ?wTarget_${propertyName} .`);\n if (Array.isArray(ops.not)) {\n const formatted = ops.not.map((v) => formatSPARQLValue(v)).join(\", \");\n filters.push(`STR(<ad4m://fn/parse_literal>(?wTarget_${propertyName})) NOT IN (${formatted})`);\n }\n else {\n filters.push(`STR(<ad4m://fn/parse_literal>(?wTarget_${propertyName})) != ${formatSPARQLValue(ops.not)}`);\n }\n }\n }\n else if (Array.isArray(condition)) {\n // IN filter: push down to SPARQL\n joins.push(`\n ?source ${iri(propMeta.predicate)} ?wTarget_${propertyName} .`);\n const formatted = condition.map((v) => formatSPARQLValue(v)).join(\", \");\n filters.push(`STR(<ad4m://fn/parse_literal>(?wTarget_${propertyName})) IN (${formatted})`);\n }\n else {\n // Simple equality: push down to SPARQL\n joins.push(`\n ?source ${iri(propMeta.predicate)} ?wTarget_${propertyName} .`);\n filters.push(`STR(<ad4m://fn/parse_literal>(?wTarget_${propertyName})) = ${formatSPARQLValue(condition)}`);\n }\n }\n else if (Array.isArray(condition)) {\n const formatted = condition.map(v => iri(v)).join(\", \");\n joins.push(`\n ?source ${iri(propMeta.predicate)} ?wTarget_${propertyName} .`);\n filters.push(`?wTarget_${propertyName} IN (${formatted})`);\n }\n else if (typeof condition === \"object\" && condition !== null) {\n const ops = condition;\n if (ops.not !== undefined) {\n if (Array.isArray(ops.not)) {\n const formatted = ops.not.map(v => iri(v)).join(\", \");\n filters.push(`\n NOT EXISTS {\n ?source ${iri(propMeta.predicate)} ?wTarget_not_${propertyName} .\n FILTER(?wTarget_not_${propertyName} IN (${formatted}))\n }\n `);\n }\n else {\n filters.push(`\n NOT EXISTS {\n ?source ${iri(propMeta.predicate)} ${iri(ops.not)} .\n }\n `);\n }\n }\n const hasCompOps = ops.gt !== undefined || ops.gte !== undefined ||\n ops.lt !== undefined || ops.lte !== undefined ||\n ops.between !== undefined || ops.contains !== undefined;\n if (hasCompOps) {\n joins.push(`\n ?source ${iri(propMeta.predicate)} ?wTarget_cmp_${propertyName} .`);\n }\n }\n else {\n // Simple equality \u2014 non-literal property, use exact IRI match\n joins.push(`\n ?source ${iri(propMeta.predicate)} ${iri(String(condition))} .`);\n }\n }\n return { joins, filters };\n}\n\n/**\n * ModelQueryBuilder \u2014 fluent query builder for Ad4mModel.\n *\n * Allows building queries with a chainable interface and either\n * running them once or subscribing to real-time updates.\n */\n/** Query builder for Ad4mModel queries.\n * Allows building queries with a fluent interface and either running them once\n * or subscribing to updates.\n *\n * @example\n * ```typescript\n * const builder = Recipe.query(perspective)\n * .where({ category: \"Dessert\" })\n * .order({ rating: \"DESC\" })\n * .limit(10);\n *\n * // Run once\n * const recipes = await builder.run();\n *\n * // Or subscribe to updates\n * await builder.subscribe(recipes => {\n * console.log(\"Updated recipes:\", recipes);\n * });\n * ```\n */\nclass ModelQueryBuilder {\n constructor(perspective, ctor, query) {\n this.queryParams = {};\n this.modelClassName = null;\n this.perspective = perspective;\n this.ctor = ctor;\n if (query)\n this.queryParams = query;\n }\n /**\n * Disposes of the current subscription if one exists.\n *\n * This method:\n * 1. Stops the keepalive signals to the subscription\n * 2. Unsubscribes from subscription updates\n * 3. Notifies the backend to clean up subscription resources\n * 4. Clears the subscription reference\n *\n * You should call this method when you're done with a subscription\n * to prevent memory leaks and ensure proper cleanup.\n */\n dispose() {\n if (this.currentSubscription) {\n this.currentSubscription.dispose();\n this.currentSubscription = undefined;\n }\n }\n /**\n * Adds where conditions to the query.\n *\n * @param conditions - The conditions to filter by\n * @returns The query builder for chaining\n *\n * @example\n * ```typescript\n * .where({\n * category: \"Dessert\",\n * rating: { gt: 4 },\n * tags: [\"vegan\", \"quick\"],\n * published: true\n * })\n * ```\n */\n where(conditions) {\n this.queryParams.where = conditions;\n return this;\n }\n /**\n * Sets the order for the query results.\n *\n * @param orderBy - The ordering criteria\n * @returns The query builder for chaining\n *\n * @example\n * ```typescript\n * .order({ createdAt: \"DESC\" })\n * ```\n */\n order(orderBy) {\n this.queryParams.order = orderBy;\n return this;\n }\n /**\n * Sets the maximum number of results to return.\n *\n * @param limit - Maximum number of results\n * @returns The query builder for chaining\n *\n * @example\n * ```typescript\n * .limit(10)\n * ```\n */\n limit(limit) {\n this.queryParams.limit = limit;\n return this;\n }\n /**\n * Sets the number of results to skip.\n *\n * @param offset - Number of results to skip\n * @returns The query builder for chaining\n *\n * @example\n * ```typescript\n * .offset(20) // Skip first 20 results\n * ```\n */\n offset(offset) {\n this.queryParams.offset = offset;\n return this;\n }\n /**\n * Scopes the query to instances linked from a parent.\n *\n * The predicate is resolved in order of precedence:\n * 1. **Instance only** \u2014 the parent's constructor is used as the model\n * class; its relation metadata is scanned for a relation whose\n * `target()` matches the queried model class.\n * 2. **Instance + options with `field`** \u2014 direct field-name lookup on\n * the parent model's relation metadata (disambiguates when a parent\n * has multiple relations targeting the same child class).\n * 3. **String id + model class** \u2014 same metadata scan (or field lookup if\n * options include `field`).\n * 4. **String id + string predicate** \u2014 raw escape hatch, no metadata lookup.\n *\n * Passing a plain string id with no second argument throws because the\n * predicate cannot be resolved without a model class.\n *\n * @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance\n * @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string\n * @param options - Optional settings: `field` for direct relation-name lookup\n * @returns The query builder for chaining\n *\n * @example\n * ```typescript\n * // Instance \u2014 predicate auto-resolved from Cookbook's @HasMany(() => Recipe)\n * Recipe.query(perspective).parent(cookbook).get();\n *\n * // Instance + field \u2014 disambiguate when parent has multiple relations to same child\n * Recipe.query(perspective).parent(cookbook, { field: \"recipes\" }).get();\n *\n * // String id + model class\n * Recipe.query(perspective).parent(cookbookId, Cookbook).get();\n *\n * // String id + model class + field\n * Recipe.query(perspective).parent(cookbookId, Cookbook, { field: \"recipes\" }).get();\n *\n * // String id + raw predicate (escape hatch)\n * Recipe.query(perspective).parent(cookbookId, \"cookbook://recipe\").get();\n * ```\n */\n parent(idOrInstance, modelOrPredicate, options) {\n const id = typeof idOrInstance === 'string' ? idOrInstance : idOrInstance.id;\n // Handle options-object as second arg: parent(instance, { field: \"recipes\" })\n if (typeof modelOrPredicate === 'object' && modelOrPredicate !== null && !('prototype' in modelOrPredicate)) {\n if (typeof idOrInstance === 'string') {\n throw new Error('parent() called with a string id and options object requires a model class as second argument');\n }\n const model = idOrInstance.constructor;\n this.queryParams.parent = { id, model, field: modelOrPredicate.field };\n return this;\n }\n const field = options?.field;\n if (typeof modelOrPredicate === 'string') {\n // Raw predicate string \u2192 raw form of ParentScope\n this.queryParams.parent = { id, predicate: modelOrPredicate };\n }\n else if (typeof modelOrPredicate === 'function') {\n // Model class \u2192 model form of ParentScope\n this.queryParams.parent = { id, model: modelOrPredicate, ...(field && { field }) };\n }\n else if (typeof idOrInstance !== 'string') {\n // Ad4mModel instance \u2014 derive model class from constructor\n this.queryParams.parent = { id, model: idOrInstance.constructor, ...(field && { field }) };\n }\n else {\n throw new Error('parent() called with a string id requires a second argument: either a model class or a predicate string');\n }\n return this;\n }\n /**\n * Specifies which properties to include in the results.\n *\n * @param properties - Array of property names to include\n * @returns The query builder for chaining\n *\n * @example\n * ```typescript\n * .properties([\"name\", \"description\", \"rating\"])\n * ```\n */\n properties(properties) {\n this.queryParams.properties = properties;\n return this;\n }\n /**\n * Controls whether SPARQL property getters are evaluated during hydration.\n *\n * By default, collection queries evaluate property getters (deepQuery=true).\n * Call `.deepQuery(false)` to skip getter evaluation for performance.\n *\n * @param enabled - Whether to evaluate property getters (default: true)\n * @returns The query builder for chaining\n *\n * @example\n * ```typescript\n * const messages = await Message.query(perspective)\n * .parent(channel)\n * .deepQuery(false) // skip property getters for performance\n * .limit(30)\n * .get();\n * ```\n */\n deepQuery(enabled = true) {\n this.queryParams.deepQuery = enabled;\n return this;\n }\n /**\n * Specifies which relations to eager-load (hydrate into model instances).\n *\n * Without `include`, relation fields contain raw expression URIs (strings).\n * With `include`, the URIs are resolved into fully-hydrated model instances\n * using the `target` class declared in the relation decorator.\n *\n * Supports nested includes for multi-level eager loading.\n *\n * @param map - An IncludeMap describing which relations to hydrate\n * @returns The query builder for chaining\n *\n * @example\n * ```typescript\n * // Hydrate comments one level deep\n * const recipes = await Recipe.query(perspective)\n * .include({ comments: true })\n * .run();\n * // recipe.comments is now Comment[] (model instances), not string[]\n *\n * // Nested: hydrate comments AND each comment's author\n * const recipes = await Recipe.query(perspective)\n * .include({ comments: { author: true } })\n * .run();\n * ```\n */\n include(map) {\n this.queryParams.include = map;\n return this;\n }\n overrideModelClassName(className) {\n this.modelClassName = className;\n return this;\n }\n /**\n * Sets the query engine to use.\n * @deprecated Prolog engine has been removed. All queries use SPARQL/Rust.\n */\n engine(_eng) {\n return this;\n }\n /**\n * Executes the query once and returns the results.\n *\n * @returns Array of matching entities\n *\n * @example\n * ```typescript\n * const recipes = await Recipe.query(perspective)\n * .where({ category: \"Dessert\" })\n * .get();\n * ```\n */\n async get() {\n return await this.executeSparqlQuery();\n }\n /**\n * Executes the query once using SPARQL and returns the results.\n */\n async getSparql() {\n return this.executeSparqlQuery();\n }\n /**\n * Shared query execution logic \u2014 routes through the executor-side modelQuery endpoint.\n */\n async executeSparqlQuery() {\n const { results } = await this.ctor.executeModelQuery(this.perspective, this.queryParams, this.modelClassName);\n return results;\n }\n /**\n * Returns the first matching instance, or `null` if none match.\n *\n * Internally sets `limit: 1` and delegates to `get()`.\n *\n * @returns The first matching instance, or `null`\n *\n * @example\n * ```typescript\n * const recipe = await Recipe.query(perspective)\n * .where({ name: \"Pasta\" })\n * .first();\n * ```\n */\n async first() {\n const savedLimit = this.queryParams.limit;\n this.queryParams.limit = 1;\n const results = await this.get();\n this.queryParams.limit = savedLimit;\n return results[0] ?? null;\n }\n /**\n * Subscribes to the query and receives updates when results change.\n *\n * This method:\n * 1. Creates and initializes a SPARQL live query subscription (default)\n * 2. Sets up the callback to process future updates\n * 3. Returns the initial results immediately\n *\n * Remember to call dispose() when you're done with the subscription\n * to clean up resources.\n *\n * @param callback - Function to call with updated results\n * @returns Initial results array\n *\n * @example\n * ```typescript\n * const builder = Recipe.query(perspective)\n * .where({ status: \"cooking\" });\n *\n * const initialRecipes = await builder.subscribe(recipes => {\n * console.log(\"Updated recipes:\", recipes);\n * });\n *\n * // When done with subscription:\n * builder.dispose();\n * ```\n *\n */\n async subscribe(callback) {\n // Clean up any existing subscription\n this.dispose();\n const ctor = this.ctor;\n // Build the model query params (className, queryJson, shapeJson)\n const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);\n // Register model subscription via Rust \u2014 this builds trigger SPARQL internally,\n // registers the subscription, and runs the initial query in one call.\n const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);\n // Convert JSON instances to model class instances\n const parseResults = (raw) => {\n return ctor.parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);\n };\n // Resolve non-literal (file-language) properties \u2014 handles both raw URI strings\n // and already-resolved FileData objects returned by the Rust executor.\n const resolveAndReturn = async (instances) => {\n await ctor.resolveNonLiteralProps(this.perspective, instances);\n return instances;\n };\n // Parse initial results (with non-literal resolution)\n const initialResults = await resolveAndReturn(parseResults(initialModelResult));\n // Track last emitted result fingerprint to suppress duplicate callbacks\n let lastResultFingerprint = null;\n const buildFingerprint = (results) => {\n if (results.length === 0)\n return '0:';\n return JSON.stringify(results, (_, v) => typeof v === 'function' ? undefined : v);\n };\n lastResultFingerprint = buildFingerprint(initialResults);\n // Listen for subscription updates via the same GraphQL subscription channel.\n // When Rust re-runs the model query and finds changed results, it pushes them.\n const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {\n try {\n const parsed = parseResults(rawResult);\n console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${parsed.length} instances`);\n resolveAndReturn(parsed).then((results) => {\n const fp = buildFingerprint(results);\n if (fp === lastResultFingerprint) {\n console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);\n return;\n }\n console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);\n lastResultFingerprint = fp;\n callback(results);\n }).catch((e) => {\n console.error('Model subscription update resolve error:', e);\n });\n }\n catch (e) {\n console.error('Model subscription update parse error:', e);\n }\n });\n // Set up keepalive with recovery \u2014 uses setTimeout loop so we can\n // break out and resubscribe when the server evicts the subscription.\n let disposed = false;\n let keepaliveTimer;\n let resubscribeAttempts = 0;\n const MAX_RESUBSCRIBE_ATTEMPTS = 5;\n const keepaliveLoop = async () => {\n if (disposed)\n return;\n try {\n await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);\n resubscribeAttempts = 0; // Reset on success\n }\n catch (e) {\n console.warn(`Model subscription keepalive failed for ${subscriptionId}:`, e);\n if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {\n resubscribeAttempts++;\n const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);\n console.warn(`Resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);\n await new Promise(r => setTimeout(r, backoffMs));\n try {\n unsubscribe();\n await this.subscribe(callback);\n }\n catch (resubErr) {\n console.error('Model subscription resubscribe failed:', resubErr);\n }\n }\n else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {\n console.error(`Model subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);\n }\n return; // new subscription owns its own keepalive loop\n }\n if (!disposed) {\n keepaliveTimer = setTimeout(keepaliveLoop, 30000);\n }\n };\n keepaliveTimer = setTimeout(keepaliveLoop, 30000);\n // Store dispose function\n this.currentSubscription = {\n dispose: () => {\n disposed = true;\n if (keepaliveTimer)\n clearTimeout(keepaliveTimer);\n unsubscribe();\n this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });\n },\n };\n // Take snapshots for dirty tracking\n for (const inst of initialResults) {\n inst.takeSnapshot?.(this.queryParams.include);\n }\n return initialResults;\n }\n /**\n * Subscribes to the query and receives updates using SPARQL.\n * @deprecated Use subscribe() instead \u2014 now routes through Rust model subscription.\n */\n async subscribeSparql(callback) {\n return this.subscribe(callback);\n }\n /**\n * Gets the total count of matching entities.\n *\n * @returns Total count\n *\n * @example\n * ```typescript\n * const totalDesserts = await Recipe.query(perspective)\n * .where({ category: \"Dessert\" })\n * .count();\n * ```\n */\n async count() {\n const { totalCount } = await this.ctor.executeModelQuery(this.perspective, { ...this.queryParams, limit: 0 }, this.modelClassName);\n return totalCount;\n }\n /**\n * Gets the total count of matching entities using SPARQL.\n * Delegates to count().\n */\n async countSparql() {\n return await this.count();\n }\n /**\n * Subscribes to count updates for matching entities.\n *\n * This method:\n * 1. Creates and initializes a SPARQL live query subscription for the count (default)\n * 2. Sets up the callback to process future count updates\n * 3. Returns the initial count immediately\n *\n * Remember to call dispose() when you're done with the subscription\n * to clean up resources.\n *\n * @param callback - Function to call with updated count\n * @returns Initial count\n *\n * @example\n * ```typescript\n * const builder = Recipe.query(perspective)\n * .where({ status: \"active\" });\n *\n * const initialCount = await builder.countSubscribe(count => {\n * console.log(\"Active items:\", count);\n * });\n *\n * // When done with subscription:\n * builder.dispose();\n * ```\n *\n */\n async countSubscribe(callback) {\n // Clean up any existing subscription\n this.dispose();\n const countParams = { ...this.queryParams, limit: 0 };\n const { className, queryJson, shapeJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);\n const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);\n const parseCount = (raw) => {\n const data = typeof raw === 'string' ? JSON.parse(raw) : raw;\n return data.totalCount ?? 0;\n };\n const initialCount = parseCount(initialModelResult);\n const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {\n try {\n callback(parseCount(rawResult));\n }\n catch (e) {\n console.error('Count subscription update parse error:', e);\n }\n });\n let disposed = false;\n let keepaliveTimer;\n let resubscribeAttempts = 0;\n const MAX_RESUBSCRIBE_ATTEMPTS = 5;\n const keepaliveLoop = async () => {\n if (disposed)\n return;\n try {\n await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);\n resubscribeAttempts = 0;\n }\n catch (e) {\n console.warn(`Count subscription keepalive failed for ${subscriptionId}:`, e);\n if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {\n resubscribeAttempts++;\n const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);\n console.warn(`Count resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);\n await new Promise(r => setTimeout(r, backoffMs));\n try {\n unsubscribe();\n await this.countSubscribe(callback);\n }\n catch (resubErr) {\n console.error('Count subscription resubscribe failed:', resubErr);\n }\n }\n else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {\n console.error(`Count subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);\n }\n return;\n }\n if (!disposed) {\n keepaliveTimer = setTimeout(keepaliveLoop, 30000);\n }\n };\n keepaliveTimer = setTimeout(keepaliveLoop, 30000);\n this.currentSubscription = {\n dispose: () => {\n disposed = true;\n if (keepaliveTimer)\n clearTimeout(keepaliveTimer);\n unsubscribe();\n this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });\n },\n };\n return initialCount;\n }\n /**\n * Subscribes to count updates using SPARQL.\n * @deprecated Use countSubscribe() instead \u2014 now routes through Rust model subscription.\n */\n async countSubscribeSparql(callback) {\n return this.countSubscribe(callback);\n }\n /**\n * Gets a page of results with pagination metadata.\n *\n * @param pageSize - Number of items per page\n * @param pageNumber - Which page to retrieve (1-based)\n * @returns Paginated results with metadata\n *\n * @example\n * ```typescript\n * const page = await Recipe.query(perspective)\n * .where({ category: \"Main\" })\n * .paginate(10, 1);\n * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);\n * ```\n */\n async paginate(pageSize, pageNumber) {\n const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };\n const { results, totalCount } = await this.ctor.executeModelQuery(this.perspective, paginationQuery, this.modelClassName);\n return { results, totalCount, pageSize, pageNumber };\n }\n /**\n * Gets a page of results using SPARQL.\n * Delegates to paginate().\n */\n async paginateSparql(pageSize, pageNumber) {\n return await this.paginate(pageSize, pageNumber);\n }\n /**\n * Subscribes to paginated results updates.\n *\n * This method:\n * 1. Creates and initializes a SPARQL live query subscription for the paginated results (default)\n * 2. Sets up the callback to process future page updates\n * 3. Returns the initial page immediately\n *\n * Remember to call dispose() when you're done with the subscription\n * to clean up resources.\n *\n * @param pageSize - Number of items per page\n * @param pageNumber - Which page to retrieve (1-based)\n * @param callback - Function to call with updated pagination results\n * @returns Initial pagination results\n *\n * @example\n * ```typescript\n * const builder = Recipe.query(perspective)\n * .where({ category: \"Main\" });\n *\n * const initialPage = await builder.paginateSubscribe(10, 1, page => {\n * console.log(\"Updated page:\", page.results);\n * });\n *\n * // When done with subscription:\n * builder.dispose();\n * ```\n *\n */\n async paginateSubscribe(pageSize, pageNumber, callback) {\n // Clean up any existing subscription\n this.dispose();\n const ctor = this.ctor;\n // Subscribe to the full result set (no limit/offset) so the subscription\n // detects changes anywhere in the dataset. Rust builds trigger SPARQL\n // from the shape predicates.\n const subscriptionParams = { ...(this.queryParams || {}) };\n delete subscriptionParams.limit;\n delete subscriptionParams.offset;\n const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);\n const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);\n // Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)\n const paginatedQuery = {\n ...(this.queryParams || {}),\n limit: pageSize,\n offset: pageSize * (pageNumber - 1),\n count: true,\n };\n const processResults = async () => {\n const { results, totalCount } = await ctor.executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);\n callback({ results, totalCount, pageSize, pageNumber });\n };\n const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {\n console.debug(`[ModelQueryBuilder.paginateSubscribe] Update received for ${subscriptionId}, re-fetching paginated data...`);\n processResults().catch(e => console.error('Paginate subscription error:', e));\n });\n let disposed = false;\n let keepaliveTimer;\n let resubscribeAttempts = 0;\n const MAX_RESUBSCRIBE_ATTEMPTS = 5;\n const keepaliveLoop = async () => {\n if (disposed)\n return;\n try {\n await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);\n resubscribeAttempts = 0;\n }\n catch (e) {\n console.warn(`Paginate subscription keepalive failed for ${subscriptionId}:`, e);\n if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {\n resubscribeAttempts++;\n const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);\n console.warn(`Paginate resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);\n await new Promise(r => setTimeout(r, backoffMs));\n try {\n unsubscribe();\n await this.paginateSubscribe(pageSize, pageNumber, callback);\n }\n catch (resubErr) {\n console.error('Paginate subscription resubscribe failed:', resubErr);\n }\n }\n else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {\n console.error(`Paginate subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);\n }\n return;\n }\n if (!disposed) {\n keepaliveTimer = setTimeout(keepaliveLoop, 30000);\n }\n };\n keepaliveTimer = setTimeout(keepaliveLoop, 30000);\n this.currentSubscription = {\n dispose: () => {\n disposed = true;\n if (keepaliveTimer)\n clearTimeout(keepaliveTimer);\n unsubscribe();\n this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });\n },\n };\n // Initial fetch (single call with count: true)\n const { results, totalCount } = await ctor.executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);\n return { results, totalCount, pageSize, pageNumber };\n }\n /**\n * Subscribes to paginated results updates using SPARQL.\n * Delegates to paginateSubscribe().\n */\n async paginateSubscribeSparql(pageSize, pageNumber, callback) {\n return await this.paginateSubscribe(pageSize, pageNumber, callback);\n }\n}\n\n/**\n * hydration.ts \u2014 Instance hydration helpers extracted from Ad4mModel.\n *\n * After the Rust model_query pipeline migration, most hydration logic moved\n * to Rust. This file retains:\n * - normalizeValue() \u2014 snapshot dirty-tracking\n */\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Pure helpers\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n/**\n * Normalize a value for snapshot storage.\n * Arrays of model instances are reduced to their `.id` strings so that\n * dirty-tracking compares stable identifiers instead of object references.\n */\nfunction normalizeValue(value) {\n if (Array.isArray(value)) {\n return value.map((v) => v && typeof v === 'object' && typeof v.id === 'string' ? v.id : v);\n }\n return value;\n}\n\n// ---------------------------------------------------------------------------\n// Default decoder for file-storage (non-literal resolveLanguage) properties\n// ---------------------------------------------------------------------------\n/**\n * When the Rust executor resolves a non-literal expression it may return a\n * `FileData`-shaped object (`{ data_base64, file_type, ... }`) rather than a\n * raw URI string. If the model class has no custom `transform` registered\n * (e.g. it was synthesised from a SHACL shape at runtime) we still want to\n * decode the content rather than passing raw `FileData` to callers.\n *\n * Decoding rules (mirrors the JS `decodeFileAsJson` / `decodeFileAsString` helpers):\n * - `application/json` (default when `file_type` is absent) \u2192 JSON.parse\n * - anything else \u2192 raw decoded string\n *\n * If `resolved` is not a `FileData` object the value is returned unchanged so\n * that callers can use this as a safe unconditional fallback.\n */\nfunction defaultFileDecode(resolved) {\n if (resolved !== null &&\n typeof resolved === 'object' &&\n 'data_base64' in resolved) {\n const fd = resolved;\n let raw;\n try {\n raw = atob(fd.data_base64);\n }\n catch {\n return resolved; // malformed base64 \u2014 keep as-is\n }\n const isJson = !fd.file_type || fd.file_type === 'application/json';\n if (isJson) {\n try {\n return JSON.parse(raw);\n }\n catch {\n return raw;\n }\n }\n return raw;\n }\n return resolved;\n}\n// ---------------------------------------------------------------------------\n// Helpers for Rust-side include resolution\n// ---------------------------------------------------------------------------\n/**\n * Recursively enrich relation metadata in the shape with target class shapes\n * so the Rust endpoint can resolve includes in-process (no extra GraphQL\n * round-trips per relation).\n */\nfunction enrichShapeForIncludes(metadata, include, allRelMeta) {\n for (const [relName, includeVal] of Object.entries(include)) {\n if (!includeVal)\n continue;\n const meta = allRelMeta[relName];\n if (!meta?.target)\n continue;\n const TargetClass = meta.target();\n // Deep-copy so we don't mutate the cached metadata\n const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));\n // Ensure the relation is in metadata.relations (fallback for edge cases)\n if (!metadata.relations[relName]) {\n metadata.relations[relName] = {\n name: relName,\n predicate: meta.predicate,\n direction: meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'\n ? 'reverse'\n : 'forward',\n };\n }\n const rel = metadata.relations[relName];\n rel.kind = meta.kind;\n rel.maxCount = meta.maxCount;\n rel.targetShape = targetMeta;\n rel.targetClassName = targetMeta.className;\n // Recurse for nested includes\n const nested = typeof includeVal === 'object' && includeVal !== null\n ? includeVal.include\n : undefined;\n if (nested) {\n const targetRelMeta = getRelationsMetadata(TargetClass);\n enrichShapeForIncludes(targetMeta, nested, targetRelMeta);\n }\n }\n}\n/**\n * Construct a model class instance from a plain JSON object returned by the\n * Rust endpoint. Recursively converts included relation values (which come\n * back as plain JSON objects) into proper model class instances.\n */\nfunction jsonToModelInstance(ModelClass, perspective, json, include, properties) {\n const instance = new ModelClass(perspective, json.id || json.baseExpression);\n // When a properties projection is active, remove own properties set by the\n // constructor that are not in the projected JSON. This ensures assertions\n // like `expect(r).to.not.have.own.property(\"body\")` pass.\n if (properties) {\n const jsonKeys = new Set(Object.keys(json));\n for (const key of Object.getOwnPropertyNames(instance)) {\n // Keep internal fields (backing store for getters), id, baseExpression, perspective\n if (key === 'id' || key === 'baseExpression' || key === 'perspective' || key.startsWith('_'))\n continue;\n if (!jsonKeys.has(key)) {\n delete instance[key];\n }\n }\n }\n for (const [key, value] of Object.entries(json)) {\n if (key === 'baseExpression' || key === 'id')\n continue;\n // Skip getter-only properties anywhere in the prototype chain\n let isReadonly = false;\n let proto = Object.getPrototypeOf(instance);\n while (proto) {\n const desc = Object.getOwnPropertyDescriptor(proto, key);\n if (desc) {\n isReadonly = !!(desc.get && !desc.set);\n break;\n }\n proto = Object.getPrototypeOf(proto);\n }\n if (isReadonly)\n continue;\n // Parse ISO timestamps to epoch milliseconds (matches hydrateFromLinks behaviour)\n if ((key === 'createdAt' || key === 'updatedAt') && typeof value === 'string' && value.includes('T')) {\n instance[key] = new Date(value).getTime();\n continue;\n }\n instance[key] = value;\n }\n // Apply property transform functions from decorators (only for literal-resolved\n // or no-resolveLanguage properties; non-literal properties are resolved + transformed\n // asynchronously in executeModelQuery).\n try {\n const propsMeta = getPropertiesMetadata(ModelClass);\n for (const [propName, opts] of Object.entries(propsMeta)) {\n const o = opts;\n if (typeof o.transform !== 'function' || !(propName in json))\n continue;\n // Skip non-literal resolveLanguage props \u2014 they need async expression resolution first\n if (o.resolveLanguage != null && o.resolveLanguage !== 'literal')\n continue;\n instance[propName] = o.transform(instance[propName]);\n }\n }\n catch (e) {\n console.debug('jsonToModelInstance: transform metadata unavailable:', e);\n }\n // Recursively convert included relation values to class instances\n if (include) {\n const relMeta = getRelationsMetadata(ModelClass);\n for (const [relName, includeVal] of Object.entries(include)) {\n if (!includeVal)\n continue;\n const meta = relMeta[relName];\n if (!meta?.target)\n continue;\n const TargetClass = meta.target();\n const nestedInclude = typeof includeVal === 'object' && includeVal !== null\n ? includeVal.include\n : undefined;\n const nestedProperties = typeof includeVal === 'object' && includeVal !== null\n ? includeVal.properties\n : undefined;\n const raw = instance[relName];\n if (Array.isArray(raw)) {\n instance[relName] = raw.map((item) => {\n if (typeof item === 'object' && item !== null && item.id) {\n return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);\n }\n return item;\n });\n }\n else if (typeof raw === 'object' && raw !== null && raw.id) {\n instance[relName] = jsonToModelInstance(TargetClass, perspective, raw, nestedInclude, nestedProperties);\n }\n }\n }\n return instance;\n}\n/**\n * Base class for defining data models in AD4M.\n *\n * @description\n * Ad4mModel provides the foundation for creating data models that are stored in AD4M perspectives.\n * Each model instance is represented as a subgraph in the perspective, with properties and relations\n * mapped to links in that graph. The class uses Prolog-based queries to efficiently search and filter\n * instances based on their properties and relationships.\n *\n * Key concepts:\n * - Each model instance has a unique base expression that serves as its identifier\n * - Properties are stored as links with predicates defined by the `through` option\n * - Relations represent one-to-many relationships as sets of links\n * - Queries are translated to Prolog for efficient graph pattern matching\n * - Changes are tracked through the perspective's subscription system\n *\n * @example\n * ```typescript\n * // Define a recipe model\n * @Model({ name: \"Recipe\" })\n * class Recipe extends Ad4mModel {\n * // Required property with literal value\n * @Property({\n * through: \"recipe://name\",\n * resolveLanguage: \"literal\"\n * })\n * name: string = \"\";\n *\n * // Optional property with custom initial value\n * @Optional({\n * through: \"recipe://status\",\n * initial: \"recipe://draft\"\n * })\n * status: string = \"\";\n *\n * // Read-only computed property\n * @ReadOnly({\n * through: \"recipe://rating\",\n * getter: `\n * findall(Rating, triple(Base, \"recipe://user_rating\", Rating), Ratings),\n * sum_list(Ratings, Sum),\n * length(Ratings, Count),\n * Value is Sum / Count\n * `\n * })\n * averageRating: number = 0;\n *\n * // Relation of ingredients\n * @HasMany({ through: \"recipe://ingredient\" })\n * ingredients: string[] = [];\n *\n * // Relation of comments linked to another model\n * @HasMany(() => Comment, { through: \"recipe://comment\" })\n * comments: Comment[] = [];\n * }\n *\n * // Create and save a new recipe\n * const recipe = new Recipe(perspective);\n * recipe.name = \"Chocolate Cake\";\n * recipe.ingredients = [\"flour\", \"sugar\", \"cocoa\"];\n * await recipe.save();\n *\n * // Query recipes in different ways\n * // Get all recipes\n * const allRecipes = await Recipe.findAll(perspective);\n *\n * // Find recipes with specific criteria\n * const desserts = await Recipe.findAll(perspective, {\n * where: {\n * status: \"recipe://published\",\n * averageRating: { gt: 4 }\n * },\n * order: { name: \"ASC\" },\n * limit: 10\n * });\n *\n * // Use the fluent query builder\n * const popularRecipes = await Recipe.query(perspective)\n * .where({ averageRating: { gt: 4.5 } })\n * .order({ averageRating: \"DESC\" })\n * .limit(5)\n * .get();\n *\n * // Subscribe to real-time updates\n * await Recipe.query(perspective)\n * .where({ status: \"recipe://cooking\" })\n * .subscribe(recipes => {\n * console.log(\"Currently being cooked:\", recipes);\n * });\n *\n * // Paginate results\n * const { results, totalCount, pageNumber } = await Recipe.query(perspective)\n * .where({ status: \"recipe://published\" })\n * .paginate(10, 1);\n * ```\n */\nclass Ad4mModel {\n /**\n * Backwards compatibility alias for createdAt.\n * @deprecated Use createdAt instead. This will be removed in a future version.\n */\n get timestamp() {\n return this.createdAt;\n }\n /**\n * Generates the SDNA (Subject DNA) Prolog rules for this model class.\n * Injected at class-definition time by the `@Model` decorator.\n * Returns a default value on un-decorated base classes.\n */\n static generateSDNA() {\n return { sdna: '', name: '' };\n }\n /**\n * Generates the SHACL shape graph for this model class.\n * Injected at class-definition time by the `@Model` decorator.\n * Returns `{ shape: null, name: '' }` on un-decorated base classes \u2014\n * the decorator's `parentSHACL?.shape?.nodeShapeUri` check handles this.\n */\n static generateSHACL() {\n return { shape: null, name: '' };\n }\n static async getClassName(perspective) {\n // Check if this is the Ad4mModel class itself or a subclass\n const isBaseClass = this === Ad4mModel;\n // For the base Ad4mModel class, we can't use the cache\n if (isBaseClass) {\n return await perspective.stringOrTemplateObjectToSubjectClassName(this);\n }\n // Get or create the cache for this class\n let classCache = this.classNamesByClass.get(this);\n if (!classCache) {\n classCache = {};\n this.classNamesByClass.set(this, classCache);\n }\n // Get or create the cached name for this perspective\n const perspectiveID = perspective.uuid;\n if (!classCache[perspectiveID]) {\n classCache[perspectiveID] = await perspective.stringOrTemplateObjectToSubjectClassName(this);\n }\n return classCache[perspectiveID];\n }\n /**\n * Extracts metadata from decorators for query building.\n *\n * @description\n * This method reads the metadata stored by decorators (@Property, @HasMany, etc.)\n * and returns it in a structured format that's easier to work with for query builders\n * and other systems that need to introspect model structure.\n *\n * The metadata includes:\n * - Class name from @Model\n * - Property metadata (predicates, types, constraints, etc.)\n * - Relation metadata (predicates, filters, etc.)\n *\n * For models created via `fromJSONSchema()`, this method will derive metadata from\n * the WeakMap registries that were populated during the dynamic class creation.\n * If these structures are empty but a JSON schema was attached to the class,\n * it can fall back to deriving metadata from that schema.\n *\n * @returns Structured metadata object containing className, properties, and relations\n * @throws Error if the class doesn't have @Model decorator\n *\n * @example\n * ```typescript\n * @Model({ name: \"Recipe\" })\n * class Recipe extends Ad4mModel {\n * @Property({ through: \"recipe://name\", resolveLanguage: \"literal\" })\n * name: string = \"\";\n *\n * @HasMany({ through: \"recipe://ingredient\" })\n * ingredients: string[] = [];\n * }\n *\n * const metadata = Recipe.getModelMetadata();\n * console.log(metadata.className); // \"Recipe\"\n * console.log(metadata.properties.name.predicate); // \"recipe://name\"\n * console.log(metadata.relations.ingredients.predicate); // \"recipe://ingredient\"\n * ```\n */\n static getModelMetadata() {\n // Access the prototype with any type to access decorator-added properties\n const prototype = this.prototype;\n // Validate that the class has @Model decorator\n // The decorator sets prototype.className, so we check for its existence\n if (!prototype.className || prototype.className === 'Ad4mModel') {\n throw new Error(\"Model class must be decorated with @Model\");\n }\n // Extract className\n const className = prototype.className;\n // Extract properties from WeakMap registry\n const propertiesMetadata = {};\n const prototypeProperties = getPropertiesMetadata(this);\n for (const [propertyName, opts] of Object.entries(prototypeProperties)) {\n const options = opts;\n propertiesMetadata[propertyName] = {\n name: propertyName,\n predicate: options.through || \"\",\n required: options.required || false,\n readOnly: !(options.writable ?? false),\n ...(options.initial !== undefined && { initial: options.initial }),\n ...(options.resolveLanguage !== undefined && { resolveLanguage: options.resolveLanguage }),\n ...(options.prologGetter !== undefined && { prologGetter: options.prologGetter }),\n ...(options.getter !== undefined && { getter: options.getter }),\n ...(options.prologSetter !== undefined && { prologSetter: options.prologSetter }),\n ...(options.local !== undefined && { local: options.local }),\n ...(options.transform !== undefined && { transform: options.transform }),\n ...(options.flag !== undefined && { flag: options.flag })\n };\n }\n // Extract relations (relations) from WeakMap registry\n const relationsMetadata = {};\n const allRelationsMeta = getRelationsMetadata(this);\n const prototypeRelations = allRelationsMeta;\n for (const [relationName, opts] of Object.entries(prototypeRelations)) {\n const options = opts;\n relationsMetadata[relationName] = {\n name: relationName,\n predicate: options.predicate || \"\",\n ...(options.local !== undefined && { local: options.local }),\n ...(options.getter !== undefined && { getter: options.getter }),\n direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',\n ...(options.kind !== undefined && { kind: options.kind }),\n ...(options.maxCount !== undefined && { maxCount: options.maxCount }),\n ...(options.target !== undefined && { target: options.target }),\n ...(options.filter !== undefined && { filter: options.filter }),\n ...(options.where !== undefined && { where: options.where }),\n };\n }\n // Fallback: If both structures are empty but a JSON schema is attached, derive from it\n // This handles edge cases where fromJSONSchema() was called but metadata wasn't properly populated\n const hasProperties = Object.keys(propertiesMetadata).length > 0;\n const hasRelations = Object.keys(relationsMetadata).length > 0;\n const hasMetadata = hasProperties || hasRelations;\n if (!hasMetadata && prototype.__jsonSchema) {\n // Derive metadata from the attached JSON schema\n const schema = prototype.__jsonSchema;\n const options = prototype.__jsonSchemaOptions || {};\n if (schema.properties) {\n for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {\n const isArray = isArrayType(propertySchema);\n const predicate = determinePredicate(schema, propertyName, propertySchema, determineNamespace(schema, options), options);\n if (isArray) {\n relationsMetadata[propertyName] = {\n name: propertyName,\n predicate: predicate,\n ...(propertySchema[\"x-ad4m\"]?.local !== undefined && { local: propertySchema[\"x-ad4m\"].local })\n };\n }\n else {\n const isRequired = schema.required?.includes(propertyName) || false;\n propertiesMetadata[propertyName] = {\n name: propertyName,\n predicate: predicate,\n required: isRequired,\n readOnly: propertySchema[\"x-ad4m\"]?.writable === false,\n ...(propertySchema[\"x-ad4m\"]?.resolveLanguage && { resolveLanguage: propertySchema[\"x-ad4m\"].resolveLanguage }),\n ...(propertySchema[\"x-ad4m\"]?.initial && { initial: propertySchema[\"x-ad4m\"].initial }),\n ...(propertySchema[\"x-ad4m\"]?.local !== undefined && { local: propertySchema[\"x-ad4m\"].local })\n };\n }\n }\n }\n }\n return {\n className,\n properties: propertiesMetadata,\n relations: relationsMetadata,\n };\n }\n /**\n * Constructs a new model instance.\n *\n * @param perspective - The perspective where this model will be stored\n * @param baseExpression - Optional expression URI for this instance.\n * If omitted, a random Literal URL is generated.\n * @param source - Optional source expression this instance is linked to\n *\n * @example\n * ```typescript\n * // Create a new recipe with auto-generated base expression\n * const recipe = new Recipe(perspective);\n *\n * // Create with specific base expression\n * const recipe = new Recipe(perspective, \"literal:...\");\n * ```\n */\n constructor(perspective, baseExpression) {\n this._snapshot = null;\n this._baseExpression = baseExpression ? baseExpression : Literal.from(makeRandomId(24)).toUrl();\n this._perspective = perspective;\n }\n /**\n * The unique identifier (expression URI) of this model instance.\n */\n get id() {\n return this._baseExpression;\n }\n /**\n * Protected getter for the perspective.\n * Allows subclasses to access the perspective while keeping it private from external code.\n */\n get perspective() {\n return this._perspective;\n }\n /**\n * Get property metadata from decorator.\n * @private\n */\n getPropertyMetadata(key) {\n const ctor = this.constructor;\n const props = getPropertiesMetadata(ctor);\n return props[key];\n }\n /**\n * Get relation options from decorator\n * @private\n */\n getRelationOptions(key) {\n const ctor = this.constructor;\n const rels = getRelationsMetadata(ctor);\n return rels[key];\n }\n /**\n * Generate property setter action from metadata.\n * @private\n */\n generatePropertySetterAction(key, metadata) {\n // Flags are always immutable \u2014 throw a clear error\n if (metadata.flag) {\n throw new Error(`Property \"${key}\" is a @Flag and cannot be written. ` +\n `Flags are immutable type markers set at creation time.`);\n }\n // Check if property is read-only\n if (metadata.readOnly) {\n throw new Error(`Property \"${key}\" is read-only and cannot be written`);\n }\n if (metadata.prologSetter) {\n // Custom Prolog setter - throw error for now (Phase 2)\n throw new Error(`Custom Prolog setter for property \"${key}\" not yet supported without Prolog. ` +\n `Use standard @Property decorator or enable Prolog for custom setters.`);\n }\n if (!metadata.through) {\n throw new Error(`Property \"${key}\" has no 'through' predicate defined`);\n }\n return [{\n action: \"setSingleTarget\",\n source: \"this\",\n predicate: metadata.through,\n target: \"value\",\n ...(metadata.local && { local: true })\n }];\n }\n /**\n * Generate relation action from metadata.\n * @private\n */\n generateRelationAction(key, actionType) {\n const metadata = this.getRelationOptions(key);\n if (!metadata) {\n throw new Error(`Relation \"${key}\" has no metadata defined`);\n }\n if (!metadata.predicate) {\n throw new Error(`Relation \"${key}\" has no predicate defined`);\n }\n const actionMap = {\n adder: \"addLink\",\n remover: \"removeLink\",\n setter: \"collectionSetter\"\n };\n return [{\n action: actionMap[actionType],\n source: \"this\",\n predicate: metadata.predicate,\n target: \"value\",\n ...(metadata.local && { local: true })\n }];\n }\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Snapshot / dirty tracking\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /**\n * @param includedRelations Controls which relation fields are recorded\n * in the snapshot for dirty-tracking:\n * \u2022 `undefined` (default) \u2014 snapshot ALL relations (used by `.get()`,\n * `.create()`, `.save()` etc. where full hydration has occurred).\n * \u2022 `IncludeMap` object (e.g. `{ views: true }`) \u2014 only snapshot the\n * relations named in the map. Fields not listed are omitted from\n * the snapshot so that `changedFields()` ignores them.\n * \u2022 `null` / empty object \u2014 skip ALL relations (used by bare\n * subscriptions that don't eagerly load relations).\n */\n /** @internal */\n takeSnapshot(includedRelations) {\n const ctor = this.constructor;\n const metadata = ctor.getModelMetadata();\n const snap = {};\n // Always snapshot properties\n for (const propName of Object.keys(metadata.properties)) {\n const val = this[propName];\n snap[propName] = normalizeValue(Array.isArray(val) ? [...val] : val);\n }\n // Snapshot relations only when appropriate:\n // undefined \u2192 all relations (backward compat)\n // IncludeMap \u2192 only the keys present in the map\n // null / {} \u2192 none\n if (includedRelations === undefined) {\n // Full snapshot \u2014 e.g. after getData() / create()\n for (const relName of Object.keys(metadata.relations)) {\n const val = this[relName];\n snap[relName] = normalizeValue(Array.isArray(val) ? [...val] : val);\n }\n }\n else if (includedRelations && Object.keys(includedRelations).length > 0) {\n // Partial snapshot \u2014 only the explicitly included relations\n for (const relName of Object.keys(includedRelations)) {\n if (relName in metadata.relations) {\n const val = this[relName];\n snap[relName] = normalizeValue(Array.isArray(val) ? [...val] : val);\n }\n }\n }\n // else: null or empty object \u2192 skip all relations\n this._snapshot = snap;\n }\n /**\n * Returns `true` if any tracked property or relation has changed\n * since the last hydration (or since `takeSnapshot()` was last called).\n *\n * Always returns `true` if no snapshot exists (e.g. a freshly\n * constructed instance that hasn't been fetched yet).\n *\n * @example\n * ```typescript\n * const recipe = await Recipe.create(perspective, { name: \"Pasta\" });\n * recipe.isDirty(); // false \u2014 just hydrated\n * recipe.name = \"Risotto\";\n * recipe.isDirty(); // true\n * ```\n */\n isDirty() {\n if (!this._snapshot)\n return true;\n return this.changedFields().length > 0;\n }\n /**\n * Returns the names of properties/relations that differ from the\n * snapshot taken at the last hydration.\n *\n * Returns **all** field names if no snapshot exists.\n *\n * @example\n * ```typescript\n * recipe.name = \"New Name\";\n * recipe.changedFields(); // [\"name\"]\n * ```\n */\n changedFields() {\n const ctor = this.constructor;\n const metadata = ctor.getModelMetadata();\n if (!this._snapshot) {\n return [\n ...Object.keys(metadata.properties),\n ...Object.keys(metadata.relations),\n ];\n }\n const changed = [];\n const allFields = [\n ...Object.keys(metadata.properties),\n ...Object.keys(metadata.relations),\n ];\n for (const field of allFields) {\n // Skip fields that were not recorded in the snapshot (e.g. relation\n // fields omitted because the originating query had no `include`).\n // Without this guard, a relation populated by hydrateFromLinks with\n // raw string IDs would appear \"dirty\" against a missing snapshot\n // entry and trigger an unnecessary (and potentially destructive)\n // setRelationValues call during innerUpdate.\n if (!(field in this._snapshot))\n continue;\n const current = normalizeValue(this[field]);\n const original = this._snapshot[field];\n if (Array.isArray(current) || Array.isArray(original)) {\n // Order-insensitive comparison (sorted) so reordering alone\n // doesn't mark a relation as dirty.\n const a = Array.isArray(current) ? [...current].sort() : [];\n const b = Array.isArray(original) ? [...original].sort() : [];\n if (a.length !== b.length || a.some((v, i) => v !== b[i])) {\n changed.push(field);\n }\n }\n else if (current !== original) {\n changed.push(field);\n }\n }\n return changed;\n }\n async getData(opts) {\n // Route through the Rust model query endpoint \u2014 same pipeline as executeModelQuery\n // but for a single instance by ID.\n try {\n const ctor = this.constructor;\n const query = {\n where: { id: this._baseExpression },\n limit: 1,\n deepQuery: true, // Single-instance get() always evaluates property getters\n };\n if (opts?.properties)\n query.properties = opts.properties;\n if (opts?.include)\n query.include = opts.include;\n const { results } = await ctor.executeModelQuery(this._perspective, query, null);\n if (results.length > 0) {\n const hydrated = results[0];\n // Copy all hydrated values from the Rust-side result onto this instance\n for (const [key, value] of Object.entries(hydrated)) {\n if (key === '_baseExpression' || key === '_perspective' || key === '_snapshot')\n continue;\n if (key.startsWith('_'))\n continue;\n // Check for readonly getters\n let isReadonly = false;\n let proto = Object.getPrototypeOf(this);\n while (proto) {\n const desc = Object.getOwnPropertyDescriptor(proto, key);\n if (desc) {\n isReadonly = !!(desc.get && !desc.set);\n break;\n }\n proto = Object.getPrototypeOf(proto);\n }\n if (isReadonly)\n continue;\n this[key] = value;\n }\n }\n // Property getters and relation conformance getters are now evaluated\n // Rust-side via evaluate_getters() in model_query.rs.\n }\n catch (e) {\n console.error(`getData via Rust model query failed for ${this._baseExpression}:`, e);\n }\n this.takeSnapshot(opts?.include);\n return this;\n }\n /**\n * Generates a SPARQL query from a Query object.\n *\n * @description\n * This method translates high-level query parameters into a SPARQL query string\n * that can be executed against the SPARQL backend. Unlike Prolog queries which\n * operate on SDNA-aware predicates, SPARQL queries operate directly on raw links\n * stored in SPARQL.\n *\n * The generated query uses a CTE (Common Table Expression) pattern:\n * 1. First, identify candidate base expressions by filtering links based on where conditions\n * 2. Then, for each candidate base, resolve properties and relations via subqueries\n * 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level\n *\n * Key architectural notes:\n * - SPARQL stores only raw links (source, predicate, target, author, timestamp)\n * - No SDNA knowledge at the database level\n * - Properties are resolved via subqueries that look for links with specific predicates\n * - Relations are similar but return multiple values instead of one\n * - Special fields (base, author, timestamp) are accessed directly, not via subqueries\n *\n * @param perspective - The perspective to query (used for metadata extraction)\n * @param query - Query parameters (where, order, limit, offset, properties, relations)\n * @returns Complete SPARQL query string ready for execution\n *\n * @example\n * ```typescript\n * const query = Recipe.queryToSPARQL(perspective, {\n * where: { name: \"Pasta\", rating: { gt: 4 } },\n * order: { timestamp: \"DESC\" },\n * limit: 10\n * });\n * // Returns: SELECT source AS base, array::first(target[WHERE predicate = ...]) AS name, ...\n * // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10\n * ```\n */\n static async queryToSPARQL(perspective, query) {\n const metadata = this.getModelMetadata();\n const allRelMeta = getRelationsMetadata(this);\n return buildSPARQLQuery(metadata, allRelMeta, query, this);\n }\n /**\n * Build the JSON parameters needed for a model query/subscription endpoint.\n * Returns the className, queryJson, and shapeJson that the Rust executor expects.\n * @internal\n */\n static prepareModelQueryParams(query = {}, classNameOverride) {\n const metadata = this.getModelMetadata();\n const className = classNameOverride || metadata.className;\n // Expand includeAll: true to a full IncludeMap covering every forward relation.\n if (query.includeAll) {\n const allRelMeta = getRelationsMetadata(this);\n const expanded = {};\n for (const [relName, relMeta] of Object.entries(allRelMeta)) {\n if (relMeta.direction !== 'reverse') {\n expanded[relName] = true;\n }\n }\n query = { ...query, include: { ...expanded, ...query.include } };\n }\n const queryInput = {};\n if (query.parent) {\n const parentPredicate = resolveParentPredicate(query.parent, this);\n queryInput.parent = { id: query.parent.id, predicate: parentPredicate };\n }\n if (query.properties)\n queryInput.properties = query.properties;\n if (query.include) {\n // Split include keys: $-prefixed / IncludeProjection values \u2192 queryInput.projections\n // All other keys (boolean | RelationSubQuery) \u2192 queryInput.include\n const normalIncludes = {};\n const projections = {};\n for (const [key, val] of Object.entries(query.include)) {\n if (key.startsWith('$')) {\n projections[key] = val;\n }\n else {\n normalIncludes[key] = val;\n }\n }\n if (Object.keys(normalIncludes).length > 0)\n queryInput.include = normalIncludes;\n if (Object.keys(projections).length > 0) {\n // Enrich projections with target shapes so Rust can apply where clause filtering\n const allRelMeta = getRelationsMetadata(this);\n for (const [, proj] of Object.entries(projections)) {\n const relMeta = allRelMeta[proj.from];\n if (!proj.targetShape && relMeta?.target) {\n try {\n const TargetClass = relMeta.target();\n const targetMeta = TargetClass.getModelMetadata?.();\n if (targetMeta) {\n proj.targetShape = targetMeta;\n }\n }\n catch (e) {\n console.debug(`prepareModelQueryParams: target class unavailable for projection:`, e);\n }\n }\n }\n queryInput.projections = projections;\n }\n }\n if (query.where)\n queryInput.where = query.where;\n if (query.order) {\n queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);\n }\n if (query.offset !== undefined)\n queryInput.offset = query.offset;\n if (query.limit !== undefined)\n queryInput.limit = query.limit;\n if (query.count !== undefined)\n queryInput.count = query.count;\n queryInput.deepQuery = query.deepQuery ?? true;\n if (queryInput.include) {\n const allRelMeta = getRelationsMetadata(this);\n enrichShapeForIncludes(metadata, queryInput.include, allRelMeta);\n }\n // Pre-compute conformance getters for Rust-side evaluation.\n // Where clauses are NOT compiled into getter SPARQL because stored\n // property values are signed expression envelopes (literal:json:...),\n // not simple literal:string:X values. Instead, where clauses are\n // attached as metadata for Rust-side post-evaluation filtering.\n {\n const allRelMeta = getRelationsMetadata(this);\n for (const [relName, relMeta] of Object.entries(metadata.relations)) {\n const rel = relMeta;\n if (rel.getter || rel.direction === 'reverse' || rel.filter === false)\n continue;\n const meta = allRelMeta[relName];\n if (!meta?.target)\n continue;\n try {\n const TargetClass = meta.target();\n const filter = buildConformanceFilter(meta.predicate, TargetClass);\n if (filter) {\n rel.getter = filter.getter;\n }\n // Attach where-clause metadata for Rust-side post-getter filtering\n if (rel.where) {\n try {\n const targetMetadata = TargetClass.getModelMetadata?.() ?? null;\n if (targetMetadata) {\n const predicates = {};\n for (const propName of Object.keys(rel.where)) {\n if (['id', 'author', 'timestamp'].includes(propName))\n continue;\n const propMeta = targetMetadata.properties[propName];\n if (propMeta?.predicate) {\n predicates[propName] = propMeta.predicate;\n }\n }\n if (Object.keys(predicates).length > 0) {\n rel.whereFilter = rel.where;\n rel.wherePredicates = predicates;\n }\n }\n }\n catch (e) {\n console.debug(`prepareModelQueryParams: target metadata unavailable for relation '${relName}':`, e);\n }\n }\n }\n catch (e) {\n console.debug(`prepareModelQueryParams: target class unavailable for relation '${relName}':`, e);\n }\n }\n }\n return {\n className,\n queryJson: JSON.stringify(queryInput),\n shapeJson: JSON.stringify(metadata),\n metadata,\n };\n }\n /**\n * Parse raw model query/subscription result JSON into typed model instances.\n * Used by ModelQueryBuilder to convert subscription updates without circular imports.\n * @internal\n */\n static parseModelResult(perspective, raw, include, properties) {\n const data = typeof raw === 'string' ? JSON.parse(raw) : raw;\n const arr = data.instances || data;\n if (!Array.isArray(arr))\n return [];\n return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));\n }\n /**\n * Resolve non-literal (file-language) properties on an array of already-constructed\n * model instances. Handles two cases:\n *\n * 1. The Rust executor returned a raw URI string \u2192 fetch via `getExpression` then apply transform.\n * 2. The Rust executor already resolved the expression and returned a `FileData` object\n * (happens when the perspective backend eagerly fetches file content) \u2192 apply transform\n * (or `defaultFileDecode` if no transform is registered on the class, e.g. for SHACL-\n * synthesised model classes).\n *\n * Extracted as a public static so `ModelQueryBuilder.subscribe()` can reuse it without\n * duplicating logic or introducing a circular dependency.\n * @internal\n */\n static async resolveNonLiteralProps(perspective, instances) {\n const propsMeta = getPropertiesMetadata(this);\n const resolveProps = Object.entries(propsMeta).filter(([, opts]) => opts.resolveLanguage != null &&\n opts.resolveLanguage !== 'literal');\n if (resolveProps.length === 0)\n return;\n await Promise.all(instances.map(async (inst) => {\n for (const [propName, opts] of resolveProps) {\n const val = inst[propName];\n const transform = opts.transform;\n const applyTransform = (resolved) => typeof transform === 'function' ? transform(resolved) : defaultFileDecode(resolved);\n if (typeof val === 'string' && val && !val.startsWith('literal:')) {\n // Case 1: raw URI \u2014 fetch from language runtime\n try {\n const expression = await perspective.getExpression(val);\n if (expression) {\n let resolved;\n try {\n resolved = JSON.parse(expression.data);\n }\n catch {\n resolved = expression.data;\n }\n inst[propName] = applyTransform(resolved);\n }\n }\n catch (e) {\n console.debug(`resolveNonLiteralProps: resolution failed for '${propName}':`, e);\n }\n }\n else if (val !== null && val !== undefined && typeof val === 'object') {\n // Case 2: already resolved by Rust \u2014 apply transform / default decode\n inst[propName] = applyTransform(val);\n }\n }\n }));\n }\n // instancesFromQueryResult \u2014 removed (superseded by Rust executeModelQuery pipeline)\n /**\n * Execute a model query via the executor-side endpoint.\n *\n * This replaces the old SPARQL-build \u2192 hydrate \u2192 JS-filter \u2192 JS-sort \u2192 JS-paginate pipeline\n * with a single RPC to the executor that handles everything in Rust.\n *\n * @internal\n */\n static async executeModelQuery(perspective, query = {}, classNameOverride) {\n // Delegate all query input building, shape enrichment, and getter\n // pre-computation to the shared prepareModelQueryParams helper.\n const { className, queryJson, shapeJson } = this.prepareModelQueryParams(query, classNameOverride);\n const result = await perspective.modelQuery(className, queryJson, shapeJson);\n // Convert JSON instances to model class instances, recursively constructing\n // class instances for any included relations resolved by Rust.\n const instances = result.instances.map((json) => {\n return jsonToModelInstance(this, perspective, json, query.include, query.properties);\n });\n // Resolve non-literal expressions (e.g. file languages where the stored\n // value is a content-addressed hash that must be fetched from the language\n // runtime). The Rust endpoint may return either a raw target URI (string)\n // or an already-resolved FileData object \u2014 both cases are handled here.\n await this.resolveNonLiteralProps(perspective, instances);\n // Take snapshots for dirty tracking (exclude $-prefixed projection keys)\n const snapshotRelations = query.include\n ? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))\n : undefined;\n for (const inst of instances) {\n inst.takeSnapshot(snapshotRelations && Object.keys(snapshotRelations).length > 0 ? snapshotRelations : undefined);\n }\n return {\n results: instances,\n totalCount: result.totalCount,\n };\n }\n /**\n * Gets all instances of the model in the perspective that match the query params.\n *\n * @param perspective - The perspective to search in\n * @param query - Optional query parameters to filter results\n * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.\n * All queries now use the Rust SPARQL pipeline.\n * @returns Array of matching models\n *\n * @example\n * ```typescript\n * const allRecipes = await Recipe.findAll(perspective);\n *\n * const recipes = await Recipe.findAll(perspective, {\n * where: {\n * name: \"Pasta\",\n * rating: { gt: 4 }\n * },\n * order: { createdAt: \"DESC\" },\n * limit: 10\n * });\n * ```\n */\n static async findAll(perspective, query = {}, \n /** @deprecated Ignored \u2014 Prolog engine has been removed. */\n _engine) {\n if (query.properties && query.properties.length === 0) {\n throw new Error(\"properties[] must not be empty \u2014 omit the field to return all properties, or specify at least one field name\");\n }\n const { results } = await this.executeModelQuery(perspective, query);\n return results;\n }\n /**\n * Finds the first instance matching the query, or `null` if none exists.\n *\n * Equivalent to `findAll` with `limit: 1` \u2014 only one instance is hydrated.\n *\n * @param perspective - The perspective to search in\n * @param query - Optional query parameters to filter results\n * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.\n * @returns The first matching instance, or `null`\n *\n * @example\n * ```typescript\n * const recipe = await Recipe.findOne(perspective, {\n * where: { name: \"Pasta\" }\n * });\n * if (recipe) {\n * console.log(recipe.name);\n * }\n * ```\n */\n static async findOne(perspective, query = {}, \n /** @deprecated Ignored \u2014 Prolog engine has been removed. */\n _engine) {\n const limitedQuery = { ...query, limit: 1 };\n const results = await this.findAll(perspective, limitedQuery);\n return results[0] ?? null;\n }\n /**\n * Gets all instances with count of total matches without offset & limit applied.\n *\n * @param perspective - The perspective to search in\n * @param query - Optional query parameters to filter results\n * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.\n * @returns Object containing results array and total count\n *\n * @example\n * ```typescript\n * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {\n * where: { category: \"Dessert\" },\n * limit: 10\n * });\n * console.log(`Showing 10 of ${totalCount} dessert recipes`);\n * ```\n */\n static async findAllAndCount(perspective, query = {}, \n /** @deprecated Ignored \u2014 Prolog engine has been removed. */\n _engine) {\n return await this.executeModelQuery(perspective, query);\n }\n /**\n * Helper function for pagination with explicit page size and number.\n *\n * @param perspective - The perspective to search in\n * @param pageSize - Number of items per page\n * @param pageNumber - Which page to retrieve (1-based)\n * @param query - Optional additional query parameters\n * @returns Paginated results with metadata\n *\n * @example\n * ```typescript\n * const page = await Recipe.paginate(perspective, 10, 1, {\n * where: { category: \"Main Course\" }\n * });\n * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);\n * ```\n */\n static async paginate(perspective, pageSize, pageNumber, query, \n /** @deprecated Ignored \u2014 Prolog engine has been removed. */\n _engine) {\n const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };\n const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);\n return { results, totalCount, pageSize, pageNumber };\n }\n /**\n * Generates a SPARQL COUNT query for the model.\n *\n * @param perspective - The perspective context\n * @param query - Query parameters to filter the count\n * @returns SPARQL COUNT query string\n *\n * @private\n */\n // countQueryToSPARQL \u2014 removed (zero callers; Rust COUNT fast-path supersedes)\n /**\n * Gets a count of all matching instances.\n *\n * @param perspective - The perspective to search in\n * @param query - Optional query parameters to filter results\n * @returns Total count of matching entities\n *\n * @example\n * ```typescript\n * const totalRecipes = await Recipe.count(perspective);\n * const activeRecipes = await Recipe.count(perspective, {\n * where: { status: \"active\" }\n * });\n * ```\n */\n static async count(perspective, query = {}) {\n const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });\n return totalCount;\n }\n async setProperty(key, value, batchId) {\n const metadata = this.getPropertyMetadata(key);\n if (!metadata) {\n console.warn(`Property \"${key}\" has no metadata, skipping`);\n return;\n }\n // Generate actions from metadata (replaces Prolog query)\n const actions = this.generatePropertySetterAction(key, metadata);\n // Get resolve language from metadata (replaces Prolog query)\n let resolveLanguage = metadata.resolveLanguage;\n // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)\n if (value === undefined || value === null || value === \"\") {\n return;\n }\n if (resolveLanguage) {\n value = await this._perspective.createExpression(value, resolveLanguage);\n }\n await this._perspective.executeAction(actions, this._baseExpression, [{ name: \"value\", value }], batchId);\n }\n /** Resolve a relation argument to a plain string ID. Accepts either a raw\n * string ID or an Ad4mModel instance (in which case `.id` is used). */\n resolveRelationId(value) {\n if (typeof value === 'string')\n return value;\n if (value && typeof value === 'object' && typeof value.id === 'string')\n return value.id;\n return String(value);\n }\n async setRelationValues(key, value, batchId) {\n const metadata = this.getRelationOptions(key);\n if (!metadata) {\n console.warn(`Relation \"${key}\" has no metadata, skipping`);\n return;\n }\n // Generate actions from metadata (replaces Prolog query)\n const actions = this.generateRelationAction(key, 'setter');\n if (value != null) {\n if (Array.isArray(value)) {\n await this._perspective.executeAction(actions, this._baseExpression, value.map((v) => ({ name: \"value\", value: this.resolveRelationId(v) })), batchId);\n }\n else {\n await this._perspective.executeAction(actions, this._baseExpression, [{ name: \"value\", value: this.resolveRelationId(value) }], batchId);\n }\n }\n }\n async addRelationValue(key, value, batchId) {\n const metadata = this.getRelationOptions(key);\n if (!metadata) {\n console.warn(`Relation \"${key}\" has no metadata, skipping`);\n return;\n }\n // Generate actions from metadata (replaces Prolog query)\n const actions = this.generateRelationAction(key, 'adder');\n if (value != null) {\n if (Array.isArray(value)) {\n await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [{ name: \"value\", value: this.resolveRelationId(v) }], batchId)));\n }\n else {\n await this._perspective.executeAction(actions, this._baseExpression, [{ name: \"value\", value: this.resolveRelationId(value) }], batchId);\n }\n }\n }\n async removeRelationValue(key, value, batchId) {\n const metadata = this.getRelationOptions(key);\n if (!metadata) {\n console.warn(`Relation \"${key}\" has no metadata, skipping`);\n return;\n }\n // Generate actions from metadata (replaces Prolog query)\n const actions = this.generateRelationAction(key, 'remover');\n if (value != null) {\n if (Array.isArray(value)) {\n await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [{ name: \"value\", value: this.resolveRelationId(v) }], batchId)));\n }\n else {\n await this._perspective.executeAction(actions, this._baseExpression, [{ name: \"value\", value: this.resolveRelationId(value) }], batchId);\n }\n }\n }\n /**\n * Saves the model instance to the perspective.\n *\n * **New instances** (no snapshot yet): creates the subject via\n * `createSubject` with initial scalar values, then sets relations\n * via `innerUpdate`.\n *\n * **Existing instances** (snapshot present, i.e. fetched via `get()`\n * or a query): updates only dirty fields via `innerUpdate`, then\n * refreshes from the perspective.\n *\n * @param batchId - Optional batch ID for batch operations\n * @throws Will throw if instance creation, linking, or updating fails\n *\n * @example\n * ```typescript\n * // Create\n * const recipe = new Recipe(perspective);\n * recipe.name = \"Spaghetti\";\n * await recipe.save();\n *\n * // Update\n * recipe.rating = 10;\n * await recipe.save();\n * ```\n */\n async save(batchId) {\n // Existing instance \u2192 update path (has been fetched / hydrated before)\n if (this._snapshot) {\n await this.innerUpdate(true, batchId);\n if (batchId) {\n // Batch hasn't been committed yet \u2014 getData() would fetch stale data\n // and overwrite in-memory values. Just refresh the snapshot so further\n // saves within the same batch diff correctly.\n this.takeSnapshot();\n }\n else {\n await this.getData();\n }\n return;\n }\n // New instance \u2192 create path\n let batchCreatedHere = false;\n if (!batchId) {\n batchId = await this.perspective.createBatch();\n batchCreatedHere = true;\n }\n // Check if the model has any constructor actions (required properties,\n // flags, or properties with initial values). Models whose properties are\n // all optional, have no @Flag, and have no initial values produce an empty\n // SHACL constructor, so calling createSubject would fail on the Rust side\n // (\"No SHACL constructor found\"). In that case we skip createSubject\n // entirely and let innerUpdate write the links directly.\n const metadata = this.constructor.getModelMetadata();\n const hasConstructor = Object.values(metadata.properties).some((p) => p.required || p.flag || p.initial !== undefined);\n // Track properties that have resolveLanguage (non-literal) so they can be\n // set via setProperty after createSubject (which doesn't resolve languages).\n const deferredResolveLanguageProps = [];\n if (hasConstructor) {\n // First filter out the properties that are not relations (arrays)\n const initialValues = {};\n for (const [key, value] of Object.entries(this)) {\n if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {\n // Check if this property requires language resolution (e.g. file storage).\n // If so, resolve the expression *before* passing to createSubject so\n // the constructor receives a valid URI instead of raw data.\n const propMeta = metadata.properties[key];\n if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal' && typeof value === 'object') {\n // Defer these properties \u2014 they need createExpression which may\n // fail inside a batch context on some languages. We'll set them\n // via setProperty after createSubject.\n deferredResolveLanguageProps.push(key);\n continue;\n }\n initialValues[key] = value;\n }\n }\n // Get the class name instead of passing the instance to avoid Prolog query generation\n const className = await this.perspective.stringOrTemplateObjectToSubjectClassName(this);\n // Create the subject with the initial values\n await this.perspective.createSubject(className, this._baseExpression, initialValues, batchId);\n }\n // Set properties and relations via innerUpdate.\n // When createSubject was skipped (no constructor actions), we must enable\n // property writing so that scalar values are persisted as links.\n await this.innerUpdate(!hasConstructor, batchId);\n // Now handle any deferred resolveLanguage properties that were excluded\n // from initialValues. setProperty will call createExpression to upload\n // the data to the appropriate language and store the resulting URI.\n for (const key of deferredResolveLanguageProps) {\n const value = this[key];\n if (value !== undefined && value !== null) {\n await this.setProperty(key, value, batchId);\n }\n }\n // If we got a batchId passed in, we let the caller decide when to commit.\n // We can't call getData() since the instance won't exist in the perspective\n // until the batch is committed.\n if (batchCreatedHere) {\n await this.perspective.commitBatch(batchId);\n await this.getData();\n }\n else {\n // Take a snapshot so that a subsequent save() within the same batch\n // routes through the UPDATE path instead of CREATE, avoiding duplicate\n // links (e.g. two competing \"title\" values).\n this.takeSnapshot();\n }\n }\n cleanCopy() {\n const ctor = this.constructor;\n const metadata = ctor.getModelMetadata();\n const cleanCopy = {};\n // Only include schema-declared fields (properties + relations),\n // preserving internal ORM machinery (_id, _perspective, generated\n // addX/removeX/setX methods, _snapshot, etc.)\n const schemaFields = new Set([\n ...Object.keys(metadata.properties),\n ...Object.keys(metadata.relations),\n ]);\n for (const key of schemaFields) {\n const value = this[key];\n if (value !== undefined && value !== null && key !== \"author\" && key !== \"timestamp\") {\n cleanCopy[key] = value;\n }\n }\n return cleanCopy;\n }\n async innerUpdate(setProperties = true, batchId) {\n const ctor = this.constructor;\n // Determine which fields actually changed (skip unchanged when snapshot exists)\n const dirty = this._snapshot ? new Set(this.changedFields()) : null;\n // Only iterate schema-declared fields, not internal ORM properties\n const metadata = ctor.getModelMetadata();\n const schemaFields = new Set([\n ...Object.keys(metadata.properties),\n ...Object.keys(metadata.relations),\n ]);\n const entries = Object.entries(this);\n for (const [key, value] of entries) {\n // Only process schema-declared fields\n if (!schemaFields.has(key))\n continue;\n // Skip unchanged fields when a snapshot is available\n if (dirty && !dirty.has(key))\n continue;\n // Skip read-only computed relations \u2014 explicit getters never write links.\n // For target+filter relations, skip only when another relation on this\n // model claims the same predicate (i.e., this is a filtered *view* of a\n // base relation and writing would collide).\n const relMeta = metadata.relations[key];\n if (relMeta) {\n if (relMeta.getter)\n continue;\n if (relMeta.target && relMeta.filter !== false) {\n // Check for predicate collision with a sibling relation\n const hasCollision = Object.entries(metadata.relations).some(([otherName, otherMeta]) => otherName !== key &&\n otherMeta.predicate === relMeta.predicate);\n if (hasCollision)\n continue;\n }\n }\n if (value !== undefined && value !== null) {\n if (value?.action) {\n switch (value.action) {\n case \"setter\":\n await this.setRelationValues(key, value.value, batchId);\n break;\n case \"adder\":\n await this.addRelationValue(key, value.value, batchId);\n break;\n case \"remover\":\n await this.removeRelationValue(key, value.value, batchId);\n break;\n default:\n await this.setRelationValues(key, value.value, batchId);\n break;\n }\n }\n else if (Array.isArray(value)) {\n // Handle all arrays as relations, including empty ones (which clears the relation)\n await this.setRelationValues(key, value, batchId);\n }\n else if (value !== undefined && value !== null && value !== \"\") {\n if (setProperties) {\n // Check if this is a relation property (has relation metadata)\n const relationMeta = this.getRelationOptions(key);\n if (relationMeta) {\n // Skip - it's a relation, not a regular property\n continue;\n }\n // Skip flag properties \u2014 they are immutable after creation\n const propMeta = this.getPropertyMetadata(key);\n if (propMeta?.flag) {\n continue;\n }\n await this.setProperty(key, value, batchId);\n }\n }\n }\n }\n }\n /**\n * Evaluate SPARQL getters for a batch of instances on demand.\n *\n * Since deepQuery defaults to true, property getters are evaluated\n * automatically during collection queries. Use this method when\n * deepQuery was explicitly set to false and you want to lazily\n * resolve getter-backed properties for a subset of instances.\n *\n * @param instances - Array of model instances to evaluate getters on\n * @param perspective - The perspective to query against\n * @param propertyNames - Optional list of getter-backed property names to evaluate.\n * If omitted, all getters are evaluated.\n *\n * @example\n * ```typescript\n * const messages = await Message.query(perspective).deepQuery(false).limit(30).get();\n * // messages[i].replyingTo is undefined (getter skipped)\n *\n * // Evaluate getters for the visible subset\n * await Message.evaluateGetters(messages.slice(0, 10), perspective, ['replyingTo']);\n * // messages[0..9].replyingTo is now populated\n * ```\n */\n static async evaluateGetters(instances, perspective, propertyNames) {\n if (instances.length === 0)\n return;\n const metadata = this.getModelMetadata();\n // Pre-compute conformance getters so the shape sent to Rust includes them\n const allRelMeta = getRelationsMetadata(this);\n for (const [relName, relMeta] of Object.entries(metadata.relations)) {\n const rel = relMeta;\n if (rel.getter || rel.direction === 'reverse' || rel.filter === false)\n continue;\n const meta = allRelMeta[relName];\n if (!meta?.target)\n continue;\n try {\n const TargetClass = meta.target();\n const filter = buildConformanceFilter(meta.predicate, TargetClass);\n if (filter)\n rel.getter = filter.getter;\n }\n catch (e) {\n console.debug(`evaluateGetters: target class unavailable for relation '${relName}':`, e);\n }\n }\n const shapeJson = JSON.stringify(metadata);\n const instanceIds = instances.map(inst => inst.id || inst._baseExpression);\n // Single RPC call evaluates all getters in-process on the executor\n const result = await perspective.evaluateGetters(metadata.className, instanceIds, shapeJson, propertyNames);\n // Determine which property names were evaluated for snapshot sync\n const evaluatedPropertyNames = [];\n for (const [propName, propMeta] of Object.entries(metadata.properties)) {\n if (propMeta.getter) {\n if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(propName)) {\n evaluatedPropertyNames.push(propName);\n }\n }\n }\n // Also include relation getters\n for (const [relName, relMeta] of Object.entries(metadata.relations)) {\n if (relMeta.getter) {\n if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(relName)) {\n evaluatedPropertyNames.push(relName);\n }\n }\n }\n // Apply results to instances and sync snapshots\n for (const instance of instances) {\n const id = instance.id || instance._baseExpression;\n const props = result[id];\n if (props) {\n for (const [key, value] of Object.entries(props)) {\n instance[key] = value;\n }\n }\n // Sync snapshot so isDirty() doesn't flag getter-only changes\n const modelInstance = instance;\n if (modelInstance._snapshot) {\n for (const propName of evaluatedPropertyNames) {\n const val = instance[propName];\n modelInstance._snapshot[propName] = normalizeValue(Array.isArray(val) ? [...val] : val);\n }\n }\n }\n }\n /**\n * Gets the model instance with all properties and relations populated.\n *\n * @param optsOrInclude - Optional hydration options. Accepts two forms:\n * - `GetOptions` wrapper: `{ include: { comments: true }, properties: ['title'] }`\n * - `IncludeMap` shorthand: `{ comments: true }` (equivalent to `{ include: { comments: true } }`)\n * @returns The populated model instance\n * @throws Will throw if data retrieval fails\n *\n * @example\n * ```typescript\n * const recipe = new Recipe(perspective, existingId);\n * await recipe.get();\n * console.log(recipe.name, recipe.ingredients);\n *\n * // Shorthand \u2014 pass IncludeMap directly:\n * await recipe.get({ ingredients: true });\n *\n * // Full options \u2014 includes sparse fieldset:\n * await recipe.get({ include: { ingredients: true }, properties: ['name'] });\n * ```\n */\n async get(optsOrInclude) {\n // Normalise: if the caller passed a plain IncludeMap shorthand (no `include`\n // or `properties` key at the top level) wrap it in GetOptions automatically.\n let opts;\n if (!optsOrInclude) {\n opts = undefined;\n }\n else if ('include' in optsOrInclude || 'properties' in optsOrInclude) {\n opts = optsOrInclude;\n }\n else {\n opts = { include: optsOrInclude };\n }\n return await this.getData(opts);\n }\n /**\n * Deletes the model instance from the perspective.\n *\n * @param batchId - Optional batch ID for batch operations\n * @throws Will throw if removal fails\n *\n * @example\n * ```typescript\n * const recipe = await Recipe.findAll(perspective)[0];\n * await recipe.delete();\n *\n * // Or with batch operations:\n * const batchId = await perspective.createBatch();\n * await recipe.delete(batchId);\n * await perspective.commitBatch(batchId);\n * ```\n */\n async delete(batchId) {\n const metadata = this.constructor.getModelMetadata();\n const hasDestructor = Object.values(metadata.properties).some((p) => p.required || p.flag || p.initial !== undefined);\n if (hasDestructor) {\n // Remove the subject itself (destructor actions)\n await this._perspective.removeSubject(this, this._baseExpression, batchId);\n }\n else {\n // No destructor (all-optional model).\n // SAFETY: We must NOT remove all outgoing links because another model\n // class may be instantiated on the same base expression. Removing\n // everything would silently destroy that other instance's data \u2014 and\n // if that instance has a destructor, it can no longer be called\n // cleanly, leaving link debris.\n //\n // Instead we only remove outgoing links whose predicate is declared\n // by THIS model's schema (properties + relations).\n try {\n const knownPredicates = new Set();\n for (const p of Object.values(metadata.properties)) {\n if (p.predicate)\n knownPredicates.add(p.predicate);\n }\n for (const r of Object.values(metadata.relations)) {\n if (r.predicate)\n knownPredicates.add(r.predicate);\n }\n const outgoingLinks = await this._perspective.get(new LinkQuery({ source: this._baseExpression }));\n const ownLinks = outgoingLinks.filter((link) => link.data.predicate && knownPredicates.has(link.data.predicate));\n if (ownLinks.length > 0) {\n await this._perspective.removeLinks(ownLinks, batchId);\n }\n }\n catch (e) {\n console.warn(`delete(): failed to remove outgoing links for ${this._baseExpression}:`, e);\n }\n }\n // Clean up incoming links \u2014 remove any links that point **to** this instance.\n // Unlike outgoing links (scoped above), incoming links originate from OTHER\n // nodes. Removing them doesn't damage sibling models on this node; it\n // prevents dangling references elsewhere (e.g. a parent's has_child link).\n try {\n const incomingLinks = await this._perspective.get(new LinkQuery({ target: this._baseExpression }));\n if (incomingLinks.length > 0) {\n await this._perspective.removeLinks(incomingLinks, batchId);\n }\n }\n catch (e) {\n // Non-fatal: the subject was already deleted; incoming link cleanup is best-effort\n console.warn(`delete(): failed to clean up incoming links for ${this._baseExpression}:`, e);\n }\n }\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Static convenience methods\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /**\n * Creates and saves a new model instance in one step.\n *\n * @param perspective - The perspective to create the instance in\n * @param data - Property values to assign before saving\n * @param options - Optional settings:\n * - `parent` \u2014 a `ParentScope` (model form or raw form) whose `id` will\n * be used to create an incoming link from the parent to the new instance.\n * - `batchId` \u2014 an existing batch id; when provided the link write and\n * `save()` are added to the batch instead of committed immediately.\n * @returns The saved model instance\n *\n * @example\n * ```typescript\n * // Simple create\n * const recipe = await Recipe.create(perspective, {\n * name: \"Spaghetti\",\n * rating: 5,\n * });\n *\n * // Create under a parent (link auto-created)\n * const comment = await Comment.create(perspective, { text: \"Great!\" }, {\n * parent: { model: Post, id: postId },\n * });\n *\n * // Create inside a transaction\n * await Ad4mModel.transaction(perspective, async (tx) => {\n * await Recipe.create(perspective, { name: \"Pasta\" }, { batchId: tx.batchId });\n * });\n * ```\n */\n static async create(perspective, data = {}, options) {\n const instance = new this(perspective);\n Object.assign(instance, data);\n // When a parent scope is provided without a caller-supplied batch, open a\n // new batch ourselves so that the instance creation and the parent\u2192child\n // link are committed atomically. If either step throws, commitBatch is\n // never reached and the batch is implicitly abandoned (rollback).\n if (options?.parent && !options?.batchId) {\n const batchId = await perspective.createBatch();\n await instance.save(batchId);\n const predicate = resolveParentPredicate(options.parent, this);\n const link = new Link({\n source: options.parent.id,\n predicate,\n target: instance.id,\n });\n await perspective.add(link, 'shared', batchId);\n await perspective.commitBatch(batchId);\n // Hydrate the instance now that the batch has been committed (mirrors the\n // behaviour of save() when it manages its own batch).\n await instance.get();\n return instance;\n }\n await instance.save(options?.batchId);\n // Create parent \u2192 child link if a parent scope was provided\n if (options?.parent) {\n const predicate = resolveParentPredicate(options.parent, this);\n const link = new Link({\n source: options.parent.id,\n predicate,\n target: instance.id,\n });\n await perspective.add(link, 'shared', options?.batchId);\n }\n return instance;\n }\n /**\n * Updates an existing model instance identified by `id`.\n *\n * Fetches the instance, applies the provided changes, calls `save()`,\n * and returns the refreshed instance.\n *\n * @param perspective - The perspective containing the instance\n * @param id - The expression URI of the instance to update\n * @param data - Property values to merge before saving\n * @returns The updated model instance\n *\n * @example\n * ```typescript\n * const recipe = await Recipe.update(perspective, recipeId, {\n * rating: 10,\n * });\n * ```\n */\n static async update(perspective, id, data) {\n const instance = new this(perspective, id);\n await instance.get();\n Object.assign(instance, data);\n await instance.save();\n return instance;\n }\n /**\n * Deletes an existing model instance identified by `id`.\n *\n * Also cleans up any incoming links that point to this instance.\n *\n * @param perspective - The perspective containing the instance\n * @param id - The expression URI of the instance to delete\n *\n * @example\n * ```typescript\n * await Recipe.delete(perspective, recipeId);\n * ```\n *\n * @deprecated Use the name `delete` \u2014 `remove` is preserved as an alias.\n */\n static async remove(perspective, id) {\n return this.delete(perspective, id);\n }\n /**\n * Deletes an existing model instance identified by `id`.\n *\n * Also cleans up any incoming links that point to this instance.\n *\n * @param perspective - The perspective containing the instance\n * @param id - The expression URI of the instance to delete\n *\n * @example\n * ```typescript\n * await Recipe.delete(perspective, recipeId);\n * ```\n */\n static async delete(perspective, id) {\n const instance = new this(perspective, id);\n await instance.delete();\n }\n /**\n * Registers this model's SHACL schema on the given perspective.\n *\n * This ensures the perspective knows about the model's shape\n * (properties, relations, constraints) so instances can be\n * created, queried, and validated.\n *\n * @param perspective - The perspective to register the model on\n *\n * @example\n * ```typescript\n * await Recipe.register(perspective);\n * // Now you can create / query Recipe instances on this perspective\n * ```\n */\n static async register(perspective) {\n await perspective.ensureSDNASubjectClass(this);\n }\n /**\n * Batch-registers multiple model classes on a perspective in a single RPC call.\n * This is significantly faster than calling `register()` on each model individually\n * because it eliminates N-1 round-trips and mutex acquisitions.\n *\n * @param perspective - The perspective to register the models on\n * @param models - Array of Ad4mModel subclasses to register\n *\n * @example\n * ```typescript\n * await Ad4mModel.registerAll(perspective, [Community, Channel, Message, Task]);\n * ```\n */\n static async registerAll(perspective, models) {\n await perspective.ensureSubjectClasses(models);\n }\n /**\n * Executes a set of model operations inside a single batch (transaction).\n *\n * All `save`, `update`, and `delete` calls made via the provided `batchId`\n * are buffered and flushed atomically when the callback completes.\n * If the callback throws, the batch is **not** committed, preventing\n * partial writes.\n *\n * @param perspective - The perspective to operate on\n * @param fn - Async callback that receives a `TransactionContext` object.\n * Pass `tx.batchId` to `save(tx.batchId)`, `update(tx.batchId)`,\n * `delete(tx.batchId)`, etc.\n * @returns The value returned by `fn`\n *\n * @example\n * ```typescript\n * await Ad4mModel.transaction(perspective, async (tx) => {\n * const recipe = new Recipe(perspective);\n * recipe.name = \"Spaghetti\";\n * await recipe.save(tx.batchId);\n *\n * const old = await Recipe.query(perspective).where({ name: \"Stale\" }).run();\n * for (const r of old) await r.delete(tx.batchId);\n * });\n * // All changes committed atomically here\n * ```\n */\n static async transaction(perspective, fn) {\n const batchId = await perspective.createBatch();\n const result = await fn({ batchId });\n await perspective.commitBatch(batchId);\n return result;\n }\n /**\n * Creates a query builder for fluent query construction.\n *\n * @param perspective - The perspective to query\n * @param query - Optional initial query parameters\n * @returns A new query builder instance\n *\n * @example\n * ```typescript\n * const recipes = await Recipe.query(perspective)\n * .where({ category: \"Dessert\" })\n * .order({ rating: \"DESC\" })\n * .limit(5)\n * .run();\n *\n * // With real-time updates\n * await Recipe.query(perspective)\n * .where({ status: \"cooking\" })\n * .subscribe(recipes => {\n * console.log(\"Currently cooking:\", recipes);\n * });\n * ```\n */\n static query(perspective, query) {\n return new ModelQueryBuilder(perspective, this, query);\n }\n /**\n * Creates an Ad4mModel class from a JSON Schema definition.\n *\n * @description\n * This method dynamically generates an Ad4mModel subclass from a JSON Schema,\n * enabling integration with systems that use JSON Schema for type definitions.\n *\n * The method follows a cascading approach for determining predicates:\n * 1. Explicit configuration in options parameter (highest precedence)\n * 2. x-ad4m metadata in the JSON Schema\n * 3. Inference from schema title and property names\n * 4. Error if no namespace can be determined\n *\n * @example\n * ```typescript\n * // With explicit configuration\n * const PersonClass = Ad4mModel.fromJSONSchema(schema, {\n * name: \"Person\",\n * namespace: \"person://\",\n * resolveLanguage: \"literal\"\n * });\n *\n * // With property mapping\n * const ContactClass = Ad4mModel.fromJSONSchema(schema, {\n * name: \"Contact\",\n * namespace: \"contact://\",\n * propertyMapping: {\n * \"name\": \"foaf://name\",\n * \"email\": \"foaf://mbox\"\n * }\n * });\n *\n * // With x-ad4m metadata in schema\n * const schema = {\n * \"title\": \"Product\",\n * \"x-ad4m\": { \"namespace\": \"product://\" },\n * \"properties\": {\n * \"name\": {\n * \"type\": \"string\",\n * \"x-ad4m\": { \"through\": \"product://title\" }\n * }\n * }\n * };\n * const ProductClass = Ad4mModel.fromJSONSchema(schema, { name: \"Product\" });\n * ```\n *\n * @param schema - JSON Schema definition\n * @param options - Configuration options\n * @returns Generated Ad4mModel subclass\n * @throws Error when namespace cannot be inferred\n */\n static fromJSONSchema(schema, options) {\n return buildModelFromJSONSchema(this, schema, options);\n }\n /**\n * Creates a fully functional Ad4mModel subclass from a SHACL shape.\n *\n * Unlike `fromJSONSchema()`, no predicate inference is required \u2014\n * `SHACLShape` already contains the exact predicate URI in `path` for\n * every property. The method reads each property's `path`, `maxCount`,\n * `writable`, and `resolveLanguage` directly and writes them to the\n * WeakMap metadata registries.\n *\n * Properties with `hasValue` (flag / type-discrimination markers) are\n * registered as hidden flag entries so that the SPARQL query builder emits\n * the fixed triple `?source <predicate> <value>` needed for type discrimination.\n * Properties without a `name` field are skipped.\n *\n * **Backward-compat:** Old Flux SHACL shapes (created before `sh:hasValue`\n * was persisted on property shapes) carry the flag value only in\n * `shape.constructor_actions` as the `target` of an `addLink` action.\n * This method recovers those values so that old perspectives are queried\n * with the correct type-discriminator triple.\n *\n * @param shape - SHACL node shape (as returned by `PerspectiveProxy.getAllShacl()`)\n * @param name - Class name to assign (e.g. \"Channel\")\n * @returns Generated Ad4mModel subclass, ready for querying\n */\n /**\n * Synthesise an `Ad4mModel` subclass from a SHACL shape.\n *\n * @param shape - The SHACL shape to synthesise from.\n * @param name - The model name (e.g. \"Channel\").\n * @param classResolver - Optional thunk factory. When provided, any collection\n * property that carries a `sh:class` URI will have its `target` wired up lazily:\n * `target: () => classResolver(localName)`. Because `target` is only called at\n * query time (inside `enrichShapeForIncludes` / `jsonToModelInstance`), the\n * resolver just needs to return the correct class by the time a query runs \u2014\n * making it safe to pass a closure over a registry object that is still being\n * populated (e.g. the `result` record inside `getModelClasses`).\n */\n static fromSHACL(shape, name, classResolver) {\n const DynamicModelClass = class extends this {\n };\n DynamicModelClass.className = name;\n DynamicModelClass.prototype.className = name;\n // Build a backward-compat fallback map: predicate \u2192 fixed-IRI-value from\n // constructor actions. Old SHACL stores (created before sh:hasValue was\n // persisted on the property shape) don't carry sh:hasValue on properties,\n // but the shape-level constructor_actions always contain an addLink action\n // with the fixed flag value as the target.\n const flagValueFromConstructor = new Map();\n for (const action of shape.constructor_actions ?? []) {\n if (action.action === 'addLink' &&\n typeof action.predicate === 'string' &&\n typeof action.target === 'string' &&\n action.target !== 'value' &&\n !action.target.startsWith('literal:')) {\n flagValueFromConstructor.set(action.predicate, action.target);\n }\n }\n for (const prop of shape.properties) {\n const resolvedHasValue = prop.hasValue ?? flagValueFromConstructor.get(prop.path);\n if (resolvedHasValue !== undefined) {\n const flagKey = prop.name ?? `_flag_${prop.path.replace(/[^a-zA-Z0-9_]/g, '_')}`;\n setPropertyRegistryEntry(DynamicModelClass, flagKey, {\n through: prop.path,\n required: true,\n initial: resolvedHasValue,\n flag: true,\n writable: false,\n readOnly: true,\n });\n continue;\n }\n // Skip properties without a declared name\n if (!prop.name)\n continue;\n const isCollection = prop.maxCount === undefined || prop.maxCount > 1;\n if (isCollection) {\n // Derive a lazy `target` thunk when a sh:class URI is present and a\n // classResolver was supplied. The thunk is evaluated at query time so\n // it is safe even if the target class hasn't been registered yet.\n let targetThunk;\n if (prop.class && classResolver) {\n const sep = Math.max(prop.class.lastIndexOf('#'), prop.class.lastIndexOf('/'));\n const localName = sep >= 0 ? prop.class.slice(sep + 1) : prop.class;\n targetThunk = () => classResolver(localName);\n }\n setRelationRegistryEntry(DynamicModelClass, prop.name, {\n predicate: prop.path,\n kind: 'hasMany',\n ...(targetThunk !== undefined && { target: targetThunk }),\n ...(prop.local !== undefined && { local: prop.local }),\n ...(prop.getter !== undefined && { getter: prop.getter }),\n });\n }\n else {\n setPropertyRegistryEntry(DynamicModelClass, prop.name, {\n through: prop.path,\n writable: prop.writable ?? true,\n ...(prop.resolveLanguage !== undefined && { resolveLanguage: prop.resolveLanguage }),\n ...(prop.local !== undefined && { local: prop.local }),\n });\n }\n }\n const ModelDecorator = Model$1({ name });\n ModelDecorator(DynamicModelClass);\n return DynamicModelClass;\n }\n}\nAd4mModel.classNamesByClass = new WeakMap();\n\nvar __classPrivateFieldSet$1 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$1 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _Ad4mClient_baseUrl, _Ad4mClient_token, _Ad4mClient_apiClient, _Ad4mClient_agentClient, _Ad4mClient_expressionClient, _Ad4mClient_languageClient, _Ad4mClient_neighbourhoodClient, _Ad4mClient_perspectiveClient, _Ad4mClient_runtimeClient, _Ad4mClient_aiClient;\n/**\n * Client for the Ad4m interface wrapping WebSocket RPC calls\n * for convenient use in user facing code.\n *\n * Aggregates the six sub-clients:\n * AgentClient, ExpressionClient, LanguageClient,\n * NeighbourhoodClient, PerspectiveClient and RuntimeClient\n * for the respective functionality.\n */\nclass Ad4mClient {\n constructor(baseUrl, token, subscribe = true, options) {\n _Ad4mClient_baseUrl.set(this, void 0);\n _Ad4mClient_token.set(this, void 0);\n _Ad4mClient_apiClient.set(this, void 0);\n _Ad4mClient_agentClient.set(this, void 0);\n _Ad4mClient_expressionClient.set(this, void 0);\n _Ad4mClient_languageClient.set(this, void 0);\n _Ad4mClient_neighbourhoodClient.set(this, void 0);\n _Ad4mClient_perspectiveClient.set(this, void 0);\n _Ad4mClient_runtimeClient.set(this, void 0);\n _Ad4mClient_aiClient.set(this, void 0);\n __classPrivateFieldSet$1(this, _Ad4mClient_baseUrl, baseUrl, \"f\");\n __classPrivateFieldSet$1(this, _Ad4mClient_token, token, \"f\");\n __classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token, options?.webSocketImpl), \"f\");\n __classPrivateFieldSet$1(this, _Ad4mClient_agentClient, new AgentClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, \"f\")), \"f\");\n __classPrivateFieldSet$1(this, _Ad4mClient_expressionClient, new ExpressionClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, \"f\")), \"f\");\n __classPrivateFieldSet$1(this, _Ad4mClient_languageClient, new LanguageClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, \"f\")), \"f\");\n __classPrivateFieldSet$1(this, _Ad4mClient_neighbourhoodClient, new NeighbourhoodClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, \"f\")), \"f\");\n __classPrivateFieldSet$1(this, _Ad4mClient_aiClient, new AIClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, \"f\")), \"f\");\n __classPrivateFieldSet$1(this, _Ad4mClient_perspectiveClient, new PerspectiveClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, \"f\")), \"f\");\n __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, \"f\").setExpressionClient(__classPrivateFieldGet$1(this, _Ad4mClient_expressionClient, \"f\"));\n __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, \"f\").setNeighbourhoodClient(__classPrivateFieldGet$1(this, _Ad4mClient_neighbourhoodClient, \"f\"));\n __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, \"f\").setAIClient(__classPrivateFieldGet$1(this, _Ad4mClient_aiClient, \"f\"));\n __classPrivateFieldSet$1(this, _Ad4mClient_runtimeClient, new RuntimeClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, \"f\")), \"f\");\n // Register with AD4M DevTools if the bridge is installed (e.g. browser extension)\n try {\n const dt = globalThis.__AD4M_DEVTOOLS__;\n if (dt) {\n dt._client = this;\n dt._Ad4mModel = Ad4mModel;\n }\n }\n catch { }\n }\n get agent() {\n return __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, \"f\");\n }\n get expression() {\n return __classPrivateFieldGet$1(this, _Ad4mClient_expressionClient, \"f\");\n }\n get languages() {\n return __classPrivateFieldGet$1(this, _Ad4mClient_languageClient, \"f\");\n }\n get neighbourhood() {\n return __classPrivateFieldGet$1(this, _Ad4mClient_neighbourhoodClient, \"f\");\n }\n get perspective() {\n return __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, \"f\");\n }\n get runtime() {\n return __classPrivateFieldGet$1(this, _Ad4mClient_runtimeClient, \"f\");\n }\n get ai() {\n return __classPrivateFieldGet$1(this, _Ad4mClient_aiClient, \"f\");\n }\n /** Start event subscriptions (agent-updated, agent-status-changed, apps-changed).\n * Safe to call if subscriptions were deferred at construction (subscribe=false). */\n startSubscriptions() {\n __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, \"f\").subscribeAgentUpdated();\n __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, \"f\").subscribeAgentStatusChanged();\n __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, \"f\").subscribeAppsChanged();\n }\n /** Close all event connections and clear in-memory caches */\n close() {\n __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, \"f\").clearByDidCache();\n __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, \"f\").closeAll();\n }\n}\n_Ad4mClient_baseUrl = new WeakMap(), _Ad4mClient_token = new WeakMap(), _Ad4mClient_apiClient = new WeakMap(), _Ad4mClient_agentClient = new WeakMap(), _Ad4mClient_expressionClient = new WeakMap(), _Ad4mClient_languageClient = new WeakMap(), _Ad4mClient_neighbourhoodClient = new WeakMap(), _Ad4mClient_perspectiveClient = new WeakMap(), _Ad4mClient_runtimeClient = new WeakMap(), _Ad4mClient_aiClient = new WeakMap();\n\nvar ExceptionType;\n(function (ExceptionType) {\n ExceptionType[\"LanguageIsNotLoaded\"] = \"LANGUAGE_IS_NOT_LOADED\";\n ExceptionType[\"ExpressionIsNotVerified\"] = \"EXPRESSION_IS_NOT_VERIFIED\";\n ExceptionType[\"AgentIsUntrusted\"] = \"AGENT_IS_UNTRUSTED\";\n ExceptionType[\"CapabilityRequested\"] = \"CAPABILITY_REQUESTED\";\n ExceptionType[\"InstallNotificationRequest\"] = \"INSTALL_NOTIFICATION_REQUEST\";\n})(ExceptionType || (ExceptionType = {}));\n\n// Unique Language ID with option type\nclass LanguageRef {\n constructor(address, name) {\n this.address = address;\n this.name = name;\n }\n}\n\n// Expression address + unique Language ID = global expression URL\nclass ExpressionRef {\n constructor(lang, expr) {\n this.language = lang;\n this.expression = expr;\n }\n}\n// Creates unique expression URI like this:\n// expr:Qm3490gfwe489hf34:Qm90ghjoaw4iehioefwe4ort\nfunction exprRef2String(ref) {\n if (ref.language.address === 'did')\n return ref.expression.toString();\n else\n return `${ref.language.address}://${ref.expression}`;\n}\nfunction parseExprUrl(url) {\n if (url.startsWith(\"literal:\")) {\n const languageRef = new LanguageRef();\n languageRef.address = 'literal';\n languageRef.name = 'literal';\n const content = url.substring(8);\n return new ExpressionRef(languageRef, content);\n }\n const URIregexp = /^([^:^\\s]+):\\/\\/([\\s\\S]+)$/;\n const URImatches = URIregexp.exec(url);\n if (URImatches && URImatches.length == 3) {\n const language = URImatches[1];\n const expression = URImatches[2];\n const languageRef = new LanguageRef();\n languageRef.address = language;\n const ref = new ExpressionRef(languageRef, expression);\n return ref;\n }\n const DIDregexp = /^did:([^\\s]+)$/;\n const DIDmatches = DIDregexp.exec(url);\n if (DIDmatches && DIDmatches.length == 2) {\n const languageRef = new LanguageRef();\n languageRef.address = 'did';\n const ref = new ExpressionRef(languageRef, url);\n return ref;\n }\n throw new Error(\"Couldn't parse string as expression URL or DID: \" + url);\n}\n\nclass Icon {\n constructor(code) {\n this.code = code;\n }\n}\n\n/**\n * # AD4M Language \u2014 client-side types\n *\n * This file only contains the client-visible types that the AD4M REST\n * API exposes on top of a running Language \u2014 interaction metadata, online\n * agent records, and the telepresence-signal callback shape.\n *\n * **If you're authoring an AD4M Language**, you don't consume types from\n * here \u2014 use [`@coasys/ad4m-ldk`](https://www.npmjs.com/package/@coasys/ad4m-ldk)\n * (or the [Rust ALDK](https://crates.io/crates/ad4m-ldk)), which provide\n * the capability traits, typed runtime-import wrappers, and authoring\n * macros/helpers.\n *\n * The normative interface definition lives in\n * [`docs-src/ad4m-lang.wit`](https://github.com/coasys/ad4m/blob/dev/docs-src/ad4m-lang.wit).\n * The prose spec is\n * [`docs-src/language-interface-spec.md`](https://github.com/coasys/ad4m/blob/dev/docs-src/language-interface-spec.md).\n */\n// ----- Interaction metadata --------------------------------------------------\n//\n// Languages optionally publish a list of user-invocable actions per\n// Expression (\"interactions\"). The runtime surfaces these to UIs via\n// the API as first-class objects.\nclass InteractionParameter {\n}\nclass InteractionMeta {\n}\nclass InteractionCall {\n get parameters() {\n return JSON.parse(this.parametersStringified);\n }\n constructor(name, parameters) {\n this.name = name;\n this.parametersStringified = JSON.stringify(parameters);\n }\n}\n// ----- Telepresence ----------------------------------------------------------\nclass OnlineAgent {\n}\n\nclass LanguageHandle {\n}\n\nclass LanguageMeta {\n}\nclass LanguageMetaInput {\n constructor(name, description) {\n this.name = name;\n this.description = description;\n if (!this.description)\n this.description = \"\";\n }\n}\nclass LanguageMetaInternal {\n}\nclass LanguageExpression extends ExpressionGeneric() {\n}\nclass LanguageLanguageInput {\n}\n\nvar PerspectiveState;\n(function (PerspectiveState) {\n PerspectiveState[\"Private\"] = \"PRIVATE\";\n PerspectiveState[\"NeighboudhoodCreationInitiated\"] = \"NEIGHBOURHOOD_CREATION_INITIATED\";\n PerspectiveState[\"NeighbourhoodJoinInitiated\"] = \"NEIGHBOURHOOD_JOIN_INITIATED\";\n PerspectiveState[\"LinkLanguageFailedToInstall\"] = \"LINK_LANGUAGE_FAILED_TO_INSTALL\";\n PerspectiveState[\"LinkLanguageInstalledButNotSynced\"] = \"LINK_LANGUAGE_INSTALLED_BUT_NOT_SYNCED\";\n PerspectiveState[\"Synced\"] = \"SYNCED\";\n})(PerspectiveState || (PerspectiveState = {}));\n// This type is used in the REST interface to reference a mutable\n// prespective that is implemented locally by the Ad4m runtime.\n// The UUID is used in mutations to identify the perspective that gets mutated.\nclass PerspectiveHandle {\n constructor(uuid, name, state) {\n this.uuid = uuid;\n this.name = name;\n if (state) {\n this.state = state;\n }\n else {\n this.state = PerspectiveState.Private;\n }\n }\n}\n\n/**\n * WakerSubscriptionManager \u2014 manages live query subscriptions for the waker.\n *\n * Lives in core so it can be imported by both the plugin and integration tests\n * without ESM/CJS import issues.\n *\n * NOTE: keep in sync with plugins/ad4m/wakerSubscriptionManager.ts\n */\nclass WakerSubscriptionManager {\n constructor(options) {\n this.proxies = new Map();\n this.activeSubscriptions = new Map();\n this.debounceTimers = new Map();\n /** Per-subscription set of already-processed message addresses (for mention subs)\n * or serialized result hash (for channel-messages subs). */\n this.seenMessages = new Map();\n this.perspectiveClient = options.perspectiveClient;\n this.logger = options.logger;\n this.debounceMs = options.debounceMs ?? 2000;\n this.onWake = options.onWake;\n this.onPersist = options.onPersist;\n this.QuerySubscriptionProxyCtor = options.QuerySubscriptionProxy ?? null;\n this.previousSeenMessages = options.previousSeenMessages ?? {};\n }\n /**\n * Create a live SPARQL subscription.\n * If a subscription with the same id already exists, it is disposed first.\n */\n async subscribe(sub) {\n // Dispose existing subscription with same id if any\n this.dispose(sub.id, false);\n if (!this.QuerySubscriptionProxyCtor) {\n throw new Error(\"WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options\");\n }\n const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;\n this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);\n this.logger.info(`[waker] ${sub.id}: SPARQL query:\\n${sub.query}`);\n const proxy = new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);\n proxy.isSPARQL = true;\n // Suppress unhandled rejection from proxy.initialized \u2014 QuerySubscriptionProxy\n // rejects this promise internally when subscribe() fails, and if nobody catches\n // it before the next microtask it crashes the process.\n if (proxy.initialized && typeof proxy.initialized.catch === \"function\") {\n proxy.initialized.catch(() => { });\n }\n try {\n await proxy.subscribe();\n await proxy.initialized;\n }\n catch (err) {\n const msg = err?.message ?? String(err);\n this.logger.warn(`[waker] ${sub.id}: subscription failed \u2014 ${msg}`);\n try {\n proxy.dispose();\n }\n catch { }\n // Remove from active state so it doesn't get persisted/retried\n this.activeSubscriptions.delete(sub.id);\n this.seenMessages.delete(sub.id);\n this.persist();\n return; // Don't throw \u2014 caller should not crash\n }\n this.logger.info(`[waker] ${sub.id}: subscription initialized successfully`);\n // Seed from persisted seen messages so we don't re-wake after restart\n const seen = new Set(this.previousSeenMessages[sub.id] ?? []);\n this.seenMessages.set(sub.id, seen);\n if (seen.size > 0) {\n this.logger.info(`[waker] ${sub.id}: seeded ${seen.size} seen message(s) from persisted state`);\n }\n proxy.onResult(async (result) => {\n this.logger.info(`[waker] ${sub.id}: onResult fired \u2014 type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);\n // Query engine can deliver non-array values (e.g. false) on disconnect/reconnect \u2014 ignore them\n if (!Array.isArray(result)) {\n this.logger.warn(`[waker] ${sub.id}: ignoring non-array result: ${JSON.stringify(result)}`);\n return;\n }\n if (sub.type === \"mention\") {\n // For mention subscriptions: track seen message addresses.\n // Only wake for messages we haven't seen before.\n const currentSeen = this.seenMessages.get(sub.id) ?? new Set();\n const newMessages = [];\n for (const item of result) {\n if (item && item.source && !currentSeen.has(item.source)) {\n newMessages.push(item.source);\n }\n }\n if (newMessages.length === 0) {\n this.logger.info(`[waker] ${sub.id}: all ${result.length} items already seen, skipping`);\n return;\n }\n this.logger.info(`[waker] ${sub.id}: ${newMessages.length} new message(s) out of ${result.length} total`);\n // Resolve parents per new message\n const mentions = [];\n for (const msgAddr of newMessages) {\n const parents = [];\n try {\n const parentQuery = `SELECT ?source WHERE { ?source <ad4m://has_child> <${msgAddr}> . }`;\n this.logger.info(`[waker] ${sub.id}: resolving parents for ${msgAddr}`);\n const parentResult = await this.perspectiveClient.querySparql(sub.perspective, parentQuery);\n const bindings = parentResult?.results?.bindings;\n if (Array.isArray(bindings)) {\n for (const binding of bindings) {\n if (binding?.source?.value) {\n parents.push(binding.source.value);\n }\n }\n }\n }\n catch (err) {\n this.logger.warn(`[waker] ${sub.id}: parent resolution failed for ${msgAddr} \u2014 ${err?.message ?? err}`);\n }\n this.logger.info(`[waker] ${sub.id}: message ${msgAddr} has ${parents.length} parent(s): ${parents.join(\", \")}`);\n mentions.push({ address: msgAddr, parents });\n }\n // Mark all new messages as seen\n for (const addr of newMessages) {\n currentSeen.add(addr);\n }\n this.seenMessages.set(sub.id, currentSeen);\n // Debounce the wake callback\n const existing = this.debounceTimers.get(sub.id);\n if (existing)\n clearTimeout(existing);\n this.debounceTimers.set(sub.id, setTimeout(() => {\n this.onWake(sub, result, mentions);\n this.debounceTimers.delete(sub.id);\n this.persist();\n }, this.debounceMs));\n }\n else {\n // For channel-messages: always notify the agent on every subscription push.\n // No deduplication \u2014 the agent reads recent messages itself.\n this.logger.info(`[waker] ${sub.id}: channel update (${result.length} items)`);\n const existing = this.debounceTimers.get(sub.id);\n if (existing)\n clearTimeout(existing);\n this.debounceTimers.set(sub.id, setTimeout(() => {\n this.onWake(sub, result);\n this.debounceTimers.delete(sub.id);\n }, this.debounceMs));\n }\n });\n this.proxies.set(sub.id, proxy);\n this.activeSubscriptions.set(sub.id, sub);\n this.persist();\n this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);\n }\n /**\n * Dispose a single subscription.\n * @param persist \u2014 if false, skip calling onPersist (used during batch cleanup).\n */\n dispose(id, persist = true) {\n const proxy = this.proxies.get(id);\n if (proxy) {\n try {\n proxy.dispose();\n }\n catch {\n /* ignore */\n }\n this.proxies.delete(id);\n }\n const timer = this.debounceTimers.get(id);\n if (timer) {\n clearTimeout(timer);\n this.debounceTimers.delete(id);\n }\n this.activeSubscriptions.delete(id);\n this.seenMessages.delete(id);\n if (persist)\n this.persist();\n }\n /** Dispose all active subscriptions. */\n disposeAll() {\n for (const [id] of this.proxies) {\n this.dispose(id, false);\n }\n }\n /** Get all active subscriptions. */\n getActive() {\n return Array.from(this.activeSubscriptions.values());\n }\n /** Check if a subscription exists. */\n has(id) {\n return this.activeSubscriptions.has(id);\n }\n persist() {\n if (this.onPersist) {\n const seen = {};\n for (const [id, set] of this.seenMessages) {\n seen[id] = Array.from(set);\n }\n this.onPersist(this.getActive(), seen);\n }\n }\n}\n\nclass PerspectiveDiff {\n}\nclass PerspectiveDiffExpression extends ExpressionGeneric() {\n}\n\nvar __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _SmartLiteral_perspective, _SmartLiteral_base;\nconst SMART_LITERAL_CONTENT_PREDICATE = \"smart_literal://content\";\nfunction makeRandomStringID(length) {\n let result = '';\n let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let charactersLength = characters.length;\n for (let i = 0; i < length; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n}\nclass SmartLiteral {\n constructor(perspective, base) {\n _SmartLiteral_perspective.set(this, void 0);\n _SmartLiteral_base.set(this, void 0);\n __classPrivateFieldSet(this, _SmartLiteral_perspective, perspective, \"f\");\n __classPrivateFieldSet(this, _SmartLiteral_base, base, \"f\");\n }\n get base() {\n return __classPrivateFieldGet(this, _SmartLiteral_base, \"f\");\n }\n static async create(perspective, literal) {\n const base = Literal.from(makeRandomStringID(10)).toUrl();\n const smartLiteral = new SmartLiteral(perspective, base);\n await smartLiteral.set(literal);\n return smartLiteral;\n }\n static async isSmartLiteralBase(perspective, base) {\n let links = await perspective.get(new LinkQuery({\n source: base,\n predicate: SMART_LITERAL_CONTENT_PREDICATE\n }));\n return links.length > 0;\n }\n static async getAllSmartLiterals(perspective) {\n let links = await perspective.get(new LinkQuery({\n predicate: SMART_LITERAL_CONTENT_PREDICATE\n }));\n return links.map(link => new SmartLiteral(perspective, link.data.source));\n }\n async get() {\n let link = await __classPrivateFieldGet(this, _SmartLiteral_perspective, \"f\").getSingleTarget(new LinkQuery({\n source: __classPrivateFieldGet(this, _SmartLiteral_base, \"f\"),\n predicate: SMART_LITERAL_CONTENT_PREDICATE\n }));\n if (!link) {\n throw `No content for smart literal ${__classPrivateFieldGet(this, _SmartLiteral_base, \"f\")}`;\n }\n return Literal.fromUrl(link).get();\n }\n async set(content) {\n let literal = Literal.from(content);\n await __classPrivateFieldGet(this, _SmartLiteral_perspective, \"f\").setSingleTarget(new Link({\n source: __classPrivateFieldGet(this, _SmartLiteral_base, \"f\"),\n predicate: SMART_LITERAL_CONTENT_PREDICATE,\n target: literal.toUrl()\n }));\n }\n}\n_SmartLiteral_perspective = new WeakMap(), _SmartLiteral_base = new WeakMap();\n\n/**\n * Shared type definitions for the Ad4mModel system.\n *\n * Extracted into a standalone module so that utility files\n * (`query-utils.ts`, `decorators.ts`, etc.) can import types without\n * creating circular runtime dependencies on `Ad4mModel.ts`.\n */\n/** Type guard for IncludeProjection objects. */\nfunction isIncludeProjection(val) {\n return typeof val === 'object' && val !== null && 'from' in val;\n}\n\nclass Neighbourhood {\n constructor(linkLanguage, meta) {\n this.linkLanguage = linkLanguage;\n this.meta = meta;\n }\n}\nclass NeighbourhoodExpression extends ExpressionGeneric() {\n}\n\n// Placeholder for type definition string.\n// Previously generated by buildSchema; kept for backward compatibility.\nconst typeDefsString = \"\";\n\nclass ModelApi {\n}\nclass TokenizerSource {\n}\nclass LocalModel {\n}\nclass Model {\n}\nclass ModelApiInput {\n}\nclass TokenizerSourceInput {\n}\nclass LocalModelInput {\n}\nclass ModelInput {\n}\nclass VoiceActivityParamsInput {\n}\n\nexport { AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, BelongsToMany, BelongsToOne, Capability, CapabilityInput, ComputeLogEntry, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LocalModel, LocalModelInput, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RpcError as RestError, RpcError, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, compileWhereClause, createPersistentCache, determineNamespace, determinePredicate, escapeQueryString, exprRef2String, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNumericType, isObjectType, isSchemaType, linkEqual, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, queryCacheSize, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString };\n", "// Gets all non-builtin properties up the prototype chain.\nconst getAllProperties = object => {\n\tconst properties = new Set();\n\n\tdo {\n\t\tfor (const key of Reflect.ownKeys(object)) {\n\t\t\tproperties.add([object, key]);\n\t\t}\n\t} while ((object = Reflect.getPrototypeOf(object)) && object !== Object.prototype);\n\n\treturn properties;\n};\n\nexport default function autoBind(self, {include, exclude} = {}) {\n\tconst filter = key => {\n\t\tconst match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key);\n\n\t\tif (include) {\n\t\t\treturn include.some(match); // eslint-disable-line unicorn/no-array-callback-reference\n\t\t}\n\n\t\tif (exclude) {\n\t\t\treturn !exclude.some(match); // eslint-disable-line unicorn/no-array-callback-reference\n\t\t}\n\n\t\treturn true;\n\t};\n\n\tfor (const [object, key] of getAllProperties(self.constructor.prototype)) {\n\t\tif (key === 'constructor' || !filter(key)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(object, key);\n\t\tif (descriptor && typeof descriptor.value === 'function') {\n\t\t\tself[key] = self[key].bind(self);\n\t\t}\n\t}\n\n\treturn self;\n}\n", "import type { RemoteHost, UserInfo } from '../types';\nimport type { Ad4mClient } from '@coasys/ad4m';\n\nconst DEFAULT_INDEX_URL = \"https://hosting.ad4m.dev\";\n\nfunction isAbsoluteUrl(value: string): boolean {\n try {\n // If this doesn't throw, it's an absolute URL\n new URL(value);\n return true;\n } catch {\n return false;\n }\n}\n\n// --- Public API ---\n\n/** Fetch available hosts from the central index API */\nexport async function fetchHosts(indexUrl?: string): Promise<RemoteHost[]> {\n const url = indexUrl || DEFAULT_INDEX_URL;\n const res = await fetch(`${url}/hosts`);\n if (!res.ok) throw new Error(`Failed to fetch hosts: ${res.status}`);\n const hosts: RemoteHost[] = await res.json();\n // Resolve relative profile image URLs against the index API base URL\n for (const host of hosts) {\n if (host.profilePicUrl && !isAbsoluteUrl(host.profilePicUrl)) {\n host.profilePicUrl = new URL(host.profilePicUrl, url).toString();\n }\n }\n return hosts;\n}\n\n/** Fetch current user info from the executor */\nexport async function fetchUserInfo(ad4mClient: Ad4mClient): Promise<UserInfo> {\n const info = await ad4mClient.agent.hostingUserInfo();\n return {\n email: info.email,\n remainingCredits: info.remainingCredits === \"unlimited\" ? Infinity : (parseFloat(info.remainingCredits) || 0),\n hotWalletAddress: info.hotWalletAddress || null,\n freeAccess: info.freeAccess,\n };\n}\n\n/** Trigger a payment request via the executor */\nexport async function requestPayment(\n ad4mClient: Ad4mClient,\n amountHOT: number\n): Promise<{ success: boolean; message: string }> {\n return ad4mClient.agent.requestPayment(amountHOT.toString());\n}\n", "import { isEmbedded, setLocal, getLocal, removeLocal, checkConnection, wsUrlToHttpBase } from './utils';\nimport { PostMessageWebSocket } from './PostMessageWebSocket';\nimport { Ad4mClient, VerificationRequestResult } from \"@coasys/ad4m\";\nimport autoBind from \"auto-bind\";\n\nimport { Ad4mConnectOptions, ConnectionStates, AuthStates, ConfigStates, RemoteHost, UserInfo } from './types';\nimport { fetchUserInfo, requestPayment } from './services/hostIndex';\n\nconst DEFAULT_PORT = 12000;\nconst DEFAULT_INDEX_URL = \"https://hosting.ad4m.dev\";\nconst CREDIT_POLL_INTERVAL_MS = 60000;\nconst DEFAULT_LOW_CREDIT_THRESHOLD = 10;\n\nexport default class Ad4mConnect extends EventTarget {\n options: Ad4mConnectOptions;\n embedded: boolean;\n port: number;\n url: string;\n token: string;\n connectionState: ConnectionStates = \"not-connected\";\n authState: AuthStates = \"unauthenticated\";\n ad4mClient?: Ad4mClient;\n /** HTTP base URL (normalizes legacy ws:// URLs from localStorage) */\n get baseUrl(): string {\n return wsUrlToHttpBase(this.url);\n }\n\n requestId?: string;\n requestedRestart: boolean = false;\n\n // Hosting state\n connectedHost: RemoteHost | null = null;\n userInfo: UserInfo | null = null;\n hostIndexUrl: string;\n lowCreditThreshold: number;\n private creditPollInterval: ReturnType<typeof setInterval> | null = null;\n\n private embeddedResolve?: (client: Ad4mClient) => void;\n private embeddedReject?: (error: Error) => void;\n\n constructor(options: Ad4mConnectOptions) {\n super();\n autoBind(this);\n \n this.options = options;\n this.port = options.port || parseInt(getLocal(\"ad4m-port\")) || DEFAULT_PORT\n this.url = options.url || getLocal(\"ad4m-url\") || `http://localhost:${this.port}`;\n this.token = getLocal(\"ad4m-token\") || '';\n this.embedded = isEmbedded();\n this.hostIndexUrl = options.hostIndexUrl || DEFAULT_INDEX_URL;\n this.lowCreditThreshold = options.lowCreditThreshold ?? DEFAULT_LOW_CREDIT_THRESHOLD;\n\n // Restore last connected host for UI pinning\n const lastHost = getLocal(\"ad4m-last-host\");\n if (lastHost) {\n try {\n const parsed = JSON.parse(lastHost);\n if (parsed && parsed.id && parsed.url && parsed.name) {\n this.connectedHost = {\n id: parsed.id,\n name: parsed.name,\n profilePicUrl: parsed.profilePicUrl || \"\",\n location: parsed.location || \"\",\n url: parsed.url,\n rates: parsed.rates || [],\n aiModels: parsed.aiModels || [],\n };\n }\n } catch { /* ignore corrupt data */ }\n }\n\n if (this.embedded) this.initializeEmbeddedMode();\n }\n\n // Core connection flow\n async connect(): Promise<Ad4mClient> {\n // In embedded mode, wait for postMessage from parent instead of connecting\n if (this.embedded) {\n console.log('[Ad4m Connect] Embedded mode - waiting for AD4M config via postMessage');\n \n return new Promise((resolve, reject) => {\n // The 30-second timeout only guards waiting for AD4M_CONFIG_ACK \u2014 the parent\n // acknowledging that it received our request and is alive. Once the ACK arrives\n // we know auth is in progress and we wait indefinitely for the actual AD4M_CONFIG\n // (the user may take several minutes to complete the auth flow).\n const ackTimeout = setTimeout(() => {\n window.removeEventListener('message', handleAck);\n reject(new Error('Timeout waiting for AD4M_CONFIG_ACK from parent window (is the app running inside we-web?)'));\n }, 30000);\n\n const handleAck = (event: MessageEvent) => {\n if (event.data?.type === 'AD4M_CONFIG_ACK' && event.source === window.parent) {\n clearTimeout(ackTimeout);\n window.removeEventListener('message', handleAck);\n console.log('[Ad4m Connect] Received AD4M_CONFIG_ACK \u2014 parent is alive, waiting for config after auth');\n }\n };\n window.addEventListener('message', handleAck);\n\n // Store resolvers to call when AD4M_CONFIG arrives (via initializeEmbeddedMode listener)\n this.embeddedResolve = (client: Ad4mClient) => {\n clearTimeout(ackTimeout);\n window.removeEventListener('message', handleAck);\n console.log('[Ad4m Connect] Successfully connected in embedded mode');\n resolve(client);\n };\n \n this.embeddedReject = (error: Error) => {\n clearTimeout(ackTimeout);\n window.removeEventListener('message', handleAck);\n reject(error);\n };\n \n // If we already have a client (message arrived before connect() was called)\n if (this.ad4mClient) {\n if (this.authState === 'authenticated') {\n clearTimeout(ackTimeout);\n window.removeEventListener('message', handleAck);\n console.log('[Ad4m Connect] Client already initialized in embedded mode');\n resolve(this.ad4mClient);\n } else {\n // Auth already failed before connect() was called\n clearTimeout(ackTimeout);\n window.removeEventListener('message', handleAck);\n reject(new Error(`Embedded auth state: ${this.authState}`));\n }\n }\n });\n }\n\n // Standalone mode - connect directly\n try {\n await checkConnection(this.baseUrl);\n setLocal(\"ad4m-url\", this.url);\n this.ad4mClient = this.buildClient();\n await this.checkAuth();\n return this.ad4mClient;\n } catch (error) {\n console.error('[Ad4m Connect] Connection failed:', error);\n this.notifyConnectionChange(\"error\");\n throw error;\n }\n }\n\n private buildClient(): Ad4mClient {\n this.notifyConnectionChange(\"connecting\");\n\n // Close old client's WebSocket connections to avoid connection pool exhaustion\n if (this.ad4mClient && typeof this.ad4mClient.close === 'function') {\n this.ad4mClient.close();\n }\n\n // Defer subscriptions until auth is verified to avoid 403 spam\n this.ad4mClient = new Ad4mClient(this.baseUrl, this.token, false);\n this.notifyConnectionChange(\"connected\");\n\n return this.ad4mClient;\n }\n\n private async withTempClient<T>(wsUrl: string, callback: (client: Ad4mClient) => Promise<T>): Promise<T> {\n const baseUrl = wsUrlToHttpBase(wsUrl);\n const client = new Ad4mClient(baseUrl, undefined, false);\n try {\n return await callback(client);\n } finally {\n client.close();\n }\n }\n\n async checkAuth(): Promise<boolean> {\n try {\n console.log('[Ad4m Connect] Checking authentication status...');\n\n // isLocked may not exist on older executors (404). Treat errors\n // as \"not locked\" and fall through to the status check.\n let isLocked = false;\n try {\n isLocked = await this.ad4mClient.agent.isLocked();\n } catch (lockErr) {\n const msg = lockErr?.message || '';\n if (msg === \"Cannot extractByTags from a ciphered wallet. You must unlock first.\") {\n console.log('[Ad4m Connect] Agent wallet is locked (error path)');\n this.notifyAuthChange(\"locked\");\n return true;\n }\n // 404 / network error \u2192 assume not locked\n console.warn('[Ad4m Connect] isLocked check unavailable, assuming unlocked:', msg);\n }\n\n if (isLocked) {\n console.log('[Ad4m Connect] Agent wallet is locked');\n this.notifyAuthChange(\"locked\");\n } else {\n await this.ad4mClient.agent.status();\n this.ad4mClient.startSubscriptions();\n this.notifyAuthChange(\"authenticated\");\n }\n\n return true;\n } catch (error) {\n console.error('[Ad4m Connect] Authentication check failed:', error);\n \n // Clear token if it's invalid (signed by different agent)\n if (error.message === \"InvalidSignature\") {\n console.log('[Ad4m Connect] Clearing invalid token due to InvalidSignature');\n this.token = '';\n removeLocal('ad4m-token');\n }\n \n this.notifyAuthChange(\"unauthenticated\");\n return false;\n }\n }\n\n // Disconnect and clean up\n async disconnect(): Promise<void> {\n console.log('[Ad4m Connect] Disconnecting...');\n \n // Clear client reference\n this.ad4mClient = undefined;\n \n // Clear token\n this.token = '';\n removeLocal('ad4m-token');\n \n // Update auth state (will trigger authstatechange event)\n this.notifyAuthChange('unauthenticated');\n \n // Clear hosting state\n this.connectedHost = null;\n this.userInfo = null;\n this.stopCreditPolling();\n removeLocal('ad4m-last-host');\n\n // Update connection state\n this.notifyConnectionChange('not-connected');\n \n console.log('[Ad4m Connect] Disconnected successfully');\n }\n\n // Hosting \u2014 credit subscription & polling fallback\n\n /**\n * Subscribe to real-time credit updates.\n * Falls back to polling if the subscription is not supported by the executor.\n */\n startCreditSubscription(): void {\n if (!this.ad4mClient) return;\n\n try {\n this.ad4mClient.agent.addHostingUserInfoChangedListener((info) => {\n const userInfo: UserInfo = {\n email: info.email,\n remainingCredits: info.remainingCredits === 'unlimited' ? Infinity : (parseFloat(info.remainingCredits) || 0),\n hotWalletAddress: info.hotWalletAddress || null,\n freeAccess: info.freeAccess,\n };\n this.userInfo = userInfo;\n this.dispatchEvent(new CustomEvent('userinfochange', { detail: userInfo }));\n\n if (!userInfo.freeAccess && userInfo.remainingCredits <= 0) {\n this.dispatchEvent(new CustomEvent('creditdepleted'));\n }\n if (!userInfo.freeAccess && userInfo.remainingCredits <= this.lowCreditThreshold) {\n this.dispatchEvent(new CustomEvent('creditlow'));\n }\n });\n this.ad4mClient.agent.subscribeHostingUserInfoChanged();\n } catch (e) {\n console.warn('[Ad4m Connect] Subscription not available, falling back to polling:', e);\n }\n\n // Subscribe to compute log updates for real-time activity log\n try {\n this.ad4mClient.agent.addComputeLogUpdatedListener((entry) => {\n this.dispatchEvent(new CustomEvent('computelogentry', { detail: entry }));\n });\n this.ad4mClient.agent.subscribeComputeLogUpdated();\n } catch (e) {\n console.warn('[Ad4m Connect] Compute log subscription not available:', e);\n }\n\n // Always start polling as a safety-net (at a longer 60s interval)\n this.startCreditPolling();\n }\n\n startCreditPolling(): void {\n this.stopCreditPolling();\n\n const poll = async () => {\n try {\n if (!this.ad4mClient) return;\n const info = await fetchUserInfo(this.ad4mClient);\n this.userInfo = info;\n this.dispatchEvent(new CustomEvent('userinfochange', { detail: info }));\n\n if (!info.freeAccess && info.remainingCredits <= this.lowCreditThreshold) {\n this.dispatchEvent(new CustomEvent('creditlow'));\n }\n if (!info.freeAccess && info.remainingCredits <= 0) {\n this.dispatchEvent(new CustomEvent('creditdepleted'));\n }\n } catch (error) {\n console.error('[Ad4m Connect] Credit polling error:', error);\n }\n };\n\n // Immediate first poll, then every 30s\n poll();\n this.creditPollInterval = setInterval(poll, CREDIT_POLL_INTERVAL_MS);\n }\n\n stopCreditPolling(): void {\n if (this.creditPollInterval) {\n clearInterval(this.creditPollInterval);\n this.creditPollInterval = null;\n }\n }\n\n async requestTopUp(amountHOT: number): Promise<{ success: boolean; message: string }> {\n if (!this.ad4mClient) throw new Error('Not connected');\n return requestPayment(this.ad4mClient, amountHOT);\n }\n\n /** Fetch recent compute log entries. */\n async fetchComputeLog(since?: string, limit?: number): Promise<import('./types').ComputeLogEntryData[]> {\n if (!this.ad4mClient) throw new Error('Not connected');\n return this.ad4mClient.agent.computeLog(since, limit) as any;\n }\n\n /** Persist selected host after successful auth */\n setConnectedHost(host: RemoteHost): void {\n this.connectedHost = host;\n setLocal('ad4m-last-host', JSON.stringify({ id: host.id, url: host.url, name: host.name, location: host.location }));\n }\n\n // Embedded mode\n private initializeEmbeddedMode(): void {\n console.log('[Ad4m Connect] Running in embedded mode - waiting for AD4M config from parent');\n \n // Set up listener for AD4M_CONFIG from parent window\n window.addEventListener('message', async (event: MessageEvent) => {\n if (event.data?.type === 'AD4M_CONFIG') {\n // Security checks: verify sender\n if (event.source !== window.parent) {\n console.warn('[Ad4m Connect] Rejected AD4M_CONFIG from invalid source (not parent window)');\n return;\n }\n\n // Verify origin is in allowlist (if configured)\n if (this.options.allowedOrigins && this.options.allowedOrigins.length > 0) {\n if (!event.origin || !this.options.allowedOrigins.includes(event.origin)) {\n console.warn('[Ad4m Connect] Rejected AD4M_CONFIG from unauthorized origin:', event.origin);\n this.rejectEmbedded(new Error(`Unauthorized origin: ${event.origin}`));\n return;\n }\n }\n\n console.log('[Ad4m Connect] Received AD4M_CONFIG from parent:', { port: event.data.port, hasToken: !!event.data.token, proxy: !!event.data.proxy });\n \n // Validate and normalize token (optional but must be string if present)\n const { token: rawToken } = event.data;\n const normalizedToken = rawToken !== undefined && rawToken !== null && typeof rawToken === 'string' \n ? rawToken \n : '';\n\n // \u2500\u2500 Proxy mode \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Parent sends proxy: true when the host application will open the real\n // WebSocket to the AD4M daemon and proxy frames via postMessage.\n // The URL/port fields are not needed in this path.\n if (event.data.proxy) {\n try {\n this.token = normalizedToken;\n if (normalizedToken) {\n setLocal('ad4m-token', normalizedToken);\n } else {\n removeLocal('ad4m-token');\n }\n\n this.notifyConnectionChange('connecting');\n this.ad4mClient = new Ad4mClient(\n 'http://proxy', // URL ignored by PostMessageWebSocket\n normalizedToken,\n false, // defer subscriptions until auth confirmed\n { webSocketImpl: PostMessageWebSocket as unknown as new (url: string) => WebSocket }\n );\n this.notifyConnectionChange('connected');\n await this.checkAuth();\n } catch (error) {\n console.error('[Ad4m Connect] Failed to initialize proxy client from AD4M_CONFIG:', error);\n this.rejectEmbedded(error as Error);\n }\n return;\n }\n\n // \u2500\u2500 Direct mode (desktop / local where PNA is not an issue) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Validate and normalize port\n const { port: rawPort } = event.data;\n\n if (rawPort === undefined || rawPort === null) {\n const error = new Error('AD4M_CONFIG missing required field: port');\n console.error('[Ad4m Connect]', error.message);\n this.rejectEmbedded(error);\n return;\n }\n \n const parsedPort = parseInt(rawPort, 10);\n if (!Number.isFinite(parsedPort) || parsedPort <= 0) {\n const error = new Error(`AD4M_CONFIG invalid port: ${rawPort} (must be a positive integer)`);\n console.error('[Ad4m Connect]', error.message);\n this.rejectEmbedded(error);\n return;\n }\n \n try {\n // Set connection details from parent (after successful validation)\n this.port = parsedPort;\n this.token = normalizedToken;\n // Use the URL provided by the parent if valid (e.g. remote host), otherwise fall back to localhost\n const rawUrl = event.data.url;\n this.url = (rawUrl && typeof rawUrl === 'string' && rawUrl.startsWith('http'))\n ? rawUrl\n : `http://localhost:${parsedPort}`;\n \n // Store in localStorage for persistence (avoid storing undefined or stale credentials)\n setLocal('ad4m-port', parsedPort.toString());\n if (normalizedToken) {\n setLocal('ad4m-token', normalizedToken);\n } else {\n // Explicitly clear stale token when absent/invalid to prevent reuse on reload\n removeLocal('ad4m-token');\n }\n setLocal('ad4m-url', this.url);\n \n // Build the client with received credentials\n this.ad4mClient = this.buildClient();\n await this.checkAuth();\n } catch (error) {\n console.error('[Ad4m Connect] Failed to initialize from AD4M_CONFIG:', error);\n this.rejectEmbedded(error as Error);\n }\n }\n });\n \n // Request AD4M config from parent window\n console.log('[Ad4m Connect] Requesting AD4M config from parent window');\n // Determine the actual parent origin for postMessage targeting.\n // Prefer document.referrer (the real parent), validated against allowedOrigins.\n // Fall back to '*' only when no origin information is available.\n let parentOrigin = '*';\n const referrerOrigin = document.referrer ? new URL(document.referrer).origin : null;\n if (referrerOrigin && this.options.allowedOrigins?.includes(referrerOrigin)) {\n parentOrigin = referrerOrigin;\n } else if (this.options.allowedOrigins && this.options.allowedOrigins.length === 1) {\n parentOrigin = this.options.allowedOrigins[0];\n }\n window.parent.postMessage({ type: 'REQUEST_AD4M_CONFIG' }, parentOrigin);\n }\n\n // Local authentication\n private buildAppInfo() {\n return {\n appName: this.options.appInfo.name,\n appDesc: this.options.appInfo.description,\n appDomain: this.options.appInfo.url,\n appUrl: window.location.origin,\n appIconPath: this.options.appInfo.iconPath,\n };\n }\n\n async requestCapability(invalidateToken = false): Promise<string> {\n if (invalidateToken) {\n this.token = '';\n removeLocal('ad4m-token');\n this.notifyConfigChange(\"token\", this.token);\n }\n\n this.requestId = await this.ad4mClient.agent.requestCapability({\n appName: this.options.appInfo.name,\n appDesc: this.options.appInfo.description,\n appUrl: this.options.appInfo.url,\n appDomain: this.options.appInfo.url,\n appIconPath: this.options.appInfo.iconPath,\n capabilities: this.options.capabilities,\n });\n\n return this.requestId;\n }\n\n async verifyLocalAd4mCode(code: string): Promise<boolean> {\n if (!this.requestId) {\n console.error('[Ad4m Connect] Cannot verify code: requestId is missing. Call requestCapability() first to obtain a requestId.');\n return false;\n }\n\n try {\n const jwt = await this.ad4mClient.agent.generateJwt(this.requestId, code);\n this.token = jwt;\n setLocal(\"ad4m-token\", this.token);\n await this.connect();\n return true;\n } catch (error) {\n console.error('[Ad4m Connect] Code verification failed:', error);\n return false;\n }\n }\n\n // Remote authentication\n async isValidAd4mAPI(): Promise<boolean> {\n try {\n await this.withTempClient(this.url, async (client) => await client.runtime.info());\n return true;\n } catch (error) {\n console.error(\"[Ad4m Connect] Failed to verify AD4M API:\", error);\n return false;\n }\n }\n\n async isMultiUser(): Promise<boolean> {\n try {\n return await this.withTempClient(this.url, async (client) => await client.runtime.multiUserEnabled());\n } catch (error) {\n console.error(\"[Ad4m Connect] Failed to detect multi-user mode:\", error);\n // If multi-user query fails, assume single-user mode\n return false;\n }\n }\n\n async submitEmail(email: string): Promise<VerificationRequestResult> {\n try {\n return await this.withTempClient(this.url, async (client) => await client.agent.requestLoginVerification(email, this.buildAppInfo()));\n } catch (e) {\n const errorMessage = (e as Error).message || \"Failed to process email. Please try again.\";\n return { success: false, message: errorMessage, requiresPassword: false, isExistingUser: false };\n }\n }\n\n async verifyEmailCode(email: string, code: string): Promise<boolean> {\n try {\n const token = await this.withTempClient(this.url, async (client) => await client.agent.verifyEmailCode(email, code, \"login\"));\n this.token = token;\n setLocal(\"ad4m-token\", this.token);\n await this.connect();\n return true;\n } catch (e) {\n console.error(\"[Ad4m Connect] Email code verification failed:\", e);\n return false;\n }\n }\n\n async loginWithPassword(email: string, password: string): Promise<boolean> {\n try {\n const token = await this.withTempClient(this.url, async (client) => await client.agent.loginUser(email, password));\n this.token = token;\n setLocal(\"ad4m-token\", this.token);\n await this.connect();\n return true;\n } catch (e) {\n console.error(\"[Ad4m Connect] Password login failed:\", e);\n return false;\n }\n }\n\n async createAccount(email: string, password: string): Promise<boolean> {\n try {\n const token = await this.withTempClient(this.url, async (client) => {\n const result = await client.agent.createUser(email, password);\n // If creation successful, log in the new user\n if (result.success) return await client.agent.loginUser(email, password);\n // Otherwise, throw an error with the failure message\n else throw new Error(result.error || \"Failed to create account\");\n });\n\n this.token = token;\n setLocal(\"ad4m-token\", this.token);\n await this.connect();\n return true;\n } catch (e) {\n console.error(\"[Ad4m Connect] Account creation error:\", e);\n return false;\n }\n }\n\n // Private helpers\n private resolveEmbedded(client: Ad4mClient): void {\n if (this.embeddedResolve) {\n this.embeddedResolve(client);\n this.embeddedResolve = undefined;\n this.embeddedReject = undefined;\n }\n }\n\n private rejectEmbedded(error: Error): void {\n if (this.embeddedReject) {\n this.embeddedReject(error);\n this.embeddedResolve = undefined;\n this.embeddedReject = undefined;\n }\n }\n\n private notifyConnectionChange(value: ConnectionStates) {\n if (this.connectionState === value) return;\n this.connectionState = value;\n this.dispatchEvent(new CustomEvent(\"connectionstatechange\", { detail: value }));\n }\n\n private notifyAuthChange(value: AuthStates) {\n this.authState = value;\n this.dispatchEvent(new CustomEvent(\"authstatechange\", { detail: value }));\n\n // In embedded mode, handle connect() promise resolution/rejection\n if (this.embedded) {\n // Resolve when authenticated\n if (value === \"authenticated\") {\n this.resolveEmbedded(this.ad4mClient);\n }\n \n // Reject on failing auth states\n if (value === \"unauthenticated\" || value === \"locked\") {\n const errorMessage = value === \"locked\" \n ? \"Authentication failed: Agent is locked\"\n : \"Authentication failed: Unauthenticated\";\n this.rejectEmbedded(new Error(errorMessage));\n }\n }\n }\n\n private notifyConfigChange(type: ConfigStates, value: string) {\n this.dispatchEvent(new CustomEvent(\"configstatechange\", { detail: { type, value } }));\n }\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nconst NODE_MODE = false;\nconst global = NODE_MODE ? globalThis : window;\n\n/**\n * Whether the current browser supports `adoptedStyleSheets`.\n */\nexport const supportsAdoptingStyleSheets: boolean =\n global.ShadowRoot &&\n (global.ShadyCSS === undefined || global.ShadyCSS.nativeShadow) &&\n 'adoptedStyleSheets' in Document.prototype &&\n 'replace' in CSSStyleSheet.prototype;\n\n/**\n * A CSSResult or native CSSStyleSheet.\n *\n * In browsers that support constructible CSS style sheets, CSSStyleSheet\n * object can be used for styling along side CSSResult from the `css`\n * template tag.\n */\nexport type CSSResultOrNative = CSSResult | CSSStyleSheet;\n\nexport type CSSResultArray = Array<CSSResultOrNative | CSSResultArray>;\n\n/**\n * A single CSSResult, CSSStyleSheet, or an array or nested arrays of those.\n */\nexport type CSSResultGroup = CSSResultOrNative | CSSResultArray;\n\nconst constructionToken = Symbol();\n\nconst cssTagCache = new WeakMap<TemplateStringsArray, CSSStyleSheet>();\n\n/**\n * A container for a string of CSS text, that may be used to create a CSSStyleSheet.\n *\n * CSSResult is the return value of `css`-tagged template literals and\n * `unsafeCSS()`. In order to ensure that CSSResults are only created via the\n * `css` tag and `unsafeCSS()`, CSSResult cannot be constructed directly.\n */\nexport class CSSResult {\n // This property needs to remain unminified.\n ['_$cssResult$'] = true;\n readonly cssText: string;\n private _styleSheet?: CSSStyleSheet;\n private _strings: TemplateStringsArray | undefined;\n\n private constructor(\n cssText: string,\n strings: TemplateStringsArray | undefined,\n safeToken: symbol\n ) {\n if (safeToken !== constructionToken) {\n throw new Error(\n 'CSSResult is not constructable. Use `unsafeCSS` or `css` instead.'\n );\n }\n this.cssText = cssText;\n this._strings = strings;\n }\n\n // This is a getter so that it's lazy. In practice, this means stylesheets\n // are not created until the first element instance is made.\n get styleSheet(): CSSStyleSheet | undefined {\n // If `supportsAdoptingStyleSheets` is true then we assume CSSStyleSheet is\n // constructable.\n let styleSheet = this._styleSheet;\n const strings = this._strings;\n if (supportsAdoptingStyleSheets && styleSheet === undefined) {\n const cacheable = strings !== undefined && strings.length === 1;\n if (cacheable) {\n styleSheet = cssTagCache.get(strings);\n }\n if (styleSheet === undefined) {\n (this._styleSheet = styleSheet = new CSSStyleSheet()).replaceSync(\n this.cssText\n );\n if (cacheable) {\n cssTagCache.set(strings, styleSheet);\n }\n }\n }\n return styleSheet;\n }\n\n toString(): string {\n return this.cssText;\n }\n}\n\ntype ConstructableCSSResult = CSSResult & {\n new (\n cssText: string,\n strings: TemplateStringsArray | undefined,\n safeToken: symbol\n ): CSSResult;\n};\n\nconst textFromCSSResult = (value: CSSResultGroup | number) => {\n // This property needs to remain unminified.\n if ((value as CSSResult)['_$cssResult$'] === true) {\n return (value as CSSResult).cssText;\n } else if (typeof value === 'number') {\n return value;\n } else {\n throw new Error(\n `Value passed to 'css' function must be a 'css' function result: ` +\n `${value}. Use 'unsafeCSS' to pass non-literal values, but take care ` +\n `to ensure page security.`\n );\n }\n};\n\n/**\n * Wrap a value for interpolation in a {@linkcode css} tagged template literal.\n *\n * This is unsafe because untrusted CSS text can be used to phone home\n * or exfiltrate data to an attacker controlled site. Take care to only use\n * this with trusted input.\n */\nexport const unsafeCSS = (value: unknown) =>\n new (CSSResult as ConstructableCSSResult)(\n typeof value === 'string' ? value : String(value),\n undefined,\n constructionToken\n );\n\n/**\n * A template literal tag which can be used with LitElement's\n * {@linkcode LitElement.styles} property to set element styles.\n *\n * For security reasons, only literal string values and number may be used in\n * embedded expressions. To incorporate non-literal values {@linkcode unsafeCSS}\n * may be used inside an expression.\n */\nexport const css = (\n strings: TemplateStringsArray,\n ...values: (CSSResultGroup | number)[]\n): CSSResult => {\n const cssText =\n strings.length === 1\n ? strings[0]\n : values.reduce(\n (acc, v, idx) => acc + textFromCSSResult(v) + strings[idx + 1],\n strings[0]\n );\n return new (CSSResult as ConstructableCSSResult)(\n cssText,\n strings,\n constructionToken\n );\n};\n\n/**\n * Applies the given styles to a `shadowRoot`. When Shadow DOM is\n * available but `adoptedStyleSheets` is not, styles are appended to the\n * `shadowRoot` to [mimic spec behavior](https://wicg.github.io/construct-stylesheets/#using-constructed-stylesheets).\n * Note, when shimming is used, any styles that are subsequently placed into\n * the shadowRoot should be placed *before* any shimmed adopted styles. This\n * will match spec behavior that gives adopted sheets precedence over styles in\n * shadowRoot.\n */\nexport const adoptStyles = (\n renderRoot: ShadowRoot,\n styles: Array<CSSResultOrNative>\n) => {\n if (supportsAdoptingStyleSheets) {\n (renderRoot as ShadowRoot).adoptedStyleSheets = styles.map((s) =>\n s instanceof CSSStyleSheet ? s : s.styleSheet!\n );\n } else {\n styles.forEach((s) => {\n const style = document.createElement('style');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const nonce = (global as any)['litNonce'];\n if (nonce !== undefined) {\n style.setAttribute('nonce', nonce);\n }\n style.textContent = (s as CSSResult).cssText;\n renderRoot.appendChild(style);\n });\n }\n};\n\nconst cssResultFromStyleSheet = (sheet: CSSStyleSheet) => {\n let cssText = '';\n for (const rule of sheet.cssRules) {\n cssText += rule.cssText;\n }\n return unsafeCSS(cssText);\n};\n\nexport const getCompatibleStyle =\n supportsAdoptingStyleSheets ||\n (NODE_MODE && global.CSSStyleSheet === undefined)\n ? (s: CSSResultOrNative) => s\n : (s: CSSResultOrNative) =>\n s instanceof CSSStyleSheet ? cssResultFromStyleSheet(s) : s;\n", "/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/**\n * Use this module if you want to create your own base class extending\n * {@link ReactiveElement}.\n * @packageDocumentation\n */\n\nimport {\n getCompatibleStyle,\n adoptStyles,\n CSSResultGroup,\n CSSResultOrNative,\n} from './css-tag.js';\nimport type {\n ReactiveController,\n ReactiveControllerHost,\n} from './reactive-controller.js';\n\n// In the Node build, this import will be injected by Rollup:\n// import {HTMLElement, customElements} from '@lit-labs/ssr-dom-shim';\n\nexport * from './css-tag.js';\nexport type {\n ReactiveController,\n ReactiveControllerHost,\n} from './reactive-controller.js';\n\nconst NODE_MODE = false;\nconst global = NODE_MODE ? globalThis : window;\n\nif (NODE_MODE) {\n global.customElements ??= customElements;\n}\n\nconst DEV_MODE = true;\n\nlet requestUpdateThenable: (name: string) => {\n then: (\n onfulfilled?: (value: boolean) => void,\n _onrejected?: () => void\n ) => void;\n};\n\nlet issueWarning: (code: string, warning: string) => void;\n\nconst trustedTypes = (global as unknown as {trustedTypes?: {emptyScript: ''}})\n .trustedTypes;\n\n// Temporary workaround for https://crbug.com/993268\n// Currently, any attribute starting with \"on\" is considered to be a\n// TrustedScript source. Such boolean attributes must be set to the equivalent\n// trusted emptyScript value.\nconst emptyStringForBooleanAttribute = trustedTypes\n ? (trustedTypes.emptyScript as unknown as '')\n : '';\n\nconst polyfillSupport = DEV_MODE\n ? global.reactiveElementPolyfillSupportDevMode\n : global.reactiveElementPolyfillSupport;\n\nif (DEV_MODE) {\n // Ensure warnings are issued only 1x, even if multiple versions of Lit\n // are loaded.\n const issuedWarnings: Set<string | undefined> = (global.litIssuedWarnings ??=\n new Set());\n\n // Issue a warning, if we haven't already.\n issueWarning = (code: string, warning: string) => {\n warning += ` See https://lit.dev/msg/${code} for more information.`;\n if (!issuedWarnings.has(warning)) {\n console.warn(warning);\n issuedWarnings.add(warning);\n }\n };\n\n issueWarning(\n 'dev-mode',\n `Lit is in dev mode. Not recommended for production!`\n );\n\n // Issue polyfill support warning.\n if (global.ShadyDOM?.inUse && polyfillSupport === undefined) {\n issueWarning(\n 'polyfill-support-missing',\n `Shadow DOM is being polyfilled via \\`ShadyDOM\\` but ` +\n `the \\`polyfill-support\\` module has not been loaded.`\n );\n }\n\n requestUpdateThenable = (name) => ({\n then: (\n onfulfilled?: (value: boolean) => void,\n _onrejected?: () => void\n ) => {\n issueWarning(\n 'request-update-promise',\n `The \\`requestUpdate\\` method should no longer return a Promise but ` +\n `does so on \\`${name}\\`. Use \\`updateComplete\\` instead.`\n );\n if (onfulfilled !== undefined) {\n onfulfilled(false);\n }\n },\n });\n}\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace ReactiveUnstable {\n /**\n * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n * we will emit 'lit-debug' events to window, with live details about the update and render\n * lifecycle. These can be useful for writing debug tooling and visualizations.\n *\n * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n * making certain operations that are normally very cheap (like a no-op render) much slower,\n * because we must copy data and dispatch events.\n */\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace DebugLog {\n export type Entry = Update;\n export interface Update {\n kind: 'update';\n }\n }\n}\n\ninterface DebugLoggingWindow {\n // Even in dev mode, we generally don't want to emit these events, as that's\n // another level of cost, so only emit them when DEV_MODE is true _and_ when\n // window.emitLitDebugEvents is true.\n emitLitDebugLogEvents?: boolean;\n}\n\n/**\n * Useful for visualizing and logging insights into what the Lit template system is doing.\n *\n * Compiled out of prod mode builds.\n */\nconst debugLogEvent = DEV_MODE\n ? (event: ReactiveUnstable.DebugLog.Entry) => {\n const shouldEmit = (global as unknown as DebugLoggingWindow)\n .emitLitDebugLogEvents;\n if (!shouldEmit) {\n return;\n }\n global.dispatchEvent(\n new CustomEvent<ReactiveUnstable.DebugLog.Entry>('lit-debug', {\n detail: event,\n })\n );\n }\n : undefined;\n\n/*\n * When using Closure Compiler, JSCompiler_renameProperty(property, object) is\n * replaced at compile time by the munged name for object[property]. We cannot\n * alias this function, so we have to use a small shim that has the same\n * behavior when not compiling.\n */\n/*@__INLINE__*/\nconst JSCompiler_renameProperty = <P extends PropertyKey>(\n prop: P,\n _obj: unknown\n): P => prop;\n\n/**\n * Converts property values to and from attribute values.\n */\nexport interface ComplexAttributeConverter<Type = unknown, TypeHint = unknown> {\n /**\n * Called to convert an attribute value to a property\n * value.\n */\n fromAttribute?(value: string | null, type?: TypeHint): Type;\n\n /**\n * Called to convert a property value to an attribute\n * value.\n *\n * It returns unknown instead of string, to be compatible with\n * https://github.com/WICG/trusted-types (and similar efforts).\n */\n toAttribute?(value: Type, type?: TypeHint): unknown;\n}\n\ntype AttributeConverter<Type = unknown, TypeHint = unknown> =\n | ComplexAttributeConverter<Type>\n | ((value: string | null, type?: TypeHint) => Type);\n\n/**\n * Defines options for a property accessor.\n */\nexport interface PropertyDeclaration<Type = unknown, TypeHint = unknown> {\n /**\n * When set to `true`, indicates the property is internal private state. The\n * property should not be set by users. When using TypeScript, this property\n * should be marked as `private` or `protected`, and it is also a common\n * practice to use a leading `_` in the name. The property is not added to\n * `observedAttributes`.\n */\n readonly state?: boolean;\n\n /**\n * Indicates how and whether the property becomes an observed attribute.\n * If the value is `false`, the property is not added to `observedAttributes`.\n * If true or absent, the lowercased property name is observed (e.g. `fooBar`\n * becomes `foobar`). If a string, the string value is observed (e.g\n * `attribute: 'foo-bar'`).\n */\n readonly attribute?: boolean | string;\n\n /**\n * Indicates the type of the property. This is used only as a hint for the\n * `converter` to determine how to convert the attribute\n * to/from a property.\n */\n readonly type?: TypeHint;\n\n /**\n * Indicates how to convert the attribute to/from a property. If this value\n * is a function, it is used to convert the attribute value a the property\n * value. If it's an object, it can have keys for `fromAttribute` and\n * `toAttribute`. If no `toAttribute` function is provided and\n * `reflect` is set to `true`, the property value is set directly to the\n * attribute. A default `converter` is used if none is provided; it supports\n * `Boolean`, `String`, `Number`, `Object`, and `Array`. Note,\n * when a property changes and the converter is used to update the attribute,\n * the property is never updated again as a result of the attribute changing,\n * and vice versa.\n */\n readonly converter?: AttributeConverter<Type, TypeHint>;\n\n /**\n * Indicates if the property should reflect to an attribute.\n * If `true`, when the property is set, the attribute is set using the\n * attribute name determined according to the rules for the `attribute`\n * property option and the value of the property converted using the rules\n * from the `converter` property option.\n */\n readonly reflect?: boolean;\n\n /**\n * A function that indicates if a property should be considered changed when\n * it is set. The function should take the `newValue` and `oldValue` and\n * return `true` if an update should be requested.\n */\n hasChanged?(value: Type, oldValue: Type): boolean;\n\n /**\n * Indicates whether an accessor will be created for this property. By\n * default, an accessor will be generated for this property that requests an\n * update when set. If this flag is `true`, no accessor will be created, and\n * it will be the user's responsibility to call\n * `this.requestUpdate(propertyName, oldValue)` to request an update when\n * the property changes.\n */\n readonly noAccessor?: boolean;\n}\n\n/**\n * Map of properties to PropertyDeclaration options. For each property an\n * accessor is made, and the property is processed according to the\n * PropertyDeclaration options.\n */\nexport interface PropertyDeclarations {\n readonly [key: string]: PropertyDeclaration;\n}\n\ntype PropertyDeclarationMap = Map<PropertyKey, PropertyDeclaration>;\n\ntype AttributeMap = Map<string, PropertyKey>;\n\n/**\n * A Map of property keys to values.\n *\n * Takes an optional type parameter T, which when specified as a non-any,\n * non-unknown type, will make the Map more strongly-typed, associating the map\n * keys with their corresponding value type on T.\n *\n * Use `PropertyValues<this>` when overriding ReactiveElement.update() and\n * other lifecycle methods in order to get stronger type-checking on keys\n * and values.\n */\n// This type is conditional so that if the parameter T is not specified, or\n// is `any`, the type will include `Map<PropertyKey, unknown>`. Since T is not\n// given in the uses of PropertyValues in this file, all uses here fallback to\n// meaning `Map<PropertyKey, unknown>`, but if a developer uses\n// `PropertyValues<this>` (or any other value for T) they will get a\n// strongly-typed Map type.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type PropertyValues<T = any> = T extends object\n ? PropertyValueMap<T>\n : Map<PropertyKey, unknown>;\n\n/**\n * Do not use, instead prefer {@linkcode PropertyValues}.\n */\n// This type must be exported such that JavaScript generated by the Google\n// Closure Compiler can import a type reference.\nexport interface PropertyValueMap<T> extends Map<PropertyKey, unknown> {\n get<K extends keyof T>(k: K): T[K];\n set<K extends keyof T>(key: K, value: T[K]): this;\n has<K extends keyof T>(k: K): boolean;\n delete<K extends keyof T>(k: K): boolean;\n}\n\nexport const defaultConverter: ComplexAttributeConverter = {\n toAttribute(value: unknown, type?: unknown): unknown {\n switch (type) {\n case Boolean:\n value = value ? emptyStringForBooleanAttribute : null;\n break;\n case Object:\n case Array:\n // if the value is `null` or `undefined` pass this through\n // to allow removing/no change behavior.\n value = value == null ? value : JSON.stringify(value);\n break;\n }\n return value;\n },\n\n fromAttribute(value: string | null, type?: unknown) {\n let fromValue: unknown = value;\n switch (type) {\n case Boolean:\n fromValue = value !== null;\n break;\n case Number:\n fromValue = value === null ? null : Number(value);\n break;\n case Object:\n case Array:\n // Do *not* generate exception when invalid JSON is set as elements\n // don't normally complain on being mis-configured.\n // TODO(sorvell): Do generate exception in *dev mode*.\n try {\n // Assert to adhere to Bazel's \"must type assert JSON parse\" rule.\n fromValue = JSON.parse(value!) as unknown;\n } catch (e) {\n fromValue = null;\n }\n break;\n }\n return fromValue;\n },\n};\n\nexport interface HasChanged {\n (value: unknown, old: unknown): boolean;\n}\n\n/**\n * Change function that returns true if `value` is different from `oldValue`.\n * This method is used as the default for a property's `hasChanged` function.\n */\nexport const notEqual: HasChanged = (value: unknown, old: unknown): boolean => {\n // This ensures (old==NaN, value==NaN) always returns false\n return old !== value && (old === old || value === value);\n};\n\nconst defaultPropertyDeclaration: PropertyDeclaration = {\n attribute: true,\n type: String,\n converter: defaultConverter,\n reflect: false,\n hasChanged: notEqual,\n};\n\n/**\n * The Closure JS Compiler doesn't currently have good support for static\n * property semantics where \"this\" is dynamic (e.g.\n * https://github.com/google/closure-compiler/issues/3177 and others) so we use\n * this hack to bypass any rewriting by the compiler.\n */\nconst finalized = 'finalized';\n\n/**\n * A string representing one of the supported dev mode warning categories.\n */\nexport type WarningKind = 'change-in-update' | 'migration';\n\nexport type Initializer = (element: ReactiveElement) => void;\n\n/**\n * Base element class which manages element properties and attributes. When\n * properties change, the `update` method is asynchronously called. This method\n * should be supplied by subclassers to render updates as desired.\n * @noInheritDoc\n */\nexport abstract class ReactiveElement\n // In the Node build, this `extends` clause will be substituted with\n // `(globalThis.HTMLElement ?? HTMLElement)`.\n //\n // This way, we will first prefer any global `HTMLElement` polyfill that the\n // user has assigned, and then fall back to the `HTMLElement` shim which has\n // been imported (see note at the top of this file about how this import is\n // generated by Rollup). Note that the `HTMLElement` variable has been\n // shadowed by this import, so it no longer refers to the global.\n extends HTMLElement\n implements ReactiveControllerHost\n{\n // Note: these are patched in only in DEV_MODE.\n /**\n * Read or set all the enabled warning categories for this class.\n *\n * This property is only used in development builds.\n *\n * @nocollapse\n * @category dev-mode\n */\n static enabledWarnings?: WarningKind[];\n\n /**\n * Enable the given warning category for this class.\n *\n * This method only exists in development builds, so it should be accessed\n * with a guard like:\n *\n * ```ts\n * // Enable for all ReactiveElement subclasses\n * ReactiveElement.enableWarning?.('migration');\n *\n * // Enable for only MyElement and subclasses\n * MyElement.enableWarning?.('migration');\n * ```\n *\n * @nocollapse\n * @category dev-mode\n */\n static enableWarning?: (warningKind: WarningKind) => void;\n\n /**\n * Disable the given warning category for this class.\n *\n * This method only exists in development builds, so it should be accessed\n * with a guard like:\n *\n * ```ts\n * // Disable for all ReactiveElement subclasses\n * ReactiveElement.disableWarning?.('migration');\n *\n * // Disable for only MyElement and subclasses\n * MyElement.disableWarning?.('migration');\n * ```\n *\n * @nocollapse\n * @category dev-mode\n */\n static disableWarning?: (warningKind: WarningKind) => void;\n\n /**\n * Adds an initializer function to the class that is called during instance\n * construction.\n *\n * This is useful for code that runs against a `ReactiveElement`\n * subclass, such as a decorator, that needs to do work for each\n * instance, such as setting up a `ReactiveController`.\n *\n * ```ts\n * const myDecorator = (target: typeof ReactiveElement, key: string) => {\n * target.addInitializer((instance: ReactiveElement) => {\n * // This is run during construction of the element\n * new MyController(instance);\n * });\n * }\n * ```\n *\n * Decorating a field will then cause each instance to run an initializer\n * that adds a controller:\n *\n * ```ts\n * class MyElement extends LitElement {\n * @myDecorator foo;\n * }\n * ```\n *\n * Initializers are stored per-constructor. Adding an initializer to a\n * subclass does not add it to a superclass. Since initializers are run in\n * constructors, initializers will run in order of the class hierarchy,\n * starting with superclasses and progressing to the instance's class.\n *\n * @nocollapse\n */\n static addInitializer(initializer: Initializer) {\n this.finalize();\n (this._initializers ??= []).push(initializer);\n }\n\n static _initializers?: Initializer[];\n\n /*\n * Due to closure compiler ES6 compilation bugs, @nocollapse is required on\n * all static methods and properties with initializers. Reference:\n * - https://github.com/google/closure-compiler/issues/1776\n */\n\n /**\n * Maps attribute names to properties; for example `foobar` attribute to\n * `fooBar` property. Created lazily on user subclasses when finalizing the\n * class.\n * @nocollapse\n */\n private static __attributeToPropertyMap: AttributeMap;\n\n /**\n * Marks class as having finished creating properties.\n */\n protected static [finalized] = true;\n\n /**\n * Memoized list of all element properties, including any superclass properties.\n * Created lazily on user subclasses when finalizing the class.\n * @nocollapse\n * @category properties\n */\n static elementProperties: PropertyDeclarationMap = new Map();\n\n /**\n * User-supplied object that maps property names to `PropertyDeclaration`\n * objects containing options for configuring reactive properties. When\n * a reactive property is set the element will update and render.\n *\n * By default properties are public fields, and as such, they should be\n * considered as primarily settable by element users, either via attribute or\n * the property itself.\n *\n * Generally, properties that are changed by the element should be private or\n * protected fields and should use the `state: true` option. Properties\n * marked as `state` do not reflect from the corresponding attribute\n *\n * However, sometimes element code does need to set a public property. This\n * should typically only be done in response to user interaction, and an event\n * should be fired informing the user; for example, a checkbox sets its\n * `checked` property when clicked and fires a `changed` event. Mutating\n * public properties should typically not be done for non-primitive (object or\n * array) properties. In other cases when an element needs to manage state, a\n * private property set with the `state: true` option should be used. When\n * needed, state properties can be initialized via public properties to\n * facilitate complex interactions.\n * @nocollapse\n * @category properties\n */\n static properties: PropertyDeclarations;\n\n /**\n * Memoized list of all element styles.\n * Created lazily on user subclasses when finalizing the class.\n * @nocollapse\n * @category styles\n */\n static elementStyles: Array<CSSResultOrNative> = [];\n\n /**\n * Array of styles to apply to the element. The styles should be defined\n * using the {@linkcode css} tag function, via constructible stylesheets, or\n * imported from native CSS module scripts.\n *\n * Note on Content Security Policy:\n *\n * Element styles are implemented with `<style>` tags when the browser doesn't\n * support adopted StyleSheets. To use such `<style>` tags with the style-src\n * CSP directive, the style-src value must either include 'unsafe-inline' or\n * `nonce-<base64-value>` with `<base64-value>` replaced be a server-generated\n * nonce.\n *\n * To provide a nonce to use on generated `<style>` elements, set\n * `window.litNonce` to a server-generated nonce in your page's HTML, before\n * loading application code:\n *\n * ```html\n * <script>\n * // Generated and unique per request:\n * window.litNonce = 'a1b2c3d4';\n * </script>\n * ```\n * @nocollapse\n * @category styles\n */\n static styles?: CSSResultGroup;\n\n /**\n * The set of properties defined by this class that caused an accessor to be\n * added during `createProperty`.\n * @nocollapse\n */\n private static __reactivePropertyKeys?: Set<PropertyKey>;\n\n /**\n * Returns a list of attributes corresponding to the registered properties.\n * @nocollapse\n * @category attributes\n */\n static get observedAttributes() {\n // note: piggy backing on this to ensure we're finalized.\n this.finalize();\n const attributes: string[] = [];\n // Use forEach so this works even if for/of loops are compiled to for loops\n // expecting arrays\n this.elementProperties.forEach((v, p) => {\n const attr = this.__attributeNameForProperty(p, v);\n if (attr !== undefined) {\n this.__attributeToPropertyMap.set(attr, p);\n attributes.push(attr);\n }\n });\n return attributes;\n }\n\n /**\n * Creates a property accessor on the element prototype if one does not exist\n * and stores a {@linkcode PropertyDeclaration} for the property with the\n * given options. The property setter calls the property's `hasChanged`\n * property option or uses a strict identity check to determine whether or not\n * to request an update.\n *\n * This method may be overridden to customize properties; however,\n * when doing so, it's important to call `super.createProperty` to ensure\n * the property is setup correctly. This method calls\n * `getPropertyDescriptor` internally to get a descriptor to install.\n * To customize what properties do when they are get or set, override\n * `getPropertyDescriptor`. To customize the options for a property,\n * implement `createProperty` like this:\n *\n * ```ts\n * static createProperty(name, options) {\n * options = Object.assign(options, {myOption: true});\n * super.createProperty(name, options);\n * }\n * ```\n *\n * @nocollapse\n * @category properties\n */\n static createProperty(\n name: PropertyKey,\n options: PropertyDeclaration = defaultPropertyDeclaration\n ) {\n // if this is a state property, force the attribute to false.\n if (options.state) {\n // Cast as any since this is readonly.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (options as any).attribute = false;\n }\n // Note, since this can be called by the `@property` decorator which\n // is called before `finalize`, we ensure finalization has been kicked off.\n this.finalize();\n this.elementProperties.set(name, options);\n // Do not generate an accessor if the prototype already has one, since\n // it would be lost otherwise and that would never be the user's intention;\n // Instead, we expect users to call `requestUpdate` themselves from\n // user-defined accessors. Note that if the super has an accessor we will\n // still overwrite it\n if (!options.noAccessor && !this.prototype.hasOwnProperty(name)) {\n const key = typeof name === 'symbol' ? Symbol() : `__${name}`;\n const descriptor = this.getPropertyDescriptor(name, key, options);\n if (descriptor !== undefined) {\n Object.defineProperty(this.prototype, name, descriptor);\n if (DEV_MODE) {\n // If this class doesn't have its own set, create one and initialize\n // with the values in the set from the nearest ancestor class, if any.\n if (!this.hasOwnProperty('__reactivePropertyKeys')) {\n this.__reactivePropertyKeys = new Set(\n this.__reactivePropertyKeys ?? []\n );\n }\n this.__reactivePropertyKeys!.add(name);\n }\n }\n }\n }\n\n /**\n * Returns a property descriptor to be defined on the given named property.\n * If no descriptor is returned, the property will not become an accessor.\n * For example,\n *\n * ```ts\n * class MyElement extends LitElement {\n * static getPropertyDescriptor(name, key, options) {\n * const defaultDescriptor =\n * super.getPropertyDescriptor(name, key, options);\n * const setter = defaultDescriptor.set;\n * return {\n * get: defaultDescriptor.get,\n * set(value) {\n * setter.call(this, value);\n * // custom action.\n * },\n * configurable: true,\n * enumerable: true\n * }\n * }\n * }\n * ```\n *\n * @nocollapse\n * @category properties\n */\n protected static getPropertyDescriptor(\n name: PropertyKey,\n key: string | symbol,\n options: PropertyDeclaration\n ): PropertyDescriptor | undefined {\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(): any {\n return (this as {[key: string]: unknown})[key as string];\n },\n set(this: ReactiveElement, value: unknown) {\n const oldValue = (this as {} as {[key: string]: unknown})[\n name as string\n ];\n (this as {} as {[key: string]: unknown})[key as string] = value;\n (this as unknown as ReactiveElement).requestUpdate(\n name,\n oldValue,\n options\n );\n },\n configurable: true,\n enumerable: true,\n };\n }\n\n /**\n * Returns the property options associated with the given property.\n * These options are defined with a `PropertyDeclaration` via the `properties`\n * object or the `@property` decorator and are registered in\n * `createProperty(...)`.\n *\n * Note, this method should be considered \"final\" and not overridden. To\n * customize the options for a given property, override\n * {@linkcode createProperty}.\n *\n * @nocollapse\n * @final\n * @category properties\n */\n static getPropertyOptions(name: PropertyKey) {\n return this.elementProperties.get(name) || defaultPropertyDeclaration;\n }\n\n /**\n * Creates property accessors for registered properties, sets up element\n * styling, and ensures any superclasses are also finalized. Returns true if\n * the element was finalized.\n * @nocollapse\n */\n protected static finalize() {\n if (this.hasOwnProperty(finalized)) {\n return false;\n }\n this[finalized] = true;\n // finalize any superclasses\n const superCtor = Object.getPrototypeOf(this) as typeof ReactiveElement;\n superCtor.finalize();\n // Create own set of initializers for this class if any exist on the\n // superclass and copy them down. Note, for a small perf boost, avoid\n // creating initializers unless needed.\n if (superCtor._initializers !== undefined) {\n this._initializers = [...superCtor._initializers];\n }\n this.elementProperties = new Map(superCtor.elementProperties);\n // initialize Map populated in observedAttributes\n this.__attributeToPropertyMap = new Map();\n // make any properties\n // Note, only process \"own\" properties since this element will inherit\n // any properties defined on the superClass, and finalization ensures\n // the entire prototype chain is finalized.\n if (this.hasOwnProperty(JSCompiler_renameProperty('properties', this))) {\n const props = this.properties;\n // support symbols in properties (IE11 does not support this)\n const propKeys = [\n ...Object.getOwnPropertyNames(props),\n ...Object.getOwnPropertySymbols(props),\n ];\n // This for/of is ok because propKeys is an array\n for (const p of propKeys) {\n // note, use of `any` is due to TypeScript lack of support for symbol in\n // index types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.createProperty(p, (props as any)[p]);\n }\n }\n this.elementStyles = this.finalizeStyles(this.styles);\n // DEV mode warnings\n if (DEV_MODE) {\n const warnRemovedOrRenamed = (name: string, renamed = false) => {\n if (this.prototype.hasOwnProperty(name)) {\n issueWarning(\n renamed ? 'renamed-api' : 'removed-api',\n `\\`${name}\\` is implemented on class ${this.name}. It ` +\n `has been ${renamed ? 'renamed' : 'removed'} ` +\n `in this version of LitElement.`\n );\n }\n };\n warnRemovedOrRenamed('initialize');\n warnRemovedOrRenamed('requestUpdateInternal');\n warnRemovedOrRenamed('_getUpdateComplete', true);\n }\n return true;\n }\n\n /**\n * Options used when calling `attachShadow`. Set this property to customize\n * the options for the shadowRoot; for example, to create a closed\n * shadowRoot: `{mode: 'closed'}`.\n *\n * Note, these options are used in `createRenderRoot`. If this method\n * is customized, options should be respected if possible.\n * @nocollapse\n * @category rendering\n */\n static shadowRootOptions: ShadowRootInit = {mode: 'open'};\n\n /**\n * Takes the styles the user supplied via the `static styles` property and\n * returns the array of styles to apply to the element.\n * Override this method to integrate into a style management system.\n *\n * Styles are deduplicated preserving the _last_ instance in the list. This\n * is a performance optimization to avoid duplicated styles that can occur\n * especially when composing via subclassing. The last item is kept to try\n * to preserve the cascade order with the assumption that it's most important\n * that last added styles override previous styles.\n *\n * @nocollapse\n * @category styles\n */\n protected static finalizeStyles(\n styles?: CSSResultGroup\n ): Array<CSSResultOrNative> {\n const elementStyles = [];\n if (Array.isArray(styles)) {\n // Dedupe the flattened array in reverse order to preserve the last items.\n // Casting to Array<unknown> works around TS error that\n // appears to come from trying to flatten a type CSSResultArray.\n const set = new Set((styles as Array<unknown>).flat(Infinity).reverse());\n // Then preserve original order by adding the set items in reverse order.\n for (const s of set) {\n elementStyles.unshift(getCompatibleStyle(s as CSSResultOrNative));\n }\n } else if (styles !== undefined) {\n elementStyles.push(getCompatibleStyle(styles));\n }\n return elementStyles;\n }\n\n /**\n * Node or ShadowRoot into which element DOM should be rendered. Defaults\n * to an open shadowRoot.\n * @category rendering\n */\n readonly renderRoot!: HTMLElement | ShadowRoot;\n\n /**\n * Returns the property name for the given attribute `name`.\n * @nocollapse\n */\n private static __attributeNameForProperty(\n name: PropertyKey,\n options: PropertyDeclaration\n ) {\n const attribute = options.attribute;\n return attribute === false\n ? undefined\n : typeof attribute === 'string'\n ? attribute\n : typeof name === 'string'\n ? name.toLowerCase()\n : undefined;\n }\n\n private __instanceProperties?: PropertyValues = new Map();\n // Initialize to an unresolved Promise so we can make sure the element has\n // connected before first update.\n private __updatePromise!: Promise<boolean>;\n\n /**\n * True if there is a pending update as a result of calling `requestUpdate()`.\n * Should only be read.\n * @category updates\n */\n isUpdatePending = false;\n\n /**\n * Is set to `true` after the first update. The element code cannot assume\n * that `renderRoot` exists before the element `hasUpdated`.\n * @category updates\n */\n hasUpdated = false;\n\n /**\n * Map with keys for any properties that have changed since the last\n * update cycle with previous values.\n *\n * @internal\n */\n _$changedProperties!: PropertyValues;\n\n /**\n * Map with keys of properties that should be reflected when updated.\n */\n private __reflectingProperties?: Map<PropertyKey, PropertyDeclaration>;\n\n /**\n * Name of currently reflecting property\n */\n private __reflectingProperty: PropertyKey | null = null;\n\n /**\n * Set of controllers.\n */\n private __controllers?: ReactiveController[];\n\n constructor() {\n super();\n this.__initialize();\n }\n\n /**\n * Internal only override point for customizing work done when elements\n * are constructed.\n */\n private __initialize() {\n this.__updatePromise = new Promise<boolean>(\n (res) => (this.enableUpdating = res)\n );\n this._$changedProperties = new Map();\n this.__saveInstanceProperties();\n // ensures first update will be caught by an early access of\n // `updateComplete`\n this.requestUpdate();\n (this.constructor as typeof ReactiveElement)._initializers?.forEach((i) =>\n i(this)\n );\n }\n\n /**\n * Registers a `ReactiveController` to participate in the element's reactive\n * update cycle. The element automatically calls into any registered\n * controllers during its lifecycle callbacks.\n *\n * If the element is connected when `addController()` is called, the\n * controller's `hostConnected()` callback will be immediately called.\n * @category controllers\n */\n addController(controller: ReactiveController) {\n (this.__controllers ??= []).push(controller);\n // If a controller is added after the element has been connected,\n // call hostConnected. Note, re-using existence of `renderRoot` here\n // (which is set in connectedCallback) to avoid the need to track a\n // first connected state.\n if (this.renderRoot !== undefined && this.isConnected) {\n controller.hostConnected?.();\n }\n }\n\n /**\n * Removes a `ReactiveController` from the element.\n * @category controllers\n */\n removeController(controller: ReactiveController) {\n // Note, if the indexOf is -1, the >>> will flip the sign which makes the\n // splice do nothing.\n this.__controllers?.splice(this.__controllers.indexOf(controller) >>> 0, 1);\n }\n\n /**\n * Fixes any properties set on the instance before upgrade time.\n * Otherwise these would shadow the accessor and break these properties.\n * The properties are stored in a Map which is played back after the\n * constructor runs. Note, on very old versions of Safari (<=9) or Chrome\n * (<=41), properties created for native platform properties like (`id` or\n * `name`) may not have default values set in the element constructor. On\n * these browsers native properties appear on instances and therefore their\n * default value will overwrite any element default (e.g. if the element sets\n * this.id = 'id' in the constructor, the 'id' will become '' since this is\n * the native platform default).\n */\n private __saveInstanceProperties() {\n // Use forEach so this works even if for/of loops are compiled to for loops\n // expecting arrays\n (this.constructor as typeof ReactiveElement).elementProperties.forEach(\n (_v, p) => {\n if (this.hasOwnProperty(p)) {\n this.__instanceProperties!.set(p, this[p as keyof this]);\n delete this[p as keyof this];\n }\n }\n );\n }\n\n /**\n * Returns the node into which the element should render and by default\n * creates and returns an open shadowRoot. Implement to customize where the\n * element's DOM is rendered. For example, to render into the element's\n * childNodes, return `this`.\n *\n * @return Returns a node into which to render.\n * @category rendering\n */\n protected createRenderRoot(): Element | ShadowRoot {\n const renderRoot =\n this.shadowRoot ??\n this.attachShadow(\n (this.constructor as typeof ReactiveElement).shadowRootOptions\n );\n adoptStyles(\n renderRoot,\n (this.constructor as typeof ReactiveElement).elementStyles\n );\n return renderRoot;\n }\n\n /**\n * On first connection, creates the element's renderRoot, sets up\n * element styling, and enables updating.\n * @category lifecycle\n */\n connectedCallback() {\n // create renderRoot before first update.\n if (this.renderRoot === undefined) {\n (\n this as {\n renderRoot: Element | DocumentFragment;\n }\n ).renderRoot = this.createRenderRoot();\n }\n this.enableUpdating(true);\n this.__controllers?.forEach((c) => c.hostConnected?.());\n }\n\n /**\n * Note, this method should be considered final and not overridden. It is\n * overridden on the element instance with a function that triggers the first\n * update.\n * @category updates\n */\n protected enableUpdating(_requestedUpdate: boolean) {}\n\n /**\n * Allows for `super.disconnectedCallback()` in extensions while\n * reserving the possibility of making non-breaking feature additions\n * when disconnecting at some point in the future.\n * @category lifecycle\n */\n disconnectedCallback() {\n this.__controllers?.forEach((c) => c.hostDisconnected?.());\n }\n\n /**\n * Synchronizes property values when attributes change.\n *\n * Specifically, when an attribute is set, the corresponding property is set.\n * You should rarely need to implement this callback. If this method is\n * overridden, `super.attributeChangedCallback(name, _old, value)` must be\n * called.\n *\n * See [using the lifecycle callbacks](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#using_the_lifecycle_callbacks)\n * on MDN for more information about the `attributeChangedCallback`.\n * @category attributes\n */\n attributeChangedCallback(\n name: string,\n _old: string | null,\n value: string | null\n ) {\n this._$attributeToProperty(name, value);\n }\n\n private __propertyToAttribute(\n name: PropertyKey,\n value: unknown,\n options: PropertyDeclaration = defaultPropertyDeclaration\n ) {\n const attr = (\n this.constructor as typeof ReactiveElement\n ).__attributeNameForProperty(name, options);\n if (attr !== undefined && options.reflect === true) {\n const converter =\n (options.converter as ComplexAttributeConverter)?.toAttribute !==\n undefined\n ? (options.converter as ComplexAttributeConverter)\n : defaultConverter;\n const attrValue = converter.toAttribute!(value, options.type);\n if (\n DEV_MODE &&\n (this.constructor as typeof ReactiveElement).enabledWarnings!.indexOf(\n 'migration'\n ) >= 0 &&\n attrValue === undefined\n ) {\n issueWarning(\n 'undefined-attribute-value',\n `The attribute value for the ${name as string} property is ` +\n `undefined on element ${this.localName}. The attribute will be ` +\n `removed, but in the previous version of \\`ReactiveElement\\`, ` +\n `the attribute would not have changed.`\n );\n }\n // Track if the property is being reflected to avoid\n // setting the property again via `attributeChangedCallback`. Note:\n // 1. this takes advantage of the fact that the callback is synchronous.\n // 2. will behave incorrectly if multiple attributes are in the reaction\n // stack at time of calling. However, since we process attributes\n // in `update` this should not be possible (or an extreme corner case\n // that we'd like to discover).\n // mark state reflecting\n this.__reflectingProperty = name;\n if (attrValue == null) {\n this.removeAttribute(attr);\n } else {\n this.setAttribute(attr, attrValue as string);\n }\n // mark state not reflecting\n this.__reflectingProperty = null;\n }\n }\n\n /** @internal */\n _$attributeToProperty(name: string, value: string | null) {\n const ctor = this.constructor as typeof ReactiveElement;\n // Note, hint this as an `AttributeMap` so closure clearly understands\n // the type; it has issues with tracking types through statics\n const propName = (ctor.__attributeToPropertyMap as AttributeMap).get(name);\n // Use tracking info to avoid reflecting a property value to an attribute\n // if it was just set because the attribute changed.\n if (propName !== undefined && this.__reflectingProperty !== propName) {\n const options = ctor.getPropertyOptions(propName);\n const converter =\n typeof options.converter === 'function'\n ? {fromAttribute: options.converter}\n : options.converter?.fromAttribute !== undefined\n ? options.converter\n : defaultConverter;\n // mark state reflecting\n this.__reflectingProperty = propName;\n this[propName as keyof this] = converter.fromAttribute!(\n value,\n options.type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ) as any;\n // mark state not reflecting\n this.__reflectingProperty = null;\n }\n }\n\n /**\n * Requests an update which is processed asynchronously. This should be called\n * when an element should update based on some state not triggered by setting\n * a reactive property. In this case, pass no arguments. It should also be\n * called when manually implementing a property setter. In this case, pass the\n * property `name` and `oldValue` to ensure that any configured property\n * options are honored.\n *\n * @param name name of requesting property\n * @param oldValue old value of requesting property\n * @param options property options to use instead of the previously\n * configured options\n * @category updates\n */\n requestUpdate(\n name?: PropertyKey,\n oldValue?: unknown,\n options?: PropertyDeclaration\n ): void {\n let shouldRequestUpdate = true;\n // If we have a property key, perform property update steps.\n if (name !== undefined) {\n options =\n options ||\n (this.constructor as typeof ReactiveElement).getPropertyOptions(name);\n const hasChanged = options.hasChanged || notEqual;\n if (hasChanged(this[name as keyof this], oldValue)) {\n if (!this._$changedProperties.has(name)) {\n this._$changedProperties.set(name, oldValue);\n }\n // Add to reflecting properties set.\n // Note, it's important that every change has a chance to add the\n // property to `_reflectingProperties`. This ensures setting\n // attribute + property reflects correctly.\n if (options.reflect === true && this.__reflectingProperty !== name) {\n if (this.__reflectingProperties === undefined) {\n this.__reflectingProperties = new Map();\n }\n this.__reflectingProperties.set(name, options);\n }\n } else {\n // Abort the request if the property should not be considered changed.\n shouldRequestUpdate = false;\n }\n }\n if (!this.isUpdatePending && shouldRequestUpdate) {\n this.__updatePromise = this.__enqueueUpdate();\n }\n // Note, since this no longer returns a promise, in dev mode we return a\n // thenable which warns if it's called.\n return DEV_MODE\n ? (requestUpdateThenable(this.localName) as unknown as void)\n : undefined;\n }\n\n /**\n * Sets up the element to asynchronously update.\n */\n private async __enqueueUpdate() {\n this.isUpdatePending = true;\n try {\n // Ensure any previous update has resolved before updating.\n // This `await` also ensures that property changes are batched.\n await this.__updatePromise;\n } catch (e) {\n // Refire any previous errors async so they do not disrupt the update\n // cycle. Errors are refired so developers have a chance to observe\n // them, and this can be done by implementing\n // `window.onunhandledrejection`.\n Promise.reject(e);\n }\n const result = this.scheduleUpdate();\n // If `scheduleUpdate` returns a Promise, we await it. This is done to\n // enable coordinating updates with a scheduler. Note, the result is\n // checked to avoid delaying an additional microtask unless we need to.\n if (result != null) {\n await result;\n }\n return !this.isUpdatePending;\n }\n\n /**\n * Schedules an element update. You can override this method to change the\n * timing of updates by returning a Promise. The update will await the\n * returned Promise, and you should resolve the Promise to allow the update\n * to proceed. If this method is overridden, `super.scheduleUpdate()`\n * must be called.\n *\n * For instance, to schedule updates to occur just before the next frame:\n *\n * ```ts\n * override protected async scheduleUpdate(): Promise<unknown> {\n * await new Promise((resolve) => requestAnimationFrame(() => resolve()));\n * super.scheduleUpdate();\n * }\n * ```\n * @category updates\n */\n protected scheduleUpdate(): void | Promise<unknown> {\n return this.performUpdate();\n }\n\n /**\n * Performs an element update. Note, if an exception is thrown during the\n * update, `firstUpdated` and `updated` will not be called.\n *\n * Call `performUpdate()` to immediately process a pending update. This should\n * generally not be needed, but it can be done in rare cases when you need to\n * update synchronously.\n *\n * Note: To ensure `performUpdate()` synchronously completes a pending update,\n * it should not be overridden. In LitElement 2.x it was suggested to override\n * `performUpdate()` to also customizing update scheduling. Instead, you should now\n * override `scheduleUpdate()`. For backwards compatibility with LitElement 2.x,\n * scheduling updates via `performUpdate()` continues to work, but will make\n * also calling `performUpdate()` to synchronously process updates difficult.\n *\n * @category updates\n */\n protected performUpdate(): void | Promise<unknown> {\n // Abort any update if one is not pending when this is called.\n // This can happen if `performUpdate` is called early to \"flush\"\n // the update.\n if (!this.isUpdatePending) {\n return;\n }\n debugLogEvent?.({kind: 'update'});\n // create renderRoot before first update.\n if (!this.hasUpdated) {\n // Produce warning if any class properties are shadowed by class fields\n if (DEV_MODE) {\n const shadowedProperties: string[] = [];\n (\n this.constructor as typeof ReactiveElement\n ).__reactivePropertyKeys?.forEach((p) => {\n if (this.hasOwnProperty(p) && !this.__instanceProperties?.has(p)) {\n shadowedProperties.push(p as string);\n }\n });\n if (shadowedProperties.length) {\n throw new Error(\n `The following properties on element ${this.localName} will not ` +\n `trigger updates as expected because they are set using class ` +\n `fields: ${shadowedProperties.join(', ')}. ` +\n `Native class fields and some compiled output will overwrite ` +\n `accessors used for detecting changes. See ` +\n `https://lit.dev/msg/class-field-shadowing ` +\n `for more information.`\n );\n }\n }\n }\n // Mixin instance properties once, if they exist.\n if (this.__instanceProperties) {\n // Use forEach so this works even if for/of loops are compiled to for loops\n // expecting arrays\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.__instanceProperties!.forEach((v, p) => ((this as any)[p] = v));\n this.__instanceProperties = undefined;\n }\n let shouldUpdate = false;\n const changedProperties = this._$changedProperties;\n try {\n shouldUpdate = this.shouldUpdate(changedProperties);\n if (shouldUpdate) {\n this.willUpdate(changedProperties);\n this.__controllers?.forEach((c) => c.hostUpdate?.());\n this.update(changedProperties);\n } else {\n this.__markUpdated();\n }\n } catch (e) {\n // Prevent `firstUpdated` and `updated` from running when there's an\n // update exception.\n shouldUpdate = false;\n // Ensure element can accept additional updates after an exception.\n this.__markUpdated();\n throw e;\n }\n // The update is no longer considered pending and further updates are now allowed.\n if (shouldUpdate) {\n this._$didUpdate(changedProperties);\n }\n }\n\n /**\n * Invoked before `update()` to compute values needed during the update.\n *\n * Implement `willUpdate` to compute property values that depend on other\n * properties and are used in the rest of the update process.\n *\n * ```ts\n * willUpdate(changedProperties) {\n * // only need to check changed properties for an expensive computation.\n * if (changedProperties.has('firstName') || changedProperties.has('lastName')) {\n * this.sha = computeSHA(`${this.firstName} ${this.lastName}`);\n * }\n * }\n *\n * render() {\n * return html`SHA: ${this.sha}`;\n * }\n * ```\n *\n * @category updates\n */\n protected willUpdate(_changedProperties: PropertyValues): void {}\n\n // Note, this is an override point for polyfill-support.\n // @internal\n _$didUpdate(changedProperties: PropertyValues) {\n this.__controllers?.forEach((c) => c.hostUpdated?.());\n if (!this.hasUpdated) {\n this.hasUpdated = true;\n this.firstUpdated(changedProperties);\n }\n this.updated(changedProperties);\n if (\n DEV_MODE &&\n this.isUpdatePending &&\n (this.constructor as typeof ReactiveElement).enabledWarnings!.indexOf(\n 'change-in-update'\n ) >= 0\n ) {\n issueWarning(\n 'change-in-update',\n `Element ${this.localName} scheduled an update ` +\n `(generally because a property was set) ` +\n `after an update completed, causing a new update to be scheduled. ` +\n `This is inefficient and should be avoided unless the next update ` +\n `can only be scheduled as a side effect of the previous update.`\n );\n }\n }\n\n private __markUpdated() {\n this._$changedProperties = new Map();\n this.isUpdatePending = false;\n }\n\n /**\n * Returns a Promise that resolves when the element has completed updating.\n * The Promise value is a boolean that is `true` if the element completed the\n * update without triggering another update. The Promise result is `false` if\n * a property was set inside `updated()`. If the Promise is rejected, an\n * exception was thrown during the update.\n *\n * To await additional asynchronous work, override the `getUpdateComplete`\n * method. For example, it is sometimes useful to await a rendered element\n * before fulfilling this Promise. To do this, first await\n * `super.getUpdateComplete()`, then any subsequent state.\n *\n * @return A promise of a boolean that resolves to true if the update completed\n * without triggering another update.\n * @category updates\n */\n get updateComplete(): Promise<boolean> {\n return this.getUpdateComplete();\n }\n\n /**\n * Override point for the `updateComplete` promise.\n *\n * It is not safe to override the `updateComplete` getter directly due to a\n * limitation in TypeScript which means it is not possible to call a\n * superclass getter (e.g. `super.updateComplete.then(...)`) when the target\n * language is ES5 (https://github.com/microsoft/TypeScript/issues/338).\n * This method should be overridden instead. For example:\n *\n * ```ts\n * class MyElement extends LitElement {\n * override async getUpdateComplete() {\n * const result = await super.getUpdateComplete();\n * await this._myChild.updateComplete;\n * return result;\n * }\n * }\n * ```\n *\n * @return A promise of a boolean that resolves to true if the update completed\n * without triggering another update.\n * @category updates\n */\n protected getUpdateComplete(): Promise<boolean> {\n return this.__updatePromise;\n }\n\n /**\n * Controls whether or not `update()` should be called when the element requests\n * an update. By default, this method always returns `true`, but this can be\n * customized to control when to update.\n *\n * @param _changedProperties Map of changed properties with old values\n * @category updates\n */\n protected shouldUpdate(_changedProperties: PropertyValues): boolean {\n return true;\n }\n\n /**\n * Updates the element. This method reflects property values to attributes.\n * It can be overridden to render and keep updated element DOM.\n * Setting properties inside this method will *not* trigger\n * another update.\n *\n * @param _changedProperties Map of changed properties with old values\n * @category updates\n */\n protected update(_changedProperties: PropertyValues) {\n if (this.__reflectingProperties !== undefined) {\n // Use forEach so this works even if for/of loops are compiled to for\n // loops expecting arrays\n this.__reflectingProperties.forEach((v, k) =>\n this.__propertyToAttribute(k, this[k as keyof this], v)\n );\n this.__reflectingProperties = undefined;\n }\n this.__markUpdated();\n }\n\n /**\n * Invoked whenever the element is updated. Implement to perform\n * post-updating tasks via DOM APIs, for example, focusing an element.\n *\n * Setting properties inside this method will trigger the element to update\n * again after this update cycle completes.\n *\n * @param _changedProperties Map of changed properties with old values\n * @category updates\n */\n protected updated(_changedProperties: PropertyValues) {}\n\n /**\n * Invoked when the element is first updated. Implement to perform one time\n * work on the element after update.\n *\n * ```ts\n * firstUpdated() {\n * this.renderRoot.getElementById('my-text-area').focus();\n * }\n * ```\n *\n * Setting properties inside this method will trigger the element to update\n * again after this update cycle completes.\n *\n * @param _changedProperties Map of changed properties with old values\n * @category updates\n */\n protected firstUpdated(_changedProperties: PropertyValues) {}\n}\n\n// Apply polyfills if available\npolyfillSupport?.({ReactiveElement});\n\n// Dev mode warnings...\nif (DEV_MODE) {\n // Default warning set.\n ReactiveElement.enabledWarnings = ['change-in-update'];\n const ensureOwnWarnings = function (ctor: typeof ReactiveElement) {\n if (\n !ctor.hasOwnProperty(JSCompiler_renameProperty('enabledWarnings', ctor))\n ) {\n ctor.enabledWarnings = ctor.enabledWarnings!.slice();\n }\n };\n ReactiveElement.enableWarning = function (\n this: typeof ReactiveElement,\n warning: WarningKind\n ) {\n ensureOwnWarnings(this);\n if (this.enabledWarnings!.indexOf(warning) < 0) {\n this.enabledWarnings!.push(warning);\n }\n };\n ReactiveElement.disableWarning = function (\n this: typeof ReactiveElement,\n warning: WarningKind\n ) {\n ensureOwnWarnings(this);\n const i = this.enabledWarnings!.indexOf(warning);\n if (i >= 0) {\n this.enabledWarnings!.splice(i, 1);\n }\n };\n}\n\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for ReactiveElement usage.\n(global.reactiveElementVersions ??= []).push('1.6.3');\nif (DEV_MODE && global.reactiveElementVersions.length > 1) {\n issueWarning!(\n 'multiple-versions',\n `Multiple versions of Lit loaded. Loading multiple versions ` +\n `is not recommended.`\n );\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n// IMPORTANT: these imports must be type-only\nimport type {Directive, DirectiveResult, PartInfo} from './directive.js';\n\nconst DEV_MODE = true;\nconst ENABLE_EXTRA_SECURITY_HOOKS = true;\nconst ENABLE_SHADYDOM_NOPATCH = true;\nconst NODE_MODE = false;\n// Use window for browser builds because IE11 doesn't have globalThis.\nconst global = NODE_MODE ? globalThis : window;\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace LitUnstable {\n /**\n * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n * we will emit 'lit-debug' events to window, with live details about the update and render\n * lifecycle. These can be useful for writing debug tooling and visualizations.\n *\n * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n * making certain operations that are normally very cheap (like a no-op render) much slower,\n * because we must copy data and dispatch events.\n */\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace DebugLog {\n export type Entry =\n | TemplatePrep\n | TemplateInstantiated\n | TemplateInstantiatedAndUpdated\n | TemplateUpdating\n | BeginRender\n | EndRender\n | CommitPartEntry\n | SetPartValue;\n export interface TemplatePrep {\n kind: 'template prep';\n template: Template;\n strings: TemplateStringsArray;\n clonableTemplate: HTMLTemplateElement;\n parts: TemplatePart[];\n }\n export interface BeginRender {\n kind: 'begin render';\n id: number;\n value: unknown;\n container: HTMLElement | DocumentFragment;\n options: RenderOptions | undefined;\n part: ChildPart | undefined;\n }\n export interface EndRender {\n kind: 'end render';\n id: number;\n value: unknown;\n container: HTMLElement | DocumentFragment;\n options: RenderOptions | undefined;\n part: ChildPart;\n }\n export interface TemplateInstantiated {\n kind: 'template instantiated';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n fragment: Node;\n parts: Array<Part | undefined>;\n values: unknown[];\n }\n export interface TemplateInstantiatedAndUpdated {\n kind: 'template instantiated and updated';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n fragment: Node;\n parts: Array<Part | undefined>;\n values: unknown[];\n }\n export interface TemplateUpdating {\n kind: 'template updating';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n parts: Array<Part | undefined>;\n values: unknown[];\n }\n export interface SetPartValue {\n kind: 'set part';\n part: Part;\n value: unknown;\n valueIndex: number;\n values: unknown[];\n templateInstance: TemplateInstance;\n }\n\n export type CommitPartEntry =\n | CommitNothingToChildEntry\n | CommitText\n | CommitNode\n | CommitAttribute\n | CommitProperty\n | CommitBooleanAttribute\n | CommitEventListener\n | CommitToElementBinding;\n\n export interface CommitNothingToChildEntry {\n kind: 'commit nothing to child';\n start: ChildNode;\n end: ChildNode | null;\n parent: Disconnectable | undefined;\n options: RenderOptions | undefined;\n }\n\n export interface CommitText {\n kind: 'commit text';\n node: Text;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitNode {\n kind: 'commit node';\n start: Node;\n parent: Disconnectable | undefined;\n value: Node;\n options: RenderOptions | undefined;\n }\n\n export interface CommitAttribute {\n kind: 'commit attribute';\n element: Element;\n name: string;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitProperty {\n kind: 'commit property';\n element: Element;\n name: string;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitBooleanAttribute {\n kind: 'commit boolean attribute';\n element: Element;\n name: string;\n value: boolean;\n options: RenderOptions | undefined;\n }\n\n export interface CommitEventListener {\n kind: 'commit event listener';\n element: Element;\n name: string;\n value: unknown;\n oldListener: unknown;\n options: RenderOptions | undefined;\n // True if we're removing the old event listener (e.g. because settings changed, or value is nothing)\n removeListener: boolean;\n // True if we're adding a new event listener (e.g. because first render, or settings changed)\n addListener: boolean;\n }\n\n export interface CommitToElementBinding {\n kind: 'commit to element binding';\n element: Element;\n value: unknown;\n options: RenderOptions | undefined;\n }\n }\n}\n\ninterface DebugLoggingWindow {\n // Even in dev mode, we generally don't want to emit these events, as that's\n // another level of cost, so only emit them when DEV_MODE is true _and_ when\n // window.emitLitDebugEvents is true.\n emitLitDebugLogEvents?: boolean;\n}\n\n/**\n * Useful for visualizing and logging insights into what the Lit template system is doing.\n *\n * Compiled out of prod mode builds.\n */\nconst debugLogEvent = DEV_MODE\n ? (event: LitUnstable.DebugLog.Entry) => {\n const shouldEmit = (global as unknown as DebugLoggingWindow)\n .emitLitDebugLogEvents;\n if (!shouldEmit) {\n return;\n }\n global.dispatchEvent(\n new CustomEvent<LitUnstable.DebugLog.Entry>('lit-debug', {\n detail: event,\n })\n );\n }\n : undefined;\n// Used for connecting beginRender and endRender events when there are nested\n// renders when errors are thrown preventing an endRender event from being\n// called.\nlet debugLogRenderId = 0;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nif (DEV_MODE) {\n global.litIssuedWarnings ??= new Set();\n\n // Issue a warning, if we haven't already.\n issueWarning = (code: string, warning: string) => {\n warning += code\n ? ` See https://lit.dev/msg/${code} for more information.`\n : '';\n if (!global.litIssuedWarnings!.has(warning)) {\n console.warn(warning);\n global.litIssuedWarnings!.add(warning);\n }\n };\n\n issueWarning(\n 'dev-mode',\n `Lit is in dev mode. Not recommended for production!`\n );\n}\n\nconst wrap =\n ENABLE_SHADYDOM_NOPATCH &&\n global.ShadyDOM?.inUse &&\n global.ShadyDOM?.noPatch === true\n ? global.ShadyDOM!.wrap\n : (node: Node) => node;\n\nconst trustedTypes = (global as unknown as Partial<Window>).trustedTypes;\n\n/**\n * Our TrustedTypePolicy for HTML which is declared using the html template\n * tag function.\n *\n * That HTML is a developer-authored constant, and is parsed with innerHTML\n * before any untrusted expressions have been mixed in. Therefor it is\n * considered safe by construction.\n */\nconst policy = trustedTypes\n ? trustedTypes.createPolicy('lit-html', {\n createHTML: (s) => s,\n })\n : undefined;\n\n/**\n * Used to sanitize any value before it is written into the DOM. This can be\n * used to implement a security policy of allowed and disallowed values in\n * order to prevent XSS attacks.\n *\n * One way of using this callback would be to check attributes and properties\n * against a list of high risk fields, and require that values written to such\n * fields be instances of a class which is safe by construction. Closure's Safe\n * HTML Types is one implementation of this technique (\n * https://github.com/google/safe-html-types/blob/master/doc/safehtml-types.md).\n * The TrustedTypes polyfill in API-only mode could also be used as a basis\n * for this technique (https://github.com/WICG/trusted-types).\n *\n * @param node The HTML node (usually either a #text node or an Element) that\n * is being written to. Note that this is just an exemplar node, the write\n * may take place against another instance of the same class of node.\n * @param name The name of an attribute or property (for example, 'href').\n * @param type Indicates whether the write that's about to be performed will\n * be to a property or a node.\n * @return A function that will sanitize this class of writes.\n */\nexport type SanitizerFactory = (\n node: Node,\n name: string,\n type: 'property' | 'attribute'\n) => ValueSanitizer;\n\n/**\n * A function which can sanitize values that will be written to a specific kind\n * of DOM sink.\n *\n * See SanitizerFactory.\n *\n * @param value The value to sanitize. Will be the actual value passed into\n * the lit-html template literal, so this could be of any type.\n * @return The value to write to the DOM. Usually the same as the input value,\n * unless sanitization is needed.\n */\nexport type ValueSanitizer = (value: unknown) => unknown;\n\nconst identityFunction: ValueSanitizer = (value: unknown) => value;\nconst noopSanitizer: SanitizerFactory = (\n _node: Node,\n _name: string,\n _type: 'property' | 'attribute'\n) => identityFunction;\n\n/** Sets the global sanitizer factory. */\nconst setSanitizer = (newSanitizer: SanitizerFactory) => {\n if (!ENABLE_EXTRA_SECURITY_HOOKS) {\n return;\n }\n if (sanitizerFactoryInternal !== noopSanitizer) {\n throw new Error(\n `Attempted to overwrite existing lit-html security policy.` +\n ` setSanitizeDOMValueFactory should be called at most once.`\n );\n }\n sanitizerFactoryInternal = newSanitizer;\n};\n\n/**\n * Only used in internal tests, not a part of the public API.\n */\nconst _testOnlyClearSanitizerFactoryDoNotCallOrElse = () => {\n sanitizerFactoryInternal = noopSanitizer;\n};\n\nconst createSanitizer: SanitizerFactory = (node, name, type) => {\n return sanitizerFactoryInternal(node, name, type);\n};\n\n// Added to an attribute name to mark the attribute as bound so we can find\n// it easily.\nconst boundAttributeSuffix = '$lit$';\n\n// This marker is used in many syntactic positions in HTML, so it must be\n// a valid element name and attribute name. We don't support dynamic names (yet)\n// but this at least ensures that the parse tree is closer to the template\n// intention.\nconst marker = `lit$${String(Math.random()).slice(9)}$`;\n\n// String used to tell if a comment is a marker comment\nconst markerMatch = '?' + marker;\n\n// Text used to insert a comment marker node. We use processing instruction\n// syntax because it's slightly smaller, but parses as a comment node.\nconst nodeMarker = `<${markerMatch}>`;\n\nconst d =\n NODE_MODE && global.document === undefined\n ? ({\n createTreeWalker() {\n return {};\n },\n } as unknown as Document)\n : document;\n\n// Creates a dynamic marker. We never have to search for these in the DOM.\nconst createMarker = () => d.createComment('');\n\n// https://tc39.github.io/ecma262/#sec-typeof-operator\ntype Primitive = null | undefined | boolean | number | string | symbol | bigint;\nconst isPrimitive = (value: unknown): value is Primitive =>\n value === null || (typeof value != 'object' && typeof value != 'function');\nconst isArray = Array.isArray;\nconst isIterable = (value: unknown): value is Iterable<unknown> =>\n isArray(value) ||\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (value as any)?.[Symbol.iterator] === 'function';\n\nconst SPACE_CHAR = `[ \\t\\n\\f\\r]`;\nconst ATTR_VALUE_CHAR = `[^ \\t\\n\\f\\r\"'\\`<>=]`;\nconst NAME_CHAR = `[^\\\\s\"'>=/]`;\n\n// These regexes represent the five parsing states that we care about in the\n// Template's HTML scanner. They match the *end* of the state they're named\n// after.\n// Depending on the match, we transition to a new state. If there's no match,\n// we stay in the same state.\n// Note that the regexes are stateful. We utilize lastIndex and sync it\n// across the multiple regexes used. In addition to the five regexes below\n// we also dynamically create a regex to find the matching end tags for raw\n// text elements.\n\n/**\n * End of text is: `<` followed by:\n * (comment start) or (tag) or (dynamic tag binding)\n */\nconst textEndRegex = /<(?:(!--|\\/[^a-zA-Z])|(\\/?[a-zA-Z][^>\\s]*)|(\\/?$))/g;\nconst COMMENT_START = 1;\nconst TAG_NAME = 2;\nconst DYNAMIC_TAG_NAME = 3;\n\nconst commentEndRegex = /-->/g;\n/**\n * Comments not started with <!--, like </{, can be ended by a single `>`\n */\nconst comment2EndRegex = />/g;\n\n/**\n * The tagEnd regex matches the end of the \"inside an opening\" tag syntax\n * position. It either matches a `>`, an attribute-like sequence, or the end\n * of the string after a space (attribute-name position ending).\n *\n * See attributes in the HTML spec:\n * https://www.w3.org/TR/html5/syntax.html#elements-attributes\n *\n * \" \\t\\n\\f\\r\" are HTML space characters:\n * https://infra.spec.whatwg.org/#ascii-whitespace\n *\n * So an attribute is:\n * * The name: any character except a whitespace character, (\"), ('), \">\",\n * \"=\", or \"/\". Note: this is different from the HTML spec which also excludes control characters.\n * * Followed by zero or more space characters\n * * Followed by \"=\"\n * * Followed by zero or more space characters\n * * Followed by:\n * * Any character except space, ('), (\"), \"<\", \">\", \"=\", (`), or\n * * (\") then any non-(\"), or\n * * (') then any non-(')\n */\nconst tagEndRegex = new RegExp(\n `>|${SPACE_CHAR}(?:(${NAME_CHAR}+)(${SPACE_CHAR}*=${SPACE_CHAR}*(?:${ATTR_VALUE_CHAR}|(\"|')|))|$)`,\n 'g'\n);\nconst ENTIRE_MATCH = 0;\nconst ATTRIBUTE_NAME = 1;\nconst SPACES_AND_EQUALS = 2;\nconst QUOTE_CHAR = 3;\n\nconst singleQuoteAttrEndRegex = /'/g;\nconst doubleQuoteAttrEndRegex = /\"/g;\n/**\n * Matches the raw text elements.\n *\n * Comments are not parsed within raw text elements, so we need to search their\n * text content for marker strings.\n */\nconst rawTextElement = /^(?:script|style|textarea|title)$/i;\n\n/** TemplateResult types */\nconst HTML_RESULT = 1;\nconst SVG_RESULT = 2;\n\ntype ResultType = typeof HTML_RESULT | typeof SVG_RESULT;\n\n// TemplatePart types\n// IMPORTANT: these must match the values in PartType\nconst ATTRIBUTE_PART = 1;\nconst CHILD_PART = 2;\nconst PROPERTY_PART = 3;\nconst BOOLEAN_ATTRIBUTE_PART = 4;\nconst EVENT_PART = 5;\nconst ELEMENT_PART = 6;\nconst COMMENT_PART = 7;\n\n/**\n * The return type of the template tag functions, {@linkcode html} and\n * {@linkcode svg}.\n *\n * A `TemplateResult` object holds all the information about a template\n * expression required to render it: the template strings, expression values,\n * and type of template (html or svg).\n *\n * `TemplateResult` objects do not create any DOM on their own. To create or\n * update DOM you need to render the `TemplateResult`. See\n * [Rendering](https://lit.dev/docs/components/rendering) for more information.\n *\n */\nexport type TemplateResult<T extends ResultType = ResultType> = {\n // This property needs to remain unminified.\n ['_$litType$']: T;\n strings: TemplateStringsArray;\n values: unknown[];\n};\n\nexport type HTMLTemplateResult = TemplateResult<typeof HTML_RESULT>;\n\nexport type SVGTemplateResult = TemplateResult<typeof SVG_RESULT>;\n\nexport interface CompiledTemplateResult {\n // This is a factory in order to make template initialization lazy\n // and allow ShadyRenderOptions scope to be passed in.\n // This property needs to remain unminified.\n ['_$litType$']: CompiledTemplate;\n values: unknown[];\n}\n\nexport interface CompiledTemplate extends Omit<Template, 'el'> {\n // el is overridden to be optional. We initialize it on first render\n el?: HTMLTemplateElement;\n\n // The prepared HTML string to create a template element from.\n // The type is a TemplateStringsArray to guarantee that the value came from\n // source code, preventing a JSON injection attack.\n h: TemplateStringsArray;\n}\n\n/**\n * Generates a template literal tag function that returns a TemplateResult with\n * the given result type.\n */\nconst tag =\n <T extends ResultType>(type: T) =>\n (strings: TemplateStringsArray, ...values: unknown[]): TemplateResult<T> => {\n // Warn against templates octal escape sequences\n // We do this here rather than in render so that the warning is closer to the\n // template definition.\n if (DEV_MODE && strings.some((s) => s === undefined)) {\n console.warn(\n 'Some template strings are undefined.\\n' +\n 'This is probably caused by illegal octal escape sequences.'\n );\n }\n return {\n // This property needs to remain unminified.\n ['_$litType$']: type,\n strings,\n values,\n };\n };\n\n/**\n * Interprets a template literal as an HTML template that can efficiently\n * render to and update a container.\n *\n * ```ts\n * const header = (title: string) => html`<h1>${title}</h1>`;\n * ```\n *\n * The `html` tag returns a description of the DOM to render as a value. It is\n * lazy, meaning no work is done until the template is rendered. When rendering,\n * if a template comes from the same expression as a previously rendered result,\n * it's efficiently updated instead of replaced.\n */\nexport const html = tag(HTML_RESULT);\n\n/**\n * Interprets a template literal as an SVG fragment that can efficiently\n * render to and update a container.\n *\n * ```ts\n * const rect = svg`<rect width=\"10\" height=\"10\"></rect>`;\n *\n * const myImage = html`\n * <svg viewBox=\"0 0 10 10\" xmlns=\"http://www.w3.org/2000/svg\">\n * ${rect}\n * </svg>`;\n * ```\n *\n * The `svg` *tag function* should only be used for SVG fragments, or elements\n * that would be contained **inside** an `<svg>` HTML element. A common error is\n * placing an `<svg>` *element* in a template tagged with the `svg` tag\n * function. The `<svg>` element is an HTML element and should be used within a\n * template tagged with the {@linkcode html} tag function.\n *\n * In LitElement usage, it's invalid to return an SVG fragment from the\n * `render()` method, as the SVG fragment will be contained within the element's\n * shadow root and thus cannot be used within an `<svg>` HTML element.\n */\nexport const svg = tag(SVG_RESULT);\n\n/**\n * A sentinel value that signals that a value was handled by a directive and\n * should not be written to the DOM.\n */\nexport const noChange = Symbol.for('lit-noChange');\n\n/**\n * A sentinel value that signals a ChildPart to fully clear its content.\n *\n * ```ts\n * const button = html`${\n * user.isAdmin\n * ? html`<button>DELETE</button>`\n * : nothing\n * }`;\n * ```\n *\n * Prefer using `nothing` over other falsy values as it provides a consistent\n * behavior between various expression binding contexts.\n *\n * In child expressions, `undefined`, `null`, `''`, and `nothing` all behave the\n * same and render no nodes. In attribute expressions, `nothing` _removes_ the\n * attribute, while `undefined` and `null` will render an empty string. In\n * property expressions `nothing` becomes `undefined`.\n */\nexport const nothing = Symbol.for('lit-nothing');\n\n/**\n * The cache of prepared templates, keyed by the tagged TemplateStringsArray\n * and _not_ accounting for the specific template tag used. This means that\n * template tags cannot be dynamic - the must statically be one of html, svg,\n * or attr. This restriction simplifies the cache lookup, which is on the hot\n * path for rendering.\n */\nconst templateCache = new WeakMap<TemplateStringsArray, Template>();\n\n/**\n * Object specifying options for controlling lit-html rendering. Note that\n * while `render` may be called multiple times on the same `container` (and\n * `renderBefore` reference node) to efficiently update the rendered content,\n * only the options passed in during the first render are respected during\n * the lifetime of renders to that unique `container` + `renderBefore`\n * combination.\n */\nexport interface RenderOptions {\n /**\n * An object to use as the `this` value for event listeners. It's often\n * useful to set this to the host component rendering a template.\n */\n host?: object;\n /**\n * A DOM node before which to render content in the container.\n */\n renderBefore?: ChildNode | null;\n /**\n * Node used for cloning the template (`importNode` will be called on this\n * node). This controls the `ownerDocument` of the rendered DOM, along with\n * any inherited context. Defaults to the global `document`.\n */\n creationScope?: {importNode(node: Node, deep?: boolean): Node};\n /**\n * The initial connected state for the top-level part being rendered. If no\n * `isConnected` option is set, `AsyncDirective`s will be connected by\n * default. Set to `false` if the initial render occurs in a disconnected tree\n * and `AsyncDirective`s should see `isConnected === false` for their initial\n * render. The `part.setConnected()` method must be used subsequent to initial\n * render to change the connected state of the part.\n */\n isConnected?: boolean;\n}\n\nconst walker = d.createTreeWalker(\n d,\n 129 /* NodeFilter.SHOW_{ELEMENT|COMMENT} */,\n null,\n false\n);\n\nlet sanitizerFactoryInternal: SanitizerFactory = noopSanitizer;\n\n//\n// Classes only below here, const variable declarations only above here...\n//\n// Keeping variable declarations and classes together improves minification.\n// Interfaces and type aliases can be interleaved freely.\n//\n\n// Type for classes that have a `_directive` or `_directives[]` field, used by\n// `resolveDirective`\nexport interface DirectiveParent {\n _$parent?: DirectiveParent;\n _$isConnected: boolean;\n __directive?: Directive;\n __directives?: Array<Directive | undefined>;\n}\n\nfunction trustFromTemplateString(\n tsa: TemplateStringsArray,\n stringFromTSA: string\n): TrustedHTML {\n // A security check to prevent spoofing of Lit template results.\n // In the future, we may be able to replace this with Array.isTemplateObject,\n // though we might need to make that check inside of the html and svg\n // functions, because precompiled templates don't come in as\n // TemplateStringArray objects.\n if (!Array.isArray(tsa) || !tsa.hasOwnProperty('raw')) {\n let message = 'invalid template strings array';\n if (DEV_MODE) {\n message = `\n Internal Error: expected template strings to be an array\n with a 'raw' field. Faking a template strings array by\n calling html or svg like an ordinary function is effectively\n the same as calling unsafeHtml and can lead to major security\n issues, e.g. opening your code up to XSS attacks.\n If you're using the html or svg tagged template functions normally\n and still seeing this error, please file a bug at\n https://github.com/lit/lit/issues/new?template=bug_report.md\n and include information about your build tooling, if any.\n `\n .trim()\n .replace(/\\n */g, '\\n');\n }\n throw new Error(message);\n }\n return policy !== undefined\n ? policy.createHTML(stringFromTSA)\n : (stringFromTSA as unknown as TrustedHTML);\n}\n\n/**\n * Returns an HTML string for the given TemplateStringsArray and result type\n * (HTML or SVG), along with the case-sensitive bound attribute names in\n * template order. The HTML contains comment markers denoting the `ChildPart`s\n * and suffixes on bound attributes denoting the `AttributeParts`.\n *\n * @param strings template strings array\n * @param type HTML or SVG\n * @return Array containing `[html, attrNames]` (array returned for terseness,\n * to avoid object fields since this code is shared with non-minified SSR\n * code)\n */\nconst getTemplateHtml = (\n strings: TemplateStringsArray,\n type: ResultType\n): [TrustedHTML, Array<string | undefined>] => {\n // Insert makers into the template HTML to represent the position of\n // bindings. The following code scans the template strings to determine the\n // syntactic position of the bindings. They can be in text position, where\n // we insert an HTML comment, attribute value position, where we insert a\n // sentinel string and re-write the attribute name, or inside a tag where\n // we insert the sentinel string.\n const l = strings.length - 1;\n // Stores the case-sensitive bound attribute names in the order of their\n // parts. ElementParts are also reflected in this array as undefined\n // rather than a string, to disambiguate from attribute bindings.\n const attrNames: Array<string | undefined> = [];\n let html = type === SVG_RESULT ? '<svg>' : '';\n\n // When we're inside a raw text tag (not it's text content), the regex\n // will still be tagRegex so we can find attributes, but will switch to\n // this regex when the tag ends.\n let rawTextEndRegex: RegExp | undefined;\n\n // The current parsing state, represented as a reference to one of the\n // regexes\n let regex = textEndRegex;\n\n for (let i = 0; i < l; i++) {\n const s = strings[i];\n // The index of the end of the last attribute name. When this is\n // positive at end of a string, it means we're in an attribute value\n // position and need to rewrite the attribute name.\n // We also use a special value of -2 to indicate that we encountered\n // the end of a string in attribute name position.\n let attrNameEndIndex = -1;\n let attrName: string | undefined;\n let lastIndex = 0;\n let match!: RegExpExecArray | null;\n\n // The conditions in this loop handle the current parse state, and the\n // assignments to the `regex` variable are the state transitions.\n while (lastIndex < s.length) {\n // Make sure we start searching from where we previously left off\n regex.lastIndex = lastIndex;\n match = regex.exec(s);\n if (match === null) {\n break;\n }\n lastIndex = regex.lastIndex;\n if (regex === textEndRegex) {\n if (match[COMMENT_START] === '!--') {\n regex = commentEndRegex;\n } else if (match[COMMENT_START] !== undefined) {\n // We started a weird comment, like </{\n regex = comment2EndRegex;\n } else if (match[TAG_NAME] !== undefined) {\n if (rawTextElement.test(match[TAG_NAME])) {\n // Record if we encounter a raw-text element. We'll switch to\n // this regex at the end of the tag.\n rawTextEndRegex = new RegExp(`</${match[TAG_NAME]}`, 'g');\n }\n regex = tagEndRegex;\n } else if (match[DYNAMIC_TAG_NAME] !== undefined) {\n if (DEV_MODE) {\n throw new Error(\n 'Bindings in tag names are not supported. Please use static templates instead. ' +\n 'See https://lit.dev/docs/templates/expressions/#static-expressions'\n );\n }\n regex = tagEndRegex;\n }\n } else if (regex === tagEndRegex) {\n if (match[ENTIRE_MATCH] === '>') {\n // End of a tag. If we had started a raw-text element, use that\n // regex\n regex = rawTextEndRegex ?? textEndRegex;\n // We may be ending an unquoted attribute value, so make sure we\n // clear any pending attrNameEndIndex\n attrNameEndIndex = -1;\n } else if (match[ATTRIBUTE_NAME] === undefined) {\n // Attribute name position\n attrNameEndIndex = -2;\n } else {\n attrNameEndIndex = regex.lastIndex - match[SPACES_AND_EQUALS].length;\n attrName = match[ATTRIBUTE_NAME];\n regex =\n match[QUOTE_CHAR] === undefined\n ? tagEndRegex\n : match[QUOTE_CHAR] === '\"'\n ? doubleQuoteAttrEndRegex\n : singleQuoteAttrEndRegex;\n }\n } else if (\n regex === doubleQuoteAttrEndRegex ||\n regex === singleQuoteAttrEndRegex\n ) {\n regex = tagEndRegex;\n } else if (regex === commentEndRegex || regex === comment2EndRegex) {\n regex = textEndRegex;\n } else {\n // Not one of the five state regexes, so it must be the dynamically\n // created raw text regex and we're at the close of that element.\n regex = tagEndRegex;\n rawTextEndRegex = undefined;\n }\n }\n\n if (DEV_MODE) {\n // If we have a attrNameEndIndex, which indicates that we should\n // rewrite the attribute name, assert that we're in a valid attribute\n // position - either in a tag, or a quoted attribute value.\n console.assert(\n attrNameEndIndex === -1 ||\n regex === tagEndRegex ||\n regex === singleQuoteAttrEndRegex ||\n regex === doubleQuoteAttrEndRegex,\n 'unexpected parse state B'\n );\n }\n\n // We have four cases:\n // 1. We're in text position, and not in a raw text element\n // (regex === textEndRegex): insert a comment marker.\n // 2. We have a non-negative attrNameEndIndex which means we need to\n // rewrite the attribute name to add a bound attribute suffix.\n // 3. We're at the non-first binding in a multi-binding attribute, use a\n // plain marker.\n // 4. We're somewhere else inside the tag. If we're in attribute name\n // position (attrNameEndIndex === -2), add a sequential suffix to\n // generate a unique attribute name.\n\n // Detect a binding next to self-closing tag end and insert a space to\n // separate the marker from the tag end:\n const end =\n regex === tagEndRegex && strings[i + 1].startsWith('/>') ? ' ' : '';\n html +=\n regex === textEndRegex\n ? s + nodeMarker\n : attrNameEndIndex >= 0\n ? (attrNames.push(attrName!),\n s.slice(0, attrNameEndIndex) +\n boundAttributeSuffix +\n s.slice(attrNameEndIndex)) +\n marker +\n end\n : s +\n marker +\n (attrNameEndIndex === -2 ? (attrNames.push(undefined), i) : end);\n }\n\n const htmlResult: string | TrustedHTML =\n html + (strings[l] || '<?>') + (type === SVG_RESULT ? '</svg>' : '');\n\n // Returned as an array for terseness\n return [trustFromTemplateString(strings, htmlResult), attrNames];\n};\n\n/** @internal */\nexport type {Template};\nclass Template {\n /** @internal */\n el!: HTMLTemplateElement;\n\n parts: Array<TemplatePart> = [];\n\n constructor(\n // This property needs to remain unminified.\n {strings, ['_$litType$']: type}: TemplateResult,\n options?: RenderOptions\n ) {\n let node: Node | null;\n let nodeIndex = 0;\n let attrNameIndex = 0;\n const partCount = strings.length - 1;\n const parts = this.parts;\n\n // Create template element\n const [html, attrNames] = getTemplateHtml(strings, type);\n this.el = Template.createElement(html, options);\n walker.currentNode = this.el.content;\n\n // Reparent SVG nodes into template root\n if (type === SVG_RESULT) {\n const content = this.el.content;\n const svgElement = content.firstChild!;\n svgElement.remove();\n content.append(...svgElement.childNodes);\n }\n\n // Walk the template to find binding markers and create TemplateParts\n while ((node = walker.nextNode()) !== null && parts.length < partCount) {\n if (node.nodeType === 1) {\n if (DEV_MODE) {\n const tag = (node as Element).localName;\n // Warn if `textarea` includes an expression and throw if `template`\n // does since these are not supported. We do this by checking\n // innerHTML for anything that looks like a marker. This catches\n // cases like bindings in textarea there markers turn into text nodes.\n if (\n /^(?:textarea|template)$/i!.test(tag) &&\n (node as Element).innerHTML.includes(marker)\n ) {\n const m =\n `Expressions are not supported inside \\`${tag}\\` ` +\n `elements. See https://lit.dev/msg/expression-in-${tag} for more ` +\n `information.`;\n if (tag === 'template') {\n throw new Error(m);\n } else issueWarning('', m);\n }\n }\n // TODO (justinfagnani): for attempted dynamic tag names, we don't\n // increment the bindingIndex, and it'll be off by 1 in the element\n // and off by two after it.\n if ((node as Element).hasAttributes()) {\n // We defer removing bound attributes because on IE we might not be\n // iterating attributes in their template order, and would sometimes\n // remove an attribute that we still need to create a part for.\n const attrsToRemove = [];\n for (const name of (node as Element).getAttributeNames()) {\n // `name` is the name of the attribute we're iterating over, but not\n // _necessarily_ the name of the attribute we will create a part\n // for. They can be different in browsers that don't iterate on\n // attributes in source order. In that case the attrNames array\n // contains the attribute name we'll process next. We only need the\n // attribute name here to know if we should process a bound attribute\n // on this element.\n if (\n name.endsWith(boundAttributeSuffix) ||\n name.startsWith(marker)\n ) {\n const realName = attrNames[attrNameIndex++];\n attrsToRemove.push(name);\n if (realName !== undefined) {\n // Lowercase for case-sensitive SVG attributes like viewBox\n const value = (node as Element).getAttribute(\n realName.toLowerCase() + boundAttributeSuffix\n )!;\n const statics = value.split(marker);\n const m = /([.?@])?(.*)/.exec(realName)!;\n parts.push({\n type: ATTRIBUTE_PART,\n index: nodeIndex,\n name: m[2],\n strings: statics,\n ctor:\n m[1] === '.'\n ? PropertyPart\n : m[1] === '?'\n ? BooleanAttributePart\n : m[1] === '@'\n ? EventPart\n : AttributePart,\n });\n } else {\n parts.push({\n type: ELEMENT_PART,\n index: nodeIndex,\n });\n }\n }\n }\n for (const name of attrsToRemove) {\n (node as Element).removeAttribute(name);\n }\n }\n // TODO (justinfagnani): benchmark the regex against testing for each\n // of the 3 raw text element names.\n if (rawTextElement.test((node as Element).tagName)) {\n // For raw text elements we need to split the text content on\n // markers, create a Text node for each segment, and create\n // a TemplatePart for each marker.\n const strings = (node as Element).textContent!.split(marker);\n const lastIndex = strings.length - 1;\n if (lastIndex > 0) {\n (node as Element).textContent = trustedTypes\n ? (trustedTypes.emptyScript as unknown as '')\n : '';\n // Generate a new text node for each literal section\n // These nodes are also used as the markers for node parts\n // We can't use empty text nodes as markers because they're\n // normalized when cloning in IE (could simplify when\n // IE is no longer supported)\n for (let i = 0; i < lastIndex; i++) {\n (node as Element).append(strings[i], createMarker());\n // Walk past the marker node we just added\n walker.nextNode();\n parts.push({type: CHILD_PART, index: ++nodeIndex});\n }\n // Note because this marker is added after the walker's current\n // node, it will be walked to in the outer loop (and ignored), so\n // we don't need to adjust nodeIndex here\n (node as Element).append(strings[lastIndex], createMarker());\n }\n }\n } else if (node.nodeType === 8) {\n const data = (node as Comment).data;\n if (data === markerMatch) {\n parts.push({type: CHILD_PART, index: nodeIndex});\n } else {\n let i = -1;\n while ((i = (node as Comment).data.indexOf(marker, i + 1)) !== -1) {\n // Comment node has a binding marker inside, make an inactive part\n // The binding won't work, but subsequent bindings will\n parts.push({type: COMMENT_PART, index: nodeIndex});\n // Move to the end of the match\n i += marker.length - 1;\n }\n }\n }\n nodeIndex++;\n }\n // We could set walker.currentNode to another node here to prevent a memory\n // leak, but every time we prepare a template, we immediately render it\n // and re-use the walker in new TemplateInstance._clone().\n debugLogEvent?.({\n kind: 'template prep',\n template: this,\n clonableTemplate: this.el,\n parts: this.parts,\n strings,\n });\n }\n\n // Overridden via `litHtmlPolyfillSupport` to provide platform support.\n /** @nocollapse */\n static createElement(html: TrustedHTML, _options?: RenderOptions) {\n const el = d.createElement('template');\n el.innerHTML = html as unknown as string;\n return el;\n }\n}\n\nexport interface Disconnectable {\n _$parent?: Disconnectable;\n _$disconnectableChildren?: Set<Disconnectable>;\n // Rather than hold connection state on instances, Disconnectables recursively\n // fetch the connection state from the RootPart they are connected in via\n // getters up the Disconnectable tree via _$parent references. This pushes the\n // cost of tracking the isConnected state to `AsyncDirectives`, and avoids\n // needing to pass all Disconnectables (parts, template instances, and\n // directives) their connection state each time it changes, which would be\n // costly for trees that have no AsyncDirectives.\n _$isConnected: boolean;\n}\n\nfunction resolveDirective(\n part: ChildPart | AttributePart | ElementPart,\n value: unknown,\n parent: DirectiveParent = part,\n attributeIndex?: number\n): unknown {\n // Bail early if the value is explicitly noChange. Note, this means any\n // nested directive is still attached and is not run.\n if (value === noChange) {\n return value;\n }\n let currentDirective =\n attributeIndex !== undefined\n ? (parent as AttributePart).__directives?.[attributeIndex]\n : (parent as ChildPart | ElementPart | Directive).__directive;\n const nextDirectiveConstructor = isPrimitive(value)\n ? undefined\n : // This property needs to remain unminified.\n (value as DirectiveResult)['_$litDirective$'];\n if (currentDirective?.constructor !== nextDirectiveConstructor) {\n // This property needs to remain unminified.\n currentDirective?.['_$notifyDirectiveConnectionChanged']?.(false);\n if (nextDirectiveConstructor === undefined) {\n currentDirective = undefined;\n } else {\n currentDirective = new nextDirectiveConstructor(part as PartInfo);\n currentDirective._$initialize(part, parent, attributeIndex);\n }\n if (attributeIndex !== undefined) {\n ((parent as AttributePart).__directives ??= [])[attributeIndex] =\n currentDirective;\n } else {\n (parent as ChildPart | Directive).__directive = currentDirective;\n }\n }\n if (currentDirective !== undefined) {\n value = resolveDirective(\n part,\n currentDirective._$resolve(part, (value as DirectiveResult).values),\n currentDirective,\n attributeIndex\n );\n }\n return value;\n}\n\nexport type {TemplateInstance};\n/**\n * An updateable instance of a Template. Holds references to the Parts used to\n * update the template instance.\n */\nclass TemplateInstance implements Disconnectable {\n _$template: Template;\n _$parts: Array<Part | undefined> = [];\n\n /** @internal */\n _$parent: ChildPart;\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n constructor(template: Template, parent: ChildPart) {\n this._$template = template;\n this._$parent = parent;\n }\n\n // Called by ChildPart parentNode getter\n get parentNode() {\n return this._$parent.parentNode;\n }\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n // This method is separate from the constructor because we need to return a\n // DocumentFragment and we don't want to hold onto it with an instance field.\n _clone(options: RenderOptions | undefined) {\n const {\n el: {content},\n parts: parts,\n } = this._$template;\n const fragment = (options?.creationScope ?? d).importNode(content, true);\n walker.currentNode = fragment;\n\n let node = walker.nextNode()!;\n let nodeIndex = 0;\n let partIndex = 0;\n let templatePart = parts[0];\n\n while (templatePart !== undefined) {\n if (nodeIndex === templatePart.index) {\n let part: Part | undefined;\n if (templatePart.type === CHILD_PART) {\n part = new ChildPart(\n node as HTMLElement,\n node.nextSibling,\n this,\n options\n );\n } else if (templatePart.type === ATTRIBUTE_PART) {\n part = new templatePart.ctor(\n node as HTMLElement,\n templatePart.name,\n templatePart.strings,\n this,\n options\n );\n } else if (templatePart.type === ELEMENT_PART) {\n part = new ElementPart(node as HTMLElement, this, options);\n }\n this._$parts.push(part);\n templatePart = parts[++partIndex];\n }\n if (nodeIndex !== templatePart?.index) {\n node = walker.nextNode()!;\n nodeIndex++;\n }\n }\n // We need to set the currentNode away from the cloned tree so that we\n // don't hold onto the tree even if the tree is detached and should be\n // freed.\n walker.currentNode = d;\n return fragment;\n }\n\n _update(values: Array<unknown>) {\n let i = 0;\n for (const part of this._$parts) {\n if (part !== undefined) {\n debugLogEvent?.({\n kind: 'set part',\n part,\n value: values[i],\n valueIndex: i,\n values,\n templateInstance: this,\n });\n if ((part as AttributePart).strings !== undefined) {\n (part as AttributePart)._$setValue(values, part as AttributePart, i);\n // The number of values the part consumes is part.strings.length - 1\n // since values are in between template spans. We increment i by 1\n // later in the loop, so increment it by part.strings.length - 2 here\n i += (part as AttributePart).strings!.length - 2;\n } else {\n part._$setValue(values[i]);\n }\n }\n i++;\n }\n }\n}\n\n/*\n * Parts\n */\ntype AttributeTemplatePart = {\n readonly type: typeof ATTRIBUTE_PART;\n readonly index: number;\n readonly name: string;\n readonly ctor: typeof AttributePart;\n readonly strings: ReadonlyArray<string>;\n};\ntype ChildTemplatePart = {\n readonly type: typeof CHILD_PART;\n readonly index: number;\n};\ntype ElementTemplatePart = {\n readonly type: typeof ELEMENT_PART;\n readonly index: number;\n};\ntype CommentTemplatePart = {\n readonly type: typeof COMMENT_PART;\n readonly index: number;\n};\n\n/**\n * A TemplatePart represents a dynamic part in a template, before the template\n * is instantiated. When a template is instantiated Parts are created from\n * TemplateParts.\n */\ntype TemplatePart =\n | ChildTemplatePart\n | AttributeTemplatePart\n | ElementTemplatePart\n | CommentTemplatePart;\n\nexport type Part =\n | ChildPart\n | AttributePart\n | PropertyPart\n | BooleanAttributePart\n | ElementPart\n | EventPart;\n\nexport type {ChildPart};\nclass ChildPart implements Disconnectable {\n readonly type = CHILD_PART;\n readonly options: RenderOptions | undefined;\n _$committedValue: unknown = nothing;\n /** @internal */\n __directive?: Directive;\n /** @internal */\n _$startNode: ChildNode;\n /** @internal */\n _$endNode: ChildNode | null;\n private _textSanitizer: ValueSanitizer | undefined;\n /** @internal */\n _$parent: Disconnectable | undefined;\n /**\n * Connection state for RootParts only (i.e. ChildPart without _$parent\n * returned from top-level `render`). This field is unsed otherwise. The\n * intention would clearer if we made `RootPart` a subclass of `ChildPart`\n * with this field (and a different _$isConnected getter), but the subclass\n * caused a perf regression, possibly due to making call sites polymorphic.\n * @internal\n */\n __isConnected: boolean;\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n // ChildParts that are not at the root should always be created with a\n // parent; only RootChildNode's won't, so they return the local isConnected\n // state\n return this._$parent?._$isConnected ?? this.__isConnected;\n }\n\n // The following fields will be patched onto ChildParts when required by\n // AsyncDirective\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n /** @internal */\n _$notifyConnectionChanged?(\n isConnected: boolean,\n removeFromParent?: boolean,\n from?: number\n ): void;\n /** @internal */\n _$reparentDisconnectables?(parent: Disconnectable): void;\n\n constructor(\n startNode: ChildNode,\n endNode: ChildNode | null,\n parent: TemplateInstance | ChildPart | undefined,\n options: RenderOptions | undefined\n ) {\n this._$startNode = startNode;\n this._$endNode = endNode;\n this._$parent = parent;\n this.options = options;\n // Note __isConnected is only ever accessed on RootParts (i.e. when there is\n // no _$parent); the value on a non-root-part is \"don't care\", but checking\n // for parent would be more code\n this.__isConnected = options?.isConnected ?? true;\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n // Explicitly initialize for consistent class shape.\n this._textSanitizer = undefined;\n }\n }\n\n /**\n * The parent node into which the part renders its content.\n *\n * A ChildPart's content consists of a range of adjacent child nodes of\n * `.parentNode`, possibly bordered by 'marker nodes' (`.startNode` and\n * `.endNode`).\n *\n * - If both `.startNode` and `.endNode` are non-null, then the part's content\n * consists of all siblings between `.startNode` and `.endNode`, exclusively.\n *\n * - If `.startNode` is non-null but `.endNode` is null, then the part's\n * content consists of all siblings following `.startNode`, up to and\n * including the last child of `.parentNode`. If `.endNode` is non-null, then\n * `.startNode` will always be non-null.\n *\n * - If both `.endNode` and `.startNode` are null, then the part's content\n * consists of all child nodes of `.parentNode`.\n */\n get parentNode(): Node {\n let parentNode: Node = wrap(this._$startNode).parentNode!;\n const parent = this._$parent;\n if (\n parent !== undefined &&\n parentNode?.nodeType === 11 /* Node.DOCUMENT_FRAGMENT */\n ) {\n // If the parentNode is a DocumentFragment, it may be because the DOM is\n // still in the cloned fragment during initial render; if so, get the real\n // parentNode the part will be committed into by asking the parent.\n parentNode = (parent as ChildPart | TemplateInstance).parentNode;\n }\n return parentNode;\n }\n\n /**\n * The part's leading marker node, if any. See `.parentNode` for more\n * information.\n */\n get startNode(): Node | null {\n return this._$startNode;\n }\n\n /**\n * The part's trailing marker node, if any. See `.parentNode` for more\n * information.\n */\n get endNode(): Node | null {\n return this._$endNode;\n }\n\n _$setValue(value: unknown, directiveParent: DirectiveParent = this): void {\n if (DEV_MODE && this.parentNode === null) {\n throw new Error(\n `This \\`ChildPart\\` has no \\`parentNode\\` and therefore cannot accept a value. This likely means the element containing the part was manipulated in an unsupported way outside of Lit's control such that the part's marker nodes were ejected from DOM. For example, setting the element's \\`innerHTML\\` or \\`textContent\\` can do this.`\n );\n }\n value = resolveDirective(this, value, directiveParent);\n if (isPrimitive(value)) {\n // Non-rendering child values. It's important that these do not render\n // empty text nodes to avoid issues with preventing default <slot>\n // fallback content.\n if (value === nothing || value == null || value === '') {\n if (this._$committedValue !== nothing) {\n debugLogEvent?.({\n kind: 'commit nothing to child',\n start: this._$startNode,\n end: this._$endNode,\n parent: this._$parent,\n options: this.options,\n });\n this._$clear();\n }\n this._$committedValue = nothing;\n } else if (value !== this._$committedValue && value !== noChange) {\n this._commitText(value);\n }\n // This property needs to remain unminified.\n } else if ((value as TemplateResult)['_$litType$'] !== undefined) {\n this._commitTemplateResult(value as TemplateResult);\n } else if ((value as Node).nodeType !== undefined) {\n if (DEV_MODE && this.options?.host === value) {\n this._commitText(\n `[probable mistake: rendered a template's host in itself ` +\n `(commonly caused by writing \\${this} in a template]`\n );\n console.warn(\n `Attempted to render the template host`,\n value,\n `inside itself. This is almost always a mistake, and in dev mode `,\n `we render some warning text. In production however, we'll `,\n `render it, which will usually result in an error, and sometimes `,\n `in the element disappearing from the DOM.`\n );\n return;\n }\n this._commitNode(value as Node);\n } else if (isIterable(value)) {\n this._commitIterable(value);\n } else {\n // Fallback, will render the string representation\n this._commitText(value);\n }\n }\n\n private _insert<T extends Node>(node: T) {\n return wrap(wrap(this._$startNode).parentNode!).insertBefore(\n node,\n this._$endNode\n );\n }\n\n private _commitNode(value: Node): void {\n if (this._$committedValue !== value) {\n this._$clear();\n if (\n ENABLE_EXTRA_SECURITY_HOOKS &&\n sanitizerFactoryInternal !== noopSanitizer\n ) {\n const parentNodeName = this._$startNode.parentNode?.nodeName;\n if (parentNodeName === 'STYLE' || parentNodeName === 'SCRIPT') {\n let message = 'Forbidden';\n if (DEV_MODE) {\n if (parentNodeName === 'STYLE') {\n message =\n `Lit does not support binding inside style nodes. ` +\n `This is a security risk, as style injection attacks can ` +\n `exfiltrate data and spoof UIs. ` +\n `Consider instead using css\\`...\\` literals ` +\n `to compose styles, and make do dynamic styling with ` +\n `css custom properties, ::parts, <slot>s, ` +\n `and by mutating the DOM rather than stylesheets.`;\n } else {\n message =\n `Lit does not support binding inside script nodes. ` +\n `This is a security risk, as it could allow arbitrary ` +\n `code execution.`;\n }\n }\n throw new Error(message);\n }\n }\n debugLogEvent?.({\n kind: 'commit node',\n start: this._$startNode,\n parent: this._$parent,\n value: value,\n options: this.options,\n });\n this._$committedValue = this._insert(value);\n }\n }\n\n private _commitText(value: unknown): void {\n // If the committed value is a primitive it means we called _commitText on\n // the previous render, and we know that this._$startNode.nextSibling is a\n // Text node. We can now just replace the text content (.data) of the node.\n if (\n this._$committedValue !== nothing &&\n isPrimitive(this._$committedValue)\n ) {\n const node = wrap(this._$startNode).nextSibling as Text;\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n if (this._textSanitizer === undefined) {\n this._textSanitizer = createSanitizer(node, 'data', 'property');\n }\n value = this._textSanitizer(value);\n }\n debugLogEvent?.({\n kind: 'commit text',\n node,\n value,\n options: this.options,\n });\n (node as Text).data = value as string;\n } else {\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n const textNode = d.createTextNode('');\n this._commitNode(textNode);\n // When setting text content, for security purposes it matters a lot\n // what the parent is. For example, <style> and <script> need to be\n // handled with care, while <span> does not. So first we need to put a\n // text node into the document, then we can sanitize its content.\n if (this._textSanitizer === undefined) {\n this._textSanitizer = createSanitizer(textNode, 'data', 'property');\n }\n value = this._textSanitizer(value);\n debugLogEvent?.({\n kind: 'commit text',\n node: textNode,\n value,\n options: this.options,\n });\n textNode.data = value as string;\n } else {\n this._commitNode(d.createTextNode(value as string));\n debugLogEvent?.({\n kind: 'commit text',\n node: wrap(this._$startNode).nextSibling as Text,\n value,\n options: this.options,\n });\n }\n }\n this._$committedValue = value;\n }\n\n private _commitTemplateResult(\n result: TemplateResult | CompiledTemplateResult\n ): void {\n // This property needs to remain unminified.\n const {values, ['_$litType$']: type} = result;\n // If $litType$ is a number, result is a plain TemplateResult and we get\n // the template from the template cache. If not, result is a\n // CompiledTemplateResult and _$litType$ is a CompiledTemplate and we need\n // to create the <template> element the first time we see it.\n const template: Template | CompiledTemplate =\n typeof type === 'number'\n ? this._$getTemplate(result as TemplateResult)\n : (type.el === undefined &&\n (type.el = Template.createElement(\n trustFromTemplateString(type.h, type.h[0]),\n this.options\n )),\n type);\n\n if ((this._$committedValue as TemplateInstance)?._$template === template) {\n debugLogEvent?.({\n kind: 'template updating',\n template,\n instance: this._$committedValue as TemplateInstance,\n parts: (this._$committedValue as TemplateInstance)._$parts,\n options: this.options,\n values,\n });\n (this._$committedValue as TemplateInstance)._update(values);\n } else {\n const instance = new TemplateInstance(template as Template, this);\n const fragment = instance._clone(this.options);\n debugLogEvent?.({\n kind: 'template instantiated',\n template,\n instance,\n parts: instance._$parts,\n options: this.options,\n fragment,\n values,\n });\n instance._update(values);\n debugLogEvent?.({\n kind: 'template instantiated and updated',\n template,\n instance,\n parts: instance._$parts,\n options: this.options,\n fragment,\n values,\n });\n this._commitNode(fragment);\n this._$committedValue = instance;\n }\n }\n\n // Overridden via `litHtmlPolyfillSupport` to provide platform support.\n /** @internal */\n _$getTemplate(result: TemplateResult) {\n let template = templateCache.get(result.strings);\n if (template === undefined) {\n templateCache.set(result.strings, (template = new Template(result)));\n }\n return template;\n }\n\n private _commitIterable(value: Iterable<unknown>): void {\n // For an Iterable, we create a new InstancePart per item, then set its\n // value to the item. This is a little bit of overhead for every item in\n // an Iterable, but it lets us recurse easily and efficiently update Arrays\n // of TemplateResults that will be commonly returned from expressions like:\n // array.map((i) => html`${i}`), by reusing existing TemplateInstances.\n\n // If value is an array, then the previous render was of an\n // iterable and value will contain the ChildParts from the previous\n // render. If value is not an array, clear this part and make a new\n // array for ChildParts.\n if (!isArray(this._$committedValue)) {\n this._$committedValue = [];\n this._$clear();\n }\n\n // Lets us keep track of how many items we stamped so we can clear leftover\n // items from a previous render\n const itemParts = this._$committedValue as ChildPart[];\n let partIndex = 0;\n let itemPart: ChildPart | undefined;\n\n for (const item of value) {\n if (partIndex === itemParts.length) {\n // If no existing part, create a new one\n // TODO (justinfagnani): test perf impact of always creating two parts\n // instead of sharing parts between nodes\n // https://github.com/lit/lit/issues/1266\n itemParts.push(\n (itemPart = new ChildPart(\n this._insert(createMarker()),\n this._insert(createMarker()),\n this,\n this.options\n ))\n );\n } else {\n // Reuse an existing part\n itemPart = itemParts[partIndex];\n }\n itemPart._$setValue(item);\n partIndex++;\n }\n\n if (partIndex < itemParts.length) {\n // itemParts always have end nodes\n this._$clear(\n itemPart && wrap(itemPart._$endNode!).nextSibling,\n partIndex\n );\n // Truncate the parts array so _value reflects the current state\n itemParts.length = partIndex;\n }\n }\n\n /**\n * Removes the nodes contained within this Part from the DOM.\n *\n * @param start Start node to clear from, for clearing a subset of the part's\n * DOM (used when truncating iterables)\n * @param from When `start` is specified, the index within the iterable from\n * which ChildParts are being removed, used for disconnecting directives in\n * those Parts.\n *\n * @internal\n */\n _$clear(\n start: ChildNode | null = wrap(this._$startNode).nextSibling,\n from?: number\n ) {\n this._$notifyConnectionChanged?.(false, true, from);\n while (start && start !== this._$endNode) {\n const n = wrap(start!).nextSibling;\n (wrap(start!) as Element).remove();\n start = n;\n }\n }\n /**\n * Implementation of RootPart's `isConnected`. Note that this metod\n * should only be called on `RootPart`s (the `ChildPart` returned from a\n * top-level `render()` call). It has no effect on non-root ChildParts.\n * @param isConnected Whether to set\n * @internal\n */\n setConnected(isConnected: boolean) {\n if (this._$parent === undefined) {\n this.__isConnected = isConnected;\n this._$notifyConnectionChanged?.(isConnected);\n } else if (DEV_MODE) {\n throw new Error(\n 'part.setConnected() may only be called on a ' +\n 'RootPart returned from render().'\n );\n }\n }\n}\n\n/**\n * A top-level `ChildPart` returned from `render` that manages the connected\n * state of `AsyncDirective`s created throughout the tree below it.\n */\nexport interface RootPart extends ChildPart {\n /**\n * Sets the connection state for `AsyncDirective`s contained within this root\n * ChildPart.\n *\n * lit-html does not automatically monitor the connectedness of DOM rendered;\n * as such, it is the responsibility of the caller to `render` to ensure that\n * `part.setConnected(false)` is called before the part object is potentially\n * discarded, to ensure that `AsyncDirective`s have a chance to dispose of\n * any resources being held. If a `RootPart` that was previously\n * disconnected is subsequently re-connected (and its `AsyncDirective`s should\n * re-connect), `setConnected(true)` should be called.\n *\n * @param isConnected Whether directives within this tree should be connected\n * or not\n */\n setConnected(isConnected: boolean): void;\n}\n\nexport type {AttributePart};\nclass AttributePart implements Disconnectable {\n readonly type = ATTRIBUTE_PART as\n | typeof ATTRIBUTE_PART\n | typeof PROPERTY_PART\n | typeof BOOLEAN_ATTRIBUTE_PART\n | typeof EVENT_PART;\n readonly element: HTMLElement;\n readonly name: string;\n readonly options: RenderOptions | undefined;\n\n /**\n * If this attribute part represents an interpolation, this contains the\n * static strings of the interpolation. For single-value, complete bindings,\n * this is undefined.\n */\n readonly strings?: ReadonlyArray<string>;\n /** @internal */\n _$committedValue: unknown | Array<unknown> = nothing;\n /** @internal */\n __directives?: Array<Directive | undefined>;\n /** @internal */\n _$parent: Disconnectable;\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n protected _sanitizer: ValueSanitizer | undefined;\n\n get tagName() {\n return this.element.tagName;\n }\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n constructor(\n element: HTMLElement,\n name: string,\n strings: ReadonlyArray<string>,\n parent: Disconnectable,\n options: RenderOptions | undefined\n ) {\n this.element = element;\n this.name = name;\n this._$parent = parent;\n this.options = options;\n if (strings.length > 2 || strings[0] !== '' || strings[1] !== '') {\n this._$committedValue = new Array(strings.length - 1).fill(new String());\n this.strings = strings;\n } else {\n this._$committedValue = nothing;\n }\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n this._sanitizer = undefined;\n }\n }\n\n /**\n * Sets the value of this part by resolving the value from possibly multiple\n * values and static strings and committing it to the DOM.\n * If this part is single-valued, `this._strings` will be undefined, and the\n * method will be called with a single value argument. If this part is\n * multi-value, `this._strings` will be defined, and the method is called\n * with the value array of the part's owning TemplateInstance, and an offset\n * into the value array from which the values should be read.\n * This method is overloaded this way to eliminate short-lived array slices\n * of the template instance values, and allow a fast-path for single-valued\n * parts.\n *\n * @param value The part value, or an array of values for multi-valued parts\n * @param valueIndex the index to start reading values from. `undefined` for\n * single-valued parts\n * @param noCommit causes the part to not commit its value to the DOM. Used\n * in hydration to prime attribute parts with their first-rendered value,\n * but not set the attribute, and in SSR to no-op the DOM operation and\n * capture the value for serialization.\n *\n * @internal\n */\n _$setValue(\n value: unknown | Array<unknown>,\n directiveParent: DirectiveParent = this,\n valueIndex?: number,\n noCommit?: boolean\n ) {\n const strings = this.strings;\n\n // Whether any of the values has changed, for dirty-checking\n let change = false;\n\n if (strings === undefined) {\n // Single-value binding case\n value = resolveDirective(this, value, directiveParent, 0);\n change =\n !isPrimitive(value) ||\n (value !== this._$committedValue && value !== noChange);\n if (change) {\n this._$committedValue = value;\n }\n } else {\n // Interpolation case\n const values = value as Array<unknown>;\n value = strings[0];\n\n let i, v;\n for (i = 0; i < strings.length - 1; i++) {\n v = resolveDirective(this, values[valueIndex! + i], directiveParent, i);\n\n if (v === noChange) {\n // If the user-provided value is `noChange`, use the previous value\n v = (this._$committedValue as Array<unknown>)[i];\n }\n change ||=\n !isPrimitive(v) || v !== (this._$committedValue as Array<unknown>)[i];\n if (v === nothing) {\n value = nothing;\n } else if (value !== nothing) {\n value += (v ?? '') + strings[i + 1];\n }\n // We always record each value, even if one is `nothing`, for future\n // change detection.\n (this._$committedValue as Array<unknown>)[i] = v;\n }\n }\n if (change && !noCommit) {\n this._commitValue(value);\n }\n }\n\n /** @internal */\n _commitValue(value: unknown) {\n if (value === nothing) {\n (wrap(this.element) as Element).removeAttribute(this.name);\n } else {\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n if (this._sanitizer === undefined) {\n this._sanitizer = sanitizerFactoryInternal(\n this.element,\n this.name,\n 'attribute'\n );\n }\n value = this._sanitizer(value ?? '');\n }\n debugLogEvent?.({\n kind: 'commit attribute',\n element: this.element,\n name: this.name,\n value,\n options: this.options,\n });\n (wrap(this.element) as Element).setAttribute(\n this.name,\n (value ?? '') as string\n );\n }\n }\n}\n\nexport type {PropertyPart};\nclass PropertyPart extends AttributePart {\n override readonly type = PROPERTY_PART;\n\n /** @internal */\n override _commitValue(value: unknown) {\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n if (this._sanitizer === undefined) {\n this._sanitizer = sanitizerFactoryInternal(\n this.element,\n this.name,\n 'property'\n );\n }\n value = this._sanitizer(value);\n }\n debugLogEvent?.({\n kind: 'commit property',\n element: this.element,\n name: this.name,\n value,\n options: this.options,\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this.element as any)[this.name] = value === nothing ? undefined : value;\n }\n}\n\n// Temporary workaround for https://crbug.com/993268\n// Currently, any attribute starting with \"on\" is considered to be a\n// TrustedScript source. Such boolean attributes must be set to the equivalent\n// trusted emptyScript value.\nconst emptyStringForBooleanAttribute = trustedTypes\n ? (trustedTypes.emptyScript as unknown as '')\n : '';\n\nexport type {BooleanAttributePart};\nclass BooleanAttributePart extends AttributePart {\n override readonly type = BOOLEAN_ATTRIBUTE_PART;\n\n /** @internal */\n override _commitValue(value: unknown) {\n debugLogEvent?.({\n kind: 'commit boolean attribute',\n element: this.element,\n name: this.name,\n value: !!(value && value !== nothing),\n options: this.options,\n });\n if (value && value !== nothing) {\n (wrap(this.element) as Element).setAttribute(\n this.name,\n emptyStringForBooleanAttribute\n );\n } else {\n (wrap(this.element) as Element).removeAttribute(this.name);\n }\n }\n}\n\ntype EventListenerWithOptions = EventListenerOrEventListenerObject &\n Partial<AddEventListenerOptions>;\n\n/**\n * An AttributePart that manages an event listener via add/removeEventListener.\n *\n * This part works by adding itself as the event listener on an element, then\n * delegating to the value passed to it. This reduces the number of calls to\n * add/removeEventListener if the listener changes frequently, such as when an\n * inline function is used as a listener.\n *\n * Because event options are passed when adding listeners, we must take case\n * to add and remove the part as a listener when the event options change.\n */\nexport type {EventPart};\nclass EventPart extends AttributePart {\n override readonly type = EVENT_PART;\n\n constructor(\n element: HTMLElement,\n name: string,\n strings: ReadonlyArray<string>,\n parent: Disconnectable,\n options: RenderOptions | undefined\n ) {\n super(element, name, strings, parent, options);\n\n if (DEV_MODE && this.strings !== undefined) {\n throw new Error(\n `A \\`<${element.localName}>\\` has a \\`@${name}=...\\` listener with ` +\n 'invalid content. Event listeners in templates must have exactly ' +\n 'one expression and no surrounding text.'\n );\n }\n }\n\n // EventPart does not use the base _$setValue/_resolveValue implementation\n // since the dirty checking is more complex\n /** @internal */\n override _$setValue(\n newListener: unknown,\n directiveParent: DirectiveParent = this\n ) {\n newListener =\n resolveDirective(this, newListener, directiveParent, 0) ?? nothing;\n if (newListener === noChange) {\n return;\n }\n const oldListener = this._$committedValue;\n\n // If the new value is nothing or any options change we have to remove the\n // part as a listener.\n const shouldRemoveListener =\n (newListener === nothing && oldListener !== nothing) ||\n (newListener as EventListenerWithOptions).capture !==\n (oldListener as EventListenerWithOptions).capture ||\n (newListener as EventListenerWithOptions).once !==\n (oldListener as EventListenerWithOptions).once ||\n (newListener as EventListenerWithOptions).passive !==\n (oldListener as EventListenerWithOptions).passive;\n\n // If the new value is not nothing and we removed the listener, we have\n // to add the part as a listener.\n const shouldAddListener =\n newListener !== nothing &&\n (oldListener === nothing || shouldRemoveListener);\n\n debugLogEvent?.({\n kind: 'commit event listener',\n element: this.element,\n name: this.name,\n value: newListener,\n options: this.options,\n removeListener: shouldRemoveListener,\n addListener: shouldAddListener,\n oldListener,\n });\n if (shouldRemoveListener) {\n this.element.removeEventListener(\n this.name,\n this,\n oldListener as EventListenerWithOptions\n );\n }\n if (shouldAddListener) {\n // Beware: IE11 and Chrome 41 don't like using the listener as the\n // options object. Figure out how to deal w/ this in IE11 - maybe\n // patch addEventListener?\n this.element.addEventListener(\n this.name,\n this,\n newListener as EventListenerWithOptions\n );\n }\n this._$committedValue = newListener;\n }\n\n handleEvent(event: Event) {\n if (typeof this._$committedValue === 'function') {\n this._$committedValue.call(this.options?.host ?? this.element, event);\n } else {\n (this._$committedValue as EventListenerObject).handleEvent(event);\n }\n }\n}\n\nexport type {ElementPart};\nclass ElementPart implements Disconnectable {\n readonly type = ELEMENT_PART;\n\n /** @internal */\n __directive?: Directive;\n\n // This is to ensure that every Part has a _$committedValue\n _$committedValue: undefined;\n\n /** @internal */\n _$parent!: Disconnectable;\n\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n options: RenderOptions | undefined;\n\n constructor(\n public element: Element,\n parent: Disconnectable,\n options: RenderOptions | undefined\n ) {\n this._$parent = parent;\n this.options = options;\n }\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n _$setValue(value: unknown): void {\n debugLogEvent?.({\n kind: 'commit to element binding',\n element: this.element,\n value,\n options: this.options,\n });\n resolveDirective(this, value);\n }\n}\n\n/**\n * END USERS SHOULD NOT RELY ON THIS OBJECT.\n *\n * Private exports for use by other Lit packages, not intended for use by\n * external users.\n *\n * We currently do not make a mangled rollup build of the lit-ssr code. In order\n * to keep a number of (otherwise private) top-level exports mangled in the\n * client side code, we export a _$LH object containing those members (or\n * helper methods for accessing private fields of those members), and then\n * re-export them for use in lit-ssr. This keeps lit-ssr agnostic to whether the\n * client-side code is being used in `dev` mode or `prod` mode.\n *\n * This has a unique name, to disambiguate it from private exports in\n * lit-element, which re-exports all of lit-html.\n *\n * @private\n */\nexport const _$LH = {\n // Used in lit-ssr\n _boundAttributeSuffix: boundAttributeSuffix,\n _marker: marker,\n _markerMatch: markerMatch,\n _HTML_RESULT: HTML_RESULT,\n _getTemplateHtml: getTemplateHtml,\n // Used in tests and private-ssr-support\n _TemplateInstance: TemplateInstance,\n _isIterable: isIterable,\n _resolveDirective: resolveDirective,\n _ChildPart: ChildPart,\n _AttributePart: AttributePart,\n _BooleanAttributePart: BooleanAttributePart,\n _EventPart: EventPart,\n _PropertyPart: PropertyPart,\n _ElementPart: ElementPart,\n};\n\n// Apply polyfills if available\nconst polyfillSupport = DEV_MODE\n ? global.litHtmlPolyfillSupportDevMode\n : global.litHtmlPolyfillSupport;\npolyfillSupport?.(Template, ChildPart);\n\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for lit-html usage.\n(global.litHtmlVersions ??= []).push('2.8.0');\nif (DEV_MODE && global.litHtmlVersions.length > 1) {\n issueWarning!(\n 'multiple-versions',\n `Multiple versions of Lit loaded. ` +\n `Loading multiple versions is not recommended.`\n );\n}\n\n/**\n * Renders a value, usually a lit-html TemplateResult, to the container.\n *\n * This example renders the text \"Hello, Zoe!\" inside a paragraph tag, appending\n * it to the container `document.body`.\n *\n * ```js\n * import {html, render} from 'lit';\n *\n * const name = \"Zoe\";\n * render(html`<p>Hello, ${name}!</p>`, document.body);\n * ```\n *\n * @param value Any [renderable\n * value](https://lit.dev/docs/templates/expressions/#child-expressions),\n * typically a {@linkcode TemplateResult} created by evaluating a template tag\n * like {@linkcode html} or {@linkcode svg}.\n * @param container A DOM container to render to. The first render will append\n * the rendered value to the container, and subsequent renders will\n * efficiently update the rendered value if the same result type was\n * previously rendered there.\n * @param options See {@linkcode RenderOptions} for options documentation.\n * @see\n * {@link https://lit.dev/docs/libraries/standalone-templates/#rendering-lit-html-templates| Rendering Lit HTML Templates}\n */\nexport const render = (\n value: unknown,\n container: HTMLElement | DocumentFragment,\n options?: RenderOptions\n): RootPart => {\n if (DEV_MODE && container == null) {\n // Give a clearer error message than\n // Uncaught TypeError: Cannot read properties of null (reading\n // '_$litPart$')\n // which reads like an internal Lit error.\n throw new TypeError(`The container to render into may not be ${container}`);\n }\n const renderId = DEV_MODE ? debugLogRenderId++ : 0;\n const partOwnerNode = options?.renderBefore ?? container;\n // This property needs to remain unminified.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let part: ChildPart = (partOwnerNode as any)['_$litPart$'];\n debugLogEvent?.({\n kind: 'begin render',\n id: renderId,\n value,\n container,\n options,\n part,\n });\n if (part === undefined) {\n const endNode = options?.renderBefore ?? null;\n // This property needs to remain unminified.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (partOwnerNode as any)['_$litPart$'] = part = new ChildPart(\n container.insertBefore(createMarker(), endNode),\n endNode,\n undefined,\n options ?? {}\n );\n }\n part._$setValue(value);\n debugLogEvent?.({\n kind: 'end render',\n id: renderId,\n value,\n container,\n options,\n part,\n });\n return part as RootPart;\n};\n\nif (ENABLE_EXTRA_SECURITY_HOOKS) {\n render.setSanitizer = setSanitizer;\n render.createSanitizer = createSanitizer;\n if (DEV_MODE) {\n render._testOnlyClearSanitizerFactoryDoNotCallOrElse =\n _testOnlyClearSanitizerFactoryDoNotCallOrElse;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/**\n * The main LitElement module, which defines the {@linkcode LitElement} base\n * class and related APIs.\n *\n * LitElement components can define a template and a set of observed\n * properties. Changing an observed property triggers a re-render of the\n * element.\n *\n * Import {@linkcode LitElement} and {@linkcode html} from this module to\n * create a component:\n *\n * ```js\n * import {LitElement, html} from 'lit-element';\n *\n * class MyElement extends LitElement {\n *\n * // Declare observed properties\n * static get properties() {\n * return {\n * adjective: {}\n * }\n * }\n *\n * constructor() {\n * this.adjective = 'awesome';\n * }\n *\n * // Define the element's template\n * render() {\n * return html`<p>your ${adjective} template here</p>`;\n * }\n * }\n *\n * customElements.define('my-element', MyElement);\n * ```\n *\n * `LitElement` extends {@linkcode ReactiveElement} and adds lit-html\n * templating. The `ReactiveElement` class is provided for users that want to\n * build their own custom element base classes that don't use lit-html.\n *\n * @packageDocumentation\n */\nimport {PropertyValues, ReactiveElement} from '@lit/reactive-element';\nimport {render, RenderOptions, noChange, RootPart} from 'lit-html';\nexport * from '@lit/reactive-element';\nexport * from 'lit-html';\n\nimport {LitUnstable} from 'lit-html';\nimport {ReactiveUnstable} from '@lit/reactive-element';\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace Unstable {\n /**\n * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n * we will emit 'lit-debug' events to window, with live details about the update and render\n * lifecycle. These can be useful for writing debug tooling and visualizations.\n *\n * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n * making certain operations that are normally very cheap (like a no-op render) much slower,\n * because we must copy data and dispatch events.\n */\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace DebugLog {\n export type Entry =\n | LitUnstable.DebugLog.Entry\n | ReactiveUnstable.DebugLog.Entry;\n }\n}\n\n// For backwards compatibility export ReactiveElement as UpdatingElement. Note,\n// IE transpilation requires exporting like this.\nexport const UpdatingElement = ReactiveElement;\n\nconst DEV_MODE = true;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nif (DEV_MODE) {\n // Ensure warnings are issued only 1x, even if multiple versions of Lit\n // are loaded.\n const issuedWarnings: Set<string | undefined> =\n (globalThis.litIssuedWarnings ??= new Set());\n\n // Issue a warning, if we haven't already.\n issueWarning = (code: string, warning: string) => {\n warning += ` See https://lit.dev/msg/${code} for more information.`;\n if (!issuedWarnings.has(warning)) {\n console.warn(warning);\n issuedWarnings.add(warning);\n }\n };\n}\n\n/**\n * Base element class that manages element properties and attributes, and\n * renders a lit-html template.\n *\n * To define a component, subclass `LitElement` and implement a\n * `render` method to provide the component's template. Define properties\n * using the {@linkcode LitElement.properties properties} property or the\n * {@linkcode property} decorator.\n */\nexport class LitElement extends ReactiveElement {\n /**\n * Ensure this class is marked as `finalized` as an optimization ensuring\n * it will not needlessly try to `finalize`.\n *\n * Note this property name is a string to prevent breaking Closure JS Compiler\n * optimizations. See @lit/reactive-element for more information.\n */\n protected static override ['finalized'] = true;\n\n // This property needs to remain unminified.\n static ['_$litElement$'] = true;\n\n /**\n * @category rendering\n */\n readonly renderOptions: RenderOptions = {host: this};\n\n private __childPart: RootPart | undefined = undefined;\n\n /**\n * @category rendering\n */\n protected override createRenderRoot() {\n const renderRoot = super.createRenderRoot();\n // When adoptedStyleSheets are shimmed, they are inserted into the\n // shadowRoot by createRenderRoot. Adjust the renderBefore node so that\n // any styles in Lit content render before adoptedStyleSheets. This is\n // important so that adoptedStyleSheets have precedence over styles in\n // the shadowRoot.\n this.renderOptions.renderBefore ??= renderRoot!.firstChild as ChildNode;\n return renderRoot;\n }\n\n /**\n * Updates the element. This method reflects property values to attributes\n * and calls `render` to render DOM via lit-html. Setting properties inside\n * this method will *not* trigger another update.\n * @param changedProperties Map of changed properties with old values\n * @category updates\n */\n protected override update(changedProperties: PropertyValues) {\n // Setting properties in `render` should not trigger an update. Since\n // updates are allowed after super.update, it's important to call `render`\n // before that.\n const value = this.render();\n if (!this.hasUpdated) {\n this.renderOptions.isConnected = this.isConnected;\n }\n super.update(changedProperties);\n this.__childPart = render(value, this.renderRoot, this.renderOptions);\n }\n\n /**\n * Invoked when the component is added to the document's DOM.\n *\n * In `connectedCallback()` you should setup tasks that should only occur when\n * the element is connected to the document. The most common of these is\n * adding event listeners to nodes external to the element, like a keydown\n * event handler added to the window.\n *\n * ```ts\n * connectedCallback() {\n * super.connectedCallback();\n * addEventListener('keydown', this._handleKeydown);\n * }\n * ```\n *\n * Typically, anything done in `connectedCallback()` should be undone when the\n * element is disconnected, in `disconnectedCallback()`.\n *\n * @category lifecycle\n */\n override connectedCallback() {\n super.connectedCallback();\n this.__childPart?.setConnected(true);\n }\n\n /**\n * Invoked when the component is removed from the document's DOM.\n *\n * This callback is the main signal to the element that it may no longer be\n * used. `disconnectedCallback()` should ensure that nothing is holding a\n * reference to the element (such as event listeners added to nodes external\n * to the element), so that it is free to be garbage collected.\n *\n * ```ts\n * disconnectedCallback() {\n * super.disconnectedCallback();\n * window.removeEventListener('keydown', this._handleKeydown);\n * }\n * ```\n *\n * An element may be re-connected after being disconnected.\n *\n * @category lifecycle\n */\n override disconnectedCallback() {\n super.disconnectedCallback();\n this.__childPart?.setConnected(false);\n }\n\n /**\n * Invoked on each update to perform rendering tasks. This method may return\n * any value renderable by lit-html's `ChildPart` - typically a\n * `TemplateResult`. Setting properties inside this method will *not* trigger\n * the element to update.\n * @category rendering\n */\n protected render(): unknown {\n return noChange;\n }\n}\n\n// Install hydration if available\nglobalThis.litElementHydrateSupport?.({LitElement});\n\n// Apply polyfills if available\nconst polyfillSupport = DEV_MODE\n ? globalThis.litElementPolyfillSupportDevMode\n : globalThis.litElementPolyfillSupport;\npolyfillSupport?.({LitElement});\n\n// DEV mode warnings\nif (DEV_MODE) {\n /* eslint-disable @typescript-eslint/no-explicit-any */\n // Note, for compatibility with closure compilation, this access\n // needs to be as a string property index.\n (LitElement as any)['finalize'] = function (this: typeof LitElement) {\n const finalized = (ReactiveElement as any).finalize.call(this);\n if (!finalized) {\n return false;\n }\n const warnRemovedOrRenamed = (obj: any, name: string, renamed = false) => {\n if (obj.hasOwnProperty(name)) {\n const ctorName = (typeof obj === 'function' ? obj : obj.constructor)\n .name;\n issueWarning(\n renamed ? 'renamed-api' : 'removed-api',\n `\\`${name}\\` is implemented on class ${ctorName}. It ` +\n `has been ${renamed ? 'renamed' : 'removed'} ` +\n `in this version of LitElement.`\n );\n }\n };\n warnRemovedOrRenamed(this, 'render');\n warnRemovedOrRenamed(this, 'getStyles', true);\n warnRemovedOrRenamed((this as typeof LitElement).prototype, 'adoptStyles');\n return true;\n };\n /* eslint-enable @typescript-eslint/no-explicit-any */\n}\n\n/**\n * END USERS SHOULD NOT RELY ON THIS OBJECT.\n *\n * Private exports for use by other Lit packages, not intended for use by\n * external users.\n *\n * We currently do not make a mangled rollup build of the lit-ssr code. In order\n * to keep a number of (otherwise private) top-level exports mangled in the\n * client side code, we export a _$LE object containing those members (or\n * helper methods for accessing private fields of those members), and then\n * re-export them for use in lit-ssr. This keeps lit-ssr agnostic to whether the\n * client-side code is being used in `dev` mode or `prod` mode.\n *\n * This has a unique name, to disambiguate it from private exports in\n * lit-html, since this module re-exports all of lit-html.\n *\n * @private\n */\nexport const _$LE = {\n _$attributeToProperty: (\n el: LitElement,\n name: string,\n value: string | null\n ) => {\n // eslint-disable-next-line\n (el as any)._$attributeToProperty(name, value);\n },\n // eslint-disable-next-line\n _$changedProperties: (el: LitElement) => (el as any)._$changedProperties,\n};\n\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for LitElement usage.\n(globalThis.litElementVersions ??= []).push('3.3.3');\nif (DEV_MODE && globalThis.litElementVersions.length > 1) {\n issueWarning!(\n 'multiple-versions',\n `Multiple versions of Lit loaded. Loading multiple versions ` +\n `is not recommended.`\n );\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/*\n * IMPORTANT: For compatibility with tsickle and the Closure JS compiler, all\n * property decorators (but not class decorators) in this file that have\n * an @ExportDecoratedItems annotation must be defined as a regular function,\n * not an arrow function.\n */\nimport {Constructor, ClassDescriptor} from './base.js';\n\n/**\n * Allow for custom element classes with private constructors\n */\ntype CustomElementClass = Omit<typeof HTMLElement, 'new'>;\n\nconst legacyCustomElement = (tagName: string, clazz: CustomElementClass) => {\n customElements.define(tagName, clazz as CustomElementConstructor);\n // Cast as any because TS doesn't recognize the return type as being a\n // subtype of the decorated class when clazz is typed as\n // `Constructor<HTMLElement>` for some reason.\n // `Constructor<HTMLElement>` is helpful to make sure the decorator is\n // applied to elements however.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return clazz as any;\n};\n\nconst standardCustomElement = (\n tagName: string,\n descriptor: ClassDescriptor\n) => {\n const {kind, elements} = descriptor;\n return {\n kind,\n elements,\n // This callback is called once the class is otherwise fully defined\n finisher(clazz: Constructor<HTMLElement>) {\n customElements.define(tagName, clazz);\n },\n };\n};\n\n/**\n * Class decorator factory that defines the decorated class as a custom element.\n *\n * ```js\n * @customElement('my-element')\n * class MyElement extends LitElement {\n * render() {\n * return html``;\n * }\n * }\n * ```\n * @category Decorator\n * @param tagName The tag name of the custom element to define.\n */\nexport const customElement =\n (tagName: string) =>\n (classOrDescriptor: CustomElementClass | ClassDescriptor) =>\n typeof classOrDescriptor === 'function'\n ? legacyCustomElement(tagName, classOrDescriptor)\n : standardCustomElement(tagName, classOrDescriptor as ClassDescriptor);\n", "/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/*\n * IMPORTANT: For compatibility with tsickle and the Closure JS compiler, all\n * property decorators (but not class decorators) in this file that have\n * an @ExportDecoratedItems annotation must be defined as a regular function,\n * not an arrow function.\n */\nimport {PropertyDeclaration, ReactiveElement} from '../reactive-element.js';\nimport {ClassElement} from './base.js';\n\nconst standardProperty = (\n options: PropertyDeclaration,\n element: ClassElement\n) => {\n // When decorating an accessor, pass it through and add property metadata.\n // Note, the `hasOwnProperty` check in `createProperty` ensures we don't\n // stomp over the user's accessor.\n if (\n element.kind === 'method' &&\n element.descriptor &&\n !('value' in element.descriptor)\n ) {\n return {\n ...element,\n finisher(clazz: typeof ReactiveElement) {\n clazz.createProperty(element.key, options);\n },\n };\n } else {\n // createProperty() takes care of defining the property, but we still\n // must return some kind of descriptor, so return a descriptor for an\n // unused prototype field. The finisher calls createProperty().\n return {\n kind: 'field',\n key: Symbol(),\n placement: 'own',\n descriptor: {},\n // store the original key so subsequent decorators have access to it.\n originalKey: element.key,\n // When @babel/plugin-proposal-decorators implements initializers,\n // do this instead of the initializer below. See:\n // https://github.com/babel/babel/issues/9260 extras: [\n // {\n // kind: 'initializer',\n // placement: 'own',\n // initializer: descriptor.initializer,\n // }\n // ],\n initializer(this: {[key: string]: unknown}) {\n if (typeof element.initializer === 'function') {\n this[element.key as string] = element.initializer.call(this);\n }\n },\n finisher(clazz: typeof ReactiveElement) {\n clazz.createProperty(element.key, options);\n },\n };\n }\n};\n\nconst legacyProperty = (\n options: PropertyDeclaration,\n proto: Object,\n name: PropertyKey\n) => {\n (proto.constructor as typeof ReactiveElement).createProperty(name, options);\n};\n\n/**\n * A property decorator which creates a reactive property that reflects a\n * corresponding attribute value. When a decorated property is set\n * the element will update and render. A {@linkcode PropertyDeclaration} may\n * optionally be supplied to configure property features.\n *\n * This decorator should only be used for public fields. As public fields,\n * properties should be considered as primarily settable by element users,\n * either via attribute or the property itself.\n *\n * Generally, properties that are changed by the element should be private or\n * protected fields and should use the {@linkcode state} decorator.\n *\n * However, sometimes element code does need to set a public property. This\n * should typically only be done in response to user interaction, and an event\n * should be fired informing the user; for example, a checkbox sets its\n * `checked` property when clicked and fires a `changed` event. Mutating public\n * properties should typically not be done for non-primitive (object or array)\n * properties. In other cases when an element needs to manage state, a private\n * property decorated via the {@linkcode state} decorator should be used. When\n * needed, state properties can be initialized via public properties to\n * facilitate complex interactions.\n *\n * ```ts\n * class MyElement {\n * @property({ type: Boolean })\n * clicked = false;\n * }\n * ```\n * @category Decorator\n * @ExportDecoratedItems\n */\nexport function property(options?: PropertyDeclaration) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (protoOrDescriptor: Object | ClassElement, name?: PropertyKey): any =>\n name !== undefined\n ? legacyProperty(options!, protoOrDescriptor as Object, name)\n : standardProperty(options!, protoOrDescriptor as ClassElement);\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/*\n * IMPORTANT: For compatibility with tsickle and the Closure JS compiler, all\n * property decorators (but not class decorators) in this file that have\n * an @ExportDecoratedItems annotation must be defined as a regular function,\n * not an arrow function.\n */\n\nimport {property} from './property.js';\n\nexport interface InternalPropertyDeclaration<Type = unknown> {\n /**\n * A function that indicates if a property should be considered changed when\n * it is set. The function should take the `newValue` and `oldValue` and\n * return `true` if an update should be requested.\n */\n hasChanged?(value: Type, oldValue: Type): boolean;\n}\n\n/**\n * Declares a private or protected reactive property that still triggers\n * updates to the element when it changes. It does not reflect from the\n * corresponding attribute.\n *\n * Properties declared this way must not be used from HTML or HTML templating\n * systems, they're solely for properties internal to the element. These\n * properties may be renamed by optimization tools like closure compiler.\n * @category Decorator\n */\nexport function state(options?: InternalPropertyDeclaration) {\n return property({\n ...options,\n state: true,\n });\n}\n", "/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/*\n * IMPORTANT: For compatibility with tsickle and the Closure JS compiler, all\n * property decorators (but not class decorators) in this file that have\n * an @ExportDecoratedItems annotation must be defined as a regular function,\n * not an arrow function.\n */\n\nimport {decorateProperty} from './base.js';\n\nimport type {ReactiveElement} from '../reactive-element.js';\nimport type {QueryAssignedNodesOptions} from './query-assigned-nodes.js';\n\nconst NODE_MODE = false;\nconst global = NODE_MODE ? globalThis : window;\n\n/**\n * A tiny module scoped polyfill for HTMLSlotElement.assignedElements.\n */\nconst slotAssignedElements =\n global.HTMLSlotElement?.prototype.assignedElements != null\n ? (slot: HTMLSlotElement, opts?: AssignedNodesOptions) =>\n slot.assignedElements(opts)\n : (slot: HTMLSlotElement, opts?: AssignedNodesOptions) =>\n slot\n .assignedNodes(opts)\n .filter(\n (node): node is Element => node.nodeType === Node.ELEMENT_NODE\n );\n\n/**\n * Options for the {@linkcode queryAssignedElements} decorator. Extends the\n * options that can be passed into\n * [HTMLSlotElement.assignedElements](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSlotElement/assignedElements).\n */\nexport interface QueryAssignedElementsOptions\n extends QueryAssignedNodesOptions {\n /**\n * CSS selector used to filter the elements returned. For example, a selector\n * of `\".item\"` will only include elements with the `item` class.\n */\n selector?: string;\n}\n\n/**\n * A property decorator that converts a class property into a getter that\n * returns the `assignedElements` of the given `slot`. Provides a declarative\n * way to use\n * [`HTMLSlotElement.assignedElements`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSlotElement/assignedElements).\n *\n * Can be passed an optional {@linkcode QueryAssignedElementsOptions} object.\n *\n * Example usage:\n * ```ts\n * class MyElement {\n * @queryAssignedElements({ slot: 'list' })\n * listItems!: Array<HTMLElement>;\n * @queryAssignedElements()\n * unnamedSlotEls!: Array<HTMLElement>;\n *\n * render() {\n * return html`\n * <slot name=\"list\"></slot>\n * <slot></slot>\n * `;\n * }\n * }\n * ```\n *\n * Note, the type of this property should be annotated as `Array<HTMLElement>`.\n *\n * @category Decorator\n */\nexport function queryAssignedElements(options?: QueryAssignedElementsOptions) {\n const {slot, selector} = options ?? {};\n return decorateProperty({\n descriptor: (_name: PropertyKey) => ({\n get(this: ReactiveElement) {\n const slotSelector = `slot${slot ? `[name=${slot}]` : ':not([name])'}`;\n const slotEl =\n this.renderRoot?.querySelector<HTMLSlotElement>(slotSelector);\n const elements =\n slotEl != null ? slotAssignedElements(slotEl, options) : [];\n if (selector) {\n return elements.filter((node) => node.matches(selector));\n }\n return elements;\n },\n enumerable: true,\n configurable: true,\n }),\n });\n}\n", "import { html } from \"lit\";\n\nexport default function Ad4mLogo() {\n return html`\n <svg viewBox=\"0 0 63.6 60\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path fill=\"currentColor\" d=\"M63.2781 52.9928C62.4038 47.0393 59.8345 41.4763 55.9242 36.935C55.9403 36.5766 55.951 36.2182 55.951 35.8545C55.951 26.6328 50.7373 18.6039 43.0937 14.5333C41.093 9.35009 37.7352 4.72854 33.2402 1.14469L31.7705 0L30.2793 1.10725L30.2096 1.16074C25.7253 4.74458 22.3729 9.36079 20.3775 14.5386C12.7339 18.6039 7.52021 26.6328 7.52021 35.8599C7.52021 36.2236 7.53094 36.582 7.54703 36.9404C3.6421 41.471 1.06742 47.034 0.198465 52.9874L0 54.9131L1.70036 55.5817C5.40683 57.0313 9.32249 57.7695 13.3401 57.7695C15.668 57.7695 17.9369 57.5127 20.1254 57.0366C23.5744 58.9248 27.533 60 31.7383 60C35.9436 60 39.9022 58.9248 43.3512 57.0366C45.5397 57.5127 47.8086 57.7695 50.1365 57.7695C54.1541 57.7695 58.0698 57.0366 61.7762 55.5817L63.5624 54.881L63.2835 52.9874L63.2781 52.9928ZM42.5734 51.8802C40.0792 51.1581 37.7352 50.0829 35.595 48.7189C39.752 44.675 42.8041 39.5079 44.263 33.7202C46.1297 34.6938 47.8891 35.8866 49.4982 37.288C49.9917 37.716 50.4637 38.1653 50.9197 38.6253C50.1258 44.1294 46.9986 48.8954 42.568 51.8855L42.5734 51.8802ZM12.5516 38.62C13.0075 38.1599 13.4849 37.716 13.973 37.288C15.5822 35.8866 17.3415 34.6938 19.2082 33.7202C20.6672 39.5079 23.7192 44.675 27.8763 48.7189C25.7361 50.0829 23.392 51.1527 20.8978 51.8802C16.4672 48.8901 13.3401 44.1241 12.5462 38.62H12.5516ZM40.3957 25.9802C40.3957 26.3332 40.3903 26.6809 40.3742 27.0286C37.585 26.2477 34.6831 25.8411 31.7383 25.8411C28.7935 25.8411 25.8916 26.2477 23.1024 27.0286C23.0917 26.6809 23.0809 26.3279 23.0809 25.9802C23.0809 23.2362 23.494 20.5563 24.2825 18.0102C26.5782 17.0527 29.0993 16.5231 31.7383 16.5231C34.3773 16.5231 36.8984 17.0527 39.1941 18.0102C39.9826 20.5563 40.3957 23.2362 40.3957 25.9802ZM23.73 31.8641C26.3047 31.0671 29.0027 30.6553 31.7383 30.6553C34.4739 30.6553 37.1719 31.0671 39.7466 31.8641C38.5344 37.2827 35.6808 42.0915 31.7383 45.7395C27.7958 42.0861 24.9422 37.2773 23.73 31.8641ZM50.7641 32.1262C48.9887 30.8104 47.0898 29.6817 45.0998 28.7671C45.1803 27.847 45.2232 26.9163 45.2232 25.9802C45.2232 24.536 45.1266 23.1131 44.9335 21.7063C47.8676 24.4343 49.9595 28.0503 50.7641 32.1262ZM31.7383 6.19417C33.6639 7.97005 35.2946 9.99198 36.6087 12.1904C35.0371 11.8695 33.4065 11.6983 31.7383 11.6983C30.0701 11.6983 28.4395 11.8695 26.8679 12.1904C28.182 9.99198 29.8127 7.97005 31.7383 6.19417ZM18.5431 21.701C18.3553 23.1078 18.2534 24.5306 18.2534 25.9749C18.2534 26.9163 18.2963 27.8417 18.3768 28.7617C16.3868 29.6764 14.4879 30.805 12.7125 32.1209C13.5171 28.0449 15.6036 24.429 18.5377 21.701H18.5431ZM5.33173 51.7518C5.9915 48.7938 7.15547 45.9802 8.74855 43.418C9.95007 47.034 11.9776 50.2808 14.622 52.9179C14.1983 52.9393 13.7692 52.95 13.3401 52.95C10.5991 52.95 7.91178 52.5488 5.32637 51.7465L5.33173 51.7518ZM31.7383 55.1859C30.1506 55.1859 28.6058 54.988 27.1307 54.6296C28.7452 53.854 30.29 52.95 31.7383 51.923C33.1866 52.95 34.7314 53.854 36.3459 54.6296C34.8655 54.988 33.326 55.1859 31.7383 55.1859ZM50.1365 52.95C49.7074 52.95 49.2783 52.9339 48.8546 52.9179C51.499 50.2808 53.5265 47.0393 54.728 43.4234C56.3211 45.9802 57.4851 48.7938 58.1449 51.7518C55.5648 52.5488 52.8775 52.95 50.1365 52.95Z\" />\n </svg>\n `;\n}\n", "import { html } from \"lit\";\n\nexport default function LocalIcon() {\n return html`\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\">\n <circle cx=\"12\" cy=\"12\" r=\"10\"></circle>\n <circle cx=\"12\" cy=\"12\" r=\"3\" fill=\"currentColor\"></circle>\n </svg>\n `;\n}\n", "import { html } from \"lit\";\n\nexport default function RemoteIcon() {\n return html`\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\">\n <circle cx=\"12\" cy=\"12\" r=\"10\"></circle>\n <path d=\"M2 12h20\"></path>\n <path d=\"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z\"></path>\n </svg>\n `;\n}", "import { html } from \"lit\";\n\nexport default function DownloadIcon() {\n return html`\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n <path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\"></path>\n <polyline points=\"7 10 12 15 17 10\"></polyline>\n <line x1=\"12\" y1=\"15\" x2=\"12\" y2=\"3\"></line>\n </svg>\n `;\n}", "import { html } from \"lit\";\n\nexport default function CheckIcon() {\n return html`\n <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\">\n <rect width=\"256\" height=\"256\" fill=\"none\"/>\n <polyline points=\"40 144 96 200 224 72\" fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"16\"/>\n </svg>\n `;\n}", "import { html } from \"lit\";\n\nexport default function CrossIcon() {\n return html`\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"32\" height=\"32\" fill=\"currentColor\" viewBox=\"0 0 256 256\">\n <path d=\"M205.66,194.34a8,8,0,0,1-11.32,11.32L128,139.31,61.66,205.66a8,8,0,0,1-11.32-11.32L116.69,128,50.34,61.66A8,8,0,0,1,61.66,50.34L128,116.69l66.34-66.35a8,8,0,0,1,11.32,11.32L139.31,128Z\"></path>\n </svg>\n `;\n}", "import { html } from \"lit\";\n\nexport default function RefreshIcon() {\n return html`\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\" fill=\"currentColor\" class=\"bi bi-arrow-clockwise\" viewBox=\"0 0 16 16\">\n <path fill-rule=\"evenodd\" d=\"M8 3a5 5 0 1 0 4.546 2.914.5.5 0 0 1 .908-.417A6 6 0 1 1 8 2z\"/>\n <path d=\"M8 4.466V.534a.25.25 0 0 1 .41-.192l2.36 1.966c.12.1.12.284 0 .384L8.41 4.658A.25.25 0 0 1 8 4.466\"/>\n </svg>\n `;\n}", "import { html } from \"lit\";\n\nexport default function ArrowLeftRightIcon() {\n return html`\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\" fill=\"currentColor\" class=\"bi bi-arrow-left-right\" viewBox=\"0 0 16 16\">\n <path fill-rule=\"evenodd\" d=\"M1 11.5a.5.5 0 0 0 .5.5h11.793l-3.147 3.146a.5.5 0 0 0 .708.708l4-4a.5.5 0 0 0 0-.708l-4-4a.5.5 0 0 0-.708.708L13.293 11H1.5a.5.5 0 0 0-.5.5m14-7a.5.5 0 0 1-.5.5H2.707l3.147 3.146a.5.5 0 1 1-.708.708l-4-4a.5.5 0 0 1 0-.708l4-4a.5.5 0 1 1 .708.708L2.707 4H14.5a.5.5 0 0 1 .5.5\"/>\n </svg>\n `;\n}", "import { html } from \"lit\";\n\nexport default function ArrowLeftIcon() {\n return html`\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\" fill=\"currentColor\" class=\"bi bi-arrow-left\" viewBox=\"0 0 16 16\">\n <path fill-rule=\"evenodd\" d=\"M15 8a.5.5 0 0 0-.5-.5H2.707l3.147-3.146a.5.5 0 1 0-.708-.708l-4 4a.5.5 0 0 0 0 .708l4 4a.5.5 0 0 0 .708-.708L2.707 8.5H14.5A.5.5 0 0 0 15 8\"/>\n </svg>\n `;\n}", "import { html } from \"lit\";\n\nexport default function GlobeIcon() {\n return html`\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n <circle cx=\"12\" cy=\"12\" r=\"10\"></circle>\n <path d=\"M2 12h20\"></path>\n <path d=\"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z\"></path>\n </svg>\n `;\n}\n", "import { html } from \"lit\";\n\nexport default function CreditIcon() {\n return html`\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n <circle cx=\"12\" cy=\"12\" r=\"10\"></circle>\n <path d=\"M12 6v12\"></path>\n <path d=\"M15.5 9.5a3 3 0 0 0-3-2.5H11a3 3 0 0 0 0 6h2a3 3 0 0 1 0 6h-1.5a3 3 0 0 1-3-2.5\"></path>\n </svg>\n `;\n}\n", "import { html } from \"lit\";\n\nexport default function WalletIcon() {\n return html`\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n <rect x=\"2\" y=\"6\" width=\"20\" height=\"14\" rx=\"2\"></rect>\n <path d=\"M2 10h20\"></path>\n <circle cx=\"16\" cy=\"14\" r=\"1\" fill=\"currentColor\"></circle>\n </svg>\n `;\n}\n", "import { html } from \"lit\";\n\nexport default function MapPinIcon() {\n return html`\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"14\" height=\"14\" fill=\"currentColor\" viewBox=\"0 0 16 16\">\n <path d=\"M8 16s6-5.686 6-10A6 6 0 0 0 2 6c0 4.314 6 10 6 10m0-7a3 3 0 1 1 0-6 3 3 0 0 1 0 6\"/>\n </svg>\n `;\n}\n", "import { css } from \"lit\";\n\n/**\n * Shared styles for all ad4m-connect components\n * Includes typography, buttons, inputs, and common utilities\n */\nexport const sharedStyles = css`\n * {\n box-sizing: border-box;\n }\n\n /* Typography */\n h1, h2, h3, p {\n margin: 0;\n text-align: center;\n }\n\n h1 {\n font-size: 28px;\n line-height: 1;\n font-weight: 700;\n margin-bottom: 20px;\n color: #ffffff;\n }\n\n h2 {\n font-size: 22px;\n line-height: 1;\n font-weight: 700;\n margin-bottom: 20px;\n color: #ffffff;\n }\n\n h3 {\n font-size: 18px;\n line-height: 1;\n font-weight: 400;\n color: #f0f0f0;\n }\n\n p {\n margin: 0;\n font-size: 16px;\n line-height: 1.5;\n color: rgba(255, 255, 255, 0.8);\n }\n\n /* Buttons */\n button {\n display: flex;\n justify-content: center;\n align-items: center;\n gap: 12px;\n height: 48px;\n padding: 0 24px;\n border-radius: 8px;\n font-size: 16px;\n font-weight: 600;\n cursor: pointer;\n transition: all 0.2s ease;\n border: none;\n outline: none;\n }\n\n button:focus-visible {\n outline: 2px solid var(--ac-primary-color);\n outline-offset: 2px;\n }\n\n button svg {\n width: 25px;\n height: 25px;\n }\n\n button.primary {\n background: var(--ac-primary-color);\n color: #000000;\n }\n\n button.primary:hover:not(:disabled) {\n background: var(--ac-primary-color-light);\n }\n\n button.secondary {\n background: #00091e5c;\n color: var(--ac-primary-color);\n border: 1px solid var(--ac-primary-color);\n }\n\n button.secondary:hover:not(:disabled) {\n background: #00091e73;\n color: var(--ac-primary-color-light);\n }\n\n button.secondary:focus-visible:not(:disabled) {\n outline: 2px solid var(--ac-primary-color-light);\n outline-offset: 2px;\n box-shadow: 0 0 0 4px rgba(255, 255, 255, 0.2);\n }\n\n button.danger {\n background: var(--ac-danger-color);\n }\n\n button.danger:hover:not(:disabled) {\n background: #c8165b;\n }\n\n button.danger:focus-visible:not(:disabled) {\n outline: 2px solid var(--ac-danger-color);\n outline-offset: 2px;\n box-shadow: 0 0 0 4px rgba(244, 54, 127, 0.2);\n }\n\n button.danger-secondary {\n background: #00091e5c;\n color: var(--ac-danger-color);\n border: 1px solid var(--ac-danger-color);\n }\n\n button.danger-secondary:hover:not(:disabled) {\n background: rgba(244, 54, 127, 0.12);\n }\n\n button.danger-secondary:focus-visible:not(:disabled) {\n outline: 2px solid var(--ac-danger-color);\n outline-offset: 2px;\n box-shadow: 0 0 0 4px rgba(244, 54, 127, 0.2);\n }\n\n button:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n button.full {\n width: 100%;\n }\n\n .close-button {\n position: absolute;\n top: 20px;\n right: 20px;\n cursor: pointer;\n }\n\n .close-button svg {\n width: 28px;\n height: 28px;\n color: white;\n opacity: 0.5;\n }\n\n .back-button {\n all: unset;\n display: inline-flex;\n align-items: center;\n gap: 4px;\n cursor: pointer;\n font-size: 14px;\n color: rgba(255, 255, 255, 0.5);\n }\n\n .back-button svg {\n width: 22px;\n height: 22px;\n }\n\n .back-button:hover {\n color: rgba(255, 255, 255, 0.8);\n }\n\n /* Inputs */\n input {\n width: 100%;\n height: 48px;\n padding: 0 16px;\n border-radius: 8px;\n box-shadow: 0 0 0 1px var(--ac-border-color-light);\n background: #00091e5c;\n color: #ffffff;\n font-size: 18px;\n border: none;\n outline: none;\n transition: all 0.2s ease;\n }\n\n input:focus, input:hover {\n box-shadow: 0 0 0 1px var(--ac-primary-color);\n background: #00091e73;\n }\n\n input:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n input::placeholder {\n color: rgba(255, 255, 255, 0.4);\n }\n\n input[type=\"number\"]::-webkit-inner-spin-button,\n input[type=\"number\"]::-webkit-outer-spin-button {\n -webkit-appearance: none;\n margin: 0;\n }\n\n input[type=\"number\"] {\n -moz-appearance: textfield;\n }\n\n /* Common layout utilities */\n .row {\n display: flex;\n align-items: center;\n gap: 12px;\n }\n\n .center {\n display: flex;\n justify-content: center;\n }\n \n .header {\n text-align: center;\n }\n\n .container {\n display: flex;\n flex-direction: column;\n gap: 30px;\n padding: 2px;\n }\n\n .box {\n display: flex;\n flex-direction: column;\n align-items: center;\n background: rgba(128, 178, 201, 0.14);\n box-shadow: 0 0 0 1px var(--ac-border-color-light);\n border-radius: 8px;\n padding: 20px;\n gap: 25px;\n transition: all 0.3s ease;\n }\n\n .box-header {\n display: flex;\n align-items: center;\n gap: 10px;\n margin-bottom: -8px;\n }\n\n .box-header h3 {\n font-weight: 600;\n }\n\n .box-header svg {\n width: 24px;\n height: 24px;\n stroke-width: 2;\n flex-shrink: 0;\n color: var(--ac-primary-color);\n }\n\n /* State indicators */\n .state {\n display: flex;\n align-items: center;\n gap: 8px;\n }\n\n .state.danger {\n margin-bottom: -8px;\n }\n\n .state.success svg {\n width: 26px;\n height: 26px;\n }\n\n .state.danger svg {\n width: 30px;\n height: 30px;\n }\n\n .state.success p,\n .state.success svg {\n color: var(--ac-success-color);\n }\n\n .state.danger p,\n .state.danger svg {\n color: var(--ac-danger-color);\n }\n\n /* Spinners */\n .spinner {\n width: 24px;\n height: 24px;\n border: 3px solid var(--ac-border-color-light);\n border-top-color: var(--ac-primary-color);\n border-radius: 50%;\n animation: spin 0.8s linear infinite;\n }\n\n @keyframes spin {\n to { transform: rotate(360deg); }\n }\n`;\n", "import { LitElement, html, css, PropertyValues } from \"lit\";\nimport { customElement, property, state } from \"lit/decorators.js\";\nimport { sharedStyles } from \"../../styles/shared-styles\";\nimport { DownloadIcon, LocalIcon, RefreshIcon, CheckIcon, GlobeIcon } from \"../icons\";\nimport CrossIcon from \"../icons/CrossIcon\";\nimport { checkConnection } from \"../../utils\";\n\n@customElement(\"connection-options\")\nexport class ConnectionOptions extends LitElement {\n @property({ type: Number }) port: number;\n @property({ type: Boolean }) showHosting: boolean = false;\n\n @state() private loading = true;\n @state() private localNodeDetected = false;\n @state() private newPort = 0;\n @state() private isMobile = false;\n\n static styles = [\n sharedStyles,\n css`\n .options {\n display: flex;\n flex-direction: column;\n gap: 30px;\n }\n\n .port-input {\n display: flex;\n justify-content: center;\n gap: 8px;\n width: 100%;\n }\n\n .port-input button {\n width: auto;\n }\n\n .url-display {\n margin: 8px 0 16px 0;\n font-size: 12px;\n opacity: 0.7;\n font-family: monospace;\n word-break: break-all;\n }\n\n button {\n width: 100%;\n }\n `\n ];\n\n private async changePort() {\n this.dispatchEvent(new CustomEvent(\"change-port\", { detail: { port: this.newPort }, bubbles: true, composed: true }));\n }\n\n private async connectLocalNode() {\n this.dispatchEvent(new CustomEvent(\"connect-local-node\", { bubbles: true, composed: true }));\n }\n\n private browseHosts() {\n this.dispatchEvent(new CustomEvent(\"browse-hosts\", { bubbles: true, composed: true }));\n }\n\n private async detectLocalNode() {\n try {\n // Try 127.0.0.1 first (more reliable in sandboxed/headless environments),\n // fall back to localhost\n try {\n await checkConnection(`http://127.0.0.1:${this.newPort}`, 3000);\n } catch {\n await checkConnection(`http://localhost:${this.newPort}`, 3000);\n }\n this.localNodeDetected = true;\n } catch (error) {\n console.log(\"[Ad4m Connect] Local detection failed:\", error);\n this.localNodeDetected = false;\n }\n }\n\n private refreshPort() {\n this.changePort();\n this.detectLocalNode();\n }\n\n private checkMobile = () => {\n this.isMobile = window.innerWidth < 800;\n };\n\n async connectedCallback() {\n super.connectedCallback();\n this.newPort = this.port;\n this.checkMobile();\n window.addEventListener('resize', this.checkMobile);\n await this.detectLocalNode();\n this.loading = false;\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n window.removeEventListener('resize', this.checkMobile);\n }\n\n willUpdate(changedProps: PropertyValues) {\n if (changedProps.has('port')) this.newPort = this.port;\n }\n\n render() {\n if (this.loading) return null;\n\n return html`\n <div class=\"container\">\n <div class=\"header\">\n <h1>Connect AD4M</h1>\n <h3>How would you like to connect?</h3>\n </div>\n\n <div class=\"options\">\n ${!this.isMobile || !this.showHosting ? html`\n <div class=\"box\">\n <div class=\"box-header\">\n ${LocalIcon()}\n <h3>Local Node</h3>\n </div>\n\n ${this.localNodeDetected\n ? html`\n <div class=\"state success\">\n ${CheckIcon()}\n <p>Local node detected on port ${this.port}</p>\n </div>\n\n <button class=\"primary\" @click=${this.connectLocalNode}>\n Connect to Local Node\n </button>\n `\n : html`\n <div class=\"state danger\">\n ${CrossIcon()}\n <p>No local node detected on port ${this.port}</p>\n </div>\n\n <p style=\"margin-bottom: -12px\">Download and install AD4M</p>\n <button class=\"secondary\" @click=${() => window.open(\"https://github.com/coasys/ad4m/releases\")}>\n ${DownloadIcon()} Download AD4M\n </button>\n `\n }\n\n <p style=\"margin-bottom: -12px\">Or try another port</p>\n <div class=\"port-input\">\n <input\n type=\"number\"\n placeholder=\"Port number...\"\n .value=${this.newPort != null ? this.newPort.toString() : ''}\n @input=${(e: Event) => {\n const input = e.target as HTMLInputElement;\n const next = Number.parseInt(input.value, 10);\n if (Number.isFinite(next)) this.newPort = next;\n }}\n @keydown=${(e: KeyboardEvent) => {\n if (e.key === 'Enter') this.refreshPort();\n }}\n />\n <button class=\"primary\" @click=${this.refreshPort}>\n ${RefreshIcon()}\n </button>\n </div>\n </div>\n ` : ''}\n\n ${this.showHosting ? html`\n <div class=\"box\">\n <div class=\"box-header\">\n ${GlobeIcon()}\n <h3>Remote Node</h3>\n </div>\n\n <p>Browse hosted AD4M nodes or enter a URL</p>\n\n <button class=\"primary\" @click=${this.browseHosts}>\n Connect to Remote Node\n </button>\n </div>\n ` : '' }\n </div>\n </div>\n `;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n \"connection-options\": ConnectionOptions;\n }\n}", "import { LitElement, html, css } from \"lit\";\r\nimport { customElement, property, state } from \"lit/decorators.js\";\r\nimport { capSentence } from \"@coasys/ad4m\";\r\nimport { sharedStyles } from \"../../styles/shared-styles\";\r\nimport { Ad4mLogo, ArrowLeftRightIcon, CheckIcon, CrossIcon } from \"../icons\";\r\n\r\n@customElement(\"local-authentication\")\r\nexport class LocalAuthentication extends LitElement {\r\n @property({ type: Array }) capabilities: string[] = [];\r\n @property({ type: String }) appname = \"\";\r\n @property({ type: String }) appiconpath = \"\";\r\n @property({ type: Boolean }) verificationError = false;\r\n\r\n @state() private requestSent = false;\r\n @state() private securityCode: string = \"\";\r\n @state() private verifying = false;\r\n\r\n static styles = [\r\n sharedStyles,\r\n css` \r\n h1 {\r\n font-size: 34px;\r\n }\r\n\r\n .connection-icons {\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n gap: 20px;\r\n margin: 20px 0;\r\n }\r\n\r\n .app-image {\r\n width: 100px;\r\n height: 100px;\r\n border-radius: 16px;\r\n object-fit: cover;\r\n }\r\n\r\n .app-initial {\r\n width: 100px;\r\n height: 100px;\r\n border-radius: 50%;\r\n border: 2px solid var(--ac-border-color-light);\r\n }\r\n\r\n .arrow-icon svg {\r\n width: 34px;\r\n height: 34px;\r\n color: white;\r\n opacity: 0.5;\r\n }\r\n\r\n .ad4m-logo svg {\r\n width: 100px;\r\n height: 100px;\r\n color: var(--ac-primary-color);\r\n }\r\n\r\n .box {\r\n list-style: none;\r\n margin: 0 0 20px 0;\r\n }\r\n\r\n .box li {\r\n display: flex;\r\n align-items: center;\r\n gap: 20px;\r\n }\r\n\r\n .box p {\r\n text-align: left;\r\n }\r\n\r\n .box svg {\r\n width: 26px;\r\n height: 26px;\r\n color: var(--ac-success-color);\r\n flex-shrink: 0;\r\n }\r\n\r\n .security-code {\r\n width: 100%;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n gap: 12px;\r\n margin-bottom: 20px;\r\n }\r\n\r\n .security-code input {\r\n width: 194px;\r\n font-size: 36px;\r\n letter-spacing: 8px;\r\n height: 60px;\r\n font-family: system-ui, -apple-system, sans-serif;\r\n font-variant-numeric: tabular-nums;\r\n padding: 0 0 0 16px;\r\n }\r\n\r\n .state {\r\n justify-content: center;\r\n }\r\n `\r\n ];\r\n\r\n willUpdate(changedProps: import(\"lit\").PropertyValues) {\r\n if (changedProps.has('verificationError') && this.verificationError) {\r\n this.verifying = false;\r\n }\r\n }\r\n\r\n private requestCapability() {\r\n this.dispatchEvent(new CustomEvent(\"request-capability\", { bubbles: true, composed: true }));\r\n this.requestSent = true;\r\n }\r\n\r\n private verifyCode() {\r\n this.verifying = true;\r\n this.dispatchEvent(new CustomEvent(\"verify-code\", { detail: { code: this.securityCode }, bubbles: true, composed: true }));\r\n }\r\n\r\n private onInputChange(e: Event) {\r\n // Clear any previous error when user starts typing\r\n this.dispatchEvent(new CustomEvent(\"clear-verification-error\", { bubbles: true, composed: true }));\r\n\r\n // Allow only digits and limit to 6 characters\r\n const input = e.target as HTMLInputElement;\r\n const cleaned = input.value.replace(/\\D/g, '').slice(0, 6);\r\n input.value = cleaned;\r\n this.securityCode = cleaned;\r\n\r\n // Auto-verify when 6 digits entered\r\n if (this.securityCode.length === 6) this.verifyCode();\r\n }\r\n\r\n render() {\r\n return html`\r\n <div class=\"container\">\r\n <div class=\"header\">\r\n <h1>${this.appname}</h1>\r\n <h3>wants to access your AD4M data</h3>\r\n </div>\r\n\r\n <div class=\"connection-icons\">\r\n ${this.appiconpath\r\n ? html`<img class=\"app-image\" src=${this.appiconpath} alt=\"App Logo\" />`\r\n : html`<div class=\"app-initial\">${this.appname.charAt(0).toUpperCase()}</div>`\r\n }\r\n <div class=\"arrow-icon\">${ArrowLeftRightIcon()}</div>\r\n <div class=\"ad4m-logo\">${Ad4mLogo()}</div>\r\n </div>\r\n\r\n ${!this.requestSent\r\n ? html`\r\n <p>This will allow ${this.appname} to</p>\r\n \r\n <ul class=\"box\">\r\n ${this.capabilities.map((cap) => html`<li>${CheckIcon()}<p>${capSentence(cap)}</p></li>`)}\r\n </ul>\r\n\r\n <div class=\"row center\">\r\n <button class=\"primary\" @click=${this.requestCapability}>\r\n Authorize\r\n </button>\r\n </div>\r\n `\r\n : html`\r\n <div class=\"state success\" style=\"margin-bottom: -12px\">\r\n ${CheckIcon()}\r\n <p>Auth request sent to local AD4M node</p>\r\n </div>\r\n\r\n <p>Enter the security code from your AD4M launcher</p>\r\n\r\n <div class=\"security-code\">\r\n <input\r\n type=\"text\"\r\n maxlength=\"6\"\r\n inputmode=\"numeric\"\r\n pattern=\"[0-9]{6}\"\r\n placeholder=\"000000\"\r\n .value=${this.securityCode || \"\"}\r\n @input=${this.onInputChange}\r\n />\r\n ${this.verifying ? html`<div class=\"spinner\"></div>` : ''}\r\n </div>\r\n\r\n ${this.verificationError\r\n ? html`\r\n <div class=\"state danger\" style=\"margin-top: -32px; margin-bottom: 20px;\">\r\n ${CrossIcon()}\r\n <p>Verification failed. Please try again.</p>\r\n </div>\r\n `\r\n : ''\r\n }\r\n `\r\n }\r\n </div>\r\n `;\r\n }\r\n}\r\n\r\ndeclare global {\r\n interface HTMLElementTagNameMap {\r\n \"local-authentication\": LocalAuthentication;\r\n }\r\n}\r\n", "import { LitElement, html, css } from \"lit\";\r\nimport { customElement, property, state } from \"lit/decorators.js\";\r\nimport { VerificationRequestResult } from \"@coasys/ad4m\";\r\nimport { sharedStyles } from \"../../styles/shared-styles\";\r\nimport { CheckIcon, CrossIcon } from \"../icons\";\r\nimport type { RemoteHost } from \"../../types\";\r\n\r\n@customElement(\"remote-authentication\")\r\nexport class RemoteAuthentication extends LitElement {\r\n @property({ type: Object }) remoteAuthState: VerificationRequestResult | null = null;\r\n @property({ type: Boolean }) remoteAuthLoading: boolean = false;\r\n @property({ type: Boolean }) emailCodeError: boolean = false;\r\n @property({ type: Boolean }) passwordError: boolean = false;\r\n @property({ type: Boolean }) accountCreationError: boolean = false;\r\n @property({ type: Object }) host: RemoteHost | null = null;\r\n\r\n @state() private email = \"\";\r\n @state() private password = \"\";\r\n @state() private emailSecurityCode: string = \"\";\r\n @state() private confirmPassword: string = \"\";\r\n\r\n static styles = [\r\n sharedStyles,\r\n css`\r\n .header h1 {\r\n font-size: 32px;\r\n margin-bottom: 0;\r\n }\r\n \r\n .input-row {\r\n display: flex;\r\n justify-content: center;\r\n }\r\n\r\n .input-row input {\r\n width: 280px;\r\n }\r\n\r\n .login-button {\r\n display: flex;\r\n justify-content: center;\r\n }\r\n\r\n .security-code {\r\n width: 100%;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n gap: 12px;\r\n margin-bottom: 20px;\r\n }\r\n\r\n .security-code input {\r\n width: 194px;\r\n font-size: 36px;\r\n letter-spacing: 8px;\r\n height: 60px;\r\n font-family: system-ui, -apple-system, sans-serif;\r\n font-variant-numeric: tabular-nums;\r\n padding: 0 0 0 16px;\r\n }\r\n\r\n .password-input {\r\n display: flex;\r\n justify-content: center;\r\n margin-bottom: 20px;\r\n }\r\n\r\n .state {\r\n justify-content: center;\r\n }\r\n `\r\n ];\r\n\r\n private emailLogin() {\r\n this.dispatchEvent(new CustomEvent(\"email-login\", { detail: { email: this.email.trim() }, bubbles: true, composed: true }));\r\n }\r\n\r\n disconnectedCallback() {\r\n super.disconnectedCallback();\r\n this.clearSensitiveState();\r\n }\r\n\r\n private clearSensitiveState() {\r\n this.password = \"\";\r\n this.confirmPassword = \"\";\r\n this.emailSecurityCode = \"\";\r\n this.email = \"\";\r\n }\r\n\r\n private tryAgain() {\r\n this.clearSensitiveState();\r\n this.dispatchEvent(new CustomEvent(\"reset-auth-state\", { bubbles: true, composed: true }));\r\n }\r\n\r\n private verifyEmailCode() {\r\n this.dispatchEvent(new CustomEvent(\"verify-email-code\", { detail: { email: this.email.trim(), code: this.emailSecurityCode }, bubbles: true, composed: true }));\r\n }\r\n\r\n private passwordLogin() {\r\n this.dispatchEvent(new CustomEvent(\"password-login\", { detail: { email: this.email.trim(), password: this.password }, bubbles: true, composed: true }));\r\n }\r\n\r\n private createAccount() {\r\n this.dispatchEvent(new CustomEvent(\"create-account\", { detail: { email: this.email.trim(), password: this.password }, bubbles: true, composed: true }));\r\n }\r\n\r\n private onEmailSecurityCodeChange(e: Event) {\r\n // Clear any previous error when user starts typing\r\n this.dispatchEvent(new CustomEvent(\"clear-email-code-error\", { bubbles: true, composed: true }));\r\n\r\n // Allow only digits and limit to 6 characters\r\n const input = e.target as HTMLInputElement;\r\n const cleaned = input.value.replace(/\\D/g, '').slice(0, 6);\r\n input.value = cleaned;\r\n this.emailSecurityCode = cleaned;\r\n\r\n // Auto-verify when 6 digits entered (only if not already verifying)\r\n if (this.emailSecurityCode.length === 6 && !this.remoteAuthLoading) {\r\n this.verifyEmailCode();\r\n }\r\n }\r\n\r\n private get passwordsMatch(): boolean {\r\n return this.password.length > 0 && this.password === this.confirmPassword;\r\n }\r\n\r\n private isValidEmail(): boolean {\r\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\r\n return emailRegex.test(this.email.trim());\r\n }\r\n\r\n render() {\r\n const showEmailInput = !this.remoteAuthState;\r\n const showEmailCodeInput = this.remoteAuthState && this.remoteAuthState.success && !this.remoteAuthState.requiresPassword;\r\n const showLoginPasswordInput = this.remoteAuthState && this.remoteAuthState.requiresPassword && this.remoteAuthState.isExistingUser;\r\n const showSignUpPasswordInput = this.remoteAuthState && this.remoteAuthState.requiresPassword && !this.remoteAuthState.isExistingUser;\r\n const showEmailSubmitError = this.remoteAuthState && !this.remoteAuthState.success && !this.remoteAuthState.requiresPassword;\r\n\r\n return html`\r\n <div class=\"container\">\r\n <div class=\"header\">\r\n <h1 style=\"font-size: 28px;\">${showLoginPasswordInput ? 'Login' : showSignUpPasswordInput ? 'Register' : 'Login or Register'}</h1>\r\n ${this.host ? html`<p style=\"font-size: 15px; color: rgba(255,255,255,0.4); margin-top: 10px;\">${this.host.url}</p>` : ''}\r\n </div>\r\n\r\n ${showEmailInput ?\r\n html`\r\n <h3>Enter your email to login to ${this.host ? html`<strong>${this.host.name}</strong>` : 'the remote node'}</h3>\r\n\r\n <div class=\"input-row\">\r\n <input\r\n type=\"email\"\r\n placeholder=\"email@example.com\"\r\n .value=${this.email || \"\"}\r\n @input=${(e: Event) => {\r\n const input = e.target as HTMLInputElement;\r\n this.email = input.value;\r\n }}\r\n @keydown=${(e: KeyboardEvent) => {\r\n if (e.key === 'Enter' && !this.remoteAuthLoading && this.isValidEmail()) {\r\n this.emailLogin();\r\n }\r\n }}\r\n />\r\n </div>\r\n\r\n <div class=\"login-button\" style=\"margin-top: 10px;\">\r\n <button class=\"primary\" @click=${this.emailLogin} .disabled=${this.remoteAuthLoading || !this.isValidEmail()}>\r\n ${this.remoteAuthLoading ? \"Loading...\" : \"Continue\"}\r\n </button>\r\n </div>\r\n `\r\n : ``\r\n }\r\n\r\n ${showEmailSubmitError ? \r\n html`\r\n <div class=\"state danger\">\r\n ${CrossIcon()}\r\n <p>${this.remoteAuthState.message || \"Failed to process email. Please try again.\"}</p>\r\n </div>\r\n <div class=\"login-button\" style=\"margin-top: 10px;\">\r\n <button class=\"primary\" @click=${this.tryAgain}>Try again</button>\r\n </div>\r\n `\r\n : ``\r\n }\r\n\r\n ${showEmailCodeInput ? \r\n html`\r\n <div class=\"state success\" style=\"margin-bottom: -12px\">\r\n ${CheckIcon()}\r\n <p>Email verification code sent</p>\r\n </div>\r\n\r\n <h3>Check your emails and paste the code below</h3>\r\n\r\n <div class=\"security-code\">\r\n <input\r\n type=\"text\"\r\n maxlength=\"6\"\r\n inputmode=\"numeric\"\r\n pattern=\"[0-9]{6}\"\r\n placeholder=\"000000\"\r\n .value=${this.emailSecurityCode || \"\"}\r\n @input=${this.onEmailSecurityCodeChange}\r\n />\r\n ${this.remoteAuthLoading ? html`<div class=\"spinner\"></div>` : ''}\r\n </div>\r\n\r\n ${this.emailCodeError\r\n ? html`\r\n <div class=\"state danger\" style=\"margin-top: -32px; margin-bottom: 20px;\">\r\n ${CrossIcon()}\r\n <p>Verification failed. Please try again.</p>\r\n </div>\r\n `\r\n : ''\r\n }\r\n `\r\n : ``\r\n }\r\n\r\n ${showLoginPasswordInput ? \r\n html`\r\n <div class=\"state success\" style=\"margin-bottom: -12px\">\r\n ${CheckIcon()}\r\n <p>Account found</p>\r\n </div>\r\n \r\n <h3>Enter your password to login</h3>\r\n\r\n <div class=\"input-row\">\r\n <input\r\n type=\"password\"\r\n placeholder=\"Password...\"\r\n .value=${this.password || \"\"}\r\n @input=${(e: Event) => {\r\n const input = e.target as HTMLInputElement;\r\n this.password = input.value;\r\n }}\r\n @keydown=${(e: KeyboardEvent) => {\r\n if (e.key === 'Enter' && !this.remoteAuthLoading && this.password.length) {\r\n this.passwordLogin();\r\n }\r\n }}\r\n />\r\n </div>\r\n\r\n <div class=\"login-button\">\r\n <button class=\"primary\" @click=${this.passwordLogin} .disabled=${this.remoteAuthLoading || !this.password.length}>\r\n ${this.remoteAuthLoading ? \"Loading...\" : \"Login\"}\r\n </button>\r\n </div>\r\n\r\n ${this.passwordError\r\n ? html`\r\n <div class=\"state danger\" style=\"margin-top: -32px; margin-bottom: 20px;\">\r\n ${CrossIcon()}\r\n <p>Incorrect password. Please try again.</p>\r\n </div>\r\n `\r\n : ''\r\n }\r\n `\r\n : ``\r\n }\r\n\r\n ${showSignUpPasswordInput ?\r\n html`\r\n <div class=\"state success\">\r\n ${CheckIcon()}\r\n <p>Creating a new account for <strong>${this.email}</strong></p>\r\n </div>\r\n\r\n <h3>Choose a password</h3>\r\n\r\n <div class=\"input-row\">\r\n <input\r\n type=\"password\"\r\n placeholder=\"Password...\"\r\n .value=${this.password || \"\"}\r\n @input=${(e: Event) => {\r\n const input = e.target as HTMLInputElement;\r\n this.password = input.value;\r\n }}\r\n />\r\n </div>\r\n\r\n <div class=\"input-row\" style=\"margin-top: 8px;\">\r\n <input\r\n type=\"password\"\r\n placeholder=\"Confirm password...\"\r\n .value=${this.confirmPassword || \"\"}\r\n @input=${(e: Event) => {\r\n const input = e.target as HTMLInputElement;\r\n this.confirmPassword = input.value;\r\n }}\r\n @keydown=${(e: KeyboardEvent) => {\r\n if (e.key === 'Enter' && !this.remoteAuthLoading && this.passwordsMatch) {\r\n this.createAccount();\r\n }\r\n }}\r\n />\r\n </div>\r\n\r\n ${this.confirmPassword.length > 0 && !this.passwordsMatch\r\n ? html`<p style=\"font-size: 13px; color: var(--ac-danger-color); text-align: center;\">Passwords do not match</p>`\r\n : ''\r\n }\r\n\r\n <div class=\"login-button\">\r\n <button class=\"primary\" @click=${this.createAccount} .disabled=${this.remoteAuthLoading || !this.passwordsMatch}>\r\n ${this.remoteAuthLoading ? \"Loading...\" : \"Create Account\"}\r\n </button>\r\n </div>\r\n\r\n ${this.accountCreationError\r\n ? html`\r\n <div class=\"state danger\" style=\"margin-top: -32px; margin-bottom: 20px;\">\r\n ${CrossIcon()}\r\n <p>Failed to create account. Please try again.</p>\r\n </div>\r\n `\r\n : ''\r\n }\r\n `\r\n : ``\r\n }\r\n\r\n </div>\r\n `;\r\n }\r\n}\r\n\r\ndeclare global {\r\n interface HTMLElementTagNameMap {\r\n \"remote-authentication\": RemoteAuthentication;\r\n }\r\n}\r\n", "import { LitElement, html, css } from \"lit\";\nimport { customElement, property } from \"lit/decorators.js\";\nimport { sharedStyles } from \"../../styles/shared-styles\";\nimport { CrossIcon, LocalIcon, RemoteIcon } from \"../icons\";\nimport type { AuthStates } from \"../../types\";\n\n@customElement(\"current-state\")\nexport class CurrentState extends LitElement {\n @property({ type: String }) url: string = \"\";\n @property({ type: Number }) port: number = 12000;\n @property({ type: String }) authState: AuthStates = \"unauthenticated\";\n\n static styles = [\n sharedStyles,\n css`\n .box {\n gap: 15px;\n }\n\n .box-header {\n margin-bottom: 6px;\n }\n\n .detail-value {\n color: var(--ac-primary-color);\n }\n\n .auth-status {\n padding: 6px 10px;\n border-radius: 8px;\n font-size: 14px;\n font-weight: 600;\n text-transform: uppercase;\n }\n\n .auth-status.authenticated {\n background: rgba(93, 210, 125, 0.2);\n color: var(--ac-success-color);\n }\n\n .auth-status.locked {\n background: rgba(255, 193, 7, 0.2);\n color: #ffc107;\n }\n\n .auth-status.unauthenticated {\n background: rgba(244, 54, 127, 0.2);\n color: var(--ac-danger-color);\n }\n `\n ];\n\n private get connectionType(): 'local' | 'remote' {\n return this.url.includes('localhost') || this.url.includes('127.0.0.1') \n ? 'local' \n : 'remote';\n }\n\n private close() {\n this.dispatchEvent(new CustomEvent(\"close\", { bubbles: true, composed: true }));\n }\n\n private disconnect() {\n this.dispatchEvent(new CustomEvent(\"disconnect\", { bubbles: true, composed: true }));\n }\n\n render() {\n const isLocal = this.connectionType === 'local';\n\n return html`\n <div class=\"container\">\n <div class=\"close-button\" @click=${this.close}>\n ${CrossIcon()}\n </div>\n\n <div class=\"header\">\n <h1>AD4M Connected</h1>\n <h3>Your current connection details:</h3>\n </div>\n\n <div class=\"box\">\n <div class=\"box-header\">\n ${isLocal ? LocalIcon() : RemoteIcon()}\n <h3>${isLocal ? 'Local Node' : 'Remote Node'}</h3>\n </div>\n\n ${isLocal \n ? html`\n <div class=\"row\">\n <span>Port:</span>\n <span class=\"detail-value\">${this.port}</span>\n </div>\n <div class=\"row\">\n <span>URL:</span>\n <span class=\"detail-value\">${this.url}</span>\n </div>\n `\n : html`\n <div class=\"row\">\n <span>URL:</span>\n <span class=\"detail-value\">${this.url}</span>\n </div>\n `\n }\n\n <div class=\"row\">\n <span>Status:</span>\n <span class=\"auth-status ${this.authState}\">${this.authState}</span>\n </div>\n </div>\n\n <div class=\"row center\">\n <button class=\"danger\" @click=${this.disconnect}>\n Disconnect\n </button>\n </div>\n </div>\n `;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n \"current-state\": CurrentState;\n }\n}\n", "import { html, TemplateResult } from \"lit\";\nimport { getInitials, getHue } from \"../../utils\";\nimport type { RemoteHost } from \"../../types\";\n\n/**\n * Render a host avatar with image-error fallback to coloured initials.\n * @param host The remote host to render\n * @param cls CSS class for the element (e.g. \"host-avatar\" or \"profile-pic\")\n */\nexport function renderHostAvatar(host: RemoteHost, cls: string): TemplateResult {\n const hue = getHue(host.id || host.name);\n const initials = getInitials(host.name);\n\n if (host.profilePicUrl) {\n const onError = (e: Event) => {\n const img = e.target as HTMLImageElement;\n const fallback = document.createElement('div');\n fallback.className = `${cls} fallback`;\n fallback.style.background = `hsl(${hue},60%,35%)`;\n fallback.textContent = initials;\n img.replaceWith(fallback);\n };\n return html`<img class=${cls} src=${host.profilePicUrl} alt=\"\" @error=${onError} />`;\n }\n\n return html`<div class=\"${cls} fallback\" style=\"background:hsl(${hue},60%,35%)\">${initials}</div>`;\n}\n", "import { LitElement, html, css } from \"lit\";\nimport { customElement, property, state } from \"lit/decorators.js\";\nimport { sharedStyles } from \"../../styles/shared-styles\";\nimport { MapPinIcon } from \"../icons\";\nimport { renderHostAvatar } from \"../shared/avatar\";\nimport { wsUrlToHttpBase } from \"../../utils\";\nimport type { RemoteHost } from \"../../types\";\n\n@customElement(\"host-browser\")\nexport class HostBrowser extends LitElement {\n @property({ type: Array }) hosts: RemoteHost[] = [];\n @property({ type: Boolean }) loading: boolean = false;\n @property({ type: String }) error: string | null = null;\n @property({ type: String }) lastHostId: string | null = null;\n @property({ type: String }) defaultUrl: string = \"\";\n\n @state() private manualUrl = \"\";\n @state() private manualUrlError: string | null = null;\n private defaultApplied = false;\n\n static styles = [\n sharedStyles,\n css`\n :host {\n display: flex;\n flex-direction: column;\n min-height: 0;\n flex: 1 1 auto;\n }\n\n .container {\n flex: 1 1 auto;\n min-height: 0;\n overflow: hidden;\n }\n\n .host-list {\n display: flex;\n flex-direction: column;\n gap: 12px;\n max-height: min(500px, calc(100vh - 380px));\n overflow-y: auto;\n padding: 2px;\n }\n\n .host-card {\n display: flex;\n align-items: center;\n gap: 16px;\n padding: 14px;\n border-radius: 8px;\n background: rgba(128, 178, 201, 0.10);\n box-shadow: 0 0 0 1px var(--ac-border-color-light);\n cursor: pointer;\n transition: all 0.2s ease;\n }\n\n .host-card:hover,\n .host-card:focus-visible {\n background: rgba(128, 178, 201, 0.20);\n box-shadow: 0 0 0 1px var(--ac-primary-color);\n outline: none;\n }\n\n .host-card.pinned {\n box-shadow: 0 0 0 1px var(--ac-primary-color);\n background: rgba(128, 178, 201, 0.16);\n }\n\n .host-avatar {\n width: 60px;\n height: 60px;\n border-radius: 50%;\n flex-shrink: 0;\n object-fit: cover;\n background: rgba(128, 178, 201, 0.2);\n }\n\n .host-avatar.fallback {\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 16px;\n font-weight: 600;\n color: #fff;\n }\n\n .host-info {\n flex: 1;\n min-width: 0;\n }\n\n .host-name {\n font-size: 15px;\n font-weight: 600;\n color: #ffffff;\n margin: 0;\n text-align: left;\n }\n\n .host-location {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n font-size: 13px;\n color: rgba(255, 255, 255, 0.6);\n margin: 2px 0 0 0;\n text-align: left;\n }\n\n .host-location svg {\n opacity: 0.7;\n }\n\n .host-meta {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n margin-top: 6px;\n }\n\n .model-chip {\n font-size: 12px;\n padding: 3px 8px;\n border-radius: 10px;\n background: rgba(145, 227, 253, 0.15);\n color: var(--ac-primary-color);\n white-space: nowrap;\n }\n\n .rates-preview {\n font-size: 12px;\n color: rgba(255, 255, 255, 0.5);\n margin-top: 6px;\n text-align: left;\n }\n\n .spinner-container {\n display: flex;\n justify-content: center;\n padding: 40px 0;\n }\n\n .spinner-container .spinner {\n width: 32px;\n height: 32px;\n }\n\n .divider {\n display: flex;\n align-items: center;\n gap: 12px;\n margin: 8px 0;\n }\n\n .divider::before,\n .divider::after {\n content: \"\";\n flex: 1;\n height: 1px;\n background: var(--ac-border-color-light);\n }\n\n .divider span {\n font-size: 13px;\n color: rgba(255, 255, 255, 0.4);\n white-space: nowrap;\n }\n\n .manual-entry {\n display: flex;\n gap: 8px;\n width: 100%;\n padding: 2px;\n }\n\n .manual-entry input {\n flex: 1;\n }\n\n .manual-entry button {\n width: auto;\n flex-shrink: 0;\n }\n\n .trust-notice {\n display: flex;\n gap: 10px;\n padding: 12px 14px;\n border-radius: 8px;\n background: rgba(255, 200, 50, 0.08);\n border: 1px solid rgba(255, 200, 50, 0.25);\n margin-bottom: 12px;\n font-size: 13px;\n line-height: 1.45;\n color: rgba(255, 255, 255, 0.75);\n }\n\n .trust-notice svg {\n flex-shrink: 0;\n margin-top: 1px;\n }\n\n .pinned-label {\n font-size: 11px;\n color: var(--ac-primary-color);\n text-transform: uppercase;\n letter-spacing: 0.5px;\n font-weight: 600;\n }\n `\n ];\n\n willUpdate(changedProps: import(\"lit\").PropertyValues) {\n // Pre-fill manual URL from defaultUrl on first render only\n if (changedProps.has('defaultUrl') && this.defaultUrl && !this.defaultApplied) {\n this.manualUrl = this.defaultUrl;\n this.defaultApplied = true;\n }\n }\n\n private selectHost(host: RemoteHost) {\n this.dispatchEvent(new CustomEvent(\"select-host\", { detail: { host }, bubbles: true, composed: true }));\n }\n\n private connectManualUrl() {\n const url = this.manualUrl.trim();\n if (!url) return;\n\n let parsedUrl: URL;\n try {\n parsedUrl = new URL(url);\n } catch {\n this.manualUrlError = \"Invalid URL format\";\n return;\n }\n\n if (!['http:', 'https:', 'ws:', 'wss:'].includes(parsedUrl.protocol)) {\n this.manualUrlError = \"URL must use http:// or https:// protocol\";\n return;\n }\n\n this.manualUrlError = null;\n\n // Normalize legacy ws/wss URLs to http/https\n const normalizedUrl = (parsedUrl.protocol === 'ws:' || parsedUrl.protocol === 'wss:')\n ? wsUrlToHttpBase(url)\n : url;\n\n const host: RemoteHost = {\n id: `manual-${Date.now()}`,\n name: parsedUrl.hostname,\n profilePicUrl: \"\",\n location: \"Custom URL\",\n url: normalizedUrl,\n rates: [],\n aiModels: [],\n };\n\n this.selectHost(host);\n }\n\n private renderAvatar(host: RemoteHost) {\n return renderHostAvatar(host, \"host-avatar\");\n }\n\n private retry() {\n this.dispatchEvent(new CustomEvent(\"retry\", { bubbles: true, composed: true }));\n }\n\n private formatPrice(price: number): string {\n if (price === 0) return \"0.00\";\n if (price >= 0.01) return price.toFixed(2);\n if (price >= 0.0001) return price.toFixed(4);\n if (price >= 0.000001) return price.toFixed(6);\n return price.toExponential(2);\n }\n\n private getLinkPrice(rates: RemoteHost[\"rates\"]): number | null {\n const r = rates.find(r => r.description.trim().toLowerCase() === \"link write\");\n return r ? r.priceInHOT : null;\n }\n\n private getAvgTokenPrice(rates: RemoteHost[\"rates\"]): number | null {\n const tokenRates = rates.filter(r => r.description.trim().toLowerCase() !== \"link write\");\n if (tokenRates.length === 0) return null;\n return tokenRates.reduce((sum, r) => sum + r.priceInHOT, 0) / tokenRates.length;\n }\n\n private getSortedHosts(): RemoteHost[] {\n if (!this.lastHostId) return this.hosts;\n const pinned = this.hosts.filter(h => h.id === this.lastHostId);\n const rest = this.hosts.filter(h => h.id !== this.lastHostId);\n return [...pinned, ...rest];\n }\n\n render() {\n return html`\n <div class=\"container\">\n <div class=\"header\">\n <h1>Remote Node</h1>\n <h3>Choose a host or enter a URL</h3>\n </div>\n\n <div class=\"trust-notice\">\n <svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"rgba(255, 200, 50, 0.9)\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n <path d=\"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z\"/>\n <line x1=\"12\" y1=\"9\" x2=\"12\" y2=\"13\"/>\n <line x1=\"12\" y1=\"17\" x2=\"12.01\" y2=\"17\"/>\n </svg>\n <span>By connecting to a remote host, you are trusting them to run AD4M on your behalf. Your data will be stored on their machine and they will have access to your agent's operations. Only connect to hosts you trust.</span>\n </div>\n\n ${this.loading ? html`\n <div class=\"spinner-container\"><div class=\"spinner\"></div></div>\n ` : this.error ? html`\n <div class=\"box\">\n <p style=\"color: var(--ac-danger-color)\">${this.error}</p>\n <button class=\"primary\" @click=${this.retry}>Retry</button>\n </div>\n ` : html`\n <div class=\"host-list\">\n ${this.getSortedHosts().map(host => html`\n <div\n class=\"host-card ${host.id === this.lastHostId ? 'pinned' : ''}\"\n tabindex=\"0\"\n role=\"button\"\n aria-label=\"Connect to ${host.name}\"\n @click=${() => this.selectHost(host)}\n @keydown=${(e: KeyboardEvent) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); this.selectHost(host); } }}\n >\n ${this.renderAvatar(host)}\n <div class=\"host-info\">\n <div style=\"display:flex;align-items:center;gap:8px;\">\n <p class=\"host-name\">${host.name}</p>\n ${host.id === this.lastHostId ? html`<span class=\"pinned-label\">Last used</span>` : ''}\n </div>\n <p class=\"host-location\">${MapPinIcon()}${host.location}</p>\n <div class=\"host-meta\">\n ${host.aiModels.map(model => html`<span class=\"model-chip\">${model}</span>`)}\n </div>\n ${host.rates.length > 0 ? (() => {\n const linkPrice = this.getLinkPrice(host.rates);\n const avgTokenPrice = this.getAvgTokenPrice(host.rates);\n return html`\n <p class=\"rates-preview\">\n ${linkPrice != null ? html`Link: ${this.formatPrice(linkPrice)} wHOT` : ''}${linkPrice != null && avgTokenPrice != null ? ' \u00B7 ' : ''}${avgTokenPrice != null ? html`Token: ~${this.formatPrice(avgTokenPrice)} wHOT` : ''}\n </p>\n `; })() : ''}\n </div>\n </div>\n `)}\n </div>\n `}\n\n <div class=\"divider\"><span>or enter URL directly</span></div>\n\n <div class=\"manual-entry\">\n <input\n type=\"text\"\n placeholder=\"https://your-host.example\"\n .value=${this.manualUrl}\n @input=${(e: Event) => { this.manualUrl = (e.target as HTMLInputElement).value; this.manualUrlError = null; }}\n @keydown=${(e: KeyboardEvent) => { if (e.key === 'Enter') this.connectManualUrl(); }}\n style=\"font-size: 14px;\"\n />\n <button\n class=\"primary\"\n ?disabled=${!this.manualUrl.trim()}\n @click=${this.connectManualUrl}\n >\n Connect\n </button>\n </div>\n ${this.manualUrlError ? html`<p class=\"state danger\" style=\"margin-top: 6px; font-size: 13px;\">${this.manualUrlError}</p>` : ''}\n </div>\n `;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n \"host-browser\": HostBrowser;\n }\n}\n", "import { LitElement, html, css, TemplateResult } from \"lit\";\nimport { customElement, property } from \"lit/decorators.js\";\nimport { sharedStyles } from \"../../styles/shared-styles\";\nimport { MapPinIcon } from \"../icons\";\nimport { renderHostAvatar } from \"../shared/avatar\";\nimport type { PricingItem, RemoteHost } from \"../../types\";\n\n@customElement(\"host-detail\")\nexport class HostDetail extends LitElement {\n @property({ type: Object }) host!: RemoteHost;\n\n static styles = [\n sharedStyles,\n css`\n .profile {\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 10px;\n }\n\n .profile-pic {\n width: 100px;\n height: 100px;\n border-radius: 50%;\n object-fit: cover;\n background: rgba(128, 178, 201, 0.2);\n }\n\n .profile-pic.fallback {\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 28px;\n font-weight: 600;\n color: #fff;\n }\n\n .profile-name {\n font-size: 22px;\n font-weight: 700;\n color: #ffffff;\n margin: 0;\n }\n\n .profile-location {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n font-size: 14px;\n color: rgba(255, 255, 255, 0.6);\n margin: 0;\n }\n\n .profile-location svg {\n opacity: 0.7;\n }\n\n .profile-description {\n font-size: 14px;\n margin: 0;\n text-align: center;\n line-height: 1.4;\n }\n\n .compute-specs {\n font-size: 14px;\n color: rgba(255, 255, 255, 0.8);\n margin: 0;\n }\n\n .models {\n display: flex;\n flex-wrap: wrap;\n justify-content: center;\n gap: 6px;\n margin-top: 4px;\n }\n\n .model-chip {\n font-size: 13px;\n padding: 4px 12px;\n border-radius: 12px;\n background: rgba(145, 227, 253, 0.15);\n color: var(--ac-primary-color);\n }\n\n .rates-section {\n width: 100%;\n }\n\n .rates-section h3 {\n text-align: left;\n font-size: 14px;\n font-weight: 600;\n color: rgba(255, 255, 255, 0.6);\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 10px;\n }\n\n .rates-table {\n width: 100%;\n border-collapse: collapse;\n }\n\n .rates-table tr {\n border-bottom: 1px solid var(--ac-border-color-dark);\n }\n\n .rates-table tr:last-child {\n border-bottom: none;\n }\n\n .rates-table td {\n padding: 8px 0;\n font-size: 14px;\n }\n\n .rates-table td:first-child {\n color: rgba(255, 255, 255, 0.8);\n }\n\n .rates-table td:last-child {\n text-align: right;\n color: var(--ac-primary-color);\n font-family: monospace;\n font-size: 13px;\n }\n\n button.connect-button {\n width: 100%;\n }\n `\n ];\n\n private proceedToAuth() {\n this.dispatchEvent(new CustomEvent(\"proceed-to-auth\", { detail: { host: this.host }, bubbles: true, composed: true }));\n }\n\n private renderAvatar(): TemplateResult {\n return renderHostAvatar(this.host, \"profile-pic\");\n }\n\n private static OPERATION_RATES = new Set([\"link write\"]);\n\n private isOperationRate(rate: PricingItem): boolean {\n return HostDetail.OPERATION_RATES.has(rate.description);\n }\n\n private rateLabel(description: string): string {\n if (description === \"link write\") return \"Link write\";\n return description;\n }\n\n private formatPrice(price: number): string {\n if (price === 0) return \"0.00\";\n // Show enough decimal places to be meaningful\n if (price >= 0.01) return price.toFixed(2);\n if (price >= 0.0001) return price.toFixed(4);\n if (price >= 0.000001) return price.toFixed(6);\n return price.toExponential(2);\n }\n\n render() {\n if (!this.host) return null;\n\n return html`\n <div class=\"container\">\n <div class=\"profile\">\n ${this.renderAvatar()}\n <p class=\"profile-name\">${this.host.name}</p>\n <p class=\"profile-location\">${MapPinIcon()}${this.host.location}</p>\n ${this.host.description ? html`<p class=\"profile-description\">${this.host.description}</p>` : ''}\n\n ${this.host.aiModels.length > 0 ? html`\n <div class=\"models\">\n ${this.host.aiModels.map(m => html`<span class=\"model-chip\">${m}</span>`)}\n </div>\n ` : ''}\n </div>\n\n ${this.host.rates.length > 0 ? html`\n <div class=\"box\">\n <div class=\"rates-section\">\n <h3>Pricing</h3>\n <table class=\"rates-table\">\n ${this.host.rates.filter(r => this.isOperationRate(r)).map(rate => html`\n <tr>\n <td>${this.rateLabel(rate.description)}</td>\n <td>${this.formatPrice(rate.priceInHOT)} wHOT</td>\n </tr>\n `)}\n ${this.host.rates.filter(r => !this.isOperationRate(r)).length > 0 ? html`\n <tr><td colspan=\"2\" style=\"text-align:left;padding-top:12px;color:rgba(255,255,255,0.5);font-size:12px;text-transform:uppercase;letter-spacing:0.5px;\">AI Models (cost per token)</td></tr>\n ${this.host.rates.filter(r => !this.isOperationRate(r)).map(rate => html`\n <tr>\n <td>${rate.description}</td>\n <td>${this.formatPrice(rate.priceInHOT)} wHOT</td>\n </tr>\n `)}\n ` : ''}\n </table>\n </div>\n </div>\n ` : ''}\n\n ${this.host.computeSpecs ? html`\n <div class=\"box\">\n <div class=\"rates-section\">\n <h3>Compute</h3>\n <p class=\"compute-specs\">${this.host.computeSpecs}</p>\n </div>\n </div>\n ` : ''}\n\n <button class=\"primary connect-button\" @click=${this.proceedToAuth}>\n Connect to ${this.host.name}\n </button>\n </div>\n `;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n \"host-detail\": HostDetail;\n }\n}\n", "import { LitElement, html, css } from \"lit\";\nimport { customElement, property, state } from \"lit/decorators.js\";\nimport { sharedStyles } from \"../../styles/shared-styles\";\nimport { CheckIcon, CrossIcon, CreditIcon, MapPinIcon, WalletIcon } from \"../icons\";\nimport type { RemoteHost, UserInfo, ComputeLogEntryData } from \"../../types\";\n\n@customElement(\"logged-in-dashboard\")\nexport class LoggedInDashboard extends LitElement {\n @property({ type: Object }) connectedHost: RemoteHost | null = null;\n @property({ type: Object }) userInfo: UserInfo | null = null;\n @property({ type: Boolean }) requestingPayment: boolean = false;\n @property({ type: String }) paymentError: string | null = null;\n /** When true (credit-depletion session), the X close button is hidden \u2014 the only exits are \"Use App\" or \"Disconnect\" */\n @property({ type: Boolean }) forceOpen: boolean = false;\n\n @state() private walletInput = \"\";\n @state() private editingWallet = false;\n @state() private walletSaveSuccess = false;\n @state() private topUpAmount = \"\";\n @state() private awaitingApproval = false;\n @state() private creditsUpdated = false;\n @state() private activityLogOpen = false;\n @state() private activityLog: ComputeLogEntryData[] = [];\n @state() private activityLogLoading = false;\n private previousCredits: number | null = null;\n\n static styles = [\n sharedStyles,\n css`\n .dashboard-header {\n text-align: center;\n }\n\n .host-badge {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 5px;\n font-size: 14px;\n color: rgba(255, 255, 255, 0.6);\n margin-bottom: 8px;\n }\n\n .host-badge strong {\n color: #ffffff;\n }\n\n .host-badge svg {\n opacity: 0.7;\n }\n\n .credit-display {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n padding: 16px;\n border-radius: 8px;\n background: rgba(128, 178, 201, 0.14);\n box-shadow: 0 0 0 1px var(--ac-border-color-light);\n }\n\n .credit-display svg {\n width: 24px;\n height: 24px;\n color: var(--ac-primary-color);\n flex-shrink: 0;\n }\n\n .credit-amount {\n font-size: 28px;\n font-weight: 700;\n color: #ffffff;\n }\n\n .credit-label {\n font-size: 14px;\n color: rgba(255, 255, 255, 0.5);\n }\n\n .credit-display.depleted {\n background: rgba(244, 54, 127, 0.12);\n box-shadow: 0 0 0 1px var(--ac-danger-color);\n }\n\n .credit-display.free-access {\n background: rgba(93, 210, 125, 0.14);\n box-shadow: 0 0 0 1px var(--ac-success-color);\n }\n\n .credit-display.free-access .credit-amount {\n color: var(--ac-success-color);\n font-size: 20px;\n }\n\n .depleted-banner {\n text-align: center;\n padding: 10px;\n border-radius: 8px;\n background: rgba(244, 54, 127, 0.15);\n color: var(--ac-danger-color);\n font-size: 14px;\n font-weight: 600;\n }\n\n .wallet-section {\n display: flex;\n flex-direction: column;\n gap: 8px;\n }\n\n .wallet-section label {\n display: flex;\n align-items: center;\n gap: 6px;\n font-size: 13px;\n color: rgba(255, 255, 255, 0.6);\n text-transform: uppercase;\n letter-spacing: 0.5px;\n font-weight: 600;\n }\n\n .wallet-section label svg {\n width: 16px;\n height: 16px;\n color: var(--ac-primary-color);\n }\n\n .wallet-row {\n display: flex;\n gap: 8px;\n }\n\n .wallet-row input {\n flex: 1;\n }\n\n .wallet-row button {\n width: auto;\n flex-shrink: 0;\n }\n\n .wallet-display {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 0 16px;\n height: 48px;\n border-radius: 8px;\n background: #00091e5c;\n box-shadow: 0 0 0 1px var(--ac-border-color-light);\n font-size: 14px;\n color: var(--ac-primary-color-light);\n font-family: monospace;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n flex: 1;\n }\n\n .topup-section {\n display: flex;\n flex-direction: column;\n gap: 10px;\n }\n\n .topup-section label {\n display: flex;\n align-items: center;\n gap: 6px;\n font-size: 13px;\n color: rgba(255, 255, 255, 0.6);\n text-transform: uppercase;\n letter-spacing: 0.5px;\n font-weight: 600;\n }\n\n .topup-section label svg {\n width: 16px;\n height: 16px;\n color: var(--ac-primary-color);\n }\n\n .topup-buttons {\n display: flex;\n gap: 8px;\n }\n\n .topup-buttons button {\n flex: 1;\n font-size: 14px;\n padding: 0 12px;\n height: 42px;\n }\n\n .pending-message {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n text-align: center;\n padding: 10px;\n border-radius: 8px;\n background: rgba(128, 178, 201, 0.14);\n box-shadow: 0 0 0 1px var(--ac-border-color-light);\n color: rgba(255, 255, 255, 0.8);\n font-size: 14px;\n }\n\n .pending-message .spinner {\n width: 16px;\n height: 16px;\n flex-shrink: 0;\n }\n\n .success-message {\n text-align: center;\n padding: 10px;\n border-radius: 8px;\n background: rgba(93, 210, 125, 0.15);\n color: var(--ac-success-color);\n font-size: 14px;\n font-weight: 600;\n }\n\n .success-message svg {\n width: 16px;\n height: 16px;\n flex-shrink: 0;\n }\n\n .error-message {\n text-align: center;\n padding: 10px;\n border-radius: 8px;\n background: rgba(244, 54, 127, 0.15);\n color: var(--ac-danger-color);\n font-size: 14px;\n }\n\n .email-display {\n font-size: 14px;\n color: rgba(255, 255, 255, 0.5);\n text-align: center;\n }\n\n .footer-actions {\n display: flex;\n justify-content: center;\n gap: 8px;\n }\n\n button.full {\n width: 100%;\n }\n\n .activity-log-toggle {\n display: flex;\n align-items: center;\n justify-content: space-between;\n cursor: pointer;\n padding: 10px 12px;\n border-radius: 8px;\n background: rgba(128, 178, 201, 0.08);\n box-shadow: 0 0 0 1px var(--ac-border-color-light);\n font-size: 14px;\n color: rgba(255, 255, 255, 0.7);\n user-select: none;\n }\n\n .activity-log-toggle:hover {\n background: rgba(128, 178, 201, 0.14);\n }\n\n .activity-log-toggle .chevron {\n transition: transform 0.2s;\n font-size: 12px;\n }\n\n .activity-log-toggle .chevron.open {\n transform: rotate(90deg);\n }\n\n .activity-log-list {\n max-height: 200px;\n overflow-y: auto;\n display: flex;\n flex-direction: column;\n gap: 4px;\n }\n\n .activity-log-entry {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 6px 10px;\n border-radius: 6px;\n background: rgba(128, 178, 201, 0.06);\n font-size: 13px;\n color: rgba(255, 255, 255, 0.75);\n }\n\n .activity-log-entry .op-badge {\n display: inline-block;\n padding: 2px 6px;\n border-radius: 4px;\n font-size: 11px;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.03em;\n }\n\n .activity-log-entry .op-badge.ai_prompt {\n background: rgba(168, 130, 255, 0.2);\n color: #c4a8ff;\n }\n\n .activity-log-entry .op-badge.ai_transcription {\n background: rgba(168, 130, 255, 0.2);\n color: #c4a8ff;\n }\n\n .activity-log-entry .op-badge.ai_embed {\n background: rgba(130, 200, 255, 0.2);\n color: #a8d8ff;\n }\n\n .activity-log-entry .op-badge.link_write {\n background: rgba(255, 200, 100, 0.2);\n color: #ffd080;\n }\n\n .activity-log-entry .cost {\n font-weight: 600;\n color: #ffffff;\n white-space: nowrap;\n }\n\n .activity-log-entry .time {\n font-size: 11px;\n color: rgba(255, 255, 255, 0.4);\n white-space: nowrap;\n }\n\n .activity-log-entry .summary {\n flex: 1;\n margin: 0 8px;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n color: rgba(255, 255, 255, 0.5);\n font-size: 12px;\n }\n\n .activity-log-empty {\n text-align: center;\n padding: 12px;\n color: rgba(255, 255, 255, 0.4);\n font-size: 13px;\n }\n `\n ];\n\n private close() {\n this.dispatchEvent(new CustomEvent(\"close\", { bubbles: true, composed: true }));\n }\n\n private _useApp() {\n this.dispatchEvent(new CustomEvent(\"use-app\", { bubbles: true, composed: true }));\n }\n\n private disconnect() {\n this.dispatchEvent(new CustomEvent(\"disconnect\", { bubbles: true, composed: true }));\n }\n\n private setWalletAddress() {\n const address = this.walletInput.trim();\n if (!address) return;\n this.editingWallet = false;\n this.walletSaveSuccess = true;\n setTimeout(() => { this.walletSaveSuccess = false; }, 3000);\n this.dispatchEvent(new CustomEvent(\"set-wallet-address\", { detail: { address }, bubbles: true, composed: true }));\n }\n\n private requestTopUp(amount: number) {\n this.creditsUpdated = false;\n this.dispatchEvent(new CustomEvent(\"request-top-up\", { detail: { amountHOT: amount }, bubbles: true, composed: true }));\n }\n\n private truncateMiddle(str: string, startChars = 8, endChars = 6): string {\n if (str.length <= startChars + endChars + 3) return str;\n return `${str.slice(0, startChars)}\u2026${str.slice(-endChars)}`;\n }\n\n private async toggleActivityLog() {\n this.activityLogOpen = !this.activityLogOpen;\n if (this.activityLogOpen && this.activityLog.length === 0) {\n await this.loadActivityLog();\n }\n }\n\n private async loadActivityLog() {\n this.activityLogLoading = true;\n try {\n this.dispatchEvent(new CustomEvent('fetch-compute-log', {\n bubbles: true, composed: true,\n detail: {\n callback: (entries: ComputeLogEntryData[]) => {\n this.activityLog = entries;\n this.activityLogLoading = false;\n }\n }\n }));\n } catch {\n this.activityLogLoading = false;\n }\n }\n\n /** Call this externally to push a realtime log entry */\n pushLogEntry(entry: ComputeLogEntryData) {\n this.activityLog = [entry, ...this.activityLog].slice(0, 100);\n }\n\n private formatTimeAgo(timestamp: string): string {\n const diff = Date.now() - new Date(timestamp).getTime();\n const seconds = Math.floor(diff / 1000);\n if (seconds < 60) return `${seconds}s ago`;\n const minutes = Math.floor(seconds / 60);\n if (minutes < 60) return `${minutes}m ago`;\n const hours = Math.floor(minutes / 60);\n if (hours < 24) return `${hours}h ago`;\n return `${Math.floor(hours / 24)}d ago`;\n }\n\n private formatOperation(op: string): string {\n switch (op) {\n case 'ai_prompt': return 'AI Prompt';\n case 'ai_embed': return 'AI Embed';\n case 'ai_transcription': return 'AI Transcription';\n case 'link_write': return 'Link Write';\n default: return op;\n }\n }\n\n private get hasWallet(): boolean {\n return !!this.userInfo?.hotWalletAddress;\n }\n\n private get isFreeAccess(): boolean {\n return !!this.userInfo?.freeAccess;\n }\n\n private get isDepleted(): boolean {\n return this.userInfo != null && !this.userInfo.freeAccess && this.userInfo.remainingCredits <= 0;\n }\n\n private get topUpDisabled(): boolean {\n return !this.hasWallet || this.requestingPayment || this.awaitingApproval;\n }\n\n updated(changed: Map<string, unknown>) {\n // When requestingPayment goes from true to false (request sent), enter awaiting approval\n if (changed.has('requestingPayment') && !this.requestingPayment && !this.paymentError) {\n const wasRequesting = changed.get('requestingPayment') as boolean;\n if (wasRequesting) {\n this.awaitingApproval = true;\n this.previousCredits = this.userInfo?.remainingCredits ?? null;\n }\n }\n // Detect credit change while awaiting approval\n if (changed.has('userInfo') && this.awaitingApproval && this.previousCredits !== null) {\n const newCredits = this.userInfo?.remainingCredits ?? 0;\n if (newCredits !== this.previousCredits) {\n this.awaitingApproval = false;\n this.creditsUpdated = true;\n this.previousCredits = null;\n setTimeout(() => { this.creditsUpdated = false; }, 4000);\n }\n }\n // Clear awaiting on error\n if (changed.has('paymentError') && this.paymentError) {\n this.awaitingApproval = false;\n this.previousCredits = null;\n }\n // Initialize wallet input from userInfo\n if (changed.has('userInfo') && this.userInfo?.hotWalletAddress && !this.walletInput) {\n this.walletInput = this.userInfo.hotWalletAddress;\n }\n }\n\n render() {\n const credits = this.userInfo?.remainingCredits ?? 0;\n\n return html`\n <div class=\"container\">\n ${this.forceOpen ? '' : html`<div class=\"close-button\" @click=${this.close}>${CrossIcon()}</div>`}\n\n <div class=\"dashboard-header\">\n <h1>Dashboard</h1>\n ${this.connectedHost ? html`\n <div class=\"host-badge\">\n Connected to <strong>${this.connectedHost.name}</strong>\n </div>\n <div class=\"host-badge\">\n ${MapPinIcon()} ${this.connectedHost.location}\n </div>\n ` : ''}\n ${this.userInfo?.email ? html`\n <p class=\"email-display\">${this.userInfo.email}</p>\n ` : ''}\n </div>\n\n <!-- Credit balance -->\n ${this.isFreeAccess ? html`\n <div class=\"credit-display free-access\">\n ${CreditIcon()}\n <span class=\"credit-amount\">Free Access</span>\n </div>\n ` : html`\n <div class=\"credit-display\">\n ${CreditIcon()}\n <span class=\"credit-amount\">${credits.toFixed(2)}</span>\n <span class=\"credit-label\">wHOT</span>\n </div>\n\n ${this.isDepleted ? html`\n <div class=\"depleted-banner\">Credits depleted \u2014 top up to continue using this host</div>\n ` : ''}\n\n ${!this.hasWallet ? html`\n <p style=\"font-size:15px;color:rgba(255,255,255,0.5);text-align:center;\">\n Set your wallet address to enable top-ups\n </p>\n ` : ''}\n\n <!-- Wallet address -->\n <div class=\"wallet-section\">\n <label>${WalletIcon()} wHOT Wallet Address</label>\n ${this.hasWallet && !this.editingWallet ? html`\n <div class=\"wallet-row\">\n <div class=\"wallet-display\" title=${this.userInfo!.hotWalletAddress}>${this.truncateMiddle(this.userInfo!.hotWalletAddress || '')}</div>\n <button class=\"secondary\" @click=${() => { this.editingWallet = true; this.walletInput = this.userInfo!.hotWalletAddress || ''; }}>\n Change\n </button>\n </div>\n ${this.walletSaveSuccess ? html`\n <div class=\"success-message\" style=\"display:flex;align-items:center;justify-content:center;gap:6px;\">\n ${CheckIcon()} Wallet saved\n </div>\n ` : ''}\n ` : html`\n <div class=\"wallet-row\">\n <input\n type=\"text\"\n placeholder=\"Enter your wHOT wallet address\"\n .value=${this.walletInput}\n @input=${(e: Event) => { this.walletInput = (e.target as HTMLInputElement).value; }}\n @keydown=${(e: KeyboardEvent) => { if (e.key === 'Enter') this.setWalletAddress(); }}\n style=\"font-size: 14px;\"\n />\n <button\n class=\"primary\"\n ?disabled=${!this.walletInput.trim()}\n @click=${this.setWalletAddress}\n >\n Save\n </button>\n </div>\n `}\n </div>\n\n <!-- Top-up -->\n <div class=\"topup-section\">\n <label>${CreditIcon()} Top Up Credits</label>\n <div class=\"wallet-row\">\n <input\n type=\"number\"\n min=\"1\"\n placeholder=\"Amount in wHOT\"\n .value=${this.topUpAmount}\n @input=${(e: Event) => { this.topUpAmount = (e.target as HTMLInputElement).value; }}\n @keydown=${(e: KeyboardEvent) => { if (e.key === 'Enter' && this.topUpAmount && Number(this.topUpAmount) > 0) this.requestTopUp(Number(this.topUpAmount)); }}\n style=\"font-size: 14px;\"\n />\n <button\n class=\"primary\"\n ?disabled=${this.topUpDisabled || !this.topUpAmount || Number(this.topUpAmount) <= 0}\n @click=${() => this.requestTopUp(Number(this.topUpAmount))}\n >\n ${this.requestingPayment ? '...' : 'Top up'}\n </button>\n </div>\n <div class=\"topup-buttons\">\n ${[100, 500, 1000].map(amount => html`\n <button\n class=\"secondary\"\n ?disabled=${this.topUpDisabled}\n @click=${() => { this.topUpAmount = String(amount); this.requestTopUp(amount); }}\n >\n ${amount} wHOT\n </button>\n `)}\n </div>\n </div>\n\n ${this.awaitingApproval ? html`\n <div class=\"pending-message\">\n <div class=\"spinner\"></div>\n Open Unyt app and approve the transaction\n </div>\n ` : ''}\n\n ${this.creditsUpdated ? html`\n <div class=\"success-message\" style=\"display:flex;align-items:center;justify-content:center;gap:6px;\">\n ${CheckIcon()} Credits updated!\n </div>\n ` : ''}\n\n ${this.paymentError ? html`\n <div class=\"error-message\">${this.paymentError}</div>\n ` : ''}\n `}\n\n <!-- Activity Log -->\n <div class=\"activity-log-toggle\" @click=${this.toggleActivityLog}>\n <span>Activity Log</span>\n <span class=\"chevron ${this.activityLogOpen ? 'open' : ''}\">▶</span>\n </div>\n ${this.activityLogOpen ? html`\n ${this.activityLogLoading ? html`\n <div class=\"activity-log-empty\">Loading...</div>\n ` : this.activityLog.length === 0 ? html`\n <div class=\"activity-log-empty\">No activity yet</div>\n ` : html`\n <div class=\"activity-log-list\">\n ${this.activityLog.map(entry => html`\n <div class=\"activity-log-entry\">\n <span class=\"op-badge ${entry.operation}\">${this.formatOperation(entry.operation)}</span>\n <span class=\"summary\" title=${entry.summary || ''}>${entry.summary || ''}</span>\n <span class=\"cost\">${entry.cost.toFixed(2)}</span>\n <span class=\"time\">${this.formatTimeAgo(entry.timestamp)}</span>\n </div>\n `)}\n </div>\n `}\n ` : ''}\n\n <div class=\"footer-actions\">\n <button class=\"primary\" ?disabled=${this.isDepleted && !this.isFreeAccess} @click=${this._useApp}>\n Use app\n </button>\n <button class=\"danger-secondary\" @click=${this.disconnect}>\n Disconnect\n </button>\n </div>\n </div>\n `;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n \"logged-in-dashboard\": LoggedInDashboard;\n }\n}\n", "import { css, html, LitElement } from \"lit\";\r\nimport { customElement, state } from \"lit/decorators.js\";\r\nimport autoBind from \"auto-bind\";\r\nimport { VerificationRequestResult } from \"@coasys/ad4m/lib/src/runtime/RuntimeTypes\";\r\nimport { checkConnection, setLocal, wsUrlToHttpBase } from \"./utils\";\r\nimport Ad4mConnect from \"./core\";\r\nimport { Ad4mLogo, ArrowLeftIcon, CreditIcon } from \"./components/icons\";\r\nimport { fetchHosts } from \"./services/hostIndex\";\r\nimport type { RemoteHost, UserInfo } from \"./types\";\r\n\r\nimport \"./components/views/ConnectionOptions\";\r\nimport \"./components/views/LocalAuthentication\";\r\nimport \"./components/views/RemoteAuthentication\";\r\nimport \"./components/views/CurrentState\";\r\nimport \"./components/views/HostBrowser\";\r\nimport \"./components/views/HostDetail\";\r\nimport \"./components/views/LoggedInDashboard\";\r\n\r\ntype Views =\r\n | 'connection-options'\r\n | 'local-authentication'\r\n | 'remote-authentication'\r\n | 'current-state'\r\n | 'host-browser'\r\n | 'host-detail'\r\n | 'logged-in-dashboard';\r\n\r\nconst styles = css`\r\n @import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&display=swap');\r\n\r\n :host {\r\n font-family: 'DM Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;\r\n --ac-primary-color: #91e3fd;\r\n --ac-primary-color-light: #acebff;\r\n --ac-success-color: #5dd27d;\r\n --ac-danger-color: #f4367f;\r\n --ac-text-color: #fff;\r\n --ac-background-color: #191c3fe0;\r\n --ac-border-color-dark: #91d4fd2b;\r\n --ac-border-color-light: #91d4fd69;\r\n }\r\n\r\n * {\r\n box-sizing: border-box;\r\n }\r\n\r\n .wrapper {\r\n position: fixed;\r\n display: grid;\r\n place-content: center;\r\n top: 0;\r\n left: 0;\r\n height: 100vh;\r\n width: 100vw;\r\n z-index: 99999;\r\n }\r\n\r\n .backdrop {\r\n position: absolute;\r\n top: 0;\r\n left: 0;\r\n height: 100vh;\r\n width: 100vw;\r\n background-color: rgba(0, 0, 0, 0.5);\r\n }\r\n\r\n .modal {\r\n z-index: 10;\r\n background-color: var(--ac-background-color);\r\n border: 1px solid var(--ac-border-color-dark);\r\n border-radius: 12px;\r\n padding: 30px;\r\n width: calc(100vw - 30px);\r\n max-width: 480px;\r\n max-height: calc(100vh - 30px);\r\n overflow-y: auto;\r\n backdrop-filter: blur(10px);\r\n -webkit-backdrop-filter: blur(10px); /* Safari */\r\n display: flex;\r\n flex-direction: column;\r\n }\r\n\r\n .modal-header {\r\n position: relative;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n color: var(--ac-primary-color);\r\n margin: 10px 0 30px 0;\r\n }\r\n\r\n .modal-header > svg {\r\n width: 70px;\r\n height: 70px;\r\n }\r\n\r\n .modal-header .back-button {\r\n all: unset;\r\n display: inline-flex;\r\n align-items: center;\r\n gap: 8px;\r\n cursor: pointer;\r\n font-size: 16px;\r\n color: rgba(255, 255, 255, 0.5);\r\n position: absolute;\r\n left: 0;\r\n top: 0;\r\n }\r\n\r\n .modal-header .back-button svg {\r\n width: 20px;\r\n height: 20px;\r\n }\r\n\r\n .modal-header .back-button:hover {\r\n color: rgba(255, 255, 255, 0.8);\r\n }\r\n\r\n .modal-content {\r\n display: flex;\r\n flex-direction: column;\r\n justify-content: center;\r\n flex: 1 1 auto;\r\n min-height: 0;\r\n }\r\n\r\n .settings-bar {\r\n position: fixed;\r\n bottom: 10px;\r\n right: 10px;\r\n display: flex;\r\n align-items: center;\r\n gap: 6px;\r\n z-index: 99999;\r\n }\r\n\r\n .credit-badge {\r\n display: flex;\r\n align-items: center;\r\n gap: 4px;\r\n background: var(--ac-background-color);\r\n backdrop-filter: blur(10px);\r\n -webkit-backdrop-filter: blur(10px);\r\n border: 1px solid var(--ac-border-color-dark);\r\n border-radius: 20px;\r\n padding: 4px 10px;\r\n font-size: 12px;\r\n font-weight: 500;\r\n color: var(--ac-primary-color);\r\n white-space: nowrap;\r\n }\r\n\r\n .credit-badge svg {\r\n width: 14px;\r\n height: 14px;\r\n }\r\n\r\n .credit-badge.low-credit {\r\n color: var(--ac-danger-color);\r\n border-color: var(--ac-danger-color);\r\n animation: pulse-danger 2s ease-in-out infinite;\r\n }\r\n\r\n .settings-button {\r\n appearance: none;\r\n border: none;\r\n background: transparent;\r\n padding: 0;\r\n cursor: pointer;\r\n color: var(--ac-primary-color);\r\n width: 34px;\r\n height: 34px;\r\n }\r\n\r\n .settings-button.low-credit {\r\n color: var(--ac-danger-color);\r\n animation: pulse-danger 2s ease-in-out infinite;\r\n }\r\n\r\n @keyframes pulse-danger {\r\n 0%, 100% { opacity: 1; }\r\n 50% { opacity: 0.4; }\r\n }\r\n`;\r\n\r\n@customElement(\"ad4m-connect\")\r\nexport class Ad4mConnectElement extends LitElement {\r\n static styles = [styles];\r\n\r\n core: Ad4mConnect;\r\n\r\n // Global state\r\n @state() modalOpen = false;\r\n @state() private currentView: Views = \"connection-options\";\r\n\r\n // Local authentication state\r\n @state() private verificationError = false;\r\n\r\n // Remote authentication state\r\n @state() private remoteAuthLoading = false;\r\n @state() private remoteAuthState: VerificationRequestResult | null = null;\r\n @state() private emailCodeError = false;\r\n @state() private passwordError = false;\r\n @state() private accountCreationError = false;\r\n\r\n // Hosting state\r\n @state() private hosts: RemoteHost[] = [];\r\n @state() private hostsLoading = false;\r\n @state() private hostsError: string | null = null;\r\n @state() private selectedHost: RemoteHost | null = null;\r\n @state() private userInfo: UserInfo | null = null;\r\n @state() private lowCredit = false;\r\n @state() private requestingPayment = false;\r\n @state() private paymentError: string | null = null;\r\n private openedDueToCreditDepletion = false;\r\n\r\n connectedCallback() {\r\n super.connectedCallback();\r\n autoBind(this);\r\n\r\n // Set up auth listener before attempting connection\r\n this.core.addEventListener('authstatechange', (e: any) => {\r\n if (e.detail === 'unauthenticated') {\r\n // Token expired or invalid - show connection options\r\n this.currentView = \"connection-options\";\r\n this.modalOpen = true;\r\n } else if (e.detail === 'authenticated') {\r\n // Successfully authenticated - switch to dashboard and close modal\r\n this.currentView = \"logged-in-dashboard\";\r\n this.modalOpen = false;\r\n }\r\n // Trigger re-render to update UI based on new auth state\r\n this.requestUpdate();\r\n });\r\n\r\n // Hosting events\r\n this.core.addEventListener('userinfochange', (e: any) => {\r\n const incoming = e.detail as UserInfo;\r\n // Preserve locally-set wallet address until server confirms it via polling\r\n if (this.userInfo?.hotWalletAddress && !incoming.hotWalletAddress) {\r\n incoming.hotWalletAddress = this.userInfo.hotWalletAddress;\r\n }\r\n this.userInfo = incoming;\r\n this.lowCredit = this.userInfo.remainingCredits <= this.core.lowCreditThreshold;\r\n this.requestUpdate();\r\n });\r\n\r\n this.core.addEventListener('creditdepleted', () => {\r\n this.lowCredit = true;\r\n if (this.core.connectedHost) {\r\n // Always record depletion state so .forceOpen can act on it later\r\n this.openedDueToCreditDepletion = true;\r\n try { this.core.options.onCreditsDepleted?.(); } catch (e) { console.error('[Ad4m Connect] onCreditsDepleted callback error:', e); }\r\n // Auto-open the dashboard so the user sees the top-up options\r\n if (!this.modalOpen) {\r\n this.currentView = \"logged-in-dashboard\";\r\n this.modalOpen = true;\r\n }\r\n }\r\n this.requestUpdate();\r\n });\r\n\r\n if (this.core.token) {\r\n // Try to auto-connect with stored token\r\n this.core.connect().then(() => {\r\n // If we have a connected host, start credit polling\r\n if (this.core.connectedHost) {\r\n this.selectedHost = this.core.connectedHost;\r\n this.core.startCreditSubscription();\r\n }\r\n }).catch((error) => {\r\n // Connection failed - show connection options\r\n console.error('[Ad4m Connect UI] Auto-connect failed:', error);\r\n this.currentView = \"connection-options\";\r\n this.modalOpen = true;\r\n });\r\n } else {\r\n // No token - show connection options\r\n this.currentView = \"connection-options\";\r\n this.modalOpen = true;\r\n }\r\n }\r\n\r\n private async changePort(event: CustomEvent) {\r\n this.core.port = event.detail.port;\r\n setLocal(\"ad4m-port\", this.core.port.toString());\r\n this.requestUpdate();\r\n }\r\n\r\n private async connectLocalNode() {\r\n // First, try same-origin (works when Vite dev server proxies /health to executor)\r\n try {\r\n const probeRes = await fetch(window.location.origin + '/health', { signal: AbortSignal.timeout(2000) });\r\n if (!probeRes.ok) throw new Error('probe failed');\r\n const body = await probeRes.json();\r\n if (body?.status !== 'ok') throw new Error('not an ad4m executor');\r\n this.core.url = window.location.origin;\r\n setLocal(\"ad4m-url\", this.core.url);\r\n console.log('[Ad4m Connect UI] Using same-origin proxy:', this.core.url);\r\n } catch {\r\n // Fall back to direct connection\r\n const host = window.location.hostname === '127.0.0.1' ? '127.0.0.1' : 'localhost';\r\n this.core.url = `http://${host}:${this.core.port}`;\r\n setLocal(\"ad4m-url\", this.core.url);\r\n }\r\n \r\n try {\r\n await this.core.connect();\r\n this.currentView = \"local-authentication\";\r\n } catch (error) {\r\n console.error('[Ad4m Connect UI] Local node connection failed:', error);\r\n this.currentView = \"connection-options\";\r\n }\r\n }\r\n\r\n private async verifyLocalAd4mCode(event: CustomEvent) {\r\n const success = await this.core.verifyLocalAd4mCode(event.detail.code);\r\n this.verificationError = !success;\r\n if (success) this.modalOpen = false;\r\n }\r\n\r\n // --- Hosting handlers ---\r\n\r\n private async browseHosts() {\r\n this.hostsLoading = true;\r\n this.hostsError = null;\r\n this.currentView = \"host-browser\";\r\n\r\n try {\r\n this.hosts = await fetchHosts(this.core.hostIndexUrl);\r\n } catch (error) {\r\n console.error('[Ad4m Connect UI] Failed to fetch hosts:', error);\r\n this.hostsError = error instanceof Error ? error.message : \"Failed to load hosts\";\r\n } finally {\r\n this.hostsLoading = false;\r\n }\r\n }\r\n\r\n private async retryFetchHosts() {\r\n this.hostsLoading = true;\r\n this.hostsError = null;\r\n\r\n try {\r\n this.hosts = await fetchHosts(this.core.hostIndexUrl);\r\n } catch (error) {\r\n console.error('[Ad4m Connect UI] Failed to fetch hosts:', error);\r\n this.hostsError = error instanceof Error ? error.message : \"Failed to load hosts\";\r\n } finally {\r\n this.hostsLoading = false;\r\n }\r\n }\r\n\r\n private selectHost(e: CustomEvent) {\r\n this.selectedHost = e.detail.host as RemoteHost;\r\n this.currentView = \"host-detail\";\r\n }\r\n\r\n private async proceedToAuth(e: CustomEvent) {\r\n const host = e.detail.host as RemoteHost;\r\n this.selectedHost = host;\r\n\r\n const candidateUrl = host.url;\r\n\r\n try {\r\n // Verify HTTP reachability before committing URL\r\n await checkConnection(wsUrlToHttpBase(candidateUrl));\r\n console.log('[Ad4m Connect UI] Host connection successful:', host.name);\r\n\r\n // Verify it's an AD4M API\r\n const prevUrl = this.core.url;\r\n this.core.url = candidateUrl;\r\n const isValid = await this.core.isValidAd4mAPI();\r\n if (!isValid) {\r\n this.core.url = prevUrl;\r\n throw new Error(\"Server is reachable but doesn't appear to be an AD4M executor\");\r\n }\r\n\r\n // Validation passed \u2014 persist\r\n setLocal(\"ad4m-url\", candidateUrl);\r\n\r\n // Navigate to remote authentication\r\n this.currentView = \"remote-authentication\";\r\n } catch (error) {\r\n console.error('[Ad4m Connect UI] Host connection failed:', error);\r\n // Go back to host detail with an error \u2014 for now just go back to browser\r\n this.hostsError = error instanceof Error ? error.message : \"Connection failed\";\r\n this.currentView = \"host-browser\";\r\n }\r\n }\r\n\r\n private async handleAuthSuccess() {\r\n // Called after successful remote auth when a host is selected\r\n if (this.selectedHost) {\r\n this.core.setConnectedHost(this.selectedHost);\r\n this.core.startCreditSubscription();\r\n this.currentView = \"logged-in-dashboard\";\r\n } else {\r\n this.modalOpen = false;\r\n }\r\n }\r\n\r\n private async handleRequestTopUp(e: CustomEvent) {\r\n this.requestingPayment = true;\r\n this.paymentError = null;\r\n\r\n try {\r\n const result = await this.core.requestTopUp(e.detail.amountHOT);\r\n if (!result.success) {\r\n this.paymentError = result.message;\r\n }\r\n } catch (error) {\r\n this.paymentError = error instanceof Error ? error.message : \"Payment request failed\";\r\n } finally {\r\n this.requestingPayment = false;\r\n }\r\n }\r\n\r\n private async handleSetWalletAddress(e: CustomEvent) {\r\n try {\r\n await this.core.ad4mClient!.agent.setHotWalletAddress(e.detail.address);\r\n if (this.userInfo) {\r\n this.userInfo = { ...this.userInfo, hotWalletAddress: e.detail.address };\r\n }\r\n } catch (error) {\r\n console.error('[Ad4m Connect] Failed to set wallet address:', error);\r\n }\r\n }\r\n\r\n // --- Remote authentication handlers (kept for remote-authentication view) ---\r\n\r\n private async connectRemoteNode(e: CustomEvent) {\r\n // Legacy direct-URL connection (kept for backward compat if needed)\r\n this.core.url = e.detail.remoteUrl;\r\n setLocal(\"ad4m-url\", this.core.url);\r\n\r\n try {\r\n await checkConnection(wsUrlToHttpBase(e.detail.remoteUrl));\r\n const isValidAd4mApi = await this.core.isValidAd4mAPI();\r\n if (!isValidAd4mApi) throw new Error(\"Server is reachable but doesn't appear to be an AD4M executor\");\r\n\r\n this.currentView = \"remote-authentication\";\r\n } catch (error) {\r\n console.error('[Ad4m Connect UI] Remote connection failed:', error);\r\n }\r\n }\r\n\r\n private async emailLogin(e: CustomEvent) {\r\n try {\r\n this.remoteAuthLoading = true;\r\n this.remoteAuthState = await this.core.submitEmail(e.detail.email);\r\n } finally {\r\n this.remoteAuthLoading = false;\r\n }\r\n }\r\n\r\n private async verifyEmailCode(event: CustomEvent) {\r\n try {\r\n this.remoteAuthLoading = true;\r\n const success = await this.core.verifyEmailCode(event.detail.email, event.detail.code);\r\n this.emailCodeError = !success;\r\n if (success) await this.handleAuthSuccess();\r\n } catch (error) {\r\n this.emailCodeError = true;\r\n } finally {\r\n this.remoteAuthLoading = false;\r\n }\r\n }\r\n\r\n private async passwordLogin(event: CustomEvent) {\r\n try {\r\n this.remoteAuthLoading = true;\r\n const success = await this.core.loginWithPassword(event.detail.email, event.detail.password);\r\n this.passwordError = !success;\r\n if (success) await this.handleAuthSuccess();\r\n } catch (error) {\r\n this.passwordError = true;\r\n } finally {\r\n this.remoteAuthLoading = false;\r\n }\r\n }\r\n\r\n private async createAccount(event: CustomEvent) {\r\n try {\r\n this.remoteAuthLoading = true;\r\n const success = await this.core.createAccount(event.detail.email, event.detail.password);\r\n this.accountCreationError = !success;\r\n if (success) await this.handleAuthSuccess();\r\n } catch (error) {\r\n this.accountCreationError = true;\r\n } finally {\r\n this.remoteAuthLoading = false;\r\n }\r\n }\r\n\r\n private async disconnect() {\r\n await this.core.disconnect();\r\n window.location.reload();\r\n }\r\n\r\n private get backTarget(): Views | null {\r\n switch (this.currentView) {\r\n case \"local-authentication\": return \"connection-options\";\r\n case \"host-browser\": return \"connection-options\";\r\n case \"host-detail\": return \"host-browser\";\r\n case \"remote-authentication\": return this.selectedHost ? \"host-detail\" : \"connection-options\";\r\n default: return null;\r\n }\r\n }\r\n\r\n private handleBack() {\r\n const target = this.backTarget;\r\n if (target) {\r\n if (this.currentView === \"remote-authentication\") {\r\n this.resetRemoteAuthState();\r\n }\r\n this.currentView = target;\r\n }\r\n }\r\n\r\n private resetRemoteAuthState() {\r\n this.remoteAuthState = null;\r\n this.remoteAuthLoading = false;\r\n this.emailCodeError = false;\r\n this.passwordError = false;\r\n this.accountCreationError = false;\r\n }\r\n\r\n renderViews() {\r\n if (this.currentView === \"connection-options\") {\r\n return html`\r\n <connection-options\r\n .port=${this.core.port}\r\n .showHosting=${!!this.core.options.hosting}\r\n @change-port=${this.changePort}\r\n @connect-local-node=${this.connectLocalNode}\r\n @browse-hosts=${this.browseHosts}\r\n ></connection-options>\r\n `;\r\n }\r\n\r\n if (this.currentView === \"local-authentication\") {\r\n return html`\r\n <local-authentication \r\n .capabilities=${this.core.options.capabilities}\r\n .appname=${this.core.options.appInfo.name}\r\n .appiconpath=${this.core.options.appInfo.iconPath}\r\n .verificationError=${this.verificationError}\r\n @back=${() => { this.currentView = \"connection-options\" }}\r\n @request-capability=${() => this.core.requestCapability(true)}\r\n @verify-code=${this.verifyLocalAd4mCode}\r\n @clear-verification-error=${() => { this.verificationError = false; }}\r\n ></local-authentication>\r\n `;\r\n }\r\n\r\n if (this.currentView === \"host-browser\") {\r\n return html`\r\n <host-browser\r\n .hosts=${this.hosts}\r\n .loading=${this.hostsLoading}\r\n .error=${this.hostsError}\r\n .lastHostId=${this.core.connectedHost?.id ?? null}\r\n .defaultUrl=${this.core.options.remoteUrl ?? ''}\r\n @select-host=${this.selectHost}\r\n @back=${() => { this.currentView = \"connection-options\" }}\r\n @retry=${this.retryFetchHosts}\r\n ></host-browser>\r\n `;\r\n }\r\n\r\n if (this.currentView === \"host-detail\") {\r\n return html`\r\n <host-detail\r\n .host=${this.selectedHost!}\r\n @proceed-to-auth=${this.proceedToAuth}\r\n @back=${() => { this.currentView = \"host-browser\" }}\r\n ></host-detail>\r\n `;\r\n }\r\n\r\n if (this.currentView === \"remote-authentication\") {\r\n return html`\r\n <remote-authentication\r\n .host=${this.selectedHost}\r\n .remoteAuthLoading=${this.remoteAuthLoading}\r\n .remoteAuthState=${this.remoteAuthState}\r\n .emailCodeError=${this.emailCodeError}\r\n .passwordError=${this.passwordError}\r\n .accountCreationError=${this.accountCreationError}\r\n @back=${() => {\r\n this.currentView = this.selectedHost ? \"host-detail\" : \"connection-options\";\r\n }}\r\n @email-login=${this.emailLogin}\r\n @verify-email-code=${this.verifyEmailCode}\r\n @password-login=${this.passwordLogin}\r\n @create-account=${this.createAccount}\r\n @clear-email-code-error=${() => { this.emailCodeError = false; }}\r\n @reset-auth-state=${() => { this.resetRemoteAuthState(); }}\r\n ></remote-authentication>\r\n `;\r\n }\r\n\r\n if (this.currentView === \"logged-in-dashboard\") {\r\n return html`\r\n <logged-in-dashboard\r\n .connectedHost=${this.core.connectedHost}\r\n .userInfo=${this.userInfo}\r\n .requestingPayment=${this.requestingPayment}\r\n .paymentError=${this.paymentError}\r\n .forceOpen=${this.openedDueToCreditDepletion}\r\n @close=${() => { this.openedDueToCreditDepletion = false; this.modalOpen = false; }}\r\n @use-app=${() => {\r\n this.openedDueToCreditDepletion = false;\r\n try { this.core.options.onUseApp?.(); } catch (e) { console.error('[Ad4m Connect] onUseApp callback error:', e); }\r\n this.modalOpen = false;\r\n }}\r\n @disconnect=${this.disconnect}\r\n @request-top-up=${this.handleRequestTopUp}\r\n @set-wallet-address=${this.handleSetWalletAddress}\r\n @fetch-compute-log=${(e: CustomEvent) => {\r\n const cb = e?.detail?.callback;\r\n if (typeof cb !== 'function') return;\r\n this.core.fetchComputeLog().then(cb).catch((err: any) => {\r\n console.error('[Ad4m Connect] Failed to fetch compute log:', err);\r\n cb([]);\r\n });\r\n }}\r\n ></logged-in-dashboard>\r\n `;\r\n }\r\n\r\n if (this.currentView === \"current-state\") {\r\n return html`\r\n <current-state\r\n .url=${this.core.url}\r\n .port=${this.core.port}\r\n .authState=${this.core.authState}\r\n @close=${() => { this.modalOpen = false; }}\r\n @disconnect=${this.disconnect}\r\n ></current-state>\r\n `;\r\n }\r\n }\r\n\r\n render() {\r\n if (this.modalOpen) {\r\n // Show modal\r\n return html`\r\n <div class=\"wrapper\">\r\n <div class=\"modal\">\r\n <header class=\"modal-header\">\r\n ${this.backTarget ? html`\r\n <button class=\"back-button\" aria-label=\"Go back\" @click=${this.handleBack}>\r\n ${ArrowLeftIcon()} Back\r\n </button>\r\n ` : ''}\r\n ${Ad4mLogo()}\r\n </header>\r\n <main class=\"modal-content\">\r\n ${this.renderViews()}\r\n </main>\r\n </div>\r\n <div class=\"backdrop\" />\r\n </div>\r\n `;\r\n } else if (this.core.authState === \"authenticated\") {\r\n // Show settings button when authenticated and modal is closed\r\n const credits = this.userInfo?.remainingCredits;\r\n const showCredits = credits != null && isFinite(credits);\r\n return html`\r\n <div class=\"settings-bar\">\r\n ${showCredits ? html`\r\n <span class=\"credit-badge ${this.lowCredit ? 'low-credit' : ''}\">\r\n ${CreditIcon()} ${credits.toFixed(2)} wHOT\r\n </span>\r\n ` : ''}\r\n <button\r\n type=\"button\"\r\n class=\"settings-button ${this.lowCredit ? 'low-credit' : ''}\"\r\n aria-label=\"Open settings\"\r\n @click=${() => {\r\n this.currentView = this.core.connectedHost ? \"logged-in-dashboard\" : \"current-state\";\r\n this.modalOpen = true;\r\n }}\r\n >\r\n ${Ad4mLogo()}\r\n </button>\r\n </div>\r\n `;\r\n }\r\n\r\n // Nothing to render\r\n return null;\r\n }\r\n}\r\n\r\nexport default function Ad4mConnectUI(core: Ad4mConnect): Ad4mConnectElement {\r\n // Create element and inject the core\r\n const element = new Ad4mConnectElement();\r\n element.core = core;\r\n \r\n if (core.embedded) {\r\n // Running in embedded mode - no UI needed\r\n console.log('[Ad4m Connect] Running in embedded mode - UI will not be shown');\r\n } else {\r\n // Not embedded - mount UI to DOM\r\n console.log('[Ad4m Connect UI] Mounting UI to DOM');\r\n document.body.appendChild(element);\r\n }\r\n\r\n return element;\r\n}\r\n", "import { Ad4mClient } from '@coasys/ad4m';\nimport Ad4mConnect from './core';\nimport Ad4mConnectUI from './web';\nimport { isEmbedded } from './utils';\nimport { Ad4mConnectOptions } from './types';\n\n/**\n * Advanced API - returns core immediately and client as promise.\n * Allows attaching event listeners before authentication completes.\n * \n * @example\n * ```typescript\n * const { core, client } = getAd4mConnect(options);\n * core.addEventListener('authstatechange', (e) => console.log(e.detail));\n * const ad4mClient = await client;\n * ```\n */\nexport function getAd4mConnect(options: Ad4mConnectOptions): { core: Ad4mConnect; client: Promise<Ad4mClient> } {\n // Build the core\n const core = new Ad4mConnect(options);\n\n if (isEmbedded()) {\n // Immediately return the core and client\n const client = core.connect();\n return { core, client };\n } else {\n // Build the UI element to allow the user to walk through authentication\n Ad4mConnectUI(core);\n \n // Setup a promise that resolves when authentication completes\n const client = new Promise<Ad4mClient>((resolve) => {\n core.addEventListener('authstatechange', (event: any) => {\n if (event.detail === 'authenticated' && core.ad4mClient) resolve(core.ad4mClient);\n });\n });\n \n return { core, client };\n }\n}\n\n/**\n * Simple API - returns just the authenticated client.\n * \n * @example\n * ```typescript\n * const ad4mClient = await getAd4mClient(options);\n * ```\n */\nexport async function getAd4mClient(options: Ad4mConnectOptions): Promise<Ad4mClient> {\n const { client } = getAd4mConnect(options);\n return client;\n}\n\n// Re-export isEmbedded utility\nexport { isEmbedded };"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,SAAS,aAAsB;AACpC,SAAO,OAAO,WAAW,eAAe,OAAO,SAAS,OAAO;AACjE;AAEA,SAAS,wBAAiC;AACxC,MAAI;AACF,iBAAa,QAAQ,QAAQ,EAAE;AAC/B,iBAAa,WAAW,MAAM;AAAA,EAChC,SAASA,IAAP;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEO,SAAS,SAAS,KAAa,OAAqB;AACzD,MAAI,sBAA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O;AACT;;;ACtrBO,SAAS,eAAe,SAAiF;AAE9G,QAAM,OAAO,IAAI,YAAY,OAAO;AAEpC,MAAI,WAAW,GAAG;AAEhB,UAAM,SAAS,KAAK,QAAQ;AAC5B,WAAO,EAAE,MAAM,OAAO;AAAA,EACxB,OAAO;AAEL,kBAAc,IAAI;AAGlB,UAAM,SAAS,IAAI,QAAoB,CAAC,YAAY;AAClD,WAAK,iBAAiB,mBAAmB,CAAC,UAAe;AACvD,YAAI,MAAM,WAAW,mBAAmB,KAAK;AAAY,kBAAQ,KAAK,UAAU;AAAA,MAClF,CAAC;AAAA,IACH,CAAC;AAED,WAAO,EAAE,MAAM,OAAO;AAAA,EACxB;AACF;AAUA,SAAsB,cAAc,SAAkD;AAAA;AACpF,UAAM,EAAE,OAAO,IAAI,eAAe,OAAO;AACzC,WAAO;AAAA,EACT;AAAA;",
|
|
6
|
+
"names": ["e", "_", "s", "i", "e", "code", "e", "err", "result", "l", "f", "i", "l", "f", "c", "i", "r", "e", "p", "v", "r", "e", "c", "l", "f", "e", "_QuerySubscriptionProxy_notifyCallbacks", "s", "t", "code", "r", "i", "p", "c", "o", "_IDBCache_open", "a", "u", "_ExpressionClient_memCacheResult", "w", "h", "n", "m", "k", "v", "rank", "s2", "b", "c2", "f", "t", "p", "normalizedNs", "v", "_", "e", "r", "results", "totalCount", "o", "a", "b", "i", "k", "ExceptionType", "PerspectiveState", "e", "DEFAULT_INDEX_URL", "e", "_a", "code", "global", "window", "supportsAdoptingStyleSheets", "ShadowRoot", "ShadyCSS", "nativeShadow", "Document", "prototype", "CSSStyleSheet", "constructionToken", "Symbol", "cssTagCache", "WeakMap", "CSSResult", "constructor", "cssText", "strings", "safeToken", "this", "Error", "_strings", "styleSheet", "_styleSheet", "cacheable", "length", "get", "replaceSync", "set", "toString", "unsafeCSS", "value", "String", "css", "values", "reduce", "acc", "v", "idx", "adoptStyles", "renderRoot", "styles", "adoptedStyleSheets", "map", "s", "forEach", "style", "document", "createElement", "nonce", "setAttribute", "textContent", "appendChild", "getCompatibleStyle", "sheet", "rule", "cssRules", "global", "window", "trustedTypes", "emptyStringForBooleanAttribute", "emptyScript", "polyfillSupport", "reactiveElementPolyfillSupport", "defaultConverter", "toAttribute", "value", "type", "Boolean", "Object", "Array", "JSON", "stringify", "fromAttribute", "fromValue", "Number", "parse", "e", "notEqual", "old", "defaultPropertyDeclaration", "attribute", "String", "converter", "reflect", "hasChanged", "finalized", "ReactiveElement", "HTMLElement", "constructor", "super", "this", "__instanceProperties", "Map", "isUpdatePending", "hasUpdated", "__reflectingProperty", "__initialize", "static", "initializer", "finalize", "_a", "_initializers", "push", "observedAttributes", "attributes", "elementProperties", "forEach", "v", "p", "attr", "__attributeNameForProperty", "__attributeToPropertyMap", "set", "name", "options", "state", "noAccessor", "prototype", "hasOwnProperty", "key", "Symbol", "descriptor", "getPropertyDescriptor", "defineProperty", "get", "oldValue", "requestUpdate", "configurable", "enumerable", "superCtor", "getPrototypeOf", "props", "properties", "propKeys", "getOwnPropertyNames", "getOwnPropertySymbols", "createProperty", "elementStyles", "finalizeStyles", "styles", "isArray", "Set", "flat", "Infinity", "reverse", "s", "unshift", "getCompatibleStyle", "toLowerCase", "__updatePromise", "Promise", "res", "enableUpdating", "_$changedProperties", "__saveInstanceProperties", "i", "addController", "controller", "__controllers", "renderRoot", "isConnected", "_b", "hostConnected", "call", "removeController", "splice", "indexOf", "_v", "createRenderRoot", "shadowRoot", "attachShadow", "shadowRootOptions", "adoptStyles", "connectedCallback", "c", "_requestedUpdate", "disconnectedCallback", "hostDisconnected", "attributeChangedCallback", "_old", "_$attributeToProperty", "__propertyToAttribute", "attrValue", "undefined", "removeAttribute", "setAttribute", "ctor", "propName", "getPropertyOptions", "shouldRequestUpdate", "has", "__reflectingProperties", "__enqueueUpdate", "async", "reject", "result", "scheduleUpdate", "performUpdate", "shouldUpdate", "changedProperties", "willUpdate", "hostUpdate", "update", "__markUpdated", "_$didUpdate", "_changedProperties", "hostUpdated", "firstUpdated", "updated", "updateComplete", "getUpdateComplete", "k", "mode", "_d", "reactiveElementVersions", "global", "window", "trustedTypes", "policy", "createPolicy", "createHTML", "s", "boundAttributeSuffix", "marker", "Math", "random", "String", "slice", "markerMatch", "nodeMarker", "d", "document", "createMarker", "createComment", "isPrimitive", "value", "isArray", "Array", "isIterable", "Symbol", "iterator", "SPACE_CHAR", "textEndRegex", "commentEndRegex", "comment2EndRegex", "tagEndRegex", "RegExp", "singleQuoteAttrEndRegex", "doubleQuoteAttrEndRegex", "rawTextElement", "tag", "type", "strings", "values", "_$litType$", "html", "svg", "noChange", "for", "nothing", "templateCache", "WeakMap", "walker", "createTreeWalker", "trustFromTemplateString", "tsa", "stringFromTSA", "hasOwnProperty", "Error", "getTemplateHtml", "l", "length", "attrNames", "rawTextEndRegex", "regex", "i", "attrName", "match", "attrNameEndIndex", "lastIndex", "exec", "test", "end", "startsWith", "push", "undefined", "Template", "constructor", "options", "node", "this", "parts", "nodeIndex", "attrNameIndex", "partCount", "el", "createElement", "currentNode", "content", "svgElement", "firstChild", "remove", "append", "childNodes", "nextNode", "nodeType", "hasAttributes", "attrsToRemove", "name", "getAttributeNames", "endsWith", "realName", "statics", "getAttribute", "toLowerCase", "split", "m", "index", "ctor", "PropertyPart", "BooleanAttributePart", "EventPart", "AttributePart", "removeAttribute", "tagName", "textContent", "emptyScript", "data", "indexOf", "static", "_options", "innerHTML", "resolveDirective", "part", "parent", "attributeIndex", "currentDirective", "_a", "__directives", "__directive", "nextDirectiveConstructor", "_b", "call", "_$initialize", "_c", "_d", "_$resolve", "TemplateInstance", "template", "_$parts", "_$disconnectableChildren", "_$template", "_$parent", "parentNode", "_$isConnected", "_clone", "fragment", "creationScope", "importNode", "partIndex", "templatePart", "ChildPart", "nextSibling", "ElementPart", "_update", "_$setValue", "startNode", "endNode", "_$committedValue", "_$startNode", "_$endNode", "__isConnected", "isConnected", "directiveParent", "_$clear", "_commitText", "_commitTemplateResult", "_commitNode", "_commitIterable", "_insert", "insertBefore", "createTextNode", "result", "_$getTemplate", "h", "instance", "get", "set", "itemParts", "itemPart", "item", "start", "from", "_$notifyConnectionChanged", "n", "setConnected", "element", "fill", "valueIndex", "noCommit", "change", "v", "_commitValue", "setAttribute", "emptyStringForBooleanAttribute", "super", "newListener", "oldListener", "shouldRemoveListener", "capture", "once", "passive", "shouldAddListener", "removeEventListener", "addEventListener", "handleEvent", "event", "host", "polyfillSupport", "global", "litHtmlPolyfillSupport", "Template", "ChildPart", "_d", "litHtmlVersions", "push", "render", "value", "container", "options", "partOwnerNode", "_a", "renderBefore", "part", "endNode", "_b", "insertBefore", "createMarker", "_$setValue", "LitElement", "ReactiveElement", "constructor", "this", "renderOptions", "host", "__childPart", "createRenderRoot", "renderRoot", "super", "_a", "_b", "renderBefore", "firstChild", "update", "changedProperties", "value", "render", "hasUpdated", "isConnected", "connectedCallback", "setConnected", "disconnectedCallback", "noChange", "globalThis", "litElementHydrateSupport", "call", "polyfillSupport", "litElementPolyfillSupport", "_c", "globalThis", "litElementVersions", "push", "customElement", "tagName", "classOrDescriptor", "clazz", "customElements", "define", "descriptor", "kind", "elements", "finisher", "standardProperty", "options", "element", "kind", "descriptor", "finisher", "clazz", "createProperty", "key", "Symbol", "placement", "originalKey", "initializer", "this", "call", "legacyProperty", "proto", "name", "constructor", "property", "protoOrDescriptor", "state", "options", "property", "slotAssignedElements", "_a", "window", "HTMLSlotElement", "prototype", "assignedElements", "slot", "opts", "assignedNodes", "filter", "node", "nodeType", "Node", "ELEMENT_NODE", "s", "e", "n", "t", "s", "e", "n", "t", "s", "e", "n", "t", "s", "n", "e", "e", "s", "e", "r", "h", "n", "t", "s", "m", "r", "n", "e", "s", "e", "n", "t", "s", "e", "_a", "_b", "err", "t"]
|
|
7
|
+
}
|