@asaidimu/utils-database 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.mts CHANGED
@@ -1,5 +1,17 @@
1
1
  import { QueryFilter, PaginationOptions } from '@asaidimu/query';
2
2
  import { SchemaDefinition, SchemaChange, DataTransform, PredicateMap } from '@asaidimu/anansi';
3
+ import { EventBus } from '@asaidimu/events';
4
+ import { StandardSchemaV1 } from '@standard-schema/spec';
5
+
6
+ declare class TransactionContext {
7
+ readonly id: string;
8
+ private buffer;
9
+ private committed;
10
+ constructor();
11
+ addOp(store: Store<any>, type: "put" | "delete", data: any): void;
12
+ commit(): Promise<void>;
13
+ rollback(): void;
14
+ }
3
15
 
4
16
  declare const DEFAULT_KEYPATH = "$id";
5
17
  interface CursorPaginationOptions {
@@ -288,6 +300,22 @@ interface Database {
288
300
  * Closes the connection to the database
289
301
  */
290
302
  close: () => void;
303
+ /**
304
+ * Ensures a collection exists; creates it if it doesn't.
305
+ * Idempotent – safe to call multiple times.
306
+ * @param schema - The schema definition for the collection.
307
+ * @returns A promise that resolves when the collection exists.
308
+ * @throws {DatabaseError} If validation fails or an unexpected error occurs.
309
+ */
310
+ ensureCollection: (schema: SchemaDefinition) => Promise<void>;
311
+ /**
312
+ * Ensures multiple collections exist; creates any that don't.
313
+ * Idempotent – safe to call multiple times.
314
+ * @param schemas - An array of schema definitions.
315
+ * @returns A promise that resolves when all collections exist.
316
+ * @throws {DatabaseError} If any schema validation fails or an unexpected error occurs.
317
+ */
318
+ setupCollections: (schemas: SchemaDefinition[]) => Promise<void>;
291
319
  }
292
320
  type CollectionMigrationOptions = {
293
321
  changes: SchemaChange<any>[];
@@ -308,27 +336,32 @@ type Document<T> = {
308
336
  readonly [K in keyof T]: T[K];
309
337
  } & {
310
338
  /**
311
- * A unique identifier for the document
312
- * @returns A promise resolving to `true` if successful, or `false` if an error occurs.
339
+ * Unique identifier for the document (assigned automatically if not provided).
313
340
  */
314
341
  $id?: string;
315
342
  /**
316
- * A timestamp indicating when the document was created
343
+ * Timestamp of document creation (ISO string or Date).
317
344
  */
318
345
  $created?: string | Date;
319
346
  /**
320
- * A timestamp indicating when the document was last updated
347
+ * Timestamp of last document update (ISO string or Date).
321
348
  */
322
349
  $updated?: string | Date;
323
350
  /**
324
- * A number representing how many times the document has changed
351
+ * Version number incremented on each change (used for optimistic concurrency control).
325
352
  */
326
353
  $version?: number;
327
354
  /**
328
- * Fetches the latest data from the database
355
+ * Fetches the latest data from the database and updates the document instance.
329
356
  * @returns A promise resolving to `true` if successful, or `false` if an error occurs.
330
357
  */
331
358
  read: () => Promise<boolean>;
359
+ /**
360
+ * Saves the current document state to the database.
361
+ * Normally called automatically by `update()` or `delete()`, but can be used manually.
362
+ * @returns A promise resolving to `true` if successful, or `false` if an error occurs.
363
+ */
364
+ save: (tx?: TransactionContext) => Promise<boolean>;
332
365
  /**
333
366
  * Updates the document with the provided properties.
334
367
  * @param props - Partial object containing the fields to update.
@@ -344,9 +377,13 @@ type Document<T> = {
344
377
  * Subscribes to document events (e.g., "update", "delete", "access").
345
378
  * @param event - The event type to subscribe to.
346
379
  * @param callback - The function to call when the event occurs.
347
- * @returns A promise resolving to an unsubscribe function.
380
+ * @returns An unsubscribe function.
348
381
  */
349
382
  subscribe: (event: DocumentEventType | TelemetryEventType, callback: (event: DocumentEvent<T> | TelemetryEvent) => void) => () => void;
383
+ /**
384
+ * Returns a plain object containing only the user-defined data (without system fields like $id, $version, etc.).
385
+ * @returns The current user data.
386
+ */
350
387
  state(): T;
351
388
  };
352
389
  /**
@@ -524,4 +561,63 @@ declare class IndexedDBStore<T extends Record<string, any>> implements Store<T>
524
561
 
525
562
  declare const createIndexedDbStore: <T extends Record<string, any>>(config: DatabaseConfig) => Store<T>;
526
563
 
527
- export { type Collection, type CollectionEvent, type CollectionEventType, type CollectionMigrationOptions, ConnectionManager, type CursorCallback, type CursorCallbackResult, type CursorPaginationOptions, DEFAULT_KEYPATH, type Database, type DatabaseConfig, type DatabaseEvent, type DatabaseEventType, type Document, type DocumentEvent, type DocumentEventType, IndexedDBStore, type Store, type StoreKeyRange, type TelemetryEvent, type TelemetryEventType, createEphemeralStore, createIndexedDbStore };
564
+ declare function DatabaseConnection(config: Omit<DatabaseConfig, "keyPath">, createStore: <T extends Record<string, any>>(config: DatabaseConfig) => Store<T>): Promise<Database>;
565
+
566
+ declare class IndexManager<T extends Record<string, any>> {
567
+ private indexes;
568
+ createIndex(field: string): void;
569
+ removeIndex(field: string): void;
570
+ hasIndex(field: string): boolean;
571
+ indexDocument(doc: T): void;
572
+ removeDocument(doc: T): void;
573
+ lookup(field: string, value: any): Set<string | number> | undefined;
574
+ clear(): void;
575
+ }
576
+
577
+ interface MiddlewareContext {
578
+ collection?: string;
579
+ documentId?: string;
580
+ operation: string;
581
+ args: any[];
582
+ eventBus?: EventBus<any>;
583
+ }
584
+ type MaybePromise<T> = T | Promise<T>;
585
+ type MiddlewareNext = () => MaybePromise<any>;
586
+ type Middleware = (ctx: MiddlewareContext, next: MiddlewareNext) => MaybePromise<any>;
587
+ declare class Pipeline {
588
+ private middlewares;
589
+ use(middleware: Middleware): void;
590
+ execute(ctx: MiddlewareContext, finalOperation: () => MaybePromise<any>): MaybePromise<any>;
591
+ wrap<T extends object>(target: T, baseContext: Partial<MiddlewareContext>): T;
592
+ }
593
+
594
+ declare class Mutex {
595
+ private queue;
596
+ private locked;
597
+ acquire(): Promise<() => void>;
598
+ private release;
599
+ }
600
+
601
+ interface DocumentOptions<T extends Record<string, any>> {
602
+ initial: Partial<T>;
603
+ collection: string;
604
+ validator?: StandardSchemaV1;
605
+ store: Store<T>;
606
+ bus: EventBus<Record<DocumentEventType | TelemetryEventType, DocumentEvent<T> | TelemetryEvent>>;
607
+ pipeline: Pipeline;
608
+ lockManager: Mutex;
609
+ indexManager: IndexManager<T>;
610
+ }
611
+ declare function createDocument<T extends Record<string, any>>(opts: DocumentOptions<T>): Promise<Document<T & {
612
+ $id: string | number;
613
+ }>>;
614
+ declare function openCollection<T extends Record<string, any>>({ collection: schema, validator, bus, store, pipeline, validate, }: {
615
+ store: Store<T>;
616
+ collection: string;
617
+ validator: StandardSchemaV1;
618
+ bus: EventBus<any>;
619
+ pipeline: Pipeline;
620
+ validate: boolean;
621
+ }): Promise<Collection<T>>;
622
+
623
+ export { type Collection, type CollectionEvent, type CollectionEventType, type CollectionMigrationOptions, ConnectionManager, type CursorCallback, type CursorCallbackResult, type CursorPaginationOptions, DEFAULT_KEYPATH, type Database, type DatabaseConfig, DatabaseConnection, type DatabaseEvent, type DatabaseEventType, type Document, type DocumentEvent, type DocumentEventType, IndexedDBStore, type Store, type StoreKeyRange, type TelemetryEvent, type TelemetryEventType, createDocument, createEphemeralStore, createIndexedDbStore, openCollection };
package/index.d.ts CHANGED
@@ -1,5 +1,17 @@
1
1
  import { QueryFilter, PaginationOptions } from '@asaidimu/query';
2
2
  import { SchemaDefinition, SchemaChange, DataTransform, PredicateMap } from '@asaidimu/anansi';
3
+ import { EventBus } from '@asaidimu/events';
4
+ import { StandardSchemaV1 } from '@standard-schema/spec';
5
+
6
+ declare class TransactionContext {
7
+ readonly id: string;
8
+ private buffer;
9
+ private committed;
10
+ constructor();
11
+ addOp(store: Store<any>, type: "put" | "delete", data: any): void;
12
+ commit(): Promise<void>;
13
+ rollback(): void;
14
+ }
3
15
 
4
16
  declare const DEFAULT_KEYPATH = "$id";
5
17
  interface CursorPaginationOptions {
@@ -288,6 +300,22 @@ interface Database {
288
300
  * Closes the connection to the database
289
301
  */
290
302
  close: () => void;
303
+ /**
304
+ * Ensures a collection exists; creates it if it doesn't.
305
+ * Idempotent – safe to call multiple times.
306
+ * @param schema - The schema definition for the collection.
307
+ * @returns A promise that resolves when the collection exists.
308
+ * @throws {DatabaseError} If validation fails or an unexpected error occurs.
309
+ */
310
+ ensureCollection: (schema: SchemaDefinition) => Promise<void>;
311
+ /**
312
+ * Ensures multiple collections exist; creates any that don't.
313
+ * Idempotent – safe to call multiple times.
314
+ * @param schemas - An array of schema definitions.
315
+ * @returns A promise that resolves when all collections exist.
316
+ * @throws {DatabaseError} If any schema validation fails or an unexpected error occurs.
317
+ */
318
+ setupCollections: (schemas: SchemaDefinition[]) => Promise<void>;
291
319
  }
292
320
  type CollectionMigrationOptions = {
293
321
  changes: SchemaChange<any>[];
@@ -308,27 +336,32 @@ type Document<T> = {
308
336
  readonly [K in keyof T]: T[K];
309
337
  } & {
310
338
  /**
311
- * A unique identifier for the document
312
- * @returns A promise resolving to `true` if successful, or `false` if an error occurs.
339
+ * Unique identifier for the document (assigned automatically if not provided).
313
340
  */
314
341
  $id?: string;
315
342
  /**
316
- * A timestamp indicating when the document was created
343
+ * Timestamp of document creation (ISO string or Date).
317
344
  */
318
345
  $created?: string | Date;
319
346
  /**
320
- * A timestamp indicating when the document was last updated
347
+ * Timestamp of last document update (ISO string or Date).
321
348
  */
322
349
  $updated?: string | Date;
323
350
  /**
324
- * A number representing how many times the document has changed
351
+ * Version number incremented on each change (used for optimistic concurrency control).
325
352
  */
326
353
  $version?: number;
327
354
  /**
328
- * Fetches the latest data from the database
355
+ * Fetches the latest data from the database and updates the document instance.
329
356
  * @returns A promise resolving to `true` if successful, or `false` if an error occurs.
330
357
  */
331
358
  read: () => Promise<boolean>;
359
+ /**
360
+ * Saves the current document state to the database.
361
+ * Normally called automatically by `update()` or `delete()`, but can be used manually.
362
+ * @returns A promise resolving to `true` if successful, or `false` if an error occurs.
363
+ */
364
+ save: (tx?: TransactionContext) => Promise<boolean>;
332
365
  /**
333
366
  * Updates the document with the provided properties.
334
367
  * @param props - Partial object containing the fields to update.
@@ -344,9 +377,13 @@ type Document<T> = {
344
377
  * Subscribes to document events (e.g., "update", "delete", "access").
345
378
  * @param event - The event type to subscribe to.
346
379
  * @param callback - The function to call when the event occurs.
347
- * @returns A promise resolving to an unsubscribe function.
380
+ * @returns An unsubscribe function.
348
381
  */
349
382
  subscribe: (event: DocumentEventType | TelemetryEventType, callback: (event: DocumentEvent<T> | TelemetryEvent) => void) => () => void;
383
+ /**
384
+ * Returns a plain object containing only the user-defined data (without system fields like $id, $version, etc.).
385
+ * @returns The current user data.
386
+ */
350
387
  state(): T;
351
388
  };
352
389
  /**
@@ -524,4 +561,63 @@ declare class IndexedDBStore<T extends Record<string, any>> implements Store<T>
524
561
 
525
562
  declare const createIndexedDbStore: <T extends Record<string, any>>(config: DatabaseConfig) => Store<T>;
526
563
 
527
- export { type Collection, type CollectionEvent, type CollectionEventType, type CollectionMigrationOptions, ConnectionManager, type CursorCallback, type CursorCallbackResult, type CursorPaginationOptions, DEFAULT_KEYPATH, type Database, type DatabaseConfig, type DatabaseEvent, type DatabaseEventType, type Document, type DocumentEvent, type DocumentEventType, IndexedDBStore, type Store, type StoreKeyRange, type TelemetryEvent, type TelemetryEventType, createEphemeralStore, createIndexedDbStore };
564
+ declare function DatabaseConnection(config: Omit<DatabaseConfig, "keyPath">, createStore: <T extends Record<string, any>>(config: DatabaseConfig) => Store<T>): Promise<Database>;
565
+
566
+ declare class IndexManager<T extends Record<string, any>> {
567
+ private indexes;
568
+ createIndex(field: string): void;
569
+ removeIndex(field: string): void;
570
+ hasIndex(field: string): boolean;
571
+ indexDocument(doc: T): void;
572
+ removeDocument(doc: T): void;
573
+ lookup(field: string, value: any): Set<string | number> | undefined;
574
+ clear(): void;
575
+ }
576
+
577
+ interface MiddlewareContext {
578
+ collection?: string;
579
+ documentId?: string;
580
+ operation: string;
581
+ args: any[];
582
+ eventBus?: EventBus<any>;
583
+ }
584
+ type MaybePromise<T> = T | Promise<T>;
585
+ type MiddlewareNext = () => MaybePromise<any>;
586
+ type Middleware = (ctx: MiddlewareContext, next: MiddlewareNext) => MaybePromise<any>;
587
+ declare class Pipeline {
588
+ private middlewares;
589
+ use(middleware: Middleware): void;
590
+ execute(ctx: MiddlewareContext, finalOperation: () => MaybePromise<any>): MaybePromise<any>;
591
+ wrap<T extends object>(target: T, baseContext: Partial<MiddlewareContext>): T;
592
+ }
593
+
594
+ declare class Mutex {
595
+ private queue;
596
+ private locked;
597
+ acquire(): Promise<() => void>;
598
+ private release;
599
+ }
600
+
601
+ interface DocumentOptions<T extends Record<string, any>> {
602
+ initial: Partial<T>;
603
+ collection: string;
604
+ validator?: StandardSchemaV1;
605
+ store: Store<T>;
606
+ bus: EventBus<Record<DocumentEventType | TelemetryEventType, DocumentEvent<T> | TelemetryEvent>>;
607
+ pipeline: Pipeline;
608
+ lockManager: Mutex;
609
+ indexManager: IndexManager<T>;
610
+ }
611
+ declare function createDocument<T extends Record<string, any>>(opts: DocumentOptions<T>): Promise<Document<T & {
612
+ $id: string | number;
613
+ }>>;
614
+ declare function openCollection<T extends Record<string, any>>({ collection: schema, validator, bus, store, pipeline, validate, }: {
615
+ store: Store<T>;
616
+ collection: string;
617
+ validator: StandardSchemaV1;
618
+ bus: EventBus<any>;
619
+ pipeline: Pipeline;
620
+ validate: boolean;
621
+ }): Promise<Collection<T>>;
622
+
623
+ export { type Collection, type CollectionEvent, type CollectionEventType, type CollectionMigrationOptions, ConnectionManager, type CursorCallback, type CursorCallbackResult, type CursorPaginationOptions, DEFAULT_KEYPATH, type Database, type DatabaseConfig, DatabaseConnection, type DatabaseEvent, type DatabaseEventType, type Document, type DocumentEvent, type DocumentEventType, IndexedDBStore, type Store, type StoreKeyRange, type TelemetryEvent, type TelemetryEventType, createDocument, createEphemeralStore, createIndexedDbStore, openCollection };
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=class extends Error{type;schema;constructor(e,t,r,s){super(t,{cause:s}),this.type=e,this.schema=r,this.name="DatabaseError"}};function t(t,r){if(t&&void 0!==t.$version&&void 0!==r.$version&&r.$version<=t.$version)throw new e("CONFLICT",`OCC Conflict: Incoming version (${r.$version}) is not greater than existing version (${t.$version}).`)}var r=class{constructor(e="$id"){this.keyPath=e}data=new Map;nextId=1;async open(){}getKey(t){const r=t[this.keyPath];if(null==r)throw new e("INVALID_DATA",`Record must have a ${this.keyPath} property`);return r}clone(e){return{...e}}async add(t){const r=Array.isArray(t)?t:[t],s=[];for(const t of r){let r=t[this.keyPath];if(void 0!==r&&""!==r||(r=String(this.nextId++),t[this.keyPath]=r),this.data.has(r))throw new e("CONFLICT",`Duplicate key ${r}`);this.data.set(r,Object.freeze(this.clone(t))),s.push(r)}return Array.isArray(t)?s:s[0]}async put(e){const r=this.getKey(e);return t(this.data.get(r),e),this.data.set(r,Object.freeze(this.clone(e))),r}async batch(r){const s=new Map,o=e=>s.has(e)?s.get(e):this.data.get(e);try{for(const n of r)if("add"===n.type||"put"===n.type){const r=Array.isArray(n.data)?n.data:[n.data];for(const i of r){let r=i[this.keyPath];"add"!==n.type||r&&""!==r?r=this.getKey(i):(r=String(this.nextId++),i[this.keyPath]=r);const a=o(r);if("add"===n.type&&null!=a)throw new e("CONFLICT",`Duplicate key ${r}`);t(a,i),s.set(r,Object.freeze(this.clone(i)))}}else if("delete"===n.type){const e=Array.isArray(n.data)?n.data:[n.data];for(const t of e)s.set(t,null)}for(const[e,t]of s.entries())null===t?this.data.delete(e):this.data.set(e,t)}catch(e){throw e}}async getById(e){const t=this.data.get(e);return t?this.clone(t):void 0}async delete(e){const t=Array.isArray(e)?e:[e];for(const e of t)this.data.delete(e)}async clear(){this.data.clear()}async count(){return this.data.size}async getByIndex(e,t){for(const r of this.data.values())if(r[e]===t)return this.clone(r)}async getByKeyRange(e,t){const r=[];for(const s of this.data.values()){const o=s[e];this.isInKeyRange(o,t)&&r.push(this.clone(s))}return r}isInKeyRange(e,t){if(!t)return!0;const{lower:r,upper:s,lowerOpen:o=!1,upperOpen:n=!1}=t;return(void 0===r||(o?e>r:e>=r))&&(void 0===s||(n?e<s:e<=s))}async getAll(){return Array.from(this.data.values()).map((e=>this.clone(e)))}async cursor(e,t="forward",r){let s=Array.from(this.data.entries());r&&(s=s.filter((([e])=>{const t=e,s=void 0===r.lower||(r.lowerOpen?t>r.lower:t>=r.lower),o=void 0===r.upper||(r.upperOpen?t<r.upper:t<=r.upper);return s&&o})));const o=s.sort((([e],[t])=>e>t?1:e<t?-1:0));"backward"===t&&o.reverse();let n=null,i=0;for(;i<o.length;){const[t,r]=o[i],{value:s,done:a,offset:c}=await e(this.clone(r),t,null);if(n=s,a)break;c&&c>0?i+=c:i++}return n}};var s=class e extends Error{constructor(t,r){super(t,{cause:r}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},o=class extends s{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},n=class{_locked=!1;_capacity;_yieldMode;waiters=[];constructor(e){this._capacity=e?.capacity??1/0,this._yieldMode=e?.yieldMode??"macrotask"}async lock(e){if(!this._locked)return void(this._locked=!0);if(this.waiters.length>=this._capacity)throw new Error(`Mutex queue is full (capacity: ${this._capacity})`);let t;const r=new Promise((e=>t=e));this.waiters.push(t),null!=e?await Promise.race([r,new Promise(((r,s)=>setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),s(new o("Mutex lock timed out"))}),e)))]):await r}tryLock(){return!this._locked&&(this._locked=!0,!0)}unlock(){if(!this._locked)throw new Error("Mutex is not locked");const e=this.waiters.shift();e?"microtask"===this._yieldMode?queueMicrotask(e):setTimeout(e,0):this._locked=!1}locked(){return this._locked}pending(){return this.waiters.length}},i=class{mutex=new n({yieldMode:"microtask"});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=Boolean(e),this.throws=Boolean(t)}async do(e,t){return this._done?this.peek():this.promise?this._awaitWithTimeout(this.promise,t,"Once do() timed out"):(await this.mutex.lock(),this.promise?(this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")):(this.promise=(async()=>{try{const t=await e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.promise=null}return this.peek()})(),this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")))}isReady(){return this._done&&null===this.promise}running(){return null!==this.promise&&!this._done}peek(){return{value:this._value,error:this._error}}get(){if(!this._done)throw new Error("Once operation is not yet complete");if(this._error)throw this._error;return this._value}reset(){this._done=!1,this.promise=null,this._value=null,this._error=void 0}resolved(){return this.promise}done(){return this._done}_awaitWithTimeout(e,t,r="Operation timed out"){return null==t?e:Promise.race([e,new Promise(((e,s)=>setTimeout((()=>s(new o(r))),t)))])}},a=class{constructor(e){this.config=e,this.schemasStoreName=e.schemasStoreName||"schemas"}connectionInitializer=new i({retry:!0,throws:!0});schemasStoreName;async openDatabase(){return new Promise(((e,t)=>{const r=indexedDB.open(this.config.name);r.onerror=()=>t(new Error(`Failed to open database: ${r.error?.message}`)),r.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(this.schemasStoreName)||t.createObjectStore(this.schemasStoreName,{keyPath:"name"})},r.onsuccess=()=>e(r.result)}))}async upgradeDatabase(e,t){const r=e.version+1;return e.close(),new Promise(((e,s)=>{const o=indexedDB.open(this.config.name,r);o.onerror=()=>s(new Error(`Failed to upgrade database: ${o.error?.message}`)),o.onupgradeneeded=e=>{const r=e.target.result;t(r)},o.onsuccess=()=>e(o.result)}))}async ensureStore(e,t="$id"){(await this.getConnection()).objectStoreNames.contains(e)||await this.upgrade((r=>{r.objectStoreNames.contains(this.schemasStoreName)||r.createObjectStore(this.schemasStoreName,{keyPath:"name"}),r.objectStoreNames.contains(e)||r.createObjectStore(e,{keyPath:t})}))}getConnection=async()=>{const t=await this.connectionInitializer.do((async()=>{const e=await this.openDatabase();return e.onclose=()=>this.connectionInitializer.reset(),e.onversionchange=()=>{e.close(),this.connectionInitializer.reset()},e}));if(t.error)throw new e("CONNECTION_FAILED",`Failed to open database: ${this.config.name}`,void 0,t.error);return t.value};async upgrade(t){const r=await this.getConnection();this.connectionInitializer.reset();const s=await this.connectionInitializer.do((async()=>await this.upgradeDatabase(r,t)));if(s.error)throw new e("INTERNAL_ERROR",`Database upgrade failed for ${this.config.name}`,void 0,s.error);return s.value}close(){const e=this.connectionInitializer.peek();e.value&&e.value.close(),this.connectionInitializer.reset()}};function c(e){if(e)return void 0!==e.lower&&void 0!==e.upper?IDBKeyRange.bound(e.lower,e.upper,e.lowerOpen,e.upperOpen):void 0!==e.lower?IDBKeyRange.lowerBound(e.lower,e.lowerOpen):void 0!==e.upper?IDBKeyRange.upperBound(e.upper,e.upperOpen):void 0}var h=class{constructor(e,t,r="$id",s){this.getConnection=e,this.storeName=t,this.keyPath=r,this.onOpen=s}async open(){return this.onOpen()}mapError(t){if(t instanceof e)return t;const r=t?.message||"Unknown IndexedDB Error",s=t?.name||"";return"QuotaExceededError"===s?new e("INTERNAL_ERROR","Storage quota exceeded"):new e("VersionError"===s?"CONFLICT":"InvalidStateError"===s||"TransactionInactiveError"===s?"TRANSIENT_ERROR":"INTERNAL_ERROR",r)}async withTx(e,t){const r=await this.getConnection();return new Promise((async(s,o)=>{const n=r.transaction(this.storeName,e),i=n.objectStore(this.storeName);let a,c;n.oncomplete=()=>{c?o(c):s(a)},n.onerror=()=>o(this.mapError(n.error)),n.onabort=()=>o(this.mapError(n.error));try{const e=t(i,n);a=e instanceof Promise?a=await e:e}catch(e){c=e;try{n.abort()}catch(e){}}}))}requestToPromise(e){return new Promise(((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)}))}async put(e){return this.withTx("readwrite",(async r=>{const s=e[this.keyPath];if(void 0!==s){t(await this.requestToPromise(r.get(s)),e)}return this.requestToPromise(r.put(e))}))}async add(e){return this.withTx("readwrite",(async t=>{const r=Array.isArray(e)?e:[e],s=[];for(const e of r){const r=await this.requestToPromise(t.add(e));s.push(r)}return Array.isArray(e)?s:s[0]}))}async batch(e){return this.withTx("readwrite",(async r=>{for(const s of e)if("put"===s.type||"add"===s.type){const e=Array.isArray(s.data)?s.data:[s.data];for(const o of e)if("put"===s.type){const e=o[this.keyPath];if(void 0!==e){t(await this.requestToPromise(r.get(e)),o)}await this.requestToPromise(r.put(o))}else await this.requestToPromise(r.add(o))}else if("delete"===s.type){const e=Array.isArray(s.data)?s.data:[s.data];for(const t of e)await this.requestToPromise(r.delete(t))}}))}async getById(e){return this.withTx("readonly",(async t=>this.requestToPromise(t.get(e))))}async delete(e){return this.withTx("readwrite",(async t=>{const r=Array.isArray(e)?e:[e];for(const e of r)await this.requestToPromise(t.delete(e))}))}async clear(){return this.withTx("readwrite",(async e=>{await this.requestToPromise(e.clear())}))}async count(){return this.withTx("readonly",(async e=>this.requestToPromise(e.count())))}async getByIndex(e,t){return this.withTx("readonly",(async r=>{const s=r.index(e);return this.requestToPromise(s.get(t))}))}async getByKeyRange(e,t){return this.withTx("readonly",(async r=>{const s=r.index(e);return this.requestToPromise(s.getAll(c(t)))}))}async getAll(){return this.withTx("readonly",(async e=>this.requestToPromise(e.getAll())))}async cursor(e,t="forward",r){return this.withTx("readonly",(async s=>{const o="forward"===t?"next":"prev",n=s.openCursor(c(r),o);return new Promise(((t,r)=>{let s=null;n.onsuccess=async o=>{const n=o.target.result;if(!n)return t(s);try{const{value:r,done:o,offset:i}=await e(n.value,n.key,n);s=r,o?t(s):i&&i>0?n.advance(i):n.continue()}catch(e){r(e)}},n.onerror=()=>r(this.mapError(n.error))}))}))}};exports.ConnectionManager=a,exports.DEFAULT_KEYPATH="$id",exports.IndexedDBStore=h,exports.createEphemeralStore=function(e){return new r(e.keyPath)},exports.createIndexedDbStore=e=>{const t=new a(e),r=t.getConnection.bind(t);return new h(r,e.name,e.keyPath,(()=>t.ensureStore(e.name,e.keyPath)))};
1
+ "use strict";var e,t,r=require("buffer"),s=require("uuid"),i=Object.create,a=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,c=Object.getPrototypeOf,h=Object.prototype.hasOwnProperty,u=(e,t)=>function(){return t||(0,e[o(e)[0]])((t={exports:{}}).exports,t),t.exports},d=(e,t,r,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of o(t))h.call(e,i)||i===r||a(e,i,{get:()=>t[i],enumerable:!(s=n(t,i))||s.enumerable});return e},l=(e,t,r)=>(r=null!=e?i(c(e)):{},d(e&&e.__esModule?r:a(r,"default",{value:e,enumerable:!0}),e)),p=e=>d(a({},"__esModule",{value:!0}),e),m=u({"node_modules/@asaidimu/events/index.js"(e,t){var r,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})})(o,{createEventBus:()=>c}),t.exports=(r=o,((e,t,r,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))n.call(e,c)||c===r||s(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e})(s({},"__esModule",{value:!0}),r));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let r=[],s=0,i=0;const a=new Map,n=new Map;let o=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?o=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{s++,i+=t,a.set(e,(a.get(e)||0)+1)},h=()=>{const t=r;r=[],t.forEach((({name:t,payload:r})=>{const s=performance.now();try{(n.get(t)||[]).forEach((e=>e(r)))}catch(s){e.errorHandler({...s,eventName:t,payload:r})}c(t,performance.now()-s)}))},u=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(h,e.batchDelay)}})(),d=e=>{const r=t.get(e);r?n.set(e,Array.from(r)):n.delete(e)};return o&&(o.onmessage=e=>{const{name:t,payload:r}=e.data;(n.get(t)||[]).forEach((e=>e(r)))}),{subscribe:(e,r)=>{t.has(e)||t.set(e,new Set);const s=t.get(e);return s.add(r),d(e),()=>{s.delete(r),0===s.size?(t.delete(e),n.delete(e)):d(e)}},emit:({name:t,payload:s})=>{if(e.async)return r.push({name:t,payload:s}),r.length>=e.batchSize?h():u(),void(o&&o.postMessage({name:t,payload:s}));const i=performance.now();try{(n.get(t)||[]).forEach((e=>e(s))),o&&o.postMessage({name:t,payload:s})}catch(r){e.errorHandler({...r,eventName:t,payload:s})}c(t,performance.now()-i)},getMetrics:()=>({totalEvents:s,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:a,averageEmitDuration:s>0?i/s:0}),clear:()=>{t.clear(),n.clear(),r=[],s=0,i=0,a.clear(),o&&(o.close(),o=null)}}}}}),f=u({"node_modules/@asaidimu/query/index.js"(e,t){var r,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})})(o,{QueryBuilder:()=>c,createJoiner:()=>y,createMatcher:()=>u,createPaginator:()=>E,createProjector:()=>_,createSorter:()=>$}),t.exports=(r=o,((e,t,r,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))!n.call(e,c)&&c!==r&&s(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e})(s({},"__esModule",{value:!0}),r));var c=class{query;constructor(){this.query={}}where(e){return this.query.filters=e,this}orderBy(e,t){return this.query.sort||(this.query.sort=[]),this.query.sort.push({field:e,direction:t}),this}offset(e,t){return this.query.pagination={type:"offset",offset:e,limit:t},this}cursor(e,t,r){return this.query.pagination={type:"cursor",cursor:e,limit:t,direction:r},this}include(e){return this.query.projection||(this.query.projection={}),this.query.projection.include=e,this}exclude(e){return this.query.projection||(this.query.projection={}),this.query.projection.exclude=e,this}computed(e,t){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:"computed",expression:e,alias:t}),this}case(e,t,r){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:"case",conditions:e,else:t,alias:r}),this}join(e,t,r){return this.query.joins||(this.query.joins=[]),this.query.joins.push({relation:e,alias:r,query:t}),this}aggregate(e,t){return this.query.aggregations={groupBy:e,metrics:t},this}window(e){return this.query.window||(this.query.window=[]),this.query.window.push(e),this}hint(e){return this.query.hints||(this.query.hints=[]),this.query.hints.push(e),this}build(){return this.query}};function h(e){function t(e,t){return function(e){return"field"===e?.type}(t)?e[t.field]:function(e){return"value"===e?.type}(t)?t.value:function(e){return"function"===e?.type}(t)?s(t,e):function(e){return"computed"===e?.type}(t)?s(t.expression,e):function(e){return"case"===e?.type}(t)?function(e,t){for(let r of t.conditions)if(i(e,r.when))return r.then;return t.else}(e,t):t}let r=new Map([["and",(e,t)=>t.every((t=>i(e,t)))],["or",(e,t)=>t.some((t=>i(e,t)))],["not",(e,t)=>!t.every((t=>i(e,t)))],["nor",(e,t)=>!t.some((t=>i(e,t)))],["xor",(e,t)=>1===t.filter((t=>i(e,t))).length]]);function s(r,s){let i=r.arguments.map((e=>t(s,e)));if(e[r.function])return e[r.function](...i);throw new Error(`Function ${r.function} not found!`)}function i(s,i){if(function(e){return!!e&&void 0!==e.conditions}(i))return function(e,t){let{operator:s,conditions:i}=t,a=r.get(s);if(a)return a(e,i);throw new Error(`Unsupported logical operator: ${s}`)}(s,i);if(!i||!i.field)return!1;let{field:a,operator:n,value:o}=i,c=s[a],h=t(s,o),u=new Map([["eq",(e,t)=>e===t],["neq",(e,t)=>e!==t],["lt",(e,t)=>e<t],["lte",(e,t)=>e<=t],["gt",(e,t)=>e>t],["gte",(e,t)=>e>=t],["in",(e,t)=>Array.isArray(t)&&t.includes(e)],["nin",(e,t)=>Array.isArray(t)&&!t.includes(e)],["contains",(e,t)=>"string"==typeof e?e.includes(t):!!Array.isArray(e)&&e.includes(o)],["ncontains",(e,t)=>"string"==typeof e&&!e.includes(t)],["startswith",(e,t)=>"string"==typeof e&&e.startsWith(t)],["endswith",(e,t)=>"string"==typeof e&&e.endsWith(t)],["exists",e=>null!=e],["nexists",e=>null==e]]),d=e[n]||u.get(n);if(d)return d(c,h);throw new Error(`Unsupported comparison operator: ${n}`)}return{resolve:t,evaluate:i}}function u(e){let{evaluate:t}=h(e),r=new WeakMap;function s(e,s){let i=r.get(e);i||(i=new Map,r.set(e,i));let a=JSON.stringify(s);if(i.has(a))return i.get(a);let n=t(e,s);return i.set(a,n),n}return{matcher:s,match:s}}var d=class extends Error{constructor(e,t){super(e),this.code=t,this.name="JoinError"}},l=e=>e&&"field"in e&&"operator"in e&&"value"in e,p=(e,t)=>{if(e){if(l(e)&&e){let r=(e=>"object"==typeof e&&null!==e&&"type"in e&&"field"===e.type)(e.value)?((e,t)=>t.split(".").reduce(((e,t)=>e?.[t]),e))(t,e.value.field):e.value;return{...e,value:r}}if((e=>"operator"in e&&"conditions"in e)(e)){let r={...e};return e.conditions&&(r.conditions=e.conditions.map((e=>p(e,t)))),r}return e}},m=async(e,t,r,s)=>{try{if(((e,t)=>{if(!e.relation)throw new d("Join configuration must specify a relation","INVALID_CONFIG");if(!t[e.relation])throw new d(`Collection "${e.relation}" not found in database`,"COLLECTION_NOT_FOUND");if(e.alias&&"string"!=typeof e.alias)throw new d("Join alias must be a string","INVALID_ALIAS")})(r,e),!Array.isArray(t))throw new d("Source data must be an array","INVALID_SOURCE_DATA");let i,a=e[r.relation];return r.query?.filters&&l(r.query.filters)&&(i=((e,t)=>{let r=new Map;return e.forEach((e=>{let s=e[t];r.has(s)||r.set(s,[]),r.get(s).push(e)})),r})(a,r.query.filters.field)),(await Promise.all(t.map((async e=>{let t,n=((e,t)=>{if(!e)return{};let r=p(e.filters,t);return{...e,filters:r}})(r.query,e);return t=n.filters&&l(n.filters)&&i?.has(n.filters.value)?i.get(n.filters.value)||[]:a.filter((e=>s.matcher(e,n.filters))),((e,t,r)=>{let s=r.alias||r.relation;return[{...e,[s]:t}]})(e,await[e=>n.sort?s.sorter(e,n.sort):e,e=>n.projection?s.projector(e,n.projection):e,async e=>n.pagination?await s.paginator(e,n.pagination):e].reduce((async(e,t)=>t(await e)),Promise.resolve(t)),r)})))).flat()}catch(e){throw e instanceof d?e:new d(`Join operation failed: ${e.message}`,"JOIN_EXECUTION_ERROR")}},f=async(e,t,r,s)=>r.reduce((async(t,r)=>m(e,await t,r,s)),Promise.resolve(t));function y(){return{join:f}}var w=class extends Error{constructor(e,t){super(`Unsupported comparison between ${typeof e} and ${typeof t}`),this.name="UnsupportedComparisonError"}},g=class extends Error{constructor(e){super(`Unsupported sort direction: ${e}`),this.name="InvalidSortDirectionError"}};function b(e,t,r){if(e===t)return 0;if(null==e||null==t)return null==e?"asc"===r?-1:1:"asc"===r?1:-1;if("string"==typeof e&&"string"==typeof t)return"asc"===r?e.localeCompare(t):t.localeCompare(e);if("number"==typeof e&&"number"==typeof t)return"asc"===r?e-t:t-e;throw new w(e,t)}function v(e,t){let r=Array.from(e);return 0===t.length?r:r.sort(((e,r)=>{for(let s of t){let{field:t,direction:i}=s,a=e[t],n=r[t];try{if("asc"!==i&&"desc"!==i)throw new g(i);let e=b(a,n,i);if(0!==e)return e}catch(e){throw e instanceof w||e instanceof g?e:new Error(`Error comparing field '${t}': ${e.message}`)}}return 0}))}function $(){return{sort:v}}function _(e){let{resolve:t}=h(e);function r(e,s){let i={};return s.include?.length&&function(e,t,s){for(let i of t)if("string"!=typeof i){for(let[t,a]of Object.entries(i))if(Object.prototype.hasOwnProperty.call(e,t)){let i=r(e[t],a);s[t]=i}}else{let t=i;s[t]=e[t]}}(e,s.include,i),s.exclude?.length&&function(e,t,s){0===Object.keys(s).length&&Object.assign(s,e);for(let e of t)if("string"!=typeof e)for(let[t,i]of Object.entries(e)){if(!Object.prototype.hasOwnProperty.call(s,t))continue;let e=s[t];e&&"object"==typeof e?s[t]=r(e,i):delete s[t]}else delete s[e]}(e,s.exclude,i),s.computed?.length&&function(e,r,s){for(let i of r)s[i.alias]=t(e,i)}(e,s.computed,i),i}return{project:r}}async function*k(e,t,r=e=>String(e)){"offset"===t.type?yield*async function*(e,t){let{offset:r,limit:s}=t,i=0,a=s,n=[];for await(let t of e)a<=0&&(yield n,n=[],a=s),i<r?i++:(n.push(t),a--);n.length>0&&(yield n)}(e,t):yield*async function*(e,t,r){let{cursor:s,limit:i,direction:a}=t,n=i,o=void 0===s,c=[];if("forward"===a)for await(let t of e)n<=0&&(yield c,c=[],n=i),o?(c.push(t),n--):o=r(t)===s;else{let t=[];for await(let r of e)t.push(r);for(let e=t.length-1;e>=0;e--){let a=t[e];o?(c.push(a),n--,n<=0&&(yield c,c=[],n=i)):o=r(a)===s}}c.length>0&&(yield c)}(e,t,r)}function E(){return{paginate:k}}}}),y=u({"node_modules/just-once/index.js"(e,t){t.exports=function(e){var t,r;if("function"!=typeof e)throw new Error("expected a function but got "+e);return function(){return t?r:(t=!0,r=e.apply(this,arguments))}}}}),w=u({"node_modules/isomorphic-textencoder/main.js"(e,t){t.exports={encode:e=>new Uint8Array(Buffer.from(e,"utf8")),decode:e=>Buffer.from(e).toString("utf8")}}}),g=u({"node_modules/just-debounce-it/index.js"(e,t){t.exports=function(e,t,r){var s;return function(){if(!t)return e.apply(this,arguments);var i=this,a=arguments,n=r&&!s;return clearTimeout(s),s=setTimeout((function(){if(s=null,!n)return e.apply(i,a)}),t),n?e.apply(this,arguments):void 0}}}}),b=u({"node_modules/@isomorphic-git/lightning-fs/src/path.js"(e,t){function r(e){if(0===e.length)return".";let t=i(e);return t=t.reduce(a,[]),s(...t)}function s(...e){if(0===e.length)return"";let t=e.join("/");return t=t.replace(/\/{2,}/g,"/"),t}function i(e){if(0===e.length)return[];if("/"===e)return["/"];let t=e.split("/");return""===t[t.length-1]&&t.pop(),"/"===e[0]?t[0]="/":"."!==t[0]&&t.unshift("."),t}function a(e,t){if(0===e.length)return e.push(t),e;if("."===t)return e;if(".."===t){if(1===e.length){if("/"===e[0])throw new Error("Unable to normalize path - traverses above root directory");if("."===e[0])return e.push(t),e}return".."===e[e.length-1]?(e.push(".."),e):(e.pop(),e)}return e.push(t),e}t.exports={join:s,normalize:r,split:i,basename:function(e){if("/"===e)throw new Error(`Cannot get basename of "${e}"`);const t=e.lastIndexOf("/");return-1===t?e:e.slice(t+1)},dirname:function(e){const t=e.lastIndexOf("/");if(-1===t)throw new Error(`Cannot get dirname of "${e}"`);return 0===t?"/":e.slice(0,t)},resolve:function(...e){let t="";for(let i of e)t=i.startsWith("/")?i:r(s(t,i));return t}}}}),v=u({"node_modules/@isomorphic-git/lightning-fs/src/errors.js"(e,t){function r(e){return class extends Error{constructor(...t){super(...t),this.code=e,this.message?this.message=e+": "+this.message:this.message=e}}}var s=r("EEXIST"),i=r("ENOENT"),a=r("ENOTDIR"),n=r("ENOTEMPTY"),o=r("ETIMEDOUT"),c=r("EISDIR");t.exports={EEXIST:s,ENOENT:i,ENOTDIR:a,ENOTEMPTY:n,ETIMEDOUT:o,EISDIR:c}}}),$=u({"node_modules/@isomorphic-git/lightning-fs/src/CacheFS.js"(e,t){var r=b(),{EEXIST:s,ENOENT:i,ENOTDIR:a,ENOTEMPTY:n,EISDIR:o}=v();t.exports=class{constructor(){}_makeRoot(e=new Map){return e.set(0,{mode:511,type:"dir",size:0,ino:0,mtimeMs:Date.now()}),e}activate(e=null){this._root=null===e?new Map([["/",this._makeRoot()]]):"string"==typeof e?new Map([["/",this._makeRoot(this.parse(e))]]):e}get activated(){return!!this._root}deactivate(){this._root=void 0}size(){return this._countInodes(this._root.get("/"))-1}_countInodes(e){let t=1;for(let[r,s]of e)0!==r&&(t+=this._countInodes(s));return t}autoinc(){return this._maxInode(this._root.get("/"))+1}_maxInode(e){let t=e.get(0).ino;for(let[r,s]of e)0!==r&&(t=Math.max(t,this._maxInode(s)));return t}print(e=this._root.get("/")){let t="";const r=(e,s)=>{for(let[i,a]of e){if(0===i)continue;let e=a.get(0),n=e.mode.toString(8);t+=`${"\t".repeat(s)}${i}\t${n}`,"file"===e.type?t+=`\t${e.size}\t${e.mtimeMs}\n`:(t+="\n",r(a,s+1))}};return r(e,0),t}parse(e){let t=0;function r(e){const r=++t,s=1===e.length?"dir":"file";let[i,a,n]=e;return i=parseInt(i,8),a=a?parseInt(a):0,n=n?parseInt(n):Date.now(),new Map([[0,{mode:i,type:s,size:a,mtimeMs:n,ino:r}]])}let s=e.trim().split("\n"),i=this._makeRoot(),a=[{indent:-1,node:i},{indent:0,node:null}];for(let e of s){let t=e.match(/^\t*/)[0].length;e=e.slice(t);let[s,...i]=e.split("\t"),n=r(i);if(t<=a[a.length-1].indent)for(;t<=a[a.length-1].indent;)a.pop();a.push({indent:t,node:n}),a[a.length-2].node.set(s,n)}return i}_lookup(e,t=!0){let s=this._root,a="/",n=r.split(e);for(let o=0;o<n.length;++o){let c=n[o];if(s=s.get(c),!s)throw new i(e);if(t||o<n.length-1){const e=s.get(0);if("symlink"===e.type){let t=r.resolve(a,e.target);s=this._lookup(t)}a=a?r.join(a,c):c}}return s}mkdir(e,{mode:t}){if("/"===e)throw new s;let i=this._lookup(r.dirname(e)),a=r.basename(e);if(i.has(a))throw new s;let n=new Map,o={mode:t,type:"dir",size:0,mtimeMs:Date.now(),ino:this.autoinc()};n.set(0,o),i.set(a,n)}rmdir(e){let t=this._lookup(e);if("dir"!==t.get(0).type)throw new a;if(t.size>1)throw new n;let s=this._lookup(r.dirname(e)),i=r.basename(e);s.delete(i)}readdir(e){let t=this._lookup(e);if("dir"!==t.get(0).type)throw new a;return[...t.keys()].filter((e=>"string"==typeof e))}writeStat(e,t,{mode:s}){let i,a;try{a=this.stat(e)}catch(e){}if(void 0!==a){if("dir"===a.type)throw new o;null==s&&(s=a.mode),i=a.ino}null==s&&(s=438),null==i&&(i=this.autoinc());let n=this._lookup(r.dirname(e)),c=r.basename(e),h={mode:s,type:"file",size:t,mtimeMs:Date.now(),ino:i},u=new Map;return u.set(0,h),n.set(c,u),h}unlink(e){let t=this._lookup(r.dirname(e)),s=r.basename(e);t.delete(s)}rename(e,t){let s=r.basename(t),i=this._lookup(e);this._lookup(r.dirname(t)).set(s,i),this.unlink(e)}stat(e){return this._lookup(e).get(0)}lstat(e){return this._lookup(e,!1).get(0)}readlink(e){return this._lookup(e,!1).get(0).target}symlink(e,t){let s,i;try{let e=this.stat(t);null===i&&(i=e.mode),s=e.ino}catch(e){}null==i&&(i=40960),null==s&&(s=this.autoinc());let a=this._lookup(r.dirname(t)),n=r.basename(t),o={mode:i,type:"symlink",target:e,size:0,mtimeMs:Date.now(),ino:s},c=new Map;return c.set(0,o),a.set(n,c),o}_du(e){let t=0;for(const[r,s]of e.entries())t+=0===r?s.size:this._du(s);return t}du(e){let t=this._lookup(e);return this._du(t)}}}}),_={};function k(){return t||(t=new e),t}function E(e,t=k()){let r;return t._withIDBStore("readwrite",(t=>{r=t.get(e)})).then((()=>r.result))}function S(e,t,r=k()){return r._withIDBStore("readwrite",(r=>{r.put(t,e)}))}function O(e,t,r=k()){return r._withIDBStore("readwrite",(r=>{const s=r.get(e);s.onsuccess=()=>{r.put(t(s.result),e)}}))}function A(e,t=k()){return t._withIDBStore("readwrite",(t=>{t.delete(e)}))}function I(e=k()){return e._withIDBStore("readwrite",(e=>{e.clear()}))}function j(e=k()){const t=[];return e._withIDBStore("readwrite",(e=>{(e.openKeyCursor||e.openCursor).call(e).onsuccess=function(){this.result&&(t.push(this.result.key),this.result.continue())}})).then((()=>t))}function x(e=k()){return e._close()}((e,t)=>{for(var r in t)a(e,r,{get:t[r],enumerable:!0})})(_,{Store:()=>e,clear:()=>I,close:()=>x,del:()=>A,get:()=>E,keys:()=>j,set:()=>S,update:()=>O});var N,T,C=(N={"node_modules/@isomorphic-git/idb-keyval/dist/idb-keyval.mjs"(){e=class{constructor(e="keyval-store",t="keyval"){this.storeName=t,this._dbName=e,this._storeName=t,this._init()}_init(){this._dbp||(this._dbp=new Promise(((e,t)=>{const r=indexedDB.open(this._dbName);r.onerror=()=>t(r.error),r.onsuccess=()=>e(r.result),r.onupgradeneeded=()=>{r.result.createObjectStore(this._storeName)}})))}_withIDBStore(e,t){return this._init(),this._dbp.then((r=>new Promise(((s,i)=>{const a=r.transaction(this.storeName,e);a.oncomplete=()=>s(),a.onabort=a.onerror=()=>i(a.error),t(a.objectStore(this.storeName))}))))}_close(){return this._init(),this._dbp.then((e=>{e.close(),this._dbp=void 0}))}}}},function(){return N&&(T=(0,N[o(N)[0]])(N=0)),T}),M=u({"node_modules/@isomorphic-git/lightning-fs/src/IdbBackend.js"(e,t){var r=(C(),p(_));t.exports=class{constructor(e,t){this._database=e,this._storename=t,this._store=new r.Store(this._database,this._storename)}saveSuperblock(e){return r.set("!root",e,this._store)}loadSuperblock(){return r.get("!root",this._store)}readFile(e){return r.get(e,this._store)}writeFile(e,t){return r.set(e,t,this._store)}unlink(e){return r.del(e,this._store)}wipe(){return r.clear(this._store)}close(){return r.close(this._store)}}}}),R=u({"node_modules/@isomorphic-git/lightning-fs/src/HttpBackend.js"(e,t){t.exports=class{constructor(e){this._url=e}loadSuperblock(){return fetch(this._url+"/.superblock.txt").then((e=>e.ok?e.text():null))}async readFile(e){const t=await fetch(this._url+e);if(200===t.status)return t.arrayBuffer();throw new Error("ENOENT")}async sizeFile(e){const t=await fetch(this._url+e,{method:"HEAD"});if(200===t.status)return t.headers.get("content-length");throw new Error("ENOENT")}}}}),D=u({"node_modules/@isomorphic-git/lightning-fs/src/Mutex.js"(e,t){var r=(C(),p(_)),s=e=>new Promise((t=>setTimeout(t,e)));t.exports=class{constructor(e,t){this._id=Math.random(),this._database=e,this._storename=t,this._store=new r.Store(this._database,this._storename),this._lock=null}async has({margin:e=2e3}={}){if(this._lock&&this._lock.holder===this._id){const t=Date.now();return this._lock.expires>t+e||await this.renew()}return!1}async renew({ttl:e=5e3}={}){let t;return await r.update("lock",(r=>{const s=Date.now()+e;return t=r&&r.holder===this._id,this._lock=t?{holder:this._id,expires:s}:r,this._lock}),this._store),t}async acquire({ttl:e=5e3}={}){let t,s,i;if(await r.update("lock",(r=>{const a=Date.now(),n=a+e;return s=r&&r.expires<a,t=void 0===r||s,i=r&&r.holder===this._id,this._lock=t?{holder:this._id,expires:n}:r,this._lock}),this._store),i)throw new Error("Mutex double-locked");return t}async wait({interval:e=100,limit:t=6e3,ttl:r}={}){for(;t--;){if(await this.acquire({ttl:r}))return!0;await s(e)}throw new Error("Mutex timeout")}async release({force:e=!1}={}){let t,s,i;if(await r.update("lock",(r=>(t=e||r&&r.holder===this._id,s=void 0===r,i=r&&r.holder!==this._id,this._lock=t?void 0:r,this._lock)),this._store),await r.close(this._store),!t&&!e){if(s)throw new Error("Mutex double-freed");if(i)throw new Error("Mutex lost ownership")}return t}}}}),P=u({"node_modules/@isomorphic-git/lightning-fs/src/Mutex2.js"(e,t){t.exports=class{constructor(e){this._id=Math.random(),this._database=e,this._has=!1,this._release=null}async has(){return this._has}async acquire(){return new Promise((e=>{navigator.locks.request(this._database+"_lock",{ifAvailable:!0},(t=>(this._has=!!t,e(!!t),new Promise((e=>{this._release=e})))))}))}async wait({timeout:e=6e5}={}){return new Promise(((t,r)=>{const s=new AbortController;setTimeout((()=>{s.abort(),r(new Error("Mutex timeout"))}),e),navigator.locks.request(this._database+"_lock",{signal:s.signal},(e=>(this._has=!!e,t(!!e),new Promise((e=>{this._release=e})))))}))}async release({force:e=!1}={}){this._has=!1,this._release?this._release():e&&navigator.locks.request(this._database+"_lock",{steal:!0},(e=>!0))}}}}),q=u({"node_modules/@isomorphic-git/lightning-fs/src/DefaultBackend.js"(e,t){var{encode:r,decode:s}=w(),i=g(),a=$(),{ENOENT:n,ENOTEMPTY:o,ETIMEDOUT:c}=v(),h=M(),u=R(),d=D(),l=P(),p=b();t.exports=class{constructor(){this.saveSuperblock=i((()=>{this.flush()}),500)}async init(e,{wipe:t,url:r,urlauto:s,fileDbName:i=e,db:n=null,fileStoreName:o=e+"_files",lockDbName:c=e+"_lock",lockStoreName:p=e+"_lock"}={}){this._name=e,this._idb=n||new h(i,o),this._mutex=navigator.locks?new l(e):new d(c,p),this._cache=new a(e),this._opts={wipe:t,url:r},this._needsWipe=!!t,r&&(this._http=new u(r),this._urlauto=!!s)}async activate(){if(this._cache.activated)return;this._needsWipe&&(this._needsWipe=!1,await this._idb.wipe(),await this._mutex.release({force:!0})),await this._mutex.has()||await this._mutex.wait();const e=await this._idb.loadSuperblock();if(e)this._cache.activate(e);else if(this._http){const e=await this._http.loadSuperblock();this._cache.activate(e),await this._saveSuperblock()}else this._cache.activate();if(!await this._mutex.has())throw new c}async deactivate(){await this._mutex.has()&&await this._saveSuperblock(),this._cache.deactivate();try{await this._mutex.release()}catch(e){console.log(e)}await this._idb.close()}async _saveSuperblock(){this._cache.activated&&(this._lastSavedAt=Date.now(),await this._idb.saveSuperblock(this._cache._root))}_writeStat(e,t,r){let s=p.split(p.dirname(e)),i=s.shift();for(let e of s){i=p.join(i,e);try{this._cache.mkdir(i,{mode:511})}catch(e){}}return this._cache.writeStat(e,t,r)}async readFile(e,t){const r="string"==typeof t?t:t&&t.encoding;if(r&&"utf8"!==r)throw new Error('Only "utf8" encoding is supported in readFile');let i=null,a=null;try{a=this._cache.stat(e),i=await this._idb.readFile(a.ino)}catch(e){if(!this._urlauto)throw e}if(!i&&this._http){let t=this._cache.lstat(e);for(;"symlink"===t.type;)e=p.resolve(p.dirname(e),t.target),t=this._cache.lstat(e);i=await this._http.readFile(e)}if(i&&(a&&a.size==i.byteLength||(a=await this._writeStat(e,i.byteLength,{mode:a?a.mode:438}),this.saveSuperblock()),"utf8"===r?i=s(i):i.toString=()=>s(i)),!a)throw new n(e);return i}async writeFile(e,t,s){const{mode:i,encoding:a="utf8"}=s;if("string"==typeof t){if("utf8"!==a)throw new Error('Only "utf8" encoding is supported in writeFile');t=r(t)}const n=await this._cache.writeStat(e,t.byteLength,{mode:i});await this._idb.writeFile(n.ino,t)}async unlink(e,t){const r=this._cache.lstat(e);this._cache.unlink(e),"symlink"!==r.type&&await this._idb.unlink(r.ino)}readdir(e,t){return this._cache.readdir(e)}mkdir(e,t){const{mode:r=511}=t;this._cache.mkdir(e,{mode:r})}rmdir(e,t){if("/"===e)throw new o;this._cache.rmdir(e)}rename(e,t){this._cache.rename(e,t)}stat(e,t){return this._cache.stat(e)}lstat(e,t){return this._cache.lstat(e)}readlink(e,t){return this._cache.readlink(e)}symlink(e,t){this._cache.symlink(e,t)}async backFile(e,t){let r=await this._http.sizeFile(e);await this._writeStat(e,r,t)}du(e){return this._cache.du(e)}flush(){return this._saveSuperblock()}}}}),F=u({"node_modules/@isomorphic-git/lightning-fs/src/Stat.js"(e,t){t.exports=class{constructor(e){this.type=e.type,this.mode=e.mode,this.size=e.size,this.ino=e.ino,this.mtimeMs=e.mtimeMs,this.ctimeMs=e.ctimeMs||e.mtimeMs,this.uid=1,this.gid=1,this.dev=1}isFile(){return"file"===this.type}isDirectory(){return"dir"===this.type}isSymbolicLink(){return"symlink"===this.type}}}}),U=u({"node_modules/@isomorphic-git/lightning-fs/src/PromisifiedFS.js"(e,t){var r=q(),s=F(),i=b();function a(e,t,...r){return void 0!==t&&"function"!=typeof t||(t={}),"string"==typeof t&&(t={encoding:t}),[e=i.normalize(e),t,...r]}function n(e,t,r,...s){return void 0!==r&&"function"!=typeof r||(r={}),"string"==typeof r&&(r={encoding:r}),[e=i.normalize(e),t,r,...s]}function o(e,t,...r){return[i.normalize(e),i.normalize(t),...r]}t.exports=class{constructor(e,t={}){this.init=this.init.bind(this),this.readFile=this._wrap(this.readFile,a,!1),this.writeFile=this._wrap(this.writeFile,n,!0),this.unlink=this._wrap(this.unlink,a,!0),this.readdir=this._wrap(this.readdir,a,!1),this.mkdir=this._wrap(this.mkdir,a,!0),this.rmdir=this._wrap(this.rmdir,a,!0),this.rename=this._wrap(this.rename,o,!0),this.stat=this._wrap(this.stat,a,!1),this.lstat=this._wrap(this.lstat,a,!1),this.readlink=this._wrap(this.readlink,a,!1),this.symlink=this._wrap(this.symlink,o,!0),this.backFile=this._wrap(this.backFile,a,!0),this.du=this._wrap(this.du,a,!1),this._deactivationPromise=null,this._deactivationTimeout=null,this._activationPromise=null,this._operations=new Set,e&&this.init(e,t)}async init(...e){return this._initPromiseResolve&&await this._initPromise,this._initPromise=this._init(...e),this._initPromise}async _init(e,t={}){await this._gracefulShutdown(),this._activationPromise&&await this._deactivate(),this._backend&&this._backend.destroy&&await this._backend.destroy(),this._backend=t.backend||new r,this._backend.init&&await this._backend.init(e,t),this._initPromiseResolve&&(this._initPromiseResolve(),this._initPromiseResolve=null),t.defer||this.stat("/")}async _gracefulShutdown(){this._operations.size>0&&(this._isShuttingDown=!0,await new Promise((e=>this._gracefulShutdownResolve=e)),this._isShuttingDown=!1,this._gracefulShutdownResolve=null)}_wrap(e,t,r){return async(...s)=>{s=t(...s);let i={name:e.name,args:s};this._operations.add(i);try{return await this._activate(),await e.apply(this,s)}finally{this._operations.delete(i),r&&this._backend.saveSuperblock(),0===this._operations.size&&(this._deactivationTimeout||clearTimeout(this._deactivationTimeout),this._deactivationTimeout=setTimeout(this._deactivate.bind(this),500))}}}async _activate(){this._initPromise||console.warn(new Error(`Attempted to use LightningFS ${this._name} before it was initialized.`)),await this._initPromise,this._deactivationTimeout&&(clearTimeout(this._deactivationTimeout),this._deactivationTimeout=null),this._deactivationPromise&&await this._deactivationPromise,this._deactivationPromise=null,this._activationPromise||(this._activationPromise=this._backend.activate?this._backend.activate():Promise.resolve()),await this._activationPromise}async _deactivate(){return this._activationPromise&&await this._activationPromise,this._deactivationPromise||(this._deactivationPromise=this._backend.deactivate?this._backend.deactivate():Promise.resolve()),this._activationPromise=null,this._gracefulShutdownResolve&&this._gracefulShutdownResolve(),this._deactivationPromise}async readFile(e,t){return this._backend.readFile(e,t)}async writeFile(e,t,r){return await this._backend.writeFile(e,t,r),null}async unlink(e,t){return await this._backend.unlink(e,t),null}async readdir(e,t){return this._backend.readdir(e,t)}async mkdir(e,t){return await this._backend.mkdir(e,t),null}async rmdir(e,t){return await this._backend.rmdir(e,t),null}async rename(e,t){return await this._backend.rename(e,t),null}async stat(e,t){const r=await this._backend.stat(e,t);return new s(r)}async lstat(e,t){const r=await this._backend.lstat(e,t);return new s(r)}async readlink(e,t){return this._backend.readlink(e,t)}async symlink(e,t){return await this._backend.symlink(e,t),null}async backFile(e,t){return await this._backend.backFile(e,t),null}async du(e){return this._backend.du(e)}async flush(){return this._backend.flush()}}}}),L=u({"node_modules/@isomorphic-git/lightning-fs/src/index.js"(e,t){var r=y(),s=U();function i(e,t){"function"==typeof e&&(t=e);return[(...e)=>t(null,...e),t=r(t)]}t.exports=class{constructor(...e){this.promises=new s(...e),this.init=this.init.bind(this),this.readFile=this.readFile.bind(this),this.writeFile=this.writeFile.bind(this),this.unlink=this.unlink.bind(this),this.readdir=this.readdir.bind(this),this.mkdir=this.mkdir.bind(this),this.rmdir=this.rmdir.bind(this),this.rename=this.rename.bind(this),this.stat=this.stat.bind(this),this.lstat=this.lstat.bind(this),this.readlink=this.readlink.bind(this),this.symlink=this.symlink.bind(this),this.backFile=this.backFile.bind(this),this.du=this.du.bind(this),this.flush=this.flush.bind(this)}init(e,t){return this.promises.init(e,t)}readFile(e,t,r){const[s,a]=i(t,r);this.promises.readFile(e,t).then(s).catch(a)}writeFile(e,t,r,s){const[a,n]=i(r,s);this.promises.writeFile(e,t,r).then(a).catch(n)}unlink(e,t,r){const[s,a]=i(t,r);this.promises.unlink(e,t).then(s).catch(a)}readdir(e,t,r){const[s,a]=i(t,r);this.promises.readdir(e,t).then(s).catch(a)}mkdir(e,t,r){const[s,a]=i(t,r);this.promises.mkdir(e,t).then(s).catch(a)}rmdir(e,t,r){const[s,a]=i(t,r);this.promises.rmdir(e,t).then(s).catch(a)}rename(e,t,r){const[s,a]=i(r);this.promises.rename(e,t).then(s).catch(a)}stat(e,t,r){const[s,a]=i(t,r);this.promises.stat(e).then(s).catch(a)}lstat(e,t,r){const[s,a]=i(t,r);this.promises.lstat(e).then(s).catch(a)}readlink(e,t,r){const[s,a]=i(t,r);this.promises.readlink(e).then(s).catch(a)}symlink(e,t,r){const[s,a]=i(r);this.promises.symlink(e,t).then(s).catch(a)}backFile(e,t,r){const[s,a]=i(t,r);this.promises.backFile(e,t).then(s).catch(a)}du(e,t){const[r,s]=i(t);this.promises.du(e).then(r).catch(s)}flush(e){const[t,r]=i(e);this.promises.flush().then(t).catch(r)}}}}),B=class extends Error{type;schema;constructor(e,t,r,s){super(t,{cause:s}),this.type=e,this.schema=r,this.name="DatabaseError"}},V=class{queue=[];locked=!1;async acquire(){return this.locked?new Promise((e=>{this.queue.push((()=>e((()=>this.release()))))})):(this.locked=!0,()=>this.release())}release(){if(this.queue.length>0){const e=this.queue.shift();e&&e()}else this.locked=!1}};function z(e){if(null===e||"object"!=typeof e||Array.isArray(e))return[e,{}];const t={};return[Object.entries(e).reduce(((e,[r,s])=>(r.startsWith("$")?t[r]=s:e[r]=s,e)),{}),t]}function H(e,t){if(e&&void 0!==e.$version&&void 0!==t.$version&&t.$version<=e.$version)throw new B("CONFLICT",`OCC Conflict: Incoming version (${t.$version}) is not greater than existing version (${e.$version}).`)}var J=class{constructor(e="$id"){this.keyPath=e}data=new Map;nextId=1;async open(){}getKey(e){const t=e[this.keyPath];if(null==t)throw new B("INVALID_DATA",`Record must have a ${this.keyPath} property`);return t}clone(e){return{...e}}async add(e){const t=Array.isArray(e)?e:[e],r=[];for(const e of t){let t=e[this.keyPath];if(void 0!==t&&""!==t||(t=String(this.nextId++),e[this.keyPath]=t),this.data.has(t))throw new B("CONFLICT",`Duplicate key ${t}`);this.data.set(t,Object.freeze(this.clone(e))),r.push(t)}return Array.isArray(e)?r:r[0]}async put(e){const t=this.getKey(e);return H(this.data.get(t),e),this.data.set(t,Object.freeze(this.clone(e))),t}async batch(e){const t=new Map,r=e=>t.has(e)?t.get(e):this.data.get(e);try{for(const s of e)if("add"===s.type||"put"===s.type){const e=Array.isArray(s.data)?s.data:[s.data];for(const i of e){let e=i[this.keyPath];"add"!==s.type||e&&""!==e?e=this.getKey(i):(e=String(this.nextId++),i[this.keyPath]=e);const a=r(e);if("add"===s.type&&null!=a)throw new B("CONFLICT",`Duplicate key ${e}`);H(a,i),t.set(e,Object.freeze(this.clone(i)))}}else if("delete"===s.type){const e=Array.isArray(s.data)?s.data:[s.data];for(const r of e)t.set(r,null)}for(const[e,r]of t.entries())null===r?this.data.delete(e):this.data.set(e,r)}catch(e){throw e}}async getById(e){const t=this.data.get(e);return t?this.clone(t):void 0}async delete(e){const t=Array.isArray(e)?e:[e];for(const e of t)this.data.delete(e)}async clear(){this.data.clear()}async count(){return this.data.size}async getByIndex(e,t){for(const r of this.data.values())if(r[e]===t)return this.clone(r)}async getByKeyRange(e,t){const r=[];for(const s of this.data.values()){const i=s[e];this.isInKeyRange(i,t)&&r.push(this.clone(s))}return r}isInKeyRange(e,t){if(!t)return!0;const{lower:r,upper:s,lowerOpen:i=!1,upperOpen:a=!1}=t;return(void 0===r||(i?e>r:e>=r))&&(void 0===s||(a?e<s:e<=s))}async getAll(){return Array.from(this.data.values()).map((e=>this.clone(e)))}async cursor(e,t="forward",r){let s=Array.from(this.data.entries());r&&(s=s.filter((([e])=>{const t=e,s=void 0===r.lower||(r.lowerOpen?t>r.lower:t>=r.lower),i=void 0===r.upper||(r.upperOpen?t<r.upper:t<=r.upper);return s&&i})));const i=s.sort((([e],[t])=>e>t?1:e<t?-1:0));"backward"===t&&i.reverse();let a=null,n=0;for(;n<i.length;){const[t,r]=i[n],{value:s,done:o,offset:c}=await e(this.clone(r),t,null);if(a=s,o)break;c&&c>0?n+=c:n++}return a}};var K=class e extends Error{constructor(t,r){super(t,{cause:r}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},W=class extends K{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},Y=class{_locked=!1;_capacity;_yieldMode;waiters=[];constructor(e){this._capacity=e?.capacity??1/0,this._yieldMode=e?.yieldMode??"macrotask"}async lock(e){if(!this._locked)return void(this._locked=!0);if(this.waiters.length>=this._capacity)throw new Error(`Mutex queue is full (capacity: ${this._capacity})`);let t;const r=new Promise((e=>t=e));this.waiters.push(t),null!=e?await Promise.race([r,new Promise(((r,s)=>setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),s(new W("Mutex lock timed out"))}),e)))]):await r}tryLock(){return!this._locked&&(this._locked=!0,!0)}unlock(){if(!this._locked)throw new Error("Mutex is not locked");const e=this.waiters.shift();e?"microtask"===this._yieldMode?queueMicrotask(e):setTimeout(e,0):this._locked=!1}locked(){return this._locked}pending(){return this.waiters.length}},G=class{mutex=new Y({yieldMode:"microtask"});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=Boolean(e),this.throws=Boolean(t)}async do(e,t){return this._done?this.peek():this.promise?this._awaitWithTimeout(this.promise,t,"Once do() timed out"):(await this.mutex.lock(),this.promise?(this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")):(this.promise=(async()=>{try{const t=await e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.promise=null}return this.peek()})(),this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")))}isReady(){return this._done&&null===this.promise}running(){return null!==this.promise&&!this._done}peek(){return{value:this._value,error:this._error}}get(){if(!this._done)throw new Error("Once operation is not yet complete");if(this._error)throw this._error;return this._value}reset(){this._done=!1,this.promise=null,this._value=null,this._error=void 0}resolved(){return this.promise}done(){return this._done}_awaitWithTimeout(e,t,r="Operation timed out"){return null==t?e:Promise.race([e,new Promise(((e,s)=>setTimeout((()=>s(new W(r))),t)))])}},X=class{constructor(e){this.config=e,this.schemasStoreName=e.schemasStoreName||"schemas"}connectionInitializer=new G({retry:!0,throws:!0});schemasStoreName;async openDatabase(){return new Promise(((e,t)=>{const r=indexedDB.open(this.config.name);r.onerror=()=>t(new Error(`Failed to open database: ${r.error?.message}`)),r.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(this.schemasStoreName)||t.createObjectStore(this.schemasStoreName,{keyPath:"name"})},r.onsuccess=()=>e(r.result)}))}async upgradeDatabase(e,t){const r=e.version+1;return e.close(),new Promise(((e,s)=>{const i=indexedDB.open(this.config.name,r);i.onerror=()=>s(new Error(`Failed to upgrade database: ${i.error?.message}`)),i.onupgradeneeded=e=>{const r=e.target.result;t(r)},i.onsuccess=()=>e(i.result)}))}async ensureStore(e,t="$id"){(await this.getConnection()).objectStoreNames.contains(e)||await this.upgrade((r=>{r.objectStoreNames.contains(this.schemasStoreName)||r.createObjectStore(this.schemasStoreName,{keyPath:"name"}),r.objectStoreNames.contains(e)||r.createObjectStore(e,{keyPath:t})}))}getConnection=async()=>{const e=await this.connectionInitializer.do((async()=>{const e=await this.openDatabase();return e.onclose=()=>this.connectionInitializer.reset(),e.onversionchange=()=>{e.close(),this.connectionInitializer.reset()},e}));if(e.error)throw new B("CONNECTION_FAILED",`Failed to open database: ${this.config.name}`,void 0,e.error);return e.value};async upgrade(e){const t=await this.getConnection();this.connectionInitializer.reset();const r=await this.connectionInitializer.do((async()=>await this.upgradeDatabase(t,e)));if(r.error)throw new B("INTERNAL_ERROR",`Database upgrade failed for ${this.config.name}`,void 0,r.error);return r.value}close(){const e=this.connectionInitializer.peek();e.value&&e.value.close(),this.connectionInitializer.reset()}};function Q(e){if(e)return void 0!==e.lower&&void 0!==e.upper?IDBKeyRange.bound(e.lower,e.upper,e.lowerOpen,e.upperOpen):void 0!==e.lower?IDBKeyRange.lowerBound(e.lower,e.lowerOpen):void 0!==e.upper?IDBKeyRange.upperBound(e.upper,e.upperOpen):void 0}var Z=class{constructor(e,t,r="$id",s){this.getConnection=e,this.storeName=t,this.keyPath=r,this.onOpen=s}async open(){return this.onOpen()}mapError(e){if(e instanceof B)return e;const t=e?.message||"Unknown IndexedDB Error",r=e?.name||"";return"QuotaExceededError"===r?new B("INTERNAL_ERROR","Storage quota exceeded"):new B("VersionError"===r?"CONFLICT":"InvalidStateError"===r||"TransactionInactiveError"===r?"TRANSIENT_ERROR":"INTERNAL_ERROR",t)}async withTx(e,t){const r=await this.getConnection();return new Promise((async(s,i)=>{const a=r.transaction(this.storeName,e),n=a.objectStore(this.storeName);let o,c;a.oncomplete=()=>{c?i(c):s(o)},a.onerror=()=>i(this.mapError(a.error)),a.onabort=()=>i(this.mapError(a.error));try{const e=t(n,a);o=e instanceof Promise?o=await e:e}catch(e){c=e;try{a.abort()}catch(e){}}}))}requestToPromise(e){return new Promise(((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)}))}async put(e){return this.withTx("readwrite",(async t=>{const r=e[this.keyPath];if(void 0!==r){H(await this.requestToPromise(t.get(r)),e)}return this.requestToPromise(t.put(e))}))}async add(e){return this.withTx("readwrite",(async t=>{const r=Array.isArray(e)?e:[e],s=[];for(const e of r){const r=await this.requestToPromise(t.add(e));s.push(r)}return Array.isArray(e)?s:s[0]}))}async batch(e){return this.withTx("readwrite",(async t=>{for(const r of e)if("put"===r.type||"add"===r.type){const e=Array.isArray(r.data)?r.data:[r.data];for(const s of e)if("put"===r.type){const e=s[this.keyPath];if(void 0!==e){H(await this.requestToPromise(t.get(e)),s)}await this.requestToPromise(t.put(s))}else await this.requestToPromise(t.add(s))}else if("delete"===r.type){const e=Array.isArray(r.data)?r.data:[r.data];for(const r of e)await this.requestToPromise(t.delete(r))}}))}async getById(e){return this.withTx("readonly",(async t=>this.requestToPromise(t.get(e))))}async delete(e){return this.withTx("readwrite",(async t=>{const r=Array.isArray(e)?e:[e];for(const e of r)await this.requestToPromise(t.delete(e))}))}async clear(){return this.withTx("readwrite",(async e=>{await this.requestToPromise(e.clear())}))}async count(){return this.withTx("readonly",(async e=>this.requestToPromise(e.count())))}async getByIndex(e,t){return this.withTx("readonly",(async r=>{const s=r.index(e);return this.requestToPromise(s.get(t))}))}async getByKeyRange(e,t){return this.withTx("readonly",(async r=>{const s=r.index(e);return this.requestToPromise(s.getAll(Q(t)))}))}async getAll(){return this.withTx("readonly",(async e=>this.requestToPromise(e.getAll())))}async cursor(e,t="forward",r){return this.withTx("readonly",(async s=>{const i="forward"===t?"next":"prev",a=s.openCursor(Q(r),i);return new Promise(((t,r)=>{let s=null;a.onsuccess=async i=>{const a=i.target.result;if(!a)return t(s);try{const{value:r,done:i,offset:n}=await e(a.value,a.key,a);s=r,i?t(s):n&&n>0?a.advance(n):a.continue()}catch(e){r(e)}},a.onerror=()=>r(this.mapError(a.error))}))}))}};l(m()),l(m()),l(f()),l(L()),l(L());var ee=class extends Error{constructor(e,t){super(e),this.operation=t,this.name="JsonPatchError"}};function te(e){let t=function(e){return""===e||"/"===e?"":e.startsWith("/")?"/"+e.substring(1).split("/").map(re).join("/"):"/"+e.split(".").map(re).join("/")}(e);return""===t?[]:t.substring(1).split("/").map(se)}function re(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function se(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}var ie=new Map;function ae(e,t){let r=e;for(let e of t){if(null===r||"object"!=typeof r)throw new ee(`Invalid path - parent not found at ${e}`);if(Array.isArray(r)){let t="-"===e?r.length:parseInt(e);if(isNaN(t)||t<0||t>r.length)throw new ee(`Invalid array index: ${e}`);r=r[t]}else{if(!r.hasOwnProperty(e))throw new ee(`Property ${e} not found`);r=r[e]}}return r}function ne(e,t){let r=ie.get(t)||te(t);if(ie.set(t,r),0===r.length)return e;let s=ae(e,r.slice(0,-1)),i=r[r.length-1];if(Array.isArray(s)){let e=parseInt(i);if(isNaN(e)||e<0||e>=s.length)throw new ee(`Invalid array index: ${i}`);return s[e]}return s[i]}function oe(e,t,r){let s=ie.get(t)||te(t);ie.set(t,s);let i=ae(e,s.slice(0,-1)),a=s[s.length-1];return Array.isArray(i)?i.splice(0,i.length,...i.filter((e=>e!==r))):i[a]===r&&delete i[a],e}function ce(e,t,r){let s=ie.get(t)||te(t);if(ie.set(t,s),0===s.length)return r;let i=s.slice(0,-1),a=s[s.length-1],n=ae(e,i);if(Array.isArray(n))if("-"===a)n.push(r);else{let e=parseInt(a);if(e<0||e>n.length)throw new ee(`Invalid array index: ${a}`);n.splice(e,0,r)}else n[a]=r;return e}function he(e,t){let r=ie.get(t)||te(t);if(ie.set(t,r),0===r.length)return;let s=ae(e,r.slice(0,-1)),i=r[r.length-1];if(Array.isArray(s)){let e=parseInt(i);s.splice(e,1)}else delete s[i];return e}function ue(e,t){let r=[];switch(e.type){case"addField":r.push({op:"add",path:`/fields/${e.id}`,value:e.definition});break;case"removeField":r.push({op:"remove",path:`/fields/${e.id}`});break;case"modifyField":{let t=`/fields/${e.id}`;Object.entries(e.changes).forEach((([e,s])=>{"object"!=typeof s||null===s||Array.isArray(s),r.push({op:"replace",path:`${t}/${e}`,value:s})}));break}case"deprecateField":r.push({op:"add",path:`/fields/${e.id}/deprecated`,value:!0});break;case"addIndex":t.indexes||r.push({op:"add",path:"/indexes",value:[]}),r.push({op:"add",path:"/indexes/-",value:e.definition});break;case"removeIndex":{let s=t.indexes?.findIndex((t=>t.name===e.name));void 0!==s&&s>=0&&r.push({op:"remove",path:`/indexes/${s}`});break}case"modifyIndex":{let s=t.indexes?.findIndex((t=>t.name===e.name));void 0!==s&&s>=0&&Object.entries(e.changes).forEach((([e,t])=>{r.push({op:"replace",path:`/indexes/${s}/${e}`,value:t})}));break}case"addConstraint":t.constraints||r.push({op:"add",path:"/constraints",value:[]}),Array.isArray(e.constraint)?e.constraint.forEach((e=>{r.push({op:"add",path:"/constraints/-",value:e})})):r.push({op:"add",path:"/constraints/-",value:e.constraint});break;case"removeConstraint":{let s=t.constraints?.findIndex((t=>Array.isArray(t)?t.some((t=>t.name===e.name)):t.name===e.name));void 0!==s&&s>=0&&r.push({op:"remove",path:`/constraints/${s}`});break}case"modifyConstraint":{let s=function(e,t){if(!e.constraints)return null;for(let r=0;r<e.constraints.length;r++){let s=e.constraints[r];if(s.name===t)return`/constraints/${r}`;if(de(s)){let e=le(s.rules,t);if(e)return`/constraints/${r}${e}`}}return null}(t,e.name);s&&Object.entries(e.changes).forEach((([e,t])=>{r.push({op:"replace",path:`${s}/${e}`,value:t})}));break}}return r}function de(e){return e&&"operator"in e&&"rules"in e}function le(e,t){for(let r=0;r<e.length;r++){let s=e[r];if("name"in s&&s.name===t)return`/rules/${r}`;if(de(s)){let e=le(s.rules,t);if(e)return`/rules/${r}${e}`}}return null}var pe=new Map;function me(e){return e instanceof RegExp?e.toString().slice(1,-1):JSON.stringify(e)}function fe(e,t){let r=e=>({issues:e}),s=(e,t,r,s)=>{switch(t){case"string":return"string"!=typeof e?[{message:"Expected string, got "+typeof e,path:r}]:[];case"number":return"number"!=typeof e||isNaN(e)?[{message:"Expected number, got "+typeof e,path:r}]:[];case"boolean":return"boolean"!=typeof e?[{message:"Expected boolean, got "+typeof e,path:r}]:[];case"array":return Array.isArray(e)?[]:[{message:"Expected array, got "+typeof e,path:r}];case"set":return Array.isArray(e)&&new Set(e).size===e.length?[]:[{message:"Expected unique array, got "+typeof e,path:r}];case"enum":return s?.values?s.values.includes(e)?[]:[{message:`Expected one of ${JSON.stringify(s.values)}, got ${e}`,path:r}]:[{message:"Enum type requires 'values' definition",path:r}];case"object":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected object, got "+typeof e,path:r}]:[];case"record":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected record (object), got "+typeof e,path:r}]:[];case"union":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected union (object), got "+typeof e,path:r}]:[];case"dynamic":return console.warn("Deprecated: 'dynamic' type used. Use 'record' instead."),"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected record (object), got "+typeof e,path:r}]:[];default:return[{message:`Unknown type '${t}'`,path:r}]}};function i(e,t,r,s,a){let n=[],o=e.rules.map(((e,o)=>{let c=[...s,`rules[${o}]`],h=`${e.name}@${c.join(".")}`;if("rules"in e){if(a.has(h))return!0;a.add(h);let s=i(e,t,r,c,a);return n.push(...s),a.delete(h),0===s.length}{let s=r[e.predicate];if(!s)return n.push({message:`Predicate '${e.predicate}' not found`,path:c}),!1;let i=`${e.predicate}:${JSON.stringify(e.parameters)}:${JSON.stringify(t[e.field])}`;if(pe.has(i)){let t=pe.get(i);return t||n.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${me(e.parameters)}`,path:c}),t}let a=s({data:t,field:e.field,arguments:e.parameters});return pe.set(i,a),a||n.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${me(e.parameters)}`,path:c}),a}}));return(()=>{switch(e.operator){case"and":return o.every((e=>e));case"or":return o.some((e=>e));case"not":return!o.every((e=>e));case"nor":return!o.some((e=>e));case"xor":return 1===o.filter((e=>e)).length}})()||n.push({message:`Constraint group '${e.name}' failed`,path:s}),n}function a(e,t,r,n,o,c=new Set){let h=[];if("type"in t&&!("fields"in t)){let a=n.length>0?e[n[n.length-1]]:e;return h.push(...s(a,t.type,n,{values:t.values})),t.constraints&&t.constraints.forEach(((e,t)=>{if("rules"in e)h.push(...i(e,{value:a},r,[...n,`constraints[${t}]`],c));else{let s=r[e.predicate];s?s({data:{value:a},field:"value",arguments:e.parameters})||h.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${me(e.parameters)}`,path:[...n,`constraints[${t}]`]}):h.push({message:`Predicate '${e.predicate}' not found`,path:[...n,`constraints[${t}]`]})}})),h}let u={};if("concrete"in t)if(!0!==t.concrete&&Array.isArray(t.fields)){let r=t.fields,s=r.find((e=>!e.when));s&&Object.assign(u,s.fields);let i=r.find((t=>t.when&&void 0!==e[t.when.field]&&e[t.when.field]===t.when.value));if(i)Object.assign(u,i.fields);else if(!s)return h.push({message:"No matching field set found for discriminated schema",path:n}),h}else u=t.fields;else u=t.fields;let d=new Set(Object.values(u).map((e=>e.name)));Object.entries(u).forEach((([t,u])=>{let d=[...n,u.name],l=Object.hasOwnProperty.call(e,u.name)?e[u.name]:void 0!==u.default?u.default:void 0;u.required&&null==l&&h.push({message:`Field '${u.name}' is required`,path:d});let p=u.schema||u.nestedSchema;if("object"===u.type&&p&&!Array.isArray(p)){let e=o[p.id];if(e)if(c.has(p.id))h.push({message:`Circular reference detected at '${p.id}'`,path:d});else{c.add(p.id);let t=l&&"object"==typeof l&&!Array.isArray(l)?l:{};h.push(...a(t,e,r,d,o,c)),p.constraints?.forEach(((e,s)=>{if("rules"in e)h.push(...i(e,t,r,[...d,`constraints[${s}]`],c));else{let i=r[e.predicate];i?i({data:t,field:void 0,arguments:e.parameters})||h.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${me(e.parameters)}`,path:[...d,`constraints[${s}]`]}):h.push({message:`Predicate '${e.predicate}' not found`,path:[...d,`constraints[${s}]`]})}})),c.delete(p.id)}else h.push({message:`Nested schema '${p.id}' not found`,path:d})}if("union"===u.type&&p&&Array.isArray(p)){let e=!1,t=[];p.forEach(((s,n)=>{let h=o[s.id];if(h)if(c.has(s.id))t.push({message:`Circular reference detected at '${s.id}'`,path:[...d,n.toString()]});else{c.add(s.id);let n=l&&"object"==typeof l&&!Array.isArray(l)?l:{},u=a(n,h,r,d,o,new Set(c));0===u.length&&void 0!==l?(e=!0,s.constraints?.forEach(((s,a)=>{if("rules"in s){let o=i(s,n,r,[...d,`constraints[${a}]`],c);o.length>0&&(e=!1,t.push(...o))}else{let i=r[s.predicate];i&&!i({data:n,field:void 0,arguments:s.parameters})&&(e=!1,t.push({message:s.errorMessage||`Constraint '${s.name}' failed`,path:[...d,`constraints[${a}]`]}))}}))):void 0===l&&t.push(...u.filter((e=>e.message.includes("is required")))),c.delete(s.id)}else t.push({message:`Nested schema '${s.id}' not found`,path:[...d,n.toString()]})})),e||void 0===l?void 0===l&&h.push(...t):(h.push({message:"Value does not match any union schema",path:d}),h.push(...t))}void 0!==l&&(h.push(...s(l,u.type,d,{values:u.values})),("array"===u.type||"set"===u.type)&&Array.isArray(l)&&(u.constraints?.forEach(((e,t)=>{let s=r[e.predicate];s&&!s({data:{[u.name]:l},field:u.name,arguments:e.parameters})&&h.push({message:e.errorMessage||`Constraint '${e.name}' failed for field '${u.name}'`,path:[...d,`constraints[${t}]`]})})),u.itemsType&&l.forEach(((e,t)=>h.push(...s(e,u.itemsType,[...d,t.toString()])))),p&&!Array.isArray(p)&&(o[p.id]?l.forEach(((e,t)=>{"object"==typeof e&&null!==e&&(c.has(p.id)?h.push({message:`Circular reference detected at '${p.id}'`,path:[...d,t.toString()]}):(c.add(p.id),h.push(...a(e,o[p.id],r,[...d,t.toString()],o,c)),c.delete(p.id)))})):h.push({message:`Nested schema '${p.id}' not found`,path:d}))),u.constraints?.forEach(((t,s)=>{if("rules"in t)h.push(...i(t,e,r,[...d,`constraints[${s}]`],c));else{let i=r[t.predicate];i?i({data:e,field:u.name,arguments:t.parameters})||h.push({message:t.errorMessage||`Constraint '${t.name}' failed for field '${u.name}' with params ${me(t.parameters)}`,path:[...d,`constraints[${s}]`]}):h.push({message:`Predicate '${t.predicate}' not found`,path:[...d,`constraints[${s}]`]})}})))}));for(let t in e)Object.hasOwnProperty.call(e,t)&&!d.has(t)&&h.push({message:`Unexpected field '${t}'`,path:[...n,t]});return t.constraints?.forEach(((t,s)=>{if("rules"in t)h.push(...i(t,e,r,[...n,`constraints[${s}]`],c));else{let i=r[t.predicate];i?i({data:e,field:t.field,arguments:t.parameters})||h.push({message:t.errorMessage||`Constraint '${t.name}' failed with params ${me(t.parameters)}`,path:[...n,`constraints[${s}]`]}):h.push({message:`Predicate '${t.predicate}' not found`,path:[...n,`constraints[${s}]`]})}})),h}return"1.0.0"!==e.version&&console.warn(`Schema version '${e.version}' may require migrations. Validator assumes version 1.0.0.`),{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:s=>{if("object"!=typeof s||null===s)return r([{message:"Input must be an object",path:[]}]);let i=s,n=a(i,e,t,[],e.nestedSchemas||{});return n.length>0?r(n):(e=>({value:e}))(i)},types:{input:{},output:{}}}}}var ye=class extends Error{constructor(e,t){super(e),this.errors=t,this.name="SchemaValidationError"}},we=e=>({value:e}),ge=e=>({issues:e}),be=(e,t,r=!0)=>(void 0!==e||r)&&("string"!=typeof e||""===e.trim())?[{message:"Must be a non-empty string",path:[t]}]:[],ve=(e,t)=>{let r=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return"string"==typeof e&&r.includes(e)?"dynamic"===e?[{message:"Field type 'dynamic' is deprecated; use 'record' instead",path:[t]}]:[]:[{message:`Must be one of ${r.join(", ")}`,path:[t]}]},$e=(e,t)=>{let r=["and","or","not","nor","xor"];return"string"==typeof e&&r.includes(e)?[]:[{message:`Must be one of ${r.join(", ")}`,path:[t]}]},_e=(e,t,r=!1)=>(void 0!==e||r)&&"boolean"!=typeof e?[{message:"Must be a boolean",path:[t]}]:[],ke=(e,t,r)=>{let s=[],i=["type","predicate","field","parameters","name","description","errorMessage"],a=e;return["predicate","name"].forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${r}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${r}.${e}`]})})),s.push(...be(e.name,`${r}.name`)),s.push(...be(e.predicate,`${r}.predicate`)),void 0!==e.field&&"string"!=typeof e.field&&s.push({message:"Field must be a string",path:[`${r}.field`]}),void 0!==e.parameters&&s.push(...(e.parameters,[])),s.push(...be(e.description,`${r}.description`,!1)),s.push(...be(e.errorMessage,`${r}.errorMessage`,!1)),s},Ee=(e,t,r)=>{let s=[],i=["name","operator","rules"],a=i,n=e;return i.forEach((e=>{void 0===n[e]&&s.push({message:`${e} is required`,path:[`${r}.${e}`]})})),Object.keys(n).forEach((e=>{a.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${r}.${e}`]})})),s.push(...be(e.name,`${r}.name`)),s.push(...$e(e.operator,`${r}.operator`)),Array.isArray(e.rules)&&0!==e.rules.length?e.rules.forEach(((e,i)=>{"rules"in e?s.push(...Ee(e,t,`${r}.rules[${i}]`)):s.push(...ke(e,0,`${r}.rules[${i}]`))})):s.push({message:"Rules must be a non-empty array",path:[`${r}.rules`]}),s},Se=(e,t,r)=>{if(!Array.isArray(e))return[{message:"Must be an array",path:[r]}];let s=[];return e.forEach(((e,i)=>{"rules"in e?s.push(...Ee(e,t,`${r}[${i}]`)):s.push(...ke(e,0,`${r}[${i}]`))})),s},Oe=(e,t)=>{let r=[],s=["operator","field","value","conditions"],i=e;return["operator","field"].forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...$e(e.operator,`${t}.operator`)),r.push(...be(e.field,`${t}.field`)),void 0!==e.conditions&&(Array.isArray(e.conditions)?e.conditions.forEach(((e,s)=>r.push(...Oe(e,`${t}.conditions[${s}]`)))):r.push({message:"Conditions must be an array",path:[`${t}.conditions`]})),r},Ae=(e,t)=>{let r=[],s=["fields","type","unique","partial","description","order","name"],i=e;return["fields","type","name"].forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...be(e.name,`${t}.name`)),r.push(...((e,t)=>{let r=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return"string"==typeof e&&r.includes(e)?[]:[{message:`Must be one of ${r.join(", ")}`,path:[t]}]})(e.type,`${t}.type`)),(!Array.isArray(e.fields)||0===e.fields.length||!e.fields.every((e=>"string"==typeof e)))&&r.push({message:"Fields must be a non-empty array of strings",path:[`${t}.fields`]}),r.push(..._e(e.unique,`${t}.unique`,!1)),e.partial&&r.push(...Oe(e.partial,`${t}.partial`)),r.push(...be(e.description,`${t}.description`,!1)),void 0!==e.order&&!["asc","desc"].includes(e.order)&&r.push({message:"Order must be 'asc' or 'desc'",path:[`${t}.order`]}),r},Ie=(e,t)=>{if(void 0===e)return[];if(!Array.isArray(e))return[{message:"Must be an array",path:[t]}];let r=[];return e.forEach(((e,s)=>r.push(...Ae(e,`${t}[${s}]`)))),r},je=(e,t,r,s,i)=>{let a=[];return void 0===e?[]:("union"===r&&Array.isArray(e)?(0===e.length&&a.push({message:"Schema array must not be empty for union type",path:[t]}),e.forEach(((e,r)=>{let i=`${t}[${r}]`;a.push(...be(e.id,`${i}.id`)),s.includes(e.id)||a.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${i}.id`]}),e.constraints&&a.push(...Se(e.constraints,"dynamic",`${i}.constraints`)),e.indexes&&a.push(...Ie(e.indexes,`${i}.indexes`))}))):"object"!==r&&("array"!==r||"object"!==i)||Array.isArray(e)?a.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[t]}):(a.push(...be(e.id,`${t}.id`)),s.includes(e.id)||a.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${t}.id`]}),e.constraints&&a.push(...Se(e.constraints,"dynamic",`${t}.constraints`)),e.indexes&&a.push(...Ie(e.indexes,`${t}.indexes`))),a)},xe=(e,t,r)=>{if(void 0===e)return[];switch(t){case"string":if("string"!=typeof e)return[{message:"Default must be a string",path:[r]}];break;case"number":if("number"!=typeof e)return[{message:"Default must be a number",path:[r]}];break;case"boolean":if("boolean"!=typeof e)return[{message:"Default must be a boolean",path:[r]}];break;case"array":case"set":if(!Array.isArray(e))return[{message:"Default must be an array",path:[r]}];break;case"enum":if(!Array.isArray(e)||!e.every((e=>"string"==typeof e||"number"==typeof e)))return[{message:"Default must be an array of strings or numbers",path:[r]}];break;case"object":case"record":if("object"!=typeof e||null===e)return[{message:"Default must be an object",path:[r]}];break;case"union":case"dynamic":return[]}return[]},Ne=(e,t)=>void 0===e?[]:"object"!=typeof e||null===e?[{message:"Hint must be an object",path:[t]}]:"input"in e&&"object"!=typeof e.input?[{message:"Hint.input must be an object",path:[`${t}.input`]}]:[],Te=(e,t,r)=>{let s=[],i=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique","hint"],a=e;if(["name","type"].forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...be(e.name,`${t}.name`)),s.push(...ve(e.type,`${t}.type`)),s.push(..._e(e.required,`${t}.required`,!1)),e.constraints&&s.push(...Se(e.constraints,e.type,`${t}.constraints`)),s.push(...xe(e.default,e.type,`${t}.default`)),void 0!==e.values&&("enum"===e.type?(!Array.isArray(e.values)||0===e.values.length||!e.values.every((e=>"string"==typeof e||"number"==typeof e)))&&s.push({message:"Values must be a non-empty array of strings or numbers",path:[`${t}.values`]}):s.push({message:"Values is only valid for 'enum' type",path:[`${t}.values`]})),void 0!==e.schema&&s.push(...je(e.schema,`${t}.schema`,e.type,r,e.itemsType)),e.itemsType&&s.push(...ve(e.itemsType,`${t}.itemsType`)),e.nestedSchema){s.push({message:"nestedSchema is deprecated; use schema instead",path:[`${t}.nestedSchema`]});let i=["id"],a=["id","constraints","indexes"],n=e.nestedSchema;i.forEach((e=>{void 0===n[e]&&s.push({message:`${e} is required`,path:[`${t}.nestedSchema.${e}`]})})),Object.keys(n).forEach((e=>{a.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchema.${e}`]})})),s.push(...be(e.nestedSchema.id,`${t}.nestedSchema.id`)),r.includes(e.nestedSchema.id)||s.push({message:`nestedSchema.id '${e.nestedSchema.id}' must match a nestedSchemas key`,path:[`${t}.nestedSchema.id`]}),e.nestedSchema.constraints&&s.push(...Se(e.nestedSchema.constraints,"dynamic",`${t}.nestedSchema.constraints`)),e.nestedSchema.indexes&&s.push(...Ie(e.nestedSchema.indexes,`${t}.nestedSchema.indexes`))}if(s.push(..._e(e.deprecated,`${t}.deprecated`,!1)),e.reference){s.push({message:"reference is deprecated",path:[`${t}.reference`]});let r=["schema","field"],i=["schema","field"],a=e.reference;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.reference.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.reference.${e}`]})})),s.push(...be(e.reference.schema,`${t}.reference.schema`)),s.push(...be(e.reference.field,`${t}.reference.field`))}return s.push(...be(e.description,`${t}.description`,!1)),s.push(..._e(e.unique,`${t}.unique`,!1)),e.hint&&s.push(...Ne(e.hint,`${t}.hint`)),s},Ce=(e,t,r)=>{let s=[];if("type"in e&&["string","number","boolean","array","set","enum","record"].includes(e.type)){let i=["name","type","default","schema","itemsType","constraints","description","metadata"],a=e;["name","type"].forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...be(e.name,`${t}.name`)),s.push(...ve(e.type,`${t}.type`)),s.push(...xe(e.default,e.type,`${t}.default`)),e.schema&&s.push(...je(e.schema,`${t}.schema`,e.type,r,e.itemsType)),e.itemsType&&s.push(...ve(e.itemsType,`${t}.itemsType`)),e.constraints&&s.push(...Se(e.constraints,e.type,`${t}.constraints`)),s.push(...be(e.description,`${t}.description`,!1)),void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata)&&s.push({message:"Metadata must be an object",path:[`${t}.metadata`]})}else{let i=["name","description","concrete","fields","indexes","constraints","metadata"],a=e;["name"].forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...be(e.name,`${t}.name`)),s.push(..._e(a.concrete,`${t}.concrete`,!1)),a.concrete&&Array.isArray(a.fields)&&s.push({message:"Fields must be an object when concrete is true",path:[`${t}.fields`]}),Array.isArray(a.fields)?(0===a.fields.length&&s.push({message:"Fields array must not be empty",path:[`${t}.fields`]}),a.fields.forEach(((e,i)=>{let a=`${t}.fields[${i}]`;if("object"==typeof e&&null!==e&&"fields"in e){let t=e.fields;"object"!=typeof t||null===t?s.push({message:"Fields must be a non-empty object",path:[`${a}.fields`]}):Object.entries(t).forEach((([e,t])=>{s.push(...Te(t,`${a}.fields.${e}`,r))})),void 0!==e.when&&("object"!=typeof e.when||null===e.when?s.push({message:"When must be an object",path:[`${a}.when`]}):s.push(...be(e.when.field,`${a}.when.field`)))}else s.push({message:"Each variant must have a 'fields' property",path:[a]})}))):void 0!==a.fields&&("object"!=typeof a.fields||null===a.fields?s.push({message:"Fields must be a non-empty object",path:[`${t}.fields`]}):Object.entries(a.fields).forEach((([e,i])=>{s.push(...Te(i,`${t}.fields.${e}`,r))}))),s.push(...be(e.description,`${t}.description`,!1)),e.indexes&&s.push(...Ie(e.indexes,`${t}.indexes`)),e.constraints&&s.push(...Se(a.constraints,"dynamic",`${t}.constraints`)),void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata)&&s.push({message:"Metadata must be an object",path:[`${t}.metadata`]})}return s},Me=(e,t)=>{let r=[];switch(e.type||r.push({message:"type is required",path:[`${t}.type`]}),e.type){case"modifyProperty":{let s=["type","id","changes"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...be(e.id,`${t}.id`)),(void 0===e.changes||"object"!=typeof e.changes)&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}case"addField":{let s=["type","id","definition"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...be(e.id,`${t}.id`)),r.push(...Te(e.definition,`${t}.definition`,[]));break}case"removeField":case"deprecateField":{let s=["type","id"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...be(e.id,`${t}.id`));break}case"modifyField":{let s=["type","id","changes","nestedSchemaChanges"],i=e;if(["type","id","changes"].forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...be(e.id,`${t}.id`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]}),e.nestedSchemaChanges){let s=["id","constraints","indexes"],i=e.nestedSchemaChanges;Object.keys(i).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchemaChanges.${e}`]})})),r.push(...be(i.id,`${t}.nestedSchemaChanges.id`,!1)),i.constraints&&r.push(...Se(i.constraints,"dynamic",`${t}.nestedSchemaChanges.constraints`)),i.indexes&&r.push(...Ie(i.indexes,`${t}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let s=["type","definition"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...Ae(e.definition,`${t}.definition`));break}case"removeIndex":{let s=["type","name"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...be(e.name,`${t}.name`));break}case"modifyIndex":{let s=["type","name","changes"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...be(e.name,`${t}.name`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}case"addConstraint":{let s=["type","constraint"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),"rules"in e.constraint?r.push(...Ee(e.constraint,"dynamic",`${t}.constraint`)):r.push(...ke(e.constraint,0,`${t}.constraint`));break}case"removeConstraint":{let s=["type","name"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...be(e.name,`${t}.name`));break}case"modifyConstraint":{let s=["type","name","changes"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...be(e.name,`${t}.name`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}case"addNestedSchema":{let s=["type","id","definition"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...be(e.id,`${t}.id`)),r.push(...Ce(e.definition,`${t}.definition`,[]));break}case"removeNestedSchema":{let s=["type","id"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...be(e.id,`${t}.id`));break}case"modifyNestedSchema":{let s=["type","id","changes"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...be(e.id,`${t}.id`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}default:r.push({message:"Unknown schema change type",path:[`${t}.type`]})}return r},Re=(e,t)=>{let r=[],s=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],i=[...s,"rollback","dependencies"],a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...be(e.id,`${t}.id`)),r.push(...be(e.schemaVersion,`${t}.schemaVersion`)),r.push(...be(e.description,`${t}.description`));let n=["pending","applied","failed"];return n.includes(e.status)||r.push({message:`Status must be one of ${n.join(", ")}`,path:[`${t}.status`]}),Array.isArray(e.changes)&&0!==e.changes.length?e.changes.forEach(((e,s)=>{r.push(...Me(e,`${t}.changes[${s}]`))})):r.push({message:"Changes must be a non-empty array",path:[`${t}.changes`]}),void 0!==e.rollback&&(Array.isArray(e.rollback)?e.rollback.forEach(((e,s)=>r.push(...Me(e,`${t}.rollback[${s}]`)))):r.push({message:"Rollback must be an array",path:[`${t}.rollback`]})),"string"==typeof e.transform?r.push(...be(e.transform,`${t}.transform`)):"object"==typeof e.transform&&null!==e.transform?r.push(...((e,t)=>{let r=[],s=["forward","backward"],i=s,a=e;return s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),"function"!=typeof e.forward&&r.push({message:"Forward must be a function",path:[`${t}.forward`]}),"function"!=typeof e.backward&&r.push({message:"Backward must be a function",path:[`${t}.backward`]}),r})(e.transform,`${t}.transform`)):r.push({message:"Transform must be a string or object",path:[`${t}.transform`]}),r.push(...be(e.createdAt,`${t}.createdAt`)),r.push(...be(e.checksum,`${t}.checksum`)),void 0!==e.dependencies&&(r.push({message:"dependencies is deprecated; use DomainModel instead",path:[`${t}.dependencies`]}),(!Array.isArray(e.dependencies)||!e.dependencies.every((e=>"string"==typeof e)))&&r.push({message:"Dependencies must be an array of strings",path:[`${t}.dependencies`]})),r},De={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return ge([{message:"Schema must be an object",path:[]}]);let t=e,r=[],s=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock","hint"],i=t;if(["name","version","fields"].forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[e]})})),Object.keys(i).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[e]})})),r.push(...be(t.name,"name")),r.push(...be(t.version,"version")),"object"!=typeof t.fields||null===t.fields)r.push({message:"Fields must be a non-empty object",path:["fields"]});else{let e=Object.keys(t.nestedSchemas||{});Object.entries(t.fields).forEach((([t,s])=>{r.push(...Te(s,`fields.${t}`,e))}))}if(void 0!==t.nestedSchemas)if("object"!=typeof t.nestedSchemas||null===t.nestedSchemas)r.push({message:"NestedSchemas must be an object",path:["nestedSchemas"]});else{let e=Object.keys(t.nestedSchemas);Object.entries(t.nestedSchemas).forEach((([t,s])=>r.push(...Ce(s,`nestedSchemas.${t}`,e))))}return r.push(...be(t.description,"description",!1)),t.indexes&&r.push(...Ie(t.indexes,"indexes")),t.constraints&&r.push(...Se(t.constraints,"dynamic","constraints")),void 0!==t.metadata&&("object"!=typeof t.metadata||null===t.metadata)&&r.push({message:"Metadata must be an object",path:["metadata"]}),void 0!==t.dependencies&&(r.push({message:"dependencies is deprecated; use DomainModel instead",path:["dependencies"]}),(!Array.isArray(t.dependencies)||!t.dependencies.every((e=>"string"==typeof e)))&&r.push({message:"Dependencies must be an array of strings",path:["dependencies"]})),void 0!==t.migrations&&(Array.isArray(t.migrations)?t.migrations.forEach(((e,t)=>r.push(...Re(e,`migrations[${t}]`)))):r.push({message:"Migrations must be an array",path:["migrations"]})),void 0!==t.mock&&"function"!=typeof t.mock&&r.push({message:"Mock must be a function",path:["mock"]}),t.hint&&r.push(...Ne(t.hint,"hint")),r.length>0?ge(r):we(t)},types:{input:{},output:{}}},Pe={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return ge([{message:"Migration must be an object",path:[]}]);let t=e,r=Re(t,"");return r.length>0?ge(r):we(t)},types:{input:{},output:{}}},qe={version:1,vendor:"@asaidimu/anansi",validate:e=>{if(!Array.isArray(e))return ge([{message:"SchemaChanges must be an array",path:[]}]);let t=e,r=[];return t.forEach(((e,t)=>r.push(...Me(e,`[${t}]`)))),r.length>0?ge(r):we(t)},types:{input:[],output:[]}};function Fe(e){try{return!De.validate(e).issues}catch(e){throw new ye("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}function Ue(e,t){switch(e.type){case"removeField":case"removeIndex":case"addConstraint":case"modifyConstraint":return"major";case"modifyField":return function(e){return!0===e.required||void 0!==e.type||void 0!==e.itemsType||void 0!==e.nestedSchema||void 0!==e.reference||!0===e.unique}(e.changes)?"major":e.changes.deprecated?"minor":"patch";case"modifyIndex":return void 0!==e.changes.unique||void 0!==e.changes.fields?"major":"minor";case"removeConstraint":case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(e)}`)}}function Le(e,t,r){if(0===t.length)throw new Error("No changes provided");(function(e){let t=new Set,r=new Set,s=new Set,i=new Set;for(let a of e)switch(a.type){case"addField":if(r.has(a.id))throw new Error(`Cannot add previously removed field: ${a.id}`);if(t.has(a.id))throw new Error(`Cannot add already modified field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot add deprecated field: ${a.id}`);s.add(a.id);break;case"removeField":if(s.has(a.id))throw new Error(`Cannot remove newly added field: ${a.id}`);if(t.has(a.id))throw new Error(`Cannot remove modified field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot remove field that is being deprecated: ${a.id}`);r.add(a.id);break;case"modifyField":if(r.has(a.id))throw new Error(`Cannot modify removed field: ${a.id}`);if(s.has(a.id))throw new Error(`Cannot modify newly added field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot modify field that is being deprecated: ${a.id}`);t.add(a.id);break;case"deprecateField":if(r.has(a.id))throw new Error(`Cannot deprecate removed field: ${a.id}`);if(s.has(a.id))throw new Error(`Cannot deprecate newly added field: ${a.id}`);if(t.has(a.id))throw new Error(`Cannot deprecate modified field: ${a.id}`);i.add(a.id)}})(t),function(e){let t=new Set,r=new Set,s=new Set;for(let i of e)switch(i.type){case"addConstraint":let e=i.constraint.name;if(r.has(e))throw new Error(`Cannot add previously removed constraint: ${e}`);if(t.has(e))throw new Error(`Cannot add already modified constraint: ${e}`);s.add(e);break;case"removeConstraint":if(s.has(i.name))throw new Error(`Cannot remove newly added constraint: ${i.name}`);if(t.has(i.name))throw new Error(`Cannot remove modified constraint: ${i.name}`);r.add(i.name);break;case"modifyConstraint":if(r.has(i.name))throw new Error(`Cannot modify removed constraint: ${i.name}`);if(s.has(i.name))throw new Error(`Cannot modify newly added constraint: ${i.name}`);t.add(i.name)}}(t);let s=function(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!t)throw new Error(`Invalid version format: ${e}. Expected format: major.minor.patch`);return{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10)}}(e),i="patch";for(let e of t){let t=Ue(e);if("major"===t){i="major";break}"minor"===t&&"patch"===i&&(i="minor")}switch(i){case"major":return`${s.major+1}.0.0`;case"minor":return`${s.major}.${s.minor+1}.0`;case"patch":return`${s.major}.${s.minor}.${s.patch+1}`}}function Be(e,t){let r=e=>e.split(".").map((e=>parseInt(e,10)||0)),[s,i,a]=r(e),[n,o,c]=r(t);return s-n||i-o||a-c}var Ve,ze=class extends Error{constructor(e,t,r,s){super(e),this.code=t,this.migrationId=r,this.cause=s,this.name="MigrationError"}},He=((Ve=He||{}).INVALID_SCHEMA="INVALID_SCHEMA",Ve.INVALID_MIGRATION="INVALID_MIGRATION",Ve.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",Ve.TIMEOUT="TIMEOUT",Ve.MEMORY_LIMIT="MEMORY_LIMIT",Ve.CONCURRENT_OPERATION="CONCURRENT_OPERATION",Ve.TRANSFORM_ERROR="TRANSFORM_ERROR",Ve.VERSION_NOT_FOUND="VERSION_NOT_FOUND",Ve.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",Ve.STREAM_ERROR="STREAM_ERROR",Ve.ROLLBACK_ERROR="ROLLBACK_ERROR",Ve.MISSING_TRANSFORM="MISSING_TRANSFORM",Ve),Je=class e{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,r){try{if(!Fe(e))throw new ze("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every((e=>function(e){try{return!Pe.validate(e).issues}catch(e){throw new ye("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}(e))))throw new ze("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort(((e,t)=>Be(e.schemaVersion,t.schemaVersion)))}r&&(this.history=r.sort(((e,t)=>Be(e.version,t.version))))}catch(e){throw e instanceof ze?e:new ze("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,e)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let t=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await(async e=>{if(typeof window<"u"&&crypto.subtle){let t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map((e=>e.toString(16).padStart(2,"0"))).join("")}{let{createHash:t}=await import("crypto");return t("sha256").update(e).digest("hex")}})(t)}catch(t){throw new ze("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new ze("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new ze("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach((e=>function(e){try{return!qe.validate(e).issues}catch(e){throw new ye("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}(e)))}catch(e){throw new ze("Invalid schema changes","INVALID_MIGRATION",void 0,e)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:(new Date).toISOString(),checksum:""};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(t,r,s){if(this.isProcessing)throw new ze("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let i={...this.currentSchema},a=this.getRelevantMigrations(r,s);return{newSchema:a.reduce(((e,t)=>{let s="forward"===r?t.changes:t.rollback||[];return this.applySchemaChanges(e,s,t.id)}),i),dataPreview:await e.processMigrationList(t,r,a)}}catch(e){throw e instanceof ze?e:new ze("Dry run failed","INVALID_SCHEMA",void 0,e)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter((r=>{let s="forward"===e?"pending":"applied",i=!t||Be(r.schemaVersion,t)>=0;return r.status===s&&i})).sort(((t,r)=>"forward"===e?t.id.localeCompare(r.id):r.id.localeCompare(t.id)))}applySchemaChanges(e,t,r){try{let s=Le(e.version,t);return t.map((t=>{try{return ue(t,e)}catch(e){throw new ze("Invalid schema change","INVALID_SCHEMA",r,e)}})).reduce(((e,t)=>{try{return function(e,t){let r=JSON.parse(JSON.stringify(e));for(let e of t)try{switch(e.op){case"add":r=ce(r,e.path,e.value);break;case"remove":r=he(r,e.path);break;case"removeValue":r=oe(r,e.path,e.value);break;case"replace":r=ce(he(r,e.path),e.path,e.value);break;case"copy":{let t=ne(r,e.from);r=ce(r,e.path,JSON.parse(JSON.stringify(t)));break}case"move":{let t=ne(r,e.from);r=ce(r,e.path,t),r=he(r,e.from);break}case"test":{let t=ne(r,e.path);if(JSON.stringify(t)!==JSON.stringify(e.value))throw new ee("Test operation failed");break}default:throw new ee(`Unsupported operation: ${e.op}`)}}catch(t){throw t instanceof ee&&(t.operation=e),t}return r}(e,t)}catch(e){throw new ze("Failed to apply patch","INVALID_SCHEMA",r,e)}}),{...e,version:s})}catch(e){throw e instanceof ze?e:new ze("Schema update failed","INVALID_SCHEMA",r,e)}}async prepareMigration(){let e=this.migrations.filter((e=>"pending"===e.status));return await this.validateMigrations(e),e}async migrate(t){if(this.isProcessing)throw new ze("Concurrent operation","CONCURRENT_OPERATION");let r=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let s=await e.processMigrationList(t,"forward",r);return this.markMigrationsApplied(r),s}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map((async e=>{let t=await this.generateChecksum(e);if(e.checksum!==t)throw new ze("Checksum mismatch","CHECKSUM_MISMATCH",e.id)})))}markMigrationsApplied(e){this.migrations=this.migrations.map((t=>e.some((e=>e.id===t.id))?{...t,status:"applied"}:t))}async rollback(e){if(this.isProcessing)throw new ze("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter((e=>"applied"===e.status)).slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(t,r){if(this.isProcessing)throw new ze("Concurrent operation","CONCURRENT_OPERATION");try{let s=this.history.findIndex((e=>e.version===t));if(-1===s)throw new Error(`Version ${t} not found in history`);let i=this.migrations.filter((e=>e.schemaVersion===t&&"applied"===e.status)).sort(((e,t)=>t.id.localeCompare(e.id))),a=this.history.length-s;if(a<0)return r;for(let e=0;e<a;e++)this.transformSchema("backward");let n=await e.processMigrationList(r,"backward",i);return this.migrations=this.migrations.map((e=>e.schemaVersion===t&&"applied"===e.status?{...e,status:"pending"}:e)),n}finally{this.isProcessing=!1}}static async processMigrationList(e,t,r){return(await Promise.all(r.map((async e=>{try{return{migration:e,transform:await this.resolveTransform(e,t)}}catch(t){throw new ze(`Failed to resolve transform for migration ${e.id}`,"TRANSFORM_ERROR",e.id,t)}})))).filter((e=>!!e.transform)).reduce(((e,{migration:t,transform:r})=>e.pipeThrough(new TransformStream({async transform(e,s){try{let t=await r(e);s.enqueue(t)}catch(e){s.error(new ze(`Data transformation failed for migration ${t.id}`,"TRANSFORM_ERROR",t.id,e))}}}))),e)}static async resolveTransform(e,t){return e.transform?"string"==typeof e.transform?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let r=await fetch(e);if(!r.ok)throw new ze(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let s=await r.text();if(typeof window<"u"){let e=new Blob([s],{type:"application/javascript"});return(await import(URL.createObjectURL(e))).default[t]}{let{runInNewContext:r}=await import("vm"),i={module:{exports:{}},console:console};return r(s,i,e),i.module.exports[t]}}catch(t){throw new ze(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,t)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}catch(t){throw new ze(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,t)}}transformSchema(e){try{if("backward"===e){let e=this.history.pop();if(!e)throw new Error("No previous version");return void(this.currentSchema=e)}let t=this.migrations.filter((e=>"pending"===e.status)).flatMap((e=>e.changes));if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce(((e,t)=>this.applySchemaChanges(e,[t])),this.currentSchema)}catch(e){throw e instanceof ze?e:new ze("Schema transformation failed","INVALID_SCHEMA",void 0,e)}}};typeof window<"u"&&(window.Buffer=r.Buffer);var Ke=l(m()),We=l(f()),Ye=class{indexes=new Map;createIndex(e){this.indexes.has(e)||this.indexes.set(e,new Map)}removeIndex(e){this.indexes.delete(e)}hasIndex(e){return this.indexes.has(e)}indexDocument(e){const t=e.$id;if(t)for(const[r,s]of this.indexes.entries()){const i=e[r];if(void 0!==i){let e=s.get(i);e||(e=new Set,s.set(i,e)),e.add(t)}}}removeDocument(e){const t=e.$id;if(t)for(const[r,s]of this.indexes.entries()){const i=e[r];if(void 0!==i){const e=s.get(i);e&&(e.delete(t),0===e.size&&s.delete(i))}}}lookup(e,t){const r=this.indexes.get(e);return r?r.get(t):void 0}clear(){this.indexes.clear()}},Ge=class{middlewares=[];use(e){this.middlewares.push(e)}execute(e,t){let r=-1;const s=i=>{if(i<=r)throw new Error("next() called multiple times");r=i;const a=this.middlewares[i];if(i===this.middlewares.length)return t();try{return a(e,(()=>s(i+1)))}catch(e){return Promise.reject(e)}};return s(0)}wrap(e,t){const r=this;return new Proxy(e,{get(e,s,i){const a=Reflect.get(e,s,i);return"function"==typeof a?function(...i){const n={...t,operation:s.toString(),args:i};return r.execute(n,(()=>a.apply(e,i)))}:a}})}},Xe=async(e,t)=>{const r=Date.now();try{const s=await t();return Qe(e,r,s,null),s}catch(t){throw Qe(e,r,void 0,t),t}};function Qe(e,t,r,s){if(!e.eventBus)return;const i=Date.now()-t;e.eventBus.emit({name:"telemetry",payload:{type:"telemetry",method:e.operation,timestamp:Date.now(),metadata:{args:e.args,performance:{durationMs:i},source:{level:e.documentId?"document":e.collection?"collection":"database",collection:e.collection,document:e.documentId},result:s?void 0:{type:Array.isArray(r)?"array":typeof r,size:Array.isArray(r)?r.length:void 0},error:s?{message:s.message,name:s.name,stack:s.stack}:null}}})}var{match:Ze}=(0,We.createMatcher)({});async function et(e){const{collection:t,initial:r,validator:i,store:a,bus:n,lockManager:o,indexManager:c}=e,[h,u]=z(r),{value:d,issues:l}=i?await i["~standard"].validate(h):{value:r,issues:void 0};if(l)throw console.warn({issues:l}),new B("INVALID_DATA",`Invalid data for ${t}`);const p={current:Object.assign(d,u)};void 0===p.current.$id&&(p.current=Object.assign(p.current,{$id:s.v7(),$created:(new Date).toJSON(),$version:1}),await a.add(p.current),c.indexDocument(p.current),n.emit({name:"document:create",payload:{type:"document:create",data:p.current,timestamp:Date.now()}}));const m={save:async e=>{const r=await o.acquire();try{const{$id:r,$version:s}=p.current;if(!r)throw new Error("Document ID missing.");const i=await a.getById(r);if(i&&i.$version!==s)throw new B("CONFLICT",`Version mismatch on ${t}/${r}`);return i&&c.removeDocument(i),p.current.$version=(s||0)+1,p.current.$updated=(new Date).toJSON(),e?e.addOp(a,"put",p.current):await a.put(p.current),c.indexDocument(p.current),n.emit({name:"document:write",payload:{type:"document:write",data:p.current,timestamp:Date.now()}}),!0}finally{r()}},update:async(e,r)=>{const[s,a]=z(Object.assign({},p.current,e)),{value:o,issues:c}=i?await i["~standard"].validate(s):{value:s,issues:void 0};if(c)throw new B("INVALID_DATA",`Invalid update for ${t}`);p.current=Object.assign(o,a);const h=await m.save(r);return h&&n.emit({name:"document:update",payload:{type:"document:update",data:p.current,timestamp:Date.now()}}),h},delete:async e=>{const r=await o.acquire();try{const{$id:r,$version:s}=p.current;if(!r)throw new Error("Document ID missing.");const i=await a.getById(r);if(i&&i.$version!==s)throw new B("CONFLICT",`Version mismatch on delete ${t}/${r}`);return e?e.addOp(a,"delete",r):await a.delete(r),c.removeDocument(p.current),n.emit({name:"document:delete",payload:{type:"document:delete",data:p.current,timestamp:Date.now()}}),!0}finally{r()}},read:async()=>{const e=p.current.$id,t=await a.getById(e);if(!t)throw new Error("Document not found.");return p.current={...t},n.emit({name:"document:read",payload:{type:"document:read",data:p.current,timestamp:Date.now()}}),!0},state:()=>(e=>{const[t]=z(e);return t})(p.current),subscribe:n.subscribe};return new Proxy({},{get:(e,t)=>["update","delete","subscribe","read","state","save"].includes(t)?m[t]:Reflect.get(p.current,t)})}async function tt({collection:e,validator:t,bus:r,store:s,pipeline:i,validate:a}){const n=new Ye,o=new V;if(a&&t.indexes)for(const e of t.indexes)n.createIndex(e.fields[0]);const c={collection:e,validator:a?t:void 0,store:s,bus:r,pipeline:i,lockManager:o,indexManager:n},h={async validate(e){const r=t["~standard"].validate(e);return r instanceof Promise?await r:r},create:async(t,s)=>{const i=await et({...c,initial:t});return s&&await i.save(s),r.emit({name:"collection:read",payload:{type:"collection:read",model:e,timestamp:Date.now()}}),i},find:async t=>{const i=await s.cursor((async e=>e&&Ze(e,t)?{value:e,done:!0}:{value:null,done:!1}));if(i){const t=et({...c,initial:i});return r.emit({name:"collection:read",payload:{type:"collection:read",method:"find",model:e,timestamp:Date.now()}}),t}return null},filter:async t=>{const i=[];return await s.cursor((async e=>(e&&Ze(e,t)&&i.push(await et({...c,initial:e})),{value:null,done:!1}))),r.emit({name:"collection:read",payload:{type:"collection:read",method:"filter",model:e,timestamp:Date.now()}}),i},list:async t=>{const i={total:await s.count(),offset:"offset"===t.type?t.offset:0,limit:t.limit,count:0};return{async next(){const a="offset"===t.type?await async function(e,t){const{offset:r,limit:s}=t,i=[];let a=0,n=!1;for(;!(n||(await e((async e=>a<r?(a++,{value:e,done:!1,offset:1}):(i.push(e),a++,a>=r+s?(n=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1}))),i.length>=s)););return i}(s.cursor.bind(s),{...t,offset:i.offset}):await async function(e,t){const{limit:r,direction:s}=t,i=[];let a=!1;for(;!a;)await e((async e=>(i.push(e),i.length>=r?(a=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1})),s);return i}(s.cursor.bind(s),{...t});i.offset+=i.limit,i.count+=a.length;const n=await Promise.all(a.map((e=>et({...c,initial:e}))));return r.emit({name:"collection:read",payload:{type:"collection:read",method:"list",model:e,timestamp:Date.now()}}),{value:n,done:i.count>=i.total}}}},subscribe:r.subscribe};return i.wrap(h,{collection:e})}var rt=class{id;buffer=[];committed=!1;constructor(){this.id=s.v7()}addOp(e,t,r){if(this.committed)throw new B("TRANSACTION_FAILED","Transaction already committed");this.buffer.push({store:e,type:t,data:r})}async commit(){if(this.committed)throw new B("TRANSACTION_FAILED","Transaction already committed");this.committed=!0;const e=new Map;for(const t of this.buffer){const r=e.get(t.store)||[];r.push({type:t.type,data:t.data}),e.set(t.store,r)}try{const t=Array.from(e.entries()).map((([e,t])=>e.batch(t)));await Promise.all(t)}catch(e){throw this.rollback(),new B("TRANSACTION_FAILED",`Transaction failed: ${e.message}`)}}rollback(){this.buffer=[],this.committed=!0}};exports.ConnectionManager=X,exports.DEFAULT_KEYPATH="$id",exports.DatabaseConnection=async function(e,t){const r=(0,Ke.createEventBus)(),s=new Ge;s.use(((e=3,t=100)=>async(r,s)=>{let i=0;for(;i<e;)try{return await s()}catch(r){if(!(r instanceof B&&"TRANSIENT_ERROR"===r.type))throw r;{if(i++,i>=e)throw r;const s=t*Math.pow(2,i)+50*Math.random();await new Promise((e=>setTimeout(e,s)))}}})()),e.enableTelemetry&&s.use(Xe);const i=new Map,a=t({...e,name:"schemas",keyPath:"name"});async function n(r){let s=i.get(r);return s||(s=t({...e,name:r,keyPath:"$id"}),i.set(r,s)),await s.open(),s}async function o(t){const i=await a.getById(t);if(!i)throw new B("SCHEMA_NOT_FOUND",`Collection ${t} missing`);const o=await n(t),c=fe(i,e.predicates||{}),h=await tt({collection:t,bus:r,validator:c,validate:Boolean(e.validate),store:o,pipeline:s});return r.emit({name:"collection:read",payload:{type:"collection:read",schema:{name:t},timestamp:Date.now()}}),h}async function c(e){return await a.put(e),r.emit({name:"collection:update",payload:{type:"collection:update",schema:e,timestamp:Date.now()}}),!0}const h={collection:o,createCollection:async e=>{if(await a.getById(e.name))throw new B("SCHEMA_ALREADY_EXISTS",`Collection ${e.name} exists`);if(!Fe(e))throw new B("INVALID_SCHEMA_DEFINITION","Invalid schema");await a.put(e);const t=o(e.name);return r.emit({name:"collection:create",payload:{type:"collection:create",schema:e,timestamp:Date.now()}}),t},deleteCollection:async e=>{const t=await a.getById(e);if(!t)throw new B("SCHEMA_NOT_FOUND",`Collection ${e} missing`);return i.delete(e),await a.delete(e),r.emit({name:"collection:delete",payload:{type:"collection:delete",schema:t,timestamp:Date.now()}}),!0},updateCollection:c,migrateCollection:async(e,t,r=100)=>{const s=await a.getById(e);if(!s)throw new B("SCHEMA_NOT_FOUND","Schema not found");const i=await n(e),o=new Je(s);await o.add(t);const h=function(e,t,r){let s,i=!1;return new ReadableStream({async pull(a){if(i)return void a.close();let n=0;const o=void 0!==s?{lower:s,lowerOpen:!0}:void 0;try{await t.cursor((async(e,t)=>(a.enqueue(e),s=t,n++,n>=r?{done:!0,value:e}:{done:!1,value:e})),"forward",o),n<r&&(i=!0)}catch(t){console.error(`[migrateCollection] Error pulling chunk for '${e}':`,t),a.error(new B("INTERNAL_ERROR",`Failed to read chunk for collection '${e}'`,void 0,t))}},cancel(){console.warn(`[migrateCollection] Input stream for collection '${e}' cancelled.`)}})}(e,i,r);c((await o.dryRun(new ReadableStream({start(e){e.close()}}),"forward")).newSchema);const u=await o.migrate(h);return await async function(e,t,r,s){const i=t.getReader();let a=[];try{for(;;){const{value:e,done:t}=await i.read();if(t)break;if(!e)continue;const{$version:n}=e;e.$version=(n||0)+1,e.$updated=(new Date).toJSON(),a.push(e),a.length>=s&&(await r.batch([{type:"put",data:a}]),a=[])}a.length>0&&await r.batch([{type:"put",data:a}])}catch(t){throw console.error(`[migrateCollection] Error writing transformed data for '${e}':`,t),new B("INTERNAL_ERROR",`Failed to write transformed data for collection '${e}'`,void 0,t)}finally{i.releaseLock()}}(e,u,i,r),!0},transaction:async e=>{const t=new rt;try{await e(t),await t.commit()}catch(e){throw t.rollback(),e}},subscribe:r.subscribe,close:()=>{i.clear(),a.clear(),r.clear()},ensureCollection:async e=>{try{await h.createCollection(e)}catch(e){if(e instanceof B&&"SCHEMA_ALREADY_EXISTS"===e.type)return;throw e}},setupCollections:async e=>{for(const t of e)await h.ensureCollection(t)}};return s.wrap(h,{})},exports.IndexedDBStore=Z,exports.createDocument=et,exports.createEphemeralStore=function(e){return new J(e.keyPath)},exports.createIndexedDbStore=e=>{const t=new X(e),r=t.getConnection.bind(t);return new Z(r,e.name,e.keyPath,(()=>t.ensureStore(e.name,e.keyPath)))},exports.openCollection=tt;
package/index.mjs CHANGED
@@ -1 +1 @@
1
- var e="$id",t=class extends Error{type;schema;constructor(e,t,r,s){super(t,{cause:s}),this.type=e,this.schema=r,this.name="DatabaseError"}};function r(e,r){if(e&&void 0!==e.$version&&void 0!==r.$version&&r.$version<=e.$version)throw new t("CONFLICT",`OCC Conflict: Incoming version (${r.$version}) is not greater than existing version (${e.$version}).`)}var s=class{constructor(e="$id"){this.keyPath=e}data=new Map;nextId=1;async open(){}getKey(e){const r=e[this.keyPath];if(null==r)throw new t("INVALID_DATA",`Record must have a ${this.keyPath} property`);return r}clone(e){return{...e}}async add(e){const r=Array.isArray(e)?e:[e],s=[];for(const e of r){let r=e[this.keyPath];if(void 0!==r&&""!==r||(r=String(this.nextId++),e[this.keyPath]=r),this.data.has(r))throw new t("CONFLICT",`Duplicate key ${r}`);this.data.set(r,Object.freeze(this.clone(e))),s.push(r)}return Array.isArray(e)?s:s[0]}async put(e){const t=this.getKey(e);return r(this.data.get(t),e),this.data.set(t,Object.freeze(this.clone(e))),t}async batch(e){const s=new Map,o=e=>s.has(e)?s.get(e):this.data.get(e);try{for(const n of e)if("add"===n.type||"put"===n.type){const e=Array.isArray(n.data)?n.data:[n.data];for(const i of e){let e=i[this.keyPath];"add"!==n.type||e&&""!==e?e=this.getKey(i):(e=String(this.nextId++),i[this.keyPath]=e);const a=o(e);if("add"===n.type&&null!=a)throw new t("CONFLICT",`Duplicate key ${e}`);r(a,i),s.set(e,Object.freeze(this.clone(i)))}}else if("delete"===n.type){const e=Array.isArray(n.data)?n.data:[n.data];for(const t of e)s.set(t,null)}for(const[e,t]of s.entries())null===t?this.data.delete(e):this.data.set(e,t)}catch(e){throw e}}async getById(e){const t=this.data.get(e);return t?this.clone(t):void 0}async delete(e){const t=Array.isArray(e)?e:[e];for(const e of t)this.data.delete(e)}async clear(){this.data.clear()}async count(){return this.data.size}async getByIndex(e,t){for(const r of this.data.values())if(r[e]===t)return this.clone(r)}async getByKeyRange(e,t){const r=[];for(const s of this.data.values()){const o=s[e];this.isInKeyRange(o,t)&&r.push(this.clone(s))}return r}isInKeyRange(e,t){if(!t)return!0;const{lower:r,upper:s,lowerOpen:o=!1,upperOpen:n=!1}=t;return(void 0===r||(o?e>r:e>=r))&&(void 0===s||(n?e<s:e<=s))}async getAll(){return Array.from(this.data.values()).map((e=>this.clone(e)))}async cursor(e,t="forward",r){let s=Array.from(this.data.entries());r&&(s=s.filter((([e])=>{const t=e,s=void 0===r.lower||(r.lowerOpen?t>r.lower:t>=r.lower),o=void 0===r.upper||(r.upperOpen?t<r.upper:t<=r.upper);return s&&o})));const o=s.sort((([e],[t])=>e>t?1:e<t?-1:0));"backward"===t&&o.reverse();let n=null,i=0;for(;i<o.length;){const[t,r]=o[i],{value:s,done:a,offset:c}=await e(this.clone(r),t,null);if(n=s,a)break;c&&c>0?i+=c:i++}return n}};function o(e){return new s(e.keyPath)}var n=class e extends Error{constructor(t,r){super(t,{cause:r}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},i=class extends n{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},a=class{_locked=!1;_capacity;_yieldMode;waiters=[];constructor(e){this._capacity=e?.capacity??1/0,this._yieldMode=e?.yieldMode??"macrotask"}async lock(e){if(!this._locked)return void(this._locked=!0);if(this.waiters.length>=this._capacity)throw new Error(`Mutex queue is full (capacity: ${this._capacity})`);let t;const r=new Promise((e=>t=e));this.waiters.push(t),null!=e?await Promise.race([r,new Promise(((r,s)=>setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),s(new i("Mutex lock timed out"))}),e)))]):await r}tryLock(){return!this._locked&&(this._locked=!0,!0)}unlock(){if(!this._locked)throw new Error("Mutex is not locked");const e=this.waiters.shift();e?"microtask"===this._yieldMode?queueMicrotask(e):setTimeout(e,0):this._locked=!1}locked(){return this._locked}pending(){return this.waiters.length}},c=class{mutex=new a({yieldMode:"microtask"});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=Boolean(e),this.throws=Boolean(t)}async do(e,t){return this._done?this.peek():this.promise?this._awaitWithTimeout(this.promise,t,"Once do() timed out"):(await this.mutex.lock(),this.promise?(this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")):(this.promise=(async()=>{try{const t=await e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.promise=null}return this.peek()})(),this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")))}isReady(){return this._done&&null===this.promise}running(){return null!==this.promise&&!this._done}peek(){return{value:this._value,error:this._error}}get(){if(!this._done)throw new Error("Once operation is not yet complete");if(this._error)throw this._error;return this._value}reset(){this._done=!1,this.promise=null,this._value=null,this._error=void 0}resolved(){return this.promise}done(){return this._done}_awaitWithTimeout(e,t,r="Operation timed out"){return null==t?e:Promise.race([e,new Promise(((e,s)=>setTimeout((()=>s(new i(r))),t)))])}},h=class{constructor(e){this.config=e,this.schemasStoreName=e.schemasStoreName||"schemas"}connectionInitializer=new c({retry:!0,throws:!0});schemasStoreName;async openDatabase(){return new Promise(((e,t)=>{const r=indexedDB.open(this.config.name);r.onerror=()=>t(new Error(`Failed to open database: ${r.error?.message}`)),r.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(this.schemasStoreName)||t.createObjectStore(this.schemasStoreName,{keyPath:"name"})},r.onsuccess=()=>e(r.result)}))}async upgradeDatabase(e,t){const r=e.version+1;return e.close(),new Promise(((e,s)=>{const o=indexedDB.open(this.config.name,r);o.onerror=()=>s(new Error(`Failed to upgrade database: ${o.error?.message}`)),o.onupgradeneeded=e=>{const r=e.target.result;t(r)},o.onsuccess=()=>e(o.result)}))}async ensureStore(e,t="$id"){(await this.getConnection()).objectStoreNames.contains(e)||await this.upgrade((r=>{r.objectStoreNames.contains(this.schemasStoreName)||r.createObjectStore(this.schemasStoreName,{keyPath:"name"}),r.objectStoreNames.contains(e)||r.createObjectStore(e,{keyPath:t})}))}getConnection=async()=>{const e=await this.connectionInitializer.do((async()=>{const e=await this.openDatabase();return e.onclose=()=>this.connectionInitializer.reset(),e.onversionchange=()=>{e.close(),this.connectionInitializer.reset()},e}));if(e.error)throw new t("CONNECTION_FAILED",`Failed to open database: ${this.config.name}`,void 0,e.error);return e.value};async upgrade(e){const r=await this.getConnection();this.connectionInitializer.reset();const s=await this.connectionInitializer.do((async()=>await this.upgradeDatabase(r,e)));if(s.error)throw new t("INTERNAL_ERROR",`Database upgrade failed for ${this.config.name}`,void 0,s.error);return s.value}close(){const e=this.connectionInitializer.peek();e.value&&e.value.close(),this.connectionInitializer.reset()}};function u(e){if(e)return void 0!==e.lower&&void 0!==e.upper?IDBKeyRange.bound(e.lower,e.upper,e.lowerOpen,e.upperOpen):void 0!==e.lower?IDBKeyRange.lowerBound(e.lower,e.lowerOpen):void 0!==e.upper?IDBKeyRange.upperBound(e.upper,e.upperOpen):void 0}var d=class{constructor(e,t,r="$id",s){this.getConnection=e,this.storeName=t,this.keyPath=r,this.onOpen=s}async open(){return this.onOpen()}mapError(e){if(e instanceof t)return e;const r=e?.message||"Unknown IndexedDB Error",s=e?.name||"";return"QuotaExceededError"===s?new t("INTERNAL_ERROR","Storage quota exceeded"):new t("VersionError"===s?"CONFLICT":"InvalidStateError"===s||"TransactionInactiveError"===s?"TRANSIENT_ERROR":"INTERNAL_ERROR",r)}async withTx(e,t){const r=await this.getConnection();return new Promise((async(s,o)=>{const n=r.transaction(this.storeName,e),i=n.objectStore(this.storeName);let a,c;n.oncomplete=()=>{c?o(c):s(a)},n.onerror=()=>o(this.mapError(n.error)),n.onabort=()=>o(this.mapError(n.error));try{const e=t(i,n);a=e instanceof Promise?a=await e:e}catch(e){c=e;try{n.abort()}catch(e){}}}))}requestToPromise(e){return new Promise(((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)}))}async put(e){return this.withTx("readwrite",(async t=>{const s=e[this.keyPath];if(void 0!==s){r(await this.requestToPromise(t.get(s)),e)}return this.requestToPromise(t.put(e))}))}async add(e){return this.withTx("readwrite",(async t=>{const r=Array.isArray(e)?e:[e],s=[];for(const e of r){const r=await this.requestToPromise(t.add(e));s.push(r)}return Array.isArray(e)?s:s[0]}))}async batch(e){return this.withTx("readwrite",(async t=>{for(const s of e)if("put"===s.type||"add"===s.type){const e=Array.isArray(s.data)?s.data:[s.data];for(const o of e)if("put"===s.type){const e=o[this.keyPath];if(void 0!==e){r(await this.requestToPromise(t.get(e)),o)}await this.requestToPromise(t.put(o))}else await this.requestToPromise(t.add(o))}else if("delete"===s.type){const e=Array.isArray(s.data)?s.data:[s.data];for(const r of e)await this.requestToPromise(t.delete(r))}}))}async getById(e){return this.withTx("readonly",(async t=>this.requestToPromise(t.get(e))))}async delete(e){return this.withTx("readwrite",(async t=>{const r=Array.isArray(e)?e:[e];for(const e of r)await this.requestToPromise(t.delete(e))}))}async clear(){return this.withTx("readwrite",(async e=>{await this.requestToPromise(e.clear())}))}async count(){return this.withTx("readonly",(async e=>this.requestToPromise(e.count())))}async getByIndex(e,t){return this.withTx("readonly",(async r=>{const s=r.index(e);return this.requestToPromise(s.get(t))}))}async getByKeyRange(e,t){return this.withTx("readonly",(async r=>{const s=r.index(e);return this.requestToPromise(s.getAll(u(t)))}))}async getAll(){return this.withTx("readonly",(async e=>this.requestToPromise(e.getAll())))}async cursor(e,t="forward",r){return this.withTx("readonly",(async s=>{const o="forward"===t?"next":"prev",n=s.openCursor(u(r),o);return new Promise(((t,r)=>{let s=null;n.onsuccess=async o=>{const n=o.target.result;if(!n)return t(s);try{const{value:r,done:o,offset:i}=await e(n.value,n.key,n);s=r,o?t(s):i&&i>0?n.advance(i):n.continue()}catch(e){r(e)}},n.onerror=()=>r(this.mapError(n.error))}))}))}},l=e=>{const t=new h(e),r=t.getConnection.bind(t);return new d(r,e.name,e.keyPath,(()=>t.ensureStore(e.name,e.keyPath)))};export{h as ConnectionManager,e as DEFAULT_KEYPATH,d as IndexedDBStore,o as createEphemeralStore,l as createIndexedDbStore};
1
+ import{Buffer as e}from"buffer";import{v7 as t}from"uuid";var r,s,i=Object.create,a=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,c=Object.getPrototypeOf,h=Object.prototype.hasOwnProperty,u=(e,t)=>function(){return t||(0,e[o(e)[0]])((t={exports:{}}).exports,t),t.exports},d=(e,t,r,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of o(t))h.call(e,i)||i===r||a(e,i,{get:()=>t[i],enumerable:!(s=n(t,i))||s.enumerable});return e},l=(e,t,r)=>(r=null!=e?i(c(e)):{},d(e&&e.__esModule?r:a(r,"default",{value:e,enumerable:!0}),e)),p=e=>d(a({},"__esModule",{value:!0}),e),m=u({"node_modules/@asaidimu/events/index.js"(e,t){var r,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})})(o,{createEventBus:()=>c}),t.exports=(r=o,((e,t,r,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))n.call(e,c)||c===r||s(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e})(s({},"__esModule",{value:!0}),r));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let r=[],s=0,i=0;const a=new Map,n=new Map;let o=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?o=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{s++,i+=t,a.set(e,(a.get(e)||0)+1)},h=()=>{const t=r;r=[],t.forEach((({name:t,payload:r})=>{const s=performance.now();try{(n.get(t)||[]).forEach((e=>e(r)))}catch(s){e.errorHandler({...s,eventName:t,payload:r})}c(t,performance.now()-s)}))},u=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(h,e.batchDelay)}})(),d=e=>{const r=t.get(e);r?n.set(e,Array.from(r)):n.delete(e)};return o&&(o.onmessage=e=>{const{name:t,payload:r}=e.data;(n.get(t)||[]).forEach((e=>e(r)))}),{subscribe:(e,r)=>{t.has(e)||t.set(e,new Set);const s=t.get(e);return s.add(r),d(e),()=>{s.delete(r),0===s.size?(t.delete(e),n.delete(e)):d(e)}},emit:({name:t,payload:s})=>{if(e.async)return r.push({name:t,payload:s}),r.length>=e.batchSize?h():u(),void(o&&o.postMessage({name:t,payload:s}));const i=performance.now();try{(n.get(t)||[]).forEach((e=>e(s))),o&&o.postMessage({name:t,payload:s})}catch(r){e.errorHandler({...r,eventName:t,payload:s})}c(t,performance.now()-i)},getMetrics:()=>({totalEvents:s,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:a,averageEmitDuration:s>0?i/s:0}),clear:()=>{t.clear(),n.clear(),r=[],s=0,i=0,a.clear(),o&&(o.close(),o=null)}}}}}),f=u({"node_modules/@asaidimu/query/index.js"(e,t){var r,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})})(o,{QueryBuilder:()=>c,createJoiner:()=>y,createMatcher:()=>u,createPaginator:()=>E,createProjector:()=>_,createSorter:()=>$}),t.exports=(r=o,((e,t,r,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))!n.call(e,c)&&c!==r&&s(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e})(s({},"__esModule",{value:!0}),r));var c=class{query;constructor(){this.query={}}where(e){return this.query.filters=e,this}orderBy(e,t){return this.query.sort||(this.query.sort=[]),this.query.sort.push({field:e,direction:t}),this}offset(e,t){return this.query.pagination={type:"offset",offset:e,limit:t},this}cursor(e,t,r){return this.query.pagination={type:"cursor",cursor:e,limit:t,direction:r},this}include(e){return this.query.projection||(this.query.projection={}),this.query.projection.include=e,this}exclude(e){return this.query.projection||(this.query.projection={}),this.query.projection.exclude=e,this}computed(e,t){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:"computed",expression:e,alias:t}),this}case(e,t,r){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:"case",conditions:e,else:t,alias:r}),this}join(e,t,r){return this.query.joins||(this.query.joins=[]),this.query.joins.push({relation:e,alias:r,query:t}),this}aggregate(e,t){return this.query.aggregations={groupBy:e,metrics:t},this}window(e){return this.query.window||(this.query.window=[]),this.query.window.push(e),this}hint(e){return this.query.hints||(this.query.hints=[]),this.query.hints.push(e),this}build(){return this.query}};function h(e){function t(e,t){return function(e){return"field"===e?.type}(t)?e[t.field]:function(e){return"value"===e?.type}(t)?t.value:function(e){return"function"===e?.type}(t)?s(t,e):function(e){return"computed"===e?.type}(t)?s(t.expression,e):function(e){return"case"===e?.type}(t)?function(e,t){for(let r of t.conditions)if(i(e,r.when))return r.then;return t.else}(e,t):t}let r=new Map([["and",(e,t)=>t.every((t=>i(e,t)))],["or",(e,t)=>t.some((t=>i(e,t)))],["not",(e,t)=>!t.every((t=>i(e,t)))],["nor",(e,t)=>!t.some((t=>i(e,t)))],["xor",(e,t)=>1===t.filter((t=>i(e,t))).length]]);function s(r,s){let i=r.arguments.map((e=>t(s,e)));if(e[r.function])return e[r.function](...i);throw new Error(`Function ${r.function} not found!`)}function i(s,i){if(function(e){return!!e&&void 0!==e.conditions}(i))return function(e,t){let{operator:s,conditions:i}=t,a=r.get(s);if(a)return a(e,i);throw new Error(`Unsupported logical operator: ${s}`)}(s,i);if(!i||!i.field)return!1;let{field:a,operator:n,value:o}=i,c=s[a],h=t(s,o),u=new Map([["eq",(e,t)=>e===t],["neq",(e,t)=>e!==t],["lt",(e,t)=>e<t],["lte",(e,t)=>e<=t],["gt",(e,t)=>e>t],["gte",(e,t)=>e>=t],["in",(e,t)=>Array.isArray(t)&&t.includes(e)],["nin",(e,t)=>Array.isArray(t)&&!t.includes(e)],["contains",(e,t)=>"string"==typeof e?e.includes(t):!!Array.isArray(e)&&e.includes(o)],["ncontains",(e,t)=>"string"==typeof e&&!e.includes(t)],["startswith",(e,t)=>"string"==typeof e&&e.startsWith(t)],["endswith",(e,t)=>"string"==typeof e&&e.endsWith(t)],["exists",e=>null!=e],["nexists",e=>null==e]]),d=e[n]||u.get(n);if(d)return d(c,h);throw new Error(`Unsupported comparison operator: ${n}`)}return{resolve:t,evaluate:i}}function u(e){let{evaluate:t}=h(e),r=new WeakMap;function s(e,s){let i=r.get(e);i||(i=new Map,r.set(e,i));let a=JSON.stringify(s);if(i.has(a))return i.get(a);let n=t(e,s);return i.set(a,n),n}return{matcher:s,match:s}}var d=class extends Error{constructor(e,t){super(e),this.code=t,this.name="JoinError"}},l=e=>e&&"field"in e&&"operator"in e&&"value"in e,p=(e,t)=>{if(e){if(l(e)&&e){let r=(e=>"object"==typeof e&&null!==e&&"type"in e&&"field"===e.type)(e.value)?((e,t)=>t.split(".").reduce(((e,t)=>e?.[t]),e))(t,e.value.field):e.value;return{...e,value:r}}if((e=>"operator"in e&&"conditions"in e)(e)){let r={...e};return e.conditions&&(r.conditions=e.conditions.map((e=>p(e,t)))),r}return e}},m=async(e,t,r,s)=>{try{if(((e,t)=>{if(!e.relation)throw new d("Join configuration must specify a relation","INVALID_CONFIG");if(!t[e.relation])throw new d(`Collection "${e.relation}" not found in database`,"COLLECTION_NOT_FOUND");if(e.alias&&"string"!=typeof e.alias)throw new d("Join alias must be a string","INVALID_ALIAS")})(r,e),!Array.isArray(t))throw new d("Source data must be an array","INVALID_SOURCE_DATA");let i,a=e[r.relation];return r.query?.filters&&l(r.query.filters)&&(i=((e,t)=>{let r=new Map;return e.forEach((e=>{let s=e[t];r.has(s)||r.set(s,[]),r.get(s).push(e)})),r})(a,r.query.filters.field)),(await Promise.all(t.map((async e=>{let t,n=((e,t)=>{if(!e)return{};let r=p(e.filters,t);return{...e,filters:r}})(r.query,e);return t=n.filters&&l(n.filters)&&i?.has(n.filters.value)?i.get(n.filters.value)||[]:a.filter((e=>s.matcher(e,n.filters))),((e,t,r)=>{let s=r.alias||r.relation;return[{...e,[s]:t}]})(e,await[e=>n.sort?s.sorter(e,n.sort):e,e=>n.projection?s.projector(e,n.projection):e,async e=>n.pagination?await s.paginator(e,n.pagination):e].reduce((async(e,t)=>t(await e)),Promise.resolve(t)),r)})))).flat()}catch(e){throw e instanceof d?e:new d(`Join operation failed: ${e.message}`,"JOIN_EXECUTION_ERROR")}},f=async(e,t,r,s)=>r.reduce((async(t,r)=>m(e,await t,r,s)),Promise.resolve(t));function y(){return{join:f}}var w=class extends Error{constructor(e,t){super(`Unsupported comparison between ${typeof e} and ${typeof t}`),this.name="UnsupportedComparisonError"}},g=class extends Error{constructor(e){super(`Unsupported sort direction: ${e}`),this.name="InvalidSortDirectionError"}};function b(e,t,r){if(e===t)return 0;if(null==e||null==t)return null==e?"asc"===r?-1:1:"asc"===r?1:-1;if("string"==typeof e&&"string"==typeof t)return"asc"===r?e.localeCompare(t):t.localeCompare(e);if("number"==typeof e&&"number"==typeof t)return"asc"===r?e-t:t-e;throw new w(e,t)}function v(e,t){let r=Array.from(e);return 0===t.length?r:r.sort(((e,r)=>{for(let s of t){let{field:t,direction:i}=s,a=e[t],n=r[t];try{if("asc"!==i&&"desc"!==i)throw new g(i);let e=b(a,n,i);if(0!==e)return e}catch(e){throw e instanceof w||e instanceof g?e:new Error(`Error comparing field '${t}': ${e.message}`)}}return 0}))}function $(){return{sort:v}}function _(e){let{resolve:t}=h(e);function r(e,s){let i={};return s.include?.length&&function(e,t,s){for(let i of t)if("string"!=typeof i){for(let[t,a]of Object.entries(i))if(Object.prototype.hasOwnProperty.call(e,t)){let i=r(e[t],a);s[t]=i}}else{let t=i;s[t]=e[t]}}(e,s.include,i),s.exclude?.length&&function(e,t,s){0===Object.keys(s).length&&Object.assign(s,e);for(let e of t)if("string"!=typeof e)for(let[t,i]of Object.entries(e)){if(!Object.prototype.hasOwnProperty.call(s,t))continue;let e=s[t];e&&"object"==typeof e?s[t]=r(e,i):delete s[t]}else delete s[e]}(e,s.exclude,i),s.computed?.length&&function(e,r,s){for(let i of r)s[i.alias]=t(e,i)}(e,s.computed,i),i}return{project:r}}async function*k(e,t,r=e=>String(e)){"offset"===t.type?yield*async function*(e,t){let{offset:r,limit:s}=t,i=0,a=s,n=[];for await(let t of e)a<=0&&(yield n,n=[],a=s),i<r?i++:(n.push(t),a--);n.length>0&&(yield n)}(e,t):yield*async function*(e,t,r){let{cursor:s,limit:i,direction:a}=t,n=i,o=void 0===s,c=[];if("forward"===a)for await(let t of e)n<=0&&(yield c,c=[],n=i),o?(c.push(t),n--):o=r(t)===s;else{let t=[];for await(let r of e)t.push(r);for(let e=t.length-1;e>=0;e--){let a=t[e];o?(c.push(a),n--,n<=0&&(yield c,c=[],n=i)):o=r(a)===s}}c.length>0&&(yield c)}(e,t,r)}function E(){return{paginate:k}}}}),y=u({"node_modules/just-once/index.js"(e,t){t.exports=function(e){var t,r;if("function"!=typeof e)throw new Error("expected a function but got "+e);return function(){return t?r:(t=!0,r=e.apply(this,arguments))}}}}),w=u({"node_modules/isomorphic-textencoder/main.js"(e,t){t.exports={encode:e=>new Uint8Array(Buffer.from(e,"utf8")),decode:e=>Buffer.from(e).toString("utf8")}}}),g=u({"node_modules/just-debounce-it/index.js"(e,t){t.exports=function(e,t,r){var s;return function(){if(!t)return e.apply(this,arguments);var i=this,a=arguments,n=r&&!s;return clearTimeout(s),s=setTimeout((function(){if(s=null,!n)return e.apply(i,a)}),t),n?e.apply(this,arguments):void 0}}}}),b=u({"node_modules/@isomorphic-git/lightning-fs/src/path.js"(e,t){function r(e){if(0===e.length)return".";let t=i(e);return t=t.reduce(a,[]),s(...t)}function s(...e){if(0===e.length)return"";let t=e.join("/");return t=t.replace(/\/{2,}/g,"/"),t}function i(e){if(0===e.length)return[];if("/"===e)return["/"];let t=e.split("/");return""===t[t.length-1]&&t.pop(),"/"===e[0]?t[0]="/":"."!==t[0]&&t.unshift("."),t}function a(e,t){if(0===e.length)return e.push(t),e;if("."===t)return e;if(".."===t){if(1===e.length){if("/"===e[0])throw new Error("Unable to normalize path - traverses above root directory");if("."===e[0])return e.push(t),e}return".."===e[e.length-1]?(e.push(".."),e):(e.pop(),e)}return e.push(t),e}t.exports={join:s,normalize:r,split:i,basename:function(e){if("/"===e)throw new Error(`Cannot get basename of "${e}"`);const t=e.lastIndexOf("/");return-1===t?e:e.slice(t+1)},dirname:function(e){const t=e.lastIndexOf("/");if(-1===t)throw new Error(`Cannot get dirname of "${e}"`);return 0===t?"/":e.slice(0,t)},resolve:function(...e){let t="";for(let i of e)t=i.startsWith("/")?i:r(s(t,i));return t}}}}),v=u({"node_modules/@isomorphic-git/lightning-fs/src/errors.js"(e,t){function r(e){return class extends Error{constructor(...t){super(...t),this.code=e,this.message?this.message=e+": "+this.message:this.message=e}}}var s=r("EEXIST"),i=r("ENOENT"),a=r("ENOTDIR"),n=r("ENOTEMPTY"),o=r("ETIMEDOUT"),c=r("EISDIR");t.exports={EEXIST:s,ENOENT:i,ENOTDIR:a,ENOTEMPTY:n,ETIMEDOUT:o,EISDIR:c}}}),$=u({"node_modules/@isomorphic-git/lightning-fs/src/CacheFS.js"(e,t){var r=b(),{EEXIST:s,ENOENT:i,ENOTDIR:a,ENOTEMPTY:n,EISDIR:o}=v();t.exports=class{constructor(){}_makeRoot(e=new Map){return e.set(0,{mode:511,type:"dir",size:0,ino:0,mtimeMs:Date.now()}),e}activate(e=null){this._root=null===e?new Map([["/",this._makeRoot()]]):"string"==typeof e?new Map([["/",this._makeRoot(this.parse(e))]]):e}get activated(){return!!this._root}deactivate(){this._root=void 0}size(){return this._countInodes(this._root.get("/"))-1}_countInodes(e){let t=1;for(let[r,s]of e)0!==r&&(t+=this._countInodes(s));return t}autoinc(){return this._maxInode(this._root.get("/"))+1}_maxInode(e){let t=e.get(0).ino;for(let[r,s]of e)0!==r&&(t=Math.max(t,this._maxInode(s)));return t}print(e=this._root.get("/")){let t="";const r=(e,s)=>{for(let[i,a]of e){if(0===i)continue;let e=a.get(0),n=e.mode.toString(8);t+=`${"\t".repeat(s)}${i}\t${n}`,"file"===e.type?t+=`\t${e.size}\t${e.mtimeMs}\n`:(t+="\n",r(a,s+1))}};return r(e,0),t}parse(e){let t=0;function r(e){const r=++t,s=1===e.length?"dir":"file";let[i,a,n]=e;return i=parseInt(i,8),a=a?parseInt(a):0,n=n?parseInt(n):Date.now(),new Map([[0,{mode:i,type:s,size:a,mtimeMs:n,ino:r}]])}let s=e.trim().split("\n"),i=this._makeRoot(),a=[{indent:-1,node:i},{indent:0,node:null}];for(let e of s){let t=e.match(/^\t*/)[0].length;e=e.slice(t);let[s,...i]=e.split("\t"),n=r(i);if(t<=a[a.length-1].indent)for(;t<=a[a.length-1].indent;)a.pop();a.push({indent:t,node:n}),a[a.length-2].node.set(s,n)}return i}_lookup(e,t=!0){let s=this._root,a="/",n=r.split(e);for(let o=0;o<n.length;++o){let c=n[o];if(s=s.get(c),!s)throw new i(e);if(t||o<n.length-1){const e=s.get(0);if("symlink"===e.type){let t=r.resolve(a,e.target);s=this._lookup(t)}a=a?r.join(a,c):c}}return s}mkdir(e,{mode:t}){if("/"===e)throw new s;let i=this._lookup(r.dirname(e)),a=r.basename(e);if(i.has(a))throw new s;let n=new Map,o={mode:t,type:"dir",size:0,mtimeMs:Date.now(),ino:this.autoinc()};n.set(0,o),i.set(a,n)}rmdir(e){let t=this._lookup(e);if("dir"!==t.get(0).type)throw new a;if(t.size>1)throw new n;let s=this._lookup(r.dirname(e)),i=r.basename(e);s.delete(i)}readdir(e){let t=this._lookup(e);if("dir"!==t.get(0).type)throw new a;return[...t.keys()].filter((e=>"string"==typeof e))}writeStat(e,t,{mode:s}){let i,a;try{a=this.stat(e)}catch(e){}if(void 0!==a){if("dir"===a.type)throw new o;null==s&&(s=a.mode),i=a.ino}null==s&&(s=438),null==i&&(i=this.autoinc());let n=this._lookup(r.dirname(e)),c=r.basename(e),h={mode:s,type:"file",size:t,mtimeMs:Date.now(),ino:i},u=new Map;return u.set(0,h),n.set(c,u),h}unlink(e){let t=this._lookup(r.dirname(e)),s=r.basename(e);t.delete(s)}rename(e,t){let s=r.basename(t),i=this._lookup(e);this._lookup(r.dirname(t)).set(s,i),this.unlink(e)}stat(e){return this._lookup(e).get(0)}lstat(e){return this._lookup(e,!1).get(0)}readlink(e){return this._lookup(e,!1).get(0).target}symlink(e,t){let s,i;try{let e=this.stat(t);null===i&&(i=e.mode),s=e.ino}catch(e){}null==i&&(i=40960),null==s&&(s=this.autoinc());let a=this._lookup(r.dirname(t)),n=r.basename(t),o={mode:i,type:"symlink",target:e,size:0,mtimeMs:Date.now(),ino:s},c=new Map;return c.set(0,o),a.set(n,c),o}_du(e){let t=0;for(const[r,s]of e.entries())t+=0===r?s.size:this._du(s);return t}du(e){let t=this._lookup(e);return this._du(t)}}}}),_={};function k(){return s||(s=new r),s}function E(e,t=k()){let r;return t._withIDBStore("readwrite",(t=>{r=t.get(e)})).then((()=>r.result))}function S(e,t,r=k()){return r._withIDBStore("readwrite",(r=>{r.put(t,e)}))}function O(e,t,r=k()){return r._withIDBStore("readwrite",(r=>{const s=r.get(e);s.onsuccess=()=>{r.put(t(s.result),e)}}))}function A(e,t=k()){return t._withIDBStore("readwrite",(t=>{t.delete(e)}))}function I(e=k()){return e._withIDBStore("readwrite",(e=>{e.clear()}))}function j(e=k()){const t=[];return e._withIDBStore("readwrite",(e=>{(e.openKeyCursor||e.openCursor).call(e).onsuccess=function(){this.result&&(t.push(this.result.key),this.result.continue())}})).then((()=>t))}function x(e=k()){return e._close()}((e,t)=>{for(var r in t)a(e,r,{get:t[r],enumerable:!0})})(_,{Store:()=>r,clear:()=>I,close:()=>x,del:()=>A,get:()=>E,keys:()=>j,set:()=>S,update:()=>O});var N,T,C=(N={"node_modules/@isomorphic-git/idb-keyval/dist/idb-keyval.mjs"(){r=class{constructor(e="keyval-store",t="keyval"){this.storeName=t,this._dbName=e,this._storeName=t,this._init()}_init(){this._dbp||(this._dbp=new Promise(((e,t)=>{const r=indexedDB.open(this._dbName);r.onerror=()=>t(r.error),r.onsuccess=()=>e(r.result),r.onupgradeneeded=()=>{r.result.createObjectStore(this._storeName)}})))}_withIDBStore(e,t){return this._init(),this._dbp.then((r=>new Promise(((s,i)=>{const a=r.transaction(this.storeName,e);a.oncomplete=()=>s(),a.onabort=a.onerror=()=>i(a.error),t(a.objectStore(this.storeName))}))))}_close(){return this._init(),this._dbp.then((e=>{e.close(),this._dbp=void 0}))}}}},function(){return N&&(T=(0,N[o(N)[0]])(N=0)),T}),M=u({"node_modules/@isomorphic-git/lightning-fs/src/IdbBackend.js"(e,t){var r=(C(),p(_));t.exports=class{constructor(e,t){this._database=e,this._storename=t,this._store=new r.Store(this._database,this._storename)}saveSuperblock(e){return r.set("!root",e,this._store)}loadSuperblock(){return r.get("!root",this._store)}readFile(e){return r.get(e,this._store)}writeFile(e,t){return r.set(e,t,this._store)}unlink(e){return r.del(e,this._store)}wipe(){return r.clear(this._store)}close(){return r.close(this._store)}}}}),R=u({"node_modules/@isomorphic-git/lightning-fs/src/HttpBackend.js"(e,t){t.exports=class{constructor(e){this._url=e}loadSuperblock(){return fetch(this._url+"/.superblock.txt").then((e=>e.ok?e.text():null))}async readFile(e){const t=await fetch(this._url+e);if(200===t.status)return t.arrayBuffer();throw new Error("ENOENT")}async sizeFile(e){const t=await fetch(this._url+e,{method:"HEAD"});if(200===t.status)return t.headers.get("content-length");throw new Error("ENOENT")}}}}),P=u({"node_modules/@isomorphic-git/lightning-fs/src/Mutex.js"(e,t){var r=(C(),p(_)),s=e=>new Promise((t=>setTimeout(t,e)));t.exports=class{constructor(e,t){this._id=Math.random(),this._database=e,this._storename=t,this._store=new r.Store(this._database,this._storename),this._lock=null}async has({margin:e=2e3}={}){if(this._lock&&this._lock.holder===this._id){const t=Date.now();return this._lock.expires>t+e||await this.renew()}return!1}async renew({ttl:e=5e3}={}){let t;return await r.update("lock",(r=>{const s=Date.now()+e;return t=r&&r.holder===this._id,this._lock=t?{holder:this._id,expires:s}:r,this._lock}),this._store),t}async acquire({ttl:e=5e3}={}){let t,s,i;if(await r.update("lock",(r=>{const a=Date.now(),n=a+e;return s=r&&r.expires<a,t=void 0===r||s,i=r&&r.holder===this._id,this._lock=t?{holder:this._id,expires:n}:r,this._lock}),this._store),i)throw new Error("Mutex double-locked");return t}async wait({interval:e=100,limit:t=6e3,ttl:r}={}){for(;t--;){if(await this.acquire({ttl:r}))return!0;await s(e)}throw new Error("Mutex timeout")}async release({force:e=!1}={}){let t,s,i;if(await r.update("lock",(r=>(t=e||r&&r.holder===this._id,s=void 0===r,i=r&&r.holder!==this._id,this._lock=t?void 0:r,this._lock)),this._store),await r.close(this._store),!t&&!e){if(s)throw new Error("Mutex double-freed");if(i)throw new Error("Mutex lost ownership")}return t}}}}),D=u({"node_modules/@isomorphic-git/lightning-fs/src/Mutex2.js"(e,t){t.exports=class{constructor(e){this._id=Math.random(),this._database=e,this._has=!1,this._release=null}async has(){return this._has}async acquire(){return new Promise((e=>{navigator.locks.request(this._database+"_lock",{ifAvailable:!0},(t=>(this._has=!!t,e(!!t),new Promise((e=>{this._release=e})))))}))}async wait({timeout:e=6e5}={}){return new Promise(((t,r)=>{const s=new AbortController;setTimeout((()=>{s.abort(),r(new Error("Mutex timeout"))}),e),navigator.locks.request(this._database+"_lock",{signal:s.signal},(e=>(this._has=!!e,t(!!e),new Promise((e=>{this._release=e})))))}))}async release({force:e=!1}={}){this._has=!1,this._release?this._release():e&&navigator.locks.request(this._database+"_lock",{steal:!0},(e=>!0))}}}}),q=u({"node_modules/@isomorphic-git/lightning-fs/src/DefaultBackend.js"(e,t){var{encode:r,decode:s}=w(),i=g(),a=$(),{ENOENT:n,ENOTEMPTY:o,ETIMEDOUT:c}=v(),h=M(),u=R(),d=P(),l=D(),p=b();t.exports=class{constructor(){this.saveSuperblock=i((()=>{this.flush()}),500)}async init(e,{wipe:t,url:r,urlauto:s,fileDbName:i=e,db:n=null,fileStoreName:o=e+"_files",lockDbName:c=e+"_lock",lockStoreName:p=e+"_lock"}={}){this._name=e,this._idb=n||new h(i,o),this._mutex=navigator.locks?new l(e):new d(c,p),this._cache=new a(e),this._opts={wipe:t,url:r},this._needsWipe=!!t,r&&(this._http=new u(r),this._urlauto=!!s)}async activate(){if(this._cache.activated)return;this._needsWipe&&(this._needsWipe=!1,await this._idb.wipe(),await this._mutex.release({force:!0})),await this._mutex.has()||await this._mutex.wait();const e=await this._idb.loadSuperblock();if(e)this._cache.activate(e);else if(this._http){const e=await this._http.loadSuperblock();this._cache.activate(e),await this._saveSuperblock()}else this._cache.activate();if(!await this._mutex.has())throw new c}async deactivate(){await this._mutex.has()&&await this._saveSuperblock(),this._cache.deactivate();try{await this._mutex.release()}catch(e){console.log(e)}await this._idb.close()}async _saveSuperblock(){this._cache.activated&&(this._lastSavedAt=Date.now(),await this._idb.saveSuperblock(this._cache._root))}_writeStat(e,t,r){let s=p.split(p.dirname(e)),i=s.shift();for(let e of s){i=p.join(i,e);try{this._cache.mkdir(i,{mode:511})}catch(e){}}return this._cache.writeStat(e,t,r)}async readFile(e,t){const r="string"==typeof t?t:t&&t.encoding;if(r&&"utf8"!==r)throw new Error('Only "utf8" encoding is supported in readFile');let i=null,a=null;try{a=this._cache.stat(e),i=await this._idb.readFile(a.ino)}catch(e){if(!this._urlauto)throw e}if(!i&&this._http){let t=this._cache.lstat(e);for(;"symlink"===t.type;)e=p.resolve(p.dirname(e),t.target),t=this._cache.lstat(e);i=await this._http.readFile(e)}if(i&&(a&&a.size==i.byteLength||(a=await this._writeStat(e,i.byteLength,{mode:a?a.mode:438}),this.saveSuperblock()),"utf8"===r?i=s(i):i.toString=()=>s(i)),!a)throw new n(e);return i}async writeFile(e,t,s){const{mode:i,encoding:a="utf8"}=s;if("string"==typeof t){if("utf8"!==a)throw new Error('Only "utf8" encoding is supported in writeFile');t=r(t)}const n=await this._cache.writeStat(e,t.byteLength,{mode:i});await this._idb.writeFile(n.ino,t)}async unlink(e,t){const r=this._cache.lstat(e);this._cache.unlink(e),"symlink"!==r.type&&await this._idb.unlink(r.ino)}readdir(e,t){return this._cache.readdir(e)}mkdir(e,t){const{mode:r=511}=t;this._cache.mkdir(e,{mode:r})}rmdir(e,t){if("/"===e)throw new o;this._cache.rmdir(e)}rename(e,t){this._cache.rename(e,t)}stat(e,t){return this._cache.stat(e)}lstat(e,t){return this._cache.lstat(e)}readlink(e,t){return this._cache.readlink(e)}symlink(e,t){this._cache.symlink(e,t)}async backFile(e,t){let r=await this._http.sizeFile(e);await this._writeStat(e,r,t)}du(e){return this._cache.du(e)}flush(){return this._saveSuperblock()}}}}),F=u({"node_modules/@isomorphic-git/lightning-fs/src/Stat.js"(e,t){t.exports=class{constructor(e){this.type=e.type,this.mode=e.mode,this.size=e.size,this.ino=e.ino,this.mtimeMs=e.mtimeMs,this.ctimeMs=e.ctimeMs||e.mtimeMs,this.uid=1,this.gid=1,this.dev=1}isFile(){return"file"===this.type}isDirectory(){return"dir"===this.type}isSymbolicLink(){return"symlink"===this.type}}}}),U=u({"node_modules/@isomorphic-git/lightning-fs/src/PromisifiedFS.js"(e,t){var r=q(),s=F(),i=b();function a(e,t,...r){return void 0!==t&&"function"!=typeof t||(t={}),"string"==typeof t&&(t={encoding:t}),[e=i.normalize(e),t,...r]}function n(e,t,r,...s){return void 0!==r&&"function"!=typeof r||(r={}),"string"==typeof r&&(r={encoding:r}),[e=i.normalize(e),t,r,...s]}function o(e,t,...r){return[i.normalize(e),i.normalize(t),...r]}t.exports=class{constructor(e,t={}){this.init=this.init.bind(this),this.readFile=this._wrap(this.readFile,a,!1),this.writeFile=this._wrap(this.writeFile,n,!0),this.unlink=this._wrap(this.unlink,a,!0),this.readdir=this._wrap(this.readdir,a,!1),this.mkdir=this._wrap(this.mkdir,a,!0),this.rmdir=this._wrap(this.rmdir,a,!0),this.rename=this._wrap(this.rename,o,!0),this.stat=this._wrap(this.stat,a,!1),this.lstat=this._wrap(this.lstat,a,!1),this.readlink=this._wrap(this.readlink,a,!1),this.symlink=this._wrap(this.symlink,o,!0),this.backFile=this._wrap(this.backFile,a,!0),this.du=this._wrap(this.du,a,!1),this._deactivationPromise=null,this._deactivationTimeout=null,this._activationPromise=null,this._operations=new Set,e&&this.init(e,t)}async init(...e){return this._initPromiseResolve&&await this._initPromise,this._initPromise=this._init(...e),this._initPromise}async _init(e,t={}){await this._gracefulShutdown(),this._activationPromise&&await this._deactivate(),this._backend&&this._backend.destroy&&await this._backend.destroy(),this._backend=t.backend||new r,this._backend.init&&await this._backend.init(e,t),this._initPromiseResolve&&(this._initPromiseResolve(),this._initPromiseResolve=null),t.defer||this.stat("/")}async _gracefulShutdown(){this._operations.size>0&&(this._isShuttingDown=!0,await new Promise((e=>this._gracefulShutdownResolve=e)),this._isShuttingDown=!1,this._gracefulShutdownResolve=null)}_wrap(e,t,r){return async(...s)=>{s=t(...s);let i={name:e.name,args:s};this._operations.add(i);try{return await this._activate(),await e.apply(this,s)}finally{this._operations.delete(i),r&&this._backend.saveSuperblock(),0===this._operations.size&&(this._deactivationTimeout||clearTimeout(this._deactivationTimeout),this._deactivationTimeout=setTimeout(this._deactivate.bind(this),500))}}}async _activate(){this._initPromise||console.warn(new Error(`Attempted to use LightningFS ${this._name} before it was initialized.`)),await this._initPromise,this._deactivationTimeout&&(clearTimeout(this._deactivationTimeout),this._deactivationTimeout=null),this._deactivationPromise&&await this._deactivationPromise,this._deactivationPromise=null,this._activationPromise||(this._activationPromise=this._backend.activate?this._backend.activate():Promise.resolve()),await this._activationPromise}async _deactivate(){return this._activationPromise&&await this._activationPromise,this._deactivationPromise||(this._deactivationPromise=this._backend.deactivate?this._backend.deactivate():Promise.resolve()),this._activationPromise=null,this._gracefulShutdownResolve&&this._gracefulShutdownResolve(),this._deactivationPromise}async readFile(e,t){return this._backend.readFile(e,t)}async writeFile(e,t,r){return await this._backend.writeFile(e,t,r),null}async unlink(e,t){return await this._backend.unlink(e,t),null}async readdir(e,t){return this._backend.readdir(e,t)}async mkdir(e,t){return await this._backend.mkdir(e,t),null}async rmdir(e,t){return await this._backend.rmdir(e,t),null}async rename(e,t){return await this._backend.rename(e,t),null}async stat(e,t){const r=await this._backend.stat(e,t);return new s(r)}async lstat(e,t){const r=await this._backend.lstat(e,t);return new s(r)}async readlink(e,t){return this._backend.readlink(e,t)}async symlink(e,t){return await this._backend.symlink(e,t),null}async backFile(e,t){return await this._backend.backFile(e,t),null}async du(e){return this._backend.du(e)}async flush(){return this._backend.flush()}}}}),L=u({"node_modules/@isomorphic-git/lightning-fs/src/index.js"(e,t){var r=y(),s=U();function i(e,t){"function"==typeof e&&(t=e);return[(...e)=>t(null,...e),t=r(t)]}t.exports=class{constructor(...e){this.promises=new s(...e),this.init=this.init.bind(this),this.readFile=this.readFile.bind(this),this.writeFile=this.writeFile.bind(this),this.unlink=this.unlink.bind(this),this.readdir=this.readdir.bind(this),this.mkdir=this.mkdir.bind(this),this.rmdir=this.rmdir.bind(this),this.rename=this.rename.bind(this),this.stat=this.stat.bind(this),this.lstat=this.lstat.bind(this),this.readlink=this.readlink.bind(this),this.symlink=this.symlink.bind(this),this.backFile=this.backFile.bind(this),this.du=this.du.bind(this),this.flush=this.flush.bind(this)}init(e,t){return this.promises.init(e,t)}readFile(e,t,r){const[s,a]=i(t,r);this.promises.readFile(e,t).then(s).catch(a)}writeFile(e,t,r,s){const[a,n]=i(r,s);this.promises.writeFile(e,t,r).then(a).catch(n)}unlink(e,t,r){const[s,a]=i(t,r);this.promises.unlink(e,t).then(s).catch(a)}readdir(e,t,r){const[s,a]=i(t,r);this.promises.readdir(e,t).then(s).catch(a)}mkdir(e,t,r){const[s,a]=i(t,r);this.promises.mkdir(e,t).then(s).catch(a)}rmdir(e,t,r){const[s,a]=i(t,r);this.promises.rmdir(e,t).then(s).catch(a)}rename(e,t,r){const[s,a]=i(r);this.promises.rename(e,t).then(s).catch(a)}stat(e,t,r){const[s,a]=i(t,r);this.promises.stat(e).then(s).catch(a)}lstat(e,t,r){const[s,a]=i(t,r);this.promises.lstat(e).then(s).catch(a)}readlink(e,t,r){const[s,a]=i(t,r);this.promises.readlink(e).then(s).catch(a)}symlink(e,t,r){const[s,a]=i(r);this.promises.symlink(e,t).then(s).catch(a)}backFile(e,t,r){const[s,a]=i(t,r);this.promises.backFile(e,t).then(s).catch(a)}du(e,t){const[r,s]=i(t);this.promises.du(e).then(r).catch(s)}flush(e){const[t,r]=i(e);this.promises.flush().then(t).catch(r)}}}}),B="$id",V=class extends Error{type;schema;constructor(e,t,r,s){super(t,{cause:s}),this.type=e,this.schema=r,this.name="DatabaseError"}},z=class{queue=[];locked=!1;async acquire(){return this.locked?new Promise((e=>{this.queue.push((()=>e((()=>this.release()))))})):(this.locked=!0,()=>this.release())}release(){if(this.queue.length>0){const e=this.queue.shift();e&&e()}else this.locked=!1}};function H(e){if(null===e||"object"!=typeof e||Array.isArray(e))return[e,{}];const t={};return[Object.entries(e).reduce(((e,[r,s])=>(r.startsWith("$")?t[r]=s:e[r]=s,e)),{}),t]}function J(e,t){if(e&&void 0!==e.$version&&void 0!==t.$version&&t.$version<=e.$version)throw new V("CONFLICT",`OCC Conflict: Incoming version (${t.$version}) is not greater than existing version (${e.$version}).`)}var K=class{constructor(e="$id"){this.keyPath=e}data=new Map;nextId=1;async open(){}getKey(e){const t=e[this.keyPath];if(null==t)throw new V("INVALID_DATA",`Record must have a ${this.keyPath} property`);return t}clone(e){return{...e}}async add(e){const t=Array.isArray(e)?e:[e],r=[];for(const e of t){let t=e[this.keyPath];if(void 0!==t&&""!==t||(t=String(this.nextId++),e[this.keyPath]=t),this.data.has(t))throw new V("CONFLICT",`Duplicate key ${t}`);this.data.set(t,Object.freeze(this.clone(e))),r.push(t)}return Array.isArray(e)?r:r[0]}async put(e){const t=this.getKey(e);return J(this.data.get(t),e),this.data.set(t,Object.freeze(this.clone(e))),t}async batch(e){const t=new Map,r=e=>t.has(e)?t.get(e):this.data.get(e);try{for(const s of e)if("add"===s.type||"put"===s.type){const e=Array.isArray(s.data)?s.data:[s.data];for(const i of e){let e=i[this.keyPath];"add"!==s.type||e&&""!==e?e=this.getKey(i):(e=String(this.nextId++),i[this.keyPath]=e);const a=r(e);if("add"===s.type&&null!=a)throw new V("CONFLICT",`Duplicate key ${e}`);J(a,i),t.set(e,Object.freeze(this.clone(i)))}}else if("delete"===s.type){const e=Array.isArray(s.data)?s.data:[s.data];for(const r of e)t.set(r,null)}for(const[e,r]of t.entries())null===r?this.data.delete(e):this.data.set(e,r)}catch(e){throw e}}async getById(e){const t=this.data.get(e);return t?this.clone(t):void 0}async delete(e){const t=Array.isArray(e)?e:[e];for(const e of t)this.data.delete(e)}async clear(){this.data.clear()}async count(){return this.data.size}async getByIndex(e,t){for(const r of this.data.values())if(r[e]===t)return this.clone(r)}async getByKeyRange(e,t){const r=[];for(const s of this.data.values()){const i=s[e];this.isInKeyRange(i,t)&&r.push(this.clone(s))}return r}isInKeyRange(e,t){if(!t)return!0;const{lower:r,upper:s,lowerOpen:i=!1,upperOpen:a=!1}=t;return(void 0===r||(i?e>r:e>=r))&&(void 0===s||(a?e<s:e<=s))}async getAll(){return Array.from(this.data.values()).map((e=>this.clone(e)))}async cursor(e,t="forward",r){let s=Array.from(this.data.entries());r&&(s=s.filter((([e])=>{const t=e,s=void 0===r.lower||(r.lowerOpen?t>r.lower:t>=r.lower),i=void 0===r.upper||(r.upperOpen?t<r.upper:t<=r.upper);return s&&i})));const i=s.sort((([e],[t])=>e>t?1:e<t?-1:0));"backward"===t&&i.reverse();let a=null,n=0;for(;n<i.length;){const[t,r]=i[n],{value:s,done:o,offset:c}=await e(this.clone(r),t,null);if(a=s,o)break;c&&c>0?n+=c:n++}return a}};function W(e){return new K(e.keyPath)}var Y=class e extends Error{constructor(t,r){super(t,{cause:r}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},G=class extends Y{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},X=class{_locked=!1;_capacity;_yieldMode;waiters=[];constructor(e){this._capacity=e?.capacity??1/0,this._yieldMode=e?.yieldMode??"macrotask"}async lock(e){if(!this._locked)return void(this._locked=!0);if(this.waiters.length>=this._capacity)throw new Error(`Mutex queue is full (capacity: ${this._capacity})`);let t;const r=new Promise((e=>t=e));this.waiters.push(t),null!=e?await Promise.race([r,new Promise(((r,s)=>setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),s(new G("Mutex lock timed out"))}),e)))]):await r}tryLock(){return!this._locked&&(this._locked=!0,!0)}unlock(){if(!this._locked)throw new Error("Mutex is not locked");const e=this.waiters.shift();e?"microtask"===this._yieldMode?queueMicrotask(e):setTimeout(e,0):this._locked=!1}locked(){return this._locked}pending(){return this.waiters.length}},Q=class{mutex=new X({yieldMode:"microtask"});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=Boolean(e),this.throws=Boolean(t)}async do(e,t){return this._done?this.peek():this.promise?this._awaitWithTimeout(this.promise,t,"Once do() timed out"):(await this.mutex.lock(),this.promise?(this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")):(this.promise=(async()=>{try{const t=await e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.promise=null}return this.peek()})(),this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")))}isReady(){return this._done&&null===this.promise}running(){return null!==this.promise&&!this._done}peek(){return{value:this._value,error:this._error}}get(){if(!this._done)throw new Error("Once operation is not yet complete");if(this._error)throw this._error;return this._value}reset(){this._done=!1,this.promise=null,this._value=null,this._error=void 0}resolved(){return this.promise}done(){return this._done}_awaitWithTimeout(e,t,r="Operation timed out"){return null==t?e:Promise.race([e,new Promise(((e,s)=>setTimeout((()=>s(new G(r))),t)))])}},Z=class{constructor(e){this.config=e,this.schemasStoreName=e.schemasStoreName||"schemas"}connectionInitializer=new Q({retry:!0,throws:!0});schemasStoreName;async openDatabase(){return new Promise(((e,t)=>{const r=indexedDB.open(this.config.name);r.onerror=()=>t(new Error(`Failed to open database: ${r.error?.message}`)),r.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(this.schemasStoreName)||t.createObjectStore(this.schemasStoreName,{keyPath:"name"})},r.onsuccess=()=>e(r.result)}))}async upgradeDatabase(e,t){const r=e.version+1;return e.close(),new Promise(((e,s)=>{const i=indexedDB.open(this.config.name,r);i.onerror=()=>s(new Error(`Failed to upgrade database: ${i.error?.message}`)),i.onupgradeneeded=e=>{const r=e.target.result;t(r)},i.onsuccess=()=>e(i.result)}))}async ensureStore(e,t="$id"){(await this.getConnection()).objectStoreNames.contains(e)||await this.upgrade((r=>{r.objectStoreNames.contains(this.schemasStoreName)||r.createObjectStore(this.schemasStoreName,{keyPath:"name"}),r.objectStoreNames.contains(e)||r.createObjectStore(e,{keyPath:t})}))}getConnection=async()=>{const e=await this.connectionInitializer.do((async()=>{const e=await this.openDatabase();return e.onclose=()=>this.connectionInitializer.reset(),e.onversionchange=()=>{e.close(),this.connectionInitializer.reset()},e}));if(e.error)throw new V("CONNECTION_FAILED",`Failed to open database: ${this.config.name}`,void 0,e.error);return e.value};async upgrade(e){const t=await this.getConnection();this.connectionInitializer.reset();const r=await this.connectionInitializer.do((async()=>await this.upgradeDatabase(t,e)));if(r.error)throw new V("INTERNAL_ERROR",`Database upgrade failed for ${this.config.name}`,void 0,r.error);return r.value}close(){const e=this.connectionInitializer.peek();e.value&&e.value.close(),this.connectionInitializer.reset()}};function ee(e){if(e)return void 0!==e.lower&&void 0!==e.upper?IDBKeyRange.bound(e.lower,e.upper,e.lowerOpen,e.upperOpen):void 0!==e.lower?IDBKeyRange.lowerBound(e.lower,e.lowerOpen):void 0!==e.upper?IDBKeyRange.upperBound(e.upper,e.upperOpen):void 0}var te=class{constructor(e,t,r="$id",s){this.getConnection=e,this.storeName=t,this.keyPath=r,this.onOpen=s}async open(){return this.onOpen()}mapError(e){if(e instanceof V)return e;const t=e?.message||"Unknown IndexedDB Error",r=e?.name||"";return"QuotaExceededError"===r?new V("INTERNAL_ERROR","Storage quota exceeded"):new V("VersionError"===r?"CONFLICT":"InvalidStateError"===r||"TransactionInactiveError"===r?"TRANSIENT_ERROR":"INTERNAL_ERROR",t)}async withTx(e,t){const r=await this.getConnection();return new Promise((async(s,i)=>{const a=r.transaction(this.storeName,e),n=a.objectStore(this.storeName);let o,c;a.oncomplete=()=>{c?i(c):s(o)},a.onerror=()=>i(this.mapError(a.error)),a.onabort=()=>i(this.mapError(a.error));try{const e=t(n,a);o=e instanceof Promise?o=await e:e}catch(e){c=e;try{a.abort()}catch(e){}}}))}requestToPromise(e){return new Promise(((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)}))}async put(e){return this.withTx("readwrite",(async t=>{const r=e[this.keyPath];if(void 0!==r){J(await this.requestToPromise(t.get(r)),e)}return this.requestToPromise(t.put(e))}))}async add(e){return this.withTx("readwrite",(async t=>{const r=Array.isArray(e)?e:[e],s=[];for(const e of r){const r=await this.requestToPromise(t.add(e));s.push(r)}return Array.isArray(e)?s:s[0]}))}async batch(e){return this.withTx("readwrite",(async t=>{for(const r of e)if("put"===r.type||"add"===r.type){const e=Array.isArray(r.data)?r.data:[r.data];for(const s of e)if("put"===r.type){const e=s[this.keyPath];if(void 0!==e){J(await this.requestToPromise(t.get(e)),s)}await this.requestToPromise(t.put(s))}else await this.requestToPromise(t.add(s))}else if("delete"===r.type){const e=Array.isArray(r.data)?r.data:[r.data];for(const r of e)await this.requestToPromise(t.delete(r))}}))}async getById(e){return this.withTx("readonly",(async t=>this.requestToPromise(t.get(e))))}async delete(e){return this.withTx("readwrite",(async t=>{const r=Array.isArray(e)?e:[e];for(const e of r)await this.requestToPromise(t.delete(e))}))}async clear(){return this.withTx("readwrite",(async e=>{await this.requestToPromise(e.clear())}))}async count(){return this.withTx("readonly",(async e=>this.requestToPromise(e.count())))}async getByIndex(e,t){return this.withTx("readonly",(async r=>{const s=r.index(e);return this.requestToPromise(s.get(t))}))}async getByKeyRange(e,t){return this.withTx("readonly",(async r=>{const s=r.index(e);return this.requestToPromise(s.getAll(ee(t)))}))}async getAll(){return this.withTx("readonly",(async e=>this.requestToPromise(e.getAll())))}async cursor(e,t="forward",r){return this.withTx("readonly",(async s=>{const i="forward"===t?"next":"prev",a=s.openCursor(ee(r),i);return new Promise(((t,r)=>{let s=null;a.onsuccess=async i=>{const a=i.target.result;if(!a)return t(s);try{const{value:r,done:i,offset:n}=await e(a.value,a.key,a);s=r,i?t(s):n&&n>0?a.advance(n):a.continue()}catch(e){r(e)}},a.onerror=()=>r(this.mapError(a.error))}))}))}},re=e=>{const t=new Z(e),r=t.getConnection.bind(t);return new te(r,e.name,e.keyPath,(()=>t.ensureStore(e.name,e.keyPath)))};l(m()),l(m()),l(f()),l(L()),l(L());var se=class extends Error{constructor(e,t){super(e),this.operation=t,this.name="JsonPatchError"}};function ie(e){let t=function(e){return""===e||"/"===e?"":e.startsWith("/")?"/"+e.substring(1).split("/").map(ae).join("/"):"/"+e.split(".").map(ae).join("/")}(e);return""===t?[]:t.substring(1).split("/").map(ne)}function ae(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function ne(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}var oe=new Map;function ce(e,t){let r=e;for(let e of t){if(null===r||"object"!=typeof r)throw new se(`Invalid path - parent not found at ${e}`);if(Array.isArray(r)){let t="-"===e?r.length:parseInt(e);if(isNaN(t)||t<0||t>r.length)throw new se(`Invalid array index: ${e}`);r=r[t]}else{if(!r.hasOwnProperty(e))throw new se(`Property ${e} not found`);r=r[e]}}return r}function he(e,t){let r=oe.get(t)||ie(t);if(oe.set(t,r),0===r.length)return e;let s=ce(e,r.slice(0,-1)),i=r[r.length-1];if(Array.isArray(s)){let e=parseInt(i);if(isNaN(e)||e<0||e>=s.length)throw new se(`Invalid array index: ${i}`);return s[e]}return s[i]}function ue(e,t,r){let s=oe.get(t)||ie(t);oe.set(t,s);let i=ce(e,s.slice(0,-1)),a=s[s.length-1];return Array.isArray(i)?i.splice(0,i.length,...i.filter((e=>e!==r))):i[a]===r&&delete i[a],e}function de(e,t,r){let s=oe.get(t)||ie(t);if(oe.set(t,s),0===s.length)return r;let i=s.slice(0,-1),a=s[s.length-1],n=ce(e,i);if(Array.isArray(n))if("-"===a)n.push(r);else{let e=parseInt(a);if(e<0||e>n.length)throw new se(`Invalid array index: ${a}`);n.splice(e,0,r)}else n[a]=r;return e}function le(e,t){let r=oe.get(t)||ie(t);if(oe.set(t,r),0===r.length)return;let s=ce(e,r.slice(0,-1)),i=r[r.length-1];if(Array.isArray(s)){let e=parseInt(i);s.splice(e,1)}else delete s[i];return e}function pe(e,t){let r=[];switch(e.type){case"addField":r.push({op:"add",path:`/fields/${e.id}`,value:e.definition});break;case"removeField":r.push({op:"remove",path:`/fields/${e.id}`});break;case"modifyField":{let t=`/fields/${e.id}`;Object.entries(e.changes).forEach((([e,s])=>{"object"!=typeof s||null===s||Array.isArray(s),r.push({op:"replace",path:`${t}/${e}`,value:s})}));break}case"deprecateField":r.push({op:"add",path:`/fields/${e.id}/deprecated`,value:!0});break;case"addIndex":t.indexes||r.push({op:"add",path:"/indexes",value:[]}),r.push({op:"add",path:"/indexes/-",value:e.definition});break;case"removeIndex":{let s=t.indexes?.findIndex((t=>t.name===e.name));void 0!==s&&s>=0&&r.push({op:"remove",path:`/indexes/${s}`});break}case"modifyIndex":{let s=t.indexes?.findIndex((t=>t.name===e.name));void 0!==s&&s>=0&&Object.entries(e.changes).forEach((([e,t])=>{r.push({op:"replace",path:`/indexes/${s}/${e}`,value:t})}));break}case"addConstraint":t.constraints||r.push({op:"add",path:"/constraints",value:[]}),Array.isArray(e.constraint)?e.constraint.forEach((e=>{r.push({op:"add",path:"/constraints/-",value:e})})):r.push({op:"add",path:"/constraints/-",value:e.constraint});break;case"removeConstraint":{let s=t.constraints?.findIndex((t=>Array.isArray(t)?t.some((t=>t.name===e.name)):t.name===e.name));void 0!==s&&s>=0&&r.push({op:"remove",path:`/constraints/${s}`});break}case"modifyConstraint":{let s=function(e,t){if(!e.constraints)return null;for(let r=0;r<e.constraints.length;r++){let s=e.constraints[r];if(s.name===t)return`/constraints/${r}`;if(me(s)){let e=fe(s.rules,t);if(e)return`/constraints/${r}${e}`}}return null}(t,e.name);s&&Object.entries(e.changes).forEach((([e,t])=>{r.push({op:"replace",path:`${s}/${e}`,value:t})}));break}}return r}function me(e){return e&&"operator"in e&&"rules"in e}function fe(e,t){for(let r=0;r<e.length;r++){let s=e[r];if("name"in s&&s.name===t)return`/rules/${r}`;if(me(s)){let e=fe(s.rules,t);if(e)return`/rules/${r}${e}`}}return null}var ye=new Map;function we(e){return e instanceof RegExp?e.toString().slice(1,-1):JSON.stringify(e)}function ge(e,t){let r=e=>({issues:e}),s=(e,t,r,s)=>{switch(t){case"string":return"string"!=typeof e?[{message:"Expected string, got "+typeof e,path:r}]:[];case"number":return"number"!=typeof e||isNaN(e)?[{message:"Expected number, got "+typeof e,path:r}]:[];case"boolean":return"boolean"!=typeof e?[{message:"Expected boolean, got "+typeof e,path:r}]:[];case"array":return Array.isArray(e)?[]:[{message:"Expected array, got "+typeof e,path:r}];case"set":return Array.isArray(e)&&new Set(e).size===e.length?[]:[{message:"Expected unique array, got "+typeof e,path:r}];case"enum":return s?.values?s.values.includes(e)?[]:[{message:`Expected one of ${JSON.stringify(s.values)}, got ${e}`,path:r}]:[{message:"Enum type requires 'values' definition",path:r}];case"object":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected object, got "+typeof e,path:r}]:[];case"record":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected record (object), got "+typeof e,path:r}]:[];case"union":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected union (object), got "+typeof e,path:r}]:[];case"dynamic":return console.warn("Deprecated: 'dynamic' type used. Use 'record' instead."),"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected record (object), got "+typeof e,path:r}]:[];default:return[{message:`Unknown type '${t}'`,path:r}]}};function i(e,t,r,s,a){let n=[],o=e.rules.map(((e,o)=>{let c=[...s,`rules[${o}]`],h=`${e.name}@${c.join(".")}`;if("rules"in e){if(a.has(h))return!0;a.add(h);let s=i(e,t,r,c,a);return n.push(...s),a.delete(h),0===s.length}{let s=r[e.predicate];if(!s)return n.push({message:`Predicate '${e.predicate}' not found`,path:c}),!1;let i=`${e.predicate}:${JSON.stringify(e.parameters)}:${JSON.stringify(t[e.field])}`;if(ye.has(i)){let t=ye.get(i);return t||n.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${we(e.parameters)}`,path:c}),t}let a=s({data:t,field:e.field,arguments:e.parameters});return ye.set(i,a),a||n.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${we(e.parameters)}`,path:c}),a}}));return(()=>{switch(e.operator){case"and":return o.every((e=>e));case"or":return o.some((e=>e));case"not":return!o.every((e=>e));case"nor":return!o.some((e=>e));case"xor":return 1===o.filter((e=>e)).length}})()||n.push({message:`Constraint group '${e.name}' failed`,path:s}),n}function a(e,t,r,n,o,c=new Set){let h=[];if("type"in t&&!("fields"in t)){let a=n.length>0?e[n[n.length-1]]:e;return h.push(...s(a,t.type,n,{values:t.values})),t.constraints&&t.constraints.forEach(((e,t)=>{if("rules"in e)h.push(...i(e,{value:a},r,[...n,`constraints[${t}]`],c));else{let s=r[e.predicate];s?s({data:{value:a},field:"value",arguments:e.parameters})||h.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${we(e.parameters)}`,path:[...n,`constraints[${t}]`]}):h.push({message:`Predicate '${e.predicate}' not found`,path:[...n,`constraints[${t}]`]})}})),h}let u={};if("concrete"in t)if(!0!==t.concrete&&Array.isArray(t.fields)){let r=t.fields,s=r.find((e=>!e.when));s&&Object.assign(u,s.fields);let i=r.find((t=>t.when&&void 0!==e[t.when.field]&&e[t.when.field]===t.when.value));if(i)Object.assign(u,i.fields);else if(!s)return h.push({message:"No matching field set found for discriminated schema",path:n}),h}else u=t.fields;else u=t.fields;let d=new Set(Object.values(u).map((e=>e.name)));Object.entries(u).forEach((([t,u])=>{let d=[...n,u.name],l=Object.hasOwnProperty.call(e,u.name)?e[u.name]:void 0!==u.default?u.default:void 0;u.required&&null==l&&h.push({message:`Field '${u.name}' is required`,path:d});let p=u.schema||u.nestedSchema;if("object"===u.type&&p&&!Array.isArray(p)){let e=o[p.id];if(e)if(c.has(p.id))h.push({message:`Circular reference detected at '${p.id}'`,path:d});else{c.add(p.id);let t=l&&"object"==typeof l&&!Array.isArray(l)?l:{};h.push(...a(t,e,r,d,o,c)),p.constraints?.forEach(((e,s)=>{if("rules"in e)h.push(...i(e,t,r,[...d,`constraints[${s}]`],c));else{let i=r[e.predicate];i?i({data:t,field:void 0,arguments:e.parameters})||h.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${we(e.parameters)}`,path:[...d,`constraints[${s}]`]}):h.push({message:`Predicate '${e.predicate}' not found`,path:[...d,`constraints[${s}]`]})}})),c.delete(p.id)}else h.push({message:`Nested schema '${p.id}' not found`,path:d})}if("union"===u.type&&p&&Array.isArray(p)){let e=!1,t=[];p.forEach(((s,n)=>{let h=o[s.id];if(h)if(c.has(s.id))t.push({message:`Circular reference detected at '${s.id}'`,path:[...d,n.toString()]});else{c.add(s.id);let n=l&&"object"==typeof l&&!Array.isArray(l)?l:{},u=a(n,h,r,d,o,new Set(c));0===u.length&&void 0!==l?(e=!0,s.constraints?.forEach(((s,a)=>{if("rules"in s){let o=i(s,n,r,[...d,`constraints[${a}]`],c);o.length>0&&(e=!1,t.push(...o))}else{let i=r[s.predicate];i&&!i({data:n,field:void 0,arguments:s.parameters})&&(e=!1,t.push({message:s.errorMessage||`Constraint '${s.name}' failed`,path:[...d,`constraints[${a}]`]}))}}))):void 0===l&&t.push(...u.filter((e=>e.message.includes("is required")))),c.delete(s.id)}else t.push({message:`Nested schema '${s.id}' not found`,path:[...d,n.toString()]})})),e||void 0===l?void 0===l&&h.push(...t):(h.push({message:"Value does not match any union schema",path:d}),h.push(...t))}void 0!==l&&(h.push(...s(l,u.type,d,{values:u.values})),("array"===u.type||"set"===u.type)&&Array.isArray(l)&&(u.constraints?.forEach(((e,t)=>{let s=r[e.predicate];s&&!s({data:{[u.name]:l},field:u.name,arguments:e.parameters})&&h.push({message:e.errorMessage||`Constraint '${e.name}' failed for field '${u.name}'`,path:[...d,`constraints[${t}]`]})})),u.itemsType&&l.forEach(((e,t)=>h.push(...s(e,u.itemsType,[...d,t.toString()])))),p&&!Array.isArray(p)&&(o[p.id]?l.forEach(((e,t)=>{"object"==typeof e&&null!==e&&(c.has(p.id)?h.push({message:`Circular reference detected at '${p.id}'`,path:[...d,t.toString()]}):(c.add(p.id),h.push(...a(e,o[p.id],r,[...d,t.toString()],o,c)),c.delete(p.id)))})):h.push({message:`Nested schema '${p.id}' not found`,path:d}))),u.constraints?.forEach(((t,s)=>{if("rules"in t)h.push(...i(t,e,r,[...d,`constraints[${s}]`],c));else{let i=r[t.predicate];i?i({data:e,field:u.name,arguments:t.parameters})||h.push({message:t.errorMessage||`Constraint '${t.name}' failed for field '${u.name}' with params ${we(t.parameters)}`,path:[...d,`constraints[${s}]`]}):h.push({message:`Predicate '${t.predicate}' not found`,path:[...d,`constraints[${s}]`]})}})))}));for(let t in e)Object.hasOwnProperty.call(e,t)&&!d.has(t)&&h.push({message:`Unexpected field '${t}'`,path:[...n,t]});return t.constraints?.forEach(((t,s)=>{if("rules"in t)h.push(...i(t,e,r,[...n,`constraints[${s}]`],c));else{let i=r[t.predicate];i?i({data:e,field:t.field,arguments:t.parameters})||h.push({message:t.errorMessage||`Constraint '${t.name}' failed with params ${we(t.parameters)}`,path:[...n,`constraints[${s}]`]}):h.push({message:`Predicate '${t.predicate}' not found`,path:[...n,`constraints[${s}]`]})}})),h}return"1.0.0"!==e.version&&console.warn(`Schema version '${e.version}' may require migrations. Validator assumes version 1.0.0.`),{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:s=>{if("object"!=typeof s||null===s)return r([{message:"Input must be an object",path:[]}]);let i=s,n=a(i,e,t,[],e.nestedSchemas||{});return n.length>0?r(n):(e=>({value:e}))(i)},types:{input:{},output:{}}}}}var be=class extends Error{constructor(e,t){super(e),this.errors=t,this.name="SchemaValidationError"}},ve=e=>({value:e}),$e=e=>({issues:e}),_e=(e,t,r=!0)=>(void 0!==e||r)&&("string"!=typeof e||""===e.trim())?[{message:"Must be a non-empty string",path:[t]}]:[],ke=(e,t)=>{let r=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return"string"==typeof e&&r.includes(e)?"dynamic"===e?[{message:"Field type 'dynamic' is deprecated; use 'record' instead",path:[t]}]:[]:[{message:`Must be one of ${r.join(", ")}`,path:[t]}]},Ee=(e,t)=>{let r=["and","or","not","nor","xor"];return"string"==typeof e&&r.includes(e)?[]:[{message:`Must be one of ${r.join(", ")}`,path:[t]}]},Se=(e,t,r=!1)=>(void 0!==e||r)&&"boolean"!=typeof e?[{message:"Must be a boolean",path:[t]}]:[],Oe=(e,t,r)=>{let s=[],i=["type","predicate","field","parameters","name","description","errorMessage"],a=e;return["predicate","name"].forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${r}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${r}.${e}`]})})),s.push(..._e(e.name,`${r}.name`)),s.push(..._e(e.predicate,`${r}.predicate`)),void 0!==e.field&&"string"!=typeof e.field&&s.push({message:"Field must be a string",path:[`${r}.field`]}),void 0!==e.parameters&&s.push(...(e.parameters,[])),s.push(..._e(e.description,`${r}.description`,!1)),s.push(..._e(e.errorMessage,`${r}.errorMessage`,!1)),s},Ae=(e,t,r)=>{let s=[],i=["name","operator","rules"],a=i,n=e;return i.forEach((e=>{void 0===n[e]&&s.push({message:`${e} is required`,path:[`${r}.${e}`]})})),Object.keys(n).forEach((e=>{a.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${r}.${e}`]})})),s.push(..._e(e.name,`${r}.name`)),s.push(...Ee(e.operator,`${r}.operator`)),Array.isArray(e.rules)&&0!==e.rules.length?e.rules.forEach(((e,i)=>{"rules"in e?s.push(...Ae(e,t,`${r}.rules[${i}]`)):s.push(...Oe(e,0,`${r}.rules[${i}]`))})):s.push({message:"Rules must be a non-empty array",path:[`${r}.rules`]}),s},Ie=(e,t,r)=>{if(!Array.isArray(e))return[{message:"Must be an array",path:[r]}];let s=[];return e.forEach(((e,i)=>{"rules"in e?s.push(...Ae(e,t,`${r}[${i}]`)):s.push(...Oe(e,0,`${r}[${i}]`))})),s},je=(e,t)=>{let r=[],s=["operator","field","value","conditions"],i=e;return["operator","field"].forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...Ee(e.operator,`${t}.operator`)),r.push(..._e(e.field,`${t}.field`)),void 0!==e.conditions&&(Array.isArray(e.conditions)?e.conditions.forEach(((e,s)=>r.push(...je(e,`${t}.conditions[${s}]`)))):r.push({message:"Conditions must be an array",path:[`${t}.conditions`]})),r},xe=(e,t)=>{let r=[],s=["fields","type","unique","partial","description","order","name"],i=e;return["fields","type","name"].forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.name,`${t}.name`)),r.push(...((e,t)=>{let r=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return"string"==typeof e&&r.includes(e)?[]:[{message:`Must be one of ${r.join(", ")}`,path:[t]}]})(e.type,`${t}.type`)),(!Array.isArray(e.fields)||0===e.fields.length||!e.fields.every((e=>"string"==typeof e)))&&r.push({message:"Fields must be a non-empty array of strings",path:[`${t}.fields`]}),r.push(...Se(e.unique,`${t}.unique`,!1)),e.partial&&r.push(...je(e.partial,`${t}.partial`)),r.push(..._e(e.description,`${t}.description`,!1)),void 0!==e.order&&!["asc","desc"].includes(e.order)&&r.push({message:"Order must be 'asc' or 'desc'",path:[`${t}.order`]}),r},Ne=(e,t)=>{if(void 0===e)return[];if(!Array.isArray(e))return[{message:"Must be an array",path:[t]}];let r=[];return e.forEach(((e,s)=>r.push(...xe(e,`${t}[${s}]`)))),r},Te=(e,t,r,s,i)=>{let a=[];return void 0===e?[]:("union"===r&&Array.isArray(e)?(0===e.length&&a.push({message:"Schema array must not be empty for union type",path:[t]}),e.forEach(((e,r)=>{let i=`${t}[${r}]`;a.push(..._e(e.id,`${i}.id`)),s.includes(e.id)||a.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${i}.id`]}),e.constraints&&a.push(...Ie(e.constraints,"dynamic",`${i}.constraints`)),e.indexes&&a.push(...Ne(e.indexes,`${i}.indexes`))}))):"object"!==r&&("array"!==r||"object"!==i)||Array.isArray(e)?a.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[t]}):(a.push(..._e(e.id,`${t}.id`)),s.includes(e.id)||a.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${t}.id`]}),e.constraints&&a.push(...Ie(e.constraints,"dynamic",`${t}.constraints`)),e.indexes&&a.push(...Ne(e.indexes,`${t}.indexes`))),a)},Ce=(e,t,r)=>{if(void 0===e)return[];switch(t){case"string":if("string"!=typeof e)return[{message:"Default must be a string",path:[r]}];break;case"number":if("number"!=typeof e)return[{message:"Default must be a number",path:[r]}];break;case"boolean":if("boolean"!=typeof e)return[{message:"Default must be a boolean",path:[r]}];break;case"array":case"set":if(!Array.isArray(e))return[{message:"Default must be an array",path:[r]}];break;case"enum":if(!Array.isArray(e)||!e.every((e=>"string"==typeof e||"number"==typeof e)))return[{message:"Default must be an array of strings or numbers",path:[r]}];break;case"object":case"record":if("object"!=typeof e||null===e)return[{message:"Default must be an object",path:[r]}];break;case"union":case"dynamic":return[]}return[]},Me=(e,t)=>void 0===e?[]:"object"!=typeof e||null===e?[{message:"Hint must be an object",path:[t]}]:"input"in e&&"object"!=typeof e.input?[{message:"Hint.input must be an object",path:[`${t}.input`]}]:[],Re=(e,t,r)=>{let s=[],i=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique","hint"],a=e;if(["name","type"].forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(..._e(e.name,`${t}.name`)),s.push(...ke(e.type,`${t}.type`)),s.push(...Se(e.required,`${t}.required`,!1)),e.constraints&&s.push(...Ie(e.constraints,e.type,`${t}.constraints`)),s.push(...Ce(e.default,e.type,`${t}.default`)),void 0!==e.values&&("enum"===e.type?(!Array.isArray(e.values)||0===e.values.length||!e.values.every((e=>"string"==typeof e||"number"==typeof e)))&&s.push({message:"Values must be a non-empty array of strings or numbers",path:[`${t}.values`]}):s.push({message:"Values is only valid for 'enum' type",path:[`${t}.values`]})),void 0!==e.schema&&s.push(...Te(e.schema,`${t}.schema`,e.type,r,e.itemsType)),e.itemsType&&s.push(...ke(e.itemsType,`${t}.itemsType`)),e.nestedSchema){s.push({message:"nestedSchema is deprecated; use schema instead",path:[`${t}.nestedSchema`]});let i=["id"],a=["id","constraints","indexes"],n=e.nestedSchema;i.forEach((e=>{void 0===n[e]&&s.push({message:`${e} is required`,path:[`${t}.nestedSchema.${e}`]})})),Object.keys(n).forEach((e=>{a.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchema.${e}`]})})),s.push(..._e(e.nestedSchema.id,`${t}.nestedSchema.id`)),r.includes(e.nestedSchema.id)||s.push({message:`nestedSchema.id '${e.nestedSchema.id}' must match a nestedSchemas key`,path:[`${t}.nestedSchema.id`]}),e.nestedSchema.constraints&&s.push(...Ie(e.nestedSchema.constraints,"dynamic",`${t}.nestedSchema.constraints`)),e.nestedSchema.indexes&&s.push(...Ne(e.nestedSchema.indexes,`${t}.nestedSchema.indexes`))}if(s.push(...Se(e.deprecated,`${t}.deprecated`,!1)),e.reference){s.push({message:"reference is deprecated",path:[`${t}.reference`]});let r=["schema","field"],i=["schema","field"],a=e.reference;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.reference.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.reference.${e}`]})})),s.push(..._e(e.reference.schema,`${t}.reference.schema`)),s.push(..._e(e.reference.field,`${t}.reference.field`))}return s.push(..._e(e.description,`${t}.description`,!1)),s.push(...Se(e.unique,`${t}.unique`,!1)),e.hint&&s.push(...Me(e.hint,`${t}.hint`)),s},Pe=(e,t,r)=>{let s=[];if("type"in e&&["string","number","boolean","array","set","enum","record"].includes(e.type)){let i=["name","type","default","schema","itemsType","constraints","description","metadata"],a=e;["name","type"].forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(..._e(e.name,`${t}.name`)),s.push(...ke(e.type,`${t}.type`)),s.push(...Ce(e.default,e.type,`${t}.default`)),e.schema&&s.push(...Te(e.schema,`${t}.schema`,e.type,r,e.itemsType)),e.itemsType&&s.push(...ke(e.itemsType,`${t}.itemsType`)),e.constraints&&s.push(...Ie(e.constraints,e.type,`${t}.constraints`)),s.push(..._e(e.description,`${t}.description`,!1)),void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata)&&s.push({message:"Metadata must be an object",path:[`${t}.metadata`]})}else{let i=["name","description","concrete","fields","indexes","constraints","metadata"],a=e;["name"].forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(..._e(e.name,`${t}.name`)),s.push(...Se(a.concrete,`${t}.concrete`,!1)),a.concrete&&Array.isArray(a.fields)&&s.push({message:"Fields must be an object when concrete is true",path:[`${t}.fields`]}),Array.isArray(a.fields)?(0===a.fields.length&&s.push({message:"Fields array must not be empty",path:[`${t}.fields`]}),a.fields.forEach(((e,i)=>{let a=`${t}.fields[${i}]`;if("object"==typeof e&&null!==e&&"fields"in e){let t=e.fields;"object"!=typeof t||null===t?s.push({message:"Fields must be a non-empty object",path:[`${a}.fields`]}):Object.entries(t).forEach((([e,t])=>{s.push(...Re(t,`${a}.fields.${e}`,r))})),void 0!==e.when&&("object"!=typeof e.when||null===e.when?s.push({message:"When must be an object",path:[`${a}.when`]}):s.push(..._e(e.when.field,`${a}.when.field`)))}else s.push({message:"Each variant must have a 'fields' property",path:[a]})}))):void 0!==a.fields&&("object"!=typeof a.fields||null===a.fields?s.push({message:"Fields must be a non-empty object",path:[`${t}.fields`]}):Object.entries(a.fields).forEach((([e,i])=>{s.push(...Re(i,`${t}.fields.${e}`,r))}))),s.push(..._e(e.description,`${t}.description`,!1)),e.indexes&&s.push(...Ne(e.indexes,`${t}.indexes`)),e.constraints&&s.push(...Ie(a.constraints,"dynamic",`${t}.constraints`)),void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata)&&s.push({message:"Metadata must be an object",path:[`${t}.metadata`]})}return s},De=(e,t)=>{let r=[];switch(e.type||r.push({message:"type is required",path:[`${t}.type`]}),e.type){case"modifyProperty":{let s=["type","id","changes"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.id,`${t}.id`)),(void 0===e.changes||"object"!=typeof e.changes)&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}case"addField":{let s=["type","id","definition"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.id,`${t}.id`)),r.push(...Re(e.definition,`${t}.definition`,[]));break}case"removeField":case"deprecateField":{let s=["type","id"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.id,`${t}.id`));break}case"modifyField":{let s=["type","id","changes","nestedSchemaChanges"],i=e;if(["type","id","changes"].forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.id,`${t}.id`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]}),e.nestedSchemaChanges){let s=["id","constraints","indexes"],i=e.nestedSchemaChanges;Object.keys(i).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchemaChanges.${e}`]})})),r.push(..._e(i.id,`${t}.nestedSchemaChanges.id`,!1)),i.constraints&&r.push(...Ie(i.constraints,"dynamic",`${t}.nestedSchemaChanges.constraints`)),i.indexes&&r.push(...Ne(i.indexes,`${t}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let s=["type","definition"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...xe(e.definition,`${t}.definition`));break}case"removeIndex":{let s=["type","name"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.name,`${t}.name`));break}case"modifyIndex":{let s=["type","name","changes"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.name,`${t}.name`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}case"addConstraint":{let s=["type","constraint"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),"rules"in e.constraint?r.push(...Ae(e.constraint,"dynamic",`${t}.constraint`)):r.push(...Oe(e.constraint,0,`${t}.constraint`));break}case"removeConstraint":{let s=["type","name"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.name,`${t}.name`));break}case"modifyConstraint":{let s=["type","name","changes"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.name,`${t}.name`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}case"addNestedSchema":{let s=["type","id","definition"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.id,`${t}.id`)),r.push(...Pe(e.definition,`${t}.definition`,[]));break}case"removeNestedSchema":{let s=["type","id"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.id,`${t}.id`));break}case"modifyNestedSchema":{let s=["type","id","changes"],i=s,a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.id,`${t}.id`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}default:r.push({message:"Unknown schema change type",path:[`${t}.type`]})}return r},qe=(e,t)=>{let r=[],s=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],i=[...s,"rollback","dependencies"],a=e;s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.id,`${t}.id`)),r.push(..._e(e.schemaVersion,`${t}.schemaVersion`)),r.push(..._e(e.description,`${t}.description`));let n=["pending","applied","failed"];return n.includes(e.status)||r.push({message:`Status must be one of ${n.join(", ")}`,path:[`${t}.status`]}),Array.isArray(e.changes)&&0!==e.changes.length?e.changes.forEach(((e,s)=>{r.push(...De(e,`${t}.changes[${s}]`))})):r.push({message:"Changes must be a non-empty array",path:[`${t}.changes`]}),void 0!==e.rollback&&(Array.isArray(e.rollback)?e.rollback.forEach(((e,s)=>r.push(...De(e,`${t}.rollback[${s}]`)))):r.push({message:"Rollback must be an array",path:[`${t}.rollback`]})),"string"==typeof e.transform?r.push(..._e(e.transform,`${t}.transform`)):"object"==typeof e.transform&&null!==e.transform?r.push(...((e,t)=>{let r=[],s=["forward","backward"],i=s,a=e;return s.forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),"function"!=typeof e.forward&&r.push({message:"Forward must be a function",path:[`${t}.forward`]}),"function"!=typeof e.backward&&r.push({message:"Backward must be a function",path:[`${t}.backward`]}),r})(e.transform,`${t}.transform`)):r.push({message:"Transform must be a string or object",path:[`${t}.transform`]}),r.push(..._e(e.createdAt,`${t}.createdAt`)),r.push(..._e(e.checksum,`${t}.checksum`)),void 0!==e.dependencies&&(r.push({message:"dependencies is deprecated; use DomainModel instead",path:[`${t}.dependencies`]}),(!Array.isArray(e.dependencies)||!e.dependencies.every((e=>"string"==typeof e)))&&r.push({message:"Dependencies must be an array of strings",path:[`${t}.dependencies`]})),r},Fe={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return $e([{message:"Schema must be an object",path:[]}]);let t=e,r=[],s=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock","hint"],i=t;if(["name","version","fields"].forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[e]})})),Object.keys(i).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[e]})})),r.push(..._e(t.name,"name")),r.push(..._e(t.version,"version")),"object"!=typeof t.fields||null===t.fields)r.push({message:"Fields must be a non-empty object",path:["fields"]});else{let e=Object.keys(t.nestedSchemas||{});Object.entries(t.fields).forEach((([t,s])=>{r.push(...Re(s,`fields.${t}`,e))}))}if(void 0!==t.nestedSchemas)if("object"!=typeof t.nestedSchemas||null===t.nestedSchemas)r.push({message:"NestedSchemas must be an object",path:["nestedSchemas"]});else{let e=Object.keys(t.nestedSchemas);Object.entries(t.nestedSchemas).forEach((([t,s])=>r.push(...Pe(s,`nestedSchemas.${t}`,e))))}return r.push(..._e(t.description,"description",!1)),t.indexes&&r.push(...Ne(t.indexes,"indexes")),t.constraints&&r.push(...Ie(t.constraints,"dynamic","constraints")),void 0!==t.metadata&&("object"!=typeof t.metadata||null===t.metadata)&&r.push({message:"Metadata must be an object",path:["metadata"]}),void 0!==t.dependencies&&(r.push({message:"dependencies is deprecated; use DomainModel instead",path:["dependencies"]}),(!Array.isArray(t.dependencies)||!t.dependencies.every((e=>"string"==typeof e)))&&r.push({message:"Dependencies must be an array of strings",path:["dependencies"]})),void 0!==t.migrations&&(Array.isArray(t.migrations)?t.migrations.forEach(((e,t)=>r.push(...qe(e,`migrations[${t}]`)))):r.push({message:"Migrations must be an array",path:["migrations"]})),void 0!==t.mock&&"function"!=typeof t.mock&&r.push({message:"Mock must be a function",path:["mock"]}),t.hint&&r.push(...Me(t.hint,"hint")),r.length>0?$e(r):ve(t)},types:{input:{},output:{}}},Ue={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return $e([{message:"Migration must be an object",path:[]}]);let t=e,r=qe(t,"");return r.length>0?$e(r):ve(t)},types:{input:{},output:{}}},Le={version:1,vendor:"@asaidimu/anansi",validate:e=>{if(!Array.isArray(e))return $e([{message:"SchemaChanges must be an array",path:[]}]);let t=e,r=[];return t.forEach(((e,t)=>r.push(...De(e,`[${t}]`)))),r.length>0?$e(r):ve(t)},types:{input:[],output:[]}};function Be(e){try{return!Fe.validate(e).issues}catch(e){throw new be("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}function Ve(e,t){switch(e.type){case"removeField":case"removeIndex":case"addConstraint":case"modifyConstraint":return"major";case"modifyField":return function(e){return!0===e.required||void 0!==e.type||void 0!==e.itemsType||void 0!==e.nestedSchema||void 0!==e.reference||!0===e.unique}(e.changes)?"major":e.changes.deprecated?"minor":"patch";case"modifyIndex":return void 0!==e.changes.unique||void 0!==e.changes.fields?"major":"minor";case"removeConstraint":case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(e)}`)}}function ze(e,t,r){if(0===t.length)throw new Error("No changes provided");(function(e){let t=new Set,r=new Set,s=new Set,i=new Set;for(let a of e)switch(a.type){case"addField":if(r.has(a.id))throw new Error(`Cannot add previously removed field: ${a.id}`);if(t.has(a.id))throw new Error(`Cannot add already modified field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot add deprecated field: ${a.id}`);s.add(a.id);break;case"removeField":if(s.has(a.id))throw new Error(`Cannot remove newly added field: ${a.id}`);if(t.has(a.id))throw new Error(`Cannot remove modified field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot remove field that is being deprecated: ${a.id}`);r.add(a.id);break;case"modifyField":if(r.has(a.id))throw new Error(`Cannot modify removed field: ${a.id}`);if(s.has(a.id))throw new Error(`Cannot modify newly added field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot modify field that is being deprecated: ${a.id}`);t.add(a.id);break;case"deprecateField":if(r.has(a.id))throw new Error(`Cannot deprecate removed field: ${a.id}`);if(s.has(a.id))throw new Error(`Cannot deprecate newly added field: ${a.id}`);if(t.has(a.id))throw new Error(`Cannot deprecate modified field: ${a.id}`);i.add(a.id)}})(t),function(e){let t=new Set,r=new Set,s=new Set;for(let i of e)switch(i.type){case"addConstraint":let e=i.constraint.name;if(r.has(e))throw new Error(`Cannot add previously removed constraint: ${e}`);if(t.has(e))throw new Error(`Cannot add already modified constraint: ${e}`);s.add(e);break;case"removeConstraint":if(s.has(i.name))throw new Error(`Cannot remove newly added constraint: ${i.name}`);if(t.has(i.name))throw new Error(`Cannot remove modified constraint: ${i.name}`);r.add(i.name);break;case"modifyConstraint":if(r.has(i.name))throw new Error(`Cannot modify removed constraint: ${i.name}`);if(s.has(i.name))throw new Error(`Cannot modify newly added constraint: ${i.name}`);t.add(i.name)}}(t);let s=function(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!t)throw new Error(`Invalid version format: ${e}. Expected format: major.minor.patch`);return{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10)}}(e),i="patch";for(let e of t){let t=Ve(e);if("major"===t){i="major";break}"minor"===t&&"patch"===i&&(i="minor")}switch(i){case"major":return`${s.major+1}.0.0`;case"minor":return`${s.major}.${s.minor+1}.0`;case"patch":return`${s.major}.${s.minor}.${s.patch+1}`}}function He(e,t){let r=e=>e.split(".").map((e=>parseInt(e,10)||0)),[s,i,a]=r(e),[n,o,c]=r(t);return s-n||i-o||a-c}var Je,Ke=class extends Error{constructor(e,t,r,s){super(e),this.code=t,this.migrationId=r,this.cause=s,this.name="MigrationError"}},We=((Je=We||{}).INVALID_SCHEMA="INVALID_SCHEMA",Je.INVALID_MIGRATION="INVALID_MIGRATION",Je.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",Je.TIMEOUT="TIMEOUT",Je.MEMORY_LIMIT="MEMORY_LIMIT",Je.CONCURRENT_OPERATION="CONCURRENT_OPERATION",Je.TRANSFORM_ERROR="TRANSFORM_ERROR",Je.VERSION_NOT_FOUND="VERSION_NOT_FOUND",Je.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",Je.STREAM_ERROR="STREAM_ERROR",Je.ROLLBACK_ERROR="ROLLBACK_ERROR",Je.MISSING_TRANSFORM="MISSING_TRANSFORM",Je),Ye=class e{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,r){try{if(!Be(e))throw new Ke("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every((e=>function(e){try{return!Ue.validate(e).issues}catch(e){throw new be("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}(e))))throw new Ke("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort(((e,t)=>He(e.schemaVersion,t.schemaVersion)))}r&&(this.history=r.sort(((e,t)=>He(e.version,t.version))))}catch(e){throw e instanceof Ke?e:new Ke("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,e)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let t=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await(async e=>{if(typeof window<"u"&&crypto.subtle){let t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map((e=>e.toString(16).padStart(2,"0"))).join("")}{let{createHash:t}=await import("crypto");return t("sha256").update(e).digest("hex")}})(t)}catch(t){throw new Ke("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new Ke("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new Ke("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach((e=>function(e){try{return!Le.validate(e).issues}catch(e){throw new be("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}(e)))}catch(e){throw new Ke("Invalid schema changes","INVALID_MIGRATION",void 0,e)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:(new Date).toISOString(),checksum:""};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(t,r,s){if(this.isProcessing)throw new Ke("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let i={...this.currentSchema},a=this.getRelevantMigrations(r,s);return{newSchema:a.reduce(((e,t)=>{let s="forward"===r?t.changes:t.rollback||[];return this.applySchemaChanges(e,s,t.id)}),i),dataPreview:await e.processMigrationList(t,r,a)}}catch(e){throw e instanceof Ke?e:new Ke("Dry run failed","INVALID_SCHEMA",void 0,e)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter((r=>{let s="forward"===e?"pending":"applied",i=!t||He(r.schemaVersion,t)>=0;return r.status===s&&i})).sort(((t,r)=>"forward"===e?t.id.localeCompare(r.id):r.id.localeCompare(t.id)))}applySchemaChanges(e,t,r){try{let s=ze(e.version,t);return t.map((t=>{try{return pe(t,e)}catch(e){throw new Ke("Invalid schema change","INVALID_SCHEMA",r,e)}})).reduce(((e,t)=>{try{return function(e,t){let r=JSON.parse(JSON.stringify(e));for(let e of t)try{switch(e.op){case"add":r=de(r,e.path,e.value);break;case"remove":r=le(r,e.path);break;case"removeValue":r=ue(r,e.path,e.value);break;case"replace":r=de(le(r,e.path),e.path,e.value);break;case"copy":{let t=he(r,e.from);r=de(r,e.path,JSON.parse(JSON.stringify(t)));break}case"move":{let t=he(r,e.from);r=de(r,e.path,t),r=le(r,e.from);break}case"test":{let t=he(r,e.path);if(JSON.stringify(t)!==JSON.stringify(e.value))throw new se("Test operation failed");break}default:throw new se(`Unsupported operation: ${e.op}`)}}catch(t){throw t instanceof se&&(t.operation=e),t}return r}(e,t)}catch(e){throw new Ke("Failed to apply patch","INVALID_SCHEMA",r,e)}}),{...e,version:s})}catch(e){throw e instanceof Ke?e:new Ke("Schema update failed","INVALID_SCHEMA",r,e)}}async prepareMigration(){let e=this.migrations.filter((e=>"pending"===e.status));return await this.validateMigrations(e),e}async migrate(t){if(this.isProcessing)throw new Ke("Concurrent operation","CONCURRENT_OPERATION");let r=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let s=await e.processMigrationList(t,"forward",r);return this.markMigrationsApplied(r),s}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map((async e=>{let t=await this.generateChecksum(e);if(e.checksum!==t)throw new Ke("Checksum mismatch","CHECKSUM_MISMATCH",e.id)})))}markMigrationsApplied(e){this.migrations=this.migrations.map((t=>e.some((e=>e.id===t.id))?{...t,status:"applied"}:t))}async rollback(e){if(this.isProcessing)throw new Ke("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter((e=>"applied"===e.status)).slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(t,r){if(this.isProcessing)throw new Ke("Concurrent operation","CONCURRENT_OPERATION");try{let s=this.history.findIndex((e=>e.version===t));if(-1===s)throw new Error(`Version ${t} not found in history`);let i=this.migrations.filter((e=>e.schemaVersion===t&&"applied"===e.status)).sort(((e,t)=>t.id.localeCompare(e.id))),a=this.history.length-s;if(a<0)return r;for(let e=0;e<a;e++)this.transformSchema("backward");let n=await e.processMigrationList(r,"backward",i);return this.migrations=this.migrations.map((e=>e.schemaVersion===t&&"applied"===e.status?{...e,status:"pending"}:e)),n}finally{this.isProcessing=!1}}static async processMigrationList(e,t,r){return(await Promise.all(r.map((async e=>{try{return{migration:e,transform:await this.resolveTransform(e,t)}}catch(t){throw new Ke(`Failed to resolve transform for migration ${e.id}`,"TRANSFORM_ERROR",e.id,t)}})))).filter((e=>!!e.transform)).reduce(((e,{migration:t,transform:r})=>e.pipeThrough(new TransformStream({async transform(e,s){try{let t=await r(e);s.enqueue(t)}catch(e){s.error(new Ke(`Data transformation failed for migration ${t.id}`,"TRANSFORM_ERROR",t.id,e))}}}))),e)}static async resolveTransform(e,t){return e.transform?"string"==typeof e.transform?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let r=await fetch(e);if(!r.ok)throw new Ke(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let s=await r.text();if(typeof window<"u"){let e=new Blob([s],{type:"application/javascript"});return(await import(URL.createObjectURL(e))).default[t]}{let{runInNewContext:r}=await import("vm"),i={module:{exports:{}},console:console};return r(s,i,e),i.module.exports[t]}}catch(t){throw new Ke(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,t)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}catch(t){throw new Ke(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,t)}}transformSchema(e){try{if("backward"===e){let e=this.history.pop();if(!e)throw new Error("No previous version");return void(this.currentSchema=e)}let t=this.migrations.filter((e=>"pending"===e.status)).flatMap((e=>e.changes));if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce(((e,t)=>this.applySchemaChanges(e,[t])),this.currentSchema)}catch(e){throw e instanceof Ke?e:new Ke("Schema transformation failed","INVALID_SCHEMA",void 0,e)}}};typeof window<"u"&&(window.Buffer=e);var Ge=l(m()),Xe=l(f()),Qe=class{indexes=new Map;createIndex(e){this.indexes.has(e)||this.indexes.set(e,new Map)}removeIndex(e){this.indexes.delete(e)}hasIndex(e){return this.indexes.has(e)}indexDocument(e){const t=e.$id;if(t)for(const[r,s]of this.indexes.entries()){const i=e[r];if(void 0!==i){let e=s.get(i);e||(e=new Set,s.set(i,e)),e.add(t)}}}removeDocument(e){const t=e.$id;if(t)for(const[r,s]of this.indexes.entries()){const i=e[r];if(void 0!==i){const e=s.get(i);e&&(e.delete(t),0===e.size&&s.delete(i))}}}lookup(e,t){const r=this.indexes.get(e);return r?r.get(t):void 0}clear(){this.indexes.clear()}},Ze=class{middlewares=[];use(e){this.middlewares.push(e)}execute(e,t){let r=-1;const s=i=>{if(i<=r)throw new Error("next() called multiple times");r=i;const a=this.middlewares[i];if(i===this.middlewares.length)return t();try{return a(e,(()=>s(i+1)))}catch(e){return Promise.reject(e)}};return s(0)}wrap(e,t){const r=this;return new Proxy(e,{get(e,s,i){const a=Reflect.get(e,s,i);return"function"==typeof a?function(...i){const n={...t,operation:s.toString(),args:i};return r.execute(n,(()=>a.apply(e,i)))}:a}})}},et=async(e,t)=>{const r=Date.now();try{const s=await t();return tt(e,r,s,null),s}catch(t){throw tt(e,r,void 0,t),t}};function tt(e,t,r,s){if(!e.eventBus)return;const i=Date.now()-t;e.eventBus.emit({name:"telemetry",payload:{type:"telemetry",method:e.operation,timestamp:Date.now(),metadata:{args:e.args,performance:{durationMs:i},source:{level:e.documentId?"document":e.collection?"collection":"database",collection:e.collection,document:e.documentId},result:s?void 0:{type:Array.isArray(r)?"array":typeof r,size:Array.isArray(r)?r.length:void 0},error:s?{message:s.message,name:s.name,stack:s.stack}:null}}})}var{match:rt}=(0,Xe.createMatcher)({});async function st(e){const{collection:r,initial:s,validator:i,store:a,bus:n,lockManager:o,indexManager:c}=e,[h,u]=H(s),{value:d,issues:l}=i?await i["~standard"].validate(h):{value:s,issues:void 0};if(l)throw console.warn({issues:l}),new V("INVALID_DATA",`Invalid data for ${r}`);const p={current:Object.assign(d,u)};void 0===p.current.$id&&(p.current=Object.assign(p.current,{$id:t(),$created:(new Date).toJSON(),$version:1}),await a.add(p.current),c.indexDocument(p.current),n.emit({name:"document:create",payload:{type:"document:create",data:p.current,timestamp:Date.now()}}));const m={save:async e=>{const t=await o.acquire();try{const{$id:t,$version:s}=p.current;if(!t)throw new Error("Document ID missing.");const i=await a.getById(t);if(i&&i.$version!==s)throw new V("CONFLICT",`Version mismatch on ${r}/${t}`);return i&&c.removeDocument(i),p.current.$version=(s||0)+1,p.current.$updated=(new Date).toJSON(),e?e.addOp(a,"put",p.current):await a.put(p.current),c.indexDocument(p.current),n.emit({name:"document:write",payload:{type:"document:write",data:p.current,timestamp:Date.now()}}),!0}finally{t()}},update:async(e,t)=>{const[s,a]=H(Object.assign({},p.current,e)),{value:o,issues:c}=i?await i["~standard"].validate(s):{value:s,issues:void 0};if(c)throw new V("INVALID_DATA",`Invalid update for ${r}`);p.current=Object.assign(o,a);const h=await m.save(t);return h&&n.emit({name:"document:update",payload:{type:"document:update",data:p.current,timestamp:Date.now()}}),h},delete:async e=>{const t=await o.acquire();try{const{$id:t,$version:s}=p.current;if(!t)throw new Error("Document ID missing.");const i=await a.getById(t);if(i&&i.$version!==s)throw new V("CONFLICT",`Version mismatch on delete ${r}/${t}`);return e?e.addOp(a,"delete",t):await a.delete(t),c.removeDocument(p.current),n.emit({name:"document:delete",payload:{type:"document:delete",data:p.current,timestamp:Date.now()}}),!0}finally{t()}},read:async()=>{const e=p.current.$id,t=await a.getById(e);if(!t)throw new Error("Document not found.");return p.current={...t},n.emit({name:"document:read",payload:{type:"document:read",data:p.current,timestamp:Date.now()}}),!0},state:()=>(e=>{const[t]=H(e);return t})(p.current),subscribe:n.subscribe};return new Proxy({},{get:(e,t)=>["update","delete","subscribe","read","state","save"].includes(t)?m[t]:Reflect.get(p.current,t)})}async function it({collection:e,validator:t,bus:r,store:s,pipeline:i,validate:a}){const n=new Qe,o=new z;if(a&&t.indexes)for(const e of t.indexes)n.createIndex(e.fields[0]);const c={collection:e,validator:a?t:void 0,store:s,bus:r,pipeline:i,lockManager:o,indexManager:n},h={async validate(e){const r=t["~standard"].validate(e);return r instanceof Promise?await r:r},create:async(t,s)=>{const i=await st({...c,initial:t});return s&&await i.save(s),r.emit({name:"collection:read",payload:{type:"collection:read",model:e,timestamp:Date.now()}}),i},find:async t=>{const i=await s.cursor((async e=>e&&rt(e,t)?{value:e,done:!0}:{value:null,done:!1}));if(i){const t=st({...c,initial:i});return r.emit({name:"collection:read",payload:{type:"collection:read",method:"find",model:e,timestamp:Date.now()}}),t}return null},filter:async t=>{const i=[];return await s.cursor((async e=>(e&&rt(e,t)&&i.push(await st({...c,initial:e})),{value:null,done:!1}))),r.emit({name:"collection:read",payload:{type:"collection:read",method:"filter",model:e,timestamp:Date.now()}}),i},list:async t=>{const i={total:await s.count(),offset:"offset"===t.type?t.offset:0,limit:t.limit,count:0};return{async next(){const a="offset"===t.type?await async function(e,t){const{offset:r,limit:s}=t,i=[];let a=0,n=!1;for(;!(n||(await e((async e=>a<r?(a++,{value:e,done:!1,offset:1}):(i.push(e),a++,a>=r+s?(n=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1}))),i.length>=s)););return i}(s.cursor.bind(s),{...t,offset:i.offset}):await async function(e,t){const{limit:r,direction:s}=t,i=[];let a=!1;for(;!a;)await e((async e=>(i.push(e),i.length>=r?(a=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1})),s);return i}(s.cursor.bind(s),{...t});i.offset+=i.limit,i.count+=a.length;const n=await Promise.all(a.map((e=>st({...c,initial:e}))));return r.emit({name:"collection:read",payload:{type:"collection:read",method:"list",model:e,timestamp:Date.now()}}),{value:n,done:i.count>=i.total}}}},subscribe:r.subscribe};return i.wrap(h,{collection:e})}var at=class{id;buffer=[];committed=!1;constructor(){this.id=t()}addOp(e,t,r){if(this.committed)throw new V("TRANSACTION_FAILED","Transaction already committed");this.buffer.push({store:e,type:t,data:r})}async commit(){if(this.committed)throw new V("TRANSACTION_FAILED","Transaction already committed");this.committed=!0;const e=new Map;for(const t of this.buffer){const r=e.get(t.store)||[];r.push({type:t.type,data:t.data}),e.set(t.store,r)}try{const t=Array.from(e.entries()).map((([e,t])=>e.batch(t)));await Promise.all(t)}catch(e){throw this.rollback(),new V("TRANSACTION_FAILED",`Transaction failed: ${e.message}`)}}rollback(){this.buffer=[],this.committed=!0}};async function nt(e,t){const r=(0,Ge.createEventBus)(),s=new Ze;s.use(((e=3,t=100)=>async(r,s)=>{let i=0;for(;i<e;)try{return await s()}catch(r){if(!(r instanceof V&&"TRANSIENT_ERROR"===r.type))throw r;{if(i++,i>=e)throw r;const s=t*Math.pow(2,i)+50*Math.random();await new Promise((e=>setTimeout(e,s)))}}})()),e.enableTelemetry&&s.use(et);const i=new Map,a=t({...e,name:"schemas",keyPath:"name"});async function n(r){let s=i.get(r);return s||(s=t({...e,name:r,keyPath:"$id"}),i.set(r,s)),await s.open(),s}async function o(t){const i=await a.getById(t);if(!i)throw new V("SCHEMA_NOT_FOUND",`Collection ${t} missing`);const o=await n(t),c=ge(i,e.predicates||{}),h=await it({collection:t,bus:r,validator:c,validate:Boolean(e.validate),store:o,pipeline:s});return r.emit({name:"collection:read",payload:{type:"collection:read",schema:{name:t},timestamp:Date.now()}}),h}async function c(e){return await a.put(e),r.emit({name:"collection:update",payload:{type:"collection:update",schema:e,timestamp:Date.now()}}),!0}const h={collection:o,createCollection:async e=>{if(await a.getById(e.name))throw new V("SCHEMA_ALREADY_EXISTS",`Collection ${e.name} exists`);if(!Be(e))throw new V("INVALID_SCHEMA_DEFINITION","Invalid schema");await a.put(e);const t=o(e.name);return r.emit({name:"collection:create",payload:{type:"collection:create",schema:e,timestamp:Date.now()}}),t},deleteCollection:async e=>{const t=await a.getById(e);if(!t)throw new V("SCHEMA_NOT_FOUND",`Collection ${e} missing`);return i.delete(e),await a.delete(e),r.emit({name:"collection:delete",payload:{type:"collection:delete",schema:t,timestamp:Date.now()}}),!0},updateCollection:c,migrateCollection:async(e,t,r=100)=>{const s=await a.getById(e);if(!s)throw new V("SCHEMA_NOT_FOUND","Schema not found");const i=await n(e),o=new Ye(s);await o.add(t);const h=function(e,t,r){let s,i=!1;return new ReadableStream({async pull(a){if(i)return void a.close();let n=0;const o=void 0!==s?{lower:s,lowerOpen:!0}:void 0;try{await t.cursor((async(e,t)=>(a.enqueue(e),s=t,n++,n>=r?{done:!0,value:e}:{done:!1,value:e})),"forward",o),n<r&&(i=!0)}catch(t){console.error(`[migrateCollection] Error pulling chunk for '${e}':`,t),a.error(new V("INTERNAL_ERROR",`Failed to read chunk for collection '${e}'`,void 0,t))}},cancel(){console.warn(`[migrateCollection] Input stream for collection '${e}' cancelled.`)}})}(e,i,r);c((await o.dryRun(new ReadableStream({start(e){e.close()}}),"forward")).newSchema);const u=await o.migrate(h);return await async function(e,t,r,s){const i=t.getReader();let a=[];try{for(;;){const{value:e,done:t}=await i.read();if(t)break;if(!e)continue;const{$version:n}=e;e.$version=(n||0)+1,e.$updated=(new Date).toJSON(),a.push(e),a.length>=s&&(await r.batch([{type:"put",data:a}]),a=[])}a.length>0&&await r.batch([{type:"put",data:a}])}catch(t){throw console.error(`[migrateCollection] Error writing transformed data for '${e}':`,t),new V("INTERNAL_ERROR",`Failed to write transformed data for collection '${e}'`,void 0,t)}finally{i.releaseLock()}}(e,u,i,r),!0},transaction:async e=>{const t=new at;try{await e(t),await t.commit()}catch(e){throw t.rollback(),e}},subscribe:r.subscribe,close:()=>{i.clear(),a.clear(),r.clear()},ensureCollection:async e=>{try{await h.createCollection(e)}catch(e){if(e instanceof V&&"SCHEMA_ALREADY_EXISTS"===e.type)return;throw e}},setupCollections:async e=>{for(const t of e)await h.ensureCollection(t)}};return s.wrap(h,{})}export{Z as ConnectionManager,B as DEFAULT_KEYPATH,nt as DatabaseConnection,te as IndexedDBStore,st as createDocument,W as createEphemeralStore,re as createIndexedDbStore,it as openCollection};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asaidimu/utils-database",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "A collection of database utilities.",
5
5
  "main": "index.js",
6
6
  "module": "index.mjs",