pocketbase-zod-schema 0.1.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.
Files changed (94) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/LICENSE +21 -0
  3. package/README.md +167 -0
  4. package/dist/cli/index.cjs +3383 -0
  5. package/dist/cli/index.cjs.map +1 -0
  6. package/dist/cli/index.d.cts +30 -0
  7. package/dist/cli/index.d.ts +30 -0
  8. package/dist/cli/index.js +3331 -0
  9. package/dist/cli/index.js.map +1 -0
  10. package/dist/cli/migrate.cjs +3380 -0
  11. package/dist/cli/migrate.cjs.map +1 -0
  12. package/dist/cli/migrate.d.cts +1 -0
  13. package/dist/cli/migrate.d.ts +1 -0
  14. package/dist/cli/migrate.js +3353 -0
  15. package/dist/cli/migrate.js.map +1 -0
  16. package/dist/cli/utils/index.cjs +540 -0
  17. package/dist/cli/utils/index.cjs.map +1 -0
  18. package/dist/cli/utils/index.d.cts +232 -0
  19. package/dist/cli/utils/index.d.ts +232 -0
  20. package/dist/cli/utils/index.js +487 -0
  21. package/dist/cli/utils/index.js.map +1 -0
  22. package/dist/enums.cjs +19 -0
  23. package/dist/enums.cjs.map +1 -0
  24. package/dist/enums.d.cts +6 -0
  25. package/dist/enums.d.ts +6 -0
  26. package/dist/enums.js +17 -0
  27. package/dist/enums.js.map +1 -0
  28. package/dist/index.cjs +4900 -0
  29. package/dist/index.cjs.map +1 -0
  30. package/dist/index.d.cts +18 -0
  31. package/dist/index.d.ts +18 -0
  32. package/dist/index.js +4726 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/migration/analyzer.cjs +1267 -0
  35. package/dist/migration/analyzer.cjs.map +1 -0
  36. package/dist/migration/analyzer.d.cts +186 -0
  37. package/dist/migration/analyzer.d.ts +186 -0
  38. package/dist/migration/analyzer.js +1232 -0
  39. package/dist/migration/analyzer.js.map +1 -0
  40. package/dist/migration/diff.cjs +557 -0
  41. package/dist/migration/diff.cjs.map +1 -0
  42. package/dist/migration/diff.d.cts +291 -0
  43. package/dist/migration/diff.d.ts +291 -0
  44. package/dist/migration/diff.js +534 -0
  45. package/dist/migration/diff.js.map +1 -0
  46. package/dist/migration/generator.cjs +778 -0
  47. package/dist/migration/generator.cjs.map +1 -0
  48. package/dist/migration/generator.d.cts +225 -0
  49. package/dist/migration/generator.d.ts +225 -0
  50. package/dist/migration/generator.js +737 -0
  51. package/dist/migration/generator.js.map +1 -0
  52. package/dist/migration/index.cjs +3390 -0
  53. package/dist/migration/index.cjs.map +1 -0
  54. package/dist/migration/index.d.cts +103 -0
  55. package/dist/migration/index.d.ts +103 -0
  56. package/dist/migration/index.js +3265 -0
  57. package/dist/migration/index.js.map +1 -0
  58. package/dist/migration/snapshot.cjs +609 -0
  59. package/dist/migration/snapshot.cjs.map +1 -0
  60. package/dist/migration/snapshot.d.cts +167 -0
  61. package/dist/migration/snapshot.d.ts +167 -0
  62. package/dist/migration/snapshot.js +575 -0
  63. package/dist/migration/snapshot.js.map +1 -0
  64. package/dist/migration/utils/index.cjs +672 -0
  65. package/dist/migration/utils/index.cjs.map +1 -0
  66. package/dist/migration/utils/index.d.cts +207 -0
  67. package/dist/migration/utils/index.d.ts +207 -0
  68. package/dist/migration/utils/index.js +641 -0
  69. package/dist/migration/utils/index.js.map +1 -0
  70. package/dist/mutator.cjs +427 -0
  71. package/dist/mutator.cjs.map +1 -0
  72. package/dist/mutator.d.cts +190 -0
  73. package/dist/mutator.d.ts +190 -0
  74. package/dist/mutator.js +425 -0
  75. package/dist/mutator.js.map +1 -0
  76. package/dist/permissions-ZHafVSIx.d.cts +71 -0
  77. package/dist/permissions-ZHafVSIx.d.ts +71 -0
  78. package/dist/schema.cjs +430 -0
  79. package/dist/schema.cjs.map +1 -0
  80. package/dist/schema.d.cts +316 -0
  81. package/dist/schema.d.ts +316 -0
  82. package/dist/schema.js +396 -0
  83. package/dist/schema.js.map +1 -0
  84. package/dist/types-BbTgmg6H.d.cts +91 -0
  85. package/dist/types-z1Dkjg8m.d.ts +91 -0
  86. package/dist/types.cjs +4 -0
  87. package/dist/types.cjs.map +1 -0
  88. package/dist/types.d.cts +14 -0
  89. package/dist/types.d.ts +14 -0
  90. package/dist/types.js +3 -0
  91. package/dist/types.js.map +1 -0
  92. package/dist/user-jS1aYoeD.d.cts +123 -0
  93. package/dist/user-jS1aYoeD.d.ts +123 -0
  94. package/package.json +165 -0
@@ -0,0 +1,3380 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var chalk = require('chalk');
5
+ var commander = require('commander');
6
+ var path4 = require('path');
7
+ var fs4 = require('fs');
8
+ var zod = require('zod');
9
+ var ora = require('ora');
10
+
11
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
+
13
+ function _interopNamespace(e) {
14
+ if (e && e.__esModule) return e;
15
+ var n = Object.create(null);
16
+ if (e) {
17
+ Object.keys(e).forEach(function (k) {
18
+ if (k !== 'default') {
19
+ var d = Object.getOwnPropertyDescriptor(e, k);
20
+ Object.defineProperty(n, k, d.get ? d : {
21
+ enumerable: true,
22
+ get: function () { return e[k]; }
23
+ });
24
+ }
25
+ });
26
+ }
27
+ n.default = e;
28
+ return Object.freeze(n);
29
+ }
30
+
31
+ var chalk__default = /*#__PURE__*/_interopDefault(chalk);
32
+ var path4__namespace = /*#__PURE__*/_interopNamespace(path4);
33
+ var fs4__namespace = /*#__PURE__*/_interopNamespace(fs4);
34
+ var ora__default = /*#__PURE__*/_interopDefault(ora);
35
+
36
+ // src/migration/errors.ts
37
+ var MigrationError = class _MigrationError extends Error {
38
+ constructor(message) {
39
+ super(message);
40
+ this.name = "MigrationError";
41
+ Object.setPrototypeOf(this, _MigrationError.prototype);
42
+ }
43
+ };
44
+ var SchemaParsingError = class _SchemaParsingError extends MigrationError {
45
+ filePath;
46
+ originalError;
47
+ constructor(message, filePath, originalError) {
48
+ super(message);
49
+ this.name = "SchemaParsingError";
50
+ this.filePath = filePath;
51
+ this.originalError = originalError;
52
+ Object.setPrototypeOf(this, _SchemaParsingError.prototype);
53
+ }
54
+ /**
55
+ * Creates a formatted error message with file path and original error details
56
+ */
57
+ getDetailedMessage() {
58
+ const parts = [this.message];
59
+ if (this.filePath) {
60
+ parts.push(`
61
+ File: ${this.filePath}`);
62
+ }
63
+ if (this.originalError) {
64
+ parts.push(`
65
+ Cause: ${this.originalError.message}`);
66
+ }
67
+ return parts.join("");
68
+ }
69
+ };
70
+ var SnapshotError = class _SnapshotError extends MigrationError {
71
+ snapshotPath;
72
+ operation;
73
+ originalError;
74
+ constructor(message, snapshotPath, operation, originalError) {
75
+ super(message);
76
+ this.name = "SnapshotError";
77
+ this.snapshotPath = snapshotPath;
78
+ this.operation = operation;
79
+ this.originalError = originalError;
80
+ Object.setPrototypeOf(this, _SnapshotError.prototype);
81
+ }
82
+ /**
83
+ * Creates a formatted error message with snapshot path and operation details
84
+ */
85
+ getDetailedMessage() {
86
+ const parts = [this.message];
87
+ if (this.operation) {
88
+ parts.push(`
89
+ Operation: ${this.operation}`);
90
+ }
91
+ if (this.snapshotPath) {
92
+ parts.push(`
93
+ Snapshot: ${this.snapshotPath}`);
94
+ }
95
+ if (this.originalError) {
96
+ parts.push(`
97
+ Cause: ${this.originalError.message}`);
98
+ }
99
+ return parts.join("");
100
+ }
101
+ };
102
+ var MigrationGenerationError = class _MigrationGenerationError extends MigrationError {
103
+ migrationPath;
104
+ originalError;
105
+ constructor(message, migrationPath, originalError) {
106
+ super(message);
107
+ this.name = "MigrationGenerationError";
108
+ this.migrationPath = migrationPath;
109
+ this.originalError = originalError;
110
+ Object.setPrototypeOf(this, _MigrationGenerationError.prototype);
111
+ }
112
+ /**
113
+ * Creates a formatted error message with migration path and original error details
114
+ */
115
+ getDetailedMessage() {
116
+ const parts = [this.message];
117
+ if (this.migrationPath) {
118
+ parts.push(`
119
+ Migration: ${this.migrationPath}`);
120
+ }
121
+ if (this.originalError) {
122
+ parts.push(`
123
+ Cause: ${this.originalError.message}`);
124
+ }
125
+ return parts.join("");
126
+ }
127
+ };
128
+ var FileSystemError = class _FileSystemError extends MigrationError {
129
+ path;
130
+ operation;
131
+ code;
132
+ originalError;
133
+ constructor(message, path6, operation, code, originalError) {
134
+ super(message);
135
+ this.name = "FileSystemError";
136
+ this.path = path6;
137
+ this.operation = operation;
138
+ this.code = code;
139
+ this.originalError = originalError;
140
+ Object.setPrototypeOf(this, _FileSystemError.prototype);
141
+ }
142
+ /**
143
+ * Creates a formatted error message with path, operation, and error code details
144
+ */
145
+ getDetailedMessage() {
146
+ const parts = [this.message];
147
+ if (this.operation) {
148
+ parts.push(`
149
+ Operation: ${this.operation}`);
150
+ }
151
+ if (this.path) {
152
+ parts.push(`
153
+ Path: ${this.path}`);
154
+ }
155
+ if (this.code) {
156
+ parts.push(`
157
+ Error Code: ${this.code}`);
158
+ }
159
+ if (this.originalError) {
160
+ parts.push(`
161
+ Cause: ${this.originalError.message}`);
162
+ }
163
+ return parts.join("");
164
+ }
165
+ };
166
+ var ConfigurationError = class _ConfigurationError extends MigrationError {
167
+ configPath;
168
+ invalidFields;
169
+ originalError;
170
+ constructor(message, configPath, invalidFields, originalError) {
171
+ super(message);
172
+ this.name = "ConfigurationError";
173
+ this.configPath = configPath;
174
+ this.invalidFields = invalidFields;
175
+ this.originalError = originalError;
176
+ Object.setPrototypeOf(this, _ConfigurationError.prototype);
177
+ }
178
+ /**
179
+ * Creates a formatted error message with configuration details
180
+ */
181
+ getDetailedMessage() {
182
+ const parts = [this.message];
183
+ if (this.configPath) {
184
+ parts.push(`
185
+ Configuration File: ${this.configPath}`);
186
+ }
187
+ if (this.invalidFields && this.invalidFields.length > 0) {
188
+ parts.push(`
189
+ Invalid Fields: ${this.invalidFields.join(", ")}`);
190
+ }
191
+ if (this.originalError) {
192
+ parts.push(`
193
+ Cause: ${this.originalError.message}`);
194
+ }
195
+ return parts.join("");
196
+ }
197
+ };
198
+
199
+ // src/schema/permission-templates.ts
200
+ var PermissionTemplates = {
201
+ /**
202
+ * Public access - anyone can perform all operations
203
+ */
204
+ public: () => ({
205
+ listRule: "",
206
+ viewRule: "",
207
+ createRule: "",
208
+ updateRule: "",
209
+ deleteRule: ""
210
+ }),
211
+ /**
212
+ * Authenticated users only - requires valid authentication for all operations
213
+ */
214
+ authenticated: () => ({
215
+ listRule: '@request.auth.id != ""',
216
+ viewRule: '@request.auth.id != ""',
217
+ createRule: '@request.auth.id != ""',
218
+ updateRule: '@request.auth.id != ""',
219
+ deleteRule: '@request.auth.id != ""'
220
+ }),
221
+ /**
222
+ * Owner-only access - users can only manage their own records
223
+ * @param ownerField - Name of the relation field pointing to user (default: 'User')
224
+ */
225
+ ownerOnly: (ownerField = "User") => ({
226
+ listRule: `@request.auth.id != "" && ${ownerField} = @request.auth.id`,
227
+ viewRule: `@request.auth.id != "" && ${ownerField} = @request.auth.id`,
228
+ createRule: '@request.auth.id != ""',
229
+ updateRule: `@request.auth.id != "" && ${ownerField} = @request.auth.id`,
230
+ deleteRule: `@request.auth.id != "" && ${ownerField} = @request.auth.id`
231
+ }),
232
+ /**
233
+ * Admin/superuser only access
234
+ * Assumes a 'role' field exists with 'admin' value
235
+ * @param roleField - Name of the role field (default: 'role')
236
+ */
237
+ adminOnly: (roleField = "role") => ({
238
+ listRule: `@request.auth.id != "" && @request.auth.${roleField} = "admin"`,
239
+ viewRule: `@request.auth.id != "" && @request.auth.${roleField} = "admin"`,
240
+ createRule: `@request.auth.id != "" && @request.auth.${roleField} = "admin"`,
241
+ updateRule: `@request.auth.id != "" && @request.auth.${roleField} = "admin"`,
242
+ deleteRule: `@request.auth.id != "" && @request.auth.${roleField} = "admin"`
243
+ }),
244
+ /**
245
+ * Public read, authenticated write
246
+ * Anyone can list/view, but only authenticated users can create/update/delete
247
+ */
248
+ readPublic: () => ({
249
+ listRule: "",
250
+ viewRule: "",
251
+ createRule: '@request.auth.id != ""',
252
+ updateRule: '@request.auth.id != ""',
253
+ deleteRule: '@request.auth.id != ""'
254
+ }),
255
+ /**
256
+ * Locked access - only superusers can perform operations
257
+ * All rules are set to null (locked)
258
+ */
259
+ locked: () => ({
260
+ listRule: null,
261
+ viewRule: null,
262
+ createRule: null,
263
+ updateRule: null,
264
+ deleteRule: null
265
+ }),
266
+ /**
267
+ * Read-only authenticated - authenticated users can read, no write access
268
+ */
269
+ readOnlyAuthenticated: () => ({
270
+ listRule: '@request.auth.id != ""',
271
+ viewRule: '@request.auth.id != ""',
272
+ createRule: null,
273
+ updateRule: null,
274
+ deleteRule: null
275
+ })
276
+ };
277
+ function resolveTemplate(config) {
278
+ let baseRules;
279
+ switch (config.template) {
280
+ case "public":
281
+ baseRules = PermissionTemplates.public();
282
+ break;
283
+ case "authenticated":
284
+ baseRules = PermissionTemplates.authenticated();
285
+ break;
286
+ case "owner-only":
287
+ baseRules = PermissionTemplates.ownerOnly(config.ownerField);
288
+ break;
289
+ case "admin-only":
290
+ baseRules = PermissionTemplates.adminOnly(config.roleField);
291
+ break;
292
+ case "read-public":
293
+ baseRules = PermissionTemplates.readPublic();
294
+ break;
295
+ case "custom":
296
+ baseRules = {};
297
+ break;
298
+ default: {
299
+ const _exhaustive = config.template;
300
+ throw new Error(`Unknown template type: ${_exhaustive}`);
301
+ }
302
+ }
303
+ return {
304
+ ...baseRules,
305
+ ...config.customRules
306
+ };
307
+ }
308
+
309
+ // src/migration/rule-validator.ts
310
+ var RuleValidator = class {
311
+ fields;
312
+ collectionName;
313
+ isAuthCollection;
314
+ constructor(collectionName, fields, isAuthCollection2 = false) {
315
+ this.collectionName = collectionName;
316
+ this.fields = new Map(fields.map((f) => [f.name, f]));
317
+ this.isAuthCollection = isAuthCollection2;
318
+ this.addSystemFields();
319
+ }
320
+ /**
321
+ * Add system fields that are always available in PocketBase collections
322
+ * These fields are automatically added by PocketBase and can be referenced in rules
323
+ */
324
+ addSystemFields() {
325
+ const systemFields = [
326
+ { name: "id", type: "text", required: true, options: {} },
327
+ { name: "created", type: "date", required: true, options: {} },
328
+ { name: "updated", type: "date", required: true, options: {} },
329
+ { name: "collectionId", type: "text", required: true, options: {} },
330
+ { name: "collectionName", type: "text", required: true, options: {} }
331
+ ];
332
+ if (this.isAuthCollection) {
333
+ systemFields.push(
334
+ { name: "email", type: "email", required: true, options: {} },
335
+ { name: "emailVisibility", type: "bool", required: false, options: {} },
336
+ { name: "verified", type: "bool", required: false, options: {} },
337
+ { name: "tokenKey", type: "text", required: true, options: {} },
338
+ { name: "password", type: "text", required: true, options: {} }
339
+ );
340
+ }
341
+ for (const field of systemFields) {
342
+ if (!this.fields.has(field.name)) {
343
+ this.fields.set(field.name, field);
344
+ }
345
+ }
346
+ }
347
+ /**
348
+ * Validate a rule expression
349
+ *
350
+ * @param ruleType - The type of rule being validated
351
+ * @param expression - The rule expression to validate
352
+ * @returns Validation result with errors, warnings, and field references
353
+ */
354
+ validate(ruleType, expression) {
355
+ const result = {
356
+ valid: true,
357
+ errors: [],
358
+ warnings: [],
359
+ fieldReferences: []
360
+ };
361
+ if (expression === null) {
362
+ return result;
363
+ }
364
+ if (expression === "") {
365
+ result.warnings.push(`${ruleType} is public - anyone can perform this operation`);
366
+ return result;
367
+ }
368
+ if (ruleType === "manageRule" && !this.isAuthCollection) {
369
+ result.valid = false;
370
+ result.errors.push("manageRule is only valid for auth collections");
371
+ return result;
372
+ }
373
+ const fieldRefs = this.extractFieldReferences(expression);
374
+ result.fieldReferences = fieldRefs;
375
+ for (const fieldRef of fieldRefs) {
376
+ this.validateFieldReference(fieldRef, result);
377
+ }
378
+ this.validateRequestReferences(expression, result);
379
+ this.validateSyntax(expression, result);
380
+ return result;
381
+ }
382
+ /**
383
+ * Extract field references from expression
384
+ *
385
+ * Matches field names that are not @request references.
386
+ * Handles dot notation for relations: user.email, post.author.name
387
+ *
388
+ * @param expression - The rule expression
389
+ * @returns Array of unique field references
390
+ */
391
+ extractFieldReferences(expression) {
392
+ const refs = [];
393
+ let cleaned = expression.replace(/"[^"]*"/g, '""').replace(/'[^']*'/g, "''");
394
+ cleaned = cleaned.replace(/@request\.[a-zA-Z_][a-zA-Z0-9_.]*/g, "");
395
+ const fieldPattern = /(?:^|[^@\w])([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)(?=[^a-zA-Z0-9_.]|$)/g;
396
+ let match;
397
+ while ((match = fieldPattern.exec(cleaned)) !== null) {
398
+ const ref = match[1];
399
+ if (!this.isKeyword(ref)) {
400
+ refs.push(ref);
401
+ }
402
+ }
403
+ return [...new Set(refs)];
404
+ }
405
+ /**
406
+ * Check if a word is a PocketBase keyword
407
+ *
408
+ * @param word - The word to check
409
+ * @returns True if the word is a keyword
410
+ */
411
+ isKeyword(word) {
412
+ const keywords = ["true", "false", "null", "AND", "OR", "NOT", "LIKE", "IN"];
413
+ return keywords.includes(word.toUpperCase());
414
+ }
415
+ /**
416
+ * Validate a field reference exists in schema
417
+ *
418
+ * Checks if the root field exists and validates relation chains.
419
+ * For nested references, warns about potential issues since we can't
420
+ * validate across collections without loading related schemas.
421
+ *
422
+ * @param fieldRef - The field reference to validate (e.g., "user" or "user.email")
423
+ * @param result - The validation result to update
424
+ */
425
+ validateFieldReference(fieldRef, result) {
426
+ const parts = fieldRef.split(".");
427
+ const rootField = parts[0];
428
+ if (!this.fields.has(rootField)) {
429
+ result.errors.push(`Field '${rootField}' does not exist in collection '${this.collectionName}'`);
430
+ result.valid = false;
431
+ return;
432
+ }
433
+ if (parts.length > 1) {
434
+ const field = this.fields.get(rootField);
435
+ if (field.type !== "relation") {
436
+ result.errors.push(`Field '${rootField}' is not a relation field, cannot access nested property '${parts[1]}'`);
437
+ result.valid = false;
438
+ } else {
439
+ result.warnings.push(
440
+ `Nested field reference '${fieldRef}' - ensure target collection has field '${parts.slice(1).join(".")}'`
441
+ );
442
+ }
443
+ }
444
+ }
445
+ /**
446
+ * Validate @request references
447
+ *
448
+ * Checks that @request references follow valid PocketBase patterns:
449
+ * - @request.auth.* - authenticated user data
450
+ * - @request.body.* - request body fields
451
+ * - @request.query.* - query parameters
452
+ * - @request.headers.* - request headers
453
+ * - @request.method - HTTP method
454
+ * - @request.context - execution context
455
+ *
456
+ * @param expression - The rule expression
457
+ * @param result - The validation result to update
458
+ */
459
+ validateRequestReferences(expression, result) {
460
+ const requestRefs = expression.match(/@request\.[a-zA-Z_][a-zA-Z0-9_.]*/g) || [];
461
+ for (const ref of requestRefs) {
462
+ const isValid = ref.startsWith("@request.auth.") || ref === "@request.method" || ref === "@request.context" || ref.startsWith("@request.body.") || ref.startsWith("@request.query.") || ref.startsWith("@request.headers.");
463
+ if (!isValid) {
464
+ result.errors.push(`Invalid @request reference: '${ref}'`);
465
+ result.valid = false;
466
+ }
467
+ }
468
+ }
469
+ /**
470
+ * Validate basic syntax patterns
471
+ *
472
+ * Checks for:
473
+ * - Balanced parentheses
474
+ * - Common operator mistakes (== instead of =)
475
+ *
476
+ * @param expression - The rule expression
477
+ * @param result - The validation result to update
478
+ */
479
+ validateSyntax(expression, result) {
480
+ let parenCount = 0;
481
+ for (const char of expression) {
482
+ if (char === "(") parenCount++;
483
+ if (char === ")") parenCount--;
484
+ if (parenCount < 0) {
485
+ result.errors.push("Unbalanced parentheses in expression");
486
+ result.valid = false;
487
+ return;
488
+ }
489
+ }
490
+ if (parenCount !== 0) {
491
+ result.errors.push("Unbalanced parentheses in expression");
492
+ result.valid = false;
493
+ }
494
+ if (expression.includes("==")) {
495
+ result.warnings.push("Use '=' instead of '==' for equality comparison in PocketBase rules");
496
+ }
497
+ }
498
+ };
499
+
500
+ // src/migration/permission-analyzer.ts
501
+ var PermissionAnalyzer = class {
502
+ /**
503
+ * Extract permission metadata from Zod schema description
504
+ *
505
+ * Zod schemas can have permission metadata attached via the describe() method.
506
+ * This method parses the description and extracts the permission configuration.
507
+ *
508
+ * @param schemaDescription - The Zod schema description string
509
+ * @returns Permission schema if found, null otherwise
510
+ *
511
+ * @example
512
+ * ```typescript
513
+ * const analyzer = new PermissionAnalyzer();
514
+ * const permissions = analyzer.extractPermissions(schema.description);
515
+ * ```
516
+ */
517
+ extractPermissions(schemaDescription) {
518
+ if (!schemaDescription) {
519
+ return null;
520
+ }
521
+ try {
522
+ const metadata = JSON.parse(schemaDescription);
523
+ if (metadata.permissions) {
524
+ return metadata.permissions;
525
+ }
526
+ } catch {
527
+ return null;
528
+ }
529
+ return null;
530
+ }
531
+ /**
532
+ * Resolve template configuration to concrete rules
533
+ *
534
+ * Takes either a template configuration or a direct permission schema
535
+ * and returns a fully resolved permission schema with all rules defined.
536
+ *
537
+ * If the input is already a permission schema (has rule properties),
538
+ * it's returned as-is. Otherwise, the template is resolved using the
539
+ * template resolver.
540
+ *
541
+ * @param config - Template configuration or direct permission schema
542
+ * @returns Resolved permission schema
543
+ *
544
+ * @example
545
+ * ```typescript
546
+ * const analyzer = new PermissionAnalyzer();
547
+ *
548
+ * // Resolve from template
549
+ * const permissions = analyzer.resolvePermissions({
550
+ * template: 'owner-only',
551
+ * ownerField: 'User'
552
+ * });
553
+ *
554
+ * // Or pass direct schema
555
+ * const permissions = analyzer.resolvePermissions({
556
+ * listRule: '@request.auth.id != ""',
557
+ * viewRule: '@request.auth.id != ""'
558
+ * });
559
+ * ```
560
+ */
561
+ resolvePermissions(config) {
562
+ if ("listRule" in config || "viewRule" in config || "createRule" in config || "updateRule" in config || "deleteRule" in config || "manageRule" in config) {
563
+ return config;
564
+ }
565
+ return resolveTemplate(config);
566
+ }
567
+ /**
568
+ * Validate all rules in a permission schema
569
+ *
570
+ * Validates each rule in the permission schema against the collection's
571
+ * field definitions. Returns a map of validation results keyed by rule type.
572
+ *
573
+ * Only validates rules that are defined (not undefined). Undefined rules
574
+ * are treated as null (locked) by default.
575
+ *
576
+ * @param collectionName - Name of the collection being validated
577
+ * @param permissions - Permission schema to validate
578
+ * @param fields - Collection field definitions
579
+ * @param isAuthCollection - Whether this is an auth collection (allows manageRule)
580
+ * @returns Map of validation results by rule type
581
+ *
582
+ * @example
583
+ * ```typescript
584
+ * const analyzer = new PermissionAnalyzer();
585
+ * const results = analyzer.validatePermissions(
586
+ * 'posts',
587
+ * { listRule: '@request.auth.id != ""', viewRule: 'author = @request.auth.id' },
588
+ * fields,
589
+ * false
590
+ * );
591
+ *
592
+ * for (const [ruleType, result] of results) {
593
+ * if (!result.valid) {
594
+ * console.error(`${ruleType} validation failed:`, result.errors);
595
+ * }
596
+ * }
597
+ * ```
598
+ */
599
+ validatePermissions(collectionName, permissions, fields, isAuthCollection2 = false) {
600
+ const validator = new RuleValidator(collectionName, fields, isAuthCollection2);
601
+ const results = /* @__PURE__ */ new Map();
602
+ const ruleTypes = ["listRule", "viewRule", "createRule", "updateRule", "deleteRule"];
603
+ if (isAuthCollection2) {
604
+ ruleTypes.push("manageRule");
605
+ }
606
+ for (const ruleType of ruleTypes) {
607
+ const expression = permissions[ruleType];
608
+ if (expression !== void 0) {
609
+ results.set(ruleType, validator.validate(ruleType, expression));
610
+ }
611
+ }
612
+ return results;
613
+ }
614
+ /**
615
+ * Merge permissions with defaults
616
+ *
617
+ * Ensures all rule types have a defined value. Undefined rules are set
618
+ * to null (locked to superusers only), which is the PocketBase default.
619
+ *
620
+ * This is useful when generating migrations to ensure all rules are
621
+ * explicitly set in the collection configuration.
622
+ *
623
+ * @param permissions - Permission schema (may have undefined rules)
624
+ * @returns Permission schema with all rules defined (null if not specified)
625
+ *
626
+ * @example
627
+ * ```typescript
628
+ * const analyzer = new PermissionAnalyzer();
629
+ * const merged = analyzer.mergeWithDefaults({
630
+ * listRule: '@request.auth.id != ""'
631
+ * // other rules undefined
632
+ * });
633
+ *
634
+ * // Result:
635
+ * // {
636
+ * // listRule: '@request.auth.id != ""',
637
+ * // viewRule: null,
638
+ * // createRule: null,
639
+ * // updateRule: null,
640
+ * // deleteRule: null,
641
+ * // manageRule: null
642
+ * // }
643
+ * ```
644
+ */
645
+ mergeWithDefaults(permissions) {
646
+ return {
647
+ listRule: permissions.listRule ?? null,
648
+ viewRule: permissions.viewRule ?? null,
649
+ createRule: permissions.createRule ?? null,
650
+ updateRule: permissions.updateRule ?? null,
651
+ deleteRule: permissions.deleteRule ?? null,
652
+ manageRule: permissions.manageRule ?? null
653
+ };
654
+ }
655
+ };
656
+
657
+ // src/migration/utils/pluralize.ts
658
+ var SPECIAL_CASES = {
659
+ // Common irregular plurals
660
+ person: "people",
661
+ Person: "People",
662
+ child: "children",
663
+ Child: "Children",
664
+ man: "men",
665
+ Man: "Men",
666
+ woman: "women",
667
+ Woman: "Women",
668
+ tooth: "teeth",
669
+ Tooth: "Teeth",
670
+ foot: "feet",
671
+ Foot: "Feet",
672
+ mouse: "mice",
673
+ Mouse: "Mice",
674
+ goose: "geese",
675
+ Goose: "Geese",
676
+ // Words ending in -y
677
+ category: "categories",
678
+ Category: "Categories",
679
+ company: "companies",
680
+ Company: "Companies",
681
+ city: "cities",
682
+ City: "Cities",
683
+ country: "countries",
684
+ Country: "Countries",
685
+ story: "stories",
686
+ Story: "Stories",
687
+ party: "parties",
688
+ Party: "Parties",
689
+ family: "families",
690
+ Family: "Families",
691
+ activity: "activities",
692
+ Activity: "Activities",
693
+ priority: "priorities",
694
+ Priority: "Priorities",
695
+ // Words ending in -f or -fe
696
+ life: "lives",
697
+ Life: "Lives",
698
+ wife: "wives",
699
+ Wife: "Wives",
700
+ knife: "knives",
701
+ Knife: "Knives",
702
+ leaf: "leaves",
703
+ Leaf: "Leaves",
704
+ shelf: "shelves",
705
+ Shelf: "Shelves",
706
+ half: "halves",
707
+ Half: "Halves",
708
+ // Words ending in -is
709
+ analysis: "analyses",
710
+ Analysis: "Analyses",
711
+ basis: "bases",
712
+ Basis: "Bases",
713
+ crisis: "crises",
714
+ Crisis: "Crises",
715
+ thesis: "theses",
716
+ Thesis: "Theses",
717
+ // Words ending in -us
718
+ cactus: "cacti",
719
+ Cactus: "Cacti",
720
+ focus: "foci",
721
+ Focus: "Foci",
722
+ fungus: "fungi",
723
+ Fungus: "Fungi",
724
+ nucleus: "nuclei",
725
+ Nucleus: "Nuclei",
726
+ radius: "radii",
727
+ Radius: "Radii",
728
+ // Words ending in -on
729
+ phenomenon: "phenomena",
730
+ Phenomenon: "Phenomena",
731
+ criterion: "criteria",
732
+ Criterion: "Criteria",
733
+ // Words ending in -um
734
+ datum: "data",
735
+ Datum: "Data",
736
+ medium: "media",
737
+ Medium: "Media",
738
+ curriculum: "curricula",
739
+ Curriculum: "Curricula",
740
+ // Unchanged plurals
741
+ sheep: "sheep",
742
+ Sheep: "Sheep",
743
+ deer: "deer",
744
+ Deer: "Deer",
745
+ fish: "fish",
746
+ Fish: "Fish",
747
+ species: "species",
748
+ Species: "Species",
749
+ series: "series",
750
+ Series: "Series"
751
+ };
752
+ function pluralize(singular) {
753
+ if (SPECIAL_CASES[singular]) {
754
+ return SPECIAL_CASES[singular];
755
+ }
756
+ if (singular.length > 3 && singular.endsWith("s") && !singular.endsWith("ss")) {
757
+ return singular;
758
+ }
759
+ const lowerSingular = singular.toLowerCase();
760
+ let plural;
761
+ if (/(?:s|ss|sh|ch|x|z)$/.test(lowerSingular)) {
762
+ plural = singular + "es";
763
+ } else if (/[^aeiou]y$/.test(lowerSingular)) {
764
+ plural = singular.slice(0, -1) + "ies";
765
+ } else if (/[^aeiou]o$/.test(lowerSingular)) {
766
+ plural = singular + "es";
767
+ } else if (/fe?$/.test(lowerSingular)) {
768
+ if (lowerSingular.endsWith("fe")) {
769
+ plural = singular.slice(0, -2) + "ves";
770
+ } else {
771
+ plural = singular.slice(0, -1) + "ves";
772
+ }
773
+ } else {
774
+ plural = singular + "s";
775
+ }
776
+ return plural;
777
+ }
778
+ function toCollectionName(entityName) {
779
+ return pluralize(entityName);
780
+ }
781
+ function isSingleRelationField(fieldName, zodType) {
782
+ let unwrappedType = zodType;
783
+ if (zodType instanceof zod.z.ZodOptional) {
784
+ unwrappedType = zodType._def.innerType;
785
+ }
786
+ if (unwrappedType instanceof zod.z.ZodNullable) {
787
+ unwrappedType = unwrappedType._def.innerType;
788
+ }
789
+ if (unwrappedType instanceof zod.z.ZodDefault) {
790
+ unwrappedType = unwrappedType._def.innerType;
791
+ }
792
+ if (!(unwrappedType instanceof zod.z.ZodString)) {
793
+ return false;
794
+ }
795
+ const startsWithUppercase = /^[A-Z]/.test(fieldName);
796
+ const commonStringFields = ["Title", "Name", "Description", "Content", "Summary", "Status", "Type"];
797
+ const isCommonField = commonStringFields.includes(fieldName);
798
+ return startsWithUppercase && !isCommonField;
799
+ }
800
+ function isMultipleRelationField(fieldName, zodType) {
801
+ let unwrappedType = zodType;
802
+ if (zodType instanceof zod.z.ZodOptional) {
803
+ unwrappedType = zodType._def.innerType;
804
+ }
805
+ if (unwrappedType instanceof zod.z.ZodNullable) {
806
+ unwrappedType = unwrappedType._def.innerType;
807
+ }
808
+ if (unwrappedType instanceof zod.z.ZodDefault) {
809
+ unwrappedType = unwrappedType._def.innerType;
810
+ }
811
+ if (!(unwrappedType instanceof zod.z.ZodArray)) {
812
+ return false;
813
+ }
814
+ const elementType = unwrappedType._def.type;
815
+ if (!(elementType instanceof zod.z.ZodString)) {
816
+ return false;
817
+ }
818
+ const hasUppercase = /[A-Z]/.test(fieldName);
819
+ return hasUppercase;
820
+ }
821
+ function resolveTargetCollection(fieldName) {
822
+ const matches = fieldName.match(/[A-Z][a-z]+/g);
823
+ if (!matches || matches.length === 0) {
824
+ return pluralize(fieldName);
825
+ }
826
+ const entityName = matches[matches.length - 1];
827
+ return pluralize(entityName);
828
+ }
829
+ function isRelationField(fieldName, zodType) {
830
+ return isSingleRelationField(fieldName, zodType) || isMultipleRelationField(fieldName, zodType);
831
+ }
832
+ function getMaxSelect(fieldName, zodType) {
833
+ if (isSingleRelationField(fieldName, zodType)) {
834
+ return 1;
835
+ }
836
+ if (isMultipleRelationField(fieldName, zodType)) {
837
+ let unwrappedType = zodType;
838
+ if (zodType instanceof zod.z.ZodOptional) {
839
+ unwrappedType = zodType._def.innerType;
840
+ }
841
+ if (unwrappedType instanceof zod.z.ZodNullable) {
842
+ unwrappedType = unwrappedType._def.innerType;
843
+ }
844
+ if (unwrappedType instanceof zod.z.ZodDefault) {
845
+ unwrappedType = unwrappedType._def.innerType;
846
+ }
847
+ if (unwrappedType instanceof zod.z.ZodArray) {
848
+ const arrayDef = unwrappedType._def;
849
+ if (arrayDef.maxLength) {
850
+ return arrayDef.maxLength.value;
851
+ }
852
+ return 999;
853
+ }
854
+ }
855
+ return 1;
856
+ }
857
+ function getMinSelect(fieldName, zodType) {
858
+ if (!isMultipleRelationField(fieldName, zodType)) {
859
+ return void 0;
860
+ }
861
+ let unwrappedType = zodType;
862
+ if (zodType instanceof zod.z.ZodOptional) {
863
+ unwrappedType = zodType._def.innerType;
864
+ }
865
+ if (unwrappedType instanceof zod.z.ZodNullable) {
866
+ unwrappedType = unwrappedType._def.innerType;
867
+ }
868
+ if (unwrappedType instanceof zod.z.ZodDefault) {
869
+ unwrappedType = unwrappedType._def.innerType;
870
+ }
871
+ if (unwrappedType instanceof zod.z.ZodArray) {
872
+ const arrayDef = unwrappedType._def;
873
+ if (arrayDef.minLength) {
874
+ return arrayDef.minLength.value;
875
+ }
876
+ }
877
+ return void 0;
878
+ }
879
+ function mapZodStringType(zodType) {
880
+ const checks = zodType._def.checks || [];
881
+ const hasEmail = checks.some((check) => check.kind === "email");
882
+ if (hasEmail) {
883
+ return "email";
884
+ }
885
+ const hasUrl = checks.some((check) => check.kind === "url");
886
+ if (hasUrl) {
887
+ return "url";
888
+ }
889
+ const hasDatetime = checks.some((check) => check.kind === "datetime");
890
+ if (hasDatetime) {
891
+ return "date";
892
+ }
893
+ return "text";
894
+ }
895
+ function mapZodNumberType(_zodType) {
896
+ return "number";
897
+ }
898
+ function mapZodBooleanType(_zodType) {
899
+ return "bool";
900
+ }
901
+ function mapZodEnumType(_zodType) {
902
+ return "select";
903
+ }
904
+ function mapZodArrayType(zodType, _fieldName) {
905
+ const elementType = zodType._def.type;
906
+ if (elementType instanceof zod.z.ZodType) {
907
+ const typeName = elementType._def.typeName;
908
+ if (typeName === "ZodType" && elementType._def?.innerType?.name === "File") {
909
+ return "file";
910
+ }
911
+ }
912
+ if (elementType._def?.typeName === "ZodType") {
913
+ const checks = elementType._def?.checks || [];
914
+ const isFileInstance = checks.some(
915
+ (check) => check.kind === "instanceof" || elementType._def?.innerType?.name === "File"
916
+ );
917
+ if (isFileInstance) {
918
+ return "file";
919
+ }
920
+ }
921
+ if (elementType instanceof zod.z.ZodString) {
922
+ return "relation";
923
+ }
924
+ return "json";
925
+ }
926
+ function mapZodDateType(_zodType) {
927
+ return "date";
928
+ }
929
+ function mapZodRecordType(_zodType) {
930
+ return "json";
931
+ }
932
+ function mapZodTypeToPocketBase(zodType, fieldName) {
933
+ let unwrappedType = zodType;
934
+ if (zodType instanceof zod.z.ZodOptional) {
935
+ unwrappedType = zodType._def.innerType;
936
+ }
937
+ if (unwrappedType instanceof zod.z.ZodNullable) {
938
+ unwrappedType = unwrappedType._def.innerType;
939
+ }
940
+ if (unwrappedType instanceof zod.z.ZodDefault) {
941
+ unwrappedType = unwrappedType._def.innerType;
942
+ }
943
+ if (unwrappedType._def?.typeName === "ZodEffects") {
944
+ const effect = unwrappedType._def?.effect;
945
+ if (effect?.type === "refinement") {
946
+ const fileFieldNames = ["avatar", "image", "file", "attachment", "photo", "picture", "document", "upload"];
947
+ if (fileFieldNames.some((name) => fieldName.toLowerCase().includes(name))) {
948
+ return "file";
949
+ }
950
+ }
951
+ }
952
+ if (unwrappedType._def?.typeName === "ZodType") {
953
+ const checks = unwrappedType._def?.checks || [];
954
+ const innerType = unwrappedType._def?.innerType;
955
+ if (innerType?.name === "File" || checks.some((check) => check.kind === "instanceof")) {
956
+ return "file";
957
+ }
958
+ }
959
+ if (unwrappedType instanceof zod.z.ZodString) {
960
+ return mapZodStringType(unwrappedType);
961
+ }
962
+ if (unwrappedType instanceof zod.z.ZodNumber) {
963
+ return mapZodNumberType();
964
+ }
965
+ if (unwrappedType instanceof zod.z.ZodBoolean) {
966
+ return mapZodBooleanType();
967
+ }
968
+ if (unwrappedType instanceof zod.z.ZodEnum) {
969
+ return mapZodEnumType();
970
+ }
971
+ if (unwrappedType instanceof zod.z.ZodArray) {
972
+ return mapZodArrayType(unwrappedType);
973
+ }
974
+ if (unwrappedType instanceof zod.z.ZodDate) {
975
+ return mapZodDateType();
976
+ }
977
+ if (unwrappedType instanceof zod.z.ZodRecord || unwrappedType instanceof zod.z.ZodObject) {
978
+ return mapZodRecordType();
979
+ }
980
+ return "text";
981
+ }
982
+ function extractFieldOptions(zodType) {
983
+ const options = {};
984
+ let unwrappedType = zodType;
985
+ if (zodType instanceof zod.z.ZodOptional) {
986
+ unwrappedType = zodType._def.innerType;
987
+ }
988
+ if (unwrappedType instanceof zod.z.ZodNullable) {
989
+ unwrappedType = unwrappedType._def.innerType;
990
+ }
991
+ if (unwrappedType instanceof zod.z.ZodDefault) {
992
+ unwrappedType = unwrappedType._def.innerType;
993
+ }
994
+ const checks = unwrappedType._def?.checks || [];
995
+ if (unwrappedType instanceof zod.z.ZodString) {
996
+ for (const check of checks) {
997
+ if (check.kind === "min") {
998
+ options.min = check.value;
999
+ }
1000
+ if (check.kind === "max") {
1001
+ options.max = check.value;
1002
+ }
1003
+ if (check.kind === "regex") {
1004
+ options.pattern = check.regex.source;
1005
+ }
1006
+ }
1007
+ }
1008
+ if (unwrappedType instanceof zod.z.ZodNumber) {
1009
+ for (const check of checks) {
1010
+ if (check.kind === "min") {
1011
+ options.min = check.value;
1012
+ }
1013
+ if (check.kind === "max") {
1014
+ options.max = check.value;
1015
+ }
1016
+ }
1017
+ }
1018
+ if (unwrappedType instanceof zod.z.ZodEnum) {
1019
+ options.values = unwrappedType._def.values;
1020
+ }
1021
+ if (unwrappedType instanceof zod.z.ZodArray) {
1022
+ const arrayChecks = unwrappedType._def?.checks || [];
1023
+ for (const check of arrayChecks) {
1024
+ if (check.kind === "min") {
1025
+ options.minSelect = check.value;
1026
+ }
1027
+ if (check.kind === "max") {
1028
+ options.maxSelect = check.value;
1029
+ }
1030
+ }
1031
+ }
1032
+ return options;
1033
+ }
1034
+ function isFieldRequired(zodType) {
1035
+ if (zodType instanceof zod.z.ZodOptional) {
1036
+ return false;
1037
+ }
1038
+ if (zodType instanceof zod.z.ZodDefault) {
1039
+ return false;
1040
+ }
1041
+ if (zodType instanceof zod.z.ZodNullable) {
1042
+ return false;
1043
+ }
1044
+ return true;
1045
+ }
1046
+
1047
+ // src/migration/analyzer.ts
1048
+ var DEFAULT_CONFIG = {
1049
+ workspaceRoot: process.cwd(),
1050
+ excludePatterns: [
1051
+ "base.ts",
1052
+ "index.ts",
1053
+ "permissions.ts",
1054
+ "permission-templates.ts",
1055
+ "base.js",
1056
+ "index.js",
1057
+ "permissions.js",
1058
+ "permission-templates.js"
1059
+ ],
1060
+ includeExtensions: [".ts", ".js"],
1061
+ schemaPatterns: ["Schema", "InputSchema"],
1062
+ useCompiledFiles: true
1063
+ };
1064
+ function mergeConfig(config) {
1065
+ return {
1066
+ ...DEFAULT_CONFIG,
1067
+ ...config,
1068
+ excludePatterns: config.excludePatterns || DEFAULT_CONFIG.excludePatterns,
1069
+ includeExtensions: config.includeExtensions || DEFAULT_CONFIG.includeExtensions,
1070
+ schemaPatterns: config.schemaPatterns || DEFAULT_CONFIG.schemaPatterns
1071
+ };
1072
+ }
1073
+ function resolveSchemaDir(config) {
1074
+ const workspaceRoot = config.workspaceRoot || process.cwd();
1075
+ if (path4__namespace.isAbsolute(config.schemaDir)) {
1076
+ return config.schemaDir;
1077
+ }
1078
+ return path4__namespace.join(workspaceRoot, config.schemaDir);
1079
+ }
1080
+ function discoverSchemaFiles(config) {
1081
+ const normalizedConfig = typeof config === "string" ? { schemaDir: config } : config;
1082
+ const mergedConfig = mergeConfig(normalizedConfig);
1083
+ const schemaDir = resolveSchemaDir(normalizedConfig);
1084
+ try {
1085
+ if (!fs4__namespace.existsSync(schemaDir)) {
1086
+ throw new FileSystemError(`Schema directory not found: ${schemaDir}`, schemaDir, "access", "ENOENT");
1087
+ }
1088
+ const files = fs4__namespace.readdirSync(schemaDir);
1089
+ const schemaFiles = files.filter((file) => {
1090
+ const hasValidExtension = mergedConfig.includeExtensions.some((ext) => file.endsWith(ext));
1091
+ if (!hasValidExtension) return false;
1092
+ const isExcluded = mergedConfig.excludePatterns.some((pattern) => {
1093
+ if (pattern.includes("*")) {
1094
+ const regex = new RegExp("^" + pattern.replace(/\*/g, ".*") + "$");
1095
+ return regex.test(file);
1096
+ }
1097
+ return file === pattern;
1098
+ });
1099
+ if (isExcluded) return false;
1100
+ return true;
1101
+ });
1102
+ return schemaFiles.map((file) => {
1103
+ const ext = mergedConfig.includeExtensions.find((ext2) => file.endsWith(ext2)) || ".ts";
1104
+ return path4__namespace.join(schemaDir, file.replace(new RegExp(`\\${ext}$`), ""));
1105
+ });
1106
+ } catch (error) {
1107
+ if (error instanceof FileSystemError) {
1108
+ throw error;
1109
+ }
1110
+ const fsError = error;
1111
+ if (fsError.code === "EACCES" || fsError.code === "EPERM") {
1112
+ throw new FileSystemError(
1113
+ `Permission denied reading schema directory: ${schemaDir}`,
1114
+ schemaDir,
1115
+ "read",
1116
+ fsError.code,
1117
+ error
1118
+ );
1119
+ }
1120
+ throw new FileSystemError(
1121
+ `Failed to read schema directory: ${schemaDir}`,
1122
+ schemaDir,
1123
+ "read",
1124
+ fsError.code,
1125
+ error
1126
+ );
1127
+ }
1128
+ }
1129
+ async function importSchemaModule(filePath, config) {
1130
+ try {
1131
+ let importPath = filePath;
1132
+ if (config?.pathTransformer) {
1133
+ importPath = config.pathTransformer(filePath);
1134
+ }
1135
+ if (!importPath.endsWith(".js")) {
1136
+ importPath = `${importPath}.js`;
1137
+ }
1138
+ const fileUrl = new URL(`file://${path4__namespace.resolve(importPath)}`);
1139
+ const module = await import(fileUrl.href);
1140
+ return module;
1141
+ } catch (error) {
1142
+ throw new SchemaParsingError(
1143
+ `Failed to import schema module. Make sure the schema files are compiled to JavaScript.`,
1144
+ filePath,
1145
+ error
1146
+ );
1147
+ }
1148
+ }
1149
+ function getCollectionNameFromFile(filePath) {
1150
+ const filename = path4__namespace.basename(filePath).replace(/\.(ts|js)$/, "");
1151
+ return toCollectionName(filename);
1152
+ }
1153
+ function extractSchemaDefinitions(module, patterns = ["Schema", "InputSchema"]) {
1154
+ const result = {};
1155
+ for (const [key, value] of Object.entries(module)) {
1156
+ if (value instanceof zod.z.ZodObject) {
1157
+ if (patterns.includes("InputSchema") && key.endsWith("InputSchema")) {
1158
+ result.inputSchema = value;
1159
+ } else if (patterns.includes("Schema") && key.endsWith("Schema") && !key.endsWith("InputSchema")) {
1160
+ result.schema = value;
1161
+ }
1162
+ }
1163
+ }
1164
+ return result;
1165
+ }
1166
+ function selectSchemaForCollection(schemas) {
1167
+ if (schemas.schema) {
1168
+ return schemas.schema;
1169
+ }
1170
+ if (schemas.inputSchema) {
1171
+ return schemas.inputSchema;
1172
+ }
1173
+ return null;
1174
+ }
1175
+ function extractFieldDefinitions(zodSchema, excludeFields) {
1176
+ const shape = zodSchema.shape;
1177
+ const fields = [];
1178
+ const baseFields = ["id", "collectionId", "collectionName", "created", "updated", "expand"];
1179
+ const defaultExcludeFields = ["thumbnailURL", "imageFiles"];
1180
+ const allExclusions = /* @__PURE__ */ new Set([...baseFields, ...defaultExcludeFields, ...[]]);
1181
+ for (const [fieldName, zodType] of Object.entries(shape)) {
1182
+ if (!allExclusions.has(fieldName)) {
1183
+ fields.push({ name: fieldName, zodType });
1184
+ }
1185
+ }
1186
+ return fields;
1187
+ }
1188
+ function isAuthCollection(fields) {
1189
+ const fieldNames = fields.map((f) => f.name.toLowerCase());
1190
+ const hasEmail = fieldNames.includes("email");
1191
+ const hasPassword = fieldNames.includes("password");
1192
+ return hasEmail && hasPassword;
1193
+ }
1194
+ function buildFieldDefinition(fieldName, zodType) {
1195
+ const fieldType = mapZodTypeToPocketBase(zodType, fieldName);
1196
+ const required = isFieldRequired(zodType);
1197
+ const options = extractFieldOptions(zodType);
1198
+ const fieldDef = {
1199
+ name: fieldName,
1200
+ type: fieldType,
1201
+ required,
1202
+ options
1203
+ };
1204
+ if (isRelationField(fieldName, zodType)) {
1205
+ fieldDef.type = "relation";
1206
+ const targetCollection = resolveTargetCollection(fieldName);
1207
+ const maxSelect = getMaxSelect(fieldName, zodType);
1208
+ const minSelect = getMinSelect(fieldName, zodType);
1209
+ fieldDef.relation = {
1210
+ collection: targetCollection,
1211
+ maxSelect,
1212
+ minSelect,
1213
+ cascadeDelete: false
1214
+ // Default to false, can be configured later
1215
+ };
1216
+ }
1217
+ return fieldDef;
1218
+ }
1219
+ function extractIndexes(schema) {
1220
+ const schemaDescription = schema.description;
1221
+ if (!schemaDescription) {
1222
+ return void 0;
1223
+ }
1224
+ try {
1225
+ const metadata = JSON.parse(schemaDescription);
1226
+ if (metadata.indexes && Array.isArray(metadata.indexes)) {
1227
+ return metadata.indexes;
1228
+ }
1229
+ } catch {
1230
+ }
1231
+ return void 0;
1232
+ }
1233
+ function convertZodSchemaToCollectionSchema(collectionName, zodSchema) {
1234
+ const rawFields = extractFieldDefinitions(zodSchema);
1235
+ const collectionType = isAuthCollection(rawFields) ? "auth" : "base";
1236
+ const fields = rawFields.map(({ name, zodType }) => buildFieldDefinition(name, zodType));
1237
+ const indexes = extractIndexes(zodSchema) || [];
1238
+ const permissionAnalyzer = new PermissionAnalyzer();
1239
+ let permissions = void 0;
1240
+ const schemaDescription = zodSchema.description;
1241
+ const extractedPermissions = permissionAnalyzer.extractPermissions(schemaDescription);
1242
+ if (extractedPermissions) {
1243
+ const resolvedPermissions = permissionAnalyzer.resolvePermissions(extractedPermissions);
1244
+ const validationResults = permissionAnalyzer.validatePermissions(
1245
+ collectionName,
1246
+ resolvedPermissions,
1247
+ fields,
1248
+ collectionType === "auth"
1249
+ );
1250
+ for (const [ruleType, result] of validationResults) {
1251
+ if (!result.valid) {
1252
+ console.error(`[${collectionName}] Permission validation failed for ${ruleType}:`);
1253
+ result.errors.forEach((error) => console.error(` - ${error}`));
1254
+ }
1255
+ if (result.warnings.length > 0) {
1256
+ console.warn(`[${collectionName}] Permission warnings for ${ruleType}:`);
1257
+ result.warnings.forEach((warning) => console.warn(` - ${warning}`));
1258
+ }
1259
+ }
1260
+ permissions = permissionAnalyzer.mergeWithDefaults(resolvedPermissions);
1261
+ }
1262
+ const collectionSchema = {
1263
+ name: collectionName,
1264
+ type: collectionType,
1265
+ fields,
1266
+ indexes,
1267
+ rules: {
1268
+ listRule: null,
1269
+ viewRule: null,
1270
+ createRule: null,
1271
+ updateRule: null,
1272
+ deleteRule: null
1273
+ },
1274
+ permissions
1275
+ };
1276
+ return collectionSchema;
1277
+ }
1278
+ async function buildSchemaDefinition(config) {
1279
+ const normalizedConfig = typeof config === "string" ? { schemaDir: config } : config;
1280
+ const mergedConfig = mergeConfig(normalizedConfig);
1281
+ const collections = /* @__PURE__ */ new Map();
1282
+ const schemaFiles = discoverSchemaFiles(normalizedConfig);
1283
+ if (schemaFiles.length === 0) {
1284
+ const schemaDir = resolveSchemaDir(normalizedConfig);
1285
+ throw new SchemaParsingError(
1286
+ `No schema files found in ${schemaDir}. Make sure you have schema files in the directory.`,
1287
+ schemaDir
1288
+ );
1289
+ }
1290
+ for (const filePath of schemaFiles) {
1291
+ try {
1292
+ let importPath = filePath;
1293
+ if (normalizedConfig.pathTransformer) {
1294
+ importPath = normalizedConfig.pathTransformer(filePath);
1295
+ } else if (mergedConfig.useCompiledFiles) {
1296
+ importPath = filePath.replace(/\/src\//, "/dist/");
1297
+ }
1298
+ const module = await importSchemaModule(importPath, normalizedConfig);
1299
+ const schemas = extractSchemaDefinitions(module, mergedConfig.schemaPatterns);
1300
+ const zodSchema = selectSchemaForCollection(schemas);
1301
+ if (!zodSchema) {
1302
+ console.warn(`No valid schema found in ${filePath}, skipping...`);
1303
+ continue;
1304
+ }
1305
+ const collectionName = getCollectionNameFromFile(filePath);
1306
+ const collectionSchema = convertZodSchemaToCollectionSchema(collectionName, zodSchema);
1307
+ collections.set(collectionName, collectionSchema);
1308
+ } catch (error) {
1309
+ if (error instanceof SchemaParsingError) {
1310
+ throw error;
1311
+ }
1312
+ throw new SchemaParsingError(
1313
+ `Error processing schema file: ${error instanceof Error ? error.message : String(error)}`,
1314
+ filePath,
1315
+ error
1316
+ );
1317
+ }
1318
+ }
1319
+ return { collections };
1320
+ }
1321
+ async function parseSchemaFiles(config) {
1322
+ return buildSchemaDefinition(config);
1323
+ }
1324
+
1325
+ // src/migration/diff.ts
1326
+ var DEFAULT_CONFIG2 = {
1327
+ warnOnDelete: true,
1328
+ requireForceForDestructive: true,
1329
+ severityThreshold: "high",
1330
+ systemCollections: ["_mfas", "_otps", "_externalAuths", "_authOrigins", "_superusers"],
1331
+ usersSystemFields: ["id", "password", "tokenKey", "email", "emailVisibility", "verified", "created", "updated"]
1332
+ };
1333
+ function mergeConfig2(config) {
1334
+ return {
1335
+ ...DEFAULT_CONFIG2,
1336
+ ...config
1337
+ };
1338
+ }
1339
+ function isSystemCollection(collectionName, config) {
1340
+ const mergedConfig = mergeConfig2(config);
1341
+ return mergedConfig.systemCollections.includes(collectionName);
1342
+ }
1343
+ function getUsersSystemFields(config) {
1344
+ const mergedConfig = mergeConfig2(config);
1345
+ return new Set(mergedConfig.usersSystemFields);
1346
+ }
1347
+ function findNewCollections(currentSchema, previousSnapshot) {
1348
+ const newCollections = [];
1349
+ if (!previousSnapshot) {
1350
+ return Array.from(currentSchema.collections.values());
1351
+ }
1352
+ for (const [collectionName, collectionSchema] of currentSchema.collections) {
1353
+ if (!previousSnapshot.collections.has(collectionName)) {
1354
+ newCollections.push(collectionSchema);
1355
+ }
1356
+ }
1357
+ return newCollections;
1358
+ }
1359
+ function findRemovedCollections(currentSchema, previousSnapshot) {
1360
+ const removedCollections = [];
1361
+ if (!previousSnapshot) {
1362
+ return removedCollections;
1363
+ }
1364
+ for (const [collectionName, collectionSchema] of previousSnapshot.collections) {
1365
+ if (!currentSchema.collections.has(collectionName)) {
1366
+ removedCollections.push(collectionSchema);
1367
+ }
1368
+ }
1369
+ return removedCollections;
1370
+ }
1371
+ function matchCollectionsByName(currentSchema, previousSnapshot) {
1372
+ const matches = [];
1373
+ if (!previousSnapshot) {
1374
+ return matches;
1375
+ }
1376
+ for (const [collectionName, currentCollection] of currentSchema.collections) {
1377
+ const previousCollection = previousSnapshot.collections.get(collectionName);
1378
+ if (previousCollection) {
1379
+ matches.push([currentCollection, previousCollection]);
1380
+ }
1381
+ }
1382
+ return matches;
1383
+ }
1384
+ function findNewFields(currentFields, previousFields) {
1385
+ const newFields = [];
1386
+ const previousFieldNames = new Set(previousFields.map((f) => f.name));
1387
+ for (const currentField of currentFields) {
1388
+ if (!previousFieldNames.has(currentField.name)) {
1389
+ newFields.push(currentField);
1390
+ }
1391
+ }
1392
+ return newFields;
1393
+ }
1394
+ function findRemovedFields(currentFields, previousFields) {
1395
+ const removedFields = [];
1396
+ const currentFieldNames = new Set(currentFields.map((f) => f.name));
1397
+ for (const previousField of previousFields) {
1398
+ if (!currentFieldNames.has(previousField.name)) {
1399
+ removedFields.push(previousField);
1400
+ }
1401
+ }
1402
+ return removedFields;
1403
+ }
1404
+ function matchFieldsByName(currentFields, previousFields) {
1405
+ const matches = [];
1406
+ const previousFieldMap = /* @__PURE__ */ new Map();
1407
+ for (const previousField of previousFields) {
1408
+ previousFieldMap.set(previousField.name, previousField);
1409
+ }
1410
+ for (const currentField of currentFields) {
1411
+ const previousField = previousFieldMap.get(currentField.name);
1412
+ if (previousField) {
1413
+ matches.push([currentField, previousField]);
1414
+ }
1415
+ }
1416
+ return matches;
1417
+ }
1418
+ function areValuesEqual(a, b) {
1419
+ if (a === b) return true;
1420
+ if (a == null || b == null) return false;
1421
+ if (Array.isArray(a) && Array.isArray(b)) {
1422
+ if (a.length !== b.length) return false;
1423
+ return a.every((val, idx) => areValuesEqual(val, b[idx]));
1424
+ }
1425
+ if (typeof a === "object" && typeof b === "object") {
1426
+ const keysA = Object.keys(a);
1427
+ const keysB = Object.keys(b);
1428
+ if (keysA.length !== keysB.length) return false;
1429
+ return keysA.every((key) => areValuesEqual(a[key], b[key]));
1430
+ }
1431
+ return a === b;
1432
+ }
1433
+ function compareFieldTypes(currentField, previousField) {
1434
+ if (currentField.type !== previousField.type) {
1435
+ return {
1436
+ property: "type",
1437
+ oldValue: previousField.type,
1438
+ newValue: currentField.type
1439
+ };
1440
+ }
1441
+ return null;
1442
+ }
1443
+ function compareFieldConstraints(currentField, previousField) {
1444
+ const changes = [];
1445
+ if (currentField.required !== previousField.required) {
1446
+ changes.push({
1447
+ property: "required",
1448
+ oldValue: previousField.required,
1449
+ newValue: currentField.required
1450
+ });
1451
+ }
1452
+ if (currentField.unique !== previousField.unique) {
1453
+ changes.push({
1454
+ property: "unique",
1455
+ oldValue: previousField.unique,
1456
+ newValue: currentField.unique
1457
+ });
1458
+ }
1459
+ return changes;
1460
+ }
1461
+ function compareFieldOptions(currentField, previousField) {
1462
+ const changes = [];
1463
+ const currentOptions = currentField.options || {};
1464
+ const previousOptions = previousField.options || {};
1465
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(currentOptions), ...Object.keys(previousOptions)]);
1466
+ for (const key of allKeys) {
1467
+ const currentValue = currentOptions[key];
1468
+ const previousValue = previousOptions[key];
1469
+ if (!areValuesEqual(currentValue, previousValue)) {
1470
+ changes.push({
1471
+ property: `options.${key}`,
1472
+ oldValue: previousValue,
1473
+ newValue: currentValue
1474
+ });
1475
+ }
1476
+ }
1477
+ return changes;
1478
+ }
1479
+ function compareRelationConfigurations(currentField, previousField) {
1480
+ const changes = [];
1481
+ const currentRelation = currentField.relation;
1482
+ const previousRelation = previousField.relation;
1483
+ if (!currentRelation && !previousRelation) {
1484
+ return changes;
1485
+ }
1486
+ if (!currentRelation || !previousRelation) {
1487
+ return changes;
1488
+ }
1489
+ if (currentRelation.collection !== previousRelation.collection) {
1490
+ changes.push({
1491
+ property: "relation.collection",
1492
+ oldValue: previousRelation.collection,
1493
+ newValue: currentRelation.collection
1494
+ });
1495
+ }
1496
+ if (currentRelation.cascadeDelete !== previousRelation.cascadeDelete) {
1497
+ changes.push({
1498
+ property: "relation.cascadeDelete",
1499
+ oldValue: previousRelation.cascadeDelete,
1500
+ newValue: currentRelation.cascadeDelete
1501
+ });
1502
+ }
1503
+ if (currentRelation.maxSelect !== previousRelation.maxSelect) {
1504
+ changes.push({
1505
+ property: "relation.maxSelect",
1506
+ oldValue: previousRelation.maxSelect,
1507
+ newValue: currentRelation.maxSelect
1508
+ });
1509
+ }
1510
+ if (currentRelation.minSelect !== previousRelation.minSelect) {
1511
+ changes.push({
1512
+ property: "relation.minSelect",
1513
+ oldValue: previousRelation.minSelect,
1514
+ newValue: currentRelation.minSelect
1515
+ });
1516
+ }
1517
+ return changes;
1518
+ }
1519
+ function detectFieldChanges(currentField, previousField) {
1520
+ const changes = [];
1521
+ const typeChange = compareFieldTypes(currentField, previousField);
1522
+ if (typeChange) {
1523
+ changes.push(typeChange);
1524
+ }
1525
+ changes.push(...compareFieldConstraints(currentField, previousField));
1526
+ changes.push(...compareFieldOptions(currentField, previousField));
1527
+ if (currentField.type === "relation" && previousField.type === "relation") {
1528
+ changes.push(...compareRelationConfigurations(currentField, previousField));
1529
+ }
1530
+ return changes;
1531
+ }
1532
+ function compareIndexes(currentIndexes = [], previousIndexes = []) {
1533
+ const currentSet = new Set(currentIndexes);
1534
+ const previousSet = new Set(previousIndexes);
1535
+ const indexesToAdd = currentIndexes.filter((idx) => !previousSet.has(idx));
1536
+ const indexesToRemove = previousIndexes.filter((idx) => !currentSet.has(idx));
1537
+ return { indexesToAdd, indexesToRemove };
1538
+ }
1539
+ function compareRules(currentRules, previousRules) {
1540
+ const updates = [];
1541
+ const ruleTypes = [
1542
+ "listRule",
1543
+ "viewRule",
1544
+ "createRule",
1545
+ "updateRule",
1546
+ "deleteRule",
1547
+ "manageRule"
1548
+ ];
1549
+ for (const ruleType of ruleTypes) {
1550
+ const currentValue = currentRules?.[ruleType] ?? null;
1551
+ const previousValue = previousRules?.[ruleType] ?? null;
1552
+ if (currentValue !== previousValue) {
1553
+ updates.push({
1554
+ ruleType,
1555
+ oldValue: previousValue,
1556
+ newValue: currentValue
1557
+ });
1558
+ }
1559
+ }
1560
+ return updates;
1561
+ }
1562
+ function comparePermissions(currentPermissions, previousPermissions) {
1563
+ const changes = [];
1564
+ const ruleTypes = ["listRule", "viewRule", "createRule", "updateRule", "deleteRule", "manageRule"];
1565
+ for (const ruleType of ruleTypes) {
1566
+ const currentValue = currentPermissions?.[ruleType] ?? null;
1567
+ const previousValue = previousPermissions?.[ruleType] ?? null;
1568
+ if (currentValue !== previousValue) {
1569
+ changes.push({
1570
+ ruleType,
1571
+ oldValue: previousValue,
1572
+ newValue: currentValue
1573
+ });
1574
+ }
1575
+ }
1576
+ return changes;
1577
+ }
1578
+ function compareCollectionFields(currentCollection, previousCollection, config) {
1579
+ let fieldsToAdd = findNewFields(currentCollection.fields, previousCollection.fields);
1580
+ const fieldsToRemove = findRemovedFields(currentCollection.fields, previousCollection.fields);
1581
+ const fieldsToModify = [];
1582
+ if (currentCollection.name === "users") {
1583
+ const systemFields = getUsersSystemFields(config);
1584
+ fieldsToAdd = fieldsToAdd.filter((field) => !systemFields.has(field.name));
1585
+ }
1586
+ const matchedFields = matchFieldsByName(currentCollection.fields, previousCollection.fields);
1587
+ for (const [currentField, previousField] of matchedFields) {
1588
+ const changes = detectFieldChanges(currentField, previousField);
1589
+ if (changes.length > 0) {
1590
+ fieldsToModify.push({
1591
+ fieldName: currentField.name,
1592
+ currentDefinition: previousField,
1593
+ newDefinition: currentField,
1594
+ changes
1595
+ });
1596
+ }
1597
+ }
1598
+ return { fieldsToAdd, fieldsToRemove, fieldsToModify };
1599
+ }
1600
+ function buildCollectionModification(currentCollection, previousCollection, config) {
1601
+ const { fieldsToAdd, fieldsToRemove, fieldsToModify } = compareCollectionFields(
1602
+ currentCollection,
1603
+ previousCollection,
1604
+ config
1605
+ );
1606
+ const { indexesToAdd, indexesToRemove } = compareIndexes(currentCollection.indexes, previousCollection.indexes);
1607
+ const rulesToUpdate = compareRules(currentCollection.rules, previousCollection.rules);
1608
+ const permissionsToUpdate = comparePermissions(currentCollection.permissions, previousCollection.permissions);
1609
+ return {
1610
+ collection: currentCollection.name,
1611
+ fieldsToAdd,
1612
+ fieldsToRemove,
1613
+ fieldsToModify,
1614
+ indexesToAdd,
1615
+ indexesToRemove,
1616
+ rulesToUpdate,
1617
+ permissionsToUpdate
1618
+ };
1619
+ }
1620
+ function hasChanges(modification) {
1621
+ return modification.fieldsToAdd.length > 0 || modification.fieldsToRemove.length > 0 || modification.fieldsToModify.length > 0 || modification.indexesToAdd.length > 0 || modification.indexesToRemove.length > 0 || modification.rulesToUpdate.length > 0 || modification.permissionsToUpdate.length > 0;
1622
+ }
1623
+ function aggregateChanges(currentSchema, previousSnapshot, config) {
1624
+ const collectionsToCreate = findNewCollections(currentSchema, previousSnapshot);
1625
+ const collectionsToDelete = findRemovedCollections(currentSchema, previousSnapshot);
1626
+ const filteredCollectionsToCreate = collectionsToCreate.filter(
1627
+ (collection) => !isSystemCollection(collection.name, config)
1628
+ );
1629
+ const filteredCollectionsToDelete = collectionsToDelete.filter(
1630
+ (collection) => !isSystemCollection(collection.name, config)
1631
+ );
1632
+ const collectionsToModify = [];
1633
+ const matchedCollections = matchCollectionsByName(currentSchema, previousSnapshot);
1634
+ for (const [currentCollection, previousCollection] of matchedCollections) {
1635
+ const modification = buildCollectionModification(currentCollection, previousCollection, config);
1636
+ if (hasChanges(modification)) {
1637
+ collectionsToModify.push(modification);
1638
+ }
1639
+ }
1640
+ return {
1641
+ collectionsToCreate: filteredCollectionsToCreate,
1642
+ collectionsToDelete: filteredCollectionsToDelete,
1643
+ collectionsToModify
1644
+ };
1645
+ }
1646
+ function categorizeChangesBySeverity(diff, _config) {
1647
+ const destructive = [];
1648
+ const nonDestructive = [];
1649
+ for (const collection of diff.collectionsToDelete) {
1650
+ destructive.push(`Delete collection: ${collection.name}`);
1651
+ }
1652
+ for (const collection of diff.collectionsToCreate) {
1653
+ nonDestructive.push(`Create collection: ${collection.name}`);
1654
+ }
1655
+ for (const modification of diff.collectionsToModify) {
1656
+ const collectionName = modification.collection;
1657
+ for (const field of modification.fieldsToRemove) {
1658
+ destructive.push(`Delete field: ${collectionName}.${field.name}`);
1659
+ }
1660
+ for (const field of modification.fieldsToAdd) {
1661
+ nonDestructive.push(`Add field: ${collectionName}.${field.name}`);
1662
+ }
1663
+ for (const fieldMod of modification.fieldsToModify) {
1664
+ const hasTypeChange = fieldMod.changes.some((c) => c.property === "type");
1665
+ const hasRequiredChange = fieldMod.changes.some((c) => c.property === "required" && c.newValue === true);
1666
+ if (hasTypeChange) {
1667
+ destructive.push(
1668
+ `Change field type: ${collectionName}.${fieldMod.fieldName} (${fieldMod.changes.find((c) => c.property === "type")?.oldValue} \u2192 ${fieldMod.changes.find((c) => c.property === "type")?.newValue})`
1669
+ );
1670
+ } else if (hasRequiredChange) {
1671
+ destructive.push(`Make field required: ${collectionName}.${fieldMod.fieldName}`);
1672
+ } else {
1673
+ nonDestructive.push(`Modify field: ${collectionName}.${fieldMod.fieldName}`);
1674
+ }
1675
+ }
1676
+ for (const _index of modification.indexesToAdd) {
1677
+ nonDestructive.push(`Add index: ${collectionName}`);
1678
+ }
1679
+ for (const _index of modification.indexesToRemove) {
1680
+ nonDestructive.push(`Remove index: ${collectionName}`);
1681
+ }
1682
+ for (const rule of modification.rulesToUpdate) {
1683
+ nonDestructive.push(`Update rule: ${collectionName}.${rule.ruleType}`);
1684
+ }
1685
+ }
1686
+ return { destructive, nonDestructive };
1687
+ }
1688
+ function compare(currentSchema, previousSnapshot, config) {
1689
+ return aggregateChanges(currentSchema, previousSnapshot, config);
1690
+ }
1691
+ var DEFAULT_TEMPLATE = `/// <reference path="{{TYPES_PATH}}" />
1692
+ migrate((app) => {
1693
+ {{UP_CODE}}
1694
+ return true;
1695
+ }, (app) => {
1696
+ {{DOWN_CODE}}
1697
+ return true;
1698
+ });
1699
+ `;
1700
+ var DEFAULT_CONFIG3 = {
1701
+ workspaceRoot: process.cwd(),
1702
+ timestampGenerator: () => Math.floor(Date.now() / 1e3).toString(),
1703
+ template: DEFAULT_TEMPLATE,
1704
+ includeTypeReference: true,
1705
+ typesPath: "../pb_data/types.d.ts"
1706
+ };
1707
+ function mergeConfig3(config) {
1708
+ return {
1709
+ ...DEFAULT_CONFIG3,
1710
+ ...config
1711
+ };
1712
+ }
1713
+ function resolveMigrationDir(config) {
1714
+ const workspaceRoot = config.workspaceRoot || process.cwd();
1715
+ if (path4__namespace.isAbsolute(config.migrationDir)) {
1716
+ return config.migrationDir;
1717
+ }
1718
+ return path4__namespace.join(workspaceRoot, config.migrationDir);
1719
+ }
1720
+ function generateTimestamp(config) {
1721
+ if (config?.timestampGenerator) {
1722
+ return config.timestampGenerator();
1723
+ }
1724
+ return Math.floor(Date.now() / 1e3).toString();
1725
+ }
1726
+ function generateMigrationDescription(diff) {
1727
+ const parts = [];
1728
+ if (diff.collectionsToCreate.length > 0) {
1729
+ if (diff.collectionsToCreate.length === 1) {
1730
+ parts.push(`created_${diff.collectionsToCreate[0].name}`);
1731
+ } else {
1732
+ parts.push(`created_${diff.collectionsToCreate.length}_collections`);
1733
+ }
1734
+ }
1735
+ if (diff.collectionsToDelete.length > 0) {
1736
+ if (diff.collectionsToDelete.length === 1) {
1737
+ parts.push(`deleted_${diff.collectionsToDelete[0].name}`);
1738
+ } else {
1739
+ parts.push(`deleted_${diff.collectionsToDelete.length}_collections`);
1740
+ }
1741
+ }
1742
+ if (diff.collectionsToModify.length > 0) {
1743
+ if (diff.collectionsToModify.length === 1) {
1744
+ parts.push(`updated_${diff.collectionsToModify[0].collection}`);
1745
+ } else {
1746
+ parts.push(`updated_${diff.collectionsToModify.length}_collections`);
1747
+ }
1748
+ }
1749
+ if (parts.length === 0) {
1750
+ return "no_changes";
1751
+ }
1752
+ let description = parts.join("_");
1753
+ if (description.length > 80) {
1754
+ description = description.substring(0, 77) + "...";
1755
+ }
1756
+ return description;
1757
+ }
1758
+ function generateMigrationFilename(diff, config) {
1759
+ const timestamp = generateTimestamp(config);
1760
+ const description = generateMigrationDescription(diff);
1761
+ return `${timestamp}_${description}.js`;
1762
+ }
1763
+ function createMigrationFileStructure(upCode, downCode, config) {
1764
+ const mergedConfig = config ? mergeConfig3(config) : DEFAULT_CONFIG3;
1765
+ let template = mergedConfig.template;
1766
+ template = template.replace("{{TYPES_PATH}}", mergedConfig.typesPath);
1767
+ template = template.replace("{{UP_CODE}}", upCode);
1768
+ template = template.replace("{{DOWN_CODE}}", downCode);
1769
+ if (!mergedConfig.includeTypeReference) {
1770
+ template = template.replace(/\/\/\/ <reference path="[^"]*" \/>\n?/, "");
1771
+ }
1772
+ return template;
1773
+ }
1774
+ function writeMigrationFile(migrationDir, filename, content) {
1775
+ try {
1776
+ if (!fs4__namespace.existsSync(migrationDir)) {
1777
+ try {
1778
+ fs4__namespace.mkdirSync(migrationDir, { recursive: true });
1779
+ } catch (error) {
1780
+ const fsError = error;
1781
+ if (fsError.code === "EACCES" || fsError.code === "EPERM") {
1782
+ throw new FileSystemError(
1783
+ `Permission denied creating migration directory. Check directory permissions.`,
1784
+ migrationDir,
1785
+ "create",
1786
+ fsError.code,
1787
+ error
1788
+ );
1789
+ }
1790
+ throw new FileSystemError(
1791
+ `Failed to create migration directory: ${fsError.message}`,
1792
+ migrationDir,
1793
+ "create",
1794
+ fsError.code,
1795
+ error
1796
+ );
1797
+ }
1798
+ }
1799
+ const filePath = path4__namespace.join(migrationDir, filename);
1800
+ fs4__namespace.writeFileSync(filePath, content, "utf-8");
1801
+ return filePath;
1802
+ } catch (error) {
1803
+ if (error instanceof FileSystemError) {
1804
+ throw error;
1805
+ }
1806
+ const fsError = error;
1807
+ const filePath = path4__namespace.join(migrationDir, filename);
1808
+ if (fsError.code === "EACCES" || fsError.code === "EPERM") {
1809
+ throw new FileSystemError(
1810
+ `Permission denied writing migration file. Check file and directory permissions.`,
1811
+ filePath,
1812
+ "write",
1813
+ fsError.code,
1814
+ error
1815
+ );
1816
+ } else if (fsError.code === "ENOSPC") {
1817
+ throw new FileSystemError(
1818
+ `No space left on device when writing migration file.`,
1819
+ filePath,
1820
+ "write",
1821
+ fsError.code,
1822
+ error
1823
+ );
1824
+ }
1825
+ throw new MigrationGenerationError(`Failed to write migration file: ${fsError.message}`, filePath, error);
1826
+ }
1827
+ }
1828
+ function formatValue(value) {
1829
+ if (value === null || value === void 0) {
1830
+ return "null";
1831
+ }
1832
+ if (typeof value === "string") {
1833
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
1834
+ }
1835
+ if (typeof value === "number" || typeof value === "boolean") {
1836
+ return String(value);
1837
+ }
1838
+ if (Array.isArray(value)) {
1839
+ const items = value.map((v) => formatValue(v)).join(", ");
1840
+ return `[${items}]`;
1841
+ }
1842
+ if (typeof value === "object") {
1843
+ const entries = Object.entries(value).map(([k, v]) => `${k}: ${formatValue(v)}`).join(", ");
1844
+ return `{ ${entries} }`;
1845
+ }
1846
+ return String(value);
1847
+ }
1848
+ function generateFieldDefinitionObject(field) {
1849
+ const parts = [];
1850
+ parts.push(` name: "${field.name}"`);
1851
+ parts.push(` type: "${field.type}"`);
1852
+ parts.push(` required: ${field.required}`);
1853
+ if (field.unique !== void 0) {
1854
+ parts.push(` unique: ${field.unique}`);
1855
+ }
1856
+ if (field.options && Object.keys(field.options).length > 0) {
1857
+ for (const [key, value] of Object.entries(field.options)) {
1858
+ parts.push(` ${key}: ${formatValue(value)}`);
1859
+ }
1860
+ }
1861
+ if (field.relation) {
1862
+ const collectionIdPlaceholder = field.relation.collection === "Users" ? '"_pb_users_auth_"' : `app.findCollectionByNameOrId("${field.relation.collection}").id`;
1863
+ parts.push(` collectionId: ${collectionIdPlaceholder}`);
1864
+ if (field.relation.maxSelect !== void 0) {
1865
+ parts.push(` maxSelect: ${field.relation.maxSelect}`);
1866
+ }
1867
+ if (field.relation.minSelect !== void 0) {
1868
+ parts.push(` minSelect: ${field.relation.minSelect}`);
1869
+ }
1870
+ if (field.relation.cascadeDelete !== void 0) {
1871
+ parts.push(` cascadeDelete: ${field.relation.cascadeDelete}`);
1872
+ }
1873
+ }
1874
+ return ` {
1875
+ ${parts.join(",\n")},
1876
+ }`;
1877
+ }
1878
+ function generateFieldsArray(fields) {
1879
+ if (fields.length === 0) {
1880
+ return "[]";
1881
+ }
1882
+ const fieldObjects = fields.map((field) => generateFieldDefinitionObject(field));
1883
+ return `[
1884
+ ${fieldObjects.join(",\n")},
1885
+ ]`;
1886
+ }
1887
+ function generateCollectionRules(rules) {
1888
+ if (!rules) {
1889
+ return "";
1890
+ }
1891
+ const parts = [];
1892
+ if (rules.listRule !== void 0) {
1893
+ parts.push(`listRule: ${formatValue(rules.listRule)}`);
1894
+ }
1895
+ if (rules.viewRule !== void 0) {
1896
+ parts.push(`viewRule: ${formatValue(rules.viewRule)}`);
1897
+ }
1898
+ if (rules.createRule !== void 0) {
1899
+ parts.push(`createRule: ${formatValue(rules.createRule)}`);
1900
+ }
1901
+ if (rules.updateRule !== void 0) {
1902
+ parts.push(`updateRule: ${formatValue(rules.updateRule)}`);
1903
+ }
1904
+ if (rules.deleteRule !== void 0) {
1905
+ parts.push(`deleteRule: ${formatValue(rules.deleteRule)}`);
1906
+ }
1907
+ if (rules.manageRule !== void 0) {
1908
+ parts.push(`manageRule: ${formatValue(rules.manageRule)}`);
1909
+ }
1910
+ return parts.join(",\n ");
1911
+ }
1912
+ function generateCollectionPermissions(permissions) {
1913
+ if (!permissions) {
1914
+ return "";
1915
+ }
1916
+ const parts = [];
1917
+ if (permissions.listRule !== void 0) {
1918
+ parts.push(`listRule: ${formatValue(permissions.listRule)}`);
1919
+ }
1920
+ if (permissions.viewRule !== void 0) {
1921
+ parts.push(`viewRule: ${formatValue(permissions.viewRule)}`);
1922
+ }
1923
+ if (permissions.createRule !== void 0) {
1924
+ parts.push(`createRule: ${formatValue(permissions.createRule)}`);
1925
+ }
1926
+ if (permissions.updateRule !== void 0) {
1927
+ parts.push(`updateRule: ${formatValue(permissions.updateRule)}`);
1928
+ }
1929
+ if (permissions.deleteRule !== void 0) {
1930
+ parts.push(`deleteRule: ${formatValue(permissions.deleteRule)}`);
1931
+ }
1932
+ if (permissions.manageRule !== void 0) {
1933
+ parts.push(`manageRule: ${formatValue(permissions.manageRule)}`);
1934
+ }
1935
+ return parts.join(",\n ");
1936
+ }
1937
+ function generateIndexesArray(indexes) {
1938
+ if (!indexes || indexes.length === 0) {
1939
+ return "[]";
1940
+ }
1941
+ const indexStrings = indexes.map((idx) => `"${idx}"`);
1942
+ return `[
1943
+ ${indexStrings.join(",\n ")},
1944
+ ]`;
1945
+ }
1946
+ function generateCollectionCreation(collection, varName = "collection") {
1947
+ const lines = [];
1948
+ lines.push(` const ${varName} = new Collection({`);
1949
+ lines.push(` name: "${collection.name}",`);
1950
+ lines.push(` type: "${collection.type}",`);
1951
+ const permissionsCode = generateCollectionPermissions(collection.permissions);
1952
+ const rulesCode = generateCollectionRules(collection.rules);
1953
+ if (permissionsCode) {
1954
+ lines.push(` ${permissionsCode},`);
1955
+ } else if (rulesCode) {
1956
+ lines.push(` ${rulesCode},`);
1957
+ }
1958
+ lines.push(` fields: ${generateFieldsArray(collection.fields)},`);
1959
+ lines.push(` indexes: ${generateIndexesArray(collection.indexes)},`);
1960
+ lines.push(` });`);
1961
+ lines.push(``);
1962
+ lines.push(` app.save(${varName});`);
1963
+ return lines.join("\n");
1964
+ }
1965
+ function getFieldConstructorName(fieldType) {
1966
+ const constructorMap = {
1967
+ text: "TextField",
1968
+ email: "EmailField",
1969
+ url: "URLField",
1970
+ number: "NumberField",
1971
+ bool: "BoolField",
1972
+ date: "DateField",
1973
+ select: "SelectField",
1974
+ relation: "RelationField",
1975
+ file: "FileField",
1976
+ json: "JSONField"
1977
+ };
1978
+ return constructorMap[fieldType] || "TextField";
1979
+ }
1980
+ function generateFieldConstructorOptions(field) {
1981
+ const parts = [];
1982
+ parts.push(` name: "${field.name}"`);
1983
+ parts.push(` required: ${field.required}`);
1984
+ if (field.unique !== void 0) {
1985
+ parts.push(` unique: ${field.unique}`);
1986
+ }
1987
+ if (field.options && Object.keys(field.options).length > 0) {
1988
+ for (const [key, value] of Object.entries(field.options)) {
1989
+ parts.push(` ${key}: ${formatValue(value)}`);
1990
+ }
1991
+ }
1992
+ if (field.relation && field.type === "relation") {
1993
+ const collectionIdPlaceholder = field.relation.collection === "Users" ? '"_pb_users_auth_"' : `app.findCollectionByNameOrId("${field.relation.collection}").id`;
1994
+ parts.push(` collectionId: ${collectionIdPlaceholder}`);
1995
+ if (field.relation.maxSelect !== void 0) {
1996
+ parts.push(` maxSelect: ${field.relation.maxSelect}`);
1997
+ }
1998
+ if (field.relation.minSelect !== void 0) {
1999
+ parts.push(` minSelect: ${field.relation.minSelect}`);
2000
+ }
2001
+ if (field.relation.cascadeDelete !== void 0) {
2002
+ parts.push(` cascadeDelete: ${field.relation.cascadeDelete}`);
2003
+ }
2004
+ }
2005
+ return parts.join(",\n");
2006
+ }
2007
+ function generateFieldAddition(collectionName, field, varName) {
2008
+ const lines = [];
2009
+ const constructorName = getFieldConstructorName(field.type);
2010
+ const collectionVar = varName || `collection_${collectionName}_${field.name}`;
2011
+ lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
2012
+ lines.push(``);
2013
+ lines.push(` ${collectionVar}.fields.add(new ${constructorName}({`);
2014
+ lines.push(generateFieldConstructorOptions(field));
2015
+ lines.push(` }));`);
2016
+ lines.push(``);
2017
+ lines.push(` app.save(${collectionVar});`);
2018
+ return lines.join("\n");
2019
+ }
2020
+ function generateFieldModification(collectionName, modification, varName) {
2021
+ const lines = [];
2022
+ const collectionVar = varName || `collection_${collectionName}_${modification.fieldName}`;
2023
+ const fieldVar = `${collectionVar}_field`;
2024
+ lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
2025
+ lines.push(` const ${fieldVar} = ${collectionVar}.fields.getByName("${modification.fieldName}");`);
2026
+ lines.push(``);
2027
+ for (const change of modification.changes) {
2028
+ if (change.property.startsWith("options.")) {
2029
+ const optionKey = change.property.replace("options.", "");
2030
+ lines.push(` ${fieldVar}.${optionKey} = ${formatValue(change.newValue)};`);
2031
+ } else if (change.property.startsWith("relation.")) {
2032
+ const relationKey = change.property.replace("relation.", "");
2033
+ if (relationKey === "collection") {
2034
+ const collectionIdValue = change.newValue === "Users" ? '"_pb_users_auth_"' : `app.findCollectionByNameOrId("${change.newValue}").id`;
2035
+ lines.push(` ${fieldVar}.collectionId = ${collectionIdValue};`);
2036
+ } else {
2037
+ lines.push(` ${fieldVar}.${relationKey} = ${formatValue(change.newValue)};`);
2038
+ }
2039
+ } else {
2040
+ lines.push(` ${fieldVar}.${change.property} = ${formatValue(change.newValue)};`);
2041
+ }
2042
+ }
2043
+ lines.push(``);
2044
+ lines.push(` app.save(${collectionVar});`);
2045
+ return lines.join("\n");
2046
+ }
2047
+ function generateFieldDeletion(collectionName, fieldName, varName) {
2048
+ const lines = [];
2049
+ const collectionVar = varName || `collection_${collectionName}_${fieldName}`;
2050
+ const fieldVar = `${collectionVar}_field`;
2051
+ lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
2052
+ lines.push(` const ${fieldVar} = ${collectionVar}.fields.getByName("${fieldName}");`);
2053
+ lines.push(``);
2054
+ lines.push(` ${collectionVar}.fields.remove(${fieldVar}.id);`);
2055
+ lines.push(``);
2056
+ lines.push(` app.save(${collectionVar});`);
2057
+ return lines.join("\n");
2058
+ }
2059
+ function generateIndexAddition(collectionName, index, varName) {
2060
+ const lines = [];
2061
+ const collectionVar = varName || `collection_${collectionName}_idx`;
2062
+ lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
2063
+ lines.push(` ${collectionVar}.indexes.push("${index}");`);
2064
+ lines.push(` app.save(${collectionVar});`);
2065
+ return lines.join("\n");
2066
+ }
2067
+ function generateIndexRemoval(collectionName, index, varName) {
2068
+ const lines = [];
2069
+ const collectionVar = varName || `collection_${collectionName}_idx`;
2070
+ const indexVar = `${collectionVar}_indexToRemove`;
2071
+ lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
2072
+ lines.push(` const ${indexVar} = ${collectionVar}.indexes.findIndex(idx => idx === "${index}");`);
2073
+ lines.push(` if (${indexVar} !== -1) {`);
2074
+ lines.push(` ${collectionVar}.indexes.splice(${indexVar}, 1);`);
2075
+ lines.push(` }`);
2076
+ lines.push(` app.save(${collectionVar});`);
2077
+ return lines.join("\n");
2078
+ }
2079
+ function generateRuleUpdate(collectionName, ruleType, newValue, varName) {
2080
+ const lines = [];
2081
+ const collectionVar = varName || `collection_${collectionName}_${ruleType}`;
2082
+ lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
2083
+ lines.push(` ${collectionVar}.${ruleType} = ${formatValue(newValue)};`);
2084
+ lines.push(` app.save(${collectionVar});`);
2085
+ return lines.join("\n");
2086
+ }
2087
+ function generatePermissionUpdate(collectionName, ruleType, newValue, varName) {
2088
+ const lines = [];
2089
+ const collectionVar = varName || `collection_${collectionName}_${ruleType}`;
2090
+ lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
2091
+ lines.push(` ${collectionVar}.${ruleType} = ${formatValue(newValue)};`);
2092
+ lines.push(` app.save(${collectionVar});`);
2093
+ return lines.join("\n");
2094
+ }
2095
+ function generateCollectionDeletion(collectionName, varName = "collection") {
2096
+ const lines = [];
2097
+ lines.push(` const ${varName} = app.findCollectionByNameOrId("${collectionName}");`);
2098
+ lines.push(` app.delete(${varName});`);
2099
+ return lines.join("\n");
2100
+ }
2101
+ function generateUpMigration(diff) {
2102
+ const lines = [];
2103
+ lines.push(` // UP MIGRATION`);
2104
+ lines.push(``);
2105
+ if (diff.collectionsToCreate.length > 0) {
2106
+ lines.push(` // Create new collections`);
2107
+ for (let i = 0; i < diff.collectionsToCreate.length; i++) {
2108
+ const collection = diff.collectionsToCreate[i];
2109
+ const varName = `collection_${collection.name}_create`;
2110
+ lines.push(generateCollectionCreation(collection, varName));
2111
+ lines.push(``);
2112
+ }
2113
+ }
2114
+ if (diff.collectionsToModify.length > 0) {
2115
+ lines.push(` // Modify existing collections`);
2116
+ for (const modification of diff.collectionsToModify) {
2117
+ const collectionName = modification.collection;
2118
+ if (modification.fieldsToAdd.length > 0) {
2119
+ lines.push(` // Add fields to ${collectionName}`);
2120
+ for (const field of modification.fieldsToAdd) {
2121
+ const varName = `collection_${collectionName}_add_${field.name}`;
2122
+ lines.push(generateFieldAddition(collectionName, field, varName));
2123
+ lines.push(``);
2124
+ }
2125
+ }
2126
+ if (modification.fieldsToModify.length > 0) {
2127
+ lines.push(` // Modify fields in ${collectionName}`);
2128
+ for (const fieldMod of modification.fieldsToModify) {
2129
+ const varName = `collection_${collectionName}_modify_${fieldMod.fieldName}`;
2130
+ lines.push(generateFieldModification(collectionName, fieldMod, varName));
2131
+ lines.push(``);
2132
+ }
2133
+ }
2134
+ if (modification.fieldsToRemove.length > 0) {
2135
+ lines.push(` // Remove fields from ${collectionName}`);
2136
+ for (const field of modification.fieldsToRemove) {
2137
+ const varName = `collection_${collectionName}_remove_${field.name}`;
2138
+ lines.push(generateFieldDeletion(collectionName, field.name, varName));
2139
+ lines.push(``);
2140
+ }
2141
+ }
2142
+ if (modification.indexesToAdd.length > 0) {
2143
+ lines.push(` // Add indexes to ${collectionName}`);
2144
+ for (let i = 0; i < modification.indexesToAdd.length; i++) {
2145
+ const index = modification.indexesToAdd[i];
2146
+ const varName = `collection_${collectionName}_addidx_${i}`;
2147
+ lines.push(generateIndexAddition(collectionName, index, varName));
2148
+ lines.push(``);
2149
+ }
2150
+ }
2151
+ if (modification.indexesToRemove.length > 0) {
2152
+ lines.push(` // Remove indexes from ${collectionName}`);
2153
+ for (let i = 0; i < modification.indexesToRemove.length; i++) {
2154
+ const index = modification.indexesToRemove[i];
2155
+ const varName = `collection_${collectionName}_rmidx_${i}`;
2156
+ lines.push(generateIndexRemoval(collectionName, index, varName));
2157
+ lines.push(``);
2158
+ }
2159
+ }
2160
+ if (modification.permissionsToUpdate && modification.permissionsToUpdate.length > 0) {
2161
+ lines.push(` // Update permissions for ${collectionName}`);
2162
+ for (const permission of modification.permissionsToUpdate) {
2163
+ const varName = `collection_${collectionName}_perm_${permission.ruleType}`;
2164
+ lines.push(generatePermissionUpdate(collectionName, permission.ruleType, permission.newValue, varName));
2165
+ lines.push(``);
2166
+ }
2167
+ } else if (modification.rulesToUpdate.length > 0) {
2168
+ lines.push(` // Update rules for ${collectionName}`);
2169
+ for (const rule of modification.rulesToUpdate) {
2170
+ const varName = `collection_${collectionName}_rule_${rule.ruleType}`;
2171
+ lines.push(generateRuleUpdate(collectionName, rule.ruleType, rule.newValue, varName));
2172
+ lines.push(``);
2173
+ }
2174
+ }
2175
+ }
2176
+ }
2177
+ if (diff.collectionsToDelete.length > 0) {
2178
+ lines.push(` // Delete collections`);
2179
+ for (let i = 0; i < diff.collectionsToDelete.length; i++) {
2180
+ const collection = diff.collectionsToDelete[i];
2181
+ const varName = `collection_${collection.name}_delete`;
2182
+ lines.push(generateCollectionDeletion(collection.name, varName));
2183
+ lines.push(``);
2184
+ }
2185
+ }
2186
+ if (lines.length === 2) {
2187
+ lines.push(` // No changes detected`);
2188
+ lines.push(``);
2189
+ }
2190
+ return lines.join("\n");
2191
+ }
2192
+ function generateDownMigration(diff) {
2193
+ const lines = [];
2194
+ lines.push(` // DOWN MIGRATION (ROLLBACK)`);
2195
+ lines.push(``);
2196
+ if (diff.collectionsToDelete.length > 0) {
2197
+ lines.push(` // Recreate deleted collections`);
2198
+ for (let i = 0; i < diff.collectionsToDelete.length; i++) {
2199
+ const collection = diff.collectionsToDelete[i];
2200
+ const varName = `collection_${collection.name}_recreate`;
2201
+ lines.push(generateCollectionCreation(collection, varName));
2202
+ lines.push(``);
2203
+ }
2204
+ }
2205
+ if (diff.collectionsToModify.length > 0) {
2206
+ lines.push(` // Revert modifications`);
2207
+ for (const modification of diff.collectionsToModify) {
2208
+ const collectionName = modification.collection;
2209
+ if (modification.permissionsToUpdate && modification.permissionsToUpdate.length > 0) {
2210
+ lines.push(` // Revert permissions for ${collectionName}`);
2211
+ for (const permission of modification.permissionsToUpdate) {
2212
+ const varName = `collection_${collectionName}_revert_perm_${permission.ruleType}`;
2213
+ lines.push(generatePermissionUpdate(collectionName, permission.ruleType, permission.oldValue, varName));
2214
+ lines.push(``);
2215
+ }
2216
+ } else if (modification.rulesToUpdate.length > 0) {
2217
+ lines.push(` // Revert rules for ${collectionName}`);
2218
+ for (const rule of modification.rulesToUpdate) {
2219
+ const varName = `collection_${collectionName}_revert_rule_${rule.ruleType}`;
2220
+ lines.push(generateRuleUpdate(collectionName, rule.ruleType, rule.oldValue, varName));
2221
+ lines.push(``);
2222
+ }
2223
+ }
2224
+ if (modification.indexesToRemove.length > 0) {
2225
+ lines.push(` // Restore indexes to ${collectionName}`);
2226
+ for (let i = 0; i < modification.indexesToRemove.length; i++) {
2227
+ const index = modification.indexesToRemove[i];
2228
+ const varName = `collection_${collectionName}_restore_idx_${i}`;
2229
+ lines.push(generateIndexAddition(collectionName, index, varName));
2230
+ lines.push(``);
2231
+ }
2232
+ }
2233
+ if (modification.indexesToAdd.length > 0) {
2234
+ lines.push(` // Remove indexes from ${collectionName}`);
2235
+ for (let i = 0; i < modification.indexesToAdd.length; i++) {
2236
+ const index = modification.indexesToAdd[i];
2237
+ const varName = `collection_${collectionName}_revert_idx_${i}`;
2238
+ lines.push(generateIndexRemoval(collectionName, index, varName));
2239
+ lines.push(``);
2240
+ }
2241
+ }
2242
+ if (modification.fieldsToRemove.length > 0) {
2243
+ lines.push(` // Restore fields to ${collectionName}`);
2244
+ for (const field of modification.fieldsToRemove) {
2245
+ const varName = `collection_${collectionName}_restore_${field.name}`;
2246
+ lines.push(generateFieldAddition(collectionName, field, varName));
2247
+ lines.push(``);
2248
+ }
2249
+ }
2250
+ if (modification.fieldsToModify.length > 0) {
2251
+ lines.push(` // Revert field modifications in ${collectionName}`);
2252
+ for (const fieldMod of modification.fieldsToModify) {
2253
+ const reverseChanges = fieldMod.changes.map((change) => ({
2254
+ property: change.property,
2255
+ oldValue: change.newValue,
2256
+ newValue: change.oldValue
2257
+ }));
2258
+ const reverseMod = {
2259
+ fieldName: fieldMod.fieldName,
2260
+ currentDefinition: fieldMod.newDefinition,
2261
+ newDefinition: fieldMod.currentDefinition,
2262
+ changes: reverseChanges
2263
+ };
2264
+ const varName = `collection_${collectionName}_revert_${fieldMod.fieldName}`;
2265
+ lines.push(generateFieldModification(collectionName, reverseMod, varName));
2266
+ lines.push(``);
2267
+ }
2268
+ }
2269
+ if (modification.fieldsToAdd.length > 0) {
2270
+ lines.push(` // Remove added fields from ${collectionName}`);
2271
+ for (const field of modification.fieldsToAdd) {
2272
+ const varName = `collection_${collectionName}_revert_add_${field.name}`;
2273
+ lines.push(generateFieldDeletion(collectionName, field.name, varName));
2274
+ lines.push(``);
2275
+ }
2276
+ }
2277
+ }
2278
+ }
2279
+ if (diff.collectionsToCreate.length > 0) {
2280
+ lines.push(` // Delete created collections`);
2281
+ for (let i = 0; i < diff.collectionsToCreate.length; i++) {
2282
+ const collection = diff.collectionsToCreate[i];
2283
+ const varName = `collection_${collection.name}_rollback`;
2284
+ lines.push(generateCollectionDeletion(collection.name, varName));
2285
+ lines.push(``);
2286
+ }
2287
+ }
2288
+ if (lines.length === 2) {
2289
+ lines.push(` // No changes to revert`);
2290
+ lines.push(``);
2291
+ }
2292
+ return lines.join("\n");
2293
+ }
2294
+ function generate(diff, config) {
2295
+ const normalizedConfig = typeof config === "string" ? { migrationDir: config } : config;
2296
+ try {
2297
+ const migrationDir = resolveMigrationDir(normalizedConfig);
2298
+ const upCode = generateUpMigration(diff);
2299
+ const downCode = generateDownMigration(diff);
2300
+ const content = createMigrationFileStructure(upCode, downCode, normalizedConfig);
2301
+ const filename = generateMigrationFilename(diff, normalizedConfig);
2302
+ const filePath = writeMigrationFile(migrationDir, filename, content);
2303
+ return filePath;
2304
+ } catch (error) {
2305
+ if (error instanceof MigrationGenerationError || error instanceof FileSystemError) {
2306
+ throw error;
2307
+ }
2308
+ throw new MigrationGenerationError(
2309
+ `Failed to generate migration: ${error instanceof Error ? error.message : String(error)}`,
2310
+ normalizedConfig.migrationDir,
2311
+ error
2312
+ );
2313
+ }
2314
+ }
2315
+ var SNAPSHOT_VERSION = "1.0.0";
2316
+ ({
2317
+ workspaceRoot: process.cwd()});
2318
+ function findLatestSnapshot(migrationsPath) {
2319
+ try {
2320
+ if (!fs4__namespace.existsSync(migrationsPath)) {
2321
+ return null;
2322
+ }
2323
+ const files = fs4__namespace.readdirSync(migrationsPath);
2324
+ const snapshotFiles = files.filter(
2325
+ (file) => file.endsWith("_collections_snapshot.js") || file.endsWith("_snapshot.js")
2326
+ );
2327
+ if (snapshotFiles.length === 0) {
2328
+ return null;
2329
+ }
2330
+ snapshotFiles.sort().reverse();
2331
+ const latestSnapshot = snapshotFiles[0];
2332
+ if (!latestSnapshot) {
2333
+ return null;
2334
+ }
2335
+ return path4__namespace.join(migrationsPath, latestSnapshot);
2336
+ } catch (error) {
2337
+ console.warn(`Error finding latest snapshot: ${error}`);
2338
+ return null;
2339
+ }
2340
+ }
2341
+ function loadSnapshotIfExists(config = {}) {
2342
+ const migrationsPath = config.migrationsPath;
2343
+ if (!migrationsPath) {
2344
+ return null;
2345
+ }
2346
+ if (fs4__namespace.existsSync(migrationsPath) && fs4__namespace.statSync(migrationsPath).isFile()) {
2347
+ try {
2348
+ const migrationContent = fs4__namespace.readFileSync(migrationsPath, "utf-8");
2349
+ return convertPocketBaseMigration(migrationContent);
2350
+ } catch (error) {
2351
+ console.warn(`Failed to load snapshot from ${migrationsPath}: ${error}`);
2352
+ return null;
2353
+ }
2354
+ }
2355
+ const latestSnapshotPath = findLatestSnapshot(migrationsPath);
2356
+ if (latestSnapshotPath) {
2357
+ try {
2358
+ const migrationContent = fs4__namespace.readFileSync(latestSnapshotPath, "utf-8");
2359
+ return convertPocketBaseMigration(migrationContent);
2360
+ } catch (error) {
2361
+ console.warn(`Failed to load snapshot from ${latestSnapshotPath}: ${error}`);
2362
+ return null;
2363
+ }
2364
+ }
2365
+ return null;
2366
+ }
2367
+ function convertPocketBaseCollection(pbCollection) {
2368
+ const fields = [];
2369
+ const systemFieldNames = ["id", "created", "updated", "collectionId", "collectionName", "expand"];
2370
+ const authSystemFieldNames = ["email", "emailVisibility", "verified", "password", "tokenKey"];
2371
+ if (pbCollection.fields && Array.isArray(pbCollection.fields)) {
2372
+ for (const pbField of pbCollection.fields) {
2373
+ if (pbField.system || systemFieldNames.includes(pbField.name)) {
2374
+ continue;
2375
+ }
2376
+ if (pbCollection.type === "auth" && authSystemFieldNames.includes(pbField.name)) {
2377
+ continue;
2378
+ }
2379
+ const field = {
2380
+ name: pbField.name,
2381
+ type: pbField.type,
2382
+ required: pbField.required || false
2383
+ };
2384
+ if (pbField.options) {
2385
+ field.options = pbField.options;
2386
+ }
2387
+ if (pbField.type === "relation") {
2388
+ field.relation = {
2389
+ collection: pbField.options?.collectionId || "",
2390
+ cascadeDelete: pbField.options?.cascadeDelete || false,
2391
+ maxSelect: pbField.options?.maxSelect,
2392
+ minSelect: pbField.options?.minSelect
2393
+ };
2394
+ }
2395
+ fields.push(field);
2396
+ }
2397
+ }
2398
+ const schema = {
2399
+ name: pbCollection.name,
2400
+ type: pbCollection.type || "base",
2401
+ fields
2402
+ };
2403
+ if (pbCollection.indexes && Array.isArray(pbCollection.indexes)) {
2404
+ schema.indexes = pbCollection.indexes;
2405
+ }
2406
+ const rules = {};
2407
+ if (pbCollection.listRule !== void 0) rules.listRule = pbCollection.listRule;
2408
+ if (pbCollection.viewRule !== void 0) rules.viewRule = pbCollection.viewRule;
2409
+ if (pbCollection.createRule !== void 0) rules.createRule = pbCollection.createRule;
2410
+ if (pbCollection.updateRule !== void 0) rules.updateRule = pbCollection.updateRule;
2411
+ if (pbCollection.deleteRule !== void 0) rules.deleteRule = pbCollection.deleteRule;
2412
+ if (pbCollection.manageRule !== void 0) rules.manageRule = pbCollection.manageRule;
2413
+ if (Object.keys(rules).length > 0) {
2414
+ schema.rules = rules;
2415
+ }
2416
+ return schema;
2417
+ }
2418
+ function convertPocketBaseMigration(migrationContent) {
2419
+ try {
2420
+ const snapshotMatch = migrationContent.match(/const\s+snapshot\s*=\s*(\[[\s\S]*?\]);/);
2421
+ if (!snapshotMatch) {
2422
+ throw new Error("Could not find snapshot array in migration file");
2423
+ }
2424
+ const snapshotArrayStr = snapshotMatch[1];
2425
+ let snapshotArray;
2426
+ try {
2427
+ snapshotArray = new Function(`return ${snapshotArrayStr}`)();
2428
+ } catch (parseError) {
2429
+ throw new Error(`Failed to parse snapshot array: ${parseError}`);
2430
+ }
2431
+ if (!Array.isArray(snapshotArray)) {
2432
+ throw new Error("Snapshot is not an array");
2433
+ }
2434
+ const collections = /* @__PURE__ */ new Map();
2435
+ for (const pbCollection of snapshotArray) {
2436
+ if (!pbCollection.name) {
2437
+ console.warn("Skipping collection without name");
2438
+ continue;
2439
+ }
2440
+ const schema = convertPocketBaseCollection(pbCollection);
2441
+ collections.set(pbCollection.name, schema);
2442
+ }
2443
+ return {
2444
+ version: SNAPSHOT_VERSION,
2445
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2446
+ collections
2447
+ };
2448
+ } catch (error) {
2449
+ throw new SnapshotError(
2450
+ `Failed to convert PocketBase migration: ${error instanceof Error ? error.message : String(error)}`,
2451
+ void 0,
2452
+ "parse",
2453
+ error instanceof Error ? error : void 0
2454
+ );
2455
+ }
2456
+ }
2457
+
2458
+ // src/migration/validation.ts
2459
+ function detectCollectionDeletions(diff) {
2460
+ const changes = [];
2461
+ for (const collection of diff.collectionsToDelete) {
2462
+ changes.push({
2463
+ type: "collection_deletion" /* COLLECTION_DELETION */,
2464
+ description: `Delete collection: ${collection.name}`,
2465
+ collection: collection.name,
2466
+ severity: "high",
2467
+ warning: `All data in the "${collection.name}" collection will be permanently deleted.`
2468
+ });
2469
+ }
2470
+ return changes;
2471
+ }
2472
+ function detectFieldDeletions(diff) {
2473
+ const changes = [];
2474
+ for (const modification of diff.collectionsToModify) {
2475
+ for (const field of modification.fieldsToRemove) {
2476
+ changes.push({
2477
+ type: "field_deletion" /* FIELD_DELETION */,
2478
+ description: `Delete field: ${modification.collection}.${field.name}`,
2479
+ collection: modification.collection,
2480
+ field: field.name,
2481
+ severity: "high",
2482
+ warning: `All data in the "${field.name}" field of "${modification.collection}" will be permanently deleted.`
2483
+ });
2484
+ }
2485
+ }
2486
+ return changes;
2487
+ }
2488
+ function detectFieldTypeChanges(diff) {
2489
+ const changes = [];
2490
+ for (const modification of diff.collectionsToModify) {
2491
+ for (const fieldMod of modification.fieldsToModify) {
2492
+ const typeChange = fieldMod.changes.find((c) => c.property === "type");
2493
+ if (typeChange) {
2494
+ changes.push({
2495
+ type: "field_type_change" /* FIELD_TYPE_CHANGE */,
2496
+ description: `Change field type: ${modification.collection}.${fieldMod.fieldName}`,
2497
+ collection: modification.collection,
2498
+ field: fieldMod.fieldName,
2499
+ details: {
2500
+ oldValue: typeChange.oldValue,
2501
+ newValue: typeChange.newValue
2502
+ },
2503
+ severity: "high",
2504
+ warning: `Changing field type from "${typeChange.oldValue}" to "${typeChange.newValue}" may cause data loss or conversion errors.`
2505
+ });
2506
+ }
2507
+ }
2508
+ }
2509
+ return changes;
2510
+ }
2511
+ function detectFieldRequiredChanges(diff) {
2512
+ const changes = [];
2513
+ for (const modification of diff.collectionsToModify) {
2514
+ for (const fieldMod of modification.fieldsToModify) {
2515
+ const requiredChange = fieldMod.changes.find(
2516
+ (c) => c.property === "required" && c.newValue === true && c.oldValue === false
2517
+ );
2518
+ if (requiredChange) {
2519
+ changes.push({
2520
+ type: "field_required_change" /* FIELD_REQUIRED_CHANGE */,
2521
+ description: `Make field required: ${modification.collection}.${fieldMod.fieldName}`,
2522
+ collection: modification.collection,
2523
+ field: fieldMod.fieldName,
2524
+ details: {
2525
+ oldValue: false,
2526
+ newValue: true
2527
+ },
2528
+ severity: "medium",
2529
+ warning: `Making "${fieldMod.fieldName}" required may cause issues with existing records that have null/empty values.`
2530
+ });
2531
+ }
2532
+ }
2533
+ }
2534
+ return changes;
2535
+ }
2536
+ function detectDestructiveChanges(diff) {
2537
+ const changes = [];
2538
+ changes.push(...detectCollectionDeletions(diff));
2539
+ changes.push(...detectFieldDeletions(diff));
2540
+ changes.push(...detectFieldTypeChanges(diff));
2541
+ changes.push(...detectFieldRequiredChanges(diff));
2542
+ return changes;
2543
+ }
2544
+ function formatDestructiveChanges(changes) {
2545
+ if (changes.length === 0) {
2546
+ return "No destructive changes detected.";
2547
+ }
2548
+ const lines = [];
2549
+ const highSeverity = changes.filter((c) => c.severity === "high");
2550
+ const mediumSeverity = changes.filter((c) => c.severity === "medium");
2551
+ const lowSeverity = changes.filter((c) => c.severity === "low");
2552
+ if (highSeverity.length > 0) {
2553
+ lines.push("\u{1F534} HIGH SEVERITY CHANGES (Data Loss Risk):");
2554
+ lines.push("");
2555
+ for (const change of highSeverity) {
2556
+ lines.push(` \u2022 ${change.description}`);
2557
+ lines.push(` \u26A0\uFE0F ${change.warning}`);
2558
+ if (change.details) {
2559
+ if (change.details.oldValue !== void 0 && change.details.newValue !== void 0) {
2560
+ lines.push(` Old: ${change.details.oldValue} \u2192 New: ${change.details.newValue}`);
2561
+ }
2562
+ }
2563
+ lines.push("");
2564
+ }
2565
+ }
2566
+ if (mediumSeverity.length > 0) {
2567
+ lines.push("\u{1F7E1} MEDIUM SEVERITY CHANGES (Potential Issues):");
2568
+ lines.push("");
2569
+ for (const change of mediumSeverity) {
2570
+ lines.push(` \u2022 ${change.description}`);
2571
+ lines.push(` \u26A0\uFE0F ${change.warning}`);
2572
+ if (change.details) {
2573
+ if (change.details.oldValue !== void 0 && change.details.newValue !== void 0) {
2574
+ lines.push(` Old: ${change.details.oldValue} \u2192 New: ${change.details.newValue}`);
2575
+ }
2576
+ }
2577
+ lines.push("");
2578
+ }
2579
+ }
2580
+ if (lowSeverity.length > 0) {
2581
+ lines.push("\u{1F7E2} LOW SEVERITY CHANGES:");
2582
+ lines.push("");
2583
+ for (const change of lowSeverity) {
2584
+ lines.push(` \u2022 ${change.description}`);
2585
+ lines.push(` \u2139\uFE0F ${change.warning}`);
2586
+ lines.push("");
2587
+ }
2588
+ }
2589
+ return lines.join("\n");
2590
+ }
2591
+ function summarizeDestructiveChanges(changes) {
2592
+ return {
2593
+ total: changes.length,
2594
+ high: changes.filter((c) => c.severity === "high").length,
2595
+ medium: changes.filter((c) => c.severity === "medium").length,
2596
+ low: changes.filter((c) => c.severity === "low").length
2597
+ };
2598
+ }
2599
+ function requiresForceFlag(changes) {
2600
+ return changes.some((c) => c.severity === "high" || c.severity === "medium");
2601
+ }
2602
+ var CONFIG_FILE_NAMES = [
2603
+ "pocketbase-migrate.config.js",
2604
+ "pocketbase-migrate.config.mjs",
2605
+ "pocketbase-migrate.config.json",
2606
+ "migrate.config.js",
2607
+ "migrate.config.mjs",
2608
+ "migrate.config.json"
2609
+ ];
2610
+ var DEFAULT_CONFIG5 = {
2611
+ schema: {
2612
+ directory: "src/schema",
2613
+ exclude: ["base.ts", "index.ts", "permissions.ts", "permission-templates.ts"]
2614
+ },
2615
+ migrations: {
2616
+ directory: "pocketbase/pb_migrations",
2617
+ format: "timestamp_description"
2618
+ },
2619
+ diff: {
2620
+ warnOnDelete: true,
2621
+ requireForceForDestructive: true
2622
+ }
2623
+ };
2624
+ function findConfigFile(directory) {
2625
+ for (const fileName of CONFIG_FILE_NAMES) {
2626
+ const filePath = path4__namespace.join(directory, fileName);
2627
+ if (fs4__namespace.existsSync(filePath)) {
2628
+ return filePath;
2629
+ }
2630
+ }
2631
+ return null;
2632
+ }
2633
+ function loadJsonConfig(configPath) {
2634
+ try {
2635
+ const content = fs4__namespace.readFileSync(configPath, "utf-8");
2636
+ return JSON.parse(content);
2637
+ } catch (error) {
2638
+ if (error instanceof SyntaxError) {
2639
+ throw new ConfigurationError("Invalid JSON syntax in configuration file", configPath, void 0, error);
2640
+ }
2641
+ throw new ConfigurationError(
2642
+ "Failed to read configuration file",
2643
+ configPath,
2644
+ void 0,
2645
+ error instanceof Error ? error : void 0
2646
+ );
2647
+ }
2648
+ }
2649
+ async function loadJsConfig(configPath) {
2650
+ try {
2651
+ const fileUrl = `file://${configPath}`;
2652
+ const module = await import(fileUrl);
2653
+ return module.default || module;
2654
+ } catch (error) {
2655
+ throw new ConfigurationError(
2656
+ "Failed to load JavaScript configuration file",
2657
+ configPath,
2658
+ void 0,
2659
+ error instanceof Error ? error : void 0
2660
+ );
2661
+ }
2662
+ }
2663
+ async function loadConfigFile(configPath) {
2664
+ if (!fs4__namespace.existsSync(configPath)) {
2665
+ return null;
2666
+ }
2667
+ const ext = path4__namespace.extname(configPath).toLowerCase();
2668
+ if (ext === ".json") {
2669
+ return loadJsonConfig(configPath);
2670
+ } else if (ext === ".js" || ext === ".mjs") {
2671
+ return loadJsConfig(configPath);
2672
+ } else {
2673
+ throw new ConfigurationError(`Unsupported configuration file format: ${ext}`, configPath, void 0);
2674
+ }
2675
+ }
2676
+ function mergeConfig4(base, override) {
2677
+ return {
2678
+ schema: { ...base.schema, ...override.schema },
2679
+ migrations: { ...base.migrations, ...override.migrations },
2680
+ diff: { ...base.diff, ...override.diff }
2681
+ };
2682
+ }
2683
+ function loadConfigFromEnv() {
2684
+ const config = {};
2685
+ if (process.env.MIGRATION_SCHEMA_DIR) {
2686
+ config.schema = { directory: process.env.MIGRATION_SCHEMA_DIR };
2687
+ }
2688
+ if (process.env.MIGRATION_SCHEMA_EXCLUDE) {
2689
+ config.schema = {
2690
+ ...config.schema,
2691
+ exclude: process.env.MIGRATION_SCHEMA_EXCLUDE.split(",").map((s) => s.trim())
2692
+ };
2693
+ }
2694
+ if (process.env.MIGRATION_OUTPUT_DIR) {
2695
+ config.migrations = { directory: process.env.MIGRATION_OUTPUT_DIR };
2696
+ }
2697
+ if (process.env.MIGRATION_REQUIRE_FORCE !== void 0) {
2698
+ config.diff = { requireForceForDestructive: process.env.MIGRATION_REQUIRE_FORCE === "true" };
2699
+ }
2700
+ return config;
2701
+ }
2702
+ function loadConfigFromArgs(options) {
2703
+ const config = {};
2704
+ if (options.output) {
2705
+ config.migrations = { directory: options.output };
2706
+ }
2707
+ if (options.schemaDir) {
2708
+ config.schema = { directory: options.schemaDir };
2709
+ }
2710
+ return config;
2711
+ }
2712
+ function validateConfig(config, configPath) {
2713
+ const invalidFields = [];
2714
+ if (typeof config.schema.directory !== "string" || config.schema.directory.trim() === "") {
2715
+ invalidFields.push("schema.directory (must be a non-empty string)");
2716
+ }
2717
+ if (!Array.isArray(config.schema.exclude)) {
2718
+ invalidFields.push("schema.exclude (must be an array of strings)");
2719
+ }
2720
+ if (typeof config.migrations.directory !== "string" || config.migrations.directory.trim() === "") {
2721
+ invalidFields.push("migrations.directory (must be a non-empty string)");
2722
+ }
2723
+ if (typeof config.diff.warnOnDelete !== "boolean") {
2724
+ invalidFields.push("diff.warnOnDelete (must be a boolean)");
2725
+ }
2726
+ if (typeof config.diff.requireForceForDestructive !== "boolean") {
2727
+ invalidFields.push("diff.requireForceForDestructive (must be a boolean)");
2728
+ }
2729
+ if (invalidFields.length > 0) {
2730
+ throw new ConfigurationError("Invalid configuration values", configPath, invalidFields);
2731
+ }
2732
+ const cwd = process.cwd();
2733
+ const possiblePaths = [
2734
+ path4__namespace.resolve(cwd, config.schema.directory),
2735
+ path4__namespace.resolve(cwd, "shared", config.schema.directory)
2736
+ ];
2737
+ const schemaDir = possiblePaths.find((p) => fs4__namespace.existsSync(p));
2738
+ if (!schemaDir) {
2739
+ throw new ConfigurationError(`Schema directory not found. Tried: ${possiblePaths.join(", ")}`, configPath, [
2740
+ "schema.directory"
2741
+ ]);
2742
+ }
2743
+ }
2744
+ async function loadConfig(options = {}) {
2745
+ let config = { ...DEFAULT_CONFIG5 };
2746
+ let configFilePath;
2747
+ const cwd = process.cwd();
2748
+ if (options.config) {
2749
+ const explicitPath = path4__namespace.resolve(cwd, options.config);
2750
+ if (!fs4__namespace.existsSync(explicitPath)) {
2751
+ throw new ConfigurationError(`Configuration file not found: ${explicitPath}`, explicitPath);
2752
+ }
2753
+ configFilePath = explicitPath;
2754
+ } else {
2755
+ const searchDirs = [cwd, path4__namespace.join(cwd, "shared")];
2756
+ for (const dir of searchDirs) {
2757
+ if (fs4__namespace.existsSync(dir)) {
2758
+ const found = findConfigFile(dir);
2759
+ if (found) {
2760
+ configFilePath = found;
2761
+ break;
2762
+ }
2763
+ }
2764
+ }
2765
+ }
2766
+ if (configFilePath) {
2767
+ const fileConfig = await loadConfigFile(configFilePath);
2768
+ if (fileConfig) {
2769
+ config = mergeConfig4(config, fileConfig);
2770
+ }
2771
+ }
2772
+ const envConfig = loadConfigFromEnv();
2773
+ if (Object.keys(envConfig).length > 0) {
2774
+ config = mergeConfig4(config, envConfig);
2775
+ }
2776
+ const argsConfig = loadConfigFromArgs(options);
2777
+ if (Object.keys(argsConfig).length > 0) {
2778
+ config = mergeConfig4(config, argsConfig);
2779
+ }
2780
+ validateConfig(config, configFilePath);
2781
+ return config;
2782
+ }
2783
+ function getSchemaDirectory(config) {
2784
+ const cwd = process.cwd();
2785
+ const possiblePaths = [
2786
+ path4__namespace.resolve(cwd, config.schema.directory),
2787
+ path4__namespace.resolve(cwd, "shared", config.schema.directory)
2788
+ ];
2789
+ return possiblePaths.find((p) => fs4__namespace.existsSync(p)) || possiblePaths[0];
2790
+ }
2791
+ function getMigrationsDirectory(config) {
2792
+ const cwd = process.cwd();
2793
+ const possiblePaths = [
2794
+ path4__namespace.resolve(cwd, config.migrations.directory),
2795
+ path4__namespace.resolve(cwd, "shared", config.migrations.directory)
2796
+ ];
2797
+ return possiblePaths.find((p) => fs4__namespace.existsSync(p)) || possiblePaths[0];
2798
+ }
2799
+ var currentVerbosity = "normal";
2800
+ function setVerbosity(level) {
2801
+ currentVerbosity = level;
2802
+ }
2803
+ function shouldLog(requiredLevel) {
2804
+ const levels = ["quiet", "normal", "verbose"];
2805
+ const currentIndex = levels.indexOf(currentVerbosity);
2806
+ const requiredIndex = levels.indexOf(requiredLevel);
2807
+ return currentIndex >= requiredIndex;
2808
+ }
2809
+ function createSpinner(text) {
2810
+ if (currentVerbosity === "quiet") {
2811
+ return ora__default.default({ text, isSilent: true });
2812
+ }
2813
+ return ora__default.default(text);
2814
+ }
2815
+ function logSuccess(message) {
2816
+ if (shouldLog("normal")) {
2817
+ console.log(chalk__default.default.green("\u2713"), message);
2818
+ }
2819
+ }
2820
+ function logError(message) {
2821
+ console.error(chalk__default.default.red("\u2717"), message);
2822
+ }
2823
+ function logWarning(message) {
2824
+ if (shouldLog("normal")) {
2825
+ console.warn(chalk__default.default.yellow("\u26A0"), message);
2826
+ }
2827
+ }
2828
+ function logInfo(message) {
2829
+ if (shouldLog("normal")) {
2830
+ console.log(chalk__default.default.blue("\u2139"), message);
2831
+ }
2832
+ }
2833
+ function logDebug(message) {
2834
+ if (shouldLog("verbose")) {
2835
+ console.log(chalk__default.default.gray("\u2699"), chalk__default.default.gray(message));
2836
+ }
2837
+ }
2838
+ function logSection(title) {
2839
+ if (shouldLog("normal")) {
2840
+ console.log();
2841
+ console.log(chalk__default.default.bold.cyan(title));
2842
+ console.log(chalk__default.default.cyan("\u2500".repeat(title.length)));
2843
+ }
2844
+ }
2845
+ function formatFieldChange(change) {
2846
+ const oldValue = change.oldValue === null ? "null" : JSON.stringify(change.oldValue);
2847
+ const newValue = change.newValue === null ? "null" : JSON.stringify(change.newValue);
2848
+ return `${change.property}: ${chalk__default.default.red(oldValue)} \u2192 ${chalk__default.default.green(newValue)}`;
2849
+ }
2850
+ function formatChangeSummary(diff) {
2851
+ const lines = [];
2852
+ const totalCollectionsToCreate = diff.collectionsToCreate.length;
2853
+ const totalCollectionsToDelete = diff.collectionsToDelete.length;
2854
+ const totalCollectionsToModify = diff.collectionsToModify.length;
2855
+ const totalChanges = totalCollectionsToCreate + totalCollectionsToDelete + totalCollectionsToModify;
2856
+ if (totalChanges === 0) {
2857
+ return chalk__default.default.gray("No changes detected");
2858
+ }
2859
+ lines.push(chalk__default.default.bold(`Found ${totalChanges} collection change(s):`));
2860
+ lines.push("");
2861
+ if (totalCollectionsToCreate > 0) {
2862
+ lines.push(chalk__default.default.green.bold(`\u2713 ${totalCollectionsToCreate} collection(s) to create:`));
2863
+ for (const collection of diff.collectionsToCreate) {
2864
+ lines.push(chalk__default.default.green(` + ${collection.name} (${collection.type})`));
2865
+ lines.push(chalk__default.default.gray(` ${collection.fields.length} field(s)`));
2866
+ }
2867
+ lines.push("");
2868
+ }
2869
+ if (totalCollectionsToDelete > 0) {
2870
+ lines.push(chalk__default.default.red.bold(`\u2717 ${totalCollectionsToDelete} collection(s) to delete:`));
2871
+ for (const collection of diff.collectionsToDelete) {
2872
+ lines.push(chalk__default.default.red(` - ${collection.name}`));
2873
+ }
2874
+ lines.push("");
2875
+ }
2876
+ if (totalCollectionsToModify > 0) {
2877
+ lines.push(chalk__default.default.yellow.bold(`\u26A1 ${totalCollectionsToModify} collection(s) to modify:`));
2878
+ for (const modification of diff.collectionsToModify) {
2879
+ lines.push(chalk__default.default.yellow(` ~ ${modification.collection}`));
2880
+ if (modification.fieldsToAdd.length > 0) {
2881
+ lines.push(chalk__default.default.green(` + ${modification.fieldsToAdd.length} field(s) to add:`));
2882
+ for (const field of modification.fieldsToAdd) {
2883
+ lines.push(chalk__default.default.green(` + ${field.name} (${field.type})`));
2884
+ }
2885
+ }
2886
+ if (modification.fieldsToRemove.length > 0) {
2887
+ lines.push(chalk__default.default.red(` - ${modification.fieldsToRemove.length} field(s) to remove:`));
2888
+ for (const field of modification.fieldsToRemove) {
2889
+ lines.push(chalk__default.default.red(` - ${field.name}`));
2890
+ }
2891
+ }
2892
+ if (modification.fieldsToModify.length > 0) {
2893
+ lines.push(chalk__default.default.yellow(` ~ ${modification.fieldsToModify.length} field(s) to modify:`));
2894
+ for (const fieldMod of modification.fieldsToModify) {
2895
+ lines.push(chalk__default.default.yellow(` ~ ${fieldMod.fieldName}`));
2896
+ for (const change of fieldMod.changes) {
2897
+ lines.push(chalk__default.default.gray(` ${formatFieldChange(change)}`));
2898
+ }
2899
+ }
2900
+ }
2901
+ if (modification.indexesToAdd.length > 0) {
2902
+ lines.push(chalk__default.default.green(` + ${modification.indexesToAdd.length} index(es) to add`));
2903
+ }
2904
+ if (modification.indexesToRemove.length > 0) {
2905
+ lines.push(chalk__default.default.red(` - ${modification.indexesToRemove.length} index(es) to remove`));
2906
+ }
2907
+ if (modification.rulesToUpdate.length > 0) {
2908
+ lines.push(chalk__default.default.yellow(` ~ ${modification.rulesToUpdate.length} rule(s) to update`));
2909
+ }
2910
+ lines.push("");
2911
+ }
2912
+ }
2913
+ return lines.join("\n");
2914
+ }
2915
+ async function withProgress(message, operation) {
2916
+ const spinner = createSpinner(message).start();
2917
+ try {
2918
+ const result = await operation();
2919
+ spinner.succeed();
2920
+ return result;
2921
+ } catch (error) {
2922
+ spinner.fail();
2923
+ throw error;
2924
+ }
2925
+ }
2926
+ function logKeyValue(key, value, indent = 2) {
2927
+ if (shouldLog("normal")) {
2928
+ const padding = " ".repeat(indent);
2929
+ console.log(`${padding}${chalk__default.default.gray(key + ":")} ${value}`);
2930
+ }
2931
+ }
2932
+ function logTable(headers, rows) {
2933
+ if (!shouldLog("normal")) return;
2934
+ const widths = headers.map((h, i) => {
2935
+ const maxRowWidth = Math.max(...rows.map((r) => (r[i] || "").length));
2936
+ return Math.max(h.length, maxRowWidth);
2937
+ });
2938
+ const headerLine = headers.map((h, i) => h.padEnd(widths[i])).join(" ");
2939
+ console.log(chalk__default.default.bold(headerLine));
2940
+ console.log(chalk__default.default.gray("\u2500".repeat(headerLine.length)));
2941
+ for (const row of rows) {
2942
+ const rowLine = row.map((cell, i) => (cell || "").padEnd(widths[i])).join(" ");
2943
+ console.log(rowLine);
2944
+ }
2945
+ }
2946
+ function formatStatusJson(output) {
2947
+ return JSON.stringify(output, null, 2);
2948
+ }
2949
+
2950
+ // src/cli/commands/generate.ts
2951
+ function hasChanges2(diff) {
2952
+ return diff.collectionsToCreate.length > 0 || diff.collectionsToDelete.length > 0 || diff.collectionsToModify.length > 0;
2953
+ }
2954
+ function handleDestructiveChanges(diff, config, force) {
2955
+ const destructiveChanges = detectDestructiveChanges(diff);
2956
+ if (destructiveChanges.length === 0) {
2957
+ return true;
2958
+ }
2959
+ logSection("\u26A0\uFE0F Destructive Changes Detected");
2960
+ console.log();
2961
+ console.log(formatDestructiveChanges(destructiveChanges));
2962
+ const summary = summarizeDestructiveChanges(destructiveChanges);
2963
+ console.log("Summary:");
2964
+ console.log(` Total: ${summary.total} destructive change(s)`);
2965
+ if (summary.high > 0) {
2966
+ console.log(` High Severity: ${summary.high}`);
2967
+ }
2968
+ if (summary.medium > 0) {
2969
+ console.log(` Medium Severity: ${summary.medium}`);
2970
+ }
2971
+ if (summary.low > 0) {
2972
+ console.log(` Low Severity: ${summary.low}`);
2973
+ }
2974
+ console.log();
2975
+ const forceRequired = config.diff.requireForceForDestructive && requiresForceFlag(destructiveChanges);
2976
+ if (forceRequired && !force) {
2977
+ logError("Destructive changes require the --force flag to proceed.");
2978
+ console.log();
2979
+ logInfo("To proceed with these changes, run the command again with --force:");
2980
+ console.log(" yarn migrate:generate --force");
2981
+ console.log();
2982
+ logWarning("\u26A0\uFE0F WARNING: Using --force will apply these changes and may result in data loss!");
2983
+ return false;
2984
+ }
2985
+ if (force) {
2986
+ logWarning("Proceeding with destructive changes (--force flag provided)");
2987
+ console.log();
2988
+ }
2989
+ return true;
2990
+ }
2991
+ async function executeGenerate(options) {
2992
+ try {
2993
+ const parentOpts = options.parent?.opts?.() || {};
2994
+ if (parentOpts.verbose) {
2995
+ setVerbosity("verbose");
2996
+ } else if (parentOpts.quiet) {
2997
+ setVerbosity("quiet");
2998
+ }
2999
+ logDebug("Starting migration generation...");
3000
+ logDebug(`Options: ${JSON.stringify(options, null, 2)}`);
3001
+ const config = await loadConfig(options);
3002
+ const schemaDir = getSchemaDirectory(config);
3003
+ const migrationsDir = getMigrationsDirectory(config);
3004
+ logSection("\u{1F50D} Analyzing Schema");
3005
+ const currentSchema = await withProgress("Parsing Zod schemas...", () => parseSchemaFiles(schemaDir));
3006
+ logSuccess(`Found ${currentSchema.collections.size} collection(s)`);
3007
+ logInfo("Loading previous snapshot...");
3008
+ const previousSnapshot = loadSnapshotIfExists({
3009
+ migrationsPath: migrationsDir,
3010
+ workspaceRoot: process.cwd()
3011
+ });
3012
+ if (!previousSnapshot) {
3013
+ logInfo("No previous snapshot found - treating as empty database (first-time generation)");
3014
+ } else {
3015
+ logSuccess("Loaded previous snapshot as base reference");
3016
+ }
3017
+ logSection("\u{1F4CA} Comparing Schemas");
3018
+ const diff = compare(currentSchema, previousSnapshot);
3019
+ if (!hasChanges2(diff)) {
3020
+ logInfo("No changes detected");
3021
+ console.log();
3022
+ logSuccess("Schema is up to date!");
3023
+ return;
3024
+ }
3025
+ console.log();
3026
+ console.log(formatChangeSummary(diff));
3027
+ if (!handleDestructiveChanges(diff, config, options.force)) {
3028
+ process.exit(1);
3029
+ }
3030
+ logSection("\u{1F4DD} Generating Migration");
3031
+ const migrationPath = await withProgress(
3032
+ "Creating migration file...",
3033
+ () => Promise.resolve(generate(diff, migrationsDir))
3034
+ );
3035
+ logSuccess(`Migration file created: ${path4__namespace.basename(migrationPath)}`);
3036
+ logSection("\u2705 Next Steps");
3037
+ console.log();
3038
+ console.log(" 1. Review the generated migration file:");
3039
+ console.log(` ${migrationPath}`);
3040
+ console.log();
3041
+ console.log(" 2. Apply the migration by running PocketBase:");
3042
+ console.log(" yarn pb");
3043
+ console.log();
3044
+ console.log(" Or apply migrations manually:");
3045
+ console.log(" cd pb && ./pocketbase migrate up");
3046
+ console.log();
3047
+ } catch (error) {
3048
+ if (error instanceof SchemaParsingError) {
3049
+ logError("Schema Parsing Error");
3050
+ console.error();
3051
+ console.error(error.getDetailedMessage());
3052
+ console.error();
3053
+ logInfo("Suggestions:");
3054
+ console.log(" \u2022 Make sure your schema files are valid Zod schemas");
3055
+ console.log(' \u2022 Run "yarn build" in the shared workspace to compile TypeScript files');
3056
+ console.log(' \u2022 Check that schema files export schemas ending with "Schema" or "InputSchema"');
3057
+ } else if (error instanceof SnapshotError) {
3058
+ logError("Snapshot Error");
3059
+ console.error();
3060
+ console.error(error.getDetailedMessage());
3061
+ console.error();
3062
+ logInfo("Suggestions:");
3063
+ console.log(" \u2022 Check that the snapshot file is not corrupted");
3064
+ console.log(" \u2022 Verify file permissions for the snapshot file");
3065
+ console.log(" \u2022 If this is the first run, this error should not occur");
3066
+ } else if (error instanceof MigrationGenerationError) {
3067
+ logError("Migration Generation Error");
3068
+ console.error();
3069
+ console.error(error.getDetailedMessage());
3070
+ console.error();
3071
+ logInfo("Suggestions:");
3072
+ console.log(" \u2022 Check that the migration directory exists and is writable");
3073
+ console.log(" \u2022 Verify you have sufficient disk space");
3074
+ console.log(" \u2022 Check file permissions for the migration directory");
3075
+ } else if (error instanceof FileSystemError) {
3076
+ logError("File System Error");
3077
+ console.error();
3078
+ console.error(error.getDetailedMessage());
3079
+ console.error();
3080
+ logInfo("Suggestions:");
3081
+ console.log(" \u2022 Check file and directory permissions");
3082
+ console.log(" \u2022 Verify you have sufficient disk space");
3083
+ console.log(" \u2022 Ensure the paths are correct and accessible");
3084
+ } else if (error instanceof ConfigurationError) {
3085
+ logError("Configuration Error");
3086
+ console.error();
3087
+ console.error(error.getDetailedMessage());
3088
+ console.error();
3089
+ logInfo("Suggestions:");
3090
+ console.log(" \u2022 Check your configuration file syntax");
3091
+ console.log(" \u2022 Verify all paths are correct and accessible");
3092
+ console.log(" \u2022 Run with --verbose flag for more details");
3093
+ } else {
3094
+ logError(`Failed to generate migration: ${error}`);
3095
+ if (error instanceof Error && error.stack) {
3096
+ console.error();
3097
+ console.error(error.stack);
3098
+ }
3099
+ }
3100
+ console.error();
3101
+ process.exit(1);
3102
+ }
3103
+ }
3104
+ function createGenerateCommand() {
3105
+ return new commander.Command("generate").description("Generate a migration from schema changes").option("-o, --output <directory>", "Output directory for migration files").option("-f, --force", "Force generation even with destructive changes", false).option("--dry-run", "Show what would be generated without creating files", false).option("--schema-dir <directory>", "Directory containing Zod schema files").addHelpText(
3106
+ "after",
3107
+ `
3108
+ Examples:
3109
+ $ pocketbase-migrate generate Generate migration from schema changes
3110
+ $ pocketbase-migrate generate --force Force generation with destructive changes
3111
+ $ pocketbase-migrate generate --dry-run Preview changes without generating files
3112
+ $ pocketbase-migrate generate -o ./migrations Specify output directory
3113
+ `
3114
+ ).action(executeGenerate);
3115
+ }
3116
+ function hasChanges3(diff) {
3117
+ return diff.collectionsToCreate.length > 0 || diff.collectionsToDelete.length > 0 || diff.collectionsToModify.length > 0;
3118
+ }
3119
+ function hasDestructiveChanges(diff) {
3120
+ const { destructive } = categorizeChangesBySeverity(diff);
3121
+ return destructive.length > 0;
3122
+ }
3123
+ function createStatusOutput(status, currentCount, snapshotCount, diff) {
3124
+ return {
3125
+ status,
3126
+ collections: {
3127
+ current: currentCount,
3128
+ snapshot: snapshotCount
3129
+ },
3130
+ changes: {
3131
+ create: diff?.collectionsToCreate.length ?? 0,
3132
+ delete: diff?.collectionsToDelete.length ?? 0,
3133
+ modify: diff?.collectionsToModify.length ?? 0
3134
+ },
3135
+ destructive: diff ? hasDestructiveChanges(diff) : false
3136
+ };
3137
+ }
3138
+ function displayDestructiveChangesSummary(diff) {
3139
+ const { destructive, nonDestructive } = categorizeChangesBySeverity(diff);
3140
+ if (destructive.length > 0) {
3141
+ logSection("\u26A0\uFE0F Destructive Changes");
3142
+ console.log();
3143
+ for (const change of destructive) {
3144
+ console.log(chalk__default.default.red(` ${change}`));
3145
+ }
3146
+ console.log();
3147
+ }
3148
+ if (nonDestructive.length > 0) {
3149
+ logSection("\u2713 Non-Destructive Changes");
3150
+ console.log();
3151
+ for (const change of nonDestructive) {
3152
+ console.log(chalk__default.default.green(` ${change}`));
3153
+ }
3154
+ console.log();
3155
+ }
3156
+ }
3157
+ function displayChangeTable(diff) {
3158
+ const rows = [];
3159
+ for (const collection of diff.collectionsToCreate) {
3160
+ rows.push([
3161
+ chalk__default.default.green("+"),
3162
+ collection.name,
3163
+ collection.type,
3164
+ `${collection.fields.length} fields`,
3165
+ chalk__default.default.green("Create")
3166
+ ]);
3167
+ }
3168
+ for (const collection of diff.collectionsToDelete) {
3169
+ rows.push([chalk__default.default.red("-"), collection.name, collection.type || "base", "-", chalk__default.default.red("Delete")]);
3170
+ }
3171
+ for (const mod of diff.collectionsToModify) {
3172
+ const changes = [];
3173
+ if (mod.fieldsToAdd.length > 0) changes.push(`+${mod.fieldsToAdd.length} fields`);
3174
+ if (mod.fieldsToRemove.length > 0) changes.push(`-${mod.fieldsToRemove.length} fields`);
3175
+ if (mod.fieldsToModify.length > 0) changes.push(`~${mod.fieldsToModify.length} fields`);
3176
+ if (mod.indexesToAdd.length > 0) changes.push(`+${mod.indexesToAdd.length} indexes`);
3177
+ if (mod.indexesToRemove.length > 0) changes.push(`-${mod.indexesToRemove.length} indexes`);
3178
+ if (mod.rulesToUpdate.length > 0) changes.push(`~${mod.rulesToUpdate.length} rules`);
3179
+ rows.push([chalk__default.default.yellow("~"), mod.collection, "-", changes.join(", ") || "No changes", chalk__default.default.yellow("Modify")]);
3180
+ }
3181
+ if (rows.length > 0) {
3182
+ logTable(["", "Collection", "Type", "Changes", "Action"], rows);
3183
+ }
3184
+ }
3185
+ async function executeStatus(options) {
3186
+ const isJsonMode = options.json === true;
3187
+ try {
3188
+ if (isJsonMode) {
3189
+ setVerbosity("quiet");
3190
+ } else {
3191
+ const parentOpts = options.parent?.opts?.() || {};
3192
+ if (parentOpts.verbose) {
3193
+ setVerbosity("verbose");
3194
+ } else if (parentOpts.quiet) {
3195
+ setVerbosity("quiet");
3196
+ }
3197
+ }
3198
+ logDebug("Checking migration status...");
3199
+ logDebug(`Options: ${JSON.stringify(options, null, 2)}`);
3200
+ const config = await loadConfig(options);
3201
+ const schemaDir = getSchemaDirectory(config);
3202
+ const migrationsDir = getMigrationsDirectory(config);
3203
+ logSection("\u{1F50D} Checking Migration Status");
3204
+ const currentSchema = await withProgress("Parsing Zod schemas...", () => parseSchemaFiles(schemaDir));
3205
+ logSuccess(`Found ${currentSchema.collections.size} collection(s) in schema`);
3206
+ logInfo("Loading previous snapshot...");
3207
+ const previousSnapshot = loadSnapshotIfExists({
3208
+ migrationsPath: migrationsDir,
3209
+ workspaceRoot: process.cwd()
3210
+ });
3211
+ if (!previousSnapshot) {
3212
+ if (isJsonMode) {
3213
+ const output = createStatusOutput("first-time-setup", currentSchema.collections.size, 0);
3214
+ console.log(formatStatusJson(output));
3215
+ return;
3216
+ }
3217
+ logSection("\u{1F195} First-Time Setup Detected");
3218
+ console.log();
3219
+ logInfo("No previous snapshot found. This appears to be a first-time setup.");
3220
+ console.log();
3221
+ logKeyValue("Collections in schema", String(currentSchema.collections.size));
3222
+ console.log();
3223
+ logInfo('Run "pocketbase-migrate generate" to create the initial migration.');
3224
+ return;
3225
+ }
3226
+ logSuccess(`Loaded snapshot with ${previousSnapshot.collections.size} collection(s)`);
3227
+ logSection("\u{1F4CA} Schema Comparison");
3228
+ const diff = compare(currentSchema, previousSnapshot);
3229
+ if (!hasChanges3(diff)) {
3230
+ if (isJsonMode) {
3231
+ const output = createStatusOutput(
3232
+ "up-to-date",
3233
+ currentSchema.collections.size,
3234
+ previousSnapshot.collections.size,
3235
+ diff
3236
+ );
3237
+ console.log(formatStatusJson(output));
3238
+ return;
3239
+ }
3240
+ console.log();
3241
+ logSuccess("\u2713 Schema is in sync with snapshot");
3242
+ logInfo("No pending changes detected");
3243
+ console.log();
3244
+ logKeyValue("Collections", String(currentSchema.collections.size));
3245
+ return;
3246
+ }
3247
+ if (isJsonMode) {
3248
+ const output = createStatusOutput(
3249
+ "changes-pending",
3250
+ currentSchema.collections.size,
3251
+ previousSnapshot.collections.size,
3252
+ diff
3253
+ );
3254
+ console.log(formatStatusJson(output));
3255
+ return;
3256
+ }
3257
+ console.log();
3258
+ console.log(formatChangeSummary(diff));
3259
+ logDebug("Detailed change table:");
3260
+ displayChangeTable(diff);
3261
+ displayDestructiveChangesSummary(diff);
3262
+ logSection("\u{1F4DD} Next Steps");
3263
+ console.log();
3264
+ console.log(" To generate a migration for these changes, run:");
3265
+ console.log(chalk__default.default.cyan(" pocketbase-migrate generate"));
3266
+ console.log();
3267
+ const { destructive } = categorizeChangesBySeverity(diff);
3268
+ if (destructive.length > 0) {
3269
+ console.log(chalk__default.default.yellow(" \u26A0\uFE0F Destructive changes detected. Use --force flag when generating:"));
3270
+ console.log(chalk__default.default.cyan(" pocketbase-migrate generate --force"));
3271
+ console.log();
3272
+ }
3273
+ } catch (error) {
3274
+ if (error instanceof SchemaParsingError) {
3275
+ logError("Schema Parsing Error");
3276
+ console.error();
3277
+ console.error(error.getDetailedMessage());
3278
+ console.error();
3279
+ logInfo("Suggestions:");
3280
+ console.log(" \u2022 Make sure your schema files are valid Zod schemas");
3281
+ console.log(' \u2022 Check that schema files export schemas ending with "Schema" or "InputSchema"');
3282
+ } else if (error instanceof SnapshotError) {
3283
+ logError("Snapshot Error");
3284
+ console.error();
3285
+ console.error(error.getDetailedMessage());
3286
+ console.error();
3287
+ logInfo("Suggestions:");
3288
+ console.log(" \u2022 Check that the snapshot file is not corrupted");
3289
+ console.log(" \u2022 Verify file permissions for the snapshot file");
3290
+ } else if (error instanceof ConfigurationError) {
3291
+ logError("Configuration Error");
3292
+ console.error();
3293
+ console.error(error.getDetailedMessage());
3294
+ console.error();
3295
+ logInfo("Suggestions:");
3296
+ console.log(" \u2022 Check your configuration file syntax");
3297
+ console.log(" \u2022 Verify all paths are correct and accessible");
3298
+ } else {
3299
+ logError(`Failed to check status: ${error}`);
3300
+ if (error instanceof Error && error.stack) {
3301
+ console.error(error.stack);
3302
+ }
3303
+ }
3304
+ process.exit(1);
3305
+ }
3306
+ }
3307
+ function createStatusCommand() {
3308
+ return new commander.Command("status").description("Show current migration status without generating files").option("--schema-dir <directory>", "Directory containing Zod schema files").option("--json", "Output status as JSON for programmatic use", false).addHelpText(
3309
+ "after",
3310
+ `
3311
+ Examples:
3312
+ $ pocketbase-migrate status Check for pending schema changes
3313
+ $ pocketbase-migrate status --json Output status as JSON
3314
+ $ pocketbase-migrate status --verbose Show detailed status information
3315
+ `
3316
+ ).action(executeStatus);
3317
+ }
3318
+
3319
+ // src/cli/migrate.ts
3320
+ var VERSION = "0.1.0";
3321
+ function displayBanner() {
3322
+ console.log();
3323
+ console.log(chalk__default.default.cyan.bold(" PocketBase Zod Migration Tool"));
3324
+ console.log(chalk__default.default.gray(` Version ${VERSION}`));
3325
+ console.log();
3326
+ }
3327
+ var program = new commander.Command();
3328
+ program.name("pocketbase-migrate").description(
3329
+ "Schema-driven PocketBase migration tool\n\nGenerate type-safe migrations from Zod schemas for PocketBase applications."
3330
+ ).version(VERSION, "-v, --version", "Output the current version").option("-c, --config <path>", "Path to configuration file").option("--verbose", "Enable verbose output").option("--quiet", "Suppress non-essential output").option("--no-color", "Disable colored output").hook("preAction", (thisCommand) => {
3331
+ const opts = thisCommand.opts();
3332
+ if (opts.color === false) {
3333
+ chalk__default.default.level = 0;
3334
+ }
3335
+ if (!opts.quiet) {
3336
+ displayBanner();
3337
+ }
3338
+ });
3339
+ program.addCommand(createGenerateCommand());
3340
+ program.addCommand(createStatusCommand());
3341
+ program.addHelpText(
3342
+ "after",
3343
+ `
3344
+ ${chalk__default.default.bold("Examples:")}
3345
+ $ pocketbase-migrate status Check for pending schema changes
3346
+ $ pocketbase-migrate generate Generate migration from schema changes
3347
+ $ pocketbase-migrate generate --force Generate migration with destructive changes
3348
+ $ pocketbase-migrate --help Show this help message
3349
+
3350
+ ${chalk__default.default.bold("Configuration:")}
3351
+ The tool looks for configuration in the following order:
3352
+ 1. CLI arguments (highest priority)
3353
+ 2. Environment variables (MIGRATION_SCHEMA_DIR, MIGRATION_OUTPUT_DIR, etc.)
3354
+ 3. Configuration file (migrate.config.js)
3355
+ 4. Default values
3356
+
3357
+ ${chalk__default.default.bold("Documentation:")}
3358
+ For more information, visit: https://github.com/dastron/pocketbase-zod-schema
3359
+ `
3360
+ );
3361
+ program.exitOverride((err) => {
3362
+ const anyErr = err;
3363
+ if (anyErr?.code === "commander.help" || anyErr?.code === "commander.helpDisplayed") {
3364
+ process.exit(0);
3365
+ }
3366
+ if (anyErr?.code === "commander.version") {
3367
+ process.exit(0);
3368
+ }
3369
+ if (typeof anyErr?.exitCode === "number") {
3370
+ process.exit(anyErr.exitCode);
3371
+ }
3372
+ process.exit(1);
3373
+ });
3374
+ if (process.argv.length === 2) {
3375
+ displayBanner();
3376
+ program.help();
3377
+ }
3378
+ program.parse(process.argv);
3379
+ //# sourceMappingURL=migrate.cjs.map
3380
+ //# sourceMappingURL=migrate.cjs.map