You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Part of #1645. Verify before anything is typed: canonical Cedar schema syntax for codegen (JSON vs human-readable — which does @cedar-policy/cedar-wasm@4.12.0 parse both ways?), JSON policy format fidelity for import, wasm API surface (validate, policy/schema parse, isAuthorized for tests). Deliverables: pin decision recorded in the lexicon README, upstreamPin declared on the plugin (language/wasm version — the project schema is local input, not the pinned upstream), ops/lexicon-upgrade/cedar-upgrade.op.ts, content-pin per the aws src/spec/pin.ts pattern where applicable (digest extracted content, commit covered names beside the digest — chant#1390).
Every claim below comes from a run in /private/tmp/claude-501/-Users-alex-Documents-checkouts-intentius-chant/60bb59f7-9477-4028-b773-a0b9bd7966ba/scratchpad/cedar-wasm-lab/
against a clean npm install @cedar-policy/cedar-wasm@4.12.0, on node v24.13.1, npm 11.8.0, bun 1.3.6, vitest 4.1.10, darwin arm64. Scripts are named inline so they can be re-run.
The distinction that matters for upstreamPin: the package is 4.12.0, the language it implements is 4.5. These move independently — the epic says "Cedar language 4.x", and 4.5 is the precise number to record. Pin both; getCedarLangVersion() is the value a drift check should assert, since a package bump that leaves lang at 4.5 cannot change grammar acceptance.
Release cadence over the last six months: 4.9.0 (Feb 10), 4.10.0 (Apr 23), 4.11.0 (May 18), 4.11.1 (Jun 9), 4.11.2 (Jun 23), 4.12.0 (Jul 28). Roughly monthly, so an upgrade op will be exercised.
There is no separate @cedar-policy/cedar-wasm types package; .d.ts ships in-tree, so no @types/* pin is needed.
1. API surface
24 exports, all synchronous, all plain functions. No classes, no async, no init step (for the nodejs and root flavors). Full signatures are in node_modules/@cedar-policy/cedar-wasm/esm/cedar_wasm.d.ts (427 lines, hand-verified below).
Both formats parse. But string always means human-readable .cedarschema, never JSON. JSON must be passed as a live JS object.
Run (schema.mjs):
checkParseSchema A. human-readable string (cedarschema) -> success
checkParseSchema B. JS object (SchemaJson) -> success
checkParseSchema C. JSON.stringify(obj) as string -> failure
:: failed to parse schema from string: error parsing schema: unexpected token `{`
JSON.parse before handing a .cedarschema.json file to the wasm — otherwise you get a confusing "unexpected token {" pointing at valid JSON. The same rule applies to schemaToJson, schemaToText, and validate({ schema }). Verified validate against a JS-object schema produces identical results to the human-readable form (2 errors both ways).
Related trap: checkParseSchema("") and checkParseSchema({}) both return success — an empty schema is legal Cedar. Do not use "did it parse" as a proxy for "is there a schema".
Policy text ⇄ JSON fidelity: semantic, not byte-level
Round-tripped a policy carrying two annotations, is ... in, action in [..], two when clauses, two unless clauses, has, like, and a >= (roundtrip.mjs).
policyToJson -> success
policyToText(json) -> success
BYTE-LEVEL identical to original? false
JSON stable across 2nd trip (semantic fidelity)? true
text stable text->json->text->json->text? true
Everything semantic survives. PolicyJson captured all four clauses in order with correct kind: "when"|"unless", the is+in principal constraint as {op:"is", entity_type, in:{entity}}, the action set as {op:"in", entities:[...]}, and like "10.*" as a PatternElem[] of [{Literal:"1"},{Literal:"0"},{Literal:"."},"Wildcard"].
What changes on the way back to text:
Annotations are re-sorted alphabetically. Source order @id, @doc came back @doc, @id. They serialize into a sorted map, so authored order is not recoverable.
Output is one long line with defensive parens: when { ((context.mfa) == true) && ((principal.level) >= 3) }.
Comments are dropped.policyToText(policyToJson("// hello\npermit(...);")) → "permit(principal, action, resource);". Comments are not in the JSON grammar at all.
Value: true / Value: 3 — literals keep their JS types, no stringification.
formatPolicies is a separate and much better pretty-printer: it preserves annotation order, preserves comments ("// hello\npermit (principal, action, resource);\n"), emits multi-line scope blocks, and is idempotent. It operates on text only — it cannot consume PolicyJson.
So the honest fidelity statement for the epic's round-trip DoD (TS → .cedar → JSON → regenerated TS): the JSON leg is semantically lossless and idempotent, but it is not a formatting-preserving representation. Golden tests must compare policyToJson output (deterministic, see §5) or formatPolicies output, never raw policyToText against an authored file.
Schema round-trip fidelity
Tested with common types, an enum entity, an optional attribute, entity tags, and an action annotation (schema-rt.mjs):
JSON idempotent (j1 === j2)? true
text idempotent (t1 === t2)? true
human text byte-identical to original? false (reformatted, entity types sorted)
commonTypes preserved? {"Level":{"type":"EntityOrCommon","name":"Long"}}
enum preserved? {"enum":["prod","dev"]}
optional attr? {"type":"EntityOrCommon","name":"String","required":false}
action annotations? {"doc":"write access"}
tags preserved? {"type":"Set","element":{"type":"EntityOrCommon","name":"String"}}
Lossless in both directions after one normalization pass.
schemaToJson vs schemaToJsonWithResolvedTypes — the codegen-relevant difference
This is the finding that most directly shapes #1650. schemaToJson emits EntityOrCommon for every named type, which is ambiguous: you cannot tell an entity reference from a primitive from a common-type alias without resolving it yourself against commonTypes and entityTypes. schemaToJsonWithResolvedTypes does that resolution (resolved.mjs):
It also fully qualifies namespaces (Chant::User, Chant::Group in memberOfTypes) and resolves extension types ({"type":"datetime"} instead of {"type":"EntityOrCommon","name":"datetime"}). Its output re-parses as a valid schema (checkParseSchema(rt.json) -> success).
Caveat: its signature is (schema_str: string) and it means it — passing a JS object traps the wasm (see §5).
Templates
Templates work end to end (templates.mjs). templateToJson/templateToText round-trip a two-slot template byte-identically (it was already in canonical form). A PolicySet with templates + templateLinks validates clean and authorizes: isAuthorized via template link -> success allow ["link1"]. policySetTextToParts correctly separates a mixed file into policies[] and policy_templates[], sorted by id.
isAuthorized as a test harness
Works, and is ergonomic enough for example tests (authz.mjs):
alice mfa=true -> allow reason=["allow-eng-write"] errs=0 warns=0
bob mfa=true -> deny reason=[] errs=0 warns=0
alice mfa=false -> deny reason=[] errs=0 warns=0
EntityUid accepts both {type,id} and {__entity:{type,id}}. Entity attributes that are entity references need the __entity wrapper ({owner:{__entity:{type:'Chant::Repo',id:'core'}}}); bare {type,id} in an attribute position is read as a record. validateRequest: true catches inapplicable requests but reports them as a top-level failure, not a deny — an invalid request and a broken policy set surface through the same channel.
getValidRequestEnvsPolicy gives coverage analysis for free, which is exactly what the epic's "every declared bucket is covered by at least one forbid" checks need:
Three subpackages, and they are not interchangeable. Results (load-cjs.cjs, load-esm.mjs, bun-test.ts, vt/cedar.test.ts, bt/cedar.bun.test.ts):
Loader
root (esm)
/nodejs (cjs)
/web
node require()
failsERR_PACKAGE_PATH_NOT_EXPORTED
works
n/a
node import()
works (+ experimental warning)
works
loads, calls fail without initSync
vitest (environment: "node", forks)
works
works
needs initSync
bun run
fails
works
needs initSync
bun test
fails
works
needs initSync
Recommendation: import @cedar-policy/cedar-wasm/nodejs everywhere. It is the only flavor that works under all four loaders.
The two failures in detail.
Root/esm under Bun — this is the one that matters, since chant's CLAUDE.md describes the project as "TypeScript on Bun":
bun import('@cedar-policy/cedar-wasm') FAILED:
wasm.__wbindgen_start is not a function.
(In 'wasm.__wbindgen_start()', 'wasm.__wbindgen_start' is undefined)
at node_modules/@cedar-policy/cedar-wasm/esm/cedar_wasm.js:6:6
The esm flavor does import * as wasm from "./cedar_wasm_bg.wasm" — a WebAssembly ESM module import. Bun's implementation does not expose the wasm start function, so the module dies at import time. Node supports it but prints ExperimentalWarning: Importing WebAssembly module instances is an experimental feature and might change at any time on every run, which will pollute chant's test output.
Root under CJS require:
CJS require(root) FAILED: ERR_PACKAGE_PATH_NOT_EXPORTED
No "exports" main defined in .../@cedar-policy/cedar-wasm/package.json
The root exports["."] map declares only import and types, no require — despite the root package.json still carrying a vestigial "main": "cedar_wasm.js" that points at a file which does not exist at the root. Any tooling that falls back to main will chase a phantom.
/nodejs loads the wasm with require('fs').readFileSync(wasmPath) synchronously — no top-level await, no async init, no bundler config. Its package.json sets "type": "commonjs", and node's ESM-CJS interop means import * as cedar from '@cedar-policy/cedar-wasm/nodejs' works too (the namespace additionally carries default and a literal module.exports key, which is normal CJS-interop noise — destructure named exports and ignore it).
chant's existing vitest.config.ts already sets environment: "node" with the forks pool, so /nodejs drops in with no config change. Confirmed: 3/3 vitest tests pass in 96 ms, and bun test passes the /nodejs case.
/web is only worth reaching for if a jest-style environment breaks the others; it requires initSync(wasmBuffer) before any call, otherwise every function throws Cannot read properties of undefined (reading '__wbindgen_free').
Monorepo note. The wasm binary is 4.2 MB per flavor, 12 MB for all three, and npm workspaces hoist to the root node_modules. One copy for the whole repo. But if lexicons/cedar declares the dep and a consumer app installs chant, they get all 12 MB including the two flavors nobody uses — there is no way to install a subset.
Load cost is negligible (~5 ms, ~13 MB RSS). Validating a 200-policy set costs ~13 ms steady-state. There is no caching between validate calls — schema and policies are re-parsed every time — but at this scale that does not warrant reaching for the preparse* cache, which is thread-local and adds lifecycle management for a single-digit-millisecond saving. Keep validate stateless in post-synth.
4. Recommendation
Canonical schema syntax for codegen input: human-readable .cedarschema, normalized to resolved JSON before codegen reads it
Authored form should be the human-readable syntax. Reasons, in order of weight:
It is what a human reviews in a PR. The JSON form of the same tiny schema is roughly 4x the bytes and buries memberOfTypes and appliesTo in nesting. The epic sells cedar-lexicon as a typed authoring layer; the input it reads should be the form people actually author.
schemaToJsonWithResolvedTypes only accepts the human-readable string. The single most codegen-useful function in the package is available exclusively on that path. Going JSON-first means either hand-rolling EntityOrCommon resolution or converting back to text first.
Conversion to JSON is free, lossless, and idempotent (verified §1), so nothing is given up. The reverse — treating JSON as canonical and generating text for review — loses schemaToJsonWithResolvedTypes and gains nothing.
Concretely for #1650: accept *.cedarschema as the declared input, call schemaToJsonWithResolvedTypes(text) once, and drive the TS emitters off the resolved SchemaJson. Emit {type:"Entity",name:"Ns::T"} as a reference to the generated entity class, {type:"String"|"Long"|"Boolean"} as primitives, {type:"Set",element} as arrays, required:false as optional properties. Accept a JSON schema as a secondary input if a user has one, but funnel it through schemaToText → schemaToJsonWithResolvedTypes so the codegen path stays single. Codegen input keys are already sorted (see §5), so generated output is deterministic without extra sorting.
Serialized artifact next to .cedar text: the wasm's PolicySet JSON envelope, with each policy in Cedar's JSON policy format
Cedar has a standard JSON representation for a single policy (PolicyJson) but no standard on-disk format for a policy set. The PolicySet shape the wasm already accepts is the natural envelope, and it round-trips (artifact.mjs):
and rendering it back through policyToText/templateToText produces text that re-parses.
Why this and not something chant-shaped: it is the only JSON a Cedar tool will accept without translation, it needs zero adaptation to be fed to validate in post-synth, it preserves template links (which per-policy JSON files cannot express), and it satisfies the walk-away test — the staticPolicies values are literally Cedar's documented JSON policy format, extractable one-by-one for AVP's CreatePolicy API.
Emit .cedar text as the human-facing artifact and this JSON as the machine-facing one, both generated from the same in-memory model. Generate the .cedar text via formatPolicies on the serializer's output rather than via policyToText — policyToText produces single-line, over-parenthesized text that nobody wants to read in a diff, whereas formatPolicies is idempotent and produces conventional layout.
For the content pin (src/spec/pin.ts pattern, chant#1390): digest the extracted content — the resolved-JSON schema and the covered entity-type/action names beside it. Both are byte-deterministic (§5), so a digest is stable.
5. What will surprise an implementer
Ranked by how much damage each one does if missed.
1. type: "success" does not mean the policies are valid. The single biggest trap, and it will silently pass a broken post-synth check.
r.type = success but validationErrors.length = 1
ValidationAnswer is {type:"failure", errors, warnings} | {type:"success", validationErrors, validationWarnings, otherWarnings}. failure means the call failed (parse error, malformed input). success means validation ran — and can carry any number of validation errors. #1651 must check r.type === "success" && r.validationErrors.length === 0. A check written as if (r.type === "failure") fail() passes every type error in the corpus.
2. validationErrors array ordering is non-deterministic. Same input, same process, 40 identical calls (determinism.mjs):
The validator parallelizes across policies and does not re-sort. Any golden test or snapshot over validation output must sort first — by policyId, then message. This will otherwise produce a test that fails maybe one run in three, which is the worst possible failure mode to debug.
Everything else is deterministic: schemaToJson, schemaToText, and policyToJson each produced exactly 1 distinct serialization over 25 runs, with keys sorted (entityTypes: ['Alpha','Repo','Zeta'] from source order Zeta/Alpha/Repo; attributes ['a','m','z']; annotations ['a','z']). Rust BTreeMap ordering, safe to digest.
3. Malformed input sometimes throws instead of returning a failure answer. The Answer union is not the whole error channel. Missing required fields on a call struct throw a bare JS Error from serde (robust.mjs):
checkParsePolicySet(undefined) -> THREW Error: invalid type: null, expected struct PolicySet at line 1 column 4
validate({}) -> THREW Error: missing field `schema` at line 1 column 2
validate(missing schema) -> THREW Error: missing field `schema` at line 1 column 68
formatPolicies({}) -> THREW Error: missing field `policyText` at line 1 column 2
isAuthorized({}) -> THREW Error: missing field `principal` at line 1 column 2
versus the same category of problem returning cleanly elsewhere:
checkParseSchema(123) -> {"type":"failure", ...}
policyToJson("") -> {"type":"failure", ...}
statefulIsAuthorized(missing) -> {"type":"failure","errors":[{"message":"preparsed policy set 'nope' not found"...
The "line 1 column N" in the thrown message refers to the internal serialized call struct, not the user's policy — it is meaningless to surface. Wrap every wasm call in try/catch and normalize both channels into one result type.
4. Non-string input to schemaToJsonWithResolvedTypes traps the wasm. Not a graceful error — a memory fault (resolved.mjs, trap.mjs):
withResolvedTypes(JS object) -> THREW memory access out of bounds
input 123 -> THREW memory access out of bounds
input {"a":1} -> THREW memory access out of bounds
input undefined -> THREW Cannot read properties of undefined (reading 'length')
input [] -> success (!)
The good news: it is recoverable. After the trap, getCedarVersion, checkParseSchema, validate, and schemaToJsonWithResolvedTypes(validString) all still work — the instance is not poisoned. Still, guard with typeof x === "string" before the call; and note [] returning success means the function does not validate its input shape at all.
5. sourceLocations are BYTE offsets, not character offsets. Verified by placing multi-byte characters ahead of the error (offsets.mjs):
Any code turning a DetailedError into an editor range or a ^^^^ underline must go through Buffer.from(text,'utf8'), not String.prototype.slice. Silent and wrong the moment a policy contains a non-ASCII annotation or string literal — which is exactly the kind of thing that shows up in a @description in production and not in a test fixture.
6. Error messages are genuinely good; the structured fields mostly are not. Messages carry did you mean suggestions:
message: "for policy `chant.bad`, attribute `levl` on entity type `Chant::User` not found"
help: "did you mean `level`?"
message: "for policy `p`, unrecognized entity type `N::Ghost`"
help: "did you mean `N::R`?"
But code, url, and severity were null on every error and warning observed across all runs. Do not build lint-rule mapping on error.code — it is never populated. Map on message-prefix or on the check that produced it. related was always [].
7. permissive and partial validation modes do not exist in this build.ValidationMode is typed as "strict" and only "strict" — anything else throws unknown variant 'permissive', expected 'strict'. Omitting validationSettings gives the same result as {mode:"strict"}. The Cedar Rust SDK has more modes; the wasm bindings expose one.
8. permit(principal, action, resource); produces no warning. The epic's DoD names a meta-policy wall for exactly this, and the validator will not help:
Bare permit warning? {"type":"success","validationErrors":[],"validationWarnings":[],"otherWarnings":[]}
That wall has to be chant's own check over the PolicyJson (principal.op === "All" && action.op === "All" && resource.op === "All" && conditions.length === 0). The good news is the other wall in the DoD — "a policy referencing an entity type or action absent from the schema fails everywhere" — is fully covered by the validator (three errors including "unable to find an applicable action given the policy scope constraints").
The validator does emit warnings for some things — an always-false policy gets policy is impossible: the policy expression evaluates to false for all valid requests — so validationWarnings is worth surfacing, just not relied on.
9. A raw-string policy set gets synthesized IDs.staticPolicies as a bare string means Cedar assigns policy0, policy1, … in source order, and @id("...") annotations do not become the policy ID — they stay as ordinary annotations. Error messages then reference policy1, which is useless in a build log. Always pass staticPolicies as a Record<PolicyId, Policy> with chant's own IDs so diagnostics name something meaningful.
10. Minor. No init/async step for /nodejs — call functions immediately after require. No global state except the preparse* thread-local caches, which are per-process under vitest's forks pool (so no cross-test bleed, but also no sharing). The preparse cache is keyed by caller-supplied string with no eviction — a long-lived process that preparses per build leaks. formatPolicies defaults are lineWidth: 80, indentWidth: 2 when omitted.
Correction to the verification report from #1664 implementation: schemaToJsonWithResolvedTypes does NOT fully resolve common types in attribute position in 4.12.0 — it returns e.g. {"type":"App::TagSet"} with the definition left in commonTypes. Codegen closes the remaining hop itself (resolveTypeRef with a cycle guard in lexicons/cedar/src/codegen/). Everything else in the report held up in implementation.
Second correction from #1666 implementation: policySetTextToParts does NOT sort by id as the report claimed — it preserves source order and returns each policy's verbatim source text (which is what makes byte-identical round-trip achievable). Also: formatPolicies does not strip policyToText's defensive parens, so the JSON leg alone can never reproduce authored condition text — #1666 adds a delimiter scanner whose extractions are verified against policyToJson trees before being trusted.
Activity
lex00 commentedon Aug 10, 2026
cedar-wasm 4.12.0 verification report
INTENTIUS/chant #1648 (cedar 1/8), epic #1645. Feeds #1650 (codegen) and #1651 (post-synth wasm validation).
Every claim below comes from a run in
/private/tmp/claude-501/-Users-alex-Documents-checkouts-intentius-chant/60bb59f7-9477-4028-b773-a0b9bd7966ba/scratchpad/cedar-wasm-lab/against a clean
npm install @cedar-policy/cedar-wasm@4.12.0, on node v24.13.1, npm 11.8.0, bun 1.3.6, vitest 4.1.10, darwin arm64. Scripts are named inline so they can be re-run.0. Pin facts
4.12.0npm view dist-tags→{"latest":"4.12.0","v3.4-x":"3.4.3"}npm view timegetCedarVersion()4.12.0getCedarSDKVersion()4.12.0getCedarLangVersion()4.5npm view dist.unpackedSizesha512-tCSj92hh4fnmas4ojO4tjx8wAAW3mKVgQ7M388NsSpXp64FVeYY6xwhKtJRaaYGK0qLiN2jnq8/SNIU2r5fdPw==npm view dist.integritycedar-wasmcrate)The distinction that matters for
upstreamPin: the package is 4.12.0, the language it implements is 4.5. These move independently — the epic says "Cedar language 4.x", and 4.5 is the precise number to record. Pin both;getCedarLangVersion()is the value a drift check should assert, since a package bump that leaves lang at 4.5 cannot change grammar acceptance.Release cadence over the last six months: 4.9.0 (Feb 10), 4.10.0 (Apr 23), 4.11.0 (May 18), 4.11.1 (Jun 9), 4.11.2 (Jun 23), 4.12.0 (Jul 28). Roughly monthly, so an upgrade op will be exercised.
There is no separate
@cedar-policy/cedar-wasmtypes package;.d.tsships in-tree, so no@types/*pin is needed.1. API surface
24 exports, all synchronous, all plain functions. No classes, no async, no init step (for the
nodejsand root flavors). Full signatures are innode_modules/@cedar-policy/cedar-wasm/esm/cedar_wasm.d.ts(427 lines, hand-verified below).Functions chant will use
The two union types everything hangs off
Schema format: both, with one sharp edge
Both formats parse. But
stringalways means human-readable.cedarschema, never JSON. JSON must be passed as a live JS object.Run (
schema.mjs):JSON.parsebefore handing a.cedarschema.jsonfile to the wasm — otherwise you get a confusing "unexpected token{" pointing at valid JSON. The same rule applies toschemaToJson,schemaToText, andvalidate({ schema }). Verifiedvalidateagainst a JS-object schema produces identical results to the human-readable form (2 errors both ways).Related trap:
checkParseSchema("")andcheckParseSchema({})both returnsuccess— an empty schema is legal Cedar. Do not use "did it parse" as a proxy for "is there a schema".Policy text ⇄ JSON fidelity: semantic, not byte-level
Round-tripped a policy carrying two annotations,
is ... in,action in [..], twowhenclauses, twounlessclauses,has,like, and a>=(roundtrip.mjs).Everything semantic survives.
PolicyJsoncaptured all four clauses in order with correctkind: "when"|"unless", theis+inprincipal constraint as{op:"is", entity_type, in:{entity}}, the action set as{op:"in", entities:[...]}, andlike "10.*"as aPatternElem[]of[{Literal:"1"},{Literal:"0"},{Literal:"."},"Wildcard"].What changes on the way back to text:
@id,@doccame back@doc,@id. They serialize into a sorted map, so authored order is not recoverable.when { ((context.mfa) == true) && ((principal.level) >= 3) }.policyToText(policyToJson("// hello\npermit(...);"))→"permit(principal, action, resource);". Comments are not in the JSON grammar at all.Value: true/Value: 3— literals keep their JS types, no stringification.formatPoliciesis a separate and much better pretty-printer: it preserves annotation order, preserves comments ("// hello\npermit (principal, action, resource);\n"), emits multi-line scope blocks, and is idempotent. It operates on text only — it cannot consumePolicyJson.So the honest fidelity statement for the epic's round-trip DoD (
TS → .cedar → JSON → regenerated TS): the JSON leg is semantically lossless and idempotent, but it is not a formatting-preserving representation. Golden tests must comparepolicyToJsonoutput (deterministic, see §5) orformatPoliciesoutput, never rawpolicyToTextagainst an authored file.Schema round-trip fidelity
Tested with common types, an enum entity, an optional attribute, entity tags, and an action annotation (
schema-rt.mjs):Lossless in both directions after one normalization pass.
schemaToJsonvsschemaToJsonWithResolvedTypes— the codegen-relevant differenceThis is the finding that most directly shapes #1650.
schemaToJsonemitsEntityOrCommonfor every named type, which is ambiguous: you cannot tell an entity reference from a primitive from a common-type alias without resolving it yourself againstcommonTypesandentityTypes.schemaToJsonWithResolvedTypesdoes that resolution (resolved.mjs):It also fully qualifies namespaces (
Chant::User,Chant::GroupinmemberOfTypes) and resolves extension types ({"type":"datetime"}instead of{"type":"EntityOrCommon","name":"datetime"}). Its output re-parses as a valid schema (checkParseSchema(rt.json) -> success).Caveat: its signature is
(schema_str: string)and it means it — passing a JS object traps the wasm (see §5).Templates
Templates work end to end (
templates.mjs).templateToJson/templateToTextround-trip a two-slot template byte-identically (it was already in canonical form). APolicySetwithtemplates+templateLinksvalidates clean and authorizes:isAuthorized via template link -> success allow ["link1"].policySetTextToPartscorrectly separates a mixed file intopolicies[]andpolicy_templates[], sorted by id.isAuthorizedas a test harnessWorks, and is ergonomic enough for example tests (
authz.mjs):EntityUidaccepts both{type,id}and{__entity:{type,id}}. Entity attributes that are entity references need the__entitywrapper ({owner:{__entity:{type:'Chant::Repo',id:'core'}}}); bare{type,id}in an attribute position is read as a record.validateRequest: truecatches inapplicable requests but reports them as a top-levelfailure, not adeny— an invalid request and a broken policy set surface through the same channel.getValidRequestEnvsPolicygives coverage analysis for free, which is exactly what the epic's "every declared bucket is covered by at least one forbid" checks need:2. Module flavor under vitest / node / bun
Three subpackages, and they are not interchangeable. Results (
load-cjs.cjs,load-esm.mjs,bun-test.ts,vt/cedar.test.ts,bt/cedar.bun.test.ts):esm)/nodejs(cjs)/webrequire()ERR_PACKAGE_PATH_NOT_EXPORTEDimport()initSyncenvironment: "node", forks)initSyncbun runinitSyncbun testinitSyncRecommendation: import
@cedar-policy/cedar-wasm/nodejseverywhere. It is the only flavor that works under all four loaders.The two failures in detail.
Root/
esmunder Bun — this is the one that matters, since chant's CLAUDE.md describes the project as "TypeScript on Bun":The
esmflavor doesimport * as wasm from "./cedar_wasm_bg.wasm"— a WebAssembly ESM module import. Bun's implementation does not expose the wasm start function, so the module dies at import time. Node supports it but printsExperimentalWarning: Importing WebAssembly module instances is an experimental feature and might change at any timeon every run, which will pollute chant's test output.Root under CJS
require:The root
exports["."]map declares onlyimportandtypes, norequire— despite the root package.json still carrying a vestigial"main": "cedar_wasm.js"that points at a file which does not exist at the root. Any tooling that falls back tomainwill chase a phantom./nodejsloads the wasm withrequire('fs').readFileSync(wasmPath)synchronously — no top-level await, no async init, no bundler config. Itspackage.jsonsets"type": "commonjs", and node's ESM-CJS interop meansimport * as cedar from '@cedar-policy/cedar-wasm/nodejs'works too (the namespace additionally carriesdefaultand a literalmodule.exportskey, which is normal CJS-interop noise — destructure named exports and ignore it).chant's existing
vitest.config.tsalready setsenvironment: "node"with the forks pool, so/nodejsdrops in with no config change. Confirmed: 3/3 vitest tests pass in 96 ms, andbun testpasses the/nodejscase./webis only worth reaching for if a jest-style environment breaks the others; it requiresinitSync(wasmBuffer)before any call, otherwise every function throwsCannot read properties of undefined (reading '__wbindgen_free').Monorepo note. The wasm binary is 4.2 MB per flavor, 12 MB for all three, and npm workspaces hoist to the root
node_modules. One copy for the whole repo. But iflexicons/cedardeclares the dep and a consumer app installs chant, they get all 12 MB including the two flavors nobody uses — there is no way to install a subset.3. Performance and footprint
Measured in
perf.mjs:Load cost is negligible (~5 ms, ~13 MB RSS). Validating a 200-policy set costs ~13 ms steady-state. There is no caching between
validatecalls — schema and policies are re-parsed every time — but at this scale that does not warrant reaching for thepreparse*cache, which is thread-local and adds lifecycle management for a single-digit-millisecond saving. Keepvalidatestateless in post-synth.4. Recommendation
Canonical schema syntax for codegen input: human-readable
.cedarschema, normalized to resolved JSON before codegen reads itAuthored form should be the human-readable syntax. Reasons, in order of weight:
memberOfTypesandappliesToin nesting. The epic sells cedar-lexicon as a typed authoring layer; the input it reads should be the form people actually author.schemaToJsonWithResolvedTypesonly accepts the human-readable string. The single most codegen-useful function in the package is available exclusively on that path. Going JSON-first means either hand-rollingEntityOrCommonresolution or converting back to text first.schemaToJsonWithResolvedTypesand gains nothing.Concretely for #1650: accept
*.cedarschemaas the declared input, callschemaToJsonWithResolvedTypes(text)once, and drive the TS emitters off the resolvedSchemaJson. Emit{type:"Entity",name:"Ns::T"}as a reference to the generated entity class,{type:"String"|"Long"|"Boolean"}as primitives,{type:"Set",element}as arrays,required:falseas optional properties. Accept a JSON schema as a secondary input if a user has one, but funnel it throughschemaToText→schemaToJsonWithResolvedTypesso the codegen path stays single. Codegen input keys are already sorted (see §5), so generated output is deterministic without extra sorting.Serialized artifact next to
.cedartext: the wasm'sPolicySetJSON envelope, with each policy in Cedar's JSON policy formatCedar has a standard JSON representation for a single policy (
PolicyJson) but no standard on-disk format for a policy set. ThePolicySetshape the wasm already accepts is the natural envelope, and it round-trips (artifact.mjs):{ "staticPolicies": { "<id>": <PolicyJson>, ... }, "templates": { "<id>": <PolicyJson with slots>, ... }, "templateLinks": [ { "templateId": "...", "newId": "...", "values": { "?principal": {...} } } ] }Verified this exact document, built entirely from
policyToJson/templateToJsonoutput:and rendering it back through
policyToText/templateToTextproduces text that re-parses.Why this and not something chant-shaped: it is the only JSON a Cedar tool will accept without translation, it needs zero adaptation to be fed to
validatein post-synth, it preserves template links (which per-policy JSON files cannot express), and it satisfies the walk-away test — thestaticPoliciesvalues are literally Cedar's documented JSON policy format, extractable one-by-one for AVP'sCreatePolicyAPI.Emit
.cedartext as the human-facing artifact and this JSON as the machine-facing one, both generated from the same in-memory model. Generate the.cedartext viaformatPolicieson the serializer's output rather than viapolicyToText—policyToTextproduces single-line, over-parenthesized text that nobody wants to read in a diff, whereasformatPoliciesis idempotent and produces conventional layout.For the content pin (
src/spec/pin.tspattern, chant#1390): digest the extracted content — the resolved-JSON schema and the covered entity-type/action names beside it. Both are byte-deterministic (§5), so a digest is stable.5. What will surprise an implementer
Ranked by how much damage each one does if missed.
1.
type: "success"does not mean the policies are valid. The single biggest trap, and it will silently pass a broken post-synth check.ValidationAnsweris{type:"failure", errors, warnings}|{type:"success", validationErrors, validationWarnings, otherWarnings}.failuremeans the call failed (parse error, malformed input).successmeans validation ran — and can carry any number of validation errors. #1651 must checkr.type === "success" && r.validationErrors.length === 0. A check written asif (r.type === "failure") fail()passes every type error in the corpus.2.
validationErrorsarray ordering is non-deterministic. Same input, same process, 40 identical calls (determinism.mjs):The validator parallelizes across policies and does not re-sort. Any golden test or snapshot over validation output must sort first — by
policyId, thenmessage. This will otherwise produce a test that fails maybe one run in three, which is the worst possible failure mode to debug.Everything else is deterministic:
schemaToJson,schemaToText, andpolicyToJsoneach produced exactly 1 distinct serialization over 25 runs, with keys sorted (entityTypes: ['Alpha','Repo','Zeta']from source order Zeta/Alpha/Repo; attributes['a','m','z']; annotations['a','z']). RustBTreeMapordering, safe to digest.3. Malformed input sometimes throws instead of returning a failure answer. The
Answerunion is not the whole error channel. Missing required fields on a call struct throw a bare JSErrorfrom serde (robust.mjs):versus the same category of problem returning cleanly elsewhere:
The
"line 1 column N"in the thrown message refers to the internal serialized call struct, not the user's policy — it is meaningless to surface. Wrap every wasm call in try/catch and normalize both channels into one result type.4. Non-string input to
schemaToJsonWithResolvedTypestraps the wasm. Not a graceful error — a memory fault (resolved.mjs,trap.mjs):The good news: it is recoverable. After the trap,
getCedarVersion,checkParseSchema,validate, andschemaToJsonWithResolvedTypes(validString)all still work — the instance is not poisoned. Still, guard withtypeof x === "string"before the call; and note[]returningsuccessmeans the function does not validate its input shape at all.5.
sourceLocationsare BYTE offsets, not character offsets. Verified by placing multi-byte characters ahead of the error (offsets.mjs):Any code turning a
DetailedErrorinto an editor range or a^^^^underline must go throughBuffer.from(text,'utf8'), notString.prototype.slice. Silent and wrong the moment a policy contains a non-ASCII annotation or string literal — which is exactly the kind of thing that shows up in a@descriptionin production and not in a test fixture.6. Error messages are genuinely good; the structured fields mostly are not. Messages carry
did you meansuggestions:But
code,url, andseveritywerenullon every error and warning observed across all runs. Do not build lint-rule mapping onerror.code— it is never populated. Map on message-prefix or on the check that produced it.relatedwas always[].7.
permissiveandpartialvalidation modes do not exist in this build.ValidationModeis typed as"strict"and only"strict"— anything else throwsunknown variant 'permissive', expected 'strict'. OmittingvalidationSettingsgives the same result as{mode:"strict"}. The Cedar Rust SDK has more modes; the wasm bindings expose one.8.
permit(principal, action, resource);produces no warning. The epic's DoD names a meta-policy wall for exactly this, and the validator will not help:That wall has to be chant's own check over the
PolicyJson(principal.op === "All" && action.op === "All" && resource.op === "All" && conditions.length === 0). The good news is the other wall in the DoD — "a policy referencing an entity type or action absent from the schema fails everywhere" — is fully covered by the validator (three errors including "unable to find an applicable action given the policy scope constraints").The validator does emit warnings for some things — an always-false policy gets
policy is impossible: the policy expression evaluates to false for all valid requests— sovalidationWarningsis worth surfacing, just not relied on.9. A raw-string policy set gets synthesized IDs.
staticPoliciesas a bare string means Cedar assignspolicy0,policy1, … in source order, and@id("...")annotations do not become the policy ID — they stay as ordinary annotations. Error messages then referencepolicy1, which is useless in a build log. Always passstaticPoliciesas aRecord<PolicyId, Policy>with chant's own IDs so diagnostics name something meaningful.10. Minor. No init/async step for
/nodejs— call functions immediately after require. No global state except thepreparse*thread-local caches, which are per-process under vitest's forks pool (so no cross-test bleed, but also no sharing). Thepreparsecache is keyed by caller-supplied string with no eviction — a long-lived process that preparses per build leaks.formatPoliciesdefaults arelineWidth: 80,indentWidth: 2when omitted.Appendix: lab contents
/private/tmp/claude-501/-Users-alex-Documents-checkouts-intentius-chant/60bb59f7-9477-4028-b773-a0b9bd7966ba/scratchpad/cedar-wasm-lab/load-cjs.cjs,load-esm.mjsbun-test.ts,bt/cedar.bun.test.tsbun testvt/cedar.test.ts,vitest.config.tsexports.mjsschema.mjsschema-rt.mjsresolved.mjsschemaToJsonvsschemaToJsonWithResolvedTypesroundtrip.mjsvalidate.mjsPolicySetshapes, error qualitydeterminism.mjsstability.mjsauthz.mjsisAuthorized, entities, context, request validationtemplates.mjspolicySetTextToPartsartifact.mjsPolicySetas a serialized artifactrobust.mjs,trap.mjsoffsets.mjsperf.mjsmisc.mjslex00 commentedon Aug 10, 2026
Correction to the verification report from #1664 implementation:
schemaToJsonWithResolvedTypesdoes NOT fully resolve common types in attribute position in 4.12.0 — it returns e.g.{"type":"App::TagSet"}with the definition left incommonTypes. Codegen closes the remaining hop itself (resolveTypeRefwith a cycle guard in lexicons/cedar/src/codegen/). Everything else in the report held up in implementation.lex00 commentedon Aug 10, 2026
Verification report archived above; the code half (upstreamPin, content pin over resolved JSON, cedar-upgrade.op.ts) landed in #1664. Done.
feat(cedar): schema-driven codegen + configSchema + upstream pin (#1650)
lex00 commentedon Aug 10, 2026
Second correction from #1666 implementation:
policySetTextToPartsdoes NOT sort by id as the report claimed — it preserves source order and returns each policy's verbatim source text (which is what makes byte-identical round-trip achievable). Also:formatPoliciesdoes not strippolicyToText's defensive parens, so the JSON leg alone can never reproduce authored condition text — #1666 adds a delimiter scanner whose extractions are verified againstpolicyToJsontrees before being trusted.feat(cedar): schema-driven codegen + configSchema + upstream pin (#1650…
feat(cedar): dogwood CLI-gated validation split (#1659)
feat(cedar): dogwood CLI-gated validation split (#1659)
feat(cedar): dogwood CLI-gated validation split (#1659) (#1677)