{"version":3,"file":"block_storage_facade.cjs","names":["createRenderLambda"],"sources":["../src/block_storage_facade.ts"],"sourcesContent":["/**\n * Block Storage Facade - Contract between bundled blocks and middle layer.\n *\n * ============================================================================\n * VERSIONING\n * ============================================================================\n *\n * Blocks declare their model API version via the `requiresModelAPIVersion` feature flag\n * (see BlockCodeKnownFeatureFlags). This determines how the middle layer manages block state:\n *\n * - Version 1: Legacy BlockModel - state is {args, uiState}, managed directly by middle layer\n * - Version 2: BlockModelV3 - uses blockStorage with VM-based callbacks (this facade)\n *\n * This facade (BlockStorageFacade) is used by blocks with `requiresModelAPIVersion: 2`.\n * The version number matches the model API version for clarity.\n *\n * ============================================================================\n * BACKWARD COMPATIBILITY WARNING\n * ============================================================================\n *\n * This file documents the FACADE between the SDK (bundled into blocks) and the\n * middle layer. Once a block is published, its SDK version is frozen. The middle\n * layer must support ALL previously released callback signatures indefinitely.\n *\n * RULES:\n * 1. NEVER change the signature of existing callbacks\n * 2. NEVER remove existing callbacks\n * 3. New callbacks CAN be added (old blocks won't register them, middle layer\n *    should handle missing callbacks gracefully)\n * 4. Callback return types can be EXTENDED (add optional fields) but not changed\n * 5. Callback parameter types should remain compatible (middle layer may need\n *    to handle both old and new formats)\n *\n * The facade consists of callbacks registered via `tryRegisterCallback()` with\n * the `__pl_` prefix. These are registered by the SDK when a block loads and\n * called by the middle layer to perform operations.\n *\n * ============================================================================\n * WHAT CAN BE CHANGED FREELY\n * ============================================================================\n *\n * - Middle layer code (lib/node/pl-middle-layer)\n * - SDK internal implementation (as long as callback contracts are preserved)\n * - SDK exports used ONLY by middle layer (not by blocks themselves)\n * - New SDK features that don't affect existing callbacks\n *\n * @module block_storage_facade\n */\n\nimport type { MutateStoragePayload } from \"./block_storage\";\nimport type { ConfigRenderLambda } from \"./bconfig\";\nimport { createRenderLambda, tryRegisterCallback } from \"./internal\";\nimport type { ArgsIssue, StringifiedJson } from \"@milaboratories/pl-model-common\";\n\n// =============================================================================\n// Facade Version\n// =============================================================================\n\n/**\n * The current facade version. This value is used for `requiresModelAPIVersion`\n * feature flag in BlockModelV3.\n */\nexport const BLOCK_STORAGE_FACADE_VERSION = 2;\n\n// =============================================================================\n// Facade Callback Names\n// =============================================================================\n\n/**\n * All facade callback names as constants.\n * These are the source of truth - the interface is derived from these.\n *\n * IMPORTANT: When adding a new callback:\n * 1. Add the constant here\n * 2. Add the callback signature to FacadeCallbackTypes below\n * 3. The BlockStorageFacade type will automatically include it\n */\nexport const BlockStorageFacadeCallbacks = {\n  StorageApplyUpdate: \"__pl_storage_applyUpdate\",\n  StorageDebugView: \"__pl_storage_debugView\",\n  StorageMigrate: \"__pl_storage_migrate\",\n  ArgsDerive: \"__pl_args_derive\",\n  PrerunArgsDerive: \"__pl_prerunArgs_derive\",\n  StorageInitial: \"__pl_storage_initial\",\n  InitializationParamsDerive: \"__pl_initializationParams_derive\",\n  StorageInitialFromParams: \"__pl_storage_initialFromParams\",\n  InitializationParamsValidate: \"__pl_initializationParams_validate\",\n} as const;\n\n/**\n * Creates a map of lambda handles from a callbacks constant object.\n * Keys are the callback string values (e.g., '__pl_storage_applyUpdate').\n */\nfunction createFacadeHandles<T extends Record<string, string>>(\n  callbacks: T,\n): { [K in T[keyof T]]: ConfigRenderLambda } {\n  return Object.fromEntries(\n    Object.values(callbacks).map((handle) => [handle, createRenderLambda({ handle })]),\n  ) as { [K in T[keyof T]]: ConfigRenderLambda };\n}\n\n/**\n * Lambda handles for facade callbacks.\n * Used by the middle layer to invoke callbacks via executeSingleLambda().\n */\nexport const BlockStorageFacadeHandles = createFacadeHandles(BlockStorageFacadeCallbacks);\n\n// =============================================================================\n// Facade Interface (source of truth for callback signatures)\n// =============================================================================\n\n/**\n * The complete facade interface between bundled blocks (SDK) and middle layer.\n *\n * This interface defines ALL callbacks that a block registers. The middle layer\n * calls these callbacks to perform storage operations.\n *\n * ALL types are inlined to simplify versioning - when a callback changes,\n * the entire signature is visible in one place.\n *\n * BACKWARD COMPATIBILITY:\n * - This interface can only be EXTENDED, never shrunk\n * - Existing callback signatures MUST NOT change\n * - Middle layer should use Partial<BlockStorageFacade> when dealing with\n *   blocks of unknown version (older blocks may not have all callbacks)\n *\n * Each callback is documented with:\n * - Purpose and when it's called\n * - Parameter descriptions\n * - Return value description\n */\nexport interface BlockStorageFacade {\n  /**\n   * Apply state update to storage.\n   * Called when UI updates block state (setState) or plugin data.\n   * @param currentStorageJson - Current storage as JSON string\n   * @param payload - Update payload with operation type and value\n   * @returns Updated storage as JSON string\n   */\n  [BlockStorageFacadeCallbacks.StorageApplyUpdate]: (\n    currentStorageJson: StringifiedJson,\n    payload: MutateStoragePayload,\n  ) => StringifiedJson;\n\n  /**\n   * Get debug view of storage.\n   * Called by developer tools to inspect storage state.\n   * @param storageJson - Storage as JSON string (or undefined for new blocks)\n   * @returns JSON string containing StorageDebugView\n   */\n  [BlockStorageFacadeCallbacks.StorageDebugView]: (\n    storageJson: StringifiedJson | undefined,\n  ) => StringifiedJson;\n\n  /**\n   * Run storage migration.\n   * Called when block loads to migrate data to latest version.\n   * @param currentStorageJson - Current storage as JSON string (or undefined for new blocks)\n   * @returns Migration result - either error or success with new storage\n   */\n  [BlockStorageFacadeCallbacks.StorageMigrate]: (\n    currentStorageJson: StringifiedJson | undefined,\n  ) =>\n    | { error: string }\n    | {\n        error?: undefined;\n        newStorageJson: StringifiedJson;\n        info: string;\n      };\n\n  /**\n   * Derive args from storage.\n   * Called to get block configuration args from storage, and whether the block may run them.\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. A block built\n   * with an SDK that predates args issues returns `{ error }` or `{ value }` with no `issues`.\n   *\n   * @param storageJson - Storage as JSON string\n   * @returns One of:\n   *   - `{ error }`: `args()` threw, so there are no args;\n   *   - `{ error, args, issues }`: args were built, but the block's `argsIssues()` found errors in\n   *     them, so the block must not run; `error` joins the error messages, `issues` lists every\n   *     issue;\n   *   - `{ value, issues }`: args the block may run; `issues` holds the warnings.\n   */\n  [BlockStorageFacadeCallbacks.ArgsDerive]: (\n    storageJson: StringifiedJson,\n  ) =>\n    | { error: string }\n    | { error: string; args: unknown; issues: ArgsIssue[] }\n    | { error?: undefined; value: unknown; issues: ArgsIssue[] };\n\n  /**\n   * Derive prerunArgs from storage.\n   * Called to get prerun args; falls back to args callback if not registered.\n   *\n   * A block with its own prerunArgs is staged with them unless its `prerunArgsIssues()` finds errors\n   * in them. A block without its own prerunArgs is staged with its args unless its `argsIssues()`\n   * finds errors in them.\n   *\n   * A middle layer that predates args issues reads only `error` and `value`: `value` is args to\n   * stage, `error` skips staging. A block built with an SDK that predates args issues returns\n   * `{ error }` or `{ value }` with no `issues`.\n   *\n   * @param storageJson - Storage as JSON string\n   * @returns One of:\n   *   - `{ error }`: the lambda building the prerun args threw;\n   *   - `{ error, issues }`: prerun args were built, but errors were found in them, so the block\n   *     is not staged; `error` joins the error messages, `issues` lists every issue;\n   *   - `{ value, issues }`: args to stage, `undefined` to skip staging; `issues` holds the\n   *     warnings.\n   */\n  [BlockStorageFacadeCallbacks.PrerunArgsDerive]: (\n    storageJson: StringifiedJson,\n  ) =>\n    | { error: string }\n    | { error: string; issues: ArgsIssue[] }\n    | { error?: undefined; value: unknown; issues: ArgsIssue[] };\n\n  /**\n   * Get initial storage JSON for new blocks.\n   * Called when creating a new block to get complete initial storage.\n   * @returns Initial storage as JSON string\n   */\n  [BlockStorageFacadeCallbacks.StorageInitial]: () => StringifiedJson;\n\n  /**\n   * Derive this block's template entry params from storage.\n   * Called when exporting the project as a template.\n   *\n   * Every V3 block declares `.templateParams()` — the model does not build without\n   * it — so every export produces params. A block whose state carries nothing worth\n   * restoring returns `{}`, which is written out and used as-is by init.\n   *\n   * The returned params are written out exactly as they come back, references included: the\n   * template engine carrying them recognizes nothing in there, and the block that receives\n   * them on the way back in is what repoints them. The caller supplies everything else in the\n   * entry — `id`, `kind` — so the lambda cannot set them.\n   *\n   * @param storageJson - Storage as JSON string\n   * @returns Either an error, or the params to write\n   */\n  [BlockStorageFacadeCallbacks.InitializationParamsDerive]: (\n    storageJson: StringifiedJson,\n  ) => { error: string } | { error?: undefined; value: unknown };\n\n  /**\n   * Get initial storage JSON for a block created from params.\n   * Called when applying a template, once per entry that carries `params`.\n   *\n   * The mirror image of {@link BlockStorageFacadeCallbacks.InitializationParamsDerive}:\n   * that one turns storage into params, this one turns params into storage. Every\n   * applied entry comes through here, including one whose file omitted `params` —\n   * an omitted key is read as `{}` and checked like any other value, so no entry\n   * reaches a block without passing its kind's contract.\n   * {@link BlockStorageFacadeCallbacks.StorageInitial} stays the UI-creation path,\n   * where there are genuinely no params.\n   *\n   * Separate from `StorageInitial` rather than an optional argument to it,\n   * deliberately: a block bundled with an older SDK does not register this\n   * callback at all, so the caller sees it missing and can say so. Widening\n   * `StorageInitial` would instead have that block silently ignore the params and\n   * produce a default-initialized block that looks successfully applied.\n   *\n   * The params arrive as ordinary live params — references are `PlRef`s, already\n   * pointing at the ids the target project just assigned. Resolution happens in\n   * the engine, before this call, so a block's init factory never handles a\n   * template-local reference.\n   *\n   * Errors are returned, not thrown: a factory rejecting params it cannot use is\n   * an expected outcome for a hand-written template file, and every entry's\n   * problem is reported together.\n   *\n   * **Also where the entry's references are pointed at this project.** Params reach here\n   * exactly as the file held them: nothing between the block that exported them and this call\n   * marks a reference, reads one, or rewrites one, because recognizing one means knowing the\n   * reference system and this bundle is where that knowledge lives. `blockIdsJson` maps each\n   * template-local entry id to the block id it was given, holding the entries created so far —\n   * so an id it does not name is left alone, and a reference to an entry created later names\n   * nothing rather than naming the wrong block.\n   *\n   * Relocating and initializing are one call rather than two because every call\n   * re-instantiates the runtime and re-evaluates the whole model bundle: splitting them would\n   * parse the block twice per entry to produce an intermediate only the second half reads.\n   *\n   * @param paramsJson - The entry's params as JSON string, as the file held them\n   * @param blockIdsJson - template-local entry id → assigned block id, as a JSON object\n   * @returns Either an error, or the initial storage as JSON string\n   */\n  [BlockStorageFacadeCallbacks.StorageInitialFromParams]: (\n    paramsJson: StringifiedJson,\n    blockIdsJson: StringifiedJson,\n  ) => { error: string } | { error?: undefined; storageJson: StringifiedJson };\n\n  /**\n   * Check params against this block's kind, creating nothing.\n   *\n   * Called once per entry before a template is applied, so params a kind rejects are\n   * reported against the entry that carries them while there is still no project — the\n   * same reason references and ids are checked before construction starts. Applying\n   * without this call is safe but worse: `StorageInitialFromParams` runs the same check\n   * and refuses, by which point earlier entries have already been created.\n   *\n   * A pass carries nothing back but its own absence of error: every kind declares a\n   * parser, so a pass means the params were checked against the contract, not merely\n   * that they were valid JSON.\n   *\n   * Reference ids inside the params may be placeholders at this point: the check runs\n   * before blocks exist, so what is verified is the shape of the params, not what they\n   * point at.\n   *\n   * @param paramsJson The entry's params as JSON string\n   * @returns Why the params were rejected, or nothing\n   */\n  [BlockStorageFacadeCallbacks.InitializationParamsValidate]: (\n    paramsJson: StringifiedJson,\n  ) => { error: string } | { error?: undefined };\n}\n\n/** Register all facade callbacks at once. Ensures all required callbacks are provided. */\nexport function registerFacadeCallbacks(callbacks: BlockStorageFacade): void {\n  for (const key of Object.values(BlockStorageFacadeCallbacks)) {\n    tryRegisterCallback(key, callbacks[key] as (...args: any[]) => any);\n  }\n}\n"],"mappings":";;;;;;AA8DA,MAAa,+BAA+B;;;;;;;;;;AAe5C,MAAa,8BAA8B;CACzC,oBAAoB;CACpB,kBAAkB;CAClB,gBAAgB;CAChB,YAAY;CACZ,kBAAkB;CAClB,gBAAgB;CAChB,4BAA4B;CAC5B,0BAA0B;CAC1B,8BAA8B;AAChC;;;;;AAMA,SAAS,oBACP,WAC2C;CAC3C,OAAO,OAAO,YACZ,OAAO,OAAO,SAAS,CAAC,CAAC,KAAK,WAAW,CAAC,QAAQA,iBAAAA,mBAAmB,EAAE,OAAO,CAAC,CAAC,CAAC,CACnF;AACF;;;;;AAMA,MAAa,4BAA4B,oBAAoB,2BAA2B;;AAwNxF,SAAgB,wBAAwB,WAAqC;CAC3E,KAAK,MAAM,OAAO,OAAO,OAAO,2BAA2B,GACzD,iBAAA,oBAAoB,KAAK,UAAU,IAA+B;AAEtE"}