@platforma-sdk/model 1.81.1 → 1.82.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/block_migrations.cjs +92 -8
- package/dist/block_migrations.cjs.map +1 -1
- package/dist/block_migrations.d.ts +121 -32
- package/dist/block_migrations.d.ts.map +1 -1
- package/dist/block_migrations.js +92 -8
- package/dist/block_migrations.js.map +1 -1
- package/dist/block_model.cjs +69 -15
- package/dist/block_model.cjs.map +1 -1
- package/dist/block_model.d.ts +58 -22
- package/dist/block_model.d.ts.map +1 -1
- package/dist/block_model.js +71 -17
- package/dist/block_model.js.map +1 -1
- package/dist/block_storage_callbacks.cjs +194 -13
- package/dist/block_storage_callbacks.cjs.map +1 -1
- package/dist/block_storage_callbacks.js +192 -15
- package/dist/block_storage_callbacks.js.map +1 -1
- package/dist/block_storage_facade.cjs +4 -1
- package/dist/block_storage_facade.cjs.map +1 -1
- package/dist/block_storage_facade.d.ts +102 -0
- package/dist/block_storage_facade.d.ts.map +1 -1
- package/dist/block_storage_facade.js +4 -1
- package/dist/block_storage_facade.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.js +1 -1
- package/package.json +10 -9
- package/src/block_migrations.ts +205 -55
- package/src/block_model.ts +190 -59
- package/src/block_storage_callbacks.ts +294 -15
- package/src/block_storage_facade.ts +95 -0
- package/src/kind_reference.test.ts +134 -0
- package/src/template_init.test.ts +413 -0
- package/src/template_params.test.ts +135 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block_storage_callbacks.js","names":["obj"],"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 { stringifyJson, type StringifiedJson } 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 const blockDefault = hooks.getDefaultBlockData();\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: blockDefault.version,\n __data: blockDefault.data,\n __pluginRegistry: pluginRegistry,\n __plugins: plugins,\n };\n return stringifyJson(storage);\n}\n\n// =============================================================================\n// Args Derivation from Storage\n// =============================================================================\n\n/**\n * Result of args derivation from storage.\n * Returned by __pl_args_derive and __pl_prerunArgs_derive callbacks.\n */\nexport type ArgsDeriveResult = { error: string } | { error?: undefined; value: unknown };\n\n/**\n * Derives args from storage using the provided args function.\n * This extracts data from storage and passes it to the block's args() function.\n *\n * @param storageJson - Storage as JSON string\n * @param argsFunction - The block's args derivation function\n * @returns ArgsDeriveResult with derived args or error\n */\nexport function deriveArgsFromStorage(\n storageJson: string,\n argsFunction: (data: unknown) => unknown,\n): ArgsDeriveResult {\n // Extract data from storage\n const { data } = normalizeStorage(storageJson);\n\n // Call the args function with extracted data\n try {\n const result = argsFunction(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `args() threw: ${errorMsg}` };\n }\n}\n\n/**\n * Derives prerunArgs from storage.\n * Uses prerunArgsFunction if provided, otherwise falls back to argsFunction.\n *\n * @param storageJson - Storage as JSON string\n * @param argsFunction - The block's args derivation function (fallback)\n * @param prerunArgsFunction - Optional prerun args derivation function\n * @returns ArgsDeriveResult with derived prerunArgs or error\n */\nexport function derivePrerunArgsFromStorage(\n storageJson: string,\n argsFunction: (data: unknown) => unknown,\n prerunArgsFunction?: (data: unknown) => unknown,\n): ArgsDeriveResult {\n // Extract data from storage\n const { data } = normalizeStorage(storageJson);\n\n // Try prerunArgs function first if available\n if (prerunArgsFunction) {\n try {\n const result = prerunArgsFunction(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `prerunArgs() threw: ${errorMsg}` };\n }\n }\n\n // Fall back to args function\n try {\n const result = argsFunction(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `args() threw (fallback): ${errorMsg}` };\n }\n}\n\n// Export discriminator key and schema version for external checks\nexport { BLOCK_STORAGE_KEY, BLOCK_STORAGE_SCHEMA_VERSION };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA8EA,SAAS,iBAAiB,YAA6C;CAErE,IAAI,eAAe,KAAA,KAAa,eAAe,MAE7C,OAAO;EAAE,SADO,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,SADO,mBAAmB,UACpB;GAAG,MAAM;EAAW;CACrC;CAIF,IAAI,eAAe,MAAM,GAAG;EAC1B,MAAM,UAAU,sBAAsB,MAAM;EAC5C,OAAO;GAAE;GAAS,MAAM,eAAe,OAAO;EAAE;CAClD;CAGA,IAAI,yBAAyB,MAAM,GAGjC,OAAO;EAAE,SADO,mBAAmB,MACpB;EAAG,MAAM;CAAO;CAKjC,OAAO;EAAE,SADO,mBAAmB,MACpB;EAAG,MAAM;CAAO;AACjC;;;;;;;;;AAUA,SAAgB,mBACd,oBACA,SAC+B;CAC/B,MAAM,EAAE,SAAS,mBAAmB,iBAAiB,kBAAkB;CAKvE,OAAO,cAFgB,kBAAkB,gBAAgB,OAEvB,CAAC;AACrC;;;;;AAMA,SAAS,yBAAyB,MAA2C;CAC3E,IAAI,SAAS,QAAQ,OAAO,SAAS,UAAU,OAAO;CACtD,IAAI,eAAe,IAAI,GAAG,OAAO;CAGjC,OAAO,UAAUA;AACnB;;;;;;;;AAaA,SAAgB,oBAAoB,YAAwD;CAC1F,MAAM,EAAE,YAA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AAU,OAAO,CAAC,IACd;CAC9C;AACF;;;;;;;;;;AAWA,SAAgB,4BACd,aACA,cACA,oBACkB;CAElB,MAAM,EAAE,SAAS,iBAAiB,WAAW;CAG7C,IAAI,oBACF,IAAI;EAEF,OAAO,EAAE,OADM,mBAAmB,IACb,EAAE;CACzB,SAAS,GAAG;EAEV,OAAO,EAAE,OAAO,uBADC,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,IACR;CACpD;CAIF,IAAI;EAEF,OAAO,EAAE,OADM,aAAa,IACP,EAAE;CACzB,SAAS,GAAG;EAEV,OAAO,EAAE,OAAO,4BADC,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,IACH;CACzD;AACF"}
|
|
1
|
+
{"version":3,"file":"block_storage_callbacks.js","names":["obj"],"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 relocateBlockIds,\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 args derivation from storage.\n * Returned by __pl_args_derive and __pl_prerunArgs_derive callbacks.\n */\nexport type ArgsDeriveResult = { error: string } | { error?: undefined; value: unknown };\n\n/**\n * Derives args from storage using the provided args function.\n * This extracts data from storage and passes it to the block's args() function.\n *\n * @param storageJson - Storage as JSON string\n * @param deriveArgs - The block's args derivation function\n * @returns ArgsDeriveResult with derived args or error\n */\nexport function deriveArgsFromStorage(\n storageJson: string,\n deriveArgs: (data: unknown) => unknown,\n): ArgsDeriveResult {\n // Extract data from storage\n const { data } = normalizeStorage(storageJson);\n\n // Call the args function with extracted data\n try {\n const result = deriveArgs(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `args() threw: ${errorMsg}` };\n }\n}\n\n/**\n * Derives prerunArgs from storage.\n * Uses derivePrerunArgs if provided, otherwise falls back to deriveArgs.\n *\n * @param storageJson - Storage as JSON string\n * @param deriveArgs - The block's args derivation function (fallback)\n * @param derivePrerunArgs - Optional prerun args derivation function\n * @returns ArgsDeriveResult with derived prerunArgs or error\n */\nexport function derivePrerunArgsFromStorage(\n storageJson: string,\n deriveArgs: (data: unknown) => unknown,\n derivePrerunArgs?: (data: unknown) => unknown,\n): ArgsDeriveResult {\n // Extract data from storage\n const { data } = normalizeStorage(storageJson);\n\n // Try prerunArgs function first if available\n if (derivePrerunArgs) {\n try {\n const result = derivePrerunArgs(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `prerunArgs() threw: ${errorMsg}` };\n }\n }\n\n // Fall back to args function\n try {\n const result = deriveArgs(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `args() threw (fallback): ${errorMsg}` };\n }\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 ArgsDeriveResult 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): ArgsDeriveResult {\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmFA,SAAS,iBAAiB,YAA6C;CAErE,IAAI,eAAe,KAAA,KAAa,eAAe,MAE7C,OAAO;EAAE,SADO,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,SADO,mBAAmB,UACpB;GAAG,MAAM;EAAW;CACrC;CAIF,IAAI,eAAe,MAAM,GAAG;EAC1B,MAAM,UAAU,sBAAsB,MAAM;EAC5C,OAAO;GAAE;GAAS,MAAM,eAAe,OAAO;EAAE;CAClD;CAGA,IAAI,yBAAyB,MAAM,GAGjC,OAAO;EAAE,SADO,mBAAmB,MACpB;EAAG,MAAM;CAAO;CAKjC,OAAO;EAAE,SADO,mBAAmB,MACpB;EAAG,MAAM;CAAO;AACjC;;;;;;;;;AAUA,SAAgB,mBACd,oBACA,SAC+B;CAC/B,MAAM,EAAE,SAAS,mBAAmB,iBAAiB,kBAAkB;CAKvE,OAAO,cAFgB,kBAAkB,gBAAgB,OAEvB,CAAC;AACrC;;;;;AAMA,SAAS,yBAAyB,MAA2C;CAC3E,IAAI,SAAS,QAAQ,OAAO,SAAS,UAAU,OAAO;CACtD,IAAI,eAAe,IAAI,GAAG,OAAO;CAGjC,OAAO,UAAUA;AACnB;;;;;;;;AAaA,SAAgB,oBAAoB,YAAwD;CAC1F,MAAM,EAAE,YAAY,iBAAiB,UAAU;CAK/C,OA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C,IACH;CACzD;AACF;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,gCACd,aACA,sBACkB;CAClB,MAAM,EAAE,SAAS,iBAAiB,WAAW;CAE7C,IAAI;EACF,OAAO,EAAE,OAAO,qBAAqB,IAAI,EAAE;CAC7C,SAAS,GAAG;EAEV,OAAO,EAAE,OAAO,2BADC,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,IACJ;CACxD;AACF"}
|
|
@@ -20,7 +20,10 @@ const BlockStorageFacadeCallbacks = {
|
|
|
20
20
|
StorageMigrate: "__pl_storage_migrate",
|
|
21
21
|
ArgsDerive: "__pl_args_derive",
|
|
22
22
|
PrerunArgsDerive: "__pl_prerunArgs_derive",
|
|
23
|
-
StorageInitial: "__pl_storage_initial"
|
|
23
|
+
StorageInitial: "__pl_storage_initial",
|
|
24
|
+
InitializationParamsDerive: "__pl_initializationParams_derive",
|
|
25
|
+
StorageInitialFromParams: "__pl_storage_initialFromParams",
|
|
26
|
+
InitializationParamsValidate: "__pl_initializationParams_validate"
|
|
24
27
|
};
|
|
25
28
|
/**
|
|
26
29
|
* Creates a map of lambda handles from a callbacks constant object.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"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 { 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} 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]: (currentStorageJson: StringifiedJson | undefined) =>\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.\n * @param storageJson - Storage as JSON string\n * @returns Args derivation result - either error or derived value\n */\n [BlockStorageFacadeCallbacks.ArgsDerive]: (\n storageJson: StringifiedJson,\n ) => { error: string } | { error?: undefined; value: unknown };\n\n /**\n * Derive prerunArgs from storage.\n * Called to get prerun args; falls back to args callback if not registered.\n * @param storageJson - Storage as JSON string\n * @returns Args derivation result - either error or derived value\n */\n [BlockStorageFacadeCallbacks.PrerunArgsDerive]: (\n storageJson: StringifiedJson,\n ) => { error: string } | { error?: undefined; value: unknown };\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/** 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;AAClB;;;;;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;;AA4FxF,SAAgB,wBAAwB,WAAqC;CAC3E,KAAK,MAAM,OAAO,OAAO,OAAO,2BAA2B,GACzD,iBAAA,oBAAoB,KAAK,UAAU,IAA+B;AAEtE"}
|
|
1
|
+
{"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 { 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]: (currentStorageJson: StringifiedJson | undefined) =>\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.\n * @param storageJson - Storage as JSON string\n * @returns Args derivation result - either error or derived value\n */\n [BlockStorageFacadeCallbacks.ArgsDerive]: (\n storageJson: StringifiedJson,\n ) => { error: string } | { error?: undefined; value: unknown };\n\n /**\n * Derive prerunArgs from storage.\n * Called to get prerun args; falls back to args callback if not registered.\n * @param storageJson - Storage as JSON string\n * @returns Args derivation result - either error or derived value\n */\n [BlockStorageFacadeCallbacks.PrerunArgsDerive]: (\n storageJson: StringifiedJson,\n ) => { error: string } | { error?: undefined; value: unknown };\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;;AAwLxF,SAAgB,wBAAwB,WAAqC;CAC3E,KAAK,MAAM,OAAO,OAAO,OAAO,2BAA2B,GACzD,iBAAA,oBAAoB,KAAK,UAAU,IAA+B;AAEtE"}
|
|
@@ -24,6 +24,9 @@ declare const BlockStorageFacadeCallbacks: {
|
|
|
24
24
|
readonly ArgsDerive: "__pl_args_derive";
|
|
25
25
|
readonly PrerunArgsDerive: "__pl_prerunArgs_derive";
|
|
26
26
|
readonly StorageInitial: "__pl_storage_initial";
|
|
27
|
+
readonly InitializationParamsDerive: "__pl_initializationParams_derive";
|
|
28
|
+
readonly StorageInitialFromParams: "__pl_storage_initialFromParams";
|
|
29
|
+
readonly InitializationParamsValidate: "__pl_initializationParams_validate";
|
|
27
30
|
};
|
|
28
31
|
/**
|
|
29
32
|
* Lambda handles for facade callbacks.
|
|
@@ -36,6 +39,9 @@ declare const BlockStorageFacadeHandles: {
|
|
|
36
39
|
__pl_args_derive: ConfigRenderLambda<unknown>;
|
|
37
40
|
__pl_prerunArgs_derive: ConfigRenderLambda<unknown>;
|
|
38
41
|
__pl_storage_initial: ConfigRenderLambda<unknown>;
|
|
42
|
+
__pl_initializationParams_derive: ConfigRenderLambda<unknown>;
|
|
43
|
+
__pl_storage_initialFromParams: ConfigRenderLambda<unknown>;
|
|
44
|
+
__pl_initializationParams_validate: ConfigRenderLambda<unknown>;
|
|
39
45
|
};
|
|
40
46
|
/**
|
|
41
47
|
* The complete facade interface between bundled blocks (SDK) and middle layer.
|
|
@@ -116,6 +122,102 @@ interface BlockStorageFacade {
|
|
|
116
122
|
* @returns Initial storage as JSON string
|
|
117
123
|
*/
|
|
118
124
|
[BlockStorageFacadeCallbacks.StorageInitial]: () => StringifiedJson;
|
|
125
|
+
/**
|
|
126
|
+
* Derive this block's template entry params from storage.
|
|
127
|
+
* Called when exporting the project as a template.
|
|
128
|
+
*
|
|
129
|
+
* Every V3 block declares `.templateParams()` — the model does not build without
|
|
130
|
+
* it — so every export produces params. A block whose state carries nothing worth
|
|
131
|
+
* restoring returns `{}`, which is written out and used as-is by init.
|
|
132
|
+
*
|
|
133
|
+
* The returned params are written out exactly as they come back, references included: the
|
|
134
|
+
* template engine carrying them recognizes nothing in there, and the block that receives
|
|
135
|
+
* them on the way back in is what repoints them. The caller supplies everything else in the
|
|
136
|
+
* entry — `id`, `kind` — so the lambda cannot set them.
|
|
137
|
+
*
|
|
138
|
+
* @param storageJson - Storage as JSON string
|
|
139
|
+
* @returns Either an error, or the params to write
|
|
140
|
+
*/
|
|
141
|
+
[BlockStorageFacadeCallbacks.InitializationParamsDerive]: (storageJson: StringifiedJson) => {
|
|
142
|
+
error: string;
|
|
143
|
+
} | {
|
|
144
|
+
error?: undefined;
|
|
145
|
+
value: unknown;
|
|
146
|
+
};
|
|
147
|
+
/**
|
|
148
|
+
* Get initial storage JSON for a block created from params.
|
|
149
|
+
* Called when applying a template, once per entry that carries `params`.
|
|
150
|
+
*
|
|
151
|
+
* The mirror image of {@link BlockStorageFacadeCallbacks.InitializationParamsDerive}:
|
|
152
|
+
* that one turns storage into params, this one turns params into storage. Every
|
|
153
|
+
* applied entry comes through here, including one whose file omitted `params` —
|
|
154
|
+
* an omitted key is read as `{}` and checked like any other value, so no entry
|
|
155
|
+
* reaches a block without passing its kind's contract.
|
|
156
|
+
* {@link BlockStorageFacadeCallbacks.StorageInitial} stays the UI-creation path,
|
|
157
|
+
* where there are genuinely no params.
|
|
158
|
+
*
|
|
159
|
+
* Separate from `StorageInitial` rather than an optional argument to it,
|
|
160
|
+
* deliberately: a block bundled with an older SDK does not register this
|
|
161
|
+
* callback at all, so the caller sees it missing and can say so. Widening
|
|
162
|
+
* `StorageInitial` would instead have that block silently ignore the params and
|
|
163
|
+
* produce a default-initialized block that looks successfully applied.
|
|
164
|
+
*
|
|
165
|
+
* The params arrive as ordinary live params — references are `PlRef`s, already
|
|
166
|
+
* pointing at the ids the target project just assigned. Resolution happens in
|
|
167
|
+
* the engine, before this call, so a block's init factory never handles a
|
|
168
|
+
* template-local reference.
|
|
169
|
+
*
|
|
170
|
+
* Errors are returned, not thrown: a factory rejecting params it cannot use is
|
|
171
|
+
* an expected outcome for a hand-written template file, and every entry's
|
|
172
|
+
* problem is reported together.
|
|
173
|
+
*
|
|
174
|
+
* **Also where the entry's references are pointed at this project.** Params reach here
|
|
175
|
+
* exactly as the file held them: nothing between the block that exported them and this call
|
|
176
|
+
* marks a reference, reads one, or rewrites one, because recognizing one means knowing the
|
|
177
|
+
* reference system and this bundle is where that knowledge lives. `blockIdsJson` maps each
|
|
178
|
+
* template-local entry id to the block id it was given, holding the entries created so far —
|
|
179
|
+
* so an id it does not name is left alone, and a reference to an entry created later names
|
|
180
|
+
* nothing rather than naming the wrong block.
|
|
181
|
+
*
|
|
182
|
+
* Relocating and initializing are one call rather than two because every call
|
|
183
|
+
* re-instantiates the runtime and re-evaluates the whole model bundle: splitting them would
|
|
184
|
+
* parse the block twice per entry to produce an intermediate only the second half reads.
|
|
185
|
+
*
|
|
186
|
+
* @param paramsJson - The entry's params as JSON string, as the file held them
|
|
187
|
+
* @param blockIdsJson - template-local entry id → assigned block id, as a JSON object
|
|
188
|
+
* @returns Either an error, or the initial storage as JSON string
|
|
189
|
+
*/
|
|
190
|
+
[BlockStorageFacadeCallbacks.StorageInitialFromParams]: (paramsJson: StringifiedJson, blockIdsJson: StringifiedJson) => {
|
|
191
|
+
error: string;
|
|
192
|
+
} | {
|
|
193
|
+
error?: undefined;
|
|
194
|
+
storageJson: StringifiedJson;
|
|
195
|
+
};
|
|
196
|
+
/**
|
|
197
|
+
* Check params against this block's kind, creating nothing.
|
|
198
|
+
*
|
|
199
|
+
* Called once per entry before a template is applied, so params a kind rejects are
|
|
200
|
+
* reported against the entry that carries them while there is still no project — the
|
|
201
|
+
* same reason references and ids are checked before construction starts. Applying
|
|
202
|
+
* without this call is safe but worse: `StorageInitialFromParams` runs the same check
|
|
203
|
+
* and refuses, by which point earlier entries have already been created.
|
|
204
|
+
*
|
|
205
|
+
* A pass carries nothing back but its own absence of error: every kind declares a
|
|
206
|
+
* parser, so a pass means the params were checked against the contract, not merely
|
|
207
|
+
* that they were valid JSON.
|
|
208
|
+
*
|
|
209
|
+
* Reference ids inside the params may be placeholders at this point: the check runs
|
|
210
|
+
* before blocks exist, so what is verified is the shape of the params, not what they
|
|
211
|
+
* point at.
|
|
212
|
+
*
|
|
213
|
+
* @param paramsJson The entry's params as JSON string
|
|
214
|
+
* @returns Why the params were rejected, or nothing
|
|
215
|
+
*/
|
|
216
|
+
[BlockStorageFacadeCallbacks.InitializationParamsValidate]: (paramsJson: StringifiedJson) => {
|
|
217
|
+
error: string;
|
|
218
|
+
} | {
|
|
219
|
+
error?: undefined;
|
|
220
|
+
};
|
|
119
221
|
}
|
|
120
222
|
/** Register all facade callbacks at once. Ensures all required callbacks are provided. */
|
|
121
223
|
declare function registerFacadeCallbacks(callbacks: BlockStorageFacade): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block_storage_facade.d.ts","names":[],"sources":["../src/block_storage_facade.ts"],"mappings":";;;;;;;;;cA8Da,4BAAA
|
|
1
|
+
{"version":3,"file":"block_storage_facade.d.ts","names":[],"sources":["../src/block_storage_facade.ts"],"mappings":";;;;;;;;;cA8Da,4BAAA;;;;;AAqEb;;;;;cAtDa,2BAAA;EAAA;;;;;;;;;;;;;;cA4BA,yBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA0BI,kBAAA;EAkCT;;;;;;;EAAA,CA1BL,2BAAA,CAA4B,kBAAA,IAC3B,kBAAA,EAAoB,e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_prerunArgs_derive",
|
|
23
|
-
StorageInitial: "__pl_storage_initial"
|
|
23
|
+
StorageInitial: "__pl_storage_initial",
|
|
24
|
+
InitializationParamsDerive: "__pl_initializationParams_derive",
|
|
25
|
+
StorageInitialFromParams: "__pl_storage_initialFromParams",
|
|
26
|
+
InitializationParamsValidate: "__pl_initializationParams_validate"
|
|
24
27
|
};
|
|
25
28
|
/**
|
|
26
29
|
* Creates a map of lambda handles from a callbacks constant object.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block_storage_facade.js","names":[],"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 { 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} 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]: (currentStorageJson: StringifiedJson | undefined) =>\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.\n * @param storageJson - Storage as JSON string\n * @returns Args derivation result - either error or derived value\n */\n [BlockStorageFacadeCallbacks.ArgsDerive]: (\n storageJson: StringifiedJson,\n ) => { error: string } | { error?: undefined; value: unknown };\n\n /**\n * Derive prerunArgs from storage.\n * Called to get prerun args; falls back to args callback if not registered.\n * @param storageJson - Storage as JSON string\n * @returns Args derivation result - either error or derived value\n */\n [BlockStorageFacadeCallbacks.PrerunArgsDerive]: (\n storageJson: StringifiedJson,\n ) => { error: string } | { error?: undefined; value: unknown };\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/** 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;AAClB;;;;;AAMA,SAAS,oBACP,WAC2C;CAC3C,OAAO,OAAO,YACZ,OAAO,OAAO,SAAS,CAAC,CAAC,KAAK,WAAW,CAAC,QAAQ,mBAAmB,EAAE,OAAO,CAAC,CAAC,CAAC,CACnF;AACF;;;;;AAMA,MAAa,4BAA4B,oBAAoB,2BAA2B;;AA4FxF,SAAgB,wBAAwB,WAAqC;CAC3E,KAAK,MAAM,OAAO,OAAO,OAAO,2BAA2B,GACzD,oBAAoB,KAAK,UAAU,IAA+B;AAEtE"}
|
|
1
|
+
{"version":3,"file":"block_storage_facade.js","names":[],"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 { 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]: (currentStorageJson: StringifiedJson | undefined) =>\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.\n * @param storageJson - Storage as JSON string\n * @returns Args derivation result - either error or derived value\n */\n [BlockStorageFacadeCallbacks.ArgsDerive]: (\n storageJson: StringifiedJson,\n ) => { error: string } | { error?: undefined; value: unknown };\n\n /**\n * Derive prerunArgs from storage.\n * Called to get prerun args; falls back to args callback if not registered.\n * @param storageJson - Storage as JSON string\n * @returns Args derivation result - either error or derived value\n */\n [BlockStorageFacadeCallbacks.PrerunArgsDerive]: (\n storageJson: StringifiedJson,\n ) => { error: string } | { error?: undefined; value: unknown };\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,QAAQ,mBAAmB,EAAE,OAAO,CAAC,CAAC,CAAC,CACnF;AACF;;;;;AAMA,MAAa,4BAA4B,oBAAoB,2BAA2B;;AAwLxF,SAAgB,wBAAwB,WAAqC;CAC3E,KAAK,MAAM,OAAO,OAAO,OAAO,2BAA2B,GACzD,oBAAoB,KAAK,UAAU,IAA+B;AAEtE"}
|
package/dist/package.cjs
CHANGED
package/dist/package.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@platforma-sdk/model",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.82.0",
|
|
4
4
|
"description": "Platforma.bio SDK / Block Model",
|
|
5
5
|
"files": [
|
|
6
6
|
"./dist/**/*",
|
|
@@ -32,10 +32,10 @@
|
|
|
32
32
|
"utility-types": "^3.11.0",
|
|
33
33
|
"zod": "~3.25.76",
|
|
34
34
|
"@milaboratories/helpers": "1.14.5",
|
|
35
|
-
"@milaboratories/pl-model-middle-layer": "1.31.0",
|
|
36
|
-
"@milaboratories/ptabler-expression-js": "1.2.37",
|
|
37
35
|
"@milaboratories/pl-error-like": "1.12.10",
|
|
38
|
-
"@milaboratories/pl-model-
|
|
36
|
+
"@milaboratories/pl-model-middle-layer": "1.32.0",
|
|
37
|
+
"@milaboratories/ptabler-expression-js": "1.2.38",
|
|
38
|
+
"@milaboratories/pl-model-common": "1.48.0"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
41
|
"@vitest/coverage-istanbul": "^4.1.3",
|
|
@@ -43,11 +43,12 @@
|
|
|
43
43
|
"typescript": "~5.9.3",
|
|
44
44
|
"vitest": "^4.1.3",
|
|
45
45
|
"@milaboratories/build-configs": "2.0.0",
|
|
46
|
-
"@milaboratories/
|
|
47
|
-
"@milaboratories/
|
|
48
|
-
"@milaboratories/pf-spec-driver": "1.5.
|
|
49
|
-
"@milaboratories/ts-
|
|
50
|
-
"@
|
|
46
|
+
"@milaboratories/columns-collection-driver": "0.2.4",
|
|
47
|
+
"@milaboratories/pf-driver": "1.9.1",
|
|
48
|
+
"@milaboratories/pf-spec-driver": "1.5.1",
|
|
49
|
+
"@milaboratories/ts-configs": "1.4.0",
|
|
50
|
+
"@platforma-sdk/block-kind": "1.1.0",
|
|
51
|
+
"@milaboratories/ts-builder": "1.7.0"
|
|
51
52
|
},
|
|
52
53
|
"scripts": {
|
|
53
54
|
"build": "ts-builder build --target node",
|