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