UNPKG

cleaker

Version:
1,578 lines (1,577 loc) 46.4 kB
class ae extends Error { constructor(t, n, r) { super(n), this.name = "CleakerError", this.code = t, this.details = r; } } class g extends ae { constructor(t, n) { super("PARSE_TARGET_FAILED", t, n), this.name = "CleakerParseError"; } } const Q = "me://", B = "[", K = "]", gt = "|", wt = ";", Wt = ","; function ce(e) { const t = String(e ?? "").trim(); if (!t) throw new g("Target cannot be empty"); return t; } function le(e) { return e.startsWith(Q) ? e.slice(Q.length) : e; } function pt(e, t, n = 0) { let r = 0; for (let o = n; o < e.length; o += 1) { const c = e[o]; if (c === B) { r += 1; continue; } if (c === K) { r = Math.max(0, r - 1); continue; } if (r === 0 && c === t) return o; } return -1; } function ue(e) { let t = 0; for (const n of e) if (n === B && (t += 1), n === K && (t -= 1), t < 0) throw new g("Target has an unexpected closing context bracket", { raw: e }); if (t !== 0) throw new g("Target has an unclosed context bracket", { raw: e }); } function fe(e, t, n) { const r = []; for (const o of e) for (const c of n) r.push([ ...o, { key: t, value: c, raw: `${t}:${c}` } ]); return r; } function pe(e) { const t = String(e ?? "").trim(); if (!t) return []; const n = t.split(gt).map((o) => o.trim()).filter(Boolean), r = []; for (const o of n) { const c = o.split(wt).map((y) => y.trim()).filter(Boolean); let h = [[]]; for (const y of c) { const S = y.indexOf(":"); if (S < 0) throw new g("Context atoms must match key:value", { raw: y }); const A = y.slice(0, S).trim().toLowerCase(), b = y.slice(S + 1).trim(); if (!A || !b) throw new g("Context atoms must match key:value", { raw: y }); const R = b.split(Wt).map((C) => C.trim()).filter(Boolean); if (R.length === 0) throw new g("Context atoms must include at least one value", { raw: y }); h = fe(h, A, R); } r.push(...h); } return r; } function de(e) { const t = String(e || "").trim(); if (!t) throw new g("Namespace cannot be empty", { raw: e }); const n = t.indexOf(B); if (n < 0) return { base: t, contextRaw: null, context: [] }; const r = t.lastIndexOf(K); if (r !== t.length - 1 || r < n) throw new g("Namespace context must appear at the end of the namespace", { raw: e }); const o = t.slice(0, n).trim(), c = t.slice(n + 1, r).trim(); if (!o) throw new g("Namespace cannot be empty", { raw: e }); return { base: o, contextRaw: c, context: pe(c) }; } function me(e) { const t = e.split("/").map((h) => h.trim()).filter(Boolean), r = (t[0] || e).split(".").filter(Boolean); if (r.length === 0) throw new g("Namespace is missing constant", { raw: e }); const o = r[r.length - 1], c = r.length > 1 ? r.slice(0, -1).join(".") : null; return { segments: t, constant: o, prefix: c }; } function he(e) { return !Array.isArray(e) || e.length === 0 ? null : e.map((t) => t.map((n) => `${n.key}:${n.value}`).join(wt)).join(gt); } function ye(e) { const t = String(e.namespace.fqdn || "").trim(); if (!t) throw new g("Namespace cannot be empty"); const n = String(e.operation || "").trim(); if (!n) throw new g("Operation cannot be empty"); const r = String(e.path || "").trim().replace(/^\/+/, ""); if (!r) throw new g("Path cannot be empty"); const o = he(e.namespace.context), c = o ? `${t}[${o}]` : t; return `${Q}${c}:${n}/${r}`; } function ge(e, t = {}) { const n = ce(e); ue(n); const r = le(n).replace(/^\/+/, "").trim(); if (!r) throw new g("Target cannot be empty"); const o = pt(r, ":"), c = o < 0; if (c && !t.allowShorthandRead) throw new g("Target must match namespace[context]:operation/path", { raw: n }); const h = c ? pt(r, "/") : pt(r, "/", o + 1); if (h < 0) throw new g("Path cannot be empty", { raw: n }); const y = r.slice(0, c ? h : o).trim(), S = c ? "read" : r.slice(o + 1, h).trim(), A = r.slice(h + 1).trim().replace(/^\/+/, ""); if (!y) throw new g("Namespace cannot be empty", { raw: n }); if (!S) throw new g("Operation cannot be empty", { raw: n }); if (!A) throw new g("Path cannot be empty", { raw: n }); const b = de(y), R = me(b.base.toLowerCase()), C = { scheme: "me", raw: "", namespace: { prefix: R.prefix, constant: R.constant, fqdn: b.base, segments: R.segments, contextRaw: b.contextRaw, context: b.context }, intent: { selector: S, path: A, mode: t.defaultMode ?? "reactive" }, operation: S, path: A }; return C.raw = ye(C), C; } function mt(e, t = {}) { return ge(e, t); } const we = "https://cleaker.me", Se = "http://localhost", Ut = 8161, ht = we, Ee = Se; function Vt(e, t = {}) { const n = { kind: "remote", target: e, identity: { constant: e.namespace.constant, prefix: e.namespace.prefix }, intent: { selector: e.intent.selector, path: e.intent.path, mode: e.intent.mode }, resolution: { status: "unresolved", namespaceRecordVerified: !1, sessionToken: null, lastError: null }, operationalState: { latencyMs: null, lastSync: null, cacheTtl: t.cacheTtl ?? 300, stale: !1 }, transport: { preferred: t.preferredTransport ?? ["quic", "https"], protocol: null, resolvedEndpoint: null } }; async function r(o = {}) { const c = e.namespace.prefix === null && (e.namespace.constant === "local" || e.namespace.constant === "self"), h = String(o.origin || ht).replace(/\/+$/, ""), y = String(e.intent.path || "").trim().replace(/^\/+/, ""), S = `${h}/${y}`, A = Date.now(); if (n.resolution.status = "resolving", n.resolution.lastError = null, n.transport.protocol = c ? "local" : h.startsWith("https://") ? "https" : "http", n.transport.resolvedEndpoint = c ? e.raw : S, c && t.resolveLocalTarget) try { const E = await t.resolveLocalTarget(e), v = Date.now() - A; return n.operationalState.latencyMs = v, n.operationalState.lastSync = Date.now(), n.resolution.status = "connected", n.resolution.namespaceRecordVerified = !0, n.operationalState.stale = !1, { ok: !0, status: 200, endpoint: e.raw, elapsedMs: v, data: { ok: !0, namespace: e.namespace.constant, path: e.intent.path, value: E } }; } catch (E) { const v = Date.now() - A; return n.operationalState.latencyMs = v, n.operationalState.lastSync = Date.now(), n.resolution.status = "error", n.resolution.lastError = E instanceof Error ? E.message : String(E), n.operationalState.stale = !1, { ok: !1, status: 500, endpoint: e.raw, elapsedMs: v, data: { ok: !1, error: n.resolution.lastError } }; } const b = o.fetcher || fetch, R = String(o.host || e.namespace.fqdn || "").trim(), C = { ...o.headers || {} }; R && !C.host && !C.Host && (C.host = R); try { const E = await b(S, { method: "GET", headers: C }); let v = null; try { v = await E.json(); } catch { v = await E.text(); } const T = Date.now() - A; return n.operationalState.latencyMs = T, n.operationalState.lastSync = Date.now(), E.ok ? (n.resolution.status = "connected", n.resolution.namespaceRecordVerified = !0, n.operationalState.stale = !1) : (n.resolution.status = E.status === 401 || E.status === 403 ? "unauthorized" : "error", n.resolution.lastError = `HTTP_${E.status}`), { ok: E.ok, status: E.status, endpoint: S, elapsedMs: T, data: v }; } catch (E) { const v = Date.now() - A; return n.operationalState.latencyMs = v, n.operationalState.lastSync = Date.now(), n.resolution.status = "timeout", n.resolution.lastError = E instanceof Error ? E.message : String(E), n.operationalState.stale = !0, { ok: !1, status: 0, endpoint: S, elapsedMs: v, data: { ok: !1, error: n.resolution.lastError } }; } } return { __ptr: n, resolve: r }; } function be(e) { const t = String(e ?? "").trim(); if (!t) throw new g("Namespace cannot be empty"); return t; } function Re(e) { return e.startsWith(Q) ? e.slice(Q.length) : e; } function Ae(e) { let t = 0; for (const n of e) if (n === B && (t += 1), n === K && (t -= 1), t < 0) throw new g("Namespace has an unexpected closing context bracket", { raw: e }); if (t !== 0) throw new g("Namespace has an unclosed context bracket", { raw: e }); } function qt(e, t, n = 0) { let r = 0; for (let o = n; o < e.length; o += 1) { const c = e[o]; if (c === B) { r += 1; continue; } if (c === K) { r = Math.max(0, r - 1); continue; } if (r === 0 && c === t) return o; } return -1; } function Ce(e, t, n) { const r = []; for (const o of e) for (const c of n) r.push([ ...o, { key: t, value: c, raw: `${t}:${c}` } ]); return r; } function ve(e) { const t = String(e ?? "").trim(); if (!t) return []; const n = t.split(gt).map((o) => o.trim()).filter(Boolean), r = []; for (const o of n) { const c = o.split(wt).map((y) => y.trim()).filter(Boolean); let h = [[]]; for (const y of c) { const S = y.indexOf(":"); if (S < 0) throw new g("Namespace selectors must match key:value", { raw: y }); const A = y.slice(0, S).trim().toLowerCase(), b = y.slice(S + 1).trim(); if (!A || !b) throw new g("Namespace selectors must match key:value", { raw: y }); const R = b.split(Wt).map((C) => C.trim()).filter(Boolean); if (R.length === 0) throw new g("Namespace selectors must include at least one value", { raw: y }); h = Ce(h, A, R); } r.push(...h); } return r; } function Oe(e) { const t = String(e || "").trim(); if (!t) throw new g("Namespace cannot be empty", { raw: e }); const n = t.indexOf(B); if (n < 0) return { base: t, contextRaw: null, context: [] }; const r = t.lastIndexOf(K); if (r !== t.length - 1 || r < n) throw new g("Namespace context must appear at the end of the namespace", { raw: e }); const o = t.slice(0, n).trim(), c = t.slice(n + 1, r).trim(); if (!o) throw new g("Namespace cannot be empty", { raw: e }); return { base: o, contextRaw: c, context: ve(c) }; } function Gt(e) { const t = String(e || "").trim().replace(/^https?:\/\//i, ""); if (!t) throw new g("Namespace base cannot be empty", { raw: e }); const n = t.indexOf("/"), r = (n >= 0 ? t.slice(0, n) : t).trim().toLowerCase(), o = r.match(/:(\d+)$/), c = o ? Number(o[1]) : null, h = o ? r.slice(0, -o[0].length) : r, y = h.split(".").map((S) => S.trim()).filter(Boolean); if (!h || y.length === 0) throw new g("Namespace base cannot be empty", { raw: e }); return { host: h, labels: y, port: c }; } function xe(e) { const t = Gt(e), n = t.port == null ? "" : `:${t.port}`; return t.labels.length === 2 && t.labels[1] === "localhost" ? { fqdn: `${t.host}${n}`, prefix: t.labels[0] || null, constant: `localhost${n}`, labels: t.labels, port: t.port } : t.labels.length <= 2 ? { fqdn: `${t.host}${n}`, prefix: null, constant: `${t.host}${n}`, labels: t.labels, port: t.port } : { fqdn: `${t.host}${n}`, prefix: t.labels[0] || null, constant: `${t.labels.slice(1).join(".")}${n}`, labels: t.labels, port: t.port }; } function Ne(e) { const t = String(e || "").trim().toLowerCase(); return /^(localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0)$/.test(t) || /\.local$/.test(t); } function q(e, t) { const n = String(t || "").trim().toLowerCase(); if (!n) return null; for (const r of e) for (const o of r) if (o.key === n) return o.value; return null; } function Te(e, t) { const n = Gt(e), r = q(t, "host") || q(t, "hostname") || q(t, "device"), o = q(t, "protocol"), c = q(t, "port"), h = String(r || n.host).trim().toLowerCase(), y = /:\d+$/.test(h), S = y ? h.replace(/:\d+$/, "") : h, b = (y && Number(h.match(/:(\d+)$/)?.[1] || 0) || null) ?? (c && /^\d+$/.test(c) ? Number(c) : n.port), R = (o || (Ne(S) ? "http" : "https")).toLowerCase() === "http" ? "http" : "https", C = b == null ? S : `${S}:${b}`, E = `${R}://${C}`; return { protocol: R, host: S, port: b, origin: E }; } function $e(e) { const t = qt(e, "/"); return t < 0 ? { head: e.trim(), path: "" } : { head: e.slice(0, t).trim(), path: e.slice(t + 1).trim().replace(/^\/+/, "") }; } function _e(e) { const t = qt(e, ":"); if (t < 0) return { namespaceToken: e.trim(), operation: null }; const n = e.slice(t + 1).trim(); return !n || /^\d+$/.test(n) ? { namespaceToken: e.trim(), operation: null } : { namespaceToken: e.slice(0, t).trim(), operation: n }; } function Ft(e, t) { const n = String(t || "").trim().toLowerCase(); if (!n) throw new g("Namespace constant cannot be empty", { constant: t }); const r = String(e || "").trim().toLowerCase().replace(/\.+$/, ""); return r ? `${r}.${n}` : n; } function Le(e) { const t = String(e.fqdn || "").trim().toLowerCase(); if (!t) throw new g("Namespace base cannot be empty", { input: e }); const n = String(e.contextRaw || "").trim(), r = String(e.operation || "").trim(), o = String(e.path || "").trim().replace(/^\/+/, ""), c = n ? `${t}[${n}]` : t, h = r ? `:${r}` : "", y = o ? `/${o}` : ""; return `${c}${h}${y}`; } function G(e) { const t = be(e); Ae(t); const n = Re(t).replace(/^\/+/, "").trim(); if (!n) throw new g("Namespace cannot be empty", { raw: t }); const r = $e(n), o = _e(r.head), c = Oe(o.namespaceToken), h = xe(c.base), y = Te(c.base, c.context), S = Le({ fqdn: h.fqdn, contextRaw: c.contextRaw, operation: o.operation, path: r.path }); return { raw: t, expression: S, base: c.base, fqdn: h.fqdn, prefix: h.prefix, constant: h.constant, labels: h.labels, contextRaw: c.contextRaw, context: c.context, operation: o.operation, path: r.path, transport: y }; } const ke = /* @__PURE__ */ Symbol.for("me.expression"), Ie = /* @__PURE__ */ Symbol.for("me.identity"); function Me(e) { if (!e || typeof e != "object") return e; const t = e, n = t.payload, o = { ...n && typeof n == "object" ? n : t }; if (!Object.prototype.hasOwnProperty.call(o, "path")) { const c = String(o.expression || "").trim(); c && (o.path = c); } return Object.prototype.hasOwnProperty.call(o, "operator") || (o.operator = null), Object.prototype.hasOwnProperty.call(o, "value") && (o.expression = o.value), !Object.prototype.hasOwnProperty.call(o, "timestamp") && t.timestamp !== void 0 && (o.timestamp = t.timestamp), !Object.prototype.hasOwnProperty.call(o, "identityHash") && t.identityHash !== void 0 && (o.identityHash = t.identityHash), o; } function yt(e) { if (e === null || typeof e != "object") return JSON.stringify(e); if (Array.isArray(e)) return `[${e.map((r) => yt(r)).join(",")}]`; const t = e; return `{${Object.keys(t).sort().map((r) => `${JSON.stringify(r)}:${yt(t[r])}`).join(",")}}`; } function st(e) { return String(e || "").trim().toLowerCase().replace(/:\d+$/i, ""); } function z(e) { const t = String(e || "").trim(); if (!t) return ""; const n = t.includes("://") ? t : `${U(t) ? "http" : "https"}://${t}`; try { const r = new URL(n.endsWith("/") ? n : `${n}/`), o = r.protocol.toLowerCase(), c = String(r.hostname || "").trim().toLowerCase(); return !o || !c ? "" : `${o}//${c}`; } catch { const r = st(t.replace(/^https?:\/\//i, "").split("/")[0] || ""); return r ? `${U(r) ? "http" : "https"}://${r}` : ""; } } function St(e) { return /^\d{1,3}(\.\d{1,3}){3}$/.test(e); } function Qt(e) { return !e.includes(".") && !St(e); } function Xt(e) { const t = e.lastIndexOf(":"); if (t > 0) { const n = e.slice(t + 1), r = parseInt(n, 10); if (String(r) === n && r > 0) return { host: e.slice(0, t), port: r }; } return { host: e, port: null }; } function tt(e) { const t = String(e || "").trim(); if (!t) return ""; if (t.includes("://")) return k(t); const { host: n, port: r } = Xt(t), o = n.toLowerCase(); if (St(o)) return `http://${o}:${r ?? Ut}`; if (Qt(o)) return `http://${o}.local:${r ?? Ut}`; const c = r ? `:${r}` : ""; return `https://${o}${c}`; } function Pe(e) { const t = String(e || "").trim(); if (!t) return ""; if (t.includes("://")) try { return new URL(t).hostname.toLowerCase(); } catch { return ""; } const { host: n } = Xt(t), r = n.toLowerCase(); return St(r) ? r : Qt(r) ? `${r}.local` : r; } function He(e) { const t = e ?? {}, n = String(t.hash || "").trim(); return n ? `h:${n}` : `v:${Number(t.timestamp || 0)}:${yt(e)}`; } function k(e) { const t = String(e || "").trim(); if (!t) return ""; const n = t.includes("://") ? t : `http://${t}`; try { return new URL(n.endsWith("/") ? n : `${n}/`).origin.toLowerCase(); } catch { return t.replace(/\/+$/, "").toLowerCase(); } } function dt(e) { return (typeof e == "string" ? e.trim() : "") || null; } function I(e) { return (typeof e == "string" ? e.trim() : "") || null; } function zt(e, t = "") { if (typeof e == "string") { const n = e.trim(); if (n) return n; } if (e && typeof e == "object") { const n = e, r = typeof n.me == "string" ? n.me.trim() : ""; if (r) return r; const o = typeof n.host == "string" ? n.host.trim() : ""; if (o) return o; } return t; } function et(e, t = "") { if (!e || typeof e != "object") return t; const n = e, r = zt(n.namespace, ""); if (r) return r; const o = n.target; return o && typeof o == "object" ? zt(o.namespace, t) : t; } function De(e) { try { const t = dt(e[ke]); if (t) return t; } catch { } try { const n = e["!"]?.currentExpression; if (typeof n == "function") { const r = dt(n()); if (r) return r; } if (n && typeof n == "object" && typeof n.call == "function") { const r = dt(n.call()); if (r) return r; } } catch { } return null; } function je(e) { try { const t = e[Ie]; if (t && typeof t == "object") { const r = I(t.hash); if (r) return r; } const n = I(t); if (n) return n; } catch { } try { const n = e["!"]?.identity; if (typeof n == "function") { const r = n(); if (r && typeof r == "object") { const c = I(r.hash); if (c) return c; } const o = I(r); if (o) return o; } if (n && typeof n == "object" && typeof n.call == "function") { const r = n.call(); if (r && typeof r == "object") { const c = I(r.hash); if (c) return c; } const o = I(r); if (o) return o; } } catch { } return null; } function Ue(e, t) { try { const r = e["!"]?.[t]; if (typeof r == "function") return r; if (r && typeof r == "object" && typeof r.call == "function") return ((...o) => r.call(...o)); } catch { } try { const n = e[t]; if (typeof n == "function") return n.bind(e); } catch { } return null; } function Fe(e) { const t = String(e || "").trim(); if (!t) return ""; try { return G(t).constant; } catch { const n = t.split(".").map((r) => r.trim()).filter(Boolean); return n.length > 1 ? n.slice(1).join(".") : t; } } async function ze(e, t) { const n = Ue( e, "prove" ); if (!n) throw new Error("PROVE_UNSUPPORTED"); const r = Fe(t); if (!r) throw new Error("ROOT_NAMESPACE_REQUIRED"); const o = await n({ rootNamespace: r, challenge: null }); if (!o || typeof o != "object") throw new Error("PROOF_INVALID"); const c = String(o.namespace || "").trim(); if (!c) throw new Error("PROOF_INVALID"); if (c !== t) throw new Error("PROOF_NAMESPACE_MISMATCH"); return o; } function U(e) { const t = st(e); return /^(localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0)$/.test(t); } function nt(e) { try { const t = new URL(e).hostname.toLowerCase(); return U(t) || t.endsWith(".local") || /^192\.168\./.test(t) || /^10\./.test(t) || /^172\.(1[6-9]|2\d|3[01])\./.test(t); } catch { return !1; } } function Be() { if (typeof globalThis > "u") return ""; const e = globalThis.location; if (!e) return ""; if (typeof e == "string") try { const o = new URL(e.includes("://") ? e : `https://${e}`).hostname.toLowerCase(); return U(o) ? "" : o; } catch { const o = st(String(e).trim().toLowerCase()); return U(o) ? "" : o; } const t = e, n = st(String(t.hostname || t.host || "").trim().toLowerCase()); if (U(n)) return ""; if (n) return n; const r = String(t.origin || t.href || "").trim(); if (!r) return ""; try { const o = new URL(r.includes("://") ? r : `https://${r}`).hostname.toLowerCase(); return U(o) ? "" : o; } catch { return ""; } } function Ke() { if (typeof globalThis > "u") return ""; const e = globalThis.location; if (!e) return ""; if (typeof e == "string") return z(e); const t = e, n = z(String(t.origin || "")); if (n) return n; const r = String(t.href || "").trim(); if (r) return z(r); const o = String(t.hostname || t.host || "").trim().toLowerCase(); return o ? z(o) : ""; } function Yt(e) { const t = ot(e); return t ? z(t) : ""; } function We() { if (typeof process > "u") return ""; const e = String( process.env.CLEAKER_SURFACE_HOST || process.env.MONAD_SELF_IDENTITY || process.env.CLEAKER_NAMESPACE_ROOT || process.env.CLEAKER_NAMESPACE_HOST || process.env.HOSTNAME || process.env.COMPUTERNAME || "" ).trim(), t = Yt(e); if (t) return t; const n = process; if (typeof n.getBuiltinModule != "function") return ""; try { const r = n.getBuiltinModule("node:os"), o = String(r?.hostname?.() || "").trim(); return o ? z(o) : ""; } catch { return ""; } } function ot(e) { const t = String(e || "").trim(); if (!t) return ""; if (/^https?:\/\//i.test(t)) try { return G(new URL(t).hostname).constant; } catch { return ""; } try { return G(t).constant; } catch { try { const n = new URL(t.includes("://") ? t : `https://${t}`); return G(n.hostname).constant; } catch { return ""; } } } function Ve(e) { const t = /* @__PURE__ */ new Set(), n = []; for (const r of e) { const o = k(String(r || "")); !o || t.has(o) || (t.add(o), n.push(o)); } return n; } function qe(e) { let t = 2166136261; for (let n = 0; n < e.length; n += 1) t ^= e.charCodeAt(n), t = Math.imul(t, 16777619); return ("00000000" + (t >>> 0).toString(16)).slice(-8); } function Ge(e) { return qe(k(e)); } function Qe(e, t) { if (t.length) try { let n = e; for (let r = 0; r < t.length; r += 1) if (n = n?.[t[r]], n == null) return; if (typeof n == "function") try { return n(); } catch { return; } return n; } catch { return; } } function _(e, t, n) { if (!t.length) return !1; try { let r = e; for (let o = 0; o < t.length; o += 1) if (r = r?.[t[o]], r == null) return !1; if (typeof r == "function") return r(n), !0; } catch { return !1; } return !1; } function Bt(e, t) { const n = k(String(e.space || "")); if (!n) return null; const r = String(e.id || "").trim() || Ge(n), o = e.status || { transport: "unknown", triad: "unverified", latencyMs: 0, lastSeen: 0 }, c = e.capabilities || { canClaim: !1, canOpen: !0, canRelay: !1 }; return { id: r, alias: e.alias ? String(e.alias) : void 0, space: n, namespace: t, status: { transport: o.transport || "unknown", triad: o.triad || "unverified", latencyMs: Number(o.latencyMs || 0), lastSeen: Number(o.lastSeen || 0) }, capabilities: { canClaim: !!c.canClaim, canOpen: c.canOpen !== !1, canRelay: !!c.canRelay }, error: e.error ? String(e.error) : void 0 }; } function Xe(e) { const t = e.join(".").trim(); return t.includes(".cleaker:") || t.includes(":") ? !0 : e.some((n, r) => { const o = n.toLowerCase(); return o.includes("cleaker:") || o.includes(":") || o === "cleaker" && r < e.length - 1; }); } function Ye(e) { const t = e.map((o) => String(o || "").trim()).filter(Boolean); if (t.length === 0) return null; const n = t.join("."); if (n.includes(":")) return n; const r = t.findIndex((o) => o.toLowerCase() === "cleaker"); if (r > 0 && r < t.length - 1) { const o = t[r - 1], c = t.slice(r + 1).join("."); return `${o}.cleaker:read/${c || "profile"}`; } return null; } function Kt(e) { if (!e || typeof e != "object") return e; const t = e; return Object.prototype.hasOwnProperty.call(t, "value") ? t.value : e; } function rt(e, t) { if (!(t.length === 0 || typeof e != "function")) try { return e(t.join(".")); } catch { return; } } function Je(e, t, n) { if (typeof e == "function") try { if (t.length === 0) return e(...n); let r = e; for (const o of t) r = r?.[o]; if (typeof r == "function") return r(...n); } catch { return; } } function Ze(e, t = {}) { const n = /* @__PURE__ */ new Set(), r = [], o = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map(), h = /* @__PURE__ */ new Map(), y = String(t.namespace || "").trim(), S = String(t.secret || ""), A = I(t.identityHash), b = Array.isArray(t.bootstrap) ? t.bootstrap.map((s) => k(s)).filter(Boolean) : [], R = t.space ? tt(t.space) : "", C = { ...R ? { origin: R } : {}, ...t.fetcher ? { fetcher: t.fetcher } : {}, headers: { accept: "application/json" } }; let E = "idle", v = 0, T = { cycleId: 0, state: "idle", overall: b.length ? "degraded" : "offline", activeNamespace: F(), totalHosts: 0, verifiedHosts: 0, hosts: [] }, it = null, Et = Promise.resolve(null); function Jt() { if (t.space) { const a = Pe(t.space); if (a) return a; } const s = Be(); if (s) return ot(s); const i = typeof process < "u" ? String(process.env.CLEAKER_NAMESPACE_ROOT || process.env.CLEAKER_NAMESPACE_HOST || "") : ""; return ot(i || ht); } function F(s) { const i = String(s || y || "").trim(); if (i) return i; const a = De(e); if (!a) return ""; if (a.includes(".")) try { const l = G(a); if (l.prefix && l.constant) return Ft(l.prefix, l.constant); } catch { } const p = Jt(); return p ? Ft(a, p) : ""; } function at(s = [], i = "") { const a = t.space ? tt(t.space) : "", p = Ke(), l = typeof process < "u" ? String(process.env.CLEAKER_NAMESPACE_ROOT || process.env.CLEAKER_NAMESPACE_HOST || "") : "", m = Yt(l || ""), d = We(); return Ve([ i, a, ...b, ...s, p, m, d, ht, Ee ]); } function bt(s) { return I(s) || A || je(e) || ""; } function Zt(s) { const i = String(s || "").trim().replace(/^\/+/, "").replace(/\//g, "."); if (i) return rt(e, i.split(".").filter(Boolean)); } function Rt(s) { const i = String(s || "").trim(); return i ? i.startsWith("me://") || i.includes(":") : !1; } function At(s) { if (!Rt(s)) return null; try { const i = mt(s, { defaultMode: "reactive", allowShorthandRead: !0 }); return String(i.path || "").trim().replace(/^\/+/, "").split("/").map((a) => a.trim()).filter(Boolean); } catch { return null; } } function L(s, ...i) { const a = h.get(s); !a || a.size === 0 || a.forEach((p) => { try { p(...i); } catch { } }); } function Ct(s, i) { const a = h.get(s) || /* @__PURE__ */ new Set(); return a.add(i), h.set(s, a), () => vt(s, i); } function vt(s, i) { const a = h.get(s); a && (a.delete(i), a.size === 0 && h.delete(s)); } function Ot(s, i) { const a = Ct(s, ((...p) => { a(), i(...p); })); return a; } function H(s, i) { E = s, T = { ...T, cycleId: i, state: s }, L("status:change", M()); } function W(s, i) { const a = ["namespaces", s, "registry", "hosts", i.id]; _(e, [...a, "id"], i.id), _(e, [...a, "alias"], i.alias || ""), _(e, [...a, "space"], i.space), _(e, [...a, "namespace"], i.namespace), _(e, [...a, "status", "transport"], i.status.transport), _(e, [...a, "status", "triad"], i.status.triad), _(e, [...a, "status", "latencyMs"], i.status.latencyMs), _(e, [...a, "status", "lastSeen"], i.status.lastSeen), _(e, [...a, "capabilities", "canClaim"], i.capabilities.canClaim), _(e, [...a, "capabilities", "canOpen"], i.capabilities.canOpen), _(e, [...a, "capabilities", "canRelay"], i.capabilities.canRelay), _(e, [...a, "error"], i.error || ""); } function ct(s = {}) { const i = F(s.namespace); if (!i) return []; const a = /* @__PURE__ */ new Map(), p = Qe(e, ["namespaces", i, "registry", "hosts"]); if (p && typeof p == "object" && !Array.isArray(p)) { const l = p; Object.keys(l).forEach((m) => { const d = l[m], u = Bt({ ...d, id: d?.id || m }, i); u && a.set(u.id, u); }); } if (a.size === 0) { const l = Array.isArray(s.bootstrap) ? s.bootstrap.map((d) => k(d)).filter(Boolean) : []; at(l).forEach((d) => { const u = Bt({ space: d }, i); u && (a.set(u.id, u), W(i, u)); }); } return Array.from(a.values()); } async function te(s, i, a) { const p = typeof AbortController < "u" ? new AbortController() : null, l = p ? setTimeout(() => p.abort(), i) : null; try { return (await a(`${k(s)}/__bootstrap`, { method: "GET", cache: "no-store", signal: p?.signal })).ok; } catch { return !1; } finally { l && clearTimeout(l); } } async function X(s, i, a, p, l = {}) { const m = typeof AbortController < "u" ? new AbortController() : null, d = m ? setTimeout(() => m.abort(), a) : null; try { const u = await p(s, { method: "POST", headers: { "content-type": "application/json", ...l }, body: JSON.stringify(i), signal: m?.signal }); let f = null; try { f = await u.json(); } catch { f = null; } return !u.ok || !f?.ok ? { ok: !1, status: u.status, data: f, error: String(f?.error || `REQUEST_FAILED_${u.status}`) } : { ok: !0, status: u.status, data: f }; } catch (u) { return { ok: !1, status: 0, data: null, error: (u instanceof Error ? u.name : String(u)) === "AbortError" ? "TIMEOUT" : "NETWORK_ERROR" }; } finally { d && clearTimeout(d); } } function xt(s, i, a) { return { ok: !0, namespace: et(s, i), identityHash: I(s.identityHash) || a, noise: String(s.noise || ""), memories: Array.isArray(s.memories) ? s.memories : [], openedAt: Number(s.openedAt || Date.now()), target: s.target && typeof s.target == "object" ? s.target : void 0 }; } function Nt(s, i, a) { return { ok: !0, namespace: et(s, i), identityHash: I(s.identityHash) || a, publicKey: typeof s.publicKey == "string" ? s.publicKey : void 0, createdAt: Number(s.createdAt || Date.now()), persistentClaim: s.persistentClaim, target: s.target && typeof s.target == "object" ? s.target : void 0 }; } async function Tt(s, i, a, p, l, m, d = {}) { const u = { namespace: i, secret: a, ...p ? { identityHash: p } : {} }, f = await X(`${k(s)}/claims/signIn`, u, l, m, d); if (f.ok && f.data) return xt(f.data, i, p); const O = String(f.error || "OPEN_FAILED"); if (O === "CLAIM_NOT_FOUND") return { ok: !1, error: O }; if (f.status === 404) { const $ = await X( `${k(s)}/`, { operation: "open", ...u }, l, m, { "x-forwarded-host": i, ...d } ); return $.ok && $.data ? xt($.data, i, p) : { ok: !1, error: String($.error || O) }; } return { ok: !1, error: O }; } async function $t(s, i, a, p, l, m = {}) { let d; try { d = await ze(e, i); } catch (f) { return { ok: !1, error: f instanceof Error ? f.message : "PROOF_INVALID" }; } const u = await X( `${k(s)}/me/kernel:claim/${encodeURIComponent(i)}`, { namespace: i, secret: a, proof: d }, p, l, m ); if (u.ok && u.data) return Nt(u.data, i, d.identityHash); if (u.status === 404 || u.status === 405) { const f = await X( `${k(s)}/`, { operation: "claim", namespace: i, secret: a, proof: d }, p, l, { "x-forwarded-host": i, ...m } ); return f.ok && f.data ? Nt(f.data, i, d.identityHash) : { ok: !1, error: String(f.error || u.error || "CLAIM_FAILED") }; } return { ok: !1, error: String(u.error || "CLAIM_FAILED") }; } async function _t(s, i, a, p, l, m, d = {}) { const u = await Tt(s, i, a, p, l, m, d); if (u.ok || u.error !== "CLAIM_NOT_FOUND") return u; const f = await $t(s, i, a, l, m, d); if (!f.ok) return { ok: !1, error: String(f.error || "CLAIM_FAILED") }; const O = I(f.identityHash) || p; return Tt( s, et(f, i), a, O, l, m, d ); } function M() { return { ...T, hosts: T.hosts.map((s) => ({ ...s, status: { ...s.status }, capabilities: { ...s.capabilities } })) }; } async function ee(s = 1e4) { return E === "ready" && it ? it : await new Promise((i, a) => { const p = setTimeout(() => { l(), a(new Error("TIMEOUT_WAITING_FOR_READY")); }, s), l = Ot("ready", (m) => { clearTimeout(p), i(m); }); }); } async function ne(s = {}) { const i = F(s.namespace), a = String(s.secret !== void 0 ? s.secret : S), p = bt(s.identityHash), l = s.triadStrategy || "first-success", m = Number(s.timeoutMs || 5e3), d = t.fetcher || fetch, u = ++v; if (!i) return L("error", { code: "NAMESPACE_REQUIRED", message: "Cannot validate hosts without namespace." }), H("offline", u), T = { ...T, cycleId: u, state: "offline", overall: "offline", activeNamespace: i, totalHosts: 0, verifiedHosts: 0, hosts: [] }, L("status:change", M()), M(); H("discovering", u); const f = ct({ namespace: i, bootstrap: s.bootstrap }); if (!f.length) return H("offline", u), T = { ...T, cycleId: u, state: "offline", overall: "offline", activeNamespace: i, totalHosts: 0, verifiedHosts: 0, hosts: [] }, L("status:change", M()), M(); H("probing", u); let O = null, $ = "", D = "", Ht = 0; const P = []; for (let N = 0; N < f.length; N += 1) { const w = f[N], J = Date.now(), Z = await te(w.space, m, d); if (w.status.transport = Z ? "up" : "down", w.status.latencyMs = Date.now() - J, w.status.lastSeen = Date.now(), !Z) { w.status.triad = "unverified", w.error = "NETWORK_ERROR", W(i, w), P.push({ origin: w.space, reason: "NETWORK_ERROR" }); const x = f[N + 1]; x && !nt(w.space) && nt(x.space) && L("namespace:fallback", { namespace: i, failedOrigin: w.space, failedReason: "NETWORK_ERROR", fallbackOrigin: x.space }); continue; } if (!a) { w.status.triad = "unverified", w.error = "SECRET_REQUIRED", W(i, w), P.push({ origin: w.space, reason: "SECRET_REQUIRED" }); continue; } H("opening", u); const j = await _t(w.space, i, a, p, m, d); if (!j.ok) { const x = String(j.error || "OPEN_FAILED"); w.status.triad = x === "CLAIM_NOT_FOUND" ? "unverified" : "failed", w.error = x, L("error", { code: x, message: `Triad open failed on ${w.space}`, hostId: w.id }), W(i, w), P.push({ origin: w.space, reason: x }); const ft = f[N + 1]; ft && !nt(w.space) && nt(ft.space) && L("namespace:fallback", { namespace: i, failedOrigin: w.space, failedReason: x, fallbackOrigin: ft.space }); continue; } w.status.triad = "verified", w.error = void 0, W(i, w), L("host:triad:success", w.id), O || (O = w), H("hydrating", u); const se = Array.isArray(j.memories) ? j.memories : [], ie = n.size; if (se.forEach((x) => { Y(x); }), Ht += Math.max(0, n.size - ie), j.noise !== void 0 && (e.noise = String(j.noise || "")), $ = w.id, D = String(j.identityHash || ""), l === "first-success") { for (let x = N + 1; x < f.length; x += 1) f[x].status.triad = "skipped"; break; } } if (u !== v) return M(); const V = f.filter((N) => N.status.triad === "verified").length, Dt = V > 0 ? "healthy" : "degraded"; if (V === 0 && P.length > 0) { const N = P.map( (J, Z) => ` [${Z + 1}] ${J.origin}${J.reason}` ), w = `namespace '${i}' failed to resolve. tried ${P.length} surface${P.length === 1 ? "" : "s"}: ` + N.join(` `); L("namespace:failed", { namespace: i, tried: P, explain: w }); } const jt = V > 0 ? "ready" : "degraded"; if (H(jt, u), T = { cycleId: u, state: jt, overall: Dt, activeNamespace: i, totalHosts: f.length, verifiedHosts: V, hosts: f }, L("status:change", M()), O) { const N = { namespace: i, cycleId: u, sourceHostId: $ || O.id, sourceOrigin: O.space, identityHash: D, timestamp: Date.now(), hydratedMemories: Ht, summary: { verifiedHosts: V, totalHosts: f.length, overall: Dt } }; it = N, L("ready", N); } return M(); } function lt(s, i = {}) { const a = mt(s, { defaultMode: "reactive" }), p = Vt(a, { ...t, resolveLocalTarget: (l) => { if (l.namespace.prefix !== null) throw new Error("LOCAL_TARGET_PREFIX_NOT_ALLOWED"); if (l.namespace.constant !== "local" && l.namespace.constant !== "self") throw new Error("LOCAL_TARGET_REQUIRED"); return Zt(l.intent.path); } }); return Object.keys(i).length ? { ...p, resolve(l = {}) { return p.resolve({ ...i, ...l }); } } : p; } function Y(s) { const i = Me(s), a = He(i); return n.has(a) ? !1 : (n.add(a), r.push(i), typeof e.learn == "function" ? (e.learn(i), !0) : (typeof e.replayMemories == "function" && e.replayMemories(r.slice()), !0)); } function Lt(s, i) { const a = s.map((p) => String(p || "").trim()).filter(Boolean); return a.length === 0 ? null : { path: a.join("."), operator: null, expression: i, value: i }; } async function kt(s) { const i = F(s.namespace), a = String(s.secret || ""), p = bt(s.identityHash); if (!i) throw new Error("NAMESPACE_REQUIRED"); if (!a) throw new Error("SECRET_REQUIRED"); const l = s.fetcher || t.fetcher || fetch, m = at([], s.space ? tt(s.space) : ""); let d = "SIGNIN_FAILED"; for (const u of m) { const f = await _t( u, i, a, p, 5e3, l, s.headers || {} ); if (!f.ok) { d = String(f.error || "SIGNIN_FAILED"); continue; } const $ = (Array.isArray(f.memories) ? f.memories : []).filter((D) => Y(D)); return e.noise = String(f.noise || ""), { status: "verified", namespace: String(f.namespace || i), identityHash: String(f.identityHash || p || ""), noise: String(f.noise || ""), openedAt: Number(f.openedAt || Date.now()), memoriesCount: $.length }; } throw new Error(d); } async function re(s) { const i = F(s.namespace), a = String(s.secret || ""); if (!i) throw new Error("NAMESPACE_REQUIRED"); if (!a) throw new Error("SECRET_REQUIRED"); const p = s.fetcher || t.fetcher || fetch, l = at([], s.space ? tt(s.space) : ""); let m = "CLAIM_FAILED"; for (const d of l) { const u = await $t(d, i, a, 5e3, p, s.headers || {}); if (!u.ok) { m = String(u.error || "CLAIM_FAILED"); continue; } return { status: "verified", namespace: String(et(u, i)), identityHash: String(u.identityHash || ""), noise: "", openedAt: Number(u.createdAt || Date.now()), memoriesCount: 0 }; } throw new Error(m); } F() && ct({ namespace: y }), t.secret && (Et = kt({ namespace: y, secret: t.secret, identityHash: t.identityHash, space: t.space, fetcher: t.fetcher }).catch(() => null)); function It(s) { if (!Xe(s)) return; const i = s.join("."), a = c.get(i); if (a) return a; const p = Ye(s); if (!p) return; const l = lt(p), m = { key: i, path: s.slice(), expression: p, pointer: l, promise: Promise.resolve({ ok: !1, status: 0, endpoint: "", elapsedMs: 0, data: null }) }; return m.promise = l.resolve(C).then((d) => { if (m.lastResult = d, d.ok) { const u = Kt(d.data); o.set(i, u); const f = Lt(s, u); f && Y(f); } return d; }), c.set(i, m), m; } function Mt(s) { const i = At(s); if (!i || i.length === 0) return; const a = `target:${s}`, p = c.get(a); if (p) return p; const l = lt(s), m = { key: a, path: i.slice(), expression: s, pointer: l, promise: Promise.resolve({ ok: !1, status: 0, endpoint: "", elapsedMs: 0, data: null }) }; return m.promise = l.resolve(C).then((d) => { if (m.lastResult = d, d.ok) { const u = Kt(d.data); o.set(a, u); const f = Lt(i, u); f && Y(f); } return d; }), c.set(a, m), m; } function Pt(s) { return { status: "pending", path: s.key, pointer: s.pointer, promise: s.promise }; } function oe(s) { if (!(s in e)) return; const i = e[s]; return typeof i == "function" ? i.bind(e) : i; } function ut(s = []) { const i = (...a) => { if (s.length === 0) { if (typeof e == "function") { if (a.length === 1 && typeof a[0] == "string") { const l = String(a[0] || "").trim(), m = At(l); if (m) { const u = rt(e, m); if (u !== void 0) return u; const f = Mt(l); return f ? Pt(f) : void 0; } const d = rt(e, l.split(".").filter(Boolean)); if (d !== void 0) return d; if (Rt(l)) { const u = Mt(l); return u ? Pt(u) : void 0; } } return e(...a); } return; } const p = Je(e, s, a); return p !== void 0 ? p : ut(s); }; return new Proxy(i, { get(a, p) { if (typeof p == "symbol") return i[p]; const l = String(p); if (s.length === 0) { if (l === "kernel") return e; if (l === "claim") return re; if (l === "signIn") return kt; if (l === "ready") return Et; if (l === "pointer") return lt; if (l === "discoverHosts") return ct; if (l === "validateHosts") return ne; if (l === "getStatus") return M; if (l === "waitUntilReady") return ee; if (l === "on") return Ct; if (l === "once") return Ot; if (l === "off") return vt; if (l === "state") return E; if (l === "currentCycleId") return v; const D = oe(l); if (D !== void 0) return D; } const m = s.join("."), d = o.get(m); if (d && typeof d == "object" && !Array.isArray(d) && Object.prototype.hasOwnProperty.call(d, l)) return d[l]; const u = It(s); if (u) { if (l === "status") return u.lastResult ? u.pointer.__ptr.resolution.status : "pending"; if (l === "pointer") return u.pointer; if (l === "promise") return u.promise; if (l === "result") return u.lastResult; if (l === "then") return u.promise.then.bind(u.promise); } const f = [...s, l], O = f.join("."); if (o.has(O)) return o.get(O); const $ = rt(e, f); return $ !== void 0 ? $ : (It(f), ut(f)); }, apply(a, p, l) { return i(...l); } }); } return ut([]); } function tn(e, t, n) { if (typeof e == "string") { const c = mt(e, { defaultMode: "reactive" }); return Vt(c, t ?? {}); } let r, o; return typeof t == "string" ? (r = t, o = n ?? {}) : o = t ?? {}, Ze(e, { ...o, ...r ? { space: r } : {} }); } export { Ft as composeNamespace, tn as default, G as parseNamespaceExpression, mt as parseTarget, Le as stringifyNamespaceExpression }; //# sourceMappingURL=cleaker.es.js.map