@supacloud/db-zenstack 0.0.0-stage → 0.2.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.
- package/LICENSE +202 -0
- package/LICENSE-APACHE-2.0.txt +202 -0
- package/NOTICE +17 -0
- package/README.md +6 -2
- package/dist/bun-dialect.d.ts +26 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +447 -0
- package/dist/model-cli.d.ts +2 -0
- package/dist/model-cli.js +151 -0
- package/dist/model.d.ts +13 -0
- package/dist/model.js +62 -0
- package/dist/zenstack.d.ts +34 -0
- package/package.json +70 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
SupaCloud
|
|
2
|
+
Copyright 2025 SupaCloud Contributors
|
|
3
|
+
|
|
4
|
+
SupaCloud project-owned code in this revision is licensed under the Apache
|
|
5
|
+
License, Version 2.0 (Apache-2.0). The complete license is provided in
|
|
6
|
+
LICENSE.
|
|
7
|
+
|
|
8
|
+
This program is distributed without any warranty; without even the implied
|
|
9
|
+
warranty of merchantability or fitness for a particular purpose.
|
|
10
|
+
|
|
11
|
+
Third-party components, incorporated upstream code, and their copyright,
|
|
12
|
+
license and attribution notices retain their original terms. This notice does
|
|
13
|
+
not replace those terms or claim ownership of third-party work.
|
|
14
|
+
|
|
15
|
+
Previously released SupaCloud versions retain the permissions granted with
|
|
16
|
+
those versions. See the historical license files and release notices where
|
|
17
|
+
applicable.
|
package/README.md
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @supacloud/db-zenstack
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Optional ZenStack adapter for model compilation and `createZenStackDatabase`.
|
|
4
|
+
|
|
5
|
+
`@supacloud/db` re-exports `@supacloud/db/zenstack` and `@supacloud/db/model` from this package so existing imports keep working. The control plane does not depend on this package. Install it only in an application that compiles ZModel or hosts the model command transaction.
|
|
6
|
+
|
|
7
|
+
`@supacloud/db` catalog, RLS, and command-receipt code does not import this adapter.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { PostgresAdapter, PostgresIntrospector, PostgresQueryCompiler, type Dialect, type Driver, type Kysely } from "kysely";
|
|
2
|
+
/** The narrow native transport contract also permits deterministic driver tests. */
|
|
3
|
+
export interface BunSqlRows extends ReadonlyArray<unknown> {
|
|
4
|
+
readonly command?: string;
|
|
5
|
+
readonly count?: number;
|
|
6
|
+
}
|
|
7
|
+
export interface BunSqlConnection {
|
|
8
|
+
unsafe(text: string, parameters: unknown[]): PromiseLike<BunSqlRows>;
|
|
9
|
+
release(): void;
|
|
10
|
+
}
|
|
11
|
+
export interface BunSqlPool {
|
|
12
|
+
reserve(): Promise<BunSqlConnection>;
|
|
13
|
+
close(): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
/** PostgreSQL compiler/adapter are upstream Kysely; only the native driver is local. */
|
|
16
|
+
export declare class BunPostgresDialect implements Dialect {
|
|
17
|
+
private readonly pool;
|
|
18
|
+
private readonly options;
|
|
19
|
+
constructor(pool: BunSqlPool, options?: {
|
|
20
|
+
closePool?: boolean;
|
|
21
|
+
});
|
|
22
|
+
createDriver(): Driver;
|
|
23
|
+
createAdapter(): PostgresAdapter;
|
|
24
|
+
createQueryCompiler(): PostgresQueryCompiler;
|
|
25
|
+
createIntrospector(db: Kysely<unknown>): PostgresIntrospector;
|
|
26
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { createZenStackDatabase, type ModelClient, type ModelCommandTransaction, type ModelReadClient, type ReadFunctionScalar, } from "./zenstack";
|
|
2
|
+
export type { CallFunctionOptions, CallFunctionPolicy, CallFunctionVolatility, JsonArgument, ReadFunctionArg, ReadFunctionRow, } from "@supacloud/db/model-contract";
|
|
3
|
+
export { BunPostgresDialect, type BunSqlPool } from "./bun-dialect";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
// src/zenstack.ts
|
|
2
|
+
import { ZenStackClient } from "@zenstackhq/orm";
|
|
3
|
+
import { PolicyPlugin } from "@zenstackhq/plugin-policy";
|
|
4
|
+
import { CommandError } from "@supacloud/contracts";
|
|
5
|
+
|
|
6
|
+
// src/bun-dialect.ts
|
|
7
|
+
import {
|
|
8
|
+
CompiledQuery,
|
|
9
|
+
PostgresAdapter,
|
|
10
|
+
PostgresIntrospector,
|
|
11
|
+
PostgresQueryCompiler
|
|
12
|
+
} from "kysely";
|
|
13
|
+
|
|
14
|
+
class Connection {
|
|
15
|
+
native;
|
|
16
|
+
active = true;
|
|
17
|
+
constructor(native) {
|
|
18
|
+
this.native = native;
|
|
19
|
+
}
|
|
20
|
+
async executeQuery(query) {
|
|
21
|
+
if (!this.active)
|
|
22
|
+
throw new Error("Database connection is released");
|
|
23
|
+
const result = await this.native.unsafe(query.sql, [...query.parameters]);
|
|
24
|
+
const rows = Array.from(result);
|
|
25
|
+
const affected = /^(INSERT|UPDATE|DELETE|MERGE)$/.test(result.command ?? "") && result.count !== undefined;
|
|
26
|
+
return { rows, ...affected ? { numAffectedRows: BigInt(result.count) } : {} };
|
|
27
|
+
}
|
|
28
|
+
async* streamQuery() {
|
|
29
|
+
throw new Error("Bun SQL cursor streaming is not supported by this dialect");
|
|
30
|
+
}
|
|
31
|
+
release() {
|
|
32
|
+
if (!this.active)
|
|
33
|
+
return;
|
|
34
|
+
this.active = false;
|
|
35
|
+
this.native.release();
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
var isolationLevels = new Set(["read uncommitted", "read committed", "repeatable read", "serializable"]);
|
|
39
|
+
function savepointName(name) {
|
|
40
|
+
if (!name || name.includes("\x00"))
|
|
41
|
+
throw new Error("Invalid savepoint name");
|
|
42
|
+
return `"${name.replaceAll('"', '""')}"`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
class BunSqlDriver {
|
|
46
|
+
pool;
|
|
47
|
+
closePool;
|
|
48
|
+
constructor(pool, closePool) {
|
|
49
|
+
this.pool = pool;
|
|
50
|
+
this.closePool = closePool;
|
|
51
|
+
}
|
|
52
|
+
async init() {}
|
|
53
|
+
async acquireConnection() {
|
|
54
|
+
return new Connection(await this.pool.reserve());
|
|
55
|
+
}
|
|
56
|
+
async beginTransaction(connection, settings) {
|
|
57
|
+
if (settings.isolationLevel && !isolationLevels.has(settings.isolationLevel))
|
|
58
|
+
throw new Error("Unsupported PostgreSQL isolation level");
|
|
59
|
+
if (settings.accessMode && !["read only", "read write"].includes(settings.accessMode))
|
|
60
|
+
throw new Error("Invalid transaction access mode");
|
|
61
|
+
const isolation = settings.isolationLevel ? ` ISOLATION LEVEL ${settings.isolationLevel}` : "";
|
|
62
|
+
const access = settings.accessMode ? ` ${settings.accessMode}` : "";
|
|
63
|
+
await connection.executeQuery(CompiledQuery.raw(`BEGIN${isolation}${access}`));
|
|
64
|
+
}
|
|
65
|
+
async commitTransaction(connection) {
|
|
66
|
+
await connection.executeQuery(CompiledQuery.raw("COMMIT"));
|
|
67
|
+
}
|
|
68
|
+
async rollbackTransaction(connection) {
|
|
69
|
+
await connection.executeQuery(CompiledQuery.raw("ROLLBACK"));
|
|
70
|
+
}
|
|
71
|
+
async savepoint(connection, name) {
|
|
72
|
+
await connection.executeQuery(CompiledQuery.raw(`SAVEPOINT ${savepointName(name)}`));
|
|
73
|
+
}
|
|
74
|
+
async rollbackToSavepoint(connection, name) {
|
|
75
|
+
await connection.executeQuery(CompiledQuery.raw(`ROLLBACK TO SAVEPOINT ${savepointName(name)}`));
|
|
76
|
+
}
|
|
77
|
+
async releaseSavepoint(connection, name) {
|
|
78
|
+
await connection.executeQuery(CompiledQuery.raw(`RELEASE SAVEPOINT ${savepointName(name)}`));
|
|
79
|
+
}
|
|
80
|
+
async releaseConnection(connection) {
|
|
81
|
+
if (!(connection instanceof Connection))
|
|
82
|
+
throw new Error("Connection belongs to another dialect");
|
|
83
|
+
connection.release();
|
|
84
|
+
}
|
|
85
|
+
async destroy() {
|
|
86
|
+
if (this.closePool)
|
|
87
|
+
await this.pool.close();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
class BunPostgresDialect {
|
|
92
|
+
pool;
|
|
93
|
+
options;
|
|
94
|
+
constructor(pool, options = {}) {
|
|
95
|
+
this.pool = pool;
|
|
96
|
+
this.options = options;
|
|
97
|
+
}
|
|
98
|
+
createDriver() {
|
|
99
|
+
return new BunSqlDriver(this.pool, this.options.closePool === true);
|
|
100
|
+
}
|
|
101
|
+
createAdapter() {
|
|
102
|
+
return new PostgresAdapter;
|
|
103
|
+
}
|
|
104
|
+
createQueryCompiler() {
|
|
105
|
+
return new PostgresQueryCompiler;
|
|
106
|
+
}
|
|
107
|
+
createIntrospector(db) {
|
|
108
|
+
return new PostgresIntrospector(db);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// src/zenstack.ts
|
|
113
|
+
import {
|
|
114
|
+
createPostgresCommandStore,
|
|
115
|
+
isSafeDefinerSearchPath
|
|
116
|
+
} from "@supacloud/db";
|
|
117
|
+
var reads = ["findUnique", "findUniqueOrThrow", "findFirst", "findFirstOrThrow", "findMany", "count", "aggregate", "groupBy"];
|
|
118
|
+
var operations = [...reads, "create", "createMany", "createManyAndReturn", "update", "updateMany", "updateManyAndReturn", "upsert", "delete", "deleteMany"];
|
|
119
|
+
var typing = { typing: { exactQueryArgs: true } };
|
|
120
|
+
var functionName = /^[a-z_][a-z0-9_]{0,62}\.[a-z_][a-z0-9_]{0,62}$/;
|
|
121
|
+
var qualifiedObject = /^[A-Za-z_][A-Za-z0-9_]{0,62}\.[A-Za-z_][A-Za-z0-9_]{0,62}$/;
|
|
122
|
+
var identifierName = /^[a-z_][a-z0-9_]{0,62}$/;
|
|
123
|
+
var objectName = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;
|
|
124
|
+
var systemSchemas = new Set(["pg_catalog", "information_schema", "pg_toast"]);
|
|
125
|
+
var sqlType = /^[A-Za-z0-9_$ .\"()\[\],]+$/;
|
|
126
|
+
function postgresArrayLiteral(values) {
|
|
127
|
+
return `{${values.map((value) => {
|
|
128
|
+
if (value === null)
|
|
129
|
+
return "NULL";
|
|
130
|
+
if (typeof value === "number")
|
|
131
|
+
return String(value);
|
|
132
|
+
if (typeof value === "boolean")
|
|
133
|
+
return value ? "TRUE" : "FALSE";
|
|
134
|
+
return `"${value.replaceAll("\\", "\\\\").replaceAll('"', "\\\"")}"`;
|
|
135
|
+
}).join(",")}}`;
|
|
136
|
+
}
|
|
137
|
+
function isJsonArgument(value) {
|
|
138
|
+
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
139
|
+
return true;
|
|
140
|
+
if (typeof value === "number")
|
|
141
|
+
return Number.isFinite(value);
|
|
142
|
+
if (Array.isArray(value))
|
|
143
|
+
return value.every(isJsonArgument);
|
|
144
|
+
return typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype && Object.values(value).every(isJsonArgument);
|
|
145
|
+
}
|
|
146
|
+
var volatilityCodes = { stable: "s", immutable: "i", volatile: "v" };
|
|
147
|
+
function facade(schema, client, allowed, assertActive) {
|
|
148
|
+
return Object.freeze(Object.fromEntries(Object.keys(schema.models).map((name) => {
|
|
149
|
+
const key = name[0].toLowerCase() + name.slice(1);
|
|
150
|
+
const delegate = Reflect.get(client, key);
|
|
151
|
+
if (!delegate || typeof delegate !== "object")
|
|
152
|
+
throw new Error(`Missing model delegate: ${key}`);
|
|
153
|
+
const methods = allowed.map((method) => {
|
|
154
|
+
const invoke = Reflect.get(delegate, method);
|
|
155
|
+
if (typeof invoke !== "function")
|
|
156
|
+
throw new Error(`Unsupported model operation: ${method}`);
|
|
157
|
+
return [method, async (...args) => {
|
|
158
|
+
assertActive();
|
|
159
|
+
return await Reflect.apply(invoke, delegate, args);
|
|
160
|
+
}];
|
|
161
|
+
});
|
|
162
|
+
return [key, Object.freeze(Object.fromEntries(methods))];
|
|
163
|
+
})));
|
|
164
|
+
}
|
|
165
|
+
function createZenStackDatabase(schema, pool, options) {
|
|
166
|
+
const { callFunction: callFunctionPolicy, ...clientOptions } = options;
|
|
167
|
+
const policySchemas = callFunctionPolicy?.schemas === undefined ? new Set(["public"]) : new Set(callFunctionPolicy.schemas);
|
|
168
|
+
const policyOwners = callFunctionPolicy?.owners === undefined ? undefined : new Set(callFunctionPolicy.owners);
|
|
169
|
+
if (policySchemas.size === 0 || [...policySchemas].some((name) => !identifierName.test(name))) {
|
|
170
|
+
throw new Error("callFunction schemas must be explicit non-system identifiers");
|
|
171
|
+
}
|
|
172
|
+
if (policyOwners && (policyOwners.size === 0 || [...policyOwners].some((name) => name.trim() === ""))) {
|
|
173
|
+
throw new Error("callFunction owners must be explicit role names");
|
|
174
|
+
}
|
|
175
|
+
const reserved = ["dialect", "plugins", "typing", "omit", "allowQueryTimeOmitOverride", "slicing", "validateInput", "skipValidationForComputedFields"];
|
|
176
|
+
if (Object.keys(clientOptions).some((key) => reserved.includes(key)))
|
|
177
|
+
throw new Error("Model facade validation and capabilities cannot be overridden");
|
|
178
|
+
const client = new ZenStackClient(schema, {
|
|
179
|
+
...clientOptions,
|
|
180
|
+
...typing,
|
|
181
|
+
dialect: new BunPostgresDialect(pool),
|
|
182
|
+
plugins: [new PolicyPlugin({ dangerouslyAllowRawSql: true })]
|
|
183
|
+
});
|
|
184
|
+
let disposed = false;
|
|
185
|
+
const assertOpen = () => {
|
|
186
|
+
if (disposed)
|
|
187
|
+
throw new Error("Database is disposed");
|
|
188
|
+
};
|
|
189
|
+
return Object.freeze({
|
|
190
|
+
forIdentity(identity, submission) {
|
|
191
|
+
assertOpen();
|
|
192
|
+
if (identity === null || identity === undefined)
|
|
193
|
+
throw new Error("Verified database identity is required");
|
|
194
|
+
const scoped = client.$setAuth(structuredClone(identity));
|
|
195
|
+
const database = {
|
|
196
|
+
transaction: (work) => {
|
|
197
|
+
assertOpen();
|
|
198
|
+
return scoped.$transaction(async (tx) => {
|
|
199
|
+
let active = true;
|
|
200
|
+
const assertActive = () => {
|
|
201
|
+
assertOpen();
|
|
202
|
+
if (!active)
|
|
203
|
+
throw new Error("Command transaction is closed");
|
|
204
|
+
};
|
|
205
|
+
const inspectFunction = async (name, argCount) => {
|
|
206
|
+
if (typeof name !== "string" || !functionName.test(name))
|
|
207
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
208
|
+
const [schemaName, procName] = name.split(".");
|
|
209
|
+
if (systemSchemas.has(schemaName) || schemaName.startsWith("pg_"))
|
|
210
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
211
|
+
if (!Number.isSafeInteger(argCount) || argCount < 0 || argCount > 16)
|
|
212
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
213
|
+
const resolved = await tx.$queryRawUnsafe(`SELECT p.prokind::text AS kind, p.provolatile::text AS volatility, p.proretset AS returns_set,
|
|
214
|
+
p.prosecdef AS security_definer, pg_get_userbyid(p.proowner) AS owner,
|
|
215
|
+
has_function_privilege(current_user, p.oid, 'EXECUTE') AS can_execute,
|
|
216
|
+
COALESCE(p.proconfig, ARRAY[]::text[]) AS config,
|
|
217
|
+
COALESCE((SELECT array_agg(format_type(u.type_oid, NULL)::text ORDER BY u.ordinality)
|
|
218
|
+
FROM unnest(p.proargtypes::oid[]) WITH ORDINALITY AS u(type_oid, ordinality)
|
|
219
|
+
WHERE u.ordinality IS NOT NULL), ARRAY[]::text[]) AS arg_types,
|
|
220
|
+
COALESCE((SELECT array_agg(u.type_oid::text ORDER BY u.ordinality)
|
|
221
|
+
FROM unnest(p.proargtypes::oid[]) WITH ORDINALITY AS u(type_oid, ordinality)
|
|
222
|
+
WHERE u.ordinality IS NOT NULL), ARRAY[]::text[]) AS arg_type_oids,
|
|
223
|
+
COALESCE((SELECT array_agg((t.typelem <> 0) ORDER BY u.ordinality)
|
|
224
|
+
FROM unnest(p.proargtypes::oid[]) WITH ORDINALITY AS u(type_oid, ordinality)
|
|
225
|
+
JOIN pg_catalog.pg_type t ON t.oid = u.type_oid
|
|
226
|
+
WHERE u.ordinality IS NOT NULL), ARRAY[]::boolean[]) AS arg_arrays,
|
|
227
|
+
COALESCE((SELECT array_agg(COALESCE(et.typtype::text, '') ORDER BY u.ordinality)
|
|
228
|
+
FROM unnest(p.proargtypes::oid[]) WITH ORDINALITY AS u(type_oid, ordinality)
|
|
229
|
+
JOIN pg_catalog.pg_type t ON t.oid = u.type_oid
|
|
230
|
+
LEFT JOIN pg_catalog.pg_type et ON et.oid = t.typelem
|
|
231
|
+
WHERE u.ordinality IS NOT NULL), ARRAY[]::text[]) AS arg_element_kinds
|
|
232
|
+
FROM pg_catalog.pg_proc p
|
|
233
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
|
|
234
|
+
WHERE n.nspname = $1 AND p.proname = $2 AND p.pronargs = $3`, schemaName, procName, argCount);
|
|
235
|
+
if (!Array.isArray(resolved) || resolved.length !== 1)
|
|
236
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
237
|
+
const signature = resolved[0];
|
|
238
|
+
if (signature === undefined || signature["kind"] !== "f")
|
|
239
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
240
|
+
const argTypes = signature["arg_types"];
|
|
241
|
+
const argTypeOids = signature["arg_type_oids"];
|
|
242
|
+
const argArrays = signature["arg_arrays"];
|
|
243
|
+
const argElementKinds = signature["arg_element_kinds"];
|
|
244
|
+
if (!Array.isArray(argTypes) || !Array.isArray(argTypeOids) || !Array.isArray(argArrays) || !Array.isArray(argElementKinds) || argTypes.length !== argCount || argTypeOids.length !== argCount || argArrays.length !== argCount || argElementKinds.length !== argCount) {
|
|
245
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
246
|
+
}
|
|
247
|
+
return { schemaName, procName, signature, argTypes, argTypeOids, argArrays, argElementKinds };
|
|
248
|
+
};
|
|
249
|
+
try {
|
|
250
|
+
return await work({
|
|
251
|
+
db: facade(schema, tx, operations, assertActive),
|
|
252
|
+
query: async (text, parameters = []) => {
|
|
253
|
+
assertActive();
|
|
254
|
+
return await tx.$queryRawUnsafe(text, ...parameters);
|
|
255
|
+
},
|
|
256
|
+
readFunction: async (name, args = []) => {
|
|
257
|
+
if (!Array.isArray(args) || args.length > 16)
|
|
258
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
259
|
+
for (const arg of args) {
|
|
260
|
+
const values = Array.isArray(arg) ? arg : [arg];
|
|
261
|
+
if (Array.isArray(arg) && values.some((value) => Array.isArray(value)))
|
|
262
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
263
|
+
for (const value of values) {
|
|
264
|
+
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
265
|
+
continue;
|
|
266
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
267
|
+
continue;
|
|
268
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
const { schemaName, procName, signature, argTypes, argArrays, argElementKinds } = await inspectFunction(name, args.length);
|
|
272
|
+
const volatility = signature["volatility"];
|
|
273
|
+
if (volatility !== "s" && volatility !== "i")
|
|
274
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
275
|
+
if (signature["returns_set"] === true)
|
|
276
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
277
|
+
const placeholders = args.map((arg, index) => {
|
|
278
|
+
const type = argTypes[index];
|
|
279
|
+
const expectsArray = argArrays[index] === true;
|
|
280
|
+
const elementKind = argElementKinds[index];
|
|
281
|
+
if (typeof type !== "string" || !sqlType.test(type) || Array.isArray(arg) !== expectsArray || expectsArray && !["b", "d", "e"].includes(elementKind))
|
|
282
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
283
|
+
return `$${index + 1}::${type}`;
|
|
284
|
+
}).join(", ");
|
|
285
|
+
const boundArgs = args.map((arg) => Array.isArray(arg) ? postgresArrayLiteral(arg) : arg);
|
|
286
|
+
const rows = await tx.$queryRawUnsafe(`SELECT "${schemaName}"."${procName}"(${placeholders}) AS result`, ...boundArgs);
|
|
287
|
+
const row = Array.isArray(rows) ? rows[0] : undefined;
|
|
288
|
+
assertActive();
|
|
289
|
+
return row === undefined ? undefined : row["result"];
|
|
290
|
+
},
|
|
291
|
+
readFunctionByRow: async (name, row) => {
|
|
292
|
+
if (row === null || typeof row !== "object" || Array.isArray(row))
|
|
293
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
294
|
+
const { table, key, value } = row;
|
|
295
|
+
if (typeof table !== "string" || !qualifiedObject.test(table))
|
|
296
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
297
|
+
if (typeof key !== "string" || !objectName.test(key))
|
|
298
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
299
|
+
if (value !== null && typeof value !== "string" && typeof value !== "boolean" && !(typeof value === "number" && Number.isFinite(value)))
|
|
300
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
301
|
+
const [tableSchema, tableName] = table.split(".");
|
|
302
|
+
if (systemSchemas.has(tableSchema) || tableSchema.startsWith("pg_"))
|
|
303
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
304
|
+
const { schemaName, procName, signature, argTypes, argTypeOids } = await inspectFunction(name, 1);
|
|
305
|
+
const volatility = signature["volatility"];
|
|
306
|
+
if (volatility !== "s" && volatility !== "i")
|
|
307
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
308
|
+
if (signature["returns_set"] === true)
|
|
309
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
310
|
+
const tableInfo = await tx.$queryRawUnsafe(`SELECT c.relkind::text AS kind, c.reltype::text AS row_type_oid,
|
|
311
|
+
format_type(a.atttypid, NULL)::text AS key_type,
|
|
312
|
+
(SELECT count(*) FROM pg_catalog.pg_index i
|
|
313
|
+
JOIN pg_catalog.pg_attribute ia ON ia.attrelid = i.indrelid AND ia.attnum = ANY(i.indkey)
|
|
314
|
+
WHERE i.indrelid = c.oid AND i.indisprimary) AS primary_columns,
|
|
315
|
+
EXISTS (SELECT 1 FROM pg_catalog.pg_index i
|
|
316
|
+
JOIN pg_catalog.pg_attribute ia ON ia.attrelid = i.indrelid AND ia.attnum = ANY(i.indkey)
|
|
317
|
+
WHERE i.indrelid = c.oid AND i.indisprimary AND ia.attname = $3) AS key_is_primary
|
|
318
|
+
FROM pg_catalog.pg_class c
|
|
319
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
320
|
+
JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid AND a.attname = $3 AND a.attnum > 0 AND NOT a.attisdropped
|
|
321
|
+
WHERE n.nspname = $1 AND c.relname = $2`, tableSchema, tableName, key);
|
|
322
|
+
if (!Array.isArray(tableInfo) || tableInfo.length !== 1)
|
|
323
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
324
|
+
const tableRow = tableInfo[0];
|
|
325
|
+
if (tableRow === undefined || tableRow["kind"] !== "r" && tableRow["kind"] !== "p" || tableRow["key_is_primary"] !== true || Number(tableRow["primary_columns"]) !== 1 || tableRow["row_type_oid"] !== argTypeOids[0] || argTypes.length !== 1 || typeof tableRow["key_type"] !== "string" || !sqlType.test(tableRow["key_type"])) {
|
|
326
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
327
|
+
}
|
|
328
|
+
const rows = await tx.$queryRawUnsafe(`SELECT "${schemaName}"."${procName}"(t) AS result
|
|
329
|
+
FROM "${tableSchema}"."${tableName}" AS t
|
|
330
|
+
WHERE t."${key}" = $1::${tableRow["key_type"]}
|
|
331
|
+
LIMIT 2`, value);
|
|
332
|
+
if (!Array.isArray(rows) || rows.length !== 1)
|
|
333
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
334
|
+
const result = rows[0];
|
|
335
|
+
assertActive();
|
|
336
|
+
return result === undefined ? undefined : result["result"];
|
|
337
|
+
},
|
|
338
|
+
callFunction: async (name, args = [], options = {}) => {
|
|
339
|
+
if (!Array.isArray(args) || args.length > 16)
|
|
340
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
341
|
+
if (!args.every(isJsonArgument))
|
|
342
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
343
|
+
if (options === null || typeof options !== "object" || Array.isArray(options))
|
|
344
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
345
|
+
const requestedVolatility = options.volatility;
|
|
346
|
+
if (requestedVolatility !== undefined && !(requestedVolatility in volatilityCodes)) {
|
|
347
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
348
|
+
}
|
|
349
|
+
const { schemaName, procName, signature, argTypes, argArrays } = await inspectFunction(name, args.length);
|
|
350
|
+
if (!policySchemas.has(schemaName))
|
|
351
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
352
|
+
const volatility = signature["volatility"];
|
|
353
|
+
if (volatility !== "s" && volatility !== "i" && volatility !== "v")
|
|
354
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
355
|
+
if (requestedVolatility !== undefined && volatilityCodes[requestedVolatility] !== volatility) {
|
|
356
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
357
|
+
}
|
|
358
|
+
if (signature["security_definer"] !== true || signature["can_execute"] !== true) {
|
|
359
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
360
|
+
}
|
|
361
|
+
const owner = signature["owner"];
|
|
362
|
+
if (typeof owner !== "string" || owner === "")
|
|
363
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
364
|
+
if (policyOwners) {
|
|
365
|
+
if (!policyOwners.has(owner))
|
|
366
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
367
|
+
} else {
|
|
368
|
+
const current = await tx.$queryRawUnsafe("SELECT current_user::text AS name");
|
|
369
|
+
if (!Array.isArray(current) || current.length !== 1 || current[0]?.["name"] !== owner) {
|
|
370
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
const config = signature["config"];
|
|
374
|
+
if (!isSafeDefinerSearchPath(config))
|
|
375
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
376
|
+
const placeholders = args.map((arg, index) => {
|
|
377
|
+
const type = argTypes[index];
|
|
378
|
+
if (typeof type !== "string" || !sqlType.test(type) || argArrays[index] === true) {
|
|
379
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
380
|
+
}
|
|
381
|
+
const jsonType = type === "json" || type === "jsonb";
|
|
382
|
+
if ((Array.isArray(arg) || arg !== null && typeof arg === "object") && !jsonType) {
|
|
383
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
384
|
+
}
|
|
385
|
+
return `$${index + 1}::${type}`;
|
|
386
|
+
}).join(", ");
|
|
387
|
+
const rows = await tx.$queryRawUnsafe(`SELECT * FROM "${schemaName}"."${procName}"(${placeholders}) LIMIT 2`, ...args);
|
|
388
|
+
if (!Array.isArray(rows) || rows.length !== 1)
|
|
389
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
390
|
+
const result = rows[0];
|
|
391
|
+
assertActive();
|
|
392
|
+
if (result === undefined)
|
|
393
|
+
return;
|
|
394
|
+
const keys = Object.keys(result);
|
|
395
|
+
return keys.length === 1 ? result[keys[0]] : result;
|
|
396
|
+
},
|
|
397
|
+
lock: async (keys) => {
|
|
398
|
+
if (!Array.isArray(keys) || keys.length === 0)
|
|
399
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
400
|
+
if (keys.length > 16)
|
|
401
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
402
|
+
const unique = [...new Set(keys.map((key) => {
|
|
403
|
+
if (typeof key !== "string" || key.trim() === "")
|
|
404
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
405
|
+
if (key.length > 200)
|
|
406
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
407
|
+
return key;
|
|
408
|
+
}))].sort();
|
|
409
|
+
assertActive();
|
|
410
|
+
for (const key of unique)
|
|
411
|
+
await tx.$queryRawUnsafe("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", key);
|
|
412
|
+
assertActive();
|
|
413
|
+
}
|
|
414
|
+
});
|
|
415
|
+
} finally {
|
|
416
|
+
active = false;
|
|
417
|
+
}
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
};
|
|
421
|
+
const internal = createPostgresCommandStore(database, submission ? { submission } : {});
|
|
422
|
+
const commandStore = {
|
|
423
|
+
transaction: (run) => internal.transaction((session) => run({
|
|
424
|
+
...session,
|
|
425
|
+
transaction: Object.freeze({
|
|
426
|
+
db: session.transaction.db,
|
|
427
|
+
lock: session.transaction.lock,
|
|
428
|
+
readFunction: session.transaction.readFunction,
|
|
429
|
+
readFunctionByRow: session.transaction.readFunctionByRow,
|
|
430
|
+
callFunction: session.transaction.callFunction
|
|
431
|
+
})
|
|
432
|
+
})),
|
|
433
|
+
redactCompleted: (scope) => internal.redactCompleted(scope)
|
|
434
|
+
};
|
|
435
|
+
const models = facade(schema, scoped, reads, assertOpen);
|
|
436
|
+
return Object.freeze({ models, commandStore: Object.freeze(commandStore) });
|
|
437
|
+
},
|
|
438
|
+
async dispose() {
|
|
439
|
+
disposed = true;
|
|
440
|
+
await client.$disconnect();
|
|
441
|
+
}
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
export {
|
|
445
|
+
BunPostgresDialect,
|
|
446
|
+
createZenStackDatabase
|
|
447
|
+
};
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
|
|
3
|
+
// src/model-cli.ts
|
|
4
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
5
|
+
import { mkdir as mkdir2 } from "node:fs/promises";
|
|
6
|
+
import { dirname as dirname2, join as join2, resolve as resolve2, sep } from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
|
|
9
|
+
// src/model.ts
|
|
10
|
+
import { loadDocument } from "@zenstackhq/language";
|
|
11
|
+
import { PrismaSchemaGenerator, TsSchemaGenerator } from "@zenstackhq/sdk";
|
|
12
|
+
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
13
|
+
import { tmpdir } from "node:os";
|
|
14
|
+
import { dirname, join, resolve } from "node:path";
|
|
15
|
+
var BOOTSTRAP_MODEL_SCHEMA = `datasource db {
|
|
16
|
+
provider = "postgresql"
|
|
17
|
+
url = env("DATABASE_URL")
|
|
18
|
+
}
|
|
19
|
+
`;
|
|
20
|
+
async function compileModel(schemaFile, output, check = false) {
|
|
21
|
+
const document = await loadDocument(resolve(schemaFile));
|
|
22
|
+
if (!document.success)
|
|
23
|
+
throw new Error(document.errors.join(`
|
|
24
|
+
`));
|
|
25
|
+
const candidate = await mkdtemp(join(tmpdir(), "supacloud-model-"));
|
|
26
|
+
try {
|
|
27
|
+
await new TsSchemaGenerator().generate(document.model, {
|
|
28
|
+
outDir: candidate,
|
|
29
|
+
importWithFileExtension: ".js",
|
|
30
|
+
generateModelTypes: true,
|
|
31
|
+
generateInputTypes: true
|
|
32
|
+
});
|
|
33
|
+
const prisma = await new PrismaSchemaGenerator(document.model).generate();
|
|
34
|
+
if (!/provider\s*=\s*["']postgresql["']/.test(prisma) || !/url\s*=\s*env\(["']DATABASE_URL["']\)/.test(prisma) || /(?:directUrl|shadowDatabaseUrl)\s*=/.test(prisma)) {
|
|
35
|
+
throw new Error('Models must use the PostgreSQL datasource with url = env("DATABASE_URL")');
|
|
36
|
+
}
|
|
37
|
+
await writeFile(join(candidate, "schema.prisma"), prisma);
|
|
38
|
+
const files = (await readdir(candidate)).sort();
|
|
39
|
+
const mismatches = [];
|
|
40
|
+
for (const file of files) {
|
|
41
|
+
const desired = await readFile(join(candidate, file), "utf8");
|
|
42
|
+
const target = join(resolve(output), file);
|
|
43
|
+
if (check) {
|
|
44
|
+
const current = await readFile(target, "utf8").catch((error) => {
|
|
45
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
46
|
+
return;
|
|
47
|
+
throw error;
|
|
48
|
+
});
|
|
49
|
+
if (current !== desired)
|
|
50
|
+
mismatches.push(file);
|
|
51
|
+
} else {
|
|
52
|
+
await mkdir(dirname(target), { recursive: true });
|
|
53
|
+
await writeFile(target, desired);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (mismatches.length)
|
|
57
|
+
throw new Error(`Model contracts are stale: ${mismatches.join(", ")}. Run supacloud-model generate.`);
|
|
58
|
+
return files;
|
|
59
|
+
} finally {
|
|
60
|
+
await rm(candidate, { recursive: true, force: true });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function modelProcess(command, schema, generated, candidate) {
|
|
64
|
+
return command === "diff" ? { binary: "prisma", args: ["migrate", "diff", "--from-schema-datasource", join(generated, "schema.prisma"), "--to-schema-datamodel", join(generated, "schema.prisma"), "--script", "--output", candidate] } : { binary: "zen", args: ["db", "pull", "--no-version-check", "--schema", schema, "--output", candidate] };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// src/model-cli.ts
|
|
68
|
+
async function modelMain(argv) {
|
|
69
|
+
const [command, ...flags] = argv;
|
|
70
|
+
if (!["generate", "check", "diff", "pull"].includes(command ?? ""))
|
|
71
|
+
throw new Error("Usage: supacloud-model generate|check|diff|pull [--schema file] [--output dir] [--candidate file]");
|
|
72
|
+
const options = new Map;
|
|
73
|
+
for (let index = 0;index < flags.length; index += 2) {
|
|
74
|
+
const key = flags[index], value = flags[index + 1];
|
|
75
|
+
if (!key || !["--schema", "--output", "--candidate"].includes(key) || !value || value.startsWith("--") || options.has(key))
|
|
76
|
+
throw new Error("Invalid model command option");
|
|
77
|
+
options.set(key, value);
|
|
78
|
+
}
|
|
79
|
+
const schemaLabel = options.get("--schema") ?? "zenstack/schema.zmodel";
|
|
80
|
+
const schema = resolve2(schemaLabel);
|
|
81
|
+
const output = resolve2(options.get("--output") ?? "zenstack/generated");
|
|
82
|
+
if (command === "generate" || command === "check") {
|
|
83
|
+
if (options.has("--candidate"))
|
|
84
|
+
throw new Error("--candidate is only supported by diff and pull");
|
|
85
|
+
if (!existsSync(schema))
|
|
86
|
+
throw new Error(`Maintain ${schemaLabel} before ${command}; adopt an existing database with supacloud-model pull first`);
|
|
87
|
+
await compileModel(schema, output, command === "check");
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (command !== "diff" && command !== "pull")
|
|
91
|
+
throw new Error("Invalid model command");
|
|
92
|
+
const databaseUrl = process.env["SUPACLOUD_MODEL_DATABASE_URL"];
|
|
93
|
+
if (!databaseUrl)
|
|
94
|
+
throw new Error("Select a read-only database explicitly with SUPACLOUD_MODEL_DATABASE_URL");
|
|
95
|
+
const rawCandidate = options.get("--candidate");
|
|
96
|
+
if (!rawCandidate)
|
|
97
|
+
throw new Error("Supply a fresh --candidate file; review it before promotion into migration history");
|
|
98
|
+
const candidate = resolve2(rawCandidate);
|
|
99
|
+
if (existsSync(candidate) || candidate === schema)
|
|
100
|
+
throw new Error("Candidate already exists; refusing to overwrite maintained files");
|
|
101
|
+
if (candidate === output || candidate.startsWith(output + sep) || !candidate.endsWith(command === "diff" ? ".sql" : ".zmodel"))
|
|
102
|
+
throw new Error("Select a candidate file outside generated contracts with the correct extension");
|
|
103
|
+
const { mkdtemp, rm, writeFile } = await import("node:fs/promises");
|
|
104
|
+
const { tmpdir } = await import("node:os");
|
|
105
|
+
const validation = await mkdtemp(resolve2(tmpdir(), "supacloud-model-pull-"));
|
|
106
|
+
try {
|
|
107
|
+
let source = schema;
|
|
108
|
+
let bootstrap = false;
|
|
109
|
+
if (command === "diff") {
|
|
110
|
+
if (!existsSync(schema))
|
|
111
|
+
throw new Error(`Maintain ${schemaLabel} before diff; adopt an existing database with supacloud-model pull first`);
|
|
112
|
+
await compileModel(schema, output, true);
|
|
113
|
+
} else if (existsSync(schema))
|
|
114
|
+
await compileModel(schema, join2(validation, "generated"));
|
|
115
|
+
else {
|
|
116
|
+
bootstrap = true;
|
|
117
|
+
source = join2(validation, "schema.zmodel");
|
|
118
|
+
await writeFile(source, BOOTSTRAP_MODEL_SCHEMA);
|
|
119
|
+
await compileModel(source, join2(validation, "generated"));
|
|
120
|
+
}
|
|
121
|
+
const operation = modelProcess(command, source, output, candidate);
|
|
122
|
+
const binary = resolve2("node_modules/.bin", operation.binary);
|
|
123
|
+
if (!existsSync(binary))
|
|
124
|
+
throw new Error(`Install the pinned ${operation.binary} tooling in the application`);
|
|
125
|
+
await mkdir2(dirname2(candidate), { recursive: true });
|
|
126
|
+
const child = Bun.spawn([binary, ...operation.args], {
|
|
127
|
+
env: { ...process.env, DATABASE_URL: databaseUrl },
|
|
128
|
+
stdio: ["ignore", "inherit", "inherit"]
|
|
129
|
+
});
|
|
130
|
+
if (await child.exited !== 0)
|
|
131
|
+
throw new Error("Model candidate generation failed; nothing was applied");
|
|
132
|
+
if (!bootstrap)
|
|
133
|
+
return;
|
|
134
|
+
await compileModel(candidate, join2(validation, "candidate"));
|
|
135
|
+
console.log(`Wrote a review candidate to ${candidate} because ${schemaLabel} does not exist yet.`);
|
|
136
|
+
console.log(`Review it, add the policy plugin and @@allow rules, move it to ${schemaLabel}, then run supacloud-model generate.`);
|
|
137
|
+
} finally {
|
|
138
|
+
await rm(validation, { recursive: true, force: true });
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (process.argv[1] && existsSync(process.argv[1]) && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) {
|
|
142
|
+
try {
|
|
143
|
+
await modelMain(process.argv.slice(2));
|
|
144
|
+
} catch (error) {
|
|
145
|
+
console.error(error instanceof Error ? error.message : "Model command failed");
|
|
146
|
+
process.exitCode = 1;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
export {
|
|
150
|
+
modelMain
|
|
151
|
+
};
|
package/dist/model.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Datasource-only ZModel used to introspect a live database before this project
|
|
3
|
+
* maintains a model. It is never written into the project: `pull` keeps it in a
|
|
4
|
+
* temporary directory so introspection cannot replace authored files.
|
|
5
|
+
*/
|
|
6
|
+
export declare const BOOTSTRAP_MODEL_SCHEMA = "datasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n";
|
|
7
|
+
/** Offline model compilation: no plugin execution, no database or migration ledger writes. */
|
|
8
|
+
export declare function compileModel(schemaFile: string, output: string, check?: boolean): Promise<string[]>;
|
|
9
|
+
export type ModelCommand = "generate" | "check" | "diff" | "pull";
|
|
10
|
+
export declare function modelProcess(command: "diff" | "pull", schema: string, generated: string, candidate: string): {
|
|
11
|
+
binary: string;
|
|
12
|
+
args: string[];
|
|
13
|
+
};
|
package/dist/model.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// src/model.ts
|
|
2
|
+
import { loadDocument } from "@zenstackhq/language";
|
|
3
|
+
import { PrismaSchemaGenerator, TsSchemaGenerator } from "@zenstackhq/sdk";
|
|
4
|
+
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { dirname, join, resolve } from "node:path";
|
|
7
|
+
var BOOTSTRAP_MODEL_SCHEMA = `datasource db {
|
|
8
|
+
provider = "postgresql"
|
|
9
|
+
url = env("DATABASE_URL")
|
|
10
|
+
}
|
|
11
|
+
`;
|
|
12
|
+
async function compileModel(schemaFile, output, check = false) {
|
|
13
|
+
const document = await loadDocument(resolve(schemaFile));
|
|
14
|
+
if (!document.success)
|
|
15
|
+
throw new Error(document.errors.join(`
|
|
16
|
+
`));
|
|
17
|
+
const candidate = await mkdtemp(join(tmpdir(), "supacloud-model-"));
|
|
18
|
+
try {
|
|
19
|
+
await new TsSchemaGenerator().generate(document.model, {
|
|
20
|
+
outDir: candidate,
|
|
21
|
+
importWithFileExtension: ".js",
|
|
22
|
+
generateModelTypes: true,
|
|
23
|
+
generateInputTypes: true
|
|
24
|
+
});
|
|
25
|
+
const prisma = await new PrismaSchemaGenerator(document.model).generate();
|
|
26
|
+
if (!/provider\s*=\s*["']postgresql["']/.test(prisma) || !/url\s*=\s*env\(["']DATABASE_URL["']\)/.test(prisma) || /(?:directUrl|shadowDatabaseUrl)\s*=/.test(prisma)) {
|
|
27
|
+
throw new Error('Models must use the PostgreSQL datasource with url = env("DATABASE_URL")');
|
|
28
|
+
}
|
|
29
|
+
await writeFile(join(candidate, "schema.prisma"), prisma);
|
|
30
|
+
const files = (await readdir(candidate)).sort();
|
|
31
|
+
const mismatches = [];
|
|
32
|
+
for (const file of files) {
|
|
33
|
+
const desired = await readFile(join(candidate, file), "utf8");
|
|
34
|
+
const target = join(resolve(output), file);
|
|
35
|
+
if (check) {
|
|
36
|
+
const current = await readFile(target, "utf8").catch((error) => {
|
|
37
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
38
|
+
return;
|
|
39
|
+
throw error;
|
|
40
|
+
});
|
|
41
|
+
if (current !== desired)
|
|
42
|
+
mismatches.push(file);
|
|
43
|
+
} else {
|
|
44
|
+
await mkdir(dirname(target), { recursive: true });
|
|
45
|
+
await writeFile(target, desired);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (mismatches.length)
|
|
49
|
+
throw new Error(`Model contracts are stale: ${mismatches.join(", ")}. Run supacloud-model generate.`);
|
|
50
|
+
return files;
|
|
51
|
+
} finally {
|
|
52
|
+
await rm(candidate, { recursive: true, force: true });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function modelProcess(command, schema, generated, candidate) {
|
|
56
|
+
return command === "diff" ? { binary: "prisma", args: ["migrate", "diff", "--from-schema-datasource", join(generated, "schema.prisma"), "--to-schema-datamodel", join(generated, "schema.prisma"), "--script", "--output", candidate] } : { binary: "zen", args: ["db", "pull", "--no-version-check", "--schema", schema, "--output", candidate] };
|
|
57
|
+
}
|
|
58
|
+
export {
|
|
59
|
+
BOOTSTRAP_MODEL_SCHEMA,
|
|
60
|
+
compileModel,
|
|
61
|
+
modelProcess
|
|
62
|
+
};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type AuthType, type ClientOptions, type QueryOptions, type ModelOperations } from "@zenstackhq/orm";
|
|
2
|
+
import type { SchemaDef, GetModels } from "@zenstackhq/schema";
|
|
3
|
+
import { type CommandStore, type CommandRetentionStore } from "@supacloud/contracts";
|
|
4
|
+
import { type BunSqlPool } from "./bun-dialect";
|
|
5
|
+
import { type CommandSubmissionBinding } from "@supacloud/db";
|
|
6
|
+
import { type CallFunctionPolicy, type ModelCommandTransaction as ModelCommandTransactionPort } from "@supacloud/db/model-contract";
|
|
7
|
+
declare const reads: readonly ["findUnique", "findUniqueOrThrow", "findFirst", "findFirstOrThrow", "findMany", "count", "aggregate", "groupBy"];
|
|
8
|
+
declare const operations: readonly ["findUnique", "findUniqueOrThrow", "findFirst", "findFirstOrThrow", "findMany", "count", "aggregate", "groupBy", "create", "createMany", "createManyAndReturn", "update", "updateMany", "updateManyAndReturn", "upsert", "delete", "deleteMany"];
|
|
9
|
+
declare const typing: {
|
|
10
|
+
readonly typing: {
|
|
11
|
+
readonly exactQueryArgs: true;
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
type Delegate<S extends SchemaDef, M extends GetModels<S>, K extends string> = Pick<ModelOperations<S, M, typeof typing>, Extract<K, keyof ModelOperations<S, M, typeof typing>>>;
|
|
15
|
+
export type ModelClient<S extends SchemaDef> = {
|
|
16
|
+
readonly [M in GetModels<S> as Uncapitalize<M>]: Delegate<S, M, typeof operations[number]>;
|
|
17
|
+
};
|
|
18
|
+
export type ModelReadClient<S extends SchemaDef> = {
|
|
19
|
+
readonly [M in GetModels<S> as Uncapitalize<M>]: Delegate<S, M, typeof reads[number]>;
|
|
20
|
+
};
|
|
21
|
+
/** Backend compatibility alias. New consumers should import the neutral port. */
|
|
22
|
+
export type ModelCommandTransaction<S extends SchemaDef> = ModelCommandTransactionPort<ModelClient<S>>;
|
|
23
|
+
export type ReadFunctionScalar = string | number | boolean | null;
|
|
24
|
+
export type { CallFunctionOptions, CallFunctionPolicy, CallFunctionVolatility, JsonArgument, ReadFunctionArg, ReadFunctionRow } from "@supacloud/db/model-contract";
|
|
25
|
+
/** Trusted composition root only. Options permit schema-required computed fields/procedures. */
|
|
26
|
+
export declare function createZenStackDatabase<S extends SchemaDef>(schema: S, pool: BunSqlPool, options: Omit<ClientOptions<S>, keyof QueryOptions<S> | "dialect" | "plugins" | "validateInput" | "skipValidationForComputedFields"> & {
|
|
27
|
+
readonly callFunction?: CallFunctionPolicy;
|
|
28
|
+
}): Readonly<{
|
|
29
|
+
forIdentity(identity: AuthType<S>, submission?: CommandSubmissionBinding): Readonly<{
|
|
30
|
+
models: ModelReadClient<S>;
|
|
31
|
+
commandStore: Readonly<CommandStore<ModelCommandTransaction<S>> & CommandRetentionStore>;
|
|
32
|
+
}>;
|
|
33
|
+
dispose(): Promise<void>;
|
|
34
|
+
}>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,72 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supacloud/db-zenstack",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "Optional ZenStack model adapter for SupaCloud. Not part of the control-plane database package.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js"
|
|
13
|
+
},
|
|
14
|
+
"./model": {
|
|
15
|
+
"types": "./dist/model.d.ts",
|
|
16
|
+
"import": "./dist/model.js"
|
|
17
|
+
},
|
|
18
|
+
"./cli": {
|
|
19
|
+
"types": "./dist/model-cli.d.ts",
|
|
20
|
+
"import": "./dist/model-cli.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"NOTICE",
|
|
25
|
+
"LICENSE-APACHE-2.0.txt",
|
|
26
|
+
"dist",
|
|
27
|
+
"README.md",
|
|
28
|
+
"LICENSE"
|
|
29
|
+
],
|
|
30
|
+
"scripts": {
|
|
31
|
+
"build": "bun run clean && bun run build:js && bun run build:types",
|
|
32
|
+
"build:js": "bun build src/index.ts src/model.ts src/model-cli.ts --root src --outdir dist --target node --external bun --external @supacloud/db --external @supacloud/db/model-contract --external @supacloud/contracts --external @zenstackhq/orm --external @zenstackhq/schema --external @zenstackhq/plugin-policy --external kysely --external @zenstackhq/language --external @zenstackhq/sdk",
|
|
33
|
+
"build:types": "tsc -p tsconfig.json --emitDeclarationOnly",
|
|
34
|
+
"clean": "rm -rf dist",
|
|
35
|
+
"test": "bun test",
|
|
36
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
37
|
+
"typecheck:test": "tsc -p tsconfig.json --noEmit"
|
|
38
|
+
},
|
|
39
|
+
"license": "Apache-2.0",
|
|
40
|
+
"repository": {
|
|
41
|
+
"type": "git",
|
|
42
|
+
"url": "https://github.com/vibeunion/supacloud.git",
|
|
43
|
+
"directory": "packages/db-zenstack"
|
|
44
|
+
},
|
|
45
|
+
"dependencies": {
|
|
46
|
+
"@supacloud/contracts": "0.16.1",
|
|
47
|
+
"@supacloud/db": "0.24.2",
|
|
48
|
+
"@zenstackhq/language": "3.10.0",
|
|
49
|
+
"@zenstackhq/orm": "3.10.0",
|
|
50
|
+
"@zenstackhq/plugin-policy": "3.10.0",
|
|
51
|
+
"@zenstackhq/schema": "3.10.0",
|
|
52
|
+
"@zenstackhq/sdk": "3.10.0",
|
|
53
|
+
"kysely": "0.29.0"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@types/bun": "^1.4.4",
|
|
57
|
+
"@zenstackhq/cli": "3.10.0",
|
|
58
|
+
"pg": "8.23.1",
|
|
59
|
+
"prisma": "6.19.3",
|
|
60
|
+
"typescript": "7.1.0-beta"
|
|
61
|
+
},
|
|
62
|
+
"overrides": {
|
|
63
|
+
"@supacloud/contracts": "0.16.1",
|
|
64
|
+
"@supacloud/db": "0.24.2",
|
|
65
|
+
"deepmerge-ts": "8.0.2",
|
|
66
|
+
"prisma": "6.19.3"
|
|
67
|
+
},
|
|
68
|
+
"patchedDependencies": {
|
|
69
|
+
"@zenstackhq/orm@3.10.0": "../../patches/@zenstackhq%2Form@3.10.0.patch",
|
|
70
|
+
"@zenstackhq/plugin-policy@3.10.0": "../../patches/@zenstackhq%2Fplugin-policy@3.10.0.patch"
|
|
71
|
+
}
|
|
72
|
+
}
|