{"version":3,"file":"block_storage.cjs","names":["obj","isDataUnrecoverableError"],"sources":["../src/block_storage.ts"],"sourcesContent":["/**\n * BlockStorage - Typed storage abstraction for block persistent data.\n *\n * This module provides:\n * - A typed structure for block storage with versioning and plugin support\n * - Utility functions for manipulating storage\n * - Handler interfaces for model-level customization\n *\n * @module block_storage\n */\n\nimport type { Branded } from \"@milaboratories/pl-model-common\";\nimport {\n  type DataVersioned,\n  type TransferRecord,\n  isDataUnrecoverableError,\n} from \"./block_migrations\";\nimport type { PluginHandle, PluginFactoryLike, InferFactoryData } from \"./plugin_handle\";\n\n// =============================================================================\n// Core Types\n// =============================================================================\n\n/**\n * Discriminator key for BlockStorage format detection.\n * This unique hash-based key identifies data as BlockStorage vs legacy formats.\n */\nexport const BLOCK_STORAGE_KEY = \"__pl_a7f3e2b9__\";\n\n/**\n * Current BlockStorage schema version.\n * Increment this when the storage structure itself changes (not block state migrations).\n */\nexport const BLOCK_STORAGE_SCHEMA_VERSION = \"v1\";\n\n/**\n * Default data version for new blocks without migrations.\n * Unique identifier ensures blocks are created via DataModel API.\n */\nexport const DATA_MODEL_LEGACY_VERSION = \"__pl_v1_d4e8f2a1__\";\n\n/**\n * Type for valid schema versions\n */\nexport type BlockStorageSchemaVersion = \"v1\"; // Add 'v2', 'v3', etc. as schema evolves\n\n/**\n * Branded type for plugin names - globally unique plugin type identifiers.\n * Using a branded type enforces explicit casting (`as PluginName`) which makes\n * it easy to find all plugin name definitions in the codebase and verify uniqueness.\n */\nexport type PluginName = Branded<string, \"PluginName\">;\n\n/**\n * Plugin registry - maps pluginId (unique within a block) to pluginName (globally unique plugin type).\n * Using a Record highlights that pluginIds must be unique within a block.\n */\nexport type PluginRegistry = Record<PluginHandle, PluginName>;\n\n/**\n * Versioned data - used for both block data and plugin data\n */\nexport interface VersionedData<TData = unknown> {\n  /** Version of the data, used for migrations */\n  __dataVersion: string;\n  /** The persistent data */\n  __data: TData;\n}\n\n/**\n * Core BlockStorage type that holds:\n * - __pl_a7f3e2b9__: Schema version (discriminator key identifies BlockStorage format)\n * - __dataVersion: Version key for block data migrations\n * - __data: The block's user-facing data (state)\n * - __pluginRegistry: Map from pluginId to pluginName (optional)\n * - __plugins: Plugin-specific data keyed by pluginId (optional)\n */\nexport type BlockStorage<TState = unknown> = {\n  /** Schema version - the key itself is the discriminator */\n  readonly [BLOCK_STORAGE_KEY]: BlockStorageSchemaVersion;\n  /** Registry of plugins: pluginId -> pluginName */\n  __pluginRegistry?: PluginRegistry;\n  /** Plugin-specific data, keyed by plugin handle */\n  __plugins?: Record<PluginHandle, VersionedData<unknown>>;\n} & VersionedData<TState>;\n\n/**\n * Type guard to check if a value is a valid BlockStorage object.\n * Checks for the discriminator key and valid schema version.\n */\nexport function isBlockStorage(value: unknown): value is BlockStorage {\n  if (value === null || typeof value !== \"object\") return false;\n  const obj = value as Record<string, unknown>;\n  const schemaVersion = obj[BLOCK_STORAGE_KEY];\n  // Currently only 'v1' is valid, but this allows future versions\n  return schemaVersion === \"v1\"; // Add more versions as schema evolves\n}\n\n// =============================================================================\n// Factory Functions\n// =============================================================================\n\n/**\n * Creates a BlockStorage with the given initial data\n *\n * @param initialData - The initial data value (defaults to empty object)\n * @param version - The initial data version key (defaults to DATA_MODEL_LEGACY_VERSION)\n * @returns A new BlockStorage instance with discriminator key\n */\nexport function createBlockStorage<TState = unknown>(\n  initialData: TState = {} as TState,\n  version: string = DATA_MODEL_LEGACY_VERSION,\n): BlockStorage<TState> {\n  return {\n    [BLOCK_STORAGE_KEY]: BLOCK_STORAGE_SCHEMA_VERSION,\n    __dataVersion: version,\n    __data: initialData,\n    __pluginRegistry: {},\n    __plugins: {},\n  };\n}\n\n/**\n * Normalizes raw storage data to BlockStorage format.\n * If the input is already a BlockStorage, returns it as-is (with defaults for missing fields).\n * If the input is legacy format (raw state), wraps it in BlockStorage structure.\n *\n * @param raw - Raw storage data (may be legacy format or BlockStorage)\n * @returns Normalized BlockStorage\n */\nexport function normalizeBlockStorage<TState = unknown>(raw: unknown): BlockStorage<TState> {\n  if (isBlockStorage(raw)) {\n    const storage = raw as BlockStorage<TState>;\n    return {\n      ...storage,\n      // Fix for early released version where __dataVersion was a number\n      __dataVersion:\n        typeof storage.__dataVersion === \"number\"\n          ? DATA_MODEL_LEGACY_VERSION\n          : storage.__dataVersion,\n      // Ensure plugin fields have defaults\n      __pluginRegistry: storage.__pluginRegistry ?? {},\n      __plugins: storage.__plugins ?? {},\n    };\n  }\n  // Legacy format: raw is the state directly\n  return createBlockStorage(raw as TState);\n}\n\n// =============================================================================\n// Data Access & Update Functions\n// =============================================================================\n\n/**\n * Gets the data from BlockStorage\n *\n * @param storage - The BlockStorage instance\n * @returns The data value\n */\nexport function getStorageData<TState>(storage: BlockStorage<TState>): TState {\n  return storage.__data;\n}\n\n/**\n * Derives data from raw block storage.\n * This function is meant to be called from sdk/ui-vue to extract\n * user-facing data from the raw storage returned by the middle layer.\n *\n * The middle layer returns raw storage (opaque to it), and the UI\n * uses this function to derive the actual data value.\n *\n * @param rawStorage - Raw storage data from middle layer (may be any format)\n * @returns The extracted data value, or undefined if storage is undefined/null\n */\nexport function deriveDataFromStorage<TData = unknown>(rawStorage: unknown): TData {\n  // Normalize to BlockStorage format (handles legacy formats too)\n  const storage = normalizeBlockStorage<TData>(rawStorage);\n  return getStorageData(storage);\n}\n\n/** Payload for storage mutation operations. SDK defines specific operations. */\nexport type MutateStoragePayload<T = unknown> =\n  | { operation: \"update-block-data\"; value: T }\n  | { operation: \"update-plugin-data\"; pluginId: PluginHandle; value: unknown };\n\n/**\n * Updates the data in BlockStorage (immutable)\n *\n * @param storage - The current BlockStorage\n * @param payload - The update payload with operation and value\n * @returns A new BlockStorage with updated data\n */\nexport function updateStorageData<TValue = unknown>(\n  storage: BlockStorage<TValue>,\n  payload: MutateStoragePayload<TValue>,\n): BlockStorage<TValue> {\n  switch (payload.operation) {\n    case \"update-block-data\":\n      return { ...storage, __data: payload.value };\n    case \"update-plugin-data\": {\n      const { pluginId, value } = payload;\n      const currentPlugins = storage.__plugins ?? {};\n      const existingEntry = currentPlugins[pluginId];\n      const version = existingEntry?.__dataVersion ?? DATA_MODEL_LEGACY_VERSION;\n      return {\n        ...storage,\n        __plugins: {\n          ...currentPlugins,\n          [pluginId]: {\n            __dataVersion: version,\n            __data: value,\n          },\n        },\n      };\n    }\n    default:\n      throw new Error(`Unknown storage operation: ${(payload as { operation: string }).operation}`);\n  }\n}\n\n// =============================================================================\n// Atomic Migration\n// =============================================================================\n\n/**\n * Result of a successful atomic migration.\n */\nexport interface MigrationSuccess<TState> {\n  success: true;\n  /** The fully migrated storage - commit this to persist */\n  storage: BlockStorage<TState>;\n}\n\n/**\n * Result of a failed atomic migration.\n * The original storage is untouched - user must choose to abort or reset.\n */\nexport interface MigrationFailure {\n  success: false;\n  /** Description of what failed */\n  error: string;\n  /** Which step failed: 'block' or pluginId */\n  failedAt: string;\n}\n\nexport type MigrationResult<TState> = MigrationSuccess<TState> | MigrationFailure;\n\n/**\n * Configuration for atomic block storage migration.\n * Callbacks use DataVersioned format (the DataModel API format).\n * Conversion to internal VersionedData format is handled by migrateBlockStorage().\n */\nexport interface MigrateBlockStorageConfig {\n  /** Migrate block data from any version to latest. Returns migrated data and transfers. */\n  migrateBlockData: (versioned: DataVersioned<unknown>) => DataVersioned<unknown> & {\n    transfers: TransferRecord;\n  };\n  /** Migrate each plugin's data. Return undefined to remove the plugin. Throws on failure. */\n  migratePluginData: (\n    handle: PluginHandle,\n    versioned: DataVersioned<unknown>,\n  ) => DataVersioned<unknown> | undefined;\n  /** The new plugin registry after migration (pluginId -> pluginName) */\n  newPluginRegistry: PluginRegistry;\n  /** Factory to create initial data for new plugins. Transfer is provided when a\n   *  .transfer() was defined for this plugin in the block's migration chain. */\n  createPluginData: (\n    handle: PluginHandle,\n    transfer?: DataVersioned<unknown>,\n  ) => DataVersioned<unknown>;\n}\n\n/**\n * Performs atomic migration of block storage including block data and all plugins.\n *\n * Migration is atomic: either everything succeeds and a new storage is returned,\n * or an error is returned and the original storage is completely untouched.\n *\n * Migration steps:\n * 1. Migrate block data\n * 2. For each plugin in newPluginRegistry:\n *    - If plugin exists with same name: migrate its data\n *    - Otherwise (new or type changed): create with initial data\n *    Plugins not in newPluginRegistry are dropped.\n *\n * If any step throws, migration fails and original storage is preserved.\n * User can then choose to:\n * - Abort: keep original storage, don't update block\n * - Reset: call createBlockStorage() to start fresh\n *\n * @param storage - The original storage (will not be modified)\n * @param config - Migration configuration\n * @returns Migration result - either success with new storage, or failure with error info\n *\n * @example\n * const result = migrateBlockStorage(storage, {\n *   migrateBlockData: (versioned) => blockDataModel.migrate(versioned),\n *   migratePluginData: (pluginId, versioned) => getPluginModel(pluginId).migrate(versioned),\n *   newPluginRegistry: { table1: 'dataTable' as PluginName },\n *   createPluginData: (pluginId) => getPluginModel(pluginId).getDefaultData(),\n * });\n *\n * if (result.success) {\n *   commitStorage(result.storage);\n * } else {\n *   const userChoice = await askUser(`Migration failed: ${result.error}. Reset data?`);\n *   if (userChoice === 'reset') {\n *     commitStorage(createBlockStorage(initialData, currentVersion));\n *   }\n *   // else: abort, keep original\n * }\n */\nexport function migrateBlockStorage(\n  storage: BlockStorage<unknown>,\n  config: MigrateBlockStorageConfig,\n): MigrationResult<unknown> {\n  const { migrateBlockData, migratePluginData, newPluginRegistry, createPluginData } = config;\n\n  // Step 1: Migrate block data and collect transfers\n  let migratedData: unknown;\n  let newVersion: string;\n  let transfers: TransferRecord;\n  try {\n    const result = migrateBlockData({ version: storage.__dataVersion, data: storage.__data });\n    migratedData = result.data;\n    newVersion = result.version;\n    transfers = result.transfers;\n  } catch (error) {\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : String(error),\n      failedAt: \"block\",\n    };\n  }\n\n  // Step 2: Migrate plugins\n  const oldPlugins = storage.__plugins ?? {};\n  const oldRegistry = storage.__pluginRegistry ?? {};\n  const newPlugins: Record<PluginHandle, VersionedData<unknown>> = {};\n\n  for (const [key, pluginName] of Object.entries(newPluginRegistry)) {\n    const handle = key as PluginHandle;\n    const existingEntry = oldPlugins[handle];\n    const existingName = oldRegistry[handle];\n\n    try {\n      if (existingEntry && existingName === pluginName) {\n        // Plugin exists with same type - migrate its data\n        const migrated = migratePluginData(handle, {\n          version: existingEntry.__dataVersion,\n          data: existingEntry.__data,\n        });\n        if (migrated) {\n          newPlugins[handle] = { __dataVersion: migrated.version, __data: migrated.data };\n        }\n        // If undefined returned, plugin is intentionally removed\n      } else if (existingEntry) {\n        // Plugin type changed — pass old data with DATA_MODEL_LEGACY_VERSION.\n        // If the new plugin has upgradeLegacy(), it migrates the old data.\n        // If not, defaultRecover throws DataUnrecoverableError → fall back to init.\n        let recovered = false;\n        try {\n          const migrated = migratePluginData(handle, {\n            version: DATA_MODEL_LEGACY_VERSION,\n            data: existingEntry.__data,\n          });\n          if (migrated) {\n            newPlugins[handle] = { __dataVersion: migrated.version, __data: migrated.data };\n            recovered = true;\n          }\n        } catch (recoverError) {\n          if (!isDataUnrecoverableError(recoverError)) throw recoverError;\n        }\n        if (!recovered) {\n          const transfer = transfers[handle];\n          const initial = createPluginData(handle, transfer);\n          newPlugins[handle] = { __dataVersion: initial.version, __data: initial.data };\n        }\n      } else {\n        // New plugin - create with initial data, passing transfer if available\n        const transfer = transfers[handle];\n        const initial = createPluginData(handle, transfer);\n        newPlugins[handle] = { __dataVersion: initial.version, __data: initial.data };\n      }\n    } catch (error) {\n      return {\n        success: false,\n        error: error instanceof Error ? error.message : String(error),\n        failedAt: handle,\n      };\n    }\n  }\n\n  // Step 3: Build final storage atomically\n  const migratedStorage: BlockStorage = {\n    [BLOCK_STORAGE_KEY]: BLOCK_STORAGE_SCHEMA_VERSION,\n    __dataVersion: newVersion,\n    __data: migratedData,\n    __pluginRegistry: newPluginRegistry,\n    __plugins: newPlugins,\n  };\n\n  return {\n    success: true,\n    storage: migratedStorage,\n  };\n}\n\n/**\n * Gets plugin-specific data from block storage.\n * Accepts raw storage (any format) and normalizes internally.\n *\n * When called with a typed PluginHandle<F>, the return type is automatically\n * inferred from the factory's phantom `__types.data` field.\n *\n * @param rawStorage - Raw block storage (may be legacy format or BlockStorage)\n * @param handle - The plugin handle (branded plugin instance id)\n * @returns The plugin data, typed via factory inference\n * @throws If plugin is not found in storage\n */\nexport function getPluginData<F extends PluginFactoryLike>(\n  rawStorage: unknown,\n  handle: PluginHandle<F>,\n): InferFactoryData<F> {\n  const storage = normalizeBlockStorage(rawStorage);\n  const pluginEntry = storage.__plugins?.[handle];\n  if (!pluginEntry) throw new Error(`Plugin '${handle}' not found in block storage`);\n  return pluginEntry.__data as InferFactoryData<F>;\n}\n"],"mappings":";;;;;;AA2BA,MAAa,oBAAoB;;;;;AAYjC,MAAa,4BAA4B;;;;;AAmDzC,SAAgB,eAAe,OAAuC;CACpE,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CAIxD,OAFsBA,MAAI,uBAED;AAC3B;;;;;;;;AAaA,SAAgB,mBACd,cAAsB,CAAC,GACvB,UAAkB,2BACI;CACtB,OAAO;GACJ,oBAAA;EACD,eAAe;EACf,QAAQ;EACR,kBAAkB,CAAC;EACnB,WAAW,CAAC;CACd;AACF;;;;;;;;;AAUA,SAAgB,sBAAwC,KAAoC;CAC1F,IAAI,eAAe,GAAG,GAAG;EACvB,MAAM,UAAU;EAChB,OAAO;GACL,GAAG;GAEH,eACE,OAAO,QAAQ,kBAAkB,WAC7B,4BACA,QAAQ;GAEd,kBAAkB,QAAQ,oBAAoB,CAAC;GAC/C,WAAW,QAAQ,aAAa,CAAC;EACnC;CACF;CAEA,OAAO,mBAAmB,GAAa;AACzC;;;;;;;AAYA,SAAgB,eAAuB,SAAuC;CAC5E,OAAO,QAAQ;AACjB;;;;;;;;;;;;AAaA,SAAgB,sBAAuC,YAA4B;CAGjF,OAAO,eADS,sBAA6B,UACjB,CAAC;AAC/B;;;;;;;;AAcA,SAAgB,kBACd,SACA,SACsB;CACtB,QAAQ,QAAQ,WAAhB;EACE,KAAK,qBACH,OAAO;GAAE,GAA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