@asaidimu/anansi 1.2.0 → 1.2.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 (5) hide show
  1. package/index.cjs +46 -1415
  2. package/index.d.cts +98 -2
  3. package/index.d.ts +98 -2
  4. package/index.js +46 -1364
  5. package/package.json +1 -1
package/index.js CHANGED
@@ -1,1364 +1,46 @@
1
- // src/lib/persistence/index.ts
2
- import { createEventBus as createEventBus2 } from "@asaidimu/events";
3
-
4
- // src/lib/persistence/collection.ts
5
- import { createEventBus } from "@asaidimu/events";
6
- import {
7
- createMatcher,
8
- createPaginator,
9
- createProjector,
10
- createSorter
11
- } from "@asaidimu/query";
12
-
13
- // src/tools/patch.ts
14
- var JsonPatchError = class extends Error {
15
- constructor(message, operation) {
16
- super(message);
17
- this.operation = operation;
18
- this.name = "JsonPatchError";
19
- }
20
- };
21
- function parseJsonPointer(path) {
22
- const normalized = normalizePath(path);
23
- if (normalized === "") return [];
24
- return normalized.substring(1).split("/").map(unescapeJsonPointer);
25
- }
26
- function normalizePath(path) {
27
- if (path === "" || path === "/") return "";
28
- if (path.startsWith("/")) {
29
- return "/" + path.substring(1).split("/").map(escapeJsonPointer).join("/");
30
- }
31
- return "/" + path.split(".").map(escapeJsonPointer).join("/");
32
- }
33
- function escapeJsonPointer(part) {
34
- return part.replace(/~/g, "~0").replace(/\//g, "~1");
35
- }
36
- function unescapeJsonPointer(part) {
37
- return part.replace(/~1/g, "/").replace(/~0/g, "~");
38
- }
39
- var pathCache = /* @__PURE__ */ new Map();
40
- function navigateTo(obj, parts) {
41
- let current = obj;
42
- for (const part of parts) {
43
- if (current === null || typeof current !== "object") {
44
- throw new JsonPatchError(`Invalid path - parent not found at ${part}`);
45
- }
46
- if (Array.isArray(current)) {
47
- const index = part === "-" ? current.length : parseInt(part);
48
- if (isNaN(index) || index < 0 || index > current.length) {
49
- throw new JsonPatchError(`Invalid array index: ${part}`);
50
- }
51
- current = current[index];
52
- } else {
53
- if (!current.hasOwnProperty(part)) {
54
- throw new JsonPatchError(`Property ${part} not found`);
55
- }
56
- current = current[part];
57
- }
58
- }
59
- return current;
60
- }
61
- function getValueAtPath(obj, path) {
62
- const parts = pathCache.get(path) || parseJsonPointer(path);
63
- pathCache.set(path, parts);
64
- if (parts.length === 0) return obj;
65
- const parent = navigateTo(obj, parts.slice(0, -1));
66
- const key = parts[parts.length - 1];
67
- if (Array.isArray(parent)) {
68
- const index = parseInt(key);
69
- if (isNaN(index) || index < 0 || index >= parent.length) {
70
- throw new JsonPatchError(`Invalid array index: ${key}`);
71
- }
72
- return parent[index];
73
- }
74
- return parent[key];
75
- }
76
- function applyRemoveValue(obj, path, value) {
77
- const parts = pathCache.get(path) || parseJsonPointer(path);
78
- pathCache.set(path, parts);
79
- const parent = navigateTo(obj, parts.slice(0, -1));
80
- const key = parts[parts.length - 1];
81
- if (Array.isArray(parent)) {
82
- parent.splice(0, parent.length, ...parent.filter((item) => item !== value));
83
- } else {
84
- if (parent[key] === value) {
85
- delete parent[key];
86
- }
87
- }
88
- return obj;
89
- }
90
- function applyAdd(obj, path, value) {
91
- const parts = pathCache.get(path) || parseJsonPointer(path);
92
- pathCache.set(path, parts);
93
- if (parts.length === 0) return value;
94
- const parentPath = parts.slice(0, -1);
95
- const key = parts[parts.length - 1];
96
- const parent = navigateTo(obj, parentPath);
97
- if (Array.isArray(parent)) {
98
- if (key === "-") {
99
- parent.push(value);
100
- } else {
101
- const index = parseInt(key);
102
- if (index < 0 || index > parent.length) {
103
- throw new JsonPatchError(`Invalid array index: ${key}`);
104
- }
105
- parent.splice(index, 0, value);
106
- }
107
- } else {
108
- parent[key] = value;
109
- }
110
- return obj;
111
- }
112
- function applyRemove(obj, path) {
113
- const parts = pathCache.get(path) || parseJsonPointer(path);
114
- pathCache.set(path, parts);
115
- if (parts.length === 0) return void 0;
116
- const parent = navigateTo(obj, parts.slice(0, -1));
117
- const key = parts[parts.length - 1];
118
- if (Array.isArray(parent)) {
119
- const index = parseInt(key);
120
- parent.splice(index, 1);
121
- } else {
122
- delete parent[key];
123
- }
124
- return obj;
125
- }
126
- function applyPatch(target, patches) {
127
- let result = JSON.parse(JSON.stringify(target));
128
- for (const patch of patches) {
129
- try {
130
- switch (patch.op) {
131
- case "add":
132
- result = applyAdd(result, patch.path, patch.value);
133
- break;
134
- case "remove":
135
- result = applyRemove(result, patch.path);
136
- break;
137
- case "removeValue":
138
- result = applyRemoveValue(result, patch.path, patch.value);
139
- break;
140
- case "replace":
141
- result = applyAdd(
142
- applyRemove(result, patch.path),
143
- patch.path,
144
- patch.value
145
- );
146
- break;
147
- case "copy": {
148
- const value = getValueAtPath(result, patch.from);
149
- result = applyAdd(
150
- result,
151
- patch.path,
152
- JSON.parse(JSON.stringify(value))
153
- );
154
- break;
155
- }
156
- case "move": {
157
- const value = getValueAtPath(result, patch.from);
158
- result = applyAdd(result, patch.path, value);
159
- result = applyRemove(result, patch.from);
160
- break;
161
- }
162
- case "test": {
163
- const actual = getValueAtPath(result, patch.path);
164
- if (JSON.stringify(actual) !== JSON.stringify(patch.value)) {
165
- throw new JsonPatchError("Test operation failed");
166
- }
167
- break;
168
- }
169
- default:
170
- throw new JsonPatchError(
171
- `Unsupported operation: ${patch.op}`
172
- );
173
- }
174
- } catch (error) {
175
- if (error instanceof JsonPatchError) {
176
- error.operation = patch;
177
- }
178
- throw error;
179
- }
180
- }
181
- return result;
182
- }
183
- function createPatch(oldObj, newObj) {
184
- const patches = [];
185
- generatePatches(oldObj, newObj, "", patches);
186
- return patches;
187
- }
188
- function generatePatches(oldObj, newObj, path, patches) {
189
- if (oldObj === newObj) return;
190
- if (typeof oldObj !== typeof newObj || Array.isArray(oldObj) !== Array.isArray(newObj)) {
191
- patches.push({ op: "replace", path, value: newObj });
192
- return;
193
- }
194
- if (typeof oldObj === "object" && oldObj !== null) {
195
- if (Array.isArray(oldObj)) {
196
- handleArrays(oldObj, newObj, path, patches);
197
- } else {
198
- handleObjects(oldObj, newObj, path, patches);
199
- }
200
- } else if (oldObj !== newObj) {
201
- patches.push({ op: "replace", path, value: newObj });
202
- }
203
- }
204
- function handleArrays(oldArr, newArr, path, patches) {
205
- const maxLen = Math.max(oldArr.length, newArr.length);
206
- for (let i = 0; i < maxLen; i++) {
207
- const currentPath = `${path}/${i}`;
208
- if (i >= oldArr.length) {
209
- patches.push({ op: "add", path: `${path}/-`, value: newArr[i] });
210
- } else if (i >= newArr.length) {
211
- patches.push({ op: "remove", path: currentPath });
212
- } else {
213
- generatePatches(oldArr[i], newArr[i], currentPath, patches);
214
- }
215
- }
216
- }
217
- function handleObjects(oldObj, newObj, path, patches) {
218
- const seen = /* @__PURE__ */ new Set();
219
- const oldKeys = Object.keys(oldObj);
220
- const newKeys = Object.keys(newObj);
221
- for (const key of oldKeys) {
222
- const escapedKey = escapeJsonPointer(key);
223
- const currentPath = path ? `${path}/${escapedKey}` : `/${escapedKey}`;
224
- if (!newObj.hasOwnProperty(key)) {
225
- patches.push({ op: "remove", path: currentPath });
226
- } else {
227
- generatePatches(
228
- oldObj[key],
229
- newObj[key],
230
- currentPath,
231
- patches
232
- );
233
- seen.add(key);
234
- }
235
- }
236
- for (const key of newKeys) {
237
- if (!seen.has(key)) {
238
- const escapedKey = escapeJsonPointer(key);
239
- const currentPath = path ? `${path}/${escapedKey}` : `/${escapedKey}`;
240
- patches.push({
241
- op: "add",
242
- path: currentPath,
243
- value: newObj[key]
244
- });
245
- }
246
- }
247
- }
248
- function schemaChangeToPatch(change, schema) {
249
- const patches = [];
250
- switch (change.type) {
251
- case "addField":
252
- patches.push({
253
- op: "add",
254
- path: `/fields/${change.name}`,
255
- value: change.definition
256
- });
257
- break;
258
- case "removeField":
259
- patches.push({
260
- op: "remove",
261
- path: `/fields/${change.name}`
262
- });
263
- break;
264
- case "modifyField": {
265
- const fieldPath = `/fields/${change.name}`;
266
- Object.entries(change.changes).forEach(([key, value]) => {
267
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
268
- patches.push({
269
- op: "replace",
270
- path: `${fieldPath}/${key}`,
271
- value
272
- });
273
- } else {
274
- patches.push({
275
- op: "replace",
276
- path: `${fieldPath}/${key}`,
277
- value
278
- });
279
- }
280
- });
281
- break;
282
- }
283
- case "deprecateField":
284
- patches.push({
285
- op: "add",
286
- path: `/fields/${change.name}/deprecated`,
287
- value: true
288
- });
289
- break;
290
- case "addIndex":
291
- if (!schema.indexes) {
292
- patches.push({
293
- op: "add",
294
- path: "/indexes",
295
- value: []
296
- });
297
- }
298
- patches.push({
299
- op: "add",
300
- path: "/indexes/-",
301
- value: change.definition
302
- });
303
- break;
304
- case "removeIndex": {
305
- const indexIndex = schema.indexes?.findIndex(
306
- (idx) => idx.name === change.name
307
- );
308
- if (indexIndex !== void 0 && indexIndex >= 0) {
309
- patches.push({
310
- op: "remove",
311
- path: `/indexes/${indexIndex}`
312
- });
313
- }
314
- break;
315
- }
316
- case "modifyIndex": {
317
- const indexIndex = schema.indexes?.findIndex(
318
- (idx) => idx.name === change.name
319
- );
320
- if (indexIndex !== void 0 && indexIndex >= 0) {
321
- Object.entries(change.changes).forEach(([key, value]) => {
322
- patches.push({
323
- op: "replace",
324
- path: `/indexes/${indexIndex}/${key}`,
325
- value
326
- });
327
- });
328
- }
329
- break;
330
- }
331
- case "addConstraint":
332
- if (!schema.constraints) {
333
- patches.push({
334
- op: "add",
335
- path: "/constraints",
336
- value: []
337
- });
338
- }
339
- if (Array.isArray(change.constraint)) {
340
- change.constraint.forEach((constraint) => {
341
- patches.push({
342
- op: "add",
343
- path: "/constraints/-",
344
- value: constraint
345
- });
346
- });
347
- } else {
348
- patches.push({
349
- op: "add",
350
- path: "/constraints/-",
351
- value: change.constraint
352
- });
353
- }
354
- break;
355
- case "removeConstraint": {
356
- const constraintIndex = schema.constraints?.findIndex(
357
- (c) => Array.isArray(c) ? c.some((rule) => rule.name === change.name) : c.name === change.name
358
- );
359
- if (constraintIndex !== void 0 && constraintIndex >= 0) {
360
- patches.push({
361
- op: "remove",
362
- path: `/constraints/${constraintIndex}`
363
- });
364
- }
365
- break;
366
- }
367
- case "modifyConstraint": {
368
- const constraintPath = findConstraintPath(schema, change.name);
369
- if (constraintPath) {
370
- Object.entries(change.changes).forEach(([key, value]) => {
371
- patches.push({
372
- op: "replace",
373
- path: `${constraintPath}/${key}`,
374
- value
375
- });
376
- });
377
- }
378
- break;
379
- }
380
- }
381
- return patches;
382
- }
383
- function findConstraintPath(schema, name) {
384
- if (!schema.constraints) return null;
385
- for (let i = 0; i < schema.constraints.length; i++) {
386
- const constraint = schema.constraints[i];
387
- if (constraint.name === name) {
388
- return `/constraints/${i}`;
389
- }
390
- if (isConstraintGroup(constraint)) {
391
- const path = searchRules(constraint.rules, name);
392
- if (path) {
393
- return `/constraints/${i}${path}`;
394
- }
395
- }
396
- }
397
- return null;
398
- }
399
- function isConstraintGroup(obj) {
400
- return obj && "operator" in obj && "rules" in obj;
401
- }
402
- function searchRules(rules, name) {
403
- for (let i = 0; i < rules.length; i++) {
404
- const rule = rules[i];
405
- if ("name" in rule && rule.name === name) {
406
- return `/rules/${i}`;
407
- }
408
- if (isConstraintGroup(rule)) {
409
- const path = searchRules(rule.rules, name);
410
- if (path) {
411
- return `/rules/${i}${path}`;
412
- }
413
- }
414
- }
415
- return null;
416
- }
417
-
418
- // src/tools/merge.ts
419
- function deepMerge(target, update) {
420
- const output = { ...target };
421
- if (isObject(target) && isObject(update)) {
422
- Object.keys(update).forEach((key) => {
423
- if (isObject(update[key])) {
424
- if (!(key in target)) {
425
- Object.assign(output, { [key]: update[key] });
426
- } else {
427
- output[key] = deepMerge(
428
- target[key],
429
- update[key]
430
- );
431
- }
432
- } else {
433
- Object.assign(output, { [key]: update[key] });
434
- }
435
- });
436
- }
437
- return output;
438
- }
439
- function isObject(item) {
440
- return item && typeof item === "object" && !Array.isArray(item);
441
- }
442
-
443
- // src/tools/validator.ts
444
- function createStandardSchemaValidator(schema, constraintsMap) {
445
- const validateTypeWithErrors = (value, fieldName, fieldDef, path) => {
446
- const issues = [];
447
- switch (fieldDef.type) {
448
- case "string":
449
- if (typeof value !== "string") {
450
- issues.push({
451
- message: `Expected type string but received ${typeof value}.`,
452
- path
453
- });
454
- }
455
- break;
456
- case "number":
457
- if (typeof value !== "number") {
458
- issues.push({
459
- message: `Expected type number but received ${typeof value}.`,
460
- path
461
- });
462
- }
463
- break;
464
- case "boolean":
465
- if (typeof value !== "boolean") {
466
- issues.push({
467
- message: `Expected type boolean but received ${typeof value}.`,
468
- path
469
- });
470
- }
471
- break;
472
- case "array":
473
- if (!Array.isArray(value)) {
474
- issues.push({
475
- message: `Expected an array but received ${typeof value}.`,
476
- path
477
- });
478
- } else if (!fieldDef.itemsType) {
479
- issues.push({
480
- message: `Expected itemsType for array ${fieldName}`,
481
- path
482
- });
483
- } else {
484
- value.forEach((item, index) => {
485
- issues.push(
486
- ...validateTypeWithErrors(
487
- item,
488
- `Array: ${fieldName}`,
489
- {
490
- type: fieldDef.itemsType,
491
- nestedSchema: fieldDef.nestedSchema
492
- },
493
- [...path, index]
494
- )
495
- );
496
- });
497
- }
498
- break;
499
- case "object":
500
- if (typeof value !== "object" || value === null) {
501
- issues.push({
502
- message: `Expected an object but received ${value === null ? "null" : typeof value}.`,
503
- path
504
- });
505
- } else if (fieldDef.nestedSchema) {
506
- const nestedSchema = {
507
- name: fieldDef.description ? `${fieldDef.description}-schema` : "nested-schema",
508
- version: "1.0",
509
- fields: fieldDef.nestedSchema
510
- };
511
- issues.push(
512
- ...validateData(
513
- nestedSchema,
514
- value,
515
- path
516
- )
517
- );
518
- }
519
- break;
520
- case "dynamic":
521
- break;
522
- default:
523
- issues.push({ message: `Unknown field type: ${fieldDef.type}`, path });
524
- break;
525
- }
526
- return issues;
527
- };
528
- const validateFieldConstraints = (fieldName, fieldDef, data, path) => {
529
- const issues = [];
530
- if (!fieldDef.constraints) return issues;
531
- fieldDef.constraints.forEach((constraint) => {
532
- const predicate = constraintsMap[constraint.predicate];
533
- if (!predicate) {
534
- issues.push({
535
- message: `Missing predicate for constraint: ${constraint.name}`,
536
- path
537
- });
538
- } else {
539
- const valid = constraint.type === "schema" ? predicate({ data, arguments: constraint.parameters }) : predicate({
540
- data,
541
- field: fieldName,
542
- arguments: constraint.parameters
543
- });
544
- if (!valid) {
545
- issues.push({
546
- message: `Constraint '${constraint.name}' failed for field '${fieldName}'.`,
547
- path
548
- });
549
- }
550
- }
551
- });
552
- return issues;
553
- };
554
- const validateField = (fieldName, fieldDef, value, data, path) => {
555
- return [
556
- ...validateTypeWithErrors(value, fieldName, fieldDef, path),
557
- ...validateFieldConstraints(fieldName, fieldDef, data, path)
558
- ];
559
- };
560
- const evaluateRuleWithErrors = (rule, data, fieldName) => {
561
- if ("operator" in rule) {
562
- return applyLogicalOperator(
563
- rule.operator,
564
- rule.rules.map((r) => evaluateRuleWithErrors(r, data, fieldName))
565
- );
566
- }
567
- const predicate = constraintsMap[rule.predicate];
568
- if (!predicate) {
569
- return false;
570
- }
571
- return rule.type === "schema" ? predicate({ data, field: rule.field, arguments: rule.parameters }) : predicate({ data, field: fieldName, arguments: rule.parameters });
572
- };
573
- const applyLogicalOperator = (operator, results) => {
574
- switch (operator) {
575
- case "and":
576
- return results.every(Boolean);
577
- case "or":
578
- return results.some(Boolean);
579
- case "not":
580
- return results.length === 1 ? !results[0] : false;
581
- case "nor":
582
- return !results.some(Boolean);
583
- case "xor":
584
- return results.filter(Boolean).length === 1;
585
- default:
586
- console.error(`Unknown logical operator: ${operator}`);
587
- return false;
588
- }
589
- };
590
- const ruleToString = (rule) => {
591
- if ("operator" in rule) {
592
- return `(${rule.rules.map(ruleToString).join(` ${rule.operator} `)})`;
593
- }
594
- return rule.name;
595
- };
596
- const validateData = (schemaToValidate, data, path = []) => {
597
- const issues = [];
598
- for (const [fieldName, fieldDef] of Object.entries(schemaToValidate.fields)) {
599
- if (fieldDef.required && data[fieldName] === void 0) {
600
- issues.push({
601
- message: `Field '${fieldName}' is required.`,
602
- path: [...path, fieldName]
603
- });
604
- }
605
- }
606
- for (const [fieldName, fieldDef] of Object.entries(schemaToValidate.fields)) {
607
- const value = data[fieldName];
608
- if (value === void 0) continue;
609
- issues.push(
610
- ...validateField(fieldName, fieldDef, value, data, [...path, fieldName])
611
- );
612
- }
613
- if (schemaToValidate.constraints) {
614
- schemaToValidate.constraints.forEach((rule) => {
615
- if (!evaluateRuleWithErrors(rule, data)) {
616
- issues.push({
617
- message: `Schema constraint failed: ${ruleToString(rule)}`,
618
- path
619
- });
620
- }
621
- });
622
- }
623
- return issues;
624
- };
625
- return {
626
- "~standard": {
627
- version: 1,
628
- vendor: "@asaidimu/anansi",
629
- validate: (value) => {
630
- if (typeof value !== "object" || value === null) {
631
- return {
632
- issues: [{ message: "Value must be a non-null object", path: [] }]
633
- };
634
- }
635
- const issues = validateData(schema, value);
636
- if (issues.length === 0) {
637
- return { value };
638
- }
639
- return { issues };
640
- }
641
- }
642
- };
643
- }
644
-
645
- // src/lib/schema/validator.ts
646
- import { z } from "zod";
647
-
648
- // src/lib/schema/error.ts
649
- var SchemaValidationError = class extends Error {
650
- constructor(message, errors) {
651
- super(message);
652
- this.errors = errors;
653
- this.name = "SchemaValidationError";
654
- }
655
- };
656
-
657
- // src/lib/schema/validator.ts
658
- var LogicalOperatorSchema = z.enum(["and", "or", "not", "nor", "xor"]);
659
- var FieldTypeSchema = z.enum(["string", "number", "boolean", "array", "object", "dynamic"]);
660
- var IndexTypeSchema = z.enum(["normal", "unique", "btree", "hash", "spatial", "fulltext", "gi", "expression", "composite"]);
661
- var ConstraintParametersSchema = z.custom(() => {
662
- return true;
663
- });
664
- var ConstraintSchema = z.object({
665
- type: z.string().optional(),
666
- name: z.string(),
667
- predicate: z.string().optional(),
668
- parameters: ConstraintParametersSchema.optional(),
669
- description: z.string().optional(),
670
- field: z.string().optional(),
671
- errorMessage: z.string().optional()
672
- });
673
- var ConstraintGroupSchema = z.object({
674
- operator: LogicalOperatorSchema,
675
- rules: z.array(z.union([ConstraintSchema, z.lazy(() => ConstraintGroupSchema)]))
676
- });
677
- var FieldDefinitionSchema = z.object({
678
- type: FieldTypeSchema,
679
- required: z.boolean().optional(),
680
- constraints: z.array(ConstraintSchema).optional(),
681
- default: z.any().optional(),
682
- itemsType: FieldTypeSchema.optional(),
683
- nestedSchema: z.record(z.lazy(() => FieldDefinitionSchema)).optional(),
684
- deprecated: z.boolean().optional(),
685
- reference: z.object({ schema: z.string(), field: z.string() }).optional(),
686
- description: z.string().optional(),
687
- unique: z.boolean().optional()
688
- });
689
- var PartialIndexConditionSchema = z.object({
690
- operator: LogicalOperatorSchema,
691
- field: z.string(),
692
- value: z.any().optional(),
693
- conditions: z.array(z.lazy(() => PartialIndexConditionSchema)).optional()
694
- });
695
- var IndexDefinitionSchema = z.object({
696
- fields: z.array(z.string()),
697
- type: IndexTypeSchema,
698
- unique: z.boolean().optional(),
699
- partial: PartialIndexConditionSchema.optional(),
700
- description: z.string().optional(),
701
- order: z.enum(["asc", "desc"]).optional(),
702
- name: z.string().optional()
703
- });
704
- var SchemaConstraintSchema = z.array(z.union([ConstraintSchema, ConstraintGroupSchema]));
705
- var SchemaDefinitionSchema = z.object({
706
- name: z.string(),
707
- version: z.string(),
708
- description: z.string().optional(),
709
- fields: z.record(FieldDefinitionSchema),
710
- indexes: z.array(IndexDefinitionSchema).optional(),
711
- constraints: SchemaConstraintSchema.optional(),
712
- metadata: z.record(z.any()).optional(),
713
- dependencies: z.array(z.string()).optional(),
714
- migrations: z.array(z.any()).optional()
715
- });
716
- var SchemaChangeSchema = z.union([
717
- z.object({ type: z.literal("addField"), name: z.string(), definition: FieldDefinitionSchema }),
718
- z.object({ type: z.literal("removeField"), name: z.string() }),
719
- z.object({ type: z.literal("modifyField"), name: z.string(), changes: FieldDefinitionSchema.partial() }),
720
- z.object({ type: z.literal("addIndex"), definition: IndexDefinitionSchema }),
721
- z.object({ type: z.literal("removeIndex"), name: z.string() }),
722
- z.object({ type: z.literal("modifyIndex"), name: z.string(), changes: IndexDefinitionSchema.partial() }),
723
- z.object({ type: z.literal("addConstraint"), constraint: z.union([ConstraintSchema, ConstraintGroupSchema]) }),
724
- z.object({ type: z.literal("removeConstraint"), name: z.string() }),
725
- z.object({ type: z.literal("modifyConstraint"), name: z.string(), changes: ConstraintSchema.partial() }),
726
- z.object({ type: z.literal("deprecateField"), name: z.string() })
727
- ]);
728
- var MigrationSchema = z.object({
729
- id: z.string(),
730
- schemaVersion: z.string(),
731
- changes: z.array(SchemaChangeSchema),
732
- description: z.string(),
733
- status: z.enum(["pending", "applied", "failed"]),
734
- rollback: z.array(SchemaChangeSchema).optional(),
735
- transform: z.unknown(),
736
- createdAt: z.string(),
737
- checksum: z.string().optional()
738
- });
739
- function validateMigration(change) {
740
- try {
741
- MigrationSchema.parse(change);
742
- return true;
743
- } catch (error) {
744
- throw new SchemaValidationError("Invalid migration definition", error);
745
- }
746
- }
747
- function validateSchemaChange(change) {
748
- try {
749
- SchemaChangeSchema.parse(change);
750
- return true;
751
- } catch (error) {
752
- throw new SchemaValidationError("Invalid schema definition", error);
753
- }
754
- }
755
- function validateSchemaDefinition(schema) {
756
- try {
757
- SchemaDefinitionSchema.parse(schema);
758
- return true;
759
- } catch (error) {
760
- throw new SchemaValidationError("Invalid schema definition", error);
761
- }
762
- }
763
- var validate = validateSchemaDefinition;
764
-
765
- // src/tools/crypto.ts
766
- var generateSHA256Hash = async (input) => {
767
- if (typeof window !== "undefined" && crypto.subtle) {
768
- const encoder = new TextEncoder();
769
- const data = encoder.encode(input);
770
- const hashBuffer = await crypto.subtle.digest("SHA-256", data);
771
- const hashArray = Array.from(new Uint8Array(hashBuffer));
772
- return hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
773
- } else {
774
- const { createHash } = await import("crypto");
775
- return createHash("sha256").update(input).digest("hex");
776
- }
777
- };
778
-
779
- // src/tools/version.ts
780
- function parseVersion(version) {
781
- const match = version.match(/^(\d+)\.(\d+)\.(\d+)$/);
782
- if (!match) {
783
- throw new Error(
784
- `Invalid version format: ${version}. Expected format: major.minor.patch`
785
- );
786
- }
787
- return {
788
- major: parseInt(match[1], 10),
789
- minor: parseInt(match[2], 10),
790
- patch: parseInt(match[3], 10)
791
- };
792
- }
793
- function determineFieldType(constraint, schema) {
794
- if (schema && "field" in constraint && constraint.field) {
795
- const fieldDef = schema.fields[constraint.field];
796
- if (fieldDef) {
797
- return fieldDef.type;
798
- }
799
- }
800
- if ("parameters" in constraint) {
801
- const params = constraint.parameters;
802
- if (params instanceof RegExp || Array.isArray(params) && typeof params[0] === "string") {
803
- return "string";
804
- }
805
- if (typeof params === "number" || Array.isArray(params) && typeof params[0] === "number") {
806
- return "number";
807
- }
808
- if (typeof params === "boolean") {
809
- return "boolean";
810
- }
811
- if (typeof params === "object" && params !== null) {
812
- if ("minItems" in params || "maxItems" in params) {
813
- return "array";
814
- }
815
- if ("schema" in params) {
816
- return "object";
817
- }
818
- }
819
- }
820
- return void 0;
821
- }
822
- function isBreakingFieldChange(changes) {
823
- if (changes.required === true) return true;
824
- if (changes.type !== void 0) return true;
825
- if (changes.itemsType !== void 0) return true;
826
- if (changes.nestedSchema !== void 0) return true;
827
- if (changes.reference !== void 0) return true;
828
- if (changes.unique === true) return true;
829
- return false;
830
- }
831
- function isBreakingConstraintParameters(oldParams, newParams, fieldType) {
832
- switch (fieldType) {
833
- case "string":
834
- if (oldParams instanceof RegExp && newParams instanceof RegExp) {
835
- return oldParams.source !== newParams.source;
836
- }
837
- if (Array.isArray(oldParams) && Array.isArray(newParams)) {
838
- return newParams.length < oldParams.length || !oldParams.every(
839
- (val) => newParams.includes(val)
840
- );
841
- }
842
- break;
843
- case "number":
844
- if (typeof oldParams === "object" && typeof newParams === "object") {
845
- if ("precision" in oldParams && "precision" in newParams) {
846
- return newParams.precision < oldParams.precision || (newParams.scale ?? 0) < (oldParams.scale ?? 0);
847
- }
848
- }
849
- if (Array.isArray(oldParams) && Array.isArray(newParams)) {
850
- return newParams.length < oldParams.length || !oldParams.every(
851
- (val) => newParams.includes(val)
852
- );
853
- }
854
- break;
855
- case "array":
856
- if (typeof oldParams === "object" && typeof newParams === "object" && "minItems" in oldParams && "maxItems" in oldParams && "minItems" in newParams && "maxItems" in newParams) {
857
- return newParams.minItems > oldParams.minItems || newParams.maxItems < oldParams.maxItems;
858
- }
859
- break;
860
- case "object":
861
- if (typeof oldParams === "object" && typeof newParams === "object" && "schema" in oldParams && "schema" in newParams) {
862
- return Object.keys(newParams.schema).length > Object.keys(oldParams.schema).length;
863
- }
864
- break;
865
- }
866
- return false;
867
- }
868
- function analyzeConstraintGroupChanges(oldGroup, newGroup) {
869
- const operatorPriority = {
870
- or: 1,
871
- xor: 2,
872
- and: 3,
873
- not: 4,
874
- nor: 4
875
- };
876
- if (newGroup.operator && operatorPriority[newGroup.operator] > operatorPriority[oldGroup.operator]) {
877
- return true;
878
- }
879
- if (newGroup.rules && newGroup.rules.length > oldGroup.rules.length) {
880
- return true;
881
- }
882
- return false;
883
- }
884
- function isBreakingConstraintChange(changes, oldConstraint, schema) {
885
- if (!oldConstraint) {
886
- return true;
887
- }
888
- if ("rules" in oldConstraint && "rules" in changes) {
889
- return analyzeConstraintGroupChanges(
890
- oldConstraint,
891
- changes
892
- );
893
- }
894
- if ("predicate" in changes && changes.predicate !== void 0) {
895
- return true;
896
- }
897
- if ("parameters" in changes && changes.parameters !== void 0) {
898
- const fieldType = determineFieldType(
899
- oldConstraint,
900
- schema
901
- );
902
- if (fieldType) {
903
- return isBreakingConstraintParameters(
904
- oldConstraint.parameters,
905
- changes.parameters,
906
- fieldType
907
- );
908
- }
909
- return true;
910
- }
911
- return false;
912
- }
913
- function getChangeImpact(change, currentSchema) {
914
- switch (change.type) {
915
- case "removeField":
916
- case "removeIndex":
917
- return "major";
918
- case "modifyField":
919
- if (isBreakingFieldChange(change.changes)) {
920
- return "major";
921
- }
922
- if (change.changes.deprecated) {
923
- return "minor";
924
- }
925
- return "patch";
926
- case "modifyIndex":
927
- if (change.changes.unique !== void 0 || change.changes.fields !== void 0) {
928
- return "major";
929
- }
930
- return "minor";
931
- case "addConstraint":
932
- return "major";
933
- case "removeConstraint":
934
- return "minor";
935
- case "modifyConstraint":
936
- const oldConstraint = currentSchema?.constraints?.find(
937
- (c) => "name" in c && c.name === change.name
938
- );
939
- if (isBreakingConstraintChange(change.changes, oldConstraint, currentSchema)) {
940
- return "major";
941
- }
942
- return "minor";
943
- case "addField":
944
- case "addIndex":
945
- case "deprecateField":
946
- return "minor";
947
- default:
948
- throw new Error(`Unhandled change type: ${JSON.stringify(change)}`);
949
- }
950
- }
951
- function validateFieldChanges(changes) {
952
- const modifiedFields = /* @__PURE__ */ new Set();
953
- const removedFields = /* @__PURE__ */ new Set();
954
- const addedFields = /* @__PURE__ */ new Set();
955
- const deprecatedFields = /* @__PURE__ */ new Set();
956
- for (const change of changes) {
957
- switch (change.type) {
958
- case "addField":
959
- if (removedFields.has(change.name)) {
960
- throw new Error(
961
- `Cannot add previously removed field: ${change.name}`
962
- );
963
- }
964
- if (modifiedFields.has(change.name)) {
965
- throw new Error(`Cannot add already modified field: ${change.name}`);
966
- }
967
- if (deprecatedFields.has(change.name)) {
968
- throw new Error(`Cannot add deprecated field: ${change.name}`);
969
- }
970
- addedFields.add(change.name);
971
- break;
972
- case "removeField":
973
- if (addedFields.has(change.name)) {
974
- throw new Error(`Cannot remove newly added field: ${change.name}`);
975
- }
976
- if (modifiedFields.has(change.name)) {
977
- throw new Error(`Cannot remove modified field: ${change.name}`);
978
- }
979
- if (deprecatedFields.has(change.name)) {
980
- throw new Error(
981
- `Cannot remove field that is being deprecated: ${change.name}`
982
- );
983
- }
984
- removedFields.add(change.name);
985
- break;
986
- case "modifyField":
987
- if (removedFields.has(change.name)) {
988
- throw new Error(`Cannot modify removed field: ${change.name}`);
989
- }
990
- if (addedFields.has(change.name)) {
991
- throw new Error(`Cannot modify newly added field: ${change.name}`);
992
- }
993
- if (deprecatedFields.has(change.name)) {
994
- throw new Error(
995
- `Cannot modify field that is being deprecated: ${change.name}`
996
- );
997
- }
998
- modifiedFields.add(change.name);
999
- break;
1000
- case "deprecateField":
1001
- if (removedFields.has(change.name)) {
1002
- throw new Error(`Cannot deprecate removed field: ${change.name}`);
1003
- }
1004
- if (addedFields.has(change.name)) {
1005
- throw new Error(`Cannot deprecate newly added field: ${change.name}`);
1006
- }
1007
- if (modifiedFields.has(change.name)) {
1008
- throw new Error(`Cannot deprecate modified field: ${change.name}`);
1009
- }
1010
- deprecatedFields.add(change.name);
1011
- break;
1012
- }
1013
- }
1014
- }
1015
- function validateConstraintChanges(changes) {
1016
- const modifiedConstraints = /* @__PURE__ */ new Set();
1017
- const removedConstraints = /* @__PURE__ */ new Set();
1018
- const addedConstraints = /* @__PURE__ */ new Set();
1019
- for (const change of changes) {
1020
- switch (change.type) {
1021
- case "addConstraint":
1022
- const c = change.constraint;
1023
- const name = "name" in c ? c.name : c.name;
1024
- if (removedConstraints.has(name)) {
1025
- throw new Error(
1026
- `Cannot add previously removed constraint: ${name}`
1027
- );
1028
- }
1029
- if (modifiedConstraints.has(name)) {
1030
- throw new Error(`Cannot add already modified constraint: ${name}`);
1031
- }
1032
- addedConstraints.add(name);
1033
- break;
1034
- case "removeConstraint":
1035
- if (addedConstraints.has(change.name)) {
1036
- throw new Error(
1037
- `Cannot remove newly added constraint: ${change.name}`
1038
- );
1039
- }
1040
- if (modifiedConstraints.has(change.name)) {
1041
- throw new Error(`Cannot remove modified constraint: ${change.name}`);
1042
- }
1043
- removedConstraints.add(change.name);
1044
- break;
1045
- case "modifyConstraint":
1046
- if (removedConstraints.has(change.name)) {
1047
- throw new Error(`Cannot modify removed constraint: ${change.name}`);
1048
- }
1049
- if (addedConstraints.has(change.name)) {
1050
- throw new Error(
1051
- `Cannot modify newly added constraint: ${change.name}`
1052
- );
1053
- }
1054
- modifiedConstraints.add(change.name);
1055
- break;
1056
- }
1057
- }
1058
- }
1059
- function calculateNextVersion(currentVersion, changes, currentSchema) {
1060
- if (changes.length === 0) {
1061
- throw new Error("No changes provided");
1062
- }
1063
- validateFieldChanges(changes);
1064
- validateConstraintChanges(changes);
1065
- const version = parseVersion(currentVersion);
1066
- let highestImpact = "patch";
1067
- for (const change of changes) {
1068
- const impact = getChangeImpact(change, currentSchema);
1069
- if (impact === "major") {
1070
- highestImpact = "major";
1071
- break;
1072
- } else if (impact === "minor" && highestImpact === "patch") {
1073
- highestImpact = "minor";
1074
- }
1075
- }
1076
- switch (highestImpact) {
1077
- case "major":
1078
- return `${version.major + 1}.0.0`;
1079
- case "minor":
1080
- return `${version.major}.${version.minor + 1}.0`;
1081
- case "patch":
1082
- return `${version.major}.${version.minor}.${version.patch + 1}`;
1083
- }
1084
- }
1085
- function compareSemanticVersions(a, b) {
1086
- const parseVersion2 = (version) => version.split(".").map((part) => parseInt(part, 10) || 0);
1087
- const [aMajor, aMinor, aPatch] = parseVersion2(a);
1088
- const [bMajor, bMinor, bPatch] = parseVersion2(b);
1089
- return aMajor - bMajor || aMinor - bMinor || aPatch - bPatch;
1090
- }
1091
- function sortSemanticVars(vars) {
1092
- return vars.sort(compareSemanticVersions);
1093
- }
1094
-
1095
- // src/lib/migration/index.ts
1096
- var MigrationError = class extends Error {
1097
- constructor(message, code, migrationId, cause) {
1098
- super(message);
1099
- this.code = code;
1100
- this.migrationId = migrationId;
1101
- this.cause = cause;
1102
- this.name = "MigrationError";
1103
- }
1104
- };
1105
- var MigrationErrorCode = /* @__PURE__ */ ((MigrationErrorCode2) => {
1106
- MigrationErrorCode2["INVALID_SCHEMA"] = "INVALID_SCHEMA";
1107
- MigrationErrorCode2["INVALID_MIGRATION"] = "INVALID_MIGRATION";
1108
- MigrationErrorCode2["CHECKSUM_MISMATCH"] = "CHECKSUM_MISMATCH";
1109
- MigrationErrorCode2["TIMEOUT"] = "TIMEOUT";
1110
- MigrationErrorCode2["MEMORY_LIMIT"] = "MEMORY_LIMIT";
1111
- MigrationErrorCode2["CONCURRENT_OPERATION"] = "CONCURRENT_OPERATION";
1112
- MigrationErrorCode2["TRANSFORM_ERROR"] = "TRANSFORM_ERROR";
1113
- MigrationErrorCode2["VERSION_NOT_FOUND"] = "VERSION_NOT_FOUND";
1114
- MigrationErrorCode2["CIRCULAR_DEPENDENCY"] = "CIRCULAR_DEPENDENCY";
1115
- MigrationErrorCode2["STREAM_ERROR"] = "STREAM_ERROR";
1116
- MigrationErrorCode2["ROLLBACK_ERROR"] = "ROLLBACK_ERROR";
1117
- MigrationErrorCode2["MISSING_TRANSFORM"] = "MISSING_TRANSFORM";
1118
- return MigrationErrorCode2;
1119
- })(MigrationErrorCode || {});
1120
-
1121
- // src/lib/schema/helpers.ts
1122
- var createSchemaMigrationHelper = (schema) => {
1123
- const migrate = [];
1124
- const rollback = [];
1125
- return {
1126
- /**
1127
- * Adds a new field to the schema.
1128
- * @param {string} fieldName - The name of the field to add.
1129
- * @param {FieldDefinition<any>} fieldDefinition - The definition of the field to add.
1130
- */
1131
- addField: (fieldName, fieldDefinition) => {
1132
- migrate.push({ type: "addField", name: fieldName, definition: fieldDefinition });
1133
- rollback.push({ type: "removeField", name: fieldName });
1134
- },
1135
- /**
1136
- * Removes a field from the schema.
1137
- * @param {string} fieldName - The name of the field to remove.
1138
- */
1139
- removeField: (fieldName) => {
1140
- migrate.push({ type: "removeField", name: fieldName });
1141
- const originalField = schema.fields[fieldName];
1142
- if (originalField) {
1143
- rollback.push({ type: "addField", name: fieldName, definition: originalField });
1144
- }
1145
- },
1146
- /**
1147
- * Modifies an existing field in the schema.
1148
- * @param {string} fieldName - The name of the field to modify.
1149
- * @param {Partial<FieldDefinition<any>>} changes - The changes to apply to the field.
1150
- */
1151
- modifyField: (fieldName, changes) => {
1152
- migrate.push({ type: "modifyField", name: fieldName, changes });
1153
- const originalField = schema.fields[fieldName];
1154
- rollback.push({ type: "modifyField", name: fieldName, changes: originalField });
1155
- },
1156
- /**
1157
- * Deprecates a field.
1158
- * @param {string} fieldName - The name of the field to deprecate.
1159
- */
1160
- deprecateField: (fieldName) => {
1161
- migrate.push({ type: "deprecateField", name: fieldName });
1162
- rollback.push({
1163
- type: "modifyField",
1164
- name: fieldName,
1165
- changes: { deprecated: false }
1166
- });
1167
- },
1168
- /**
1169
- * Adds a new index to the schema.
1170
- * @param {IndexDefinition} indexDefinition - The definition of the index to add.
1171
- */
1172
- addIndex: (indexDefinition) => {
1173
- migrate.push({ type: "addIndex", definition: indexDefinition });
1174
- rollback.push({ type: "removeIndex", name: indexDefinition.name });
1175
- },
1176
- /**
1177
- * Removes an index from the schema.
1178
- * @param {string} indexName - The name of the index to remove.
1179
- */
1180
- removeIndex: (indexName) => {
1181
- migrate.push({ type: "removeIndex", name: indexName });
1182
- const originalIndex = schema.indexes?.find((index) => index.name === indexName);
1183
- if (originalIndex) {
1184
- rollback.push({ type: "addIndex", definition: originalIndex });
1185
- }
1186
- },
1187
- /**
1188
- * Modifies an existing index in the schema.
1189
- * @param {string} indexName - The name of the index to modify.
1190
- * @param {Partial<IndexDefinition>} changes - The changes to apply to the index.
1191
- */
1192
- modifyIndex: (indexName, changes) => {
1193
- migrate.push({ type: "modifyIndex", name: indexName, changes });
1194
- const originalIndex = schema.indexes?.find((index) => index.name === indexName);
1195
- if (originalIndex) {
1196
- rollback.push({ type: "modifyIndex", name: indexName, changes: originalIndex });
1197
- }
1198
- },
1199
- /**
1200
- * Adds a new constraint to the schema.
1201
- * @param {SchemaConstraint<any>} constraint - The constraint to add.
1202
- */
1203
- addConstraint: (constraint) => {
1204
- migrate.push({ type: "addConstraint", constraint });
1205
- rollback.push({ type: "removeConstraint", name: constraint.name });
1206
- },
1207
- /**
1208
- * Removes a constraint from the schema.
1209
- * @param {string} constraintName - The name of the constraint to remove.
1210
- */
1211
- removeConstraint: (constraintName) => {
1212
- migrate.push({ type: "removeConstraint", name: constraintName });
1213
- const originalConstraint = schema.constraints?.find((c) => "name" in c && c.name === constraintName);
1214
- if (originalConstraint) {
1215
- rollback.push({ type: "addConstraint", constraint: originalConstraint });
1216
- }
1217
- },
1218
- /**
1219
- * Modifies an existing constraint in the schema.
1220
- * @param {string} constraintName - The name of the constraint to modify.
1221
- * @param {Partial<SchemaConstraint<any>>} changes - The changes to apply to the constraint.
1222
- */
1223
- modifyConstraint: (constraintName, changes) => {
1224
- migrate.push({ type: "modifyConstraint", name: constraintName, changes });
1225
- const originalConstraint = schema.constraints?.find((c) => "name" in c && c.name === constraintName);
1226
- if (originalConstraint) {
1227
- rollback.push({ type: "modifyConstraint", name: constraintName, changes: originalConstraint });
1228
- }
1229
- },
1230
- /**
1231
- * Returns the migration changes and their corresponding rollback changes.
1232
- * @returns {Object} An object containing the migrate and rollback changes.
1233
- */
1234
- changes: () => ({
1235
- migrate,
1236
- rollback
1237
- })
1238
- };
1239
- };
1240
-
1241
- // src/lib/registry/index.ts
1242
- import LightningFS from "@isomorphic-git/lightning-fs";
1243
- import { Buffer } from "buffer";
1244
- import git from "isomorphic-git";
1245
- import http from "isomorphic-git/http/web";
1246
- window.Buffer = Buffer;
1247
-
1248
- // src/tools/typegen.ts
1249
- function convertFieldTypeToTS(field, parentType, fieldName) {
1250
- switch (field.type) {
1251
- case "string":
1252
- return "string";
1253
- case "number":
1254
- return "number";
1255
- case "boolean":
1256
- return "boolean";
1257
- case "array":
1258
- if (field.itemsType) {
1259
- if (field.itemsType === "object" && field.nestedSchema) {
1260
- const nestedTypeName = `${parentType}ItemsItem`;
1261
- return `${nestedTypeName}[]`;
1262
- }
1263
- return `${field.itemsType}[]`;
1264
- }
1265
- return "any[]";
1266
- case "object":
1267
- if (field.nestedSchema) {
1268
- return `${parentType}${capitalize(fieldName)}`;
1269
- }
1270
- return "Record<string, any>";
1271
- case "dynamic":
1272
- return "any";
1273
- default:
1274
- return "any";
1275
- }
1276
- }
1277
- function generateNestedTypes(fields, parentName) {
1278
- let types = "";
1279
- for (const [fieldName, field] of Object.entries(fields)) {
1280
- if (field.type === "object" && field.nestedSchema) {
1281
- const typeName = `${parentName}${capitalize(fieldName)}`;
1282
- types += `
1283
- export interface ${typeName} {
1284
- ${generateTypeProperties(field.nestedSchema, typeName)}
1285
- }`;
1286
- const nestedTypes = generateNestedTypes(field.nestedSchema, typeName);
1287
- if (nestedTypes) {
1288
- types += `
1289
- ${nestedTypes}`;
1290
- }
1291
- } else if (field.type === "array" && field.itemsType === "object" && field.nestedSchema) {
1292
- const typeName = `${parentName}ItemsItem`;
1293
- types += `
1294
- export interface ${typeName} {
1295
- ${generateTypeProperties(field.nestedSchema, typeName)}
1296
- }`;
1297
- const nestedTypes = generateNestedTypes(field.nestedSchema, typeName);
1298
- if (nestedTypes) {
1299
- types += `
1300
- ${nestedTypes}`;
1301
- }
1302
- }
1303
- }
1304
- return types;
1305
- }
1306
- function generateTypeProperties(fields, parentType) {
1307
- return Object.entries(fields).map(([fieldName, field]) => {
1308
- const lines = [];
1309
- if (field.description) {
1310
- lines.push(` /** ${field.description} */`);
1311
- }
1312
- if (field.deprecated) {
1313
- lines.push(" /** @deprecated */");
1314
- }
1315
- const optional = !field.required ? "?" : "";
1316
- const tsType = convertFieldTypeToTS(field, parentType, fieldName);
1317
- lines.push(` ${fieldName}${optional}: ${tsType};`);
1318
- return lines.join("\n");
1319
- }).join("\n");
1320
- }
1321
- function capitalize(str) {
1322
- return str.charAt(0).toUpperCase() + str.slice(1);
1323
- }
1324
- function schemaToTypes(schema) {
1325
- const mainTypeName = capitalize(schema.name);
1326
- let output = `// Generated from schema version ${schema.version}
1327
- `;
1328
- if (schema.description) {
1329
- output += `/** ${schema.description} */
1330
- `;
1331
- }
1332
- output += `export interface ${mainTypeName} {
1333
- ${generateTypeProperties(schema.fields, mainTypeName)}
1334
- }`;
1335
- const nestedTypes = generateNestedTypes(schema.fields, mainTypeName);
1336
- if (nestedTypes) {
1337
- output += `
1338
- ${nestedTypes}`;
1339
- }
1340
- output += "\n";
1341
- return output;
1342
- }
1343
- export {
1344
- JsonPatchError,
1345
- MigrationError,
1346
- MigrationErrorCode,
1347
- MigrationSchema,
1348
- applyPatch,
1349
- calculateNextVersion,
1350
- compareSemanticVersions,
1351
- createPatch,
1352
- createSchemaMigrationHelper,
1353
- createStandardSchemaValidator,
1354
- deepMerge,
1355
- generateSHA256Hash,
1356
- normalizePath,
1357
- schemaChangeToPatch,
1358
- schemaToTypes,
1359
- sortSemanticVars,
1360
- validate,
1361
- validateMigration,
1362
- validateSchemaChange,
1363
- validateSchemaDefinition
1364
- };
1
+ import{createEventBus as at}from"@asaidimu/events";import{createEventBus as Ue}from"@asaidimu/events";import{createMatcher as ze,createPaginator as qe,createProjector as Ke,createSorter as Ye}from"@asaidimu/query";var y=class extends Error{constructor(t,n){super(t);this.operation=n;this.name="JsonPatchError"}};function $(e){let r=q(e);return r===""?[]:r.substring(1).split("/").map(K)}function q(e){return e===""||e==="/"?"":e.startsWith("/")?"/"+e.substring(1).split("/").map(C).join("/"):"/"+e.split(".").map(C).join("/")}function C(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function K(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}var w=new Map;function T(e,r){let t=e;for(let n of r){if(t===null||typeof t!="object")throw new y(`Invalid path - parent not found at ${n}`);if(Array.isArray(t)){let a=n==="-"?t.length:parseInt(n);if(isNaN(a)||a<0||a>t.length)throw new y(`Invalid array index: ${n}`);t=t[a]}else{if(!t.hasOwnProperty(n))throw new y(`Property ${n} not found`);t=t[n]}}return t}function E(e,r){let t=w.get(r)||$(r);if(w.set(r,t),t.length===0)return e;let n=T(e,t.slice(0,-1)),a=t[t.length-1];if(Array.isArray(n)){let i=parseInt(a);if(isNaN(i)||i<0||i>=n.length)throw new y(`Invalid array index: ${a}`);return n[i]}return n[a]}function Y(e,r,t){let n=w.get(r)||$(r);w.set(r,n);let a=T(e,n.slice(0,-1)),i=n[n.length-1];return Array.isArray(a)?a.splice(0,a.length,...a.filter(m=>m!==t)):a[i]===t&&delete a[i],e}function v(e,r,t){let n=w.get(r)||$(r);if(w.set(r,n),n.length===0)return t;let a=n.slice(0,-1),i=n[n.length-1],m=T(e,a);if(Array.isArray(m))if(i==="-")m.push(t);else{let c=parseInt(i);if(c<0||c>m.length)throw new y(`Invalid array index: ${i}`);m.splice(c,0,t)}else m[i]=t;return e}function I(e,r){let t=w.get(r)||$(r);if(w.set(r,t),t.length===0)return;let n=T(e,t.slice(0,-1)),a=t[t.length-1];if(Array.isArray(n)){let i=parseInt(a);n.splice(i,1)}else delete n[a];return e}function j(e,r){let t=JSON.parse(JSON.stringify(e));for(let n of r)try{switch(n.op){case"add":t=v(t,n.path,n.value);break;case"remove":t=I(t,n.path);break;case"removeValue":t=Y(t,n.path,n.value);break;case"replace":t=v(I(t,n.path),n.path,n.value);break;case"copy":{let a=E(t,n.from);t=v(t,n.path,JSON.parse(JSON.stringify(a)));break}case"move":{let a=E(t,n.from);t=v(t,n.path,a),t=I(t,n.from);break}case"test":{let a=E(t,n.path);if(JSON.stringify(a)!==JSON.stringify(n.value))throw new y("Test operation failed");break}default:throw new y(`Unsupported operation: ${n.op}`)}}catch(a){throw a instanceof y&&(a.operation=n),a}return t}function $e(e,r){let t=[];return R(e,r,"",t),t}function R(e,r,t,n){if(e!==r){if(typeof e!=typeof r||Array.isArray(e)!==Array.isArray(r)){n.push({op:"replace",path:t,value:r});return}typeof e=="object"&&e!==null?Array.isArray(e)?Q(e,r,t,n):W(e,r,t,n):e!==r&&n.push({op:"replace",path:t,value:r})}}function Q(e,r,t,n){let a=Math.max(e.length,r.length);for(let i=0;i<a;i++){let m=`${t}/${i}`;i>=e.length?n.push({op:"add",path:`${t}/-`,value:r[i]}):i>=r.length?n.push({op:"remove",path:m}):R(e[i],r[i],m,n)}}function W(e,r,t,n){let a=new Set,i=Object.keys(e),m=Object.keys(r);for(let c of i){let d=C(c),s=t?`${t}/${d}`:`/${d}`;r.hasOwnProperty(c)?(R(e[c],r[c],s,n),a.add(c)):n.push({op:"remove",path:s})}for(let c of m)if(!a.has(c)){let d=C(c),s=t?`${t}/${d}`:`/${d}`;n.push({op:"add",path:s,value:r[c]})}}function Z(e,r){let t=[];switch(e.type){case"addField":t.push({op:"add",path:`/fields/${e.name}`,value:e.definition});break;case"removeField":t.push({op:"remove",path:`/fields/${e.name}`});break;case"modifyField":{let n=`/fields/${e.name}`;Object.entries(e.changes).forEach(([a,i])=>{typeof i=="object"&&i!==null&&!Array.isArray(i)?t.push({op:"replace",path:`${n}/${a}`,value:i}):t.push({op:"replace",path:`${n}/${a}`,value:i})});break}case"deprecateField":t.push({op:"add",path:`/fields/${e.name}/deprecated`,value:!0});break;case"addIndex":r.indexes||t.push({op:"add",path:"/indexes",value:[]}),t.push({op:"add",path:"/indexes/-",value:e.definition});break;case"removeIndex":{let n=r.indexes?.findIndex(a=>a.name===e.name);n!==void 0&&n>=0&&t.push({op:"remove",path:`/indexes/${n}`});break}case"modifyIndex":{let n=r.indexes?.findIndex(a=>a.name===e.name);n!==void 0&&n>=0&&Object.entries(e.changes).forEach(([a,i])=>{t.push({op:"replace",path:`/indexes/${n}/${a}`,value:i})});break}case"addConstraint":r.constraints||t.push({op:"add",path:"/constraints",value:[]}),Array.isArray(e.constraint)?e.constraint.forEach(n=>{t.push({op:"add",path:"/constraints/-",value:n})}):t.push({op:"add",path:"/constraints/-",value:e.constraint});break;case"removeConstraint":{let n=r.constraints?.findIndex(a=>Array.isArray(a)?a.some(i=>i.name===e.name):a.name===e.name);n!==void 0&&n>=0&&t.push({op:"remove",path:`/constraints/${n}`});break}case"modifyConstraint":{let n=X(r,e.name);n&&Object.entries(e.changes).forEach(([a,i])=>{t.push({op:"replace",path:`${n}/${a}`,value:i})});break}}return t}function X(e,r){if(!e.constraints)return null;for(let t=0;t<e.constraints.length;t++){let n=e.constraints[t];if(n.name===r)return`/constraints/${t}`;if(V(n)){let a=J(n.rules,r);if(a)return`/constraints/${t}${a}`}}return null}function V(e){return e&&"operator"in e&&"rules"in e}function J(e,r){for(let t=0;t<e.length;t++){let n=e[t];if("name"in n&&n.name===r)return`/rules/${t}`;if(V(n)){let a=J(n.rules,r);if(a)return`/rules/${t}${a}`}}return null}function _(e,r){let t={...e};return k(e)&&k(r)&&Object.keys(r).forEach(n=>{k(r[n])?n in e?t[n]=_(e[n],r[n]):Object.assign(t,{[n]:r[n]}):Object.assign(t,{[n]:r[n]})}),t}function k(e){return e&&typeof e=="object"&&!Array.isArray(e)}function ee(e,r){let t=(s,l,u,p)=>{let f=[];switch(u.type){case"string":typeof s!="string"&&f.push({message:`Expected type string but received ${typeof s}.`,path:p});break;case"number":typeof s!="number"&&f.push({message:`Expected type number but received ${typeof s}.`,path:p});break;case"boolean":typeof s!="boolean"&&f.push({message:`Expected type boolean but received ${typeof s}.`,path:p});break;case"array":Array.isArray(s)?u.itemsType?s.forEach((h,g)=>{f.push(...t(h,`Array: ${l}`,{type:u.itemsType,nestedSchema:u.nestedSchema},[...p,g]))}):f.push({message:`Expected itemsType for array ${l}`,path:p}):f.push({message:`Expected an array but received ${typeof s}.`,path:p});break;case"object":if(typeof s!="object"||s===null)f.push({message:`Expected an object but received ${s===null?"null":typeof s}.`,path:p});else if(u.nestedSchema){let h={name:u.description?`${u.description}-schema`:"nested-schema",version:"1.0",fields:u.nestedSchema};f.push(...d(h,s,p))}break;case"dynamic":break;default:f.push({message:`Unknown field type: ${u.type}`,path:p});break}return f},n=(s,l,u,p)=>{let f=[];return l.constraints&&l.constraints.forEach(h=>{let g=r[h.predicate];g?(h.type==="schema"?g({data:u,arguments:h.parameters}):g({data:u,field:s,arguments:h.parameters}))||f.push({message:`Constraint '${h.name}' failed for field '${s}'.`,path:p}):f.push({message:`Missing predicate for constraint: ${h.name}`,path:p})}),f},a=(s,l,u,p,f)=>[...t(u,s,l,f),...n(s,l,p,f)],i=(s,l,u)=>{if("operator"in s)return m(s.operator,s.rules.map(f=>i(f,l,u)));let p=r[s.predicate];return p?s.type==="schema"?p({data:l,field:s.field,arguments:s.parameters}):p({data:l,field:u,arguments:s.parameters}):!1},m=(s,l)=>{switch(s){case"and":return l.every(Boolean);case"or":return l.some(Boolean);case"not":return l.length===1?!l[0]:!1;case"nor":return!l.some(Boolean);case"xor":return l.filter(Boolean).length===1;default:return console.error(`Unknown logical operator: ${s}`),!1}},c=s=>"operator"in s?`(${s.rules.map(c).join(` ${s.operator} `)})`:s.name,d=(s,l,u=[])=>{let p=[];for(let[f,h]of Object.entries(s.fields))h.required&&l[f]===void 0&&p.push({message:`Field '${f}' is required.`,path:[...u,f]});for(let[f,h]of Object.entries(s.fields)){let g=l[f];g!==void 0&&p.push(...a(f,h,g,l,[...u,f]))}return s.constraints&&s.constraints.forEach(f=>{i(f,l)||p.push({message:`Schema constraint failed: ${c(f)}`,path:u})}),p};return{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:s=>{if(typeof s!="object"||s===null)return{issues:[{message:"Value must be a non-null object",path:[]}]};let l=d(e,s);return l.length===0?{value:s}:{issues:l}}}}}import{z as o}from"zod";var S=class extends Error{constructor(t,n){super(t);this.errors=n;this.name="SchemaValidationError"}};var H=o.enum(["and","or","not","nor","xor"]),L=o.enum(["string","number","boolean","array","object","dynamic"]),te=o.enum(["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"]),ne=o.custom(()=>!0),b=o.object({type:o.string().optional(),name:o.string(),predicate:o.string().optional(),parameters:ne.optional(),description:o.string().optional(),field:o.string().optional(),errorMessage:o.string().optional()}),M=o.object({operator:H,rules:o.array(o.union([b,o.lazy(()=>M)]))}),x=o.object({type:L,required:o.boolean().optional(),constraints:o.array(b).optional(),default:o.any().optional(),itemsType:L.optional(),nestedSchema:o.record(o.lazy(()=>x)).optional(),deprecated:o.boolean().optional(),reference:o.object({schema:o.string(),field:o.string()}).optional(),description:o.string().optional(),unique:o.boolean().optional()}),G=o.object({operator:H,field:o.string(),value:o.any().optional(),conditions:o.array(o.lazy(()=>G)).optional()}),D=o.object({fields:o.array(o.string()),type:te,unique:o.boolean().optional(),partial:G.optional(),description:o.string().optional(),order:o.enum(["asc","desc"]).optional(),name:o.string().optional()}),re=o.array(o.union([b,M])),ae=o.object({name:o.string(),version:o.string(),description:o.string().optional(),fields:o.record(x),indexes:o.array(D).optional(),constraints:re.optional(),metadata:o.record(o.any()).optional(),dependencies:o.array(o.string()).optional(),migrations:o.array(o.any()).optional()}),O=o.union([o.object({type:o.literal("addField"),name:o.string(),definition:x}),o.object({type:o.literal("removeField"),name:o.string()}),o.object({type:o.literal("modifyField"),name:o.string(),changes:x.partial()}),o.object({type:o.literal("addIndex"),definition:D}),o.object({type:o.literal("removeIndex"),name:o.string()}),o.object({type:o.literal("modifyIndex"),name:o.string(),changes:D.partial()}),o.object({type:o.literal("addConstraint"),constraint:o.union([b,M])}),o.object({type:o.literal("removeConstraint"),name:o.string()}),o.object({type:o.literal("modifyConstraint"),name:o.string(),changes:b.partial()}),o.object({type:o.literal("deprecateField"),name:o.string()})]),ie=o.object({id:o.string(),schemaVersion:o.string(),changes:o.array(O),description:o.string(),status:o.enum(["pending","applied","failed"]),rollback:o.array(O).optional(),transform:o.unknown(),createdAt:o.string(),checksum:o.string().optional()});function oe(e){try{return ie.parse(e),!0}catch(r){throw new S("Invalid migration definition",r)}}function se(e){try{return O.parse(e),!0}catch(r){throw new S("Invalid schema definition",r)}}function U(e){try{return ae.parse(e),!0}catch(r){throw new S("Invalid schema definition",r)}}var Oe=U;var B=async e=>{if(typeof window<"u"&&crypto.subtle){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}else{let{createHash:r}=await import("crypto");return r("sha256").update(e).digest("hex")}};function ce(e){let r=e.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!r)throw new Error(`Invalid version format: ${e}. Expected format: major.minor.patch`);return{major:parseInt(r[1],10),minor:parseInt(r[2],10),patch:parseInt(r[3],10)}}function pe(e,r){if(r&&"field"in e&&e.field){let t=r.fields[e.field];if(t)return t.type}if("parameters"in e){let t=e.parameters;if(t instanceof RegExp||Array.isArray(t)&&typeof t[0]=="string")return"string";if(typeof t=="number"||Array.isArray(t)&&typeof t[0]=="number")return"number";if(typeof t=="boolean")return"boolean";if(typeof t=="object"&&t!==null){if("minItems"in t||"maxItems"in t)return"array";if("schema"in t)return"object"}}}function me(e){return e.required===!0||e.type!==void 0||e.itemsType!==void 0||e.nestedSchema!==void 0||e.reference!==void 0||e.unique===!0}function de(e,r,t){switch(t){case"string":if(e instanceof RegExp&&r instanceof RegExp)return e.source!==r.source;if(Array.isArray(e)&&Array.isArray(r))return r.length<e.length||!e.every(n=>r.includes(n));break;case"number":if(typeof e=="object"&&typeof r=="object"&&"precision"in e&&"precision"in r)return r.precision<e.precision||(r.scale??0)<(e.scale??0);if(Array.isArray(e)&&Array.isArray(r))return r.length<e.length||!e.every(n=>r.includes(n));break;case"array":if(typeof e=="object"&&typeof r=="object"&&"minItems"in e&&"maxItems"in e&&"minItems"in r&&"maxItems"in r)return r.minItems>e.minItems||r.maxItems<e.maxItems;break;case"object":if(typeof e=="object"&&typeof r=="object"&&"schema"in e&&"schema"in r)return Object.keys(r.schema).length>Object.keys(e.schema).length;break}return!1}function le(e,r){let t={or:1,xor:2,and:3,not:4,nor:4};return!!(r.operator&&t[r.operator]>t[e.operator]||r.rules&&r.rules.length>e.rules.length)}function fe(e,r,t){if(!r)return!0;if("rules"in r&&"rules"in e)return le(r,e);if("predicate"in e&&e.predicate!==void 0)return!0;if("parameters"in e&&e.parameters!==void 0){let n=pe(r,t);return n?de(r.parameters,e.parameters,n):!0}return!1}function ue(e,r){switch(e.type){case"removeField":case"removeIndex":return"major";case"modifyField":return me(e.changes)?"major":e.changes.deprecated?"minor":"patch";case"modifyIndex":return e.changes.unique!==void 0||e.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let t=r?.constraints?.find(n=>"name"in n&&n.name===e.name);return fe(e.changes,t,r)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(e)}`)}}function he(e){let r=new Set,t=new Set,n=new Set,a=new Set;for(let i of e)switch(i.type){case"addField":if(t.has(i.name))throw new Error(`Cannot add previously removed field: ${i.name}`);if(r.has(i.name))throw new Error(`Cannot add already modified field: ${i.name}`);if(a.has(i.name))throw new Error(`Cannot add deprecated field: ${i.name}`);n.add(i.name);break;case"removeField":if(n.has(i.name))throw new Error(`Cannot remove newly added field: ${i.name}`);if(r.has(i.name))throw new Error(`Cannot remove modified field: ${i.name}`);if(a.has(i.name))throw new Error(`Cannot remove field that is being deprecated: ${i.name}`);t.add(i.name);break;case"modifyField":if(t.has(i.name))throw new Error(`Cannot modify removed field: ${i.name}`);if(n.has(i.name))throw new Error(`Cannot modify newly added field: ${i.name}`);if(a.has(i.name))throw new Error(`Cannot modify field that is being deprecated: ${i.name}`);r.add(i.name);break;case"deprecateField":if(t.has(i.name))throw new Error(`Cannot deprecate removed field: ${i.name}`);if(n.has(i.name))throw new Error(`Cannot deprecate newly added field: ${i.name}`);if(r.has(i.name))throw new Error(`Cannot deprecate modified field: ${i.name}`);a.add(i.name);break}}function ye(e){let r=new Set,t=new Set,n=new Set;for(let a of e)switch(a.type){case"addConstraint":let i=a.constraint,m=("name"in i,i.name);if(t.has(m))throw new Error(`Cannot add previously removed constraint: ${m}`);if(r.has(m))throw new Error(`Cannot add already modified constraint: ${m}`);n.add(m);break;case"removeConstraint":if(n.has(a.name))throw new Error(`Cannot remove newly added constraint: ${a.name}`);if(r.has(a.name))throw new Error(`Cannot remove modified constraint: ${a.name}`);t.add(a.name);break;case"modifyConstraint":if(t.has(a.name))throw new Error(`Cannot modify removed constraint: ${a.name}`);if(n.has(a.name))throw new Error(`Cannot modify newly added constraint: ${a.name}`);r.add(a.name);break}}function ge(e,r,t){if(r.length===0)throw new Error("No changes provided");he(r),ye(r);let n=ce(e),a="patch";for(let i of r){let m=ue(i,t);if(m==="major"){a="major";break}else m==="minor"&&a==="patch"&&(a="minor")}switch(a){case"major":return`${n.major+1}.0.0`;case"minor":return`${n.major}.${n.minor+1}.0`;case"patch":return`${n.major}.${n.minor}.${n.patch+1}`}}function P(e,r){let t=s=>s.split(".").map(l=>parseInt(l,10)||0),[n,a,i]=t(e),[m,c,d]=t(r);return n-m||a-c||i-d}function Fe(e){return e.sort(P)}var z=class extends Error{constructor(t,n,a,i){super(t);this.code=n;this.migrationId=a;this.cause=i;this.name="MigrationError"}},we=(p=>(p.INVALID_SCHEMA="INVALID_SCHEMA",p.INVALID_MIGRATION="INVALID_MIGRATION",p.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",p.TIMEOUT="TIMEOUT",p.MEMORY_LIMIT="MEMORY_LIMIT",p.CONCURRENT_OPERATION="CONCURRENT_OPERATION",p.TRANSFORM_ERROR="TRANSFORM_ERROR",p.VERSION_NOT_FOUND="VERSION_NOT_FOUND",p.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",p.STREAM_ERROR="STREAM_ERROR",p.ROLLBACK_ERROR="ROLLBACK_ERROR",p.MISSING_TRANSFORM="MISSING_TRANSFORM",p))(we||{});var Se=e=>{let r=[],t=[];return{addField:(n,a)=>{r.push({type:"addField",name:n,definition:a}),t.push({type:"removeField",name:n})},removeField:n=>{r.push({type:"removeField",name:n});let a=e.fields[n];a&&t.push({type:"addField",name:n,definition:a})},modifyField:(n,a)=>{r.push({type:"modifyField",name:n,changes:a});let i=e.fields[n];t.push({type:"modifyField",name:n,changes:i})},deprecateField:n=>{r.push({type:"deprecateField",name:n}),t.push({type:"modifyField",name:n,changes:{deprecated:!1}})},addIndex:n=>{r.push({type:"addIndex",definition:n}),t.push({type:"removeIndex",name:n.name})},removeIndex:n=>{r.push({type:"removeIndex",name:n});let a=e.indexes?.find(i=>i.name===n);a&&t.push({type:"addIndex",definition:a})},modifyIndex:(n,a)=>{r.push({type:"modifyIndex",name:n,changes:a});let i=e.indexes?.find(m=>m.name===n);i&&t.push({type:"modifyIndex",name:n,changes:i})},addConstraint:n=>{r.push({type:"addConstraint",constraint:n}),t.push({type:"removeConstraint",name:n.name})},removeConstraint:n=>{r.push({type:"removeConstraint",name:n});let a=e.constraints?.find(i=>"name"in i&&i.name===n);a&&t.push({type:"addConstraint",constraint:a})},modifyConstraint:(n,a)=>{r.push({type:"modifyConstraint",name:n,changes:a});let i=e.constraints?.find(m=>"name"in m&&m.name===n);i&&t.push({type:"modifyConstraint",name:n,changes:i})},changes:()=>({migrate:r,rollback:t})}};import wt from"@isomorphic-git/lightning-fs";import{Buffer as be}from"buffer";import vt from"isomorphic-git";import $t from"isomorphic-git/http/web";window.Buffer=be;function ve(e,r,t){switch(e.type){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return e.itemsType?e.itemsType==="object"&&e.nestedSchema?`${`${r}ItemsItem`}[]`:`${e.itemsType}[]`:"any[]";case"object":return e.nestedSchema?`${r}${N(t)}`:"Record<string, any>";case"dynamic":return"any";default:return"any"}}function F(e,r){let t="";for(let[n,a]of Object.entries(e))if(a.type==="object"&&a.nestedSchema){let i=`${r}${N(n)}`;t+=`
2
+ export interface ${i} {
3
+ ${A(a.nestedSchema,i)}
4
+ }`;let m=F(a.nestedSchema,i);m&&(t+=`
5
+ ${m}`)}else if(a.type==="array"&&a.itemsType==="object"&&a.nestedSchema){let i=`${r}ItemsItem`;t+=`
6
+ export interface ${i} {
7
+ ${A(a.nestedSchema,i)}
8
+ }`;let m=F(a.nestedSchema,i);m&&(t+=`
9
+ ${m}`)}return t}function A(e,r){return Object.entries(e).map(([t,n])=>{let a=[];n.description&&a.push(` /** ${n.description} */`),n.deprecated&&a.push(" /** @deprecated */");let i=n.required?"":"?",m=ve(n,r,t);return a.push(` ${t}${i}: ${m};`),a.join(`
10
+ `)}).join(`
11
+ `)}function N(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Dt(e){let r=N(e.name),t=`// Generated from schema version ${e.version}
12
+ `;e.description&&(t+=`/** ${e.description} */
13
+ `),t+=`export interface ${r} {
14
+ ${A(e.fields,r)}
15
+ }`;let n=F(e.fields,r);return n&&(t+=`
16
+ ${n}`),t+=`
17
+ `,t}function Mt(e,r){let t=[],n=c=>c===void 0?"`None`":`\`${JSON.stringify(c,null,2)}\``,a=(c=[])=>c.map(d=>`- **${d.name}**: ${d.description||""}
18
+ - Parameters: ${JSON.stringify(d.parameters)}
19
+ - Error: ${d.errorMessage||"None"}`).join(`
20
+ `),i=c=>{let d=`**${c.field}** ${c.operator}`;return c.value!==void 0&&(d+=` ${JSON.stringify(c.value)}`),c.conditions&&(d+=` [
21
+ ${c.conditions.map(s=>` ${i(s)}`).join(`
22
+ `)}
23
+ ]`),d},m=(c,d=1)=>{let s="#".repeat(d+2);return Object.entries(c).map(([l,u])=>{let p=`${s} ${l} (${u.type})
24
+
25
+ `;return p+=`**Required:** ${u.required?"Yes":"No"}
26
+
27
+ `,u.description&&(p+=`**Description:** ${u.description}
28
+
29
+ `),u.itemsType&&(p+=`**Item Type:** ${u.itemsType}
30
+
31
+ `),u.nestedSchema&&(p+=m(u.nestedSchema,d+1)),p}).join(`
32
+ `)};t.push(`# ${e.name} Schema (Version ${e.version})`),e.description&&t.push(`
33
+ ${e.description}
34
+ `),t.push("## Metadata"),t.push(`- **Dependencies:** ${e.dependencies?.join(", ")||"None"}`),t.push(`- **Created:** ${new Date().toISOString()}
35
+ `),t.push(`## Fields
36
+ `),t.push("| Name | Type | Required | Default | Description | Deprecated | Unique | Constraints |"),t.push("|------|------|----------|---------|-------------|------------|--------|-------------|");for(let[c,d]of Object.entries(e.fields))t.push([c,d.type,d.required?"Yes":"No",n(d.default),d.description?.replace(/\n/g," ")||"",d.deprecated?"Yes":"No",d.unique?"Yes":"No",d.constraints?.length||0].join("|"));Object.entries(e.fields).forEach(([c,d])=>{d.nestedSchema&&(t.push(`
37
+ ### Nested Schema: ${c}
38
+ `),t.push(m(d.nestedSchema)))}),t.push(`
39
+ ## Indexes
40
+ `),t.push("| Name | Type | Fields | Unique | Order | Partial Condition | Description |"),t.push("|------|------|--------|--------|-------|-------------------|-------------|");for(let c of e.indexes||[])t.push([c.name,c.type,c.fields.join(", "),c.unique?"Yes":"No",c.order||"asc",c.partial?i(c.partial):"None",c.description||""].join("|"));t.push(`
41
+ ## Constraints
42
+ `),e.constraints&&t.push("### Schema-level Constraints"),t.push(`
43
+ ## Migrations
44
+ `),t.push("| ID | Description | Status | Changes |"),t.push("|----|-------------|--------|---------|");for(let c of e.migrations||[])t.push([c.id,c.description,c.status,c.changes.length].join("|"));if(e.mock&&r?.faker)try{let c=e.mock(r.faker).next().value;t.push("\n## Example Data\n```json\n"+JSON.stringify(c,null,2)+"\n```")}catch{t.push(`
45
+ <!-- Error generating mock data -->`)}return t.join(`
46
+ `)}export{y as JsonPatchError,z as MigrationError,we as MigrationErrorCode,ie as MigrationSchema,j as applyPatch,ge as calculateNextVersion,P as compareSemanticVersions,$e as createPatch,Se as createSchemaMigrationHelper,ee as createStandardSchemaValidator,_ as deepMerge,Mt as docgen,B as generateSHA256Hash,q as normalizePath,Z as schemaChangeToPatch,Dt as schemaToTypes,Fe as sortSemanticVars,Oe as validate,oe as validateMigration,se as validateSchemaChange,U as validateSchemaDefinition};