@platforma-sdk/model 1.53.0 → 1.53.2

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.
@@ -3,112 +3,408 @@
3
3
  var internal = require('./internal.cjs');
4
4
  var block_storage = require('./block_storage.cjs');
5
5
 
6
- /** Internal builder for chaining migrations */
7
- class DataModelBuilder {
6
+ /**
7
+ * Helper to define version keys with literal type inference and runtime validation.
8
+ * - Validates that all version values are unique
9
+ * - Validates that no version value is empty
10
+ * - Eliminates need for `as const` assertion
11
+ *
12
+ * @throws Error if duplicate or empty version values are found
13
+ *
14
+ * @example
15
+ * const Version = defineDataVersions({
16
+ * Initial: 'v1',
17
+ * AddedLabels: 'v2',
18
+ * });
19
+ *
20
+ * type VersionedData = {
21
+ * [Version.Initial]: DataV1;
22
+ * [Version.AddedLabels]: DataV2;
23
+ * };
24
+ */
25
+ function defineDataVersions(versions) {
26
+ const values = Object.values(versions);
27
+ const keys = Object.keys(versions);
28
+ const emptyKeys = keys.filter((key) => versions[key] === '');
29
+ if (emptyKeys.length > 0) {
30
+ throw new Error(`Version values must be non-empty strings (empty: ${emptyKeys.join(', ')})`);
31
+ }
32
+ const unique = new Set(values);
33
+ if (unique.size !== values.length) {
34
+ const duplicates = values.filter((v, i) => values.indexOf(v) !== i);
35
+ throw new Error(`Duplicate version values: ${[...new Set(duplicates)].join(', ')}`);
36
+ }
37
+ return versions;
38
+ }
39
+ /** Create a DataVersioned wrapper with correct shape */
40
+ function makeDataVersioned(version, data) {
41
+ return { version, data };
42
+ }
43
+ /** Thrown by recover() to signal unrecoverable data. */
44
+ class DataUnrecoverableError extends Error {
45
+ name = 'DataUnrecoverableError';
46
+ constructor(dataVersion) {
47
+ super(`Unknown version '${dataVersion}'`);
48
+ }
49
+ }
50
+ function isDataUnrecoverableError(error) {
51
+ return error instanceof Error && error.name === 'DataUnrecoverableError';
52
+ }
53
+ /**
54
+ * Default recover function for unknown versions.
55
+ * Use as fallback at the end of custom recover functions.
56
+ *
57
+ * @example
58
+ * .recover((version, data) => {
59
+ * if (version === 'legacy') {
60
+ * return transformLegacyData(data);
61
+ * }
62
+ * return defaultRecover(version, data);
63
+ * })
64
+ */
65
+ const defaultRecover = (version, _data) => {
66
+ throw new DataUnrecoverableError(version);
67
+ };
68
+ /** Symbol for internal builder creation method */
69
+ const FROM_BUILDER = Symbol('fromBuilder');
70
+ /**
71
+ * Final builder state after recover() is called.
72
+ * Only allows calling create() to finalize the DataModel.
73
+ *
74
+ * @typeParam VersionedData - Map of version keys to their data types
75
+ * @typeParam CurrentVersion - The current (final) version in the chain
76
+ * @internal
77
+ */
78
+ class DataModelBuilderWithRecover {
79
+ versionChain;
8
80
  migrationSteps;
9
- constructor(steps = []) {
81
+ recoverFn;
82
+ /** @internal */
83
+ constructor({ versionChain, steps, recoverFn, }) {
84
+ this.versionChain = versionChain;
10
85
  this.migrationSteps = steps;
86
+ this.recoverFn = recoverFn;
87
+ }
88
+ /**
89
+ * Finalize the DataModel with initial data factory.
90
+ *
91
+ * The initial data factory is called when creating new blocks or when
92
+ * migration/recovery fails and data must be reset.
93
+ *
94
+ * @param initialData - Factory function returning initial state (must exactly match CurrentVersion's data type)
95
+ * @returns Finalized DataModel instance
96
+ *
97
+ * @example
98
+ * .init(() => ({ numbers: [], labels: [], description: '' }))
99
+ */
100
+ init(initialData,
101
+ // Compile-time check: S must have exactly the same keys as VersionedData[CurrentVersion]
102
+ ..._noExtraKeys) {
103
+ return DataModel[FROM_BUILDER]({
104
+ versionChain: this.versionChain,
105
+ steps: this.migrationSteps,
106
+ initialDataFn: initialData,
107
+ recoverFn: this.recoverFn,
108
+ });
11
109
  }
12
- /** Start a migration chain from an initial type */
13
- static from() {
14
- return new DataModelBuilder();
110
+ }
111
+ /**
112
+ * Internal builder for constructing DataModel with type-safe migration chains.
113
+ *
114
+ * Tracks the current version through the generic type system, ensuring:
115
+ * - Migration functions receive correctly typed input
116
+ * - Migration functions must return the correct output type
117
+ * - Version keys must exist in the VersionedData map
118
+ * - All versions must be covered before calling init()
119
+ *
120
+ * @typeParam VersionedData - Map of version keys to their data types
121
+ * @typeParam CurrentVersion - The current version in the migration chain
122
+ * @typeParam RemainingVersions - Versions not yet covered by migrations
123
+ * @internal
124
+ */
125
+ class DataModelMigrationChain {
126
+ versionChain;
127
+ migrationSteps;
128
+ /** @internal */
129
+ constructor({ versionChain, steps = [], }) {
130
+ this.versionChain = versionChain;
131
+ this.migrationSteps = steps;
15
132
  }
16
- /** Add a migration step */
17
- migrate(fn) {
18
- return new DataModelBuilder([...this.migrationSteps, fn]);
133
+ /**
134
+ * Add a migration step to transform data from current version to next version.
135
+ *
136
+ * Migration functions:
137
+ * - Receive data typed as the current version's data type (readonly)
138
+ * - Must return data matching the target version's data type
139
+ * - Should be pure functions (no side effects)
140
+ * - May throw errors (will result in data reset with warning)
141
+ *
142
+ * @typeParam NextVersion - The target version key (must be in RemainingVersions)
143
+ * @param nextVersion - The version key to migrate to
144
+ * @param fn - Migration function transforming current data to next version
145
+ * @returns Builder with updated current version
146
+ *
147
+ * @example
148
+ * .migrate(Version.V2, (data) => ({ ...data, labels: [] }))
149
+ */
150
+ migrate(nextVersion, fn) {
151
+ if (this.versionChain.includes(nextVersion)) {
152
+ throw new Error(`Duplicate version '${nextVersion}' in migration chain`);
153
+ }
154
+ const fromVersion = this.versionChain[this.versionChain.length - 1];
155
+ const step = { fromVersion, toVersion: nextVersion, migrate: fn };
156
+ return new DataModelMigrationChain({
157
+ versionChain: [...this.versionChain, nextVersion],
158
+ steps: [...this.migrationSteps, step],
159
+ });
19
160
  }
20
- /** Finalize with initial data, creating the DataModel */
21
- create(initialData, ..._) {
22
- return DataModel._fromBuilder(this.migrationSteps, initialData);
161
+ /**
162
+ * Set a recovery handler for unknown or legacy versions.
163
+ *
164
+ * The recover function is called when data has a version not in the migration chain.
165
+ * It should either:
166
+ * - Transform the data to the current version's format and return it
167
+ * - Call `defaultRecover(version, data)` to signal unrecoverable data
168
+ *
169
+ * Can only be called once. After calling, only `init()` is available.
170
+ *
171
+ * @param fn - Recovery function that transforms unknown data or throws
172
+ * @returns Builder with only init() method available
173
+ *
174
+ * @example
175
+ * .recover((version, data) => {
176
+ * if (version === 'legacy' && isLegacyFormat(data)) {
177
+ * return transformLegacy(data);
178
+ * }
179
+ * return defaultRecover(version, data);
180
+ * })
181
+ */
182
+ recover(fn) {
183
+ return new DataModelBuilderWithRecover({
184
+ versionChain: [...this.versionChain],
185
+ steps: [...this.migrationSteps],
186
+ recoverFn: fn,
187
+ });
188
+ }
189
+ /**
190
+ * Finalize the DataModel with initial data factory.
191
+ *
192
+ * Can only be called when all versions in VersionedData have been covered
193
+ * by the migration chain (RemainingVersions is empty).
194
+ *
195
+ * The initial data factory is called when creating new blocks or when
196
+ * migration/recovery fails and data must be reset.
197
+ *
198
+ * @param initialData - Factory function returning initial state (must exactly match CurrentVersion's data type)
199
+ * @returns Finalized DataModel instance
200
+ *
201
+ * @example
202
+ * .init(() => ({ numbers: [], labels: [], description: '' }))
203
+ */
204
+ init(initialData,
205
+ // Compile-time check: S must have exactly the same keys as VersionedData[CurrentVersion]
206
+ ..._noExtraKeys) {
207
+ return DataModel[FROM_BUILDER]({
208
+ versionChain: this.versionChain,
209
+ steps: this.migrationSteps,
210
+ initialDataFn: initialData,
211
+ });
212
+ }
213
+ }
214
+ /**
215
+ * Builder entry point for creating DataModel with type-safe migrations.
216
+ *
217
+ * @typeParam VersionedData - Map of version keys to their data types
218
+ *
219
+ * @example
220
+ * const Version = defineDataVersions({
221
+ * V1: 'v1',
222
+ * V2: 'v2',
223
+ * });
224
+ *
225
+ * type VersionedData = {
226
+ * [Version.V1]: { count: number };
227
+ * [Version.V2]: { count: number; label: string };
228
+ * };
229
+ *
230
+ * const dataModel = new DataModelBuilder<VersionedData>()
231
+ * .from(Version.V1)
232
+ * .migrate(Version.V2, (data) => ({ ...data, label: '' }))
233
+ * .init(() => ({ count: 0, label: '' }));
234
+ */
235
+ class DataModelBuilder {
236
+ /**
237
+ * Start a migration chain from an initial version.
238
+ *
239
+ * @typeParam InitialVersion - The starting version key (inferred from argument)
240
+ * @param initialVersion - The version key to start from
241
+ * @returns Migration chain builder for adding migrations
242
+ *
243
+ * @example
244
+ * new DataModelBuilder<VersionedData>()
245
+ * .from(Version.V1)
246
+ * .migrate(Version.V2, (data) => ({ ...data, newField: '' }))
247
+ */
248
+ from(initialVersion) {
249
+ return new DataModelMigrationChain({ versionChain: [initialVersion] });
23
250
  }
24
251
  }
25
252
  /**
26
253
  * DataModel defines the block's data structure, initial values, and migrations.
27
254
  * Used by BlockModelV3 to manage data state.
28
255
  *
256
+ * Two ways to create a DataModel:
257
+ *
258
+ * 1. **Simple (no migrations)** - Use `DataModel.create()`:
29
259
  * @example
30
- * // Simple data model (no migrations)
31
260
  * const dataModel = DataModel.create<BlockData>(() => ({
32
261
  * numbers: [],
33
262
  * labels: [],
34
263
  * }));
35
264
  *
36
- * // Data model with migrations
37
- * const dataModel = DataModel
38
- * .from<V1>()
39
- * .migrate((data) => ({ ...data, labels: [] })) // v1 → v2
40
- * .migrate((data) => ({ ...data, description: '' })) // v2 → v3
41
- * .create<BlockData>(() => ({ numbers: [], labels: [], description: '' }));
265
+ * 2. **With migrations** - Use `new DataModelBuilder<VersionedData>()`:
266
+ * @example
267
+ * const Version = defineDataVersions({
268
+ * V1: 'v1',
269
+ * V2: 'v2',
270
+ * V3: 'v3',
271
+ * });
272
+ *
273
+ * type VersionedData = {
274
+ * [Version.V1]: { numbers: number[] };
275
+ * [Version.V2]: { numbers: number[]; labels: string[] };
276
+ * [Version.V3]: { numbers: number[]; labels: string[]; description: string };
277
+ * };
278
+ *
279
+ * const dataModel = new DataModelBuilder<VersionedData>()
280
+ * .from(Version.V1)
281
+ * .migrate(Version.V2, (data) => ({ ...data, labels: [] }))
282
+ * .migrate(Version.V3, (data) => ({ ...data, description: '' }))
283
+ * .recover((version, data) => {
284
+ * if (version === 'legacy' && typeof data === 'object' && data !== null && 'numbers' in data) {
285
+ * return { numbers: (data as { numbers: number[] }).numbers, labels: [], description: '' };
286
+ * }
287
+ * return defaultRecover(version, data);
288
+ * })
289
+ * .init(() => ({ numbers: [], labels: [], description: '' }));
42
290
  */
43
291
  class DataModel {
292
+ versionChain;
44
293
  steps;
45
- _initialData;
46
- constructor(steps, initialData) {
294
+ initialDataFn;
295
+ recoverFn;
296
+ constructor({ versionChain, steps, initialDataFn, recoverFn = defaultRecover, }) {
297
+ if (versionChain.length === 0) {
298
+ throw new Error('DataModel requires at least one version key');
299
+ }
300
+ this.versionChain = versionChain;
47
301
  this.steps = steps;
48
- this._initialData = initialData;
49
- }
50
- /** Start a migration chain from an initial type */
51
- static from() {
52
- return DataModelBuilder.from();
302
+ this.initialDataFn = initialDataFn;
303
+ this.recoverFn = recoverFn;
53
304
  }
54
- /** Create a data model with just initial data (no migrations) */
55
- static create(initialData) {
56
- return new DataModel([], initialData);
305
+ /**
306
+ * Create a DataModel with just initial data (no migrations).
307
+ *
308
+ * Use this for simple blocks that don't need version migrations.
309
+ * The version will be set to an internal default value.
310
+ *
311
+ * @typeParam S - The state type
312
+ * @param initialData - Factory function returning initial state
313
+ * @param version - Optional custom version key (defaults to internal version)
314
+ * @returns Finalized DataModel instance
315
+ *
316
+ * @example
317
+ * const dataModel = DataModel.create<BlockData>(() => ({
318
+ * numbers: [],
319
+ * labels: [],
320
+ * }));
321
+ */
322
+ static create(initialData, version = block_storage.DATA_MODEL_DEFAULT_VERSION) {
323
+ return new DataModel({
324
+ versionChain: [version],
325
+ steps: [],
326
+ initialDataFn: initialData,
327
+ });
57
328
  }
58
- /** Create from builder (internal use) */
59
- static _fromBuilder(steps, initialData) {
60
- return new DataModel(steps, initialData);
329
+ /**
330
+ * Internal method for creating DataModel from builder.
331
+ * Uses Symbol key to prevent external access.
332
+ * @internal
333
+ */
334
+ static [FROM_BUILDER](state) {
335
+ return new DataModel(state);
61
336
  }
62
337
  /**
63
- * Latest version number.
64
- * Version 1 = initial state, each migration adds 1.
338
+ * The latest (current) version key in the migration chain.
65
339
  */
66
340
  get version() {
67
- return this.steps.length + 1;
341
+ return this.versionChain[this.versionChain.length - 1];
68
342
  }
69
- /** Number of migration steps */
343
+ /**
344
+ * Number of migration steps defined.
345
+ */
70
346
  get migrationCount() {
71
347
  return this.steps.length;
72
348
  }
73
- /** Get initial data */
349
+ /**
350
+ * Get a fresh copy of the initial data.
351
+ */
74
352
  initialData() {
75
- return this._initialData();
353
+ return this.initialDataFn();
76
354
  }
77
- /** Get default data wrapped with current version */
355
+ /**
356
+ * Get initial data wrapped with current version.
357
+ * Used when creating new blocks or resetting to defaults.
358
+ */
78
359
  getDefaultData() {
79
- return { version: this.version, data: this._initialData() };
360
+ return makeDataVersioned(this.version, this.initialDataFn());
361
+ }
362
+ recoverFrom(data, version) {
363
+ try {
364
+ return { version: this.version, data: this.recoverFn(version, data) };
365
+ }
366
+ catch (error) {
367
+ if (isDataUnrecoverableError(error)) {
368
+ return { ...this.getDefaultData(), warning: error.message };
369
+ }
370
+ const errorMessage = error instanceof Error ? error.message : String(error);
371
+ return {
372
+ ...this.getDefaultData(),
373
+ warning: `Recover failed for version '${version}': ${errorMessage}`,
374
+ };
375
+ }
80
376
  }
81
377
  /**
82
- * Upgrade versioned data from any version to the latest.
83
- * Applies only the migrations needed (skips already-applied ones).
84
- * If a migration fails, returns default data with a warning.
378
+ * Migrate versioned data from any version to the latest.
379
+ *
380
+ * - If data is already at latest version, returns as-is
381
+ * - If version is in chain, applies needed migrations
382
+ * - If version is unknown, calls recover function
383
+ * - If migration/recovery fails, returns default data with warning
384
+ *
385
+ * @param versioned - Data with version tag
386
+ * @returns Migration result with data at latest version
85
387
  */
86
- upgrade(versioned) {
388
+ migrate(versioned) {
87
389
  const { version: fromVersion, data } = versioned;
88
- if (fromVersion > this.version) {
89
- throw new Error(`Cannot downgrade from version ${fromVersion} to ${this.version}`);
90
- }
91
390
  if (fromVersion === this.version) {
92
391
  return { version: this.version, data: data };
93
392
  }
94
- // Apply migrations starting from (fromVersion - 1) index
95
- // Version 1 -> no migrations applied yet -> start at index 0
96
- // Version 2 -> migration[0] already applied -> start at index 1
97
- const startIndex = fromVersion - 1;
98
- const migrationsToApply = this.steps.slice(startIndex);
393
+ const startIndex = this.versionChain.indexOf(fromVersion);
394
+ if (startIndex < 0) {
395
+ return this.recoverFrom(data, fromVersion);
396
+ }
99
397
  let currentData = data;
100
- for (let i = 0; i < migrationsToApply.length; i++) {
101
- const stepIndex = startIndex + i;
102
- const fromVer = stepIndex + 1;
103
- const toVer = stepIndex + 2;
398
+ for (let i = startIndex; i < this.steps.length; i++) {
399
+ const step = this.steps[i];
104
400
  try {
105
- currentData = migrationsToApply[i](currentData);
401
+ currentData = step.migrate(currentData);
106
402
  }
107
403
  catch (error) {
108
404
  const errorMessage = error instanceof Error ? error.message : String(error);
109
405
  return {
110
406
  ...this.getDefaultData(),
111
- warning: `Migration v${fromVer}→v${toVer} failed: ${errorMessage}`,
407
+ warning: `Migration ${step.fromVersion}→${step.toVersion} failed: ${errorMessage}`,
112
408
  };
113
409
  }
114
410
  }
@@ -118,14 +414,11 @@ class DataModel {
118
414
  * Register callbacks for use in the VM.
119
415
  * Called by BlockModelV3.create() to set up internal callbacks.
120
416
  *
121
- * All callbacks are prefixed with `__pl_` to indicate internal SDK use:
122
- * - `__pl_data_initial`: returns initial data for new blocks
123
- * - `__pl_data_upgrade`: upgrades versioned data from any version to latest
124
- * - `__pl_storage_initial`: returns initial BlockStorage as JSON string
417
+ * @internal
125
418
  */
126
419
  registerCallbacks() {
127
- internal.tryRegisterCallback('__pl_data_initial', () => this._initialData());
128
- internal.tryRegisterCallback('__pl_data_upgrade', (versioned) => this.upgrade(versioned));
420
+ internal.tryRegisterCallback('__pl_data_initial', () => this.initialDataFn());
421
+ internal.tryRegisterCallback('__pl_data_upgrade', (versioned) => this.migrate(versioned));
129
422
  internal.tryRegisterCallback('__pl_storage_initial', () => {
130
423
  const { version, data } = this.getDefaultData();
131
424
  const storage = block_storage.createBlockStorage(data, version);
@@ -135,4 +428,10 @@ class DataModel {
135
428
  }
136
429
 
137
430
  exports.DataModel = DataModel;
431
+ exports.DataModelBuilder = DataModelBuilder;
432
+ exports.DataUnrecoverableError = DataUnrecoverableError;
433
+ exports.defaultRecover = defaultRecover;
434
+ exports.defineDataVersions = defineDataVersions;
435
+ exports.isDataUnrecoverableError = isDataUnrecoverableError;
436
+ exports.makeDataVersioned = makeDataVersioned;
138
437
  //# sourceMappingURL=block_migrations.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"block_migrations.cjs","sources":["../src/block_migrations.ts"],"sourcesContent":["import { tryRegisterCallback } from './internal';\nimport { createBlockStorage } from './block_storage';\n\nexport type MigrationFn<From, To> = (prev: Readonly<From>) => To;\n\n/** Versioned data wrapper for persistence */\nexport type Versioned<T> = {\n version: number;\n data: T;\n};\n\n/** Result of upgrade operation, may include warning if migration failed */\nexport type UpgradeResult<T> = Versioned<T> & {\n warning?: string;\n};\n\n/** Internal builder for chaining migrations */\nclass DataModelBuilder<State> {\n private readonly migrationSteps: Array<(x: unknown) => unknown>;\n\n private constructor(steps: Array<(x: unknown) => unknown> = []) {\n this.migrationSteps = steps;\n }\n\n /** Start a migration chain from an initial type */\n static from<T = unknown>(): DataModelBuilder<T> {\n return new DataModelBuilder<T>();\n }\n\n /** Add a migration step */\n migrate<Next>(fn: MigrationFn<State, Next>): DataModelBuilder<Next> {\n return new DataModelBuilder<Next>([...this.migrationSteps, fn as any]);\n }\n\n /** Finalize with initial data, creating the DataModel */\n create<S>(\n initialData: () => S,\n ..._: [State] extends [S] ? [] : [never]\n ): DataModel<S> {\n return DataModel._fromBuilder<S>(this.migrationSteps, initialData);\n }\n}\n\n/**\n * DataModel defines the block's data structure, initial values, and migrations.\n * Used by BlockModelV3 to manage data state.\n *\n * @example\n * // Simple data model (no migrations)\n * const dataModel = DataModel.create<BlockData>(() => ({\n * numbers: [],\n * labels: [],\n * }));\n *\n * // Data model with migrations\n * const dataModel = DataModel\n * .from<V1>()\n * .migrate((data) => ({ ...data, labels: [] })) // v1 → v2\n * .migrate((data) => ({ ...data, description: '' })) // v2 → v3\n * .create<BlockData>(() => ({ numbers: [], labels: [], description: '' }));\n */\nexport class DataModel<State> {\n private readonly steps: Array<(x: unknown) => unknown>;\n private readonly _initialData: () => State;\n\n private constructor(steps: Array<(x: unknown) => unknown>, initialData: () => State) {\n this.steps = steps;\n this._initialData = initialData;\n }\n\n /** Start a migration chain from an initial type */\n static from<S>(): DataModelBuilder<S> {\n return DataModelBuilder.from<S>();\n }\n\n /** Create a data model with just initial data (no migrations) */\n static create<S>(initialData: () => S): DataModel<S> {\n return new DataModel<S>([], initialData);\n }\n\n /** Create from builder (internal use) */\n static _fromBuilder<S>(\n steps: Array<(x: unknown) => unknown>,\n initialData: () => S,\n ): DataModel<S> {\n return new DataModel<S>(steps, initialData);\n }\n\n /**\n * Latest version number.\n * Version 1 = initial state, each migration adds 1.\n */\n get version(): number {\n return this.steps.length + 1;\n }\n\n /** Number of migration steps */\n get migrationCount(): number {\n return this.steps.length;\n }\n\n /** Get initial data */\n initialData(): State {\n return this._initialData();\n }\n\n /** Get default data wrapped with current version */\n getDefaultData(): Versioned<State> {\n return { version: this.version, data: this._initialData() };\n }\n\n /**\n * Upgrade versioned data from any version to the latest.\n * Applies only the migrations needed (skips already-applied ones).\n * If a migration fails, returns default data with a warning.\n */\n upgrade(versioned: Versioned<unknown>): UpgradeResult<State> {\n const { version: fromVersion, data } = versioned;\n\n if (fromVersion > this.version) {\n throw new Error(\n `Cannot downgrade from version ${fromVersion} to ${this.version}`,\n );\n }\n\n if (fromVersion === this.version) {\n return { version: this.version, data: data as State };\n }\n\n // Apply migrations starting from (fromVersion - 1) index\n // Version 1 -> no migrations applied yet -> start at index 0\n // Version 2 -> migration[0] already applied -> start at index 1\n const startIndex = fromVersion - 1;\n const migrationsToApply = this.steps.slice(startIndex);\n\n let currentData: unknown = data;\n for (let i = 0; i < migrationsToApply.length; i++) {\n const stepIndex = startIndex + i;\n const fromVer = stepIndex + 1;\n const toVer = stepIndex + 2;\n try {\n currentData = migrationsToApply[i](currentData);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return {\n ...this.getDefaultData(),\n warning: `Migration v${fromVer}→v${toVer} failed: ${errorMessage}`,\n };\n }\n }\n\n return { version: this.version, data: currentData as State };\n }\n\n /**\n * Register callbacks for use in the VM.\n * Called by BlockModelV3.create() to set up internal callbacks.\n *\n * All callbacks are prefixed with `__pl_` to indicate internal SDK use:\n * - `__pl_data_initial`: returns initial data for new blocks\n * - `__pl_data_upgrade`: upgrades versioned data from any version to latest\n * - `__pl_storage_initial`: returns initial BlockStorage as JSON string\n */\n registerCallbacks(): void {\n tryRegisterCallback('__pl_data_initial', () => this._initialData());\n tryRegisterCallback('__pl_data_upgrade', (versioned: Versioned<unknown>) => this.upgrade(versioned));\n tryRegisterCallback('__pl_storage_initial', () => {\n const { version, data } = this.getDefaultData();\n const storage = createBlockStorage(data, version);\n return JSON.stringify(storage);\n });\n }\n}\n"],"names":["tryRegisterCallback","createBlockStorage"],"mappings":";;;;;AAgBA;AACA,MAAM,gBAAgB,CAAA;AACH,IAAA,cAAc;AAE/B,IAAA,WAAA,CAAoB,QAAwC,EAAE,EAAA;AAC5D,QAAA,IAAI,CAAC,cAAc,GAAG,KAAK;IAC7B;;AAGA,IAAA,OAAO,IAAI,GAAA;QACT,OAAO,IAAI,gBAAgB,EAAK;IAClC;;AAGA,IAAA,OAAO,CAAO,EAA4B,EAAA;AACxC,QAAA,OAAO,IAAI,gBAAgB,CAAO,CAAC,GAAG,IAAI,CAAC,cAAc,EAAE,EAAS,CAAC,CAAC;IACxE;;AAGA,IAAA,MAAM,CACJ,WAAoB,EACpB,GAAG,CAAqC,EAAA;QAExC,OAAO,SAAS,CAAC,YAAY,CAAI,IAAI,CAAC,cAAc,EAAE,WAAW,CAAC;IACpE;AACD;AAED;;;;;;;;;;;;;;;;;AAiBG;MACU,SAAS,CAAA;AACH,IAA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AAI,EAAE,GAAG,IAAI,CAAC,cAAc,EAAE;YAC/C,MAAM,OAAO,GAAGC,gCAAkB,CAAC,IAAI,EAAE,OAAO,CAAC;AACjD,YAAA,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC;AAChC,QAAA,CAAC,CAAC;IACJ;AACD;;;;"}
1
+ {"version":3,"file":"block_migrations.cjs","sources":["../src/block_migrations.ts"],"sourcesContent":["import { tryRegisterCallback } from './internal';\nimport { createBlockStorage, DATA_MODEL_DEFAULT_VERSION } from './block_storage';\n\nexport type DataVersionKey = string;\nexport type DataVersionMap = Record<string, unknown>;\nexport type DataMigrateFn<From, To> = (prev: Readonly<From>) => To;\nexport type DataCreateFn<T> = () => T;\nexport type DataRecoverFn<T> = (version: DataVersionKey, data: unknown) => T;\n\n/**\n * Helper to define version keys with literal type inference and runtime validation.\n * - Validates that all version values are unique\n * - Validates that no version value is empty\n * - Eliminates need for `as const` assertion\n *\n * @throws Error if duplicate or empty version values are found\n *\n * @example\n * const Version = defineDataVersions({\n * Initial: 'v1',\n * AddedLabels: 'v2',\n * });\n *\n * type VersionedData = {\n * [Version.Initial]: DataV1;\n * [Version.AddedLabels]: DataV2;\n * };\n */\nexport function defineDataVersions<const T extends Record<string, string>>(versions: T): T {\n const values = Object.values(versions) as (string & keyof T)[];\n const keys = Object.keys(versions) as (keyof T)[];\n const emptyKeys = keys.filter((key) => versions[key] === '');\n if (emptyKeys.length > 0) {\n throw new Error(`Version values must be non-empty strings (empty: ${emptyKeys.join(', ')})`);\n }\n const unique = new Set(values);\n if (unique.size !== values.length) {\n const duplicates = values.filter((v, i) => values.indexOf(v) !== i);\n throw new Error(`Duplicate version values: ${[...new Set(duplicates)].join(', ')}`);\n }\n return versions;\n}\n\n/** Versioned data wrapper for persistence */\nexport type DataVersioned<T> = {\n version: DataVersionKey;\n data: T;\n};\n\n/** Create a DataVersioned wrapper with correct shape */\nexport function makeDataVersioned<T>(version: DataVersionKey, data: T): DataVersioned<T> {\n return { version, data };\n}\n\n/** Result of migration operation, may include warning if migration failed */\nexport type DataMigrationResult<T> = DataVersioned<T> & {\n warning?: string;\n};\n\n/** Thrown by recover() to signal unrecoverable data. */\nexport class DataUnrecoverableError extends Error {\n name = 'DataUnrecoverableError';\n constructor(dataVersion: DataVersionKey) {\n super(`Unknown version '${dataVersion}'`);\n }\n}\n\nexport function isDataUnrecoverableError(error: unknown): error is DataUnrecoverableError {\n return error instanceof Error && error.name === 'DataUnrecoverableError';\n}\n\ntype MigrationStep = {\n fromVersion: DataVersionKey;\n toVersion: DataVersionKey;\n migrate: (data: unknown) => unknown;\n};\n\n/**\n * Default recover function for unknown versions.\n * Use as fallback at the end of custom recover functions.\n *\n * @example\n * .recover((version, data) => {\n * if (version === 'legacy') {\n * return transformLegacyData(data);\n * }\n * return defaultRecover(version, data);\n * })\n */\nexport const defaultRecover: DataRecoverFn<never> = (version, _data) => {\n throw new DataUnrecoverableError(version);\n};\n\n/** Symbol for internal builder creation method */\nconst FROM_BUILDER = Symbol('fromBuilder');\n\n/** Internal state passed from builder to DataModel */\ntype BuilderState<S> = {\n versionChain: DataVersionKey[];\n steps: MigrationStep[];\n initialDataFn: () => S;\n recoverFn?: DataRecoverFn<S>;\n};\n\n/**\n * Final builder state after recover() is called.\n * Only allows calling create() to finalize the DataModel.\n *\n * @typeParam VersionedData - Map of version keys to their data types\n * @typeParam CurrentVersion - The current (final) version in the chain\n * @internal\n */\nclass DataModelBuilderWithRecover<\n VersionedData extends DataVersionMap,\n CurrentVersion extends keyof VersionedData & string,\n> {\n private readonly versionChain: DataVersionKey[];\n private readonly migrationSteps: MigrationStep[];\n private readonly recoverFn: DataRecoverFn<VersionedData[CurrentVersion]>;\n\n /** @internal */\n constructor({\n versionChain,\n steps,\n recoverFn,\n }: {\n versionChain: DataVersionKey[];\n steps: MigrationStep[];\n recoverFn: DataRecoverFn<VersionedData[CurrentVersion]>;\n }) {\n this.versionChain = versionChain;\n this.migrationSteps = steps;\n this.recoverFn = recoverFn;\n }\n\n /**\n * Finalize the DataModel with initial data factory.\n *\n * The initial data factory is called when creating new blocks or when\n * migration/recovery fails and data must be reset.\n *\n * @param initialData - Factory function returning initial state (must exactly match CurrentVersion's data type)\n * @returns Finalized DataModel instance\n *\n * @example\n * .init(() => ({ numbers: [], labels: [], description: '' }))\n */\n init<S extends VersionedData[CurrentVersion]>(\n initialData: DataCreateFn<S>,\n // Compile-time check: S must have exactly the same keys as VersionedData[CurrentVersion]\n ..._noExtraKeys: Exclude<keyof S, keyof VersionedData[CurrentVersion]> extends never ? [] : [never]\n ): DataModel<VersionedData[CurrentVersion]> {\n return DataModel[FROM_BUILDER]<VersionedData[CurrentVersion]>({\n versionChain: this.versionChain,\n steps: this.migrationSteps,\n initialDataFn: initialData as DataCreateFn<VersionedData[CurrentVersion]>,\n recoverFn: this.recoverFn,\n });\n }\n}\n\n/**\n * Internal builder for constructing DataModel with type-safe migration chains.\n *\n * Tracks the current version through the generic type system, ensuring:\n * - Migration functions receive correctly typed input\n * - Migration functions must return the correct output type\n * - Version keys must exist in the VersionedData map\n * - All versions must be covered before calling init()\n *\n * @typeParam VersionedData - Map of version keys to their data types\n * @typeParam CurrentVersion - The current version in the migration chain\n * @typeParam RemainingVersions - Versions not yet covered by migrations\n * @internal\n */\nclass DataModelMigrationChain<\n VersionedData extends DataVersionMap,\n CurrentVersion extends keyof VersionedData & string,\n RemainingVersions extends keyof VersionedData & string = Exclude<keyof VersionedData & string, CurrentVersion>,\n> {\n private readonly versionChain: DataVersionKey[];\n private readonly migrationSteps: MigrationStep[];\n\n /** @internal */\n constructor({\n versionChain,\n steps = [],\n }: {\n versionChain: DataVersionKey[];\n steps?: MigrationStep[];\n }) {\n this.versionChain = versionChain;\n this.migrationSteps = steps;\n }\n\n /**\n * Add a migration step to transform data from current version to next version.\n *\n * Migration functions:\n * - Receive data typed as the current version's data type (readonly)\n * - Must return data matching the target version's data type\n * - Should be pure functions (no side effects)\n * - May throw errors (will result in data reset with warning)\n *\n * @typeParam NextVersion - The target version key (must be in RemainingVersions)\n * @param nextVersion - The version key to migrate to\n * @param fn - Migration function transforming current data to next version\n * @returns Builder with updated current version\n *\n * @example\n * .migrate(Version.V2, (data) => ({ ...data, labels: [] }))\n */\n migrate<NextVersion extends RemainingVersions>(\n nextVersion: NextVersion,\n fn: DataMigrateFn<VersionedData[CurrentVersion], VersionedData[NextVersion]>,\n ): DataModelMigrationChain<VersionedData, NextVersion, Exclude<RemainingVersions, NextVersion>> {\n if (this.versionChain.includes(nextVersion)) {\n throw new Error(`Duplicate version '${nextVersion}' in migration chain`);\n }\n const fromVersion = this.versionChain[this.versionChain.length - 1];\n const step: MigrationStep = { fromVersion, toVersion: nextVersion, migrate: fn as (data: unknown) => unknown };\n return new DataModelMigrationChain<VersionedData, NextVersion, Exclude<RemainingVersions, NextVersion>>({\n versionChain: [...this.versionChain, nextVersion],\n steps: [...this.migrationSteps, step],\n });\n }\n\n /**\n * Set a recovery handler for unknown or legacy versions.\n *\n * The recover function is called when data has a version not in the migration chain.\n * It should either:\n * - Transform the data to the current version's format and return it\n * - Call `defaultRecover(version, data)` to signal unrecoverable data\n *\n * Can only be called once. After calling, only `init()` is available.\n *\n * @param fn - Recovery function that transforms unknown data or throws\n * @returns Builder with only init() method available\n *\n * @example\n * .recover((version, data) => {\n * if (version === 'legacy' && isLegacyFormat(data)) {\n * return transformLegacy(data);\n * }\n * return defaultRecover(version, data);\n * })\n */\n recover(\n fn: DataRecoverFn<VersionedData[CurrentVersion]>,\n ): DataModelBuilderWithRecover<VersionedData, CurrentVersion> {\n return new DataModelBuilderWithRecover<VersionedData, CurrentVersion>({\n versionChain: [...this.versionChain],\n steps: [...this.migrationSteps],\n recoverFn: fn,\n });\n }\n\n /**\n * Finalize the DataModel with initial data factory.\n *\n * Can only be called when all versions in VersionedData have been covered\n * by the migration chain (RemainingVersions is empty).\n *\n * The initial data factory is called when creating new blocks or when\n * migration/recovery fails and data must be reset.\n *\n * @param initialData - Factory function returning initial state (must exactly match CurrentVersion's data type)\n * @returns Finalized DataModel instance\n *\n * @example\n * .init(() => ({ numbers: [], labels: [], description: '' }))\n */\n init<S extends VersionedData[CurrentVersion]>(\n // Compile-time check: RemainingVersions must be empty (all versions covered)\n this: DataModelMigrationChain<VersionedData, CurrentVersion, never>,\n initialData: DataCreateFn<S>,\n // Compile-time check: S must have exactly the same keys as VersionedData[CurrentVersion]\n ..._noExtraKeys: Exclude<keyof S, keyof VersionedData[CurrentVersion]> extends never ? [] : [never]\n ): DataModel<VersionedData[CurrentVersion]> {\n return DataModel[FROM_BUILDER]<VersionedData[CurrentVersion]>({\n versionChain: this.versionChain,\n steps: this.migrationSteps,\n initialDataFn: initialData as DataCreateFn<VersionedData[CurrentVersion]>,\n });\n }\n}\n\n/**\n * Builder entry point for creating DataModel with type-safe migrations.\n *\n * @typeParam VersionedData - Map of version keys to their data types\n *\n * @example\n * const Version = defineDataVersions({\n * V1: 'v1',\n * V2: 'v2',\n * });\n *\n * type VersionedData = {\n * [Version.V1]: { count: number };\n * [Version.V2]: { count: number; label: string };\n * };\n *\n * const dataModel = new DataModelBuilder<VersionedData>()\n * .from(Version.V1)\n * .migrate(Version.V2, (data) => ({ ...data, label: '' }))\n * .init(() => ({ count: 0, label: '' }));\n */\nexport class DataModelBuilder<VersionedData extends DataVersionMap> {\n /**\n * Start a migration chain from an initial version.\n *\n * @typeParam InitialVersion - The starting version key (inferred from argument)\n * @param initialVersion - The version key to start from\n * @returns Migration chain builder for adding migrations\n *\n * @example\n * new DataModelBuilder<VersionedData>()\n * .from(Version.V1)\n * .migrate(Version.V2, (data) => ({ ...data, newField: '' }))\n */\n from<InitialVersion extends keyof VersionedData & string>(\n initialVersion: InitialVersion,\n ): DataModelMigrationChain<VersionedData, InitialVersion, Exclude<keyof VersionedData & string, InitialVersion>> {\n return new DataModelMigrationChain<\n VersionedData,\n InitialVersion,\n Exclude<keyof VersionedData & string, InitialVersion>\n >({ versionChain: [initialVersion] });\n }\n}\n\n/**\n * DataModel defines the block's data structure, initial values, and migrations.\n * Used by BlockModelV3 to manage data state.\n *\n * Two ways to create a DataModel:\n *\n * 1. **Simple (no migrations)** - Use `DataModel.create()`:\n * @example\n * const dataModel = DataModel.create<BlockData>(() => ({\n * numbers: [],\n * labels: [],\n * }));\n *\n * 2. **With migrations** - Use `new DataModelBuilder<VersionedData>()`:\n * @example\n * const Version = defineDataVersions({\n * V1: 'v1',\n * V2: 'v2',\n * V3: 'v3',\n * });\n *\n * type VersionedData = {\n * [Version.V1]: { numbers: number[] };\n * [Version.V2]: { numbers: number[]; labels: string[] };\n * [Version.V3]: { numbers: number[]; labels: string[]; description: string };\n * };\n *\n * const dataModel = new DataModelBuilder<VersionedData>()\n * .from(Version.V1)\n * .migrate(Version.V2, (data) => ({ ...data, labels: [] }))\n * .migrate(Version.V3, (data) => ({ ...data, description: '' }))\n * .recover((version, data) => {\n * if (version === 'legacy' && typeof data === 'object' && data !== null && 'numbers' in data) {\n * return { numbers: (data as { numbers: number[] }).numbers, labels: [], description: '' };\n * }\n * return defaultRecover(version, data);\n * })\n * .init(() => ({ numbers: [], labels: [], description: '' }));\n */\nexport class DataModel<State> {\n private readonly versionChain: DataVersionKey[];\n private readonly steps: MigrationStep[];\n private readonly initialDataFn: () => State;\n private readonly recoverFn: DataRecoverFn<State>;\n\n private constructor({\n versionChain,\n steps,\n initialDataFn,\n recoverFn = defaultRecover as DataRecoverFn<State>,\n }: {\n versionChain: DataVersionKey[];\n steps: MigrationStep[];\n initialDataFn: () => State;\n recoverFn?: DataRecoverFn<State>;\n }) {\n if (versionChain.length === 0) {\n throw new Error('DataModel requires at least one version key');\n }\n this.versionChain = versionChain;\n this.steps = steps;\n this.initialDataFn = initialDataFn;\n this.recoverFn = recoverFn;\n }\n\n /**\n * Create a DataModel with just initial data (no migrations).\n *\n * Use this for simple blocks that don't need version migrations.\n * The version will be set to an internal default value.\n *\n * @typeParam S - The state type\n * @param initialData - Factory function returning initial state\n * @param version - Optional custom version key (defaults to internal version)\n * @returns Finalized DataModel instance\n *\n * @example\n * const dataModel = DataModel.create<BlockData>(() => ({\n * numbers: [],\n * labels: [],\n * }));\n */\n static create<S>(initialData: () => S, version: DataVersionKey = DATA_MODEL_DEFAULT_VERSION): DataModel<S> {\n return new DataModel<S>({\n versionChain: [version],\n steps: [],\n initialDataFn: initialData,\n });\n }\n\n /**\n * Internal method for creating DataModel from builder.\n * Uses Symbol key to prevent external access.\n * @internal\n */\n static [FROM_BUILDER]<S>(state: BuilderState<S>): DataModel<S> {\n return new DataModel<S>(state);\n }\n\n /**\n * The latest (current) version key in the migration chain.\n */\n get version(): DataVersionKey {\n return this.versionChain[this.versionChain.length - 1];\n }\n\n /**\n * Number of migration steps defined.\n */\n get migrationCount(): number {\n return this.steps.length;\n }\n\n /**\n * Get a fresh copy of the initial data.\n */\n initialData(): State {\n return this.initialDataFn();\n }\n\n /**\n * Get initial data wrapped with current version.\n * Used when creating new blocks or resetting to defaults.\n */\n getDefaultData(): DataVersioned<State> {\n return makeDataVersioned(this.version, this.initialDataFn());\n }\n\n private recoverFrom(data: unknown, version: DataVersionKey): DataMigrationResult<State> {\n try {\n return { version: this.version, data: this.recoverFn(version, data) };\n } catch (error) {\n if (isDataUnrecoverableError(error)) {\n return { ...this.getDefaultData(), warning: error.message };\n }\n const errorMessage = error instanceof Error ? error.message : String(error);\n return {\n ...this.getDefaultData(),\n warning: `Recover failed for version '${version}': ${errorMessage}`,\n };\n }\n }\n\n /**\n * Migrate versioned data from any version to the latest.\n *\n * - If data is already at latest version, returns as-is\n * - If version is in chain, applies needed migrations\n * - If version is unknown, calls recover function\n * - If migration/recovery fails, returns default data with warning\n *\n * @param versioned - Data with version tag\n * @returns Migration result with data at latest version\n */\n migrate(versioned: DataVersioned<unknown>): DataMigrationResult<State> {\n const { version: fromVersion, data } = versioned;\n\n if (fromVersion === this.version) {\n return { version: this.version, data: data as State };\n }\n\n const startIndex = this.versionChain.indexOf(fromVersion);\n if (startIndex < 0) {\n return this.recoverFrom(data, fromVersion);\n }\n\n let currentData: unknown = data;\n for (let i = startIndex; i < this.steps.length; i++) {\n const step = this.steps[i];\n try {\n currentData = step.migrate(currentData);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return {\n ...this.getDefaultData(),\n warning: `Migration ${step.fromVersion}→${step.toVersion} failed: ${errorMessage}`,\n };\n }\n }\n\n return { version: this.version, data: currentData as State };\n }\n\n /**\n * Register callbacks for use in the VM.\n * Called by BlockModelV3.create() to set up internal callbacks.\n *\n * @internal\n */\n registerCallbacks(): void {\n tryRegisterCallback('__pl_data_initial', () => this.initialDataFn());\n tryRegisterCallback('__pl_data_upgrade', (versioned: DataVersioned<unknown>) => this.migrate(versioned));\n tryRegisterCallback('__pl_storage_initial', () => {\n const { version, data } = this.getDefaultData();\n const storage = createBlockStorage(data, version);\n return JSON.stringify(storage);\n });\n }\n}\n"],"names":["DATA_MODEL_DEFAULT_VERSION","tryRegisterCallback","createBlockStorage"],"mappings":";;;;;AASA;;;;;;;;;;;;;;;;;;AAkBG;AACG,SAAU,kBAAkB,CAAyC,QAAW,EAAA;IACpF,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAyB;IAC9D,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAgB;AACjD,IAAA,MAAM,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,KAAK,QAAQ,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC;AAC5D,IAAA,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE;AACxB,QAAA,MAAM,IAAI,KAAK,CAAC,CAAA,iDAAA,EAAoD,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA,CAAA,CAAG,CAAC;IAC9F;AACA,IAAA,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC;IAC9B,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM,CAAC,MAAM,EAAE;QACjC,MAAM,UA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