UNPKG

cleaker

Version:
1 lines 140 kB
{"version":3,"file":"cleaker.cjs","sources":["../src/protocol/errors.ts","../src/parse/grammar.ts","../src/parse/parseMeTarget.ts","../src/parse/parseTarget.ts","../src/constants.ts","../src/pointer/remotePointer.ts","../src/namespace/expression.ts","../src/binder.ts","../src/cleaker.ts"],"sourcesContent":["export class CleakerError extends Error {\n readonly code: string;\n readonly details?: Record<string, unknown>;\n\n constructor(code: string, message: string, details?: Record<string, unknown>) {\n super(message);\n this.name = 'CleakerError';\n this.code = code;\n this.details = details;\n }\n}\n\nexport class CleakerParseError extends CleakerError {\n constructor(message: string, details?: Record<string, unknown>) {\n super('PARSE_TARGET_FAILED', message, details);\n this.name = 'CleakerParseError';\n }\n}\n","export const ME_SCHEME = 'me://';\nexport const CONTEXT_OPEN = '[';\nexport const CONTEXT_CLOSE = ']';\nexport const CONTEXT_BRANCH_SEPARATOR = '|';\nexport const CONTEXT_AND_SEPARATOR = ';';\nexport const CONTEXT_VALUE_SEPARATOR = ',';\n","import { CleakerParseError } from '../protocol/errors';\nimport {\n CONTEXT_AND_SEPARATOR,\n CONTEXT_BRANCH_SEPARATOR,\n CONTEXT_OPEN,\n CONTEXT_CLOSE,\n CONTEXT_VALUE_SEPARATOR,\n ME_SCHEME,\n} from './grammar';\nimport type {\n MeTargetContextAtom,\n MeTargetContextClause,\n MeTargetContextSet,\n ParseTargetOptions,\n ParsedTarget,\n} from '../types/target';\n\nfunction normalizeInput(input: string): string {\n const raw = String(input ?? '').trim();\n if (!raw) throw new CleakerParseError('Target cannot be empty');\n return raw;\n}\n\nfunction stripScheme(raw: string): string {\n if (raw.startsWith(ME_SCHEME)) return raw.slice(ME_SCHEME.length);\n return raw;\n}\n\nfunction findTokenOutsideContext(input: string, token: string, start = 0): number {\n let depth = 0;\n for (let index = start; index < input.length; index += 1) {\n const char = input[index];\n if (char === CONTEXT_OPEN) {\n depth += 1;\n continue;\n }\n if (char === CONTEXT_CLOSE) {\n depth = Math.max(0, depth - 1);\n continue;\n }\n if (depth === 0 && char === token) return index;\n }\n return -1;\n}\n\nfunction ensureBalancedContext(input: string): void {\n let depth = 0;\n for (const char of input) {\n if (char === CONTEXT_OPEN) depth += 1;\n if (char === CONTEXT_CLOSE) depth -= 1;\n if (depth < 0) {\n throw new CleakerParseError('Target has an unexpected closing context bracket', { raw: input });\n }\n }\n if (depth !== 0) {\n throw new CleakerParseError('Target has an unclosed context bracket', { raw: input });\n }\n}\n\nfunction expandClauseWithAtom(\n clauses: MeTargetContextClause[],\n atomKey: string,\n values: string[],\n): MeTargetContextClause[] {\n const next: MeTargetContextClause[] = [];\n for (const clause of clauses) {\n for (const value of values) {\n next.push([\n ...clause,\n {\n key: atomKey,\n value,\n raw: `${atomKey}:${value}`,\n },\n ]);\n }\n }\n return next;\n}\n\nfunction parseContext(raw: string | null): MeTargetContextSet {\n const value = String(raw ?? '').trim();\n if (!value) return [];\n\n const groups = value\n .split(CONTEXT_BRANCH_SEPARATOR)\n .map((group) => group.trim())\n .filter(Boolean);\n\n const clauses: MeTargetContextSet = [];\n for (const group of groups) {\n const parts = group\n .split(CONTEXT_AND_SEPARATOR)\n .map((part) => part.trim())\n .filter(Boolean);\n\n let expanded: MeTargetContextClause[] = [[]];\n for (const part of parts) {\n const colon = part.indexOf(':');\n if (colon < 0) {\n throw new CleakerParseError('Context atoms must match key:value', { raw: part });\n }\n\n const key = part.slice(0, colon).trim().toLowerCase();\n const rest = part.slice(colon + 1).trim();\n if (!key || !rest) {\n throw new CleakerParseError('Context atoms must match key:value', { raw: part });\n }\n\n const values = rest\n .split(CONTEXT_VALUE_SEPARATOR)\n .map((item) => item.trim())\n .filter(Boolean);\n\n if (values.length === 0) {\n throw new CleakerParseError('Context atoms must include at least one value', { raw: part });\n }\n\n expanded = expandClauseWithAtom(expanded, key, values);\n }\n\n clauses.push(...expanded);\n }\n\n return clauses;\n}\n\nfunction extractNamespaceParts(namespaceToken: string): {\n base: string;\n contextRaw: string | null;\n context: MeTargetContextSet;\n} {\n const trimmed = String(namespaceToken || '').trim();\n if (!trimmed) {\n throw new CleakerParseError('Namespace cannot be empty', { raw: namespaceToken });\n }\n\n const openIndex = trimmed.indexOf(CONTEXT_OPEN);\n if (openIndex < 0) {\n return {\n base: trimmed,\n contextRaw: null,\n context: [],\n };\n }\n\n const closeIndex = trimmed.lastIndexOf(CONTEXT_CLOSE);\n if (closeIndex !== trimmed.length - 1 || closeIndex < openIndex) {\n throw new CleakerParseError('Namespace context must appear at the end of the namespace', {\n raw: namespaceToken,\n });\n }\n\n const base = trimmed.slice(0, openIndex).trim();\n const contextRaw = trimmed.slice(openIndex + 1, closeIndex).trim();\n if (!base) {\n throw new CleakerParseError('Namespace cannot be empty', { raw: namespaceToken });\n }\n\n return {\n base,\n contextRaw,\n context: parseContext(contextRaw),\n };\n}\n\nfunction deriveCompatibilityNamespace(base: string) {\n const segments = base\n .split('/')\n .map((segment) => segment.trim())\n .filter(Boolean);\n const head = segments[0] || base;\n const labels = head.split('.').filter(Boolean);\n\n if (labels.length === 0) {\n throw new CleakerParseError('Namespace is missing constant', { raw: base });\n }\n\n const constant = labels[labels.length - 1];\n const prefix = labels.length > 1 ? labels.slice(0, -1).join('.') : null;\n\n return {\n segments,\n constant,\n prefix,\n };\n}\n\nfunction stringifyContext(context: MeTargetContextSet): string | null {\n if (!Array.isArray(context) || context.length === 0) return null;\n return context\n .map((clause) => clause.map((atom) => `${atom.key}:${atom.value}`).join(CONTEXT_AND_SEPARATOR))\n .join(CONTEXT_BRANCH_SEPARATOR);\n}\n\nexport function stringifyMeTarget(target: Pick<ParsedTarget, 'namespace' | 'operation' | 'path'>): string {\n const namespace = String(target.namespace.fqdn || '').trim();\n if (!namespace) throw new CleakerParseError('Namespace cannot be empty');\n\n const operation = String(target.operation || '').trim();\n if (!operation) throw new CleakerParseError('Operation cannot be empty');\n\n const path = String(target.path || '').trim().replace(/^\\/+/, '');\n if (!path) throw new CleakerParseError('Path cannot be empty');\n\n const context = stringifyContext(target.namespace.context);\n const namespaceToken = context ? `${namespace}[${context}]` : namespace;\n\n return `${ME_SCHEME}${namespaceToken}:${operation}/${path}`;\n}\n\n/**\n * @deprecated Compatibility parser for the older `me://namespace:operation/path`\n * target grammar. New namespace/context work should use\n * `parseNamespaceExpression()` from `src/namespace/expression.ts`.\n */\nexport function parseMeTarget(input: string, options: ParseTargetOptions = {}): ParsedTarget {\n const raw = normalizeInput(input);\n ensureBalancedContext(raw);\n\n const body = stripScheme(raw).replace(/^\\/+/, '').trim();\n if (!body) throw new CleakerParseError('Target cannot be empty');\n\n const operationSeparator = findTokenOutsideContext(body, ':');\n const operationMissing = operationSeparator < 0;\n if (operationMissing && !options.allowShorthandRead) {\n throw new CleakerParseError('Target must match namespace[context]:operation/path', { raw });\n }\n\n const pathSeparator = operationMissing\n ? findTokenOutsideContext(body, '/')\n : findTokenOutsideContext(body, '/', operationSeparator + 1);\n\n if (pathSeparator < 0) {\n throw new CleakerParseError('Path cannot be empty', { raw });\n }\n\n const namespaceToken = body.slice(0, operationMissing ? pathSeparator : operationSeparator).trim();\n const operationToken = operationMissing\n ? 'read'\n : body.slice(operationSeparator + 1, pathSeparator).trim();\n const path = body.slice(pathSeparator + 1).trim().replace(/^\\/+/, '');\n\n if (!namespaceToken) throw new CleakerParseError('Namespace cannot be empty', { raw });\n if (!operationToken) throw new CleakerParseError('Operation cannot be empty', { raw });\n if (!path) throw new CleakerParseError('Path cannot be empty', { raw });\n\n const namespace = extractNamespaceParts(namespaceToken);\n const compatibility = deriveCompatibilityNamespace(namespace.base.toLowerCase());\n\n const parsed: ParsedTarget = {\n scheme: 'me',\n raw: '',\n namespace: {\n prefix: compatibility.prefix,\n constant: compatibility.constant,\n fqdn: namespace.base,\n segments: compatibility.segments,\n contextRaw: namespace.contextRaw,\n context: namespace.context,\n },\n intent: {\n selector: operationToken,\n path,\n mode: options.defaultMode ?? 'reactive',\n },\n operation: operationToken,\n path,\n };\n\n parsed.raw = stringifyMeTarget(parsed);\n return parsed;\n}\n","import type { ParseTargetOptions, ParsedTarget } from '../types/target';\nimport { parseMeTarget } from './parseMeTarget';\n\n/**\n * Compatibility wrapper for remote pointer targets.\n *\n * The contextual namespace grammar lives in `parseNamespaceExpression()`;\n * this parser remains for `cleaker(\"me://...\")` remote pointer support.\n */\nexport function parseTarget(input: string, options: ParseTargetOptions = {}): ParsedTarget {\n return parseMeTarget(input, options);\n}\n","export const DEFAULT_CLEAKER_NAMESPACE_SURFACE_ORIGIN = 'https://cleaker.me';\nexport const DEFAULT_CLEAKER_LOCAL_SURFACE_ORIGIN = 'http://localhost';\nexport const DEFAULT_CLEAKER_LAN_PORT = 8161;\n\n// Backward-compatible aliases. These now represent host-level default surfaces,\n// not port-pinned daemon channels.\nexport const DEFAULT_CLEAKER_NAMESPACE_ORIGIN = DEFAULT_CLEAKER_NAMESPACE_SURFACE_ORIGIN;\nexport const DEFAULT_CLEAKER_DEVELOPMENT_ORIGIN = DEFAULT_CLEAKER_LOCAL_SURFACE_ORIGIN;\n","import type { ParsedTarget } from '../types/target';\nimport { DEFAULT_CLEAKER_NAMESPACE_ORIGIN } from '../constants';\nimport type {\n RemotePointerDefinition,\n RemotePointerPayload,\n ResolvePointerOptions,\n ResolvePointerResult,\n} from '../types/pointer';\n\nexport interface CreateRemotePointerOptions {\n preferredTransport?: string[];\n cacheTtl?: number;\n resolveLocalTarget?: (target: ParsedTarget) => unknown | Promise<unknown>;\n}\n\nexport function createRemotePointer(\n target: ParsedTarget,\n options: CreateRemotePointerOptions = {},\n): RemotePointerDefinition {\n const payload: RemotePointerPayload = {\n kind: 'remote',\n target,\n identity: {\n constant: target.namespace.constant,\n prefix: target.namespace.prefix,\n },\n intent: {\n selector: target.intent.selector,\n path: target.intent.path,\n mode: target.intent.mode,\n },\n resolution: {\n status: 'unresolved',\n namespaceRecordVerified: false,\n sessionToken: null,\n lastError: null,\n },\n operationalState: {\n latencyMs: null,\n lastSync: null,\n cacheTtl: options.cacheTtl ?? 300,\n stale: false,\n },\n transport: {\n preferred: options.preferredTransport ?? ['quic', 'https'],\n protocol: null,\n resolvedEndpoint: null,\n },\n };\n\n async function resolve(resolveOptions: ResolvePointerOptions = {}): Promise<ResolvePointerResult> {\n const isSovereignTarget =\n target.namespace.prefix === null &&\n (target.namespace.constant === 'local' || target.namespace.constant === 'self');\n const origin = String(resolveOptions.origin || DEFAULT_CLEAKER_NAMESPACE_ORIGIN).replace(/\\/+$/, '');\n const dotPath = String(target.intent.path || '').trim().replace(/^\\/+/, '');\n const endpoint = `${origin}/${dotPath}`;\n const startedAt = Date.now();\n\n payload.resolution.status = 'resolving';\n payload.resolution.lastError = null;\n payload.transport.protocol = isSovereignTarget ? 'local' : origin.startsWith('https://') ? 'https' : 'http';\n payload.transport.resolvedEndpoint = isSovereignTarget ? target.raw : endpoint;\n\n if (isSovereignTarget && options.resolveLocalTarget) {\n try {\n const value = await options.resolveLocalTarget(target);\n const elapsedMs = Date.now() - startedAt;\n payload.operationalState.latencyMs = elapsedMs;\n payload.operationalState.lastSync = Date.now();\n payload.resolution.status = 'connected';\n payload.resolution.namespaceRecordVerified = true;\n payload.operationalState.stale = false;\n\n return {\n ok: true,\n status: 200,\n endpoint: target.raw,\n elapsedMs,\n data: {\n ok: true,\n namespace: target.namespace.constant,\n path: target.intent.path,\n value,\n },\n };\n } catch (error) {\n const elapsedMs = Date.now() - startedAt;\n payload.operationalState.latencyMs = elapsedMs;\n payload.operationalState.lastSync = Date.now();\n payload.resolution.status = 'error';\n payload.resolution.lastError = error instanceof Error ? error.message : String(error);\n payload.operationalState.stale = false;\n\n return {\n ok: false,\n status: 500,\n endpoint: target.raw,\n elapsedMs,\n data: {\n ok: false,\n error: payload.resolution.lastError,\n },\n };\n }\n }\n\n const fetcher = resolveOptions.fetcher || fetch;\n const host = String(resolveOptions.host || target.namespace.fqdn || '').trim();\n const headers: Record<string, string> = {\n ...(resolveOptions.headers || {}),\n };\n if (host && !headers.host && !headers.Host) {\n headers.host = host;\n }\n\n try {\n const response = await fetcher(endpoint, {\n method: 'GET',\n headers,\n });\n\n let data: unknown = null;\n try {\n data = await response.json();\n } catch {\n data = await response.text();\n }\n\n const elapsedMs = Date.now() - startedAt;\n payload.operationalState.latencyMs = elapsedMs;\n payload.operationalState.lastSync = Date.now();\n\n if (response.ok) {\n payload.resolution.status = 'connected';\n payload.resolution.namespaceRecordVerified = true;\n payload.operationalState.stale = false;\n } else {\n payload.resolution.status = response.status === 401 || response.status === 403\n ? 'unauthorized'\n : 'error';\n payload.resolution.lastError = `HTTP_${response.status}`;\n }\n\n return {\n ok: response.ok,\n status: response.status,\n endpoint,\n elapsedMs,\n data,\n };\n } catch (error) {\n const elapsedMs = Date.now() - startedAt;\n payload.operationalState.latencyMs = elapsedMs;\n payload.operationalState.lastSync = Date.now();\n payload.resolution.status = 'timeout';\n payload.resolution.lastError = error instanceof Error ? error.message : String(error);\n payload.operationalState.stale = true;\n\n return {\n ok: false,\n status: 0,\n endpoint,\n elapsedMs,\n data: {\n ok: false,\n error: payload.resolution.lastError,\n },\n };\n }\n }\n\n return { __ptr: payload, resolve };\n}\n","import { CleakerParseError } from '../protocol/errors';\nimport {\n CONTEXT_AND_SEPARATOR,\n CONTEXT_BRANCH_SEPARATOR,\n CONTEXT_CLOSE,\n CONTEXT_OPEN,\n CONTEXT_VALUE_SEPARATOR,\n ME_SCHEME,\n} from '../parse/grammar';\nimport type {\n NamespaceSelectorAtom,\n NamespaceSelectorClause,\n NamespaceSelectorSet,\n ParsedNamespaceExpression,\n} from '../types/namespace';\n\nfunction normalizeInput(input: string): string {\n const raw = String(input ?? '').trim();\n if (!raw) throw new CleakerParseError('Namespace cannot be empty');\n return raw;\n}\n\nfunction stripScheme(raw: string): string {\n if (raw.startsWith(ME_SCHEME)) return raw.slice(ME_SCHEME.length);\n return raw;\n}\n\nfunction ensureBalancedContext(input: string): void {\n let depth = 0;\n for (const char of input) {\n if (char === CONTEXT_OPEN) depth += 1;\n if (char === CONTEXT_CLOSE) depth -= 1;\n if (depth < 0) {\n throw new CleakerParseError('Namespace has an unexpected closing context bracket', { raw: input });\n }\n }\n if (depth !== 0) {\n throw new CleakerParseError('Namespace has an unclosed context bracket', { raw: input });\n }\n}\n\nfunction findTokenOutsideContext(input: string, token: string, start = 0): number {\n let depth = 0;\n for (let index = start; index < input.length; index += 1) {\n const char = input[index];\n if (char === CONTEXT_OPEN) {\n depth += 1;\n continue;\n }\n if (char === CONTEXT_CLOSE) {\n depth = Math.max(0, depth - 1);\n continue;\n }\n if (depth === 0 && char === token) return index;\n }\n return -1;\n}\n\nfunction expandClauseWithAtom(\n clauses: NamespaceSelectorClause[],\n atomKey: string,\n values: string[],\n): NamespaceSelectorClause[] {\n const next: NamespaceSelectorClause[] = [];\n for (const clause of clauses) {\n for (const value of values) {\n next.push([\n ...clause,\n {\n key: atomKey,\n value,\n raw: `${atomKey}:${value}`,\n },\n ]);\n }\n }\n return next;\n}\n\nfunction parseContext(raw: string | null): NamespaceSelectorSet {\n const value = String(raw ?? '').trim();\n if (!value) return [];\n\n const groups = value\n .split(CONTEXT_BRANCH_SEPARATOR)\n .map((group) => group.trim())\n .filter(Boolean);\n\n const clauses: NamespaceSelectorSet = [];\n for (const group of groups) {\n const parts = group\n .split(CONTEXT_AND_SEPARATOR)\n .map((part) => part.trim())\n .filter(Boolean);\n\n let expanded: NamespaceSelectorClause[] = [[]];\n for (const part of parts) {\n const colon = part.indexOf(':');\n if (colon < 0) {\n throw new CleakerParseError('Namespace selectors must match key:value', { raw: part });\n }\n\n const key = part.slice(0, colon).trim().toLowerCase();\n const rest = part.slice(colon + 1).trim();\n if (!key || !rest) {\n throw new CleakerParseError('Namespace selectors must match key:value', { raw: part });\n }\n\n const values = rest\n .split(CONTEXT_VALUE_SEPARATOR)\n .map((item) => item.trim())\n .filter(Boolean);\n\n if (values.length === 0) {\n throw new CleakerParseError('Namespace selectors must include at least one value', { raw: part });\n }\n\n expanded = expandClauseWithAtom(expanded, key, values);\n }\n\n clauses.push(...expanded);\n }\n\n return clauses;\n}\n\nfunction extractNamespaceParts(namespaceToken: string): {\n base: string;\n contextRaw: string | null;\n context: NamespaceSelectorSet;\n} {\n const trimmed = String(namespaceToken || '').trim();\n if (!trimmed) {\n throw new CleakerParseError('Namespace cannot be empty', { raw: namespaceToken });\n }\n\n const openIndex = trimmed.indexOf(CONTEXT_OPEN);\n if (openIndex < 0) {\n return {\n base: trimmed,\n contextRaw: null,\n context: [],\n };\n }\n\n const closeIndex = trimmed.lastIndexOf(CONTEXT_CLOSE);\n if (closeIndex !== trimmed.length - 1 || closeIndex < openIndex) {\n throw new CleakerParseError('Namespace context must appear at the end of the namespace', {\n raw: namespaceToken,\n });\n }\n\n const base = trimmed.slice(0, openIndex).trim();\n const contextRaw = trimmed.slice(openIndex + 1, closeIndex).trim();\n if (!base) {\n throw new CleakerParseError('Namespace cannot be empty', { raw: namespaceToken });\n }\n\n return {\n base,\n contextRaw,\n context: parseContext(contextRaw),\n };\n}\n\nfunction normalizeBaseToken(raw: string): { host: string; labels: string[]; port: number | null } {\n const candidate = String(raw || '').trim().replace(/^https?:\\/\\//i, '');\n if (!candidate) throw new CleakerParseError('Namespace base cannot be empty', { raw });\n\n const slash = candidate.indexOf('/');\n const hostToken = (slash >= 0 ? candidate.slice(0, slash) : candidate).trim().toLowerCase();\n const portMatch = hostToken.match(/:(\\d+)$/);\n const port = portMatch ? Number(portMatch[1]) : null;\n const host = portMatch ? hostToken.slice(0, -portMatch[0].length) : hostToken;\n const labels = host.split('.').map((label) => label.trim()).filter(Boolean);\n\n if (!host || labels.length === 0) {\n throw new CleakerParseError('Namespace base cannot be empty', { raw });\n }\n\n return { host, labels, port };\n}\n\nfunction deriveConstantAndPrefix(base: string): {\n fqdn: string;\n prefix: string | null;\n constant: string;\n labels: string[];\n port: number | null;\n} {\n const normalized = normalizeBaseToken(base);\n const portSuffix = normalized.port == null ? '' : `:${normalized.port}`;\n\n if (normalized.labels.length === 2 && normalized.labels[1] === 'localhost') {\n return {\n fqdn: `${normalized.host}${portSuffix}`,\n prefix: normalized.labels[0] || null,\n constant: `localhost${portSuffix}`,\n labels: normalized.labels,\n port: normalized.port,\n };\n }\n\n if (normalized.labels.length <= 2) {\n return {\n fqdn: `${normalized.host}${portSuffix}`,\n prefix: null,\n constant: `${normalized.host}${portSuffix}`,\n labels: normalized.labels,\n port: normalized.port,\n };\n }\n\n return {\n fqdn: `${normalized.host}${portSuffix}`,\n prefix: normalized.labels[0] || null,\n constant: `${normalized.labels.slice(1).join('.')}${portSuffix}`,\n labels: normalized.labels,\n port: normalized.port,\n };\n}\n\nfunction isLocalishHost(host: string): boolean {\n const normalized = String(host || '').trim().toLowerCase();\n return /^(localhost|127(?:\\.\\d{1,3}){3}|0\\.0\\.0\\.0)$/.test(normalized) || /\\.local$/.test(normalized);\n}\n\nfunction findSelectorValue(context: NamespaceSelectorSet, selectorType: string): string | null {\n const key = String(selectorType || '').trim().toLowerCase();\n if (!key) return null;\n\n for (const clause of context) {\n for (const atom of clause) {\n if (atom.key === key) return atom.value;\n }\n }\n\n return null;\n}\n\nfunction resolveTransport(base: string, context: NamespaceSelectorSet): ParsedNamespaceExpression['transport'] {\n const normalized = normalizeBaseToken(base);\n const overrideHost =\n findSelectorValue(context, 'host') ||\n findSelectorValue(context, 'hostname') ||\n findSelectorValue(context, 'device');\n const overrideProtocol = findSelectorValue(context, 'protocol');\n const overridePort = findSelectorValue(context, 'port');\n\n const hostToken = String(overrideHost || normalized.host).trim().toLowerCase();\n const hostHasPort = /:\\d+$/.test(hostToken);\n const hostBase = hostHasPort ? hostToken.replace(/:\\d+$/, '') : hostToken;\n const portFromHost = hostHasPort ? Number(hostToken.match(/:(\\d+)$/)?.[1] || 0) || null : null;\n const port =\n portFromHost ??\n (overridePort && /^\\d+$/.test(overridePort) ? Number(overridePort) : normalized.port);\n const protocol = (overrideProtocol || (isLocalishHost(hostBase) ? 'http' : 'https')).toLowerCase() === 'http'\n ? 'http'\n : 'https';\n const host = port == null ? hostBase : `${hostBase}:${port}`;\n const origin = `${protocol}://${host}`;\n\n return {\n protocol,\n host: hostBase,\n port,\n origin,\n };\n}\n\nfunction splitHeadAndPath(body: string): { head: string; path: string } {\n const slashIndex = findTokenOutsideContext(body, '/');\n if (slashIndex < 0) {\n return {\n head: body.trim(),\n path: '',\n };\n }\n\n return {\n head: body.slice(0, slashIndex).trim(),\n path: body.slice(slashIndex + 1).trim().replace(/^\\/+/, ''),\n };\n}\n\nfunction splitNamespaceAndOperation(head: string): { namespaceToken: string; operation: string | null } {\n const colonIndex = findTokenOutsideContext(head, ':');\n if (colonIndex < 0) {\n return {\n namespaceToken: head.trim(),\n operation: null,\n };\n }\n\n const suffix = head.slice(colonIndex + 1).trim();\n if (!suffix || /^\\d+$/.test(suffix)) {\n return {\n namespaceToken: head.trim(),\n operation: null,\n };\n }\n\n return {\n namespaceToken: head.slice(0, colonIndex).trim(),\n operation: suffix,\n };\n}\n\nexport function composeNamespace(prefix: string | null | undefined, constant: string): string {\n const normalizedConstant = String(constant || '').trim().toLowerCase();\n if (!normalizedConstant) throw new CleakerParseError('Namespace constant cannot be empty', { constant });\n\n const normalizedPrefix = String(prefix || '').trim().toLowerCase().replace(/\\.+$/, '');\n if (!normalizedPrefix) return normalizedConstant;\n return `${normalizedPrefix}.${normalizedConstant}`;\n}\n\nexport function stringifyNamespaceExpression(\n input: Pick<ParsedNamespaceExpression, 'fqdn' | 'contextRaw' | 'operation' | 'path'>,\n): string {\n const base = String(input.fqdn || '').trim().toLowerCase();\n if (!base) throw new CleakerParseError('Namespace base cannot be empty', { input });\n\n const contextRaw = String(input.contextRaw || '').trim();\n const operation = String(input.operation || '').trim();\n const path = String(input.path || '').trim().replace(/^\\/+/, '');\n const namespaceToken = contextRaw ? `${base}[${contextRaw}]` : base;\n const operationToken = operation ? `:${operation}` : '';\n const pathToken = path ? `/${path}` : '';\n return `${namespaceToken}${operationToken}${pathToken}`;\n}\n\nexport function parseNamespaceExpression(input: string): ParsedNamespaceExpression {\n const raw = normalizeInput(input);\n ensureBalancedContext(raw);\n\n const body = stripScheme(raw).replace(/^\\/+/, '').trim();\n if (!body) throw new CleakerParseError('Namespace cannot be empty', { raw });\n\n const parts = splitHeadAndPath(body);\n const head = splitNamespaceAndOperation(parts.head);\n const namespace = extractNamespaceParts(head.namespaceToken);\n const derived = deriveConstantAndPrefix(namespace.base);\n const transport = resolveTransport(namespace.base, namespace.context);\n\n const expression = stringifyNamespaceExpression({\n fqdn: derived.fqdn,\n contextRaw: namespace.contextRaw,\n operation: head.operation,\n path: parts.path,\n });\n\n return {\n raw,\n expression,\n base: namespace.base,\n fqdn: derived.fqdn,\n prefix: derived.prefix,\n constant: derived.constant,\n labels: derived.labels,\n contextRaw: namespace.contextRaw,\n context: namespace.context,\n operation: head.operation,\n path: parts.path,\n transport,\n };\n}\n","import { parseTarget } from './parse/parseTarget';\nimport { createRemotePointer } from './pointer/remotePointer';\nimport {\n DEFAULT_CLEAKER_DEVELOPMENT_ORIGIN,\n DEFAULT_CLEAKER_LAN_PORT,\n DEFAULT_CLEAKER_NAMESPACE_ORIGIN,\n} from './constants';\nimport { composeNamespace, parseNamespaceExpression } from './namespace/expression';\nimport type { CreateRemotePointerOptions } from './pointer/remotePointer';\nimport type {\n CleakerErrorPayload,\n CleakerEvents,\n CleakerHostRecord,\n CleakerNode,\n CleakerReadyPayload,\n CleakerState,\n CleakerStatus,\n KernelPendingResolution,\n MeKernel,\n OpenNodeInput,\n OpenNodeResult,\n ValidateHostsOptions,\n} from './types/kernel';\nimport type { RemotePointerDefinition, ResolvePointerResult } from './types/pointer';\nimport type { ResolvePointerOptions } from './types/pointer';\n\nconst ME_EXPRESSION_SYMBOL = Symbol.for('me.expression');\nconst ME_IDENTITY_SYMBOL = Symbol.for('me.identity');\n\ntype SignInResponse = {\n ok: boolean;\n error?: string;\n namespace?: string;\n identityHash?: string;\n noise?: string;\n memories?: unknown[];\n openedAt?: number;\n target?: {\n namespace?: string | { me?: string; host?: string };\n };\n};\n\ntype ClaimProof = {\n identityHash: string;\n expression: string;\n namespace: string;\n rootNamespace: string;\n publicKey: string;\n message: string;\n signature: string;\n timestamp: number;\n};\n\ntype ClaimResponse = {\n ok: boolean;\n error?: string;\n namespace?: string | { me?: string; host?: string };\n identityHash?: string;\n publicKey?: string;\n createdAt?: number;\n persistentClaim?: unknown;\n target?: {\n namespace?: string | { me?: string; host?: string };\n };\n};\n\nexport interface BindKernelOptions extends CreateRemotePointerOptions {\n namespace?: string;\n secret?: string;\n identityHash?: string;\n space?: string;\n bootstrap?: string[];\n fetcher?: typeof fetch;\n}\n\ntype RemoteSlot = {\n key: string;\n path: string[];\n expression: string;\n pointer: RemotePointerDefinition;\n promise: Promise<ResolvePointerResult>;\n lastResult?: ResolvePointerResult;\n};\n\ntype LearnedMemory = {\n path: string;\n operator: string | null;\n expression: unknown;\n value: unknown;\n};\n\nfunction normalizeReplayMemory(memory: unknown): unknown {\n if (!memory || typeof memory !== 'object') return memory;\n\n const record = memory as Record<string, unknown>;\n const payload = record.payload;\n const source = payload && typeof payload === 'object'\n ? payload as Record<string, unknown>\n : record;\n const merged: Record<string, unknown> = {\n ...source,\n };\n\n // Server write payloads use `expression` as the written dot-path.\n // `.me` replay expects semantic memories shaped as `{ path, operator, expression, value }`.\n if (!Object.prototype.hasOwnProperty.call(merged, 'path')) {\n const rawExpression = String(merged.expression || '').trim();\n if (rawExpression) {\n merged.path = rawExpression;\n }\n }\n\n if (!Object.prototype.hasOwnProperty.call(merged, 'operator')) {\n merged.operator = null;\n }\n\n if (Object.prototype.hasOwnProperty.call(merged, 'value')) {\n merged.expression = merged.value;\n }\n\n if (!Object.prototype.hasOwnProperty.call(merged, 'timestamp') && record.timestamp !== undefined) {\n merged.timestamp = record.timestamp;\n }\n\n if (!Object.prototype.hasOwnProperty.call(merged, 'identityHash') && record.identityHash !== undefined) {\n merged.identityHash = record.identityHash;\n }\n\n return merged;\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map((v) => stableStringify(v)).join(',')}]`;\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(',')}}`;\n}\n\nfunction stripPort(raw: string): string {\n return String(raw || '').trim().toLowerCase().replace(/:\\d+$/i, '');\n}\n\nfunction normalizeSurfaceOrigin(input: string): string {\n const raw = String(input || '').trim();\n if (!raw) return '';\n\n const candidate = raw.includes('://')\n ? raw\n : `${isLoopbackishHost(raw) ? 'http' : 'https'}://${raw}`;\n\n try {\n const parsed = new URL(candidate.endsWith('/') ? candidate : `${candidate}/`);\n const protocol = parsed.protocol.toLowerCase();\n const hostname = String(parsed.hostname || '').trim().toLowerCase();\n if (!protocol || !hostname) return '';\n return `${protocol}//${hostname}`;\n } catch {\n const host = stripPort(raw.replace(/^https?:\\/\\//i, '').split('/')[0] || '');\n if (!host) return '';\n return `${isLoopbackishHost(host) ? 'http' : 'https'}://${host}`;\n }\n}\n\nfunction isIpAddress(host: string): boolean {\n return /^\\d{1,3}(\\.\\d{1,3}){3}$/.test(host);\n}\n\nfunction isBareHostname(host: string): boolean {\n return !host.includes('.') && !isIpAddress(host);\n}\n\nfunction parseSpaceHostPort(raw: string): { host: string; port: number | null } {\n const colonIdx = raw.lastIndexOf(':');\n if (colonIdx > 0) {\n const portStr = raw.slice(colonIdx + 1);\n const portNum = parseInt(portStr, 10);\n if (String(portNum) === portStr && portNum > 0) {\n return { host: raw.slice(0, colonIdx), port: portNum };\n }\n }\n return { host: raw, port: null };\n}\n\n// Resolves a user-supplied space string to a normalized origin URL per spec:\n// - IP address (with optional port) → http://{ip}:{port|8161}\n// - Bare hostname (no dot) → http://{host}.local:{port|8161}\n// - Domain (has dot) → https://{domain}:{port?}\n// - Already has :// → normalize as-is\nfunction normalizeSpaceOrigin(space: string): string {\n const raw = String(space || '').trim();\n if (!raw) return '';\n\n if (raw.includes('://')) {\n return normalizeOrigin(raw);\n }\n\n const { host, port } = parseSpaceHostPort(raw);\n const lowerHost = host.toLowerCase();\n\n if (isIpAddress(lowerHost)) {\n return `http://${lowerHost}:${port ?? DEFAULT_CLEAKER_LAN_PORT}`;\n }\n\n if (isBareHostname(lowerHost)) {\n return `http://${lowerHost}.local:${port ?? DEFAULT_CLEAKER_LAN_PORT}`;\n }\n\n // Public domain (has dot)\n const portSuffix = port ? `:${port}` : '';\n return `https://${lowerHost}${portSuffix}`;\n}\n\n// Returns the namespace constant (no port) for a user-supplied space string.\nfunction deriveSpaceNamespaceConstant(space: string): string {\n const raw = String(space || '').trim();\n if (!raw) return '';\n\n if (raw.includes('://')) {\n try {\n return new URL(raw).hostname.toLowerCase();\n } catch {\n return '';\n }\n }\n\n const { host } = parseSpaceHostPort(raw);\n const lowerHost = host.toLowerCase();\n\n if (isIpAddress(lowerHost)) return lowerHost;\n if (isBareHostname(lowerHost)) return `${lowerHost}.local`;\n return lowerHost;\n}\n\nfunction hashMemory(memory: unknown): string {\n const m = (memory ?? {}) as Record<string, unknown>;\n const explicit = String(m.hash || '').trim();\n if (explicit) return `h:${explicit}`;\n const ts = Number(m.timestamp || 0);\n return `v:${ts}:${stableStringify(memory)}`;\n}\n\nfunction normalizeOrigin(origin: string): string {\n const raw = String(origin || '').trim();\n if (!raw) return '';\n const withScheme = raw.includes('://') ? raw : `http://${raw}`;\n try {\n const url = new URL(withScheme.endsWith('/') ? withScheme : `${withScheme}/`);\n return url.origin.toLowerCase();\n } catch {\n return raw.replace(/\\/+$/, '').toLowerCase();\n }\n}\n\nfunction normalizeExpression(value: unknown): string | null {\n const normalized = typeof value === 'string' ? value.trim() : '';\n return normalized || null;\n}\n\nfunction normalizeIdentityHash(value: unknown): string | null {\n const normalized = typeof value === 'string' ? value.trim() : '';\n return normalized || null;\n}\n\nfunction normalizeNamespaceValue(value: unknown, fallback = ''): string {\n if (typeof value === 'string') {\n const normalized = value.trim();\n if (normalized) return normalized;\n }\n\n if (value && typeof value === 'object') {\n const record = value as Record<string, unknown>;\n const me = typeof record.me === 'string' ? record.me.trim() : '';\n if (me) return me;\n const host = typeof record.host === 'string' ? record.host.trim() : '';\n if (host) return host;\n }\n\n return fallback;\n}\n\nfunction resolveEnvelopeNamespace(data: unknown, fallback = ''): string {\n if (!data || typeof data !== 'object') return fallback;\n const record = data as Record<string, unknown>;\n const direct = normalizeNamespaceValue(record.namespace, '');\n if (direct) return direct;\n const target = record.target;\n if (target && typeof target === 'object') {\n return normalizeNamespaceValue((target as Record<string, unknown>).namespace, fallback);\n }\n return fallback;\n}\n\nfunction readKernelExpression(me: MeKernel): string | null {\n try {\n const viaSymbol = normalizeExpression((me as any)[ME_EXPRESSION_SYMBOL]);\n if (viaSymbol) return viaSymbol;\n } catch {\n // Ignore and fall through to the reflective plane.\n }\n\n try {\n const runtime = (me as any)['!'];\n const currentExpression = runtime?.currentExpression;\n if (typeof currentExpression === 'function') {\n const value = normalizeExpression(currentExpression());\n if (value) return value;\n }\n if (\n currentExpression &&\n typeof currentExpression === 'object' &&\n typeof (currentExpression as { call?: () => unknown }).call === 'function'\n ) {\n const value = normalizeExpression((currentExpression as { call: () => unknown }).call());\n if (value) return value;\n }\n } catch {\n // Kernels may omit the escape plane entirely.\n }\n\n return null;\n}\n\nfunction readKernelIdentityHash(me: MeKernel): string | null {\n try {\n const viaSymbol = (me as any)[ME_IDENTITY_SYMBOL];\n if (viaSymbol && typeof viaSymbol === 'object') {\n const value = normalizeIdentityHash((viaSymbol as { hash?: unknown }).hash);\n if (value) return value;\n }\n const direct = normalizeIdentityHash(viaSymbol);\n if (direct) return direct;\n } catch {\n // Ignore and fall through to the reflective plane.\n }\n\n try {\n const runtime = (me as any)['!'];\n const identity = runtime?.identity;\n if (typeof identity === 'function') {\n const value = identity();\n if (value && typeof value === 'object') {\n const hash = normalizeIdentityHash((value as { hash?: unknown }).hash);\n if (hash) return hash;\n }\n const direct = normalizeIdentityHash(value);\n if (direct) return direct;\n }\n if (\n identity &&\n typeof identity === 'object' &&\n typeof (identity as { call?: () => unknown }).call === 'function'\n ) {\n const value = (identity as { call: () => unknown }).call();\n if (value && typeof value === 'object') {\n const hash = normalizeIdentityHash((value as { hash?: unknown }).hash);\n if (hash) return hash;\n }\n const direct = normalizeIdentityHash(value);\n if (direct) return direct;\n }\n } catch {\n // Kernels may omit the escape plane entirely.\n }\n\n return null;\n}\n\nfunction readKernelRuntimeMethod<T extends (...args: any[]) => unknown>(\n me: MeKernel,\n methodName: string,\n): T | null {\n try {\n const runtime = (me as any)['!'];\n const method = runtime?.[methodName];\n if (typeof method === 'function') return method as T;\n if (method && typeof method === 'object' && typeof method.call === 'function') {\n return ((...args: unknown[]) => method.call(...args)) as T;\n }\n } catch {\n // Ignore and fall back.\n }\n\n try {\n const direct = (me as any)[methodName];\n if (typeof direct === 'function') return direct.bind(me) as T;\n } catch {\n // Ignore and report unsupported below.\n }\n\n return null;\n}\n\nfunction resolveProofRootNamespace(namespace: string): string {\n const raw = String(namespace || '').trim();\n if (!raw) return '';\n try {\n return parseNamespaceExpression(raw).constant;\n } catch {\n const parts = raw.split('.').map((part) => part.trim()).filter(Boolean);\n if (parts.length > 1) return parts.slice(1).join('.');\n return raw;\n }\n}\n\nasync function proveKernelNamespace(me: MeKernel, namespace: string): Promise<ClaimProof> {\n const prove = readKernelRuntimeMethod<(input: { rootNamespace: string; challenge?: string | null }) => Promise<unknown>>(\n me,\n 'prove',\n );\n if (!prove) {\n throw new Error('PROVE_UNSUPPORTED');\n }\n\n const rootNamespace = resolveProofRootNamespace(namespace);\n if (!rootNamespace) {\n throw new Error('ROOT_NAMESPACE_REQUIRED');\n }\n\n const proof = await prove({ rootNamespace, challenge: null });\n if (!proof || typeof proof !== 'object') {\n throw new Error('PROOF_INVALID');\n }\n\n const claimedNamespace = String((proof as Record<string, unknown>).namespace || '').trim();\n if (!claimedNamespace) {\n throw new Error('PROOF_INVALID');\n }\n if (claimedNamespace !== namespace) {\n throw new Error('PROOF_NAMESPACE_MISMATCH');\n }\n\n return proof as ClaimProof;\n}\n\nfunction isLoopbackishHost(raw: string): boolean {\n const host = stripPort(raw);\n return /^(localhost|127(?:\\.\\d{1,3}){3}|0\\.0\\.0\\.0)$/.test(host);\n}\n\n/** Returns true when an origin resolves to a local/LAN surface (loopback, .local, private IP). */\nfunction isLocalSurface(origin: string): boolean {\n try {\n const hostname = new URL(origin).hostname.toLowerCase();\n return (\n isLoopbackishHost(hostname) ||\n hostname.endsWith('.local') ||\n /^192\\.168\\./.test(hostname) ||\n /^10\\./.test(hostname) ||\n /^172\\.(1[6-9]|2\\d|3[01])\\./.test(hostname)\n );\n } catch {\n return false;\n }\n}\n\nfunction readLocationHost(): string {\n if (typeof globalThis === 'undefined') return '';\n\n const locationLike = (globalThis as { location?: unknown }).location;\n if (!locationLike) return '';\n\n if (typeof locationLike === 'string') {\n try {\n const parsedHost = new URL(locationLike.includes('://') ? locationLike : `https://${locationLike}`).hostname.toLowerCase();\n return isLoopbackishHost(parsedHost) ? '' : parsedHost;\n } catch {\n const fallbackHost = stripPort(String(locationLike).trim().toLowerCase());\n return isLoopbackishHost(fallbackHost) ? '' : fallbackHost;\n }\n }\n\n const record = locationLike as Record<string, unknown>;\n const host = stripPort(String(record.hostname || record.host || '').trim().toLowerCase());\n if (isLoopbackishHost(host)) return '';\n if (host) return host;\n\n const origin = String(record.origin || record.href || '').trim();\n if (!origin) return '';\n\n try {\n const parsedHost = new URL(origin.includes('://') ? origin : `https://${origin}`).hostname.toLowerCase();\n return isLoopbackishHost(parsedHost) ? '' : parsedHost;\n } catch {\n return '';\n }\n}\n\nfunction readLocationSurfaceOrigin(): string {\n if (typeof globalThis === 'undefined') return '';\n\n const locationLike = (globalThis as { location?: unknown }).location;\n if (!locationLike) return '';\n\n if (typeof locationLike === 'string') {\n return normalizeSurfaceOrigin(locationLike);\n }\n\n const record = locationLike as Record<string, unknown>;\n const origin = normalizeSurfaceOrigin(String(record.origin || ''));\n if (origin) return origin;\n\n const href = String(record.href || '').trim();\n if (href) return normalizeSurfaceOrigin(href);\n\n const host = String(record.hostname || record.host || '').trim().toLowerCase();\n if (!host) return '';\n return normalizeSurfaceOrigin(host);\n}\n\nfunction readConfiguredSurfaceOrigin(input: string): string {\n const constant = deriveNamespaceConstant(input);\n if (!constant) return '';\n return normalizeSurfaceOrigin(constant);\n}\n\ntype BuiltinOsLike = {\n hostname?: () => string;\n};\n\nfunction readRuntimeHostSurfaceOrigin(): string {\n if (typeof process === 'undefined') return '';\n\n const envCandidate = String(\n process.env.CLEAKER_SURFACE_HOST\n || process.env.MONAD_SELF_IDENTITY\n || process.env.CLEAKER_NAMESPACE_ROOT\n || process.env.CLEAKER_NAMESPACE_HOST\n || process.env.HOSTNAME\n || process.env.COMPUTERNAME\n || '',\n ).trim();\n const envSurface = readConfiguredSurfaceOrigin(envCandidate);\n if (envSurface) return envSurface;\n\n const runtime = process as typeof process & {\n getBuiltinModule?: (name: string) => unknown;\n };\n if (typeof runtime.getBuiltinModule !== 'function') return '';\n\n try {\n const os = runtime.getBuiltinModule('node:os') as BuiltinOsLike | undefined;\n const hostname = String(os?.hostname?.() || '').trim();\n if (!hostname) return '';\n return normalizeSurfaceOrigin(hostname);\n } catch {\n return '';\n }\n}\n\nfunction deriveNamespaceConstant(input: string): string {\n const raw = String(input || '').trim();\n if (!raw) return '';\n\n if (/^https?:\\/\\//i.test(raw)) {\n try {\n return parseNamespaceExpression(new URL(raw).hostname).constant;\n } catch {\n return '';\n }\n }\n\n try {\n return parseNamespaceExpression(raw).constant;\n } catch {\n try {\n const url = new URL(raw.includes('://') ? raw : `https://${raw}`);\n return parseNamespaceExpression(url.hostname).constant;\n } catch {\n return '';\n }\n }\n}\n\nfunction uniqueOrigins(origins: Array<string | null | undefined>): string[] {\n const seen = new Set<string>();\n const output: string[] = [];\n\n for (const origin of origins) {\n const normalized = normalizeOrigin(String(origin || ''));\n if (!normalized || seen.has(normalized)) continue;\n seen.add(normalized);\n output.push(normalized);\n }\n\n return output;\n}\n\nfunction hashFn(input: string): string {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i += 1) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return ('00000000' + (h >>> 0).toString(16)).slice(-8);\n}\n\nfunction computeHostId(origin: string): string {\n return hashFn(normalizeOrigin(origin));\n}\n\nfunction readKernelPath(me: MeKernel, segments: string[]): unknown {\n if (!segments.length) return undefined;\n try {\n let ref: any = me;\n for (let i = 0; i < segments.length; i += 1) {\n ref = ref?.[segments[i]];\n if (ref == null) return undefined;\n }\n if (typeof ref === 'function') {\n try {\n return ref();\n } catch {\n return undefined;\n }\n }\n return ref;\n } catch {\n return undefined;\n }\n}\n\nfunction writeKernelPath(me: MeKernel, segments: string[], value: unknown): boolean {\n if (!segments.length) return false;\n try {\n let ref: any = me;\n for (let i = 0; i < segments.length; i += 1) {\n ref = ref?.[segments[i]];\n if (ref == null) return false;\n }\n if (typeof ref === 'function') {\n ref(value);\n return true;\n }\n } catch {\n return false;\n }\n return false;\n}\n\nfunction toHostRecord(input: Partial<CleakerHostRecord>, namespace: string): CleakerHostRecord | null {\n const origin = normalizeOrigin(String(input.space || ''));\n if (!origin) return null;\n const id = String(input.id || '').trim() || computeHostId(origin);\n const baseStatus = input.status || {\n transport: 'unknown',\n triad: 'unverified',\n latencyMs: 0,\n lastSeen: 0,\n };\n const baseCapabilities = input.capabilities || {\n canClaim: false,\n canOpen: true,\n canRelay: false,\n };\n return {\n id,\n alias: input.alias ? String(input.alias) : undefined,\n space: origin,\n namespace,\n status: {\n transport: baseStatus.transport || 'unknown',\n triad: baseStatus.triad || 'unverified',\n latencyMs: Number(baseStatus.latencyMs || 0),\n lastSeen: Number(baseStatus.lastSeen || 0),\n },\n capabilities: {\n canClaim: !!baseCapabilities.canClaim,\n canOpen: baseCapabilities.canOpen !== false,\n canRelay: !!baseCapabilities.canRelay,\n },\n error: input.error ? String(input.error) : undefined,\n };\n}\n\nfunction defaultDetectRemote(path: string[]): boolean {\n const joined = path.join('.').trim();\n if (joined.includes('.cleaker:') || joined.includes(':')) return true;\n\n return path.some((segment, index) => {\n const normalized = segment.toLowerCase();\n return (\n normalized.includes('cleaker:') ||\n normalized.includes(':') ||\n (normalized === 'cleaker' && index < path.length - 1)\n );\n });\n}\n\nfunction defaultMapToExpression(inputPath: string[]): string | null {\n const path = inputPath.map((x) => String(x || '').trim()).filter(Boolean);\n if (path.length === 0) return null;\n\n const joined = path.join('.');\n if (joined.includes(':')) return joined;\n\n const cleakerIx = path.findIndex((segment) => segment.toLowerCase() === 'cleaker');\n if (cleakerIx > 0 && cleakerIx < path.length - 1) {\n const prefix = path[cleakerIx - 1];\n const rest = path.slice(cleakerIx + 1).join('.');\n return `${prefix}.cleaker:read/${rest || 'profile'}`;\n }\n\n return null;\n}\n\nfunction unwrapResolvedValue(data: unknown): unknown {\n if (!data || typeof data !== 'object') return data;\n const record = data as Record<string, unknown>;\n if (Object.prototype.hasOwnProperty.call(record, 'value')) return record.value;\n return data;\n}\n\nfunction tryReadLocal(me: MeKernel, path: string[]): unknown {\n if (path.length === 0 || typeof me !== 'function') return undefined;\n try {\n return (me as any)(path.join('.'));\n } catch {\n return undefined;\n }\n}\n\nfunction tryInvokeKernelPath(me: MeKernel, path: string[], args: unknown[]): unknown {\n if (typeof me !== 'function') return undefined;\n\n try {\n if (path.length === 0) {\n return (me as any)(...args);\n }\n\n let ref: any = me;\n for (const part of path) {\n ref = ref?.[part];\n }\n if (typeof ref === 'function') {\n