import { BlockKindReference } from "@milaboratories/pl-model-common"; import { CompiledBlockKind } from "@platforma-sdk/block-kind"; export type DataVersionKey = string; export type DataMigrateFn = (prev: Readonly) => To; /** * Initial-data factory. Object-arg so future inputs (services, resolved refs) * can extend it without a signature break. `Params` carries the block's * kind-declared params type; `never` means the block reads no params yet. */ export type DataCreateFn = (args: { params?: Params; }) => T; export type DataRecoverFn = (version: DataVersionKey, data: unknown) => T; /** * The compiled block-kind object a block declares — exactly the output of * `defineBlockKind` from `@platforma-sdk/block-kind`, consumed type-only. * * The kind object carries no reference field: the `{name}@{version}` reference * is derived from it internally (via `formatKindRef`) at the point the builder * and `BlockModelV3.create` need it. Aliased here so `DataModelBuilder` / * `create` signatures directly accept `defineBlockKind`'s output. */ export type BlockKind = CompiledBlockKind; /** * Minimal interface that .transfer() accepts. PluginInstance implements this. * Defined here to avoid circular dependency with plugin_model.ts. */ export interface TransferTarget { readonly id: Id; /** Version key in the plugin's data model chain where transferred data enters. */ readonly transferVersion: string; /** @internal Phantom field for TransferData type extraction */ readonly __transferBrand?: TransferData; } /** Internal record of a single transfer step in the migration chain. */ export type TransferStep = { pluginId: string; /** Capture data before this step index executes. */ beforeStepIndex: number; extract: (data: unknown) => unknown; /** Version key in the plugin's data model chain where the transferred data enters. */ targetVersion: string; }; /** Map of plugin ID → versioned data extracted during migration. */ export type TransferRecord = Record>; /** Versioned data wrapper for persistence */ export type DataVersioned = { version: DataVersionKey; data: T; }; type MigrationStep = { fromVersion: DataVersionKey; toVersion: DataVersionKey; migrate: (data: unknown) => unknown; }; /** Symbol for internal builder creation method */ declare const FROM_BUILDER: unique symbol; /** Legacy V1 model state shape: { args, uiState } */ export type LegacyV1State = { args: Args; uiState: UiState; }; /** * The kind a chain belongs to, threaded unchanged from the builder into `DataModel`. * * Named because every constructor in this file carries exactly this pair, and they travel * together by construction: a reference with no parser could not check the params it names, * and a parser with no reference would have nothing to check them against. */ type KindWiring = { /** Reference to the block kind this data model belongs to, if declared. */ kindRef?: BlockKindReference; /** The kind's runtime params check, threaded with {@link KindWiring.kindRef}. */ parseInitializationParams?: (value: unknown) => unknown; }; type RecoverState = { recoverFn?: (version: DataVersionKey, data: unknown) => unknown; /** Index of the first step to run after recovery. Equals the number of steps * present at the time recover() was called. */ recoverFromIndex?: number; }; /** Internal state passed from builder to DataModel */ type BuilderState = KindWiring & RecoverState & { versionChain: DataVersionKey[]; steps: MigrationStep[]; transferSteps: TransferStep[]; /** * The params type is erased to `unknown` here: the builder checks the block's * factory against its kind's params, but a caller that supplies params carries them as * data it did not type — parsed file content, today — and cannot state the type. The * kind's own parser is what recovers it. */ initialDataFn: DataCreateFn; }; /** * Abstract base for both migration chain types. * Holds shared state, buildStep() helper, and init(). * migrate() cannot be shared due to a TypeScript limitation: when the base class * migrate() return type is abstract, subclasses cannot narrow it without losing type safety. * Each subclass therefore owns its migrate() with the correct concrete return type. * * @internal */ declare abstract class MigrationChainBase = {}, Params = never> { protected readonly versionChain: DataVersionKey[]; protected readonly migrationSteps: MigrationStep[]; protected readonly transferSteps: TransferStep[]; /** Kind reference seeded by the builder, threaded through the chain into init(). */ protected readonly kindRef?: BlockKindReference; /** The kind's runtime params check, carried for `init()` to hand to the DataModel. */ protected readonly parseInitializationParams?: (value: unknown) => unknown; protected constructor(state: KindWiring & { versionChain: DataVersionKey[]; steps: MigrationStep[]; transferSteps?: TransferStep[]; }); /** Appends a migration step and returns the new versionChain and steps arrays. */ protected buildStep(nextVersion: string, fn: DataMigrateFn): { versionChain: DataVersionKey[]; steps: MigrationStep[]; }; /** Validates uniqueness and records a TransferStep. */ protected buildTransfer(target: TransferTarget, extract: (data: Current) => L): { transferSteps: TransferStep[]; }; /** Returns recover-specific fields for DataModel construction. Overridden by WithRecover. */ protected recoverState(): RecoverState; /** * Finalize the DataModel with initial data factory. * * @param initialData - Factory function returning the initial state * @returns Finalized DataModel instance */ init(initialData: DataCreateFn): DataModel; } /** * Migration chain after recover() or upgradeLegacy() has been called. * Further migrate() and transfer() calls are allowed; recover() and upgradeLegacy() are not * (enforced by type — no such methods on this class). * * @typeParam Current - Data type at the current point in the chain * @typeParam Transfers - Accumulated transfer types keyed by plugin ID * @internal */ declare class DataModelMigrationChainWithRecover = {}, Params = never> extends MigrationChainBase { private readonly recoverFn?; private readonly recoverFromIndex?; /** @internal */ constructor(state: KindWiring & RecoverState & { versionChain: DataVersionKey[]; steps: MigrationStep[]; transferSteps?: TransferStep[]; }); protected recoverState(): RecoverState; /** * Add a migration step. Same semantics as on the base chain. * recover() and upgradeLegacy() are not available — one has already been called. */ migrate(nextVersion: string, fn: DataMigrateFn): DataModelMigrationChainWithRecover; /** * Extract data at the current chain position for seeding a new plugin. * The extract function's return type must match the plugin's transfer data type. * Duplicate plugin IDs are rejected at both type and runtime level. */ transfer(target: TransferTarget, extract: (data: Current) => L): DataModelMigrationChainWithRecover, Params>; } /** * Migration chain builder. * Each migrate() call advances the current data type. recover() can be called once * at any point — it removes itself from the returned chain so it cannot be called again. * Duplicate version keys throw at runtime. * * @typeParam Current - Data type at the current point in the migration chain * @typeParam Transfers - Accumulated transfer types keyed by plugin ID * @internal */ declare class DataModelMigrationChain = {}, Params = never> extends MigrationChainBase { /** @internal */ constructor({ versionChain, steps, transferSteps, kindRef, parseInitializationParams }: KindWiring & { versionChain: DataVersionKey[]; steps?: MigrationStep[]; transferSteps?: TransferStep[]; }); /** * Add a migration step transforming data from the current version to the next. * * @typeParam Next - Data type of the next version * @param nextVersion - Version key to migrate to (must be unique in the chain) * @param fn - Migration function * @returns Builder with the next version as current * * @example * .migrate("v2", (v1) => ({ ...v1, labels: [] })) */ migrate(nextVersion: string, fn: DataMigrateFn): DataModelMigrationChain; /** * Extract data at the current chain position for seeding a new plugin. * The extract function's return type must match the plugin's transfer data type. * Duplicate plugin IDs are rejected at both type and runtime level. * * Calling .transfer() on DataModelInitialChain returns DataModelMigrationChain, * which removes .upgradeLegacy() from the chain (preventing a problematic combination). * * @example * .from("v1") * .transfer(tablePlugin, (v1) => ({ state: v1.tableState })) * .migrate("v2", ({ tableState: _, ...rest }) => rest) */ transfer(target: TransferTarget, extract: (data: Current) => L): DataModelMigrationChain, Params>; /** * Set a recovery handler for unknown or legacy versions. * * The recover function is called when data has a version not in the migration chain. * It must return data of the type at this point in the chain (Current). Any migrate() * steps added after recover() will then run on the recovered data. * * Can only be called once — the returned chain has no recover() method. * * @param fn - Recovery function returning Current (the type at this chain position) * @returns Builder with migrate() and init() but without recover() * * @example * // Recover between migrations — recovered data goes through v3 migration * new DataModelBuilder("v1") * .migrate("v2", (v1) => ({ ...v1, label: "" })) * .recover((version, data) => { * if (version === 'legacy') return transformLegacy(data); // returns V2 * return defaultRecover(version, data); * }) * .migrate("v3", (v2) => ({ ...v2, description: "" })) * .init(() => ({ count: 0, label: "", description: "" })); */ recover(fn: DataRecoverFn): DataModelMigrationChainWithRecover; } /** * Initial migration chain returned by `.from()`. * Extends DataModelMigrationChain with `upgradeLegacy()` — available only before * any `.migrate()` calls, since legacy data always arrives at the initial version. * * @typeParam Current - Data type at the initial version * @typeParam Transfers - Accumulated transfer types keyed by plugin ID * @internal */ declare class DataModelInitialChain = {}, Params = never> extends DataModelMigrationChain { /** * Handle legacy V1 model state ({ args, uiState }) when upgrading a block from * BlockModel V1 to BlockModelV3. * * When a V1 block is upgraded, its stored state `{ args, uiState }` is normalized * to the internal default version. This method inserts a migration step from that * internal version to the version specified in `.from()`, using the provided typed * callback to transform the legacy shape. Non-legacy data passes through unchanged. * * Must be called right after `.from()` — not available after `.migrate()` calls. * Any `.migrate()` steps added after `upgradeLegacy()` will run on the transformed result. * * Can only be called once — the returned chain has no upgradeLegacy() method. * Mutually exclusive with recover(). * * @typeParam Args - Type of the legacy block args * @typeParam UiState - Type of the legacy block uiState * @param fn - Typed transform from { args, uiState } to Current * @returns Builder with migrate() and init() but without recover() or upgradeLegacy() * * @example * type OldArgs = { inputFile: string; threshold: number }; * type OldUiState = { selectedTab: string }; * type BlockData = { inputFile: string; threshold: number; selectedTab: string }; * * const dataModel = new DataModelBuilder() * .from("v1") * .upgradeLegacy(({ args, uiState }) => ({ * inputFile: args.inputFile, * threshold: args.threshold, * selectedTab: uiState.selectedTab, * })) * .init(() => ({ inputFile: '', threshold: 0, selectedTab: 'main' })); */ upgradeLegacy(fn: (legacy: LegacyV1State) => Current): DataModelMigrationChainWithRecover; } /** * Builder entry point for creating DataModel with type-safe migrations. * * @example * // Simple (no migrations): * const dataModel = new DataModelBuilder() * .from("v1") * .init(() => ({ numbers: [] })); * * @example * // With migrations: * const dataModel = new DataModelBuilder() * .from("v1") * .migrate("v2", (v1) => ({ ...v1, labels: [] })) * .migrate("v3", (v2) => ({ ...v2, description: '' })) * .init(() => ({ numbers: [], labels: [], description: '' })); * * @example * // With recover() between migrations — recovered data goes through remaining migrations: * const dataModelChain = new DataModelBuilder() * .from("v1") * .migrate("v2", (v1) => ({ ...v1, labels: [] })); * * // recover() placed before the v3 migration: recovered data goes through v3 * const dataModel = dataModelChain * .recover((version, data) => { * if (version === 'legacy' && isLegacyData(data)) return transformLegacy(data); // returns V2 * return defaultRecover(version, data); * }) * .migrate("v3", (v2) => ({ ...v2, description: '' })) * .init(() => ({ numbers: [], labels: [], description: '' })); * * @example * // With upgradeLegacy() — typed upgrade from BlockModel V1 state: * type OldArgs = { inputFile: string }; * type OldUiState = { selectedTab: string }; * type BlockData = { inputFile: string; selectedTab: string }; * * const dataModel = new DataModelBuilder() * .from("v1") * .upgradeLegacy(({ args, uiState }) => ({ * inputFile: args.inputFile, * selectedTab: uiState.selectedTab, * })) * .init(() => ({ inputFile: '', selectedTab: 'main' })); */ export declare class DataModelBuilder { #private; /** * @param opts.kind - The block kind this data model implements. Its reference * is captured and baked into the config so the manifest can advertise which * kind the block satisfies, and its `Params` type flows into `.init()`. * Optional during the transition window while existing V3 blocks are * migrated to kind-carrying builders; a kind-less builder simply carries no * reference and the reconciler can't project it yet. Object form mirrors * `BlockModelV3.create({ dataModel, kind })`. */ constructor(opts?: { kind?: BlockKind; }); /** * Start the migration chain with the given initial data type and version key. * * @typeParam T - Data type for the initial version * @param initialVersion - Version key string (e.g. "v1") * @returns Migration chain builder */ from(initialVersion: string): DataModelInitialChain; } /** * DataModel defines the block's data structure, initial values, and migrations. * Used by BlockModelV3 to manage data state. * * Use `new DataModelBuilder()` to create a DataModel. * * @example * // With recover() between migrations: * // Recovered data (V2) goes through the v2→v3 migration automatically. * const dataModel = new DataModelBuilder() * .from("v1") * .migrate("v2", (v1) => ({ ...v1, label: "" })) * .recover((version, data) => { * if (version === "legacy") return transformLegacy(data); // returns V2 * return defaultRecover(version, data); * }) * .migrate("v3", (v2) => ({ ...v2, description: "" })) * .init(() => ({ count: 0, label: "", description: "" })); */ export declare class DataModel = {}> { /** @internal Phantom field to anchor the Transfers type parameter. */ readonly __transfers?: Transfers; /** @internal Phantom field to anchor the Params type parameter (drives the * compile-time kind cross-check in `BlockModelV3.create`). */ readonly __params?: Params; /** Latest version key — O(1) access for the common "already current" check. */ private readonly latestVersion; /** Maps each known version key to the index of the first step to run from it. O(1) lookup. */ private readonly stepsByFromVersion; private readonly steps; private readonly transferSteps; private readonly initialDataFn; private readonly recoverFn; private readonly recoverFromIndex; /** Reference to the block kind this data model was built for, if any. */ private readonly _kindRef?; /** The kind's runtime params check, if it declares one. */ private readonly _parseInitializationParams?; private constructor(); /** * Internal method for creating DataModel from builder. * Uses Symbol key to prevent external access. * @internal */ static [FROM_BUILDER] = {}>(state: BuilderState): DataModel; /** * Reference to the block kind this data model was built for, or `undefined` * for a kind-less builder. Used by `BlockModelV3.create` to cross-check that * the kind handed to the builder matches the kind handed to `create`. * @internal */ get kindRef(): BlockKindReference | undefined; /** * The kind's runtime params check, or `undefined` if the kind declares none (or * there is no kind). Read by `BlockModelV3.done()` to register the check, and * carried here rather than only on the model because `init` — the one place params * are consumed — lives on this side. * @internal */ get templateParamsParser(): ((value: unknown) => unknown) | undefined; /** * The latest (current) version key in the migration chain. */ get version(): DataVersionKey; /** * Get a fresh copy of the initial data. */ initialData(): State; /** * Get initial data wrapped with current version. * Used when creating new blocks or resetting to defaults. */ getDefaultData(): DataVersioned; /** * Get initial data built from params, wrapped with current version. * * The counterpart of {@link getDefaultData} for a block created from a template * entry: the factory receives the entry's params instead of nothing. A factory * that ignores its argument produces the same result as `getDefaultData`, which * is why the two are separate methods rather than one optional argument — the * caller decides which contract it is asking for, and a block that cannot honour * params must not silently look like one that can. * * References inside `params` are already resolved to the target project's * concrete ids by the time they get here; the factory never sees a * template-local one. */ getDataFromParams(params: unknown): DataVersioned; private recoverFrom; /** * Migrate versioned data from any version to the latest. * Collects transfer extractions at their designated chain positions. * * - If version is in chain, applies needed migrations (O(1) lookup) * - If version is unknown, attempts recovery; falls back to initial data * - If a migration step fails, throws so the caller can preserve original data * * Transfers only fire during normal step-by-step migration: * - Recovery path: returns empty transfers * - Fast-path (already at latest): returns empty transfers * * @param versioned - Data with version tag * @returns Migrated data at the latest version with transfer record * @throws If a migration step from a known version fails */ migrate(versioned: DataVersioned): DataVersioned & { transfers: TransferRecord; }; } export {}; //# sourceMappingURL=block_migrations.d.ts.map