@bernierllc/contentful-migration-service 1.0.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.
package/LICENSE.md ADDED
@@ -0,0 +1,11 @@
1
+ # Limited Use License
2
+
3
+ Copyright (c) 2025 Bernier LLC
4
+
5
+ This file is licensed to the client under a limited-use license.
6
+
7
+ The client may use and modify this code **only within the scope of the project it was delivered for**.
8
+
9
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
10
+
11
+ For licensing inquiries, please contact: legal@bernierllc.com
package/README.md ADDED
@@ -0,0 +1,463 @@
1
+ # @bernierllc/contentful-migration-service
2
+
3
+ Content model migration management with version control, rollback support, and migration history tracking for Contentful.
4
+
5
+ ## Features
6
+
7
+ - **Migration Execution**: Run content model migrations using Contentful's official migration library
8
+ - **History Tracking**: Track migration execution history with flexible storage backends
9
+ - **Dry-Run Mode**: Validate migrations before executing them
10
+ - **Abstract Storage**: Plug in your own storage implementation (PostgreSQL, MongoDB, etc.)
11
+ - **NeverHub Integration**: Optional integration with NeverHub for event tracking
12
+ - **Type Safety**: Full TypeScript support with strict typing
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install @bernierllc/contentful-migration-service
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ ### Quick Start
23
+
24
+ ```typescript
25
+ import {
26
+ ContentfulMigrationService,
27
+ InMemoryMigrationStorage
28
+ } from '@bernierllc/contentful-migration-service';
29
+
30
+ // Create storage (in-memory for testing, use persistent storage in production)
31
+ const storage = new InMemoryMigrationStorage();
32
+
33
+ // Initialize service
34
+ const service = new ContentfulMigrationService({
35
+ spaceId: 'your-space-id',
36
+ environmentId: 'master',
37
+ accessToken: 'your-cma-token',
38
+ storage,
39
+ executedBy: 'john@example.com',
40
+ });
41
+
42
+ // Define migration
43
+ const migrationFn = (migration) => {
44
+ const blogPost = migration.createContentType('blogPost', {
45
+ name: 'Blog Post',
46
+ description: 'A blog post content type',
47
+ });
48
+
49
+ blogPost.createField('title', {
50
+ name: 'Title',
51
+ type: 'Symbol',
52
+ required: true,
53
+ });
54
+
55
+ blogPost.createField('content', {
56
+ name: 'Content',
57
+ type: 'Text',
58
+ });
59
+ };
60
+
61
+ // Run migration
62
+ const result = await service.runMigration(migrationFn, {
63
+ id: 'create-blog-post-001',
64
+ name: 'Create Blog Post Content Type',
65
+ description: 'Initial blog post content type with title and content fields',
66
+ });
67
+
68
+ if (result.success) {
69
+ console.log(`Migration completed in ${result.duration}ms`);
70
+ } else {
71
+ console.error(`Migration failed: ${result.error}`);
72
+ }
73
+ ```
74
+
75
+ ## Core Concepts
76
+
77
+ ### Migration Storage
78
+
79
+ The service uses an abstract `MigrationStorage` interface, allowing you to plug in any storage backend:
80
+
81
+ ```typescript
82
+ interface MigrationStorage {
83
+ saveMigration(record: MigrationRecord): Promise<void>;
84
+ getMigration(id: string): Promise<MigrationRecord | null>;
85
+ getMigrations(spaceId: string, environmentId: string): Promise<MigrationRecord[]>;
86
+ hasMigration(id: string, spaceId: string, environmentId: string): Promise<boolean>;
87
+ updateMigrationStatus(
88
+ id: string,
89
+ status: MigrationRecord['status'],
90
+ error?: string,
91
+ duration?: number
92
+ ): Promise<void>;
93
+ }
94
+ ```
95
+
96
+ ### Built-in Storage
97
+
98
+ **InMemoryMigrationStorage**: For testing and development
99
+ ```typescript
100
+ import { InMemoryMigrationStorage } from '@bernierllc/contentful-migration-service';
101
+
102
+ const storage = new InMemoryMigrationStorage();
103
+ ```
104
+
105
+ ### Custom Storage
106
+
107
+ Implement your own storage for production use:
108
+
109
+ ```typescript
110
+ import { MigrationStorage, MigrationRecord } from '@bernierllc/contentful-migration-service';
111
+ import { Pool } from 'pg';
112
+
113
+ class PostgresMigrationStorage implements MigrationStorage {
114
+ constructor(private pool: Pool) {}
115
+
116
+ async saveMigration(record: MigrationRecord): Promise<void> {
117
+ await this.pool.query(
118
+ `INSERT INTO migrations (id, name, description, executed_at, status, space_id, environment_id, dry_run)
119
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
120
+ ON CONFLICT (id) DO UPDATE SET
121
+ status = EXCLUDED.status,
122
+ duration = EXCLUDED.duration,
123
+ error = EXCLUDED.error`,
124
+ [record.id, record.name, record.description, record.executedAt,
125
+ record.status, record.spaceId, record.environmentId, record.dryRun]
126
+ );
127
+ }
128
+
129
+ // Implement other methods...
130
+ }
131
+ ```
132
+
133
+ ## API Reference
134
+
135
+ ### ContentfulMigrationService
136
+
137
+ #### Constructor
138
+
139
+ ```typescript
140
+ constructor(config: MigrationServiceConfig)
141
+ ```
142
+
143
+ **Config Options:**
144
+ - `spaceId` (string): Contentful space ID
145
+ - `environmentId` (string, optional): Environment ID (default: 'master')
146
+ - `accessToken` (string): Contentful CMA access token
147
+ - `storage` (MigrationStorage): Storage implementation for migration history
148
+ - `executedBy` (string, optional): Identifier for who is executing migrations
149
+
150
+ #### runMigration
151
+
152
+ Run a migration function:
153
+
154
+ ```typescript
155
+ async runMigration(
156
+ migrationFn: MigrationFunction,
157
+ options: MigrationOptions
158
+ ): Promise<MigrationResult>
159
+ ```
160
+
161
+ **Options:**
162
+ - `id` (string): Unique migration ID
163
+ - `name` (string): Human-readable name
164
+ - `description` (string, optional): Description of what the migration does
165
+ - `dryRun` (boolean, optional): Run in validation-only mode
166
+ - `timeout` (number, optional): Timeout in milliseconds
167
+
168
+ **Returns:** `MigrationResult` with success status, duration, and any errors
169
+
170
+ #### getMigrationHistory
171
+
172
+ Get all migrations for the configured space/environment:
173
+
174
+ ```typescript
175
+ async getMigrationHistory(): Promise<MigrationRecord[]>
176
+ ```
177
+
178
+ #### getMigration
179
+
180
+ Get a specific migration by ID:
181
+
182
+ ```typescript
183
+ async getMigration(id: string): Promise<MigrationRecord | null>
184
+ ```
185
+
186
+ #### hasExecutedMigration
187
+
188
+ Check if a migration has been successfully executed:
189
+
190
+ ```typescript
191
+ async hasExecutedMigration(id: string): Promise<boolean>
192
+ ```
193
+
194
+ #### validateMigration
195
+
196
+ Validate a migration without executing it:
197
+
198
+ ```typescript
199
+ async validateMigration(
200
+ migrationFn: MigrationFunction,
201
+ options: Pick<MigrationOptions, 'id' | 'name' | 'description'>
202
+ ): Promise<ValidationResult>
203
+ ```
204
+
205
+ #### getPendingMigrations
206
+
207
+ Get migrations that haven't been executed yet:
208
+
209
+ ```typescript
210
+ async getPendingMigrations(migrationIds: string[]): Promise<string[]>
211
+ ```
212
+
213
+ #### getCMAClient
214
+
215
+ Get the underlying Contentful CMA client for advanced operations:
216
+
217
+ ```typescript
218
+ getCMAClient(): ContentfulCMAClient
219
+ ```
220
+
221
+ ## Migration Examples
222
+
223
+ ### Creating a Content Type
224
+
225
+ ```typescript
226
+ const migrationFn = (migration) => {
227
+ const author = migration.createContentType('author', {
228
+ name: 'Author',
229
+ description: 'Author of blog posts',
230
+ });
231
+
232
+ author.createField('name', {
233
+ name: 'Name',
234
+ type: 'Symbol',
235
+ required: true,
236
+ });
237
+
238
+ author.createField('bio', {
239
+ name: 'Biography',
240
+ type: 'Text',
241
+ });
242
+
243
+ author.displayField('name');
244
+ };
245
+
246
+ await service.runMigration(migrationFn, {
247
+ id: 'create-author-001',
248
+ name: 'Create Author Content Type',
249
+ });
250
+ ```
251
+
252
+ ### Modifying an Existing Content Type
253
+
254
+ ```typescript
255
+ const migrationFn = (migration) => {
256
+ const blogPost = migration.editContentType('blogPost');
257
+
258
+ blogPost.createField('publishDate', {
259
+ name: 'Publish Date',
260
+ type: 'Date',
261
+ required: false,
262
+ });
263
+
264
+ blogPost.createField('author', {
265
+ name: 'Author',
266
+ type: 'Link',
267
+ linkType: 'Entry',
268
+ validations: [{
269
+ linkContentType: ['author'],
270
+ }],
271
+ });
272
+ };
273
+
274
+ await service.runMigration(migrationFn, {
275
+ id: 'add-author-to-blog-post-001',
276
+ name: 'Add Author and Publish Date to Blog Post',
277
+ });
278
+ ```
279
+
280
+ ### Dry-Run Mode
281
+
282
+ Test migrations before executing:
283
+
284
+ ```typescript
285
+ const result = await service.runMigration(migrationFn, {
286
+ id: 'risky-migration-001',
287
+ name: 'Risky Migration',
288
+ dryRun: true,
289
+ });
290
+
291
+ if (result.success) {
292
+ console.log('Migration is valid!');
293
+ // Now run it for real
294
+ await service.runMigration(migrationFn, {
295
+ id: 'risky-migration-001',
296
+ name: 'Risky Migration',
297
+ dryRun: false,
298
+ });
299
+ }
300
+ ```
301
+
302
+ ### Migration History
303
+
304
+ ```typescript
305
+ // Get all migrations
306
+ const history = await service.getMigrationHistory();
307
+ console.log(`Total migrations: ${history.length}`);
308
+
309
+ history.forEach(migration => {
310
+ console.log(`${migration.name}: ${migration.status} (${migration.executedAt})`);
311
+ });
312
+
313
+ // Check if specific migration was executed
314
+ const hasRun = await service.hasExecutedMigration('create-blog-post-001');
315
+ if (hasRun) {
316
+ console.log('Migration already executed, skipping...');
317
+ }
318
+ ```
319
+
320
+ ### Pending Migrations
321
+
322
+ ```typescript
323
+ const allMigrationIds = [
324
+ 'create-blog-post-001',
325
+ 'create-author-001',
326
+ 'add-author-to-blog-post-001',
327
+ ];
328
+
329
+ const pending = await service.getPendingMigrations(allMigrationIds);
330
+ console.log(`Pending migrations: ${pending.join(', ')}`);
331
+
332
+ // Run all pending migrations
333
+ for (const id of pending) {
334
+ const migrationFn = getMigrationFunction(id); // Your function to load migration
335
+ await service.runMigration(migrationFn, {
336
+ id,
337
+ name: getMigrationName(id),
338
+ });
339
+ }
340
+ ```
341
+
342
+ ## Integration Status
343
+
344
+ **Logger Integration**: ✅ Implemented
345
+ Uses `@bernierllc/logger` for structured logging throughout the service.
346
+
347
+ **NeverHub Integration**: ✅ Implemented
348
+ Automatically detects and integrates with NeverHub if available.
349
+
350
+ ## NeverHub Integration
351
+
352
+ The service automatically detects and integrates with NeverHub if available:
353
+
354
+ ```typescript
355
+ // Events emitted:
356
+ // - migration.completed: When migration succeeds
357
+ // - migration.failed: When migration fails
358
+
359
+ const service = new ContentfulMigrationService(config);
360
+ // NeverHub automatically initialized if available
361
+ ```
362
+
363
+ ## Best Practices
364
+
365
+ ### 1. Use Unique Migration IDs
366
+
367
+ Always use unique, descriptive IDs for migrations:
368
+
369
+ ```typescript
370
+ // Good
371
+ id: 'create-blog-post-content-type-2025-01-15'
372
+ id: 'add-seo-fields-to-blog-post-001'
373
+
374
+ // Bad
375
+ id: '1'
376
+ id: 'migration'
377
+ ```
378
+
379
+ ### 2. Test with Dry-Run First
380
+
381
+ Always validate migrations in dry-run mode before executing:
382
+
383
+ ```typescript
384
+ // Validate first
385
+ await service.runMigration(migrationFn, { id, name, dryRun: true });
386
+
387
+ // Then execute
388
+ await service.runMigration(migrationFn, { id, name, dryRun: false });
389
+ ```
390
+
391
+ ### 3. Use Persistent Storage in Production
392
+
393
+ Never use `InMemoryMigrationStorage` in production:
394
+
395
+ ```typescript
396
+ // Development
397
+ const storage = new InMemoryMigrationStorage();
398
+
399
+ // Production
400
+ const storage = new PostgresMigrationStorage(pgPool);
401
+ ```
402
+
403
+ ### 4. Handle Failures Gracefully
404
+
405
+ Always check migration results and handle failures:
406
+
407
+ ```typescript
408
+ const result = await service.runMigration(migrationFn, options);
409
+
410
+ if (!result.success) {
411
+ console.error(`Migration failed: ${result.error}`);
412
+ // Send alert, log to monitoring system, etc.
413
+ throw new Error(`Migration ${options.id} failed: ${result.error}`);
414
+ }
415
+ ```
416
+
417
+ ### 5. Keep Migrations Small
418
+
419
+ Break large changes into smaller, atomic migrations:
420
+
421
+ ```typescript
422
+ // Instead of one large migration:
423
+ // ❌ 'update-entire-content-model-001'
424
+
425
+ // Use multiple smaller migrations:
426
+ // ✅ 'add-seo-fields-to-blog-post-001'
427
+ // ✅ 'add-author-relationship-to-blog-post-002'
428
+ // ✅ 'add-categories-to-blog-post-003'
429
+ ```
430
+
431
+ ## Error Handling
432
+
433
+ The service handles errors gracefully and tracks them in storage:
434
+
435
+ ```typescript
436
+ try {
437
+ const result = await service.runMigration(migrationFn, options);
438
+
439
+ if (!result.success) {
440
+ // Migration failed but error was caught
441
+ console.error(result.error);
442
+ }
443
+ } catch (error) {
444
+ // Unexpected error (storage failure, etc.)
445
+ console.error('Unexpected error:', error);
446
+ }
447
+ ```
448
+
449
+ ## Dependencies
450
+
451
+ - `@bernierllc/contentful-types` - Type definitions
452
+ - `@bernierllc/contentful-cma-client` - CMA client wrapper
453
+ - `@bernierllc/logger` - Logging
454
+ - `@bernierllc/neverhub-adapter` - Optional event tracking
455
+ - `contentful-migration` - Official Contentful migration library
456
+
457
+ ## License
458
+
459
+ Copyright (c) 2025 Bernier LLC - See LICENSE.md for details
460
+
461
+ ## Support
462
+
463
+ For issues and questions, please contact: support@bernierllc.com
@@ -0,0 +1,49 @@
1
+ import { ContentfulCMAClient } from '@bernierllc/contentful-cma-client';
2
+ import { MigrationServiceConfig, MigrationOptions, MigrationResult, MigrationRecord, MigrationFunction, ValidationResult } from './types';
3
+ /**
4
+ * ContentfulMigrationService manages content model migrations with version control,
5
+ * rollback support, and migration history tracking.
6
+ */
7
+ export declare class ContentfulMigrationService {
8
+ private logger;
9
+ private cmaClient;
10
+ private config;
11
+ private neverhub?;
12
+ constructor(config: MigrationServiceConfig);
13
+ /**
14
+ * Initialize NeverHub integration if available
15
+ */
16
+ private initializeNeverHub;
17
+ /**
18
+ * Run a migration function
19
+ */
20
+ runMigration(migrationFn: MigrationFunction, options: MigrationOptions): Promise<MigrationResult>;
21
+ /**
22
+ * Get migration history
23
+ */
24
+ getMigrationHistory(): Promise<MigrationRecord[]>;
25
+ /**
26
+ * Get a specific migration by ID
27
+ */
28
+ getMigration(id: string): Promise<MigrationRecord | null>;
29
+ /**
30
+ * Check if a migration has been executed
31
+ */
32
+ hasExecutedMigration(id: string): Promise<boolean>;
33
+ /**
34
+ * Validate a migration function without executing
35
+ */
36
+ validateMigration(migrationFn: MigrationFunction, options: Pick<MigrationOptions, 'id' | 'name' | 'description'>): Promise<ValidationResult>;
37
+ /**
38
+ * Get pending migrations (not yet executed)
39
+ */
40
+ getPendingMigrations(migrationIds: string[]): Promise<string[]>;
41
+ /**
42
+ * Get the Contentful CMA client (for advanced operations)
43
+ */
44
+ getCMAClient(): ContentfulCMAClient;
45
+ /**
46
+ * Close connections and cleanup
47
+ */
48
+ close(): Promise<void>;
49
+ }
@@ -0,0 +1,239 @@
1
+ "use strict";
2
+ /*
3
+ Copyright (c) 2025 Bernier LLC
4
+
5
+ This file is licensed to the client under a limited-use license.
6
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
7
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.ContentfulMigrationService = void 0;
11
+ const contentful_migration_1 = require("contentful-migration");
12
+ const contentful_cma_client_1 = require("@bernierllc/contentful-cma-client");
13
+ const logger_1 = require("@bernierllc/logger");
14
+ const neverhub_adapter_1 = require("@bernierllc/neverhub-adapter");
15
+ /**
16
+ * ContentfulMigrationService manages content model migrations with version control,
17
+ * rollback support, and migration history tracking.
18
+ */
19
+ class ContentfulMigrationService {
20
+ constructor(config) {
21
+ this.config = {
22
+ ...config,
23
+ environmentId: config.environmentId || 'master',
24
+ };
25
+ this.logger = new logger_1.Logger({
26
+ level: 2, // INFO level
27
+ transports: [],
28
+ context: {
29
+ service: 'ContentfulMigrationService',
30
+ version: '1.0.0',
31
+ environment: process.env.NODE_ENV || 'development',
32
+ },
33
+ });
34
+ this.cmaClient = new contentful_cma_client_1.ContentfulCMAClient({
35
+ accessToken: config.accessToken,
36
+ spaceId: config.spaceId,
37
+ environmentId: this.config.environmentId,
38
+ });
39
+ this.initializeNeverHub();
40
+ }
41
+ /**
42
+ * Initialize NeverHub integration if available
43
+ */
44
+ async initializeNeverHub() {
45
+ try {
46
+ if (await neverhub_adapter_1.NeverHubAdapter.detect()) {
47
+ this.neverhub = new neverhub_adapter_1.NeverHubAdapter();
48
+ await this.neverhub.register({
49
+ type: 'contentful-migration-service',
50
+ name: '@bernierllc/contentful-migration-service',
51
+ version: '1.0.0',
52
+ dependencies: [
53
+ '@bernierllc/contentful-cma-client',
54
+ '@bernierllc/contentful-types',
55
+ ],
56
+ capabilities: [
57
+ {
58
+ type: 'migration',
59
+ name: 'contentful-migrations',
60
+ version: '1.0.0',
61
+ },
62
+ ],
63
+ });
64
+ this.logger.info('NeverHub integration initialized');
65
+ }
66
+ }
67
+ catch (error) {
68
+ this.logger.warn('NeverHub integration not available', { error });
69
+ }
70
+ }
71
+ /**
72
+ * Run a migration function
73
+ */
74
+ async runMigration(migrationFn, options) {
75
+ const startTime = Date.now();
76
+ const { id, name, description, dryRun = false } = options;
77
+ this.logger.info(`Starting migration: ${name}`, { id, dryRun });
78
+ // Check if migration already executed
79
+ const alreadyExecuted = await this.config.storage.hasMigration(id, this.config.spaceId, this.config.environmentId);
80
+ if (alreadyExecuted && !dryRun) {
81
+ this.logger.warn(`Migration ${id} already executed, skipping`);
82
+ return {
83
+ success: true,
84
+ migrationId: id,
85
+ duration: 0,
86
+ dryRun: false,
87
+ error: 'Migration already executed',
88
+ };
89
+ }
90
+ // Create migration record
91
+ const record = {
92
+ id,
93
+ name,
94
+ description,
95
+ executedAt: new Date(),
96
+ executedBy: this.config.executedBy,
97
+ status: 'running',
98
+ spaceId: this.config.spaceId,
99
+ environmentId: this.config.environmentId,
100
+ dryRun,
101
+ };
102
+ await this.config.storage.saveMigration(record);
103
+ try {
104
+ // Run migration using contentful-migration
105
+ await (0, contentful_migration_1.runMigration)({
106
+ spaceId: this.config.spaceId,
107
+ environmentId: this.config.environmentId,
108
+ accessToken: this.config.accessToken,
109
+ yes: !dryRun,
110
+ migrationFunction: migrationFn,
111
+ });
112
+ const duration = Date.now() - startTime;
113
+ // Update status
114
+ await this.config.storage.updateMigrationStatus(id, 'completed', undefined, duration);
115
+ this.logger.info(`Migration completed: ${name}`, { id, duration, dryRun });
116
+ if (this.neverhub) {
117
+ await this.neverhub.publishEvent({
118
+ type: 'migration.completed',
119
+ data: {
120
+ migrationId: id,
121
+ name,
122
+ duration,
123
+ dryRun,
124
+ },
125
+ });
126
+ }
127
+ return {
128
+ success: true,
129
+ migrationId: id,
130
+ duration,
131
+ dryRun,
132
+ };
133
+ }
134
+ catch (error) {
135
+ const duration = Date.now() - startTime;
136
+ const errorMessage = error instanceof Error ? error.message : String(error);
137
+ const errorObj = error instanceof Error ? error : new Error(String(error));
138
+ await this.config.storage.updateMigrationStatus(id, 'failed', errorMessage, duration);
139
+ this.logger.error(`Migration failed: ${name}`, errorObj, { migrationId: id });
140
+ if (this.neverhub) {
141
+ await this.neverhub.publishEvent({
142
+ type: 'migration.failed',
143
+ data: {
144
+ migrationId: id,
145
+ name,
146
+ error: errorMessage,
147
+ duration,
148
+ },
149
+ });
150
+ }
151
+ return {
152
+ success: false,
153
+ migrationId: id,
154
+ duration,
155
+ dryRun,
156
+ error: errorMessage,
157
+ };
158
+ }
159
+ }
160
+ /**
161
+ * Get migration history
162
+ */
163
+ async getMigrationHistory() {
164
+ this.logger.debug('Fetching migration history');
165
+ return this.config.storage.getMigrations(this.config.spaceId, this.config.environmentId);
166
+ }
167
+ /**
168
+ * Get a specific migration by ID
169
+ */
170
+ async getMigration(id) {
171
+ return this.config.storage.getMigration(id);
172
+ }
173
+ /**
174
+ * Check if a migration has been executed
175
+ */
176
+ async hasExecutedMigration(id) {
177
+ return this.config.storage.hasMigration(id, this.config.spaceId, this.config.environmentId);
178
+ }
179
+ /**
180
+ * Validate a migration function without executing
181
+ */
182
+ async validateMigration(migrationFn, options) {
183
+ this.logger.info('Validating migration', { id: options.id });
184
+ try {
185
+ // Run in dry-run mode for validation
186
+ const result = await this.runMigration(migrationFn, {
187
+ ...options,
188
+ dryRun: true,
189
+ });
190
+ if (result.success) {
191
+ return {
192
+ valid: true,
193
+ errors: [],
194
+ warnings: [],
195
+ };
196
+ }
197
+ return {
198
+ valid: false,
199
+ errors: result.error ? [result.error] : ['Unknown validation error'],
200
+ warnings: [],
201
+ };
202
+ }
203
+ catch (error) {
204
+ const errorMessage = error instanceof Error ? error.message : String(error);
205
+ return {
206
+ valid: false,
207
+ errors: [errorMessage],
208
+ warnings: [],
209
+ };
210
+ }
211
+ }
212
+ /**
213
+ * Get pending migrations (not yet executed)
214
+ */
215
+ async getPendingMigrations(migrationIds) {
216
+ const pending = [];
217
+ for (const id of migrationIds) {
218
+ const executed = await this.hasExecutedMigration(id);
219
+ if (!executed) {
220
+ pending.push(id);
221
+ }
222
+ }
223
+ return pending;
224
+ }
225
+ /**
226
+ * Get the Contentful CMA client (for advanced operations)
227
+ */
228
+ getCMAClient() {
229
+ return this.cmaClient;
230
+ }
231
+ /**
232
+ * Close connections and cleanup
233
+ */
234
+ async close() {
235
+ this.logger.info('Closing ContentfulMigrationService');
236
+ // No cleanup needed for current implementation
237
+ }
238
+ }
239
+ exports.ContentfulMigrationService = ContentfulMigrationService;
@@ -0,0 +1,5 @@
1
+ export declare class NeverHubAdapter {
2
+ static detect(): Promise<boolean>;
3
+ register(): Promise<void>;
4
+ publishEvent(): Promise<void>;
5
+ }
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NeverHubAdapter = void 0;
4
+ class NeverHubAdapter {
5
+ static async detect() {
6
+ return false;
7
+ }
8
+ async register() {
9
+ return;
10
+ }
11
+ async publishEvent() {
12
+ return;
13
+ }
14
+ }
15
+ exports.NeverHubAdapter = NeverHubAdapter;
@@ -0,0 +1,3 @@
1
+ export { ContentfulMigrationService } from './ContentfulMigrationService';
2
+ export { InMemoryMigrationStorage } from './storage/InMemoryMigrationStorage';
3
+ export type { MigrationRecord, MigrationStorage, MigrationServiceConfig, MigrationOptions, MigrationResult, MigrationFunction, ValidationResult, } from './types';
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ /*
3
+ Copyright (c) 2025 Bernier LLC
4
+
5
+ This file is licensed to the client under a limited-use license.
6
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
7
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.InMemoryMigrationStorage = exports.ContentfulMigrationService = void 0;
11
+ var ContentfulMigrationService_1 = require("./ContentfulMigrationService");
12
+ Object.defineProperty(exports, "ContentfulMigrationService", { enumerable: true, get: function () { return ContentfulMigrationService_1.ContentfulMigrationService; } });
13
+ var InMemoryMigrationStorage_1 = require("./storage/InMemoryMigrationStorage");
14
+ Object.defineProperty(exports, "InMemoryMigrationStorage", { enumerable: true, get: function () { return InMemoryMigrationStorage_1.InMemoryMigrationStorage; } });
@@ -0,0 +1,20 @@
1
+ import { MigrationStorage, MigrationRecord } from '../types';
2
+ /**
3
+ * In-memory implementation of MigrationStorage for testing and development
4
+ */
5
+ export declare class InMemoryMigrationStorage implements MigrationStorage {
6
+ private migrations;
7
+ saveMigration(record: MigrationRecord): Promise<void>;
8
+ getMigration(id: string): Promise<MigrationRecord | null>;
9
+ getMigrations(spaceId: string, environmentId: string): Promise<MigrationRecord[]>;
10
+ hasMigration(id: string, spaceId: string, environmentId: string): Promise<boolean>;
11
+ updateMigrationStatus(id: string, status: MigrationRecord['status'], error?: string, duration?: number): Promise<void>;
12
+ /**
13
+ * Clear all migrations (for testing)
14
+ */
15
+ clear(): void;
16
+ /**
17
+ * Get count of migrations (for testing)
18
+ */
19
+ count(): number;
20
+ }
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ /*
3
+ Copyright (c) 2025 Bernier LLC
4
+
5
+ This file is licensed to the client under a limited-use license.
6
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
7
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.InMemoryMigrationStorage = void 0;
11
+ /**
12
+ * In-memory implementation of MigrationStorage for testing and development
13
+ */
14
+ class InMemoryMigrationStorage {
15
+ constructor() {
16
+ this.migrations = new Map();
17
+ }
18
+ async saveMigration(record) {
19
+ this.migrations.set(record.id, { ...record });
20
+ }
21
+ async getMigration(id) {
22
+ return this.migrations.get(id) || null;
23
+ }
24
+ async getMigrations(spaceId, environmentId) {
25
+ return Array.from(this.migrations.values())
26
+ .filter(m => m.spaceId === spaceId && m.environmentId === environmentId)
27
+ .sort((a, b) => b.executedAt.getTime() - a.executedAt.getTime());
28
+ }
29
+ async hasMigration(id, spaceId, environmentId) {
30
+ const migration = this.migrations.get(id);
31
+ return !!(migration &&
32
+ migration.spaceId === spaceId &&
33
+ migration.environmentId === environmentId &&
34
+ migration.status === 'completed');
35
+ }
36
+ async updateMigrationStatus(id, status, error, duration) {
37
+ const migration = this.migrations.get(id);
38
+ if (!migration) {
39
+ throw new Error(`Migration ${id} not found`);
40
+ }
41
+ migration.status = status;
42
+ if (error !== undefined) {
43
+ migration.error = error;
44
+ }
45
+ if (duration !== undefined) {
46
+ migration.duration = duration;
47
+ }
48
+ this.migrations.set(id, migration);
49
+ }
50
+ /**
51
+ * Clear all migrations (for testing)
52
+ */
53
+ clear() {
54
+ this.migrations.clear();
55
+ }
56
+ /**
57
+ * Get count of migrations (for testing)
58
+ */
59
+ count() {
60
+ return this.migrations.size;
61
+ }
62
+ }
63
+ exports.InMemoryMigrationStorage = InMemoryMigrationStorage;
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Migration record stored in persistent storage
3
+ */
4
+ export interface MigrationRecord {
5
+ id: string;
6
+ name: string;
7
+ description?: string;
8
+ executedAt: Date;
9
+ executedBy?: string;
10
+ status: 'pending' | 'running' | 'completed' | 'failed' | 'rolled_back';
11
+ spaceId: string;
12
+ environmentId: string;
13
+ dryRun: boolean;
14
+ duration?: number;
15
+ error?: string;
16
+ checksum?: string;
17
+ }
18
+ /**
19
+ * Abstract storage interface for migration history tracking
20
+ * Allows users to provide their own storage implementation
21
+ */
22
+ export interface MigrationStorage {
23
+ /**
24
+ * Save a migration record
25
+ */
26
+ saveMigration(record: MigrationRecord): Promise<void>;
27
+ /**
28
+ * Get a migration by ID
29
+ */
30
+ getMigration(id: string): Promise<MigrationRecord | null>;
31
+ /**
32
+ * Get all migrations for a space/environment
33
+ */
34
+ getMigrations(spaceId: string, environmentId: string): Promise<MigrationRecord[]>;
35
+ /**
36
+ * Check if a migration has been executed
37
+ */
38
+ hasMigration(id: string, spaceId: string, environmentId: string): Promise<boolean>;
39
+ /**
40
+ * Update migration status
41
+ */
42
+ updateMigrationStatus(id: string, status: MigrationRecord['status'], error?: string, duration?: number): Promise<void>;
43
+ }
44
+ /**
45
+ * Configuration for ContentfulMigrationService
46
+ */
47
+ export interface MigrationServiceConfig {
48
+ /**
49
+ * Contentful space ID
50
+ */
51
+ spaceId: string;
52
+ /**
53
+ * Contentful environment ID (default: 'master')
54
+ */
55
+ environmentId?: string;
56
+ /**
57
+ * Contentful CMA access token
58
+ */
59
+ accessToken: string;
60
+ /**
61
+ * Storage implementation for migration history
62
+ */
63
+ storage: MigrationStorage;
64
+ /**
65
+ * Optional identifier for who is executing migrations
66
+ */
67
+ executedBy?: string;
68
+ }
69
+ /**
70
+ * Options for running a migration
71
+ */
72
+ export interface MigrationOptions {
73
+ /**
74
+ * Migration ID (for tracking)
75
+ */
76
+ id: string;
77
+ /**
78
+ * Human-readable name
79
+ */
80
+ name: string;
81
+ /**
82
+ * Optional description
83
+ */
84
+ description?: string;
85
+ /**
86
+ * Run in dry-run mode (validation only)
87
+ */
88
+ dryRun?: boolean;
89
+ /**
90
+ * Timeout in milliseconds
91
+ */
92
+ timeout?: number;
93
+ }
94
+ /**
95
+ * Result of migration execution
96
+ */
97
+ export interface MigrationResult {
98
+ success: boolean;
99
+ migrationId: string;
100
+ duration: number;
101
+ dryRun: boolean;
102
+ error?: string;
103
+ }
104
+ /**
105
+ * Migration function type
106
+ * The migration parameter is the Contentful migration context object
107
+ * from the contentful-migration library (typed as any due to external library)
108
+ */
109
+ export type MigrationFunction = (migration: any) => void;
110
+ /**
111
+ * Validation result for migration
112
+ */
113
+ export interface ValidationResult {
114
+ valid: boolean;
115
+ errors: string[];
116
+ warnings: string[];
117
+ }
package/dist/types.js ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ /*
3
+ Copyright (c) 2025 Bernier LLC
4
+
5
+ This file is licensed to the client under a limited-use license.
6
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
7
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@bernierllc/contentful-migration-service",
3
+ "version": "1.0.2",
4
+ "description": "Content model migration management with version control, rollback support, and migration history tracking",
5
+ "keywords": [
6
+ "contentful",
7
+ "migrations",
8
+ "content-model",
9
+ "versioning",
10
+ "service",
11
+ "bernierllc"
12
+ ],
13
+ "author": "Bernier LLC",
14
+ "license": "SEE LICENSE IN LICENSE.md",
15
+ "main": "dist/index.js",
16
+ "types": "dist/index.d.ts",
17
+ "files": [
18
+ "dist",
19
+ "LICENSE.md",
20
+ "README.md"
21
+ ],
22
+ "dependencies": {
23
+ "@bernierllc/contentful-types": "^1.0.4",
24
+ "@bernierllc/contentful-cma-client": "^1.0.2",
25
+ "@bernierllc/logger": "^1.0.1",
26
+ "@bernierllc/neverhub-adapter": "^1.0.2",
27
+ "contentful-migration": "^4.0.0"
28
+ },
29
+ "devDependencies": {
30
+ "@types/jest": "^29.5.14",
31
+ "@types/node": "^22.10.1",
32
+ "@typescript-eslint/eslint-plugin": "^8.15.0",
33
+ "@typescript-eslint/parser": "^8.15.0",
34
+ "eslint": "^9.15.0",
35
+ "jest": "^29.7.0",
36
+ "ts-jest": "^29.2.5",
37
+ "typescript": "^5.7.2"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "scripts": {
43
+ "build": "tsc",
44
+ "test": "jest --runInBand",
45
+ "test:run": "jest --runInBand",
46
+ "test:watch": "jest --watch",
47
+ "test:coverage": "jest --coverage --runInBand",
48
+ "lint": "eslint src --ext .ts",
49
+ "lint:fix": "eslint src --ext .ts --fix",
50
+ "clean": "rm -rf dist"
51
+ }
52
+ }