2026-10-11 03:50:23 +02:00
import assert from "node:assert/strict" ;
2026-10-11 03:54:30 +02:00
import { existsSync } from "node:fs" ;
2026-10-11 03:50:23 +02:00
import { mkdtemp , readFile , writeFile } from "node:fs/promises" ;
import { tmpdir } from "node:os" ;
import { join , resolve } from "node:path" ;
import { test } from "node:test" ;
import { decode , encode } from "@msgpack/msgpack" ;
import { z } from "zod" ;
import { codecs } from "../src" ;
2026-10-11 09:18:18 +02:00
import { MAX_SLOT_KEY , type Codec } from "../src/codec" ;
2026-10-11 03:50:23 +02:00
import { CultCache } from "../src/cult-cache" ;
2026-10-11 04:49:13 +02:00
import { readWire , WireFloat , writeWire } from "../src/wire" ;
2026-10-12 00:01:59 +02:00
import {
CultCachePayloadDepthError ,
MAX_PAYLOAD_DEPTH ,
decodeDocumentPayload ,
defineDocumentType ,
documentPayloadBytes ,
documentPayloadFromBytes ,
encodeDocumentPayload ,
} from "../src/document" ;
2026-10-11 03:50:23 +02:00
import { SingleFileMessagePackBackingStore } from "../src/single-file-messagepack-backing-store" ;
2026-10-11 04:55:22 +02:00
import type { AnyCultCacheDocumentDefinition , CacheBackingStore , CultCacheEnvelope } from "../src/types" ;
2026-10-11 03:50:23 +02:00
2026-10-11 04:49:13 +02:00
const { array , boolean , bytes , float32 , float64 , int32 , int64 , lazy , list , nullable , slots , string , union , unit } = codecs ;
// The names the C# reference gives the fixture's types (CultSchemaTypeNames.FromType), as union-surface.cc carries them.
const CS = "GameCult.Caching.Tests.UnionParityVectorTests+" ;
2026-10-11 03:50:23 +02:00
// The golden is tests/vectors/union-parity, written by the C# reference. Everything below that is bytes or an expected
// outcome is read from those committed files; only the value the payload must decode to is spelled here.
2026-10-11 03:54:30 +02:00
function findVectors ( from : string ) : string {
for ( let dir = from ; ; dir = resolve ( dir , ".." ) ) {
if ( existsSync ( join ( dir , "tests" , "vectors" , "union-parity" ) ) ) return join ( dir , "tests" , "vectors" , "union-parity" ) ;
if ( resolve ( dir , ".." ) === dir ) throw new Error ( "tests/vectors/union-parity not found above the test." ) ;
}
}
const vectors = findVectors ( __dirname ) ;
2026-10-11 03:50:23 +02:00
const read = async ( name : string ) = > new Uint8Array ( await readFile ( join ( vectors , name ) ) ) ;
// The string the C# writer put inside every refusal payload, to prove a refusal never echoes the payload.
const CANARY = "CANARY-union-golden-4c2a" ;
type Node =
| { kind : "Box" ; id : string ; children : ( Node | null ) [ ] }
| { kind : "Text" ; id : string ; content : string }
| { kind : "Use" ; id : string ; composition : Composition ; slots : ( Node | null ) [ ] }
2026-10-12 00:01:59 +02:00
| { kind : "Image" ; id : string ; uri : string ; alt : string }
2026-10-14 19:44:28 +02:00
| { kind : "Wrap" ; inner : Node | null ; id : string } ;
2026-10-11 03:50:23 +02:00
interface Composition { name : string ; body : Node | null }
2026-10-12 00:01:59 +02:00
type Outcome = { kind : "Pending" ; message : string } | { kind : "Completed" ; sourceVersion : number } | { kind : "Denied" } | { kind : "Floor" } | { kind : "Ceiling" } ;
2026-10-14 19:44:28 +02:00
// The golden's Outcome: the arms of a list carry an element id, so Denied, Floor and Ceiling are one-slot records.
type GoldenOutcome =
| { kind : "Pending" ; message : string ; id : string }
| { kind : "Completed" ; sourceVersion : number ; id : string }
| { kind : "Denied" ; id : string }
| { kind : "Floor" ; id : string }
| { kind : "Ceiling" ; id : string } ;
2026-10-11 03:50:23 +02:00
type Item = { kind : "Gem" ; name : string } | { kind : "Tool" ; name : string ; uses : number } | { kind : "Part" ; name : string ; count : number } ;
type CraftedItem = { kind : "Tool" ; name : string ; uses : number } | { kind : "Part" ; name : string ; count : number } ;
interface Surface {
id : string ;
version : number ;
root : Node | null ;
2026-10-14 19:46:22 +02:00
outcomes : ( GoldenOutcome | null ) [ ] ;
2026-10-11 03:50:23 +02:00
part : Item | null ;
crafted : CraftedItem | null ;
missing : Node | null ;
}
2026-10-11 04:49:13 +02:00
const composition = slots < Composition > ( { 0 : [ "name" , string ] , 1 : [ "body" , lazy ( ( ) = > node ) ] } , ` ${ CS } Composition ` ) ;
2026-10-11 03:51:11 +02:00
const node : Codec < Node | null > = union < Node > ( "Node" , {
2026-10-11 03:50:23 +02:00
0 : [ "Box" , slots < { id : string ; children : ( Node | null ) [ ] } > ( { 0 : [ "id" , string ] , 1 : [ "children" , list ( lazy ( ( ) = > node ) ) ] } ) ] ,
1 : [ "Text" , slots < { id : string ; content : string } > ( { 0 : [ "id" , string ] , 1 : [ "content" , string ] } ) ] ,
2 : [ "Use" , slots < { id : string ; composition : Composition ; slots : ( Node | null ) [ ] } > ( {
0 : [ "id" , string ] , 1 : [ "composition" , composition ] , 2 : [ "slots" , list ( lazy ( ( ) = > node ) ) ] ,
} ) ] ,
5 : [ "Image" , slots < { id : string ; uri : string ; alt : string } > ( { 0 : [ "id" , string ] , 1 : [ "uri" , string ] , 3 : [ "alt" , string ] } ) ] ,
2026-10-14 19:44:28 +02:00
6 : [ "Wrap" , slots < { inner : Node | null ; id : string } > ( { 0 : [ "inner" , lazy ( ( ) = > node ) ] , 1 : [ "id" , string ] } ) ] ,
2026-10-11 04:49:13 +02:00
} , ` ${ CS } Node ` ) ;
2026-10-11 03:50:23 +02:00
const outcome = union < Outcome > ( "Outcome" , {
0 : [ "Pending" , slots < { message : string } > ( { 0 : [ "message" , string ] } ) ] ,
2026-10-11 04:49:13 +02:00
1 : [ "Completed" , slots < { sourceVersion : number } > ( { 0 : [ "sourceVersion" , int32 ] } ) ] ,
2026-10-11 03:50:23 +02:00
2 : [ "Denied" , unit ] ,
2026-10-12 00:01:59 +02:00
[ - 2147483648 ] : [ "Floor" , unit ] ,
2147483647 : [ "Ceiling" , unit ] ,
2026-10-11 04:49:13 +02:00
} , ` ${ CS } Outcome ` ) ;
2026-10-14 19:44:28 +02:00
const idOnly = slots < { id : string } > ( { 0 : [ "id" , string ] } ) ;
const goldenOutcome = union < GoldenOutcome > ( "Outcome" , {
0 : [ "Pending" , slots < { message : string ; id : string } > ( { 0 : [ "message" , string ] , 1 : [ "id" , string ] } ) ] ,
1 : [ "Completed" , slots < { sourceVersion : number ; id : string } > ( { 0 : [ "sourceVersion" , int32 ] , 1 : [ "id" , string ] } ) ] ,
2 : [ "Denied" , idOnly ] ,
[ - 2147483648 ] : [ "Floor" , idOnly ] ,
2147483647 : [ "Ceiling" , idOnly ] ,
} , ` ${ CS } Outcome ` ) ;
2026-10-11 04:49:13 +02:00
const toolArm = slots < { name : string ; uses : number } > ( { 0 : [ "name" , string ] , 1 : [ "uses" , int32 ] } ) ;
const partArm = slots < { name : string ; count : number } > ( { 0 : [ "name" , string ] , 1 : [ "count" , int32 ] } ) ;
2026-10-11 03:50:23 +02:00
const item = union < Item > ( "Item" , {
0 : [ "Gem" , slots < { name : string } > ( { 0 : [ "name" , string ] } ) ] ,
1 : [ "Tool" , toolArm ] ,
2 : [ "Part" , partArm ] ,
2026-10-11 04:49:13 +02:00
} , ` ${ CS } Item ` ) ;
const craftedItem = union < CraftedItem > ( "CraftedItem" , { 0 : [ "Tool" , toolArm ] , 1 : [ "Part" , partArm ] } , ` ${ CS } CraftedItem ` ) ;
2026-10-11 03:50:23 +02:00
const surfaceCodec = slots < Surface > ( {
0 : [ "id" , string ] ,
2026-10-11 04:49:13 +02:00
1 : [ "version" , int32 ] ,
2026-10-11 03:50:23 +02:00
2 : [ "root" , node ] ,
2026-10-14 19:44:28 +02:00
3 : [ "outcomes" , list ( goldenOutcome ) ] ,
2026-10-11 03:50:23 +02:00
4 : [ "part" , item ] ,
5 : [ "crafted" , craftedItem ] ,
6 : [ "missing" , node , null ] ,
2026-10-11 04:49:13 +02:00
} , ` ${ CS } UnionSurface ` ) ;
2026-10-11 03:50:23 +02:00
const nodeSchema : z.ZodType < Node | null > = z . lazy ( ( ) = >
z . union ( [
z . null ( ) ,
z . discriminatedUnion ( "kind" , [
z . object ( { kind : z.literal ( "Box" ) , id : z.string ( ) , children : z.array ( nodeSchema ) } ) ,
z . object ( { kind : z.literal ( "Text" ) , id : z.string ( ) , content : z.string ( ) } ) ,
z . object ( {
kind : z.literal ( "Use" ) ,
id : z.string ( ) ,
composition : z.object ( { name : z.string ( ) , body : nodeSchema } ) ,
slots : z.array ( nodeSchema ) ,
} ) ,
z . object ( { kind : z.literal ( "Image" ) , id : z.string ( ) , uri : z.string ( ) , alt : z.string ( ) } ) ,
2026-10-14 19:44:28 +02:00
z . object ( { kind : z.literal ( "Wrap" ) , inner : nodeSchema , id : z.string ( ) } ) ,
2026-10-11 03:50:23 +02:00
] ) ,
] ) ) ;
const surfaceSchema = z . object ( {
id : z.string ( ) ,
version : z.number ( ) ,
root : nodeSchema ,
outcomes : z.array ( z . union ( [
z . null ( ) ,
z . discriminatedUnion ( "kind" , [
2026-10-14 19:44:28 +02:00
z . object ( { kind : z.literal ( "Pending" ) , message : z.string ( ) , id : z.string ( ) } ) ,
z . object ( { kind : z.literal ( "Completed" ) , sourceVersion : z.number ( ) , id : z.string ( ) } ) ,
z . object ( { kind : z.literal ( "Denied" ) , id : z.string ( ) } ) ,
z . object ( { kind : z.literal ( "Floor" ) , id : z.string ( ) } ) ,
z . object ( { kind : z.literal ( "Ceiling" ) , id : z.string ( ) } ) ,
2026-10-11 03:50:23 +02:00
] ) ,
] ) ) ,
part : z.union ( [ z . null ( ) , z . discriminatedUnion ( "kind" , [
z . object ( { kind : z.literal ( "Gem" ) , name : z.string ( ) } ) ,
z . object ( { kind : z.literal ( "Tool" ) , name : z.string ( ) , uses : z.number ( ) } ) ,
z . object ( { kind : z.literal ( "Part" ) , name : z.string ( ) , count : z.number ( ) } ) ,
] ) ] ) ,
crafted : z.union ( [ z . null ( ) , z . discriminatedUnion ( "kind" , [
z . object ( { kind : z.literal ( "Tool" ) , name : z.string ( ) , uses : z.number ( ) } ) ,
z . object ( { kind : z.literal ( "Part" ) , name : z.string ( ) , count : z.number ( ) } ) ,
] ) ] ) ,
missing : nodeSchema ,
} ) as unknown as z . ZodType < Surface > ;
function surfaceDocument ( schemaId? : string ) {
return defineDocumentType ( {
type : "tests.union_surface" ,
schemaId : schemaId ? ? "tests.union_surface.v1" ,
schemaName : "tests.union_surface" ,
schemaVersion : "tests.union_surface.v1" ,
schema : surfaceSchema ,
codec : surfaceCodec ,
name : "id" ,
} ) ;
}
const golden : Surface = {
id : "surface" ,
version : 3 ,
root : {
kind : "Box" ,
2026-10-14 19:44:28 +02:00
id : "0000000000c0" ,
2026-10-11 03:50:23 +02:00
children : [
2026-10-14 19:44:28 +02:00
{ kind : "Text" , id : "0000000000c1" , content : "hello" } ,
2026-10-11 03:50:23 +02:00
{
kind : "Use" ,
2026-10-14 19:44:28 +02:00
id : "0000000000c2" ,
2026-10-11 03:50:23 +02:00
composition : {
name : "comp" ,
body : {
kind : "Box" ,
2026-10-14 19:44:28 +02:00
id : "0000000000d0" ,
2026-10-11 03:50:23 +02:00
children : [
2026-10-14 19:44:28 +02:00
{ kind : "Text" , id : "0000000000d1" , content : "x" } ,
{ kind : "Image" , id : "0000000000d2" , uri : "uri://a" , alt : "alt" } ,
2026-10-11 03:50:23 +02:00
] ,
} ,
} ,
2026-10-14 19:44:28 +02:00
slots : [ { kind : "Text" , id : "0000000000e1" , content : "slot" } , null , { kind : "Box" , id : "0000000000e2" , children : [ ] } ] ,
2026-10-11 03:50:23 +02:00
} ,
2026-10-14 19:44:28 +02:00
{ kind : "Image" , id : "0000000000c3" , uri : "uri://b" , alt : "" } ,
2026-10-11 03:50:23 +02:00
] ,
} ,
2026-10-14 19:44:28 +02:00
outcomes : [
{ kind : "Pending" , message : "wait" , id : "0000000000a1" } ,
{ kind : "Completed" , sourceVersion : 7 , id : "0000000000a2" } ,
{ kind : "Denied" , id : "0000000000a3" } ,
] ,
2026-10-11 03:50:23 +02:00
part : { kind : "Tool" , name : "hammer" , uses : 12 } ,
crafted : { kind : "Part" , name : "gear" , count : 4 } ,
missing : null ,
} ;
const hex = ( data : Uint8Array ) = > Buffer . from ( data ) . toString ( "hex" ) ;
async function outcomeEntries() {
const entries = decode ( await read ( "outcomes.msgpack" ) ) as [ string , string , string , number | null , string ] [ ] ;
return entries . map ( ( [ file , outcome , unionName , key , detail ] ) = > ( { file , outcome , unionName , key , detail } ) ) ;
}
test ( "the union surface vector decodes to the constructed value and re-encodes byte-identical" , async ( ) = > {
const committed = await read ( "union-surface.msgpack" ) ;
2026-10-11 04:49:13 +02:00
const decoded = surfaceCodec . decode ( readWire ( committed ) ) ;
2026-10-11 03:50:23 +02:00
assert . deepEqual ( decoded , golden ) ;
2026-10-11 04:49:13 +02:00
assert . equal ( hex ( writeWire ( surfaceCodec . encode ( decoded ) ) ) , hex ( committed ) ) ;
assert . equal ( hex ( writeWire ( surfaceCodec . encode ( golden ) ) ) , hex ( committed ) ) ;
2026-10-11 03:50:23 +02:00
} ) ;
2026-10-14 20:33:24 +02:00
test ( "a unit arm is written as the C# reference writes it, and its payload must be an array" , async ( ) = > {
// The bytes are tests/vectors/union-parity/unit-arm-*.msgpack, written by the reference, not spelled here.
for ( const [ file , kind ] of [ [ "denied" , "Denied" ] , [ "floor" , "Floor" ] , [ "ceiling" , "Ceiling" ] ] as const ) {
const reference = await read ( ` unit-arm- ${ file } .msgpack ` ) ;
assert . deepEqual ( outcome . decode ( readWire ( reference ) ) , { kind } , file ) ;
assert . equal ( hex ( writeWire ( outcome . encode ( { kind } ) ) ) , hex ( reference ) , file ) ;
}
2026-10-11 03:50:23 +02:00
assert . throws ( ( ) = > outcome . decode ( [ 2 , null ] ) , / U n i o n O u t c o m e / u ) ;
} ) ;
test ( "union-surface.cc reads through SingleFileMessagePackBackingStore and writes the same payload" , async ( ) = > {
const dir = await mkdtemp ( join ( tmpdir ( ) , "union-parity-" ) ) ;
const file = join ( dir , "union-surface.cc" ) ;
await writeFile ( file , await read ( "union-surface.cc" ) ) ;
const [ envelope ] = await new SingleFileMessagePackBackingStore ( file ) . pullAll ( ) ;
One typed owner of document-payload reads and writes: DocumentPayload is opaque, the definition is required
DocumentPayload is an opaque object type over the same runtime Uint8Array, keyed by a string
property, and types CultCacheEnvelope.payload, CultNetRawDocumentRecord.payload and
CultMeshRealtimeFrame.payload. decodeDocumentPayload(definition, payload) and
encodeDocumentPayload(definition, value) are the only reader and writer; documentPayloadFromBytes
and documentPayloadBytes are the two named escapes at the edges where bytes enter and leave.
resolveDocumentFormatter leaves the package index. The cache, cultnet replication, the mesh read
paths, the provider command (now a CultCache document), and the browser's decodeCultNetPayload
(definition required, cultcache-ts/document entry) all go through the owner.
Compile-fail fixtures per payload-carrying package pin the type with expect-error lines.
check-typescript-tests-wired.mjs fails when a test file is run by no script; cultcache-ts now
runs dist-test/test/*.test.js, and the portability workflow runs the check and the cache suite.
Builds in every package (tsc, src and tests); the suites run once, at the end of the pass.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-11 19:33:42 +02:00
assert . equal ( hex ( documentPayloadBytes ( envelope . payload ) ) , hex ( await read ( "union-surface.msgpack" ) ) ) ;
2026-10-11 03:50:23 +02:00
const document = surfaceDocument ( envelope . schemaId ) ;
const cache = CultCache . builder ( ) . withDocumentType ( document ) . withGenericStore ( new SingleFileMessagePackBackingStore ( file ) ) . build ( ) ;
await cache . pullAllBackingStores ( ) ;
assert . deepEqual ( cache . get ( document , envelope . key ) , golden ) ;
const written = join ( dir , "written.cc" ) ;
const fresh = CultCache . builder ( ) . withDocumentType ( document ) . withGenericStore ( new SingleFileMessagePackBackingStore ( written ) ) . build ( ) ;
await fresh . put ( document , envelope . key , golden ) ;
const [ rewritten ] = await new SingleFileMessagePackBackingStore ( written ) . pullAll ( ) ;
One typed owner of document-payload reads and writes: DocumentPayload is opaque, the definition is required
DocumentPayload is an opaque object type over the same runtime Uint8Array, keyed by a string
property, and types CultCacheEnvelope.payload, CultNetRawDocumentRecord.payload and
CultMeshRealtimeFrame.payload. decodeDocumentPayload(definition, payload) and
encodeDocumentPayload(definition, value) are the only reader and writer; documentPayloadFromBytes
and documentPayloadBytes are the two named escapes at the edges where bytes enter and leave.
resolveDocumentFormatter leaves the package index. The cache, cultnet replication, the mesh read
paths, the provider command (now a CultCache document), and the browser's decodeCultNetPayload
(definition required, cultcache-ts/document entry) all go through the owner.
Compile-fail fixtures per payload-carrying package pin the type with expect-error lines.
check-typescript-tests-wired.mjs fails when a test file is run by no script; cultcache-ts now
runs dist-test/test/*.test.js, and the portability workflow runs the check and the cache suite.
Builds in every package (tsc, src and tests); the suites run once, at the end of the pass.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-11 19:33:42 +02:00
assert . equal ( hex ( documentPayloadBytes ( rewritten . payload ) ) , hex ( documentPayloadBytes ( envelope . payload ) ) ) ;
2026-10-11 04:51:51 +02:00
// The reference refuses a store whose schema catalog names another type for a slot, so the catalog TS writes must be
// the one C# wrote: same canonical schema text, same member names, slots and types.
assert . equal ( rewritten . catalogEntry ! . canonicalSchemaJson , envelope . catalogEntry ! . canonicalSchemaJson ) ;
const shape = ( members : readonly { slot : number ; memberName : string ; typeName : string ; isName? : boolean } [ ] ) = >
members . map ( ( member ) = > [ member . slot , member . memberName , member . typeName , member . isName === true ] ) ;
assert . deepEqual ( shape ( rewritten . catalogEntry ! . members ! ) , shape ( envelope . catalogEntry ! . members ! ) ) ;
assert . equal ( rewritten . catalogEntry ! . members ! . length , 7 ) ;
2026-10-11 03:50:23 +02:00
} ) ;
test ( "every outcome vector is listed and holds: refusals name the union and key, never the payload" , async ( ) = > {
const entries = await outcomeEntries ( ) ;
assert . equal ( entries . length , 9 ) ;
const document = surfaceDocument ( ) ;
let refused = 0 ;
2026-10-11 03:51:37 +02:00
const carrying : string [ ] = [ ] ;
2026-10-11 03:50:23 +02:00
let readOnly = 0 ;
for ( const { file , outcome : expected , unionName , key , detail } of entries ) {
const payload = await read ( file ) ;
if ( expected === "refused" ) {
refused += 1 ;
2026-10-11 03:51:37 +02:00
if ( Buffer . from ( payload ) . includes ( CANARY ) ) carrying . push ( file ) ;
2026-10-11 03:50:23 +02:00
assert . throws (
2026-10-11 04:49:13 +02:00
( ) = > surfaceCodec . decode ( readWire ( payload ) ) ,
2026-10-11 03:50:23 +02:00
( error : Error ) = > {
assert . ok ( ! error . message . includes ( CANARY ) , ` ${ file } : the refusal echoed the payload ` ) ;
if ( detail === "arity" ) {
return error . message . includes ( ` Union ${ unionName } ` ) && error . message . includes ( "expected [key, slots]" ) ;
}
return error . message . includes ( ` Union ${ unionName } : ` ) && error . message . includes ( ` key ${ key } ` ) ;
} ,
file ,
) ;
const refusingCache = CultCache . builder ( ) . withDocumentType ( document ) . withGenericStore ( memoryStore ( [ envelopeOf ( payload ) ] ) ) . build ( ) ;
await assert . rejects ( ( ) = > refusingCache . pullAllBackingStores ( ) , new RegExp ( ` Union ${ unionName } ` , "u" ) , file ) ;
} else {
readOnly += 1 ;
assert . equal ( expected , "read-only" ) ;
2026-10-11 04:49:13 +02:00
assert . deepEqual ( surfaceCodec . decode ( readWire ( payload ) ) , golden , ` ${ file } : the extra slot is read past ` ) ;
2026-10-11 03:50:23 +02:00
}
}
assert . deepEqual ( [ refused , readOnly ] , [ 5 , 4 ] ) ;
2026-10-11 03:51:37 +02:00
assert . deepEqual ( carrying , [ "unknown-arm-field.msgpack" , "unknown-arm-list.msgpack" , "unknown-arm-nested.msgpack" ] , "the canary is in the payloads whose arm is unknown" ) ;
2026-10-11 03:50:23 +02:00
} ) ;
test ( "a refusal lists the declared keys, so a key only the outer union declares is unknown to the inner" , async ( ) = > {
const entry = ( await outcomeEntries ( ) ) . find ( ( candidate ) = > candidate . file === "inner-union-outer-key.msgpack" ) ! ;
2026-10-11 04:49:13 +02:00
const payload = readWire ( await read ( entry . file ) ) as unknown [ ] ;
2026-10-11 03:50:23 +02:00
assert . throws (
( ) = > surfaceCodec . decode ( payload ) ,
/ U n i o n C r a f t e d I t e m : u n k n o w n a r m k e y 2 \ ( d e c l a r e d k e y s : 0 , 1 \ ) \ . / u ,
) ;
} ) ;
test ( "an arm that is not [key, slots] is refused naming the union, and a non-integer key is not echoed" , ( ) = > {
for ( const bad of [ [ 1 ] , [ 1 , null ] , [ 1 , [ ] , [ ] ] , "x" , 7 , { } ] ) {
assert . throws ( ( ) = > node . decode ( bad ) , / ^ E r r o r : U n i o n N o d e : e x p e c t e d \ [ k e y , s l o t s \ ] / u ) ;
}
assert . throws (
( ) = > node . decode ( [ CANARY , [ ] ] ) ,
( error : Error ) = > error . message . includes ( "Union Node" ) && error . message . includes ( "not an integer" ) && ! error . message . includes ( CANARY ) ,
) ;
} ) ;
test ( "an arm key that is not a declared key is refused, with no fallback" , ( ) = > {
2026-10-12 00:01:59 +02:00
assert . throws ( ( ) = > node . decode ( [ 4 , [ ] ] ) , / U n i o n N o d e : u n k n o w n a r m k e y 4 \ ( d e c l a r e d k e y s : 0 , 1 , 2 , 5 , 6 \ ) / u ) ;
2026-10-11 03:50:23 +02:00
assert . throws ( ( ) = > outcome . decode ( [ 3 , [ ] ] ) , / U n i o n O u t c o m e : u n k n o w n a r m k e y 3 / u ) ;
} ) ;
test ( "a union encodes by kind and refuses a kind it does not declare without echoing it" , ( ) = > {
assert . deepEqual ( node . encode ( { kind : "Text" , id : "a" , content : "b" } ) , [ 1 , [ "a" , "b" ] ] ) ;
assert . equal ( node . encode ( null ) , null ) ;
assert . throws (
( ) = > node . encode ( { kind : CANARY , id : "a" } as unknown as Node ) ,
( error : Error ) = > error . message . includes ( "Union Node" ) && ! error . message . includes ( CANARY ) ,
) ;
} ) ;
test ( "slots: a gap writes nil, a missing slot reads its default, one without a default is refused naming the slot" , ( ) = > {
2026-10-11 04:49:13 +02:00
const record = slots < { a : string ; c : string ; d : number } > ( { 0 : [ "a" , string ] , 2 : [ "c" , string ] , 4 : [ "d" , int32 , 9 ] } ) ;
2026-10-11 03:50:23 +02:00
assert . deepEqual ( record . encode ( { a : "x" , c : "y" , d : 1 } ) , [ "x" , null , "y" , null , 1 ] ) ;
assert . deepEqual ( record . decode ( [ "x" , null , "y" ] ) , { a : "x" , c : "y" , d : 9 } ) ;
2026-10-11 21:05:09 +02:00
assert . deepEqual ( record . decode ( [ "x" , 5 , "y" , null ] ) , { a : "x" , c : "y" , d : 9 } ) ;
assert . throws ( ( ) = > record . decode ( [ "x" , 5 , "y" , null , null ] ) , { message : "d (slot 4): expected an int32, found nil" } ) ;
2026-10-11 03:50:23 +02:00
assert . throws ( ( ) = > record . decode ( [ "x" ] ) , / c \ ( s l o t 2 \ ) : t h e s l o t i s m i s s i n g a n d d e c l a r e s n o d e f a u l t / u ) ;
assert . deepEqual ( record . decode ( [ "x" , null , "y" , null , 1 , "extra" , "slots" ] ) , { a : "x" , c : "y" , d : 1 } ) ;
assert . throws ( ( ) = > record . decode ( { a : "x" } ) , / e x p e c t e d a n a r r a y o f s l o t s / u ) ;
} ) ;
2026-10-11 21:05:09 +02:00
test ( "slots: a default may be a function and fills only a missing slot, never a nil" , ( ) = > {
2026-10-11 03:50:23 +02:00
const record = slots < { tags : string [ ] } > ( { 0 : [ "tags" , list ( string ) , ( ) = > [ "fresh" ] ] } ) ;
assert . deepEqual ( record . decode ( [ ] ) , { tags : [ "fresh" ] } ) ;
2026-10-11 21:05:09 +02:00
assert . deepEqual ( record . decode ( [ null ] ) , { tags : null } ) ;
const counted = slots < { n : number } > ( { 0 : [ "n" , int32 , 4 ] } ) ;
assert . deepEqual ( counted . decode ( [ ] ) , { n : 4 } ) ;
assert . throws ( ( ) = > counted . decode ( [ null ] ) , { message : "n (slot 0): expected an int32, found nil" } ) ;
2026-10-11 03:50:23 +02:00
} ) ;
test ( "a slot refusal names the field and slot and never the value" , ( ) = > {
const record = slots < { name : string } > ( { 3 : [ "name" , string ] } ) ;
assert . throws (
( ) = > record . decode ( [ null , null , null , { secret : CANARY } ] ) ,
( error : Error ) = > error . message . startsWith ( "name (slot 3):" ) && ! error . message . includes ( CANARY ) ,
) ;
} ) ;
2026-10-11 04:03:04 +02:00
test ( "leaf codecs refuse the wrong shape on both sides, saying what was expected and what kind was found" , ( ) = > {
const table : [ string , Codec < unknown > , string , unknown , string ] [ ] = [
[ "string" , string , "a string" , 5 , "number" ] ,
2026-10-11 04:49:13 +02:00
[ "int32" , int32 , "an int32" , "5" , "string" ] ,
[ "int32" , int32 , "an int32" , Number . POSITIVE_INFINITY , "a non-integer number" ] ,
[ "int32" , int32 , "an int32" , Number . NaN , "a non-integer number" ] ,
[ "int32" , int32 , "an int32" , 1.5 , "a non-integer number" ] ,
[ "int32" , int32 , "an int32" , 2 * * 31 , "an integer out of range" ] ,
[ "int64" , int64 , "an int64" , 2 * * 53 , "a number beyond 2^53, which needs a bigint" ] ,
[ "int64" , int64 , "an int64" , 2 n * * 63 n , "an integer out of range" ] ,
[ "float64" , float64 , "a float64" , "1.5" , "string" ] ,
[ "float32" , float32 , "a float32" , null , "nil" ] ,
2026-10-11 04:03:04 +02:00
[ "boolean" , boolean , "a boolean" , "true" , "string" ] ,
[ "bytes" , bytes , "bytes" , [ 1 , 2 ] , "array" ] ,
[ "string" , string , "a string" , null , "nil" ] ,
[ "list" , list ( string ) , "an array" , "abc" , "string" ] ,
] ;
for ( const [ label , codec , what , bad , found ] of table ) {
for ( const side of [ "encode" , "decode" ] as const ) {
2026-10-11 04:49:13 +02:00
// Decode sees the wire's shapes: a JS float or a number beyond 2^53 never arrives from a payload.
if ( side === "decode" && ( typeof bad === "number" && ( ! Number . isInteger ( bad ) || Math . abs ( bad ) >= 2 * * 53 ) ) ) continue ;
2026-10-11 04:51:51 +02:00
assert . throws ( ( ) = > codec [ side ] ( bad ) , { message : ` expected ${ what } , found ${ found } ` } , ` ${ label } ${ side } ` ) ;
2026-10-11 04:03:04 +02:00
}
}
2026-10-11 04:49:13 +02:00
for ( const [ codec , good ] of [ [ string , "s" ] , [ int32 , 1 ] , [ int64 , 5 ] , [ float64 , 1.5 ] , [ float32 , 1.5 ] , [ boolean , false ] , [ bytes , new Uint8Array ( [ 7 ] ) ] , [ list ( int32 ) , [ 1 , 2 ] ] ] as [ Codec < unknown > , unknown ] [ ] ) {
2026-10-11 04:03:04 +02:00
assert . deepEqual ( codec . decode ( codec . encode ( good ) ) , good ) ;
}
} ) ;
test ( "a list element refusal names the element, and nullable writes nil for null and undefined" , ( ) = > {
2026-10-11 04:49:13 +02:00
const numbers = list ( int32 ) ;
assert . throws ( ( ) = > numbers . encode ( [ 1 , "x" as unknown as number ] ) , / ^ E r r o r : e l e m e n t 1 : e x p e c t e d a n i n t 3 2 , f o u n d s t r i n g $ / u ) ;
assert . throws ( ( ) = > numbers . decode ( [ 1 , 2 , null ] ) , / ^ E r r o r : e l e m e n t 2 : e x p e c t e d a n i n t 3 2 , f o u n d n i l $ / u ) ;
const maybe = nullable ( int32 ) ;
2026-10-11 04:03:04 +02:00
assert . equal ( maybe . encode ( null ) , null ) ;
assert . equal ( maybe . encode ( undefined as unknown as null ) , null ) ;
assert . equal ( maybe . encode ( 0 ) , 0 ) ;
assert . equal ( maybe . decode ( null ) , null ) ;
assert . equal ( maybe . decode ( 0 ) , 0 ) ;
2026-10-11 04:49:13 +02:00
assert . throws ( ( ) = > maybe . decode ( "x" ) , / e x p e c t e d a n i n t 3 2 / u ) ;
2026-10-11 04:03:04 +02:00
} ) ;
test ( "a record refuses what is not a record and names the field and slot of a bad value" , ( ) = > {
const record = slots < { name : string } > ( { 3 : [ "name" , string ] } ) ;
assert . throws ( ( ) = > record . encode ( null as unknown as { name : string } ) , / ^ E r r o r : e x p e c t e d a r e c o r d , f o u n d n i l $ / u ) ;
assert . throws ( ( ) = > record . encode ( "x" as unknown as { name : string } ) , / ^ E r r o r : e x p e c t e d a r e c o r d , f o u n d s t r i n g $ / u ) ;
assert . throws ( ( ) = > record . encode ( { name : 5 as unknown as string } ) , / ^ E r r o r : n a m e \ ( s l o t 3 \ ) : e x p e c t e d a s t r i n g , f o u n d n u m b e r $ / u ) ;
} ) ;
test ( "a union names itself, its arm and the field when an arm's slots are refused" , ( ) = > {
assert . throws ( ( ) = > node . encode ( { kind : "Text" , id : "a" , content : 5 as unknown as string } ) , / ^ E r r o r : a r m T e x t : c o n t e n t \ ( s l o t 1 \ ) : e x p e c t e d a s t r i n g , f o u n d n u m b e r $ / u ) ;
assert . throws ( ( ) = > node . decode ( [ 1 , [ "a" , 5 ] ] ) , / ^ E r r o r : a r m T e x t : c o n t e n t \ ( s l o t 1 \ ) : e x p e c t e d a s t r i n g , f o u n d n u m b e r $ / u ) ;
assert . equal ( node . encode ( undefined as unknown as null ) , null ) ;
assert . throws (
( ) = > node . encode ( { kind : "Nope" } as unknown as Node ) ,
2026-10-12 00:05:27 +02:00
/ ^ E r r o r : U n i o n N o d e : t h e v a l u e ' s k i n d i s n o t o n e o f i t s a r m s \ ( B o x , T e x t , U s e , I m a g e , W r a p \ ) \ . $ / u ,
2026-10-11 04:03:04 +02:00
) ;
} ) ;
test ( "slot names become catalog member names in Pascal case" , ( ) = > {
const record = slots < { _hidden : string ; two_words : string ; Mixed9 : string } > ( { 0 : [ "_hidden" , string ] , 1 : [ "two_words" , string ] , 2 : [ "Mixed9" , string ] } ) ;
assert . deepEqual ( record . members . map ( ( member ) = > member . memberName ) , [ "Hidden" , "TwoWords" , "Mixed9" ] ) ;
2026-10-11 03:50:23 +02:00
} ) ;
test ( "definitions are refused at definition time" , ( ) = > {
assert . throws ( ( ) = > union < { kind : "A" } > ( "U" , { 0 : [ "A" , slots < { kind : string } > ( { 0 : [ "kind" , string ] } ) ] } ) , / U n i o n U a r m " A " d e c l a r e s a s l o t n a m e d k i n d / u ) ;
assert . throws ( ( ) = > union < { kind : "A" | "B" } > ( "U" , { 0 : [ "A" , unit ] , 1 : [ "A" as "B" , unit ] } ) , / d e c l a r e s t h e a r m " A " t w i c e / u ) ;
2026-10-11 08:34:31 +02:00
assert . throws ( ( ) = > union < { kind : "A" } > ( "U" , { x : [ "A" , unit ] } as never ) , / ^ E r r o r : U n i o n U d e c l a r e s t h e k e y " x " , w h i c h i s n o t a n i n t e g e r \ . $ / u ) ;
2026-10-11 04:03:04 +02:00
assert . throws ( ( ) = > union < { kind : "A" } > ( "U" , { "01" : [ "A" , unit ] } as never ) , / k e y " 0 1 " / u ) ;
assert . throws ( ( ) = > union < { kind : "A" } > ( "U" , { "1.5" : [ "A" , unit ] } as never ) , / k e y " 1 \ . 5 " / u ) ;
assert . throws ( ( ) = > union < { kind : "A" } > ( "U" , { } as never ) , / ^ E r r o r : U n i o n U d e c l a r e s n o a r m s \ . $ / u ) ;
2026-10-11 03:50:23 +02:00
assert . throws ( ( ) = > slots < { a : string ; b : string } > ( { 0 : [ "a" , string ] , 1 : [ "a" as "b" , string ] } ) , / d e c l a r e s t h e f i e l d " a " t w i c e / u ) ;
assert . throws ( ( ) = > slots < { a : string } > ( { } ) , / d e c l a r e s n o s l o t s / u ) ;
2026-10-11 04:03:04 +02:00
assert . throws ( ( ) = > slots < { a : string } > ( { [ - 1 ] : [ "a" , string ] } ) , / ^ E r r o r : A s l o t r e c o r d d e c l a r e s t h e k e y " - 1 " / u ) ;
2026-10-11 03:50:23 +02:00
assert . throws (
( ) = > defineDocumentType ( {
type : "t" ,
schema : surfaceSchema ,
codec : surfaceCodec ,
formatter : { encode : ( ) = > new Uint8Array ( ) , decode : ( ) = > golden } ,
} ) ,
/ d e c l a r e s b o t h a c o d e c a n d a f o r m a t t e r / u ,
) ;
} ) ;
test ( "a codec supplies the document's catalog members unless it is given its own" , ( ) = > {
const document = defineDocumentType ( {
type : "t" ,
schema : z.object ( { a : z.string ( ) , the_b : z.string ( ) } ) ,
codec : slots < { a : string ; the_b : string } > ( { 0 : [ "a" , string ] , 3 : [ "the_b" , string ] } ) ,
name : "a" ,
indexes : { byB : "the_b" } ,
} ) ;
assert . deepEqual ( document . members , [
2026-10-11 04:49:13 +02:00
{ slot : 0 , memberName : "A" , typeName : "System.String" , isName : true , indexAlias : null } ,
{ slot : 3 , memberName : "TheB" , typeName : "System.String" , isName : false , indexAlias : "byB" } ,
2026-10-11 03:50:23 +02:00
] ) ;
const given = [ { slot : 9 , memberName : "Mine" , typeName : "System.String" } ] ;
const own = defineDocumentType ( { type : "t" , schema : z.object ( { a : z.string ( ) } ) , codec : slots < { a : string } > ( { 0 : [ "a" , string ] } ) , members : given } ) ;
assert . deepEqual ( own . members , given ) ;
} ) ;
test ( "schema.parse still runs on a decoded value, and a document without a codec still writes a map" , async ( ) = > {
const strict = defineDocumentType ( {
type : "t" ,
schema : z.object ( { a : z.string ( ) . min ( 3 ) } ) ,
codec : slots < { a : string } > ( { 0 : [ "a" , string ] } ) ,
} ) ;
One typed owner of document-payload reads and writes: DocumentPayload is opaque, the definition is required
DocumentPayload is an opaque object type over the same runtime Uint8Array, keyed by a string
property, and types CultCacheEnvelope.payload, CultNetRawDocumentRecord.payload and
CultMeshRealtimeFrame.payload. decodeDocumentPayload(definition, payload) and
encodeDocumentPayload(definition, value) are the only reader and writer; documentPayloadFromBytes
and documentPayloadBytes are the two named escapes at the edges where bytes enter and leave.
resolveDocumentFormatter leaves the package index. The cache, cultnet replication, the mesh read
paths, the provider command (now a CultCache document), and the browser's decodeCultNetPayload
(definition required, cultcache-ts/document entry) all go through the owner.
Compile-fail fixtures per payload-carrying package pin the type with expect-error lines.
check-typescript-tests-wired.mjs fails when a test file is run by no script; cultcache-ts now
runs dist-test/test/*.test.js, and the portability workflow runs the check and the cache suite.
Builds in every package (tsc, src and tests); the suites run once, at the end of the pass.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-11 19:33:42 +02:00
const store = memoryStore ( [ { key : "k" , type : "t" , payload : documentPayloadFromBytes ( encode ( [ "xy" ] ) ) , storedAt : new Date ( ) . toISOString ( ) } ] ) ;
2026-10-11 03:50:23 +02:00
await assert . rejects ( ( ) = > CultCache . builder ( ) . withDocumentType ( strict ) . withGenericStore ( store ) . build ( ) . pullAllBackingStores ( ) ) ;
const plain = defineDocumentType ( { type : "p" , schema : z.object ( { id : z.string ( ) } ) } ) ;
const holder = memoryStore ( [ ] ) ;
await CultCache . builder ( ) . withDocumentType ( plain ) . withGenericStore ( holder ) . build ( ) . put ( plain , "k" , { id : "d" } ) ;
One typed owner of document-payload reads and writes: DocumentPayload is opaque, the definition is required
DocumentPayload is an opaque object type over the same runtime Uint8Array, keyed by a string
property, and types CultCacheEnvelope.payload, CultNetRawDocumentRecord.payload and
CultMeshRealtimeFrame.payload. decodeDocumentPayload(definition, payload) and
encodeDocumentPayload(definition, value) are the only reader and writer; documentPayloadFromBytes
and documentPayloadBytes are the two named escapes at the edges where bytes enter and leave.
resolveDocumentFormatter leaves the package index. The cache, cultnet replication, the mesh read
paths, the provider command (now a CultCache document), and the browser's decodeCultNetPayload
(definition required, cultcache-ts/document entry) all go through the owner.
Compile-fail fixtures per payload-carrying package pin the type with expect-error lines.
check-typescript-tests-wired.mjs fails when a test file is run by no script; cultcache-ts now
runs dist-test/test/*.test.js, and the portability workflow runs the check and the cache suite.
Builds in every package (tsc, src and tests); the suites run once, at the end of the pass.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-11 19:33:42 +02:00
assert . deepEqual ( decode ( documentPayloadBytes ( holder . entries [ 0 ] . payload ) ) , { id : "d" } ) ;
2026-10-11 03:50:23 +02:00
} ) ;
test ( "bytes and nullable round-trip through a slot record" , ( ) = > {
const record = slots < { blob : Uint8Array ; maybe : string | null } > ( { 0 : [ "blob" , bytes ] , 1 : [ "maybe" , nullable ( string ) ] } ) ;
const wire = encode ( record . encode ( { blob : new Uint8Array ( [ 1 , 2 ] ) , maybe : null } ) ) ;
assert . deepEqual ( record . decode ( decode ( wire ) ) , { blob : new Uint8Array ( [ 1 , 2 ] ) , maybe : null } ) ;
assert . throws ( ( ) = > record . decode ( [ new Uint8Array ( ) , 4 ] ) , / m a y b e \ ( s l o t 1 \ ) : e x p e c t e d a s t r i n g / u ) ;
} ) ;
2026-10-11 04:51:51 +02:00
const fromHex = ( text : string ) = > new Uint8Array ( Buffer . from ( text , "hex" ) ) ;
// Arm keys are integers within Int32 in the reference: a float key is refused even when it holds a whole number, and a
// key outside Int32 is refused whether it is declared or read. Every payload below is [key, [7]] or [key, ["wait"]].
test ( "an arm key is an integer in any MessagePack integer encoding, and a float-typed key is refused" , ( ) = > {
const completed = { kind : "Completed" , sourceVersion : 7 } ;
for ( const key of [ "01" , "cc01" , "cd0001" , "ce00000001" , "cf0000000000000001" , "d001" , "d10001" , "d200000001" , "d30000000000000001" ] ) {
assert . deepEqual ( outcome . decode ( readWire ( fromHex ( ` 92 ${ key } 9107 ` ) ) ) , completed , key ) ;
}
for ( const key of [ "ca3f800000" , "cb3ff0000000000000" ] ) {
2026-10-12 00:01:59 +02:00
assert . throws ( ( ) = > outcome . decode ( readWire ( fromHex ( ` 92 ${ key } 9107 ` ) ) ) , { message : "Union Outcome: the arm key is not an integer (declared keys: -2147483648, 0, 1, 2, 2147483647)." } , key ) ;
2026-10-11 04:51:51 +02:00
}
assert . throws ( ( ) = > outcome . decode ( readWire ( fromHex ( "92cb800000000000000091a477616974" ) ) ) , / ^ E r r o r : U n i o n O u t c o m e : t h e a r m k e y i s n o t a n i n t e g e r / u , " - 0 . 0 i s a f l o a t , n o t k e y 0 " ) ;
for ( const key of [ "ce80000000" , "cf8000000000000000" , "d30000000080000000" ] ) {
2026-10-12 00:01:59 +02:00
assert . throws ( ( ) = > outcome . decode ( readWire ( fromHex ( ` 92 ${ key } 9107 ` ) ) ) , { message : "Union Outcome: the arm key is outside Int32 (declared keys: -2147483648, 0, 1, 2, 2147483647)." } , key ) ;
2026-10-11 04:51:51 +02:00
}
2026-10-12 00:01:59 +02:00
assert . throws ( ( ) = > outcome . decode ( readWire ( fromHex ( "92d2800000019107" ) ) ) , { message : "Union Outcome: unknown arm key -2147483647 (declared keys: -2147483648, 0, 1, 2, 2147483647)." } ) ;
assert . throws ( ( ) = > outcome . decode ( readWire ( fromHex ( "92ff9107" ) ) ) , { message : "Union Outcome: unknown arm key -1 (declared keys: -2147483648, 0, 1, 2, 2147483647)." } ) ;
2026-10-11 04:51:51 +02:00
} ) ;
test ( "a union refuses a declared arm key outside Int32" , ( ) = > {
assert . doesNotThrow ( ( ) = > union < { kind : "A" } > ( "U" , { 2147483647 : [ "A" , unit ] } ) ) ;
assert . throws ( ( ) = > union < { kind : "A" } > ( "U" , { 2147483648 : [ "A" , unit ] } ) , { message : "Union U declares the key 2147483648, which is outside Int32." } ) ;
assert . throws ( ( ) = > union < { kind : "A" } > ( "U" , { 3000000000 : [ "A" , unit ] } ) , / o u t s i d e I n t 3 2 / u ) ;
} ) ;
test ( "the wire reader keeps 64-bit integers whole, tells a float from an integer, and refuses what is not a value" , ( ) = > {
assert . equal ( readWire ( fromHex ( "cf0020000000000001" ) ) , 2 n * * 53 n + 1 n ) ;
assert . equal ( readWire ( fromHex ( "cf001fffffffffffff" ) ) , 2 * * 53 - 1 ) ;
assert . equal ( readWire ( fromHex ( "d38000000000000000" ) ) , - ( 2 n * * 63 n ) ) ;
assert . equal ( readWire ( fromHex ( "cfffffffffffffffff" ) ) , 2 n * * 64 n - 1 n ) ;
assert . ok ( readWire ( fromHex ( "cb3ff0000000000000" ) ) instanceof WireFloat ) ;
assert . ok ( readWire ( fromHex ( "ca3f800000" ) ) instanceof WireFloat ) ;
assert . equal ( readWire ( fromHex ( "01" ) ) , 1 ) ;
assert . throws ( ( ) = > readWire ( fromHex ( "92a161" ) ) , / t r u n c a t e d / u , " a n a r r a y t h a t p r o m i s e s m o r e t h a n t h e p a y l o a d h o l d s " ) ;
assert . throws ( ( ) = > readWire ( fromHex ( "dd" ) ) , / t r u n c a t e d / u ) ;
assert . throws ( ( ) = > readWire ( fromHex ( "ddffffffff" ) ) , / t r u n c a t e d / u , " a h u g e a r r a y h e a d e r r e s e r v e s n o t h i n g " ) ;
assert . throws ( ( ) = > readWire ( fromHex ( "a5616263" ) ) , / t r u n c a t e d / u ) ;
assert . throws ( ( ) = > readWire ( fromHex ( "0102" ) ) , / b y t e s a f t e r i t s v a l u e / u ) ;
assert . throws ( ( ) = > readWire ( fromHex ( "81a161a162" ) ) , / m a p , e x t e n s i o n o r r e s e r v e d / u ) ;
assert . throws ( ( ) = > readWire ( fromHex ( "c1" ) ) , / m a p , e x t e n s i o n o r r e s e r v e d / u ) ;
assert . throws ( ( ) = > readWire ( fromHex ( "d4010a" ) ) , / m a p , e x t e n s i o n o r r e s e r v e d / u ) ;
} ) ;
test ( "the wire writer writes the smallest integer, keeps a float's width, and round-trips what it reads" , ( ) = > {
const tree = [ 0 , 127 , 128 , 255 , 256 , 65535 , 65536 , 4294967295 , 4294967296 , - 1 , - 32 , - 33 , - 128 , - 129 , - 32768 , - 32769 , - 2147483648 , - 2147483649 ,
2 n * * 53 n , 2 n * * 64 n - 1 n , - ( 2 n * * 63 n ) , new WireFloat ( 1.5 , false ) , new WireFloat ( 1.5 , true ) , "" , "a" . repeat ( 31 ) , "a" . repeat ( 32 ) , "a" . repeat ( 256 ) ,
new Uint8Array ( 0 ) , new Uint8Array ( 300 ) , [ ] , null , true , false , "héllo" ] ;
assert . deepEqual ( readWire ( writeWire ( tree ) ) , tree ) ;
assert . equal ( hex ( writeWire ( 5 ) ) , "05" ) ;
assert . equal ( hex ( writeWire ( 128 ) ) , "cc80" ) ;
assert . equal ( hex ( writeWire ( - 33 ) ) , "d0df" ) ;
assert . equal ( hex ( writeWire ( 2 n * * 53 n + 2 n ) ) , "cf0020000000000002" ) ;
assert . equal ( hex ( writeWire ( new WireFloat ( 3 , true ) ) ) , "cb4008000000000000" ) ;
assert . equal ( hex ( writeWire ( new WireFloat ( 1.5 , false ) ) ) , "ca3fc00000" ) ;
assert . equal ( hex ( writeWire ( new Array ( 16 ) . fill ( null ) ) ) , ` dc0010 ${ "c0" . repeat ( 16 ) } ` ) ;
assert . throws ( ( ) = > writeWire ( 1.5 ) , / n o t a s a f e i n t e g e r / u ) ;
assert . throws ( ( ) = > writeWire ( 2 * * 53 ) , / n o t a s a f e i n t e g e r / u ) ;
assert . throws ( ( ) = > writeWire ( 2 n * * 64 n ) , / w i d e r t h a n 6 4 b i t s / u ) ;
assert . throws ( ( ) = > writeWire ( { } ) , / t h i s k i n d o f v a l u e / u ) ;
} ) ;
test ( "a codec and a formatter are refused together wherever the definition enters" , ( ) = > {
const both = { type : "t" , schema : surfaceSchema , codec : surfaceCodec , formatter : { encode : ( ) = > new Uint8Array ( ) , decode : ( ) = > golden } } ;
assert . throws ( ( ) = > defineDocumentType ( both ) , / d e c l a r e s b o t h a c o d e c a n d a f o r m a t t e r / u ) ;
assert . throws ( ( ) = > CultCache . builder ( ) . withDocumentType ( both ) , / d e c l a r e s b o t h a c o d e c a n d a f o r m a t t e r / u ) ;
assert . throws ( ( ) = > CultCache . builder ( ) . withRegistry ( [ both ] ) , / d e c l a r e s b o t h a c o d e c a n d a f o r m a t t e r / u ) ;
} ) ;
test ( "a definition that skips defineDocumentType still writes its codec's bytes and its derived catalog" , async ( ) = > {
2026-10-11 04:55:22 +02:00
const raw = { type : "tests.union_surface" , schemaId : "tests.union_surface.v1" , schema : surfaceSchema , codec : surfaceCodec , name : "id" } as unknown as AnyCultCacheDocumentDefinition ;
2026-10-11 04:51:51 +02:00
const holder = memoryStore ( [ ] ) ;
const cache = CultCache . builder ( ) . withDocumentType ( raw ) . withGenericStore ( holder ) . build ( ) ;
2026-10-11 04:55:22 +02:00
await cache . put ( raw as never , "surface" , golden as never ) ;
One typed owner of document-payload reads and writes: DocumentPayload is opaque, the definition is required
DocumentPayload is an opaque object type over the same runtime Uint8Array, keyed by a string
property, and types CultCacheEnvelope.payload, CultNetRawDocumentRecord.payload and
CultMeshRealtimeFrame.payload. decodeDocumentPayload(definition, payload) and
encodeDocumentPayload(definition, value) are the only reader and writer; documentPayloadFromBytes
and documentPayloadBytes are the two named escapes at the edges where bytes enter and leave.
resolveDocumentFormatter leaves the package index. The cache, cultnet replication, the mesh read
paths, the provider command (now a CultCache document), and the browser's decodeCultNetPayload
(definition required, cultcache-ts/document entry) all go through the owner.
Compile-fail fixtures per payload-carrying package pin the type with expect-error lines.
check-typescript-tests-wired.mjs fails when a test file is run by no script; cultcache-ts now
runs dist-test/test/*.test.js, and the portability workflow runs the check and the cache suite.
Builds in every package (tsc, src and tests); the suites run once, at the end of the pass.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-11 19:33:42 +02:00
assert . equal ( hex ( documentPayloadBytes ( holder . entries [ 0 ] . payload ) ) , hex ( await read ( "union-surface.msgpack" ) ) ) ;
2026-10-11 04:51:51 +02:00
const [ snapshot ] = cache . snapshot ( ) ;
assert . deepEqual ( snapshot . catalogEntry ! . members ! . map ( ( member ) = > member . typeName ) . slice ( 0 , 2 ) , [ "System.String" , "System.Int32" ] ) ;
} ) ;
test ( "every leaf and wrapper carries the reference's type name, and a catalog is not derived from a codec that cannot name a slot" , ( ) = > {
assert . deepEqual (
[ string , boolean , bytes , int32 , int64 , float32 , float64 ] . map ( ( codec ) = > codec . typeName ) ,
[ "System.String" , "System.Boolean" , "System.Byte[]" , "System.Int32" , "System.Int64" , "System.Single" , "System.Double" ] ,
) ;
assert . equal ( list ( int64 ) . typeName , "System.Collections.Generic.List<System.Int64>" ) ;
assert . equal ( array ( string ) . typeName , "System.String[]" ) ;
assert . equal ( nullable ( int32 ) . typeName , "System.Nullable<System.Int32>" ) ;
assert . equal ( nullable ( string ) . typeName , "System.String" ) ;
assert . equal ( nullable ( list ( string ) ) . typeName , "System.Collections.Generic.List<System.String>" ) ;
assert . equal ( list ( union < { kind : "A" } > ( "U" , { 0 : [ "A" , unit ] } ) ) . typeName , undefined ) ;
const unnamed = slots < { id : string ; what : { kind : "A" } | null } > ( { 0 : [ "id" , string ] , 1 : [ "what" , union < { kind : "A" } > ( "U" , { 0 : [ "A" , unit ] } ) ] } ) ;
assert . throws ( ( ) = > unnamed . members , / ^ E r r o r : w h a t \ ( s l o t 1 \ ) h a s n o C # t y p e n a m e f o r t h e s c h e m a c a t a l o g / u ) ;
assert . throws ( ( ) = > defineDocumentType ( { type : "t" , schema : z.any ( ) , codec : unnamed as never } ) , / w h a t \ ( s l o t 1 \ ) h a s n o C # t y p e n a m e / u ) ;
const given = defineDocumentType ( { type : "t" , schema : z.any ( ) , codec : unnamed as never , members : [ { slot : 0 , memberName : "Id" , typeName : "System.String" } ] } ) ;
assert . equal ( given . members ! . length , 1 ) ;
} ) ;
2026-10-11 08:34:31 +02:00
// tests/vectors/numeric-leaves is written by the C# reference (NumericLeafVectorTests): what it reads and refuses for each
// numeric leaf, and the bytes it writes.
const numericVectors = join ( vectors , ".." , "numeric-leaves" ) ;
2026-10-11 04:55:22 +02:00
const numericLeaves : Record < string , Codec < unknown > > = { int32 , int64 , float32 , float64 } ;
2026-10-11 08:34:31 +02:00
const doubleBitsHex = ( value : number ) = > {
const view = new DataView ( new ArrayBuffer ( 8 ) ) ;
view . setFloat64 ( 0 , value ) ;
return Buffer . from ( view . buffer ) . toString ( "hex" ) ;
} ;
const int64BitsHex = ( value : number | bigint ) = > BigInt . asUintN ( 64 , BigInt ( value ) ) . toString ( 16 ) . padStart ( 16 , "0" ) ;
const isNaNBits = ( bitsHex : string ) = > {
const bits = BigInt ( ` 0x ${ bitsHex } ` ) ;
return ( ( bits >> 52 n ) & 0x7ff n ) === 0x7ff n && ( bits & ( ( 1 n << 52 n ) - 1 n ) ) !== 0 n ;
} ;
2026-10-11 04:55:22 +02:00
2026-10-11 09:18:18 +02:00
const isSignallingFloat32 = ( payload : Uint8Array ) = > {
// payload is a one-slot record [float32]: 91 ca b0 b1 b2 b3
if ( payload . length !== 6 || payload [ 1 ] !== 0xca ) return false ;
const bits = new DataView ( payload . buffer , payload . byteOffset ) . getUint32 ( 2 ) ;
return ( bits & 0x7f800000 ) === 0x7f800000 && ( bits & 0x007fffff ) !== 0 && ( bits & 0x00400000 ) === 0 ;
} ;
2026-10-11 08:34:31 +02:00
test ( "numeric leaves read and refuse exactly what the C# reference does" , async ( ) = > {
const rows = readWire ( new Uint8Array ( await readFile ( join ( numericVectors , "reads.msgpack" ) ) ) ) as [ string , Uint8Array , boolean , Uint8Array ] [ ] ;
2026-10-11 09:18:18 +02:00
assert . equal ( rows . length , 160 ) ;
2026-10-11 04:55:22 +02:00
let accepted = 0 ;
let refused = 0 ;
2026-10-11 08:34:31 +02:00
for ( const [ leaf , payload , wasAccepted , bits ] of rows ) {
const label = ` ${ leaf } ${ hex ( payload ) } ` ;
2026-10-11 04:55:22 +02:00
const record = slots < { v : unknown } > ( { 0 : [ "v" , numericLeaves [ leaf ] ] } ) ;
2026-10-11 09:18:18 +02:00
if ( wasAccepted && leaf === "float32" && isSignallingFloat32 ( payload ) ) {
// The one reading that differs from the reference: it reads a float32 signalling NaN, this runtime refuses it
// (float32-nan.msgpack shows the reference keeps its bits, which a JS number cannot).
assert . throws ( ( ) = > record . decode ( readWire ( payload ) ) , ( error : Error ) = > ! error . message . includes ( hex ( payload ) . slice ( 2 ) ) , label ) ;
refused += 1 ;
} else if ( wasAccepted ) {
2026-10-11 08:34:31 +02:00
const read = record . decode ( readWire ( payload ) ) . v as number | bigint ;
const wanted = hex ( bits ) ;
if ( leaf . startsWith ( "float" ) ) {
if ( isNaNBits ( wanted ) ) assert . ok ( Number . isNaN ( read ) , label ) ;
else assert . equal ( doubleBitsHex ( read as number ) , wanted , label ) ;
} else {
assert . equal ( int64BitsHex ( read ) , wanted , label ) ;
}
2026-10-11 04:55:22 +02:00
accepted += 1 ;
2026-10-11 08:34:31 +02:00
} else {
assert . throws ( ( ) = > record . decode ( readWire ( payload ) ) , ( error : Error ) = > ! error . message . includes ( hex ( payload ) . slice ( 2 ) ) , label ) ;
2026-10-11 04:55:22 +02:00
refused += 1 ;
}
}
2026-10-11 08:34:31 +02:00
assert . ok ( accepted > 40 && refused > 40 , ` accepted ${ accepted } , refused ${ refused } ` ) ;
assert . equal ( accepted + refused , rows . length ) ;
2026-10-11 04:55:22 +02:00
} ) ;
2026-10-11 09:18:18 +02:00
// float32-nan.msgpack: [payload, bytes the reference writes after reading it] for a float32 slot holding an infinity or a NaN.
// The reference keeps every payload bit; a JS number cannot keep a signalling NaN's, so that read is refused.
test ( "a float32 NaN round-trips with its bits, and a signalling one is refused on read" , async ( ) = > {
const rows = readWire ( new Uint8Array ( await readFile ( join ( numericVectors , "float32-nan.msgpack" ) ) ) ) as [ Uint8Array , Uint8Array ] [ ] ;
assert . equal ( rows . length , 6 ) ;
const record = slots < { v : number } > ( { 0 : [ "v" , float32 ] } ) ;
let refused = 0 ;
for ( const [ payload , rewritten ] of rows ) {
if ( isSignallingFloat32 ( payload ) ) {
assert . equal ( hex ( rewritten ) , hex ( payload ) , "the reference keeps the signalling bits" ) ;
assert . throws ( ( ) = > record . decode ( readWire ( payload ) ) , { message : "v (slot 0): expected a float32, found a signalling NaN" } , hex ( payload ) ) ;
refused += 1 ;
} else {
assert . equal ( hex ( writeWire ( record . encode ( record . decode ( readWire ( payload ) ) ) ) ) , hex ( rewritten ) , hex ( payload ) ) ;
}
}
assert . equal ( refused , 3 ) ;
} ) ;
2026-10-11 09:47:01 +02:00
test ( "only a NaN with its quiet bit clear is signalling: a finite float32 with a clear bit 22 reads, and a float64 slot reads any float32 NaN" , ( ) = > {
const f32 = slots < { v : number } > ( { 0 : [ "v" , float32 ] } ) ;
const f64 = slots < { v : number } > ( { 0 : [ "v" , float64 ] } ) ;
assert . equal ( f32 . decode ( readWire ( fromHex ( "91ca3f800001" ) ) ) . v , Math . fround ( 1.0000001192092896 ) ) ;
assert . equal ( f32 . decode ( readWire ( fromHex ( "91ca00000001" ) ) ) . v , Math . fround ( 1 e - 45 ) ) ;
assert . equal ( f32 . decode ( readWire ( fromHex ( "91ca7f800000" ) ) ) . v , Infinity ) ;
assert . ok ( Number . isNaN ( f32 . decode ( readWire ( fromHex ( "91ca7fc00001" ) ) ) . v ) ) ;
assert . ok ( Number . isNaN ( f64 . decode ( readWire ( fromHex ( "91ca7f800001" ) ) ) . v ) ) ;
} ) ;
2026-10-11 08:34:31 +02:00
test ( "numeric leaves write the bytes the C# reference writes, and 64-bit values lose nothing" , async ( ) = > {
const rows = readWire ( new Uint8Array ( await readFile ( join ( numericVectors , "writes.msgpack" ) ) ) ) as [ string , string , Uint8Array ] [ ] ;
assert . equal ( rows . length , 46 ) ;
for ( const [ leaf , text , expected ] of rows ) {
const value = leaf . startsWith ( "float" ) ? new DataView ( Uint8Array . from ( Buffer . from ( text , "hex" ) ) . buffer ) . getFloat64 ( 0 ) : leaf === "int32" ? Number ( text ) : BigInt ( text ) ;
2026-10-11 04:55:22 +02:00
const record = slots < { v : unknown } > ( { 0 : [ "v" , numericLeaves [ leaf ] ] } ) ;
2026-10-11 08:34:31 +02:00
assert . equal ( hex ( writeWire ( record . encode ( { v : value } ) ) ) , hex ( expected ) , ` ${ leaf } ${ text } ` ) ;
2026-10-11 04:55:22 +02:00
}
const wide = slots < { v : number | bigint } > ( { 0 : [ "v" , int64 ] } ) ;
for ( const value of [ 2 n * * 53 n + 1 n , 2 n * * 63 n - 1 n , - ( 2 n * * 63 n ) , - ( 2 n * * 53 n ) - 1 n ] ) {
assert . equal ( wide . decode ( readWire ( writeWire ( wide . encode ( { v : value } ) ) ) ) . v , value ) ;
}
assert . equal ( wide . decode ( readWire ( writeWire ( wide . encode ( { v : 2n } ) ) ) ) . v , 2 , "a bigint that fits comes back a number" ) ;
} ) ;
2026-10-11 05:04:23 +02:00
test ( "the wire writer's width boundaries: where a length or an integer changes its header" , ( ) = > {
assert . equal ( hex ( writeWire ( 0 ) ) , "00" ) ;
assert . equal ( hex ( writeWire ( "a" . repeat ( 31 ) ) ) . slice ( 0 , 2 ) , "bf" ) ;
assert . equal ( hex ( writeWire ( "a" . repeat ( 32 ) ) ) . slice ( 0 , 4 ) , "d920" ) ;
assert . equal ( hex ( writeWire ( "a" . repeat ( 255 ) ) ) . slice ( 0 , 4 ) , "d9ff" ) ;
assert . equal ( hex ( writeWire ( "a" . repeat ( 256 ) ) ) . slice ( 0 , 6 ) , "da0100" ) ;
assert . equal ( hex ( writeWire ( "a" . repeat ( 65535 ) ) ) . slice ( 0 , 6 ) , "daffff" ) ;
assert . equal ( hex ( writeWire ( "a" . repeat ( 65536 ) ) ) . slice ( 0 , 10 ) , "db00010000" ) ;
assert . equal ( hex ( writeWire ( new Uint8Array ( 1 ) ) ) , "c40100" ) ;
assert . equal ( hex ( writeWire ( new Uint8Array ( 256 ) ) ) . slice ( 0 , 6 ) , "c50100" ) ;
assert . equal ( hex ( writeWire ( new Uint8Array ( 65536 ) ) ) . slice ( 0 , 10 ) , "c600010000" ) ;
assert . equal ( hex ( writeWire ( new Array ( 15 ) . fill ( null ) ) ) , ` 9f ${ "c0" . repeat ( 15 ) } ` ) ;
assert . equal ( hex ( writeWire ( new Array ( 65535 ) . fill ( null ) ) ) . slice ( 0 , 6 ) , "dcffff" ) ;
assert . equal ( hex ( writeWire ( new Array ( 65536 ) . fill ( null ) ) ) . slice ( 0 , 10 ) , "dd00010000" ) ;
assert . throws ( ( ) = > writeWire ( - ( 2 n * * 63 n ) - 1 n ) , { message : "cannot write an integer wider than 64 bits." } ) ;
assert . throws ( ( ) = > writeWire ( undefined ) , / t h i s k i n d o f v a l u e / u ) ;
assert . equal ( hex ( writeWire ( - ( 2 n * * 63 n ) ) ) , "d38000000000000000" ) ;
} ) ;
test ( "the wire reader's boundaries: the largest fixarray, the 32-bit binary and string, the safe integer edge" , ( ) = > {
assert . deepEqual ( readWire ( fromHex ( ` 9f ${ "c0" . repeat ( 15 ) } ` ) ) , new Array ( 15 ) . fill ( null ) ) ;
assert . deepEqual ( readWire ( fromHex ( "c600000001aa" ) ) , new Uint8Array ( [ 0xaa ] ) ) ;
assert . equal ( readWire ( fromHex ( "db0000000161" ) ) , "a" ) ;
assert . equal ( readWire ( fromHex ( "d3ffe0000000000001" ) ) , - ( 2 * * 53 - 1 ) ) ;
assert . equal ( readWire ( fromHex ( "d3ffe0000000000000" ) ) , - ( 2 n * * 53 n ) ) ;
assert . equal ( readWire ( fromHex ( "cf0020000000000000" ) ) , 2 n * * 53 n ) ;
} ) ;
test ( "a refusal says what was found: nil, a float, an integer that is not the slot's, a plain kind" , ( ) = > {
assert . throws ( ( ) = > int32 . encode ( undefined as unknown as number ) , { message : "expected an int32, found nil" } ) ;
assert . throws ( ( ) = > string . decode ( new WireFloat ( 1 , true ) ) , { message : "expected a string, found float" } ) ;
assert . throws ( ( ) = > string . decode ( 5 n ) , { message : "expected a string, found integer" } ) ;
assert . throws ( ( ) = > int32 . decode ( new WireFloat ( 7 , true ) ) , { message : "expected an int32, found float" } ) ;
assert . throws ( ( ) = > float64 . decode ( "1" ) , { message : "expected a float64, found string" } ) ;
assert . throws ( ( ) = > int64 . encode ( 1.5 ) , { message : "expected an int64, found a non-integer number" } ) ;
} ) ;
test ( "nullable names a value type Nullable<T> and anything else as itself" , ( ) = > {
assert . equal ( nullable ( boolean ) . typeName , "System.Nullable<System.Boolean>" ) ;
assert . equal ( nullable ( int64 ) . typeName , "System.Nullable<System.Int64>" ) ;
assert . equal ( nullable ( float32 ) . typeName , "System.Nullable<System.Single>" ) ;
assert . equal ( nullable ( float64 ) . typeName , "System.Nullable<System.Double>" ) ;
assert . equal ( nullable ( bytes ) . typeName , "System.Byte[]" ) ;
const unnamedValueType : Codec < number > = { valueType : true , encode : ( value ) = > value , decode : ( raw ) = > raw as number } ;
assert . equal ( nullable ( unnamedValueType ) . typeName , undefined ) ;
assert . equal ( lazy ( ( ) = > int32 ) . valueType , true ) ;
} ) ;
test ( "the Int32 edges of an arm key: the largest is an arm, one past either end is outside" , ( ) = > {
const edge = union < { kind : "A" } > ( "U" , { 2147483647 : [ "A" , unit ] } ) ;
assert . deepEqual ( edge . decode ( readWire ( fromHex ( "92ce7fffffff90" ) ) ) , { kind : "A" } ) ;
assert . deepEqual ( edge . encode ( { kind : "A" } ) , [ 2147483647 , [ ] ] ) ;
assert . throws ( ( ) = > edge . decode ( readWire ( fromHex ( "92ce8000000090" ) ) ) , { message : "Union U: the arm key is outside Int32 (declared keys: 2147483647)." } ) ;
assert . throws ( ( ) = > edge . decode ( readWire ( fromHex ( "92d3ffffffff7fffffff90" ) ) ) , { message : "Union U: the arm key is outside Int32 (declared keys: 2147483647)." } ) ;
assert . throws ( ( ) = > edge . decode ( readWire ( fromHex ( "92d3ffffffff8000000090" ) ) ) , { message : "Union U: unknown arm key -2147483648 (declared keys: 2147483647)." } ) ;
} ) ;
2026-10-11 03:50:23 +02:00
function envelopeOf ( payload : Uint8Array ) : CultCacheEnvelope {
One typed owner of document-payload reads and writes: DocumentPayload is opaque, the definition is required
DocumentPayload is an opaque object type over the same runtime Uint8Array, keyed by a string
property, and types CultCacheEnvelope.payload, CultNetRawDocumentRecord.payload and
CultMeshRealtimeFrame.payload. decodeDocumentPayload(definition, payload) and
encodeDocumentPayload(definition, value) are the only reader and writer; documentPayloadFromBytes
and documentPayloadBytes are the two named escapes at the edges where bytes enter and leave.
resolveDocumentFormatter leaves the package index. The cache, cultnet replication, the mesh read
paths, the provider command (now a CultCache document), and the browser's decodeCultNetPayload
(definition required, cultcache-ts/document entry) all go through the owner.
Compile-fail fixtures per payload-carrying package pin the type with expect-error lines.
check-typescript-tests-wired.mjs fails when a test file is run by no script; cultcache-ts now
runs dist-test/test/*.test.js, and the portability workflow runs the check and the cache suite.
Builds in every package (tsc, src and tests); the suites run once, at the end of the pass.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-11 19:33:42 +02:00
return { key : "surface" , type : "tests.union_surface" , payload : documentPayloadFromBytes ( payload ) , storedAt : new Date ( ) . toISOString ( ) } ;
2026-10-11 03:50:23 +02:00
}
function memoryStore ( entries : CultCacheEnvelope [ ] ) : CacheBackingStore & { entries : CultCacheEnvelope [ ] } {
return {
entries ,
async pullAll() { return entries . map ( ( entry ) = > ( { . . . entry } ) ) ; } ,
async push ( entry ) { entries . push ( entry ) ; } ,
async delete ( ) { } ,
} ;
}
2026-10-11 08:34:31 +02:00
test ( "arm keys span Int32 and are listed ascending; slot keys are non-negative Int32" , ( ) = > {
const keys = union < { kind : "High" | "Zero" | "Neg" | "Low" } > ( "U" , {
2147483647 : [ "High" , unit ] ,
0 : [ "Zero" , unit ] ,
[ - 1 ] : [ "Neg" , unit ] ,
[ - 2147483648 ] : [ "Low" , unit ] ,
} ) ;
for ( const [ kind , key ] of [ [ "High" , 2147483647 ] , [ "Zero" , 0 ] , [ "Neg" , - 1 ] , [ "Low" , - 2147483648 ] ] as const ) {
const written = keys . encode ( { kind } ) ;
assert . deepEqual ( written , [ key , [ ] ] ) ;
assert . deepEqual ( keys . decode ( readWire ( writeWire ( written ) ) ) , { kind } ) ;
}
2026-10-11 08:39:42 +02:00
assert . throws ( ( ) = > keys . decode ( readWire ( fromHex ( "920590" ) ) ) , { message : "Union U: unknown arm key 5 (declared keys: -2147483648, -1, 0, 2147483647)." } ) ;
2026-10-11 08:34:31 +02:00
assert . throws ( ( ) = > union < { kind : "A" } > ( "U" , { [ - 2147483649 ] : [ "A" , unit ] } ) , { message : "Union U declares the key -2147483649, which is outside Int32." } ) ;
assert . throws ( ( ) = > union < { kind : "A" } > ( "U" , { 99999999999999999999 : [ "A" , unit ] } as never ) , { message : "Union U declares the key 100000000000000000000, which is outside Int32." } ) ;
2026-10-11 09:18:18 +02:00
assert . throws ( ( ) = > slots < { a : string } > ( { 2147483647 : [ "a" , string ] } ) , { message : "A slot record declares the key 2147483647, which is above the slot key limit 65535." } ) ;
assert . throws ( ( ) = > slots < { a : string } > ( { 2147483648 : [ "a" , string ] } ) , { message : "A slot record declares the key 2147483648, which is above the slot key limit 65535." } ) ;
2026-10-11 08:34:31 +02:00
assert . throws ( ( ) = > slots < { a : string } > ( { [ - 1 ] : [ "a" , string ] } ) , { message : 'A slot record declares the key "-1", which is not a non-negative integer.' } ) ;
} ) ;
2026-10-11 09:18:18 +02:00
// A slot record is a dense array of key+1 slots, as the reference writes it, so the key is capped: the largest accepted
// key writes a 65536-slot payload, one more is refused at definition.
test ( "a slot key is capped at 65535: the cap is the largest slot record, one past it is refused at definition" , ( ) = > {
assert . equal ( MAX_SLOT_KEY , 65535 ) ;
const edge = slots < { a : string } > ( { 65535 : [ "a" , string ] } ) ;
const written = edge . encode ( { a : "x" } ) as unknown [ ] ;
assert . equal ( written . length , 65536 ) ;
assert . equal ( written [ 65535 ] , "x" ) ;
assert . equal ( written . filter ( ( slot ) = > slot === null ) . length , 65535 ) ;
assert . deepEqual ( edge . decode ( readWire ( writeWire ( written ) ) ) , { a : "x" } ) ;
assert . throws ( ( ) = > slots < { a : string } > ( { 65536 : [ "a" , string ] } ) , { message : "A slot record declares the key 65536, which is above the slot key limit 65535." } ) ;
} ) ;
2026-10-11 08:34:31 +02:00
test ( "the mixed-record vector is the bytes the reference writes for a record of every leaf kind" , async ( ) = > {
const mixed = slots < { id : string ; i : number ; l : number | bigint ; f : number ; d : number } > ( {
0 : [ "id" , string ] , 1 : [ "i" , int32 ] , 2 : [ "l" , int64 ] , 3 : [ "f" , float32 ] , 4 : [ "d" , float64 ] ,
} ) ;
const committed = new Uint8Array ( await readFile ( join ( vectors , ".." , "numeric-leaves" , "mixed-record.msgpack" ) ) ) ;
assert . equal ( hex ( writeWire ( mixed . encode ( { id : "n1" , i : 7 , l : 8 , f : 1.5 , d : 2.5 } ) ) ) , hex ( committed ) ) ;
assert . deepEqual ( mixed . decode ( readWire ( committed ) ) , { id : "n1" , i : 7 , l : 8 , f : 1.5 , d : 2.5 } ) ;
} ) ;
2026-10-11 21:05:09 +02:00
// tests/vectors/slot-nil is written by the C# reference (SlotNilVectorTests): what it reads and rewrites for a nil, a str in a
// byte[] slot, and a record short of its last slots. A runtime accepts what it accepts and rewrites the same bytes.
test ( "slots read and rewrite exactly what the C# reference does for nil, a str in bytes, and short records" , async ( ) = > {
const inner = slots < { x : string } > ( { 0 : [ "x" , string , "" ] } ) ;
const probe = slots < { s : string ; i : number ; b : Uint8Array ; r : { x : string } ; l : string [ ] } > ( {
0 : [ "s" , string , "" ] ,
1 : [ "i" , int32 , 0 ] ,
2 : [ "b" , bytes , ( ) = > new Uint8Array ( ) ] ,
3 : [ "r" , inner , null as unknown as { x : string } ] ,
4 : [ "l" , list ( string ) , ( ) = > [ ] ] ,
} ) ;
const rows = readWire ( new Uint8Array ( await readFile ( join ( vectors , ".." , "slot-nil" , "reads.msgpack" ) ) ) ) as [ string , Uint8Array , boolean , Uint8Array ] [ ] ;
2026-10-12 00:08:23 +02:00
assert . equal ( rows . length , 17 ) ;
2026-10-11 21:05:09 +02:00
let accepted = 0 ;
for ( const [ name , payload , wasAccepted , rewritten ] of rows ) {
if ( wasAccepted ) {
assert . equal ( hex ( writeWire ( probe . encode ( probe . decode ( readWire ( payload ) ) ) ) ) , hex ( rewritten ) , name ) ;
accepted += 1 ;
} else {
assert . throws ( ( ) = > probe . decode ( readWire ( payload ) ) , ( error : Error ) = > ! error . message . includes ( hex ( payload ) . slice ( 2 ) ) , name ) ;
}
}
2026-10-12 00:08:23 +02:00
assert . equal ( accepted , 15 ) ;
// A character outside the BMP is four UTF-8 bytes (U+1F600 is f0 9f 98 80); a CESU-8 reader, or one with no four-byte
// branch, fails here against the bytes the C# reference wrote.
const astral = rows . find ( ( [ name ] ) = > name === "string-astral" ) ! ;
assert . equal ( probe . decode ( readWire ( astral [ 1 ] ) ) . s , "\u{1F600}" ) ;
assert . equal ( hex ( writeWire ( probe . encode ( probe . decode ( readWire ( astral [ 1 ] ) ) ) ) ) , hex ( astral [ 3 ] ) ) ;
const astralInBytes = rows . find ( ( [ name ] ) = > name === "bytes-str-astral" ) ! ;
assert . equal ( hex ( probe . decode ( readWire ( astralInBytes [ 1 ] ) ) . b ) , "f09f9880" ) ;
2026-10-11 21:05:09 +02:00
} ) ;
test ( "a nil reads as null and writes as nil in every reference slot, and a value slot refuses it" , ( ) = > {
const record = slots < { s : string ; b : Uint8Array ; i : number } > ( { 0 : [ "s" , string ] , 1 : [ "b" , bytes ] , 2 : [ "i" , int32 , 5 ] } ) ;
const read = record . decode ( [ null , null , 3 ] ) ;
assert . deepEqual ( read , { s : null , b : null , i : 3 } ) ;
assert . deepEqual ( record . encode ( read ) , [ null , null , 3 ] ) ;
assert . throws ( ( ) = > record . encode ( { s : "a" , b : new Uint8Array ( ) , i : null as unknown as number } ) , { message : "i (slot 2): expected an int32, found nil" } ) ;
assert . throws ( ( ) = > record . decode ( [ "a" , new Uint8Array ( ) , null ] ) , { message : "i (slot 2): expected an int32, found nil" } ) ;
} ) ;
test ( "a bytes slot reads a MessagePack str as its bytes and writes bin, and refuses a str that was not valid UTF-8" , ( ) = > {
const record = slots < { b : Uint8Array } > ( { 0 : [ "b" , bytes ] } ) ;
const read = record . decode ( readWire ( fromHex ( "91a3616263" ) ) ) ;
assert . equal ( hex ( read . b ) , "616263" ) ;
assert . equal ( hex ( writeWire ( record . encode ( read ) ) ) , "91c403616263" ) ;
assert . throws ( ( ) = > record . decode ( readWire ( fromHex ( "91a2c328" ) ) ) , { message : "b (slot 0): expected bytes, found a string that is not valid UTF-8" } ) ;
assert . throws ( ( ) = > record . decode ( [ 5 ] ) , { message : "b (slot 0): expected bytes, found number" } ) ;
} ) ;
2026-10-12 00:01:59 +02:00
// ---- the bounds vectors: arm keys at the ends of the Int32 domain, nil arm slots, payload nesting ----
const wrapChain = ( wraps : number , leaf : Node ) : Node = > {
let node : Node = leaf ;
2026-10-14 19:44:28 +02:00
for ( let index = 0 ; index < wraps ; index += 1 ) node = { kind : "Wrap" , inner : node , id : "0000000000b1" } ;
2026-10-12 00:01:59 +02:00
return node ;
} ;
// A Wrap adds 2 containers, a Box with no children 3, a Text leaf 2, and the outermost array is 1 (the C# test's arithmetic).
const AT_LIMIT_WRAPS = ( MAX_PAYLOAD_DEPTH - 1 - 3 ) / 2 ;
const PAST_LIMIT_WRAPS = ( MAX_PAYLOAD_DEPTH + 1 - 1 - 2 ) / 2 ;
2026-10-14 19:44:28 +02:00
const atLimitValue : Surface = { . . . golden , root : wrapChain ( AT_LIMIT_WRAPS , { kind : "Box" , id : "0000000000f0" , children : [ ] } ) } ;
const pastLimitValue : Surface = { . . . golden , root : wrapChain ( PAST_LIMIT_WRAPS , { kind : "Text" , id : "0000000000f0" , content : CANARY } ) } ;
2026-10-12 00:01:59 +02:00
async function boundsEntries() {
const raw = decode ( await read ( "bounds-outcomes.msgpack" ) ) as unknown [ ] [ ] ;
const [ limit , . . . rest ] = raw ;
return { limit , entries : rest.map ( ( [ file , outcome , unionName , key , detail ] ) = > ( { file : file as string , outcome : outcome as string , unionName : unionName as string , key : key as number | null , detail : detail as string } ) ) } ;
}
test ( "every bounds vector is listed and holds: accepted files decode and re-encode, refused files are refused naming the union or the depth" , async ( ) = > {
const { limit , entries } = await boundsEntries ( ) ;
assert . deepEqual ( limit , [ "limit" , MAX_PAYLOAD_DEPTH ] ) ;
assert . equal ( entries . length , 12 ) ;
const document = surfaceDocument ( ) ;
const counts = { accepted : 0 , refused : 0 , readOnly : 0 } ;
for ( const { file , outcome : expected , unionName , key , detail } of entries ) {
const payload = documentPayloadFromBytes ( await read ( file ) ) ;
if ( expected === "accepted" ) {
counts . accepted += 1 ;
const value = decodeDocumentPayload ( document , payload ) ;
assert . equal ( hex ( documentPayloadBytes ( encodeDocumentPayload ( document , value ) ) ) , hex ( await read ( detail ) ) , ` ${ file } : re-encodes to ${ detail } ` ) ;
} else if ( expected === "read-only" ) {
counts . readOnly += 1 ;
assert . deepEqual ( decodeDocumentPayload ( document , payload ) , golden , ` ${ file } : the extra slots are read past ` ) ;
} else {
counts . refused += 1 ;
assert . throws (
( ) = > decodeDocumentPayload ( document , payload ) ,
( error : Error ) = > {
assert . ok ( ! error . message . includes ( CANARY ) , ` ${ file } : the refusal echoed the payload ` ) ;
if ( detail === "depth" ) {
return error instanceof CultCachePayloadDepthError && error . depth === MAX_PAYLOAD_DEPTH + 1 && error . limit === MAX_PAYLOAD_DEPTH
&& error . message . includes ( ` " ${ document . type } " ` ) && error . message . includes ( "257" ) && error . message . includes ( "256" ) ;
}
assert . ok ( ! ( error instanceof CultCachePayloadDepthError ) , file ) ;
const said = detail === "key-out-of-range" ? "outside Int32" : detail === "key-not-integer" ? "not an integer" : "expected [key, slots]" ;
return error . message . includes ( ` Union ${ unionName } : ` ) && error . message . includes ( said ) ;
} ,
file ,
) ;
}
}
assert . deepEqual ( counts , { accepted : 3 + 1 , refused : 4 + 1 + 2 , readOnly : 1 } ) ;
} ) ;
test ( "the constructed values write the committed at-limit payload byte for byte, and the past-limit value is refused and stored nowhere" , async ( ) = > {
const document = surfaceDocument ( ) ;
assert . equal ( hex ( documentPayloadBytes ( encodeDocumentPayload ( document , atLimitValue ) ) ) , hex ( await read ( "depth-at-limit.msgpack" ) ) ) ;
assert . deepEqual ( decodeDocumentPayload ( document , documentPayloadFromBytes ( await read ( "depth-at-limit.msgpack" ) ) ) , atLimitValue ) ;
assert . throws (
( ) = > encodeDocumentPayload ( document , pastLimitValue ) ,
( error : Error ) = > error instanceof CultCachePayloadDepthError && error . depth === 257 && ! error . message . includes ( CANARY ) ,
) ;
const entries : CultCacheEnvelope [ ] = [ ] ;
const cache = CultCache . builder ( ) . withDocumentType ( document ) . withGenericStore ( memoryStore ( entries ) ) . build ( ) ;
await assert . rejects ( ( ) = > cache . put ( document , "past" , pastLimitValue ) , CultCachePayloadDepthError ) ;
2026-10-12 00:05:27 +02:00
assert . equal ( entries . length , 0 , "nothing reached the store" ) ;
2026-10-12 00:01:59 +02:00
assert . equal ( cache . get ( document , "past" ) , undefined , "nothing is held in memory" ) ;
await cache . put ( document , "at" , atLimitValue ) ;
assert . equal ( entries . length , 1 ) ;
assert . equal ( hex ( documentPayloadBytes ( entries [ 0 ] ! . payload ) ) , hex ( await read ( "depth-at-limit.msgpack" ) ) ) ;
} ) ;
test ( "a cache load refuses a store whose record is past the limit, naming the type and not the payload" , async ( ) = > {
const document = surfaceDocument ( ) ;
const refusing = CultCache . builder ( ) . withDocumentType ( document ) . withGenericStore ( memoryStore ( [ envelopeOf ( await read ( "depth-past-limit.msgpack" ) ) ] ) ) . build ( ) ;
await assert . rejects ( ( ) = > refusing . pullAllBackingStores ( ) , ( error : Error ) = > error instanceof CultCachePayloadDepthError && ! error . message . includes ( CANARY ) ) ;
} ) ;