@schemarch/mcp-server-schemarch 0.0.0-stage → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/dist/chunk-5DTK5H23.js +2 -0
- package/dist/chunk-5DTK5H23.js.map +1 -0
- package/dist/chunk-BV2TY4MO.cjs +2 -0
- package/dist/chunk-BV2TY4MO.cjs.map +1 -0
- package/dist/chunk-GEJ6NAOC.cjs +2 -0
- package/dist/chunk-GEJ6NAOC.cjs.map +1 -0
- package/dist/chunk-LU6L7C36.js +1 -0
- package/dist/chunk-LU6L7C36.js.map +1 -0
- package/dist/chunk-N4WMNFDY.cjs +65 -0
- package/dist/chunk-N4WMNFDY.cjs.map +1 -0
- package/dist/chunk-ONL2HNNT.js +284 -0
- package/dist/chunk-ONL2HNNT.js.map +1 -0
- package/dist/chunk-ORH6UYIY.js +65 -0
- package/dist/chunk-ORH6UYIY.js.map +1 -0
- package/dist/chunk-PHWSETKC.cjs +1 -0
- package/dist/chunk-PHWSETKC.cjs.map +1 -0
- package/dist/chunk-T3Q2DPRT.cjs +284 -0
- package/dist/chunk-T3Q2DPRT.cjs.map +1 -0
- package/dist/chunk-XKU4Q6WQ.js +2 -0
- package/dist/chunk-XKU4Q6WQ.js.map +1 -0
- package/dist/cli.cjs +3 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +3 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +2405 -0
- package/dist/index.d.ts +2405 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/platform/api-platform.cjs +2 -0
- package/dist/platform/api-platform.cjs.map +1 -0
- package/dist/platform/api-platform.d.cts +20 -0
- package/dist/platform/api-platform.d.ts +20 -0
- package/dist/platform/api-platform.js +2 -0
- package/dist/platform/api-platform.js.map +1 -0
- package/dist/platform/index.cjs +2 -0
- package/dist/platform/index.cjs.map +1 -0
- package/dist/platform/index.d.cts +577 -0
- package/dist/platform/index.d.ts +577 -0
- package/dist/platform/index.js +2 -0
- package/dist/platform/index.js.map +1 -0
- package/package.json +88 -3
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Schemarch
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as x,b as P,c as _,e as B,g as G}from"./chunk-ORH6UYIY.js";import{i as N,j as z,k as q,l as L,m as U,n as D,q as H,r as V,u as $}from"./chunk-XKU4Q6WQ.js";import{getMultipartBoundary as ne,parseMultipartStream as oe}from"@mjackson/multipart-parser";import{fileURLToPath as j}from"url";import Y from"openapi-fetch";import{z as K}from"zod/v4";function F(i,c,d={}){return Y({baseUrl:i,headers:{Authorization:`Bearer ${c}`,...d}})}var I=K.object({message:K.string()});function o(i,c){if("error"in i){if(i.response.status===401)throw new Error("Unauthorized. Please provide a valid access token to the MCP server via the --access-token flag or SCHEMARCH_ACCESS_TOKEN.");let{data:d}=I.safeParse(i.error);throw d?new Error(d.message):new Error(c)}}function T(i,c,d){if("error"in i&&i.response.status===403){let{data:m}=I.safeParse(i.error),g=(m?.message??c).replace(/\.$/,"");throw new Error(`${g}. Access to project '${d}' was denied. If this project exists, your access token may be scoped to a different organization: re-authenticate with the MCP server and select the organization that owns this project.`)}o(i,c)}import Z from"openapi-fetch";import{z as R}from"zod/v4";function C(i,c,d={}){return Z({baseUrl:i,headers:{Authorization:`Bearer ${c}`,...d}})}var ee=R.object({error:R.object({message:R.string()})});function v(i,c){if("error"in i){if(i.response.status===401)throw new Error("Unauthorized. Please provide a valid access token to the MCP server via the --access-token flag or SCHEMARCH_ACCESS_TOKEN.");let{data:d}=ee.safeParse(i.error);throw d?new Error(d.error.message):new Error(c)}}var te="ABCDEFGHIJKLMNOPQRSTUVWXYZ",se="abcdefghijklmnopqrstuvwxyz",re="0123456789",ae="!@#$%^&*()_+~`|}{[]:;?><,./-=",Q=({length:i=10,numbers:c=!1,symbols:d=!1,uppercase:m=!0,lowercase:g=!0}={})=>{let a="";if(m&&(a+=te),g&&(a+=se),c&&(a+=re),d&&(a+=ae),a.length===0)throw new Error("at least one character set must be selected");let l=new Uint32Array(i);crypto.getRandomValues(l);let E="";for(let w=0;w<i;w++){let A=l[w]%a.length;E+=a.charAt(A)}return E};var{version:ie}=x;var pe=["log_data_api_error_rate_high","log_auth_error_rate_high","log_storage_error_rate_high","log_edge_function_error_rate_high"],ce=new Set(["project_not_active","advisor_check_unavailable"]);function xe(i){let{accessToken:c,apiUrl:d}=i,m=d??"https://api.schemarch.com",g,a=F(m,c),l=C(m,c),E={async listOrganizations(){let t=await a.GET("/v1/organizations");return o(t,"Failed to fetch organizations"),t.data},async getOrganization(t){let e=await a.GET("/v1/organizations/{slug}",{params:{path:{slug:t}}});return o(e,"Failed to fetch organization"),e.data},async listProjects(){let t=await a.GET("/v1/projects");return o(t,"Failed to fetch projects"),t.data},async getProject(t){let e=await a.GET("/v1/projects/{ref}",{params:{path:{ref:t}}});return o(e,"Failed to fetch project"),e.data},async createProject(t){let{name:e,organization_id:s,region:r,db_pass:n}=N.parse(t),p=await a.POST("/v1/projects",{body:{name:e,region:r,organization_slug:s,db_pass:n??Q({length:16,numbers:!0,uppercase:!0,lowercase:!0})}});return o(p,"Failed to create project"),p.data},async pauseProject(t){let e=await a.POST("/v1/projects/{ref}/pause",{params:{path:{ref:t}}});o(e,"Failed to pause project")},async restoreProject(t){let e=await a.POST("/v1/projects/{ref}/restore",{params:{path:{ref:t}}});o(e,"Failed to restore project")}},w={async executeSql(t,e){let{query:s,parameters:r,read_only:n}=U.parse(e),p=await a.POST("/v1/projects/{ref}/database/query",{params:{path:{ref:t}},body:{query:s,parameters:r,read_only:n}});return T(p,"Failed to execute SQL query",t),p.data},async listMigrations(t){let e=await a.GET("/v1/projects/{ref}/database/migrations",{params:{path:{ref:t}}});return T(e,"Failed to fetch migrations",t),e.data},async applyMigration(t,e){let{name:s,query:r}=D.parse(e),n=await a.POST("/v1/projects/{ref}/database/migrations",{params:{path:{ref:t}},body:{name:s,query:r}});T(n,"Failed to apply migration",t)}},A={logsDialect:"clickhouse",async getLogs(t,e){let{service:s,iso_timestamp_start:r,iso_timestamp_end:n}=H.parse(e),p=B(s),u=await a.GET("/v1/projects/{ref}/analytics/endpoints/logs",{params:{path:{ref:t},query:{sql:p,iso_timestamp_start:r,iso_timestamp_end:n}}});return o(u,"Failed to fetch logs"),u.data},async queryLogs(t,e){let{sql:s,iso_timestamp_start:r,iso_timestamp_end:n}=V.parse(e),p=await a.GET("/v1/projects/{ref}/analytics/endpoints/logs",{params:{path:{ref:t},query:{sql:s,iso_timestamp_start:r,iso_timestamp_end:n}}});return o(p,"Failed to query logs"),p.data},async getSecurityAdvisors(t){let e=await a.GET("/v1/projects/{ref}/advisors/security",{params:{path:{ref:t}}});return o(e,"Failed to fetch security advisors"),e.data},async getPerformanceAdvisors(t){let e=await a.GET("/v1/projects/{ref}/advisors/performance",{params:{path:{ref:t}}});return o(e,"Failed to fetch performance advisors"),e.data},async getHealthAdvisors(t){let e=await l.POST("/v2/projects/{ref}/advisors/run",{params:{path:{ref:t}},body:{data:{type:"project_advisors",attributes:{lints:pe.map(r=>({name:r}))}}}});v(e,"Failed to fetch health advisors");let s=e.data.data.attributes;return{...s,lints:s.lints.filter(({name:r})=>!ce.has(r))}}},W={async getProjectUrl(t){let e=new URL(m);return`https://${t}.${me(e.hostname)}`},async getPublishableKeys(t){let e=await a.GET("/v1/projects/{ref}/api-keys",{params:{path:{ref:t},query:{reveal:"false"}}});o(e,"Failed to fetch API keys");let s;try{let n=await a.GET("/v1/projects/{ref}/api-keys/legacy",{params:{path:{ref:t}}});n.response.ok&&(s=n.data?.enabled??!0)}catch{s=void 0}let r=e.data?.filter(n=>n.name==="anon"||n.type==="publishable")??[];if(r.length===0)throw new Error("No client-safe API keys (anon or publishable) found. Please create a publishable key in your project settings.");return r.map(n=>({api_key:n.api_key,name:n.name,type:n.type==="publishable"?"publishable":"legacy",...s!==void 0&&{disabled:n.type==="legacy"&&!s},description:n.description??void 0,id:n.id??void 0}))},async generateTypescriptTypes(t){let e=await a.GET("/v1/projects/{ref}/types/typescript",{params:{path:{ref:t}}});return o(e,"Failed to fetch TypeScript types"),e.data}},M={async listEdgeFunctions(t){let e=await a.GET("/v1/projects/{ref}/functions",{params:{path:{ref:t}}});return o(e,"Failed to fetch Edge Functions"),e.data.map(s=>{let r=P(t,s.id,s.version),n=s.entrypoint_path?_({deploymentId:r,filename:j(s.entrypoint_path,{windows:!1})}):void 0,p=s.import_map_path?_({deploymentId:r,filename:j(s.import_map_path,{windows:!1})}):void 0;return{...s,entrypoint_path:n,import_map_path:p}})},async getEdgeFunction(t,e){let s=await a.GET("/v1/projects/{ref}/functions/{function_slug}",{params:{path:{ref:t,function_slug:e}}});if(s.error)throw s.error;o(s,"Failed to fetch Edge Function");let r=s.data,n=P(t,r.id,r.version),p=r.entrypoint_path?_({deploymentId:n,filename:j(r.entrypoint_path,{windows:!1})}):void 0,u=r.import_map_path?_({deploymentId:n,filename:j(r.import_map_path,{windows:!1})}):void 0,f=await a.GET("/v1/projects/{ref}/functions/{function_slug}/body",{params:{path:{ref:t,function_slug:e}},headers:{Accept:"multipart/form-data"},parseAs:"stream"});o(f,"Failed to fetch Edge Function files");let y=f.response.headers.get("content-type");if(!y||!y.startsWith("multipart/form-data"))throw new Error(`Unexpected content type: ${y}. Expected multipart/form-data.`);let S=ne(y);if(!S)throw new Error("No multipart boundary found in response headers");if(!f.data)throw new Error("No data received from Edge Function body");let h=[],O=oe(f.data,{boundary:S});for await(let b of O)b.isFile&&b.filename&&h.push({name:_({deploymentId:n,filename:b.filename}),content:b.text});return{...r,entrypoint_path:p,import_map_path:u,files:h}},async deployEdgeFunction(t,e){let{name:s,entrypoint_path:r,import_map_path:n,verify_jwt:p,files:u}=L.parse(e),f;try{f=await M.getEdgeFunction(t,s)}catch{}let y=u.find(h=>["deno.json","import_map.json"].includes(h.name));n??=f?.import_map_path??y?.name;let S=await a.POST("/v1/projects/{ref}/functions/deploy",{params:{path:{ref:t},query:{slug:s}},body:{metadata:{name:s,entrypoint_path:r,import_map_path:n,verify_jwt:p},file:u},bodySerializer(h){let O=new FormData,b=new Blob([JSON.stringify(h.metadata)],{type:"application/json"});return O.append("metadata",b),h.file?.forEach(J=>{let k=J,X=new Blob([k.content],{type:"application/typescript"});O.append("file",X,k.name)}),O}});return o(S,"Failed to deploy Edge Function"),S.data}};return{async init(t){let{clientInfo:e}=t;if(!e)throw new Error("Client info is required");let s={"User-Agent":`schemarch-mcp/${ie} (${e.name}/${e.version})`};a=F(m,c,s),l=C(m,c,s)},account:E,database:w,debugging:A,development:W,functions:M,branching:{async listBranches(t){let e=await a.GET("/v1/projects/{ref}/branches",{params:{path:{ref:t}}});return e.response.status===422?[]:(o(e,"Failed to list branches"),e.data)},async createBranch(t,e){let{name:s}=z.parse(e),r=await a.POST("/v1/projects/{ref}/branches",{params:{path:{ref:t}},body:{branch_name:s}});return o(r,"Failed to create branch"),r.data},async deleteBranch(t){let e=await a.DELETE("/v1/branches/{branch_id_or_ref}",{params:{path:{branch_id_or_ref:t}}});o(e,"Failed to delete branch")},async mergeBranch(t){let e=await a.POST("/v1/branches/{branch_id_or_ref}/merge",{params:{path:{branch_id_or_ref:t}},body:{}});o(e,"Failed to merge branch")},async resetBranch(t,e){let{migration_version:s}=q.parse(e),r=await a.POST("/v1/branches/{branch_id_or_ref}/reset",{params:{path:{branch_id_or_ref:t}},body:{migration_version:s}});o(r,"Failed to reset branch")},async rebaseBranch(t){let e=await a.POST("/v1/branches/{branch_id_or_ref}/push",{params:{path:{branch_id_or_ref:t}},body:{}});o(e,"Failed to rebase branch")}},storage:{async listAllBuckets(t){let e=await a.GET("/v1/projects/{ref}/storage/buckets",{params:{path:{ref:t}}});return o(e,"Failed to list storage buckets"),e.data},async getStorageConfig(t){let e=await a.GET("/v1/projects/{ref}/config/storage",{params:{path:{ref:t}}});return o(e,"Failed to get storage config"),e.data},async updateStorageConfig(t,e){let s=await a.PATCH("/v1/projects/{ref}/config/storage",{params:{path:{ref:t}},body:{fileSizeLimit:e.fileSizeLimit,features:{imageTransformation:{enabled:e.features.imageTransformation.enabled},s3Protocol:{enabled:e.features.s3Protocol.enabled}}}});o(s,"Failed to update storage config")}},secrets:{async getUpdatedAt(t,e){let s=await a.GET("/v1/projects/{ref}/secrets",{params:{path:{ref:t}}});o(s,"Failed to fetch secrets");let r=s.data.find(n=>n.name===e);if(!(!r||!r.updated_at))return new Date(r.updated_at)}},notebooks:{async createNotebook(t,e){let s=$.parse(e),r=await l.POST("/v2/projects/{ref}/notebooks",{params:{path:{ref:t}},body:{data:{type:"notebook",attributes:s}}});v(r,"Failed to create notebook");let{id:n,attributes:p}=r.data.data;return{id:n,...p}},async listNotebooks(t){let e=[],s;do{let r=await l.GET("/v2/projects/{ref}/notebooks",{params:{path:{ref:t},query:s?{page:{after:s}}:void 0}});v(r,"Failed to retrieve project's notebooks"),e.push(...r.data.data.map(({id:n,attributes:p})=>({id:n,...p}))),s=de(r.data.links.next)}while(s);return e},async getNotebook(t,e){let s=await l.GET("/v2/projects/{ref}/notebooks/{id}",{params:{path:{ref:t,id:e}}});v(s,"Failed to retrieve notebook");let{id:r,attributes:n}=s.data.data;return{id:r,...n}}},feedback:G({environment:new URL(m).origin==="https://api.schemarch.com"?"production":"staging",async getUserId(){return g??=(await a.GET("/v1/profile",{signal:AbortSignal.timeout(5e3)})).response.headers.get("X-Gotrue-Id")??void 0,g}})}}function de(i){return i?new URL(i,"https://schemarch.com").searchParams.get("page[after]")??void 0:void 0}function me(i){switch(i){case"api.schemarch.com":return"schemarch.co";case"api.schemarch.green":return"schemarch.green";default:return"schemarch.red"}}export{xe as a};
|
|
2
|
+
//# sourceMappingURL=chunk-5DTK5H23.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/platform/api-platform.ts","../src/management-api/index.ts","../src/management-api-v2/index.ts","../src/password.ts"],"sourcesContent":["import {\n getMultipartBoundary,\n parseMultipartStream,\n} from '@mjackson/multipart-parser';\nimport type { InitData } from '@schemarch/mcp-utils';\nimport { fileURLToPath } from 'node:url';\nimport packageJson from '../../package.json' with { type: 'json' };\nimport { getDeploymentId, normalizeFilename } from '../edge-function.js';\nimport { getClickHouseLogQuery } from '../logs.js';\nimport {\n assertProjectScopedSuccess,\n assertSuccess,\n createManagementApiClient,\n} from '../management-api/index.js';\nimport {\n assertSuccessV2,\n createManagementApiV2Client,\n} from '../management-api-v2/index.js';\nimport type { components as ManagementApiV2Components } from '../management-api-v2/types.js';\nimport { generatePassword } from '../password.js';\nimport { createFeedbackOperations } from './feedback.js';\nimport {\n applyMigrationOptionsSchema,\n createNotebookOptionsSchema,\n createBranchOptionsSchema,\n createProjectOptionsSchema,\n deployEdgeFunctionOptionsSchema,\n executeSqlOptionsSchema,\n getLogsOptionsSchema,\n queryLogsOptionsSchema,\n resetBranchOptionsSchema,\n type AccountOperations,\n type ApiKey,\n type ApiKeyType,\n type ApplyMigrationOptions,\n type BranchingOperations,\n type CreateBranchOptions,\n type CreateProjectOptions,\n type DatabaseOperations,\n type DebuggingOperations,\n type DeployEdgeFunctionOptions,\n type DevelopmentOperations,\n type SuccessResponse,\n type EdgeFunction,\n type EdgeFunctionsOperations,\n type EdgeFunctionWithBody,\n type ExecuteSqlOptions,\n type GetLogsOptions,\n type Notebook,\n type NotebookOperations,\n type QueryLogsOptions,\n type ResetBranchOptions,\n type SecretOperations,\n type StorageConfig,\n type StorageOperations,\n type SchemarchPlatform,\n} from './index.js';\n\nconst { version } = packageJson;\n\nconst SUCCESS_RESPONSE: SuccessResponse = { success: true };\n\ntype HealthAdvisorName =\n ManagementApiV2Components['schemas']['V2RunProjectAdvisorsBody']['data']['attributes']['lints'][number]['name'];\n\nconst healthAdvisorNames = [\n 'log_data_api_error_rate_high',\n 'log_auth_error_rate_high',\n 'log_storage_error_rate_high',\n 'log_edge_function_error_rate_high',\n] as const satisfies readonly HealthAdvisorName[];\n\nconst hiddenHealthAdvisorResultNames: ReadonlySet<string> = new Set([\n 'project_not_active',\n 'advisor_check_unavailable',\n]);\n\nexport type SchemarchApiPlatformOptions = {\n /**\n * The access token for the Schemarch Management API.\n */\n accessToken: string;\n\n /**\n * The API URL for the Schemarch Management API.\n */\n apiUrl?: string;\n};\n\n/**\n * Creates a Schemarch platform implementation using the Schemarch Management API.\n */\nexport function createSchemarchApiPlatform(\n options: SchemarchApiPlatformOptions\n): SchemarchPlatform {\n const { accessToken, apiUrl } = options;\n\n const managementApiUrl = apiUrl ?? 'https://api.schemarch.com';\n\n let userId: string | undefined;\n\n let managementApiClient = createManagementApiClient(\n managementApiUrl,\n accessToken\n );\n let managementApiV2Client = createManagementApiV2Client(\n managementApiUrl,\n accessToken\n );\n\n const account: AccountOperations = {\n async listOrganizations() {\n const response = await managementApiClient.GET('/v1/organizations');\n\n assertSuccess(response, 'Failed to fetch organizations');\n\n return response.data;\n },\n async getOrganization(organizationId: string) {\n const response = await managementApiClient.GET(\n '/v1/organizations/{slug}',\n {\n params: {\n path: {\n slug: organizationId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch organization');\n\n return response.data;\n },\n async listProjects() {\n const response = await managementApiClient.GET('/v1/projects');\n\n assertSuccess(response, 'Failed to fetch projects');\n\n return response.data;\n },\n async getProject(projectId: string) {\n const response = await managementApiClient.GET('/v1/projects/{ref}', {\n params: {\n path: {\n ref: projectId,\n },\n },\n });\n assertSuccess(response, 'Failed to fetch project');\n return response.data;\n },\n async createProject(options: CreateProjectOptions) {\n const { name, organization_id, region, db_pass } =\n createProjectOptionsSchema.parse(options);\n\n const response = await managementApiClient.POST('/v1/projects', {\n body: {\n name,\n region,\n organization_slug: organization_id,\n db_pass:\n db_pass ??\n generatePassword({\n length: 16,\n numbers: true,\n uppercase: true,\n lowercase: true,\n }),\n },\n });\n\n assertSuccess(response, 'Failed to create project');\n\n return response.data;\n },\n async pauseProject(projectId: string) {\n const response = await managementApiClient.POST(\n '/v1/projects/{ref}/pause',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to pause project');\n },\n async restoreProject(projectId: string) {\n const response = await managementApiClient.POST(\n '/v1/projects/{ref}/restore',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to restore project');\n },\n };\n\n const database: DatabaseOperations = {\n async executeSql<T>(projectId: string, options: ExecuteSqlOptions) {\n const { query, parameters, read_only } =\n executeSqlOptionsSchema.parse(options);\n\n const response = await managementApiClient.POST(\n '/v1/projects/{ref}/database/query',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n body: {\n query,\n parameters,\n read_only,\n },\n }\n );\n\n assertProjectScopedSuccess(\n response,\n 'Failed to execute SQL query',\n projectId\n );\n\n return response.data as unknown as T[];\n },\n async listMigrations(projectId: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/database/migrations',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n assertProjectScopedSuccess(\n response,\n 'Failed to fetch migrations',\n projectId\n );\n\n return response.data;\n },\n async applyMigration(projectId: string, options: ApplyMigrationOptions) {\n const { name, query } = applyMigrationOptionsSchema.parse(options);\n\n const response = await managementApiClient.POST(\n '/v1/projects/{ref}/database/migrations',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n body: {\n name,\n query,\n },\n }\n );\n\n assertProjectScopedSuccess(\n response,\n 'Failed to apply migration',\n projectId\n );\n\n // Intentionally don't return the result of the migration\n // to avoid prompt injection attacks. If the migration failed,\n // it will throw an error.\n },\n };\n\n const debugging: DebuggingOperations = {\n logsDialect: 'clickhouse',\n async getLogs(projectId: string, options: GetLogsOptions) {\n const { service, iso_timestamp_start, iso_timestamp_end } =\n getLogsOptionsSchema.parse(options);\n\n const sql = getClickHouseLogQuery(service);\n\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/analytics/endpoints/logs',\n {\n params: {\n path: {\n ref: projectId,\n },\n query: {\n sql,\n iso_timestamp_start,\n iso_timestamp_end,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch logs');\n\n return response.data;\n },\n async queryLogs(projectId: string, options: QueryLogsOptions) {\n const { sql, iso_timestamp_start, iso_timestamp_end } =\n queryLogsOptionsSchema.parse(options);\n\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/analytics/endpoints/logs',\n {\n params: {\n path: {\n ref: projectId,\n },\n query: {\n sql,\n iso_timestamp_start,\n iso_timestamp_end,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to query logs');\n\n return response.data;\n },\n async getSecurityAdvisors(projectId: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/advisors/security',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch security advisors');\n\n return response.data;\n },\n async getPerformanceAdvisors(projectId: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/advisors/performance',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch performance advisors');\n\n return response.data;\n },\n async getHealthAdvisors(projectId: string) {\n const response = await managementApiV2Client.POST(\n '/v2/projects/{ref}/advisors/run',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n body: {\n data: {\n type: 'project_advisors',\n attributes: {\n lints: healthAdvisorNames.map((name) => ({ name })),\n },\n },\n },\n }\n );\n\n assertSuccessV2(response, 'Failed to fetch health advisors');\n\n const attributes = response.data.data.attributes;\n\n return {\n ...attributes,\n lints: attributes.lints.filter(\n ({ name }) => !hiddenHealthAdvisorResultNames.has(name)\n ),\n };\n },\n };\n\n const development: DevelopmentOperations = {\n async getProjectUrl(projectId: string): Promise<string> {\n const apiUrl = new URL(managementApiUrl);\n return `https://${projectId}.${getProjectDomain(apiUrl.hostname)}`;\n },\n async getPublishableKeys(projectId: string): Promise<ApiKey[]> {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/api-keys',\n {\n params: {\n path: {\n ref: projectId,\n },\n query: {\n reveal: 'false',\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch API keys');\n\n // Try to check if legacy JWT-based keys are enabled\n // If this fails, we'll continue without the disabled field\n let legacyKeysEnabled: boolean | undefined = undefined;\n try {\n const legacyKeysResponse = await managementApiClient.GET(\n '/v1/projects/{ref}/api-keys/legacy',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n if (legacyKeysResponse.response.ok) {\n legacyKeysEnabled = legacyKeysResponse.data?.enabled ?? true;\n }\n } catch (error) {\n // If we can't fetch legacy key status, continue without it\n legacyKeysEnabled = undefined;\n }\n\n // Filter for client-safe keys: legacy 'anon' or publishable type\n const clientKeys =\n response.data?.filter(\n (key) => key.name === 'anon' || key.type === 'publishable'\n ) ?? [];\n\n if (clientKeys.length === 0) {\n throw new Error(\n 'No client-safe API keys (anon or publishable) found. Please create a publishable key in your project settings.'\n );\n }\n\n return clientKeys.map((key) => ({\n api_key: key.api_key!,\n name: key.name,\n type: (key.type === 'publishable'\n ? 'publishable'\n : 'legacy') satisfies ApiKeyType,\n // Only include disabled field if we successfully fetched legacy key status\n ...(legacyKeysEnabled !== undefined && {\n disabled: key.type === 'legacy' && !legacyKeysEnabled,\n }),\n description: key.description ?? undefined,\n id: key.id ?? undefined,\n }));\n },\n async generateTypescriptTypes(projectId: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/types/typescript',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch TypeScript types');\n\n return response.data;\n },\n };\n\n const functions: EdgeFunctionsOperations = {\n async listEdgeFunctions(projectId: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/functions',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch Edge Functions');\n\n return response.data.map((edgeFunction) => {\n const deploymentId = getDeploymentId(\n projectId,\n edgeFunction.id,\n edgeFunction.version\n );\n\n const entrypoint_path = edgeFunction.entrypoint_path\n ? normalizeFilename({\n deploymentId,\n filename: fileURLToPath(edgeFunction.entrypoint_path, {\n windows: false,\n }),\n })\n : undefined;\n\n const import_map_path = edgeFunction.import_map_path\n ? normalizeFilename({\n deploymentId,\n filename: fileURLToPath(edgeFunction.import_map_path, {\n windows: false,\n }),\n })\n : undefined;\n\n return {\n ...edgeFunction,\n entrypoint_path,\n import_map_path,\n };\n });\n },\n async getEdgeFunction(projectId: string, functionSlug: string) {\n const functionResponse = await managementApiClient.GET(\n '/v1/projects/{ref}/functions/{function_slug}',\n {\n params: {\n path: {\n ref: projectId,\n function_slug: functionSlug,\n },\n },\n }\n );\n\n if (functionResponse.error) {\n throw functionResponse.error;\n }\n\n assertSuccess(functionResponse, 'Failed to fetch Edge Function');\n\n const edgeFunction = functionResponse.data;\n\n const deploymentId = getDeploymentId(\n projectId,\n edgeFunction.id,\n edgeFunction.version\n );\n\n const entrypoint_path = edgeFunction.entrypoint_path\n ? normalizeFilename({\n deploymentId,\n filename: fileURLToPath(edgeFunction.entrypoint_path, {\n windows: false,\n }),\n })\n : undefined;\n\n const import_map_path = edgeFunction.import_map_path\n ? normalizeFilename({\n deploymentId,\n filename: fileURLToPath(edgeFunction.import_map_path, {\n windows: false,\n }),\n })\n : undefined;\n\n const bodyResponse = await managementApiClient.GET(\n '/v1/projects/{ref}/functions/{function_slug}/body',\n {\n params: {\n path: {\n ref: projectId,\n function_slug: functionSlug,\n },\n },\n headers: {\n Accept: 'multipart/form-data',\n },\n parseAs: 'stream',\n }\n );\n\n assertSuccess(bodyResponse, 'Failed to fetch Edge Function files');\n\n const contentType = bodyResponse.response.headers.get('content-type');\n\n if (!contentType || !contentType.startsWith('multipart/form-data')) {\n throw new Error(\n `Unexpected content type: ${contentType}. Expected multipart/form-data.`\n );\n }\n\n const boundary = getMultipartBoundary(contentType);\n\n if (!boundary) {\n throw new Error('No multipart boundary found in response headers');\n }\n\n if (!bodyResponse.data) {\n throw new Error('No data received from Edge Function body');\n }\n\n const files: EdgeFunctionWithBody['files'] = [];\n const parts = parseMultipartStream(bodyResponse.data, { boundary });\n\n for await (const part of parts) {\n if (part.isFile && part.filename) {\n files.push({\n name: normalizeFilename({\n deploymentId,\n filename: part.filename,\n }),\n content: part.text,\n });\n }\n }\n\n return {\n ...edgeFunction,\n entrypoint_path,\n import_map_path,\n files,\n };\n },\n async deployEdgeFunction(\n projectId: string,\n options: DeployEdgeFunctionOptions\n ) {\n let {\n name,\n entrypoint_path,\n import_map_path,\n verify_jwt,\n files: inputFiles,\n } = deployEdgeFunctionOptionsSchema.parse(options);\n\n let existingEdgeFunction: EdgeFunction | undefined;\n try {\n existingEdgeFunction = await functions.getEdgeFunction(projectId, name);\n } catch (error) {}\n\n const import_map_file = inputFiles.find((file) =>\n ['deno.json', 'import_map.json'].includes(file.name)\n );\n\n // Use existing import map path or file name heuristic if not provided\n import_map_path ??=\n existingEdgeFunction?.import_map_path ?? import_map_file?.name;\n\n const response = await managementApiClient.POST(\n '/v1/projects/{ref}/functions/deploy',\n {\n params: {\n path: {\n ref: projectId,\n },\n query: { slug: name },\n },\n body: {\n metadata: {\n name,\n entrypoint_path,\n import_map_path,\n verify_jwt,\n },\n file: inputFiles as any, // We need to pass file name and content to our serializer\n },\n bodySerializer(body) {\n const formData = new FormData();\n\n const blob = new Blob([JSON.stringify(body.metadata)], {\n type: 'application/json',\n });\n formData.append('metadata', blob);\n\n body.file?.forEach((f: any) => {\n const file: { name: string; content: string } = f;\n const blob = new Blob([file.content], {\n type: 'application/typescript',\n });\n formData.append('file', blob, file.name);\n });\n\n return formData;\n },\n }\n );\n\n assertSuccess(response, 'Failed to deploy Edge Function');\n\n return response.data;\n },\n };\n\n const branching: BranchingOperations = {\n async listBranches(projectId: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/branches',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n // There are no branches if branching is disabled\n if (response.response.status === 422) return [];\n assertSuccess(response, 'Failed to list branches');\n\n return response.data;\n },\n async createBranch(projectId: string, options: CreateBranchOptions) {\n const { name } = createBranchOptionsSchema.parse(options);\n\n const createBranchResponse = await managementApiClient.POST(\n '/v1/projects/{ref}/branches',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n body: {\n branch_name: name,\n },\n }\n );\n\n assertSuccess(createBranchResponse, 'Failed to create branch');\n\n return createBranchResponse.data;\n },\n async deleteBranch(branchId: string) {\n const response = await managementApiClient.DELETE(\n '/v1/branches/{branch_id_or_ref}',\n {\n params: {\n path: {\n branch_id_or_ref: branchId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to delete branch');\n },\n async mergeBranch(branchId: string) {\n const response = await managementApiClient.POST(\n '/v1/branches/{branch_id_or_ref}/merge',\n {\n params: {\n path: {\n branch_id_or_ref: branchId,\n },\n },\n body: {},\n }\n );\n\n assertSuccess(response, 'Failed to merge branch');\n },\n async resetBranch(branchId: string, options: ResetBranchOptions) {\n const { migration_version } = resetBranchOptionsSchema.parse(options);\n\n const response = await managementApiClient.POST(\n '/v1/branches/{branch_id_or_ref}/reset',\n {\n params: {\n path: {\n branch_id_or_ref: branchId,\n },\n },\n body: {\n migration_version,\n },\n }\n );\n\n assertSuccess(response, 'Failed to reset branch');\n },\n async rebaseBranch(branchId: string) {\n const response = await managementApiClient.POST(\n '/v1/branches/{branch_id_or_ref}/push',\n {\n params: {\n path: {\n branch_id_or_ref: branchId,\n },\n },\n body: {},\n }\n );\n\n assertSuccess(response, 'Failed to rebase branch');\n },\n };\n\n const storage: StorageOperations = {\n // Storage methods\n async listAllBuckets(project_id: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/storage/buckets',\n {\n params: {\n path: {\n ref: project_id,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to list storage buckets');\n\n return response.data;\n },\n\n async getStorageConfig(project_id: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/config/storage',\n {\n params: {\n path: {\n ref: project_id,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to get storage config');\n\n return response.data;\n },\n\n async updateStorageConfig(projectId: string, config: StorageConfig) {\n const response = await managementApiClient.PATCH(\n '/v1/projects/{ref}/config/storage',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n body: {\n fileSizeLimit: config.fileSizeLimit,\n features: {\n imageTransformation: {\n enabled: config.features.imageTransformation.enabled,\n },\n s3Protocol: {\n enabled: config.features.s3Protocol.enabled,\n },\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to update storage config');\n },\n };\n\n const secrets: SecretOperations = {\n async getUpdatedAt(projectId: string, name: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/secrets',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch secrets');\n\n const secret = response.data.find((s) => s.name === name);\n if (!secret || !secret.updated_at) {\n return undefined;\n }\n\n return new Date(secret.updated_at);\n },\n };\n\n const notebooks: NotebookOperations = {\n async createNotebook(projectId, options) {\n const attributes = createNotebookOptionsSchema.parse(options);\n const response = await managementApiV2Client.POST(\n '/v2/projects/{ref}/notebooks',\n {\n params: { path: { ref: projectId } },\n body: { data: { type: 'notebook', attributes } },\n }\n );\n\n assertSuccessV2(response, 'Failed to create notebook');\n\n const { id, attributes: notebook } = response.data.data;\n return { id, ...notebook };\n },\n async listNotebooks(projectId: string) {\n const notebooks: Notebook[] = [];\n let cursor: string | undefined;\n\n do {\n const response = await managementApiV2Client.GET(\n '/v2/projects/{ref}/notebooks',\n {\n params: {\n path: {\n ref: projectId,\n },\n query: cursor ? { page: { after: cursor } } : undefined,\n },\n }\n );\n\n assertSuccessV2(response, \"Failed to retrieve project's notebooks\");\n\n notebooks.push(\n ...response.data.data.map(({ id, attributes }) => ({\n id,\n ...attributes,\n }))\n );\n\n cursor = getNextNotebooksCursor(response.data.links.next);\n } while (cursor);\n\n return notebooks;\n },\n async getNotebook(projectId: string, notebookId: string) {\n const response = await managementApiV2Client.GET(\n '/v2/projects/{ref}/notebooks/{id}',\n {\n params: {\n path: {\n ref: projectId,\n id: notebookId,\n },\n },\n }\n );\n\n assertSuccessV2(response, 'Failed to retrieve notebook');\n\n const { id, attributes } = response.data.data;\n\n return { id, ...attributes };\n },\n };\n\n const platform: SchemarchPlatform = {\n async init(info: InitData) {\n const { clientInfo } = info;\n if (!clientInfo) {\n throw new Error('Client info is required');\n }\n\n // Re-initialize the management API clients with the user agent\n const userAgentHeaders = {\n 'User-Agent': `schemarch-mcp/${version} (${clientInfo.name}/${clientInfo.version})`,\n };\n managementApiClient = createManagementApiClient(\n managementApiUrl,\n accessToken,\n userAgentHeaders\n );\n managementApiV2Client = createManagementApiV2Client(\n managementApiUrl,\n accessToken,\n userAgentHeaders\n );\n },\n account,\n database,\n debugging,\n development,\n functions,\n branching,\n storage,\n secrets,\n notebooks,\n feedback: createFeedbackOperations({\n // Staging, local, and custom API URLs keep their feedback out of production\n environment:\n new URL(managementApiUrl).origin === 'https://api.schemarch.com'\n ? 'production'\n : 'staging',\n async getUserId() {\n // X-Gotrue-Id is set on every response, see how CLI uses this too: https://github.com/schemarch/cli/blob/8a549dffa6bc5c88069c61c1f55ef55ad9b82ae2/apps/cli/src/command-internal/identity-stitch.ts#L10-L20\n userId ??=\n (\n await managementApiClient.GET('/v1/profile', {\n signal: AbortSignal.timeout(5_000),\n })\n ).response.headers.get('X-Gotrue-Id') ?? undefined;\n return userId;\n },\n }),\n };\n\n return platform;\n}\n\n/**\n * Extracts the `page[after]` cursor from a JSON:API `links.next` URL path\n * (e.g. `/v2/projects/{ref}/notebooks?page[size]=10&page[after]=<cursor>`).\n */\nfunction getNextNotebooksCursor(next: string | null | undefined) {\n if (!next) {\n return undefined;\n }\n\n const url = new URL(next, 'https://schemarch.com');\n return url.searchParams.get('page[after]') ?? undefined;\n}\n\nfunction getProjectDomain(apiHostname: string) {\n switch (apiHostname) {\n case 'api.schemarch.com':\n return 'schemarch.co';\n case 'api.schemarch.green':\n return 'schemarch.green';\n default:\n return 'schemarch.red';\n }\n}\n","import createClient, {\n type Client,\n type FetchResponse,\n type ParseAsResponse,\n} from 'openapi-fetch';\nimport type {\n MediaType,\n ResponseObjectMap,\n SuccessResponse,\n} from 'openapi-typescript-helpers';\nimport { z } from 'zod/v4';\nimport type { paths } from './types.js';\n\nexport function createManagementApiClient(\n baseUrl: string,\n accessToken: string,\n headers: Record<string, string> = {}\n) {\n return createClient<paths>({\n baseUrl,\n headers: {\n Authorization: `Bearer ${accessToken}`,\n ...headers,\n },\n });\n}\n\nexport type ManagementApiClient = Client<paths>;\n\nexport type SuccessResponseType<\n T extends Record<string | number, any>,\n Options,\n Media extends MediaType,\n> = {\n data: ParseAsResponse<SuccessResponse<ResponseObjectMap<T>, Media>, Options>;\n error?: never;\n response: Response;\n};\n\nconst errorSchema = z.object({\n message: z.string(),\n});\n\nexport function assertSuccess<\n T extends Record<string | number, any>,\n Options,\n Media extends MediaType,\n>(\n response: FetchResponse<T, Options, Media>,\n fallbackMessage: string\n): asserts response is SuccessResponseType<T, Options, Media> {\n if ('error' in response) {\n if (response.response.status === 401) {\n throw new Error(\n 'Unauthorized. Please provide a valid access token to the MCP server via the --access-token flag or SCHEMARCH_ACCESS_TOKEN.'\n );\n }\n\n const { data: errorContent } = errorSchema.safeParse(response.error);\n\n if (errorContent) {\n throw new Error(errorContent.message);\n }\n\n throw new Error(fallbackMessage);\n }\n}\n\n/**\n * Asserts success for project-scoped endpoints, mapping 403 responses to an\n * actionable message. A permission error on a specific project most commonly\n * means the access token is scoped to an organization that doesn't own the\n * project (e.g. the wrong organization was selected during OAuth login).\n *\n * Currently applied only to database operations (see AI-178). Before adopting\n * for other endpoints, check that a 403 there isn't better explained by plan\n * or role restrictions, where org-selection advice would mislead.\n */\nexport function assertProjectScopedSuccess<\n T extends Record<string | number, any>,\n Options,\n Media extends MediaType,\n>(\n response: FetchResponse<T, Options, Media>,\n fallbackMessage: string,\n projectId: string\n): asserts response is SuccessResponseType<T, Options, Media> {\n if ('error' in response && response.response.status === 403) {\n const { data: errorContent } = errorSchema.safeParse(response.error);\n const apiMessage = (errorContent?.message ?? fallbackMessage).replace(\n /\\.$/,\n ''\n );\n\n throw new Error(\n `${apiMessage}. Access to project '${projectId}' was denied. If this project exists, your access token may be scoped to a different organization: re-authenticate with the MCP server and select the organization that owns this project.`\n );\n }\n\n assertSuccess(response, fallbackMessage);\n}\n","import createClient, {\n type Client,\n type FetchResponse,\n type ParseAsResponse,\n} from 'openapi-fetch';\nimport type {\n MediaType,\n ResponseObjectMap,\n SuccessResponse as OpenApiSuccessResponse,\n} from 'openapi-typescript-helpers';\nimport { z } from 'zod/v4';\nimport type { paths } from './types.js';\n\nexport function createManagementApiV2Client(\n baseUrl: string,\n accessToken: string,\n headers: Record<string, string> = {}\n) {\n return createClient<paths>({\n baseUrl,\n headers: {\n Authorization: `Bearer ${accessToken}`,\n ...headers,\n },\n });\n}\n\nexport type ManagementApiV2Client = Client<paths>;\n\ntype SuccessResponseType<\n T extends Record<string | number, any>,\n Options,\n Media extends MediaType,\n> = {\n data: ParseAsResponse<\n OpenApiSuccessResponse<ResponseObjectMap<T>, Media>,\n Options\n >;\n error?: never;\n response: Response;\n};\n\nconst errorSchema = z.object({\n error: z.object({\n message: z.string(),\n }),\n});\n\n/**\n * Asserts success for v2 (JSON:API-style) endpoints. Error bodies here are\n * shaped as `{ error: { message, code, ... } }`, unlike v1's flat\n * `{ message }` — so this can't reuse `assertSuccess` from `management-api`.\n */\nexport function assertSuccessV2<\n T extends Record<string | number, any>,\n Options,\n Media extends MediaType,\n>(\n response: FetchResponse<T, Options, Media>,\n fallbackMessage: string\n): asserts response is SuccessResponseType<T, Options, Media> {\n if ('error' in response) {\n if (response.response.status === 401) {\n throw new Error(\n 'Unauthorized. Please provide a valid access token to the MCP server via the --access-token flag or SCHEMARCH_ACCESS_TOKEN.'\n );\n }\n\n const { data: errorContent } = errorSchema.safeParse(response.error);\n\n if (errorContent) {\n throw new Error(errorContent.error.message);\n }\n\n throw new Error(fallbackMessage);\n }\n}\n","const UPPERCASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\nconst LOWERCASE_CHARS = 'abcdefghijklmnopqrstuvwxyz';\nconst NUMBER_CHARS = '0123456789';\nconst SYMBOL_CHARS = '!@#$%^&*()_+~`|}{[]:;?><,./-=';\n\nexport type GeneratePasswordOptions = {\n length?: number;\n numbers?: boolean;\n uppercase?: boolean;\n lowercase?: boolean;\n symbols?: boolean;\n};\n\n/**\n * Generates a cryptographically secure random password.\n *\n * @returns The generated password\n */\nexport const generatePassword = ({\n length = 10,\n numbers = false,\n symbols = false,\n uppercase = true,\n lowercase = true,\n} = {}) => {\n // Build the character set based on options\n let chars = '';\n if (uppercase) {\n chars += UPPERCASE_CHARS;\n }\n if (lowercase) {\n chars += LOWERCASE_CHARS;\n }\n if (numbers) {\n chars += NUMBER_CHARS;\n }\n if (symbols) {\n chars += SYMBOL_CHARS;\n }\n\n if (chars.length === 0) {\n throw new Error('at least one character set must be selected');\n }\n\n const randomValues = new Uint32Array(length);\n crypto.getRandomValues(randomValues);\n\n // Map random values to our character set\n let password = '';\n for (let i = 0; i < length; i++) {\n const randomIndex = randomValues[i]! % chars.length;\n password += chars.charAt(randomIndex);\n }\n\n return password;\n};\n"],"mappings":"oKAAA,OACE,wBAAAA,GACA,wBAAAC,OACK,6BAEP,OAAS,iBAAAC,MAAqB,MCL9B,OAAOC,MAIA,gBAMP,OAAS,KAAAC,MAAS,SAGX,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,EAAU,KACR,GAAG7E,EAAS,KAAK,KAAK,IAAI,CAAC,CAAE,GAAA2E,EAAI,WAAAjD,CAAW,KAAO,CACjD,GAAAiD,EACA,GAAGjD,CACL,EAAE,CACJ,EAEAoD,EAASC,GAAuB/E,EAAS,KAAK,MAAM,IAAI,CAC1D,OAAS8E,GAET,OAAOD,CACT,EACA,MAAM,YAAY1E,EAAmB6E,EAAoB,CACvD,IAAMhF,EAAW,MAAMH,EAAsB,IAC3C,oCACA,CACE,OAAQ,CACN,KAAM,CACJ,IAAKM,EACL,GAAI6E,CACN,CACF,CACF,CACF,EAEAvD,EAAgBzB,EAAU,6BAA6B,EAEvD,GAAM,CAAE,GAAA2E,EAAI,WAAAjD,CAAW,EAAI1B,EAAS,KAAK,KAEzC,MAAO,CAAE,GAAA2E,EAAI,GAAGjD,CAAW,CAC7B,CACF,EAiCE,SAAUuD,EAAyB,CAEjC,YACE,IAAI,IAAIxF,CAAgB,EAAE,SAAW,4BACjC,aACA,UACN,MAAM,WAAY,CAEhB,OAAAC,KAEI,MAAMC,EAAoB,IAAI,cAAe,CAC3C,OAAQ,YAAY,QAAQ,GAAK,CACnC,CAAC,GACD,SAAS,QAAQ,IAAI,aAAa,GAAK,OACpCD,CACT,CACF,CAAC,CACH,CAGF,CAMA,SAASqF,GAAuBG,EAAiC,CAC/D,OAAKA,EAIO,IAAI,IAAIA,EAAM,uBAAuB,EACtC,aAAa,IAAI,aAAa,GAAK,OAJ5C,MAKJ,CAEA,SAAStD,GAAiBuD,EAAqB,CAC7C,OAAQA,EAAa,CACnB,IAAK,oBACH,MAAO,eACT,IAAK,sBACH,MAAO,kBACT,QACE,MAAO,eACX,CACF","names":["getMultipartBoundary","parseMultipartStream","fileURLToPath","createClient","z","createManagementApiClient","baseUrl","accessToken","headers","errorSchema","assertSuccess","response","fallbackMessage","errorContent","assertProjectScopedSuccess","projectId","apiMessage","createClient","z","createManagementApiV2Client","baseUrl","accessToken","headers","errorSchema","assertSuccessV2","response","fallbackMessage","errorContent","UPPERCASE_CHARS","LOWERCASE_CHARS","NUMBER_CHARS","SYMBOL_CHARS","generatePassword","length","numbers","symbols","uppercase","lowercase","chars","randomValues","password","i","randomIndex","version","package_default","healthAdvisorNames","hiddenHealthAdvisorResultNames","createSchemarchApiPlatform","options","accessToken","apiUrl","managementApiUrl","userId","managementApiClient","createManagementApiClient","managementApiV2Client","createManagementApiV2Client","account","response","assertSuccess","organizationId","projectId","name","organization_id","region","db_pass","createProjectOptionsSchema","generatePassword","database","query","parameters","read_only","executeSqlOptionsSchema","assertProjectScopedSuccess","applyMigrationOptionsSchema","debugging","service","iso_timestamp_start","iso_timestamp_end","getLogsOptionsSchema","sql","getClickHouseLogQuery","queryLogsOptionsSchema","assertSuccessV2","attributes","development","getProjectDomain","legacyKeysEnabled","legacyKeysResponse","clientKeys","key","functions","edgeFunction","deploymentId","getDeploymentId","entrypoint_path","normalizeFilename","fileURLToPath","import_map_path","functionSlug","functionResponse","bodyResponse","contentType","boundary","getMultipartBoundary","files","parts","parseMultipartStream","part","verify_jwt","inputFiles","deployEdgeFunctionOptionsSchema","existingEdgeFunction","import_map_file","file","body","formData","blob","f","info","clientInfo","userAgentHeaders","version","createBranchOptionsSchema","createBranchResponse","branchId","migration_version","resetBranchOptionsSchema","project_id","config","secret","s","createNotebookOptionsSchema","id","notebook","notebooks","cursor","getNextNotebooksCursor","notebookId","createFeedbackOperations","next","apiHostname"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkN4WMNFDYcjs = require('./chunk-N4WMNFDY.cjs');var _chunkGEJ6NAOCcjs = require('./chunk-GEJ6NAOC.cjs');var _multipartparser = require('@mjackson/multipart-parser');var _url = require('url');var _openapifetch = require('openapi-fetch'); var _openapifetch2 = _interopRequireDefault(_openapifetch);var _v4 = require('zod/v4');function F(i,c,d={}){return _openapifetch2.default.call(void 0, {baseUrl:i,headers:{Authorization:`Bearer ${c}`,...d}})}var I=_v4.z.object({message:_v4.z.string()});function o(i,c){if("error"in i){if(i.response.status===401)throw new Error("Unauthorized. Please provide a valid access token to the MCP server via the --access-token flag or SCHEMARCH_ACCESS_TOKEN.");let{data:d}=I.safeParse(i.error);throw d?new Error(d.message):new Error(c)}}function T(i,c,d){if("error"in i&&i.response.status===403){let{data:m}=I.safeParse(i.error),g=(_nullishCoalesce(_optionalChain([m, 'optionalAccess', _2 => _2.message]), () => (c))).replace(/\.$/,"");throw new Error(`${g}. Access to project '${d}' was denied. If this project exists, your access token may be scoped to a different organization: re-authenticate with the MCP server and select the organization that owns this project.`)}o(i,c)}function C(i,c,d={}){return _openapifetch2.default.call(void 0, {baseUrl:i,headers:{Authorization:`Bearer ${c}`,...d}})}var ee=_v4.z.object({error:_v4.z.object({message:_v4.z.string()})});function v(i,c){if("error"in i){if(i.response.status===401)throw new Error("Unauthorized. Please provide a valid access token to the MCP server via the --access-token flag or SCHEMARCH_ACCESS_TOKEN.");let{data:d}=ee.safeParse(i.error);throw d?new Error(d.error.message):new Error(c)}}var te="ABCDEFGHIJKLMNOPQRSTUVWXYZ",se="abcdefghijklmnopqrstuvwxyz",re="0123456789",ae="!@#$%^&*()_+~`|}{[]:;?><,./-=",Q=({length:i=10,numbers:c=!1,symbols:d=!1,uppercase:m=!0,lowercase:g=!0}={})=>{let a="";if(m&&(a+=te),g&&(a+=se),c&&(a+=re),d&&(a+=ae),a.length===0)throw new Error("at least one character set must be selected");let l=new Uint32Array(i);crypto.getRandomValues(l);let E="";for(let w=0;w<i;w++){let A=l[w]%a.length;E+=a.charAt(A)}return E};var{version:ie}=_chunkN4WMNFDYcjs.a;var pe=["log_data_api_error_rate_high","log_auth_error_rate_high","log_storage_error_rate_high","log_edge_function_error_rate_high"],ce=new Set(["project_not_active","advisor_check_unavailable"]);function xe(i){let{accessToken:c,apiUrl:d}=i,m=_nullishCoalesce(d, () => ("https://api.schemarch.com")),g,a=F(m,c),l=C(m,c),E={async listOrganizations(){let t=await a.GET("/v1/organizations");return o(t,"Failed to fetch organizations"),t.data},async getOrganization(t){let e=await a.GET("/v1/organizations/{slug}",{params:{path:{slug:t}}});return o(e,"Failed to fetch organization"),e.data},async listProjects(){let t=await a.GET("/v1/projects");return o(t,"Failed to fetch projects"),t.data},async getProject(t){let e=await a.GET("/v1/projects/{ref}",{params:{path:{ref:t}}});return o(e,"Failed to fetch project"),e.data},async createProject(t){let{name:e,organization_id:s,region:r,db_pass:n}=_chunkGEJ6NAOCcjs.i.parse(t),p=await a.POST("/v1/projects",{body:{name:e,region:r,organization_slug:s,db_pass:_nullishCoalesce(n, () => (Q({length:16,numbers:!0,uppercase:!0,lowercase:!0})))}});return o(p,"Failed to create project"),p.data},async pauseProject(t){let e=await a.POST("/v1/projects/{ref}/pause",{params:{path:{ref:t}}});o(e,"Failed to pause project")},async restoreProject(t){let e=await a.POST("/v1/projects/{ref}/restore",{params:{path:{ref:t}}});o(e,"Failed to restore project")}},w={async executeSql(t,e){let{query:s,parameters:r,read_only:n}=_chunkGEJ6NAOCcjs.m.parse(e),p=await a.POST("/v1/projects/{ref}/database/query",{params:{path:{ref:t}},body:{query:s,parameters:r,read_only:n}});return T(p,"Failed to execute SQL query",t),p.data},async listMigrations(t){let e=await a.GET("/v1/projects/{ref}/database/migrations",{params:{path:{ref:t}}});return T(e,"Failed to fetch migrations",t),e.data},async applyMigration(t,e){let{name:s,query:r}=_chunkGEJ6NAOCcjs.n.parse(e),n=await a.POST("/v1/projects/{ref}/database/migrations",{params:{path:{ref:t}},body:{name:s,query:r}});T(n,"Failed to apply migration",t)}},A={logsDialect:"clickhouse",async getLogs(t,e){let{service:s,iso_timestamp_start:r,iso_timestamp_end:n}=_chunkGEJ6NAOCcjs.q.parse(e),p=_chunkN4WMNFDYcjs.e.call(void 0, s),u=await a.GET("/v1/projects/{ref}/analytics/endpoints/logs",{params:{path:{ref:t},query:{sql:p,iso_timestamp_start:r,iso_timestamp_end:n}}});return o(u,"Failed to fetch logs"),u.data},async queryLogs(t,e){let{sql:s,iso_timestamp_start:r,iso_timestamp_end:n}=_chunkGEJ6NAOCcjs.r.parse(e),p=await a.GET("/v1/projects/{ref}/analytics/endpoints/logs",{params:{path:{ref:t},query:{sql:s,iso_timestamp_start:r,iso_timestamp_end:n}}});return o(p,"Failed to query logs"),p.data},async getSecurityAdvisors(t){let e=await a.GET("/v1/projects/{ref}/advisors/security",{params:{path:{ref:t}}});return o(e,"Failed to fetch security advisors"),e.data},async getPerformanceAdvisors(t){let e=await a.GET("/v1/projects/{ref}/advisors/performance",{params:{path:{ref:t}}});return o(e,"Failed to fetch performance advisors"),e.data},async getHealthAdvisors(t){let e=await l.POST("/v2/projects/{ref}/advisors/run",{params:{path:{ref:t}},body:{data:{type:"project_advisors",attributes:{lints:pe.map(r=>({name:r}))}}}});v(e,"Failed to fetch health advisors");let s=e.data.data.attributes;return{...s,lints:s.lints.filter(({name:r})=>!ce.has(r))}}},W={async getProjectUrl(t){let e=new URL(m);return`https://${t}.${me(e.hostname)}`},async getPublishableKeys(t){let e=await a.GET("/v1/projects/{ref}/api-keys",{params:{path:{ref:t},query:{reveal:"false"}}});o(e,"Failed to fetch API keys");let s;try{let n=await a.GET("/v1/projects/{ref}/api-keys/legacy",{params:{path:{ref:t}}});n.response.ok&&(s=_nullishCoalesce(_optionalChain([n, 'access', _3 => _3.data, 'optionalAccess', _4 => _4.enabled]), () => (!0)))}catch (e2){s=void 0}let r=_nullishCoalesce(_optionalChain([e, 'access', _5 => _5.data, 'optionalAccess', _6 => _6.filter, 'call', _7 => _7(n=>n.name==="anon"||n.type==="publishable")]), () => ([]));if(r.length===0)throw new Error("No client-safe API keys (anon or publishable) found. Please create a publishable key in your project settings.");return r.map(n=>({api_key:n.api_key,name:n.name,type:n.type==="publishable"?"publishable":"legacy",...s!==void 0&&{disabled:n.type==="legacy"&&!s},description:_nullishCoalesce(n.description, () => (void 0)),id:_nullishCoalesce(n.id, () => (void 0))}))},async generateTypescriptTypes(t){let e=await a.GET("/v1/projects/{ref}/types/typescript",{params:{path:{ref:t}}});return o(e,"Failed to fetch TypeScript types"),e.data}},M={async listEdgeFunctions(t){let e=await a.GET("/v1/projects/{ref}/functions",{params:{path:{ref:t}}});return o(e,"Failed to fetch Edge Functions"),e.data.map(s=>{let r=_chunkN4WMNFDYcjs.b.call(void 0, t,s.id,s.version),n=s.entrypoint_path?_chunkN4WMNFDYcjs.c.call(void 0, {deploymentId:r,filename:_url.fileURLToPath.call(void 0, s.entrypoint_path,{windows:!1})}):void 0,p=s.import_map_path?_chunkN4WMNFDYcjs.c.call(void 0, {deploymentId:r,filename:_url.fileURLToPath.call(void 0, s.import_map_path,{windows:!1})}):void 0;return{...s,entrypoint_path:n,import_map_path:p}})},async getEdgeFunction(t,e){let s=await a.GET("/v1/projects/{ref}/functions/{function_slug}",{params:{path:{ref:t,function_slug:e}}});if(s.error)throw s.error;o(s,"Failed to fetch Edge Function");let r=s.data,n=_chunkN4WMNFDYcjs.b.call(void 0, t,r.id,r.version),p=r.entrypoint_path?_chunkN4WMNFDYcjs.c.call(void 0, {deploymentId:n,filename:_url.fileURLToPath.call(void 0, r.entrypoint_path,{windows:!1})}):void 0,u=r.import_map_path?_chunkN4WMNFDYcjs.c.call(void 0, {deploymentId:n,filename:_url.fileURLToPath.call(void 0, r.import_map_path,{windows:!1})}):void 0,f=await a.GET("/v1/projects/{ref}/functions/{function_slug}/body",{params:{path:{ref:t,function_slug:e}},headers:{Accept:"multipart/form-data"},parseAs:"stream"});o(f,"Failed to fetch Edge Function files");let y=f.response.headers.get("content-type");if(!y||!y.startsWith("multipart/form-data"))throw new Error(`Unexpected content type: ${y}. Expected multipart/form-data.`);let S=_multipartparser.getMultipartBoundary.call(void 0, y);if(!S)throw new Error("No multipart boundary found in response headers");if(!f.data)throw new Error("No data received from Edge Function body");let h=[],O=_multipartparser.parseMultipartStream.call(void 0, f.data,{boundary:S});for await(let b of O)b.isFile&&b.filename&&h.push({name:_chunkN4WMNFDYcjs.c.call(void 0, {deploymentId:n,filename:b.filename}),content:b.text});return{...r,entrypoint_path:p,import_map_path:u,files:h}},async deployEdgeFunction(t,e){let{name:s,entrypoint_path:r,import_map_path:n,verify_jwt:p,files:u}=_chunkGEJ6NAOCcjs.l.parse(e),f;try{f=await M.getEdgeFunction(t,s)}catch (e3){}let y=u.find(h=>["deno.json","import_map.json"].includes(h.name));n??=_nullishCoalesce(_optionalChain([f, 'optionalAccess', _8 => _8.import_map_path]), () => (_optionalChain([y, 'optionalAccess', _9 => _9.name])));let S=await a.POST("/v1/projects/{ref}/functions/deploy",{params:{path:{ref:t},query:{slug:s}},body:{metadata:{name:s,entrypoint_path:r,import_map_path:n,verify_jwt:p},file:u},bodySerializer(h){let O=new FormData,b=new Blob([JSON.stringify(h.metadata)],{type:"application/json"});return O.append("metadata",b),_optionalChain([h, 'access', _10 => _10.file, 'optionalAccess', _11 => _11.forEach, 'call', _12 => _12(J=>{let k=J,X=new Blob([k.content],{type:"application/typescript"});O.append("file",X,k.name)})]),O}});return o(S,"Failed to deploy Edge Function"),S.data}};return{async init(t){let{clientInfo:e}=t;if(!e)throw new Error("Client info is required");let s={"User-Agent":`schemarch-mcp/${ie} (${e.name}/${e.version})`};a=F(m,c,s),l=C(m,c,s)},account:E,database:w,debugging:A,development:W,functions:M,branching:{async listBranches(t){let e=await a.GET("/v1/projects/{ref}/branches",{params:{path:{ref:t}}});return e.response.status===422?[]:(o(e,"Failed to list branches"),e.data)},async createBranch(t,e){let{name:s}=_chunkGEJ6NAOCcjs.j.parse(e),r=await a.POST("/v1/projects/{ref}/branches",{params:{path:{ref:t}},body:{branch_name:s}});return o(r,"Failed to create branch"),r.data},async deleteBranch(t){let e=await a.DELETE("/v1/branches/{branch_id_or_ref}",{params:{path:{branch_id_or_ref:t}}});o(e,"Failed to delete branch")},async mergeBranch(t){let e=await a.POST("/v1/branches/{branch_id_or_ref}/merge",{params:{path:{branch_id_or_ref:t}},body:{}});o(e,"Failed to merge branch")},async resetBranch(t,e){let{migration_version:s}=_chunkGEJ6NAOCcjs.k.parse(e),r=await a.POST("/v1/branches/{branch_id_or_ref}/reset",{params:{path:{branch_id_or_ref:t}},body:{migration_version:s}});o(r,"Failed to reset branch")},async rebaseBranch(t){let e=await a.POST("/v1/branches/{branch_id_or_ref}/push",{params:{path:{branch_id_or_ref:t}},body:{}});o(e,"Failed to rebase branch")}},storage:{async listAllBuckets(t){let e=await a.GET("/v1/projects/{ref}/storage/buckets",{params:{path:{ref:t}}});return o(e,"Failed to list storage buckets"),e.data},async getStorageConfig(t){let e=await a.GET("/v1/projects/{ref}/config/storage",{params:{path:{ref:t}}});return o(e,"Failed to get storage config"),e.data},async updateStorageConfig(t,e){let s=await a.PATCH("/v1/projects/{ref}/config/storage",{params:{path:{ref:t}},body:{fileSizeLimit:e.fileSizeLimit,features:{imageTransformation:{enabled:e.features.imageTransformation.enabled},s3Protocol:{enabled:e.features.s3Protocol.enabled}}}});o(s,"Failed to update storage config")}},secrets:{async getUpdatedAt(t,e){let s=await a.GET("/v1/projects/{ref}/secrets",{params:{path:{ref:t}}});o(s,"Failed to fetch secrets");let r=s.data.find(n=>n.name===e);if(!(!r||!r.updated_at))return new Date(r.updated_at)}},notebooks:{async createNotebook(t,e){let s=_chunkGEJ6NAOCcjs.u.parse(e),r=await l.POST("/v2/projects/{ref}/notebooks",{params:{path:{ref:t}},body:{data:{type:"notebook",attributes:s}}});v(r,"Failed to create notebook");let{id:n,attributes:p}=r.data.data;return{id:n,...p}},async listNotebooks(t){let e=[],s;do{let r=await l.GET("/v2/projects/{ref}/notebooks",{params:{path:{ref:t},query:s?{page:{after:s}}:void 0}});v(r,"Failed to retrieve project's notebooks"),e.push(...r.data.data.map(({id:n,attributes:p})=>({id:n,...p}))),s=de(r.data.links.next)}while(s);return e},async getNotebook(t,e){let s=await l.GET("/v2/projects/{ref}/notebooks/{id}",{params:{path:{ref:t,id:e}}});v(s,"Failed to retrieve notebook");let{id:r,attributes:n}=s.data.data;return{id:r,...n}}},feedback:_chunkN4WMNFDYcjs.g.call(void 0, {environment:new URL(m).origin==="https://api.schemarch.com"?"production":"staging",async getUserId(){return g??=await _asyncNullishCoalesce((await a.GET("/v1/profile",{signal:AbortSignal.timeout(5e3)})).response.headers.get("X-Gotrue-Id"), async () => (void 0)),g}})}}function de(i){return i?_nullishCoalesce(new URL(i,"https://schemarch.com").searchParams.get("page[after]"), () => (void 0)):void 0}function me(i){switch(i){case"api.schemarch.com":return"schemarch.co";case"api.schemarch.green":return"schemarch.green";default:return"schemarch.red"}}exports.a = xe;
|
|
2
|
+
//# sourceMappingURL=chunk-BV2TY4MO.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/copilot/dev/schemarch-rebuild/mcp/packages/mcp-server-schemarch/dist/chunk-BV2TY4MO.cjs","../src/platform/api-platform.ts","../src/management-api/index.ts"],"names":["createManagementApiClient","baseUrl","accessToken","headers","createClient"],"mappings":"AAAA,87BAAoE,wDAAiG,6DCG9J,0BAEuB,yGCDvB,4BAMW,SAGFA,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAAkC,CAAC,CAAA,CACnC,CACA,OAAOC,oCAAAA,CACL,OAAA,CAAAH,CAAAA,CACA,OAAA,CAAS,CACP,aAAA,CAAe,CAAA,OAAA,EAAUC,CAAW,CAAA,CAAA","file":"/home/copilot/dev/schemarch-rebuild/mcp/packages/mcp-server-schemarch/dist/chunk-BV2TY4MO.cjs","sourcesContent":[null,"import {\n getMultipartBoundary,\n parseMultipartStream,\n} from '@mjackson/multipart-parser';\nimport type { InitData } from '@schemarch/mcp-utils';\nimport { fileURLToPath } from 'node:url';\nimport packageJson from '../../package.json' with { type: 'json' };\nimport { getDeploymentId, normalizeFilename } from '../edge-function.js';\nimport { getClickHouseLogQuery } from '../logs.js';\nimport {\n assertProjectScopedSuccess,\n assertSuccess,\n createManagementApiClient,\n} from '../management-api/index.js';\nimport {\n assertSuccessV2,\n createManagementApiV2Client,\n} from '../management-api-v2/index.js';\nimport type { components as ManagementApiV2Components } from '../management-api-v2/types.js';\nimport { generatePassword } from '../password.js';\nimport { createFeedbackOperations } from './feedback.js';\nimport {\n applyMigrationOptionsSchema,\n createNotebookOptionsSchema,\n createBranchOptionsSchema,\n createProjectOptionsSchema,\n deployEdgeFunctionOptionsSchema,\n executeSqlOptionsSchema,\n getLogsOptionsSchema,\n queryLogsOptionsSchema,\n resetBranchOptionsSchema,\n type AccountOperations,\n type ApiKey,\n type ApiKeyType,\n type ApplyMigrationOptions,\n type BranchingOperations,\n type CreateBranchOptions,\n type CreateProjectOptions,\n type DatabaseOperations,\n type DebuggingOperations,\n type DeployEdgeFunctionOptions,\n type DevelopmentOperations,\n type SuccessResponse,\n type EdgeFunction,\n type EdgeFunctionsOperations,\n type EdgeFunctionWithBody,\n type ExecuteSqlOptions,\n type GetLogsOptions,\n type Notebook,\n type NotebookOperations,\n type QueryLogsOptions,\n type ResetBranchOptions,\n type SecretOperations,\n type StorageConfig,\n type StorageOperations,\n type SchemarchPlatform,\n} from './index.js';\n\nconst { version } = packageJson;\n\nconst SUCCESS_RESPONSE: SuccessResponse = { success: true };\n\ntype HealthAdvisorName =\n ManagementApiV2Components['schemas']['V2RunProjectAdvisorsBody']['data']['attributes']['lints'][number]['name'];\n\nconst healthAdvisorNames = [\n 'log_data_api_error_rate_high',\n 'log_auth_error_rate_high',\n 'log_storage_error_rate_high',\n 'log_edge_function_error_rate_high',\n] as const satisfies readonly HealthAdvisorName[];\n\nconst hiddenHealthAdvisorResultNames: ReadonlySet<string> = new Set([\n 'project_not_active',\n 'advisor_check_unavailable',\n]);\n\nexport type SchemarchApiPlatformOptions = {\n /**\n * The access token for the Schemarch Management API.\n */\n accessToken: string;\n\n /**\n * The API URL for the Schemarch Management API.\n */\n apiUrl?: string;\n};\n\n/**\n * Creates a Schemarch platform implementation using the Schemarch Management API.\n */\nexport function createSchemarchApiPlatform(\n options: SchemarchApiPlatformOptions\n): SchemarchPlatform {\n const { accessToken, apiUrl } = options;\n\n const managementApiUrl = apiUrl ?? 'https://api.schemarch.com';\n\n let userId: string | undefined;\n\n let managementApiClient = createManagementApiClient(\n managementApiUrl,\n accessToken\n );\n let managementApiV2Client = createManagementApiV2Client(\n managementApiUrl,\n accessToken\n );\n\n const account: AccountOperations = {\n async listOrganizations() {\n const response = await managementApiClient.GET('/v1/organizations');\n\n assertSuccess(response, 'Failed to fetch organizations');\n\n return response.data;\n },\n async getOrganization(organizationId: string) {\n const response = await managementApiClient.GET(\n '/v1/organizations/{slug}',\n {\n params: {\n path: {\n slug: organizationId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch organization');\n\n return response.data;\n },\n async listProjects() {\n const response = await managementApiClient.GET('/v1/projects');\n\n assertSuccess(response, 'Failed to fetch projects');\n\n return response.data;\n },\n async getProject(projectId: string) {\n const response = await managementApiClient.GET('/v1/projects/{ref}', {\n params: {\n path: {\n ref: projectId,\n },\n },\n });\n assertSuccess(response, 'Failed to fetch project');\n return response.data;\n },\n async createProject(options: CreateProjectOptions) {\n const { name, organization_id, region, db_pass } =\n createProjectOptionsSchema.parse(options);\n\n const response = await managementApiClient.POST('/v1/projects', {\n body: {\n name,\n region,\n organization_slug: organization_id,\n db_pass:\n db_pass ??\n generatePassword({\n length: 16,\n numbers: true,\n uppercase: true,\n lowercase: true,\n }),\n },\n });\n\n assertSuccess(response, 'Failed to create project');\n\n return response.data;\n },\n async pauseProject(projectId: string) {\n const response = await managementApiClient.POST(\n '/v1/projects/{ref}/pause',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to pause project');\n },\n async restoreProject(projectId: string) {\n const response = await managementApiClient.POST(\n '/v1/projects/{ref}/restore',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to restore project');\n },\n };\n\n const database: DatabaseOperations = {\n async executeSql<T>(projectId: string, options: ExecuteSqlOptions) {\n const { query, parameters, read_only } =\n executeSqlOptionsSchema.parse(options);\n\n const response = await managementApiClient.POST(\n '/v1/projects/{ref}/database/query',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n body: {\n query,\n parameters,\n read_only,\n },\n }\n );\n\n assertProjectScopedSuccess(\n response,\n 'Failed to execute SQL query',\n projectId\n );\n\n return response.data as unknown as T[];\n },\n async listMigrations(projectId: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/database/migrations',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n assertProjectScopedSuccess(\n response,\n 'Failed to fetch migrations',\n projectId\n );\n\n return response.data;\n },\n async applyMigration(projectId: string, options: ApplyMigrationOptions) {\n const { name, query } = applyMigrationOptionsSchema.parse(options);\n\n const response = await managementApiClient.POST(\n '/v1/projects/{ref}/database/migrations',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n body: {\n name,\n query,\n },\n }\n );\n\n assertProjectScopedSuccess(\n response,\n 'Failed to apply migration',\n projectId\n );\n\n // Intentionally don't return the result of the migration\n // to avoid prompt injection attacks. If the migration failed,\n // it will throw an error.\n },\n };\n\n const debugging: DebuggingOperations = {\n logsDialect: 'clickhouse',\n async getLogs(projectId: string, options: GetLogsOptions) {\n const { service, iso_timestamp_start, iso_timestamp_end } =\n getLogsOptionsSchema.parse(options);\n\n const sql = getClickHouseLogQuery(service);\n\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/analytics/endpoints/logs',\n {\n params: {\n path: {\n ref: projectId,\n },\n query: {\n sql,\n iso_timestamp_start,\n iso_timestamp_end,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch logs');\n\n return response.data;\n },\n async queryLogs(projectId: string, options: QueryLogsOptions) {\n const { sql, iso_timestamp_start, iso_timestamp_end } =\n queryLogsOptionsSchema.parse(options);\n\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/analytics/endpoints/logs',\n {\n params: {\n path: {\n ref: projectId,\n },\n query: {\n sql,\n iso_timestamp_start,\n iso_timestamp_end,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to query logs');\n\n return response.data;\n },\n async getSecurityAdvisors(projectId: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/advisors/security',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch security advisors');\n\n return response.data;\n },\n async getPerformanceAdvisors(projectId: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/advisors/performance',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch performance advisors');\n\n return response.data;\n },\n async getHealthAdvisors(projectId: string) {\n const response = await managementApiV2Client.POST(\n '/v2/projects/{ref}/advisors/run',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n body: {\n data: {\n type: 'project_advisors',\n attributes: {\n lints: healthAdvisorNames.map((name) => ({ name })),\n },\n },\n },\n }\n );\n\n assertSuccessV2(response, 'Failed to fetch health advisors');\n\n const attributes = response.data.data.attributes;\n\n return {\n ...attributes,\n lints: attributes.lints.filter(\n ({ name }) => !hiddenHealthAdvisorResultNames.has(name)\n ),\n };\n },\n };\n\n const development: DevelopmentOperations = {\n async getProjectUrl(projectId: string): Promise<string> {\n const apiUrl = new URL(managementApiUrl);\n return `https://${projectId}.${getProjectDomain(apiUrl.hostname)}`;\n },\n async getPublishableKeys(projectId: string): Promise<ApiKey[]> {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/api-keys',\n {\n params: {\n path: {\n ref: projectId,\n },\n query: {\n reveal: 'false',\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch API keys');\n\n // Try to check if legacy JWT-based keys are enabled\n // If this fails, we'll continue without the disabled field\n let legacyKeysEnabled: boolean | undefined = undefined;\n try {\n const legacyKeysResponse = await managementApiClient.GET(\n '/v1/projects/{ref}/api-keys/legacy',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n if (legacyKeysResponse.response.ok) {\n legacyKeysEnabled = legacyKeysResponse.data?.enabled ?? true;\n }\n } catch (error) {\n // If we can't fetch legacy key status, continue without it\n legacyKeysEnabled = undefined;\n }\n\n // Filter for client-safe keys: legacy 'anon' or publishable type\n const clientKeys =\n response.data?.filter(\n (key) => key.name === 'anon' || key.type === 'publishable'\n ) ?? [];\n\n if (clientKeys.length === 0) {\n throw new Error(\n 'No client-safe API keys (anon or publishable) found. Please create a publishable key in your project settings.'\n );\n }\n\n return clientKeys.map((key) => ({\n api_key: key.api_key!,\n name: key.name,\n type: (key.type === 'publishable'\n ? 'publishable'\n : 'legacy') satisfies ApiKeyType,\n // Only include disabled field if we successfully fetched legacy key status\n ...(legacyKeysEnabled !== undefined && {\n disabled: key.type === 'legacy' && !legacyKeysEnabled,\n }),\n description: key.description ?? undefined,\n id: key.id ?? undefined,\n }));\n },\n async generateTypescriptTypes(projectId: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/types/typescript',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch TypeScript types');\n\n return response.data;\n },\n };\n\n const functions: EdgeFunctionsOperations = {\n async listEdgeFunctions(projectId: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/functions',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch Edge Functions');\n\n return response.data.map((edgeFunction) => {\n const deploymentId = getDeploymentId(\n projectId,\n edgeFunction.id,\n edgeFunction.version\n );\n\n const entrypoint_path = edgeFunction.entrypoint_path\n ? normalizeFilename({\n deploymentId,\n filename: fileURLToPath(edgeFunction.entrypoint_path, {\n windows: false,\n }),\n })\n : undefined;\n\n const import_map_path = edgeFunction.import_map_path\n ? normalizeFilename({\n deploymentId,\n filename: fileURLToPath(edgeFunction.import_map_path, {\n windows: false,\n }),\n })\n : undefined;\n\n return {\n ...edgeFunction,\n entrypoint_path,\n import_map_path,\n };\n });\n },\n async getEdgeFunction(projectId: string, functionSlug: string) {\n const functionResponse = await managementApiClient.GET(\n '/v1/projects/{ref}/functions/{function_slug}',\n {\n params: {\n path: {\n ref: projectId,\n function_slug: functionSlug,\n },\n },\n }\n );\n\n if (functionResponse.error) {\n throw functionResponse.error;\n }\n\n assertSuccess(functionResponse, 'Failed to fetch Edge Function');\n\n const edgeFunction = functionResponse.data;\n\n const deploymentId = getDeploymentId(\n projectId,\n edgeFunction.id,\n edgeFunction.version\n );\n\n const entrypoint_path = edgeFunction.entrypoint_path\n ? normalizeFilename({\n deploymentId,\n filename: fileURLToPath(edgeFunction.entrypoint_path, {\n windows: false,\n }),\n })\n : undefined;\n\n const import_map_path = edgeFunction.import_map_path\n ? normalizeFilename({\n deploymentId,\n filename: fileURLToPath(edgeFunction.import_map_path, {\n windows: false,\n }),\n })\n : undefined;\n\n const bodyResponse = await managementApiClient.GET(\n '/v1/projects/{ref}/functions/{function_slug}/body',\n {\n params: {\n path: {\n ref: projectId,\n function_slug: functionSlug,\n },\n },\n headers: {\n Accept: 'multipart/form-data',\n },\n parseAs: 'stream',\n }\n );\n\n assertSuccess(bodyResponse, 'Failed to fetch Edge Function files');\n\n const contentType = bodyResponse.response.headers.get('content-type');\n\n if (!contentType || !contentType.startsWith('multipart/form-data')) {\n throw new Error(\n `Unexpected content type: ${contentType}. Expected multipart/form-data.`\n );\n }\n\n const boundary = getMultipartBoundary(contentType);\n\n if (!boundary) {\n throw new Error('No multipart boundary found in response headers');\n }\n\n if (!bodyResponse.data) {\n throw new Error('No data received from Edge Function body');\n }\n\n const files: EdgeFunctionWithBody['files'] = [];\n const parts = parseMultipartStream(bodyResponse.data, { boundary });\n\n for await (const part of parts) {\n if (part.isFile && part.filename) {\n files.push({\n name: normalizeFilename({\n deploymentId,\n filename: part.filename,\n }),\n content: part.text,\n });\n }\n }\n\n return {\n ...edgeFunction,\n entrypoint_path,\n import_map_path,\n files,\n };\n },\n async deployEdgeFunction(\n projectId: string,\n options: DeployEdgeFunctionOptions\n ) {\n let {\n name,\n entrypoint_path,\n import_map_path,\n verify_jwt,\n files: inputFiles,\n } = deployEdgeFunctionOptionsSchema.parse(options);\n\n let existingEdgeFunction: EdgeFunction | undefined;\n try {\n existingEdgeFunction = await functions.getEdgeFunction(projectId, name);\n } catch (error) {}\n\n const import_map_file = inputFiles.find((file) =>\n ['deno.json', 'import_map.json'].includes(file.name)\n );\n\n // Use existing import map path or file name heuristic if not provided\n import_map_path ??=\n existingEdgeFunction?.import_map_path ?? import_map_file?.name;\n\n const response = await managementApiClient.POST(\n '/v1/projects/{ref}/functions/deploy',\n {\n params: {\n path: {\n ref: projectId,\n },\n query: { slug: name },\n },\n body: {\n metadata: {\n name,\n entrypoint_path,\n import_map_path,\n verify_jwt,\n },\n file: inputFiles as any, // We need to pass file name and content to our serializer\n },\n bodySerializer(body) {\n const formData = new FormData();\n\n const blob = new Blob([JSON.stringify(body.metadata)], {\n type: 'application/json',\n });\n formData.append('metadata', blob);\n\n body.file?.forEach((f: any) => {\n const file: { name: string; content: string } = f;\n const blob = new Blob([file.content], {\n type: 'application/typescript',\n });\n formData.append('file', blob, file.name);\n });\n\n return formData;\n },\n }\n );\n\n assertSuccess(response, 'Failed to deploy Edge Function');\n\n return response.data;\n },\n };\n\n const branching: BranchingOperations = {\n async listBranches(projectId: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/branches',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n // There are no branches if branching is disabled\n if (response.response.status === 422) return [];\n assertSuccess(response, 'Failed to list branches');\n\n return response.data;\n },\n async createBranch(projectId: string, options: CreateBranchOptions) {\n const { name } = createBranchOptionsSchema.parse(options);\n\n const createBranchResponse = await managementApiClient.POST(\n '/v1/projects/{ref}/branches',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n body: {\n branch_name: name,\n },\n }\n );\n\n assertSuccess(createBranchResponse, 'Failed to create branch');\n\n return createBranchResponse.data;\n },\n async deleteBranch(branchId: string) {\n const response = await managementApiClient.DELETE(\n '/v1/branches/{branch_id_or_ref}',\n {\n params: {\n path: {\n branch_id_or_ref: branchId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to delete branch');\n },\n async mergeBranch(branchId: string) {\n const response = await managementApiClient.POST(\n '/v1/branches/{branch_id_or_ref}/merge',\n {\n params: {\n path: {\n branch_id_or_ref: branchId,\n },\n },\n body: {},\n }\n );\n\n assertSuccess(response, 'Failed to merge branch');\n },\n async resetBranch(branchId: string, options: ResetBranchOptions) {\n const { migration_version } = resetBranchOptionsSchema.parse(options);\n\n const response = await managementApiClient.POST(\n '/v1/branches/{branch_id_or_ref}/reset',\n {\n params: {\n path: {\n branch_id_or_ref: branchId,\n },\n },\n body: {\n migration_version,\n },\n }\n );\n\n assertSuccess(response, 'Failed to reset branch');\n },\n async rebaseBranch(branchId: string) {\n const response = await managementApiClient.POST(\n '/v1/branches/{branch_id_or_ref}/push',\n {\n params: {\n path: {\n branch_id_or_ref: branchId,\n },\n },\n body: {},\n }\n );\n\n assertSuccess(response, 'Failed to rebase branch');\n },\n };\n\n const storage: StorageOperations = {\n // Storage methods\n async listAllBuckets(project_id: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/storage/buckets',\n {\n params: {\n path: {\n ref: project_id,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to list storage buckets');\n\n return response.data;\n },\n\n async getStorageConfig(project_id: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/config/storage',\n {\n params: {\n path: {\n ref: project_id,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to get storage config');\n\n return response.data;\n },\n\n async updateStorageConfig(projectId: string, config: StorageConfig) {\n const response = await managementApiClient.PATCH(\n '/v1/projects/{ref}/config/storage',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n body: {\n fileSizeLimit: config.fileSizeLimit,\n features: {\n imageTransformation: {\n enabled: config.features.imageTransformation.enabled,\n },\n s3Protocol: {\n enabled: config.features.s3Protocol.enabled,\n },\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to update storage config');\n },\n };\n\n const secrets: SecretOperations = {\n async getUpdatedAt(projectId: string, name: string) {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/secrets',\n {\n params: {\n path: {\n ref: projectId,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch secrets');\n\n const secret = response.data.find((s) => s.name === name);\n if (!secret || !secret.updated_at) {\n return undefined;\n }\n\n return new Date(secret.updated_at);\n },\n };\n\n const notebooks: NotebookOperations = {\n async createNotebook(projectId, options) {\n const attributes = createNotebookOptionsSchema.parse(options);\n const response = await managementApiV2Client.POST(\n '/v2/projects/{ref}/notebooks',\n {\n params: { path: { ref: projectId } },\n body: { data: { type: 'notebook', attributes } },\n }\n );\n\n assertSuccessV2(response, 'Failed to create notebook');\n\n const { id, attributes: notebook } = response.data.data;\n return { id, ...notebook };\n },\n async listNotebooks(projectId: string) {\n const notebooks: Notebook[] = [];\n let cursor: string | undefined;\n\n do {\n const response = await managementApiV2Client.GET(\n '/v2/projects/{ref}/notebooks',\n {\n params: {\n path: {\n ref: projectId,\n },\n query: cursor ? { page: { after: cursor } } : undefined,\n },\n }\n );\n\n assertSuccessV2(response, \"Failed to retrieve project's notebooks\");\n\n notebooks.push(\n ...response.data.data.map(({ id, attributes }) => ({\n id,\n ...attributes,\n }))\n );\n\n cursor = getNextNotebooksCursor(response.data.links.next);\n } while (cursor);\n\n return notebooks;\n },\n async getNotebook(projectId: string, notebookId: string) {\n const response = await managementApiV2Client.GET(\n '/v2/projects/{ref}/notebooks/{id}',\n {\n params: {\n path: {\n ref: projectId,\n id: notebookId,\n },\n },\n }\n );\n\n assertSuccessV2(response, 'Failed to retrieve notebook');\n\n const { id, attributes } = response.data.data;\n\n return { id, ...attributes };\n },\n };\n\n const platform: SchemarchPlatform = {\n async init(info: InitData) {\n const { clientInfo } = info;\n if (!clientInfo) {\n throw new Error('Client info is required');\n }\n\n // Re-initialize the management API clients with the user agent\n const userAgentHeaders = {\n 'User-Agent': `schemarch-mcp/${version} (${clientInfo.name}/${clientInfo.version})`,\n };\n managementApiClient = createManagementApiClient(\n managementApiUrl,\n accessToken,\n userAgentHeaders\n );\n managementApiV2Client = createManagementApiV2Client(\n managementApiUrl,\n accessToken,\n userAgentHeaders\n );\n },\n account,\n database,\n debugging,\n development,\n functions,\n branching,\n storage,\n secrets,\n notebooks,\n feedback: createFeedbackOperations({\n // Staging, local, and custom API URLs keep their feedback out of production\n environment:\n new URL(managementApiUrl).origin === 'https://api.schemarch.com'\n ? 'production'\n : 'staging',\n async getUserId() {\n // X-Gotrue-Id is set on every response, see how CLI uses this too: https://github.com/schemarch/cli/blob/8a549dffa6bc5c88069c61c1f55ef55ad9b82ae2/apps/cli/src/command-internal/identity-stitch.ts#L10-L20\n userId ??=\n (\n await managementApiClient.GET('/v1/profile', {\n signal: AbortSignal.timeout(5_000),\n })\n ).response.headers.get('X-Gotrue-Id') ?? undefined;\n return userId;\n },\n }),\n };\n\n return platform;\n}\n\n/**\n * Extracts the `page[after]` cursor from a JSON:API `links.next` URL path\n * (e.g. `/v2/projects/{ref}/notebooks?page[size]=10&page[after]=<cursor>`).\n */\nfunction getNextNotebooksCursor(next: string | null | undefined) {\n if (!next) {\n return undefined;\n }\n\n const url = new URL(next, 'https://schemarch.com');\n return url.searchParams.get('page[after]') ?? undefined;\n}\n\nfunction getProjectDomain(apiHostname: string) {\n switch (apiHostname) {\n case 'api.schemarch.com':\n return 'schemarch.co';\n case 'api.schemarch.green':\n return 'schemarch.green';\n default:\n return 'schemarch.red';\n }\n}\n","import createClient, {\n type Client,\n type FetchResponse,\n type ParseAsResponse,\n} from 'openapi-fetch';\nimport type {\n MediaType,\n ResponseObjectMap,\n SuccessResponse,\n} from 'openapi-typescript-helpers';\nimport { z } from 'zod/v4';\nimport type { paths } from './types.js';\n\nexport function createManagementApiClient(\n baseUrl: string,\n accessToken: string,\n headers: Record<string, string> = {}\n) {\n return createClient<paths>({\n baseUrl,\n headers: {\n Authorization: `Bearer ${accessToken}`,\n ...headers,\n },\n });\n}\n\nexport type ManagementApiClient = Client<paths>;\n\nexport type SuccessResponseType<\n T extends Record<string | number, any>,\n Options,\n Media extends MediaType,\n> = {\n data: ParseAsResponse<SuccessResponse<ResponseObjectMap<T>, Media>, Options>;\n error?: never;\n response: Response;\n};\n\nconst errorSchema = z.object({\n message: z.string(),\n});\n\nexport function assertSuccess<\n T extends Record<string | number, any>,\n Options,\n Media extends MediaType,\n>(\n response: FetchResponse<T, Options, Media>,\n fallbackMessage: string\n): asserts response is SuccessResponseType<T, Options, Media> {\n if ('error' in response) {\n if (response.response.status === 401) {\n throw new Error(\n 'Unauthorized. Please provide a valid access token to the MCP server via the --access-token flag or SCHEMARCH_ACCESS_TOKEN.'\n );\n }\n\n const { data: errorContent } = errorSchema.safeParse(response.error);\n\n if (errorContent) {\n throw new Error(errorContent.message);\n }\n\n throw new Error(fallbackMessage);\n }\n}\n\n/**\n * Asserts success for project-scoped endpoints, mapping 403 responses to an\n * actionable message. A permission error on a specific project most commonly\n * means the access token is scoped to an organization that doesn't own the\n * project (e.g. the wrong organization was selected during OAuth login).\n *\n * Currently applied only to database operations (see AI-178). Before adopting\n * for other endpoints, check that a 403 there isn't better explained by plan\n * or role restrictions, where org-selection advice would mislead.\n */\nexport function assertProjectScopedSuccess<\n T extends Record<string | number, any>,\n Options,\n Media extends MediaType,\n>(\n response: FetchResponse<T, Options, Media>,\n fallbackMessage: string,\n projectId: string\n): asserts response is SuccessResponseType<T, Options, Media> {\n if ('error' in response && response.response.status === 403) {\n const { data: errorContent } = errorSchema.safeParse(response.error);\n const apiMessage = (errorContent?.message ?? fallbackMessage).replace(\n /\\.$/,\n ''\n );\n\n throw new Error(\n `${apiMessage}. Access to project '${projectId}' was denied. If this project exists, your access token may be scoped to a different organization: re-authenticate with the MCP server and select the organization that owns this project.`\n );\n }\n\n assertSuccess(response, fallbackMessage);\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _v4 = require('zod/v4');var n=["us-west-1","us-east-1","us-east-2","ca-central-1","eu-west-1","eu-west-2","eu-west-3","eu-central-1","eu-central-2","eu-north-1","ap-south-1","ap-southeast-1","ap-northeast-1","ap-northeast-2","ap-southeast-2","sa-east-1"];var j=_v4.z.object({id:_v4.z.string(),name:_v4.z.string(),owner:_v4.z.string(),created_at:_v4.z.string(),updated_at:_v4.z.string(),public:_v4.z.boolean()}),x= exports.c =_v4.z.object({fileSizeLimit:_v4.z.number().int().min(0).max(536870912e3),features:_v4.z.object({imageTransformation:_v4.z.object({enabled:_v4.z.boolean()}),s3Protocol:_v4.z.object({enabled:_v4.z.boolean()})})}),_= exports.d =_v4.z.object({id:_v4.z.string(),name:_v4.z.string(),plan:_v4.z.string().optional(),allowed_release_channels:_v4.z.array(_v4.z.string()),opt_in_tags:_v4.z.array(_v4.z.string())}),O= exports.e =_v4.z.object({id:_v4.z.string(),ref:_v4.z.string(),organization_id:_v4.z.string(),organization_slug:_v4.z.string(),name:_v4.z.string(),status:_v4.z.string(),created_at:_v4.z.string(),region:_v4.z.string()}),P= exports.f =_v4.z.object({id:_v4.z.string(),name:_v4.z.string(),project_ref:_v4.z.string(),parent_project_ref:_v4.z.string(),is_default:_v4.z.boolean(),git_branch:_v4.z.string().optional(),pr_number:_v4.z.number().optional(),latest_check_run_id:_v4.z.number().optional(),persistent:_v4.z.boolean(),status:_v4.z.enum(["CREATING_PROJECT","RUNNING_MIGRATIONS","MIGRATIONS_PASSED","MIGRATIONS_FAILED","FUNCTIONS_DEPLOYED","FUNCTIONS_FAILED"]),created_at:_v4.z.string(),updated_at:_v4.z.string()}),m= exports.g =_v4.z.object({id:_v4.z.string(),slug:_v4.z.string(),name:_v4.z.string(),status:_v4.z.string(),version:_v4.z.number(),created_at:_v4.z.number().optional(),updated_at:_v4.z.number().optional(),verify_jwt:_v4.z.boolean().optional(),import_map:_v4.z.boolean().optional(),import_map_path:_v4.z.string().optional(),entrypoint_path:_v4.z.string().optional()}),k= exports.h =m.extend({files:_v4.z.array(_v4.z.object({name:_v4.z.string(),content:_v4.z.string()}))}),I= exports.i =_v4.z.object({name:_v4.z.string().min(1).max(256),organization_id:_v4.z.string(),region:_v4.z.enum(n),db_pass:_v4.z.string().optional()}),z= exports.j =_v4.z.object({name:_v4.z.string().min(1)}),v= exports.k =_v4.z.object({migration_version:_v4.z.string().optional()}),C= exports.l =_v4.z.object({name:_v4.z.string().regex(/^[A-Za-z][A-Za-z0-9_-]*$/),entrypoint_path:_v4.z.string(),import_map_path:_v4.z.string().optional(),verify_jwt:_v4.z.boolean().optional(),files:_v4.z.array(_v4.z.object({name:_v4.z.string(),content:_v4.z.string()}))}),N= exports.m =_v4.z.object({query:_v4.z.string().min(1),parameters:_v4.z.array(_v4.z.unknown()).optional(),read_only:_v4.z.boolean().optional(),max_result_bytes:_v4.z.number().int().nonnegative().optional()}),T= exports.n =_v4.z.object({name:_v4.z.string().min(1),query:_v4.z.string().min(1)}),B= exports.o =_v4.z.object({version:_v4.z.string(),name:_v4.z.string().optional()}),l= exports.p =_v4.z.enum(["api","branch-action","postgres","edge-function","edge-function-runtime","auth","storage","realtime"]),E= exports.q =_v4.z.object({service:l,iso_timestamp_start:_v4.z.string().optional(),iso_timestamp_end:_v4.z.string().optional()}),w= exports.r =_v4.z.object({sql:_v4.z.string().min(1),iso_timestamp_start:_v4.z.string().optional(),iso_timestamp_end:_v4.z.string().optional()}),A= exports.s =_v4.z.object({types:_v4.z.string()}),i=_v4.z.object({id:_v4.z.number(),username:_v4.z.string()}).nullable(),t=_v4.z.object({type:_v4.z.enum(["bar","line"]),x_column:_v4.z.string(),y_series:_v4.z.array(_v4.z.object({column:_v4.z.string()})),scale:_v4.z.enum(["linear","log"]),cumulative:_v4.z.boolean(),show_labels:_v4.z.boolean()}),a=_v4.z.object({id:_v4.z.string(),type:_v4.z.literal("markdown"),text:_v4.z.string()}),p=_v4.z.object({id:_v4.z.string(),type:_v4.z.literal("database"),sql:_v4.z.string(),row_limit:_v4.z.number(),database_identifier:_v4.z.string().optional(),title:_v4.z.string().optional(),view:_v4.z.enum(["table","chart"]).optional(),chart:t.optional()}),c=_v4.z.enum(["minute","hour","day","week","month","year"]),d=_v4.z.union([_v4.z.object({type:_v4.z.literal("absolute"),start:_v4.z.string(),end:_v4.z.string()}),_v4.z.object({type:_v4.z.literal("relative"),unit:c,amount:_v4.z.number()})]),g=_v4.z.object({id:_v4.z.string(),type:_v4.z.literal("log"),sql:_v4.z.string(),time_range:d,title:_v4.z.string().optional(),view:_v4.z.enum(["table","chart"]).optional(),chart:t.optional()}),u= exports.t =_v4.z.discriminatedUnion("type",[a,p,g]),r=t.extend({y_series:_v4.z.array(t.shape.y_series.element.strict())}).strict(),s=_v4.z.string().trim().min(1),y=_v4.z.discriminatedUnion("type",[a.omit({id:!0}).strict(),p.omit({id:!0}).extend({sql:s,row_limit:_v4.z.number().int().positive(),database_identifier:_v4.z.string().min(1).optional(),chart:r.optional()}).strict(),g.omit({id:!0}).extend({sql:s,time_range:_v4.z.discriminatedUnion("type",[_v4.z.object({type:_v4.z.literal("absolute"),start:_v4.z.iso.datetime({offset:!0}),end:_v4.z.iso.datetime({offset:!0})}).strict().refine(o=>Date.parse(o.end)>Date.parse(o.start),{message:"The end must be later than the start of the range.",path:["end"]}),_v4.z.object({type:_v4.z.literal("relative"),unit:c,amount:_v4.z.number().int().positive()}).strict()]),chart:r.optional()}).strict()]),D= exports.u =_v4.z.object({name:_v4.z.string().trim().min(1),description:_v4.z.string().optional(),content:_v4.z.object({cells:_v4.z.array(y)})}),b= exports.v =_v4.z.object({id:_v4.z.string(),name:_v4.z.string(),description:_v4.z.string().nullable(),favorite:_v4.z.boolean(),inserted_at:_v4.z.string(),updated_at:_v4.z.string(),owner:i,updated_by:i}),F= exports.w =b.extend({content:_v4.z.object({schema_version:_v4.z.number(),cells:_v4.z.array(u)})}),L= exports.x =_v4.z.enum(["legacy","publishable"]);exports.a = n; exports.b = j; exports.c = x; exports.d = _; exports.e = O; exports.f = P; exports.g = m; exports.h = k; exports.i = I; exports.j = z; exports.k = v; exports.l = C; exports.m = N; exports.n = T; exports.o = B; exports.p = l; exports.q = E; exports.r = w; exports.s = A; exports.t = u; exports.u = D; exports.v = b; exports.w = F; exports.x = L;
|
|
2
|
+
//# sourceMappingURL=chunk-GEJ6NAOC.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/platform/types.ts","../src/regions.ts"],"names":["AWS_REGION_CODES","storageBucketSchema","z","storageConfigSchema","organizationSchema","projectSchema","branchSchema","edgeFunctionSchema","edgeFunctionWithBodySchema","createProjectOptionsSchema","createBranchOptionsSchema","resetBranchOptionsSchema","deployEdgeFunctionOptionsSchema","executeSqlOptionsSchema","applyMigrationOptionsSchema","migrationSchema","logsServiceSchema","getLogsOptionsSchema","queryLogsOptionsSchema","generateTypescriptTypesResultSchema","notebookUserSchema","notebookChartConfigSchema","notebookMarkdownCellSchema","notebookDatabaseCellSchema","notebookLogTimeUnitSchema","notebookLogTimeRangeSchema","notebookLogCellSchema","notebookCellSchema","newNotebookChartConfigSchema","newNotebookSqlSchema","newNotebookCellSchema","range","createNotebookOptionsSchema","notebookSchema","notebookWithContentSchema","apiKeyTypeSchema"],"mappings":"AACA,qGAAkB,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CAAU,aAAa,CAAC,CAAA,CAAA,uWAAA","file":"/home/copilot/dev/schemarch-rebuild/mcp/packages/mcp-server-schemarch/dist/chunk-GEJ6NAOC.cjs","sourcesContent":["import type { InitData } from '@schemarch/mcp-utils';\nimport { z } from 'zod/v4';\nimport { AWS_REGION_CODES } from '../regions.js';\n\nexport type SuccessResponse = {\n success: true;\n};\n\nexport const storageBucketSchema = z.object({\n id: z.string(),\n name: z.string(),\n owner: z.string(),\n created_at: z.string(),\n updated_at: z.string(),\n public: z.boolean(),\n});\n\nexport const storageConfigSchema = z.object({\n fileSizeLimit: z.number().int().min(0).max(536_870_912_000), // 500GB\n features: z.object({\n imageTransformation: z.object({ enabled: z.boolean() }),\n s3Protocol: z.object({ enabled: z.boolean() }),\n }),\n});\n\nexport const organizationSchema = z.object({\n id: z.string(),\n name: z.string(),\n plan: z.string().optional(),\n allowed_release_channels: z.array(z.string()),\n opt_in_tags: z.array(z.string()),\n});\n\nexport const projectSchema = z.object({\n id: z.string(),\n ref: z.string(),\n organization_id: z.string(),\n organization_slug: z.string(),\n name: z.string(),\n status: z.string(),\n created_at: z.string(),\n region: z.string(),\n});\n\nexport const branchSchema = z.object({\n id: z.string(),\n name: z.string(),\n project_ref: z.string(),\n parent_project_ref: z.string(),\n is_default: z.boolean(),\n git_branch: z.string().optional(),\n pr_number: z.number().optional(),\n latest_check_run_id: z.number().optional(),\n persistent: z.boolean(),\n status: z.enum([\n 'CREATING_PROJECT',\n 'RUNNING_MIGRATIONS',\n 'MIGRATIONS_PASSED',\n 'MIGRATIONS_FAILED',\n 'FUNCTIONS_DEPLOYED',\n 'FUNCTIONS_FAILED',\n ]),\n created_at: z.string(),\n updated_at: z.string(),\n});\n\nexport const edgeFunctionSchema = z.object({\n id: z.string(),\n slug: z.string(),\n name: z.string(),\n status: z.string(),\n version: z.number(),\n created_at: z.number().optional(),\n updated_at: z.number().optional(),\n verify_jwt: z.boolean().optional(),\n import_map: z.boolean().optional(),\n import_map_path: z.string().optional(),\n entrypoint_path: z.string().optional(),\n});\n\nexport const edgeFunctionWithBodySchema = edgeFunctionSchema.extend({\n files: z.array(\n z.object({\n name: z.string(),\n content: z.string(),\n })\n ),\n});\n\nexport const createProjectOptionsSchema = z.object({\n name: z.string().min(1).max(256),\n organization_id: z.string(),\n region: z.enum(AWS_REGION_CODES),\n db_pass: z.string().optional(),\n});\n\nexport const createBranchOptionsSchema = z.object({\n name: z.string().min(1),\n});\n\nexport const resetBranchOptionsSchema = z.object({\n migration_version: z.string().optional(),\n});\n\nexport const deployEdgeFunctionOptionsSchema = z.object({\n name: z.string().regex(/^[A-Za-z][A-Za-z0-9_-]*$/),\n entrypoint_path: z.string(),\n import_map_path: z.string().optional(),\n verify_jwt: z.boolean().optional(),\n files: z.array(\n z.object({\n name: z.string(),\n content: z.string(),\n })\n ),\n});\n\nexport const executeSqlOptionsSchema = z.object({\n query: z.string().min(1),\n parameters: z.array(z.unknown()).optional(),\n read_only: z.boolean().optional(),\n /**\n * Largest result, in bytes of JSON, the caller will use. Platforms that\n * buffer results in shared server memory should stop reading and throw once\n * it's exceeded. Callers still check the rows they get back.\n */\n max_result_bytes: z.number().int().nonnegative().optional(),\n});\n\nexport const applyMigrationOptionsSchema = z.object({\n name: z.string().min(1),\n query: z.string().min(1),\n});\n\nexport const migrationSchema = z.object({\n version: z.string(),\n name: z.string().optional(),\n});\n\nexport const logsServiceSchema = z.enum([\n 'api',\n 'branch-action',\n 'postgres',\n 'edge-function',\n 'edge-function-runtime',\n 'auth',\n 'storage',\n 'realtime',\n]);\n\nexport const getLogsOptionsSchema = z.object({\n service: logsServiceSchema,\n iso_timestamp_start: z.string().optional(),\n iso_timestamp_end: z.string().optional(),\n});\n\nexport const queryLogsOptionsSchema = z.object({\n sql: z.string().min(1),\n iso_timestamp_start: z.string().optional(),\n iso_timestamp_end: z.string().optional(),\n});\n\nexport const generateTypescriptTypesResultSchema = z.object({\n types: z.string(),\n});\n\nconst notebookUserSchema = z\n .object({\n id: z.number(),\n username: z.string(),\n })\n .nullable();\n\nconst notebookChartConfigSchema = z.object({\n type: z.enum(['bar', 'line']),\n x_column: z.string(),\n y_series: z.array(z.object({ column: z.string() })),\n scale: z.enum(['linear', 'log']),\n cumulative: z.boolean(),\n show_labels: z.boolean(),\n});\n\nconst notebookMarkdownCellSchema = z.object({\n id: z.string(),\n type: z.literal('markdown'),\n text: z.string(),\n});\n\nconst notebookDatabaseCellSchema = z.object({\n id: z.string(),\n type: z.literal('database'),\n sql: z.string(),\n row_limit: z.number(),\n database_identifier: z.string().optional(),\n title: z.string().optional(),\n view: z.enum(['table', 'chart']).optional(),\n chart: notebookChartConfigSchema.optional(),\n});\n\nconst notebookLogTimeUnitSchema = z.enum([\n 'minute',\n 'hour',\n 'day',\n 'week',\n 'month',\n 'year',\n]);\n\nconst notebookLogTimeRangeSchema = z.union([\n z.object({\n type: z.literal('absolute'),\n start: z.string(),\n end: z.string(),\n }),\n z.object({\n type: z.literal('relative'),\n unit: notebookLogTimeUnitSchema,\n amount: z.number(),\n }),\n]);\n\nconst notebookLogCellSchema = z.object({\n id: z.string(),\n type: z.literal('log'),\n sql: z.string(),\n time_range: notebookLogTimeRangeSchema,\n title: z.string().optional(),\n view: z.enum(['table', 'chart']).optional(),\n chart: notebookChartConfigSchema.optional(),\n});\n\nexport const notebookCellSchema = z.discriminatedUnion('type', [\n notebookMarkdownCellSchema,\n notebookDatabaseCellSchema,\n notebookLogCellSchema,\n]);\n\n// Cell keys to create, without server-assigned ids. Stricter than the read\n// schemas above, so a misspelled cell key fails instead of being dropped.\nconst newNotebookChartConfigSchema = notebookChartConfigSchema\n .extend({\n y_series: z.array(\n notebookChartConfigSchema.shape.y_series.element.strict()\n ),\n })\n .strict();\n\nconst newNotebookSqlSchema = z.string().trim().min(1);\n\nconst newNotebookCellSchema = z.discriminatedUnion('type', [\n notebookMarkdownCellSchema.omit({ id: true }).strict(),\n notebookDatabaseCellSchema\n .omit({ id: true })\n .extend({\n sql: newNotebookSqlSchema,\n row_limit: z.number().int().positive(),\n database_identifier: z.string().min(1).optional(),\n chart: newNotebookChartConfigSchema.optional(),\n })\n .strict(),\n notebookLogCellSchema\n .omit({ id: true })\n .extend({\n sql: newNotebookSqlSchema,\n time_range: z.discriminatedUnion('type', [\n z\n .object({\n type: z.literal('absolute'),\n start: z.iso.datetime({ offset: true }),\n end: z.iso.datetime({ offset: true }),\n })\n .strict()\n .refine((range) => Date.parse(range.end) > Date.parse(range.start), {\n message: 'The end must be later than the start of the range.',\n path: ['end'],\n }),\n z\n .object({\n type: z.literal('relative'),\n unit: notebookLogTimeUnitSchema,\n amount: z.number().int().positive(),\n })\n .strict(),\n ]),\n chart: newNotebookChartConfigSchema.optional(),\n })\n .strict(),\n]);\n\nexport const createNotebookOptionsSchema = z.object({\n name: z.string().trim().min(1),\n description: z.string().optional(),\n content: z.object({\n cells: z.array(newNotebookCellSchema),\n }),\n});\n\nexport const notebookSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string().nullable(),\n favorite: z.boolean(),\n inserted_at: z.string(),\n updated_at: z.string(),\n owner: notebookUserSchema,\n updated_by: notebookUserSchema,\n});\n\nexport const notebookWithContentSchema = notebookSchema.extend({\n content: z.object({\n schema_version: z.number(),\n cells: z.array(notebookCellSchema),\n }),\n});\n\nexport type Organization = z.infer<typeof organizationSchema>;\nexport type Project = z.infer<typeof projectSchema>;\nexport type Branch = z.infer<typeof branchSchema>;\nexport type EdgeFunction = z.infer<typeof edgeFunctionSchema>;\nexport type EdgeFunctionWithBody = z.infer<typeof edgeFunctionWithBodySchema>;\n\nexport type CreateProjectOptions = z.infer<typeof createProjectOptionsSchema>;\nexport type CreateBranchOptions = z.infer<typeof createBranchOptionsSchema>;\nexport type ResetBranchOptions = z.infer<typeof resetBranchOptionsSchema>;\nexport type DeployEdgeFunctionOptions = z.infer<\n typeof deployEdgeFunctionOptionsSchema\n>;\n\nexport type ExecuteSqlOptions = z.infer<typeof executeSqlOptionsSchema>;\nexport type ApplyMigrationOptions = z.infer<typeof applyMigrationOptionsSchema>;\nexport type Migration = z.infer<typeof migrationSchema>;\nexport type ListMigrationsResult = z.infer<typeof migrationSchema>;\n\nexport type LogsService = z.infer<typeof logsServiceSchema>;\nexport type GetLogsOptions = z.infer<typeof getLogsOptionsSchema>;\nexport type QueryLogsOptions = z.infer<typeof queryLogsOptionsSchema>;\nexport type GenerateTypescriptTypesResult = z.infer<\n typeof generateTypescriptTypesResultSchema\n>;\n\nexport type StorageConfig = z.infer<typeof storageConfigSchema>;\nexport type StorageBucket = z.infer<typeof storageBucketSchema>;\n\nexport type NotebookCell = z.infer<typeof notebookCellSchema>;\nexport type CreateNotebookOptions = z.infer<typeof createNotebookOptionsSchema>;\nexport type Notebook = z.infer<typeof notebookSchema>;\nexport type NotebookWithContent = z.infer<typeof notebookWithContentSchema>;\n\nexport type DatabaseOperations = {\n executeSql<T>(projectId: string, options: ExecuteSqlOptions): Promise<T[]>;\n listMigrations(projectId: string): Promise<Migration[]>;\n applyMigration(\n projectId: string,\n options: ApplyMigrationOptions\n ): Promise<void>;\n};\n\nexport type AccountOperations = {\n listOrganizations(): Promise<{ id: string; slug: string; name: string }[]>;\n getOrganization(organizationId: string): Promise<Organization>;\n listProjects(): Promise<Project[]>;\n getProject(projectId: string): Promise<Project>;\n createProject(options: CreateProjectOptions): Promise<Project>;\n pauseProject(projectId: string): Promise<void>;\n restoreProject(projectId: string): Promise<void>;\n};\n\nexport type EdgeFunctionsOperations = {\n listEdgeFunctions(projectId: string): Promise<EdgeFunction[]>;\n getEdgeFunction(\n projectId: string,\n functionSlug: string\n ): Promise<EdgeFunctionWithBody>;\n deployEdgeFunction(\n projectId: string,\n options: DeployEdgeFunctionOptions\n ): Promise<Omit<EdgeFunction, 'files'>>;\n};\n\n/**\n * SQL dialect that a platform's logs endpoint speaks. Selects the\n * dialect-appropriate `query_logs` description and `sql` parameter hint so a\n * single tool can roll out across environments that back logs with different\n * engines (hosted ClickHouse vs. self-hosted/CLI BigQuery).\n */\nexport type LogsDialect = 'clickhouse' | 'bigquery';\n\nexport type DebuggingOperations = {\n /**\n * SQL dialect accepted by `queryLogs`. Defaults to `'clickhouse'` when unset,\n * preserving the behavior of platforms that predate this field.\n */\n logsDialect?: LogsDialect;\n getLogs(projectId: string, options: GetLogsOptions): Promise<unknown>;\n queryLogs?(projectId: string, options: QueryLogsOptions): Promise<unknown>;\n getSecurityAdvisors(projectId: string): Promise<unknown>;\n getPerformanceAdvisors(projectId: string): Promise<unknown>;\n getHealthAdvisors?(projectId: string): Promise<unknown>;\n};\n\nexport const apiKeyTypeSchema = z.enum(['legacy', 'publishable']);\nexport type ApiKeyType = z.infer<typeof apiKeyTypeSchema>;\n\nexport type ApiKey = {\n api_key: string;\n name: string;\n type: ApiKeyType;\n description?: string;\n id?: string;\n disabled?: boolean;\n};\n\nexport type DevelopmentOperations = {\n getProjectUrl(projectId: string): Promise<string>;\n getPublishableKeys(projectId: string): Promise<ApiKey[]>;\n generateTypescriptTypes(\n projectId: string\n ): Promise<GenerateTypescriptTypesResult>;\n};\n\nexport type StorageOperations = {\n getStorageConfig(projectId: string): Promise<StorageConfig>;\n updateStorageConfig(projectId: string, config: StorageConfig): Promise<void>;\n listAllBuckets(projectId: string): Promise<StorageBucket[]>;\n};\n\nexport type BranchingOperations = {\n listBranches(projectId: string): Promise<Branch[]>;\n createBranch(\n projectId: string,\n options: CreateBranchOptions\n ): Promise<Branch>;\n deleteBranch(branchId: string): Promise<void>;\n mergeBranch(branchId: string): Promise<void>;\n resetBranch(branchId: string, options: ResetBranchOptions): Promise<void>;\n rebaseBranch(branchId: string): Promise<void>;\n};\n\n/**\n * Returns only the `updated_at` timestamp of the named secret, never its\n * value or digest.\n */\nexport type SecretOperations = {\n getUpdatedAt(projectId: string, name: string): Promise<Date | undefined>;\n};\n\nexport type NotebookOperations = {\n /** Optional for platforms that only support reading notebooks. */\n createNotebook?(\n projectId: string,\n options: CreateNotebookOptions\n ): Promise<NotebookWithContent>;\n listNotebooks(projectId: string): Promise<Notebook[]>;\n getNotebook(\n projectId: string,\n notebookId: string\n ): Promise<NotebookWithContent>;\n};\n\nexport type FeedbackOperations = {\n submit(input: {\n feedback: string;\n projectId?: string;\n clientInfo?: { name: string; version: string };\n }): Promise<{ deleteToken: string }>;\n delete(input: {\n deleteToken: string;\n projectId?: string;\n }): Promise<{ deleted: boolean }>;\n};\n\nexport type SchemarchPlatform = {\n init?(info: InitData): Promise<void>;\n account?: AccountOperations;\n database?: DatabaseOperations;\n functions?: EdgeFunctionsOperations;\n debugging?: DebuggingOperations;\n development?: DevelopmentOperations;\n storage?: StorageOperations;\n branching?: BranchingOperations;\n secrets?: SecretOperations;\n notebooks?: NotebookOperations;\n feedback?: FeedbackOperations;\n};\n","export const AWS_REGION_CODES = [\n 'us-west-1',\n 'us-east-1',\n 'us-east-2',\n 'ca-central-1',\n 'eu-west-1',\n 'eu-west-2',\n 'eu-west-3',\n 'eu-central-1',\n 'eu-central-2',\n 'eu-north-1',\n 'ap-south-1',\n 'ap-southeast-1',\n 'ap-northeast-1',\n 'ap-northeast-2',\n 'ap-southeast-2',\n 'sa-east-1',\n] as const;\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=chunk-LU6L7C36.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|