@warlock.js/cascade 5.30.0 → 5.31.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.
Files changed (89) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -5
  3. package/cjs/index.cjs +0 -1
  4. package/cjs/index.cjs.map +1 -1
  5. package/esm/contracts/database-restorer.contract.d.mts.map +1 -1
  6. package/esm/data-source/data-source-registry.d.mts.map +1 -1
  7. package/esm/data-source/data-source-registry.mjs.map +1 -1
  8. package/esm/drivers/mongodb/mongodb-driver.d.mts.map +1 -1
  9. package/esm/drivers/mongodb/mongodb-driver.mjs.map +1 -1
  10. package/esm/drivers/mongodb/mongodb-id-generator.d.mts.map +1 -1
  11. package/esm/drivers/mongodb/mongodb-id-generator.mjs.map +1 -1
  12. package/esm/drivers/mongodb/mongodb-query-builder.d.mts.map +1 -1
  13. package/esm/drivers/mongodb/mongodb-query-builder.mjs.map +1 -1
  14. package/esm/drivers/mongodb/mongodb-query-operations.d.mts.map +1 -1
  15. package/esm/drivers/mongodb/mongodb-query-operations.mjs.map +1 -1
  16. package/esm/drivers/mongodb/mongodb-query-parser.d.mts.map +1 -1
  17. package/esm/drivers/mongodb/mongodb-query-parser.mjs.map +1 -1
  18. package/esm/drivers/postgres/naming.mjs.map +1 -1
  19. package/esm/drivers/postgres/postgres-dialect.d.mts.map +1 -1
  20. package/esm/drivers/postgres/postgres-dialect.mjs.map +1 -1
  21. package/esm/drivers/postgres/postgres-driver.d.mts.map +1 -1
  22. package/esm/drivers/postgres/postgres-driver.mjs.map +1 -1
  23. package/esm/drivers/postgres/postgres-migration-driver.d.mts.map +1 -1
  24. package/esm/drivers/postgres/postgres-migration-driver.mjs.map +1 -1
  25. package/esm/drivers/postgres/postgres-query-builder.d.mts.map +1 -1
  26. package/esm/drivers/postgres/postgres-query-builder.mjs.map +1 -1
  27. package/esm/drivers/postgres/postgres-query-parser.d.mts.map +1 -1
  28. package/esm/drivers/postgres/postgres-query-parser.mjs +0 -1
  29. package/esm/drivers/postgres/postgres-query-parser.mjs.map +1 -1
  30. package/esm/drivers/postgres/postgres-sql-serializer.mjs.map +1 -1
  31. package/esm/drivers/postgres/postgres-ttl-purge.mjs.map +1 -1
  32. package/esm/drivers/postgres/types.d.mts.map +1 -1
  33. package/esm/errors/unsupported-query-operation.error.mjs.map +1 -1
  34. package/esm/expressions/column-expressions.d.mts.map +1 -1
  35. package/esm/expressions/column-expressions.mjs.map +1 -1
  36. package/esm/migration/foreign-key-builder.mjs.map +1 -1
  37. package/esm/migration/parse-created-at.mjs.map +1 -1
  38. package/esm/migration/sql-grammar.mjs.map +1 -1
  39. package/esm/model/generate-model-id.mjs.map +1 -1
  40. package/esm/model/methods/accessor-methods.mjs.map +1 -1
  41. package/esm/model/methods/dirty-methods.mjs.map +1 -1
  42. package/esm/model/methods/hydration-methods.mjs.map +1 -1
  43. package/esm/model/methods/query-methods.mjs.map +1 -1
  44. package/esm/model/methods/scope-methods.mjs.map +1 -1
  45. package/esm/model/methods/static-event-methods.mjs.map +1 -1
  46. package/esm/model/methods/write-methods.mjs.map +1 -1
  47. package/esm/model/model.d.mts.map +1 -1
  48. package/esm/model/model.mjs.map +1 -1
  49. package/esm/model/register-model.d.mts.map +1 -1
  50. package/esm/model/register-model.mjs.map +1 -1
  51. package/esm/operations/migrations.d.mts.map +1 -1
  52. package/esm/operations/migrations.mjs.map +1 -1
  53. package/esm/query-builder/query-builder.d.mts.map +1 -1
  54. package/esm/query-builder/query-builder.mjs.map +1 -1
  55. package/esm/relations/key-conventions.mjs.map +1 -1
  56. package/esm/relations/pivot-operations.d.mts.map +1 -1
  57. package/esm/relations/pivot-operations.mjs.map +1 -1
  58. package/esm/relations/relation-loader.d.mts.map +1 -1
  59. package/esm/relations/relation-loader.mjs.map +1 -1
  60. package/esm/remover/database-remover.d.mts.map +1 -1
  61. package/esm/remover/database-remover.mjs.map +1 -1
  62. package/esm/sync/sync-context.d.mts.map +1 -1
  63. package/esm/sync/sync-context.mjs.map +1 -1
  64. package/esm/sync/sync-fanout.mjs.map +1 -1
  65. package/esm/sync/sync-manager.d.mts.map +1 -1
  66. package/esm/sync/sync-manager.mjs.map +1 -1
  67. package/esm/utils/database-writer.utils.d.mts.map +1 -1
  68. package/esm/utils/database-writer.utils.mjs.map +1 -1
  69. package/esm/utils/is-valid-date-value.mjs.map +1 -1
  70. package/esm/writer/database-writer.d.mts.map +1 -1
  71. package/esm/writer/database-writer.mjs.map +1 -1
  72. package/llms-full.txt +541 -434
  73. package/package.json +5 -5
  74. package/skills/aggregate-data/SKILL.md +28 -17
  75. package/skills/alter-migration/SKILL.md +325 -233
  76. package/skills/cascade-basics/SKILL.md +19 -19
  77. package/skills/configure-delete-strategy/SKILL.md +11 -11
  78. package/skills/define-model/SKILL.md +19 -17
  79. package/skills/define-relations/SKILL.md +13 -18
  80. package/skills/index.md +3 -0
  81. package/skills/manage-transactions/SKILL.md +18 -12
  82. package/skills/paginate-results/SKILL.md +6 -8
  83. package/skills/perform-atomic-ops/SKILL.md +26 -21
  84. package/skills/query-data/SKILL.md +27 -33
  85. package/skills/run-cascade-cli/SKILL.md +11 -10
  86. package/skills/search-by-vector/SKILL.md +8 -5
  87. package/skills/subscribe-to-model-events/SKILL.md +17 -17
  88. package/skills/track-changes/SKILL.md +9 -9
  89. package/skills/write-migration/SKILL.md +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"column-expressions.mjs","names":[],"sources":["../../../../../../../../packages/cascade/src/expressions/column-expressions.ts"],"sourcesContent":["/**\n * Database-agnostic, **typed** column expressions for aggregate inputs.\n *\n * These let `$agg.sum(...)` (and any future expression-accepting aggregate)\n * operate on a composed arithmetic expression — e.g. `price * quantity` — not\n * just a bare column, while staying portable across drivers.\n *\n * The builders are grouped under a single `$expr` object (mirroring `$agg`),\n * so the package root exposes exactly two expression namespaces — `$agg` for\n * aggregates and `$expr` for the scalar arithmetic that feeds them — rather\n * than a handful of collision-prone bare verbs (`mul`, `add`, `col`, …).\n *\n * The expression tree is a small, closed union of safe nodes:\n *\n * - `$expr.col(\"price\")` — a column reference (driver quotes/escapes it)\n * - `$expr.lit(2)` — a numeric/boolean literal\n * - `$expr.mul(a, b, …)` / `$expr.add(…)` / `$expr.sub(a, b)` / `$expr.div(a, b)` — arithmetic\n * - `$expr.raw(\"price * 1.2\")` — an explicit escape hatch for a raw SQL fragment\n *\n * Only `$expr.raw` ever embeds an uninterpreted string, and it is opt-in by\n * name. Everything else is composed from typed nodes, so user-supplied column\n * names flow through the driver's identifier-quoting path rather than being\n * string-interpolated into SQL. This is the boundary the S2 task calls out: a\n * tiny typed DSL for the common safe ops, plus a clearly-named raw escape\n * hatch for everything beyond it.\n *\n * Bare strings are still accepted everywhere a `ColumnExpression` is — a plain\n * string is treated as a column reference (`\"price\"` === `$expr.col(\"price\")`),\n * so the existing `$agg.sum(\"amount\")` call site keeps working unchanged.\n *\n * @example\n * ```typescript\n * import { $agg, $expr } from \"@warlock.js/cascade\";\n *\n * query.groupByDate(\"created_at\", \"month\", {\n * revenue: $agg.sum($expr.mul(\"price\", \"quantity\")),\n * });\n * ```\n */\n\n/** Discriminator tag identifying a node in the column-expression tree. */\nexport type ColumnExpressionType =\n | \"column\"\n | \"literal\"\n | \"add\"\n | \"subtract\"\n | \"multiply\"\n | \"divide\"\n | \"raw\";\n\n/**\n * A reference to a column/field. The driver is responsible for quoting the\n * name (SQL) or prefixing it with `$` (Mongo) — it is never interpolated raw.\n */\nexport type ColumnRefExpression = {\n readonly __expr: \"column\";\n readonly column: string;\n};\n\n/** A scalar literal value embedded directly in the expression. */\nexport type LiteralExpression = {\n readonly __expr: \"literal\";\n readonly value: number | boolean;\n};\n\n/**\n * An arithmetic operation over one or more operands.\n *\n * `add` / `multiply` are variadic; `subtract` / `divide` take exactly two\n * operands (left, right) since they are not associative.\n */\nexport type ArithmeticExpression = {\n readonly __expr: \"add\" | \"subtract\" | \"multiply\" | \"divide\";\n readonly operands: ColumnExpression[];\n};\n\n/**\n * A raw expression escape hatch. The string is emitted verbatim into the\n * generated SQL — callers MUST NOT build it from untrusted input. This is the\n * documented boundary for anything the typed nodes above don't cover.\n */\nexport type RawColumnExpression = {\n readonly __expr: \"raw\";\n readonly expression: string;\n};\n\n/**\n * Any node in the typed column-expression tree. A bare `string` is also a\n * valid expression input wherever this type is accepted — it is interpreted as\n * a column reference.\n */\nexport type ColumnExpression =\n | ColumnRefExpression\n | LiteralExpression\n | ArithmeticExpression\n | RawColumnExpression;\n\n/** Input accepted by expression-aware helpers: a typed node or a column-name string. */\nexport type ColumnExpressionInput = ColumnExpression | string;\n\n/**\n * Type guard: is `value` one of the typed column-expression nodes?\n *\n * @param value - The value to test\n * @returns `true` when `value` is a `ColumnExpression` node\n */\nexport function isColumnExpression(value: unknown): value is ColumnExpression {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as ColumnExpression).__expr === \"string\"\n );\n}\n\n/**\n * Reference a column/field by name.\n *\n * @param column - The column/field name\n * @returns A column-reference expression node\n */\nfunction col(column: string): ColumnRefExpression {\n return { __expr: \"column\", column };\n}\n\n/**\n * A scalar literal (number or boolean) operand.\n *\n * @param value - The literal value\n * @returns A literal expression node\n */\nfunction lit(value: number | boolean): LiteralExpression {\n return { __expr: \"literal\", value };\n}\n\n/**\n * Multiply two or more operands.\n *\n * @param operands - Column names, literals, or nested expression nodes\n * @returns A multiply expression node\n */\nfunction mul(...operands: ColumnExpressionInput[]): ArithmeticExpression {\n return { __expr: \"multiply\", operands: operands.map(toColumnExpression) };\n}\n\n/**\n * Add two or more operands.\n *\n * @param operands - Column names, literals, or nested expression nodes\n * @returns An add expression node\n */\nfunction add(...operands: ColumnExpressionInput[]): ArithmeticExpression {\n return { __expr: \"add\", operands: operands.map(toColumnExpression) };\n}\n\n/**\n * Subtract `right` from `left`.\n *\n * @param left - The minuend\n * @param right - The subtrahend\n * @returns A subtract expression node\n */\nfunction sub(\n left: ColumnExpressionInput,\n right: ColumnExpressionInput,\n): ArithmeticExpression {\n return {\n __expr: \"subtract\",\n operands: [toColumnExpression(left), toColumnExpression(right)],\n };\n}\n\n/**\n * Divide `left` by `right`.\n *\n * @param left - The dividend\n * @param right - The divisor\n * @returns A divide expression node\n */\nfunction div(\n left: ColumnExpressionInput,\n right: ColumnExpressionInput,\n): ArithmeticExpression {\n return {\n __expr: \"divide\",\n operands: [toColumnExpression(left), toColumnExpression(right)],\n };\n}\n\n/**\n * Wrap a raw expression string as an escape hatch.\n *\n * The string is emitted verbatim — never build it from untrusted input. Use\n * this only when the typed `$expr.mul` / `$expr.add` / `$expr.sub` /\n * `$expr.div` / `$expr.col` / `$expr.lit` combinators can't express what you\n * need.\n *\n * @param expression - A raw, driver-native expression fragment\n * @returns A raw expression node\n */\nfunction raw(expression: string): RawColumnExpression {\n return { __expr: \"raw\", expression };\n}\n\n/**\n * Normalize an expression input to a `ColumnExpression` node. A bare string\n * becomes a `$expr.col(...)` reference; an existing node passes through\n * unchanged.\n *\n * @param input - A typed expression node or a bare column-name string\n * @returns The corresponding `ColumnExpression` node\n */\nexport function toColumnExpression(input: ColumnExpressionInput): ColumnExpression {\n return typeof input === \"string\" ? col(input) : input;\n}\n\n/**\n * Typed, database-agnostic column-expression builders.\n *\n * Grouped under one object (like `$agg`) so the scalar arithmetic that feeds\n * an aggregate reads as a single, discoverable namespace: `$agg.sum($expr.mul(\n * \"price\", \"quantity\"))`. Each builder returns a plain, closed `ColumnExpression`\n * node — the driver translates it to native SQL / a Mongo pipeline.\n *\n * @example\n * ```typescript\n * import { $agg, $expr } from \"@warlock.js/cascade\";\n *\n * // SUM(price * quantity)\n * query.groupBy(\"product_id\", { revenue: $agg.sum($expr.mul(\"price\", \"quantity\")) });\n *\n * // SUM((1 - discount) * price)\n * query.groupBy(\"product_id\", {\n * net: $agg.sum($expr.mul($expr.sub($expr.lit(1), \"discount\"), \"price\")),\n * });\n *\n * // price * 1.2 (e.g. tax)\n * $agg.sum($expr.mul(\"price\", $expr.lit(1.2)));\n *\n * // escape hatch (Postgres-only, emitted verbatim — never from user input)\n * $agg.sum($expr.raw(\"price * quantity * (1 - discount)\"));\n * ```\n */\nexport const $expr = {\n col,\n lit,\n mul,\n add,\n sub,\n div,\n raw,\n};\n"],"mappings":";;;;;;;AA0GA,SAAgB,mBAAmB,OAA2C;CAC5E,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA2B,WAAW;AAElD;;;;;;;AAQA,SAAS,IAAI,QAAqC;CAChD,OAAO;EAAE,QAAQ;EAAU;CAAO;AACpC;;;;;;;AAQA,SAAS,IAAI,OAA4C;CACvD,OAAO;EAAE,QAAQ;EAAW;CAAM;AACpC;;;;;;;AAQA,SAAS,IAAI,GAAG,UAAyD;CACvE,OAAO;EAAE,QAAQ;EAAY,UAAU,SAAS,IAAI,kBAAkB;CAAE;AAC1E;;;;;;;AAQA,SAAS,IAAI,GAAG,UAAyD;CACvE,OAAO;EAAE,QAAQ;EAAO,UAAU,SAAS,IAAI,kBAAkB;CAAE;AACrE;;;;;;;;AASA,SAAS,IACP,MACA,OACsB;CACtB,OAAO;EACL,QAAQ;EACR,UAAU,CAAC,mBAAmB,IAAI,GAAG,mBAAmB,KAAK,CAAC;CAChE;AACF;;;;;;;;AASA,SAAS,IACP,MACA,OACsB;CACtB,OAAO;EACL,QAAQ;EACR,UAAU,CAAC,mBAAmB,IAAI,GAAG,mBAAmB,KAAK,CAAC;CAChE;AACF;;;;;;;;;;;;AAaA,SAAS,IAAI,YAAyC;CACpD,OAAO;EAAE,QAAQ;EAAO;CAAW;AACrC;;;;;;;;;AAUA,SAAgB,mBAAmB,OAAgD;CACjF,OAAO,OAAO,UAAU,WAAW,IAAI,KAAK,IAAI;AAClD;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,QAAQ;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
1
+ {"version":3,"file":"column-expressions.mjs","names":[],"sources":["../../../../../../../../packages/cascade/src/expressions/column-expressions.ts"],"sourcesContent":["/**\n * Database-agnostic, **typed** column expressions for aggregate inputs.\n *\n * These let `$agg.sum(...)` (and any future expression-accepting aggregate)\n * operate on a composed arithmetic expression — e.g. `price * quantity` — not\n * just a bare column, while staying portable across drivers.\n *\n * The builders are grouped under a single `$expr` object (mirroring `$agg`),\n * so the package root exposes exactly two expression namespaces — `$agg` for\n * aggregates and `$expr` for the scalar arithmetic that feeds them — rather\n * than a handful of collision-prone bare verbs (`mul`, `add`, `col`, …).\n *\n * The expression tree is a small, closed union of safe nodes:\n *\n * - `$expr.col(\"price\")` — a column reference (driver quotes/escapes it)\n * - `$expr.lit(2)` — a numeric/boolean literal\n * - `$expr.mul(a, b, …)` / `$expr.add(…)` / `$expr.sub(a, b)` / `$expr.div(a, b)` — arithmetic\n * - `$expr.raw(\"price * 1.2\")` — an explicit escape hatch for a raw SQL fragment\n *\n * Only `$expr.raw` ever embeds an uninterpreted string, and it is opt-in by\n * name. Everything else is composed from typed nodes, so user-supplied column\n * names flow through the driver's identifier-quoting path rather than being\n * string-interpolated into SQL. This is the boundary the S2 task calls out: a\n * tiny typed DSL for the common safe ops, plus a clearly-named raw escape\n * hatch for everything beyond it.\n *\n * Bare strings are still accepted everywhere a `ColumnExpression` is — a plain\n * string is treated as a column reference (`\"price\"` === `$expr.col(\"price\")`),\n * so the existing `$agg.sum(\"amount\")` call site keeps working unchanged.\n *\n * @example\n * ```typescript\n * import { $agg, $expr } from \"@warlock.js/cascade\";\n *\n * query.groupByDate(\"created_at\", \"month\", {\n * revenue: $agg.sum($expr.mul(\"price\", \"quantity\")),\n * });\n * ```\n */\n\n/** Discriminator tag identifying a node in the column-expression tree. */\nexport type ColumnExpressionType =\n | \"column\"\n | \"literal\"\n | \"add\"\n | \"subtract\"\n | \"multiply\"\n | \"divide\"\n | \"raw\";\n\n/**\n * A reference to a column/field. The driver is responsible for quoting the\n * name (SQL) or prefixing it with `$` (Mongo) — it is never interpolated raw.\n */\nexport type ColumnRefExpression = {\n readonly __expr: \"column\";\n readonly column: string;\n};\n\n/** A scalar literal value embedded directly in the expression. */\nexport type LiteralExpression = {\n readonly __expr: \"literal\";\n readonly value: number | boolean;\n};\n\n/**\n * An arithmetic operation over one or more operands.\n *\n * `add` / `multiply` are variadic; `subtract` / `divide` take exactly two\n * operands (left, right) since they are not associative.\n */\nexport type ArithmeticExpression = {\n readonly __expr: \"add\" | \"subtract\" | \"multiply\" | \"divide\";\n readonly operands: ColumnExpression[];\n};\n\n/**\n * A raw expression escape hatch. The string is emitted verbatim into the\n * generated SQL — callers MUST NOT build it from untrusted input. This is the\n * documented boundary for anything the typed nodes above don't cover.\n */\nexport type RawColumnExpression = {\n readonly __expr: \"raw\";\n readonly expression: string;\n};\n\n/**\n * Any node in the typed column-expression tree. A bare `string` is also a\n * valid expression input wherever this type is accepted — it is interpreted as\n * a column reference.\n */\nexport type ColumnExpression =\n | ColumnRefExpression\n | LiteralExpression\n | ArithmeticExpression\n | RawColumnExpression;\n\n/** Input accepted by expression-aware helpers: a typed node or a column-name string. */\nexport type ColumnExpressionInput = ColumnExpression | string;\n\n/**\n * Type guard: is `value` one of the typed column-expression nodes?\n *\n * @param value - The value to test\n * @returns `true` when `value` is a `ColumnExpression` node\n */\nexport function isColumnExpression(value: unknown): value is ColumnExpression {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as ColumnExpression).__expr === \"string\"\n );\n}\n\n/**\n * Reference a column/field by name.\n *\n * @param column - The column/field name\n * @returns A column-reference expression node\n */\nfunction col(column: string): ColumnRefExpression {\n return { __expr: \"column\", column };\n}\n\n/**\n * A scalar literal (number or boolean) operand.\n *\n * @param value - The literal value\n * @returns A literal expression node\n */\nfunction lit(value: number | boolean): LiteralExpression {\n return { __expr: \"literal\", value };\n}\n\n/**\n * Multiply two or more operands.\n *\n * @param operands - Column names, literals, or nested expression nodes\n * @returns A multiply expression node\n */\nfunction mul(...operands: ColumnExpressionInput[]): ArithmeticExpression {\n return { __expr: \"multiply\", operands: operands.map(toColumnExpression) };\n}\n\n/**\n * Add two or more operands.\n *\n * @param operands - Column names, literals, or nested expression nodes\n * @returns An add expression node\n */\nfunction add(...operands: ColumnExpressionInput[]): ArithmeticExpression {\n return { __expr: \"add\", operands: operands.map(toColumnExpression) };\n}\n\n/**\n * Subtract `right` from `left`.\n *\n * @param left - The minuend\n * @param right - The subtrahend\n * @returns A subtract expression node\n */\nfunction sub(left: ColumnExpressionInput, right: ColumnExpressionInput): ArithmeticExpression {\n return {\n __expr: \"subtract\",\n operands: [toColumnExpression(left), toColumnExpression(right)],\n };\n}\n\n/**\n * Divide `left` by `right`.\n *\n * @param left - The dividend\n * @param right - The divisor\n * @returns A divide expression node\n */\nfunction div(left: ColumnExpressionInput, right: ColumnExpressionInput): ArithmeticExpression {\n return {\n __expr: \"divide\",\n operands: [toColumnExpression(left), toColumnExpression(right)],\n };\n}\n\n/**\n * Wrap a raw expression string as an escape hatch.\n *\n * The string is emitted verbatim — never build it from untrusted input. Use\n * this only when the typed `$expr.mul` / `$expr.add` / `$expr.sub` /\n * `$expr.div` / `$expr.col` / `$expr.lit` combinators can't express what you\n * need.\n *\n * @param expression - A raw, driver-native expression fragment\n * @returns A raw expression node\n */\nfunction raw(expression: string): RawColumnExpression {\n return { __expr: \"raw\", expression };\n}\n\n/**\n * Normalize an expression input to a `ColumnExpression` node. A bare string\n * becomes a `$expr.col(...)` reference; an existing node passes through\n * unchanged.\n *\n * @param input - A typed expression node or a bare column-name string\n * @returns The corresponding `ColumnExpression` node\n */\nexport function toColumnExpression(input: ColumnExpressionInput): ColumnExpression {\n return typeof input === \"string\" ? col(input) : input;\n}\n\n/**\n * Typed, database-agnostic column-expression builders.\n *\n * Grouped under one object (like `$agg`) so the scalar arithmetic that feeds\n * an aggregate reads as a single, discoverable namespace: `$agg.sum($expr.mul(\n * \"price\", \"quantity\"))`. Each builder returns a plain, closed `ColumnExpression`\n * node — the driver translates it to native SQL / a Mongo pipeline.\n *\n * @example\n * ```typescript\n * import { $agg, $expr } from \"@warlock.js/cascade\";\n *\n * // SUM(price * quantity)\n * query.groupBy(\"product_id\", { revenue: $agg.sum($expr.mul(\"price\", \"quantity\")) });\n *\n * // SUM((1 - discount) * price)\n * query.groupBy(\"product_id\", {\n * net: $agg.sum($expr.mul($expr.sub($expr.lit(1), \"discount\"), \"price\")),\n * });\n *\n * // price * 1.2 (e.g. tax)\n * $agg.sum($expr.mul(\"price\", $expr.lit(1.2)));\n *\n * // escape hatch (Postgres-only, emitted verbatim — never from user input)\n * $agg.sum($expr.raw(\"price * quantity * (1 - discount)\"));\n * ```\n */\nexport const $expr = {\n col,\n lit,\n mul,\n add,\n sub,\n div,\n raw,\n};\n"],"mappings":";;;;;;;AA0GA,SAAgB,mBAAmB,OAA2C;CAC5E,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA2B,WAAW;AAElD;;;;;;;AAQA,SAAS,IAAI,QAAqC;CAChD,OAAO;EAAE,QAAQ;EAAU;CAAO;AACpC;;;;;;;AAQA,SAAS,IAAI,OAA4C;CACvD,OAAO;EAAE,QAAQ;EAAW;CAAM;AACpC;;;;;;;AAQA,SAAS,IAAI,GAAG,UAAyD;CACvE,OAAO;EAAE,QAAQ;EAAY,UAAU,SAAS,IAAI,kBAAkB;CAAE;AAC1E;;;;;;;AAQA,SAAS,IAAI,GAAG,UAAyD;CACvE,OAAO;EAAE,QAAQ;EAAO,UAAU,SAAS,IAAI,kBAAkB;CAAE;AACrE;;;;;;;;AASA,SAAS,IAAI,MAA6B,OAAoD;CAC5F,OAAO;EACL,QAAQ;EACR,UAAU,CAAC,mBAAmB,IAAI,GAAG,mBAAmB,KAAK,CAAC;CAChE;AACF;;;;;;;;AASA,SAAS,IAAI,MAA6B,OAAoD;CAC5F,OAAO;EACL,QAAQ;EACR,UAAU,CAAC,mBAAmB,IAAI,GAAG,mBAAmB,KAAK,CAAC;CAChE;AACF;;;;;;;;;;;;AAaA,SAAS,IAAI,YAAyC;CACpD,OAAO;EAAE,QAAQ;EAAO;CAAW;AACrC;;;;;;;;;AAUA,SAAgB,mBAAmB,OAAgD;CACjF,OAAO,OAAO,UAAU,WAAW,IAAI,KAAK,IAAI;AAClD;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,QAAQ;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"foreign-key-builder.mjs","names":[],"sources":["../../../../../../../../packages/cascade/src/migration/foreign-key-builder.ts"],"sourcesContent":["import type { ForeignKeyDefinition } from \"../contracts/migration-driver.contract\";\n\n/**\n * Reference to the Migration type to avoid circular imports.\n */\ntype MigrationLike = {\n addForeignKeyOperation(fk: ForeignKeyDefinition): void;\n};\n\n/**\n * Mutable foreign key definition being built.\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 foreign key constraints.\n *\n * Allows building foreign key definitions with a chainable API.\n * SQL-only feature; NoSQL drivers ignore foreign keys.\n *\n * The operation is pushed when `.references()` is called using a mutable\n * reference — subsequent `.onDelete()` / `.onUpdate()` calls mutate the\n * same definition already queued in pendingOperations.\n *\n * @example\n * ```typescript\n * this.foreign(\"user_id\")\n * .references(\"users\", \"id\")\n * .onDelete(\"cascade\")\n * .onUpdate(\"cascade\");\n * ```\n */\nexport class ForeignKeyBuilder {\n /** Mutable foreign key definition being accumulated */\n private readonly definition: MutableForeignKeyDefinition;\n\n /**\n * Create a new foreign key builder.\n *\n * @param migration - Parent migration instance\n * @param column - Local column name that will reference another table\n */\n public constructor(\n private readonly migration: MigrationLike,\n column: string,\n ) {\n this.definition = {\n column,\n referencesTable: \"\",\n referencesColumn: \"id\",\n onDelete: \"restrict\",\n onUpdate: \"restrict\",\n };\n }\n\n /**\n * Set the constraint name.\n *\n * @param name - Constraint name (auto-generated if not provided)\n * @returns This builder for chaining\n */\n public name(name: string): this {\n this.definition.name = name;\n return this;\n }\n\n /**\n * Set the referenced table and column, and register the foreign key operation.\n *\n * Pushes the operation immediately using a mutable reference — any\n * `.onDelete()` / `.onUpdate()` calls after this will mutate the same\n * definition already queued in pendingOperations.\n *\n * @param table - Referenced table name\n * @param column - Referenced column name (default: \"id\")\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.foreign(\"user_id\").references(\"users\", \"id\");\n * this.foreign(\"category_id\").references(\"categories\"); // defaults to \"id\"\n * ```\n */\n public references(table: string, column = \"id\"): this {\n this.definition.referencesTable = table;\n this.definition.referencesColumn = column;\n this.migration.addForeignKeyOperation(this.definition as ForeignKeyDefinition);\n return this;\n }\n\n /**\n * Set the ON DELETE action.\n *\n * @param action - Action to take when referenced row is deleted\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.foreign(\"user_id\")\n * .references(\"users\")\n * .onDelete(\"cascade\"); // Delete child when parent is deleted\n * ```\n */\n public onDelete(action: ForeignKeyDefinition[\"onDelete\"]): this {\n this.definition.onDelete = action;\n return this;\n }\n\n /**\n * Set the ON UPDATE action.\n *\n * @param action - Action to take when referenced row's key is updated\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.foreign(\"user_id\")\n * .references(\"users\")\n * .onUpdate(\"cascade\"); // Update child when parent key changes\n * ```\n */\n public onUpdate(action: ForeignKeyDefinition[\"onUpdate\"]): this {\n this.definition.onUpdate = action;\n return this;\n }\n\n /**\n * Shorthand for `.onDelete(\"cascade\").onUpdate(\"cascade\")`.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.foreign(\"user_id\").references(\"users\").cascadeAll();\n * ```\n */\n public cascadeAll(): this {\n this.definition.onDelete = \"cascade\";\n this.definition.onUpdate = \"cascade\";\n return this;\n }\n\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuCA,IAAa,oBAAb,MAA+B;CAWV;;CATnB,AAAiB;;;;;;;CAQjB,AAAO,YACL,AAAiB,WACjB,QACA;EAFiB;EAGjB,KAAK,aAAa;GAChB;GACA,iBAAiB;GACjB,kBAAkB;GAClB,UAAU;GACV,UAAU;EACZ;CACF;;;;;;;CAQA,AAAO,KAAK,MAAoB;EAC9B,KAAK,WAAW,OAAO;EACvB,OAAO;CACT;;;;;;;;;;;;;;;;;;CAmBA,AAAO,WAAW,OAAe,SAAS,MAAY;EACpD,KAAK,WAAW,kBAAkB;EAClC,KAAK,WAAW,mBAAmB;EACnC,KAAK,UAAU,uBAAuB,KAAK,UAAkC;EAC7E,OAAO;CACT;;;;;;;;;;;;;;CAeA,AAAO,SAAS,QAAgD;EAC9D,KAAK,WAAW,WAAW;EAC3B,OAAO;CACT;;;;;;;;;;;;;;CAeA,AAAO,SAAS,QAAgD;EAC9D,KAAK,WAAW,WAAW;EAC3B,OAAO;CACT;;;;;;;;;;;CAYA,AAAO,aAAmB;EACxB,KAAK,WAAW,WAAW;EAC3B,KAAK,WAAW,WAAW;EAC3B,OAAO;CACT;AAEF"}
1
+ {"version":3,"file":"foreign-key-builder.mjs","names":[],"sources":["../../../../../../../../packages/cascade/src/migration/foreign-key-builder.ts"],"sourcesContent":["import type { ForeignKeyDefinition } from \"../contracts/migration-driver.contract\";\n\n/**\n * Reference to the Migration type to avoid circular imports.\n */\ntype MigrationLike = {\n addForeignKeyOperation(fk: ForeignKeyDefinition): void;\n};\n\n/**\n * Mutable foreign key definition being built.\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 foreign key constraints.\n *\n * Allows building foreign key definitions with a chainable API.\n * SQL-only feature; NoSQL drivers ignore foreign keys.\n *\n * The operation is pushed when `.references()` is called using a mutable\n * reference — subsequent `.onDelete()` / `.onUpdate()` calls mutate the\n * same definition already queued in pendingOperations.\n *\n * @example\n * ```typescript\n * this.foreign(\"user_id\")\n * .references(\"users\", \"id\")\n * .onDelete(\"cascade\")\n * .onUpdate(\"cascade\");\n * ```\n */\nexport class ForeignKeyBuilder {\n /** Mutable foreign key definition being accumulated */\n private readonly definition: MutableForeignKeyDefinition;\n\n /**\n * Create a new foreign key builder.\n *\n * @param migration - Parent migration instance\n * @param column - Local column name that will reference another table\n */\n public constructor(\n private readonly migration: MigrationLike,\n column: string,\n ) {\n this.definition = {\n column,\n referencesTable: \"\",\n referencesColumn: \"id\",\n onDelete: \"restrict\",\n onUpdate: \"restrict\",\n };\n }\n\n /**\n * Set the constraint name.\n *\n * @param name - Constraint name (auto-generated if not provided)\n * @returns This builder for chaining\n */\n public name(name: string): this {\n this.definition.name = name;\n return this;\n }\n\n /**\n * Set the referenced table and column, and register the foreign key operation.\n *\n * Pushes the operation immediately using a mutable reference — any\n * `.onDelete()` / `.onUpdate()` calls after this will mutate the same\n * definition already queued in pendingOperations.\n *\n * @param table - Referenced table name\n * @param column - Referenced column name (default: \"id\")\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.foreign(\"user_id\").references(\"users\", \"id\");\n * this.foreign(\"category_id\").references(\"categories\"); // defaults to \"id\"\n * ```\n */\n public references(table: string, column = \"id\"): this {\n this.definition.referencesTable = table;\n this.definition.referencesColumn = column;\n this.migration.addForeignKeyOperation(this.definition as ForeignKeyDefinition);\n return this;\n }\n\n /**\n * Set the ON DELETE action.\n *\n * @param action - Action to take when referenced row is deleted\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.foreign(\"user_id\")\n * .references(\"users\")\n * .onDelete(\"cascade\"); // Delete child when parent is deleted\n * ```\n */\n public onDelete(action: ForeignKeyDefinition[\"onDelete\"]): this {\n this.definition.onDelete = action;\n return this;\n }\n\n /**\n * Set the ON UPDATE action.\n *\n * @param action - Action to take when referenced row's key is updated\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.foreign(\"user_id\")\n * .references(\"users\")\n * .onUpdate(\"cascade\"); // Update child when parent key changes\n * ```\n */\n public onUpdate(action: ForeignKeyDefinition[\"onUpdate\"]): this {\n this.definition.onUpdate = action;\n return this;\n }\n\n /**\n * Shorthand for `.onDelete(\"cascade\").onUpdate(\"cascade\")`.\n *\n * @returns This builder for chaining\n *\n * @example\n * ```typescript\n * this.foreign(\"user_id\").references(\"users\").cascadeAll();\n * ```\n */\n public cascadeAll(): this {\n this.definition.onDelete = \"cascade\";\n this.definition.onUpdate = \"cascade\";\n return this;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuCA,IAAa,oBAAb,MAA+B;CAWV;;CATnB,AAAiB;;;;;;;CAQjB,AAAO,YACL,AAAiB,WACjB,QACA;EAFiB;EAGjB,KAAK,aAAa;GAChB;GACA,iBAAiB;GACjB,kBAAkB;GAClB,UAAU;GACV,UAAU;EACZ;CACF;;;;;;;CAQA,AAAO,KAAK,MAAoB;EAC9B,KAAK,WAAW,OAAO;EACvB,OAAO;CACT;;;;;;;;;;;;;;;;;;CAmBA,AAAO,WAAW,OAAe,SAAS,MAAY;EACpD,KAAK,WAAW,kBAAkB;EAClC,KAAK,WAAW,mBAAmB;EACnC,KAAK,UAAU,uBAAuB,KAAK,UAAkC;EAC7E,OAAO;CACT;;;;;;;;;;;;;;CAeA,AAAO,SAAS,QAAgD;EAC9D,KAAK,WAAW,WAAW;EAC3B,OAAO;CACT;;;;;;;;;;;;;;CAeA,AAAO,SAAS,QAAgD;EAC9D,KAAK,WAAW,WAAW;EAC3B,OAAO;CACT;;;;;;;;;;;CAYA,AAAO,aAAmB;EACxB,KAAK,WAAW,WAAW;EAC3B,KAAK,WAAW,WAAW;EAC3B,OAAO;CACT;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"parse-created-at.mjs","names":[],"sources":["../../../../../../../../packages/cascade/src/migration/parse-created-at.ts"],"sourcesContent":["/**\n * Parse a migration's `createdAt` stamp into a `Date`.\n *\n * Migration filenames generated by the framework carry a\n * `MM-DD-YYYY_HH-MM-SS` prefix, which **`new Date()` cannot parse** — it\n * returns `Invalid Date`. Anything ordering migrations by timestamp must come\n * through here; using the native constructor silently yields `NaN` and\n * degrades the sort into whatever its tiebreaker is.\n *\n * Supports `MM-DD-YYYY_HH-MM-SS` and `DD-MM-YYYY_HH-MM-SS`, telling them apart\n * by whether the first field exceeds 12 (a month cannot), and falls back to\n * native parsing for ISO strings.\n *\n * @returns the parsed date, or `undefined` when the stamp is unusable.\n */\nexport function parseCreatedAt(createdAt: string): Date | undefined {\n const match = createdAt.match(/^(\\d{2})-(\\d{2})-(\\d{4})_(\\d{2})-(\\d{2})-(\\d{2})$/);\n\n if (match) {\n const [, first, second, year, hour, minute, second_time] = match;\n\n // All six groups are present whenever the pattern matched — but that is a\n // property of the regex literal above, not something the compiler carries\n // to here, so each is `string | undefined`. Returning `undefined` is\n // exactly this function's documented answer for a stamp it cannot use, so\n // the guard costs nothing and removes six assertions.\n if (\n first === undefined ||\n second === undefined ||\n year === undefined ||\n hour === undefined ||\n minute === undefined ||\n second_time === undefined\n ) {\n return undefined;\n }\n\n const firstNum = parseInt(first);\n const secondNum = parseInt(second);\n\n let month: number, day: number;\n\n // Intelligently detect format:\n // If first > 12, it must be DD-MM-YYYY (day can't be month)\n // If second > 12, it must be MM-DD-YYYY (day can't be month)\n // Otherwise, assume MM-DD-YYYY (US format as default)\n if (firstNum > 12) {\n // DD-MM-YYYY format\n day = firstNum;\n month = secondNum;\n } else if (secondNum > 12) {\n // MM-DD-YYYY format\n month = firstNum;\n day = secondNum;\n } else {\n // Ambiguous — default to MM-DD-YYYY\n month = firstNum;\n day = secondNum;\n }\n\n const date = new Date(\n parseInt(year),\n month - 1, // JavaScript months are 0-indexed\n day,\n parseInt(hour),\n parseInt(minute),\n parseInt(second_time),\n );\n\n // Validate the date is actually valid\n if (isNaN(date.getTime())) {\n return undefined;\n }\n\n return date;\n }\n\n // Fallback to standard Date parsing for ISO strings\n try {\n const date = new Date(createdAt);\n\n return isNaN(date.getTime()) ? undefined : date;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Compare two migration timestamps for ordering.\n *\n * Shared by every migration comparator so they cannot drift apart: a stamp\n * that parses always sorts before one that doesn't, and two unparseable\n * stamps are equal (leaving the caller's own tiebreaker to decide).\n *\n * Returns `undefined` when the timestamps do not settle the comparison.\n */\nexport function compareCreatedAt(\n a: string | undefined,\n b: string | undefined,\n): number | undefined {\n const dateA = a ? parseCreatedAt(a) : undefined;\n const dateB = b ? parseCreatedAt(b) : undefined;\n\n if (dateA && dateB) {\n const difference = dateA.getTime() - dateB.getTime();\n\n return difference === 0 ? undefined : difference;\n }\n\n if (dateA) {\n return -1;\n }\n\n if (dateB) {\n return 1;\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,SAAgB,eAAe,WAAqC;CAClE,MAAM,QAAQ,UAAU,MAAM,mDAAmD;CAEjF,IAAI,OAAO;EACT,MAAM,GAAG,OAAO,QAAQ,MAAM,MAAM,QAAQ,eAAe;EAO3D,IACE,UAAU,UACV,WAAW,UACX,SAAS,UACT,SAAS,UACT,WAAW,UACX,gBAAgB,QAEhB;EAGF,MAAM,WAAW,SAAS,KAAK;EAC/B,MAAM,YAAY,SAAS,MAAM;EAEjC,IAAI,OAAe;EAMnB,IAAI,WAAW,IAAI;GAEjB,MAAM;GACN,QAAQ;EACV,OAAO,IAAI,YAAY,IAAI;GAEzB,QAAQ;GACR,MAAM;EACR,OAAO;GAEL,QAAQ;GACR,MAAM;EACR;EAEA,MAAM,OAAO,IAAI,KACf,SAAS,IAAI,GACb,QAAQ,GACR,KACA,SAAS,IAAI,GACb,SAAS,MAAM,GACf,SAAS,WAAW,CACtB;EAGA,IAAI,MAAM,KAAK,QAAQ,CAAC,GACtB;EAGF,OAAO;CACT;CAGA,IAAI;EACF,MAAM,OAAO,IAAI,KAAK,SAAS;EAE/B,OAAO,MAAM,KAAK,QAAQ,CAAC,IAAI,SAAY;CAC7C,QAAQ;EACN;CACF;AACF;;;;;;;;;;AAWA,SAAgB,iBACd,GACA,GACoB;CACpB,MAAM,QAAQ,IAAI,eAAe,CAAC,IAAI;CACtC,MAAM,QAAQ,IAAI,eAAe,CAAC,IAAI;CAEtC,IAAI,SAAS,OAAO;EAClB,MAAM,aAAa,MAAM,QAAQ,IAAI,MAAM,QAAQ;EAEnD,OAAO,eAAe,IAAI,SAAY;CACxC;CAEA,IAAI,OACF,OAAO;CAGT,IAAI,OACF,OAAO;AAIX"}
1
+ {"version":3,"file":"parse-created-at.mjs","names":[],"sources":["../../../../../../../../packages/cascade/src/migration/parse-created-at.ts"],"sourcesContent":["/**\n * Parse a migration's `createdAt` stamp into a `Date`.\n *\n * Migration filenames generated by the framework carry a\n * `MM-DD-YYYY_HH-MM-SS` prefix, which **`new Date()` cannot parse** — it\n * returns `Invalid Date`. Anything ordering migrations by timestamp must come\n * through here; using the native constructor silently yields `NaN` and\n * degrades the sort into whatever its tiebreaker is.\n *\n * Supports `MM-DD-YYYY_HH-MM-SS` and `DD-MM-YYYY_HH-MM-SS`, telling them apart\n * by whether the first field exceeds 12 (a month cannot), and falls back to\n * native parsing for ISO strings.\n *\n * @returns the parsed date, or `undefined` when the stamp is unusable.\n */\nexport function parseCreatedAt(createdAt: string): Date | undefined {\n const match = createdAt.match(/^(\\d{2})-(\\d{2})-(\\d{4})_(\\d{2})-(\\d{2})-(\\d{2})$/);\n\n if (match) {\n const [, first, second, year, hour, minute, second_time] = match;\n\n // All six groups are present whenever the pattern matched — but that is a\n // property of the regex literal above, not something the compiler carries\n // to here, so each is `string | undefined`. Returning `undefined` is\n // exactly this function's documented answer for a stamp it cannot use, so\n // the guard costs nothing and removes six assertions.\n if (\n first === undefined ||\n second === undefined ||\n year === undefined ||\n hour === undefined ||\n minute === undefined ||\n second_time === undefined\n ) {\n return undefined;\n }\n\n const firstNum = parseInt(first);\n const secondNum = parseInt(second);\n\n let month: number, day: number;\n\n // Intelligently detect format:\n // If first > 12, it must be DD-MM-YYYY (day can't be month)\n // If second > 12, it must be MM-DD-YYYY (day can't be month)\n // Otherwise, assume MM-DD-YYYY (US format as default)\n if (firstNum > 12) {\n // DD-MM-YYYY format\n day = firstNum;\n month = secondNum;\n } else if (secondNum > 12) {\n // MM-DD-YYYY format\n month = firstNum;\n day = secondNum;\n } else {\n // Ambiguous — default to MM-DD-YYYY\n month = firstNum;\n day = secondNum;\n }\n\n const date = new Date(\n parseInt(year),\n month - 1, // JavaScript months are 0-indexed\n day,\n parseInt(hour),\n parseInt(minute),\n parseInt(second_time),\n );\n\n // Validate the date is actually valid\n if (isNaN(date.getTime())) {\n return undefined;\n }\n\n return date;\n }\n\n // Fallback to standard Date parsing for ISO strings\n try {\n const date = new Date(createdAt);\n\n return isNaN(date.getTime()) ? undefined : date;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Compare two migration timestamps for ordering.\n *\n * Shared by every migration comparator so they cannot drift apart: a stamp\n * that parses always sorts before one that doesn't, and two unparseable\n * stamps are equal (leaving the caller's own tiebreaker to decide).\n *\n * Returns `undefined` when the timestamps do not settle the comparison.\n */\nexport function compareCreatedAt(a: string | undefined, b: string | undefined): number | undefined {\n const dateA = a ? parseCreatedAt(a) : undefined;\n const dateB = b ? parseCreatedAt(b) : undefined;\n\n if (dateA && dateB) {\n const difference = dateA.getTime() - dateB.getTime();\n\n return difference === 0 ? undefined : difference;\n }\n\n if (dateA) {\n return -1;\n }\n\n if (dateB) {\n return 1;\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,SAAgB,eAAe,WAAqC;CAClE,MAAM,QAAQ,UAAU,MAAM,mDAAmD;CAEjF,IAAI,OAAO;EACT,MAAM,GAAG,OAAO,QAAQ,MAAM,MAAM,QAAQ,eAAe;EAO3D,IACE,UAAU,UACV,WAAW,UACX,SAAS,UACT,SAAS,UACT,WAAW,UACX,gBAAgB,QAEhB;EAGF,MAAM,WAAW,SAAS,KAAK;EAC/B,MAAM,YAAY,SAAS,MAAM;EAEjC,IAAI,OAAe;EAMnB,IAAI,WAAW,IAAI;GAEjB,MAAM;GACN,QAAQ;EACV,OAAO,IAAI,YAAY,IAAI;GAEzB,QAAQ;GACR,MAAM;EACR,OAAO;GAEL,QAAQ;GACR,MAAM;EACR;EAEA,MAAM,OAAO,IAAI,KACf,SAAS,IAAI,GACb,QAAQ,GACR,KACA,SAAS,IAAI,GACb,SAAS,MAAM,GACf,SAAS,WAAW,CACtB;EAGA,IAAI,MAAM,KAAK,QAAQ,CAAC,GACtB;EAGF,OAAO;CACT;CAGA,IAAI;EACF,MAAM,OAAO,IAAI,KAAK,SAAS;EAE/B,OAAO,MAAM,KAAK,QAAQ,CAAC,IAAI,SAAY;CAC7C,QAAQ;EACN;CACF;AACF;;;;;;;;;;AAWA,SAAgB,iBAAiB,GAAuB,GAA2C;CACjG,MAAM,QAAQ,IAAI,eAAe,CAAC,IAAI;CACtC,MAAM,QAAQ,IAAI,eAAe,CAAC,IAAI;CAEtC,IAAI,SAAS,OAAO;EAClB,MAAM,aAAa,MAAM,QAAQ,IAAI,MAAM,QAAQ;EAEnD,OAAO,eAAe,IAAI,SAAY;CACxC;CAEA,IAAI,OACF,OAAO;CAGT,IAAI,OACF,OAAO;AAIX"}
@@ -1 +1 @@
1
- {"version":3,"file":"sql-grammar.mjs","names":[],"sources":["../../../../../../../../packages/cascade/src/migration/sql-grammar.ts"],"sourcesContent":["import { compareCreatedAt } from \"./parse-created-at\";\nimport type { SQLStatementType, TaggedSQL } from \"./types\";\n\n/**\n * Parses and sorts SQL statements globally based on their execution phase,\n * and classifies statements by their semantic type.\n */\nexport class SQLGrammar {\n /**\n * Determine the execution phase of a SQL statement (1–6).\n *\n * Phase ordering ensures DDL operations run in dependency-safe order\n * regardless of which migration file they originate from.\n *\n * | Phase | Statements |\n * |-------|-----------------------------------------------|\n * | 1 | CREATE EXTENSION, TYPE, DOMAIN, SCHEMA |\n * | 2 | CREATE TABLE |\n * | 3 | ADD COLUMN, ADD PRIMARY KEY |\n * | 4 | CREATE INDEX, ADD FOREIGN KEY |\n * | 5 | DROP COLUMN, ALTER COLUMN, DROP TABLE |\n * | 6 | Raw / unclassified |\n *\n * @example\n * SQLGrammar.phase(\"CREATE EXTENSION IF NOT EXISTS vector\"); // => 1\n * SQLGrammar.phase(\"ALTER TABLE users ADD COLUMN email TEXT\"); // => 3\n */\n public static phase(sql: string): 1 | 2 | 3 | 4 | 5 | 6 {\n const s = sql.trim().toUpperCase();\n\n // Phase 1: Preparation (Extensions, Enums, Domains, Types)\n if (\n s.startsWith(\"CREATE EXTENSION\") ||\n s.startsWith(\"CREATE TYPE\") ||\n s.startsWith(\"CREATE DOMAIN\") ||\n s.startsWith(\"CREATE SCHEMA\")\n ) {\n return 1;\n }\n\n // Phase 2: Table Creation\n if (s.startsWith(\"CREATE TABLE\")) {\n return 2;\n }\n\n // Phase 3 / 4 / 5: ALTER TABLE — broken down by clause\n if (s.startsWith(\"ALTER TABLE\")) {\n if (s.includes(\"ADD CONSTRAINT\") && s.includes(\"FOREIGN KEY\")) return 4;\n if (s.includes(\"DROP COLUMN\") || s.includes(\"DROP CONSTRAINT\") || s.includes(\"ALTER COLUMN\")) return 5;\n if (s.includes(\"ADD COLUMN\")) return 3;\n if (s.includes(\"ADD CONSTRAINT\") && s.includes(\"PRIMARY KEY\")) return 3;\n }\n\n // Phase 4: Index Creation\n if (s.startsWith(\"CREATE INDEX\") || s.startsWith(\"CREATE UNIQUE INDEX\")) {\n return 4;\n }\n\n // Phase 5: Destructive table/index operations\n if (s.startsWith(\"DROP TABLE\") || s.startsWith(\"TRUNCATE TABLE\") || s.startsWith(\"DROP INDEX\")) {\n return 5;\n }\n\n // Phase 6: Raw / unclassified (DML, triggers, procedures, views)\n return 6;\n }\n\n /**\n * Classify a SQL statement into its semantic statement type.\n *\n * This is independent of execution phase — it identifies *what* a statement\n * does, not *when* it should run. Use this for pre-flight checks, dry-run\n * display, selective filtering, and extension detection.\n *\n * @example\n * SQLGrammar.classify(\"CREATE EXTENSION IF NOT EXISTS vector\");\n * // => \"CREATE_EXTENSION\"\n *\n * SQLGrammar.classify(\"ALTER TABLE users ADD COLUMN email TEXT\");\n * // => \"ADD_COLUMN\"\n */\n public static classify(sql: string): SQLStatementType {\n const s = sql.trim().toUpperCase();\n\n if (s.startsWith(\"CREATE EXTENSION\")) return \"CREATE_EXTENSION\";\n if (s.startsWith(\"CREATE SCHEMA\")) return \"CREATE_SCHEMA\";\n if (s.startsWith(\"CREATE TYPE\")) return \"CREATE_TYPE\";\n if (s.startsWith(\"CREATE DOMAIN\")) return \"CREATE_DOMAIN\";\n if (s.startsWith(\"CREATE TABLE\")) return \"CREATE_TABLE\";\n if (s.startsWith(\"DROP TABLE\")) return \"DROP_TABLE\";\n if (s.startsWith(\"TRUNCATE TABLE\")) return \"TRUNCATE_TABLE\";\n if (s.startsWith(\"DROP INDEX\")) return \"DROP_INDEX\";\n\n // Must check UNIQUE before plain INDEX to avoid misclassification\n if (s.startsWith(\"CREATE UNIQUE INDEX\")) return \"CREATE_UNIQUE_INDEX\";\n if (s.startsWith(\"CREATE INDEX\")) return \"CREATE_INDEX\";\n\n if (s.startsWith(\"ALTER TABLE\")) {\n if (s.includes(\"ADD CONSTRAINT\") && s.includes(\"FOREIGN KEY\")) return \"ADD_FOREIGN_KEY\";\n if (s.includes(\"DROP CONSTRAINT\") && s.includes(\"FOREIGN KEY\")) return \"DROP_FOREIGN_KEY\";\n if (s.includes(\"ADD CONSTRAINT\") && s.includes(\"PRIMARY KEY\")) return \"ADD_PRIMARY_KEY\";\n if (s.includes(\"DROP CONSTRAINT\")) return \"DROP_PRIMARY_KEY\";\n if (s.includes(\"ADD COLUMN\")) return \"ADD_COLUMN\";\n if (s.includes(\"DROP COLUMN\")) return \"DROP_COLUMN\";\n if (s.includes(\"RENAME COLUMN\")) return \"RENAME_COLUMN\";\n if (s.includes(\"RENAME TO\")) return \"RENAME_TABLE\";\n if (s.includes(\"ALTER COLUMN\")) return \"MODIFY_COLUMN\";\n }\n\n return \"RAW\";\n }\n\n /**\n * Extract the extension name from a CREATE EXTENSION statement.\n *\n * Returns undefined if the statement is not a CREATE EXTENSION statement\n * or the name cannot be parsed.\n *\n * @example\n * SQLGrammar.extractExtensionName(\"CREATE EXTENSION IF NOT EXISTS vector\");\n * // => \"vector\"\n *\n * SQLGrammar.extractExtensionName(\"CREATE EXTENSION postgis\");\n * // => \"postgis\"\n */\n public static extractExtensionName(sql: string): string | undefined {\n // Matches: CREATE EXTENSION [IF NOT EXISTS] <name>\n const match = sql\n .trim()\n .match(/^CREATE\\s+EXTENSION\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(\\w+)/i);\n\n return match?.[1]?.toLowerCase();\n }\n\n /**\n * Sort an array of tagged SQL statements by phase, then creation date, then migration name.\n *\n * This is the sort that decides **execution order** — it runs across every\n * pending migration's statements at once, after the migration list itself\n * has been ordered, so whatever it decides is final.\n *\n * The creation date must go through {@link compareCreatedAt}. Parsing these\n * stamps with `new Date()` returns `Invalid Date` for the framework's own\n * `MM-DD-YYYY_HH-MM-SS` filename format, which collapsed every timestamp to\n * the same value and quietly handed the whole ordering to the alphabetical\n * tiebreaker below — running, for example, a January 2026 migration before a\n * December 2025 one.\n */\n public static sort(statements: TaggedSQL[]): TaggedSQL[] {\n return statements.slice().sort((a, b) => {\n // 1. Sort by Phase (ascending)\n if (a.phase !== b.phase) {\n return a.phase - b.phase;\n }\n\n // 2. Sort by CreatedAt (within same phase)\n const byCreatedAt = compareCreatedAt(a.createdAt, b.createdAt);\n\n if (byCreatedAt !== undefined) {\n return byCreatedAt;\n }\n\n // 3. Sort by Migration Name (tie-breaker)\n const nameA = a.migrationName || \"\";\n const nameB = b.migrationName || \"\";\n return nameA.localeCompare(nameB);\n });\n }\n}\n"],"mappings":";;;;;;;AAOA,IAAa,aAAb,MAAwB;;;;;;;;;;;;;;;;;;;;CAoBtB,OAAc,MAAM,KAAoC;EACtD,MAAM,IAAI,IAAI,KAAK,CAAC,CAAC,YAAY;EAGjC,IACE,EAAE,WAAW,kBAAkB,KAC/B,EAAE,W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a,GAAG,OAAO;GACtE,IAAI,EAAE,SAAS,iBAAiB,KAAK,EAAE,SAAS,aAAa,GAAG,OAAO;GACvE,IAAI,EAAE,SAAS,gBAAgB,KAAK,EAAE,SAAS,aAAa,GAAG,OAAO;GACtE,IAAI,EAAE,SAAS,iBAAiB,GAAG,OAAO;GAC1C,IAAI,EAAE,SAAS,YAAY,GAAG,OAAO;GACrC,IAAI,EAAE,SAAS,aAAa,GAAG,OAAO;GACtC,IAAI,EAAE,SAAS,eAAe,GAAG,OAAO;GACxC,IAAI,EAAE,SAAS,WAAW,GAAG,OAAO;GACpC,IAAI,EAAE,SAAS,cAAc,GAAG,OAAO;EACzC;EAEA,OAAO;CACT;;;;;;;;;;;;;;CAeA,OAAc,qBAAqB,KAAiC;EAMlE,OAJc,IACX,KAAK,CAAC,CACN,MAAM,uDAEE,CAAC,GAAG,EAAE,EAAE,YAAY;CACjC;;;;;;;;;;;;;;;CAgBA,OAAc,KAAK,YAAsC;EACvD,OAAO,WAAW,MAAM,CAAC,CAAC,MAAM,GAAG,MAAM;GAEvC,IAAI,EAAE,UAAU,EAAE,OAChB,OAAO,EAAE,QAAQ,EAAE;GAIrB,MAAM,cAAc,iBAAiB,EAAE,WAAW,EAAE,SAAS;GAE7D,IAAI,gBAAgB,QAClB,OAAO;GAIT,MAAM,QAAQ,EAAE,iBAAiB;GACjC,MAAM,QAAQ,EAAE,iBAAiB;GACjC,OAAO,MAAM,cAAc,KAAK;EAClC,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"sql-grammar.mjs","names":[],"sources":["../../../../../../../../packages/cascade/src/migration/sql-grammar.ts"],"sourcesContent":["import { compareCreatedAt } from \"./parse-created-at\";\nimport type { SQLStatementType, TaggedSQL } from \"./types\";\n\n/**\n * Parses and sorts SQL statements globally based on their execution phase,\n * and classifies statements by their semantic type.\n */\nexport class SQLGrammar {\n /**\n * Determine the execution phase of a SQL statement (1–6).\n *\n * Phase ordering ensures DDL operations run in dependency-safe order\n * regardless of which migration file they originate from.\n *\n * | Phase | Statements |\n * |-------|-----------------------------------------------|\n * | 1 | CREATE EXTENSION, TYPE, DOMAIN, SCHEMA |\n * | 2 | CREATE TABLE |\n * | 3 | ADD COLUMN, ADD PRIMARY KEY |\n * | 4 | CREATE INDEX, ADD FOREIGN KEY |\n * | 5 | DROP COLUMN, ALTER COLUMN, DROP TABLE |\n * | 6 | Raw / unclassified |\n *\n * @example\n * SQLGrammar.phase(\"CREATE EXTENSION IF NOT EXISTS vector\"); // => 1\n * SQLGrammar.phase(\"ALTER TABLE users ADD COLUMN email TEXT\"); // => 3\n */\n public static phase(sql: string): 1 | 2 | 3 | 4 | 5 | 6 {\n const s = sql.trim().toUpperCase();\n\n // Phase 1: Preparation (Extensions, Enums, Domains, Types)\n if (\n s.startsWith(\"CREATE EXTENSION\") ||\n s.startsWith(\"CREATE TYPE\") ||\n s.startsWith(\"CREATE DOMAIN\") ||\n s.startsWith(\"CREATE SCHEMA\")\n ) {\n return 1;\n }\n\n // Phase 2: Table Creation\n if (s.startsWith(\"CREATE TABLE\")) {\n return 2;\n }\n\n // Phase 3 / 4 / 5: ALTER TABLE — broken down by clause\n if (s.startsWith(\"ALTER TABLE\")) {\n if (s.includes(\"ADD CONSTRAINT\") && s.includes(\"FOREIGN KEY\")) return 4;\n if (s.includes(\"DROP COLUMN\") || s.includes(\"DROP CONSTRAINT\") || s.includes(\"ALTER COLUMN\"))\n return 5;\n if (s.includes(\"ADD COLUMN\")) return 3;\n if (s.includes(\"ADD CONSTRAINT\") && s.includes(\"PRIMARY KEY\")) return 3;\n }\n\n // Phase 4: Index Creation\n if (s.startsWith(\"CREATE INDEX\") || s.startsWith(\"CREATE UNIQUE INDEX\")) {\n return 4;\n }\n\n // Phase 5: Destructive table/index operations\n if (\n s.startsWith(\"DROP TABLE\") ||\n s.startsWith(\"TRUNCATE TABLE\") ||\n s.startsWith(\"DROP INDEX\")\n ) {\n return 5;\n }\n\n // Phase 6: Raw / unclassified (DML, triggers, procedures, views)\n return 6;\n }\n\n /**\n * Classify a SQL statement into its semantic statement type.\n *\n * This is independent of execution phase — it identifies *what* a statement\n * does, not *when* it should run. Use this for pre-flight checks, dry-run\n * display, selective filtering, and extension detection.\n *\n * @example\n * SQLGrammar.classify(\"CREATE EXTENSION IF NOT EXISTS vector\");\n * // => \"CREATE_EXTENSION\"\n *\n * SQLGrammar.classify(\"ALTER TABLE users ADD COLUMN email TEXT\");\n * // => \"ADD_COLUMN\"\n */\n public static classify(sql: string): SQLStatementType {\n const s = sql.trim().toUpperCase();\n\n if (s.startsWith(\"CREATE EXTENSION\")) return \"CREATE_EXTENSION\";\n if (s.startsWith(\"CREATE SCHEMA\")) return \"CREATE_SCHEMA\";\n if (s.startsWith(\"CREATE TYPE\")) return \"CREATE_TYPE\";\n if (s.startsWith(\"CREATE DOMAIN\")) return \"CREATE_DOMAIN\";\n if (s.startsWith(\"CREATE TABLE\")) return \"CREATE_TABLE\";\n if (s.startsWith(\"DROP TABLE\")) return \"DROP_TABLE\";\n if (s.startsWith(\"TRUNCATE TABLE\")) return \"TRUNCATE_TABLE\";\n if (s.startsWith(\"DROP INDEX\")) return \"DROP_INDEX\";\n\n // Must check UNIQUE before plain INDEX to avoid misclassification\n if (s.startsWith(\"CREATE UNIQUE INDEX\")) return \"CREATE_UNIQUE_INDEX\";\n if (s.startsWith(\"CREATE INDEX\")) return \"CREATE_INDEX\";\n\n if (s.startsWith(\"ALTER TABLE\")) {\n if (s.includes(\"ADD CONSTRAINT\") && s.includes(\"FOREIGN KEY\")) return \"ADD_FOREIGN_KEY\";\n if (s.includes(\"DROP CONSTRAINT\") && s.includes(\"FOREIGN KEY\")) return \"DROP_FOREIGN_KEY\";\n if (s.includes(\"ADD CONSTRAINT\") && s.includes(\"PRIMARY KEY\")) return \"ADD_PRIMARY_KEY\";\n if (s.includes(\"DROP CONSTRAINT\")) return \"DROP_PRIMARY_KEY\";\n if (s.includes(\"ADD COLUMN\")) return \"ADD_COLUMN\";\n if (s.includes(\"DROP COLUMN\")) return \"DROP_COLUMN\";\n if (s.includes(\"RENAME COLUMN\")) return \"RENAME_COLUMN\";\n if (s.includes(\"RENAME TO\")) return \"RENAME_TABLE\";\n if (s.includes(\"ALTER COLUMN\")) return \"MODIFY_COLUMN\";\n }\n\n return \"RAW\";\n }\n\n /**\n * Extract the extension name from a CREATE EXTENSION statement.\n *\n * Returns undefined if the statement is not a CREATE EXTENSION statement\n * or the name cannot be parsed.\n *\n * @example\n * SQLGrammar.extractExtensionName(\"CREATE EXTENSION IF NOT EXISTS vector\");\n * // => \"vector\"\n *\n * SQLGrammar.extractExtensionName(\"CREATE EXTENSION postgis\");\n * // => \"postgis\"\n */\n public static extractExtensionName(sql: string): string | undefined {\n // Matches: CREATE EXTENSION [IF NOT EXISTS] <name>\n const match = sql.trim().match(/^CREATE\\s+EXTENSION\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(\\w+)/i);\n\n return match?.[1]?.toLowerCase();\n }\n\n /**\n * Sort an array of tagged SQL statements by phase, then creation date, then migration name.\n *\n * This is the sort that decides **execution order** — it runs across every\n * pending migration's statements at once, after the migration list itself\n * has been ordered, so whatever it decides is final.\n *\n * The creation date must go through {@link compareCreatedAt}. Parsing these\n * stamps with `new Date()` returns `Invalid Date` for the framework's own\n * `MM-DD-YYYY_HH-MM-SS` filename format, which collapsed every timestamp to\n * the same value and quietly handed the whole ordering to the alphabetical\n * tiebreaker below — running, for example, a January 2026 migration before a\n * December 2025 one.\n */\n public static sort(statements: TaggedSQL[]): TaggedSQL[] {\n return statements.slice().sort((a, b) => {\n // 1. Sort by Phase (ascending)\n if (a.phase !== b.phase) {\n return a.phase - b.phase;\n }\n\n // 2. Sort by CreatedAt (within same phase)\n const byCreatedAt = compareCreatedAt(a.createdAt, b.createdAt);\n\n if (byCreatedAt !== undefined) {\n return byCreatedAt;\n }\n\n // 3. Sort by Migration Name (tie-breaker)\n const nameA = a.migrationName || \"\";\n const nameB = b.migrationName || \"\";\n return nameA.localeCompare(nameB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W,YAAY,GAAG,OAAO;EAGvC,IAAI,EAAE,WAAW,qBAAqB,GAAG,OAAO;EAChD,IAAI,EAAE,WAAW,cAAc,GAAG,OAAO;EAEzC,IAAI,EAAE,WAAW,aAAa,GAAG;GAC/B,IAAI,EAAE,SAAS,gBAAgB,KAAK,EAAE,SAAS,aAAa,GAAG,OAAO;GACtE,IAAI,EAAE,SAAS,iBAAiB,KAAK,EAAE,SAAS,aAAa,GAAG,OAAO;GACvE,IAAI,EAAE,SAAS,gBAAgB,KAAK,EAAE,SAAS,aAAa,GAAG,OAAO;GACtE,IAAI,EAAE,SAAS,iBAAiB,GAAG,OAAO;GAC1C,IAAI,EAAE,SAAS,YAAY,GAAG,OAAO;GACrC,IAAI,EAAE,SAAS,aAAa,GAAG,OAAO;GACtC,IAAI,EAAE,SAAS,eAAe,GAAG,OAAO;GACxC,IAAI,EAAE,SAAS,WAAW,GAAG,OAAO;GACpC,IAAI,EAAE,SAAS,cAAc,GAAG,OAAO;EACzC;EAEA,OAAO;CACT;;;;;;;;;;;;;;CAeA,OAAc,qBAAqB,KAAiC;EAIlE,OAFc,IAAI,KAAK,CAAC,CAAC,MAAM,uDAEpB,CAAC,GAAG,EAAE,EAAE,YAAY;CACjC;;;;;;;;;;;;;;;CAgBA,OAAc,KAAK,YAAsC;EACvD,OAAO,WAAW,MAAM,CAAC,CAAC,MAAM,GAAG,MAAM;GAEvC,IAAI,EAAE,UAAU,EAAE,OAChB,OAAO,EAAE,QAAQ,EAAE;GAIrB,MAAM,cAAc,iBAAiB,EAAE,WAAW,EAAE,SAAS;GAE7D,IAAI,gBAAgB,QAClB,OAAO;GAIT,MAAM,QAAQ,EAAE,iBAAiB;GACjC,MAAM,QAAQ,EAAE,iBAAiB;GACjC,OAAO,MAAM,cAAc,KAAK;EAClC,CAAC;CACH;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"generate-model-id.mjs","names":[],"sources":["../../../../../../../../packages/cascade/src/model/generate-model-id.ts"],"sourcesContent":["import type { ChildModel, Model } from \"./model\";\n\n/**\n * Generate the next model id using the model's configured sequence options.\n *\n * This is shared by normal inserts and MongoDB upserts so both write paths\n * resolve random and configured sequence settings identically.\n */\nexport async function generateModelId<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n): Promise<number | undefined> {\n const idGenerator = ModelClass.getDataSource().idGenerator;\n\n if (!idGenerator) {\n return undefined;\n }\n\n const randomInt = (min: number, max: number) =>\n Math.floor(Math.random() * (max - min + 1)) + min;\n const initialId = ModelClass.initialId\n ? ModelClass.initialId\n : ModelClass.randomInitialId\n ? typeof ModelClass.randomInitialId === \"function\"\n ? ModelClass.randomInitialId()\n : randomInt(10000, 499999)\n : 1;\n const incrementIdBy = ModelClass.randomIncrement\n ? typeof ModelClass.randomIncrement === \"function\"\n ? ModelClass.randomIncrement()\n : randomInt(1, 10)\n : ModelClass.incrementIdBy || 1;\n\n return await idGenerator.generateNextId({\n table: ModelClass.table,\n initialId,\n incrementIdBy,\n });\n}\n"],"mappings":";;;;;;;AAQA,eAAsB,gBACpB,YAC6B;CAC7B,MAAM,cAAc,WAAW,cAAc,CAAC,CAAC;CAE/C,IAAI,CAAC,aACH;CAGF,MAAM,aAAa,KAAa,QAC9B,KAAK,MAAM,KAAK,OAAO,KAAK,MAAM,MAAM,EAAE,IAAI;CAChD,MAAM,YAAY,WAAW,YACzB,WAAW,YACX,WAAW,kBACT,OAAO,WAAW,oBAAoB,aACpC,WAAW,gBAAgB,IAC3B,UAAU,KAAO,MAAM,IACzB;CACN,MAAM,gBAAgB,WAAW,kBAC7B,OAAO,WAAW,oBAAoB,aACpC,WAAW,gBAAgB,IAC3B,UAAU,GAAG,EAAE,IACjB,WAAW,iBAAiB;CAEhC,OAAO,MAAM,YAAY,eAAe;EACtC,OAAO,WAAW;EAClB;EACA;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"generate-model-id.mjs","names":[],"sources":["../../../../../../../../packages/cascade/src/model/generate-model-id.ts"],"sourcesContent":["import type { ChildModel, Model } from \"./model\";\n\n/**\n * Generate the next model id using the model's configured sequence options.\n *\n * This is shared by normal inserts and MongoDB upserts so both write paths\n * resolve random and configured sequence settings identically.\n */\nexport async function generateModelId<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n): Promise<number | undefined> {\n const idGenerator = ModelClass.getDataSource().idGenerator;\n\n if (!idGenerator) {\n return undefined;\n }\n\n const randomInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min;\n const initialId = ModelClass.initialId\n ? ModelClass.initialId\n : ModelClass.randomInitialId\n ? typeof ModelClass.randomInitialId === \"function\"\n ? ModelClass.randomInitialId()\n : randomInt(10000, 499999)\n : 1;\n const incrementIdBy = ModelClass.randomIncrement\n ? typeof ModelClass.randomIncrement === \"function\"\n ? ModelClass.randomIncrement()\n : randomInt(1, 10)\n : ModelClass.incrementIdBy || 1;\n\n return await idGenerator.generateNextId({\n table: ModelClass.table,\n initialId,\n incrementIdBy,\n });\n}\n"],"mappings":";;;;;;;AAQA,eAAsB,gBACpB,YAC6B;CAC7B,MAAM,cAAc,WAAW,cAAc,CAAC,CAAC;CAE/C,IAAI,CAAC,aACH;CAGF,MAAM,aAAa,KAAa,QAAgB,KAAK,MAAM,KAAK,OAAO,KAAK,MAAM,MAAM,EAAE,IAAI;CAC9F,MAAM,YAAY,WAAW,YACzB,WAAW,YACX,WAAW,kBACT,OAAO,WAAW,oBAAoB,aACpC,WAAW,gBAAgB,IAC3B,UAAU,KAAO,MAAM,IACzB;CACN,MAAM,gBAAgB,WAAW,kBAC7B,OAAO,WAAW,oBAAoB,aACpC,WAAW,gBAAgB,IAC3B,UAAU,GAAG,EAAE,IACjB,WAAW,iBAAiB;CAEhC,OAAO,MAAM,YAAY,eAAe;EACtC,OAAO,WAAW;EAClB;EACA;CACF,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"accessor-methods.mjs","names":[],"sources":["../../../../../../../../../packages/cascade/src/model/methods/accessor-methods.ts"],"sourcesContent":["import { get, merge, only, set, unset } from \"@mongez/reinforcements\";\nimport { pruneEmptyParents } from \"../../utils/prune-empty-parents\";\nimport type { Model } from \"../model\";\n\n/**\n * Sentinel symbol to distinguish a genuinely missing field from a field\n * whose value is `undefined`. Encapsulated here — callers use `hasField()`.\n */\nconst MISSING_VALUE = Symbol(\"missing\");\n\nexport function getFieldValue(model: Model, field: string, defaultValue?: unknown): any {\n return get(model.data, field, defaultValue);\n}\n\nexport function setFieldValue(model: Model, field: string, value: unknown): Model {\n const path = String(field);\n set(model.data, path, value);\n\n model.dirtyTracker.setAtPath(path, value);\n\n return model;\n}\n\nexport function hasField(model: Model, field: string): boolean {\n return get(model.data, field, MISSING_VALUE as any) !== MISSING_VALUE;\n}\n\nexport function incrementField(model: Model, field: string, amount?: number): Model {\n const value = getFieldValue(model, field, 0) as number;\n const incrementedValue = value + (amount ?? 1);\n return setFieldValue(model, field, incrementedValue);\n}\n\nexport function decrementField(model: Model, field: string, amount?: number): Model {\n const value = getFieldValue(model, field, 0) as number;\n const decrementedValue = value - (amount ?? 1);\n return setFieldValue(model, field, decrementedValue);\n}\n\n/**\n * Remove fields from the model data.\n *\n * Unsetting the last key of a nested object also removes the parents that this\n * unset left empty (`unset(\"a.b\")` on `{ a: { b: 1 } }` leaves `{}`, not\n * `{ a: {} }`). A parent is pruned only when this unset emptied it: an object\n * the user stored as `{}` is never touched, and arrays are never pruned.\n */\nexport function unsetFields(model: Model, ...fields: string[]): Model {\n const existing = fields.filter(field => hasField(model, field));\n\n model.data = unset(model.data, fields);\n\n for (const field of existing) {\n pruneEmptyParents(model.data, field);\n }\n\n model.dirtyTracker.unset(fields);\n\n return model;\n}\n\n/**\n * Identity columns that a mass-assignment payload may never carry into an\n * already-persisted model. `merge()` is the method request bodies reach\n * (`model.merge(req.body)` / `save({ merge })`), and the primary key is what\n * the UPDATE filter is built from — letting it through means a payload of\n * `{ id: \"<victim-id>\" }` rewrites which document the save targets. Both the\n * configured primary key and the two framework identity columns are dropped,\n * because `id` and `_id` are managed by the writer/driver either way.\n *\n * A NEW model is untouched: creating with an explicit id is a legitimate flow,\n * and the writer itself merges the driver-returned document (`_id`, defaults)\n * back onto the instance before it is marked persisted.\n */\nfunction stripIdentityColumns(\n model: Model,\n values: Record<string, unknown>,\n): Record<string, unknown> {\n if (model.isNew) return values;\n\n const identityColumns = new Set([model.getPrimaryKey(), \"id\", \"_id\"]);\n const blockedKeys = Object.keys(values).filter(key => identityColumns.has(key));\n\n if (blockedKeys.length === 0) return values;\n\n // Copy — the caller's object (often the request body itself) is not ours to mutate.\n const safeValues = { ...values };\n for (const key of blockedKeys) {\n delete safeValues[key];\n }\n\n return safeValues;\n}\n\nexport function mergeFields(model: Model, values: Record<string, unknown>): Model {\n return mergeDriverFields(model, stripIdentityColumns(model, values));\n}\n\n/**\n * Merge a document the DRIVER produced (generated `_id`, `RETURNING *`, DB\n * defaults) back onto the model, identity columns included.\n *\n * Framework-internal counterpart of {@link mergeFields}: the write pipeline is\n * the one caller allowed to set identity columns on an already-persisted\n * instance, because the values come from the database rather than from a\n * request. Never route caller-supplied data through this.\n */\nexport function mergeDriverFields(model: Model, values: Record<string, unknown>): Model {\n model.data = merge(model.data, values) as any;\n model.dirtyTracker.mergeChanges(values);\n return model;\n}\n\nexport function getOnlyFields(model: Model, fields: string[]): Record<string, unknown> {\n return only(model.data, fields);\n}\n\nexport function getStringField(model: Model, key: string, defaultValue?: string): string | undefined {\n return getFieldValue(model, key, defaultValue) as string | undefined;\n}\n\nexport function getNumberField(model: Model, key: string, defaultValue?: number): number | undefined {\n return getFieldValue(model, key, defaultValue) as number | undefined;\n}\n\nexport function getBooleanField(model: Model, key: string, defaultValue?: boolean): boolean | undefined {\n return getFieldValue(model, key, defaultValue) as boolean | undefined;\n}\n"],"mappings":";;;;;;;;AAQA,MAAM,gBAAgB,OAAO,SAAS;AAEtC,SAAgB,cAAc,OAAc,OAAe,cAA6B;CACtF,OAAO,IAAI,MAAM,MAAM,OAAO,YAAY;AAC5C;AAEA,SAAg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wC;CACtF,MAAM,OAAO,MAAM,MAAM,MAAM,MAAM;CACrC,MAAM,aAAa,aAAa,MAAM;CACtC,OAAO;AACT;AAEA,SAAgB,cAAc,OAAc,QAA2C;CACrF,OAAO,KAAK,MAAM,MAAM,MAAM;AAChC;AAEA,SAAgB,eAAe,OAAc,KAAa,cAA2C;CACnG,OAAO,cAAc,OAAO,KAAK,YAAY;AAC/C;AAEA,SAAgB,eAAe,OAAc,KAAa,cAA2C;CACnG,OAAO,cAAc,OAAO,KAAK,YAAY;AAC/C;AAEA,SAAgB,gBAAgB,OAAc,KAAa,cAA6C;CACtG,OAAO,cAAc,OAAO,KAAK,YAAY;AAC/C"}
1
+ {"version":3,"file":"accessor-methods.mjs","names":[],"sources":["../../../../../../../../../packages/cascade/src/model/methods/accessor-methods.ts"],"sourcesContent":["import { get, merge, only, set, unset } from \"@mongez/reinforcements\";\nimport { pruneEmptyParents } from \"../../utils/prune-empty-parents\";\nimport type { Model } from \"../model\";\n\n/**\n * Sentinel symbol to distinguish a genuinely missing field from a field\n * whose value is `undefined`. Encapsulated here — callers use `hasField()`.\n */\nconst MISSING_VALUE = Symbol(\"missing\");\n\nexport function getFieldValue(model: Model, field: string, defaultValue?: unknown): any {\n return get(model.data, field, defaultValue);\n}\n\nexport function setFieldValue(model: Model, field: string, value: unknown): Model {\n const path = String(field);\n set(model.data, path, value);\n\n model.dirtyTracker.setAtPath(path, value);\n\n return model;\n}\n\nexport function hasField(model: Model, field: string): boolean {\n return get(model.data, field, MISSING_VALUE as any) !== MISSING_VALUE;\n}\n\nexport function incrementField(model: Model, field: string, amount?: number): Model {\n const value = getFieldValue(model, field, 0) as number;\n const incrementedValue = value + (amount ?? 1);\n return setFieldValue(model, field, incrementedValue);\n}\n\nexport function decrementField(model: Model, field: string, amount?: number): Model {\n const value = getFieldValue(model, field, 0) as number;\n const decrementedValue = value - (amount ?? 1);\n return setFieldValue(model, field, decrementedValue);\n}\n\n/**\n * Remove fields from the model data.\n *\n * Unsetting the last key of a nested object also removes the parents that this\n * unset left empty (`unset(\"a.b\")` on `{ a: { b: 1 } }` leaves `{}`, not\n * `{ a: {} }`). A parent is pruned only when this unset emptied it: an object\n * the user stored as `{}` is never touched, and arrays are never pruned.\n */\nexport function unsetFields(model: Model, ...fields: string[]): Model {\n const existing = fields.filter((field) => hasField(model, field));\n\n model.data = unset(model.data, fields);\n\n for (const field of existing) {\n pruneEmptyParents(model.data, field);\n }\n\n model.dirtyTracker.unset(fields);\n\n return model;\n}\n\n/**\n * Identity columns that a mass-assignment payload may never carry into an\n * already-persisted model. `merge()` is the method request bodies reach\n * (`model.merge(req.body)` / `save({ merge })`), and the primary key is what\n * the UPDATE filter is built from — letting it through means a payload of\n * `{ id: \"<victim-id>\" }` rewrites which document the save targets. Both the\n * configured primary key and the two framework identity columns are dropped,\n * because `id` and `_id` are managed by the writer/driver either way.\n *\n * A NEW model is untouched: creating with an explicit id is a legitimate flow,\n * and the writer itself merges the driver-returned document (`_id`, defaults)\n * back onto the instance before it is marked persisted.\n */\nfunction stripIdentityColumns(\n model: Model,\n values: Record<string, unknown>,\n): Record<string, unknown> {\n if (model.isNew) return values;\n\n const identityColumns = new Set([model.getPrimaryKey(), \"id\", \"_id\"]);\n const blockedKeys = Object.keys(values).filter((key) => identityColumns.has(key));\n\n if (blockedKeys.length === 0) return values;\n\n // Copy — the caller's object (often the request body itself) is not ours to mutate.\n const safeValues = { ...values };\n for (const key of blockedKeys) {\n delete safeValues[key];\n }\n\n return safeValues;\n}\n\nexport function mergeFields(model: Model, values: Record<string, unknown>): Model {\n return mergeDriverFields(model, stripIdentityColumns(model, values));\n}\n\n/**\n * Merge a document the DRIVER produced (generated `_id`, `RETURNING *`, DB\n * defaults) back onto the model, identity columns included.\n *\n * Framework-internal counterpart of {@link mergeFields}: the write pipeline is\n * the one caller allowed to set identity columns on an already-persisted\n * instance, because the values come from the database rather than from a\n * request. Never route caller-supplied data through this.\n */\nexport function mergeDriverFields(model: Model, values: Record<string, unknown>): Model {\n model.data = merge(model.data, values) as any;\n model.dirtyTracker.mergeChanges(values);\n return model;\n}\n\nexport function getOnlyFields(model: Model, fields: string[]): Record<string, unknown> {\n return only(model.data, fields);\n}\n\nexport function getStringField(\n model: Model,\n key: string,\n defaultValue?: string,\n): string | undefined {\n return getFieldValue(model, key, defaultValue) as string | undefined;\n}\n\nexport function getNumberField(\n model: Model,\n key: string,\n defaultValue?: number,\n): number | undefined {\n return getFieldValue(model, key, defaultValue) as number | undefined;\n}\n\nexport function getBooleanField(\n model: Model,\n key: string,\n defaultValue?: boolean,\n): boolean | undefined {\n return getFieldValue(model, key, defaultValue) as boolean | undefined;\n}\n"],"mappings":";;;;;;;;AAQA,MAAM,gBAAgB,OAAO,SAAS;AAEtC,SAAgB,cAAc,OAAc,OAAe,cAA6B;CACtF,OAAO,IAAI,MAAM,MAAM,OAAO,YAAY;AAC5C;AAEA,SAAgB,cAAc,OAAc,OAAe,OAAuB;CAChF,MAAM,OAAO,OAAO,KAAK;CACzB,IAAI,MAAM,MAAM,MAAM,KAAK;CAE3B,MAAM,aAAa,UAAU,MAAM,KAAK;CAExC,OAAO;AACT;AAEA,SAAgB,SAAS,OAAc,OAAwB;CAC7D,OAAO,IAAI,MAAM,MAAM,OAAO,aAAoB,MAAM;AAC1D;AAEA,SAAgB,eAAe,OAAc,OAAe,QAAwB;CAGlF,OAAO,cAAc,OAAO,OAFd,cAAc,OAAO,OAAO,CACb,KAAK,UAAU,EACO;AACrD;AAEA,SAAgB,eAAe,OAAc,OAAe,QAAwB;CAGlF,OAAO,cAAc,OAAO,OAFd,cAAc,OAAO,OAAO,CACb,KAAK,UAAU,EACO;AACrD;;;;;;;;;AAUA,SAAgB,YAAY,OAAc,GAAG,QAAyB;CACpE,MAAM,WAAW,OAAO,QAAQ,UAAU,SAAS,OAAO,KAAK,CAAC;CAEhE,MAAM,OAAO,MAAM,MAAM,MAAM,MAAM;CAErC,KAAK,MAAM,SAAS,UAClB,kBAAkB,MAAM,MAAM,KAAK;CAGrC,MAAM,aAAa,MAAM,MAAM;CAE/B,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAS,qBACP,OACA,QACyB;CACzB,IAAI,MAAM,OAAO,OAAO;CAExB,MAAM,kBAAkB,IAAI,IAAI;EAAC,MAAM,cAAc;EAAG;EAAM;CAAK,CAAC;CACpE,MAAM,cAAc,OAAO,KAAK,MAAM,CAAC,CAAC,QAAQ,QAAQ,gBAAgB,IAAI,GAAG,CAAC;CAEhF,IAAI,YAAY,WAAW,GAAG,OAAO;CAGrC,MAAM,aAAa,EAAE,GAAG,OAAO;CAC/B,KAAK,MAAM,OAAO,aAChB,OAAO,WAAW;CAGpB,OAAO;AACT;AAEA,SAAgB,YAAY,OAAc,QAAwC;CAChF,OAAO,kBAAkB,OAAO,qBAAqB,OAAO,MAAM,CAAC;AACrE;;;;;;;;;;AAWA,SAAgB,kBAAkB,OAAc,QAAwC;CACtF,MAAM,OAAO,MAAM,MAAM,MAAM,MAAM;CACrC,MAAM,aAAa,aAAa,MAAM;CACtC,OAAO;AACT;AAEA,SAAgB,cAAc,OAAc,QAA2C;CACrF,OAAO,KAAK,MAAM,MAAM,MAAM;AAChC;AAEA,SAAgB,eACd,OACA,KACA,cACoB;CACpB,OAAO,cAAc,OAAO,KAAK,YAAY;AAC/C;AAEA,SAAgB,eACd,OACA,KACA,cACoB;CACpB,OAAO,cAAc,OAAO,KAAK,YAAY;AAC/C;AAEA,SAAgB,gBACd,OACA,KACA,cACqB;CACrB,OAAO,cAAc,OAAO,KAAK,YAAY;AAC/C"}
@@ -1 +1 @@
1
- {"version":3,"file":"dirty-methods.mjs","names":[],"sources":["../../../../../../../../../packages/cascade/src/model/methods/dirty-methods.ts"],"sourcesContent":["import type { Model } from \"../model\";\n\nexport function checkHasChanges(model: Model): boolean {\n return model.dirtyTracker.hasChanges();\n}\n\nexport function checkIsDirty(model: Model, column: string): boolean {\n return model.dirtyTracker.isDirty(column);\n}\n\nexport function getDirtyColumnsWithValues(model: Model): Record<string, { oldValue: unknown; newValue: unknown }> {\n return model.dirtyTracker.getDirtyColumnsWithValues();\n}\n\nexport function getRemovedColumns(model: Model): string[] {\n return model.dirtyTracker.getRemovedColumns();\n}\n\nexport function getDirtyColumns(model: Model): string[] {\n return model.dirtyTracker.getDirtyColumns();\n}\n"],"mappings":";AAEA,SAAgB,gBAAgB,OAAuB;CACrD,OAAO,MAAM,aAAa,WAAW;AACvC;AAEA,SAAgB,aAAa,OAAc,QAAyB;CAClE,OAAO,MAAM,aAAa,QAAQ,MAAM;AAC1C;AAEA,SAAgB,0BAA0B,OAAwE;CAChH,OAAO,MAAM,aAAa,0BAA0B;AACtD;AAEA,SAAgB,kBAAkB,OAAwB;CACxD,OAAO,MAAM,aAAa,kBAAkB;AAC9C;AAEA,SAAgB,gBAAgB,OAAwB;CACtD,OAAO,MAAM,aAAa,gBAAgB;AAC5C"}
1
+ {"version":3,"file":"dirty-methods.mjs","names":[],"sources":["../../../../../../../../../packages/cascade/src/model/methods/dirty-methods.ts"],"sourcesContent":["import type { Model } from \"../model\";\n\nexport function checkHasChanges(model: Model): boolean {\n return model.dirtyTracker.hasChanges();\n}\n\nexport function checkIsDirty(model: Model, column: string): boolean {\n return model.dirtyTracker.isDirty(column);\n}\n\nexport function getDirtyColumnsWithValues(\n model: Model,\n): Record<string, { oldValue: unknown; newValue: unknown }> {\n return model.dirtyTracker.getDirtyColumnsWithValues();\n}\n\nexport function getRemovedColumns(model: Model): string[] {\n return model.dirtyTracker.getRemovedColumns();\n}\n\nexport function getDirtyColumns(model: Model): string[] {\n return model.dirtyTracker.getDirtyColumns();\n}\n"],"mappings":";AAEA,SAAgB,gBAAgB,OAAuB;CACrD,OAAO,MAAM,aAAa,WAAW;AACvC;AAEA,SAAgB,aAAa,OAAc,QAAyB;CAClE,OAAO,MAAM,aAAa,QAAQ,MAAM;AAC1C;AAEA,SAAgB,0BACd,OAC0D;CAC1D,OAAO,MAAM,aAAa,0BAA0B;AACtD;AAEA,SAAgB,kBAAkB,OAAwB;CACxD,OAAO,MAAM,aAAa,kBAAkB;AAC9C;AAEA,SAAgB,gBAAgB,OAAwB;CACtD,OAAO,MAAM,aAAa,gBAAgB;AAC5C"}
@@ -1 +1 @@
1
- {"version":3,"file":"hydration-methods.mjs","names":[],"sources":["../../../../../../../../../packages/cascade/src/model/methods/hydration-methods.ts"],"sourcesContent":["import { clone } from \"@mongez/reinforcements\";\nimport { DateValidator } from \"@warlock.js/seal\";\nimport { RelationHydrator, type ModelSnapshot, type SerializedRelation } from \"../../relations/relation-hydrator\";\nimport type { ChildModel, Model } from \"../model\";\n\n/**\n * Drivers re-inflate any ISO-looking string into a Date. Only fields the model\n * schema declares as dates may be converted, so put every other string back.\n */\nfunction restoreUndeclaredDateStrings<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n original: Record<string, string>,\n data: Record<string, unknown>,\n): void {\n const shape = ModelClass.schema?.schema ?? {};\n\n for (const [key, value] of Object.entries(original)) {\n if (data[key] instanceof Date && !(shape[key] instanceof DateValidator)) {\n data[key] = value;\n }\n }\n}\n\nexport function hydrateModel<TModel extends Model = Model>(\n ModelClass: ChildModel<TModel>,\n data: Record<string, unknown>,\n): TModel {\n const strings: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(data)) {\n if (typeof value === \"string\") strings[key] = value;\n }\n\n const deserialized = ModelClass.getDriver().deserialize(data);\n restoreUndeclaredDateStrings(ModelClass, strings, deserialized);\n\n const model = new ModelClass(deserialized);\n model.isNew = false;\n return model;\n}\n\nexport function modelFromSnapshot<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n snapshot: ModelSnapshot,\n): TModel {\n const model = ModelClass.hydrate(snapshot.data) as TModel;\n RelationHydrator.hydrate(model, ModelClass.relations, snapshot.relations);\n return model;\n}\n\nexport function modelToSnapshot(model: Model): ModelSnapshot {\n const driver = (model.constructor as typeof Model).getDataSource().driver;\n const relations: Record<string, SerializedRelation> = {};\n\n for (const [name, related] of model.loadedRelations) {\n if (related === null) {\n relations[name] = null;\n } else if (Array.isArray(related)) {\n relations[name] = related.map((m) => (m instanceof Object && typeof m.toSnapshot === \"function\" ? m.toSnapshot() : m));\n } else if (related instanceof Object && typeof related.toSnapshot === \"function\") {\n relations[name] = related.toSnapshot();\n }\n }\n\n return {\n data: driver.serialize({ ...model.data }) as Record<string, unknown>,\n relations,\n };\n}\n\nexport function serializeModel(model: Model) {\n return (model.constructor as typeof Model).getDataSource().driver.serialize(model.data);\n}\n\nexport function cloneModel<TModel extends Model>(model: TModel): TModel {\n const clonedData = clone(model.data);\n const ModelClass = model.self();\n const clonedModel = new ModelClass(clonedData) as TModel;\n\n clonedModel.isNew = model.isNew;\n deepFreezeObject(clonedModel.data);\n clonedModel.dirtyTracker.reset();\n\n return clonedModel;\n}\n\nexport function deepFreezeObject<T>(obj: T): T {\n Object.freeze(obj);\n\n Object.getOwnPropertyNames(obj).forEach((prop) => {\n const value = (obj as any)[prop];\n if (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n !Object.isFrozen(value)\n ) {\n deepFreezeObject(value);\n }\n });\n\n return obj;\n}\n\nexport function replaceModelData<TModel extends Model>(\n model: TModel,\n data: Record<string, unknown>,\n): void {\n model.data = data as any;\n model.dirtyTracker.replaceCurrentData(data);\n}\n"],"mappings":";;;;;;;;;AASA,SAAS,6BACP,YACA,UACA,MACM;CACN,MAAM,QAAQ,WAAW,QAAQ,UAAU,CAAC;CAE5C,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,GAChD,IAAI,KAAK,gBAAgB,QAAQ,EAAE,MAAM,gBAAgB,gBACvD,KAAK,OAAO;AAGlB;AAEA,SAAgB,aACd,YACA,MACQ;CACR,MAAM,UAAkC,CAAC;CAEzC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,GAC5C,IAAI,OAAO,UAAU,UAAU,QAAQ,OAAO;CAGhD,MAAM,eAAe,WAAW,UAAU,CAAC,CAAC,YAAY,IAAI;CAC5D,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S,KAAK,GAEtB,iBAAiB,KAAK;CAE1B,CAAC;CAED,OAAO;AACT;AAEA,SAAgB,iBACd,OACA,MACM;CACN,MAAM,OAAO;CACb,MAAM,aAAa,mBAAmB,IAAI;AAC5C"}
1
+ {"version":3,"file":"hydration-methods.mjs","names":[],"sources":["../../../../../../../../../packages/cascade/src/model/methods/hydration-methods.ts"],"sourcesContent":["import { clone } from \"@mongez/reinforcements\";\nimport { DateValidator } from \"@warlock.js/seal\";\nimport {\n RelationHydrator,\n type ModelSnapshot,\n type SerializedRelation,\n} from \"../../relations/relation-hydrator\";\nimport type { ChildModel, Model } from \"../model\";\n\n/**\n * Drivers re-inflate any ISO-looking string into a Date. Only fields the model\n * schema declares as dates may be converted, so put every other string back.\n */\nfunction restoreUndeclaredDateStrings<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n original: Record<string, string>,\n data: Record<string, unknown>,\n): void {\n const shape = ModelClass.schema?.schema ?? {};\n\n for (const [key, value] of Object.entries(original)) {\n if (data[key] instanceof Date && !(shape[key] instanceof DateValidator)) {\n data[key] = value;\n }\n }\n}\n\nexport function hydrateModel<TModel extends Model = Model>(\n ModelClass: ChildModel<TModel>,\n data: Record<string, unknown>,\n): TModel {\n const strings: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(data)) {\n if (typeof value === \"string\") strings[key] = value;\n }\n\n const deserialized = ModelClass.getDriver().deserialize(data);\n restoreUndeclaredDateStrings(ModelClass, strings, deserialized);\n\n const model = new ModelClass(deserialized);\n model.isNew = false;\n return model;\n}\n\nexport function modelFromSnapshot<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n snapshot: ModelSnapshot,\n): TModel {\n const model = ModelClass.hydrate(snapshot.data) as TModel;\n RelationHydrator.hydrate(model, ModelClass.relations, snapshot.relations);\n return model;\n}\n\nexport function modelToSnapshot(model: Model): ModelSnapshot {\n const driver = (model.constructor as typeof Model).getDataSource().driver;\n const relations: Record<string, SerializedRelation> = {};\n\n for (const [name, related] of model.loadedRelations) {\n if (related === null) {\n relations[name] = null;\n } else if (Array.isArray(related)) {\n relations[name] = related.map((m) =>\n m instanceof Object && typeof m.toSnapshot === \"function\" ? m.toSnapshot() : m,\n );\n } else if (related instanceof Object && typeof related.toSnapshot === \"function\") {\n relations[name] = related.toSnapshot();\n }\n }\n\n return {\n data: driver.serialize({ ...model.data }) as Record<string, unknown>,\n relations,\n };\n}\n\nexport function serializeModel(model: Model) {\n return (model.constructor as typeof Model).getDataSource().driver.serialize(model.data);\n}\n\nexport function cloneModel<TModel extends Model>(model: TModel): TModel {\n const clonedData = clone(model.data);\n const ModelClass = model.self();\n const clonedModel = new ModelClass(clonedData) as TModel;\n\n clonedModel.isNew = model.isNew;\n deepFreezeObject(clonedModel.data);\n clonedModel.dirtyTracker.reset();\n\n return clonedModel;\n}\n\nexport function deepFreezeObject<T>(obj: T): T {\n Object.freeze(obj);\n\n Object.getOwnPropertyNames(obj).forEach((prop) => {\n const value = (obj as any)[prop];\n if (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n !Object.isFrozen(value)\n ) {\n deepFreezeObject(value);\n }\n });\n\n return obj;\n}\n\nexport function replaceModelData<TModel extends Model>(\n model: TModel,\n data: Record<string, unknown>,\n): void {\n model.data = data as any;\n model.dirtyTracker.replaceCurrentData(data);\n}\n"],"mappings":";;;;;;;;;AAaA,SAAS,6BACP,YACA,UACA,MACM;CACN,MAAM,QAAQ,WAAW,QAAQ,UAAU,CAAC;CAE5C,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,GAChD,IAAI,KAAK,gBAAgB,QAAQ,EAAE,MAAM,gBAAgB,gBACvD,KAAK,OAAO;AAGlB;AAEA,SAAgB,aACd,YACA,MACQ;CACR,MAAM,UAAkC,CAAC;CAEzC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,GAC5C,IAAI,OAAO,UAAU,UAAU,QAAQ,OAAO;CAGhD,MAAM,eAAe,WAAW,UAAU,CA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,UAAU,eAC/C,CAAC,OAAO,SAAS,KAAK,GAEtB,iBAAiB,KAAK;CAE1B,CAAC;CAED,OAAO;AACT;AAEA,SAAgB,iBACd,OACA,MACM;CACN,MAAM,OAAO;CACb,MAAM,aAAa,mBAAmB,IAAI;AAC5C"}
@@ -1 +1 @@
1
- {"version":3,"file":"query-methods.mjs","names":[],"sources":["../../../../../../../../../packages/cascade/src/model/methods/query-methods.ts"],"sourcesContent":["import type {\n AtomicUpdate,\n AtomicUpdateOptions,\n FindOneAndUpdateOptions,\n PaginationOptions,\n PaginationResult,\n QueryBuilderContract,\n} from \"../../contracts\";\nimport type { DataSource } from \"../../data-source/data-source\";\nimport { dataSourceRegistry } from \"../../data-source/data-source-registry\";\nimport { sanitizeFilter } from \"../../utils/sanitize-filter\";\nimport { generateModelId } from \"../generate-model-id\";\nimport type { ChildModel, GlobalScopeDefinition, Model } from \"../model\";\nimport { emitStaticEvent } from \"./static-event-methods\";\nimport { warnUndeclaredSensitiveFields } from \"./serialization-methods\";\n\nexport function buildQuery<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n BaseModel: typeof Model,\n): QueryBuilderContract<TModel> {\n const queryBuilder = ModelClass.newQueryBuilder<TModel>();\n const qb = queryBuilder;\n\n // Collect global scopes from base Model and child model\n const allGlobalScopes = new Map<string, GlobalScopeDefinition>([\n ...BaseModel.globalScopes,\n ...ModelClass.globalScopes,\n ]);\n\n queryBuilder.pendingGlobalScopes = allGlobalScopes;\n queryBuilder.availableLocalScopes = ModelClass.localScopes;\n queryBuilder.disabledGlobalScopes = new Set();\n queryBuilder.relationDefinitions = ModelClass.relations;\n queryBuilder.modelClass = ModelClass;\n\n let fetchStartedAt = Date.now();\n\n // Emitted from the builder's execute path (awaited), not at construction, so\n // listener changes apply before the query runs and a throwing listener fails\n // the query instead of becoming an unhandled rejection.\n queryBuilder.onFetching(async () => {\n fetchStartedAt = Date.now();\n\n await emitStaticEvent(ModelClass, \"fetching\", queryBuilder, {\n table: ModelClass.table,\n modelClass: ModelClass,\n });\n });\n\n queryBuilder.onHydrating(async (records: any[], context: any) => {\n await emitStaticEvent(ModelClass, \"hydrating\", records as any, {\n query: queryBuilder,\n hydrateCallback: context?.hydrateCallback,\n });\n });\n\n queryBuilder.hydrate((data: any) => {\n return ModelClass.hydrate(data);\n });\n\n // Eager-loading runs inside the driver's `get()` so it works for any\n // builder construction path (Model.query, Model.newQueryBuilder, custom\n // subclassed builders). This hook only handles the model-level `fetched`\n // event emission.\n queryBuilder.onFetched(async (models: any[], context: any) => {\n await emitStaticEvent(ModelClass, \"fetched\", models as any, {\n query: queryBuilder,\n rawRecords: context?.rawRecords ?? [],\n duration: context?.duration ?? Date.now() - fetchStartedAt,\n });\n });\n\n return queryBuilder;\n}\n\nexport function buildNewQueryBuilder<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n): QueryBuilderContract<TModel> {\n const dataSource = ModelClass.getDataSource();\n\n if (ModelClass.builder) {\n const BuilderClass = ModelClass.builder;\n return new BuilderClass(ModelClass.table, dataSource) as QueryBuilderContract<TModel>;\n }\n\n const queryBuilder = dataSource.driver.queryBuilder<TModel>(ModelClass.table);\n return queryBuilder;\n}\n\nexport async function findFirst<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter?: Record<string, unknown>,\n): Promise<TModel | null> {\n const query = ModelClass.query();\n if (filter) {\n query.where(filter);\n }\n return query.first();\n}\n\nexport async function findLast<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter?: Record<string, unknown>,\n): Promise<TModel | null> {\n const query = ModelClass.query();\n if (filter) {\n query.where(filter);\n }\n\n return query.last();\n}\n\nexport async function findAll<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter?: Record<string, unknown>,\n): Promise<TModel[]> {\n const query = ModelClass.query();\n if (filter) {\n query.where(filter);\n }\n return query.get();\n}\n\nexport function countRecords<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter?: Record<string, unknown>,\n): Promise<number> {\n const query = ModelClass.query();\n if (filter) {\n query.where(filter);\n }\n return query.count();\n}\n\nexport async function findById<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n id: string | number,\n): Promise<TModel | null> {\n const query = ModelClass.query();\n return query.where(ModelClass.primaryKey, id).first();\n}\n\nexport async function paginateRecords<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n options: PaginationOptions & { filter?: Record<string, unknown> } = {},\n): Promise<PaginationResult<TModel>> {\n const query = ModelClass.query();\n if (options.filter) {\n query.where(options.filter);\n }\n\n return query.paginate({\n limit: options.limit,\n page: options.page,\n });\n}\n\nexport async function findLatest<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter?: Record<string, unknown>,\n): Promise<TModel[]> {\n const query = ModelClass.query();\n if (filter) {\n query.where(filter);\n }\n return (await query.latest()) as unknown as TModel[];\n}\n\nexport function increaseField<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter: Record<string, unknown>,\n field: string,\n amount: number,\n): Promise<number> {\n const query = ModelClass.query().where(filter);\n return query.increment(field, amount);\n}\n\nexport function decreaseField<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter: Record<string, unknown>,\n field: string,\n amount: number,\n): Promise<number> {\n const query = ModelClass.query().where(filter);\n return query.decrement(field, amount);\n}\n\n// The atomic/find-and-modify statics below forward their filter straight to\n// the driver — they never pass through where(), so they must run the same\n// operator-injection check themselves. Only the FILTER is sanitized; update\n// operators ($set/$inc/…) are the point of these APIs and stay untouched.\n//\n// `trustedFilter` is the explicit, code-authored opt-out: it lets a conditional\n// filter such as `{ used: { $lt: 10 } }` through. It is stripped before the\n// options reach the driver.\nfunction resolveFilter(\n filter: Record<string, unknown>,\n options: AtomicUpdateOptions | undefined,\n): Record<string, unknown> {\n return options?.trustedFilter ? filter : sanitizeFilter(filter);\n}\n\nfunction toDriverOptions<TOptions extends AtomicUpdateOptions>(\n options: TOptions | undefined,\n): Omit<TOptions, \"trustedFilter\"> | undefined {\n if (!options) {\n return undefined;\n }\n\n const { trustedFilter: _trustedFilter, ...rest } = options;\n\n return rest;\n}\n\nfunction applyWriteFilter<TModel extends Model>(\n query: QueryBuilderContract<TModel>,\n filter: Record<string, unknown>,\n trustedFilter: boolean,\n): QueryBuilderContract<TModel> {\n // Query builders supplied by integrations predating `whereTrusted` can\n // still apply a code-authored filter through their regular `where` method.\n // Concrete Cascade builders implement `whereTrusted`, which is required for\n // MongoDB operator filters; retain the fallback for compatible custom\n // builders and test doubles.\n if (trustedFilter && typeof query.whereTrusted === \"function\") {\n return query.whereTrusted(filter);\n }\n\n return query.where(filter);\n}\n\n/**\n * Add the same generated `id` that normal Mongo inserts receive to an upsert's\n * insert branch. `$setOnInsert` keeps an existing document's id immutable.\n */\nasync function withAutoGeneratedUpsertId<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter: Record<string, unknown>,\n operations: AtomicUpdate,\n options: AtomicUpdateOptions | undefined,\n): Promise<AtomicUpdate> {\n if (\n !options?.upsert ||\n !ModelClass.autoGenerateId ||\n ModelClass.getDriver().name !== \"mongodb\" ||\n Array.isArray(operations)\n ) {\n return operations;\n }\n\n const filterId = filter.id;\n const filterConstrainsId =\n Object.hasOwn(filter, \"id\") &&\n (filterId === null ||\n typeof filterId !== \"object\" ||\n (!Array.isArray(filterId) && Object.hasOwn(filterId, \"$eq\")));\n const updateSuppliesId =\n Object.hasOwn(operations.$set ?? {}, \"id\") ||\n Object.hasOwn(operations.$setOnInsert ?? {}, \"id\");\n\n if (filterConstrainsId || updateSuppliesId) {\n return operations;\n }\n\n const id = await generateModelId(ModelClass);\n\n if (id === undefined) {\n return operations;\n }\n\n return {\n ...operations,\n $setOnInsert: { ...operations.$setOnInsert, id },\n };\n}\n\n/**\n * Pin a driver-level write to the rows the model's global scopes (tenant, soft\n * delete) allow. The driver write APIs take a raw filter and never see scopes,\n * so the target ids are resolved through the scoped query builder and added to\n * the filter. `null` means no visible row matches: the write must be a no-op.\n */\nexport async function scopeWriteFilter(\n ModelClass: ChildModel<any>,\n filter: Record<string, unknown>,\n single: boolean,\n trustedFilter = false,\n): Promise<Record<string, unknown> | null> {\n const primaryKey = ModelClass.primaryKey;\n const query = ModelClass.query();\n const ids = await applyWriteFilter(query, filter, trustedFilter).pluck(primaryKey);\n\n if (ids.length === 0) {\n return null;\n }\n\n return { ...filter, [primaryKey]: single ? ids[0] : { $in: ids } };\n}\n\n/**\n * Scoped filter for a write that may insert (`upsert`). With no visible match\n * the driver would insert or, worse, update a row a scope hides (another\n * tenant's, a soft-deleted one), so a hidden match is refused.\n */\nexport async function scopeUpsertFilter(\n ModelClass: ChildModel<any>,\n filter: Record<string, unknown>,\n trustedFilter = false,\n): Promise<Record<string, unknown>> {\n const scoped = await scopeWriteFilter(ModelClass, filter, true, trustedFilter);\n\n if (scoped) {\n return scoped;\n }\n\n const query = ModelClass.query().withoutGlobalScopes();\n const hidden = await applyWriteFilter(query, filter, trustedFilter).exists();\n\n if (hidden) {\n throw new Error(\n `${ModelClass.name}: upsert matches a row hidden by a global scope (tenant or soft delete); refusing to touch it.`,\n );\n }\n\n return filter;\n}\n\n/**\n * Run an atomic update and return the number of documents modified plus the\n * number inserted by an `upsert`.\n */\nexport async function performAtomic<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter: Record<string, unknown>,\n operations: AtomicUpdate,\n options?: AtomicUpdateOptions,\n): Promise<number> {\n const resolved = resolveFilter(filter, options);\n const scoped = options?.upsert\n ? await scopeUpsertFilter(ModelClass, resolved, options?.trustedFilter)\n : await scopeWriteFilter(ModelClass, resolved, false, options?.trustedFilter);\n\n if (!scoped) {\n return 0;\n }\n\n const upsertOperations = await withAutoGeneratedUpsertId(ModelClass, scoped, operations, options);\n\n const result = await ModelClass.getDriver().atomic(\n ModelClass.table,\n scoped,\n upsertOperations,\n toDriverOptions(options),\n );\n\n return result.modifiedCount + (result.upsertedCount ?? 0);\n}\n\n/**\n * Update a row by id through the model writer: the row is loaded (scopes\n * apply), merged, and saved, so the schema, strictMode, casting, `updatedAt`\n * and events all apply. Returns 1 when a row was saved, 0 when none is visible.\n */\nexport async function updateById<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n id: string | number,\n data: Record<string, unknown>,\n): Promise<number> {\n const model = await ModelClass.query().where(ModelClass.primaryKey, id).first();\n\n if (!model) {\n return 0;\n }\n\n model.merge(data);\n await model.save();\n\n return 1;\n}\n\nexport async function findAndUpdateRecords<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter: Record<string, unknown>,\n update: AtomicUpdate,\n options?: AtomicUpdateOptions,\n): Promise<TModel[]> {\n const primaryKey = ModelClass.primaryKey;\n const safeFilter = resolveFilter(filter, options);\n\n // Capture the matching ids first: the update usually changes the very field\n // the filter matches on, so re-querying with the filter would find nothing.\n const query = ModelClass.query();\n const ids = await applyWriteFilter(query, safeFilter, options?.trustedFilter ?? false).pluck(\n primaryKey,\n );\n\n if (ids.length === 0) {\n if (!options?.upsert) {\n return [];\n }\n\n await performAtomic(ModelClass, safeFilter, update, { ...options, trustedFilter: true });\n return await ModelClass.query().where(safeFilter).get();\n }\n\n await performAtomic(ModelClass, { [primaryKey]: { $in: ids } }, update, {\n ...options,\n trustedFilter: true,\n });\n\n return await ModelClass.query().whereIn(primaryKey, ids).get();\n}\n\nexport async function findOneAndUpdateRecord<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter: Record<string, unknown>,\n update: AtomicUpdate,\n options?: FindOneAndUpdateOptions,\n): Promise<TModel | null> {\n const resolved = resolveFilter(filter, options);\n const scoped = options?.upsert\n ? await scopeUpsertFilter(ModelClass, resolved, options?.trustedFilter)\n : await scopeWriteFilter(ModelClass, resolved, true, options?.trustedFilter);\n\n if (!scoped) return null;\n\n const upsertUpdate = await withAutoGeneratedUpsertId(ModelClass, scoped, update, options);\n\n const result = await ModelClass.getDriver().findOneAndUpdate(\n ModelClass.table,\n scoped,\n upsertUpdate,\n toDriverOptions(options),\n );\n if (!result) return null;\n return ModelClass.hydrate(result as Record<string, unknown>) as TModel;\n}\n\nexport async function findAndReplaceRecord<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter: Record<string, unknown>,\n document: Record<string, unknown>,\n): Promise<TModel | null> {\n const scoped = await scopeWriteFilter(ModelClass, sanitizeFilter(filter), true);\n\n if (!scoped) return null;\n\n const result = await ModelClass.getDriver().replace(ModelClass.table, scoped, document);\n if (!result) return null;\n return ModelClass.hydrate(result as Record<string, unknown>) as TModel;\n}\n\nexport async function findOneAndDeleteRecord<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter: Record<string, unknown>,\n options?: Record<string, unknown>,\n): Promise<TModel | null> {\n const scoped = await scopeWriteFilter(ModelClass, sanitizeFilter(filter), true);\n\n if (!scoped) {\n return null;\n }\n\n const result = await ModelClass.getDriver().findOneAndDelete(ModelClass.table, scoped, options);\n\n if (!result) {\n return null;\n }\n\n const model = ModelClass.hydrate(result as Record<string, unknown>);\n model.dirtyTracker.reset();\n return model;\n}\n\nexport function resolveDataSource<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n): DataSource {\n const ref = ModelClass.dataSource;\n let dataSource: DataSource;\n\n if (typeof ref === \"string\") {\n dataSource = dataSourceRegistry.get(ref);\n } else if (ref) {\n dataSource = ref;\n } else {\n dataSource = dataSourceRegistry.get();\n }\n\n if (!ModelClass.hasOwnProperty(\"_defaultsApplied\")) {\n const driverDefaults = dataSource.driver.modelDefaults || {};\n const dataSourceDefaults = dataSource.modelDefaults || {};\n\n const mergedDefaults = {\n ...driverDefaults,\n ...dataSourceDefaults,\n };\n\n if (Object.keys(mergedDefaults).length > 0) {\n (ModelClass as any).applyModelDefaults(mergedDefaults);\n }\n\n (ModelClass as any)._defaultsApplied = true;\n }\n\n // First data-source resolution is the earliest per-class hook every model\n // passes through — warn here (once) if the schema carries credential-shaped\n // fields that toJSON() would expose.\n warnUndeclaredSensitiveFields(ModelClass);\n\n return dataSource;\n}\n"],"mappings":";;;;;;;AAgBA,SAAgB,WACd,YACA,WAC8B;CAC9B,MAAM,eAAe,WA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AAQ,UACjB,aAAa,mBAAmB,IAAI,GAAG;MAClC,IAAI,KACT,aAAa;MAEb,aAAa,mBAAmB,IAAI;CAGtC,IAAI,CAAC,WAAW,eAAe,kBAAkB,GAAG;EAClD,MAAM,iBAAiB,WAAW,OAAO,iBAAiB,CAAC;EAC3D,MAAM,qBAAqB,WAAW,iBAAiB,CAAC;EAExD,MAAM,iBAAiB;GACrB,GAAG;GACH,GAAG;EACL;EAEA,IAAI,OAAO,KAAK,cAAc,CAAC,CAAC,SAAS,GACvC,AAAC,WAAmB,mBAAmB,cAAc;EAGvD,AAAC,WAAmB,mBAAmB;CACzC;CAKA,8BAA8B,UAAU;CAExC,OAAO;AACT"}
1
+ {"version":3,"file":"query-methods.mjs","names":[],"sources":["../../../../../../../../../packages/cascade/src/model/methods/query-methods.ts"],"sourcesContent":["import type {\n AtomicUpdate,\n AtomicUpdateOptions,\n FindOneAndUpdateOptions,\n PaginationOptions,\n PaginationResult,\n QueryBuilderContract,\n} from \"../../contracts\";\nimport type { DataSource } from \"../../data-source/data-source\";\nimport { dataSourceRegistry } from \"../../data-source/data-source-registry\";\nimport { sanitizeFilter } from \"../../utils/sanitize-filter\";\nimport { generateModelId } from \"../generate-model-id\";\nimport type { ChildModel, GlobalScopeDefinition, Model } from \"../model\";\nimport { emitStaticEvent } from \"./static-event-methods\";\nimport { warnUndeclaredSensitiveFields } from \"./serialization-methods\";\n\nexport function buildQuery<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n BaseModel: typeof Model,\n): QueryBuilderContract<TModel> {\n const queryBuilder = ModelClass.newQueryBuilder<TModel>();\n\n // Collect global scopes from base Model and child model\n const allGlobalScopes = new Map<string, GlobalScopeDefinition>([\n ...BaseModel.globalScopes,\n ...ModelClass.globalScopes,\n ]);\n\n queryBuilder.pendingGlobalScopes = allGlobalScopes;\n queryBuilder.availableLocalScopes = ModelClass.localScopes;\n queryBuilder.disabledGlobalScopes = new Set();\n queryBuilder.relationDefinitions = ModelClass.relations;\n queryBuilder.modelClass = ModelClass;\n\n let fetchStartedAt = Date.now();\n\n // Emitted from the builder's execute path (awaited), not at construction, so\n // listener changes apply before the query runs and a throwing listener fails\n // the query instead of becoming an unhandled rejection.\n queryBuilder.onFetching(async () => {\n fetchStartedAt = Date.now();\n\n await emitStaticEvent(ModelClass, \"fetching\", queryBuilder, {\n table: ModelClass.table,\n modelClass: ModelClass,\n });\n });\n\n queryBuilder.onHydrating(async (records: any[], context: any) => {\n await emitStaticEvent(ModelClass, \"hydrating\", records as any, {\n query: queryBuilder,\n hydrateCallback: context?.hydrateCallback,\n });\n });\n\n queryBuilder.hydrate((data: any) => {\n return ModelClass.hydrate(data);\n });\n\n // Eager-loading runs inside the driver's `get()` so it works for any\n // builder construction path (Model.query, Model.newQueryBuilder, custom\n // subclassed builders). This hook only handles the model-level `fetched`\n // event emission.\n queryBuilder.onFetched(async (models: any[], context: any) => {\n await emitStaticEvent(ModelClass, \"fetched\", models as any, {\n query: queryBuilder,\n rawRecords: context?.rawRecords ?? [],\n duration: context?.duration ?? Date.now() - fetchStartedAt,\n });\n });\n\n return queryBuilder;\n}\n\nexport function buildNewQueryBuilder<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n): QueryBuilderContract<TModel> {\n const dataSource = ModelClass.getDataSource();\n\n if (ModelClass.builder) {\n const BuilderClass = ModelClass.builder;\n return new BuilderClass(ModelClass.table, dataSource) as QueryBuilderContract<TModel>;\n }\n\n const queryBuilder = dataSource.driver.queryBuilder<TModel>(ModelClass.table);\n return queryBuilder;\n}\n\nexport async function findFirst<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter?: Record<string, unknown>,\n): Promise<TModel | null> {\n const query = ModelClass.query();\n if (filter) {\n query.where(filter);\n }\n return query.first();\n}\n\nexport async function findLast<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter?: Record<string, unknown>,\n): Promise<TModel | null> {\n const query = ModelClass.query();\n if (filter) {\n query.where(filter);\n }\n\n return query.last();\n}\n\nexport async function findAll<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter?: Record<string, unknown>,\n): Promise<TModel[]> {\n const query = ModelClass.query();\n if (filter) {\n query.where(filter);\n }\n return query.get();\n}\n\nexport function countRecords<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter?: Record<string, unknown>,\n): Promise<number> {\n const query = ModelClass.query();\n if (filter) {\n query.where(filter);\n }\n return query.count();\n}\n\nexport async function findById<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n id: string | number,\n): Promise<TModel | null> {\n const query = ModelClass.query();\n return query.where(ModelClass.primaryKey, id).first();\n}\n\nexport async function paginateRecords<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n options: PaginationOptions & { filter?: Record<string, unknown> } = {},\n): Promise<PaginationResult<TModel>> {\n const query = ModelClass.query();\n if (options.filter) {\n query.where(options.filter);\n }\n\n return query.paginate({\n limit: options.limit,\n page: options.page,\n });\n}\n\nexport async function findLatest<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter?: Record<string, unknown>,\n): Promise<TModel[]> {\n const query = ModelClass.query();\n if (filter) {\n query.where(filter);\n }\n return (await query.latest()) as unknown as TModel[];\n}\n\nexport function increaseField<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter: Record<string, unknown>,\n field: string,\n amount: number,\n): Promise<number> {\n const query = ModelClass.query().where(filter);\n return query.increment(field, amount);\n}\n\nexport function decreaseField<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter: Record<string, unknown>,\n field: string,\n amount: number,\n): Promise<number> {\n const query = ModelClass.query().where(filter);\n return query.decrement(field, amount);\n}\n\n// The atomic/find-and-modify statics below forward their filter straight to\n// the driver — they never pass through where(), so they must run the same\n// operator-injection check themselves. Only the FILTER is sanitized; update\n// operators ($set/$inc/…) are the point of these APIs and stay untouched.\n//\n// `trustedFilter` is the explicit, code-authored opt-out: it lets a conditional\n// filter such as `{ used: { $lt: 10 } }` through. It is stripped before the\n// options reach the driver.\nfunction resolveFilter(\n filter: Record<string, unknown>,\n options: AtomicUpdateOptions | undefined,\n): Record<string, unknown> {\n return options?.trustedFilter ? filter : sanitizeFilter(filter);\n}\n\nfunction toDriverOptions<TOptions extends AtomicUpdateOptions>(\n options: TOptions | undefined,\n): Omit<TOptions, \"trustedFilter\"> | undefined {\n if (!options) {\n return undefined;\n }\n\n const { trustedFilter: _trustedFilter, ...rest } = options;\n\n return rest;\n}\n\nfunction applyWriteFilter<TModel extends Model>(\n query: QueryBuilderContract<TModel>,\n filter: Record<string, unknown>,\n trustedFilter: boolean,\n): QueryBuilderContract<TModel> {\n // Query builders supplied by integrations predating `whereTrusted` can\n // still apply a code-authored filter through their regular `where` method.\n // Concrete Cascade builders implement `whereTrusted`, which is required for\n // MongoDB operator filters; retain the fallback for compatible custom\n // builders and test doubles.\n if (trustedFilter && typeof query.whereTrusted === \"function\") {\n return query.whereTrusted(filter);\n }\n\n return query.where(filter);\n}\n\n/**\n * Add the same generated `id` that normal Mongo inserts receive to an upsert's\n * insert branch. `$setOnInsert` keeps an existing document's id immutable.\n */\nasync function withAutoGeneratedUpsertId<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter: Record<string, unknown>,\n operations: AtomicUpdate,\n options: AtomicUpdateOptions | undefined,\n): Promise<AtomicUpdate> {\n if (\n !options?.upsert ||\n !ModelClass.autoGenerateId ||\n ModelClass.getDriver().name !== \"mongodb\" ||\n Array.isArray(operations)\n ) {\n return operations;\n }\n\n const filterId = filter.id;\n const filterConstrainsId =\n Object.hasOwn(filter, \"id\") &&\n (filterId === null ||\n typeof filterId !== \"object\" ||\n (!Array.isArray(filterId) && Object.hasOwn(filterId, \"$eq\")));\n const updateSuppliesId =\n Object.hasOwn(operations.$set ?? {}, \"id\") ||\n Object.hasOwn(operations.$setOnInsert ?? {}, \"id\");\n\n if (filterConstrainsId || updateSuppliesId) {\n return operations;\n }\n\n const id = await generateModelId(ModelClass);\n\n if (id === undefined) {\n return operations;\n }\n\n return {\n ...operations,\n $setOnInsert: { ...operations.$setOnInsert, id },\n };\n}\n\n/**\n * Pin a driver-level write to the rows the model's global scopes (tenant, soft\n * delete) allow. The driver write APIs take a raw filter and never see scopes,\n * so the target ids are resolved through the scoped query builder and added to\n * the filter. `null` means no visible row matches: the write must be a no-op.\n */\nexport async function scopeWriteFilter(\n ModelClass: ChildModel<any>,\n filter: Record<string, unknown>,\n single: boolean,\n trustedFilter = false,\n): Promise<Record<string, unknown> | null> {\n const primaryKey = ModelClass.primaryKey;\n const query = ModelClass.query();\n const ids = await applyWriteFilter(query, filter, trustedFilter).pluck(primaryKey);\n\n if (ids.length === 0) {\n return null;\n }\n\n return { ...filter, [primaryKey]: single ? ids[0] : { $in: ids } };\n}\n\n/**\n * Scoped filter for a write that may insert (`upsert`). With no visible match\n * the driver would insert or, worse, update a row a scope hides (another\n * tenant's, a soft-deleted one), so a hidden match is refused.\n */\nexport async function scopeUpsertFilter(\n ModelClass: ChildModel<any>,\n filter: Record<string, unknown>,\n trustedFilter = false,\n): Promise<Record<string, unknown>> {\n const scoped = await scopeWriteFilter(ModelClass, filter, true, trustedFilter);\n\n if (scoped) {\n return scoped;\n }\n\n const query = ModelClass.query().withoutGlobalScopes();\n const hidden = await applyWriteFilter(query, filter, trustedFilter).exists();\n\n if (hidden) {\n throw new Error(\n `${ModelClass.name}: upsert matches a row hidden by a global scope (tenant or soft delete); refusing to touch it.`,\n );\n }\n\n return filter;\n}\n\n/**\n * Run an atomic update and return the number of documents modified plus the\n * number inserted by an `upsert`.\n */\nexport async function performAtomic<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter: Record<string, unknown>,\n operations: AtomicUpdate,\n options?: AtomicUpdateOptions,\n): Promise<number> {\n const resolved = resolveFilter(filter, options);\n const scoped = options?.upsert\n ? await scopeUpsertFilter(ModelClass, resolved, options?.trustedFilter)\n : await scopeWriteFilter(ModelClass, resolved, false, options?.trustedFilter);\n\n if (!scoped) {\n return 0;\n }\n\n const upsertOperations = await withAutoGeneratedUpsertId(ModelClass, scoped, operations, options);\n\n const result = await ModelClass.getDriver().atomic(\n ModelClass.table,\n scoped,\n upsertOperations,\n toDriverOptions(options),\n );\n\n return result.modifiedCount + (result.upsertedCount ?? 0);\n}\n\n/**\n * Update a row by id through the model writer: the row is loaded (scopes\n * apply), merged, and saved, so the schema, strictMode, casting, `updatedAt`\n * and events all apply. Returns 1 when a row was saved, 0 when none is visible.\n */\nexport async function updateById<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n id: string | number,\n data: Record<string, unknown>,\n): Promise<number> {\n const model = await ModelClass.query().where(ModelClass.primaryKey, id).first();\n\n if (!model) {\n return 0;\n }\n\n model.merge(data);\n await model.save();\n\n return 1;\n}\n\nexport async function findAndUpdateRecords<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter: Record<string, unknown>,\n update: AtomicUpdate,\n options?: AtomicUpdateOptions,\n): Promise<TModel[]> {\n const primaryKey = ModelClass.primaryKey;\n const safeFilter = resolveFilter(filter, options);\n\n // Capture the matching ids first: the update usually changes the very field\n // the filter matches on, so re-querying with the filter would find nothing.\n const query = ModelClass.query();\n const ids = await applyWriteFilter(query, safeFilter, options?.trustedFilter ?? false).pluck(\n primaryKey,\n );\n\n if (ids.length === 0) {\n if (!options?.upsert) {\n return [];\n }\n\n await performAtomic(ModelClass, safeFilter, update, { ...options, trustedFilter: true });\n return await ModelClass.query().where(safeFilter).get();\n }\n\n await performAtomic(ModelClass, { [primaryKey]: { $in: ids } }, update, {\n ...options,\n trustedFilter: true,\n });\n\n return await ModelClass.query().whereIn(primaryKey, ids).get();\n}\n\nexport async function findOneAndUpdateRecord<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter: Record<string, unknown>,\n update: AtomicUpdate,\n options?: FindOneAndUpdateOptions,\n): Promise<TModel | null> {\n const resolved = resolveFilter(filter, options);\n const scoped = options?.upsert\n ? await scopeUpsertFilter(ModelClass, resolved, options?.trustedFilter)\n : await scopeWriteFilter(ModelClass, resolved, true, options?.trustedFilter);\n\n if (!scoped) return null;\n\n const upsertUpdate = await withAutoGeneratedUpsertId(ModelClass, scoped, update, options);\n\n const result = await ModelClass.getDriver().findOneAndUpdate(\n ModelClass.table,\n scoped,\n upsertUpdate,\n toDriverOptions(options),\n );\n if (!result) return null;\n return ModelClass.hydrate(result as Record<string, unknown>) as TModel;\n}\n\nexport async function findAndReplaceRecord<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter: Record<string, unknown>,\n document: Record<string, unknown>,\n): Promise<TModel | null> {\n const scoped = await scopeWriteFilter(ModelClass, sanitizeFilter(filter), true);\n\n if (!scoped) return null;\n\n const result = await ModelClass.getDriver().replace(ModelClass.table, scoped, document);\n if (!result) return null;\n return ModelClass.hydrate(result as Record<string, unknown>) as TModel;\n}\n\nexport async function findOneAndDeleteRecord<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n filter: Record<string, unknown>,\n options?: Record<string, unknown>,\n): Promise<TModel | null> {\n const scoped = await scopeWriteFilter(ModelClass, sanitizeFilter(filter), true);\n\n if (!scoped) {\n return null;\n }\n\n const result = await ModelClass.getDriver().findOneAndDelete(ModelClass.table, scoped, options);\n\n if (!result) {\n return null;\n }\n\n const model = ModelClass.hydrate(result as Record<string, unknown>);\n model.dirtyTracker.reset();\n return model;\n}\n\nexport function resolveDataSource<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n): DataSource {\n const ref = ModelClass.dataSource;\n let dataSource: DataSource;\n\n if (typeof ref === \"string\") {\n dataSource = dataSourceRegistry.get(ref);\n } else if (ref) {\n dataSource = ref;\n } else {\n dataSource = dataSourceRegistry.get();\n }\n\n if (!ModelClass.hasOwnProperty(\"_defaultsApplied\")) {\n const driverDefaults = dataSource.driver.modelDefaults || {};\n const dataSourceDefaults = dataSource.modelDefaults || {};\n\n const mergedDefaults = {\n ...driverDefaults,\n ...dataSourceDefaults,\n };\n\n if (Object.keys(mergedDefaults).length > 0) {\n (ModelClass as any).applyModelDefaults(mergedDefaults);\n }\n\n (ModelClass as any)._defaultsApplied = true;\n }\n\n // First data-source resolution is the earliest per-class hook every model\n // passes through — warn here (once) if the schema carries credential-shaped\n // fields that toJSON() would expose.\n warnUndeclaredSensitiveFields(ModelClass);\n\n return dataSource;\n}\n"],"mappings":";;;;;;;AAgBA,SAAgB,WACd,YACA,WAC8B;CAC9B,MAAM,eAAe,WAAW,gBAAwB;CAQxD,aAAa,sBAAsB,IALP,IAAmC,CAC7D,GAAG,UAAU,cACb,GAAG,WAAW,YAChB,CAEiD;CACjD,aAAa,uBAAuB,WAAW;CAC/C,aAAa,uCAAuB,IAAI,IAAI;CAC5C,aAAa,sBAAsB,WAAW;CAC9C,aAAa,aAAa;CAE1B,IAAI,iBAAiB,KAAK,IAAI;CAK9B,aAAa,WAAW,YAAY;EAClC,iBAAiB,KAAK,IAAI;EAE1B,MAAM,gBAAgB,YAAY,YAAY,cAAc;GAC1D,OAAO,WAAW;GAClB,YAAY;EACd,CAAC;CACH,CAAC;CAED,aAAa,YAAY,OAAO,SAAgB,YAAiB;EAC/D,MAAM,gBAAgB,YAAY,aAAa,SAAgB;GAC7D,OAAO;GACP,iBAAiB,SAAS;EAC5B,CAAC;CACH,CAAC;CAED,aAAa,SAAS,SAAc;EAClC,OAAO,WAAW,QAAQ,IAAI;CAChC,CAAC;CAMD,aAAa,UAAU,OAAO,QAAe,YAAiB;EAC5D,MAAM,gBAAgB,YAAY,WAAW,QAAe;GAC1D,OAAO;GACP,YAAY,SAAS,cAAc,CAAC;GACpC,UAAU,SAAS,YAAY,KAAK,IAAI,IAAI;EAC9C,CAAC;CACH,CAAC;CAED,OAAO;AACT;AAEA,SAAgB,qBACd,YAC8B;CAC9B,MAAM,aAAa,WAAW,cAAc;CAE5C,IAAI,WAAW,SAAS;EACtB,MAAM,eAAe,WAAW;EAChC,OAAO,IAAI,aAAa,WAAW,OAAO,UAAU;CACtD;CAGA,OADqB,WAAW,OAAO,aAAqB,WAAW,KACrD;AACpB;AAEA,eAAsB,UACpB,YACA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BAAiB,WAAW,OAAO,QAAQ,OAAO;CAE9F,IAAI,CAAC,QACH,OAAO;CAGT,MAAM,QAAQ,WAAW,QAAQ,MAAiC;CAClE,MAAM,aAAa,MAAM;CACzB,OAAO;AACT;AAEA,SAAgB,kBACd,YACY;CACZ,MAAM,MAAM,WAAW;CACvB,IAAI;CAEJ,IAAI,OAAO,QAAQ,UACjB,aAAa,mBAAmB,IAAI,GAAG;MAClC,IAAI,KACT,aAAa;MAEb,aAAa,mBAAmB,IAAI;CAGtC,IAAI,CAAC,WAAW,eAAe,kBAAkB,GAAG;EAClD,MAAM,iBAAiB,WAAW,OAAO,iBAAiB,CAAC;EAC3D,MAAM,qBAAqB,WAAW,iBAAiB,CAAC;EAExD,MAAM,iBAAiB;GACrB,GAAG;GACH,GAAG;EACL;EAEA,IAAI,OAAO,KAAK,cAAc,CAAC,CAAC,SAAS,GACvC,AAAC,WAAmB,mBAAmB,cAAc;EAGvD,AAAC,WAAmB,mBAAmB;CACzC;CAKA,8BAA8B,UAAU;CAExC,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"scope-methods.mjs","names":[],"sources":["../../../../../../../../../packages/cascade/src/model/methods/scope-methods.ts"],"sourcesContent":["import type { QueryBuilderContract } from \"../../contracts\";\nimport type { GlobalScopeOptions, LocalScopeCallback, ChildModel, Model } from \"../model\";\n\n/**\n * Give the model class its OWN scope map before mutating.\n *\n * The `globalScopes` / `localScopes` statics live on the base `Model`; without\n * this, `ModelClass.globalScopes.set(...)` from any subclass mutates the ONE\n * inherited Map and the scope leaks onto every other model (a soft-delete\n * `notDeleted` scope registered on `User` would filter `Post` too). The own\n * map snapshots the currently-inherited entries so parent scopes registered so\n * far are kept.\n */\nfunction ownScopeMap(\n ModelClass: ChildModel<any>,\n property: \"globalScopes\" | \"localScopes\",\n): Map<string, any> {\n if (!Object.prototype.hasOwnProperty.call(ModelClass, property)) {\n (ModelClass as any)[property] = new Map((ModelClass as any)[property]);\n }\n\n return (ModelClass as any)[property];\n}\n\nexport function addGlobalModelScope(\n ModelClass: ChildModel<any>,\n name: string,\n callback: (query: QueryBuilderContract) => void,\n options: GlobalScopeOptions = {},\n): void {\n ownScopeMap(ModelClass, \"globalScopes\").set(name, {\n callback,\n timing: options.timing || \"before\",\n });\n}\n\nexport function removeGlobalModelScope(ModelClass: ChildModel<any>, name: string): void {\n ownScopeMap(ModelClass, \"globalScopes\").delete(name);\n}\n\nexport function addLocalModelScope(\n ModelClass: ChildModel<any>,\n name: string,\n callback: LocalScopeCallback,\n): void {\n ownScopeMap(ModelClass, \"localScopes\").set(name, callback);\n}\n\nexport function removeLocalModelScope(ModelClass: ChildModel<any>, name: string): void {\n ownScopeMap(ModelClass, \"localScopes\").delete(name);\n}\n"],"mappings":";;;;;;;;;;;AAaA,SAAS,YACP,YACA,UACkB;CAClB,IAAI,CAAC,OAAO,UAAU,eAAe,KAAK,YAAY,QAAQ,GAC5D,AAAC,WAAmB,YAAY,IAAI,IAAK,WAAmB,SAAS;CAGvE,OAAQ,WAAmB;AAC7B;AAEA,SAAgB,oBACd,YACA,MACA,UACA,UAA8B,CAAC,GACzB;CACN,YAAY,YAAY,cAAc,CAAC,CAAC,IAAI,MAAM;EAChD;EACA,QAAQ,QAAQ,UAAU;CAC5B,CAAC;AACH;AAEA,SAAgB,uBAAuB,YAA6B,MAAoB;CACtF,YAAY,YAAY,cAAc,CAAC,CAAC,OAAO,IAAI;AACrD;AAEA,SAAgB,mBACd,YACA,MACA,UACM;CACN,YAAY,YAAY,aAAa,CAAC,CAAC,IAAI,MAAM,QAAQ;AAC3D;AAEA,SAAgB,sBAAsB,YAA6B,MAAoB;CACrF,YAAY,YAAY,aAAa,CAAC,CAAC,OAAO,IAAI;AACpD"}
1
+ {"version":3,"file":"scope-methods.mjs","names":[],"sources":["../../../../../../../../../packages/cascade/src/model/methods/scope-methods.ts"],"sourcesContent":["import type { QueryBuilderContract } from \"../../contracts\";\nimport type { GlobalScopeOptions, LocalScopeCallback, ChildModel } from \"../model\";\n\n/**\n * Give the model class its OWN scope map before mutating.\n *\n * The `globalScopes` / `localScopes` statics live on the base `Model`; without\n * this, `ModelClass.globalScopes.set(...)` from any subclass mutates the ONE\n * inherited Map and the scope leaks onto every other model (a soft-delete\n * `notDeleted` scope registered on `User` would filter `Post` too). The own\n * map snapshots the currently-inherited entries so parent scopes registered so\n * far are kept.\n */\nfunction ownScopeMap(\n ModelClass: ChildModel<any>,\n property: \"globalScopes\" | \"localScopes\",\n): Map<string, any> {\n if (!Object.prototype.hasOwnProperty.call(ModelClass, property)) {\n (ModelClass as any)[property] = new Map((ModelClass as any)[property]);\n }\n\n return (ModelClass as any)[property];\n}\n\nexport function addGlobalModelScope(\n ModelClass: ChildModel<any>,\n name: string,\n callback: (query: QueryBuilderContract) => void,\n options: GlobalScopeOptions = {},\n): void {\n ownScopeMap(ModelClass, \"globalScopes\").set(name, {\n callback,\n timing: options.timing || \"before\",\n });\n}\n\nexport function removeGlobalModelScope(ModelClass: ChildModel<any>, name: string): void {\n ownScopeMap(ModelClass, \"globalScopes\").delete(name);\n}\n\nexport function addLocalModelScope(\n ModelClass: ChildModel<any>,\n name: string,\n callback: LocalScopeCallback,\n): void {\n ownScopeMap(ModelClass, \"localScopes\").set(name, callback);\n}\n\nexport function removeLocalModelScope(ModelClass: ChildModel<any>, name: string): void {\n ownScopeMap(ModelClass, \"localScopes\").delete(name);\n}\n"],"mappings":";;;;;;;;;;;AAaA,SAAS,YACP,YACA,UACkB;CAClB,IAAI,CAAC,OAAO,UAAU,eAAe,KAAK,YAAY,QAAQ,GAC5D,AAAC,WAAmB,YAAY,IAAI,IAAK,WAAmB,SAAS;CAGvE,OAAQ,WAAmB;AAC7B;AAEA,SAAgB,oBACd,YACA,MACA,UACA,UAA8B,CAAC,GACzB;CACN,YAAY,YAAY,cAAc,CAAC,CAAC,IAAI,MAAM;EAChD;EACA,QAAQ,QAAQ,UAAU;CAC5B,CAAC;AACH;AAEA,SAAgB,uBAAuB,YAA6B,MAAoB;CACtF,YAAY,YAAY,cAAc,CAAC,CAAC,OAAO,IAAI;AACrD;AAEA,SAAgB,mBACd,YACA,MACA,UACM;CACN,YAAY,YAAY,aAAa,CAAC,CAAC,IAAI,MAAM,QAAQ;AAC3D;AAEA,SAAgB,sBAAsB,YAA6B,MAAoB;CACrF,YAAY,YAAY,aAAa,CAAC,CAAC,OAAO,IAAI;AACpD"}
@@ -1 +1 @@
1
- {"version":3,"file":"static-event-methods.mjs","names":[],"sources":["../../../../../../../../../packages/cascade/src/model/methods/static-event-methods.ts"],"sourcesContent":["import {\n ModelEvents,\n globalModelEvents,\n type ModelEventListener,\n type ModelEventName,\n} from \"../../events/model-events\";\nimport { removeModelFromRegistery } from \"../register-model\";\nimport type { ChildModel, Model } from \"../model\";\n\n/**\n * Isolated event emitter registry — one ModelEvents instance per model constructor.\n * Encapsulated here so no other module needs to know it exists.\n */\nconst modelEventsRegistry = new WeakMap<any, any>();\n\nexport function getModelEvents<TModel extends Model>(\n ModelClass: any,\n): ModelEvents<TModel> {\n let events = modelEventsRegistry.get(ModelClass);\n if (!events) {\n events = new ModelEvents<TModel>();\n modelEventsRegistry.set(ModelClass, events);\n }\n return events as ModelEvents<TModel>;\n}\n\n/**\n * Emit a static event to the class's listeners and then to every ancestor\n * class's listeners up to `Model`, so a listener registered on a shared base\n * (`class AppModel extends Model`) fires for its subclasses too. Ancestors are\n * only read, never given an emitter they don't already have.\n */\nexport async function emitStaticEvent<TContext = unknown>(\n ModelClass: any,\n event: ModelEventName,\n model: any,\n context: TContext,\n): Promise<void> {\n await ModelClass.events().emit(event, model, context);\n\n let ancestor = Object.getPrototypeOf(ModelClass);\n\n while (ancestor && ancestor !== Function.prototype) {\n const events = modelEventsRegistry.get(ancestor);\n\n if (events) {\n await events.emit(event, model, context);\n }\n\n ancestor = Object.getPrototypeOf(ancestor);\n }\n}\n\nexport function cleanupModelEvents(ModelClass: any): void {\n modelEventsRegistry.delete(ModelClass);\n removeModelFromRegistery(ModelClass.name);\n}\n\nexport function onStaticEvent<TModel extends Model = Model, TContext = unknown>(\n ModelClass: ChildModel<TModel>,\n event: ModelEventName,\n listener: ModelEventListener<TModel, TContext>,\n): () => void {\n return ModelClass.events<TModel>().on(event, listener);\n}\n\nexport function onceStaticEvent<TModel extends Model = Model, TContext = unknown>(\n ModelClass: ChildModel<TModel>,\n event: ModelEventName,\n listener: ModelEventListener<TModel, TContext>,\n): () => void {\n return ModelClass.events<TModel>().once(event, listener);\n}\n\nexport function offStaticEvent<TModel extends Model = Model, TContext = unknown>(\n ModelClass: ChildModel<TModel>,\n event: ModelEventName,\n listener: ModelEventListener<TModel, TContext>,\n): void {\n ModelClass.events<TModel>().off(event, listener);\n}\n\nexport function getGlobalEvents(): ModelEvents<Model> {\n return globalModelEvents;\n}\n"],"mappings":";;;;;;;;AAaA,MAAM,sCAAsB,IAAI,QAAkB;AAElD,SAAgB,eACd,YACqB;CACrB,IAAI,SAAS,oBAAoB,IAAI,UAAU;CAC/C,IAAI,CAAC,QAAQ;EACX,SAAS,IAAI,YAAoB;EACjC,oBAAoB,IAAI,YAAY,MAAM;CAC5C;CACA,OAAO;AACT;;;;;;;AAQA,eAAsB,gBACpB,YACA,OACA,OACA,SACe;CACf,MAAM,WAAW,OAAO,CAAC,CAAC,KAAK,OAAO,OAAO,OAAO;CAEpD,IAAI,WAAW,OAAO,eAAe,UAAU;CAE/C,OAAO,YAAY,aAAa,SAAS,WAAW;EAClD,MAAM,SAAS,oBAAoB,IAAI,QAAQ;EAE/C,IAAI,QACF,MAAM,OAAO,KAAK,OAAO,OAAO,OAAO;EAGzC,WAAW,OAAO,eAAe,QAAQ;CAC3C;AACF;AAEA,SAAgB,mBAAmB,YAAuB;CACxD,oBAAoB,OAAO,UAAU;CACrC,yBAAyB,WAAW,IAAI;AAC1C;AAEA,SAAgB,cACd,YACA,OACA,UACY;CACZ,OAAO,WAAW,OAAe,CAAC,CAAC,GAAG,OAAO,QAAQ;AACvD;AAEA,SAAgB,gBACd,YACA,OACA,UACY;CACZ,OAAO,WAAW,OAAe,CAAC,CAAC,KAAK,OAAO,QAAQ;AACzD;AAEA,SAAgB,eACd,YACA,OACA,UACM;CACN,WAAW,OAAe,CAAC,CAAC,IAAI,OAAO,QAAQ;AACjD;AAEA,SAAgB,kBAAsC;CACpD,OAAO;AACT"}
1
+ {"version":3,"file":"static-event-methods.mjs","names":[],"sources":["../../../../../../../../../packages/cascade/src/model/methods/static-event-methods.ts"],"sourcesContent":["import {\n ModelEvents,\n globalModelEvents,\n type ModelEventListener,\n type ModelEventName,\n} from \"../../events/model-events\";\nimport { removeModelFromRegistery } from \"../register-model\";\nimport type { ChildModel, Model } from \"../model\";\n\n/**\n * Isolated event emitter registry — one ModelEvents instance per model constructor.\n * Encapsulated here so no other module needs to know it exists.\n */\nconst modelEventsRegistry = new WeakMap<any, any>();\n\nexport function getModelEvents<TModel extends Model>(ModelClass: any): ModelEvents<TModel> {\n let events = modelEventsRegistry.get(ModelClass);\n if (!events) {\n events = new ModelEvents<TModel>();\n modelEventsRegistry.set(ModelClass, events);\n }\n return events as ModelEvents<TModel>;\n}\n\n/**\n * Emit a static event to the class's listeners and then to every ancestor\n * class's listeners up to `Model`, so a listener registered on a shared base\n * (`class AppModel extends Model`) fires for its subclasses too. Ancestors are\n * only read, never given an emitter they don't already have.\n */\nexport async function emitStaticEvent<TContext = unknown>(\n ModelClass: any,\n event: ModelEventName,\n model: any,\n context: TContext,\n): Promise<void> {\n await ModelClass.events().emit(event, model, context);\n\n let ancestor = Object.getPrototypeOf(ModelClass);\n\n while (ancestor && ancestor !== Function.prototype) {\n const events = modelEventsRegistry.get(ancestor);\n\n if (events) {\n await events.emit(event, model, context);\n }\n\n ancestor = Object.getPrototypeOf(ancestor);\n }\n}\n\nexport function cleanupModelEvents(ModelClass: any): void {\n modelEventsRegistry.delete(ModelClass);\n removeModelFromRegistery(ModelClass.name);\n}\n\nexport function onStaticEvent<TModel extends Model = Model, TContext = unknown>(\n ModelClass: ChildModel<TModel>,\n event: ModelEventName,\n listener: ModelEventListener<TModel, TContext>,\n): () => void {\n return ModelClass.events<TModel>().on(event, listener);\n}\n\nexport function onceStaticEvent<TModel extends Model = Model, TContext = unknown>(\n ModelClass: ChildModel<TModel>,\n event: ModelEventName,\n listener: ModelEventListener<TModel, TContext>,\n): () => void {\n return ModelClass.events<TModel>().once(event, listener);\n}\n\nexport function offStaticEvent<TModel extends Model = Model, TContext = unknown>(\n ModelClass: ChildModel<TModel>,\n event: ModelEventName,\n listener: ModelEventListener<TModel, TContext>,\n): void {\n ModelClass.events<TModel>().off(event, listener);\n}\n\nexport function getGlobalEvents(): ModelEvents<Model> {\n return globalModelEvents;\n}\n"],"mappings":";;;;;;;;AAaA,MAAM,sCAAsB,IAAI,QAAkB;AAElD,SAAgB,eAAqC,YAAsC;CACzF,IAAI,SAAS,oBAAoB,IAAI,UAAU;CAC/C,IAAI,CAAC,QAAQ;EACX,SAAS,IAAI,YAAoB;EACjC,oBAAoB,IAAI,YAAY,MAAM;CAC5C;CACA,OAAO;AACT;;;;;;;AAQA,eAAsB,gBACpB,YACA,OACA,OACA,SACe;CACf,MAAM,WAAW,OAAO,CAAC,CAAC,KAAK,OAAO,OAAO,OAAO;CAEpD,IAAI,WAAW,OAAO,eAAe,UAAU;CAE/C,OAAO,YAAY,aAAa,SAAS,WAAW;EAClD,MAAM,SAAS,oBAAoB,IAAI,QAAQ;EAE/C,IAAI,QACF,MAAM,OAAO,KAAK,OAAO,OAAO,OAAO;EAGzC,WAAW,OAAO,eAAe,QAAQ;CAC3C;AACF;AAEA,SAAgB,mBAAmB,YAAuB;CACxD,oBAAoB,OAAO,UAAU;CACrC,yBAAyB,WAAW,IAAI;AAC1C;AAEA,SAAgB,cACd,YACA,OACA,UACY;CACZ,OAAO,WAAW,OAAe,CAAC,CAAC,GAAG,OAAO,QAAQ;AACvD;AAEA,SAAgB,gBACd,YACA,OACA,UACY;CACZ,OAAO,WAAW,OAAe,CAAC,CAAC,KAAK,OAAO,QAAQ;AACzD;AAEA,SAAgB,eACd,YACA,OACA,UACM;CACN,WAAW,OAAe,CAAC,CAAC,IAAI,OAAO,QAAQ;AACjD;AAEA,SAAgB,kBAAsC;CACpD,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"write-methods.mjs","names":[],"sources":["../../../../../../../../../packages/cascade/src/model/methods/write-methods.ts"],"sourcesContent":["import { DatabaseWriter } from \"../../writer/database-writer\";\nimport type { InsertResult, WriterOptions } from \"../../contracts\";\nimport type { ChildModel, Model, ModelSchema } from \"../model\";\nimport { mergeDriverFields } from \"./accessor-methods\";\nimport { sanitizeFilter } from \"../../utils/sanitize-filter\";\nimport { emitModelEvent } from \"./instance-event-methods\";\n\n/**\n * Default number of rows processed per chunk by {@link createManyRecords}.\n *\n * Chunking keeps a single huge `createMany` call from flooding the driver:\n * the default path runs each chunk's `save()` calls under one `Promise.all`,\n * and the bulk path emits one multi-row `insertMany` per chunk so the\n * generated `INSERT ... VALUES (...),(...)` stays under the database's bind\n * parameter ceiling.\n */\nexport const DEFAULT_CREATE_MANY_BATCH_SIZE = 500;\n\n/**\n * Options for {@link createManyRecords} (and `Model.createMany`).\n */\nexport type CreateManyOptions = {\n /**\n * Number of rows processed per chunk.\n *\n * @default 500 ({@link DEFAULT_CREATE_MANY_BATCH_SIZE})\n */\n batchSize?: number;\n\n /**\n * Route each chunk through the driver's native multi-row insert\n * (`insertMany`) instead of per-row `save()`.\n *\n * **Tradeoff:** the bulk path is 10–100× faster for large arrays but\n * SKIPS the per-row lifecycle: `saving` / `creating` / `created` / `saved`\n * events, instance hooks, and sync operations are NOT emitted. Casts,\n * timestamps, defaults and id-generation that the writer normally applies\n * ARE still applied (the rows are prepped through the same writer pipeline),\n * so persisted columns match the default path.\n *\n * @default false\n */\n bulk?: boolean;\n};\n\nexport async function saveModel<TModel extends Model>(\n model: TModel,\n options?: WriterOptions & { merge?: Partial<ModelSchema> },\n): Promise<TModel> {\n if (options?.merge) {\n model.merge(options.merge);\n }\n const writer = new DatabaseWriter(model);\n await writer.save(options);\n return model;\n}\n\nexport async function createRecord<\n TModel extends Model,\n TSchema extends ModelSchema = TModel extends Model<infer S> ? S : ModelSchema,\n>(ModelClass: ChildModel<TModel>, data: Partial<TSchema>): Promise<TModel> {\n const model = new ModelClass(data);\n await model.save();\n return model;\n}\n\n/**\n * Split an array into sequential chunks of at most `size` elements.\n *\n * @param items - The array to split.\n * @param size - Maximum chunk length (callers pass a value `>= 1`).\n * @returns An array of chunks preserving the original order.\n */\nfunction chunkArray<TItem>(items: TItem[], size: number): TItem[][] {\n const chunks: TItem[][] = [];\n\n for (let index = 0; index < items.length; index += size) {\n chunks.push(items.slice(index, index + size));\n }\n\n return chunks;\n}\n\n/**\n * Create many records, chunking the work so a huge array can't overwhelm the\n * driver.\n *\n * Two strategies are available via `options.bulk`:\n *\n * - **Default (`bulk` falsy):** each row is persisted through `save()`, so\n * model hooks, lifecycle events, casts and generated ids are all preserved.\n * Rows are processed in sequential chunks of `batchSize`, each chunk running\n * under a single `Promise.all`, so an array of millions of rows can't open\n * millions of concurrent inserts at once.\n *\n * - **Bulk (`bulk: true`):** each chunk is routed to the driver's native\n * multi-row insert (`insertMany`) for 10–100× throughput. This SKIPS the\n * per-row save lifecycle (no `saving` / `creating` / `created` / `saved`\n * events, hooks, or sync). Rows are still prepped through the writer\n * pipeline (validation, casting, timestamps, defaults, id-generation) so the\n * persisted columns match the default path, and the values returned by the\n * driver (generated `_id`, timestamps, SQL `RETURNING *`) are merged back\n * onto the returned models.\n *\n * Both strategies return the created model instances (an empty array is a\n * no-op that never touches the driver).\n *\n * @param ModelClass - The model class to create records for.\n * @param data - The rows to insert.\n * @param options - Chunking / bulk options.\n * @returns The created model instances.\n *\n * @example\n * ```typescript\n * // Default: per-row save(), chunked in batches of 500\n * const users = await User.createMany(rows);\n *\n * // Bulk: one multi-row INSERT per 1000-row chunk (skips per-row hooks)\n * const users = await User.createMany(rows, { bulk: true, batchSize: 1000 });\n * ```\n */\nexport async function createManyRecords<\n TModel extends Model,\n TSchema extends ModelSchema = TModel extends Model<infer S> ? S : ModelSchema,\n>(\n ModelClass: ChildModel<TModel>,\n data: Partial<TSchema>[],\n options: CreateManyOptions = {},\n): Promise<TModel[]> {\n if (data.length === 0) {\n return [];\n }\n\n const batchSize =\n options.batchSize && options.batchSize > 0\n ? options.batchSize\n : DEFAULT_CREATE_MANY_BATCH_SIZE;\n\n const chunks = chunkArray(data, batchSize);\n\n if (options.bulk === true) {\n return await createManyBulk(ModelClass, chunks);\n }\n\n const created: TModel[] = [];\n\n for (const chunk of chunks) {\n const models = chunk.map((item) => new ModelClass(item)) as TModel[];\n\n // Reserve one contiguous id block for the whole chunk (1 counter op instead\n // of N), pre-seeding each id-less model so its per-row save() no-ops id-gen.\n await assignIdBlock(ModelClass, models);\n\n const chunkModels = await Promise.all(\n models.map(async (model) => {\n await model.save();\n return model;\n }),\n );\n\n created.push(...chunkModels);\n }\n\n return created;\n}\n\n/**\n * Reserve a single contiguous id block for one chunk and pre-assign the ids to\n * the models that don't already carry one, so the per-row writer's id\n * generation no-ops (its `model.get(\"id\")` guard short-circuits). This turns N\n * per-row counter round-trips into ONE per chunk.\n *\n * Falls back to per-row generation (a no-op here) when:\n * - the model disables auto-generation (`autoGenerateId === false`) — e.g. SQL,\n * which uses native `SERIAL`;\n * - the data source's id generator has no batch API (`generateNextIds`) — the\n * optional contract member is feature-detected;\n * - the model uses a random initial id / increment — a random stride can't form\n * a contiguous block, so those models keep per-row generation.\n *\n * Only models WITHOUT a caller-supplied id consume a block slot, so a chunk\n * mixing supplied and auto ids allocates exactly the right number (no gaps).\n *\n * @param ModelClass - The model class being inserted.\n * @param models - The freshly-constructed (unsaved) models for one chunk.\n */\nasync function assignIdBlock<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n models: TModel[],\n): Promise<void> {\n if (!ModelClass.autoGenerateId || ModelClass.randomInitialId || ModelClass.randomIncrement) {\n return;\n }\n\n const idGenerator = ModelClass.getDataSource().idGenerator;\n\n if (!idGenerator || typeof idGenerator.generateNextIds !== \"function\") {\n return;\n }\n\n const idLessModels = models.filter((model) => !model.get(\"id\"));\n\n if (idLessModels.length === 0) {\n return;\n }\n\n const ids = await idGenerator.generateNextIds({\n table: ModelClass.table,\n initialId: ModelClass.initialId || 1,\n incrementIdBy: ModelClass.incrementIdBy || 1,\n count: idLessModels.length,\n });\n\n // Enforce the contract at this pluggable, feature-detected boundary: a\n // non-conforming generator returning the wrong count would otherwise set\n // `id = undefined` on the unmatched rows, the per-row writer would silently\n // re-generate single ids, and the reserved block would no longer match what\n // is persisted. Fail loud instead of corrupting the sequence.\n if (ids.length !== idLessModels.length) {\n throw new Error(\n `generateNextIds returned ${ids.length} id(s) for ${idLessModels.length} row(s) on ` +\n `\"${ModelClass.table}\" — a batch id generator must return exactly the requested count.`,\n );\n }\n\n idLessModels.forEach((model, index) => {\n model.set(\"id\", ids[index]);\n });\n}\n\n/**\n * Bulk variant of {@link createManyRecords}: prep each row through the writer\n * pipeline (validation, casting, timestamps, defaults, id-generation) without\n * touching the database, then flush each chunk with a single\n * `driver.insertMany` call.\n *\n * The writer reuse goes through `DatabaseWriter.prepareForInsert()`, the same\n * pipeline `save()` uses for an insert, so the shared driver is never mutated\n * and concurrent `save()` calls are unaffected.\n *\n * @param ModelClass - The model class to create records for.\n * @param chunks - Pre-chunked rows.\n * @returns The created model instances with driver-returned values merged in.\n */\nasync function createManyBulk<\n TModel extends Model,\n TSchema extends ModelSchema = TModel extends Model<infer S> ? S : ModelSchema,\n>(ModelClass: ChildModel<TModel>, chunks: Partial<TSchema>[][]): Promise<TModel[]> {\n const dataSource = ModelClass.getDataSource();\n const driver = dataSource.driver;\n const table = ModelClass.table;\n\n const created: TModel[] = [];\n\n {\n for (const chunk of chunks) {\n const models = chunk.map((item) => new ModelClass(item)) as TModel[];\n\n // Reserve one contiguous id block for the whole chunk (1 counter op\n // instead of N), pre-seeding each id-less model so the per-row writer's\n // id generation no-ops.\n await assignIdBlock(ModelClass, models);\n\n // Prep every model through the real writer pipeline. The captured\n // `insert` keeps this off the wire while still mutating each model's\n // data with casts/timestamps/defaults/generated ids.\n const preparedDocuments = await Promise.all(\n models.map(async (model) => {\n const document = await new DatabaseWriter(model).prepareForInsert({\n skipEvents: true,\n skipSync: true,\n });\n return { ...document } as Record<string, unknown>;\n }),\n );\n\n const results = await driver.insertMany(table, preparedDocuments);\n\n // Merge driver-returned values (generated _id, timestamps, RETURNING *)\n // back onto each model so the returned instances reflect persisted state.\n models.forEach((model, index) => {\n const result = results[index] as InsertResult | Record<string, unknown> | undefined;\n\n if (result) {\n const returnedDocument =\n \"document\" in (result as Record<string, unknown>)\n ? (result as InsertResult).document\n : result;\n\n // Driver-returned identity (generated _id / RETURNING *) — merged\n // through the framework-internal path so it is not treated as mass\n // assignment on a model the writer has already marked persisted.\n mergeDriverFields(model, returnedDocument as Record<string, unknown>);\n }\n\n model.dirtyTracker.reset();\n model.isNew = false;\n });\n\n created.push(...models);\n }\n }\n\n return created;\n}\n\nexport async function findOrCreateRecord<\n TModel extends Model,\n TSchema extends ModelSchema = TModel extends Model<infer S> ? S : ModelSchema,\n>(\n ModelClass: ChildModel<TModel>,\n filter: Partial<TSchema>,\n data: Partial<TSchema>,\n): Promise<TModel> {\n const existing = await ModelClass.first(filter as Record<string, unknown>);\n\n if (existing) {\n return existing;\n }\n\n return await createRecord(ModelClass, { ...filter, ...data } as Partial<TSchema>);\n}\n\nexport async function upsertRecord<\n TModel extends Model,\n TSchema extends ModelSchema = TModel extends Model<infer S> ? S : ModelSchema,\n>(\n ModelClass: ChildModel<TModel>,\n filter: Partial<TSchema>,\n data: Partial<TSchema>,\n options?: Record<string, unknown>,\n): Promise<TModel> {\n const driver = ModelClass.getDriver();\n const safeFilter = sanitizeFilter(filter as Record<string, unknown>);\n const mergedData = { ...safeFilter, ...data } as Record<string, unknown>;\n\n const tempModel = new ModelClass(mergedData as Partial<TSchema>);\n tempModel.isNew = true;\n\n // One `saving` run against the model itself, so listener changes (slug,\n // createdBy, ...) land in the data that is written.\n await emitModelEvent(tempModel, \"saving\", {\n isInsert: true,\n options,\n mode: \"upsert\",\n });\n\n // Validation, casting and Mongo id generation, same as `create()`.\n await new DatabaseWriter(tempModel).prepareForUpsert();\n\n const setData: Record<string, unknown> = { ...tempModel.data };\n const setOnInsert: Record<string, unknown> = {};\n const now = new Date();\n\n // Identity and creation time belong to the insert only; an existing row\n // keeps its own.\n for (const key of new Set([\"id\", \"_id\", ModelClass.primaryKey])) {\n if (key in setData) {\n setOnInsert[key] = setData[key];\n delete setData[key];\n }\n }\n\n const createdAtColumn = ModelClass.createdAtColumn;\n if (createdAtColumn) {\n setOnInsert[createdAtColumn] = setData[createdAtColumn] ?? now;\n delete setData[createdAtColumn];\n }\n\n const updatedAtColumn = ModelClass.updatedAtColumn;\n if (updatedAtColumn) {\n setData[updatedAtColumn] = now;\n }\n\n const result = await driver.findOneAndUpdate(\n ModelClass.table,\n safeFilter,\n { $set: setData, $setOnInsert: setOnInsert },\n { ...options, upsert: true, returnDocument: \"after\" },\n );\n\n const model = ModelClass.hydrate(result as Record<string, unknown>) as TModel;\n model.dirtyTracker.reset();\n\n await emitModelEvent(model, \"saved\", { filter: safeFilter, data: result, options, mode: \"upsert\" });\n\n return model;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,MAAa,iCAAiC;AA6B9C,eAAsB,UACpB,OACA,SACiB;CACjB,IAAI,SAAS,OACX,MAAM,MAAM,QAAQ,KAAK;CAG3B,MAAM,IADa,eAAe,KACvB,CAAC,CAAC,KAAK,OAAO;CACzB,OAAO;AACT;AAEA,eAAsB,aAGpB,YAAgC,MAAyC;CACzE,MAAM,QAAQ,IAAI,WAAW,IAAI;CACjC,MAAM,MAAM,KAAK;CACjB,OAAO;AACT;;;;;;;;AASA,SAAS,WAAkB,OAAgB,MAAyB;CAClE,MAAM,SAAoB,CAAC;CAE3B,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,MACjD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;EACxC,UAAU;EACV;EACA,MAAM;CACR,CAAC;CAGD,MAAM,IAAI,eAAe,SAAS,CAAC,CAAC,iBAAiB;CAErD,MAAM,UAAmC,EAAE,GAAG,UAAU,KAAK;CAC7D,MAAM,cAAuC,CAAC;CAC9C,MAAM,sBAAM,IAAI,KAAK;CAIrB,KAAK,MAAM,OAAO,IAAI,IAAI;EAAC;EAAM;EAAO,WAAW;CAAU,CAAC,GAC5D,IAAI,OAAO,SAAS;EAClB,YAAY,OAAO,QAAQ;EAC3B,OAAO,QAAQ;CACjB;CAGF,MAAM,kBAAkB,WAAW;CACnC,IAAI,iBAAiB;EACnB,YAAY,mBAAmB,QAAQ,oBAAoB;EAC3D,OAAO,QAAQ;CACjB;CAEA,MAAM,kBAAkB,WAAW;CACnC,IAAI,iBACF,QAAQ,mBAAmB;CAG7B,MAAM,SAAS,MAAM,OAAO,iBAC1B,WAAW,OACX,YACA;EAAE,MAAM;EAAS,cAAc;CAAY,GAC3C;EAAE,GAAG;EAAS,QAAQ;EAAM,gBAAgB;CAAQ,CACtD;CAEA,MAAM,QAAQ,WAAW,QAAQ,MAAiC;CAClE,MAAM,aAAa,MAAM;CAEzB,MAAM,eAAe,OAAO,SAAS;EAAE,QAAQ;EAAY,MAAM;EAAQ;EAAS,MAAM;CAAS,CAAC;CAElG,OAAO;AACT"}
1
+ {"version":3,"file":"write-methods.mjs","names":[],"sources":["../../../../../../../../../packages/cascade/src/model/methods/write-methods.ts"],"sourcesContent":["import { DatabaseWriter } from \"../../writer/database-writer\";\nimport type { InsertResult, WriterOptions } from \"../../contracts\";\nimport type { ChildModel, Model, ModelSchema } from \"../model\";\nimport { mergeDriverFields } from \"./accessor-methods\";\nimport { sanitizeFilter } from \"../../utils/sanitize-filter\";\nimport { emitModelEvent } from \"./instance-event-methods\";\n\n/**\n * Default number of rows processed per chunk by {@link createManyRecords}.\n *\n * Chunking keeps a single huge `createMany` call from flooding the driver:\n * the default path runs each chunk's `save()` calls under one `Promise.all`,\n * and the bulk path emits one multi-row `insertMany` per chunk so the\n * generated `INSERT ... VALUES (...),(...)` stays under the database's bind\n * parameter ceiling.\n */\nexport const DEFAULT_CREATE_MANY_BATCH_SIZE = 500;\n\n/**\n * Options for {@link createManyRecords} (and `Model.createMany`).\n */\nexport type CreateManyOptions = {\n /**\n * Number of rows processed per chunk.\n *\n * @default 500 ({@link DEFAULT_CREATE_MANY_BATCH_SIZE})\n */\n batchSize?: number;\n\n /**\n * Route each chunk through the driver's native multi-row insert\n * (`insertMany`) instead of per-row `save()`.\n *\n * **Tradeoff:** the bulk path is 10–100× faster for large arrays but\n * SKIPS the per-row lifecycle: `saving` / `creating` / `created` / `saved`\n * events, instance hooks, and sync operations are NOT emitted. Casts,\n * timestamps, defaults and id-generation that the writer normally applies\n * ARE still applied (the rows are prepped through the same writer pipeline),\n * so persisted columns match the default path.\n *\n * @default false\n */\n bulk?: boolean;\n};\n\nexport async function saveModel<TModel extends Model>(\n model: TModel,\n options?: WriterOptions & { merge?: Partial<ModelSchema> },\n): Promise<TModel> {\n if (options?.merge) {\n model.merge(options.merge);\n }\n const writer = new DatabaseWriter(model);\n await writer.save(options);\n return model;\n}\n\nexport async function createRecord<\n TModel extends Model,\n TSchema extends ModelSchema = TModel extends Model<infer S> ? S : ModelSchema,\n>(ModelClass: ChildModel<TModel>, data: Partial<TSchema>): Promise<TModel> {\n const model = new ModelClass(data);\n await model.save();\n return model;\n}\n\n/**\n * Split an array into sequential chunks of at most `size` elements.\n *\n * @param items - The array to split.\n * @param size - Maximum chunk length (callers pass a value `>= 1`).\n * @returns An array of chunks preserving the original order.\n */\nfunction chunkArray<TItem>(items: TItem[], size: number): TItem[][] {\n const chunks: TItem[][] = [];\n\n for (let index = 0; index < items.length; index += size) {\n chunks.push(items.slice(index, index + size));\n }\n\n return chunks;\n}\n\n/**\n * Create many records, chunking the work so a huge array can't overwhelm the\n * driver.\n *\n * Two strategies are available via `options.bulk`:\n *\n * - **Default (`bulk` falsy):** each row is persisted through `save()`, so\n * model hooks, lifecycle events, casts and generated ids are all preserved.\n * Rows are processed in sequential chunks of `batchSize`, each chunk running\n * under a single `Promise.all`, so an array of millions of rows can't open\n * millions of concurrent inserts at once.\n *\n * - **Bulk (`bulk: true`):** each chunk is routed to the driver's native\n * multi-row insert (`insertMany`) for 10–100× throughput. This SKIPS the\n * per-row save lifecycle (no `saving` / `creating` / `created` / `saved`\n * events, hooks, or sync). Rows are still prepped through the writer\n * pipeline (validation, casting, timestamps, defaults, id-generation) so the\n * persisted columns match the default path, and the values returned by the\n * driver (generated `_id`, timestamps, SQL `RETURNING *`) are merged back\n * onto the returned models.\n *\n * Both strategies return the created model instances (an empty array is a\n * no-op that never touches the driver).\n *\n * @param ModelClass - The model class to create records for.\n * @param data - The rows to insert.\n * @param options - Chunking / bulk options.\n * @returns The created model instances.\n *\n * @example\n * ```typescript\n * // Default: per-row save(), chunked in batches of 500\n * const users = await User.createMany(rows);\n *\n * // Bulk: one multi-row INSERT per 1000-row chunk (skips per-row hooks)\n * const users = await User.createMany(rows, { bulk: true, batchSize: 1000 });\n * ```\n */\nexport async function createManyRecords<\n TModel extends Model,\n TSchema extends ModelSchema = TModel extends Model<infer S> ? S : ModelSchema,\n>(\n ModelClass: ChildModel<TModel>,\n data: Partial<TSchema>[],\n options: CreateManyOptions = {},\n): Promise<TModel[]> {\n if (data.length === 0) {\n return [];\n }\n\n const batchSize =\n options.batchSize && options.batchSize > 0 ? options.batchSize : DEFAULT_CREATE_MANY_BATCH_SIZE;\n\n const chunks = chunkArray(data, batchSize);\n\n if (options.bulk === true) {\n return await createManyBulk(ModelClass, chunks);\n }\n\n const created: TModel[] = [];\n\n for (const chunk of chunks) {\n const models = chunk.map((item) => new ModelClass(item)) as TModel[];\n\n // Reserve one contiguous id block for the whole chunk (1 counter op instead\n // of N), pre-seeding each id-less model so its per-row save() no-ops id-gen.\n await assignIdBlock(ModelClass, models);\n\n const chunkModels = await Promise.all(\n models.map(async (model) => {\n await model.save();\n return model;\n }),\n );\n\n created.push(...chunkModels);\n }\n\n return created;\n}\n\n/**\n * Reserve a single contiguous id block for one chunk and pre-assign the ids to\n * the models that don't already carry one, so the per-row writer's id\n * generation no-ops (its `model.get(\"id\")` guard short-circuits). This turns N\n * per-row counter round-trips into ONE per chunk.\n *\n * Falls back to per-row generation (a no-op here) when:\n * - the model disables auto-generation (`autoGenerateId === false`) — e.g. SQL,\n * which uses native `SERIAL`;\n * - the data source's id generator has no batch API (`generateNextIds`) — the\n * optional contract member is feature-detected;\n * - the model uses a random initial id / increment — a random stride can't form\n * a contiguous block, so those models keep per-row generation.\n *\n * Only models WITHOUT a caller-supplied id consume a block slot, so a chunk\n * mixing supplied and auto ids allocates exactly the right number (no gaps).\n *\n * @param ModelClass - The model class being inserted.\n * @param models - The freshly-constructed (unsaved) models for one chunk.\n */\nasync function assignIdBlock<TModel extends Model>(\n ModelClass: ChildModel<TModel>,\n models: TModel[],\n): Promise<void> {\n if (!ModelClass.autoGenerateId || ModelClass.randomInitialId || ModelClass.randomIncrement) {\n return;\n }\n\n const idGenerator = ModelClass.getDataSource().idGenerator;\n\n if (!idGenerator || typeof idGenerator.generateNextIds !== \"function\") {\n return;\n }\n\n const idLessModels = models.filter((model) => !model.get(\"id\"));\n\n if (idLessModels.length === 0) {\n return;\n }\n\n const ids = await idGenerator.generateNextIds({\n table: ModelClass.table,\n initialId: ModelClass.initialId || 1,\n incrementIdBy: ModelClass.incrementIdBy || 1,\n count: idLessModels.length,\n });\n\n // Enforce the contract at this pluggable, feature-detected boundary: a\n // non-conforming generator returning the wrong count would otherwise set\n // `id = undefined` on the unmatched rows, the per-row writer would silently\n // re-generate single ids, and the reserved block would no longer match what\n // is persisted. Fail loud instead of corrupting the sequence.\n if (ids.length !== idLessModels.length) {\n throw new Error(\n `generateNextIds returned ${ids.length} id(s) for ${idLessModels.length} row(s) on ` +\n `\"${ModelClass.table}\" — a batch id generator must return exactly the requested count.`,\n );\n }\n\n idLessModels.forEach((model, index) => {\n model.set(\"id\", ids[index]);\n });\n}\n\n/**\n * Bulk variant of {@link createManyRecords}: prep each row through the writer\n * pipeline (validation, casting, timestamps, defaults, id-generation) without\n * touching the database, then flush each chunk with a single\n * `driver.insertMany` call.\n *\n * The writer reuse goes through `DatabaseWriter.prepareForInsert()`, the same\n * pipeline `save()` uses for an insert, so the shared driver is never mutated\n * and concurrent `save()` calls are unaffected.\n *\n * @param ModelClass - The model class to create records for.\n * @param chunks - Pre-chunked rows.\n * @returns The created model instances with driver-returned values merged in.\n */\nasync function createManyBulk<\n TModel extends Model,\n TSchema extends ModelSchema = TModel extends Model<infer S> ? S : ModelSchema,\n>(ModelClass: ChildModel<TModel>, chunks: Partial<TSchema>[][]): Promise<TModel[]> {\n const dataSource = ModelClass.getDataSource();\n const driver = dataSource.driver;\n const table = ModelClass.table;\n\n const created: TModel[] = [];\n\n {\n for (const chunk of chunks) {\n const models = chunk.map((item) => new ModelClass(item)) as TModel[];\n\n // Reserve one contiguous id block for the whole chunk (1 counter op\n // instead of N), pre-seeding each id-less model so the per-row writer's\n // id generation no-ops.\n await assignIdBlock(ModelClass, models);\n\n // Prep every model through the real writer pipeline. The captured\n // `insert` keeps this off the wire while still mutating each model's\n // data with casts/timestamps/defaults/generated ids.\n const preparedDocuments = await Promise.all(\n models.map(async (model) => {\n const document = await new DatabaseWriter(model).prepareForInsert({\n skipEvents: true,\n skipSync: true,\n });\n return { ...document } as Record<string, unknown>;\n }),\n );\n\n const results = await driver.insertMany(table, preparedDocuments);\n\n // Merge driver-returned values (generated _id, timestamps, RETURNING *)\n // back onto each model so the returned instances reflect persisted state.\n models.forEach((model, index) => {\n const result = results[index] as InsertResult | Record<string, unknown> | undefined;\n\n if (result) {\n const returnedDocument =\n \"document\" in (result as Record<string, unknown>)\n ? (result as InsertResult).document\n : result;\n\n // Driver-returned identity (generated _id / RETURNING *) — merged\n // through the framework-internal path so it is not treated as mass\n // assignment on a model the writer has already marked persisted.\n mergeDriverFields(model, returnedDocument as Record<string, unknown>);\n }\n\n model.dirtyTracker.reset();\n model.isNew = false;\n });\n\n created.push(...models);\n }\n }\n\n return created;\n}\n\nexport async function findOrCreateRecord<\n TModel extends Model,\n TSchema extends ModelSchema = TModel extends Model<infer S> ? S : ModelSchema,\n>(\n ModelClass: ChildModel<TModel>,\n filter: Partial<TSchema>,\n data: Partial<TSchema>,\n): Promise<TModel> {\n const existing = await ModelClass.first(filter as Record<string, unknown>);\n\n if (existing) {\n return existing;\n }\n\n return await createRecord(ModelClass, { ...filter, ...data } as Partial<TSchema>);\n}\n\nexport async function upsertRecord<\n TModel extends Model,\n TSchema extends ModelSchema = TModel extends Model<infer S> ? S : ModelSchema,\n>(\n ModelClass: ChildModel<TModel>,\n filter: Partial<TSchema>,\n data: Partial<TSchema>,\n options?: Record<string, unknown>,\n): Promise<TModel> {\n const driver = ModelClass.getDriver();\n const safeFilter = sanitizeFilter(filter as Record<string, unknown>);\n const mergedData = { ...safeFilter, ...data } as Record<string, unknown>;\n\n const tempModel = new ModelClass(mergedData as Partial<TSchema>);\n tempModel.isNew = true;\n\n // One `saving` run against the model itself, so listener changes (slug,\n // createdBy, ...) land in the data that is written.\n await emitModelEvent(tempModel, \"saving\", {\n isInsert: true,\n options,\n mode: \"upsert\",\n });\n\n // Validation, casting and Mongo id generation, same as `create()`.\n await new DatabaseWriter(tempModel).prepareForUpsert();\n\n const setData: Record<string, unknown> = { ...tempModel.data };\n const setOnInsert: Record<string, unknown> = {};\n const now = new Date();\n\n // Identity and creation time belong to the insert only; an existing row\n // keeps its own.\n for (const key of new Set([\"id\", \"_id\", ModelClass.primaryKey])) {\n if (key in setData) {\n setOnInsert[key] = setData[key];\n delete setData[key];\n }\n }\n\n const createdAtColumn = ModelClass.createdAtColumn;\n if (createdAtColumn) {\n setOnInsert[createdAtColumn] = setData[createdAtColumn] ?? now;\n delete setData[createdAtColumn];\n }\n\n const updatedAtColumn = ModelClass.updatedAtColumn;\n if (updatedAtColumn) {\n setData[updatedAtColumn] = now;\n }\n\n const result = await driver.findOneAndUpdate(\n ModelClass.table,\n safeFilter,\n { $set: setData, $setOnInsert: setOnInsert },\n { ...options, upsert: true, returnDocument: \"after\" },\n );\n\n const model = ModelClass.hydrate(result as Record<string, unknown>) as TModel;\n model.dirtyTracker.reset();\n\n await emitModelEvent(model, \"saved\", {\n filter: safeFilter,\n data: result,\n options,\n mode: \"upsert\",\n });\n\n return model;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,MAAa,iCAAiC;AA6B9C,eAAsB,UACpB,OACA,SACiB;CACjB,IAAI,SAAS,OACX,MAAM,MAAM,QAAQ,KAAK;CAG3B,MAAM,IADa,eAAe,KACvB,CAAC,CAAC,KAAK,OAAO;CACzB,OAAO;AACT;AAEA,eAAsB,aAGpB,YAAgC,MAAyC;CACzE,MAAM,QAAQ,IAAI,WAAW,IAAI;CACjC,MAAM,MAAM,KAAK;CACjB,OAAO;AACT;;;;;;;;AASA,SAAS,WAAkB,OAAgB,MAAyB;CAClE,MAAM,SAAoB,CAAC;CAE3B,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,MACjD,OAAO,KAAK,MAAM,MAAM,OAAO,QAAQ,IAAI,CAAC;CAG9C,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,eAAsB,kBAIpB,YACA,MACA,UAA6B,CAAC,GACX;CACnB,IAAI,KAAK,WAAW,GAClB,OAAO,CAAC;CAMV,MAAM,SAAS,WAAW,MAFxB,QAAQ,aAAa,QAAQ,YAAY,IAAI,QAAQ,eAEd;CAEzC,IAAI,QAAQ,SAAS,MACnB,OAAO,MAAM,eAAe,YAAY,MAAM;CAGhD,MAAM,UAAoB,CAAC;CAE3B,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,SAAS,MAAM,KAAK,SAAS,IAAI,WAAW,IAAI,CAAC;EAIvD,MAAM,cAAc,YAAY,MAAM;EAEtC,MAAM,cAAc,MAAM,QAAQ,IAChC,OAAO,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