diff --git a/packages/cultmesh-ts/src/index.ts b/packages/cultmesh-ts/src/index.ts index b87167d8..f2505358 100644 --- a/packages/cultmesh-ts/src/index.ts +++ b/packages/cultmesh-ts/src/index.ts @@ -99,6 +99,38 @@ export interface CultMeshQueryContext { export type CultMeshUnsubscribe = () => void; +export type CultMeshDocumentWatcher = ( + context: CultMeshQueryContext, + callback: (value: TDocument) => void, +) => CultMeshUnsubscribe; + +export type CultMeshDocumentReplacer = ( + context: CultMeshQueryContext, + value: TDocument, +) => Promise; + +export type CultMeshCollectionSnapshot = readonly TDocument[]; + +export type CultMeshCollectionChangeKind = "added" | "updated" | "removed" | "reset"; + +export interface CultMeshCollectionChange { + readonly kind: CultMeshCollectionChangeKind; + readonly key?: string; + readonly value?: TDocument; +} + +export type CultMeshCollectionWatcher = ( + context: CultMeshQueryContext, + callback: (change: CultMeshCollectionChange) => void, +) => CultMeshUnsubscribe; + +export interface CultMeshDocumentSchemaDescriptor { + readonly type?: string; + readonly schemaId?: string; + readonly schemaName?: string; + readonly schemaVersion?: string; +} + export type CultMeshStatePointerResolver = ( context: CultMeshQueryContext, ) => Promise; @@ -406,6 +438,18 @@ export class CultMeshVerse { return cultMeshBindLiveFeed(this.context, feed); } + public bindDocument( + document: CultMeshDocumentHandle, + ): CultMeshBoundDocumentHandle { + return cultMeshBindDocument(this.context, document); + } + + public bindCollection( + collection: CultMeshCollectionHandle, + ): CultMeshBoundCollectionHandle { + return cultMeshBindCollection(this.context, collection); + } + public bindStatePointer( pointer: CultMeshStatePointer, ): CultMeshBoundStatePointer { @@ -660,6 +704,401 @@ export class CultMeshBoundLiveFeed { } } +export class CultMeshDocumentHandle { + public readonly schema: CultMeshDocumentSchemaDescriptor; + public readonly sources: readonly CultMeshProjectionSource[]; + public readonly routeHint: CultMeshRouteHint; + + public constructor( + public readonly documentId: string, + schema: CultMeshDocumentSchemaDescriptor, + private readonly snapshotDocument: (context: CultMeshQueryContext) => Promise, + options: { + sources?: readonly CultMeshProjectionSource[]; + routeHint?: CultMeshRouteHint; + watchDocument?: CultMeshDocumentWatcher; + replaceDocument?: CultMeshDocumentReplacer; + } = {}, + ) { + requireNonEmpty(documentId, "documentId"); + this.schema = normalizeCultMeshDocumentSchema(schema); + this.sources = [...(options.sources ?? [])]; + this.routeHint = options.routeHint ?? cultMeshRouteHint(); + this.watchDocument = options.watchDocument; + this.replaceDocument = options.replaceDocument; + } + + private readonly watchDocument: CultMeshDocumentWatcher | undefined; + private readonly replaceDocument: CultMeshDocumentReplacer | undefined; + + public get canReplace(): boolean { + return this.replaceDocument !== undefined; + } + + public latest(context: CultMeshQueryContext | string = "local"): Promise { + return this.snapshotDocument( + this.resolveContext(typeof context === "string" ? cultMeshQueryContext(context) : context), + ); + } + + public read(context: CultMeshQueryContext | string = "local"): Promise { + return this.latest(context); + } + + public watch(callback: (value: TDocument) => void): CultMeshUnsubscribe; + public watch(context: CultMeshQueryContext | string, callback: (value: TDocument) => void): CultMeshUnsubscribe; + public watch( + contextOrCallback: CultMeshQueryContext | string | ((value: TDocument) => void), + maybeCallback?: (value: TDocument) => void, + ): CultMeshUnsubscribe { + if (!this.watchDocument) { + throw new Error(`Document '${this.documentId}' does not support watches.`); + } + + const callback = + typeof contextOrCallback === "function" ? contextOrCallback : maybeCallback; + if (!callback) { + throw new Error(`Document '${this.documentId}' requires a watch callback.`); + } + + const context = + typeof contextOrCallback === "function" + ? cultMeshQueryContext("local") + : typeof contextOrCallback === "string" + ? cultMeshQueryContext(contextOrCallback) + : contextOrCallback; + + return this.watchDocument(this.resolveContext(context), callback); + } + + public replace(value: TDocument): Promise; + public replace(context: CultMeshQueryContext | string, value: TDocument): Promise; + public replace( + contextOrValue: CultMeshQueryContext | string | TDocument, + maybeValue?: TDocument, + ): Promise { + if (!this.replaceDocument) { + throw new Error(`Document '${this.documentId}' does not support replacement.`); + } + + const hasContext = + typeof contextOrValue === "string" || isCultMeshQueryContext(contextOrValue); + const context = hasContext + ? typeof contextOrValue === "string" + ? cultMeshQueryContext(contextOrValue) + : contextOrValue as CultMeshQueryContext + : cultMeshQueryContext("local"); + const value = hasContext ? maybeValue : contextOrValue as TDocument; + if (value === undefined) { + throw new Error(`Document '${this.documentId}' requires a replacement value.`); + } + + return this.replaceDocument(this.resolveContext(context), value); + } + + public asSchemaAlias( + schema: CultMeshDocumentSchemaDescriptor, + options: { parse?: (value: unknown) => TAlias } = {}, + ): CultMeshDocumentHandle { + const aliasSchema = normalizeCultMeshDocumentSchema(schema); + if (!cultMeshSchemasAreCompatible(this.schema, aliasSchema)) { + throw new Error( + `Document '${this.documentId}' schema ${cultMeshSchemaLabel(this.schema)} is not compatible with alias ${cultMeshSchemaLabel(aliasSchema)}.`, + ); + } + + const parse = options.parse ?? ((value: unknown) => value as TAlias); + return new CultMeshDocumentHandle( + this.documentId, + aliasSchema, + async (context) => parse(await this.latest(context)), + { + sources: this.sources, + routeHint: this.routeHint, + watchDocument: this.watchDocument + ? (context, callback) => this.watch(context, value => callback(parse(value))) + : undefined, + replaceDocument: this.replaceDocument + ? (context, value) => this.replace(context, value as unknown as TDocument) + : undefined, + }, + ); + } + + public bind(verse: CultMeshVerseContext | CultMeshVerse): CultMeshBoundDocumentHandle { + return cultMeshBindDocument(verse, this); + } + + private resolveContext(context: CultMeshQueryContext): CultMeshQueryContext { + if (context.routeHint.kind !== "automatic" || this.routeHint.kind === "automatic") { + return context; + } + + return cultMeshQueryContext(context.runtimeId, { + routeHint: this.routeHint, + }); + } +} + +export class CultMeshBoundDocumentHandle { + public constructor( + public readonly verse: CultMeshVerseContext, + public readonly document: CultMeshDocumentHandle, + ) {} + + public get documentId(): string { + return this.document.documentId; + } + + public get schema(): CultMeshDocumentSchemaDescriptor { + return this.document.schema; + } + + public get canReplace(): boolean { + return this.document.canReplace; + } + + public latest(): Promise { + return this.document.latest(cultMeshQueryContextFromVerse(this.verse)); + } + + public read(): Promise { + return this.latest(); + } + + public watch(callback: (value: TDocument) => void): CultMeshUnsubscribe { + return this.document.watch(cultMeshQueryContextFromVerse(this.verse), callback); + } + + public replace(value: TDocument): Promise { + return this.document.replace(cultMeshQueryContextFromVerse(this.verse), value); + } + + public asSchemaAlias( + schema: CultMeshDocumentSchemaDescriptor, + options: { parse?: (value: unknown) => TAlias } = {}, + ): CultMeshBoundDocumentHandle { + return cultMeshBindDocument(this.verse, this.document.asSchemaAlias(schema, options)); + } +} + +export class CultMeshDocumentCatalog { + readonly #byDocumentId = new Map>(); + readonly #byType = new Map>(); + readonly #bySchemaId = new Map>(); + readonly #bySchemaNameVersion = new Map>(); + + public constructor(documents: Iterable>) { + for (const document of documents) { + this.add(document); + } + } + + public get documents(): readonly CultMeshDocumentHandle[] { + return [...this.#byDocumentId.values()]; + } + + public add(document: CultMeshDocumentHandle): this { + this.#byDocumentId.set(document.documentId, document as CultMeshDocumentHandle); + if (document.schema.type) { + this.#byType.set(document.schema.type, document as CultMeshDocumentHandle); + } + if (document.schema.schemaId) { + this.#bySchemaId.set(document.schema.schemaId, document as CultMeshDocumentHandle); + } + const key = cultMeshSchemaNameVersionKey(document.schema); + if (key) { + this.#bySchemaNameVersion.set(key, document as CultMeshDocumentHandle); + } + return this; + } + + public tryDocument( + schema: CultMeshDocumentSchemaDescriptor, + options: { parse?: (value: unknown) => TDocument } = {}, + ): CultMeshDocumentHandle | undefined { + const descriptor = normalizeCultMeshDocumentSchema(schema); + const exact = + (descriptor.type ? this.#byType.get(descriptor.type) : undefined) ?? + (descriptor.schemaId ? this.#bySchemaId.get(descriptor.schemaId) : undefined) ?? + (() => { + const key = cultMeshSchemaNameVersionKey(descriptor); + return key ? this.#bySchemaNameVersion.get(key) : undefined; + })(); + + if (!exact) { + return undefined; + } + + return cultMeshSchemasAreCompatible(exact.schema, descriptor) + ? exact.asSchemaAlias(descriptor, options) + : undefined; + } + + public document( + schema: CultMeshDocumentSchemaDescriptor, + options: { parse?: (value: unknown) => TDocument } = {}, + ): CultMeshDocumentHandle { + const document = this.tryDocument(schema, options); + if (!document) { + throw new Error(`Document catalog has no document for ${cultMeshSchemaLabel(schema)}.`); + } + return document; + } + + public latest( + schema: CultMeshDocumentSchemaDescriptor, + context: CultMeshQueryContext | string = "local", + options: { parse?: (value: unknown) => TDocument } = {}, + ): Promise { + return this.document(schema, options).latest(context); + } + + public watch( + schema: CultMeshDocumentSchemaDescriptor, + callback: (value: TDocument) => void, + options: { parse?: (value: unknown) => TDocument; context?: CultMeshQueryContext | string } = {}, + ): CultMeshUnsubscribe { + return this.document(schema, options).watch(options.context ?? "local", callback); + } +} + +export class CultMeshCollectionHandle { + public readonly schema: CultMeshDocumentSchemaDescriptor; + public readonly sources: readonly CultMeshProjectionSource[]; + public readonly routeHint: CultMeshRouteHint; + + public constructor( + public readonly collectionId: string, + schema: CultMeshDocumentSchemaDescriptor, + private readonly snapshotCollection: (context: CultMeshQueryContext) => Promise>, + options: { + sources?: readonly CultMeshProjectionSource[]; + routeHint?: CultMeshRouteHint; + watchCollection?: CultMeshCollectionWatcher; + } = {}, + ) { + requireNonEmpty(collectionId, "collectionId"); + this.schema = normalizeCultMeshDocumentSchema(schema); + this.sources = [...(options.sources ?? [])]; + this.routeHint = options.routeHint ?? cultMeshRouteHint(); + this.watchCollection = options.watchCollection; + } + + private readonly watchCollection: CultMeshCollectionWatcher | undefined; + + public latest(context: CultMeshQueryContext | string = "local"): Promise> { + return this.snapshotCollection( + this.resolveContext(typeof context === "string" ? cultMeshQueryContext(context) : context), + ); + } + + public watchChanges(callback: (change: CultMeshCollectionChange) => void): CultMeshUnsubscribe; + public watchChanges( + context: CultMeshQueryContext | string, + callback: (change: CultMeshCollectionChange) => void, + ): CultMeshUnsubscribe; + public watchChanges( + contextOrCallback: + | CultMeshQueryContext + | string + | ((change: CultMeshCollectionChange) => void), + maybeCallback?: (change: CultMeshCollectionChange) => void, + ): CultMeshUnsubscribe { + if (!this.watchCollection) { + throw new Error(`Collection '${this.collectionId}' does not support watches.`); + } + + const callback = + typeof contextOrCallback === "function" ? contextOrCallback : maybeCallback; + if (!callback) { + throw new Error(`Collection '${this.collectionId}' requires a watch callback.`); + } + + const context = + typeof contextOrCallback === "function" + ? cultMeshQueryContext("local") + : typeof contextOrCallback === "string" + ? cultMeshQueryContext(contextOrCallback) + : contextOrCallback; + + return this.watchCollection(this.resolveContext(context), callback); + } + + public asSchemaAlias( + schema: CultMeshDocumentSchemaDescriptor, + options: { parse?: (value: unknown) => TAlias } = {}, + ): CultMeshCollectionHandle { + const aliasSchema = normalizeCultMeshDocumentSchema(schema); + if (!cultMeshSchemasAreCompatible(this.schema, aliasSchema)) { + throw new Error( + `Collection '${this.collectionId}' schema ${cultMeshSchemaLabel(this.schema)} is not compatible with alias ${cultMeshSchemaLabel(aliasSchema)}.`, + ); + } + + const parse = options.parse ?? ((value: unknown) => value as TAlias); + return new CultMeshCollectionHandle( + this.collectionId, + aliasSchema, + async (context) => (await this.latest(context)).map(value => parse(value)), + { + sources: this.sources, + routeHint: this.routeHint, + watchCollection: this.watchCollection + ? (context, callback) => this.watchChanges(context, change => callback({ + ...change, + value: change.value === undefined ? undefined : parse(change.value), + })) + : undefined, + }, + ); + } + + public bind(verse: CultMeshVerseContext | CultMeshVerse): CultMeshBoundCollectionHandle { + return cultMeshBindCollection(verse, this); + } + + private resolveContext(context: CultMeshQueryContext): CultMeshQueryContext { + if (context.routeHint.kind !== "automatic" || this.routeHint.kind === "automatic") { + return context; + } + + return cultMeshQueryContext(context.runtimeId, { + routeHint: this.routeHint, + }); + } +} + +export class CultMeshBoundCollectionHandle { + public constructor( + public readonly verse: CultMeshVerseContext, + public readonly collection: CultMeshCollectionHandle, + ) {} + + public get collectionId(): string { + return this.collection.collectionId; + } + + public get schema(): CultMeshDocumentSchemaDescriptor { + return this.collection.schema; + } + + public latest(): Promise> { + return this.collection.latest(cultMeshQueryContextFromVerse(this.verse)); + } + + public watchChanges(callback: (change: CultMeshCollectionChange) => void): CultMeshUnsubscribe { + return this.collection.watchChanges(cultMeshQueryContextFromVerse(this.verse), callback); + } + + public asSchemaAlias( + schema: CultMeshDocumentSchemaDescriptor, + options: { parse?: (value: unknown) => TAlias } = {}, + ): CultMeshBoundCollectionHandle { + return cultMeshBindCollection(this.verse, this.collection.asSchemaAlias(schema, options)); + } +} + export class CultMeshStatePointer { public readonly sources: readonly CultMeshProjectionSource[]; public readonly routeHint: CultMeshRouteHint; @@ -1191,6 +1630,20 @@ export function cultMeshBindMutableStatePointer( return new CultMeshBoundMutableStatePointer(resolveCultMeshVerseContext(verse), pointer); } +export function cultMeshBindDocument( + verse: CultMeshVerseContext | CultMeshVerse, + document: CultMeshDocumentHandle, +): CultMeshBoundDocumentHandle { + return new CultMeshBoundDocumentHandle(resolveCultMeshVerseContext(verse), document); +} + +export function cultMeshBindCollection( + verse: CultMeshVerseContext | CultMeshVerse, + collection: CultMeshCollectionHandle, +): CultMeshBoundCollectionHandle { + return new CultMeshBoundCollectionHandle(resolveCultMeshVerseContext(verse), collection); +} + function resolveCultMeshVerseContext(verse: CultMeshVerseContext | CultMeshVerse): CultMeshVerseContext { return verse instanceof CultMeshVerse ? verse.context : verse; } @@ -1326,6 +1779,125 @@ export function cultMeshLiveFeed( return new CultMeshLiveFeed(feedId, snapshotFeed, options); } +export function cultMeshDocument( + documentId: string, + schema: CultMeshDocumentSchemaDescriptor, + snapshotDocument: (context: CultMeshQueryContext) => Promise, + options: { + sources?: readonly CultMeshProjectionSource[]; + routeHint?: CultMeshRouteHint; + watchDocument?: CultMeshDocumentWatcher; + replaceDocument?: CultMeshDocumentReplacer; + } = {}, +): CultMeshDocumentHandle { + return new CultMeshDocumentHandle(documentId, schema, snapshotDocument, options); +} + +export function cultMeshDocumentFromCache( + cache: CultCache, + definition: TDefinition, + key: string, + options: { + documentId?: string; + routeHint?: CultMeshRouteHint; + pollMs?: number; + } = {}, +): CultMeshDocumentHandle> { + requireNonEmpty(key, "key"); + const documentId = options.documentId ?? `${definition.type}:${key}`; + const schema = cultMeshSchemaFromDefinition(definition); + return cultMeshDocument( + documentId, + schema, + async () => cache.getRequired(definition, key), + { + routeHint: options.routeHint ?? cultMeshRouteHint("in-process", "CultCache"), + sources: [cultMeshProjectionSource(documentId, { schemaId: schema.schemaId })], + watchDocument: cultMeshPollingDocumentWatcher( + async () => cache.getRequired(definition, key), + { intervalMs: options.pollMs ?? 50 }, + ), + replaceDocument: async (_context, value) => { + await cache.put(definition, key, value); + }, + }, + ); +} + +export function cultMeshGlobalDocumentFromCache( + cache: CultCache, + definition: TDefinition, + options: { + documentId?: string; + routeHint?: CultMeshRouteHint; + pollMs?: number; + } = {}, +): CultMeshDocumentHandle> { + const documentId = options.documentId ?? `${definition.type}:global`; + const schema = cultMeshSchemaFromDefinition(definition); + return cultMeshDocument( + documentId, + schema, + async () => cache.getRequiredGlobal(definition), + { + routeHint: options.routeHint ?? cultMeshRouteHint("in-process", "CultCache"), + sources: [cultMeshProjectionSource(documentId, { schemaId: schema.schemaId })], + watchDocument: cultMeshPollingDocumentWatcher( + async () => cache.getRequiredGlobal(definition), + { intervalMs: options.pollMs ?? 50 }, + ), + replaceDocument: async (_context, value) => { + await cache.putGlobal(definition, value); + }, + }, + ); +} + +export function cultMeshDocuments( + ...documents: readonly CultMeshDocumentHandle[] +): CultMeshDocumentCatalog { + return new CultMeshDocumentCatalog(documents); +} + +export function cultMeshCollection( + collectionId: string, + schema: CultMeshDocumentSchemaDescriptor, + snapshotCollection: (context: CultMeshQueryContext) => Promise>, + options: { + sources?: readonly CultMeshProjectionSource[]; + routeHint?: CultMeshRouteHint; + watchCollection?: CultMeshCollectionWatcher; + } = {}, +): CultMeshCollectionHandle { + return new CultMeshCollectionHandle(collectionId, schema, snapshotCollection, options); +} + +export function cultMeshCollectionFromCache( + cache: CultCache, + definition: TDefinition, + options: { + collectionId?: string; + routeHint?: CultMeshRouteHint; + pollMs?: number; + } = {}, +): CultMeshCollectionHandle> { + const collectionId = options.collectionId ?? definition.type; + const schema = cultMeshSchemaFromDefinition(definition); + return cultMeshCollection( + collectionId, + schema, + async () => cache.getAll(definition), + { + routeHint: options.routeHint ?? cultMeshRouteHint("in-process", "CultCache"), + sources: [cultMeshProjectionSource(collectionId, { schemaId: schema.schemaId })], + watchCollection: cultMeshPollingCollectionWatcher( + async () => cache.getAll(definition), + { intervalMs: options.pollMs ?? 50 }, + ), + }, + ); +} + export function cultMeshDescribeLiveFeed( feed: { readonly feedId: string; @@ -1390,6 +1962,33 @@ export function cultMeshPollingQueryWatcher( }; } +export function cultMeshPollingDocumentWatcher( + readDocument: (context: CultMeshQueryContext) => Promise, + options: CultMeshPollingWatchOptions = {}, +): CultMeshDocumentWatcher { + const watch = cultMeshPollingQueryWatcher( + async (_parameters, context) => readDocument(context), + options, + ); + return (context, callback) => watch(undefined, context, callback); +} + +export function cultMeshPollingCollectionWatcher( + readCollection: (context: CultMeshQueryContext) => Promise>, + options: CultMeshPollingWatchOptions> = {}, +): CultMeshCollectionWatcher { + const watch = cultMeshPollingQueryWatcher>( + async (_parameters, context) => readCollection(context), + { + ...options, + equals: options.equals ?? ((left, right) => JSON.stringify(left) === JSON.stringify(right)), + }, + ); + return (context, callback) => watch(undefined, context, () => callback({ + kind: "reset", + })); +} + export function cultMeshStatePointer( pointerId: string, resolvePointer: (() => Promise) | CultMeshStatePointerResolver, @@ -2122,6 +2721,40 @@ export class CultMeshNode { return this.cache.delete(definition, key); } + public document( + definition: TDefinition, + key: string, + options: { + documentId?: string; + routeHint?: CultMeshRouteHint; + pollMs?: number; + } = {}, + ): CultMeshDocumentHandle> { + return cultMeshDocumentFromCache(this.cache, definition, key, options); + } + + public globalDocument( + definition: TDefinition, + options: { + documentId?: string; + routeHint?: CultMeshRouteHint; + pollMs?: number; + } = {}, + ): CultMeshDocumentHandle> { + return cultMeshGlobalDocumentFromCache(this.cache, definition, options); + } + + public collection( + definition: TDefinition, + options: { + collectionId?: string; + routeHint?: CultMeshRouteHint; + pollMs?: number; + } = {}, + ): CultMeshCollectionHandle> { + return cultMeshCollectionFromCache(this.cache, definition, options); + } + public async flush(soft = false): Promise { await this.store.pushAll?.(this.cache.snapshot(), { soft }); } @@ -2819,6 +3452,90 @@ export class CultMesh { return cultMeshLiveFeed(feedId, snapshotFeed, options); } + public static document( + documentId: string, + schema: CultMeshDocumentSchemaDescriptor, + snapshotDocument: (context: CultMeshQueryContext) => Promise, + options: { + sources?: readonly CultMeshProjectionSource[]; + routeHint?: CultMeshRouteHint; + watchDocument?: CultMeshDocumentWatcher; + replaceDocument?: CultMeshDocumentReplacer; + } = {}, + ): CultMeshDocumentHandle { + return cultMeshDocument(documentId, schema, snapshotDocument, options); + } + + public static documentFromCache( + cache: CultCache, + definition: TDefinition, + key: string, + options: { + documentId?: string; + routeHint?: CultMeshRouteHint; + pollMs?: number; + } = {}, + ): CultMeshDocumentHandle> { + return cultMeshDocumentFromCache(cache, definition, key, options); + } + + public static globalDocumentFromCache( + cache: CultCache, + definition: TDefinition, + options: { + documentId?: string; + routeHint?: CultMeshRouteHint; + pollMs?: number; + } = {}, + ): CultMeshDocumentHandle> { + return cultMeshGlobalDocumentFromCache(cache, definition, options); + } + + public static documents( + ...documents: readonly CultMeshDocumentHandle[] + ): CultMeshDocumentCatalog { + return cultMeshDocuments(...documents); + } + + public static bindDocument( + verse: CultMeshVerseContext | CultMeshVerse, + document: CultMeshDocumentHandle, + ): CultMeshBoundDocumentHandle { + return cultMeshBindDocument(verse, document); + } + + public static collection( + collectionId: string, + schema: CultMeshDocumentSchemaDescriptor, + snapshotCollection: (context: CultMeshQueryContext) => Promise>, + options: { + sources?: readonly CultMeshProjectionSource[]; + routeHint?: CultMeshRouteHint; + watchCollection?: CultMeshCollectionWatcher; + } = {}, + ): CultMeshCollectionHandle { + return cultMeshCollection(collectionId, schema, snapshotCollection, options); + } + + public static collectionFromCache( + cache: CultCache, + definition: TDefinition, + options: { + collectionId?: string; + routeHint?: CultMeshRouteHint; + pollMs?: number; + } = {}, + ): CultMeshCollectionHandle> { + return cultMeshCollectionFromCache(cache, definition, options); + } + + public static bindCollection( + verse: CultMeshVerseContext | CultMeshVerse, + collection: CultMeshCollectionHandle, + ): CultMeshBoundCollectionHandle { + return cultMeshBindCollection(verse, collection); + } + public static describeLiveFeed( feed: { readonly feedId: string; @@ -3660,6 +4377,69 @@ export class CultMesh { } } +function cultMeshSchemaFromDefinition( + definition: AnyCultCacheDocumentDefinition, +): CultMeshDocumentSchemaDescriptor { + return { + type: definition.type, + schemaId: definition.schemaId ?? definition.type, + schemaName: definition.schemaName, + schemaVersion: definition.schemaVersion, + }; +} + +function normalizeCultMeshDocumentSchema( + schema: CultMeshDocumentSchemaDescriptor, +): CultMeshDocumentSchemaDescriptor { + const normalized = { + type: schema.type?.trim() || undefined, + schemaId: schema.schemaId?.trim() || undefined, + schemaName: schema.schemaName?.trim() || undefined, + schemaVersion: schema.schemaVersion?.trim() || undefined, + }; + + if (!normalized.type && !normalized.schemaId && !normalized.schemaName) { + throw new Error("Document schema must include type, schemaId, or schemaName."); + } + + return normalized; +} + +function cultMeshSchemaNameVersionKey( + schema: CultMeshDocumentSchemaDescriptor, +): string | undefined { + return schema.schemaName + ? `${schema.schemaName}@${schema.schemaVersion ?? ""}` + : undefined; +} + +function cultMeshSchemasAreCompatible( + left: CultMeshDocumentSchemaDescriptor, + right: CultMeshDocumentSchemaDescriptor, +): boolean { + if (left.schemaId && right.schemaId && left.schemaId === right.schemaId) { + return true; + } + + if ( + left.schemaName && + right.schemaName && + left.schemaName === right.schemaName && + (left.schemaVersion ?? "") === (right.schemaVersion ?? "") + ) { + return true; + } + + return Boolean(left.type && right.type && left.type === right.type); +} + +function cultMeshSchemaLabel(schema: CultMeshDocumentSchemaDescriptor): string { + return schema.schemaId ?? + cultMeshSchemaNameVersionKey(schema) ?? + schema.type ?? + ""; +} + function requireNonEmpty(value: string, name: string): void { if (!value || value.trim().length === 0) { throw new Error(`${name} must be non-empty.`); diff --git a/packages/cultmesh-ts/test/cultmesh.test.ts b/packages/cultmesh-ts/test/cultmesh.test.ts index 1fd8ffa3..2660595d 100644 --- a/packages/cultmesh-ts/test/cultmesh.test.ts +++ b/packages/cultmesh-ts/test/cultmesh.test.ts @@ -24,6 +24,16 @@ const noteDocument = defineDocumentType({ name: "noteId", }); +const noteAliasDocument = defineDocumentType({ + type: "cultmesh.note.ui", + schemaId: "cultmesh.note.v0", + schema: z.object({ + noteId: z.string(), + body: z.string(), + }), + name: "noteId", +}); + async function waitFor(predicate: () => boolean, description: string): Promise { const startedAt = Date.now(); while (!predicate()) { @@ -58,6 +68,89 @@ test("CultMesh TS opens a durable local node and registers document bindings", a assert.ok(reopened.documents.getBySchemaId("cultmesh.note.v0")); }); +test("CultMesh TS document handles hide local cache plumbing behind typed reactive reads", async () => { + const filePath = join(await mkdtemp(join(tmpdir(), "cultmesh-ts-doc-")), "node.ccmp"); + const node = await CultMesh.startNode(filePath, { + documents: [noteDocument], + }); + await node.put(noteDocument, "note:1", { + noteId: "note:1", + body: "initial", + }); + + const document = node.document(noteDocument, "note:1", { pollMs: 5 }); + const verse = CultMesh.verse("local", "browser-client", { + routeHint: CultMesh.routeHint("shared-memory", "local cache"), + }); + const bound = verse.bindDocument(document); + const observed: string[] = []; + const unsubscribe = bound.watch(note => observed.push(note.body)); + + assert.equal(document.documentId, "cultmesh.note:note:1"); + assert.equal(document.canReplace, true); + assert.equal((await bound.latest()).body, "initial"); + + await bound.replace({ + noteId: "note:1", + body: "updated", + }); + await waitFor(() => observed.includes("updated"), "document handle update"); + unsubscribe(); + + const alias = bound.asSchemaAlias(noteAliasDocument, { + parse: value => noteAliasDocument.schema.parse(value), + }); + assert.equal((await alias.latest()).body, "updated"); + + const catalog = CultMesh.documents(document); + assert.equal( + (await catalog.latest(noteAliasDocument, "browser-client", { + parse: value => noteAliasDocument.schema.parse(value), + })).body, + "updated", + ); + assert.throws( + () => document.asSchemaAlias({ schemaId: "cultmesh.other.v0" }), + /not compatible/, + ); +}); + +test("CultMesh TS collection handles expose typed snapshots and reset watches", async () => { + const filePath = join(await mkdtemp(join(tmpdir(), "cultmesh-ts-coll-")), "node.ccmp"); + const node = await CultMesh.startNode(filePath, { + documents: [noteDocument], + }); + await node.put(noteDocument, "note:a", { + noteId: "note:a", + body: "alpha", + }); + + const collection = node.collection(noteDocument, { pollMs: 5 }); + const bound = CultMesh.bindCollection( + CultMesh.verse("local", "rts-client").withRoute("shared-memory", "local cache"), + collection, + ); + const changes: string[] = []; + const unsubscribe = bound.watchChanges(change => changes.push(change.kind)); + + assert.deepEqual((await bound.latest()).map(note => note.body), ["alpha"]); + + await node.put(noteDocument, "note:b", { + noteId: "note:b", + body: "bravo", + }); + await waitFor(() => changes.length >= 2, "collection reset after update"); + unsubscribe(); + + assert.deepEqual( + (await collection.asSchemaAlias(noteAliasDocument, { + parse: value => noteAliasDocument.schema.parse(value), + }).latest()).map(note => note.body).sort(), + ["alpha", "bravo"], + ); + assert.ok(changes.every(kind => kind === "reset")); +}); + test("CultMesh TS local authority leases do not trust peer cards by contact alone", () => { const peers = CultMesh.createPeerCatalog(); const leases = CultMesh.createAuthorityLeaseCatalog(); diff --git a/src/GameCult.Mesh/docs/public-api.md b/src/GameCult.Mesh/docs/public-api.md index 3a35d7f8..e34d8263 100644 --- a/src/GameCult.Mesh/docs/public-api.md +++ b/src/GameCult.Mesh/docs/public-api.md @@ -307,6 +307,38 @@ const objects = await visibleObjects.execute(viewportRequest); await movePilot.invoke({ actorEntityKey, directionX: 1, directionY: 0 }); ``` +TypeScript runtimes expose the same document and collection handle shape: + +```ts +const station = await CultMesh.startNode(statePath, { + documents: [stationStockDocument, currentDockingDocument], +}); + +const stock = station.document(stationStockDocument, "station:starbridge:stock"); +const docking = station.document(currentDockingDocument, "player:raven:docking"); +const catalog = CultMesh.documents(stock, docking); + +const stockUi = catalog.document(stationStockUiDocument, { + parse: value => stationStockUiDocument.schema.parse(value), +}); + +const currentStock = await stockUi.latest(); +const unsubscribe = stockUi.watch(next => renderStock(next)); +await stockUi.replace(updatedStock); +unsubscribe(); + +const pilots = station.collection(playerShipDocument); +const currentPilots = await pilots.latest(); +const stopRoster = pilots.watchChanges(change => refreshRoster(change)); +``` + +Projected, remote, shared-memory, IPC, WASM, and local-cache documents all use +the same TS handle contract. The caller names the typed document or collection +it wants; the handle owns route defaults, snapshot reads, reactive watches, +schema alias validation, and replacement when the backing source is mutable. +Generated Aetheria and Ymir facades should bind those handles to a Verse once +and keep transport, quorum, and cache mechanics behind CultMesh. + Native view descriptors can name unmanaged columns without hand-entered byte sizes: