@warlock.js/cascade 5.19.1 → 5.21.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/CHANGELOG.md +36 -1
- package/cjs/index.cjs +2356 -1039
- package/cjs/index.cjs.map +1 -1
- package/esm/context/database-transaction-context.d.mts +10 -0
- package/esm/context/database-transaction-context.d.mts.map +1 -1
- package/esm/context/database-transaction-context.mjs +17 -0
- package/esm/context/database-transaction-context.mjs.map +1 -1
- package/esm/contracts/query-builder.contract.d.mts +30 -3
- package/esm/contracts/query-builder.contract.d.mts.map +1 -1
- package/esm/data-source/data-source-registry.d.mts +33 -1
- package/esm/data-source/data-source-registry.d.mts.map +1 -1
- package/esm/data-source/data-source-registry.mjs +75 -5
- package/esm/data-source/data-source-registry.mjs.map +1 -1
- package/esm/database-dirty-tracker.d.mts +5 -0
- package/esm/database-dirty-tracker.d.mts.map +1 -1
- package/esm/database-dirty-tracker.mjs +16 -0
- package/esm/database-dirty-tracker.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-driver.d.mts +12 -0
- package/esm/drivers/mongodb/mongodb-driver.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-driver.mjs +58 -19
- package/esm/drivers/mongodb/mongodb-driver.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-migration-driver.d.mts +1 -1
- package/esm/drivers/mongodb/mongodb-migration-driver.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-migration-driver.mjs +15 -18
- package/esm/drivers/mongodb/mongodb-migration-driver.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-builder.d.mts +13 -3
- package/esm/drivers/mongodb/mongodb-query-builder.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-builder.mjs +72 -19
- package/esm/drivers/mongodb/mongodb-query-builder.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-parser.d.mts +6 -0
- package/esm/drivers/mongodb/mongodb-query-parser.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-parser.mjs +128 -30
- package/esm/drivers/mongodb/mongodb-query-parser.mjs.map +1 -1
- package/esm/drivers/postgres/index.d.mts +2 -3
- package/esm/drivers/postgres/index.mjs +1 -2
- package/esm/drivers/postgres/postgres-blueprint.mjs +4 -4
- package/esm/drivers/postgres/postgres-blueprint.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-dialect.d.mts +5 -1
- package/esm/drivers/postgres/postgres-dialect.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-dialect.mjs +38 -8
- package/esm/drivers/postgres/postgres-dialect.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-driver.d.mts +52 -29
- package/esm/drivers/postgres/postgres-driver.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-driver.mjs +196 -58
- package/esm/drivers/postgres/postgres-driver.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-migration-driver.d.mts +2 -1
- package/esm/drivers/postgres/postgres-migration-driver.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-migration-driver.mjs +8 -6
- package/esm/drivers/postgres/postgres-migration-driver.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-query-builder.d.mts +18 -7
- package/esm/drivers/postgres/postgres-query-builder.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-query-builder.mjs +146 -31
- package/esm/drivers/postgres/postgres-query-builder.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-query-parser.d.mts +23 -1
- package/esm/drivers/postgres/postgres-query-parser.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-query-parser.mjs +160 -43
- package/esm/drivers/postgres/postgres-query-parser.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-sql-serializer.mjs +3 -2
- package/esm/drivers/postgres/postgres-sql-serializer.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-type-converters.mjs +57 -0
- package/esm/drivers/postgres/postgres-type-converters.mjs.map +1 -0
- package/esm/events/model-events.d.mts +1 -1
- package/esm/events/model-events.d.mts.map +1 -1
- package/esm/events/model-events.mjs.map +1 -1
- package/esm/index.d.mts +6 -6
- package/esm/index.mjs +5 -5
- package/esm/migration/column-builder.d.mts.map +1 -1
- package/esm/migration/column-builder.mjs +2 -2
- package/esm/migration/column-builder.mjs.map +1 -1
- package/esm/migration/index.d.mts +2 -2
- package/esm/migration/index.mjs +1 -1
- package/esm/migration/migration-order.mjs +5 -2
- package/esm/migration/migration-order.mjs.map +1 -1
- package/esm/migration/migration-runner.d.mts +50 -5
- package/esm/migration/migration-runner.d.mts.map +1 -1
- package/esm/migration/migration-runner.mjs +370 -147
- package/esm/migration/migration-runner.mjs.map +1 -1
- package/esm/migration/migration.d.mts +36 -3
- package/esm/migration/migration.d.mts.map +1 -1
- package/esm/migration/migration.mjs +62 -5
- package/esm/migration/migration.mjs.map +1 -1
- package/esm/model/methods/accessor-methods.mjs +1 -3
- package/esm/model/methods/accessor-methods.mjs.map +1 -1
- package/esm/model/methods/delete-methods.mjs +6 -2
- package/esm/model/methods/delete-methods.mjs.map +1 -1
- package/esm/model/methods/hydration-methods.mjs +16 -2
- package/esm/model/methods/hydration-methods.mjs.map +1 -1
- package/esm/model/methods/instance-event-methods.mjs +2 -1
- package/esm/model/methods/instance-event-methods.mjs.map +1 -1
- package/esm/model/methods/meta-methods.mjs +53 -16
- package/esm/model/methods/meta-methods.mjs.map +1 -1
- package/esm/model/methods/query-methods.mjs +86 -15
- package/esm/model/methods/query-methods.mjs.map +1 -1
- package/esm/model/methods/static-event-methods.mjs +16 -1
- package/esm/model/methods/static-event-methods.mjs.map +1 -1
- package/esm/model/methods/write-methods.d.mts.map +1 -1
- package/esm/model/methods/write-methods.mjs +50 -50
- package/esm/model/methods/write-methods.mjs.map +1 -1
- package/esm/model/model.d.mts +16 -1
- package/esm/model/model.d.mts.map +1 -1
- package/esm/model/model.mjs +39 -5
- package/esm/model/model.mjs.map +1 -1
- package/esm/model/register-model.d.mts +6 -1
- package/esm/model/register-model.d.mts.map +1 -1
- package/esm/model/register-model.mjs +16 -1
- package/esm/model/register-model.mjs.map +1 -1
- package/esm/query-builder/query-builder.d.mts +21 -2
- package/esm/query-builder/query-builder.d.mts.map +1 -1
- package/esm/query-builder/query-builder.mjs +97 -20
- package/esm/query-builder/query-builder.mjs.map +1 -1
- package/esm/relations/key-conventions.mjs +13 -3
- package/esm/relations/key-conventions.mjs.map +1 -1
- package/esm/relations/pivot-operations.mjs +1 -1
- package/esm/relations/relation-loader.d.mts +15 -5
- package/esm/relations/relation-loader.d.mts.map +1 -1
- package/esm/relations/relation-loader.mjs +51 -16
- package/esm/relations/relation-loader.mjs.map +1 -1
- package/esm/remover/database-remover.d.mts.map +1 -1
- package/esm/remover/database-remover.mjs +21 -7
- package/esm/remover/database-remover.mjs.map +1 -1
- package/esm/restorer/database-restorer.d.mts +12 -2
- package/esm/restorer/database-restorer.d.mts.map +1 -1
- package/esm/restorer/database-restorer.mjs +43 -13
- package/esm/restorer/database-restorer.mjs.map +1 -1
- package/esm/sync/model-events.mjs +63 -3
- package/esm/sync/model-events.mjs.map +1 -1
- package/esm/sync/model-sync-operation.d.mts.map +1 -1
- package/esm/sync/model-sync-operation.mjs +3 -2
- package/esm/sync/model-sync-operation.mjs.map +1 -1
- package/esm/sync/sync-manager.d.mts +3 -42
- package/esm/sync/sync-manager.d.mts.map +1 -1
- package/esm/sync/sync-manager.mjs +37 -126
- package/esm/sync/sync-manager.mjs.map +1 -1
- package/esm/transactions/after-commit.d.mts +24 -0
- package/esm/transactions/after-commit.d.mts.map +1 -0
- package/esm/transactions/after-commit.mjs +47 -0
- package/esm/transactions/after-commit.mjs.map +1 -0
- package/esm/utils/connect-to-database.d.mts.map +1 -1
- package/esm/utils/connect-to-database.mjs +4 -4
- package/esm/utils/connect-to-database.mjs.map +1 -1
- package/esm/utils/database-writer.utils.d.mts +1 -1
- package/esm/utils/database-writer.utils.d.mts.map +1 -1
- package/esm/utils/database-writer.utils.mjs +1 -0
- package/esm/utils/database-writer.utils.mjs.map +1 -1
- package/esm/utils/define-model.d.mts.map +1 -1
- package/esm/utils/define-model.mjs +2 -10
- package/esm/utils/define-model.mjs.map +1 -1
- package/esm/utils/is-valid-date-value.mjs +3 -2
- package/esm/utils/is-valid-date-value.mjs.map +1 -1
- package/esm/utils/once-connected.d.mts.map +1 -1
- package/esm/utils/once-connected.mjs +12 -2
- package/esm/utils/once-connected.mjs.map +1 -1
- package/esm/validation/mutators/embed-mutator.mjs +19 -11
- package/esm/validation/mutators/embed-mutator.mjs.map +1 -1
- package/esm/validation/plugins/embed-validator-plugin.d.mts +2 -2
- package/esm/validation/plugins/embed-validator-plugin.d.mts.map +1 -1
- package/esm/validation/plugins/embed-validator-plugin.mjs +8 -2
- package/esm/validation/plugins/embed-validator-plugin.mjs.map +1 -1
- package/esm/validation/rules/database-model-rule.mjs +6 -5
- package/esm/validation/rules/database-model-rule.mjs.map +1 -1
- package/esm/validation/rules/exists-rule.mjs +6 -4
- package/esm/validation/rules/exists-rule.mjs.map +1 -1
- package/esm/validation/rules/unique-rule.mjs +5 -2
- package/esm/validation/rules/unique-rule.mjs.map +1 -1
- package/esm/validation/validators/embed-validator.d.mts.map +1 -1
- package/esm/validation/validators/embed-validator.mjs +1 -1
- package/esm/validation/validators/embed-validator.mjs.map +1 -1
- package/esm/writer/database-writer.d.mts +27 -0
- package/esm/writer/database-writer.d.mts.map +1 -1
- package/esm/writer/database-writer.mjs +84 -17
- package/esm/writer/database-writer.mjs.map +1 -1
- package/llms-full.txt +2783 -2766
- package/llms.txt +15 -15
- package/package.json +6 -6
- package/skills/aggregate-data/SKILL.md +165 -165
- package/skills/alter-migration/SKILL.md +531 -531
- package/skills/configure-delete-strategy/SKILL.md +130 -130
- package/skills/define-model/SKILL.md +205 -205
- package/skills/define-relations/SKILL.md +171 -171
- package/skills/index.md +23 -0
- package/skills/manage-data-sources/SKILL.md +140 -140
- package/skills/manage-transactions/SKILL.md +208 -191
- package/skills/paginate-results/SKILL.md +122 -122
- package/skills/perform-atomic-ops/SKILL.md +156 -156
- package/skills/query-data/SKILL.md +213 -213
- package/skills/run-cascade-cli/SKILL.md +125 -125
- package/skills/search-by-vector/SKILL.md +127 -127
- package/skills/subscribe-to-model-events/SKILL.md +148 -148
- package/skills/track-changes/SKILL.md +127 -127
- package/skills/write-migration/SKILL.md +206 -206
- package/esm/drivers/postgres/postgres-sync-adapter.d.mts +0 -79
- package/esm/drivers/postgres/postgres-sync-adapter.d.mts.map +0 -1
- package/esm/drivers/postgres/postgres-sync-adapter.mjs +0 -162
- package/esm/drivers/postgres/postgres-sync-adapter.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-events.mjs","names":[],"sources":["../../../../../../../cascade/src/events/model-events.ts"],"sourcesContent":["import { type QueryBuilderContract } from \"../contracts\";\r\nimport type { Model } from \"../model/model\";\r\nimport { type DeleteStrategy } from \"../types\";\r\n\r\ntype OnValidatingEventContext = {\r\n isInsert: boolean;\r\n mode: \"insert\" | \"update\";\r\n};\r\n\r\ntype OnSavingEventContext = {\r\n isInsert: boolean;\r\n mode: \"insert\" | \"update\";\r\n};\r\n\r\ntype OnDeletingEventContext = {\r\n strategy: DeleteStrategy;\r\n primaryKeyValue: string | number;\r\n primaryKey: string;\r\n};\r\n\r\nexport type OnDeletedEventContext = OnDeletingEventContext & {\r\n deletedCount: number;\r\n trashRecord?: Record<string, unknown>;\r\n};\r\n\r\ntype OnFetchingEventContext = {\r\n table: string;\r\n modelClass: any;\r\n};\r\n\r\ntype OnHydratingEventContext = {\r\n query: QueryBuilderContract;\r\n hydrateCallback?: (data: any, index: number) => any;\r\n};\r\n\r\ntype OnFetchedEventContext = {\r\n query: QueryBuilderContract;\r\n rawRecords: any[];\r\n duration: number;\r\n};\r\n\r\n/**\r\n * Lifecycle events understood by Cascade models.\r\n *\r\n * The list mirrors the hooks in the legacy ORM so downstream code can subscribe\r\n * with consistent semantics.\r\n */\r\nexport type ModelEventName =\r\n | \"initializing\"\r\n | \"fetching\"\r\n | \"hydrating\"\r\n | \"fetched\"\r\n | \"validating\"\r\n | \"validated\"\r\n | \"saving\"\r\n | \"saved\"\r\n | \"creating\"\r\n | \"created\"\r\n | \"updating\"\r\n | \"updated\"\r\n | \"deleting\"\r\n | \"deleted\"\r\n | \"restoring\"\r\n | \"restored\";\r\n\r\n/** Signature of an event listener registered against a model lifecycle hook. */\r\nexport type ModelEventListener<TModel, TContext = unknown> = (\r\n model: TModel,\r\n context: TContext,\r\n) => void | Promise<void>;\r\n\r\n/**\r\n * Light-weight async event emitter used to power model lifecycle hooks.\r\n *\r\n * The implementation intentionally avoids any external dependency so we can\r\n * re-use it in drivers, writers, and other core services without pulling in\r\n * heavier event libraries.\r\n */\r\nexport class ModelEvents<TModel> {\r\n public readonly listeners = new Map<ModelEventName, Set<ModelEventListener<TModel>>>();\r\n\r\n /**\r\n * Register a listener for the given event.\r\n * Returns an unsubscribe function for convenience.\r\n */\r\n public on<TContext = unknown>(\r\n event: ModelEventName,\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n const listeners = this.ensureListenerSet(event);\r\n listeners.add(listener as ModelEventListener<TModel>);\r\n return () => this.off(event, listener);\r\n }\r\n\r\n /**\r\n * Register a listener that automatically unsubscribes after the first call.\r\n */\r\n public once<TContext = unknown>(\r\n event: ModelEventName,\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n const wrapper: ModelEventListener<TModel, TContext> = async (model, context) => {\r\n try {\r\n await listener(model, context);\r\n } finally {\r\n this.off(event, wrapper);\r\n }\r\n };\r\n return this.on(event, wrapper);\r\n }\r\n\r\n /**\r\n * Deregister a listener for the given event.\r\n */\r\n public off<TContext = unknown>(\r\n event: ModelEventName,\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): void {\r\n const listeners = this.listeners.get(event);\r\n if (!listeners) {\r\n return;\r\n }\r\n listeners.delete(listener as ModelEventListener<TModel>);\r\n if (listeners.size === 0) {\r\n this.listeners.delete(event);\r\n }\r\n }\r\n\r\n /**\r\n * Emit an event to all registered listeners.\r\n */\r\n public async emit<TContext = unknown>(\r\n event: ModelEventName,\r\n model: TModel,\r\n context: TContext,\r\n ): Promise<void> {\r\n const listeners = this.listeners.get(event);\r\n if (!listeners || listeners.size === 0) {\r\n return;\r\n }\r\n for (const listener of Array.from(listeners)) {\r\n await listener(model, context);\r\n }\r\n }\r\n\r\n /**\r\n * Emit events for fetching\r\n */\r\n public async emitFetching<TContext = unknown>(\r\n query: QueryBuilderContract,\r\n context?: TContext,\r\n ): Promise<void> {\r\n await this.emit(\"fetching\", query as any, context);\r\n }\r\n\r\n /**\r\n * Remove all registered listeners.\r\n */\r\n public clear(): void {\r\n this.listeners.clear();\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"saving\" event.\r\n *\r\n * Fired before a model is persisted (both insert and update), and before validation.\r\n * Use this hook for data enrichment and preparation (e.g., setting createdBy, updatedBy).\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onSaving<TContext = OnSavingEventContext>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"saving\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"saved\" event.\r\n *\r\n * Fired after a model has been successfully persisted.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onSaved<TContext = unknown>(listener: ModelEventListener<TModel, TContext>): () => void {\r\n return this.on(\"saved\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"creating\" event.\r\n *\r\n * Fired before a new model is inserted into the database.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onCreating<TContext = unknown>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"creating\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"created\" event.\r\n *\r\n * Fired after a new model has been successfully inserted.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onCreated<TContext = unknown>(listener: ModelEventListener<TModel, TContext>): () => void {\r\n return this.on(\"created\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"updating\" event.\r\n *\r\n * Fired before an existing model is updated in the database.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onUpdating<TContext = unknown>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"updating\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"updated\" event.\r\n *\r\n * Fired after an existing model has been successfully updated.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onUpdated<TContext = unknown>(listener: ModelEventListener<TModel, TContext>): () => void {\r\n return this.on(\"updated\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"deleting\" event.\r\n *\r\n * Fired before a model is deleted from the database.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onDeleting<TContext = OnDeletingEventContext>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"deleting\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"deleted\" event.\r\n *\r\n * Fired after a model has been successfully deleted.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onDeleted<TContext = OnDeletedEventContext>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"deleted\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"validating\" event.\r\n *\r\n * Fired before model validation is performed.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onValidating<TContext = OnValidatingEventContext>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"validating\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"validated\" event.\r\n *\r\n * Fired after model validation has completed.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onValidated<TContext = unknown>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"validated\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"fetching\" event.\r\n *\r\n * Fired before a query is executed to fetch models.\r\n * Receives the query builder instance, allowing modification before execution.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onFetching<TContext = OnFetchingEventContext>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"fetching\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"hydrating\" event.\r\n *\r\n * Fired after raw records are fetched but before they are hydrated into model instances.\r\n * Allows modification of raw data before hydration.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onHydrating<TContext = OnHydratingEventContext>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"hydrating\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"fetched\" event.\r\n *\r\n * Fired after models have been fetched and hydrated.\r\n * Receives hydrated model instances and query context.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onFetched<TContext = OnFetchedEventContext>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"fetched\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"restoring\" event.\r\n *\r\n * Fired before a soft-deleted model is restored.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onRestoring<TContext = unknown>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"restoring\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"restored\" event.\r\n *\r\n * Fired after a soft-deleted model has been successfully restored.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onRestored<TContext = unknown>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"restored\", listener);\r\n }\r\n\r\n /**\r\n * Ensures a listener set exists for the given event.\r\n *\r\n * @param event - The event name\r\n * @returns The listener set for the event\r\n * @private\r\n */\r\n private ensureListenerSet(event: ModelEventName): Set<ModelEventListener<TModel>> {\r\n let listeners = this.listeners.get(event);\r\n if (!listeners) {\r\n listeners = new Set();\r\n this.listeners.set(event, listeners);\r\n }\r\n return listeners;\r\n }\r\n}\r\n\r\n/**\r\n * Global event emitter invoked for every model instance, regardless of type.\r\n * Useful for cross-cutting concerns like auditing or request-scoped enrichment.\r\n */\r\nexport const globalModelEvents = new ModelEvents<Model>();\r\n"],"mappings":";;;;;;;;AA8EA,IAAa,cAAb,MAAiC;CAC/B,AAAgB,4BAAY,IAAI,IAAqD;;;;;CAMrF,AAAO,GACL,OACA,UACY;EAEZ,AADkB,KAAK,kBAAkB,KACjC,CAAC,CAAC,IAAI,QAAsC;EACpD,aAAa,KAAK,IAAI,OAAO,QAAQ;CACvC;;;;CAKA,AAAO,KACL,OACA,UACY;EACZ,MAAM,UAAgD,OAAO,OAAO,YAAY;GAC9E,IAAI;IACF,MAAM,SAAS,OAAO,OAAO;GAC/B,UAAU;IACR,KAAK,IAAI,OAAO,OAAO;GACzB;EACF;EACA,OAAO,KAAK,GAAG,OAAO,OAAO;CAC/B;;;;CAKA,AAAO,IACL,OACA,UACM;EACN,MAAM,YAAY,KAAK,UAAU,IAAI,KAAK;EAC1C,IAAI,CAAC,WACH;EAEF,UAAU,OAAO,QAAsC;EACvD,IAAI,UAAU,SAAS,GACrB,KAAK,UAAU,OAAO,KAAK;CAE/B;;;;CAKA,MAAa,KACX,OACA,OACA,SACe;EACf,MAAM,YAAY,KAAK,UAAU,IAAI,KAAK;EAC1C,IAAI,CAAC,aAAa,UAAU,SAAS,GACnC;EAEF,KAAK,MAAM,YAAY,MAAM,KAAK,SAAS,GACzC,MAAM,SAAS,OAAO,OAAO;C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;EACZ,OAAO,KAAK,GAAG,YAAY,QAAQ;CACrC;;;;;;;;CASA,AAAQ,kBAAkB,OAAwD;EAChF,IAAI,YAAY,KAAK,UAAU,IAAI,KAAK;EACxC,IAAI,CAAC,WAAW;GACd,4BAAY,IAAI,IAAI;GACpB,KAAK,UAAU,IAAI,OAAO,SAAS;EACrC;EACA,OAAO;CACT;AACF;;;;;AAMA,MAAa,oBAAoB,IAAI,YAAmB"}
|
|
1
|
+
{"version":3,"file":"model-events.mjs","names":[],"sources":["../../../../../../../cascade/src/events/model-events.ts"],"sourcesContent":["import { type QueryBuilderContract } from \"../contracts\";\r\nimport type { Model } from \"../model/model\";\r\nimport { type DeleteStrategy } from \"../types\";\r\n\r\ntype OnValidatingEventContext = {\r\n isInsert: boolean;\r\n mode: \"insert\" | \"update\";\r\n};\r\n\r\ntype OnSavingEventContext = {\r\n isInsert: boolean;\r\n mode: \"insert\" | \"update\";\r\n};\r\n\r\ntype OnDeletingEventContext = {\r\n strategy: DeleteStrategy;\r\n primaryKeyValue: string | number;\r\n primaryKey: string;\r\n};\r\n\r\nexport type OnDeletedEventContext = OnDeletingEventContext & {\r\n deletedCount: number;\r\n trashRecord?: Record<string, unknown>;\r\n};\r\n\r\ntype OnFetchingEventContext = {\r\n table: string;\r\n modelClass: any;\r\n};\r\n\r\ntype OnHydratingEventContext = {\r\n query: QueryBuilderContract;\r\n hydrateCallback?: (data: any, index: number) => any;\r\n};\r\n\r\ntype OnFetchedEventContext = {\r\n query: QueryBuilderContract;\r\n rawRecords: any[];\r\n duration: number;\r\n};\r\n\r\n/**\r\n * Lifecycle events understood by Cascade models.\r\n *\r\n * The list mirrors the hooks in the legacy ORM so downstream code can subscribe\r\n * with consistent semantics.\r\n */\r\nexport type ModelEventName =\r\n | \"fetching\"\r\n | \"hydrating\"\r\n | \"fetched\"\r\n | \"validating\"\r\n | \"validated\"\r\n | \"saving\"\r\n | \"saved\"\r\n | \"creating\"\r\n | \"created\"\r\n | \"updating\"\r\n | \"updated\"\r\n | \"deleting\"\r\n | \"deleted\"\r\n | \"restoring\"\r\n | \"restored\";\r\n\r\n/** Signature of an event listener registered against a model lifecycle hook. */\r\nexport type ModelEventListener<TModel, TContext = unknown> = (\r\n model: TModel,\r\n context: TContext,\r\n) => void | Promise<void>;\r\n\r\n/**\r\n * Light-weight async event emitter used to power model lifecycle hooks.\r\n *\r\n * The implementation intentionally avoids any external dependency so we can\r\n * re-use it in drivers, writers, and other core services without pulling in\r\n * heavier event libraries.\r\n */\r\nexport class ModelEvents<TModel> {\r\n public readonly listeners = new Map<ModelEventName, Set<ModelEventListener<TModel>>>();\r\n\r\n /**\r\n * Register a listener for the given event.\r\n * Returns an unsubscribe function for convenience.\r\n */\r\n public on<TContext = unknown>(\r\n event: ModelEventName,\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n const listeners = this.ensureListenerSet(event);\r\n listeners.add(listener as ModelEventListener<TModel>);\r\n return () => this.off(event, listener);\r\n }\r\n\r\n /**\r\n * Register a listener that automatically unsubscribes after the first call.\r\n */\r\n public once<TContext = unknown>(\r\n event: ModelEventName,\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n const wrapper: ModelEventListener<TModel, TContext> = async (model, context) => {\r\n try {\r\n await listener(model, context);\r\n } finally {\r\n this.off(event, wrapper);\r\n }\r\n };\r\n return this.on(event, wrapper);\r\n }\r\n\r\n /**\r\n * Deregister a listener for the given event.\r\n */\r\n public off<TContext = unknown>(\r\n event: ModelEventName,\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): void {\r\n const listeners = this.listeners.get(event);\r\n if (!listeners) {\r\n return;\r\n }\r\n listeners.delete(listener as ModelEventListener<TModel>);\r\n if (listeners.size === 0) {\r\n this.listeners.delete(event);\r\n }\r\n }\r\n\r\n /**\r\n * Emit an event to all registered listeners.\r\n */\r\n public async emit<TContext = unknown>(\r\n event: ModelEventName,\r\n model: TModel,\r\n context: TContext,\r\n ): Promise<void> {\r\n const listeners = this.listeners.get(event);\r\n if (!listeners || listeners.size === 0) {\r\n return;\r\n }\r\n for (const listener of Array.from(listeners)) {\r\n await listener(model, context);\r\n }\r\n }\r\n\r\n /**\r\n * Emit events for fetching\r\n */\r\n public async emitFetching<TContext = unknown>(\r\n query: QueryBuilderContract,\r\n context?: TContext,\r\n ): Promise<void> {\r\n await this.emit(\"fetching\", query as any, context);\r\n }\r\n\r\n /**\r\n * Remove all registered listeners.\r\n */\r\n public clear(): void {\r\n this.listeners.clear();\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"saving\" event.\r\n *\r\n * Fired before a model is persisted (both insert and update), and before validation.\r\n * Use this hook for data enrichment and preparation (e.g., setting createdBy, updatedBy).\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onSaving<TContext = OnSavingEventContext>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"saving\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"saved\" event.\r\n *\r\n * Fired after a model has been successfully persisted.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onSaved<TContext = unknown>(listener: ModelEventListener<TModel, TContext>): () => void {\r\n return this.on(\"saved\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"creating\" event.\r\n *\r\n * Fired before a new model is inserted into the database.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onCreating<TContext = unknown>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"creating\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"created\" event.\r\n *\r\n * Fired after a new model has been successfully inserted.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onCreated<TContext = unknown>(listener: ModelEventListener<TModel, TContext>): () => void {\r\n return this.on(\"created\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"updating\" event.\r\n *\r\n * Fired before an existing model is updated in the database.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onUpdating<TContext = unknown>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"updating\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"updated\" event.\r\n *\r\n * Fired after an existing model has been successfully updated.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onUpdated<TContext = unknown>(listener: ModelEventListener<TModel, TContext>): () => void {\r\n return this.on(\"updated\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"deleting\" event.\r\n *\r\n * Fired before a model is deleted from the database.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onDeleting<TContext = OnDeletingEventContext>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"deleting\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"deleted\" event.\r\n *\r\n * Fired after a model has been successfully deleted.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onDeleted<TContext = OnDeletedEventContext>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"deleted\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"validating\" event.\r\n *\r\n * Fired before model validation is performed.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onValidating<TContext = OnValidatingEventContext>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"validating\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"validated\" event.\r\n *\r\n * Fired after model validation has completed.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onValidated<TContext = unknown>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"validated\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"fetching\" event.\r\n *\r\n * Fired before a query is executed to fetch models.\r\n * Receives the query builder instance, allowing modification before execution.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onFetching<TContext = OnFetchingEventContext>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"fetching\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"hydrating\" event.\r\n *\r\n * Fired after raw records are fetched but before they are hydrated into model instances.\r\n * Allows modification of raw data before hydration.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onHydrating<TContext = OnHydratingEventContext>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"hydrating\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"fetched\" event.\r\n *\r\n * Fired after models have been fetched and hydrated.\r\n * Receives hydrated model instances and query context.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onFetched<TContext = OnFetchedEventContext>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"fetched\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"restoring\" event.\r\n *\r\n * Fired before a soft-deleted model is restored.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onRestoring<TContext = unknown>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"restoring\", listener);\r\n }\r\n\r\n /**\r\n * Registers a listener for the \"restored\" event.\r\n *\r\n * Fired after a soft-deleted model has been successfully restored.\r\n *\r\n * @param listener - The callback to invoke\r\n * @returns An unsubscribe function\r\n */\r\n public onRestored<TContext = unknown>(\r\n listener: ModelEventListener<TModel, TContext>,\r\n ): () => void {\r\n return this.on(\"restored\", listener);\r\n }\r\n\r\n /**\r\n * Ensures a listener set exists for the given event.\r\n *\r\n * @param event - The event name\r\n * @returns The listener set for the event\r\n * @private\r\n */\r\n private ensureListenerSet(event: ModelEventName): Set<ModelEventListener<TModel>> {\r\n let listeners = this.listeners.get(event);\r\n if (!listeners) {\r\n listeners = new Set();\r\n this.listeners.set(event, listeners);\r\n }\r\n return listeners;\r\n }\r\n}\r\n\r\n/**\r\n * Global event emitter invoked for every model instance, regardless of type.\r\n * Useful for cross-cutting concerns like auditing or request-scoped enrichment.\r\n */\r\nexport const globalModelEvents = new ModelEvents<Model>();\r\n"],"mappings":";;;;;;;;AA6EA,IAAa,cAAb,MAAiC;CAC/B,AAAgB,4BAAY,IAAI,IAAqD;;;;;CAMrF,AAAO,GACL,OACA,UACY;EAEZ,AADkB,KAAK,kBAAkB,KACjC,CAAC,CAAC,IAAI,QAAsC;EACpD,aAAa,KAAK,IAAI,OAAO,QAAQ;CACvC;;;;CAKA,AAAO,KACL,OACA,UACY;EACZ,MAAM,UAAgD,OAAO,OAAO,YAAY;GAC9E,IAAI;IACF,MAAM,SAAS,OAAO,OAAO;GAC/B,UAAU;IACR,KAAK,IAAI,OAAO,OAAO;GACzB;EACF;EACA,OAAO,KAAK,GAAG,OAAO,OAAO;CAC/B;;;;CAKA,AAAO,IACL,OACA,UACM;EACN,MAAM,YAAY,KAAK,UAAU,IAAI,KAAK;EAC1C,IAAI,CAAC,WACH;EAEF,UAAU,OAAO,QAAsC;EACvD,IAAI,UAAU,SAAS,GACrB,KAAK,UAAU,OAAO,KAAK;CAE/B;;;;CAKA,MAAa,KACX,OACA,OACA,SACe;EACf,MAAM,YAAY,KAAK,UAAU,IAAI,KAAK;EAC1C,IAAI,CAAC,aAAa,UAAU,SAAS,GACnC;EAEF,KAAK,MAAM,YAAY,MAAM,KAAK,SAAS,GACzC,MAAM,SAAS,OAAO,OAAO;CAEjC;;;;CAKA,MAAa,aACX,OACA,SACe;EACf,MAAM,KAAK,KAAK,YAAY,OAAc,OAAO;CACnD;;;;CAKA,AAAO,QAAc;EACnB,KAAK,U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AAK;EACxC,IAAI,CAAC,WAAW;GACd,4BAAY,IAAI,IAAI;GACpB,KAAK,UAAU,IAAI,OAAO,SAAS;EACrC;EACA,OAAO;CACT;AACF;;;;;AAMA,MAAa,oBAAoB,IAAI,YAAmB"}
|
package/esm/index.d.mts
CHANGED
|
@@ -13,7 +13,7 @@ import { EmbedKey, ModelSyncConfig, ModelSyncContract, ModelSyncOperationContrac
|
|
|
13
13
|
import { Model } from "./model/model.mjs";
|
|
14
14
|
import { ConnectionOptions, DatabaseDriver, ModelDefaultConfig, connectToDatabase, getDatabaseDriver, transaction } from "./utils/connect-to-database.mjs";
|
|
15
15
|
import { ForeignKeyBuilder } from "./migration/foreign-key-builder.mjs";
|
|
16
|
-
import { AlterSchema, ColumnMap, IndexEntry, Migration, MigrationAlterOptions, MigrationConstructor, MigrationContract, MigrationCreateOptions, OperationType, PendingOperation, UniqueEntry, migrate } from "./migration/migration.mjs";
|
|
16
|
+
import { AlterSchema, ColumnMap, IndexEntry, Migration, MigrationAlterOptions, MigrationConstructor, MigrationContract, MigrationCreateOptions, MigrationStep, OperationType, PendingOperation, UniqueEntry, migrate } from "./migration/migration.mjs";
|
|
17
17
|
import { ChunkCallback, CursorPaginationOptions, CursorPaginationResult, DriverQuery, GroupByInput, HavingInput, JoinOptions, LeanDocument, LockForUpdateOptions, OrderDirection, PaginationOptions, PaginationResult, QueryBuilderContract, RawExpression, UnwindOptions, WhereCallback, WhereObject, WhereOperator } from "./contracts/query-builder.contract.mjs";
|
|
18
18
|
import { SyncAdapterContract } from "./contracts/sync-adapter.contract.mjs";
|
|
19
19
|
import { AtomicUpdate, AtomicUpdateOptions, CreateDatabaseOptions, DriverAtomicUpdateOptions, DriverContract, DriverEvent, DriverEventListener, DriverTransactionContract, DropDatabaseOptions, FindOneAndUpdateOptions, InsertResult, RawQueryResult, TransactionContext, UpdateOperations, UpdatePipeline, UpdateResult } from "./contracts/database-driver.contract.mjs";
|
|
@@ -24,6 +24,7 @@ import { BuildUpdateOperationsResult, WriterContract, WriterOptions, WriterResul
|
|
|
24
24
|
import { DataSource, DataSourceOptions } from "./data-source/data-source.mjs";
|
|
25
25
|
import { databaseDataSourceContext } from "./context/database-data-source-context.mjs";
|
|
26
26
|
import { databaseTransactionContext } from "./context/database-transaction-context.mjs";
|
|
27
|
+
import { afterCommit } from "./transactions/after-commit.mjs";
|
|
27
28
|
import { DataSourceRegistryEvent, DataSourceRegistryListener, dataSourceRegistry } from "./data-source/data-source-registry.mjs";
|
|
28
29
|
import { MissingDataSourceError } from "./errors/missing-data-source.error.mjs";
|
|
29
30
|
import { TransactionRollbackError } from "./errors/transaction-rollback.error.mjs";
|
|
@@ -33,7 +34,7 @@ import { UnsafeRawExpressionError } from "./errors/unsafe-raw-expression.error.m
|
|
|
33
34
|
import { UnsupportedLeanOperationError } from "./errors/unsupported-lean-operation.error.mjs";
|
|
34
35
|
import { UnsupportedQueryOperationError } from "./errors/unsupported-query-operation.error.mjs";
|
|
35
36
|
import { UnsupportedUpdateOperationError } from "./errors/unsupported-update-operation.error.mjs";
|
|
36
|
-
import { ModelRef, RegisterModel, RegisterModelOptions, cleanupModelsRegistery, getAllModelsFromRegistry, getModelFromRegistry, registerModelInRegistry, removeModelFromRegistery, resolveModelClass, resolveModelName, tryResolveModelClass, verifyRegisteredRelations } from "./model/register-model.mjs";
|
|
37
|
+
import { ModelRef, RegisterModel, RegisterModelOptions, cleanupModelsRegistery, getAllModelsFromRegistry, getModelFromRegistry, registerModelInRegistry, removeModelFromRegistery, requireModelClass, resolveModelClass, resolveModelName, tryResolveModelClass, verifyRegisteredRelations } from "./model/register-model.mjs";
|
|
37
38
|
import { BelongsTo, BelongsToMany, HasMany, HasOne, RELATION_METADATA_KEY } from "./model/relation-decorators.mjs";
|
|
38
39
|
import { DatabaseRemover } from "./remover/database-remover.mjs";
|
|
39
40
|
import { DatabaseRestorer } from "./restorer/database-restorer.mjs";
|
|
@@ -58,21 +59,20 @@ import { ModelTransformCallback, useModelTransformer } from "./utils/database-wr
|
|
|
58
59
|
import { DefineModelOptions, ModelType, defineModel } from "./utils/define-model.mjs";
|
|
59
60
|
import { onceConnected, onceDisconnected } from "./utils/once-connected.mjs";
|
|
60
61
|
import { MigrationRecord, MigrationResult, MigrationRunnerOptions, MigrationStatus, RollbackOptions, RunMigrationsOptions } from "./migration/types.mjs";
|
|
61
|
-
import { MigrationRunner, migrationRunner } from "./migration/migration-runner.mjs";
|
|
62
|
+
import { MigrationRunner, inferMigrationName, migrationRunner } from "./migration/migration-runner.mjs";
|
|
62
63
|
import { CreateDatabaseResult, DropAllTablesResult, createDatabase, dropAllTables } from "./operations/database.mjs";
|
|
63
64
|
import { ExportMigrationsSQLOptions, PendingMigration, RollbackMigrationsOptions, exportMigrationsSQL, freshMigrate, listExecutedMigrations, listPendingMigrations, rollbackMigrations, runMigrations } from "./operations/migrations.mjs";
|
|
64
65
|
import { MongoMigrationDriver } from "./drivers/mongodb/mongodb-migration-driver.mjs";
|
|
65
66
|
import { SqlDialectContract } from "./drivers/sql/sql-dialect.contract.mjs";
|
|
66
67
|
import { SqlAggregateFunction, SqlDeleteOperation, SqlGroupClause, SqlHavingClause, SqlInsertOperation, SqlJoinClause, SqlJoinType, SqlOrderClause, SqlQueryConfig, SqlQueryResult, SqlSelectClause, SqlUpdateOperation, SqlWhereOperation, SqlWhereType } from "./drivers/sql/sql-types.mjs";
|
|
67
|
-
import { PostgresDialect } from "./drivers/postgres/postgres-dialect.mjs";
|
|
68
|
+
import { PostgresDialect, escapeSqlLiteral } from "./drivers/postgres/postgres-dialect.mjs";
|
|
68
69
|
import { PostgresConnectionConfig, PostgresCopyOptions, PostgresIsolationLevel, PostgresNotification, PostgresOperation, PostgresPoolConfig, PostgresQueryResult, PostgresTransactionOptions, PostgresWhereClause } from "./drivers/postgres/types.mjs";
|
|
69
70
|
import { PostgresDriver, buildPostgresPoolConfig } from "./drivers/postgres/postgres-driver.mjs";
|
|
70
71
|
import { PostgresBlueprint } from "./drivers/postgres/postgres-blueprint.mjs";
|
|
71
72
|
import { PostgresMigrationDriver } from "./drivers/postgres/postgres-migration-driver.mjs";
|
|
72
73
|
import { PostgresQueryBuilder } from "./drivers/postgres/postgres-query-builder.mjs";
|
|
73
74
|
import { PostgresOperationType, PostgresParserOperation, PostgresParserOptions, PostgresQueryParser } from "./drivers/postgres/postgres-query-parser.mjs";
|
|
74
|
-
import { PostgresSyncAdapter } from "./drivers/postgres/postgres-sync-adapter.mjs";
|
|
75
75
|
import { MongoClientOptions, TransactionOptions } from "mongodb";
|
|
76
|
-
export { $agg, $expr, AggregateExpression, AggregateFunction, AlterSchema, ArithmeticExpression, AtomicUpdate, AtomicUpdateOptions, type BaseQueryRuleOptions, type BaseUniqueRuleOptions, BelongsTo, BelongsToMany, type BelongsToManyOptions, type BelongsToOptions, BuildUpdateOperationsResult, type ChildModel, ChunkCallback, ColumnBuilder, ColumnDefinition, ColumnExpression, ColumnExpressionInput, ColumnExpressionType, ColumnMap, ColumnRefExpression, ColumnType, ConnectionOptions, CreateDatabaseOptions, CreateDatabaseResult, CursorPaginationOptions, CursorPaginationResult, DEFAULT_MAX_SYNC_DEPTH, DataSource, DataSourceOptions, DataSourceRegistryEvent, DataSourceRegistryListener, DatabaseDirtyTracker, DatabaseDriver, DatabaseRemover, DatabaseRestorer, DatabaseWriter, DatabaseWriterValidationError, DefineModelOptions, DeleteStrategy, DetachedColumnBuilder, DriverAtomicUpdateOptions, DriverContract, DriverEvent, DriverEventListener, DriverQuery, DriverTransactionContract, DropAllTablesResult, DropDatabaseOptions, type EmbedKey, type ExistsRuleOptions, ExportMigrationsSQLOptions, FindOneAndUpdateOptions, ForeignKeyBuilder, ForeignKeyDefinition, FullTextIndexOptions, GenerateIdOptions, GeoIndexOptions, type GlobalScopeDefinition, type GlobalScopeOptions, GroupByInput, HasMany, type HasManyOptions, HasOne, type HasOneOptions, HavingInput, IdGeneratorContract, IndexDefinition, IndexEntry, InsertResult, JoinOptions, LeanDocument, LiteralExpression, type LoadedRelationResult, type LoadedRelationsMap, type LocalScopeCallback, LockForUpdateOptions, Migration, MigrationAlterOptions, MigrationConstructor, MigrationContract, MigrationCreateOptions, MigrationDefaults, MigrationDriverContract, MigrationDriverFactory, type MigrationRecord, type MigrationResult, MigrationRunner, type MigrationRunnerOptions, type MigrationStatus, MissingDataSourceError, Model, ModelDefaultConfig, ModelDefaults, ModelEventListener, ModelEventName, ModelEvents, ModelRef, type ModelSchema, type ModelSnapshot, type ModelSyncConfig, type ModelSyncContract, ModelSyncOperation, type ModelSyncOperationContract, ModelTransformCallback, ModelType, type MongoClientOptions, MongoDbDriver, MongoDriverOptions, MongoIdGenerator, MongoMigrationDriver, MongoQueryBuilder, MongoSyncAdapter, NamingConvention, OnDeletedEventContext, Operation, OperationType, OrderDirection, PaginationOptions, PaginationResult, PendingMigration, PendingOperation, PipelineStage, type PivotData, type PivotIds, PivotOperations, PostgresBlueprint, PostgresConnectionConfig, PostgresCopyOptions, PostgresDialect, PostgresDriver, PostgresIsolationLevel, PostgresMigrationDriver, PostgresNotification, PostgresOperation, PostgresOperationType, PostgresParserOperation, PostgresParserOptions, PostgresPoolConfig, PostgresQueryBuilder, PostgresQueryParser, PostgresQueryResult,
|
|
76
|
+
export { $agg, $expr, AggregateExpression, AggregateFunction, AlterSchema, ArithmeticExpression, AtomicUpdate, AtomicUpdateOptions, type BaseQueryRuleOptions, type BaseUniqueRuleOptions, BelongsTo, BelongsToMany, type BelongsToManyOptions, type BelongsToOptions, BuildUpdateOperationsResult, type ChildModel, ChunkCallback, ColumnBuilder, ColumnDefinition, ColumnExpression, ColumnExpressionInput, ColumnExpressionType, ColumnMap, ColumnRefExpression, ColumnType, ConnectionOptions, CreateDatabaseOptions, CreateDatabaseResult, CursorPaginationOptions, CursorPaginationResult, DEFAULT_MAX_SYNC_DEPTH, DataSource, DataSourceOptions, DataSourceRegistryEvent, DataSourceRegistryListener, DatabaseDirtyTracker, DatabaseDriver, DatabaseRemover, DatabaseRestorer, DatabaseWriter, DatabaseWriterValidationError, DefineModelOptions, DeleteStrategy, DetachedColumnBuilder, DriverAtomicUpdateOptions, DriverContract, DriverEvent, DriverEventListener, DriverQuery, DriverTransactionContract, DropAllTablesResult, DropDatabaseOptions, type EmbedKey, type ExistsRuleOptions, ExportMigrationsSQLOptions, FindOneAndUpdateOptions, ForeignKeyBuilder, ForeignKeyDefinition, FullTextIndexOptions, GenerateIdOptions, GeoIndexOptions, type GlobalScopeDefinition, type GlobalScopeOptions, GroupByInput, HasMany, type HasManyOptions, HasOne, type HasOneOptions, HavingInput, IdGeneratorContract, IndexDefinition, IndexEntry, InsertResult, JoinOptions, LeanDocument, LiteralExpression, type LoadedRelationResult, type LoadedRelationsMap, type LocalScopeCallback, LockForUpdateOptions, Migration, MigrationAlterOptions, MigrationConstructor, MigrationContract, MigrationCreateOptions, MigrationDefaults, MigrationDriverContract, MigrationDriverFactory, type MigrationRecord, type MigrationResult, MigrationRunner, type MigrationRunnerOptions, type MigrationStatus, MigrationStep, MissingDataSourceError, Model, ModelDefaultConfig, ModelDefaults, ModelEventListener, ModelEventName, ModelEvents, ModelRef, type ModelSchema, type ModelSnapshot, type ModelSyncConfig, type ModelSyncContract, ModelSyncOperation, type ModelSyncOperationContract, ModelTransformCallback, ModelType, type MongoClientOptions, MongoDbDriver, MongoDriverOptions, MongoIdGenerator, MongoMigrationDriver, MongoQueryBuilder, MongoSyncAdapter, NamingConvention, OnDeletedEventContext, Operation, OperationType, OrderDirection, PaginationOptions, PaginationResult, PendingMigration, PendingOperation, PipelineStage, type PivotData, type PivotIds, PivotOperations, PostgresBlueprint, PostgresConnectionConfig, PostgresCopyOptions, PostgresDialect, PostgresDriver, PostgresIsolationLevel, PostgresMigrationDriver, PostgresNotification, PostgresOperation, PostgresOperationType, PostgresParserOperation, PostgresParserOptions, PostgresPoolConfig, PostgresQueryBuilder, PostgresQueryParser, PostgresQueryResult, PostgresTransactionOptions, PostgresWhereClause, QueryBuilderContract, RELATION_METADATA_KEY, RawColumnExpression, RawExpression, RawQueryResult, RegisterModel, RegisterModelOptions, type RelationConstraintCallback, type RelationConstraints, RelationDefaults, type RelationDefinition, type RelationDefinitions, RelationHydrator, RelationLoader, type RelationType, RemoverContract, RemoverOptions, RemoverResult, RestorerContract, RestorerOptions, RestorerResult, RollbackMigrationsOptions, type RollbackOptions, type RunMigrationsOptions, type ScopeTiming, type SerializedRelation, SqlAggregateFunction, SqlDeleteOperation, SqlDialectContract, SqlGroupClause, SqlHavingClause, SqlInsertOperation, SqlJoinClause, SqlJoinType, SqlOrderClause, SqlQueryConfig, SqlQueryResult, SqlSelectClause, SqlUpdateOperation, SqlWhereOperation, SqlWhereType, StrictMode, SyncAdapterContract, type SyncConfig, type SyncContext, SyncContextManager, type SyncEventPayload, SyncInstruction, type SyncInstructionOptions, SyncManager, type SyncResult, type TableIndexInformation, TransactionContext, type TransactionOptions, TransactionRollbackError, UndefinedWhereValueError, UniqueEntry, type UniqueRuleOptions, UnsafeFilterError, UnsafeRawExpressionError, UnsupportedLeanOperationError, UnsupportedQueryOperationError, UnsupportedUpdateOperationError, UnwindOptions, UpdateOperations, UpdatePipeline, UpdateResult, UuidStrategy, VectorIndexOptions, WhereCallback, WhereObject, WhereOperator, WriterContract, WriterOptions, WriterResult, afterCommit, arrayBigInt, arrayBoolean, arrayDate, arrayDecimal, arrayFloat, arrayInt, arrayJson, arrayText, arrayTimestamp, arrayUuid, assertDefined, bigInt, bigInteger, binary, blobCol, boolCol as bool, boolCol, buildPostgresPoolConfig, char, cleanupModelsRegistery, connectToDatabase, createDatabase, createPivotOperations, dataSourceRegistry, databaseDataSourceContext, databaseTransactionContext, date, dateTime, decimal, defineModel, double, dropAllTables, enumCol, escapeRegex, escapeSqlLiteral, exportMigrationsSQL, float, freshMigrate, geometry, getAllModelsFromRegistry, getDatabaseDriver, getModelFromRegistry, globalModelEvents, inferMigrationName, int, integer, ipAddress, isAggregateExpression, isColumnExpression, isMongoDBDriverLoaded, json, likePatternToRegexSource, lineString, listExecutedMigrations, listPendingMigrations, longText, macAddress, mediumText, migrate, migrationRunner, modelSync, objectCol, onceConnected, onceDisconnected, point, polygon, registerModelInRegistry, removeModelFromRegistery, requireModelClass, resolveLikePattern, resolveModelClass, resolveModelName, rollbackMigrations, runMigrations, sanitizeFilter, sanitizeFilterValue, setCol, smallInt, smallInteger, string, text, time, timestamp, tinyInt, tinyInteger, toColumnExpression, transaction, tryResolveModelClass, ulid, useModelTransformer, uuid, vector, verifyRegisteredRelations, year };
|
|
77
77
|
import "./validation/plugins/database-rules-plugin.mjs";
|
|
78
78
|
import "./validation/plugins/embed-validator-plugin.mjs";
|
package/esm/index.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { databaseDataSourceContext } from "./context/database-data-source-context.mjs";
|
|
2
2
|
import { databaseTransactionContext } from "./context/database-transaction-context.mjs";
|
|
3
|
+
import { afterCommit } from "./transactions/after-commit.mjs";
|
|
3
4
|
import { DataSource } from "./data-source/data-source.mjs";
|
|
4
5
|
import { MissingDataSourceError } from "./errors/missing-data-source.error.mjs";
|
|
5
6
|
import { dataSourceRegistry } from "./data-source/data-source-registry.mjs";
|
|
@@ -13,7 +14,7 @@ import { UnsupportedUpdateOperationError } from "./errors/unsupported-update-ope
|
|
|
13
14
|
import { DatabaseDirtyTracker } from "./database-dirty-tracker.mjs";
|
|
14
15
|
import { ModelEvents, globalModelEvents } from "./events/model-events.mjs";
|
|
15
16
|
import { BelongsTo, BelongsToMany, HasMany, HasOne, RELATION_METADATA_KEY } from "./model/relation-decorators.mjs";
|
|
16
|
-
import { RegisterModel, cleanupModelsRegistery, getAllModelsFromRegistry, getModelFromRegistry, registerModelInRegistry, removeModelFromRegistery, resolveModelClass, resolveModelName, tryResolveModelClass, verifyRegisteredRelations } from "./model/register-model.mjs";
|
|
17
|
+
import { RegisterModel, cleanupModelsRegistery, getAllModelsFromRegistry, getModelFromRegistry, registerModelInRegistry, removeModelFromRegistery, requireModelClass, resolveModelClass, resolveModelName, tryResolveModelClass, verifyRegisteredRelations } from "./model/register-model.mjs";
|
|
17
18
|
import { RelationLoader } from "./relations/relation-loader.mjs";
|
|
18
19
|
import { DEFAULT_MAX_SYNC_DEPTH, SyncContextManager } from "./sync/sync-context.mjs";
|
|
19
20
|
import { SyncManager } from "./sync/sync-manager.mjs";
|
|
@@ -38,11 +39,10 @@ import { MongoQueryBuilder } from "./drivers/mongodb/mongodb-query-builder.mjs";
|
|
|
38
39
|
import { MongoSyncAdapter } from "./drivers/mongodb/mongodb-sync-adapter.mjs";
|
|
39
40
|
import { MongoDbDriver, isMongoDBDriverLoaded } from "./drivers/mongodb/mongodb-driver.mjs";
|
|
40
41
|
import { PostgresBlueprint } from "./drivers/postgres/postgres-blueprint.mjs";
|
|
41
|
-
import { PostgresDialect } from "./drivers/postgres/postgres-dialect.mjs";
|
|
42
|
+
import { PostgresDialect, escapeSqlLiteral } from "./drivers/postgres/postgres-dialect.mjs";
|
|
42
43
|
import { PostgresMigrationDriver } from "./drivers/postgres/postgres-migration-driver.mjs";
|
|
43
44
|
import { PostgresQueryParser } from "./drivers/postgres/postgres-query-parser.mjs";
|
|
44
45
|
import { PostgresQueryBuilder } from "./drivers/postgres/postgres-query-builder.mjs";
|
|
45
|
-
import { PostgresSyncAdapter } from "./drivers/postgres/postgres-sync-adapter.mjs";
|
|
46
46
|
import { PostgresDriver, buildPostgresPoolConfig } from "./drivers/postgres/postgres-driver.mjs";
|
|
47
47
|
import "./drivers/postgres/index.mjs";
|
|
48
48
|
import { connectToDatabase, getDatabaseDriver, transaction } from "./utils/connect-to-database.mjs";
|
|
@@ -53,10 +53,10 @@ import { ColumnBuilder } from "./migration/column-builder.mjs";
|
|
|
53
53
|
import { ForeignKeyBuilder } from "./migration/foreign-key-builder.mjs";
|
|
54
54
|
import { DetachedColumnBuilder, arrayBigInt, arrayBoolean, arrayDate, arrayDecimal, arrayFloat, arrayInt, arrayJson, arrayText, arrayTimestamp, arrayUuid, bigInt, bigInteger, binary, blobCol, boolCol, char, date, dateTime, decimal, double, enumCol, float, geometry, int, integer, ipAddress, json, lineString, longText, macAddress, mediumText, objectCol, point, polygon, setCol, smallInt, smallInteger, string, text, time, timestamp, tinyInt, tinyInteger, ulid, uuid, vector, year } from "./migration/column-helpers.mjs";
|
|
55
55
|
import { Migration, migrate } from "./migration/migration.mjs";
|
|
56
|
-
import { MigrationRunner, migrationRunner } from "./migration/migration-runner.mjs";
|
|
56
|
+
import { MigrationRunner, inferMigrationName, migrationRunner } from "./migration/migration-runner.mjs";
|
|
57
57
|
import "./migration/index.mjs";
|
|
58
58
|
import { createDatabase, dropAllTables } from "./operations/database.mjs";
|
|
59
59
|
import { exportMigrationsSQL, freshMigrate, listExecutedMigrations, listPendingMigrations, rollbackMigrations, runMigrations } from "./operations/migrations.mjs";
|
|
60
60
|
import "./operations/index.mjs";
|
|
61
61
|
|
|
62
|
-
export { $agg, $expr, BelongsTo, BelongsToMany, ColumnBuilder, DEFAULT_MAX_SYNC_DEPTH, DataSource, DatabaseDirtyTracker, DatabaseRemover, DatabaseRestorer, DatabaseWriter, DatabaseWriterValidationError, DetachedColumnBuilder, ForeignKeyBuilder, HasMany, HasOne, Migration, MigrationRunner, MissingDataSourceError, Model, ModelEvents, ModelSyncOperation, MongoDbDriver, MongoIdGenerator, MongoMigrationDriver, MongoQueryBuilder, MongoSyncAdapter, PivotOperations, PostgresBlueprint, PostgresDialect, PostgresDriver, PostgresMigrationDriver, PostgresQueryBuilder, PostgresQueryParser,
|
|
62
|
+
export { $agg, $expr, BelongsTo, BelongsToMany, ColumnBuilder, DEFAULT_MAX_SYNC_DEPTH, DataSource, DatabaseDirtyTracker, DatabaseRemover, DatabaseRestorer, DatabaseWriter, DatabaseWriterValidationError, DetachedColumnBuilder, ForeignKeyBuilder, HasMany, HasOne, Migration, MigrationRunner, MissingDataSourceError, Model, ModelEvents, ModelSyncOperation, MongoDbDriver, MongoIdGenerator, MongoMigrationDriver, MongoQueryBuilder, MongoSyncAdapter, PivotOperations, PostgresBlueprint, PostgresDialect, PostgresDriver, PostgresMigrationDriver, PostgresQueryBuilder, PostgresQueryParser, RELATION_METADATA_KEY, RegisterModel, RelationHydrator, RelationLoader, SyncContextManager, SyncManager, TransactionRollbackError, UndefinedWhereValueError, UnsafeFilterError, UnsafeRawExpressionError, UnsupportedLeanOperationError, UnsupportedQueryOperationError, UnsupportedUpdateOperationError, afterCommit, arrayBigInt, arrayBoolean, arrayDate, arrayDecimal, arrayFloat, arrayInt, arrayJson, arrayText, arrayTimestamp, arrayUuid, assertDefined, bigInt, bigInteger, binary, blobCol, boolCol as bool, boolCol, buildPostgresPoolConfig, char, cleanupModelsRegistery, connectToDatabase, createDatabase, createPivotOperations, dataSourceRegistry, databaseDataSourceContext, databaseTransactionContext, date, dateTime, decimal, defineModel, double, dropAllTables, enumCol, escapeRegex, escapeSqlLiteral, exportMigrationsSQL, float, freshMigrate, geometry, getAllModelsFromRegistry, getDatabaseDriver, getModelFromRegistry, globalModelEvents, inferMigrationName, int, integer, ipAddress, isAggregateExpression, isColumnExpression, isMongoDBDriverLoaded, json, likePatternToRegexSource, lineString, listExecutedMigrations, listPendingMigrations, longText, macAddress, mediumText, migrate, migrationRunner, modelSync, objectCol, onceConnected, onceDisconnected, point, polygon, registerModelInRegistry, removeModelFromRegistery, requireModelClass, resolveLikePattern, resolveModelClass, resolveModelName, rollbackMigrations, runMigrations, sanitizeFilter, sanitizeFilterValue, setCol, smallInt, smallInteger, string, text, time, timestamp, tinyInt, tinyInteger, toColumnExpression, transaction, tryResolveModelClass, ulid, useModelTransformer, uuid, vector, verifyRegisteredRelations, year };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"column-builder.d.mts","names":[],"sources":["../../../../../../../cascade/src/migration/column-builder.ts"],"mappings":";;;;;AAKgD;;KAM3C,aAAA;EACH,eAAA,CAAgB,KAAA;IAAS,OAAA;IAAmB,MAAA;EAAA;EAC5C,sBAAA,CAAuB,EAAA,EAAI,oBAAA;EAC3B,qBAAA,EAAuB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CAAM,UAAA;;;;;;;;;;;;;EAiBN,KAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;EAmCA,UAAA,CAAW,YAAA;IAAyB,KAAA;EAAA;;;;;;;;;;;;;;EA2BpC,EAAA,CAAG,MAAA;;;;;;;;;;;;;;EAoBH,QAAA,CAAS,MAAA,EAAQ,oBAAA;;;;;;;;;;;;;;EAoBjB,QAAA,CAAS,MAAA,EAAQ,oBAAA;;;;;;;;;;;;;EAmBjB,UAAA;;;;;;;;;;;;;;;;;;;;;EAgCA,MAAA;;;;EAsCA,MAAA;;;;;;;;;;;;;;;;;;;;;;;EA8BA,WAAA,CAAY,UAAA;;;;;;;;EAYZ,MAAA;;;;;;;;EAiBA,OAAA;;;;;;;;EAqBA,aAAA,IAAiB,gBAAA;AAAA"}
|
|
@@ -441,8 +441,8 @@ var ColumnBuilder = class {
|
|
|
441
441
|
*/
|
|
442
442
|
change() {
|
|
443
443
|
const operations = this.migration.pendingOperations;
|
|
444
|
-
const
|
|
445
|
-
if (
|
|
444
|
+
const addIndex = operations.findIndex((op) => op.type === "addColumn" && op.payload === this.definition);
|
|
445
|
+
if (addIndex !== -1) operations.splice(addIndex, 1);
|
|
446
446
|
let pendingFkOp;
|
|
447
447
|
if (this.fkDefinition) {
|
|
448
448
|
const tail = operations[operations.length - 1];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"column-builder.mjs","names":[],"sources":["../../../../../../../cascade/src/migration/column-builder.ts"],"sourcesContent":["import type {\n ColumnDefinition,\n ColumnType,\n ForeignKeyDefinition,\n VectorIndexOptions,\n} from \"../contracts/migration-driver.contract\";\n\n/**\n * Reference to the Migration type to avoid circular imports.\n * The actual type is injected at runtime.\n */\ntype MigrationLike = {\n addPendingIndex(index: { columns: string[]; unique?: boolean }): void;\n addForeignKeyOperation(fk: ForeignKeyDefinition): void;\n addPendingVectorIndex?(column: string, options: Omit<VectorIndexOptions, \"column\">): void;\n};\n\n/**\n * Mutable foreign key definition being built via ColumnBuilder.\n */\ninterface MutableForeignKeyDefinition {\n name?: string;\n column: string;\n referencesTable: string;\n referencesColumn: string;\n onDelete: ForeignKeyDefinition[\"onDelete\"];\n onUpdate: ForeignKeyDefinition[\"onUpdate\"];\n}\n\n/**\n * Fluent builder for defining column properties.\n *\n * Allows chaining modifiers like `.nullable()`, `.unique()`, `.default()`.\n * Each column builder is bound to a parent migration and accumulates\n * the column definition through method chains.\n *\n * @example\n * ```typescript\n * this.string(\"email\")\n * .nullable()\n * .unique()\n * .default(\"guest@example.com\");\n * ```\n *\n * @example\n * ```typescript\n * this.integer(\"age\")\n * .unsigned()\n * .comment(\"User's age in years\");\n * ```\n */\nexport class ColumnBuilder {\n /** Mutable column definition being accumulated */\n private readonly definition: ColumnDefinition;\n\n /** Mutable foreign key definition, set when .references() is called */\n private fkDefinition?: MutableForeignKeyDefinition;\n\n /** Temporary storage for generated expression before .stored() or .virtual() is called */\n private generatedExpression?: string;\n\n /**\n * Create a new column builder.\n *\n * @param migration - Parent migration instance for index registration\n * @param name - Column name\n * @param type - Column data type\n * @param options - Optional initial configuration\n */\n public constructor(\n private readonly migration: MigrationLike,\n name: string,\n type: ColumnType,\n options: Partial<\n Pick<ColumnDefinition, \"length\" | \"precision\" | \"scale\" | \"dimensions\" | \"values\">\n > = {},\n ) {\n this.definition = {\n name,\n type,\n nullable: false,\n ...options,\n };\n }\n\n // ============================================================================\n // NULLABILITY\n // ============================================================================\n\n /**\n * Mark column as nullable (allows NULL values).\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.string(\"middleName\").nullable();\n * ```\n */\n public nullable(): this {\n this.definition.nullable = true;\n return this;\n }\n\n /**\n * Mark column as not nullable (disallows NULL values).\n *\n * This is the default, but can be used for clarity.\n *\n * @returns This builder for chaining\n */\n public notNullable(): this {\n this.definition.nullable = false;\n return this;\n }\n\n // ============================================================================\n // DEFAULT VALUES\n // ============================================================================\n\n /**\n * Set default value for the column as a raw SQL expression.\n *\n * The value will be used as-is in the SQL statement without escaping.\n * Use this for database functions and expressions.\n *\n * @param value - Default value (SQL expression, number, or boolean)\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.uuid(\"id\").default(\"gen_random_uuid()\");\n * this.timestamp(\"created_at\").default(\"NOW()\");\n * this.integer(\"version\").default(1);\n * this.boolean(\"is_active\").default(true);\n * ```\n */\n public default(value: string | number | boolean): this {\n this.definition.defaultValue = value;\n this.definition.isRawDefault = true;\n return this;\n }\n\n /**\n * Set default value for the column as a literal string.\n *\n * The value will be properly escaped and quoted in the SQL statement.\n * Use this for literal string values, not SQL expressions.\n *\n * @param value - Default string value (will be escaped)\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.text(\"status\").defaultString(\"active\");\n * this.text(\"greeting\").defaultString(\"Hello, World!\");\n * ```\n */\n public defaultString(value: string): this {\n this.definition.defaultValue = value;\n this.definition.isRawDefault = false;\n return this;\n }\n\n /**\n * Set default value to the current timestamp.\n *\n * Database-agnostic. Generates NOW() / CURRENT_TIMESTAMP / GETDATE() based on driver.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.timestamp(\"created_at\").useCurrent();\n * ```\n */\n public useCurrent(): this {\n this.definition.defaultValue = { __type: \"CURRENT_TIMESTAMP\" };\n return this;\n }\n\n /**\n * Set column to update to current timestamp on row update.\n *\n * MySQL only. Other databases ignore this.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.timestamp(\"updated_at\").useCurrent().useCurrentOnUpdate();\n * ```\n */\n public useCurrentOnUpdate(): this {\n this.definition.onUpdateCurrent = true;\n return this;\n }\n\n // ============================================================================\n // INDEXES\n // ============================================================================\n\n /**\n * Add unique constraint/index on this column.\n *\n * Registers a pending unique index with the parent migration.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.string(\"email\").unique();\n * ```\n */\n public unique(): this {\n this.migration.addPendingIndex({\n columns: [this.definition.name],\n unique: true,\n });\n return this;\n }\n\n /**\n * Add regular index on this column.\n *\n * Registers a pending index with the parent migration.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.string(\"email\").index();\n * ```\n */\n public index(): this {\n this.migration.addPendingIndex({\n columns: [this.definition.name],\n });\n return this;\n }\n\n /**\n * Add a vector search index on this column.\n *\n * Registers a pending vector index with the parent migration.\n *\n * @param options - Vector index options\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.vector(1536).vectorIndex({ similarity: \"cosine\" });\n * ```\n */\n public vectorIndex(options: Omit<VectorIndexOptions, \"dimensions\"> = {}): this {\n if (this.migration.addPendingVectorIndex) {\n this.migration.addPendingVectorIndex(this.definition.name, {\n ...options,\n dimensions: this.definition.dimensions || 0,\n });\n }\n return this;\n }\n\n // ============================================================================\n // PRIMARY KEY & AUTO INCREMENT\n // ============================================================================\n\n /**\n * Mark as primary key.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.integer(\"id\").primary();\n * ```\n */\n public primary(): this {\n this.definition.primary = true;\n return this;\n }\n\n /**\n * Mark as auto-increment (numeric types only).\n *\n * SQL databases will use native AUTO_INCREMENT/SERIAL.\n * NoSQL databases ignore this.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.integer(\"id\").primary().autoIncrement();\n * ```\n */\n public autoIncrement(): this {\n this.definition.autoIncrement = true;\n return this;\n }\n\n // ============================================================================\n // NUMERIC MODIFIERS\n // ============================================================================\n\n /**\n * Mark as unsigned (numeric types only).\n *\n * Disallows negative values and doubles the positive range.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.integer(\"age\").unsigned();\n * ```\n */\n public unsigned(): this {\n this.definition.unsigned = true;\n return this;\n }\n\n // ============================================================================\n // METADATA\n // ============================================================================\n\n /**\n * Add comment/description to column.\n *\n * Stored as column metadata in the database.\n *\n * @param text - Comment text\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.string(\"sku\").comment(\"Stock Keeping Unit code\");\n * ```\n */\n public comment(text: string): this {\n this.definition.comment = text;\n return this;\n }\n\n // ============================================================================\n // CONSTRAINTS\n // ============================================================================\n\n /**\n * Add a CHECK constraint scoped to this column.\n *\n * @param expression - SQL CHECK expression (can reference the column by name)\n * @param name - Constraint name (defaults to `check_<column>`)\n * @returns This builder for chaining\n */\n public check(expression: string, name?: string): this {\n this.definition.checkConstraint = {\n expression,\n name: name ?? `check_${this.definition.name}`,\n };\n return this;\n }\n\n // ============================================================================\n // COLUMN POSITIONING (MySQL/MariaDB only)\n // ============================================================================\n\n /**\n * Position this column after another column.\n *\n * MySQL/MariaDB only. Ignored by PostgreSQL and NoSQL drivers.\n *\n * @param columnName - Column to position after\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.string(\"middle_name\").after(\"first_name\");\n * ```\n */\n public after(columnName: string): this {\n this.definition.after = columnName;\n return this;\n }\n\n /**\n * Position this column as the first column in the table.\n *\n * MySQL/MariaDB only. Ignored by PostgreSQL and NoSQL drivers.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.integer(\"id\").primary().first();\n * ```\n */\n public first(): this {\n this.definition.first = true;\n return this;\n }\n\n // ============================================================================\n // FOREIGN KEY\n // ============================================================================\n\n /**\n * Declare a foreign key constraint on this column.\n *\n * Accepts either a raw table-name string or a Model class (anything with a\n * static `table` property). Using a Model class is preferred — it is\n * type-safe and automatically tracks table renames.\n *\n * Pushes an `addForeignKey` operation immediately using a mutable reference —\n * subsequent `.on()`, `.onDelete()`, `.onUpdate()` calls mutate the same\n * definition that is already queued, so no `.add()` terminator is needed.\n *\n * Referenced column defaults to `\"id\"` — use `.on()` to override.\n *\n * @param tableOrModel - Referenced table name OR a Model class with a static `table` property\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * // Preferred — model class reference (type-safe, rename-proof)\n * this.uuid(\"organization_id\").references(Organization).onDelete(\"cascade\");\n *\n * // Also supported — raw table string\n * this.uuid(\"organization_id\").references(\"organizations\").onDelete(\"cascade\");\n * this.uuid(\"organization_id\").references(Organization.table).onDelete(\"cascade\");\n * ```\n */\n public references(tableOrModel: string | { table: string }): this {\n const tableName = typeof tableOrModel === \"string\" ? tableOrModel : tableOrModel.table;\n\n this.fkDefinition = {\n column: this.definition.name,\n referencesTable: tableName,\n referencesColumn: \"id\",\n onDelete: \"restrict\",\n onUpdate: \"restrict\",\n };\n this.migration.addForeignKeyOperation(this.fkDefinition as ForeignKeyDefinition);\n return this;\n }\n\n /**\n * Set the referenced column for the foreign key.\n *\n * Only meaningful after `.references()`. Defaults to `\"id\"` if omitted.\n *\n * @param column - Referenced column name\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.integer(\"user_id\").references(\"users\").on(\"custom_id\");\n * ```\n */\n public on(column: string): this {\n if (this.fkDefinition) {\n this.fkDefinition.referencesColumn = column;\n }\n return this;\n }\n\n /**\n * Set the ON DELETE action for the foreign key.\n *\n * Only meaningful after `.references()`.\n *\n * @param action - Action when the referenced row is deleted\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.integer(\"user_id\").references(\"users\").onDelete(\"cascade\");\n * ```\n */\n public onDelete(action: ForeignKeyDefinition[\"onDelete\"]): this {\n if (this.fkDefinition) {\n this.fkDefinition.onDelete = action;\n }\n return this;\n }\n\n /**\n * Set the ON UPDATE action for the foreign key.\n *\n * Only meaningful after `.references()`.\n *\n * @param action - Action when the referenced row's key is updated\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.integer(\"user_id\").references(\"users\").onUpdate(\"cascade\");\n * ```\n */\n public onUpdate(action: ForeignKeyDefinition[\"onUpdate\"]): this {\n if (this.fkDefinition) {\n this.fkDefinition.onUpdate = action;\n }\n return this;\n }\n\n /**\n * Shorthand for `.onDelete(\"cascade\").onUpdate(\"cascade\")`.\n *\n * Only meaningful after `.references()`.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.integer(\"user_id\").references(\"users\").cascadeAll();\n * ```\n */\n public cascadeAll(): this {\n if (this.fkDefinition) {\n this.fkDefinition.onDelete = \"cascade\";\n this.fkDefinition.onUpdate = \"cascade\";\n }\n return this;\n }\n\n // ============================================================================\n // COLUMN MODIFICATION\n // ============================================================================\n\n /**\n * Mark this column definition as a modification of an existing column.\n *\n * Pushes a `modifyColumn` operation instead of `addColumn`.\n * This method breaks the builder chain and returns the parent migration.\n *\n * @returns The parent migration instance (breaks builder chain)\n *\n * @example\n * ```typescript\n * // Make email nullable\n * this.string(\"email\").nullable().change();\n *\n * // Increase length\n * this.string(\"name\", 255).change();\n *\n * // Change type\n * this.text(\"description\").change();\n * ```\n */\n public change(): unknown {\n const operations = (this.migration as any).pendingOperations;\n\n // Remove the addColumn pushed by the column type method (e.g. uuid(), string())\n const lastOp = operations[operations.length - 1];\n if (lastOp?.type === \"addColumn\" && lastOp.payload === this.definition) {\n operations.pop();\n }\n\n // If .references() was called before .change(), the addForeignKey op is now\n // last in the queue. We must pop it, push modifyColumn first, then re-push\n // the FK — because SQL requires: ALTER COLUMN (type change) → ADD CONSTRAINT (FK).\n let pendingFkOp: (typeof operations)[number] | undefined;\n if (this.fkDefinition) {\n const tail = operations[operations.length - 1];\n if (tail?.type === \"addForeignKey\" && tail.payload === this.fkDefinition) {\n pendingFkOp = operations.pop();\n }\n }\n\n // Push modifyColumn — it must precede the FK constraint\n operations.push({ type: \"modifyColumn\", payload: this.definition });\n\n // Re-queue the FK after the column modification\n if (pendingFkOp) {\n operations.push(pendingFkOp);\n }\n\n return this.migration;\n }\n\n /**\n * @alias change\n */\n public modify(): unknown {\n return this.change();\n }\n\n // ============================================================================\n // GENERATED COLUMNS\n // ============================================================================\n\n /**\n * Mark this column as a generated column with the given SQL expression.\n *\n * Must be followed by `.stored()` or `.virtual()` to specify storage type.\n *\n * PostgreSQL: GENERATED ALWAYS AS (...) STORED\n * MySQL: GENERATED ALWAYS AS (...) STORED | VIRTUAL\n *\n * @param expression - SQL expression to compute the value\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.string(\"full_name\")\n * .generatedAs(\"CONCAT(first_name, ' ', last_name)\")\n * .stored();\n *\n * this.decimal(\"price_with_tax\")\n * .generatedAs(\"price * 1.2\")\n * .virtual();\n * ```\n */\n public generatedAs(expression: string): this {\n this.generatedExpression = expression;\n return this;\n }\n\n /**\n * Mark the generated column as stored (computed and persisted to disk).\n *\n * Must be called after `.generatedAs()`.\n *\n * @returns This builder for chaining\n */\n public stored(): this {\n if (this.generatedExpression) {\n this.definition.generated = {\n expression: this.generatedExpression,\n stored: true,\n };\n }\n return this;\n }\n\n /**\n * Mark the generated column as virtual (computed on read, not stored).\n *\n * Must be called after `.generatedAs()`. Not supported by PostgreSQL.\n *\n * @returns This builder for chaining\n */\n public virtual(): this {\n if (this.generatedExpression) {\n this.definition.generated = {\n expression: this.generatedExpression,\n stored: false,\n };\n }\n return this;\n }\n\n // ============================================================================\n // ACCESSOR\n // ============================================================================\n\n /**\n * Get the built column definition.\n *\n * Called internally by the Migration class to extract the final definition.\n *\n * @returns The accumulated column definition\n */\n public getDefinition(): ColumnDefinition {\n return this.definition;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmDA,IAAa,gBAAb,MAA2B;CAmBN;;CAjBnB,AAAiB;;CAGjB,AAAQ;;CAGR,AAAQ;;;;;;;;;CAUR,AAAO,YACL,AAAiB,WACjB,MACA,MACA,UAEI,CAAC,GACL;EANiB;EAOjB,KAAK,aAAa;GAChB;GACA;GACA,UAAU;GACV,GAAG;EACL;CACF;;;;;;;;;;;CAgBA,AAAO,WAAiB;EACtB,KAAK,WAAW,WAAW;EAC3B,OAAO;CACT;;;;;;;;CASA,AAAO,cAAoB;EACzB,KAAK,WAAW,WAAW;EAC3B,OAAO;CACT;;;;;;;;;;;;;;;;;;CAuBA,AAAO,QAAQ,OAAwC;EACrD,KAAK,WAAW,eAAe;EAC/B,KAAK,WAAW,eAAe;EAC/B,OAAO;CACT;;;;;;;;;;;;;;;;CAiBA,AAAO,cAAc,OAAqB;EACxC,KAAK,WAAW,eAAe;EAC/B,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EACvB,OAAO,KAAK,OAAO;CACrB;;;;;;;;;;;;;;;;;;;;;;;CA4BA,AAAO,YAAY,YAA0B;EAC3C,KAAK,sBAAsB;EAC3B,OAAO;CACT;;;;;;;;CASA,AAAO,SAAe;EACpB,IAAI,KAAK,qBACP,KAAK,WAAW,YAAY;GAC1B,YAAY,KAAK;GACjB,QAAQ;EACV;EAEF,OAAO;CACT;;;;;;;;CASA,AAAO,UAAgB;EACrB,IAAI,KAAK,qBACP,KAAK,WAAW,YAAY;GAC1B,YAAY,KAAK;GACjB,QAAQ;EACV;EAEF,OAAO;CACT;;;;;;;;CAaA,AAAO,gBAAkC;EACvC,OAAO,KAAK;CACd;AACF"}
|
|
1
|
+
{"version":3,"file":"column-builder.mjs","names":[],"sources":["../../../../../../../cascade/src/migration/column-builder.ts"],"sourcesContent":["import type {\n ColumnDefinition,\n ColumnType,\n ForeignKeyDefinition,\n VectorIndexOptions,\n} from \"../contracts/migration-driver.contract\";\n\n/**\n * Reference to the Migration type to avoid circular imports.\n * The actual type is injected at runtime.\n */\ntype MigrationLike = {\n addPendingIndex(index: { columns: string[]; unique?: boolean }): void;\n addForeignKeyOperation(fk: ForeignKeyDefinition): void;\n addPendingVectorIndex?(column: string, options: Omit<VectorIndexOptions, \"column\">): void;\n};\n\n/**\n * Mutable foreign key definition being built via ColumnBuilder.\n */\ninterface MutableForeignKeyDefinition {\n name?: string;\n column: string;\n referencesTable: string;\n referencesColumn: string;\n onDelete: ForeignKeyDefinition[\"onDelete\"];\n onUpdate: ForeignKeyDefinition[\"onUpdate\"];\n}\n\n/**\n * Fluent builder for defining column properties.\n *\n * Allows chaining modifiers like `.nullable()`, `.unique()`, `.default()`.\n * Each column builder is bound to a parent migration and accumulates\n * the column definition through method chains.\n *\n * @example\n * ```typescript\n * this.string(\"email\")\n * .nullable()\n * .unique()\n * .default(\"guest@example.com\");\n * ```\n *\n * @example\n * ```typescript\n * this.integer(\"age\")\n * .unsigned()\n * .comment(\"User's age in years\");\n * ```\n */\nexport class ColumnBuilder {\n /** Mutable column definition being accumulated */\n private readonly definition: ColumnDefinition;\n\n /** Mutable foreign key definition, set when .references() is called */\n private fkDefinition?: MutableForeignKeyDefinition;\n\n /** Temporary storage for generated expression before .stored() or .virtual() is called */\n private generatedExpression?: string;\n\n /**\n * Create a new column builder.\n *\n * @param migration - Parent migration instance for index registration\n * @param name - Column name\n * @param type - Column data type\n * @param options - Optional initial configuration\n */\n public constructor(\n private readonly migration: MigrationLike,\n name: string,\n type: ColumnType,\n options: Partial<\n Pick<ColumnDefinition, \"length\" | \"precision\" | \"scale\" | \"dimensions\" | \"values\">\n > = {},\n ) {\n this.definition = {\n name,\n type,\n nullable: false,\n ...options,\n };\n }\n\n // ============================================================================\n // NULLABILITY\n // ============================================================================\n\n /**\n * Mark column as nullable (allows NULL values).\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.string(\"middleName\").nullable();\n * ```\n */\n public nullable(): this {\n this.definition.nullable = true;\n return this;\n }\n\n /**\n * Mark column as not nullable (disallows NULL values).\n *\n * This is the default, but can be used for clarity.\n *\n * @returns This builder for chaining\n */\n public notNullable(): this {\n this.definition.nullable = false;\n return this;\n }\n\n // ============================================================================\n // DEFAULT VALUES\n // ============================================================================\n\n /**\n * Set default value for the column as a raw SQL expression.\n *\n * The value will be used as-is in the SQL statement without escaping.\n * Use this for database functions and expressions.\n *\n * @param value - Default value (SQL expression, number, or boolean)\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.uuid(\"id\").default(\"gen_random_uuid()\");\n * this.timestamp(\"created_at\").default(\"NOW()\");\n * this.integer(\"version\").default(1);\n * this.boolean(\"is_active\").default(true);\n * ```\n */\n public default(value: string | number | boolean): this {\n this.definition.defaultValue = value;\n this.definition.isRawDefault = true;\n return this;\n }\n\n /**\n * Set default value for the column as a literal string.\n *\n * The value will be properly escaped and quoted in the SQL statement.\n * Use this for literal string values, not SQL expressions.\n *\n * @param value - Default string value (will be escaped)\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.text(\"status\").defaultString(\"active\");\n * this.text(\"greeting\").defaultString(\"Hello, World!\");\n * ```\n */\n public defaultString(value: string): this {\n this.definition.defaultValue = value;\n this.definition.isRawDefault = false;\n return this;\n }\n\n /**\n * Set default value to the current timestamp.\n *\n * Database-agnostic. Generates NOW() / CURRENT_TIMESTAMP / GETDATE() based on driver.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.timestamp(\"created_at\").useCurrent();\n * ```\n */\n public useCurrent(): this {\n this.definition.defaultValue = { __type: \"CURRENT_TIMESTAMP\" };\n return this;\n }\n\n /**\n * Set column to update to current timestamp on row update.\n *\n * MySQL only. Other databases ignore this.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.timestamp(\"updated_at\").useCurrent().useCurrentOnUpdate();\n * ```\n */\n public useCurrentOnUpdate(): this {\n this.definition.onUpdateCurrent = true;\n return this;\n }\n\n // ============================================================================\n // INDEXES\n // ============================================================================\n\n /**\n * Add unique constraint/index on this column.\n *\n * Registers a pending unique index with the parent migration.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.string(\"email\").unique();\n * ```\n */\n public unique(): this {\n this.migration.addPendingIndex({\n columns: [this.definition.name],\n unique: true,\n });\n return this;\n }\n\n /**\n * Add regular index on this column.\n *\n * Registers a pending index with the parent migration.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.string(\"email\").index();\n * ```\n */\n public index(): this {\n this.migration.addPendingIndex({\n columns: [this.definition.name],\n });\n return this;\n }\n\n /**\n * Add a vector search index on this column.\n *\n * Registers a pending vector index with the parent migration.\n *\n * @param options - Vector index options\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.vector(1536).vectorIndex({ similarity: \"cosine\" });\n * ```\n */\n public vectorIndex(options: Omit<VectorIndexOptions, \"dimensions\"> = {}): this {\n if (this.migration.addPendingVectorIndex) {\n this.migration.addPendingVectorIndex(this.definition.name, {\n ...options,\n dimensions: this.definition.dimensions || 0,\n });\n }\n return this;\n }\n\n // ============================================================================\n // PRIMARY KEY & AUTO INCREMENT\n // ============================================================================\n\n /**\n * Mark as primary key.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.integer(\"id\").primary();\n * ```\n */\n public primary(): this {\n this.definition.primary = true;\n return this;\n }\n\n /**\n * Mark as auto-increment (numeric types only).\n *\n * SQL databases will use native AUTO_INCREMENT/SERIAL.\n * NoSQL databases ignore this.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.integer(\"id\").primary().autoIncrement();\n * ```\n */\n public autoIncrement(): this {\n this.definition.autoIncrement = true;\n return this;\n }\n\n // ============================================================================\n // NUMERIC MODIFIERS\n // ============================================================================\n\n /**\n * Mark as unsigned (numeric types only).\n *\n * Disallows negative values and doubles the positive range.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.integer(\"age\").unsigned();\n * ```\n */\n public unsigned(): this {\n this.definition.unsigned = true;\n return this;\n }\n\n // ============================================================================\n // METADATA\n // ============================================================================\n\n /**\n * Add comment/description to column.\n *\n * Stored as column metadata in the database.\n *\n * @param text - Comment text\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.string(\"sku\").comment(\"Stock Keeping Unit code\");\n * ```\n */\n public comment(text: string): this {\n this.definition.comment = text;\n return this;\n }\n\n // ============================================================================\n // CONSTRAINTS\n // ============================================================================\n\n /**\n * Add a CHECK constraint scoped to this column.\n *\n * @param expression - SQL CHECK expression (can reference the column by name)\n * @param name - Constraint name (defaults to `check_<column>`)\n * @returns This builder for chaining\n */\n public check(expression: string, name?: string): this {\n this.definition.checkConstraint = {\n expression,\n name: name ?? `check_${this.definition.name}`,\n };\n return this;\n }\n\n // ============================================================================\n // COLUMN POSITIONING (MySQL/MariaDB only)\n // ============================================================================\n\n /**\n * Position this column after another column.\n *\n * MySQL/MariaDB only. Ignored by PostgreSQL and NoSQL drivers.\n *\n * @param columnName - Column to position after\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.string(\"middle_name\").after(\"first_name\");\n * ```\n */\n public after(columnName: string): this {\n this.definition.after = columnName;\n return this;\n }\n\n /**\n * Position this column as the first column in the table.\n *\n * MySQL/MariaDB only. Ignored by PostgreSQL and NoSQL drivers.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.integer(\"id\").primary().first();\n * ```\n */\n public first(): this {\n this.definition.first = true;\n return this;\n }\n\n // ============================================================================\n // FOREIGN KEY\n // ============================================================================\n\n /**\n * Declare a foreign key constraint on this column.\n *\n * Accepts either a raw table-name string or a Model class (anything with a\n * static `table` property). Using a Model class is preferred — it is\n * type-safe and automatically tracks table renames.\n *\n * Pushes an `addForeignKey` operation immediately using a mutable reference —\n * subsequent `.on()`, `.onDelete()`, `.onUpdate()` calls mutate the same\n * definition that is already queued, so no `.add()` terminator is needed.\n *\n * Referenced column defaults to `\"id\"` — use `.on()` to override.\n *\n * @param tableOrModel - Referenced table name OR a Model class with a static `table` property\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * // Preferred — model class reference (type-safe, rename-proof)\n * this.uuid(\"organization_id\").references(Organization).onDelete(\"cascade\");\n *\n * // Also supported — raw table string\n * this.uuid(\"organization_id\").references(\"organizations\").onDelete(\"cascade\");\n * this.uuid(\"organization_id\").references(Organization.table).onDelete(\"cascade\");\n * ```\n */\n public references(tableOrModel: string | { table: string }): this {\n const tableName = typeof tableOrModel === \"string\" ? tableOrModel : tableOrModel.table;\n\n this.fkDefinition = {\n column: this.definition.name,\n referencesTable: tableName,\n referencesColumn: \"id\",\n onDelete: \"restrict\",\n onUpdate: \"restrict\",\n };\n this.migration.addForeignKeyOperation(this.fkDefinition as ForeignKeyDefinition);\n return this;\n }\n\n /**\n * Set the referenced column for the foreign key.\n *\n * Only meaningful after `.references()`. Defaults to `\"id\"` if omitted.\n *\n * @param column - Referenced column name\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.integer(\"user_id\").references(\"users\").on(\"custom_id\");\n * ```\n */\n public on(column: string): this {\n if (this.fkDefinition) {\n this.fkDefinition.referencesColumn = column;\n }\n return this;\n }\n\n /**\n * Set the ON DELETE action for the foreign key.\n *\n * Only meaningful after `.references()`.\n *\n * @param action - Action when the referenced row is deleted\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.integer(\"user_id\").references(\"users\").onDelete(\"cascade\");\n * ```\n */\n public onDelete(action: ForeignKeyDefinition[\"onDelete\"]): this {\n if (this.fkDefinition) {\n this.fkDefinition.onDelete = action;\n }\n return this;\n }\n\n /**\n * Set the ON UPDATE action for the foreign key.\n *\n * Only meaningful after `.references()`.\n *\n * @param action - Action when the referenced row's key is updated\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.integer(\"user_id\").references(\"users\").onUpdate(\"cascade\");\n * ```\n */\n public onUpdate(action: ForeignKeyDefinition[\"onUpdate\"]): this {\n if (this.fkDefinition) {\n this.fkDefinition.onUpdate = action;\n }\n return this;\n }\n\n /**\n * Shorthand for `.onDelete(\"cascade\").onUpdate(\"cascade\")`.\n *\n * Only meaningful after `.references()`.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.integer(\"user_id\").references(\"users\").cascadeAll();\n * ```\n */\n public cascadeAll(): this {\n if (this.fkDefinition) {\n this.fkDefinition.onDelete = \"cascade\";\n this.fkDefinition.onUpdate = \"cascade\";\n }\n return this;\n }\n\n // ============================================================================\n // COLUMN MODIFICATION\n // ============================================================================\n\n /**\n * Mark this column definition as a modification of an existing column.\n *\n * Pushes a `modifyColumn` operation instead of `addColumn`.\n * This method breaks the builder chain and returns the parent migration.\n *\n * @returns The parent migration instance (breaks builder chain)\n *\n * @example\n * ```typescript\n * // Make email nullable\n * this.string(\"email\").nullable().change();\n *\n * // Increase length\n * this.string(\"name\", 255).change();\n *\n * // Change type\n * this.text(\"description\").change();\n * ```\n */\n public change(): unknown {\n const operations = (this.migration as any).pendingOperations;\n\n // Remove the addColumn pushed by the column type method (e.g. uuid(), string())\n // (by identity, anywhere in the queue: .unique()/.index() may have pushed ops after it)\n const addIndex = operations.findIndex(\n (op: { type: string; payload: unknown }) =>\n op.type === \"addColumn\" && op.payload === this.definition,\n );\n if (addIndex !== -1) {\n operations.splice(addIndex, 1);\n }\n\n // If .references() was called before .change(), the addForeignKey op is now\n // last in the queue. We must pop it, push modifyColumn first, then re-push\n // the FK — because SQL requires: ALTER COLUMN (type change) → ADD CONSTRAINT (FK).\n let pendingFkOp: (typeof operations)[number] | undefined;\n if (this.fkDefinition) {\n const tail = operations[operations.length - 1];\n if (tail?.type === \"addForeignKey\" && tail.payload === this.fkDefinition) {\n pendingFkOp = operations.pop();\n }\n }\n\n // Push modifyColumn — it must precede the FK constraint\n operations.push({ type: \"modifyColumn\", payload: this.definition });\n\n // Re-queue the FK after the column modification\n if (pendingFkOp) {\n operations.push(pendingFkOp);\n }\n\n return this.migration;\n }\n\n /**\n * @alias change\n */\n public modify(): unknown {\n return this.change();\n }\n\n // ============================================================================\n // GENERATED COLUMNS\n // ============================================================================\n\n /**\n * Mark this column as a generated column with the given SQL expression.\n *\n * Must be followed by `.stored()` or `.virtual()` to specify storage type.\n *\n * PostgreSQL: GENERATED ALWAYS AS (...) STORED\n * MySQL: GENERATED ALWAYS AS (...) STORED | VIRTUAL\n *\n * @param expression - SQL expression to compute the value\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.string(\"full_name\")\n * .generatedAs(\"CONCAT(first_name, ' ', last_name)\")\n * .stored();\n *\n * this.decimal(\"price_with_tax\")\n * .generatedAs(\"price * 1.2\")\n * .virtual();\n * ```\n */\n public generatedAs(expression: string): this {\n this.generatedExpression = expression;\n return this;\n }\n\n /**\n * Mark the generated column as stored (computed and persisted to disk).\n *\n * Must be called after `.generatedAs()`.\n *\n * @returns This builder for chaining\n */\n public stored(): this {\n if (this.generatedExpression) {\n this.definition.generated = {\n expression: this.generatedExpression,\n stored: true,\n };\n }\n return this;\n }\n\n /**\n * Mark the generated column as virtual (computed on read, not stored).\n *\n * Must be called after `.generatedAs()`. Not supported by PostgreSQL.\n *\n * @returns This builder for chaining\n */\n public virtual(): this {\n if (this.generatedExpression) {\n this.definition.generated = {\n expression: this.generatedExpression,\n stored: false,\n };\n }\n return this;\n }\n\n // ============================================================================\n // ACCESSOR\n // ============================================================================\n\n /**\n * Get the built column definition.\n *\n * Called internally by the Migration class to extract the final definition.\n *\n * @returns The accumulated column definition\n */\n public getDefinition(): ColumnDefinition {\n return this.definition;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmDA,IAAa,gBAAb,MAA2B;CAmBN;;CAjBnB,AAAiB;;CAGjB,AAAQ;;CAGR,AAAQ;;;;;;;;;CAUR,AAAO,YACL,AAAiB,WACjB,MACA,MACA,UAEI,CAAC,GACL;EANiB;EAOjB,KAAK,aAAa;GAChB;GACA;GACA,UAAU;GACV,GAAG;EACL;CACF;;;;;;;;;;;CAgBA,AAAO,WAAiB;EACtB,KAAK,WAAW,WAAW;EAC3B,OAAO;CACT;;;;;;;;CASA,AAAO,cAAoB;EACzB,KAAK,WAAW,WAAW;EAC3B,OAAO;CACT;;;;;;;;;;;;;;;;;;CAuBA,AAAO,QAAQ,OAAwC;EACrD,KAAK,WAAW,eAAe;EAC/B,KAAK,WAAW,eAAe;EAC/B,OAAO;CACT;;;;;;;;;;;;;;;;CAiBA,AAAO,cAAc,OAAqB;EACxC,KAAK,WAAW,eAAe;EAC/B,KAAK,WAAW,eAAe;EAC/B,OAAO;CACT;;;;;;;;;;;;;CAcA,AAAO,aAAmB;EACxB,KAAK,WAAW,eAAe,EAAE,QAAQ,oBAAoB;EAC7D,OAAO;CACT;;;;;;;;;;;;;CAcA,AAAO,qBAA2B;EAChC,KAAK,WAAW,kBAAkB;EAClC,OAAO;CACT;;;;;;;;;;;;;CAkBA,AAAO,SAAe;EACpB,KAAK,UAAU,gBAAgB;GAC7B,SAAS,CAAC,KAAK,WAAW,IAAI;GAC9B,QAAQ;EACV,C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GAC1B,YAAY,KAAK;GACjB,QAAQ;EACV;EAEF,OAAO;CACT;;;;;;;;CAaA,AAAO,gBAAkC;EACvC,OAAO,KAAK;CACd;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ColumnBuilder } from "./column-builder.mjs";
|
|
2
2
|
import { DetachedColumnBuilder, arrayBigInt, arrayBoolean, arrayDate, arrayDecimal, arrayFloat, arrayInt, arrayJson, arrayText, arrayTimestamp, arrayUuid, bigInt, bigInteger, binary, blobCol, boolCol, char, date, dateTime, decimal, double, enumCol, float, geometry, int, integer, ipAddress, json, lineString, longText, macAddress, mediumText, objectCol, point, polygon, setCol, smallInt, smallInteger, string, text, time, timestamp, tinyInt, tinyInteger, ulid, uuid, vector, year } from "./column-helpers.mjs";
|
|
3
3
|
import { ForeignKeyBuilder } from "./foreign-key-builder.mjs";
|
|
4
|
-
import { AlterSchema, ColumnMap, IndexEntry, Migration, MigrationAlterOptions, MigrationConstructor, MigrationContract, MigrationCreateOptions, OperationType, PendingOperation, UniqueEntry, migrate } from "./migration.mjs";
|
|
4
|
+
import { AlterSchema, ColumnMap, IndexEntry, Migration, MigrationAlterOptions, MigrationConstructor, MigrationContract, MigrationCreateOptions, MigrationStep, OperationType, PendingOperation, UniqueEntry, migrate } from "./migration.mjs";
|
|
5
5
|
import { MigrationRecord, MigrationResult, MigrationRunnerOptions, MigrationStatus, RollbackOptions, RunMigrationsOptions } from "./types.mjs";
|
|
6
|
-
import { MigrationRunner, migrationRunner } from "./migration-runner.mjs";
|
|
6
|
+
import { MigrationRunner, inferMigrationName, migrationRunner } from "./migration-runner.mjs";
|
package/esm/migration/index.mjs
CHANGED
|
@@ -2,6 +2,6 @@ import { ColumnBuilder } from "./column-builder.mjs";
|
|
|
2
2
|
import { ForeignKeyBuilder } from "./foreign-key-builder.mjs";
|
|
3
3
|
import { DetachedColumnBuilder, arrayBigInt, arrayBoolean, arrayDate, arrayDecimal, arrayFloat, arrayInt, arrayJson, arrayText, arrayTimestamp, arrayUuid, bigInt, bigInteger, binary, blobCol, boolCol, char, date, dateTime, decimal, double, enumCol, float, geometry, int, integer, ipAddress, json, lineString, longText, macAddress, mediumText, objectCol, point, polygon, setCol, smallInt, smallInteger, string, text, time, timestamp, tinyInt, tinyInteger, ulid, uuid, vector, year } from "./column-helpers.mjs";
|
|
4
4
|
import { Migration, migrate } from "./migration.mjs";
|
|
5
|
-
import { MigrationRunner, migrationRunner } from "./migration-runner.mjs";
|
|
5
|
+
import { MigrationRunner, inferMigrationName, migrationRunner } from "./migration-runner.mjs";
|
|
6
6
|
|
|
7
7
|
export { };
|
|
@@ -5,10 +5,13 @@ import { compareCreatedAt } from "./parse-created-at.mjs";
|
|
|
5
5
|
* Comparator for applying migrations — oldest first.
|
|
6
6
|
*
|
|
7
7
|
* Priority:
|
|
8
|
-
* 1. `
|
|
9
|
-
* 2.
|
|
8
|
+
* 1. `order` override (lower = earlier, default 0)
|
|
9
|
+
* 2. `createdAt` timestamp (older = earlier)
|
|
10
|
+
* 3. Alphabetical by migration name (last resort)
|
|
10
11
|
*/
|
|
11
12
|
function sortMigrations(a, b) {
|
|
13
|
+
const byOrder = (a.order ?? 0) - (b.order ?? 0);
|
|
14
|
+
if (byOrder !== 0) return byOrder;
|
|
12
15
|
const byCreatedAt = compareCreatedAt(a.createdAt, b.createdAt);
|
|
13
16
|
if (byCreatedAt !== void 0) return byCreatedAt;
|
|
14
17
|
return a.migrationName.localeCompare(b.migrationName);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration-order.mjs","names":[],"sources":["../../../../../../../cascade/src/migration/migration-order.ts"],"sourcesContent":["import { compareCreatedAt } from \"./parse-created-at\";\n\n/** The minimum shape ordering needs — the runner passes full migration classes. */\ntype Orderable = {\n createdAt?: string;\n migrationName: string;\n};\n\n/**\n * Comparator for applying migrations — oldest first.\n *\n * Priority:\n * 1. `createdAt` timestamp (older = earlier)\n *
|
|
1
|
+
{"version":3,"file":"migration-order.mjs","names":[],"sources":["../../../../../../../cascade/src/migration/migration-order.ts"],"sourcesContent":["import { compareCreatedAt } from \"./parse-created-at\";\n\n/** The minimum shape ordering needs — the runner passes full migration classes. */\ntype Orderable = {\n createdAt?: string;\n migrationName: string;\n order?: number;\n};\n\n/**\n * Comparator for applying migrations — oldest first.\n *\n * Priority:\n * 1. `order` override (lower = earlier, default 0)\n * 2. `createdAt` timestamp (older = earlier)\n * 3. Alphabetical by migration name (last resort)\n */\nexport function sortMigrations(a: Orderable, b: Orderable): number {\n const byOrder = (a.order ?? 0) - (b.order ?? 0);\n\n if (byOrder !== 0) {\n return byOrder;\n }\n\n const byCreatedAt = compareCreatedAt(a.createdAt, b.createdAt);\n\n if (byCreatedAt !== undefined) {\n return byCreatedAt;\n }\n\n // Last resort: alphabetical\n return a.migrationName.localeCompare(b.migrationName);\n}\n\n/**\n * Comparator for rolling migrations back — newest first, the exact inverse of\n * {@link sortMigrations}.\n *\n * A rollback has to undo migrations in the reverse of the order they were\n * applied, or a `down()` will hit schema its predecessor already removed —\n * dropping a table before dropping the column that was added to it.\n *\n * This must be an explicit descending sort rather than a `.reverse()` of the\n * executed list: that list is read back ordered by `batch, name`, so it is\n * alphabetical rather than chronological, and reversing it merely produces\n * reverse-alphabetical order.\n */\nexport function sortMigrationsForRollback(a: Orderable, b: Orderable): number {\n return sortMigrations(b, a);\n}\n"],"mappings":";;;;;;;;;;;AAiBA,SAAgB,eAAe,GAAc,GAAsB;CACjE,MAAM,WAAW,EAAE,SAAS,MAAM,EAAE,SAAS;CAE7C,IAAI,YAAY,GACd,OAAO;CAGT,MAAM,cAAc,iBAAiB,EAAE,WAAW,EAAE,SAAS;CAE7D,IAAI,gBAAgB,QAClB,OAAO;CAIT,OAAO,EAAE,cAAc,cAAc,EAAE,aAAa;AACtD;;;;;;;;;;;;;;AAeA,SAAgB,0BAA0B,GAAc,GAAsB;CAC5E,OAAO,eAAe,GAAG,CAAC;AAC5B"}
|
|
@@ -36,7 +36,18 @@ type RegisterableMigration = (new () => MigrationContract) & {
|
|
|
36
36
|
type ExecuteOptions = {
|
|
37
37
|
/** Run in dry-run mode (no actual changes) */readonly dryRun?: boolean; /** Record to migrations table (default: true for batch, false for single) */
|
|
38
38
|
readonly record?: boolean;
|
|
39
|
+
/**
|
|
40
|
+
* Rollback only: delete the `_migrations` rows whose migration file is no
|
|
41
|
+
* longer registered, instead of failing on them.
|
|
42
|
+
*/
|
|
43
|
+
readonly pruneMissing?: boolean;
|
|
39
44
|
};
|
|
45
|
+
/**
|
|
46
|
+
* Derive a migration name from a file path: drop everything after the first dot
|
|
47
|
+
* and strip a trailing `-migration` / `_migration` suffix. Shared by every CLI
|
|
48
|
+
* so the same file is recorded under the same name.
|
|
49
|
+
*/
|
|
50
|
+
declare function inferMigrationName(file: string): string;
|
|
40
51
|
/**
|
|
41
52
|
* Migration runner that executes migrations.
|
|
42
53
|
*
|
|
@@ -76,8 +87,8 @@ declare class MigrationRunner {
|
|
|
76
87
|
readonly migrations: MigrationClass[];
|
|
77
88
|
/** Data source to use */
|
|
78
89
|
private dataSource?;
|
|
79
|
-
/** Cached migration
|
|
80
|
-
private
|
|
90
|
+
/** Cached migration drivers, one per data source */
|
|
91
|
+
private readonly migrationDrivers;
|
|
81
92
|
/** Table name for tracking migrations */
|
|
82
93
|
private readonly migrationsTable;
|
|
83
94
|
/** Whether to log operations */
|
|
@@ -104,6 +115,34 @@ declare class MigrationRunner {
|
|
|
104
115
|
* Get the migration driver.
|
|
105
116
|
*/
|
|
106
117
|
private getMigrationDriver;
|
|
118
|
+
/**
|
|
119
|
+
* Resolve a migration's declared data source (name or instance).
|
|
120
|
+
* Falls back to the runner's own data source when it declares none.
|
|
121
|
+
*/
|
|
122
|
+
private resolveDataSource;
|
|
123
|
+
/** Data source a registered migration class runs against. */
|
|
124
|
+
private sourceOf;
|
|
125
|
+
/** Distinct data sources across the registered migrations (runner's own included). */
|
|
126
|
+
private getSources;
|
|
127
|
+
/**
|
|
128
|
+
* Resolve whether a migration runs in a transaction:
|
|
129
|
+
* 1. migration-level flag (instance, else the static from `Migration.create/alter`)
|
|
130
|
+
* 2. `CONCURRENTLY` statements cannot run in a transaction block
|
|
131
|
+
* 3. data-source config
|
|
132
|
+
* 4. driver default
|
|
133
|
+
*/
|
|
134
|
+
private resolveTransactional;
|
|
135
|
+
/** Locks held by the run in progress (Mongo TTL heartbeat). */
|
|
136
|
+
private activeLocks;
|
|
137
|
+
/** Extend every held lock's TTL; called between migrations. */
|
|
138
|
+
private refreshLocks;
|
|
139
|
+
/**
|
|
140
|
+
* Run `callback` while holding a migration lock on every given data source, so
|
|
141
|
+
* concurrent `migrate` invocations (replicas, init containers) serialize.
|
|
142
|
+
*/
|
|
143
|
+
private withLock;
|
|
144
|
+
/** Acquire the lock for one data source; `undefined` when its driver has no lock support. */
|
|
145
|
+
private acquireLock;
|
|
107
146
|
/**
|
|
108
147
|
* Register a migration.
|
|
109
148
|
*
|
|
@@ -178,6 +217,7 @@ declare class MigrationRunner {
|
|
|
178
217
|
* ```
|
|
179
218
|
*/
|
|
180
219
|
runAll(options?: ExecuteOptions): Promise<MigrationResult[]>;
|
|
220
|
+
private runAllUnlocked;
|
|
181
221
|
/**
|
|
182
222
|
* Export migrations as phase-ordered SQL files in database/sql/ directory.
|
|
183
223
|
* By default, it exports all registered migrations. Use `pendingOnly: true` to export only pending ones.
|
|
@@ -201,6 +241,7 @@ declare class MigrationRunner {
|
|
|
201
241
|
* @returns Results for each migration
|
|
202
242
|
*/
|
|
203
243
|
rollbackBatches(batches: number, options?: ExecuteOptions): Promise<MigrationResult[]>;
|
|
244
|
+
private rollbackBatchesUnlocked;
|
|
204
245
|
/**
|
|
205
246
|
* Rollback all executed migrations.
|
|
206
247
|
*
|
|
@@ -280,7 +321,9 @@ declare class MigrationRunner {
|
|
|
280
321
|
*
|
|
281
322
|
* @see listPendingMigrations
|
|
282
323
|
*/
|
|
283
|
-
getPendingMigrations(
|
|
324
|
+
getPendingMigrations(options?: {
|
|
325
|
+
readOnly?: boolean;
|
|
326
|
+
}): Promise<MigrationClass[]>;
|
|
284
327
|
/**
|
|
285
328
|
* Get migrations to rollback, newest-first.
|
|
286
329
|
*
|
|
@@ -299,7 +342,9 @@ declare class MigrationRunner {
|
|
|
299
342
|
/**
|
|
300
343
|
* Get executed migration records.
|
|
301
344
|
*/
|
|
302
|
-
getExecutedMigrations(
|
|
345
|
+
getExecutedMigrations(dataSource?: DataSource, options?: {
|
|
346
|
+
readOnly?: boolean;
|
|
347
|
+
}): Promise<MigrationRecord[]>;
|
|
303
348
|
/**
|
|
304
349
|
* Record a migration.
|
|
305
350
|
*/
|
|
@@ -315,5 +360,5 @@ declare class MigrationRunner {
|
|
|
315
360
|
}
|
|
316
361
|
declare const migrationRunner: MigrationRunner;
|
|
317
362
|
//#endregion
|
|
318
|
-
export { MigrationRunner, migrationRunner };
|
|
363
|
+
export { MigrationRunner, inferMigrationName, migrationRunner };
|
|
319
364
|
//# sourceMappingURL=migration-runner.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration-runner.d.mts","names":[],"sources":["../../../../../../../cascade/src/migration/migration-runner.ts"],"mappings":";;;;;;;AAW2E;KAKtE,cAAA,cAA4B,SAAS;EACxC,aAAA;EACA,SAAA;AAAA;;;;AAAS;AAAA;;;;;;;;AAqBA;AAAA;;;KAFN,qBAAA,cAAmC,iBAAiB;EACvD,aAAA;EACA,SAAA;AAAA
|
|
1
|
+
{"version":3,"file":"migration-runner.d.mts","names":[],"sources":["../../../../../../../cascade/src/migration/migration-runner.ts"],"mappings":";;;;;;;AAW2E;KAKtE,cAAA,cAA4B,SAAS;EACxC,aAAA;EACA,SAAA;AAAA;;;;AAAS;AAAA;;;;;;;;AAqBA;AAAA;;;KAFN,qBAAA,cAAmC,iBAAiB;EACvD,aAAA;EACA,SAAA;AAAA;;AAmCqB;AAqCvB;KA9CK,cAAA;yDAEM,MAAA,YA4CoC;EAAA,SA1CpC,MAAA;EAkFiB;;;;EAAA,S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