@quickback-dev/cli 0.66.7 → 0.66.9

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 (83) hide show
  1. package/dist/commands/build.d.ts +0 -1
  2. package/dist/commands/build.d.ts.map +1 -1
  3. package/dist/commands/build.js +11 -2
  4. package/dist/commands/build.js.map +1 -1
  5. package/dist/commands/build.test.js +53 -2
  6. package/dist/commands/build.test.js.map +1 -1
  7. package/dist/commands/canary.d.ts +17 -5
  8. package/dist/commands/canary.d.ts.map +1 -1
  9. package/dist/commands/canary.js +34 -24
  10. package/dist/commands/canary.js.map +1 -1
  11. package/dist/commands/canary.test.d.ts +2 -0
  12. package/dist/commands/canary.test.d.ts.map +1 -0
  13. package/dist/commands/canary.test.js +100 -0
  14. package/dist/commands/canary.test.js.map +1 -0
  15. package/dist/commands/deploy.d.ts +14 -1
  16. package/dist/commands/deploy.d.ts.map +1 -1
  17. package/dist/commands/deploy.js +49 -19
  18. package/dist/commands/deploy.js.map +1 -1
  19. package/dist/commands/deploy.test.d.ts +2 -0
  20. package/dist/commands/deploy.test.d.ts.map +1 -0
  21. package/dist/commands/deploy.test.js +139 -0
  22. package/dist/commands/deploy.test.js.map +1 -0
  23. package/dist/index.js +3 -3
  24. package/dist/lib/compile-next-steps.d.ts.map +1 -1
  25. package/dist/lib/compile-next-steps.js +12 -5
  26. package/dist/lib/compile-next-steps.js.map +1 -1
  27. package/dist/lib/deployment-target.d.ts +29 -0
  28. package/dist/lib/deployment-target.d.ts.map +1 -0
  29. package/dist/lib/deployment-target.js +46 -0
  30. package/dist/lib/deployment-target.js.map +1 -0
  31. package/dist/lib/deployment-target.test.d.ts +2 -0
  32. package/dist/lib/deployment-target.test.d.ts.map +1 -0
  33. package/dist/lib/deployment-target.test.js +27 -0
  34. package/dist/lib/deployment-target.test.js.map +1 -0
  35. package/dist/lib/file-writer.d.ts +1 -1
  36. package/dist/lib/file-writer.d.ts.map +1 -1
  37. package/dist/lib/file-writer.js +2 -3
  38. package/dist/lib/file-writer.js.map +1 -1
  39. package/dist/lib/neon-canary.d.ts +4 -0
  40. package/dist/lib/neon-canary.d.ts.map +1 -1
  41. package/dist/lib/neon-canary.js +24 -4
  42. package/dist/lib/neon-canary.js.map +1 -1
  43. package/dist/lib/neon-canary.test.js +39 -3
  44. package/dist/lib/neon-canary.test.js.map +1 -1
  45. package/dist/lib/neon-target.d.ts +5 -48
  46. package/dist/lib/neon-target.d.ts.map +1 -1
  47. package/dist/lib/neon-target.js +18 -42
  48. package/dist/lib/neon-target.js.map +1 -1
  49. package/dist/lib/neon-target.test.js +26 -4
  50. package/dist/lib/neon-target.test.js.map +1 -1
  51. package/dist/lib/shell.d.ts +10 -0
  52. package/dist/lib/shell.d.ts.map +1 -1
  53. package/dist/lib/shell.js +20 -0
  54. package/dist/lib/shell.js.map +1 -1
  55. package/dist/lib/shell.test.js +35 -1
  56. package/dist/lib/shell.test.js.map +1 -1
  57. package/dist/lib/wrangler-resources.d.ts +1 -1
  58. package/dist/lib/wrangler-resources.d.ts.map +1 -1
  59. package/dist/lib/wrangler-resources.js +20 -9
  60. package/dist/lib/wrangler-resources.js.map +1 -1
  61. package/dist/lib/wrangler-resources.test.js +20 -0
  62. package/dist/lib/wrangler-resources.test.js.map +1 -1
  63. package/dist/schema-engine/index.js +3 -0
  64. package/dist/schema-engine/index.js.map +2 -2
  65. package/dist/schema-engine/provider-dialects.d.ts +1 -1
  66. package/dist/schema-engine/provider-dialects.d.ts.map +1 -1
  67. package/dist/skill/docs/configure/providers.md +18 -3
  68. package/dist/skill/docs/define/actions/scoped-db.md +88 -41
  69. package/dist/skill/docs/platform/database/d1.md +2 -2
  70. package/dist/skill/docs/platform/database/index.md +7 -2
  71. package/dist/skill/docs/platform/database/neon.md +283 -57
  72. package/dist/skill/docs/platform/database/planetscale-postgres.md +205 -0
  73. package/dist/skill/docs/start/deploy.md +30 -0
  74. package/dist/skill/docs/tooling/cli.md +41 -0
  75. package/package.json +1 -1
  76. package/src/skill/docs/configure/providers.md +18 -3
  77. package/src/skill/docs/define/actions/scoped-db.md +88 -41
  78. package/src/skill/docs/platform/database/d1.md +2 -2
  79. package/src/skill/docs/platform/database/index.md +7 -2
  80. package/src/skill/docs/platform/database/neon.md +283 -57
  81. package/src/skill/docs/platform/database/planetscale-postgres.md +205 -0
  82. package/src/skill/docs/start/deploy.md +30 -0
  83. package/src/skill/docs/tooling/cli.md +41 -0
@@ -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 '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"],
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;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;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AA,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;",
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"],
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,MA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
7
7
  }
@@ -9,7 +9,7 @@
9
9
  */
10
10
  export type ProviderDialect = 'sqlite' | 'postgres' | 'mysql';
11
11
  export declare const SQLITE_PROVIDERS: readonly ["cloudflare-d1", "better-sqlite3", "bun-sqlite", "libsql", "turso"];
12
- export declare const POSTGRES_PROVIDERS: readonly ["supabase", "neon", "vercel-postgres", "postgres", "postgresql"];
12
+ export declare const POSTGRES_PROVIDERS: readonly ["supabase", "neon", "planetscale-postgres", "vercel-postgres", "postgres", "postgresql"];
13
13
  export declare const MYSQL_PROVIDERS: readonly ["planetscale", "mysql", "mysql2"];
14
14
  /**
15
15
  * Resolve a database provider name to its SQL dialect family.
@@ -1 +1 @@
1
- {"version":3,"file":"provider-dialects.d.ts","sourceRoot":"","sources":["../src/provider-dialects.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,MAAM,MAAM,eAAe,GAAG,QAAQ,GAAG,UAAU,GAAG,OAAO,CAAC;AAE9D,eAAO,MAAM,gBAAgB,+EAMnB,CAAC;AAEX,eAAO,MAAM,kBAAkB,4EAMrB,CAAC;AAEX,eAAO,MAAM,eAAe,6CAA8C,CAAC;AAE3E;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CACpC,YAAY,EAAE,MAAM,GAAG,SAAS,GAC/B,eAAe,GAAG,SAAS,CAM7B"}
1
+ {"version":3,"file":"provider-dialects.d.ts","sourceRoot":"","sources":["../src/provider-dialects.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,MAAM,MAAM,eAAe,GAAG,QAAQ,GAAG,UAAU,GAAG,OAAO,CAAC;AAE9D,eAAO,MAAM,gBAAgB,+EAMnB,CAAC;AAEX,eAAO,MAAM,kBAAkB,oGASrB,CAAC;AAEX,eAAO,MAAM,eAAe,6CAA8C,CAAC;AAE3E;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CACpC,YAAY,EAAE,MAAM,GAAG,SAAS,GAC/B,eAAe,GAAG,SAAS,CAM7B"}
@@ -59,15 +59,20 @@ providers: {
59
59
 
60
60
  ## Database Providers
61
61
 
62
- Two databases are supported, both Cloudflare-native:
62
+ Three provider names are supported — one SQLite target and one Postgres
63
+ implementation on two hosts:
63
64
 
64
65
  | Provider | Description |
65
66
  |----------|-------------|
66
67
  | `cloudflare-d1` | Cloudflare D1 (SQLite at the edge) |
67
- | `neon` | Neon serverless PostgreSQL (`@neondatabase/serverless` over HTTP) |
68
+ | `neon` | Neon serverless PostgreSQL (`@neondatabase/serverless` over HTTP, or postgres.js over Hyperdrive) |
69
+ | `planetscale-postgres` | [PlanetScale Postgres](/platform/database/planetscale-postgres) over a Cloudflare Hyperdrive binding — the same Postgres emitters as `neon` (Hyperdrive only) |
70
+
71
+ `planetscale` — without the suffix — is the MySQL name and is **not** a
72
+ registered provider; MySQL is not supported.
68
73
 
69
74
  One database provider per app: auth tables and feature tables always share the
70
- selected database. On `neon`, Better Auth uses its PostgreSQL/Drizzle adapter
75
+ selected database. On either Postgres provider, Better Auth uses its PostgreSQL/Drizzle adapter
71
76
  in the same Postgres database as your features; on `cloudflare-d1`, both use
72
77
  D1. A per-service map (`database: { auth: ..., features: ... }`) is rejected at
73
78
  compile time — mixed database providers are not supported.
@@ -126,6 +131,16 @@ The Worker connects through a single `DATABASE_URL` secret — auth and feature
126
131
  queries share it. See [Neon](/platform/database/neon) for
127
132
  connection modes, RLS, and the migration workflow.
128
133
 
134
+ #### PlanetScale Postgres Options
135
+
136
+ Same options, one transport: `connectionMode` accepts `"auto"` and
137
+ `"hyperdrive"` only (omitted is `"hyperdrive"`), `hyperdrive.id` is required,
138
+ and there is no `DATABASE_URL` Worker secret — the runtime reads
139
+ `env.HYPERDRIVE.connectionString`. `pooled` does not apply; Hyperdrive is the
140
+ pool. See [PlanetScale Postgres](/platform/database/planetscale-postgres) for
141
+ role bootstrap, the `role.branch_id` connection username, and the mandatory
142
+ cache-disabled Hyperdrive config.
143
+
129
144
  #### Audit Database
130
145
 
131
146
  Cross-tenant `unsafe` actions (see [Actions → Unsafe mode](/define/actions/scoped-db#unsafe-mode)) write mandatory audit events. Those events land in a dedicated D1 database — separate from your features DB — so audit history stays isolated from application data and can't be tampered with through a normal CRUD route.
@@ -74,11 +74,17 @@ intersected with the same authority context: a single or shared hydration
74
74
  target is required, while targets selected by distinct relationship lanes are
75
75
  optional and must be narrowed by the handler.
76
76
 
77
- For tables queried by authored actions, `resource.databaseAccess` adds an
78
- independent Postgres RLS policy without adding HTTP surface. It never mounts a
79
- read/CRUD route and never adds an OpenAPI operation. The action remains the API
80
- layer where validation, state transitions, side effects, and business logic
81
- belong; `databaseAccess` is only the database's row-level upper bound.
77
+ For tables queried by authored actions, `resource.databaseAccess` opens a
78
+ **delegated-principal lane** at the database: an independent Postgres RLS policy
79
+ with no HTTP surface. It never mounts a read/CRUD route and never adds an
80
+ OpenAPI operation. The action remains the API layer where validation, state
81
+ transitions, side effects, and business logic belong; `databaseAccess` is only
82
+ the database's row-level upper bound.
83
+
84
+ It exists for one reason. A delegated principal has no `userId`, no active
85
+ organization, and no membership roles, so the table's ordinary firewall
86
+ predicate — `organizationId = ctx.activeOrgId` — can never match for it. The
87
+ lane is the row rule that CAN: the principal's own verified claims.
82
88
 
83
89
  {/* doc-compile: skip — provider prerequisite: `resource.databaseAccess` compiles only on Cloudflare + Neon `connectionMode: "hyperdrive"` (RLS + transaction-local claims), and the gate's harness is D1. The file is otherwise whole and compiles on a Neon project. */}
84
90
  ```typescript
@@ -95,49 +101,81 @@ export const attendanceEvidence = q.table('attendanceEvidence', {
95
101
  });
96
102
 
97
103
  export default defineTable(attendanceEvidence, {
98
- // Ordinary account CRUD remains organization-scoped.
104
+ // The ACCOUNT lane: ordinary organization-scoped CRUD. This is the firewall,
105
+ // and the firewall is the only pillar that lowers to SQL.
99
106
  firewall: [
100
107
  { field: "organizationId", equals: "ctx.activeOrgId" },
101
108
  ],
102
109
 
103
- // Authored actions can use their caller-scoped db under one of two exact
104
- // row lanes. Sibling arms OR; fields in each arm AND.
110
+ // The DELEGATE lane: the event delegate has no active organization, so the
111
+ // firewall above can never admit it. Its rows are the ones its own claims
112
+ // name. Fields inside one arm AND; sibling `or` arms are independent lanes.
105
113
  databaseAccess: {
106
114
  select: {
107
- or: [
108
- {
109
- roles: ["AUTHENTICATED"],
110
- record: {
111
- organizationId: { equals: "$ctx.activeOrgId" },
112
- },
113
- },
114
- {
115
- principals: ["event_delegate"],
116
- record: {
117
- eventId: { equals: "$ctx.principal.claims.eventId" },
118
- personId: { equals: "$ctx.principal.claims.personId" },
119
- },
120
- },
121
- ],
115
+ principals: ["event_delegate"],
116
+ record: {
117
+ eventId: { equals: "$ctx.principal.claims.eventId" },
118
+ personId: { equals: "$ctx.principal.claims.personId" },
119
+ },
122
120
  },
123
121
  },
124
122
  });
125
123
  ```
126
124
 
127
- `databaseAccess` supports `select`, `insert`, `update`, and `delete` with a
128
- purpose-built, SQL-pushable rule language: `principals`, `roles`, recursive
129
- `or`/`and`, and record `equals` against a DB-visible account or principal
130
- context value. Application-only values such as `userRole`, functions, and
131
- request/body fields stay at the action access layer; the compiler refuses them
132
- inside database RLS rather than pretending PostgreSQL can evaluate them.
133
-
134
- Every authorization path must contain at least one nonempty record equality.
135
- A principal-only or role-only leaf is rejected; every `or` arm must be bounded.
136
- An `and` group is bounded when at least one child bounds every expansion (for
137
- example, a principal child AND an event-id record child). A node cannot mix
138
- leaf fields with `or`/`and`, because the boolean node is the complete rule.
139
- This mandatory shape prevents an action declaration from accidentally granting
140
- the delegated principal an entire table.
125
+ ### One lane, one policy
126
+
127
+ The compiler emits exactly **one** permissive policy per table with a lane,
128
+ `<table>_principal_scope`, whose `USING` is the OR over the declared principal
129
+ arms. Two principal types on the same table are two arms of that one policy,
130
+ not two policies.
131
+
132
+ Its **command is the lane's declared reach**:
133
+
134
+ | Declared | Emitted |
135
+ |----------|---------|
136
+ | `select` only | `FOR SELECT`, `USING` only — the lane reads and cannot write |
137
+ | any of `insert` / `update` / `delete` | `FOR ALL`, with the same predicate as `WITH CHECK` |
138
+
139
+ Whether a delegate may write is a property of the lane, declared once by the
140
+ author, so the database enforces it as the policy's command. Which *verb* a
141
+ caller may reach is still the API's decision — RLS is the lane backstop, not a
142
+ per-operation access matrix.
143
+
144
+ The policy is **permissive**, and PostgreSQL ORs permissive policies together,
145
+ so the lane opens *beside* the table's `<table>_scope` firewall policy rather
146
+ than narrowing it. That is the point — the delegated caller has no active
147
+ organization — but it means a `databaseAccess` arm is never a place to write a
148
+ restriction: a row that satisfies the arm is reachable even when the table
149
+ firewall would not have matched it, and even when it is soft-deleted.
150
+ Restrictions belong in `firewall`. The restrictive `<table>_deny_anon` and
151
+ `<table>_principal_fence` policies remain the only arms that cap every lane.
152
+
153
+ ### What the compiler refuses, and why
154
+
155
+ `databaseAccess` lowers **only** `principals` + `record`, plus recursive
156
+ `or`/`and` over those. Two shapes that used to be spellable here are now
157
+ compile errors:
158
+
159
+ - **`roles`, anywhere.** Authored roles are enforced by the API and never reach
160
+ SQL (generated RLS is a backstop, not a second copy of `access`), so a role
161
+ arm here promised an authorization the database did not enforce. `roles` is
162
+ absent from the `DatabaseAccessRule` type as well, so an editor rejects it
163
+ before the compiler does.
164
+ - **A `record` equality with no `principals` gate.** That is an owner or tenant
165
+ rule, and those go in `firewall` — the one pillar that lowers to SQL. If the
166
+ owner boundary must hold at the database, author it as a firewall arm.
167
+
168
+ Both produce: *databaseAccess lowers only delegated-principal lanes (principals
169
+ + record). Account-lane scope belongs in firewall; roles are enforced by the
170
+ API.*
171
+
172
+ Every authorization path must also contain at least one record equality. A
173
+ principal-only leaf is rejected; every `or` arm must be bounded on its own,
174
+ because each is an independent lane. An `and` group is one lane whose children
175
+ may split the principal gate and the row bound between them. A node cannot mix
176
+ leaf fields with `or`/`and`, because the boolean node is the complete rule. This
177
+ mandatory shape is what stops a lane declaration from quietly granting a
178
+ delegated principal an entire table.
141
179
 
142
180
  The supported equality sources are `ctx.userId`, `ctx.activeOrgId`,
143
181
  `ctx.activeTeamId`, `ctx.principal.actor.id`, optional principal session/family
@@ -145,10 +183,19 @@ ids, and `ctx.principal.claims.<name>` (with or without a leading `$`). The
145
183
  record keys are Drizzle/JavaScript table field names; Quickback resolves them
146
184
  through the table metadata and quotes the exact physical PostgreSQL identifier,
147
185
  so a field such as `eventId: text("event-id")` is safe. Unknown fields fail the
148
- compile. `ADMIN` and the app-only `INTERNAL` marker are forbidden on this DB
149
- surface, while `SYSADMIN` retains its explicit `cms.sysadmin` prerequisite. The
150
- feature is rejected outside Cloudflare + Neon Hyperdrive because those targets
151
- cannot guarantee request-scoped Postgres claims.
186
+ compile. Application-only values — `userRole`, functions, request/body fields —
187
+ stay at the action access layer; the compiler refuses them rather than
188
+ pretending PostgreSQL can evaluate them. The feature is rejected outside
189
+ Cloudflare + Neon Hyperdrive because no other target can guarantee
190
+ request-scoped Postgres claims.
191
+
192
+ > **Upgrading.** The four per-operation `<table>_database_<op>` policies are
193
+ > retired. One appended `quickback_rls` migration drops them on every table and
194
+ > creates the single `<table>_principal_scope` where a lane is declared —
195
+ > append-only, like every other security migration. A `databaseAccess` block that
196
+ > still carries `roles` (or a principal-less `record`) fails the compile with the
197
+ > message above; move the account arm to `firewall` and keep the principal arm.
198
+
152
199
 
153
200
  ### Scoped relational-query safety
154
201
 
@@ -395,7 +395,7 @@ For all Quickback-generated code, D1's application-layer security provides equiv
395
395
  2. **Generated code enforces rules** - All CRUD and Action endpoints automatically apply firewall, access, guards, and masking.
396
396
  3. **Single entry point** - Every request flows through your API where security is enforced.
397
397
 
398
- Unlike Neon, where PostgreSQL RLS provides database-level enforcement (protecting data even if application code has bugs), D1's security comes from architecture: the database is inaccessible except through your Worker, and all generated routes apply the four security pillars. The trade-off is that **custom routes you write outside Quickback must manually apply security** — there is no database-level safety net.
398
+ Unlike Neon, where PostgreSQL RLS provides a database-level backstop (protecting tenant scope, soft delete and lane admission even if application code has bugs — roles, status, transitions and masking stay with the API either way, see [Row Level Security](/platform/database/neon#row-level-security)), D1's security comes from architecture: the database is inaccessible except through your Worker, and all generated routes apply the four security pillars. The trade-off is that **custom routes you write outside Quickback must manually apply security** — there is no database-level safety net.
399
399
 
400
400
  ### Comparison with Neon RLS
401
401
 
@@ -403,7 +403,7 @@ Unlike Neon, where PostgreSQL RLS provides database-level enforcement (protectin
403
403
  |----------|------|-----|
404
404
  | CRUD endpoints | ✅ Secure (RLS + App) | ✅ Secure (App) |
405
405
  | Actions | ✅ Secure (RLS + App) | ✅ Secure (App) |
406
- | Manual routes | ✅ RLS still protects | ⚠️ Must apply firewall |
406
+ | Manual routes | ✅ RLS still fences tenant scope, soft delete and lane admission — not roles | ⚠️ Must apply firewall |
407
407
  | External DB access | ⚠️ Possible with credentials | ✅ Not possible |
408
408
  | Dashboard queries | Via the Neon console | ⚠️ Admin only (audit logged) |
409
409
 
@@ -10,6 +10,7 @@ security definitions compile to either provider.
10
10
  |----------|----------|---------------|
11
11
  | [Cloudflare D1](/platform/database/d1) | CRUD-heavy SaaS, content catalogs, internal tools, straightforward workflows | Managed SQLite, no connection strings or pooling, Cloudflare-native operations, FTS5 and JSON functions when needed |
12
12
  | [Neon](/platform/database/neon) | Data-intensive products and apps designed around PostgreSQL | Native JSONB/arrays, `tsvector` + GIN, PostGIS/extensions, database RLS, advanced indexing and interactive transactions through Hyperdrive |
13
+ | [PlanetScale Postgres](/platform/database/planetscale-postgres) | The same Postgres implementation, hosted on PlanetScale | Identical generated schema, RLS and migrations to Neon; Cloudflare Hyperdrive only |
13
14
 
14
15
  ## Quick decision
15
16
 
@@ -18,11 +19,15 @@ security definitions compile to either provider.
18
19
  - Pick **Neon/Postgres** up front when advanced search, rich data types,
19
20
  sustained concurrent writes, Postgres extensions, or database-level RLS are
20
21
  product requirements.
21
- - Hyperdrive is optional: Neon HTTP is the lightweight default on Cloudflare;
22
- Hyperdrive is the full-featured lane for interactive transactions.
22
+ - Hyperdrive is optional on Neon: HTTP is the lightweight default on
23
+ Cloudflare, Hyperdrive the full-featured lane for interactive transactions.
24
+ On **PlanetScale Postgres** Hyperdrive is the only transport.
25
+ - The Postgres choice is a hosting choice: `neon` and `planetscale-postgres`
26
+ emit byte-identical schema and security migrations for the same definitions.
23
27
 
24
28
  ## Getting Started
25
29
 
26
30
  - **[D1 Setup](/platform/database/d1)** — Bindings, wrangler config, migrations
27
31
  - **[Using D1](/platform/database/using-d1)** — Drizzle queries, dual-DB mode, schema patterns
28
32
  - **[Neon](/platform/database/neon)** — Serverless Postgres setup and usage
33
+ - **[PlanetScale Postgres](/platform/database/planetscale-postgres)** — Roles, connection usernames, the cache-disabled Hyperdrive binding