2026-10-11 21:05:09 +02:00
|
|
|
import { resolveDocumentFormatter } from "./document-formatter";
|
2026-10-12 00:01:59 +02:00
|
|
|
import { checkPayloadDepth } 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.`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (Array.isArray(definition.indexes)) {
|
|
|
|
|
const seen = new Set<string>();
|
|
|
|
|
for (const index of definition.indexes) {
|
|
|
|
|
if (!index.name || index.name.trim().length === 0) {
|
|
|
|
|
throw new Error(`CultCache document type "${definition.type}" declares an index with an empty name.`);
|
|
|
|
|
}
|
|
|
|
|
if (seen.has(index.name)) {
|
|
|
|
|
throw new Error(`CultCache document type "${definition.type}" declares duplicate index "${index.name}".`);
|
|
|
|
|
}
|
|
|
|
|
seen.add(index.name);
|
|
|
|
|
}
|
|
|
|
|
} else if (definition.indexes) {
|
|
|
|
|
for (const name of Object.keys(definition.indexes)) {
|
|
|
|
|
if (!name || name.trim().length === 0) {
|
|
|
|
|
throw new Error(`CultCache document type "${definition.type}" declares an index with an empty name.`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-12 00:01:59 +02:00
|
|
|
export { CultCachePayloadDepthError, MAX_PAYLOAD_DEPTH } from "./payload-depth";
|
|
|
|
|
|
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-10-12 00:01:59 +02:00
|
|
|
const bytes = documentPayloadBytes(payload);
|
2026-10-12 01:04:27 +02:00
|
|
|
if (writesLibraryMessagePack(definition)) checkPayloadDepth(bytes, `document type "${definition.type}" payload`);
|
2026-10-12 00:01:59 +02:00
|
|
|
const decoded = resolveDocumentFormatter(definition).decode(bytes);
|
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 definition.schema.parse(decoded) as CultCacheDocumentValue<TDefinition>;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 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-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;
|
|
|
|
|
const indexAlias = (slotName: string) =>
|
|
|
|
|
!Array.isArray(definition.indexes) && definition.indexes
|
|
|
|
|
? Object.entries(definition.indexes).find(([, accessor]) => accessor === slotName)?.[0] ?? null
|
|
|
|
|
: null;
|
|
|
|
|
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,
|
|
|
|
|
});
|
|
|
|
|
}
|