@dbmason/core 0.1.0-alpha.1

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 (104) hide show
  1. package/README.md +17 -0
  2. package/dist/DbmasonContext-Baf-v6-B.mjs +31 -0
  3. package/dist/DbmasonContext-Baf-v6-B.mjs.map +1 -0
  4. package/dist/DbmasonContext-Dw0gG7AV.js +2 -0
  5. package/dist/DbmasonContext-Dw0gG7AV.js.map +1 -0
  6. package/dist/ast/nodes.d.ts +192 -0
  7. package/dist/ast/nodes.d.ts.map +1 -0
  8. package/dist/cli/commands/client.d.ts +2 -0
  9. package/dist/cli/commands/client.d.ts.map +1 -0
  10. package/dist/cli/commands/generate.d.ts +2 -0
  11. package/dist/cli/commands/generate.d.ts.map +1 -0
  12. package/dist/cli/commands/init.d.ts +2 -0
  13. package/dist/cli/commands/init.d.ts.map +1 -0
  14. package/dist/cli/commands/migrate.d.ts +2 -0
  15. package/dist/cli/commands/migrate.d.ts.map +1 -0
  16. package/dist/cli/commands/pull.d.ts +2 -0
  17. package/dist/cli/commands/pull.d.ts.map +1 -0
  18. package/dist/cli/index.d.ts +3 -0
  19. package/dist/cli/index.d.ts.map +1 -0
  20. package/dist/cli/index.js +81 -0
  21. package/dist/cli/index.js.map +1 -0
  22. package/dist/cli/index.mjs +929 -0
  23. package/dist/cli/index.mjs.map +1 -0
  24. package/dist/client/generateClientMetadata.d.ts +8 -0
  25. package/dist/client/generateClientMetadata.d.ts.map +1 -0
  26. package/dist/client/standaloneGenerator.d.ts +5 -0
  27. package/dist/client/standaloneGenerator.d.ts.map +1 -0
  28. package/dist/compiler/DbmasonContext.d.ts +74 -0
  29. package/dist/compiler/DbmasonContext.d.ts.map +1 -0
  30. package/dist/compiler/Dialect.d.ts +25 -0
  31. package/dist/compiler/Dialect.d.ts.map +1 -0
  32. package/dist/compiler/Introspector.d.ts +5 -0
  33. package/dist/compiler/Introspector.d.ts.map +1 -0
  34. package/dist/compiler/SnapshotBuilder.d.ts +5 -0
  35. package/dist/compiler/SnapshotBuilder.d.ts.map +1 -0
  36. package/dist/compiler/analyzers/dependency.resolver.d.ts +11 -0
  37. package/dist/compiler/analyzers/dependency.resolver.d.ts.map +1 -0
  38. package/dist/compiler/analyzers/schema.analyzer.d.ts +11 -0
  39. package/dist/compiler/analyzers/schema.analyzer.d.ts.map +1 -0
  40. package/dist/compiler/compile.d.ts +18 -0
  41. package/dist/compiler/compile.d.ts.map +1 -0
  42. package/dist/compiler/diff.d.ts +25 -0
  43. package/dist/compiler/diff.d.ts.map +1 -0
  44. package/dist/definitions/Cron.d.ts +2 -0
  45. package/dist/definitions/Cron.d.ts.map +1 -0
  46. package/dist/definitions/Extension.d.ts +2 -0
  47. package/dist/definitions/Extension.d.ts.map +1 -0
  48. package/dist/definitions/Function.d.ts +2 -0
  49. package/dist/definitions/Function.d.ts.map +1 -0
  50. package/dist/definitions/Grant.d.ts +2 -0
  51. package/dist/definitions/Grant.d.ts.map +1 -0
  52. package/dist/definitions/Module.d.ts +2 -0
  53. package/dist/definitions/Module.d.ts.map +1 -0
  54. package/dist/definitions/Policy.d.ts +2 -0
  55. package/dist/definitions/Policy.d.ts.map +1 -0
  56. package/dist/definitions/Procedure.d.ts +2 -0
  57. package/dist/definitions/Procedure.d.ts.map +1 -0
  58. package/dist/definitions/Role.d.ts +2 -0
  59. package/dist/definitions/Role.d.ts.map +1 -0
  60. package/dist/definitions/Table.d.ts +4 -0
  61. package/dist/definitions/Table.d.ts.map +1 -0
  62. package/dist/definitions/Trigger.d.ts +2 -0
  63. package/dist/definitions/Trigger.d.ts.map +1 -0
  64. package/dist/definitions/Type.d.ts +2 -0
  65. package/dist/definitions/Type.d.ts.map +1 -0
  66. package/dist/definitions/View.d.ts +3 -0
  67. package/dist/definitions/View.d.ts.map +1 -0
  68. package/dist/definitions/collectors/Cron.internal.d.ts +6 -0
  69. package/dist/definitions/collectors/Cron.internal.d.ts.map +1 -0
  70. package/dist/definitions/collectors/Extension.internal.d.ts +9 -0
  71. package/dist/definitions/collectors/Extension.internal.d.ts.map +1 -0
  72. package/dist/definitions/collectors/Function.internal.d.ts +8 -0
  73. package/dist/definitions/collectors/Function.internal.d.ts.map +1 -0
  74. package/dist/definitions/collectors/Grant.internal.d.ts +8 -0
  75. package/dist/definitions/collectors/Grant.internal.d.ts.map +1 -0
  76. package/dist/definitions/collectors/Policy.internal.d.ts +7 -0
  77. package/dist/definitions/collectors/Policy.internal.d.ts.map +1 -0
  78. package/dist/definitions/collectors/Procedure.internal.d.ts +8 -0
  79. package/dist/definitions/collectors/Procedure.internal.d.ts.map +1 -0
  80. package/dist/definitions/collectors/Role.internal.d.ts +8 -0
  81. package/dist/definitions/collectors/Role.internal.d.ts.map +1 -0
  82. package/dist/definitions/collectors/Table.internal.d.ts +23 -0
  83. package/dist/definitions/collectors/Table.internal.d.ts.map +1 -0
  84. package/dist/definitions/collectors/Trigger.internal.d.ts +5 -0
  85. package/dist/definitions/collectors/Trigger.internal.d.ts.map +1 -0
  86. package/dist/definitions/collectors/Type.internal.d.ts +11 -0
  87. package/dist/definitions/collectors/Type.internal.d.ts.map +1 -0
  88. package/dist/definitions/collectors/View.internal.d.ts +10 -0
  89. package/dist/definitions/collectors/View.internal.d.ts.map +1 -0
  90. package/dist/definitions/handles.d.ts +121 -0
  91. package/dist/definitions/handles.d.ts.map +1 -0
  92. package/dist/index.d.ts +21 -0
  93. package/dist/index.d.ts.map +1 -0
  94. package/dist/index.js +2 -0
  95. package/dist/index.js.map +1 -0
  96. package/dist/index.mjs +353 -0
  97. package/dist/index.mjs.map +1 -0
  98. package/dist/templates/cli/auth.cli.template.ts +95 -0
  99. package/dist/templates/cli/minimal.cli.template.ts +5 -0
  100. package/dist/types.d.ts +18 -0
  101. package/dist/types.d.ts.map +1 -0
  102. package/package.json +38 -0
  103. package/templates/cli/auth.cli.template.ts +95 -0
  104. package/templates/cli/minimal.cli.template.ts +5 -0
package/README.md ADDED
@@ -0,0 +1,17 @@
1
+ # @dbmason/core
2
+
3
+ The Dbmason Core Kernel: Database-agnostic schema analysis and planning.
4
+
5
+ Dbmason is a universal database schema management tool that brings code-first principles to database architecture.
6
+
7
+ ## Features
8
+
9
+ - **Canonical Architecture**: Clear separation of intent, truth, and change.
10
+ - **Dialect Agnostic**: Core logic is separated from database-specific emitters.
11
+ - **Type-Safe**: Built with TypeScript for maximum reliability.
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install @dbmason/core
17
+ ```
@@ -0,0 +1,31 @@
1
+ function i(t) {
2
+ return t instanceof e ? { ctx: t } : t;
3
+ }
4
+ class e {
5
+ constructor(s) {
6
+ this.tables = /* @__PURE__ */ new Map(), this.types = /* @__PURE__ */ new Map(), this.views = /* @__PURE__ */ new Map(), this.materializedViews = /* @__PURE__ */ new Map(), this.procedures = /* @__PURE__ */ new Map(), this.functions = /* @__PURE__ */ new Map(), this.triggers = /* @__PURE__ */ new Map(), this.roles = /* @__PURE__ */ new Map(), this.policies = /* @__PURE__ */ new Map(), this.grants = /* @__PURE__ */ new Map(), this.indexes = /* @__PURE__ */ new Map(), this.constraints = /* @__PURE__ */ new Map(), this.crons = /* @__PURE__ */ new Map(), this.extensions = /* @__PURE__ */ new Map(), this.config = s || {}, this.config.dialect && typeof this.config.dialect.setContext == "function" && this.config.dialect.setContext(this);
7
+ }
8
+ snapshot() {
9
+ return {
10
+ tables: Object.fromEntries(this.tables),
11
+ types: Object.fromEntries(this.types),
12
+ procedures: Object.fromEntries(this.procedures),
13
+ functions: Object.fromEntries(this.functions),
14
+ views: Object.fromEntries(this.views),
15
+ materializedViews: Object.fromEntries(this.materializedViews),
16
+ extensions: Object.fromEntries(this.extensions),
17
+ roles: Object.fromEntries(this.roles),
18
+ grants: Object.fromEntries(this.grants),
19
+ crons: Object.fromEntries(this.crons),
20
+ policies: Object.fromEntries(this.policies),
21
+ triggers: Object.fromEntries(this.triggers),
22
+ hashes: {}
23
+ // To be implemented or handled by compiler
24
+ };
25
+ }
26
+ }
27
+ export {
28
+ e as D,
29
+ i as r
30
+ };
31
+ //# sourceMappingURL=DbmasonContext-Baf-v6-B.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DbmasonContext-Baf-v6-B.mjs","sources":["../src/compiler/DbmasonContext.ts"],"sourcesContent":["import { \n TableNode, \n ConstraintNode, \n IndexNode,\n TypeNode,\n ProcedureNode,\n FunctionNode,\n ViewNode,\n MaterializedViewNode,\n TriggerNode,\n PolicyNode,\n RoleNode,\n CronNode,\n ExtensionNode,\n GrantNode\n} from '../ast/nodes';\nimport { DbmasonDialect } from './Dialect';\n\nexport interface DbmasonConfig {\n dialect?: DbmasonDialect;\n connectionString?: string;\n schema?: string;\n paths?: {\n migrations?: string;\n client?: string;\n };\n}\n\nexport interface DbmasonScope {\n ctx: DbmasonContext;\n moduleName?: string;\n}\n\nexport function resolveScope(scope: DbmasonContext | DbmasonScope): DbmasonScope {\n return scope instanceof DbmasonContext ? { ctx: scope } : scope;\n}\n\nexport class DbmasonContext {\n // Core schema objects\n tables = new Map<string, TableNode>();\n types = new Map<string, TypeNode>();\n views = new Map<string, ViewNode>();\n materializedViews = new Map<string, MaterializedViewNode>();\n\n // Executable logic\n procedures = new Map<string, ProcedureNode>();\n functions = new Map<string, FunctionNode>();\n triggers = new Map<string, TriggerNode>();\n\n // Security & access control\n roles = new Map<string, RoleNode>();\n policies = new Map<string, PolicyNode>();\n grants = new Map<string, GrantNode>();\n\n // Indexing & performance\n indexes = new Map<string, IndexNode>();\n constraints = new Map<string, ConstraintNode>();\n\n // Eventing & async\n crons = new Map<string, CronNode>(); // pg_cron jobs\n\n extensions = new Map<string, ExtensionNode>();\n\n\n\n public config: DbmasonConfig;\n\n constructor(config?: DbmasonConfig) {\n this.config = config || {};\n if (this.config.dialect && typeof this.config.dialect.setContext === 'function') {\n this.config.dialect.setContext(this);\n }\n }\n\n snapshot() {\n return {\n tables: Object.fromEntries(this.tables),\n types: Object.fromEntries(this.types),\n procedures: Object.fromEntries(this.procedures),\n functions: Object.fromEntries(this.functions),\n views: Object.fromEntries(this.views),\n materializedViews: Object.fromEntries(this.materializedViews),\n extensions: Object.fromEntries(this.extensions),\n roles: Object.fromEntries(this.roles),\n grants: Object.fromEntries(this.grants),\n crons: Object.fromEntries(this.crons),\n policies: Object.fromEntries(this.policies),\n triggers: Object.fromEntries(this.triggers),\n hashes: {} // To be implemented or handled by compiler\n };\n }\n}\n"],"names":["resolveScope","scope","DbmasonContext","config"],"mappings":"AAiCO,SAASA,EAAaC,GAAoD;AAC7E,SAAOA,aAAiBC,IAAiB,EAAE,KAAKD,MAAUA;AAC9D;AAEO,MAAMC,EAAe;AAAA,EA8BxB,YAAYC,GAAwB;AA5BpC,SAAA,6BAAa,IAAA,GACb,KAAA,4BAAY,IAAA,GACZ,KAAA,4BAAY,IAAA,GACZ,KAAA,wCAAwB,IAAA,GAGxB,KAAA,iCAAiB,IAAA,GACjB,KAAA,gCAAgB,IAAA,GAChB,KAAA,+BAAe,IAAA,GAGf,KAAA,4BAAY,IAAA,GACZ,KAAA,+BAAe,IAAA,GACf,KAAA,6BAAa,IAAA,GAGb,KAAA,8BAAc,IAAA,GACd,KAAA,kCAAkB,IAAA,GAGlB,KAAA,4BAAY,IAAA,GAEZ,KAAA,iCAAiB,IAAA,GAOb,KAAK,SAASA,KAAU,CAAA,GACpB,KAAK,OAAO,WAAW,OAAO,KAAK,OAAO,QAAQ,cAAe,cACjE,KAAK,OAAO,QAAQ,WAAW,IAAI;AAAA,EAE3C;AAAA,EAEA,WAAW;AACP,WAAO;AAAA,MACH,QAAQ,OAAO,YAAY,KAAK,MAAM;AAAA,MACtC,OAAO,OAAO,YAAY,KAAK,KAAK;AAAA,MACpC,YAAY,OAAO,YAAY,KAAK,UAAU;AAAA,MAC9C,WAAW,OAAO,YAAY,KAAK,SAAS;AAAA,MAC5C,OAAO,OAAO,YAAY,KAAK,KAAK;AAAA,MACpC,mBAAmB,OAAO,YAAY,KAAK,iBAAiB;AAAA,MAC5D,YAAY,OAAO,YAAY,KAAK,UAAU;AAAA,MAC9C,OAAO,OAAO,YAAY,KAAK,KAAK;AAAA,MACpC,QAAQ,OAAO,YAAY,KAAK,MAAM;AAAA,MACtC,OAAO,OAAO,YAAY,KAAK,KAAK;AAAA,MACpC,UAAU,OAAO,YAAY,KAAK,QAAQ;AAAA,MAC1C,UAAU,OAAO,YAAY,KAAK,QAAQ;AAAA,MAC1C,QAAQ,CAAA;AAAA;AAAA,IAAC;AAAA,EAEjB;AACJ;"}
@@ -0,0 +1,2 @@
1
+ "use strict";function i(t){return t instanceof s?{ctx:t}:t}class s{constructor(e){this.tables=new Map,this.types=new Map,this.views=new Map,this.materializedViews=new Map,this.procedures=new Map,this.functions=new Map,this.triggers=new Map,this.roles=new Map,this.policies=new Map,this.grants=new Map,this.indexes=new Map,this.constraints=new Map,this.crons=new Map,this.extensions=new Map,this.config=e||{},this.config.dialect&&typeof this.config.dialect.setContext=="function"&&this.config.dialect.setContext(this)}snapshot(){return{tables:Object.fromEntries(this.tables),types:Object.fromEntries(this.types),procedures:Object.fromEntries(this.procedures),functions:Object.fromEntries(this.functions),views:Object.fromEntries(this.views),materializedViews:Object.fromEntries(this.materializedViews),extensions:Object.fromEntries(this.extensions),roles:Object.fromEntries(this.roles),grants:Object.fromEntries(this.grants),crons:Object.fromEntries(this.crons),policies:Object.fromEntries(this.policies),triggers:Object.fromEntries(this.triggers),hashes:{}}}}exports.DbmasonContext=s;exports.resolveScope=i;
2
+ //# sourceMappingURL=DbmasonContext-Dw0gG7AV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DbmasonContext-Dw0gG7AV.js","sources":["../src/compiler/DbmasonContext.ts"],"sourcesContent":["import { \n TableNode, \n ConstraintNode, \n IndexNode,\n TypeNode,\n ProcedureNode,\n FunctionNode,\n ViewNode,\n MaterializedViewNode,\n TriggerNode,\n PolicyNode,\n RoleNode,\n CronNode,\n ExtensionNode,\n GrantNode\n} from '../ast/nodes';\nimport { DbmasonDialect } from './Dialect';\n\nexport interface DbmasonConfig {\n dialect?: DbmasonDialect;\n connectionString?: string;\n schema?: string;\n paths?: {\n migrations?: string;\n client?: string;\n };\n}\n\nexport interface DbmasonScope {\n ctx: DbmasonContext;\n moduleName?: string;\n}\n\nexport function resolveScope(scope: DbmasonContext | DbmasonScope): DbmasonScope {\n return scope instanceof DbmasonContext ? { ctx: scope } : scope;\n}\n\nexport class DbmasonContext {\n // Core schema objects\n tables = new Map<string, TableNode>();\n types = new Map<string, TypeNode>();\n views = new Map<string, ViewNode>();\n materializedViews = new Map<string, MaterializedViewNode>();\n\n // Executable logic\n procedures = new Map<string, ProcedureNode>();\n functions = new Map<string, FunctionNode>();\n triggers = new Map<string, TriggerNode>();\n\n // Security & access control\n roles = new Map<string, RoleNode>();\n policies = new Map<string, PolicyNode>();\n grants = new Map<string, GrantNode>();\n\n // Indexing & performance\n indexes = new Map<string, IndexNode>();\n constraints = new Map<string, ConstraintNode>();\n\n // Eventing & async\n crons = new Map<string, CronNode>(); // pg_cron jobs\n\n extensions = new Map<string, ExtensionNode>();\n\n\n\n public config: DbmasonConfig;\n\n constructor(config?: DbmasonConfig) {\n this.config = config || {};\n if (this.config.dialect && typeof this.config.dialect.setContext === 'function') {\n this.config.dialect.setContext(this);\n }\n }\n\n snapshot() {\n return {\n tables: Object.fromEntries(this.tables),\n types: Object.fromEntries(this.types),\n procedures: Object.fromEntries(this.procedures),\n functions: Object.fromEntries(this.functions),\n views: Object.fromEntries(this.views),\n materializedViews: Object.fromEntries(this.materializedViews),\n extensions: Object.fromEntries(this.extensions),\n roles: Object.fromEntries(this.roles),\n grants: Object.fromEntries(this.grants),\n crons: Object.fromEntries(this.crons),\n policies: Object.fromEntries(this.policies),\n triggers: Object.fromEntries(this.triggers),\n hashes: {} // To be implemented or handled by compiler\n };\n }\n}\n"],"names":["resolveScope","scope","DbmasonContext","config"],"mappings":"aAiCO,SAASA,EAAaC,EAAoD,CAC7E,OAAOA,aAAiBC,EAAiB,CAAE,IAAKD,GAAUA,CAC9D,CAEO,MAAMC,CAAe,CA8BxB,YAAYC,EAAwB,CA5BpC,KAAA,WAAa,IACb,KAAA,UAAY,IACZ,KAAA,UAAY,IACZ,KAAA,sBAAwB,IAGxB,KAAA,eAAiB,IACjB,KAAA,cAAgB,IAChB,KAAA,aAAe,IAGf,KAAA,UAAY,IACZ,KAAA,aAAe,IACf,KAAA,WAAa,IAGb,KAAA,YAAc,IACd,KAAA,gBAAkB,IAGlB,KAAA,UAAY,IAEZ,KAAA,eAAiB,IAOb,KAAK,OAASA,GAAU,CAAA,EACpB,KAAK,OAAO,SAAW,OAAO,KAAK,OAAO,QAAQ,YAAe,YACjE,KAAK,OAAO,QAAQ,WAAW,IAAI,CAE3C,CAEA,UAAW,CACP,MAAO,CACH,OAAQ,OAAO,YAAY,KAAK,MAAM,EACtC,MAAO,OAAO,YAAY,KAAK,KAAK,EACpC,WAAY,OAAO,YAAY,KAAK,UAAU,EAC9C,UAAW,OAAO,YAAY,KAAK,SAAS,EAC5C,MAAO,OAAO,YAAY,KAAK,KAAK,EACpC,kBAAmB,OAAO,YAAY,KAAK,iBAAiB,EAC5D,WAAY,OAAO,YAAY,KAAK,UAAU,EAC9C,MAAO,OAAO,YAAY,KAAK,KAAK,EACpC,OAAQ,OAAO,YAAY,KAAK,MAAM,EACtC,MAAO,OAAO,YAAY,KAAK,KAAK,EACpC,SAAU,OAAO,YAAY,KAAK,QAAQ,EAC1C,SAAU,OAAO,YAAY,KAAK,QAAQ,EAC1C,OAAQ,CAAA,CAAC,CAEjB,CACJ"}
@@ -0,0 +1,192 @@
1
+ export type PolicyMethod = 'rbac' | 'rls' | 'hybrid';
2
+ export type AstNodeKind = 'Table' | 'Column' | 'Procedure' | 'Function' | 'View' | 'MaterializedView' | 'Policy' | 'Trigger' | 'Index' | 'Constraint' | 'Type' | 'Cron' | 'Extension' | 'Role' | 'Grant';
3
+ export interface BaseNode {
4
+ kind: AstNodeKind;
5
+ name: string;
6
+ module?: string;
7
+ }
8
+ export interface RoutineInput {
9
+ args?: Record<string, any>;
10
+ returns?: any;
11
+ language?: string;
12
+ body: string;
13
+ }
14
+ export interface Snapshot {
15
+ tables: Record<string, BaseNode>;
16
+ procedures: Record<string, BaseNode>;
17
+ functions: Record<string, BaseNode>;
18
+ views: Record<string, BaseNode>;
19
+ materializedViews: Record<string, BaseNode>;
20
+ types: Record<string, BaseNode>;
21
+ crons: Record<string, BaseNode>;
22
+ extensions: Record<string, BaseNode>;
23
+ roles: Record<string, BaseNode>;
24
+ grants: Record<string, BaseNode>;
25
+ policies: Record<string, BaseNode>;
26
+ triggers: Record<string, BaseNode>;
27
+ hashes: Record<string, string>;
28
+ }
29
+ export interface AnalyzedSchema {
30
+ tables: Map<string, BaseNode>;
31
+ types: Map<string, BaseNode>;
32
+ procedures: Map<string, BaseNode>;
33
+ functions: Map<string, BaseNode>;
34
+ views: Map<string, BaseNode>;
35
+ materializedViews: Map<string, BaseNode>;
36
+ extensions: Map<string, BaseNode>;
37
+ roles: Map<string, BaseNode>;
38
+ grants: Map<string, BaseNode>;
39
+ crons: Map<string, BaseNode>;
40
+ policies: Map<string, BaseNode>;
41
+ triggers: Map<string, BaseNode>;
42
+ order: string[];
43
+ }
44
+ export type PlanAction = 'create' | 'alter' | 'drop' | 'replace' | 'comment';
45
+ export interface PlanStep {
46
+ action: PlanAction;
47
+ node: BaseNode;
48
+ diff?: any;
49
+ }
50
+ export type ExecutionPlan = PlanStep[];
51
+ /**
52
+ * Node Specific Types
53
+ */
54
+ export interface ColumnNode extends BaseNode {
55
+ kind: 'Column';
56
+ type: string;
57
+ notNull?: boolean;
58
+ primaryKey?: boolean;
59
+ unique?: boolean;
60
+ default?: string;
61
+ check?: string;
62
+ references?: {
63
+ module?: string;
64
+ table: string;
65
+ column: string;
66
+ onDelete?: 'CASCADE' | 'RESTRICT' | 'SET NULL' | 'SET DEFAULT' | 'NO ACTION';
67
+ onUpdate?: 'CASCADE' | 'RESTRICT' | 'SET NULL' | 'SET DEFAULT' | 'NO ACTION';
68
+ };
69
+ options?: unknown;
70
+ }
71
+ export interface IndexNode extends BaseNode {
72
+ kind: 'Index';
73
+ table: string;
74
+ columns: string[];
75
+ unique?: boolean;
76
+ method?: string;
77
+ where?: string;
78
+ expression?: string;
79
+ }
80
+ export interface ConstraintNode extends BaseNode {
81
+ kind: 'Constraint';
82
+ table: string;
83
+ type: 'check' | 'foreign_key' | 'unique' | 'primary_key';
84
+ definition: string;
85
+ description?: string;
86
+ }
87
+ export interface TriggerNode extends BaseNode {
88
+ kind: 'Trigger';
89
+ table: string;
90
+ events: string[];
91
+ when: string;
92
+ functionName: string;
93
+ functionArgs?: string[];
94
+ forEach?: string;
95
+ condition?: string;
96
+ body?: string;
97
+ }
98
+ export type TriggerEvent = 'INSERT' | 'UPDATE' | 'DELETE' | 'TRUNCATE';
99
+ export type TriggerWhen = 'BEFORE' | 'AFTER' | 'INSTEAD OF';
100
+ export type TriggerForEach = 'ROW' | 'STATEMENT';
101
+ export interface PolicyNode extends BaseNode {
102
+ kind: 'Policy';
103
+ table: string;
104
+ method: PolicyMethod;
105
+ rbac?: {
106
+ roles: string[];
107
+ operations: DbOperation[];
108
+ }[];
109
+ sql?: string;
110
+ }
111
+ export type DbOperation = 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE' | 'TRUNCATE' | 'REFERENCES' | 'TRIGGER' | 'ALL';
112
+ export interface TableNode extends BaseNode {
113
+ kind: 'Table';
114
+ name: string;
115
+ columns: Record<string, ColumnNode>;
116
+ indexes: IndexNode[];
117
+ constraints: ConstraintNode[];
118
+ policies: PolicyNode[];
119
+ triggers: TriggerNode[];
120
+ migration?: 'safe' | 'destructive';
121
+ options?: unknown;
122
+ module?: string;
123
+ }
124
+ export interface AnalyzedTableNode extends TableNode {
125
+ dependencies: string[];
126
+ rls: {
127
+ enabled: boolean;
128
+ policies: PolicyNode[];
129
+ };
130
+ }
131
+ export interface ProcedureNode extends BaseNode {
132
+ kind: 'Procedure';
133
+ args: Record<string, string>;
134
+ returns: string;
135
+ language: string;
136
+ body: string;
137
+ }
138
+ export interface FunctionNode extends BaseNode {
139
+ kind: 'Function';
140
+ args: Record<string, string>;
141
+ returns: string;
142
+ language: string;
143
+ body: string;
144
+ }
145
+ export interface ViewNode extends BaseNode {
146
+ kind: 'View' | 'MaterializedView';
147
+ query: string;
148
+ }
149
+ export interface MaterializedViewNode extends ViewNode {
150
+ kind: 'MaterializedView';
151
+ }
152
+ export interface TypeNode extends BaseNode {
153
+ kind: 'Type';
154
+ name: string;
155
+ type: 'enum' | 'composite';
156
+ values?: string[];
157
+ fields?: Record<string, string>;
158
+ }
159
+ export type GrantObjectKind = 'TABLE' | 'SEQUENCE' | 'FUNCTION' | 'PROCEDURE' | 'SCHEMA' | 'DATABASE';
160
+ export interface GrantNode extends BaseNode {
161
+ kind: 'Grant';
162
+ privileges: string[];
163
+ on: GrantObjectKind;
164
+ to: string;
165
+ object: string;
166
+ }
167
+ export interface CronNode extends BaseNode {
168
+ kind: 'Cron';
169
+ schedule: string;
170
+ command: string;
171
+ }
172
+ export interface ExtensionNode extends BaseNode {
173
+ kind: 'Extension';
174
+ schema?: string;
175
+ version?: string;
176
+ }
177
+ export interface RoleNode extends BaseNode {
178
+ kind: 'Role';
179
+ options?: {
180
+ login?: boolean;
181
+ superuser?: boolean;
182
+ createrole?: boolean;
183
+ createdb?: boolean;
184
+ inherit?: boolean;
185
+ password?: string;
186
+ validUntil?: string;
187
+ };
188
+ }
189
+ export interface DbmasonIntrospector {
190
+ introspect(connectionString: string): Promise<Snapshot>;
191
+ }
192
+ //# sourceMappingURL=nodes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nodes.d.ts","sourceRoot":"","sources":["../../src/ast/nodes.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAC;AAErD,MAAM,MAAM,WAAW,GACjB,OAAO,GACP,QAAQ,GACR,WAAW,GACX,UA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E,OAAO,CAAC;IACd,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,EAAE,EAAE,eAAe,CAAC;IACpB,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,QAAS,SAAQ,QAAQ;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,aAAc,SAAQ,QAAQ;IAC3C,IAAI,EAAE,WAAW,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,QAAS,SAAQ,QAAQ;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE;QACN,KAAK,CAAC,EAAE,OAAO,CAAC;QAChB,SAAS,CAAC,EAAE,OAAO,CAAC;QACpB,UAAU,CAAC,EAAE,OAAO,CAAC;QACrB,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,OAAO,CAAC,EAAE,OAAO,CAAC;QAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,UAAU,CAAC,EAAE,MAAM,CAAC;KACvB,CAAC;CACL;AAED,MAAM,WAAW,mBAAmB;IAChC,UAAU,CAAC,gBAAgB,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CAC3D"}
@@ -0,0 +1,2 @@
1
+ export declare function clientCommand(options: any): Promise<void>;
2
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/cli/commands/client.ts"],"names":[],"mappings":"AAIA,wBAAsB,aAAa,CAAC,OAAO,EAAE,GAAG,iBA+B/C"}
@@ -0,0 +1,2 @@
1
+ export declare function generateCommand(name?: string, options?: any): Promise<void>;
2
+ //# sourceMappingURL=generate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate.d.ts","sourceRoot":"","sources":["../../../src/cli/commands/generate.ts"],"names":[],"mappings":"AASA,wBAAsB,eAAe,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,OAAO,GAAE,GAAQ,iBAiFrE"}
@@ -0,0 +1,2 @@
1
+ export declare function initCommand(projectName: string, options: any): void;
2
+ //# sourceMappingURL=init.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../../src/cli/commands/init.ts"],"names":[],"mappings":"AAIA,wBAAgB,WAAW,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,QAuI5D"}
@@ -0,0 +1,2 @@
1
+ export declare function migrateCommand(options?: any): Promise<void>;
2
+ //# sourceMappingURL=migrate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrate.d.ts","sourceRoot":"","sources":["../../../src/cli/commands/migrate.ts"],"names":[],"mappings":"AA2DA,wBAAsB,cAAc,CAAC,OAAO,GAAE,GAAQ,iBAqDrD"}
@@ -0,0 +1,2 @@
1
+ export declare function pullCommand(options?: any): Promise<void>;
2
+ //# sourceMappingURL=pull.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pull.d.ts","sourceRoot":"","sources":["../../../src/cli/commands/pull.ts"],"names":[],"mappings":"AAkBA,wBAAsB,WAAW,CAAC,OAAO,GAAE,GAAQ,iBA2HlD"}
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/cli/index.ts"],"names":[],"mappings":""}
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env node
2
+ "use strict";const H=require("commander"),U=require("fs"),W=require("path"),B=require("child_process"),D=require("../DbmasonContext-Dw0gG7AV.js"),V=require("crypto");function C(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const n in i)if(n!=="default"){const t=Object.getOwnPropertyDescriptor(i,n);Object.defineProperty(e,n,t.get?t:{enumerable:!0,get:()=>i[n]})}}return e.default=i,Object.freeze(e)}const p=C(U),d=C(W),G=C(V);function K(i,e){const n=d.resolve(process.cwd(),i);p.existsSync(n)&&(console.error(`Directory ${i} already exists.`),process.exit(1)),p.mkdirSync(n);const t=d.join(n,"src");p.mkdirSync(t),p.mkdirSync(d.join(n,"migrations"));const s=d.join(n,"dbmason");p.mkdirSync(s);const o=d.resolve(__dirname,"../../templates/cli"),r=(e.template||"auth").toLowerCase(),c=r.endsWith(".ts")?r:`${r}.ts`,a=d.join(o,c);p.existsSync(a)||(console.error(`Template '${r}' not found in ${o}`),process.exit(1));const l=p.readFileSync(a,"utf8");p.writeFileSync(d.join(s,"schema.ts"),l.trim()),p.writeFileSync(d.join(s,"helpers.ts"),`import { DbmasonContext, definePolicy, DbOperation, TableReference } from '@dbmason/postgres';
3
+
4
+ /**
5
+ * RLS Helper: Restricts WHICH ROWS a user can see.
6
+ */
7
+ export function defineRLSPolicy(ctx: DbmasonContext, table: TableReference, name: string) {
8
+ definePolicy(table, name, {
9
+ method: 'rls',
10
+ sql: \\\`(SELECT role FROM users WHERE id = current_setting('app.user_id')::uuid) = 'admin'\\\`
11
+ });
12
+ }
13
+
14
+ /**
15
+ * RBAC Helper: Restricts WHICH ACTIONS (SELECT, INSERT, etc.) a role can perform.
16
+ */
17
+ export function defineRBACPolicy(ctx: DbmasonContext, table: TableReference, role: string, operations: DbOperation[]) {
18
+ definePolicy(table, \\\`\\\${role}_rbac\\\`, {
19
+ method: 'rbac',
20
+ rbac: [{ roles: [role], operations }]
21
+ });
22
+ }
23
+ `.trim()),p.writeFileSync(d.join(s,"index.ts"),`import { DbmasonContext } from '@dbmason/core';
24
+ import { PostgresDialect } from '@dbmason/postgres';
25
+ import { setupSchema } from './schema';
26
+
27
+ const ctx = new DbmasonContext();
28
+
29
+ // Setup Authentication (Tables, Procedures, Crons)
30
+ setupSchema(ctx);
31
+
32
+ export const dialect = new PostgresDialect(ctx);
33
+ export default ctx;
34
+ `.trim()),p.writeFileSync(d.join(n,"docker-compose.yml"),`
35
+ services:
36
+ db:
37
+ image: postgres:latest
38
+ environment:
39
+ POSTGRES_USER: postgres
40
+ POSTGRES_PASSWORD: postgres
41
+ POSTGRES_DB: postgres
42
+ ports:
43
+ - "5432:5432"
44
+ volumes:
45
+ - pgdata:/var/lib/postgresql/data
46
+
47
+ volumes:
48
+ pgdata:
49
+ `.trim()),p.writeFileSync(d.join(n,".env"),"DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres".trim());const T={compilerOptions:{target:"ES2020",module:"CommonJS",moduleResolution:"node",esModuleInterop:!0,resolveJsonModule:!0,skipLibCheck:!0,strict:!0,outDir:"./dist",rootDir:"./"}};p.writeFileSync(d.join(n,"tsconfig.json"),JSON.stringify(T,null,2));const y={name:i,version:"1.0.0",scripts:{generate:"dbmason generate",migrate:"dbmason migrate","db:up":"docker compose up -d","db:down":"docker compose down"},dependencies:{"@dbmason/core":"file:../packages/core","@dbmason/postgres":"file:../packages/postgres",pg:"^8.11.0",dotenv:"^16.3.1"},devDependencies:{typescript:"^5.0.0","ts-node":"^10.9.1"}};p.writeFileSync(d.join(n,"package.json"),JSON.stringify(y,null,2)),console.log(`Dbmason project ${i} initialized with default Auth template.`);try{console.log("Installing dependencies..."),B.execSync("npm install",{cwd:n,stdio:"inherit"}),console.log("Dependencies installed successfully.")}catch(w){console.error("Failed to install dependencies:",w)}}class Q{constructor(e){this.ctx=e}resolveOrder(){const e=[],n=new Set,t=new Set;for(const r of this.ctx.extensions.keys())e.push(`extension:${r}`);for(const r of this.ctx.roles.keys())e.push(`role:${r}`);const s=Array.from(this.ctx.types.keys());for(const r of s)this.visit(`type:${r}`,n,t,e);const o=Array.from(this.ctx.tables.keys());for(const r of o)this.visit(`table:${r}`,n,t,e);for(const r of this.ctx.views.keys())e.push(`view:${r}`);for(const r of this.ctx.procedures.keys())e.push(`procedure:${r}`);for(const r of this.ctx.functions.keys())e.push(`function:${r}`);for(const r of this.ctx.crons.keys())e.push(`cron:${r}`);for(const r of this.ctx.policies.keys())e.push(`policy:${r}`);for(const r of this.ctx.triggers.keys())e.push(`trigger:${r}`);for(const r of this.ctx.grants.keys())e.push(`grant:${r}`);return e}visit(e,n,t,s){if(n.has(e))return;if(t.has(e))throw new Error(`Circular dependency detected: ${e}`);t.add(e);const[o,r]=e.split(":");if(o==="table"){const c=this.ctx.tables.get(r);if(c)for(const a of Object.values(c.columns))a.references&&this.visit(`table:${a.references.table}`,n,t,s),this.ctx.types.has(a.type)&&this.visit(`type:${a.type}`,n,t,s)}t.delete(e),n.add(e),s.push(e)}}class j{constructor(e,n){this.ctx=e,this.dialect=n,this.dependencyResolver=new Q(e)}analyze(){const e=new Map;for(const[s,o]of this.ctx.tables.entries())e.set(s,this.dialect.analyzeTable(o));const n=this.dependencyResolver.resolveOrder();return{tables:e,types:new Map(this.ctx.types),views:new Map(this.ctx.views),materializedViews:new Map(this.ctx.materializedViews),procedures:new Map(this.ctx.procedures),functions:new Map(this.ctx.functions),extensions:new Map(this.ctx.extensions),roles:new Map(this.ctx.roles),grants:new Map(this.ctx.grants),crons:new Map(this.ctx.crons),policies:new Map(this.ctx.policies),triggers:new Map(this.ctx.triggers),order:n}}}class Y{constructor(e,n){this.analyzedSchema=e,this.oldSnapshot=n}plan(){const e=[];for(const n of this.analyzedSchema.order){const[t,s]=n.split(":");switch(t){case"extension":this.planExtension(s,e);break;case"type":this.planType(s,e);break;case"table":this.planTable(s,e);break;case"view":this.planView(s,e);break;case"procedure":this.planProcedure(s,e);break;case"function":this.planFunction(s,e);break;case"cron":this.planCron(s,e);break;case"policy":this.planPolicy(s,e);break;case"trigger":this.planTrigger(s,e);break;case"role":this.planRole(s,e);break;case"grant":this.planGrant(s,e);break}}return this.oldSnapshot&&this.planDeletions(e),e}planExtension(e,n){const t=this.analyzedSchema.extensions.get(e),s=this.oldSnapshot?.extensions[e];t&&(!s||JSON.stringify(t)!==JSON.stringify(s))&&n.push({action:"create",node:t})}planType(e,n){const t=this.analyzedSchema.types.get(e),s=this.oldSnapshot?.types[e];t&&(!s||JSON.stringify(t)!==JSON.stringify(s))&&n.push({action:"create",node:t})}planTable(e,n){const t=this.analyzedSchema.tables.get(e);if(!t)return;const s=this.oldSnapshot?.tables[e];s?JSON.stringify(t)!==JSON.stringify(s)&&n.push({action:"alter",node:t,diff:{old:s}}):n.push({action:"create",node:t})}planView(e,n){const t=this.analyzedSchema.views.get(e);if(!t)return;const s=this.oldSnapshot?.views[e];(!s||JSON.stringify(t)!==JSON.stringify(s))&&n.push({action:"replace",node:t})}planProcedure(e,n){const t=this.analyzedSchema.procedures.get(e);if(!t)return;const s=this.oldSnapshot?.hashes?.[e],o=require("crypto").createHash("md5").update(t.body).digest("hex");(!s||s!==o)&&n.push({action:"replace",node:t})}planFunction(e,n){const t=this.analyzedSchema.functions.get(e);if(!t)return;const s=this.oldSnapshot?.hashes?.[e],o=require("crypto").createHash("md5").update(t.body).digest("hex");(!s||s!==o)&&n.push({action:"replace",node:t})}planCron(e,n){const t=this.analyzedSchema.crons.get(e),s=this.oldSnapshot?.crons[e];t&&(!s||JSON.stringify(t)!==JSON.stringify(s))&&n.push({action:"create",node:t})}planPolicy(e,n){const t=this.analyzedSchema.policies.get(e),s=this.oldSnapshot?.policies?.[e];t&&(!s||JSON.stringify(t)!==JSON.stringify(s))&&n.push({action:"create",node:t})}planTrigger(e,n){const t=this.analyzedSchema.triggers.get(e),s=this.oldSnapshot?.triggers?.[e];t&&(!s||JSON.stringify(t)!==JSON.stringify(s))&&n.push({action:"create",node:t})}planRole(e,n){const t=this.analyzedSchema.roles.get(e),s=this.oldSnapshot?.roles?.[e];t&&(!s||JSON.stringify(t)!==JSON.stringify(s))&&n.push({action:"create",node:t})}planGrant(e,n){const t=this.analyzedSchema.grants.get(e),s=this.oldSnapshot?.grants?.[e];t&&(!s||JSON.stringify(t)!==JSON.stringify(s))&&n.push({action:"create",node:t})}planDeletions(e){for(const n of Object.keys(this.oldSnapshot.tables))this.analyzedSchema.tables.has(n)||e.push({action:"drop",node:this.oldSnapshot.tables[n]});for(const n of Object.keys(this.oldSnapshot.roles||{}))this.analyzedSchema.roles.has(n)||e.push({action:"drop",node:this.oldSnapshot.roles[n]})}}class k{constructor(e,n){this.ctx=e,this.dialect=n}compile(e){const t=new j(this.ctx,this.dialect).analyze(),o=new Y(t,e).plan();return this.dialect.emit(o)}}function X(i,e){const n={tables:{},procedures:{},functions:{},views:{},types:{},modules:{}};function t(r){if(!r||r==="global")return n;const c=r.split(".");let a=n;for(const l of c)a.modules[l]||(a.modules[l]={tables:{},procedures:{},functions:{},views:{},types:{},modules:{}}),a=a.modules[l];return a}function s(r){if(!r)return"any";let c=r.replace(/\\"/g,"").replace(/"/g,"");return c.toUpperCase().startsWith("SETOF ")?`SETOF '${c.substring(6).trim()}'`:c}for(const r of i.tables.values()){const c=t(r.module);c.tables[r.name]={name:r.name,module:r.module,columns:Object.fromEntries(Object.entries(r.columns).map(([a,l])=>[a,{type:s(l.type),primaryKey:!!l.primaryKey,notNull:!!l.notNull}]))}}for(const r of i.procedures.values()){const c=t(r.module);c.procedures[r.name]={kind:r.kind,name:r.name,module:r.module,args:Object.fromEntries(Object.entries(r.args).map(([a,l])=>[a,s(l)])),returns:s(r.returns)}}for(const r of i.functions.values()){const c=t(r.module);c.functions[r.name]={kind:r.kind,name:r.name,module:r.module,args:Object.fromEntries(Object.entries(r.args).map(([a,l])=>[a,s(l)])),returns:s(r.returns)}}for(const r of i.views.values()){const c=t(r.module);c.views[r.name]={name:r.name,module:r.module,columns:{}}}for(const r of i.types.values()){const c=t(r.module);c.types[r.name]={name:r.name,kind:r.type,module:r.module,values:r.values,fields:r.fields?Object.fromEntries(Object.entries(r.fields).map(([a,l])=>[a,s(l)])):void 0}}const o=d.join(e,"dbmason.metadata.json");return p.existsSync(e)||p.mkdirSync(e,{recursive:!0}),p.writeFileSync(o,JSON.stringify(n,null,2)),{configPath:o}}class R{static build(e){const n={},t=new Map([...e.procedures,...e.functions]);for(const[s,o]of t.entries()){const r=o.body||"";n[s]=G.createHash("md5").update(r).digest("hex")}return{tables:Object.fromEntries(e.tables),procedures:Object.fromEntries(e.procedures),functions:Object.fromEntries(e.functions),views:Object.fromEntries(e.views),materializedViews:Object.fromEntries(e.materializedViews),types:Object.fromEntries(e.types),crons:Object.fromEntries(e.crons),extensions:Object.fromEntries(e.extensions),roles:Object.fromEntries(e.roles),grants:Object.fromEntries(e.grants),policies:Object.fromEntries(e.policies),triggers:Object.fromEntries(e.triggers),hashes:n}}}async function Z(i,e={}){const n=d.resolve(process.cwd(),"dbmason/index.ts");p.existsSync(n)||(console.error("dbmason/index.ts not found."),process.exit(1));try{require("ts-node").register({transpileOnly:!0});const t=require(n),s=t.default||t.ctx;let o=t.dialect;if(!(s instanceof D.DbmasonContext)&&s?.constructor?.name!=="DbmasonContext")throw new Error("dbmason/index.ts must export a DbmasonContext.");if(!o&&s.config?.dialect&&(o=s.config.dialect),!o)throw new Error('dbmason/index.ts must export a "dialect" or pass it to DbmasonContext constructor.');const c=new j(s,o).analyze(),a=d.resolve(process.cwd(),"node_modules/@dbmason/core"),l=d.join(a,".dbmason-snapshot.json");let h;p.existsSync(l)&&(h=JSON.parse(p.readFileSync(l,"utf8")));const f=new k(s,o).compile(h),g=f.split(`
50
+ `).filter(y=>!y.trim().startsWith("--")).join(`
51
+ `).trim();if(g){if((g.toLowerCase().includes("drop table")||g.toLowerCase().includes("drop column"))&&(e.allowDestructive||(console.error("Destructive changes detected! Use --allow-destructive to confirm."),process.exit(1))),e.dry){console.log("-- Dry Run Output (No files written) --"),console.log(f);return}const y=d.resolve(process.cwd(),s.config.paths?.migrations||"migrations");p.existsSync(y)||p.mkdirSync(y,{recursive:!0});const w=`${Date.now()}_${i||"migration"}.sql`;p.writeFileSync(d.join(y,w),f);const b=R.build(c);p.existsSync(a)||p.mkdirSync(a,{recursive:!0}),p.writeFileSync(l,JSON.stringify(b,null,2)),console.log(`Generated migration: ${d.relative(process.cwd(),d.join(y,w))}`)}else console.log("No changes detected.");const T=s.config.paths?.client?d.resolve(process.cwd(),s.config.paths.client):process.cwd();X(c,T)}catch(t){console.error("Generation failed:",t.message),process.exit(1)}}class ee{constructor(e,n="migrations"){this.driver=e,this.migrationDir=d.resolve(process.cwd(),n)}async runMigrations(){await this.driver.connect();try{await this.driver.query(`
52
+ CREATE TABLE IF NOT EXISTS dbmason_migrations (
53
+ id SERIAL PRIMARY KEY,
54
+ name TEXT NOT NULL UNIQUE,
55
+ applied_at TIMESTAMPTZ DEFAULT NOW()
56
+ );
57
+ `);const e=await this.driver.query("SELECT name FROM dbmason_migrations"),n=new Set(e.rows.map(s=>s.name));if(!p.existsSync(this.migrationDir))return;const t=p.readdirSync(this.migrationDir).sort();for(const s of t)if(s.endsWith(".sql")&&!n.has(s)){const o=p.readFileSync(d.join(this.migrationDir,s),"utf-8");console.log(`Running migration: ${s}`),await this.driver.beginTransaction();try{await this.driver.query(o),await this.driver.query("INSERT INTO dbmason_migrations (name) VALUES ($1)",[s]),await this.driver.commitTransaction()}catch(r){throw await this.driver.rollbackTransaction(),console.error(`Error in migration ${s}:`,r),r}}else s.endsWith(".sql")}finally{await this.driver.close()}}}async function te(i={}){const e=d.resolve(process.cwd(),"dbmason/index.ts"),n=d.resolve(process.cwd(),".env");if(p.existsSync(n)){const t=p.readFileSync(n,"utf8");for(const s of t.split(`
58
+ `)){const[o,...r]=s.split("=");o&&r.length>0&&(process.env[o.trim()]=r.join("=").trim().replace(/^['"]|['"]$/g,""))}}p.existsSync(e)||(console.error("dbmason/index.ts not found."),process.exit(1));try{require("ts-node").register({transpileOnly:!0});const t=require(e),s=t.default||t.ctx;let o=t.dialect;if(!o&&s.config?.dialect&&(o=s.config.dialect),!o)throw new Error('dbmason/index.ts must export a "dialect" or pass it to DbmasonContext constructor.');const r=s.config?.connectionString||process.env.DATABASE_URL;if(!r)throw new Error("Connection string not found. Please configure it in DbmasonContext or set DATABASE_URL.");const c=o.getDriver(r);console.log("Applying migrations to database...");const a=s.config?.paths?.migrations;await new ee(c,a).runMigrations(),console.log("Migration completed successfully.")}catch(t){console.error("Migration failed:",t.message),process.exit(1)}}function se(i,e){const n={types:new Map};_(i,n);const t=["// Generated by @dbmason/core - DO NOT EDIT DIRECTLY",'import { Pool, PoolConfig, QueryResult, QueryResultRow } from "pg";',"",`/**
59
+ * Base Client Logic (Bundled)
60
+ */`,re.join(`
61
+ `),"","/**"," * Internal Helper Types"," */","export type Trigger = void; // Type alias for procedure returns","","/**"," * Database Schema Types & Enums"," */"];return q(i,t,n),t.push(""),t.push("/**"),t.push(" * Database Table & View Interfaces"," */"),A(i,t,n,""),t.push(""),t.push("/**"),t.push(" * Typed DbmasonClient"," */"),t.push("export class DbmasonClient extends StandaloneDbmasonClient {"),t.push(" constructor(options?: StandaloneDbmasonClientOptions) {"),t.push(" super(options);"),t.push(" }"),t.push(""),ne(i,t,1,n),t.push("}"),t.push(""),t.join(`
62
+ `)}function S(i,e){const n=i.replace(/['"]/g,""),t=n.split(".");if(t.length>1)return N(t.join("_"));const s=e.endsWith("_")?e:e?e+"_":"",o=oe(n);return s&&(o.startsWith(s)||n.startsWith(s))?N(n):N(s+n)}function _(i,e,n=""){if(i.types)for(const[t,s]of Object.entries(i.types)){const o=S(t,n);if(e.types.set(t,o),n){const r=n.replace(/_$/,"").replace(/_/g,".");e.types.set(`${r}.${t}`,o)}}if(i.modules)for(const[t,s]of Object.entries(i.modules))_(s,e,n+t+"_")}function q(i,e,n,t=""){if(i.types)for(const[s,o]of Object.entries(i.types)){const r=n.types.get(s)||S(s,t);if(o.kind==="enum"&&o.values){const c=o.values.map(a=>`'${a}'`).join(" | ");e.push(`export type ${r} = ${c};`)}else if(o.kind==="composite"&&o.fields){e.push(`export interface ${r} {`);for(const[c,a]of Object.entries(o.fields))e.push(` ${c}: ${v(a,n,t)};`);e.push("}")}}if(i.modules)for(const[s,o]of Object.entries(i.modules))q(o,e,n,t+s+"_")}function A(i,e,n,t=""){const s={...i.tables||{},...i.views||{}};for(const[o,r]of Object.entries(s)){const c=r,a=S(o,t);if(e.push(`export interface ${a} {`),c.columns&&Object.keys(c.columns).length>0)for(const[l,h]of Object.entries(c.columns)){const u=v(h.type,n,t);e.push(` ${l}${h.notNull?"":"?"}: ${u};`)}else e.push(" [key: string]: any;");e.push("}"),e.push("")}if(i.modules)for(const[o,r]of Object.entries(i.modules))A(r,e,n,t+o+"_")}function ne(i,e,n,t,s=""){const o=" ".repeat(n);if(i.tables)for(const[c]of Object.entries(i.tables)){const a=S(c,s);e.push(`${o}get ${c}() {`),e.push(`${o} return this.getTableHandler<${a}>("${s?s.replace(/_/g,".")+"."+c:c}");`),e.push(`${o}}`),e.push("")}if(i.views)for(const[c]of Object.entries(i.views)){const a=S(c,s);e.push(`${o}get ${c}() {`),e.push(`${o} return this.getTableHandler<${a}>("${s?s.replace(/_/g,".")+"."+c:c}");`),e.push(`${o}}`),e.push("")}const r={...i.procedures||{},...i.functions||{}};for(const[c,a]of Object.entries(r)){const l=M(a,t,s),h=z(a,t,s),u=l==="void"?"undefined":"params",f=JSON.stringify(a.args),g=a.kind==="Procedure"&&a.returns.toLowerCase()==="void";e.push(`${o}async ${c}(params?: ${l}): Promise<${h}> {`),e.push(`${o} return this.rpc("${s?s.replace(/_/g,".")+"."+c:c}", ${u}, ${f}, ${g}) as any;`),e.push(`${o}}`),e.push("")}if(i.modules)for(const[c,a]of Object.entries(i.modules))e.push(`${o}get ${c}() {`),e.push(`${o} const self = this;`),e.push(`${o} return {`),L(a,e,n+2,t,s?`${s}.${c}`:c),e.push(`${o} };`),e.push(`${o}}`),e.push("")}function L(i,e,n,t,s){const o=" ".repeat(n),r=s.replace(/\./g,"_")+"_";if(i.tables)for(const[a]of Object.entries(i.tables)){const l=S(a,r);e.push(`${o}get ${a}() { return self.getTableHandler<${l}>("${s}.${a}"); },`)}if(i.views)for(const[a]of Object.entries(i.views)){const l=S(a,r);e.push(`${o}get ${a}() { return self.getTableHandler<${l}>("${s}.${a}"); },`)}const c={...i.procedures||{},...i.functions||{}};for(const[a,l]of Object.entries(c)){const h=M(l,t,r),u=z(l,t,r),f=JSON.stringify(l.args),g=l.kind==="Procedure"&&l.returns.toLowerCase()==="void";e.push(`${o}${a}(params?: ${h}): Promise<${u}> { return self.rpc("${s}.${a}", params, ${f}, ${g}) as any; },`)}if(i.modules)for(const[a,l]of Object.entries(i.modules))e.push(`${o}get ${a}() {`),e.push(`${o} return {`),L(l,e,n+2,t,`${s}.${a}`),e.push(`${o} };`),e.push(`${o}},`)}function M(i,e,n){if(!i.args||Object.keys(i.args).length===0)return"void";const t=[];for(const[s,o]of Object.entries(i.args)){const r=o,c=r.toLowerCase().includes("default"),a=r.split(" ")[0];t.push(`${s}${c?"?":""}: ${v(a,e,n)}`)}return`{ ${t.join(", ")} }`}function z(i,e,n){const t=i.returns||"any",s=t.toLowerCase().includes("setof"),o=t.replace(/setof/i,"").replace(/'/g,"").trim(),r=v(o,e,n);return r.toLowerCase()==="trigger"?"Trigger":s?`${r}[]`:r}function v(i,e,n=""){const t=i.toLowerCase().replace(/['"]/g,"").trim();return e.types.has(t)?e.types.get(t):t.includes("serial")||t.includes("int")||t.includes("float")||t.includes("double")||t.includes("numeric")||t.includes("decimal")||t.includes("real")||t.includes("money")?"number":t.includes("bool")?"boolean":t.includes("json")?"any":t.includes("date")||t.includes("timestamp")?"Date | string":t==="void"?"void":["text","varchar","char","uuid","bytea","interval","xml","point","line","lseg","box","path","polygon","circle","cidr","inet","macaddr"].some(o=>t.includes(o))?"string":S(t,n)}function N(i){return i?i.replace(/['"]/g,"").split(/[\._-]/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""):"Any"}function oe(i){return i.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`).replace(/^_/,"")}const re=["export interface StandaloneDbmasonClientOptions {"," returnCase?: 'camel' | 'pascal' | 'snake';"," poolConfig?: PoolConfig;","}","","export type TableMethods<T> = {"," create: (data: Partial<T>) => Promise<T[]>;"," read: (filter?: Partial<T>) => Promise<T[]>;"," update: (data: Partial<T>, filter: Partial<T>) => Promise<T[]>;"," delete: (filter: Partial<T>) => Promise<T[]>;"," list: (options?: { where?: Partial<T>; limit?: number; orderBy?: string }) => Promise<T[]>;","};","","export class StandaloneDbmasonClient {"," private pool: Pool;"," private returnCase: 'camel' | 'pascal' | 'snake';",""," constructor(options?: StandaloneDbmasonClientOptions) {"," this.returnCase = options?.returnCase || 'camel';"," this.pool = new Pool(options?.poolConfig || {"," connectionString: process.env.DATABASE_URL"," });"," }",""," protected getTableHandler<T>(tableName: string): TableMethods<T> {"," return {"," create: (data: Partial<T>) => this.create<T>(tableName, data),"," read: (filter?: Partial<T>) => this.read<T>(tableName, filter),"," update: (data: Partial<T>, filter: Partial<T>) => this.update<T>(tableName, data, filter),"," delete: (filter: Partial<T>) => this.delete<T>(tableName, filter),"," list: (options?: { where?: Partial<T> }) => this.read<T>(tableName, options?.where),"," };"," }",""," async query<T extends QueryResultRow = any>(sql: string, params?: any[]): Promise<QueryResult<T>> {"," return this.pool.query<T>(sql, params);"," }",""," async sql<T extends QueryResultRow = any>(text: string, params?: any[]): Promise<T[]> {"," const result = await this.pool.query<T>(text, params);"," return this.formatReturn(result.rows);"," }",""," async rpc<T = any>(procName: string, params?: Record<string, any>, types?: Record<string, string>, isProcedure?: boolean): Promise<T[]> {"," const argNames = Object.keys(params || {});"," const argValues = Object.values(params || {});",""," if (argNames.length === 0) {"," const sql = isProcedure ? `CALL ${procName}()` : `SELECT * FROM ${procName}()`;"," const result = await this.pool.query(sql);"," return this.formatReturn(result.rows as T[]);"," }",""," const placeholders = argNames.map((_, i) => {"," const cast = types && argNames[i] && types[argNames[i]] ? `::${types[argNames[i]]}` : '';"," return `$${i + 1}${cast}`;"," }).join(', ');"," "," const sql = isProcedure ? `CALL ${procName}(${placeholders})` : `SELECT * FROM ${procName}(${placeholders})`;"," const result = await this.pool.query(sql, argValues);"," return this.formatReturn(result.rows as T[]);"," }",""," async create<T = any>(table: string, data: Partial<T>): Promise<T[]> {"," return this.rpc<T>(`${table}_create`, { p_input: data });"," }",""," async read<T = any>(table: string, filter: Partial<T> = {}): Promise<T[]> {"," return this.rpc<T>(`${table}_read`, { p_filter: filter });"," }",""," async update<T = any>(table: string, data: Partial<T>, filter: Partial<T>): Promise<T[]> {"," return this.rpc<T>(`${table}_update`, { p_input: data, p_filter: filter });"," }",""," async delete<T = any>(table: string, filter: Partial<T>): Promise<T[]> {"," return this.rpc<T>(`${table}_delete`, { p_filter: filter });"," }",""," private formatReturn<T>(data: T): T {"," if (this.returnCase === 'snake') return data;"," return convertKeysDeep(data, this.returnCase) as T;"," }",""," async connect() { return Promise.resolve(); }"," async disconnect() { return this.close(); }",""," async close() {"," await this.pool.end();"," }","}","","function convertKeysDeep(obj: any, targetCase: 'camel' | 'pascal' | 'snake'): any {"," if (Array.isArray(obj)) return obj.map(v => convertKeysDeep(v, targetCase));"," if (obj !== null && typeof obj === 'object' && !(obj instanceof Date)) {"," return Object.fromEntries("," Object.entries(obj).map(([key, value]) => ["," convertCase(key, targetCase),"," convertKeysDeep(value, targetCase)"," ])"," );"," }"," return obj;","}","","function convertCase(str: string, targetCase: 'camel' | 'pascal' | 'snake'): string {"," const parts = str.split('_');"," if (targetCase === 'snake') return parts.join('_');"," if (targetCase === 'camel') return parts[0] + parts.slice(1).map(p => p.charAt(0).toUpperCase() + p.slice(1)).join('');"," if (targetCase === 'pascal') return parts.map(p => p.charAt(0).toUpperCase() + p.slice(1)).join('');"," return str;","}"];async function ie(i){const e=d.resolve(process.cwd(),i.config||"src/generated/dbmason.config.json"),n=d.resolve(process.cwd(),i.output||"src/generated-client.ts");p.existsSync(e)||(console.error(`Metadata file not found: ${e}`),console.info('Run "dbmason generate" first to produce the metadata file.'),process.exit(1));try{const t=JSON.parse(p.readFileSync(e,"utf8"));console.log(`Generating ${i.lang||"typescript"} client...`);const s=se(t,{lang:i.lang||"typescript"}),o=d.dirname(n);p.existsSync(o)||p.mkdirSync(o,{recursive:!0}),p.writeFileSync(n,s),console.log(`Client generated successfully: ${n}`)}catch(t){console.error("Client generation failed:",t.message),process.exit(1)}}async function ae(i={}){console.log("Starting introspection...");const e=d.resolve(process.cwd(),"dbmason/index.ts");p.existsSync(e)||(console.error("dbmason/index.ts not found."),process.exit(1));const n=d.resolve(process.cwd(),"dbmason/schema.ts");p.existsSync(n)||p.writeFileSync(n,`// Initial empty schema
63
+ `);try{require("ts-node").register({transpileOnly:!0});const t=require(e),s=t.default||t.ctx;let o=t.dialect;if(!(s instanceof D.DbmasonContext)&&s?.constructor?.name!=="DbmasonContext")throw new Error("dbmason/index.ts must export a DbmasonContext.");if(!o&&s.config?.dialect&&(o=s.config.dialect),!o)throw new Error('dbmason/index.ts must export a "dialect" or pass it to DbmasonContext constructor.');if(!o.introspector)throw new Error(`Dialect ${o.name} does not support introspection.`);const r=s.config?.connectionString;if(!r)throw new Error('DbmasonContext must have a "connectionString" configured for introspection.');const c=await o.introspector.introspect(r),a=d.resolve(process.cwd(),"node_modules/@dbmason/core"),l=d.join(a,".dbmason-snapshot.json");p.existsSync(a)||p.mkdirSync(a,{recursive:!0}),p.writeFileSync(l,JSON.stringify(c,null,2)),console.log(`Snapshot saved to ${d.relative(process.cwd(),l)}`);const h=ce(c),u=d.resolve(process.cwd(),"dbmason/schema.ts");p.writeFileSync(u,h),console.log(`Schema written to ${d.relative(process.cwd(),u)}`),delete require.cache[require.resolve(u)],delete require.cache[require.resolve(e)];const f=require(e),g=f.default||f.ctx,y=new j(g,o).analyze(),w=R.build(y);if(p.writeFileSync(l,JSON.stringify(w,null,2)),i.init){console.log("Baselining existing schema...");const b=d.resolve(process.cwd(),s.config.paths?.migrations||"migrations");if(!p.existsSync(b))p.mkdirSync(b,{recursive:!0});else{const I=p.readdirSync(b);for(const E of I)E.endsWith(".sql")&&p.unlinkSync(d.join(b,E));console.log("Cleared existing migrations.")}delete require.cache[require.resolve(u)],delete require.cache[require.resolve(e)];const P=require(e),F=P.default||P.ctx,J=new k(F,o).compile(void 0),O=`${Date.now()}_init.sql`;p.writeFileSync(d.join(b,O),J),console.log(`Created baseline migration: ${d.relative(process.cwd(),d.join(b,O))}`);const x=o.getDriver(r);await x.connect();try{await x.query(`
64
+ CREATE TABLE IF NOT EXISTS dbmason_migrations (
65
+ id SERIAL PRIMARY KEY,
66
+ name TEXT NOT NULL UNIQUE,
67
+ applied_at TIMESTAMPTZ DEFAULT NOW()
68
+ );
69
+ `),await x.query("INSERT INTO dbmason_migrations (name) VALUES ($1)",[O]),console.log("Marked baseline migration as applied in database.")}finally{await x.close()}}}catch(t){console.error("Pull failed:",t.message),process.exit(1)}}const m=i=>" ".repeat(i);function ce(i){const e=[],n=new Set(["defineTable","defineView","defineEnum","defineFunction","defineProcedure","defineTrigger","text","integer","boolean","timestamp","jsonb","uuid","custom"]);if(e.push(`import {
70
+ ${m(1)}${Array.from(n).join(`,
71
+ ${m(1)}`)}
72
+ } from '@dbmason/postgres';`),e.push(`import ctx from './index';
73
+ `),i.types)for(const[t,s]of Object.entries(i.types)){const o=s;o.type==="enum"&&e.push(`export const ${t} = defineEnum(ctx, '${t}', [${o.values?.map(r=>`'${r}'`).join(", ")}]);
74
+ `)}for(const[t,s]of Object.entries(i.tables)){if(t==="dbmason_migrations")continue;const o=s;e.push(`export const ${t} = defineTable(ctx, '${t}', {`),e.push(`${m(1)}columns: {`);for(const[a,l]of Object.entries(o.columns||{})){const h=l;let u=`${m(2)}${a}: `;const f=h.type.toLowerCase();if(f==="text"||f==="varchar"?u+="text()":f==="integer"||f==="int4"?u+="integer()":f==="boolean"||f==="bool"?u+="boolean()":f==="uuid"?u+="uuid()":f==="jsonb"?u+="jsonb()":f.includes("timestamp")?u+="timestamp()":u+=`custom('${h.type}')`,h.notNull&&(u+=".notNull()"),h.default){const g=h.default.replace(/"/g,'\\"');u+=`.default("${g}")`}h.primaryKey&&(u+=".primaryKey()"),e.push(`${u},`)}e.push(`${m(1)}},`);const r=o.constraints||[],c=o.indexes||[];if(r.length>0||c.length>0){if(r.length>0){e.push(`${m(1)}constraints: [`);for(const a of r){const l=a;e.push(`${m(2)}{ kind: 'Constraint', type: '${l.type}', name: '${l.name}', definition: \`${l.definition}\`, table: '${t}' },`)}e.push(`${m(1)}],`)}if(c.length>0){e.push(`${m(1)}indexes: [`);for(const a of c){const l=a;e.push(`${m(2)}{ kind: 'Index', name: '${l.name}', table: '${t}', columns: ${JSON.stringify(l.columns)}, unique: ${l.unique} },`)}e.push(`${m(1)}],`)}}e.push(`});
75
+ `)}if(i.views)for(const[t,s]of Object.entries(i.views)){const o=s;e.push(`export const ${t} = defineView(ctx, '${t}', \`${o.query.replace(/`/g,"\\`")}\`);
76
+ `)}if(i.procedures)for(const[t,s]of Object.entries(i.procedures)){const o=s;e.push(`export const ${t} = defineProcedure(ctx, '${t}', {`),e.push(`${m(1)}args: ${JSON.stringify(o.args)},`),e.push(`${m(1)}returns: '${o.returns}',`),e.push(`${m(1)}language: '${o.language}',`),e.push(`${m(1)}body: \`${o.body.replace(/`/g,"\\`")}\``),e.push(`});
77
+ `)}if(i.functions)for(const[t,s]of Object.entries(i.functions)){const o=s;e.push(`export const ${t} = defineFunction(ctx, '${t}', {`),e.push(`${m(1)}args: ${JSON.stringify(o.args)},`),e.push(`${m(1)}returns: '${o.returns}',`),e.push(`${m(1)}language: '${o.language}',`),e.push(`${m(1)}body: \`${o.body.replace(/`/g,"\\`")}\``),e.push(`});
78
+ `)}if(i.triggers)for(const[t,s]of Object.entries(i.triggers)){const o=s;e.push(`export const ${t} = defineTrigger(ctx, '${o.table}', '${t}', {`),e.push(`${m(1)}events: ${JSON.stringify(o.events)},`),e.push(`${m(1)}procedure: '${o.functionName}',`),e.push(`${m(1)}when: '${o.when}',`),e.push(`${m(1)}forEach: '${o.forEach}'`),e.push(`});
79
+ `)}return e.join(`
80
+ `)}const $=new H.Command;$.command("pull").description("Introspect database and generate schema").option("--init","Initialize migration history and create a baseline migration").action(i=>ae(i));$.name("dbmason").description("Dbmason Database Management CLI").version("0.2.0");$.command("init <projectName>").description("Initialize a new PDK project").option("-t, --template <name>","Project template to use","auth.cli.template").action((i,e)=>K(i,e));$.command("generate [name]").description("Generate migration files").option("--allow-destructive","Allow generated migrations to include destructive operations").option("-d, --dry","Dry run (log SQL but do not write files)").action((i,e)=>Z(i,e));$.command("migrate").description("Apply migrations to the database").action(i=>te(i));$.command("client").description("Generate a type-safe database client").option("-c, --config <path>","Path to dbmason.metadata.json","dbmason.metadata.json").option("-l, --lang <language>","Target language (typescript)","typescript").option("-o, --output <path>","Output file path","src/generated-client.ts").action(i=>ie(i));$.parse(process.argv);
81
+ //# sourceMappingURL=index.js.map