2026-11-12 05:03:29 +00:00
|
|
|
import type { NotedSlots } from "./codec";
|
|
|
|
|
import { decodeMarked, resolveDocumentFormatter } from "./document-formatter";
|
2026-11-12 06:02:51 +00:00
|
|
|
import { checkPayloadDepth, checkPayloadIsOneValue } from "./payload-depth";
|
2026-05-30 00:39:39 +01:00
|
|
|
import type {
|
|
|
|
|
AnyCultCacheDocumentDefinition,
|
2026-10-11 04:49:13 +02:00
|
|
|
CultCacheSchemaCatalogMember,
|
2026-05-30 00:39:39 +01:00
|
|
|
CultCacheDocumentDefinition,
|
|
|
|
|
CultCacheDocumentRegistry,
|
2026-10-11 19:21:32 +02:00
|
|
|
CultCacheDocumentValue,
|
2026-05-30 00:39:39 +01:00
|
|
|
CultCacheSchema,
|
|
|
|
|
} from "./types";
|
|
|
|
|
|
|
|
|
|
export function defineDocumentType<TSchema extends CultCacheSchema>(
|
|
|
|
|
definition: CultCacheDocumentDefinition<TSchema>,
|
|
|
|
|
): CultCacheDocumentDefinition<TSchema> {
|
|
|
|
|
if (!definition.type || definition.type.trim().length === 0) {
|
|
|
|
|
throw new Error("CultCache document types must declare a non-empty type.");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for (const [fieldName, fieldValue] of [
|
|
|
|
|
["schemaId", definition.schemaId],
|
|
|
|
|
["schemaName", definition.schemaName],
|
|
|
|
|
["schemaVersion", definition.schemaVersion],
|
|
|
|
|
["contentHash", definition.contentHash],
|
|
|
|
|
["canonicalSchemaJson", definition.canonicalSchemaJson],
|
|
|
|
|
] as const) {
|
|
|
|
|
if (fieldValue !== undefined && fieldValue.trim().length === 0) {
|
|
|
|
|
throw new Error(`CultCache document type "${definition.type}" declares an empty ${fieldName}.`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (definition.name !== undefined && typeof definition.name !== "string" && typeof definition.name !== "function") {
|
|
|
|
|
throw new Error(`CultCache document type "${definition.type}" declares an invalid name accessor.`);
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-11 05:13:08 +00:00
|
|
|
const declared = new Set<string>();
|
|
|
|
|
for (const [kind, set] of [["index", definition.indexes], ["role", definition.roles]] as const) {
|
|
|
|
|
const names = new Set<string>();
|
|
|
|
|
for (const name of Array.isArray(set) ? set.map((entry) => entry.name) : set ? Object.keys(set) : []) {
|
|
|
|
|
if (!name || name.trim().length === 0) {
|
|
|
|
|
throw new Error(`CultCache document type "${definition.type}" declares ${kind === "index" ? "an index" : "a role"} with an empty name.`);
|
2026-05-30 00:39:39 +01:00
|
|
|
}
|
2026-11-11 05:13:08 +00:00
|
|
|
if (names.has(name)) {
|
|
|
|
|
throw new Error(`CultCache document type "${definition.type}" declares duplicate ${kind} "${name}".`);
|
2026-05-30 00:39:39 +01:00
|
|
|
}
|
2026-11-11 05:13:08 +00:00
|
|
|
if (kind === "role" && declared.has(name)) {
|
|
|
|
|
throw new Error(`CultCache document type "${definition.type}" declares "${name}" as both an index and a role; an index already names its role.`);
|
2026-05-30 00:39:39 +01:00
|
|
|
}
|
2026-11-11 05:13:08 +00:00
|
|
|
names.add(name);
|
2026-05-30 00:39:39 +01:00
|
|
|
}
|
2026-11-11 05:13:08 +00:00
|
|
|
for (const name of names) declared.add(name);
|
2026-05-30 00:39:39 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (definition.members) {
|
|
|
|
|
const seenSlots = new Set<number>();
|
|
|
|
|
for (const member of definition.members) {
|
|
|
|
|
if (!Number.isInteger(member.slot) || member.slot < 0) {
|
|
|
|
|
throw new Error(`CultCache document type "${definition.type}" declares an invalid schema member slot.`);
|
|
|
|
|
}
|
|
|
|
|
if (seenSlots.has(member.slot)) {
|
|
|
|
|
throw new Error(`CultCache document type "${definition.type}" declares duplicate schema member slot ${member.slot}.`);
|
|
|
|
|
}
|
|
|
|
|
seenSlots.add(member.slot);
|
|
|
|
|
if (!member.memberName || member.memberName.trim().length === 0) {
|
|
|
|
|
throw new Error(`CultCache document type "${definition.type}" declares a schema member with an empty name.`);
|
|
|
|
|
}
|
|
|
|
|
if (!member.typeName || member.typeName.trim().length === 0) {
|
|
|
|
|
throw new Error(`CultCache document type "${definition.type}" declares schema member "${member.memberName}" with an empty type.`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-11 04:49:13 +02:00
|
|
|
resolveDocumentFormatter(definition);
|
|
|
|
|
return Object.freeze(definition.codec ? { ...definition, members: resolveDocumentMembers(definition) } : { ...definition });
|
|
|
|
|
}
|
|
|
|
|
|
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
|
|
|
/**
|
|
|
|
|
* The bytes of one document, as they travel in a store envelope, a CultNet record or a realtime frame.
|
|
|
|
|
*
|
|
|
|
|
* At run time this is the same `Uint8Array`, so frames encode as they always did. At compile time it is opaque: it is not
|
|
|
|
|
* assignable to or from `Uint8Array` or `ArrayLike<number>`, so no byte decoder accepts it. The only reader is
|
|
|
|
|
* `decodeDocumentPayload(definition, payload)`, which needs the definition that says how the bytes are laid out, and the
|
|
|
|
|
* only writer is `encodeDocumentPayload(definition, value)`. The two escapes are named: `documentPayloadFromBytes` where
|
|
|
|
|
* bytes enter (a validated record, a store read, tests, a writer of pre-encoded or signed bytes) and
|
|
|
|
|
* `documentPayloadBytes` where they leave (a store write, a frame encode, hashing or signing).
|
|
|
|
|
*
|
|
|
|
|
* The key is a plain string, not a unique symbol, so two installed copies of this package stay compatible.
|
2026-10-11 20:37:29 +02:00
|
|
|
*
|
|
|
|
|
* What the type guarantees: a payload cannot be read or assigned directly (a decoder call, `const b: Uint8Array = p`,
|
2026-10-11 22:03:20 +02:00
|
|
|
* `new Uint8Array(p)` fail to compile). What it does not: the runtime value is a `Uint8Array`, so these routes read it
|
|
|
|
|
* without the owner: `instanceof Uint8Array` or `ArrayBuffer.isView` narrowing, `Object.values`, `Object.assign` onto a
|
|
|
|
|
* `Uint8Array`, a JSON round trip, `Reflect.get`, and a cast. A codec or formatter document read that way is raw bytes,
|
|
|
|
|
* not the document. The sanctioned escape for bytes is `documentPayloadBytes`; the reader is `decodeDocumentPayload`.
|
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
|
|
|
*/
|
|
|
|
|
export interface DocumentPayload {
|
|
|
|
|
readonly "cultcache.documentPayload": true;
|
|
|
|
|
readonly byteLength: number;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function documentPayloadFromBytes(bytes: Uint8Array): DocumentPayload {
|
|
|
|
|
return bytes as unknown as DocumentPayload;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function documentPayloadBytes(payload: DocumentPayload): Uint8Array {
|
|
|
|
|
return payload as unknown as Uint8Array;
|
|
|
|
|
}
|
|
|
|
|
|
cultnet-ts/content: the TypeScript CDN manifest, codec, hashing, record keys and packer
One browser-safe module owns the manifest and chunk-ref shapes, their MessagePack form (positional ten-array, metadata as
ordered entries, duplicate keys and unsafe integers refused, payload depth through cultcache-ts's own checkPayloadDepth),
normalizeHash/parseSha256Hex, both record-key grammars (StableToken per UTF-16 unit), WebCrypto sha256Hex and packContent.
cultcache-ts/document re-exports checkPayloadDepth. scripts/write-cultmesh-content-vectors.mjs writes the TypeScript
manifest vectors for the C# reference to judge.
Builds. Co-Authored-By below.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:35:15 +02:00
|
|
|
export { CultCachePayloadDepthError, MAX_PAYLOAD_DEPTH, checkPayloadDepth } from "./payload-depth";
|
2026-10-12 00:01:59 +02:00
|
|
|
|
2026-10-12 01:04:27 +02:00
|
|
|
// The payload nesting bound covers the MessagePack the library itself writes: the plain default formatter and a codec. A
|
|
|
|
|
// user formatter's bytes are opaque and in any format; its format and bounds are its own.
|
|
|
|
|
function writesLibraryMessagePack(definition: AnyCultCacheDocumentDefinition): boolean {
|
|
|
|
|
return !definition.formatter;
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-11 19:21:32 +02:00
|
|
|
// The one reader of a document payload: through the definition's formatter, codec or plain map, then its schema. A
|
|
|
|
|
// reader holds the definition or it has no business reading the bytes, so there is no definition-less form.
|
|
|
|
|
export function decodeDocumentPayload<TDefinition extends AnyCultCacheDocumentDefinition>(
|
|
|
|
|
definition: TDefinition,
|
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
|
|
|
payload: DocumentPayload,
|
2026-10-11 19:21:32 +02:00
|
|
|
): CultCacheDocumentValue<TDefinition> {
|
2026-11-12 05:03:29 +00:00
|
|
|
return decodeDocumentPayloadMarked(definition, payload).value;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// The same read with the slots it read past (cult-cache-ts slot-readonly). The depth check runs first: a payload past the
|
|
|
|
|
// limit is refused, never marked.
|
|
|
|
|
export function decodeDocumentPayloadMarked<TDefinition extends AnyCultCacheDocumentDefinition>(
|
|
|
|
|
definition: TDefinition,
|
|
|
|
|
payload: DocumentPayload,
|
|
|
|
|
): { value: CultCacheDocumentValue<TDefinition>; unreadSlots?: NotedSlots } {
|
2026-10-12 00:01:59 +02:00
|
|
|
const bytes = documentPayloadBytes(payload);
|
2026-11-12 06:02:51 +00:00
|
|
|
if (writesLibraryMessagePack(definition)) {
|
|
|
|
|
// A payload is exactly one MessagePack value: bytes after the first are refused by count before any formatter reads,
|
|
|
|
|
// so a tail is refused before any slot is marked.
|
|
|
|
|
checkPayloadIsOneValue(bytes, `document type "${definition.type}" payload`);
|
|
|
|
|
}
|
2026-11-12 05:03:29 +00:00
|
|
|
const { value: decoded, unreadSlots } = decodeMarked(definition, bytes);
|
|
|
|
|
const value = definition.schema.parse(decoded) as CultCacheDocumentValue<TDefinition>;
|
|
|
|
|
return unreadSlots ? { value, unreadSlots } : { value };
|
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
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// The one writer: the definition's schema first, then its formatter, codec or plain map.
|
|
|
|
|
export function encodeDocumentPayload(definition: AnyCultCacheDocumentDefinition, value: unknown): DocumentPayload {
|
2026-10-12 00:01:59 +02:00
|
|
|
const bytes = resolveDocumentFormatter(definition).encode(definition.schema.parse(value));
|
2026-10-12 01:04:27 +02:00
|
|
|
if (writesLibraryMessagePack(definition)) checkPayloadDepth(bytes, `document type "${definition.type}" value`);
|
2026-10-12 00:01:59 +02:00
|
|
|
return documentPayloadFromBytes(bytes);
|
2026-10-11 04:49:13 +02:00
|
|
|
}
|
2026-10-11 03:50:23 +02:00
|
|
|
|
2026-11-11 08:43:52 +00:00
|
|
|
// Whether the definition declares `name` as a role alias (either `roles` form).
|
|
|
|
|
export function declaresRole(definition: AnyCultCacheDocumentDefinition, name: string): boolean {
|
|
|
|
|
const roles = definition.roles;
|
|
|
|
|
return Array.isArray(roles) ? roles.some((entry) => entry.name === name) : roles ? Object.hasOwn(roles, name) : false;
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-11 04:49:13 +02:00
|
|
|
// The schema members of a document: the ones it declares, else those its codec derives, else none.
|
|
|
|
|
export function resolveDocumentMembers(definition: AnyCultCacheDocumentDefinition): readonly CultCacheSchemaCatalogMember[] {
|
|
|
|
|
if (definition.members || !definition.codec) {
|
|
|
|
|
return definition.members ?? [];
|
|
|
|
|
}
|
|
|
|
|
const codec = definition.codec;
|
2026-11-11 05:13:08 +00:00
|
|
|
const indexAlias = (slotName: string) => {
|
|
|
|
|
for (const set of [definition.indexes, definition.roles]) {
|
|
|
|
|
const alias = !Array.isArray(set) && set ? Object.entries(set).find(([, accessor]) => accessor === slotName)?.[0] : undefined;
|
|
|
|
|
if (alias !== undefined) return alias;
|
|
|
|
|
}
|
|
|
|
|
return null;
|
|
|
|
|
};
|
2026-10-11 04:49:13 +02:00
|
|
|
return codec.members.map((member, index) => ({
|
|
|
|
|
...member,
|
2026-10-11 04:51:51 +02:00
|
|
|
isName: (definition.name as unknown) === codec.names[index],
|
2026-10-11 04:49:13 +02:00
|
|
|
indexAlias: indexAlias(codec.names[index]),
|
|
|
|
|
}));
|
2026-05-30 00:39:39 +01:00
|
|
|
}
|
|
|
|
|
|
2026-09-30 19:49:41 +02:00
|
|
|
// The identity a definition's records carry: the schema id they are stamped with, the schema name and version, and every id
|
|
|
|
|
// the definition answers to (its own first). Every CultCache runtime surface and every CultNet or CultMesh layer over it
|
|
|
|
|
// derives a definition's identity here and nowhere else, so a record's id means the same type wherever it is read.
|
|
|
|
|
export interface CultCacheSchemaIdentity {
|
|
|
|
|
readonly schemaId: string;
|
|
|
|
|
readonly schemaName: string;
|
|
|
|
|
readonly schemaVersion: string;
|
|
|
|
|
readonly compatibleSchemaIds: readonly string[];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function schemaIdentityOf(definition: AnyCultCacheDocumentDefinition): CultCacheSchemaIdentity {
|
|
|
|
|
const schemaName = definition.schemaName ?? definition.type;
|
|
|
|
|
const schemaId = definition.schemaId ?? schemaName;
|
|
|
|
|
return {
|
|
|
|
|
schemaId,
|
|
|
|
|
schemaName,
|
|
|
|
|
schemaVersion: definition.schemaVersion ?? `${schemaName}.v1`,
|
|
|
|
|
compatibleSchemaIds: [...new Set([schemaId, ...(definition.compatibleSchemaIds ?? [])])],
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-30 00:39:39 +01:00
|
|
|
export function defineDocumentRegistry<
|
|
|
|
|
TDefinitions extends readonly AnyCultCacheDocumentDefinition[],
|
|
|
|
|
>(...definitions: TDefinitions): CultCacheDocumentRegistry<TDefinitions> {
|
|
|
|
|
return Object.freeze({
|
|
|
|
|
definitions: Object.freeze([...definitions]) as TDefinitions,
|
|
|
|
|
});
|
|
|
|
|
}
|