{"version":3,"file":"policy-edge.mjs","names":[],"sources":["../src/policy-evaluator-edge.ts"],"sourcesContent":["/**\n * Cedar policy-evaluator bridge — EDGE (Cloudflare Workers / Vercel Edge).\n *\n * Edge sibling of `policy-evaluator.ts` (the Node bridge). The Node bridge\n * uses `createRequire` + `fs.readFileSync` at module load — incompatible with\n * Cloudflare Workers. This module loads the cedar `--target web` glue via the\n * async `__wbg_init` default export, the SAME canonical wrangler pattern as\n * `engine/edge.ts` (read that file's header for the full WASM-on-wrangler\n * incident history — it took three prod deploys + two rollbacks to land for\n * the detection engine; do not deviate from this shape).\n *\n * The host (the gateway worker) statically imports the cedar-web `.wasm`\n * (wrangler bundles it → a `WebAssembly.Module`) and passes it to\n * {@link initPolicyEvaluatorEdge} once at module load. The ~2 MB cedar WASM is\n * INSTANTIATED LAZILY on first {@link evaluatePolicy} call — detection-only\n * requests never pay the compile/instantiate cost (only the bundle-size cost).\n *\n * Language-agnostic seam: every caller routes through {@link evaluatePolicy}\n * (language, sourceText), NEVER a Cedar-specific factory — so adding a future\n * Rego/OPA evaluator is one new switch arm here with zero call-site changes.\n */\n\nimport { assertCedarNesting, cedarNestingError } from './cedar-nesting';\nimport { edgeEngineCedarGlue } from './engine/edge';\nimport {\n  isCedarModule,\n  noteCedarAttempt,\n  registerCedarModule,\n  registeredCedarModule,\n} from './engine/edge-wasm';\nimport { WasmModuleNotRegisteredError } from './wasm-module-error';\n\n// Type-only import → fully erased at compile, so the Node bridge's\n// `node:module`/`fs` runtime imports are NOT pulled into the edge bundle.\nimport type { AuthorizeInput, Decision, PolicyValidation } from './policy-evaluator';\n\nexport type { AuthorizeInput, Decision, BlockReason, PolicyValidation } from './policy-evaluator';\nexport { WasmModuleNotRegisteredError, type EdgeWasmArtifact } from './wasm-module-error';\n/**\n * Whether a module is the cedar-web build, which serves both the engine and\n * Cedar: a host can tell from the module it was given whether Cedar is\n * available, instead of probing the module's exports itself.\n */\nexport { isCedarModule } from './engine/edge-wasm';\n\n/** Structural type of the WASM `PolicyEvaluator` class the cedar-web glue exports. */\ninterface WasmPolicyEvaluator {\n  authorize(input: AuthorizeInput): unknown;\n  free(): void;\n}\n\ntype CedarWebGlue = {\n  default: (moduleOrPath: { module_or_path: WebAssembly.Module }) => Promise<unknown>;\n  PolicyEvaluator: new (policyText: string) => WasmPolicyEvaluator;\n  validatePolicy: (policyText: string) => PolicyValidation;\n};\n\n/**\n * Host-facing wrapper around one compiled policy bundle. Mirrors the Node\n * `PolicyEvaluatorRuntime`: construction (in {@link evaluatePolicy}) compiles\n * once; every {@link authorize} reuses it. The evaluator owns the fail-closed\n * posture — a request it cannot marshal, or one matching no `permit`, returns\n * a `Block` Decision, not a throw.\n */\nexport class PolicyEvaluatorRuntime {\n  constructor(private readonly inner: WasmPolicyEvaluator) {}\n\n  authorize(input: AuthorizeInput): Decision {\n    // REASON: the WASM glue's `authorize` returns `any`/`unknown` (wasm-bindgen\n    // serde-wasm-bindgen boundary); the engine contract guarantees a `Decision`\n    // JSON object (see the cedar-web .d.ts + engine types). Validated by the\n    // mapDecision consumer which switches on the known `kind` union.\n    return this.inner.authorize(input) as Decision;\n  }\n\n  free(): void {\n    this.inner.free();\n  }\n}\n\n// The registered module and its attempt state live in ./engine/edge-wasm, where\n// the edge engine can run on it too (same module rule as engine/edge.ts).\nlet ready: Promise<CedarWebGlue> | null = null;\n/** A module was refused because it is not the cedar-web build. */\nlet refusedNonCedarModule = false;\n\n/**\n * Register the wrangler-bundled cedar-web `WebAssembly.Module`. Call once at\n * worker module load with the statically-imported `.wasm`. Does NOT instantiate\n * the WASM — that is deferred to the first {@link evaluatePolicy} call so the\n * ~2 MB cedar binary stays off the detection-only hot path.\n *\n * A module that is not the cedar-web build is refused, without throwing (hosts\n * call this at module load): Cedar then rejects with\n * `WasmModuleNotRegisteredError`, whose message says the module was wrong.\n */\nexport function initPolicyEvaluatorEdge(wasmModule: WebAssembly.Module): void {\n  if (wasmModule === undefined) return;\n  if (!isCedarModule(wasmModule)) {\n    refusedNonCedarModule = true;\n    return;\n  }\n  registerCedarModule(wasmModule);\n}\n\nfunction ensureReady(): Promise<CedarWebGlue> {\n  // The edge engine runs on the cedar-web module: evaluate Cedar on that one\n  // instance rather than instantiating the same build a second time.\n  const shared = edgeEngineCedarGlue();\n  if (shared) return shared as Promise<CedarWebGlue>;\n  if (ready) return ready;\n\n  const pending = (async () => {\n    // The cedar-web glue has no URL fallback, so without a registered module\n    // there is nothing to instantiate.\n    const wasmModule = registeredCedarModule();\n    if (wasmModule === undefined) {\n      throw new WasmModuleNotRegisteredError(\n        'cedar',\n        refusedNonCedarModule\n          ? 'initPolicyEvaluatorEdge() (the module it was given is not the cedar-web build), or to initEngine() in place of the engine-web module'\n          : 'initPolicyEvaluatorEdge(), or to initEngine() in place of the engine-web module'\n      );\n    }\n    // Package self-import — kept external by tsup (`wasm/kya-os-engine-cedar-web/`\n    // in commonOpts.external); wrangler resolves it via the `./wasm/*` exports\n    // pattern. Mirrors engine/edge.ts:ensureReady exactly.\n    // REASON: the wasm-bindgen glue ships no usable module types; cast the\n    // dynamic import to the CedarWebGlue shape pinned against the cedar-web\n    // .d.ts (default __wbg_init + PolicyEvaluator class).\n    const mod = (await import(\n      '@kya-os/checkpoint-wasm-runtime/wasm/kya-os-engine-cedar-web/kya_os_engine.js'\n    )) as unknown as CedarWebGlue;\n    // web-target init with an explicit Module → WebAssembly.instantiate(Module)\n    // internally (the Cloudflare-Workers path). The `{ module_or_path }` wrapper\n    // suppresses the bare-arg deprecation warning.\n    await mod.default({ module_or_path: wasmModule });\n    return mod;\n  })();\n\n  ready = pending;\n  noteCedarAttempt(registeredCedarModule(), pending);\n  // Clear the cache on rejection so a retry (e.g. after a transient instantiate\n  // fault) can re-init rather than caching the rejection forever; the module\n  // stays registered for that retry, and a newly registered one may replace it.\n  pending.catch(() => {\n    if (ready === pending) {\n      ready = null;\n    }\n  });\n  return ready;\n}\n\n/** Policy languages the edge seam can evaluate. Cedar today; Rego/OPA later. */\nexport const SUPPORTED_POLICY_LANGUAGES = ['cedar'] as const;\nexport type PolicyLanguage = (typeof SUPPORTED_POLICY_LANGUAGES)[number];\n\n/**\n * Compile a tenant policy bundle into a reusable evaluator, dispatched by\n * language. The ONE seam every surface routes through — adding Rego is a new\n * `case` here, not a call-site change.\n *\n * @throws if `language` is unsupported (fail-closed — never silently treated as\n *   Cedar) or if `sourceText` is not valid for that language (surfaced at\n *   compile, never as a per-request deny).\n */\nexport async function evaluatePolicy(\n  language: string,\n  sourceText: string\n): Promise<PolicyEvaluatorRuntime> {\n  switch (language) {\n    case 'cedar': {\n      assertCedarNesting(sourceText);\n      const mod = await ensureReady();\n      return new PolicyEvaluatorRuntime(new mod.PolicyEvaluator(sourceText));\n    }\n    default:\n      throw new Error(`Unsupported policy language: ${language}`);\n  }\n}\n\n/**\n * Edge sibling of the Node `validatePolicy`: type-check a tenant Cedar bundle\n * against the canonical schema WITHOUT compiling an evaluator or throwing\n * (E4.7 / #3076), returning the errors + warnings. Async because it awaits the\n * lazy cedar-web init (like {@link evaluatePolicy}). Cedar-only today; a blank\n * bundle is valid (\"no composed policy\").\n */\nexport async function validatePolicy(policyText: string): Promise<PolicyValidation> {\n  const nesting = cedarNestingError(policyText);\n  if (nesting !== undefined) return { valid: false, errors: [nesting], warnings: [] };\n  const mod = await ensureReady();\n  return mod.validatePolicy(policyText);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,IAAa,yBAAb,MAAoC;CACL;CAA7B,YAAY,OAA6C;EAA5B,KAAA,QAAA;CAA6B;CAE1D,UAAU,OAAiC;EAKzC,OAAO,KAAK,MAAM,UAAU,KAAK;CACnC;CAEA,OAAa;EACX,KAAK,MAAM,KAAK;CAClB;AACF;AAIA,IAAI,QAAsC;;AAE1C,IAAI,wBAAwB;;;;;;;;;;;AAY5B,SAAgB,wBAAwB,YAAsC;CAC5E,IAAI,eAAe,KAAA,GAAW;CAC9B,IAAI,CAAC,cAAc,UAAU,GAAG;EAC9B,wB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