{"version":3,"file":"block_storage_callbacks.cjs","names":["createBlockStorage","isBlockStorage","normalizeBlockStorage","getStorageData","updateStorageData","stringifyJson","obj","migrateBlockStorage","BLOCK_STORAGE_KEY","expandTemplateRefs","relocateBlockIds","parseArgsIssues"],"sources":["../src/block_storage_callbacks.ts"],"sourcesContent":["/**\n * BlockStorage Callback Implementations - wired to facade callbacks in BlockModelV3.done().\n *\n * Provides pure functions for storage operations (migration, initialization,\n * args derivation, updates, debug views). Each function takes its dependencies\n * explicitly as parameters.\n *\n * @module block_storage_callbacks\n * @internal\n */\n\nimport {\n  BLOCK_STORAGE_KEY,\n  BLOCK_STORAGE_SCHEMA_VERSION,\n  type BlockStorage,\n  type MutateStoragePayload,\n  type PluginRegistry,\n  type VersionedData,\n  createBlockStorage,\n  getStorageData,\n  isBlockStorage,\n  migrateBlockStorage,\n  normalizeBlockStorage,\n  updateStorageData,\n} from \"./block_storage\";\nimport type { PluginHandle } from \"./plugin_handle\";\n\nimport {\n  stringifyJson,\n  expandTemplateRefs,\n  parseArgsIssues,\n  relocateBlockIds,\n  type ArgsIssue,\n  type StringifiedJson,\n} from \"@milaboratories/pl-model-common\";\nimport type { DataVersioned, TransferRecord } from \"./block_migrations\";\nimport type { StorageDebugView } from \"@milaboratories/pl-model-middle-layer\";\n\n// =============================================================================\n// Hook interfaces for dependency injection\n// =============================================================================\n\n/** Dependencies for storage migration */\nexport interface MigrationHooks {\n  migrateBlockData: (versioned: DataVersioned<unknown>) => DataVersioned<unknown> & {\n    transfers: TransferRecord;\n  };\n  getPluginRegistry: () => PluginRegistry;\n  migratePluginData: (\n    handle: PluginHandle,\n    versioned: DataVersioned<unknown>,\n  ) => DataVersioned<unknown> | undefined;\n  createPluginData: (\n    handle: PluginHandle,\n    transfer?: DataVersioned<unknown>,\n  ) => DataVersioned<unknown>;\n}\n\n/** Dependencies for initial storage creation */\nexport interface InitialStorageHooks {\n  getDefaultBlockData: () => DataVersioned<unknown>;\n  getPluginRegistry: () => PluginRegistry;\n  createPluginData: (handle: PluginHandle) => DataVersioned<unknown>;\n}\n\n/**\n * Result of storage normalization\n */\nexport interface NormalizeStorageResult {\n  /** The normalized BlockStorage object */\n  storage: BlockStorage;\n  /** The extracted data (what developers see) */\n  data: unknown;\n}\n\n/**\n * Normalizes raw storage data and extracts state.\n * Handles all formats:\n * - New BlockStorage format (has discriminator)\n * - Legacy V1/V2 format ({ args, uiState })\n * - Raw V3 state (any other format)\n *\n * @param rawStorage - Raw data from blockStorage field (may be JSON string or object)\n * @returns Object with normalized storage and extracted state\n */\nfunction normalizeStorage(rawStorage: unknown): NormalizeStorageResult {\n  // Handle undefined/null\n  if (rawStorage === undefined || rawStorage === null) {\n    const storage = createBlockStorage({});\n    return { storage, data: {} };\n  }\n\n  // Parse JSON string if needed\n  let parsed = rawStorage;\n  if (typeof rawStorage === \"string\") {\n    try {\n      parsed = JSON.parse(rawStorage);\n    } catch {\n      // If parsing fails, treat string as the data\n      const storage = createBlockStorage(rawStorage);\n      return { storage, data: rawStorage };\n    }\n  }\n\n  // Check for BlockStorage format (has discriminator)\n  if (isBlockStorage(parsed)) {\n    const storage = normalizeBlockStorage(parsed);\n    return { storage, data: getStorageData(storage) };\n  }\n\n  // Check for legacy V1/V2 format: { args, uiState }\n  if (isLegacyModelV1ApiFormat(parsed)) {\n    // For legacy format, the whole object IS the data\n    const storage = createBlockStorage(parsed);\n    return { storage, data: parsed };\n  }\n\n  // Raw V3 data - wrap it\n  const storage = createBlockStorage(parsed);\n  return { storage, data: parsed };\n}\n\n/**\n * Applies a state update to existing storage.\n * Used when setData is called from the frontend.\n *\n * @param currentStorageJson - Current storage as JSON string (must be defined)\n * @param payload - Update payload with operation type and value\n * @returns Updated storage as StringifiedJson<BlockStorage>\n */\nexport function applyStorageUpdate(\n  currentStorageJson: string,\n  payload: MutateStoragePayload,\n): StringifiedJson<BlockStorage> {\n  const { storage: currentStorage } = normalizeStorage(currentStorageJson);\n\n  // Update data while preserving other storage fields (version, plugins)\n  const updatedStorage = updateStorageData(currentStorage, payload);\n\n  return stringifyJson(updatedStorage);\n}\n\n/**\n * Checks if data is in legacy Model API v1 format.\n * Legacy format has { args, uiState? } at top level without the BlockStorage discriminator.\n */\nfunction isLegacyModelV1ApiFormat(data: unknown): data is { args?: unknown } {\n  if (data === null || typeof data !== \"object\") return false;\n  if (isBlockStorage(data)) return false;\n\n  const obj = data as Record<string, unknown>;\n  return \"args\" in obj;\n}\n\n// =============================================================================\n// Facade Callback Implementations\n// =============================================================================\n\n/**\n * Gets storage debug view from raw storage data.\n * Returns structured debug info about the storage state.\n *\n * @param rawStorage - Raw data from blockStorage field (may be JSON string or object)\n * @returns JSON string with storage debug view\n */\nexport function getStorageDebugView(rawStorage: unknown): StringifiedJson<StorageDebugView> {\n  const { storage } = normalizeStorage(rawStorage);\n  const debugView: StorageDebugView = {\n    dataVersion: storage.__dataVersion,\n    data: storage.__data,\n  };\n  return stringifyJson(debugView);\n}\n\n// =============================================================================\n// Migration Support\n// =============================================================================\n\n/**\n * Result of storage migration.\n * Returned by __pl_storage_migrate callback.\n *\n * - Error result: { error: string } - serious failure (no context, etc.)\n * - Success result: { newStorageJson: StringifiedJson<BlockStorage>, info: string } - migration succeeded\n */\nexport type MigrationResult =\n  | { error: string }\n  | { error?: undefined; newStorageJson: StringifiedJson<BlockStorage>; info: string };\n\n/**\n * Runs storage migration using the provided hooks.\n * This is the main entry point for the middle layer to trigger migrations.\n *\n * @param currentStorageJson - Current storage as JSON string (or undefined)\n * @param hooks - Migration dependencies (block/plugin data migration and creation functions)\n * @returns MigrationResult\n */\nexport function migrateStorage(\n  currentStorageJson: string | undefined,\n  hooks: MigrationHooks,\n): MigrationResult {\n  // Normalize current storage\n  const { storage: currentStorage } = normalizeStorage(currentStorageJson);\n\n  const newPluginRegistry = hooks.getPluginRegistry();\n\n  // Perform atomic migration of block + all plugins\n  const migrationResult = migrateBlockStorage(currentStorage, {\n    migrateBlockData: hooks.migrateBlockData,\n    migratePluginData: hooks.migratePluginData,\n    newPluginRegistry,\n    createPluginData: hooks.createPluginData,\n  });\n\n  if (!migrationResult.success) {\n    return {\n      error: `Migration failed at '${migrationResult.failedAt}': ${migrationResult.error}`,\n    };\n  }\n\n  // Build info message\n  const oldVersion = currentStorage.__dataVersion;\n  const newVersion = migrationResult.storage.__dataVersion;\n  const info =\n    oldVersion === newVersion\n      ? `No migration needed (${oldVersion})`\n      : `Migrated ${oldVersion} -> ${newVersion}`;\n\n  return {\n    newStorageJson: stringifyJson(migrationResult.storage),\n    info,\n  };\n}\n\n// =============================================================================\n// Initial Storage Creation\n// =============================================================================\n\n/**\n * Creates complete initial storage (block data + all plugin data) atomically.\n *\n * @param hooks - Dependencies for creating initial block and plugin data\n * @returns Initial storage as branded JSON string\n * @throws If initialDataFn or createPluginData throws\n */\nexport function createInitialStorage(hooks: InitialStorageHooks): StringifiedJson<BlockStorage> {\n  return assembleStorage(hooks.getDefaultBlockData(), hooks);\n}\n\n/**\n * Wraps freshly created block data and freshly created plugin data into storage.\n *\n * Shared by the two ways a block's first storage comes into being — from defaults\n * and from template params. Only the block's own data differs between them:\n * plugins have no params channel, so they are always created at their defaults.\n */\nfunction assembleStorage(\n  blockData: DataVersioned<unknown>,\n  hooks: Omit<InitialStorageHooks, \"getDefaultBlockData\">,\n): StringifiedJson<BlockStorage> {\n  const pluginRegistry = hooks.getPluginRegistry();\n\n  const plugins: Record<PluginHandle, VersionedData<unknown>> = {};\n  for (const handle of Object.keys(pluginRegistry) as PluginHandle[]) {\n    const initial = hooks.createPluginData(handle);\n    plugins[handle] = { __dataVersion: initial.version, __data: initial.data };\n  }\n\n  const storage: BlockStorage = {\n    [BLOCK_STORAGE_KEY]: BLOCK_STORAGE_SCHEMA_VERSION,\n    __dataVersion: blockData.version,\n    __data: blockData.data,\n    __pluginRegistry: pluginRegistry,\n    __plugins: plugins,\n  };\n  return stringifyJson(storage);\n}\n\n/** Dependencies for creating storage from a template entry's params. */\nexport interface ParamsStorageHooks extends Omit<InitialStorageHooks, \"getDefaultBlockData\"> {\n  /** The block's init factory, called with the entry's params. */\n  getBlockDataFromParams: (params: unknown) => DataVersioned<unknown>;\n  /**\n   * The kind's runtime params check. Applied before the factory sees anything, and its\n   * output is what the factory gets.\n   */\n  parseInitializationParams: (value: unknown) => unknown;\n}\n\n/** Result of checking params against their kind: the params to use, or why they lost. */\nexport type TemplateParamsValidationResult =\n  | { error: string }\n  | { error?: undefined; value: unknown };\n\n/**\n * Check params against their kind's declared shape.\n *\n * The kind owns this rather than the block because the params contract belongs to the\n * kind: many block versions implement one kind, and a per-block check would let them\n * drift from each other and from the type.\n *\n * A parser rejects by throwing and accepts by returning the params to use, so its\n * output — not the input — is what flows onward. That is what lets a kind strip keys\n * it does not declare, which is the difference between a typo being ignored and a typo\n * being reported.\n *\n * Every kind declares a parser, so every set of params that reaches here is checked;\n * there is no pass-through path.\n *\n * @param value The params to check, references already in live form\n * @param parseInitializationParams The kind's parser\n */\nexport function validateTemplateParams(\n  value: unknown,\n  parseInitializationParams: (value: unknown) => unknown,\n): TemplateParamsValidationResult {\n  try {\n    return { value: parseInitializationParams(value) };\n  } catch (e) {\n    // A rejection is an expected outcome for a hand-written file, so it is reported,\n    // not thrown.\n    return { error: `params do not match this block's kind: ${describeRejection(e)}` };\n  }\n}\n\n/** One `{ path, message }` entry of a schema library's error. */\ntype IssueLike = { path?: unknown; message?: unknown };\n\n/**\n * Render whatever a parser threw as one readable line.\n *\n * An error carrying an `issues` array is unpacked rather than printed: that is the\n * shape zod (and several others) use, and its `message` is the whole issue list as\n * JSON — technically complete and unreadable in a dialog. Duck-typed on purpose, since\n * this package prescribes no schema library and takes no dependency on one; anything\n * else falls back to its own message.\n */\nfunction describeRejection(e: unknown): string {\n  const issues = (e as { issues?: unknown }).issues;\n  if (!Array.isArray(issues) || issues.length === 0) return messageOf(e);\n\n  return issues\n    .map((issue) => {\n      const { path, message } = issue as IssueLike;\n      const what = typeof message === \"string\" ? message : \"is invalid\";\n      const where = Array.isArray(path) ? formatPath(path) : \"\";\n      return where === \"\" ? what : `${where}: ${what}`;\n    })\n    .join(\"; \");\n}\n\n/** `[\"numbers\", 0]` → `numbers[0]` — how the params are written, not how they parse. */\nfunction formatPath(path: readonly unknown[]): string {\n  return path.reduce<string>((acc, segment) => {\n    if (typeof segment === \"number\") return `${acc}[${segment}]`;\n    return acc === \"\" ? String(segment) : `${acc}.${String(segment)}`;\n  }, \"\");\n}\n\n/**\n * Result of the `__pl_params_validate` callback.\n *\n * Carries no params back. The check is a pre-flight — its answer is \"may this entry be\n * applied\", and the params that actually reach the block are produced by\n * {@link createInitialStorageFromParams}, which parses again. One authoritative\n * producer, rather than two values that could differ.\n */\nexport type InitializationParamsValidateCallbackResult = { error: string } | { error?: undefined };\n\n/**\n * Check params that crossed into the model VM as text.\n *\n * The pre-flight entry point: a caller asks this before creating anything, once per\n * template entry, so params a kind rejects are reported while there is still no\n * project to half-build.\n *\n * The readable reference spelling is expanded here too, so what the kind checks is the shape it\n * declared. The ids it sees are the file's own — no block exists yet — which is why a kind must\n * not read meaning into a specific id.\n *\n * @param paramsJson The entry's params as JSON string\n * @param parseInitializationParams The kind's parser\n */\nexport function validateTemplateParamsJson(\n  paramsJson: string,\n  parseInitializationParams: (value: unknown) => unknown,\n): InitializationParamsValidateCallbackResult {\n  let params: unknown;\n  try {\n    params = JSON.parse(paramsJson);\n  } catch (e) {\n    return { error: `params are not valid JSON: ${messageOf(e)}` };\n  }\n\n  // Expanded before the kind sees anything, or a hand-written file would be rejected by every\n  // kind that declares a reference: `{ block, name }` is not a `PlRef` and no contract accepts\n  // one. Expansion needs nothing but the params, so this stays a two-argument check — the ids\n  // are not known yet and are not needed to answer the question this asks.\n  const result = validateTemplateParams(expandTemplateRefs(params), parseInitializationParams);\n  if (result.error !== undefined) return { error: result.error };\n  return {};\n}\n\nfunction messageOf(e: unknown): string {\n  return e instanceof Error ? e.message : String(e);\n}\n\n/**\n * Result of building initial storage from params.\n * Returned by the `__pl_storage_initialFromParams` callback.\n */\nexport type ParamsStorageResult =\n  | { error: string }\n  | { error?: undefined; storageJson: StringifiedJson<BlockStorage> };\n\n/**\n * Creates complete initial storage for a block being created from template params.\n *\n * The inverse of {@link deriveTemplateParamsFromStorage}: that projects storage\n * into params, this builds storage from them. The params are handed to the block's\n * init factory, whose output is versioned and wrapped exactly as\n * {@link createInitialStorage} wraps the defaults — so a block created from a\n * template is indistinguishable from one created in the UI and then edited.\n *\n * **This is where a template's references become the block's own**, and it is the only place in\n * a template's life where a reference is recognized at all. Params travel from the file\n * untouched — the engine carrying them neither marks a reference nor reads one, because\n * recognizing one means knowing the reference system, and that knowledge is here.\n *\n * Two things happen, in this order. The readable spelling a person may have written\n * (`{ block, name }`) is expanded into the `PlRef` it stands for. Then every reference naming\n * an entry that has a block is repointed at it: `blockIds` maps each template-local entry id to\n * the block id it was given, and an id it does not name is left alone, which is how a reference\n * to an entry created later ends up naming nothing rather than naming the wrong block.\n *\n * Relocation happens before the kind's parser and before the factory, so both see the ids the\n * block will actually hold. It is one step of this function rather than a callback of its own\n * precisely because nothing else wants its result: every VM call re-instantiates the runtime\n * and re-evaluates the whole model bundle, so a separate call would parse the block twice per\n * entry to produce a value only the next line reads.\n *\n * Params arrive as JSON text because this runs across the model-VM boundary, where\n * only strings pass. Anything the factory rejects is returned as an error rather\n * than thrown: applying a hand-written template is expected to surface bad params,\n * and the applier reports every entry's problem in one pass.\n *\n * @param paramsJson - The entry's params as JSON string, exactly as the file held them\n * @param blockIdsJson - template-local entry id → assigned block id, as a JSON object\n * @param hooks - The block's init factory plus plugin creation\n * @returns The storage to write, or why the params could not produce any\n */\nexport function createInitialStorageFromParams(\n  paramsJson: string,\n  blockIdsJson: string,\n  hooks: ParamsStorageHooks,\n): ParamsStorageResult {\n  let params: unknown;\n  try {\n    params = JSON.parse(paramsJson);\n  } catch (e) {\n    return { error: `params are not valid JSON: ${messageOf(e)}` };\n  }\n\n  // Read separately from the params, and reported separately, because the two fail for\n  // completely different reasons. Params are the file's and a bad one is the author's mistake;\n  // this argument is the caller's, so the only way it arrives unreadable is a caller that does\n  // not send it — a middle layer older than this block, which is a build to refresh rather than\n  // anything to fix in the template. Folding both into one message sent the reader to the file.\n  let blockIds: Map<string, string>;\n  try {\n    blockIds = new Map(Object.entries(JSON.parse(blockIdsJson) as Record<string, string>));\n  } catch (e) {\n    return {\n      error:\n        `this block was not told which blocks the template's references should point at ` +\n        `(${messageOf(e)}). The application applying the template is older than the block; ` +\n        `rebuild or update it.`,\n    };\n  }\n\n  try {\n    // Spelling first, ids second. Expansion turns `{ block, name }` into a `PlRef` naming an\n    // ENTRY, which is exactly what relocation then repoints — so both spellings reach the\n    // block through the same step and cannot diverge in how they behave.\n    params = relocateBlockIds(expandTemplateRefs(params), blockIds);\n  } catch (e) {\n    return { error: `this entry's references could not be relocated: ${messageOf(e)}` };\n  }\n\n  // Checked here too, not only in the caller's pre-flight pass. The pre-flight is\n  // about reporting every bad entry before anything is created; this is about the\n  // factory never being handed a value the kind rejects, whichever path got here.\n  const checked = validateTemplateParams(params, hooks.parseInitializationParams);\n  if (checked.error !== undefined) return { error: checked.error };\n\n  try {\n    return { storageJson: assembleStorage(hooks.getBlockDataFromParams(checked.value), hooks) };\n  } catch (e) {\n    return { error: `init() threw on the given params: ${messageOf(e)}` };\n  }\n}\n\n// =============================================================================\n// Args Derivation from Storage\n// =============================================================================\n\n/**\n * Result of a derivation that either produced a value or failed.\n * Returned by the __pl_initializationParams_derive callback.\n */\nexport type DeriveResult = { error: string } | { error?: undefined; value: unknown };\n\n/**\n * Result of args derivation from storage, returned by the __pl_args_derive callback.\n *\n * A middle layer that predates args issues reads only `error` and `value`, and each variant\n * means the same to it as before: `value` is runnable args, `error` is no args.\n *\n * - `{ error }`: `args()` threw, so there are no args.\n * - `{ error, args, issues }`: args were built, but `argsIssues()` found errors in them, so the\n *   block must not run. `error` joins the error messages; `issues` lists every issue found.\n * - `{ value, issues }`: args were built and nothing blocks the run; `issues` holds the warnings.\n */\nexport type ArgsDeriveResult =\n  | { error: string }\n  | { error: string; args: unknown; issues: ArgsIssue[] }\n  | { error?: undefined; value: unknown; issues: ArgsIssue[] };\n\n/**\n * Result of prerun args derivation from storage, returned by the __pl_prerunArgs_derive\n * callback.\n *\n * A middle layer that predates args issues reads only `error` and `value`, and each variant\n * means the same to it as before: `value` is args to stage, `error` skips staging.\n *\n * - `{ error }`: the lambda that builds the prerun args threw.\n * - `{ error, issues }`: prerun args were built, but the issues found in them include errors, so\n *   the block is not staged. `error` joins the error messages; `issues` lists every issue found.\n * - `{ value, issues }`: args to stage; `issues` holds the warnings. A `value` of `undefined`\n *   comes from a `prerunArgs()` that returned nothing, and skips staging.\n */\nexport type PrerunArgsDeriveResult =\n  | { error: string }\n  | { error: string; issues: ArgsIssue[] }\n  | { error?: undefined; value: unknown; issues: ArgsIssue[] };\n\n/** The block's lambdas that turn its data into args and find what keeps those args from running. */\nexport interface ArgsDerivation {\n  /** The block's `args()` lambda. */\n  deriveArgs: (data: unknown) => unknown;\n  /** The block's `argsIssues()` lambda; `undefined` when the block declares none. */\n  argsIssues: ((input: { args: unknown; data: unknown }) => ArgsIssue[]) | undefined;\n}\n\n/** The block's own lambdas for staging: its `prerunArgs()` and the `prerunArgsIssues()` set after it. */\nexport interface OwnPrerunArgsDerivation {\n  /** The block's `prerunArgs()` lambda. */\n  derivePrerunArgs: (data: unknown) => unknown;\n  /** The block's `prerunArgsIssues()` lambda; `undefined` when the block declares none. */\n  prerunArgsIssues: ((input: { prerunArgs: unknown; data: unknown }) => ArgsIssue[]) | undefined;\n}\n\n/** {@link ArgsDerivation} plus the block's own lambdas for staging args. */\nexport interface PrerunArgsDerivation extends ArgsDerivation {\n  /** The block's own staging lambdas; `undefined` when the block stages its args. */\n  ownPrerunArgs: OwnPrerunArgsDerivation | undefined;\n}\n\n/**\n * Derives args from storage using the block's args function, then finds the issues in them\n * with the block's `argsIssues()`.\n *\n * A throw from `argsIssues()`, or a result that is not a list of issues, is one error carrying\n * the thrown or parser message, so a broken check keeps the block from running instead of\n * letting it run unchecked.\n *\n * @param storageJson - Storage as JSON string\n * @param derivation - The block's args and args issues lambdas\n * @returns ArgsDeriveResult with derived args and args issues, or error\n */\nexport function deriveArgsFromStorage(\n  storageJson: string,\n  derivation: ArgsDerivation,\n): ArgsDeriveResult {\n  const { data } = normalizeStorage(storageJson);\n\n  const run = deriveArgsWithIssues(data, derivation);\n  if (run.type === \"threw\") return { error: `args() threw: ${run.message}` };\n\n  const { args, issues } = run;\n  const errors = errorMessages(issues);\n  if (errors.length > 0) return { error: errors.join(\"; \"), args, issues };\n  return { value: args, issues };\n}\n\n/**\n * Derives prerunArgs from storage.\n *\n * A block with its own `prerunArgs()` is staged with what it returns, unless its\n * `prerunArgsIssues()` finds errors in it; `argsIssues()` is not consulted then. A `prerunArgs()`\n * that returns `undefined` skips staging, and `prerunArgsIssues()` is not called for it.\n *\n * A block without its own `prerunArgs()` is staged with its args, unless `argsIssues()` finds\n * errors in them: args that may not run are not staged either.\n *\n * A throw from either issues lambda, or a result that is not a list of issues, is one error\n * carrying the thrown or parser message.\n *\n * @param storageJson - Storage as JSON string\n * @param derivation - The block's args, args issues and own staging lambdas\n * @returns PrerunArgsDeriveResult with derived prerunArgs and their issues, or error\n */\nexport function derivePrerunArgsFromStorage(\n  storageJson: string,\n  derivation: PrerunArgsDerivation,\n): PrerunArgsDeriveResult {\n  const { data } = normalizeStorage(storageJson);\n  const { ownPrerunArgs } = derivation;\n\n  if (ownPrerunArgs !== undefined) {\n    const run = derivePrerunArgsWithIssues(data, ownPrerunArgs);\n    if (run.type === \"threw\") return { error: `prerunArgs() threw: ${run.message}` };\n\n    const errors = errorMessages(run.issues);\n    if (errors.length > 0) return { error: errors.join(\"; \"), issues: run.issues };\n    return { value: run.args, issues: run.issues };\n  }\n\n  const run = deriveArgsWithIssues(data, derivation);\n  if (run.type === \"threw\") return { error: `args() threw (fallback): ${run.message}` };\n\n  const errors = errorMessages(run.issues);\n  if (errors.length > 0) {\n    return {\n      error: `argsIssues() found errors (fallback): ${errors.join(\"; \")}`,\n      issues: run.issues,\n    };\n  }\n  return { value: run.args, issues: run.issues };\n}\n\n// =============================================================================\n// Template Entry Derivation from Storage\n// =============================================================================\n\n/**\n * Derives this block's template-entry params from storage.\n *\n * The inverse of the data model's `init`: `init` turns `params` into data, this\n * turns data back into the params that would recreate it.\n *\n * The lambda returns ordinary live params — references as `PlRef`s, column identifiers as they\n * are stored — and that is exactly what gets written. Nothing is marked, normalized or\n * rewritten on the way out: a template holds what the block holds. Repointing those references\n * at another project is the business of {@link createInitialStorageFromParams}, on the way back\n * in, where the ids to point at are known.\n *\n * Every block declares the lambda, so every export produces params; a block with\n * nothing worth restoring returns `{}` rather than declining.\n *\n * @param storageJson - Storage as JSON string\n * @param deriveTemplateParams - The block's templateParams lambda\n * @returns DeriveResult holding the params exactly as the block projected them\n */\nexport function deriveTemplateParamsFromStorage<TP extends (data: unknown) => unknown>(\n  storageJson: string,\n  deriveTemplateParams: TP,\n): DeriveResult {\n  const { data } = normalizeStorage(storageJson);\n\n  try {\n    return { value: deriveTemplateParams(data) };\n  } catch (e) {\n    const errorMsg = e instanceof Error ? e.message : String(e);\n    return { error: `templateParams() threw: ${errorMsg}` };\n  }\n}\n\n// Export discriminator key and schema version for external checks\nexport { BLOCK_STORAGE_KEY, BLOCK_STORAGE_SCHEMA_VERSION };\n\n// =============================================================================\n// Internals\n// =============================================================================\n\n/** What a lambda building args, and the issues lambda checking them, made of a block's data. */\ntype ArgsWithIssues =\n  | { type: \"threw\"; message: string }\n  | { type: \"derived\"; args: unknown; issues: ArgsIssue[] };\n\nfunction deriveArgsWithIssues(data: unknown, derivation: ArgsDerivation): ArgsWithIssues {\n  const { deriveArgs, argsIssues } = derivation;\n\n  let args: unknown;\n  try {\n    args = deriveArgs(data);\n  } catch (e) {\n    return { type: \"threw\", message: messageOf(e) };\n  }\n\n  if (argsIssues === undefined) return { type: \"derived\", args, issues: [] };\n  return { type: \"derived\", args, issues: collectIssues(() => argsIssues({ args, data })) };\n}\n\nfunction derivePrerunArgsWithIssues(\n  data: unknown,\n  derivation: OwnPrerunArgsDerivation,\n): ArgsWithIssues {\n  const { derivePrerunArgs, prerunArgsIssues } = derivation;\n\n  let prerunArgs: unknown;\n  try {\n    prerunArgs = derivePrerunArgs(data);\n  } catch (e) {\n    return { type: \"threw\", message: messageOf(e) };\n  }\n\n  if (prerunArgsIssues === undefined || prerunArgs === undefined) {\n    return { type: \"derived\", args: prerunArgs, issues: [] };\n  }\n  return {\n    type: \"derived\",\n    args: prerunArgs,\n    issues: collectIssues(() => prerunArgsIssues({ prerunArgs, data })),\n  };\n}\n\n/**\n * Calls an issues lambda of the block. Its result is parsed rather than trusted: a block's types\n * do not hold at run time, and an entry that cannot be read must count as an error, not slip\n * past. A throw, or a result that cannot be read, is one error carrying its message.\n */\nfunction collectIssues(issuesOf: () => unknown): ArgsIssue[] {\n  try {\n    return parseArgsIssues(issuesOf());\n  } catch (e) {\n    return [{ severity: \"error\", message: messageOf(e) }];\n  }\n}\n\nfunction errorMessages(issues: ArgsIssue[]): string[] {\n  return issues.filter((issue) => issue.severity !== \"warning\").map((issue) => issue.message);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqFA,SAAS,iBAAiB,YAA6C;CAErE,IAAI,eAAe,KAAA,KAAa,eAAe,MAE7C,OAAO;EAAE,SADOA,sBAAAA,mBAAmB,CAAC,CACrB;EAAG,MAAM,CAAC;CAAE;CAI7B,IAAI,SAAS;CACb,IAAI,OAAO,eAAe,UACxB,IAAI;EACF,SAAS,KAAK,MAAM,UAAU;CAChC,QAAQ;EAGN,OAAO;GAAE,SADOA,sBAAAA,mBAAmB,UACpB;GAAG,MAAM;EAAW;CACrC;CAIF,IAAIC,sBAAAA,eAAe,MAAM,GAAG;EAC1B,MAAM,UAAUC,sBAAAA,sBAAsB,MAAM;EAC5C,OAAO;GAAE;GAAS,MAAMC,sBAAAA,eAAe,OAAO;EAAE;CAClD;CAGA,IAAI,yBAA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