@quickback-dev/cli 0.66.14 → 0.66.15

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 (211) hide show
  1. package/dist/commands/schema.d.ts +1 -1
  2. package/dist/commands/schema.d.ts.map +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/lib/file-loader.js +1 -1
  5. package/dist/lib/file-loader.js.map +1 -1
  6. package/dist/lib/migrations/file-envelopes.d.ts.map +1 -1
  7. package/dist/lib/migrations/file-envelopes.js +79 -4
  8. package/dist/lib/migrations/file-envelopes.js.map +1 -1
  9. package/dist/lib/migrations/staging.js.map +1 -1
  10. package/dist/lib/schema-sync/index.d.ts +1 -1
  11. package/dist/lib/schema-sync/index.d.ts.map +1 -1
  12. package/dist/lib/schema-sync/index.js +10 -4
  13. package/dist/lib/schema-sync/index.js.map +1 -1
  14. package/dist/schema-engine/index.js.map +1 -1
  15. package/dist/schema-engine/source-sync.d.ts +1 -1
  16. package/dist/schema-engine/source-sync.d.ts.map +1 -1
  17. package/dist/skill/docs/api/batch-operations.md +1 -1
  18. package/dist/skill/docs/define/feature.md +10 -0
  19. package/dist/skill/docs/define/schema.md +5 -0
  20. package/dist/skill/docs/platform/auth/plugins/aws-ses.md +5 -0
  21. package/dist/skill/docs/tooling/cli.md +3 -1
  22. package/dist/skill/docs/tooling/cloud-compiler/local-compiler.md +15 -0
  23. package/dist/skill/docs/ui/account/environment-variables.md +5 -4
  24. package/dist/skill/docs/ui/account/features/index.md +14 -9
  25. package/dist/skill/docs/ui/account/hooks.md +12 -5
  26. package/package.json +1 -1
  27. package/src/skill/docs/api/batch-operations.md +1 -1
  28. package/src/skill/docs/define/feature.md +10 -0
  29. package/src/skill/docs/define/schema.md +5 -0
  30. package/src/skill/docs/platform/auth/plugins/aws-ses.md +5 -0
  31. package/src/skill/docs/tooling/cli.md +3 -1
  32. package/src/skill/docs/tooling/cloud-compiler/local-compiler.md +15 -0
  33. package/src/skill/docs/ui/account/environment-variables.md +5 -4
  34. package/src/skill/docs/ui/account/features/index.md +14 -9
  35. package/src/skill/docs/ui/account/hooks.md +12 -5
  36. package/dist/commands/build.test.d.ts +0 -2
  37. package/dist/commands/build.test.d.ts.map +0 -1
  38. package/dist/commands/build.test.js +0 -201
  39. package/dist/commands/build.test.js.map +0 -1
  40. package/dist/commands/canary.test.d.ts +0 -2
  41. package/dist/commands/canary.test.d.ts.map +0 -1
  42. package/dist/commands/canary.test.js +0 -100
  43. package/dist/commands/canary.test.js.map +0 -1
  44. package/dist/commands/deploy.test.d.ts +0 -2
  45. package/dist/commands/deploy.test.d.ts.map +0 -1
  46. package/dist/commands/deploy.test.js +0 -139
  47. package/dist/commands/deploy.test.js.map +0 -1
  48. package/dist/commands/migrate.test.d.ts +0 -2
  49. package/dist/commands/migrate.test.d.ts.map +0 -1
  50. package/dist/commands/migrate.test.js +0 -283
  51. package/dist/commands/migrate.test.js.map +0 -1
  52. package/dist/commands/migrations.test.d.ts +0 -2
  53. package/dist/commands/migrations.test.d.ts.map +0 -1
  54. package/dist/commands/migrations.test.js +0 -162
  55. package/dist/commands/migrations.test.js.map +0 -1
  56. package/dist/commands/push.test.d.ts +0 -2
  57. package/dist/commands/push.test.d.ts.map +0 -1
  58. package/dist/commands/push.test.js +0 -76
  59. package/dist/commands/push.test.js.map +0 -1
  60. package/dist/commands/schema.test.d.ts +0 -2
  61. package/dist/commands/schema.test.d.ts.map +0 -1
  62. package/dist/commands/schema.test.js +0 -137
  63. package/dist/commands/schema.test.js.map +0 -1
  64. package/dist/docs/index.test.d.ts +0 -2
  65. package/dist/docs/index.test.d.ts.map +0 -1
  66. package/dist/docs/index.test.js +0 -51
  67. package/dist/docs/index.test.js.map +0 -1
  68. package/dist/lib/action-harvest.test.d.ts +0 -2
  69. package/dist/lib/action-harvest.test.d.ts.map +0 -1
  70. package/dist/lib/action-harvest.test.js +0 -645
  71. package/dist/lib/action-harvest.test.js.map +0 -1
  72. package/dist/lib/api-client.test.d.ts +0 -2
  73. package/dist/lib/api-client.test.d.ts.map +0 -1
  74. package/dist/lib/api-client.test.js +0 -373
  75. package/dist/lib/api-client.test.js.map +0 -1
  76. package/dist/lib/artifact-routing.test.d.ts +0 -2
  77. package/dist/lib/artifact-routing.test.d.ts.map +0 -1
  78. package/dist/lib/artifact-routing.test.js +0 -48
  79. package/dist/lib/artifact-routing.test.js.map +0 -1
  80. package/dist/lib/auth.test.d.ts +0 -2
  81. package/dist/lib/auth.test.d.ts.map +0 -1
  82. package/dist/lib/auth.test.js +0 -19
  83. package/dist/lib/auth.test.js.map +0 -1
  84. package/dist/lib/compile-next-steps.test.d.ts +0 -2
  85. package/dist/lib/compile-next-steps.test.d.ts.map +0 -1
  86. package/dist/lib/compile-next-steps.test.js +0 -76
  87. package/dist/lib/compile-next-steps.test.js.map +0 -1
  88. package/dist/lib/compiler-floor.test.d.ts +0 -2
  89. package/dist/lib/compiler-floor.test.d.ts.map +0 -1
  90. package/dist/lib/compiler-floor.test.js +0 -67
  91. package/dist/lib/compiler-floor.test.js.map +0 -1
  92. package/dist/lib/config-id-splice.test.d.ts +0 -2
  93. package/dist/lib/config-id-splice.test.d.ts.map +0 -1
  94. package/dist/lib/config-id-splice.test.js +0 -246
  95. package/dist/lib/config-id-splice.test.js.map +0 -1
  96. package/dist/lib/config-sync.test.d.ts +0 -2
  97. package/dist/lib/config-sync.test.d.ts.map +0 -1
  98. package/dist/lib/config-sync.test.js +0 -151
  99. package/dist/lib/config-sync.test.js.map +0 -1
  100. package/dist/lib/copy-public-assets.test.d.ts +0 -2
  101. package/dist/lib/copy-public-assets.test.d.ts.map +0 -1
  102. package/dist/lib/copy-public-assets.test.js +0 -151
  103. package/dist/lib/copy-public-assets.test.js.map +0 -1
  104. package/dist/lib/copy-source-apps.test.d.ts +0 -2
  105. package/dist/lib/copy-source-apps.test.d.ts.map +0 -1
  106. package/dist/lib/copy-source-apps.test.js +0 -170
  107. package/dist/lib/copy-source-apps.test.js.map +0 -1
  108. package/dist/lib/deployment-target.test.d.ts +0 -2
  109. package/dist/lib/deployment-target.test.d.ts.map +0 -1
  110. package/dist/lib/deployment-target.test.js +0 -63
  111. package/dist/lib/deployment-target.test.js.map +0 -1
  112. package/dist/lib/drizzle-meta-routing.test.d.ts +0 -2
  113. package/dist/lib/drizzle-meta-routing.test.d.ts.map +0 -1
  114. package/dist/lib/drizzle-meta-routing.test.js +0 -136
  115. package/dist/lib/drizzle-meta-routing.test.js.map +0 -1
  116. package/dist/lib/file-loader-typescript-fallback.test.d.ts +0 -2
  117. package/dist/lib/file-loader-typescript-fallback.test.d.ts.map +0 -1
  118. package/dist/lib/file-loader-typescript-fallback.test.js +0 -58
  119. package/dist/lib/file-loader-typescript-fallback.test.js.map +0 -1
  120. package/dist/lib/file-loader.test.d.ts +0 -2
  121. package/dist/lib/file-loader.test.d.ts.map +0 -1
  122. package/dist/lib/file-loader.test.js +0 -475
  123. package/dist/lib/file-loader.test.js.map +0 -1
  124. package/dist/lib/file-writer.test.d.ts +0 -2
  125. package/dist/lib/file-writer.test.d.ts.map +0 -1
  126. package/dist/lib/file-writer.test.js +0 -131
  127. package/dist/lib/file-writer.test.js.map +0 -1
  128. package/dist/lib/migrations/command-runner.test.d.ts +0 -2
  129. package/dist/lib/migrations/command-runner.test.d.ts.map +0 -1
  130. package/dist/lib/migrations/command-runner.test.js +0 -19
  131. package/dist/lib/migrations/command-runner.test.js.map +0 -1
  132. package/dist/lib/migrations/drizzle-prompts.test.d.ts +0 -2
  133. package/dist/lib/migrations/drizzle-prompts.test.d.ts.map +0 -1
  134. package/dist/lib/migrations/drizzle-prompts.test.js +0 -135
  135. package/dist/lib/migrations/drizzle-prompts.test.js.map +0 -1
  136. package/dist/lib/migrations/drizzle-wrapper.test.d.ts +0 -2
  137. package/dist/lib/migrations/drizzle-wrapper.test.d.ts.map +0 -1
  138. package/dist/lib/migrations/drizzle-wrapper.test.js +0 -64
  139. package/dist/lib/migrations/drizzle-wrapper.test.js.map +0 -1
  140. package/dist/lib/migrations/drizzle.test.d.ts +0 -2
  141. package/dist/lib/migrations/drizzle.test.d.ts.map +0 -1
  142. package/dist/lib/migrations/drizzle.test.js +0 -71
  143. package/dist/lib/migrations/drizzle.test.js.map +0 -1
  144. package/dist/lib/migrations/executor.test.d.ts +0 -2
  145. package/dist/lib/migrations/executor.test.d.ts.map +0 -1
  146. package/dist/lib/migrations/executor.test.js +0 -270
  147. package/dist/lib/migrations/executor.test.js.map +0 -1
  148. package/dist/lib/migrations/headless-generate.test.d.ts +0 -2
  149. package/dist/lib/migrations/headless-generate.test.d.ts.map +0 -1
  150. package/dist/lib/migrations/headless-generate.test.js +0 -167
  151. package/dist/lib/migrations/headless-generate.test.js.map +0 -1
  152. package/dist/lib/migrations/inventory.test.d.ts +0 -2
  153. package/dist/lib/migrations/inventory.test.d.ts.map +0 -1
  154. package/dist/lib/migrations/inventory.test.js +0 -81
  155. package/dist/lib/migrations/inventory.test.js.map +0 -1
  156. package/dist/lib/migrations/lock.test.d.ts +0 -2
  157. package/dist/lib/migrations/lock.test.d.ts.map +0 -1
  158. package/dist/lib/migrations/lock.test.js +0 -35
  159. package/dist/lib/migrations/lock.test.js.map +0 -1
  160. package/dist/lib/migrations/paths.test.d.ts +0 -2
  161. package/dist/lib/migrations/paths.test.d.ts.map +0 -1
  162. package/dist/lib/migrations/paths.test.js +0 -32
  163. package/dist/lib/migrations/paths.test.js.map +0 -1
  164. package/dist/lib/migrations/plan.test.d.ts +0 -2
  165. package/dist/lib/migrations/plan.test.d.ts.map +0 -1
  166. package/dist/lib/migrations/plan.test.js +0 -104
  167. package/dist/lib/migrations/plan.test.js.map +0 -1
  168. package/dist/lib/migrations/postprocessors/index.test.d.ts +0 -2
  169. package/dist/lib/migrations/postprocessors/index.test.d.ts.map +0 -1
  170. package/dist/lib/migrations/postprocessors/index.test.js +0 -393
  171. package/dist/lib/migrations/postprocessors/index.test.js.map +0 -1
  172. package/dist/lib/migrations/prompt-runner.test.d.ts +0 -2
  173. package/dist/lib/migrations/prompt-runner.test.d.ts.map +0 -1
  174. package/dist/lib/migrations/prompt-runner.test.js +0 -135
  175. package/dist/lib/migrations/prompt-runner.test.js.map +0 -1
  176. package/dist/lib/migrations/staging.test.d.ts +0 -2
  177. package/dist/lib/migrations/staging.test.d.ts.map +0 -1
  178. package/dist/lib/migrations/staging.test.js +0 -73
  179. package/dist/lib/migrations/staging.test.js.map +0 -1
  180. package/dist/lib/neon-canary.test.d.ts +0 -2
  181. package/dist/lib/neon-canary.test.d.ts.map +0 -1
  182. package/dist/lib/neon-canary.test.js +0 -186
  183. package/dist/lib/neon-canary.test.js.map +0 -1
  184. package/dist/lib/neon-target.test.d.ts +0 -2
  185. package/dist/lib/neon-target.test.d.ts.map +0 -1
  186. package/dist/lib/neon-target.test.js +0 -122
  187. package/dist/lib/neon-target.test.js.map +0 -1
  188. package/dist/lib/neon.test.d.ts +0 -2
  189. package/dist/lib/neon.test.d.ts.map +0 -1
  190. package/dist/lib/neon.test.js +0 -154
  191. package/dist/lib/neon.test.js.map +0 -1
  192. package/dist/lib/prepare-output.test.d.ts +0 -2
  193. package/dist/lib/prepare-output.test.d.ts.map +0 -1
  194. package/dist/lib/prepare-output.test.js +0 -105
  195. package/dist/lib/prepare-output.test.js.map +0 -1
  196. package/dist/lib/prepare-state-output.test.d.ts +0 -2
  197. package/dist/lib/prepare-state-output.test.d.ts.map +0 -1
  198. package/dist/lib/prepare-state-output.test.js +0 -111
  199. package/dist/lib/prepare-state-output.test.js.map +0 -1
  200. package/dist/lib/schema-sync/index.test.d.ts +0 -2
  201. package/dist/lib/schema-sync/index.test.d.ts.map +0 -1
  202. package/dist/lib/schema-sync/index.test.js +0 -216
  203. package/dist/lib/schema-sync/index.test.js.map +0 -1
  204. package/dist/lib/shell.test.d.ts +0 -2
  205. package/dist/lib/shell.test.d.ts.map +0 -1
  206. package/dist/lib/shell.test.js +0 -73
  207. package/dist/lib/shell.test.js.map +0 -1
  208. package/dist/lib/wrangler-resources.test.d.ts +0 -2
  209. package/dist/lib/wrangler-resources.test.d.ts.map +0 -1
  210. package/dist/lib/wrangler-resources.test.js +0 -347
  211. package/dist/lib/wrangler-resources.test.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../schema-engine/src/managed-columns.ts", "../../../schema-engine/src/provider-dialects.ts", "../../../schema-engine/src/source-sync.ts"],
4
- "sourcesContent": ["/**\n * Canonical feature-owned managed-column requirements.\n *\n * This module deliberately contains no filesystem, process, network, or\n * user-module access. Callers supply the project facts that determine which\n * requirements apply to each discovered table.\n */\n\nexport const SCHEMA_ENGINE_VERSION = '2026-07-28.1';\n\nexport const SQLITE_EPOCH_SENTINEL = `'1970-01-01T00:00:00.000Z'`;\nexport const SQLITE_ISO_NOW_FN = `() => new Date().toISOString()`;\n\nexport type SchemaDialect = 'postgres' | 'sqlite';\nexport type ManagedColumnDialect = SchemaDialect;\nexport type NamingConvention = 'snake_case' | 'camelCase';\nexport type ManagedRequirementKind = 'audit' | 'soft-delete' | 'id' | 'scope';\n\nexport const AUDIT_JS_NAMES = ['createdAt', 'modifiedAt', 'createdBy', 'modifiedBy'] as const;\nexport const SOFT_DELETE_JS_NAMES = ['deletedAt', 'deletedBy'] as const;\n\nexport type AuditJsName = (typeof AUDIT_JS_NAMES)[number];\nexport type SoftDeleteJsName = (typeof SOFT_DELETE_JS_NAMES)[number];\nexport type AuditManagedJsName = AuditJsName | SoftDeleteJsName;\n\nexport interface ManagedColumnSpec {\n jsName: string;\n snakeName: string;\n kind: 'timestamp' | 'text';\n notNull: boolean;\n /** Compatibility discriminator used by existing compiler consumers. */\n audit: boolean;\n requirement: ManagedRequirementKind;\n}\n\nexport const AUDIT_COLUMN_SPECS: ReadonlyArray<ManagedColumnSpec> = [\n {\n jsName: 'createdAt',\n snakeName: 'created_at',\n kind: 'timestamp',\n notNull: true,\n audit: true,\n requirement: 'audit',\n },\n {\n jsName: 'modifiedAt',\n snakeName: 'modified_at',\n kind: 'timestamp',\n notNull: true,\n audit: true,\n requirement: 'audit',\n },\n {\n jsName: 'createdBy',\n snakeName: 'created_by',\n kind: 'text',\n notNull: false,\n audit: true,\n requirement: 'audit',\n },\n {\n jsName: 'modifiedBy',\n snakeName: 'modified_by',\n kind: 'text',\n notNull: false,\n audit: true,\n requirement: 'audit',\n },\n];\n\nexport const SOFT_DELETE_COLUMN_SPECS: ReadonlyArray<ManagedColumnSpec> = [\n {\n jsName: 'deletedAt',\n snakeName: 'deleted_at',\n kind: 'timestamp',\n notNull: false,\n audit: false,\n requirement: 'soft-delete',\n },\n {\n jsName: 'deletedBy',\n snakeName: 'deleted_by',\n kind: 'text',\n notNull: false,\n audit: false,\n requirement: 'soft-delete',\n },\n];\n\nexport const MANAGED_AUDIT_COLUMN_SPECS: ReadonlyArray<ManagedColumnSpec> = [\n ...AUDIT_COLUMN_SPECS,\n ...SOFT_DELETE_COLUMN_SPECS,\n];\nexport const MANAGED_COLUMN_SPECS = MANAGED_AUDIT_COLUMN_SPECS;\nexport const MANAGED_AUDIT_JS_NAMES: ReadonlySet<string> = new Set([\n ...AUDIT_JS_NAMES,\n ...SOFT_DELETE_JS_NAMES,\n]);\n\nexport interface ManagedGroupRequirement {\n kind: 'audit' | 'soft-delete';\n columns: ReadonlyArray<ManagedColumnSpec>;\n /** Canonical q-DSL spread helper, without the leading `...` or call. */\n qHelper: 'audit' | 'softDelete';\n}\n\nexport interface ManagedPhysicalColumnRequirement {\n kind: 'id' | 'scope';\n jsName: string;\n sqlName: string;\n /** Canonical q initializer, without `<jsName>:`. */\n qExpression: string;\n /** Canonical raw-Drizzle initializer, without `<jsName>:`. */\n rawExpression: string;\n /**\n * Additional exact expressions accepted as canonical. This is useful while\n * source-visible ID strategies are migrated without weakening validation.\n */\n acceptedQExpressions?: ReadonlyArray<string>;\n acceptedRawExpressions?: ReadonlyArray<string>;\n}\n\nexport type ManagedColumnRequirement =\n | ManagedGroupRequirement\n | ManagedPhysicalColumnRequirement;\n\nexport interface IdRequirementOptions {\n dialect: SchemaDialect;\n namingConvention?: NamingConvention;\n qExpression?: string;\n rawExpression?: string;\n acceptedQExpressions?: ReadonlyArray<string>;\n acceptedRawExpressions?: ReadonlyArray<string>;\n}\n\nexport interface ScopeRequirementOptions {\n dialect: SchemaDialect;\n kind: string;\n jsName?: string;\n sqlName?: string;\n namingConvention?: NamingConvention;\n qExpression?: string;\n rawExpression?: string;\n acceptedQExpressions?: ReadonlyArray<string>;\n acceptedRawExpressions?: ReadonlyArray<string>;\n}\n\nexport function managedSqlName(\n spec: Pick<ManagedColumnSpec, 'jsName' | 'snakeName'>,\n convention: NamingConvention,\n): string {\n return convention === 'snake_case' ? spec.snakeName : spec.jsName;\n}\n\nexport function managedColumnExpr(\n spec: ManagedColumnSpec,\n dialect: SchemaDialect,\n sqlName: string,\n): string {\n if (spec.kind === 'text' || (spec.jsName === 'deletedAt' && dialect === 'sqlite')) {\n return dialect === 'postgres' && spec.kind === 'timestamp'\n ? `timestamp(\"${sqlName}\", { withTimezone: true })`\n : `text(\"${sqlName}\")`;\n }\n if (spec.jsName === 'deletedAt') {\n return `timestamp(\"${sqlName}\", { withTimezone: true })`;\n }\n const pgUpdate = spec.jsName === 'modifiedAt' ? `.$onUpdate(() => new Date())` : '';\n const sqliteUpdate =\n spec.jsName === 'modifiedAt' ? `.$onUpdate(${SQLITE_ISO_NOW_FN})` : '';\n return dialect === 'postgres'\n ? `timestamp(\"${sqlName}\", { withTimezone: true }).notNull().defaultNow()${pgUpdate}`\n : `text(\"${sqlName}\").notNull().default(${SQLITE_EPOCH_SENTINEL}).$defaultFn(${SQLITE_ISO_NOW_FN})${sqliteUpdate}`;\n}\n\nexport function managedColumnLine(\n spec: ManagedColumnSpec,\n dialect: SchemaDialect,\n convention: NamingConvention,\n): string {\n return `${spec.jsName}: ${managedColumnExpr(\n spec,\n dialect,\n managedSqlName(spec, convention),\n )},`;\n}\n\nexport function auditRequirement(): ManagedGroupRequirement {\n return {\n kind: 'audit',\n columns: AUDIT_COLUMN_SPECS,\n qHelper: 'audit',\n };\n}\n\nexport function softDeleteRequirement(): ManagedGroupRequirement {\n return {\n kind: 'soft-delete',\n columns: SOFT_DELETE_COLUMN_SPECS,\n qHelper: 'softDelete',\n };\n}\n\nexport function idRequirement(options: IdRequirementOptions): ManagedPhysicalColumnRequirement {\n const sqlName = options.namingConvention === 'camelCase' ? 'id' : 'id';\n return {\n kind: 'id',\n jsName: 'id',\n sqlName,\n qExpression: options.qExpression ?? 'q.id()',\n rawExpression: options.rawExpression ?? `text(\"${sqlName}\").primaryKey()`,\n acceptedQExpressions: options.acceptedQExpressions,\n acceptedRawExpressions: options.acceptedRawExpressions,\n };\n}\n\nexport function scopeRequirement(\n options: ScopeRequirementOptions,\n): ManagedPhysicalColumnRequirement {\n const jsName = options.jsName ?? `${options.kind}Id`;\n const convention = options.namingConvention ?? 'snake_case';\n const snakeName = jsName.replace(/[A-Z]/g, (character) => `_${character.toLowerCase()}`);\n const sqlName = options.sqlName ?? (convention === 'snake_case' ? snakeName : jsName);\n return {\n kind: 'scope',\n jsName,\n sqlName,\n qExpression: options.qExpression ?? `q.scope(\"${options.kind}\")`,\n rawExpression: options.rawExpression ?? `text(\"${sqlName}\").notNull()`,\n acceptedQExpressions: options.acceptedQExpressions,\n acceptedRawExpressions: options.acceptedRawExpressions,\n };\n}\n", "/**\n * Single source of truth for database provider \u2192 SQL dialect resolution.\n *\n * Both the compiler (`apps/compiler/src/transforms/dialect.ts`) and the CLI\n * (`quickback schema check|sync`) resolve dialects through this module. Keeping\n * one definition here is what prevents the class of bug where the two sides\n * disagree and `schema sync` writes wrong-dialect declarations into authored\n * source (issue #213).\n */\n\nexport type ProviderDialect = 'sqlite' | 'postgres' | 'mysql';\n\nexport const SQLITE_PROVIDERS = [\n 'cloudflare-d1',\n 'better-sqlite3',\n 'bun-sqlite',\n 'libsql',\n 'turso',\n] as const;\n\nexport const POSTGRES_PROVIDERS = [\n 'supabase',\n 'neon',\n // `planetscale` (below) stays MySQL: PlanetScale ships both engines, and\n // the Postgres one is a distinct provider name.\n 'planetscale-postgres',\n 'vercel-postgres',\n 'postgres',\n 'postgresql',\n] as const;\n\nexport const MYSQL_PROVIDERS = ['planetscale', 'mysql', 'mysql2'] as const;\n\n/**\n * Resolve a database provider name to its SQL dialect family.\n *\n * Returns `undefined` for unknown or missing provider names so each caller\n * chooses its own fallback explicitly (the compiler defaults to sqlite; the\n * CLI does the same but refuses dialects it cannot emit).\n */\nexport function resolveProviderDialect(\n providerName: string | undefined,\n): ProviderDialect | undefined {\n if (!providerName) return undefined;\n if ((SQLITE_PROVIDERS as readonly string[]).includes(providerName)) return 'sqlite';\n if ((POSTGRES_PROVIDERS as readonly string[]).includes(providerName)) return 'postgres';\n if ((MYSQL_PROVIDERS as readonly string[]).includes(providerName)) return 'mysql';\n return undefined;\n}\n", "import type * as TypeScript from 'typescript';\nimport {\n managedColumnExpr,\n managedColumnLine,\n managedSqlName,\n type ManagedColumnRequirement,\n type ManagedGroupRequirement,\n type ManagedPhysicalColumnRequirement,\n type NamingConvention,\n type SchemaDialect,\n} from './managed-columns.js';\n\nexport type TypeScriptApi = Omit<typeof TypeScript, 'default'>;\nexport type SchemaTableStyle = 'q-feature' | 'q-table' | 'raw-drizzle';\nexport type StaticDeleteMode = 'hard' | 'soft' | 'default' | 'dynamic';\n\nexport interface SchemaTableContext {\n /** Stable within one source file, even when SQL table names repeat. */\n id: string;\n fileName: string;\n tableName: string;\n variableName?: string;\n style: SchemaTableStyle;\n dialect: SchemaDialect;\n namingConvention: NamingConvention;\n hasResourceConfig: boolean;\n deleteMode: StaticDeleteMode;\n /**\n * `crud.batchDelete.mode`, inheriting `deleteMode` when unset \u2014 the same\n * resolution the compiler applies in `resolveDeleteModes`. Soft-delete\n * columns are required unless BOTH paths are hard, so a resolver that reads\n * only `deleteMode` under-reports the requirement for\n * `delete: { mode: 'hard' }, batchDelete: { mode: 'soft' }`.\n */\n batchDeleteMode: StaticDeleteMode;\n sourceStart: number;\n sourceEnd: number;\n}\n\nexport type ManagedRequirementResolver = (\n table: SchemaTableContext,\n) => ReadonlyArray<ManagedColumnRequirement>;\n\nexport interface SchemaSourceEdit {\n start: number;\n end: number;\n text: string;\n tableId?: string;\n reason: string;\n}\n\nexport type SchemaSyncDiagnosticCode =\n | 'DIVERGENT_MANAGED_COLUMN'\n | 'DUPLICATE_MANAGED_REPRESENTATION'\n | 'DUPLICATE_TABLE_COLUMN'\n | 'MISSING_VALUE_IMPORT'\n | 'SOURCE_PARSE_ERROR'\n | 'UNSUPPORTED_DYNAMIC_DELETE_MODE'\n | 'REQUIREMENT_RESOLUTION_FAILED'\n | 'INVALID_REQUIREMENT'\n | 'OVERLAPPING_SOURCE_EDITS';\n\nexport interface SchemaSyncDiagnostic {\n code: SchemaSyncDiagnosticCode;\n message: string;\n fileName: string;\n tableId?: string;\n tableName?: string;\n start?: number;\n end?: number;\n expected?: string;\n actual?: string;\n}\n\nexport interface PlanSchemaSourceOptions {\n fileName: string;\n source: string;\n typescript: TypeScriptApi;\n dialect: SchemaDialect;\n namingConvention?: NamingConvention;\n resolveRequirements: ManagedRequirementResolver;\n}\n\nexport interface SchemaSourcePlan {\n fileName: string;\n source: string;\n tables: ReadonlyArray<SchemaTableContext>;\n edits: ReadonlyArray<SchemaSourceEdit>;\n diagnostics: ReadonlyArray<SchemaSyncDiagnostic>;\n updatedSource: string;\n changed: boolean;\n canApply: boolean;\n}\n\ninterface DiscoveredTable {\n context: SchemaTableContext;\n columns: TypeScript.ObjectLiteralExpression;\n}\n\ninterface PlannedEntry {\n source: string;\n order: number;\n}\n\ninterface ImportRequirement {\n identifiers: Set<string>;\n tableIds: Set<string>;\n}\n\nconst MANAGED_MARKER =\n '// \u2500\u2500 quickback:audit (compiler-managed \u2014 edits are validated, not merged) \u2500\u2500';\n\n/**\n * Inspect every table in one source file and calculate formatting-preserving,\n * additive-only source edits. No edit is applied here.\n */\nexport function planSchemaSource(options: PlanSchemaSourceOptions): SchemaSourcePlan {\n const ts = options.typescript;\n const namingConvention = options.namingConvention ?? 'snake_case';\n const sourceFile = ts.createSourceFile(\n options.fileName,\n options.source,\n ts.ScriptTarget.Latest,\n true,\n options.fileName.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,\n );\n const diagnostics: SchemaSyncDiagnostic[] = [];\n const parseDiagnostics = (\n sourceFile as TypeScript.SourceFile & {\n parseDiagnostics?: ReadonlyArray<TypeScript.Diagnostic>;\n }\n ).parseDiagnostics;\n if (parseDiagnostics && parseDiagnostics.length > 0) {\n for (const diagnostic of parseDiagnostics) {\n diagnostics.push({\n code: 'SOURCE_PARSE_ERROR',\n fileName: options.fileName,\n start: diagnostic.start,\n end:\n diagnostic.start !== undefined && diagnostic.length !== undefined\n ? diagnostic.start + diagnostic.length\n : undefined,\n message:\n `TypeScript could not parse this schema source: ` +\n ts.flattenDiagnosticMessageText(diagnostic.messageText, '\\n'),\n });\n }\n return {\n fileName: options.fileName,\n source: options.source,\n tables: [],\n edits: [],\n diagnostics,\n updatedSource: options.source,\n changed: false,\n canApply: false,\n };\n }\n const discovered = discoverTables(ts, sourceFile, options.dialect, namingConvention);\n const edits: SchemaSourceEdit[] = [];\n const imports = new Map<string, ImportRequirement>();\n\n for (const table of discovered) {\n let requirements: ReadonlyArray<ManagedColumnRequirement>;\n try {\n requirements = options.resolveRequirements(table.context);\n } catch (error) {\n diagnostics.push({\n code: 'REQUIREMENT_RESOLUTION_FAILED',\n fileName: options.fileName,\n tableId: table.context.id,\n tableName: table.context.tableName,\n start: table.context.sourceStart,\n end: table.context.sourceEnd,\n message:\n `Could not determine managed-column requirements for table ` +\n `\"${table.context.tableName}\": ${error instanceof Error ? error.message : String(error)}`,\n });\n continue;\n }\n if (!Array.isArray(requirements)) {\n diagnostics.push({\n code: 'INVALID_REQUIREMENT',\n fileName: options.fileName,\n tableId: table.context.id,\n tableName: table.context.tableName,\n message:\n `The managed-column resolver for table \"${table.context.tableName}\" did not return an array.`,\n });\n continue;\n }\n\n const entries: PlannedEntry[] = [];\n const seenKinds = new Set<string>();\n let needsManagedMarker = false;\n\n for (const requirement of requirements) {\n const key =\n requirement.kind === 'scope'\n ? `${requirement.kind}:${requirement.jsName}`\n : requirement.kind;\n if (seenKinds.has(key)) {\n diagnostics.push({\n code: 'INVALID_REQUIREMENT',\n fileName: options.fileName,\n tableId: table.context.id,\n tableName: table.context.tableName,\n message: `Requirement \"${key}\" was supplied more than once for table \"${table.context.tableName}\".`,\n });\n continue;\n }\n seenKinds.add(key);\n\n if (isManagedGroupRequirement(requirement)) {\n const result = planManagedGroup(\n ts,\n sourceFile,\n table,\n requirement,\n options.fileName,\n diagnostics,\n );\n entries.push(...result.entries);\n needsManagedMarker ||= result.needsMarker;\n for (const identifier of result.requiredImports) {\n addImportRequirement(\n imports,\n drizzleCoreModule(table.context.dialect),\n identifier,\n table.context.id,\n );\n }\n if (result.needsQImport) {\n addImportRequirement(imports, '@quickback/compiler', 'q', table.context.id);\n }\n continue;\n }\n\n const result = planPhysicalColumn(\n ts,\n sourceFile,\n table,\n requirement,\n options.fileName,\n diagnostics,\n );\n entries.push(...result.entries);\n for (const identifier of result.requiredImports) {\n addImportRequirement(\n imports,\n drizzleCoreModule(table.context.dialect),\n identifier,\n table.context.id,\n );\n }\n if (result.needsQImport) {\n addImportRequirement(imports, '@quickback/compiler', 'q', table.context.id);\n }\n }\n\n if (entries.length === 0) continue;\n entries.sort((a, b) => a.order - b.order);\n if (\n table.context.style === 'raw-drizzle' &&\n needsManagedMarker &&\n !options.source\n .slice(table.columns.getStart(sourceFile), table.columns.getEnd())\n .includes('quickback:audit')\n ) {\n const firstManagedIndex = entries.findIndex((entry) => entry.order >= 20);\n entries.splice(firstManagedIndex < 0 ? entries.length : firstManagedIndex, 0, {\n source: MANAGED_MARKER,\n order: 19,\n });\n }\n edits.push(\n ...planObjectInsertion(\n sourceFile,\n table.columns,\n entries.map((entry) => entry.source),\n table.context.id,\n ),\n );\n }\n\n for (const [moduleName, requirement] of imports) {\n planNamedImport(\n ts,\n sourceFile,\n moduleName,\n requirement,\n options.fileName,\n edits,\n diagnostics,\n );\n }\n\n let updatedSource = options.source;\n try {\n updatedSource = applySchemaSourceEdits(options.source, edits);\n } catch (error) {\n diagnostics.push({\n code: 'OVERLAPPING_SOURCE_EDITS',\n fileName: options.fileName,\n message: error instanceof Error ? error.message : String(error),\n });\n }\n\n return {\n fileName: options.fileName,\n source: options.source,\n tables: discovered.map((table) => table.context),\n edits,\n diagnostics,\n updatedSource,\n changed: updatedSource !== options.source,\n canApply: diagnostics.length === 0,\n };\n}\n\nfunction isManagedGroupRequirement(\n requirement: ManagedColumnRequirement,\n): requirement is ManagedGroupRequirement {\n return requirement.kind === 'audit' || requirement.kind === 'soft-delete';\n}\n\nexport function applySchemaSourceEdits(\n source: string,\n edits: ReadonlyArray<SchemaSourceEdit>,\n): string {\n const ordered = [...edits].sort((left, right) => {\n if (left.start !== right.start) return right.start - left.start;\n return right.end - left.end;\n });\n let previousStart = source.length + 1;\n let output = source;\n for (const edit of ordered) {\n if (\n edit.start < 0 ||\n edit.end < edit.start ||\n edit.end > source.length ||\n edit.end > previousStart\n ) {\n throw new Error(\n `Schema source edits overlap or address an invalid span: ${edit.start}..${edit.end} (${edit.reason}).`,\n );\n }\n output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);\n previousStart = edit.start;\n }\n return output;\n}\n\nfunction discoverTables(\n ts: TypeScriptApi,\n sourceFile: TypeScript.SourceFile,\n defaultDialect: SchemaDialect,\n namingConvention: NamingConvention,\n): DiscoveredTable[] {\n const resourceByVariable = new Map<string, TypeScript.Expression>();\n\n const collectResources = (node: TypeScript.Node): void => {\n if (ts.isCallExpression(node) && isNamedCall(ts, node.expression, 'defineTable')) {\n const tableArg = node.arguments[0];\n const configArg = node.arguments[1];\n if (tableArg && ts.isIdentifier(tableArg) && configArg) {\n resourceByVariable.set(tableArg.text, configArg);\n }\n }\n ts.forEachChild(node, collectResources);\n };\n collectResources(sourceFile);\n\n const tables: DiscoveredTable[] = [];\n const occurrenceByName = new Map<string, number>();\n const visit = (node: TypeScript.Node): void => {\n if (!ts.isCallExpression(node)) {\n ts.forEachChild(node, visit);\n return;\n }\n\n const callKind = tableCallKind(ts, node.expression);\n if (!callKind) {\n ts.forEachChild(node, visit);\n return;\n }\n const nameArg = node.arguments[0];\n const bodyArg = node.arguments[1];\n if (!nameArg || !ts.isStringLiteralLike(nameArg) || !bodyArg) {\n ts.forEachChild(node, visit);\n return;\n }\n\n const variableName = enclosingVariableName(ts, node);\n let columns: TypeScript.ObjectLiteralExpression | undefined;\n let resource: TypeScript.Expression | undefined;\n let style: SchemaTableStyle;\n let dialect = defaultDialect;\n\n if (callKind === 'feature') {\n if (!ts.isObjectLiteralExpression(bodyArg)) {\n ts.forEachChild(node, visit);\n return;\n }\n columns = objectPropertyObject(ts, bodyArg, 'columns');\n resource = bodyArg;\n style = 'q-feature';\n } else if (callKind === 'q-table') {\n if (!ts.isObjectLiteralExpression(bodyArg)) {\n ts.forEachChild(node, visit);\n return;\n }\n columns = bodyArg;\n resource = variableName ? resourceByVariable.get(variableName) : undefined;\n style = 'q-table';\n } else {\n if (!ts.isObjectLiteralExpression(bodyArg)) {\n ts.forEachChild(node, visit);\n return;\n }\n columns = bodyArg;\n resource = variableName ? resourceByVariable.get(variableName) : undefined;\n style = 'raw-drizzle';\n dialect = callKind === 'pg-table' ? 'postgres' : 'sqlite';\n }\n\n if (!columns) {\n ts.forEachChild(node, visit);\n return;\n }\n const tableName = nameArg.text;\n const occurrence = (occurrenceByName.get(tableName) ?? 0) + 1;\n occurrenceByName.set(tableName, occurrence);\n tables.push({\n context: {\n id: `${tableName}@${occurrence}`,\n fileName: sourceFile.fileName,\n tableName,\n variableName,\n style,\n dialect,\n namingConvention,\n hasResourceConfig: resource !== undefined,\n deleteMode: resource ? readDeleteMode(ts, resource) : 'default',\n batchDeleteMode: resource ? readBatchDeleteMode(ts, resource) : 'default',\n sourceStart: node.getStart(sourceFile),\n sourceEnd: node.getEnd(),\n },\n columns,\n });\n // Table calls cannot contain another table definition in their columns.\n };\n visit(sourceFile);\n return tables.sort((left, right) => left.context.sourceStart - right.context.sourceStart);\n}\n\ntype TableCallKind = 'feature' | 'q-table' | 'pg-table' | 'sqlite-table';\n\nfunction tableCallKind(\n ts: TypeScriptApi,\n expression: TypeScript.LeftHandSideExpression,\n): TableCallKind | undefined {\n if (ts.isIdentifier(expression)) {\n if (expression.text === 'feature') return 'feature';\n if (expression.text === 'pgTable') return 'pg-table';\n if (expression.text === 'sqliteTable') return 'sqlite-table';\n return undefined;\n }\n if (!ts.isPropertyAccessExpression(expression)) return undefined;\n if (expression.name.text === 'pgTable') return 'pg-table';\n if (expression.name.text === 'sqliteTable') return 'sqlite-table';\n if (\n ts.isIdentifier(expression.expression) &&\n (expression.expression.text === 'q' || expression.expression.text === 'qb')\n ) {\n if (expression.name.text === 'table') return 'q-table';\n if (expression.name.text === 'feature') return 'feature';\n }\n return undefined;\n}\n\nfunction enclosingVariableName(\n ts: TypeScriptApi,\n call: TypeScript.CallExpression,\n): string | undefined {\n const parent = call.parent;\n return ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name)\n ? parent.name.text\n : undefined;\n}\n\nfunction isNamedCall(\n ts: TypeScriptApi,\n expression: TypeScript.LeftHandSideExpression,\n name: string,\n): boolean {\n return (\n (ts.isIdentifier(expression) && expression.text === name) ||\n (ts.isPropertyAccessExpression(expression) && expression.name.text === name)\n );\n}\n\nfunction objectPropertyObject(\n ts: TypeScriptApi,\n object: TypeScript.ObjectLiteralExpression,\n name: string,\n): TypeScript.ObjectLiteralExpression | undefined {\n const property = object.properties.find(\n (candidate): candidate is TypeScript.PropertyAssignment =>\n ts.isPropertyAssignment(candidate) && propertyName(ts, candidate.name) === name,\n );\n return property && ts.isObjectLiteralExpression(property.initializer)\n ? property.initializer\n : undefined;\n}\n\nfunction readDeleteMode(\n ts: TypeScriptApi,\n expression: TypeScript.Expression,\n): StaticDeleteMode {\n if (!ts.isObjectLiteralExpression(expression)) return 'dynamic';\n let deleteExpression = propertyInitializer(ts, expression, 'delete');\n if (!deleteExpression) {\n const crud = propertyInitializer(ts, expression, 'crud');\n if (crud && !ts.isObjectLiteralExpression(crud)) return 'dynamic';\n if (crud && ts.isObjectLiteralExpression(crud)) {\n deleteExpression = propertyInitializer(ts, crud, 'delete');\n }\n }\n if (!deleteExpression) return 'default';\n if (!ts.isObjectLiteralExpression(deleteExpression)) return 'dynamic';\n const mode = propertyInitializer(ts, deleteExpression, 'mode');\n if (!mode) return 'default';\n if (!ts.isStringLiteralLike(mode)) return 'dynamic';\n if (mode.text === 'hard') return 'hard';\n if (mode.text === 'soft') return 'soft';\n return 'dynamic';\n}\n\n/**\n * `batchDelete.mode`, resolved with the inheritance the compiler applies in\n * `resolveDeleteModes`: an absent or `false` batchDelete inherits the delete\n * mode, and an explicit batchDelete without its own `mode` inherits it too.\n *\n * This exists because soft-delete columns are required unless EVERY delete\n * path is hard. Reading `delete.mode` alone silently under-reports the\n * requirement for `delete: { mode: 'hard' }, batchDelete: { mode: 'soft' }`,\n * which the compiler then rejects.\n */\nfunction readBatchDeleteMode(\n ts: TypeScriptApi,\n expression: TypeScript.Expression,\n): StaticDeleteMode {\n if (!ts.isObjectLiteralExpression(expression)) return 'dynamic';\n const inherited = readDeleteMode(ts, expression);\n\n let batchExpression = propertyInitializer(ts, expression, 'batchDelete');\n if (!batchExpression) {\n const crud = propertyInitializer(ts, expression, 'crud');\n if (crud && !ts.isObjectLiteralExpression(crud)) return 'dynamic';\n if (crud && ts.isObjectLiteralExpression(crud)) {\n batchExpression = propertyInitializer(ts, crud, 'batchDelete');\n }\n }\n // Absent, or disabled outright \u2014 the delete mode governs.\n if (!batchExpression) return inherited;\n if (batchExpression.kind === ts.SyntaxKind.FalseKeyword) return inherited;\n if (!ts.isObjectLiteralExpression(batchExpression)) return 'dynamic';\n\n const mode = propertyInitializer(ts, batchExpression, 'mode');\n if (!mode) return inherited;\n if (!ts.isStringLiteralLike(mode)) return 'dynamic';\n if (mode.text === 'hard') return 'hard';\n if (mode.text === 'soft') return 'soft';\n return 'dynamic';\n}\n\nfunction propertyInitializer(\n ts: TypeScriptApi,\n object: TypeScript.ObjectLiteralExpression,\n name: string,\n): TypeScript.Expression | undefined {\n for (const property of object.properties) {\n if (ts.isPropertyAssignment(property) && propertyName(ts, property.name) === name) {\n return property.initializer;\n }\n if (ts.isShorthandPropertyAssignment(property) && property.name.text === name) {\n return property.name;\n }\n }\n return undefined;\n}\n\nfunction propertyName(\n ts: TypeScriptApi,\n name: TypeScript.PropertyName,\n): string | undefined {\n if (ts.isIdentifier(name) || ts.isPrivateIdentifier(name)) return name.text;\n if (ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) return name.text;\n return undefined;\n}\n\nfunction planManagedGroup(\n ts: TypeScriptApi,\n sourceFile: TypeScript.SourceFile,\n table: DiscoveredTable,\n requirement: ManagedGroupRequirement,\n fileName: string,\n diagnostics: SchemaSyncDiagnostic[],\n): {\n entries: PlannedEntry[];\n requiredImports: Set<string>;\n needsQImport: boolean;\n needsMarker: boolean;\n} {\n if (table.context.style !== 'raw-drizzle') {\n const helperSpread = findQHelperSpread(ts, table.columns, requirement.qHelper);\n const explicit = table.columns.properties.filter((property) => {\n if (!ts.isPropertyAssignment(property)) return false;\n const name = propertyName(ts, property.name);\n return requirement.columns.some((column) => column.jsName === name);\n });\n if (helperSpread && explicit.length > 0) {\n diagnostics.push({\n code: 'DUPLICATE_MANAGED_REPRESENTATION',\n fileName,\n tableId: table.context.id,\n tableName: table.context.tableName,\n start: explicit[0]!.getStart(sourceFile),\n end: explicit[explicit.length - 1]!.getEnd(),\n expected: `...q.${requirement.qHelper}(),`,\n actual: explicit.map((property) => property.getText(sourceFile)).join('\\n'),\n message:\n `Table \"${table.context.tableName}\" declares both ...q.${requirement.qHelper}() ` +\n `and explicit ${requirement.kind} columns. Remove the explicit duplicates manually.`,\n });\n return {\n entries: [],\n requiredImports: new Set(),\n needsQImport: false,\n needsMarker: false,\n };\n }\n if (helperSpread) {\n return {\n entries: [],\n requiredImports: new Set(),\n needsQImport: false,\n needsMarker: false,\n };\n }\n if (explicit.length > 0) {\n diagnostics.push({\n code: 'DIVERGENT_MANAGED_COLUMN',\n fileName,\n tableId: table.context.id,\n tableName: table.context.tableName,\n start: explicit[0]!.getStart(sourceFile),\n end: explicit[explicit.length - 1]!.getEnd(),\n expected: `...q.${requirement.qHelper}(),`,\n actual: explicit.map((property) => property.getText(sourceFile)).join('\\n'),\n message:\n `Table \"${table.context.tableName}\" uses explicit q-DSL ${requirement.kind} ` +\n `columns. Quickback cannot prove that hand-written q chains match the managed ` +\n `contract; replace them manually with ...q.${requirement.qHelper}().`,\n });\n return {\n entries: [],\n requiredImports: new Set(),\n needsQImport: false,\n needsMarker: false,\n };\n }\n return {\n entries: [{ source: `...q.${requirement.qHelper}(),`, order: groupOrder(requirement.kind) }],\n requiredImports: new Set(),\n needsQImport: true,\n needsMarker: false,\n };\n }\n\n const entries: PlannedEntry[] = [];\n const requiredImports = new Set<string>();\n for (const column of requirement.columns) {\n const sqlName = managedSqlName(column, table.context.namingConvention);\n const expectedExpression = managedColumnExpr(column, table.context.dialect, sqlName);\n const expectedLine = managedColumnLine(\n column,\n table.context.dialect,\n table.context.namingConvention,\n );\n const matches = matchingRawProperties(ts, table.columns, column.jsName, sqlName);\n if (matches.length > 1) {\n diagnostics.push(duplicateColumnDiagnostic(fileName, sourceFile, table, column.jsName, matches));\n continue;\n }\n const existing = matches[0];\n if (!existing) {\n entries.push({ source: expectedLine, order: groupOrder(requirement.kind) });\n for (const identifier of calledBuilderIdentifiers(expectedExpression)) {\n requiredImports.add(identifier);\n }\n continue;\n }\n if (\n propertyName(ts, existing.name) !== column.jsName ||\n !expressionMatches(sourceFile, existing.initializer, [expectedExpression])\n ) {\n diagnostics.push(\n divergentColumnDiagnostic(\n fileName,\n sourceFile,\n table,\n existing,\n expectedLine,\n column.jsName,\n ),\n );\n }\n }\n return {\n entries,\n requiredImports,\n needsQImport: false,\n needsMarker: entries.length > 0,\n };\n}\n\nfunction planPhysicalColumn(\n ts: TypeScriptApi,\n sourceFile: TypeScript.SourceFile,\n table: DiscoveredTable,\n requirement: ManagedPhysicalColumnRequirement,\n fileName: string,\n diagnostics: SchemaSyncDiagnostic[],\n): {\n entries: PlannedEntry[];\n requiredImports: Set<string>;\n needsQImport: boolean;\n} {\n const raw = table.context.style === 'raw-drizzle';\n const matches = raw\n ? matchingRawProperties(ts, table.columns, requirement.jsName, requirement.sqlName)\n : matchingQProperties(ts, table.columns, requirement.jsName);\n if (matches.length > 1) {\n diagnostics.push(\n duplicateColumnDiagnostic(fileName, sourceFile, table, requirement.jsName, matches),\n );\n return { entries: [], requiredImports: new Set(), needsQImport: false };\n }\n\n const expression = raw ? requirement.rawExpression : requirement.qExpression;\n const accepted = raw\n ? [requirement.rawExpression, ...(requirement.acceptedRawExpressions ?? [])]\n : [requirement.qExpression, ...(requirement.acceptedQExpressions ?? [])];\n const expected = `${requirement.jsName}: ${expression},`;\n const existing = matches[0];\n if (existing) {\n if (\n propertyName(ts, existing.name) !== requirement.jsName ||\n !expressionMatches(sourceFile, existing.initializer, accepted)\n ) {\n diagnostics.push(\n divergentColumnDiagnostic(\n fileName,\n sourceFile,\n table,\n existing,\n expected,\n requirement.jsName,\n ),\n );\n }\n return { entries: [], requiredImports: new Set(), needsQImport: false };\n }\n\n return {\n entries: [{ source: expected, order: requirement.kind === 'id' ? 0 : 10 }],\n requiredImports: raw\n ? new Set(calledBuilderIdentifiers(requirement.rawExpression))\n : new Set(),\n needsQImport: !raw,\n };\n}\n\nfunction groupOrder(kind: 'audit' | 'soft-delete'): number {\n return kind === 'audit' ? 20 : 30;\n}\n\nfunction findQHelperSpread(\n ts: TypeScriptApi,\n object: TypeScript.ObjectLiteralExpression,\n helper: string,\n): TypeScript.SpreadAssignment | undefined {\n return object.properties.find((property): property is TypeScript.SpreadAssignment => {\n if (!ts.isSpreadAssignment(property) || !ts.isCallExpression(property.expression)) {\n return false;\n }\n const callee = property.expression.expression;\n return (\n ts.isPropertyAccessExpression(callee) &&\n ts.isIdentifier(callee.expression) &&\n callee.expression.text === 'q' &&\n callee.name.text === helper &&\n property.expression.arguments.length === 0\n );\n });\n}\n\nfunction matchingQProperties(\n ts: TypeScriptApi,\n object: TypeScript.ObjectLiteralExpression,\n jsName: string,\n): TypeScript.PropertyAssignment[] {\n return object.properties.filter(\n (property): property is TypeScript.PropertyAssignment =>\n ts.isPropertyAssignment(property) && propertyName(ts, property.name) === jsName,\n );\n}\n\nfunction matchingRawProperties(\n ts: TypeScriptApi,\n object: TypeScript.ObjectLiteralExpression,\n jsName: string,\n sqlName: string,\n): TypeScript.PropertyAssignment[] {\n return object.properties.filter((property): property is TypeScript.PropertyAssignment => {\n if (!ts.isPropertyAssignment(property)) return false;\n if (propertyName(ts, property.name) === jsName) return true;\n return firstStringArgument(ts, property.initializer) === sqlName;\n });\n}\n\nfunction firstStringArgument(\n ts: TypeScriptApi,\n expression: TypeScript.Expression,\n): string | undefined {\n let current = expression;\n while (ts.isCallExpression(current)) {\n const first = current.arguments[0];\n if (first && ts.isStringLiteralLike(first)) return first.text;\n const callee = current.expression;\n if (!ts.isPropertyAccessExpression(callee)) break;\n current = callee.expression;\n }\n return undefined;\n}\n\nfunction expressionMatches(\n sourceFile: TypeScript.SourceFile,\n expression: TypeScript.Expression,\n accepted: ReadonlyArray<string>,\n): boolean {\n const actual = normalizeExpression(expression.getText(sourceFile));\n return accepted.some((candidate) => normalizeExpression(candidate) === actual);\n}\n\nfunction normalizeExpression(source: string): string {\n return source\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n .replace(/\\/\\/[^\\r\\n]*/g, '')\n .replace(/'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)'/g, (_match, value: string) => `\"${value}\"`)\n .replace(/\\s+/g, '');\n}\n\nfunction calledBuilderIdentifiers(expression: string): string[] {\n const identifiers = new Set<string>();\n for (const match of expression.matchAll(/(?:^|[\\s:,{(])([A-Za-z_$][\\w$]*)\\s*\\(/g)) {\n const identifier = match[1]!;\n if (identifier !== 'Date') identifiers.add(identifier);\n }\n return [...identifiers].sort();\n}\n\nfunction duplicateColumnDiagnostic(\n fileName: string,\n sourceFile: TypeScript.SourceFile,\n table: DiscoveredTable,\n jsName: string,\n properties: TypeScript.PropertyAssignment[],\n): SchemaSyncDiagnostic {\n return {\n code: 'DUPLICATE_TABLE_COLUMN',\n fileName,\n tableId: table.context.id,\n tableName: table.context.tableName,\n start: properties[0]!.getStart(sourceFile),\n end: properties[properties.length - 1]!.getEnd(),\n actual: properties.map((property) => property.getText(sourceFile)).join('\\n'),\n message:\n `Table \"${table.context.tableName}\" declares managed column \"${jsName}\" more than once. ` +\n `Resolve the duplicate manually before syncing.`,\n };\n}\n\nfunction divergentColumnDiagnostic(\n fileName: string,\n sourceFile: TypeScript.SourceFile,\n table: DiscoveredTable,\n property: TypeScript.PropertyAssignment,\n expected: string,\n jsName: string,\n): SchemaSyncDiagnostic {\n return {\n code: 'DIVERGENT_MANAGED_COLUMN',\n fileName,\n tableId: table.context.id,\n tableName: table.context.tableName,\n start: property.getStart(sourceFile),\n end: property.getEnd(),\n expected,\n actual: property.getText(sourceFile),\n message:\n `Table \"${table.context.tableName}\" has a divergent managed column \"${jsName}\". ` +\n `Quickback will not rewrite it automatically; replace it with the canonical form.`,\n };\n}\n\nfunction planObjectInsertion(\n sourceFile: TypeScript.SourceFile,\n object: TypeScript.ObjectLiteralExpression,\n entries: string[],\n tableId: string,\n): SchemaSourceEdit[] {\n if (entries.length === 0) return [];\n const source = sourceFile.text;\n const lineEnding = source.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const open = object.getStart(sourceFile);\n const close = object.getEnd() - 1;\n const multiline = source.slice(open, close).includes('\\n');\n const edits: SchemaSourceEdit[] = [];\n const last = object.properties[object.properties.length - 1];\n const hasTrailingComma = last\n ? source.slice(last.getEnd(), close).includes(',')\n : false;\n\n if (!multiline) {\n if (last) {\n const tail = source.slice(last.getEnd(), close);\n const preservesComment = tail.includes('//') || tail.includes('/*');\n edits.push({\n start: last.getEnd(),\n end: close,\n text: preservesComment\n ? `${hasTrailingComma ? '' : ','}${tail}${/\\s$/.test(tail) ? '' : ' '}${entries.join(' ')} `\n : `, ${entries.join(' ')} `,\n tableId,\n reason: 'insert managed columns into single-line table object',\n });\n } else {\n edits.push({\n start: open + 1,\n end: close,\n text: ` ${entries.join(' ')} `,\n tableId,\n reason: 'insert managed columns into empty single-line table object',\n });\n }\n return edits;\n }\n\n if (last && !hasTrailingComma) {\n edits.push({\n start: last.getEnd(),\n end: last.getEnd(),\n text: ',',\n tableId,\n reason: 'terminate the previous table column before managed-column insertion',\n });\n }\n\n const closeLineStart = source.lastIndexOf('\\n', close - 1) + 1;\n const closeIndent = source.slice(closeLineStart, close).match(/^[ \\t]*/)?.[0] ?? '';\n const first = object.properties[0];\n let entryIndent: string;\n if (first) {\n const firstStart = first.getStart(sourceFile);\n const firstLineStart = source.lastIndexOf('\\n', firstStart - 1) + 1;\n entryIndent = source.slice(firstLineStart, firstStart);\n } else {\n entryIndent = closeIndent.includes('\\t') ? `${closeIndent}\\t` : `${closeIndent} `;\n }\n const text = entries.map((entry) => `${entryIndent}${entry}`).join(lineEnding) + lineEnding;\n edits.push({\n start: closeLineStart,\n end: closeLineStart,\n text,\n tableId,\n reason: 'insert canonical managed-column declarations',\n });\n return edits;\n}\n\nfunction addImportRequirement(\n imports: Map<string, ImportRequirement>,\n moduleName: string,\n identifier: string,\n tableId: string,\n): void {\n let requirement = imports.get(moduleName);\n if (!requirement) {\n requirement = { identifiers: new Set(), tableIds: new Set() };\n imports.set(moduleName, requirement);\n }\n requirement.identifiers.add(identifier);\n requirement.tableIds.add(tableId);\n}\n\nfunction drizzleCoreModule(dialect: SchemaDialect): string {\n return dialect === 'postgres' ? 'drizzle-orm/pg-core' : 'drizzle-orm/sqlite-core';\n}\n\nfunction planNamedImport(\n ts: TypeScriptApi,\n sourceFile: TypeScript.SourceFile,\n moduleName: string,\n requirement: ImportRequirement,\n fileName: string,\n edits: SchemaSourceEdit[],\n diagnostics: SchemaSyncDiagnostic[],\n): void {\n const candidates = sourceFile.statements.filter(\n (statement): statement is TypeScript.ImportDeclaration =>\n ts.isImportDeclaration(statement) &&\n ts.isStringLiteralLike(statement.moduleSpecifier) &&\n statement.moduleSpecifier.text === moduleName &&\n !!statement.importClause &&\n !statement.importClause.isTypeOnly &&\n !!statement.importClause.namedBindings &&\n ts.isNamedImports(statement.importClause.namedBindings),\n );\n const present = new Set<string>();\n for (const candidate of candidates) {\n const bindings = candidate.importClause!.namedBindings as TypeScript.NamedImports;\n for (const element of bindings.elements) present.add(element.name.text);\n }\n const missing = [...requirement.identifiers].filter((name) => !present.has(name)).sort();\n if (missing.length === 0) return;\n const target = candidates[0];\n if (!target) {\n diagnostics.push({\n code: 'MISSING_VALUE_IMPORT',\n fileName,\n tableId: requirement.tableIds.size === 1 ? [...requirement.tableIds][0] : undefined,\n expected: `import { ${missing.join(', ')} } from \"${moduleName}\";`,\n message:\n `Managed-column synchronization needs { ${missing.join(', ')} } from ` +\n `\"${moduleName}\", but no plain named value import can be widened. ` +\n `Add the import manually; namespace and type-only imports are not rewritten.`,\n });\n return;\n }\n\n const bindings = target.importClause!.namedBindings as TypeScript.NamedImports;\n const source = sourceFile.text;\n const close = bindings.getEnd() - 1;\n const multiline = source.slice(bindings.getStart(sourceFile), close).includes('\\n');\n const last = bindings.elements[bindings.elements.length - 1];\n if (!multiline) {\n if (last) {\n const tail = source.slice(last.getEnd(), close);\n const preservesComment = tail.includes('//') || tail.includes('/*');\n edits.push({\n start: last.getEnd(),\n end: close,\n text: preservesComment\n ? `${tail.includes(',') ? '' : ','}${tail}${/\\s$/.test(tail) ? '' : ' '}${missing.join(', ')} `\n : `, ${missing.join(', ')} `,\n reason: `add required value imports from ${moduleName}`,\n });\n } else {\n edits.push({\n start: bindings.getStart(sourceFile) + 1,\n end: close,\n text: ` ${missing.join(', ')} `,\n reason: `add required value imports from ${moduleName}`,\n });\n }\n return;\n }\n if (last && !source.slice(last.getEnd(), close).includes(',')) {\n edits.push({\n start: last.getEnd(),\n end: last.getEnd(),\n text: ',',\n reason: `terminate the existing ${moduleName} import before widening it`,\n });\n }\n const lineEnding = source.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const closeLineStart = source.lastIndexOf('\\n', close - 1) + 1;\n const first = bindings.elements[0];\n const indent = first\n ? source.slice(source.lastIndexOf('\\n', first.getStart(sourceFile) - 1) + 1, first.getStart(sourceFile))\n : ' ';\n edits.push({\n start: closeLineStart,\n end: closeLineStart,\n text: missing.map((name) => `${indent}${name},`).join(lineEnding) + lineEnding,\n reason: `add required value imports from ${moduleName}`,\n });\n}\n"],
4
+ "sourcesContent": ["/**\n * Canonical feature-owned managed-column requirements.\n *\n * This module deliberately contains no filesystem, process, network, or\n * user-module access. Callers supply the project facts that determine which\n * requirements apply to each discovered table.\n */\n\nexport const SCHEMA_ENGINE_VERSION = '2026-07-28.1';\n\nexport const SQLITE_EPOCH_SENTINEL = `'1970-01-01T00:00:00.000Z'`;\nexport const SQLITE_ISO_NOW_FN = `() => new Date().toISOString()`;\n\nexport type SchemaDialect = 'postgres' | 'sqlite';\nexport type ManagedColumnDialect = SchemaDialect;\nexport type NamingConvention = 'snake_case' | 'camelCase';\nexport type ManagedRequirementKind = 'audit' | 'soft-delete' | 'id' | 'scope';\n\nexport const AUDIT_JS_NAMES = ['createdAt', 'modifiedAt', 'createdBy', 'modifiedBy'] as const;\nexport const SOFT_DELETE_JS_NAMES = ['deletedAt', 'deletedBy'] as const;\n\nexport type AuditJsName = (typeof AUDIT_JS_NAMES)[number];\nexport type SoftDeleteJsName = (typeof SOFT_DELETE_JS_NAMES)[number];\nexport type AuditManagedJsName = AuditJsName | SoftDeleteJsName;\n\nexport interface ManagedColumnSpec {\n jsName: string;\n snakeName: string;\n kind: 'timestamp' | 'text';\n notNull: boolean;\n /** Compatibility discriminator used by existing compiler consumers. */\n audit: boolean;\n requirement: ManagedRequirementKind;\n}\n\nexport const AUDIT_COLUMN_SPECS: ReadonlyArray<ManagedColumnSpec> = [\n {\n jsName: 'createdAt',\n snakeName: 'created_at',\n kind: 'timestamp',\n notNull: true,\n audit: true,\n requirement: 'audit',\n },\n {\n jsName: 'modifiedAt',\n snakeName: 'modified_at',\n kind: 'timestamp',\n notNull: true,\n audit: true,\n requirement: 'audit',\n },\n {\n jsName: 'createdBy',\n snakeName: 'created_by',\n kind: 'text',\n notNull: false,\n audit: true,\n requirement: 'audit',\n },\n {\n jsName: 'modifiedBy',\n snakeName: 'modified_by',\n kind: 'text',\n notNull: false,\n audit: true,\n requirement: 'audit',\n },\n];\n\nexport const SOFT_DELETE_COLUMN_SPECS: ReadonlyArray<ManagedColumnSpec> = [\n {\n jsName: 'deletedAt',\n snakeName: 'deleted_at',\n kind: 'timestamp',\n notNull: false,\n audit: false,\n requirement: 'soft-delete',\n },\n {\n jsName: 'deletedBy',\n snakeName: 'deleted_by',\n kind: 'text',\n notNull: false,\n audit: false,\n requirement: 'soft-delete',\n },\n];\n\nexport const MANAGED_AUDIT_COLUMN_SPECS: ReadonlyArray<ManagedColumnSpec> = [\n ...AUDIT_COLUMN_SPECS,\n ...SOFT_DELETE_COLUMN_SPECS,\n];\nexport const MANAGED_COLUMN_SPECS = MANAGED_AUDIT_COLUMN_SPECS;\nexport const MANAGED_AUDIT_JS_NAMES: ReadonlySet<string> = new Set([\n ...AUDIT_JS_NAMES,\n ...SOFT_DELETE_JS_NAMES,\n]);\n\nexport interface ManagedGroupRequirement {\n kind: 'audit' | 'soft-delete';\n columns: ReadonlyArray<ManagedColumnSpec>;\n /** Canonical q-DSL spread helper, without the leading `...` or call. */\n qHelper: 'audit' | 'softDelete';\n}\n\nexport interface ManagedPhysicalColumnRequirement {\n kind: 'id' | 'scope';\n jsName: string;\n sqlName: string;\n /** Canonical q initializer, without `<jsName>:`. */\n qExpression: string;\n /** Canonical raw-Drizzle initializer, without `<jsName>:`. */\n rawExpression: string;\n /**\n * Additional exact expressions accepted as canonical. This is useful while\n * source-visible ID strategies are migrated without weakening validation.\n */\n acceptedQExpressions?: ReadonlyArray<string>;\n acceptedRawExpressions?: ReadonlyArray<string>;\n}\n\nexport type ManagedColumnRequirement =\n | ManagedGroupRequirement\n | ManagedPhysicalColumnRequirement;\n\nexport interface IdRequirementOptions {\n dialect: SchemaDialect;\n namingConvention?: NamingConvention;\n qExpression?: string;\n rawExpression?: string;\n acceptedQExpressions?: ReadonlyArray<string>;\n acceptedRawExpressions?: ReadonlyArray<string>;\n}\n\nexport interface ScopeRequirementOptions {\n dialect: SchemaDialect;\n kind: string;\n jsName?: string;\n sqlName?: string;\n namingConvention?: NamingConvention;\n qExpression?: string;\n rawExpression?: string;\n acceptedQExpressions?: ReadonlyArray<string>;\n acceptedRawExpressions?: ReadonlyArray<string>;\n}\n\nexport function managedSqlName(\n spec: Pick<ManagedColumnSpec, 'jsName' | 'snakeName'>,\n convention: NamingConvention,\n): string {\n return convention === 'snake_case' ? spec.snakeName : spec.jsName;\n}\n\nexport function managedColumnExpr(\n spec: ManagedColumnSpec,\n dialect: SchemaDialect,\n sqlName: string,\n): string {\n if (spec.kind === 'text' || (spec.jsName === 'deletedAt' && dialect === 'sqlite')) {\n return dialect === 'postgres' && spec.kind === 'timestamp'\n ? `timestamp(\"${sqlName}\", { withTimezone: true })`\n : `text(\"${sqlName}\")`;\n }\n if (spec.jsName === 'deletedAt') {\n return `timestamp(\"${sqlName}\", { withTimezone: true })`;\n }\n const pgUpdate = spec.jsName === 'modifiedAt' ? `.$onUpdate(() => new Date())` : '';\n const sqliteUpdate =\n spec.jsName === 'modifiedAt' ? `.$onUpdate(${SQLITE_ISO_NOW_FN})` : '';\n return dialect === 'postgres'\n ? `timestamp(\"${sqlName}\", { withTimezone: true }).notNull().defaultNow()${pgUpdate}`\n : `text(\"${sqlName}\").notNull().default(${SQLITE_EPOCH_SENTINEL}).$defaultFn(${SQLITE_ISO_NOW_FN})${sqliteUpdate}`;\n}\n\nexport function managedColumnLine(\n spec: ManagedColumnSpec,\n dialect: SchemaDialect,\n convention: NamingConvention,\n): string {\n return `${spec.jsName}: ${managedColumnExpr(\n spec,\n dialect,\n managedSqlName(spec, convention),\n )},`;\n}\n\nexport function auditRequirement(): ManagedGroupRequirement {\n return {\n kind: 'audit',\n columns: AUDIT_COLUMN_SPECS,\n qHelper: 'audit',\n };\n}\n\nexport function softDeleteRequirement(): ManagedGroupRequirement {\n return {\n kind: 'soft-delete',\n columns: SOFT_DELETE_COLUMN_SPECS,\n qHelper: 'softDelete',\n };\n}\n\nexport function idRequirement(options: IdRequirementOptions): ManagedPhysicalColumnRequirement {\n const sqlName = options.namingConvention === 'camelCase' ? 'id' : 'id';\n return {\n kind: 'id',\n jsName: 'id',\n sqlName,\n qExpression: options.qExpression ?? 'q.id()',\n rawExpression: options.rawExpression ?? `text(\"${sqlName}\").primaryKey()`,\n acceptedQExpressions: options.acceptedQExpressions,\n acceptedRawExpressions: options.acceptedRawExpressions,\n };\n}\n\nexport function scopeRequirement(\n options: ScopeRequirementOptions,\n): ManagedPhysicalColumnRequirement {\n const jsName = options.jsName ?? `${options.kind}Id`;\n const convention = options.namingConvention ?? 'snake_case';\n const snakeName = jsName.replace(/[A-Z]/g, (character) => `_${character.toLowerCase()}`);\n const sqlName = options.sqlName ?? (convention === 'snake_case' ? snakeName : jsName);\n return {\n kind: 'scope',\n jsName,\n sqlName,\n qExpression: options.qExpression ?? `q.scope(\"${options.kind}\")`,\n rawExpression: options.rawExpression ?? `text(\"${sqlName}\").notNull()`,\n acceptedQExpressions: options.acceptedQExpressions,\n acceptedRawExpressions: options.acceptedRawExpressions,\n };\n}\n", "/**\n * Single source of truth for database provider \u2192 SQL dialect resolution.\n *\n * Both the compiler (`apps/compiler/src/transforms/dialect.ts`) and the CLI\n * (`quickback schema check|sync`) resolve dialects through this module. Keeping\n * one definition here is what prevents the class of bug where the two sides\n * disagree and `schema sync` writes wrong-dialect declarations into authored\n * source (issue #213).\n */\n\nexport type ProviderDialect = 'sqlite' | 'postgres' | 'mysql';\n\nexport const SQLITE_PROVIDERS = [\n 'cloudflare-d1',\n 'better-sqlite3',\n 'bun-sqlite',\n 'libsql',\n 'turso',\n] as const;\n\nexport const POSTGRES_PROVIDERS = [\n 'supabase',\n 'neon',\n // `planetscale` (below) stays MySQL: PlanetScale ships both engines, and\n // the Postgres one is a distinct provider name.\n 'planetscale-postgres',\n 'vercel-postgres',\n 'postgres',\n 'postgresql',\n] as const;\n\nexport const MYSQL_PROVIDERS = ['planetscale', 'mysql', 'mysql2'] as const;\n\n/**\n * Resolve a database provider name to its SQL dialect family.\n *\n * Returns `undefined` for unknown or missing provider names so each caller\n * chooses its own fallback explicitly (the compiler defaults to sqlite; the\n * CLI does the same but refuses dialects it cannot emit).\n */\nexport function resolveProviderDialect(\n providerName: string | undefined,\n): ProviderDialect | undefined {\n if (!providerName) return undefined;\n if ((SQLITE_PROVIDERS as readonly string[]).includes(providerName)) return 'sqlite';\n if ((POSTGRES_PROVIDERS as readonly string[]).includes(providerName)) return 'postgres';\n if ((MYSQL_PROVIDERS as readonly string[]).includes(providerName)) return 'mysql';\n return undefined;\n}\n", "import type * as TypeScript from '@typescript/typescript6';\nimport {\n managedColumnExpr,\n managedColumnLine,\n managedSqlName,\n type ManagedColumnRequirement,\n type ManagedGroupRequirement,\n type ManagedPhysicalColumnRequirement,\n type NamingConvention,\n type SchemaDialect,\n} from './managed-columns.js';\n\nexport type TypeScriptApi = Omit<typeof TypeScript, 'default'>;\nexport type SchemaTableStyle = 'q-feature' | 'q-table' | 'raw-drizzle';\nexport type StaticDeleteMode = 'hard' | 'soft' | 'default' | 'dynamic';\n\nexport interface SchemaTableContext {\n /** Stable within one source file, even when SQL table names repeat. */\n id: string;\n fileName: string;\n tableName: string;\n variableName?: string;\n style: SchemaTableStyle;\n dialect: SchemaDialect;\n namingConvention: NamingConvention;\n hasResourceConfig: boolean;\n deleteMode: StaticDeleteMode;\n /**\n * `crud.batchDelete.mode`, inheriting `deleteMode` when unset \u2014 the same\n * resolution the compiler applies in `resolveDeleteModes`. Soft-delete\n * columns are required unless BOTH paths are hard, so a resolver that reads\n * only `deleteMode` under-reports the requirement for\n * `delete: { mode: 'hard' }, batchDelete: { mode: 'soft' }`.\n */\n batchDeleteMode: StaticDeleteMode;\n sourceStart: number;\n sourceEnd: number;\n}\n\nexport type ManagedRequirementResolver = (\n table: SchemaTableContext,\n) => ReadonlyArray<ManagedColumnRequirement>;\n\nexport interface SchemaSourceEdit {\n start: number;\n end: number;\n text: string;\n tableId?: string;\n reason: string;\n}\n\nexport type SchemaSyncDiagnosticCode =\n | 'DIVERGENT_MANAGED_COLUMN'\n | 'DUPLICATE_MANAGED_REPRESENTATION'\n | 'DUPLICATE_TABLE_COLUMN'\n | 'MISSING_VALUE_IMPORT'\n | 'SOURCE_PARSE_ERROR'\n | 'UNSUPPORTED_DYNAMIC_DELETE_MODE'\n | 'REQUIREMENT_RESOLUTION_FAILED'\n | 'INVALID_REQUIREMENT'\n | 'OVERLAPPING_SOURCE_EDITS';\n\nexport interface SchemaSyncDiagnostic {\n code: SchemaSyncDiagnosticCode;\n message: string;\n fileName: string;\n tableId?: string;\n tableName?: string;\n start?: number;\n end?: number;\n expected?: string;\n actual?: string;\n}\n\nexport interface PlanSchemaSourceOptions {\n fileName: string;\n source: string;\n typescript: TypeScriptApi;\n dialect: SchemaDialect;\n namingConvention?: NamingConvention;\n resolveRequirements: ManagedRequirementResolver;\n}\n\nexport interface SchemaSourcePlan {\n fileName: string;\n source: string;\n tables: ReadonlyArray<SchemaTableContext>;\n edits: ReadonlyArray<SchemaSourceEdit>;\n diagnostics: ReadonlyArray<SchemaSyncDiagnostic>;\n updatedSource: string;\n changed: boolean;\n canApply: boolean;\n}\n\ninterface DiscoveredTable {\n context: SchemaTableContext;\n columns: TypeScript.ObjectLiteralExpression;\n}\n\ninterface PlannedEntry {\n source: string;\n order: number;\n}\n\ninterface ImportRequirement {\n identifiers: Set<string>;\n tableIds: Set<string>;\n}\n\nconst MANAGED_MARKER =\n '// \u2500\u2500 quickback:audit (compiler-managed \u2014 edits are validated, not merged) \u2500\u2500';\n\n/**\n * Inspect every table in one source file and calculate formatting-preserving,\n * additive-only source edits. No edit is applied here.\n */\nexport function planSchemaSource(options: PlanSchemaSourceOptions): SchemaSourcePlan {\n const ts = options.typescript;\n const namingConvention = options.namingConvention ?? 'snake_case';\n const sourceFile = ts.createSourceFile(\n options.fileName,\n options.source,\n ts.ScriptTarget.Latest,\n true,\n options.fileName.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,\n );\n const diagnostics: SchemaSyncDiagnostic[] = [];\n const parseDiagnostics = (\n sourceFile as TypeScript.SourceFile & {\n parseDiagnostics?: ReadonlyArray<TypeScript.Diagnostic>;\n }\n ).parseDiagnostics;\n if (parseDiagnostics && parseDiagnostics.length > 0) {\n for (const diagnostic of parseDiagnostics) {\n diagnostics.push({\n code: 'SOURCE_PARSE_ERROR',\n fileName: options.fileName,\n start: diagnostic.start,\n end:\n diagnostic.start !== undefined && diagnostic.length !== undefined\n ? diagnostic.start + diagnostic.length\n : undefined,\n message:\n `TypeScript could not parse this schema source: ` +\n ts.flattenDiagnosticMessageText(diagnostic.messageText, '\\n'),\n });\n }\n return {\n fileName: options.fileName,\n source: options.source,\n tables: [],\n edits: [],\n diagnostics,\n updatedSource: options.source,\n changed: false,\n canApply: false,\n };\n }\n const discovered = discoverTables(ts, sourceFile, options.dialect, namingConvention);\n const edits: SchemaSourceEdit[] = [];\n const imports = new Map<string, ImportRequirement>();\n\n for (const table of discovered) {\n let requirements: ReadonlyArray<ManagedColumnRequirement>;\n try {\n requirements = options.resolveRequirements(table.context);\n } catch (error) {\n diagnostics.push({\n code: 'REQUIREMENT_RESOLUTION_FAILED',\n fileName: options.fileName,\n tableId: table.context.id,\n tableName: table.context.tableName,\n start: table.context.sourceStart,\n end: table.context.sourceEnd,\n message:\n `Could not determine managed-column requirements for table ` +\n `\"${table.context.tableName}\": ${error instanceof Error ? error.message : String(error)}`,\n });\n continue;\n }\n if (!Array.isArray(requirements)) {\n diagnostics.push({\n code: 'INVALID_REQUIREMENT',\n fileName: options.fileName,\n tableId: table.context.id,\n tableName: table.context.tableName,\n message:\n `The managed-column resolver for table \"${table.context.tableName}\" did not return an array.`,\n });\n continue;\n }\n\n const entries: PlannedEntry[] = [];\n const seenKinds = new Set<string>();\n let needsManagedMarker = false;\n\n for (const requirement of requirements) {\n const key =\n requirement.kind === 'scope'\n ? `${requirement.kind}:${requirement.jsName}`\n : requirement.kind;\n if (seenKinds.has(key)) {\n diagnostics.push({\n code: 'INVALID_REQUIREMENT',\n fileName: options.fileName,\n tableId: table.context.id,\n tableName: table.context.tableName,\n message: `Requirement \"${key}\" was supplied more than once for table \"${table.context.tableName}\".`,\n });\n continue;\n }\n seenKinds.add(key);\n\n if (isManagedGroupRequirement(requirement)) {\n const result = planManagedGroup(\n ts,\n sourceFile,\n table,\n requirement,\n options.fileName,\n diagnostics,\n );\n entries.push(...result.entries);\n needsManagedMarker ||= result.needsMarker;\n for (const identifier of result.requiredImports) {\n addImportRequirement(\n imports,\n drizzleCoreModule(table.context.dialect),\n identifier,\n table.context.id,\n );\n }\n if (result.needsQImport) {\n addImportRequirement(imports, '@quickback/compiler', 'q', table.context.id);\n }\n continue;\n }\n\n const result = planPhysicalColumn(\n ts,\n sourceFile,\n table,\n requirement,\n options.fileName,\n diagnostics,\n );\n entries.push(...result.entries);\n for (const identifier of result.requiredImports) {\n addImportRequirement(\n imports,\n drizzleCoreModule(table.context.dialect),\n identifier,\n table.context.id,\n );\n }\n if (result.needsQImport) {\n addImportRequirement(imports, '@quickback/compiler', 'q', table.context.id);\n }\n }\n\n if (entries.length === 0) continue;\n entries.sort((a, b) => a.order - b.order);\n if (\n table.context.style === 'raw-drizzle' &&\n needsManagedMarker &&\n !options.source\n .slice(table.columns.getStart(sourceFile), table.columns.getEnd())\n .includes('quickback:audit')\n ) {\n const firstManagedIndex = entries.findIndex((entry) => entry.order >= 20);\n entries.splice(firstManagedIndex < 0 ? entries.length : firstManagedIndex, 0, {\n source: MANAGED_MARKER,\n order: 19,\n });\n }\n edits.push(\n ...planObjectInsertion(\n sourceFile,\n table.columns,\n entries.map((entry) => entry.source),\n table.context.id,\n ),\n );\n }\n\n for (const [moduleName, requirement] of imports) {\n planNamedImport(\n ts,\n sourceFile,\n moduleName,\n requirement,\n options.fileName,\n edits,\n diagnostics,\n );\n }\n\n let updatedSource = options.source;\n try {\n updatedSource = applySchemaSourceEdits(options.source, edits);\n } catch (error) {\n diagnostics.push({\n code: 'OVERLAPPING_SOURCE_EDITS',\n fileName: options.fileName,\n message: error instanceof Error ? error.message : String(error),\n });\n }\n\n return {\n fileName: options.fileName,\n source: options.source,\n tables: discovered.map((table) => table.context),\n edits,\n diagnostics,\n updatedSource,\n changed: updatedSource !== options.source,\n canApply: diagnostics.length === 0,\n };\n}\n\nfunction isManagedGroupRequirement(\n requirement: ManagedColumnRequirement,\n): requirement is ManagedGroupRequirement {\n return requirement.kind === 'audit' || requirement.kind === 'soft-delete';\n}\n\nexport function applySchemaSourceEdits(\n source: string,\n edits: ReadonlyArray<SchemaSourceEdit>,\n): string {\n const ordered = [...edits].sort((left, right) => {\n if (left.start !== right.start) return right.start - left.start;\n return right.end - left.end;\n });\n let previousStart = source.length + 1;\n let output = source;\n for (const edit of ordered) {\n if (\n edit.start < 0 ||\n edit.end < edit.start ||\n edit.end > source.length ||\n edit.end > previousStart\n ) {\n throw new Error(\n `Schema source edits overlap or address an invalid span: ${edit.start}..${edit.end} (${edit.reason}).`,\n );\n }\n output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);\n previousStart = edit.start;\n }\n return output;\n}\n\nfunction discoverTables(\n ts: TypeScriptApi,\n sourceFile: TypeScript.SourceFile,\n defaultDialect: SchemaDialect,\n namingConvention: NamingConvention,\n): DiscoveredTable[] {\n const resourceByVariable = new Map<string, TypeScript.Expression>();\n\n const collectResources = (node: TypeScript.Node): void => {\n if (ts.isCallExpression(node) && isNamedCall(ts, node.expression, 'defineTable')) {\n const tableArg = node.arguments[0];\n const configArg = node.arguments[1];\n if (tableArg && ts.isIdentifier(tableArg) && configArg) {\n resourceByVariable.set(tableArg.text, configArg);\n }\n }\n ts.forEachChild(node, collectResources);\n };\n collectResources(sourceFile);\n\n const tables: DiscoveredTable[] = [];\n const occurrenceByName = new Map<string, number>();\n const visit = (node: TypeScript.Node): void => {\n if (!ts.isCallExpression(node)) {\n ts.forEachChild(node, visit);\n return;\n }\n\n const callKind = tableCallKind(ts, node.expression);\n if (!callKind) {\n ts.forEachChild(node, visit);\n return;\n }\n const nameArg = node.arguments[0];\n const bodyArg = node.arguments[1];\n if (!nameArg || !ts.isStringLiteralLike(nameArg) || !bodyArg) {\n ts.forEachChild(node, visit);\n return;\n }\n\n const variableName = enclosingVariableName(ts, node);\n let columns: TypeScript.ObjectLiteralExpression | undefined;\n let resource: TypeScript.Expression | undefined;\n let style: SchemaTableStyle;\n let dialect = defaultDialect;\n\n if (callKind === 'feature') {\n if (!ts.isObjectLiteralExpression(bodyArg)) {\n ts.forEachChild(node, visit);\n return;\n }\n columns = objectPropertyObject(ts, bodyArg, 'columns');\n resource = bodyArg;\n style = 'q-feature';\n } else if (callKind === 'q-table') {\n if (!ts.isObjectLiteralExpression(bodyArg)) {\n ts.forEachChild(node, visit);\n return;\n }\n columns = bodyArg;\n resource = variableName ? resourceByVariable.get(variableName) : undefined;\n style = 'q-table';\n } else {\n if (!ts.isObjectLiteralExpression(bodyArg)) {\n ts.forEachChild(node, visit);\n return;\n }\n columns = bodyArg;\n resource = variableName ? resourceByVariable.get(variableName) : undefined;\n style = 'raw-drizzle';\n dialect = callKind === 'pg-table' ? 'postgres' : 'sqlite';\n }\n\n if (!columns) {\n ts.forEachChild(node, visit);\n return;\n }\n const tableName = nameArg.text;\n const occurrence = (occurrenceByName.get(tableName) ?? 0) + 1;\n occurrenceByName.set(tableName, occurrence);\n tables.push({\n context: {\n id: `${tableName}@${occurrence}`,\n fileName: sourceFile.fileName,\n tableName,\n variableName,\n style,\n dialect,\n namingConvention,\n hasResourceConfig: resource !== undefined,\n deleteMode: resource ? readDeleteMode(ts, resource) : 'default',\n batchDeleteMode: resource ? readBatchDeleteMode(ts, resource) : 'default',\n sourceStart: node.getStart(sourceFile),\n sourceEnd: node.getEnd(),\n },\n columns,\n });\n // Table calls cannot contain another table definition in their columns.\n };\n visit(sourceFile);\n return tables.sort((left, right) => left.context.sourceStart - right.context.sourceStart);\n}\n\ntype TableCallKind = 'feature' | 'q-table' | 'pg-table' | 'sqlite-table';\n\nfunction tableCallKind(\n ts: TypeScriptApi,\n expression: TypeScript.LeftHandSideExpression,\n): TableCallKind | undefined {\n if (ts.isIdentifier(expression)) {\n if (expression.text === 'feature') return 'feature';\n if (expression.text === 'pgTable') return 'pg-table';\n if (expression.text === 'sqliteTable') return 'sqlite-table';\n return undefined;\n }\n if (!ts.isPropertyAccessExpression(expression)) return undefined;\n if (expression.name.text === 'pgTable') return 'pg-table';\n if (expression.name.text === 'sqliteTable') return 'sqlite-table';\n if (\n ts.isIdentifier(expression.expression) &&\n (expression.expression.text === 'q' || expression.expression.text === 'qb')\n ) {\n if (expression.name.text === 'table') return 'q-table';\n if (expression.name.text === 'feature') return 'feature';\n }\n return undefined;\n}\n\nfunction enclosingVariableName(\n ts: TypeScriptApi,\n call: TypeScript.CallExpression,\n): string | undefined {\n const parent = call.parent;\n return ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name)\n ? parent.name.text\n : undefined;\n}\n\nfunction isNamedCall(\n ts: TypeScriptApi,\n expression: TypeScript.LeftHandSideExpression,\n name: string,\n): boolean {\n return (\n (ts.isIdentifier(expression) && expression.text === name) ||\n (ts.isPropertyAccessExpression(expression) && expression.name.text === name)\n );\n}\n\nfunction objectPropertyObject(\n ts: TypeScriptApi,\n object: TypeScript.ObjectLiteralExpression,\n name: string,\n): TypeScript.ObjectLiteralExpression | undefined {\n const property = object.properties.find(\n (candidate): candidate is TypeScript.PropertyAssignment =>\n ts.isPropertyAssignment(candidate) && propertyName(ts, candidate.name) === name,\n );\n return property && ts.isObjectLiteralExpression(property.initializer)\n ? property.initializer\n : undefined;\n}\n\nfunction readDeleteMode(\n ts: TypeScriptApi,\n expression: TypeScript.Expression,\n): StaticDeleteMode {\n if (!ts.isObjectLiteralExpression(expression)) return 'dynamic';\n let deleteExpression = propertyInitializer(ts, expression, 'delete');\n if (!deleteExpression) {\n const crud = propertyInitializer(ts, expression, 'crud');\n if (crud && !ts.isObjectLiteralExpression(crud)) return 'dynamic';\n if (crud && ts.isObjectLiteralExpression(crud)) {\n deleteExpression = propertyInitializer(ts, crud, 'delete');\n }\n }\n if (!deleteExpression) return 'default';\n if (!ts.isObjectLiteralExpression(deleteExpression)) return 'dynamic';\n const mode = propertyInitializer(ts, deleteExpression, 'mode');\n if (!mode) return 'default';\n if (!ts.isStringLiteralLike(mode)) return 'dynamic';\n if (mode.text === 'hard') return 'hard';\n if (mode.text === 'soft') return 'soft';\n return 'dynamic';\n}\n\n/**\n * `batchDelete.mode`, resolved with the inheritance the compiler applies in\n * `resolveDeleteModes`: an absent or `false` batchDelete inherits the delete\n * mode, and an explicit batchDelete without its own `mode` inherits it too.\n *\n * This exists because soft-delete columns are required unless EVERY delete\n * path is hard. Reading `delete.mode` alone silently under-reports the\n * requirement for `delete: { mode: 'hard' }, batchDelete: { mode: 'soft' }`,\n * which the compiler then rejects.\n */\nfunction readBatchDeleteMode(\n ts: TypeScriptApi,\n expression: TypeScript.Expression,\n): StaticDeleteMode {\n if (!ts.isObjectLiteralExpression(expression)) return 'dynamic';\n const inherited = readDeleteMode(ts, expression);\n\n let batchExpression = propertyInitializer(ts, expression, 'batchDelete');\n if (!batchExpression) {\n const crud = propertyInitializer(ts, expression, 'crud');\n if (crud && !ts.isObjectLiteralExpression(crud)) return 'dynamic';\n if (crud && ts.isObjectLiteralExpression(crud)) {\n batchExpression = propertyInitializer(ts, crud, 'batchDelete');\n }\n }\n // Absent, or disabled outright \u2014 the delete mode governs.\n if (!batchExpression) return inherited;\n if (batchExpression.kind === ts.SyntaxKind.FalseKeyword) return inherited;\n if (!ts.isObjectLiteralExpression(batchExpression)) return 'dynamic';\n\n const mode = propertyInitializer(ts, batchExpression, 'mode');\n if (!mode) return inherited;\n if (!ts.isStringLiteralLike(mode)) return 'dynamic';\n if (mode.text === 'hard') return 'hard';\n if (mode.text === 'soft') return 'soft';\n return 'dynamic';\n}\n\nfunction propertyInitializer(\n ts: TypeScriptApi,\n object: TypeScript.ObjectLiteralExpression,\n name: string,\n): TypeScript.Expression | undefined {\n for (const property of object.properties) {\n if (ts.isPropertyAssignment(property) && propertyName(ts, property.name) === name) {\n return property.initializer;\n }\n if (ts.isShorthandPropertyAssignment(property) && property.name.text === name) {\n return property.name;\n }\n }\n return undefined;\n}\n\nfunction propertyName(\n ts: TypeScriptApi,\n name: TypeScript.PropertyName,\n): string | undefined {\n if (ts.isIdentifier(name) || ts.isPrivateIdentifier(name)) return name.text;\n if (ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) return name.text;\n return undefined;\n}\n\nfunction planManagedGroup(\n ts: TypeScriptApi,\n sourceFile: TypeScript.SourceFile,\n table: DiscoveredTable,\n requirement: ManagedGroupRequirement,\n fileName: string,\n diagnostics: SchemaSyncDiagnostic[],\n): {\n entries: PlannedEntry[];\n requiredImports: Set<string>;\n needsQImport: boolean;\n needsMarker: boolean;\n} {\n if (table.context.style !== 'raw-drizzle') {\n const helperSpread = findQHelperSpread(ts, table.columns, requirement.qHelper);\n const explicit = table.columns.properties.filter((property) => {\n if (!ts.isPropertyAssignment(property)) return false;\n const name = propertyName(ts, property.name);\n return requirement.columns.some((column) => column.jsName === name);\n });\n if (helperSpread && explicit.length > 0) {\n diagnostics.push({\n code: 'DUPLICATE_MANAGED_REPRESENTATION',\n fileName,\n tableId: table.context.id,\n tableName: table.context.tableName,\n start: explicit[0]!.getStart(sourceFile),\n end: explicit[explicit.length - 1]!.getEnd(),\n expected: `...q.${requirement.qHelper}(),`,\n actual: explicit.map((property) => property.getText(sourceFile)).join('\\n'),\n message:\n `Table \"${table.context.tableName}\" declares both ...q.${requirement.qHelper}() ` +\n `and explicit ${requirement.kind} columns. Remove the explicit duplicates manually.`,\n });\n return {\n entries: [],\n requiredImports: new Set(),\n needsQImport: false,\n needsMarker: false,\n };\n }\n if (helperSpread) {\n return {\n entries: [],\n requiredImports: new Set(),\n needsQImport: false,\n needsMarker: false,\n };\n }\n if (explicit.length > 0) {\n diagnostics.push({\n code: 'DIVERGENT_MANAGED_COLUMN',\n fileName,\n tableId: table.context.id,\n tableName: table.context.tableName,\n start: explicit[0]!.getStart(sourceFile),\n end: explicit[explicit.length - 1]!.getEnd(),\n expected: `...q.${requirement.qHelper}(),`,\n actual: explicit.map((property) => property.getText(sourceFile)).join('\\n'),\n message:\n `Table \"${table.context.tableName}\" uses explicit q-DSL ${requirement.kind} ` +\n `columns. Quickback cannot prove that hand-written q chains match the managed ` +\n `contract; replace them manually with ...q.${requirement.qHelper}().`,\n });\n return {\n entries: [],\n requiredImports: new Set(),\n needsQImport: false,\n needsMarker: false,\n };\n }\n return {\n entries: [{ source: `...q.${requirement.qHelper}(),`, order: groupOrder(requirement.kind) }],\n requiredImports: new Set(),\n needsQImport: true,\n needsMarker: false,\n };\n }\n\n const entries: PlannedEntry[] = [];\n const requiredImports = new Set<string>();\n for (const column of requirement.columns) {\n const sqlName = managedSqlName(column, table.context.namingConvention);\n const expectedExpression = managedColumnExpr(column, table.context.dialect, sqlName);\n const expectedLine = managedColumnLine(\n column,\n table.context.dialect,\n table.context.namingConvention,\n );\n const matches = matchingRawProperties(ts, table.columns, column.jsName, sqlName);\n if (matches.length > 1) {\n diagnostics.push(duplicateColumnDiagnostic(fileName, sourceFile, table, column.jsName, matches));\n continue;\n }\n const existing = matches[0];\n if (!existing) {\n entries.push({ source: expectedLine, order: groupOrder(requirement.kind) });\n for (const identifier of calledBuilderIdentifiers(expectedExpression)) {\n requiredImports.add(identifier);\n }\n continue;\n }\n if (\n propertyName(ts, existing.name) !== column.jsName ||\n !expressionMatches(sourceFile, existing.initializer, [expectedExpression])\n ) {\n diagnostics.push(\n divergentColumnDiagnostic(\n fileName,\n sourceFile,\n table,\n existing,\n expectedLine,\n column.jsName,\n ),\n );\n }\n }\n return {\n entries,\n requiredImports,\n needsQImport: false,\n needsMarker: entries.length > 0,\n };\n}\n\nfunction planPhysicalColumn(\n ts: TypeScriptApi,\n sourceFile: TypeScript.SourceFile,\n table: DiscoveredTable,\n requirement: ManagedPhysicalColumnRequirement,\n fileName: string,\n diagnostics: SchemaSyncDiagnostic[],\n): {\n entries: PlannedEntry[];\n requiredImports: Set<string>;\n needsQImport: boolean;\n} {\n const raw = table.context.style === 'raw-drizzle';\n const matches = raw\n ? matchingRawProperties(ts, table.columns, requirement.jsName, requirement.sqlName)\n : matchingQProperties(ts, table.columns, requirement.jsName);\n if (matches.length > 1) {\n diagnostics.push(\n duplicateColumnDiagnostic(fileName, sourceFile, table, requirement.jsName, matches),\n );\n return { entries: [], requiredImports: new Set(), needsQImport: false };\n }\n\n const expression = raw ? requirement.rawExpression : requirement.qExpression;\n const accepted = raw\n ? [requirement.rawExpression, ...(requirement.acceptedRawExpressions ?? [])]\n : [requirement.qExpression, ...(requirement.acceptedQExpressions ?? [])];\n const expected = `${requirement.jsName}: ${expression},`;\n const existing = matches[0];\n if (existing) {\n if (\n propertyName(ts, existing.name) !== requirement.jsName ||\n !expressionMatches(sourceFile, existing.initializer, accepted)\n ) {\n diagnostics.push(\n divergentColumnDiagnostic(\n fileName,\n sourceFile,\n table,\n existing,\n expected,\n requirement.jsName,\n ),\n );\n }\n return { entries: [], requiredImports: new Set(), needsQImport: false };\n }\n\n return {\n entries: [{ source: expected, order: requirement.kind === 'id' ? 0 : 10 }],\n requiredImports: raw\n ? new Set(calledBuilderIdentifiers(requirement.rawExpression))\n : new Set(),\n needsQImport: !raw,\n };\n}\n\nfunction groupOrder(kind: 'audit' | 'soft-delete'): number {\n return kind === 'audit' ? 20 : 30;\n}\n\nfunction findQHelperSpread(\n ts: TypeScriptApi,\n object: TypeScript.ObjectLiteralExpression,\n helper: string,\n): TypeScript.SpreadAssignment | undefined {\n return object.properties.find((property): property is TypeScript.SpreadAssignment => {\n if (!ts.isSpreadAssignment(property) || !ts.isCallExpression(property.expression)) {\n return false;\n }\n const callee = property.expression.expression;\n return (\n ts.isPropertyAccessExpression(callee) &&\n ts.isIdentifier(callee.expression) &&\n callee.expression.text === 'q' &&\n callee.name.text === helper &&\n property.expression.arguments.length === 0\n );\n });\n}\n\nfunction matchingQProperties(\n ts: TypeScriptApi,\n object: TypeScript.ObjectLiteralExpression,\n jsName: string,\n): TypeScript.PropertyAssignment[] {\n return object.properties.filter(\n (property): property is TypeScript.PropertyAssignment =>\n ts.isPropertyAssignment(property) && propertyName(ts, property.name) === jsName,\n );\n}\n\nfunction matchingRawProperties(\n ts: TypeScriptApi,\n object: TypeScript.ObjectLiteralExpression,\n jsName: string,\n sqlName: string,\n): TypeScript.PropertyAssignment[] {\n return object.properties.filter((property): property is TypeScript.PropertyAssignment => {\n if (!ts.isPropertyAssignment(property)) return false;\n if (propertyName(ts, property.name) === jsName) return true;\n return firstStringArgument(ts, property.initializer) === sqlName;\n });\n}\n\nfunction firstStringArgument(\n ts: TypeScriptApi,\n expression: TypeScript.Expression,\n): string | undefined {\n let current = expression;\n while (ts.isCallExpression(current)) {\n const first = current.arguments[0];\n if (first && ts.isStringLiteralLike(first)) return first.text;\n const callee = current.expression;\n if (!ts.isPropertyAccessExpression(callee)) break;\n current = callee.expression;\n }\n return undefined;\n}\n\nfunction expressionMatches(\n sourceFile: TypeScript.SourceFile,\n expression: TypeScript.Expression,\n accepted: ReadonlyArray<string>,\n): boolean {\n const actual = normalizeExpression(expression.getText(sourceFile));\n return accepted.some((candidate) => normalizeExpression(candidate) === actual);\n}\n\nfunction normalizeExpression(source: string): string {\n return source\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n .replace(/\\/\\/[^\\r\\n]*/g, '')\n .replace(/'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)'/g, (_match, value: string) => `\"${value}\"`)\n .replace(/\\s+/g, '');\n}\n\nfunction calledBuilderIdentifiers(expression: string): string[] {\n const identifiers = new Set<string>();\n for (const match of expression.matchAll(/(?:^|[\\s:,{(])([A-Za-z_$][\\w$]*)\\s*\\(/g)) {\n const identifier = match[1]!;\n if (identifier !== 'Date') identifiers.add(identifier);\n }\n return [...identifiers].sort();\n}\n\nfunction duplicateColumnDiagnostic(\n fileName: string,\n sourceFile: TypeScript.SourceFile,\n table: DiscoveredTable,\n jsName: string,\n properties: TypeScript.PropertyAssignment[],\n): SchemaSyncDiagnostic {\n return {\n code: 'DUPLICATE_TABLE_COLUMN',\n fileName,\n tableId: table.context.id,\n tableName: table.context.tableName,\n start: properties[0]!.getStart(sourceFile),\n end: properties[properties.length - 1]!.getEnd(),\n actual: properties.map((property) => property.getText(sourceFile)).join('\\n'),\n message:\n `Table \"${table.context.tableName}\" declares managed column \"${jsName}\" more than once. ` +\n `Resolve the duplicate manually before syncing.`,\n };\n}\n\nfunction divergentColumnDiagnostic(\n fileName: string,\n sourceFile: TypeScript.SourceFile,\n table: DiscoveredTable,\n property: TypeScript.PropertyAssignment,\n expected: string,\n jsName: string,\n): SchemaSyncDiagnostic {\n return {\n code: 'DIVERGENT_MANAGED_COLUMN',\n fileName,\n tableId: table.context.id,\n tableName: table.context.tableName,\n start: property.getStart(sourceFile),\n end: property.getEnd(),\n expected,\n actual: property.getText(sourceFile),\n message:\n `Table \"${table.context.tableName}\" has a divergent managed column \"${jsName}\". ` +\n `Quickback will not rewrite it automatically; replace it with the canonical form.`,\n };\n}\n\nfunction planObjectInsertion(\n sourceFile: TypeScript.SourceFile,\n object: TypeScript.ObjectLiteralExpression,\n entries: string[],\n tableId: string,\n): SchemaSourceEdit[] {\n if (entries.length === 0) return [];\n const source = sourceFile.text;\n const lineEnding = source.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const open = object.getStart(sourceFile);\n const close = object.getEnd() - 1;\n const multiline = source.slice(open, close).includes('\\n');\n const edits: SchemaSourceEdit[] = [];\n const last = object.properties[object.properties.length - 1];\n const hasTrailingComma = last\n ? source.slice(last.getEnd(), close).includes(',')\n : false;\n\n if (!multiline) {\n if (last) {\n const tail = source.slice(last.getEnd(), close);\n const preservesComment = tail.includes('//') || tail.includes('/*');\n edits.push({\n start: last.getEnd(),\n end: close,\n text: preservesComment\n ? `${hasTrailingComma ? '' : ','}${tail}${/\\s$/.test(tail) ? '' : ' '}${entries.join(' ')} `\n : `, ${entries.join(' ')} `,\n tableId,\n reason: 'insert managed columns into single-line table object',\n });\n } else {\n edits.push({\n start: open + 1,\n end: close,\n text: ` ${entries.join(' ')} `,\n tableId,\n reason: 'insert managed columns into empty single-line table object',\n });\n }\n return edits;\n }\n\n if (last && !hasTrailingComma) {\n edits.push({\n start: last.getEnd(),\n end: last.getEnd(),\n text: ',',\n tableId,\n reason: 'terminate the previous table column before managed-column insertion',\n });\n }\n\n const closeLineStart = source.lastIndexOf('\\n', close - 1) + 1;\n const closeIndent = source.slice(closeLineStart, close).match(/^[ \\t]*/)?.[0] ?? '';\n const first = object.properties[0];\n let entryIndent: string;\n if (first) {\n const firstStart = first.getStart(sourceFile);\n const firstLineStart = source.lastIndexOf('\\n', firstStart - 1) + 1;\n entryIndent = source.slice(firstLineStart, firstStart);\n } else {\n entryIndent = closeIndent.includes('\\t') ? `${closeIndent}\\t` : `${closeIndent} `;\n }\n const text = entries.map((entry) => `${entryIndent}${entry}`).join(lineEnding) + lineEnding;\n edits.push({\n start: closeLineStart,\n end: closeLineStart,\n text,\n tableId,\n reason: 'insert canonical managed-column declarations',\n });\n return edits;\n}\n\nfunction addImportRequirement(\n imports: Map<string, ImportRequirement>,\n moduleName: string,\n identifier: string,\n tableId: string,\n): void {\n let requirement = imports.get(moduleName);\n if (!requirement) {\n requirement = { identifiers: new Set(), tableIds: new Set() };\n imports.set(moduleName, requirement);\n }\n requirement.identifiers.add(identifier);\n requirement.tableIds.add(tableId);\n}\n\nfunction drizzleCoreModule(dialect: SchemaDialect): string {\n return dialect === 'postgres' ? 'drizzle-orm/pg-core' : 'drizzle-orm/sqlite-core';\n}\n\nfunction planNamedImport(\n ts: TypeScriptApi,\n sourceFile: TypeScript.SourceFile,\n moduleName: string,\n requirement: ImportRequirement,\n fileName: string,\n edits: SchemaSourceEdit[],\n diagnostics: SchemaSyncDiagnostic[],\n): void {\n const candidates = sourceFile.statements.filter(\n (statement): statement is TypeScript.ImportDeclaration =>\n ts.isImportDeclaration(statement) &&\n ts.isStringLiteralLike(statement.moduleSpecifier) &&\n statement.moduleSpecifier.text === moduleName &&\n !!statement.importClause &&\n !statement.importClause.isTypeOnly &&\n !!statement.importClause.namedBindings &&\n ts.isNamedImports(statement.importClause.namedBindings),\n );\n const present = new Set<string>();\n for (const candidate of candidates) {\n const bindings = candidate.importClause!.namedBindings as TypeScript.NamedImports;\n for (const element of bindings.elements) present.add(element.name.text);\n }\n const missing = [...requirement.identifiers].filter((name) => !present.has(name)).sort();\n if (missing.length === 0) return;\n const target = candidates[0];\n if (!target) {\n diagnostics.push({\n code: 'MISSING_VALUE_IMPORT',\n fileName,\n tableId: requirement.tableIds.size === 1 ? [...requirement.tableIds][0] : undefined,\n expected: `import { ${missing.join(', ')} } from \"${moduleName}\";`,\n message:\n `Managed-column synchronization needs { ${missing.join(', ')} } from ` +\n `\"${moduleName}\", but no plain named value import can be widened. ` +\n `Add the import manually; namespace and type-only imports are not rewritten.`,\n });\n return;\n }\n\n const bindings = target.importClause!.namedBindings as TypeScript.NamedImports;\n const source = sourceFile.text;\n const close = bindings.getEnd() - 1;\n const multiline = source.slice(bindings.getStart(sourceFile), close).includes('\\n');\n const last = bindings.elements[bindings.elements.length - 1];\n if (!multiline) {\n if (last) {\n const tail = source.slice(last.getEnd(), close);\n const preservesComment = tail.includes('//') || tail.includes('/*');\n edits.push({\n start: last.getEnd(),\n end: close,\n text: preservesComment\n ? `${tail.includes(',') ? '' : ','}${tail}${/\\s$/.test(tail) ? '' : ' '}${missing.join(', ')} `\n : `, ${missing.join(', ')} `,\n reason: `add required value imports from ${moduleName}`,\n });\n } else {\n edits.push({\n start: bindings.getStart(sourceFile) + 1,\n end: close,\n text: ` ${missing.join(', ')} `,\n reason: `add required value imports from ${moduleName}`,\n });\n }\n return;\n }\n if (last && !source.slice(last.getEnd(), close).includes(',')) {\n edits.push({\n start: last.getEnd(),\n end: last.getEnd(),\n text: ',',\n reason: `terminate the existing ${moduleName} import before widening it`,\n });\n }\n const lineEnding = source.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const closeLineStart = source.lastIndexOf('\\n', close - 1) + 1;\n const first = bindings.elements[0];\n const indent = first\n ? source.slice(source.lastIndexOf('\\n', first.getStart(sourceFile) - 1) + 1, first.getStart(sourceFile))\n : ' ';\n edits.push({\n start: closeLineStart,\n end: closeLineStart,\n text: missing.map((name) => `${indent}${name},`).join(lineEnding) + lineEnding,\n reason: `add required value imports from ${moduleName}`,\n });\n}\n"],
5
5
  "mappings": ";AAQO,IAAM,wBAAwB;AAE9B,IAAM,wBAAwB;AAC9B,IAAM,oBAAoB;AAO1B,IAAM,iBAAiB,CAAC,aAAa,cAAc,aAAa,YAAY;AAC5E,IAAM,uBAAuB,CAAC,aAAa,WAAW;AAgBtD,IAAM,qBAAuD;AAAA,EAClE;AAAA,IACE,QAAQ;AAAA,IACR,WAAW;AAAA,IACX,MAAM;AAAA,IACN,SAAS;AAAA,IACT,OAAO;AAAA,IACP,aAAa;AAAA,EACf;AAAA,EACA;AAAA,IACE,QAAQ;AAAA,IACR,WAAW;AAAA,IACX,MAAM;AAAA,IACN,SAAS;AAAA,IACT,OAAO;AAAA,IACP,aAAa;AAAA,EACf;AAAA,EACA;AAAA,IACE,QAAQ;AAAA,IACR,WAAW;AAAA,IACX,MAAM;AAAA,IACN,SAAS;AAAA,IACT,OAAO;AA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;AACL,YAAM,KAAK;AAAA,QACT,OAAO,SAAS,SAAS,UAAU,IAAI;AAAA,QACvC,KAAK;AAAA,QACL,MAAM,IAAI,QAAQ,KAAK,IAAI,CAAC;AAAA,QAC5B,QAAQ,mCAAmC,UAAU;AAAA,MACvD,CAAC;AAAA,IACH;AACA;AAAA,EACF;AACA,MAAI,QAAQ,CAAC,OAAO,MAAM,KAAK,OAAO,GAAG,KAAK,EAAE,SAAS,GAAG,GAAG;AAC7D,UAAM,KAAK;AAAA,MACT,OAAO,KAAK,OAAO;AAAA,MACnB,KAAK,KAAK,OAAO;AAAA,MACjB,MAAM;AAAA,MACN,QAAQ,0BAA0B,UAAU;AAAA,IAC9C,CAAC;AAAA,EACH;AACA,QAAM,aAAa,OAAO,SAAS,MAAM,IAAI,SAAS;AACtD,QAAM,iBAAiB,OAAO,YAAY,MAAM,QAAQ,CAAC,IAAI;AAC7D,QAAM,QAAQ,SAAS,SAAS,CAAC;AACjC,QAAM,SAAS,QACX,OAAO,MAAM,OAAO,YAAY,MAAM,MAAM,SAAS,UAAU,IAAI,CAAC,IAAI,GAAG,MAAM,SAAS,UAAU,CAAC,IACrG;AACJ,QAAM,KAAK;AAAA,IACT,OAAO;AAAA,IACP,KAAK;AAAA,IACL,MAAM,QAAQ,IAAI,CAAC,SAAS,GAAG,MAAM,GAAG,IAAI,GAAG,EAAE,KAAK,UAAU,IAAI;AAAA,IACpE,QAAQ,mCAAmC,UAAU;AAAA,EACvD,CAAC;AACH;",
6
6
  "names": ["result", "bindings"]
7
7
  }
@@ -1,4 +1,4 @@
1
- import type * as TypeScript from 'typescript';
1
+ import type * as TypeScript from '@typescript/typescript6';
2
2
  import { type ManagedColumnRequirement, type NamingConvention, type SchemaDialect } from './managed-columns.js';
3
3
  export type TypeScriptApi = Omit<typeof TypeScript, 'default'>;
4
4
  export type SchemaTableStyle = 'q-feature' | 'q-table' | 'raw-drizzle';
@@ -1 +1 @@
1
- {"version":3,"file":"source-sync.d.ts","sourceRoot":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  Inserts new records or updates existing ones. Every record must include an `id` field.
218
218
 
219
- **Note:** Batch upsert is only available when `generateId` is set to `false` (user-provided IDs) in your configuration.
219
+ **Note:** Batch upsert requires both `generateId: false` (user-provided IDs) in your database configuration and `guards: false` on the table. Explicitly enabling `crud.batchUpsert` without both settings is a compile error. Use `crud.batchUpdate` for guarded updates.
220
220
 
221
221
  ### Request
222
222
 
@@ -2,6 +2,11 @@
2
2
 
3
3
  `feature()` is **the** way to write a Quickback feature: one file, one default export, the table and its security contract together. It expands at compile time into `q.table()` + `defineTable()`, which stays available for the cases that need it — see [When to use which](#when-to-use-which).
4
4
 
5
+ The name must be a string literal and the configuration must be an inline object
6
+ with an explicit `columns: { … }` object. Missing columns, configuration spreads,
7
+ and referenced configuration objects produce a compile error; elided examples
8
+ must be filled in before compiling.
9
+
5
10
  ## Quick reference
6
11
 
7
12
  One object. Everything a table exposes is a key in it, and every key is optional
@@ -48,6 +53,11 @@ feature("name", {
48
53
  | Semantic search over the table | `embeddings` | [Embeddings](/platform/vector/using-embeddings) |
49
54
  | The CMS to render it well | `displayColumn`, `defaultSort`, `inputHints`, `layouts` | [CMS](/ui/admin/table-views) |
50
55
 
56
+ A resource's `path` sits under the API prefix (default `/api/v1`). Leading and
57
+ trailing slashes are normalized: `path: "accounting-settings"` and
58
+ `path: "/accounting-settings/"` both produce `/api/v1/accounting-settings`.
59
+ CRUD routes, mapped actions, OpenAPI, and action-schema harvest use the same path.
60
+
51
61
  The rest of this page is the form itself; [One object, not just
52
62
  CRUD](#one-object-not-just-crud) shows the non-CRUD keys filled in.
53
63
 
@@ -227,6 +227,11 @@ If you have an existing Drizzle schema you're bringing forward — or need a dia
227
227
  | Neon, PlanetScale Postgres, PostgreSQL | `drizzle-orm/pg-core` | `pgTable` |
228
228
  | MySQL (`planetscale`, `mysql`) — dialect only, no registered provider | `drizzle-orm/mysql-core` | `mysqlTable` |
229
229
 
230
+ For PostgreSQL targets, the compiler places feature tables in the `app` database
231
+ schema. It initializes the generated schema binding before any table declarations,
232
+ including when several authored table files are combined and retain imports between
233
+ tables. Keep authoring with `pgTable`; the compiler handles schema qualification.
234
+
230
235
  ```typescript
231
236
  // quickback/features/jobs/jobs.ts
232
237
  import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core';
@@ -10,6 +10,11 @@ None. The compiler bundles the plugin source and emits it into your project at `
10
10
 
11
11
  The plugin is wired up only when you explicitly opt in via `email.provider: 'aws-ses'` in your Quickback config. Without that, `email.provider` defaults to `'cloudflare'` and the Cloudflare Email helper is used instead.
12
12
 
13
+ > **SES only sends through the emailOtp plugin**
14
+ >
15
+ > The compiler wires SES into Better Auth via the `emailOtp` plugin's send callback. With `email.provider: 'aws-ses'` and no `emailOtp` plugin, password-reset, email-verification, and organization-invitation emails are not sent — the compiler warns, and it rejects `requireEmailVerification: true` outright in that shape (no user could ever verify). Add `"emailOtp"` to `providers.auth.config.plugins` (or `account.auth.emailOTP: true`).
16
+
17
+
13
18
  ## Email Types
14
19
 
15
20
  The plugin handles 8 email types:
@@ -374,7 +374,9 @@ quickback build
374
374
 
375
375
  The CLI parses your feature files with the TypeScript compiler API, and falls back to a **regex** table detector when it can't. That fallback feeds schema sync, firewall analysis, masking detection, and migration generation — a weaker parser for the input that drives your security pillars.
376
376
 
377
- `typescript` is an optional peer dependency, supported at **`>=5.0.0 <7`**. TypeScript 7 (the native port) resolves its main entry to a module exporting only `version` — parsing moved to the explicitly-unstable `typescript/unstable/*` subpaths — so it cannot drive the AST parser, and the CLI says so by name rather than degrading quietly.
377
+ `typescript` is an optional peer dependency, supported at **`>=5.0.0 <7`** — both 5.x and 6.x expose the classic compiler API. TypeScript 7 (the native port) resolves its main entry to a module exporting only `version` — parsing moved to the explicitly-unstable `typescript/unstable/*` subpaths — so it cannot drive the AST parser, and the CLI says so by name rather than degrading quietly.
378
+
379
+ Compiled projects pin TypeScript 7 for `tsc`, which typechecks generated output correctly. Add a 6.x devDependency alongside it if you want `quickback schema sync` in that project.
378
380
 
379
381
  Set `QUICKBACK_STRICT_PARSE=1` in CI so a regex-parsed build fails the pipeline instead of shipping:
380
382
 
@@ -101,6 +101,21 @@ cd apps/compiler-cloud && bash deploy.sh
101
101
 
102
102
  ## Troubleshooting
103
103
 
104
+ ### Image dependency or startup check fails
105
+
106
+ The Docker build installs the compiler's dependencies with a frozen lockfile,
107
+ then starts the compiler and checks `/health`. A missing startup dependency
108
+ or startup crash therefore fails the image build before deployment.
109
+
110
+ Every package imported by compiler code at runtime must be declared in
111
+ `apps/compiler/package.json` under `dependencies`. A package available through
112
+ another workspace's install is not necessarily available in the image. Keep
113
+ `apps/compiler/bun.lock` in sync with the Dockerfile's isolated workspace
114
+ (`apps/compiler/package.json` plus `packages/deploy-contract`); do not bypass a
115
+ frozen-lockfile failure with an unlocked install. The compiler's
116
+ `compiler-image-imports.test.ts` check also enforces this import boundary during
117
+ `pnpm verify`.
118
+
104
119
  ### Container not starting
105
120
 
106
121
  ```bash
@@ -149,7 +149,7 @@ Enable or disable features using boolean environment variables. **Every flag car
149
149
  |---|---|---|
150
150
  | `VITE_ENABLE_ORGANIZATIONS` | `organizations` | `false` |
151
151
  | `VITE_ENABLE_ORG_TEAMS` | `orgTeams` | `false` |
152
- | `VITE_ENABLE_ADMIN` | `admin` | `true` |
152
+ | `VITE_ENABLE_ADMIN` | `admin` | `false` |
153
153
  | `VITE_ENABLE_FILE_UPLOADS` | `fileUploads` | `false` |
154
154
  | `VITE_ENABLE_PASSKEY` | `passkey` | `false` |
155
155
  | `VITE_ENABLE_EMAIL_OTP` | `emailOTP` | `false` |
@@ -157,13 +157,14 @@ Enable or disable features using boolean environment variables. **Every flag car
157
157
  | `VITE_ENABLE_GOOGLE_OAUTH` | `googleOAuth` | `false` |
158
158
  | `VITE_ENABLE_SUBSCRIPTIONS` | `subscriptions` | `false` |
159
159
  | `VITE_ENABLE_REALTIME` | `realtime` | `false` |
160
+ | `VITE_ENABLE_API_KEYS` | `apiKeys` | `true` |
160
161
 
161
162
  ### `appConfig.auth`
162
163
 
163
164
  | Variable | `auth` key | Default |
164
165
  |---|---|---|
165
166
  | `VITE_ENABLE_SIGNUP` | `enableSignup` | `true` |
166
- | `VITE_ENABLE_EMAIL_VERIFICATION` | `requireEmailVerification` | `true` |
167
+ | `VITE_ENABLE_EMAIL_VERIFICATION` | `requireEmailVerification` | `false` |
167
168
  | `VITE_DISABLE_EMAIL_STATUS_CHECK` | `disableEmailStatusCheck` | `false` |
168
169
 
169
170
  > **Password is on, passkey and OTP are off**
@@ -176,7 +177,7 @@ Enable or disable features using boolean environment variables. **Every flag car
176
177
  ```bash
177
178
  # Authentication
178
179
  VITE_ENABLE_SIGNUP=true # default: true
179
- VITE_ENABLE_EMAIL_VERIFICATION=true # default: true
180
+ VITE_ENABLE_EMAIL_VERIFICATION=false # default: false — matches the server (Better Auth requireEmailVerification)
180
181
  VITE_DISABLE_EMAIL_STATUS_CHECK=false # default: false — inverted sense
181
182
  VITE_ENABLE_PASSWORD=true # default: true
182
183
  VITE_ENABLE_PASSKEY=false # default: false
@@ -195,7 +196,7 @@ VITE_ENABLE_ORG_TEAMS=false # default: false
195
196
  # When false the Teams tab is hidden and the auth client doesn't expose team APIs.
196
197
 
197
198
  # Admin
198
- VITE_ENABLE_ADMIN=true # default: true
199
+ VITE_ENABLE_ADMIN=false # default: false — the compiler always emits it explicitly
199
200
  ```
200
201
 
201
202
  Per-flag behaviour is documented under [Feature Flags](/ui/account/features).
@@ -11,13 +11,13 @@ Control which features are available in your Account UI deployment using feature
11
11
 
12
12
  ### `appConfig.features`
13
13
 
14
- These ten flags populate `appConfig.features` and are the ones `isFeatureEnabled()` accepts.
14
+ These eleven flags populate `appConfig.features` and are the ones `isFeatureEnabled()` accepts.
15
15
 
16
16
  | Variable | `features` key | Default |
17
17
  |---|---|---|
18
18
  | `VITE_ENABLE_ORGANIZATIONS` | `organizations` | `false` |
19
19
  | `VITE_ENABLE_ORG_TEAMS` | `orgTeams` | `false` |
20
- | `VITE_ENABLE_ADMIN` | `admin` | `true` |
20
+ | `VITE_ENABLE_ADMIN` | `admin` | `false` |
21
21
  | `VITE_ENABLE_FILE_UPLOADS` | `fileUploads` | `false` |
22
22
  | `VITE_ENABLE_PASSKEY` | `passkey` | `false` |
23
23
  | `VITE_ENABLE_EMAIL_OTP` | `emailOTP` | `false` |
@@ -25,6 +25,7 @@ These ten flags populate `appConfig.features` and are the ones `isFeatureEnabled
25
25
  | `VITE_ENABLE_GOOGLE_OAUTH` | `googleOAuth` | `false` |
26
26
  | `VITE_ENABLE_SUBSCRIPTIONS` | `subscriptions` | `false` |
27
27
  | `VITE_ENABLE_REALTIME` | `realtime` | `false` |
28
+ | `VITE_ENABLE_API_KEYS` | `apiKeys` | `true` |
28
29
 
29
30
  ### `appConfig.auth`
30
31
 
@@ -33,12 +34,12 @@ Three further flags configure the signup and email flows. They live on `appConfi
33
34
  | Variable | `auth` key | Default |
34
35
  |---|---|---|
35
36
  | `VITE_ENABLE_SIGNUP` | `enableSignup` | `true` |
36
- | `VITE_ENABLE_EMAIL_VERIFICATION` | `requireEmailVerification` | `true` |
37
+ | `VITE_ENABLE_EMAIL_VERIFICATION` | `requireEmailVerification` | `false` |
37
38
  | `VITE_DISABLE_EMAIL_STATUS_CHECK` | `disableEmailStatusCheck` | `false` |
38
39
 
39
40
  > **Password is on, passkey and OTP are off**
40
41
  >
41
- > The out-of-the-box posture is email + password only. Passkey, email OTP, organizations, and Google OAuth all default to `false` — you opt in. Admin defaults to `true`.
42
+ > The out-of-the-box posture is email + password only. Passkey, email OTP, organizations, admin, and Google OAuth all default to `false` — you opt in. API keys default to `true` in a standalone build; a compiled project always emits the flag from whether the `apiKey` plugin is listed.
42
43
 
43
44
 
44
45
  > **These are the SPA's built-in defaults — the compiler overrides most of them**
@@ -48,7 +49,8 @@ Three further flags configure the signup and email flows. They live on `appConfi
48
49
  > Two derivations are worth knowing because they do not match the built-in default:
49
50
  >
50
51
  > - **`organizations` resolves to `true`** unless you set `account.auth.organizations: false`, so a compiled project has organizations on even though the SPA default is `false`.
51
- > - **`admin` is emitted only when you set `account.auth.admin`.** Leave it unset and the compiler strips the `/admin` route files from the bundle while the SPA's built-in `admin: true` default still reports the feature as enabled. Set `account.auth.admin` explicitly — in either direction — rather than relying on the default.
52
+ > - **`admin`, `apiKeys`, and `emailVerification` are always emitted as explicit booleans**, never left to the SPA default — the generic bundle carries every route and gates it on the injected flag, so "unset" must arrive as a hard `false`.
53
+ > - **Password reset needs `emailOTP`.** The Account UI's reset flow is code-based (`/forgot-password` sends a one-time code), so a password-only project shows no "Forgot your password?" link and the compiler warns that users have no self-serve recovery. Set `account.auth.emailOTP: true` to enable it.
52
54
 
53
55
 
54
56
  ## Authentication Features
@@ -74,10 +76,10 @@ Controls whether new users can register.
74
76
  ### Email Verification
75
77
 
76
78
  ```bash
77
- VITE_ENABLE_EMAIL_VERIFICATION=true # default: true
79
+ VITE_ENABLE_EMAIL_VERIFICATION=false # default: false
78
80
  ```
79
81
 
80
- Controls the email verification flow.
82
+ Controls the email verification flow. The default matches the server (Better Auth `requireEmailVerification` is off unless you set it); a compiled project always emits this flag explicitly.
81
83
 
82
84
  **When enabled:**
83
85
  - Users must verify email before full access
@@ -122,10 +124,12 @@ VITE_ENABLE_PASSWORD=true # default: true
122
124
  - Email + password fields on login page
123
125
  - Password field on signup page
124
126
  - Traditional username/password authentication
127
+ - "Forgot your password?" link and profile "Change Password" — only when `VITE_ENABLE_EMAIL_OTP` is also on, because the reset flow is code-based. Without OTP the profile offers an in-session "Update Password" dialog only.
125
128
 
126
129
  **When disabled:**
127
130
  - No password fields shown
128
131
  - Users authenticate via email OTP or passkey
132
+ - The server's password endpoints are off too — the compiler emits the flag from `emailAndPassword.enabled`
129
133
 
130
134
  ### Passkey Login
131
135
 
@@ -158,6 +162,7 @@ VITE_ENABLE_EMAIL_OTP=false # default: false
158
162
  - Users can receive one-time passwords via email
159
163
  - Alternative to password login
160
164
  - `/email-otp` route available
165
+ - Enables the `/forgot-password` reset flow when password auth is also on
161
166
 
162
167
  **When disabled:**
163
168
  - No email OTP option
@@ -290,7 +295,7 @@ Sub-groups within an organization. Auto-set to `true` by the compiler when your
290
295
  ### Admin Panel
291
296
 
292
297
  ```bash
293
- VITE_ENABLE_ADMIN=true # default: true
298
+ VITE_ENABLE_ADMIN=false # default: false
294
299
  ```
295
300
 
296
301
  **When enabled:**
@@ -323,7 +328,7 @@ VITE_ENABLE_ORGANIZATIONS=false
323
328
  VITE_ENABLE_ADMIN=false
324
329
  ```
325
330
 
326
- Simple email/password authentication for apps that do not need advanced auth methods. Only `VITE_ENABLE_ADMIN` differs from the built-in defaults here.
331
+ Simple email/password authentication for apps that do not need advanced auth methods. These are the built-in defaults. Note there is no self-serve password reset in this shape — add `VITE_ENABLE_EMAIL_OTP=true` for that.
327
332
 
328
333
  ### Maximum Security
329
334
 
@@ -137,14 +137,21 @@ server hook when tenant selection cannot be derived solely from the session's
137
137
  active organization.
138
138
 
139
139
  ```ts title="quickback/hooks/resolve-oauth-context.ts"
140
- export default async ({ token, session, user, context }, { authDb, authSchema, env }) => {
140
+ import type { OAuthContextResolver } from '@quickback/compiler';
141
+
142
+ const resolveContext: OAuthContextResolver = async (
143
+ { claims, session, user, request, baseContext },
144
+ { authDb, authSchema, env },
145
+ ) => {
141
146
  return {
142
- activeOrgId: session.activeOrganizationId ?? null,
143
- activeTeamId: session.activeTeamId ?? null,
144
- tenantId: session.activeOrganizationId ?? null,
145
- roles: context.roles,
147
+ activeOrgId: session.activeOrganizationId ?? undefined,
148
+ activeTeamId: session.activeTeamId ?? undefined,
149
+ tenantId: session.activeOrganizationId ?? undefined,
150
+ roles: baseContext.roles,
146
151
  };
147
152
  };
153
+
154
+ export default resolveContext;
148
155
  ```
149
156
 
150
157
  The returned object is merged into the standard `AppContext`. The compiler
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.66.14",
3
+ "version": "0.66.15",
4
4
  "description": "CLI for Quickback — define your backend in TypeScript, compile to a fully wired Cloudflare Worker (or Bun / Node) with auth, database, migrations, security, CMS, and Account UI.",
5
5
  "author": "Kardoe Incorporated <paul@kardoe.com>",
6
6
  "license": "MIT",
@@ -216,7 +216,7 @@ PUT /api/v1/{resource}/batch
216
216
 
217
217
  Inserts new records or updates existing ones. Every record must include an `id` field.
218
218
 
219
- **Note:** Batch upsert is only available when `generateId` is set to `false` (user-provided IDs) in your configuration.
219
+ **Note:** Batch upsert requires both `generateId: false` (user-provided IDs) in your database configuration and `guards: false` on the table. Explicitly enabling `crud.batchUpsert` without both settings is a compile error. Use `crud.batchUpdate` for guarded updates.
220
220
 
221
221
  ### Request
222
222