import type { ApplogForInsertOptionalAgent, ApplogValue, EntityID } from '../applog/datom-types.ts' /** * Generic ObjectBuilder for type-safe entity creation and updates. * * Provides a fluent API to build a set of applogs for an entity. * Modeled after the note3 builder pattern. * * Usage: * ```ts * ObjectBuilder.create({ name: 'foo' }) * .update({ type: 'bar' }) * .build(thread) * ``` */ export class ObjectBuilder< TARGET extends Record = Record, > { constructor( private _data: Partial, public en: EntityID | null = null, private _atPrefix: string | null = null, private _atOverrides: Partial> = {}, ) {} /** * Create a new builder with initial data. */ static create>( init: Partial = {}, en?: EntityID, atPrefix?: string, atOverrides?: Partial>, ): ObjectBuilder { return new ObjectBuilder(init, en, atPrefix, atOverrides) } /** * Update the data being built. */ update(updateObj: Partial): this { Object.assign(this._data, updateObj) return this } /** * Build the applogs for this entity, optionally resolving against a thread. */ build(thread?: { insert(applogs: ApplogForInsertOptionalAgent[]): ApplogForInsertOptionalAgent[] }): ApplogForInsertOptionalAgent[] { const atPrefix = this._atPrefix const applogs: ApplogForInsertOptionalAgent[] = [] for (const [key, value] of Object.entries(this._data) as [keyof TARGET, ApplogValue][]) { if (value === undefined) continue const atOverride = this._atOverrides[key] const at = atOverride ?? (atPrefix ? `${atPrefix}/${String(key)}` : String(key)) applogs.push({ en: this.en!, at, vl: value }) } return applogs } /** * Get the raw data being built. */ get data(): Partial { return { ...this._data } } }