@vreko/api-client 1.0.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 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 SnapBack, Inc.
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,38 @@
1
+ import { A as ApiRouterClient } from '../types-DX_FMVpM.js';
2
+ import '@orpc/server';
3
+ import '@vreko/api/orpc/router';
4
+
5
+ /**
6
+ * Browser/Web adapter for Vreko API client.
7
+ *
8
+ * Better Auth Integration:
9
+ * - Uses session cookies (automatic via credentials: 'include')
10
+ * - No explicit token needed - Better Auth validates cookies
11
+ * - CORS credentials enabled for cross-subdomain requests
12
+ */
13
+
14
+ interface BrowserClientConfig {
15
+ /** Base URL (defaults to NEXT_PUBLIC_API_URL or window.location.origin) */
16
+ baseUrl?: string;
17
+ /** Custom headers */
18
+ headers?: Record<string, string>;
19
+ }
20
+ /**
21
+ * Create a browser-optimized API client.
22
+ *
23
+ * Automatically handles:
24
+ * - Cookie-based authentication via Better Auth session cookies
25
+ * - CORS credentials for cross-subdomain requests
26
+ * - Environment detection for base URL
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * import { createBrowserClient } from '@vreko/api-client/browser';
31
+ *
32
+ * const client = createBrowserClient();
33
+ * const metrics = await client.dashboard.getMetrics();
34
+ * ```
35
+ */
36
+ declare function createBrowserClient(config?: BrowserClientConfig): ApiRouterClient;
37
+
38
+ export { type BrowserClientConfig, createBrowserClient };
@@ -0,0 +1,66 @@
1
+ import { onError, createORPCClient } from '@orpc/client';
2
+ import { RPCLink } from '@orpc/client/fetch';
3
+
4
+ // src/client.ts
5
+ function createVrekoClient(config) {
6
+ const link = new RPCLink({
7
+ url: `${config.baseUrl}/api/rpc`,
8
+ fetch: config.fetch,
9
+ headers: async () => {
10
+ const headers = {
11
+ "Content-Type": "application/json",
12
+ ...config.headers
13
+ };
14
+ if (config.apiKey) {
15
+ headers["X-API-Key"] = config.apiKey;
16
+ } else if (config.accessToken) {
17
+ headers.Authorization = `Bearer ${config.accessToken}`;
18
+ }
19
+ return headers;
20
+ },
21
+ interceptors: [
22
+ onError((error) => {
23
+ if (error instanceof Error && error.name === "AbortError") {
24
+ return;
25
+ }
26
+ config.onError?.(error instanceof Error ? error : new Error(String(error)));
27
+ if (process.env.NODE_ENV === "development") ;
28
+ })
29
+ ]
30
+ });
31
+ return createORPCClient(link);
32
+ }
33
+
34
+ // src/adapters/browser.ts
35
+ function createBrowserClient(config = {}) {
36
+ const baseUrl = config.baseUrl || getDefaultBaseUrl();
37
+ const fetchWithCredentials = (input, init) => {
38
+ return fetch(input, {
39
+ ...init,
40
+ credentials: "include"
41
+ // Critical for Better Auth session cookies
42
+ });
43
+ };
44
+ return createVrekoClient({
45
+ baseUrl,
46
+ headers: config.headers,
47
+ fetch: fetchWithCredentials
48
+ // No apiKey or accessToken - browser uses cookies
49
+ });
50
+ }
51
+ function getDefaultBaseUrl() {
52
+ if (typeof window === "undefined") {
53
+ return process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
54
+ }
55
+ if (process.env.NEXT_PUBLIC_API_URL) {
56
+ return process.env.NEXT_PUBLIC_API_URL;
57
+ }
58
+ if (process.env.NODE_ENV === "development") {
59
+ return "http://localhost:3001";
60
+ }
61
+ return window.location.origin;
62
+ }
63
+
64
+ export { createBrowserClient };
65
+ //# sourceMappingURL=browser.js.map
66
+ //# sourceMappingURL=browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/client.ts","../../src/adapters/browser.ts"],"names":[],"mappings":";;;;AAqDO,SAAS,kBAAkB,MAAA,EAAuC;AACxE,EAAA,MAAM,IAAA,GAAO,IAAI,OAAA,CAAQ;AAAA,IACxB,GAAA,EAAK,CAAA,EAAG,MAAA,CAAO,OAAO,CAAA,QAAA,CAAA;AAAA,IACtB,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,SAAS,YAAY;AACpB,MAAA,MAA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,EAAO;AAAA;AAAA,GAEP,CAAA;AACF;AAEA,SAAS,iBAAA,GAA4B;AAEpC,EAAA,IAAI,OAAO,WAAW,WAAA,EAAa;AAClC,IAAA,OAAO,OAAA,CAAQ,IAAI,mBAAA,IAAuB,uBAAA;AAAA,EAC3C;AAGA,EAAA,IAAI,OAAA,CAAQ,IAAI,mBAAA,EAAqB;AACpC,IAAA,OAAO,QAAQ,GAAA,CAAI,mBAAA;AAAA,EACpB;AAGA,EAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,QAAA,KAAa,aAAA,EAAe;AAC3C,IAAA,OAAO,uBAAA;AAAA,EACR;AAGA,EAAA,OAAO,OAAO,QAAA,CAAS,MAAA;AACxB","file":"browser.js","sourcesContent":["import { createORPCClient, onError } from \"@orpc/client\";\nimport { RPCLink } from \"@orpc/client/fetch\";\nimport type { ApiRouterClient } from \"./types\";\n\n/**\n * Configuration for creating a Vreko API client\n *\n * Better Auth supports three authentication methods:\n * 1. API Key (X-API-Key header) - for CLI/scripts\n * 2. Bearer Token (Authorization header) - for VS Code extension\n * 3. Session Cookies (automatic) - for web/browser\n */\nexport interface ClientConfig {\n\t/** Base URL of the API server */\n\tbaseUrl: string;\n\n\t/** Optional API key for authentication (sets X-API-Key header) */\n\tapiKey?: string;\n\n\t/** Optional access token for Bearer auth (sets Authorization header) */\n\taccessToken?: string;\n\n\t/** Custom headers to include with every request */\n\theaders?: Record<string, string>;\n\n\t/** Custom fetch implementation (for testing or special environments) */\n\tfetch?: typeof fetch;\n\n\t/** Error handler callback */\n\tonError?: (error: Error) => void;\n}\n\n/**\n * Create a Vreko API client with Better Auth integration.\n *\n * All requests flow through Better Auth middleware which validates:\n * - X-API-Key headers (for CLI/Node)\n * - Authorization Bearer tokens (for VS Code)\n * - Session cookies (for browser)\n *\n * @param config - Client configuration\n * @returns Fully typed API client\n *\n * @example\n * ```typescript\n * const client = createVrekoClient({\n * baseUrl: 'https://api.vreko.dev',\n * apiKey: 'sk_...'\n * });\n *\n * const metrics = await client.dashboard.getMetrics();\n * ```\n */\nexport function createVrekoClient(config: ClientConfig): ApiRouterClient {\n\tconst link = new RPCLink({\n\t\turl: `${config.baseUrl}/api/rpc`,\n\t\tfetch: config.fetch,\n\t\theaders: async () => {\n\t\t\tconst headers: Record<string, string> = {\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...config.headers,\n\t\t\t};\n\n\t\t\t// Better Auth Authentication Priority:\n\t\t\t// 1. API Key (for CLI/scripts) - most explicit\n\t\t\tif (config.apiKey) {\n\t\t\t\theaders[\"X-API-Key\"] = config.apiKey;\n\t\t\t}\n\t\t\t// 2. Bearer Token (for VS Code extension)\n\t\t\telse if (config.accessToken) {\n\t\t\t\theaders.Authorization = `Bearer ${config.accessToken}`;\n\t\t\t}\n\t\t\t// 3. Session cookies handled automatically by browser\n\n\t\t\treturn headers;\n\t\t},\n\t\tinterceptors: [\n\t\t\tonError((error) => {\n\t\t\t\t// Skip abort errors (user cancelled)\n\t\t\t\tif (error instanceof Error && error.name === \"AbortError\") {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Call custom error handler if provided\n\t\t\t\tconfig.onError?.(error instanceof Error ? error : new Error(String(error)));\n\n\t\t\t\t// Log to console in development\n\t\t\t\tif (process.env.NODE_ENV === \"development\") {\n\t\t\t\t\t// intentionally empty\n\t\t\t\t}\n\t\t\t}),\n\t\t],\n\t});\n\n\treturn createORPCClient(link) as ApiRouterClient;\n}\n","/**\n * Browser/Web adapter for Vreko API client.\n *\n * Better Auth Integration:\n * - Uses session cookies (automatic via credentials: 'include')\n * - No explicit token needed - Better Auth validates cookies\n * - CORS credentials enabled for cross-subdomain requests\n */\n\nimport { createVrekoClient } from \"../client\";\nimport type { ApiRouterClient } from \"../types\";\n\nexport interface BrowserClientConfig {\n\t/** Base URL (defaults to NEXT_PUBLIC_API_URL or window.location.origin) */\n\tbaseUrl?: string;\n\n\t/** Custom headers */\n\theaders?: Record<string, string>;\n}\n\n/**\n * Create a browser-optimized API client.\n *\n * Automatically handles:\n * - Cookie-based authentication via Better Auth session cookies\n * - CORS credentials for cross-subdomain requests\n * - Environment detection for base URL\n *\n * @example\n * ```typescript\n * import { createBrowserClient } from '@vreko/api-client/browser';\n *\n * const client = createBrowserClient();\n * const metrics = await client.dashboard.getMetrics();\n * ```\n */\nexport function createBrowserClient(config: BrowserClientConfig = {}): ApiRouterClient {\n\tconst baseUrl = config.baseUrl || getDefaultBaseUrl();\n\n\t// Custom fetch that includes credentials for Better Auth cookies\n\tconst fetchWithCredentials: typeof fetch = (input, init) => {\n\t\treturn fetch(input, {\n\t\t\t...init,\n\t\t\tcredentials: \"include\", // Critical for Better Auth session cookies\n\t\t});\n\t};\n\n\treturn createVrekoClient({\n\t\tbaseUrl,\n\t\theaders: config.headers,\n\t\tfetch: fetchWithCredentials,\n\t\t// No apiKey or accessToken - browser uses cookies\n\t});\n}\n\nfunction getDefaultBaseUrl(): string {\n\t// Server-side (Next.js)\n\tif (typeof window === \"undefined\") {\n\t\treturn process.env.NEXT_PUBLIC_API_URL || \"http://localhost:3001\";\n\t}\n\n\t// Client-side\n\tif (process.env.NEXT_PUBLIC_API_URL) {\n\t\treturn process.env.NEXT_PUBLIC_API_URL;\n\t}\n\n\t// Development fallback\n\tif (process.env.NODE_ENV === \"development\") {\n\t\treturn \"http://localhost:3001\";\n\t}\n\n\t// Production - use same origin\n\treturn window.location.origin;\n}\n"]}
@@ -0,0 +1,48 @@
1
+ import { A as ApiRouterClient } from '../types-DX_FMVpM.js';
2
+ import '@orpc/server';
3
+ import '@vreko/api/orpc/router';
4
+
5
+ /**
6
+ * Node.js/CLI adapter for Vreko API client.
7
+ *
8
+ * Better Auth Integration:
9
+ * - Uses X-API-Key header for authentication
10
+ * - Fallback to Bearer token if access token provided
11
+ * - Environment variable support (VREKO_API_KEY)
12
+ */
13
+
14
+ interface NodeClientConfig {
15
+ /** Base URL of the API server */
16
+ baseUrl?: string;
17
+ /** API key for authentication (sent as X-API-Key header) */
18
+ apiKey?: string;
19
+ /** Access token (alternative to API key, sent as Bearer token) */
20
+ accessToken?: string;
21
+ }
22
+ /**
23
+ * Create a Node.js-optimized API client.
24
+ *
25
+ * Automatically handles:
26
+ * - API key authentication via X-API-Key header (Better Auth validates)
27
+ * - Bearer token authentication (fallback)
28
+ * - Environment variable fallbacks (VREKO_API_KEY, VREKO_API_URL)
29
+ *
30
+ * @example
31
+ * ```typescript
32
+ * import { createNodeClient } from '@vreko/api-client/node';
33
+ *
34
+ * // Using environment variables
35
+ * const client = createNodeClient();
36
+ *
37
+ * // Or explicit configuration
38
+ * const client = createNodeClient({
39
+ * baseUrl: 'https://api.vreko.dev',
40
+ * apiKey: 'sk_...'
41
+ * });
42
+ *
43
+ * const result = await client.signals.comprehensive({ files: [...] });
44
+ * ```
45
+ */
46
+ declare function createNodeClient(config?: NodeClientConfig): ApiRouterClient;
47
+
48
+ export { type NodeClientConfig, createNodeClient };
@@ -0,0 +1,48 @@
1
+ import { onError, createORPCClient } from '@orpc/client';
2
+ import { RPCLink } from '@orpc/client/fetch';
3
+
4
+ // src/client.ts
5
+ function createVrekoClient(config) {
6
+ const link = new RPCLink({
7
+ url: `${config.baseUrl}/api/rpc`,
8
+ fetch: config.fetch,
9
+ headers: async () => {
10
+ const headers = {
11
+ "Content-Type": "application/json",
12
+ ...config.headers
13
+ };
14
+ if (config.apiKey) {
15
+ headers["X-API-Key"] = config.apiKey;
16
+ } else if (config.accessToken) {
17
+ headers.Authorization = `Bearer ${config.accessToken}`;
18
+ }
19
+ return headers;
20
+ },
21
+ interceptors: [
22
+ onError((error) => {
23
+ if (error instanceof Error && error.name === "AbortError") {
24
+ return;
25
+ }
26
+ config.onError?.(error instanceof Error ? error : new Error(String(error)));
27
+ if (process.env.NODE_ENV === "development") ;
28
+ })
29
+ ]
30
+ });
31
+ return createORPCClient(link);
32
+ }
33
+
34
+ // src/adapters/node.ts
35
+ function createNodeClient(config = {}) {
36
+ const baseUrl = config.baseUrl || process.env.VREKO_API_URL || "https://api.vreko.dev";
37
+ const apiKey = config.apiKey || process.env.VREKO_API_KEY;
38
+ const accessToken = config.accessToken || process.env.VREKO_ACCESS_TOKEN;
39
+ return createVrekoClient({
40
+ baseUrl,
41
+ apiKey,
42
+ accessToken
43
+ });
44
+ }
45
+
46
+ export { createNodeClient };
47
+ //# sourceMappingURL=node.js.map
48
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/client.ts","../../src/adapters/node.ts"],"names":[],"mappings":";;;;AAqDO,SAAS,kBAAkB,MAAA,EAAuC;AACxE,EAAA,MAAM,IAAA,GAAO,IAAI,OAAA,CAAQ;AAAA,IACxB,GAAA,EAAK,CAAA,EAAG,MAAA,CAAO,OAAO,CAAA,QAAA,CAAA;AAAA,IACtB,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,SAAS,YAAY;AACpB,MAAA,MAAM,OAAA,GAAkC;AAAA,QACvC,cAAA,EAAgB,kBAAA;AAAA,QAChB,GAAG,MAAA,CAAO;AAAA,OACX;AAIA,MAAA,IAAI,OAAO,MAAA,EAAQ;AAClB,QAAA,OAAA,CAAQ,WAAW,IAAI,MAAA,CAAO,MAAA;AAAA,MAC/B,CAAA,MAAA,IAES,OAAO,WAAA,EAAa;AAC5B,QAAA,OAAA,CAAQ,aAAA,GAAgB,CAAA,OAAA,EAAU,MAAA,CAAO,WAAW,CAAA,CAAA;AAAA,MACrD;AAGA,MAAA,OAAO,OAAA;AAAA,IACR,CAAA;AAAA,IACA,YAAA,EAAc;AAAA,MACb,OAAA,CAAQ,CAAC,KAAA,KAAU;AAElB,QAAA,IAAI,KAAA,YAAiB,KAAA,IAAS,KAAA,CAAM,IAAA,KAAS,YAAA,EAAc;AAC1D,UAAA;AAAA,QACD;AAGA,QAAA,MAAA,CAAO,OAAA,GAAU,iBAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAA,CAAO,KAAK,CAAC,CAAC,CAAA;AAG1E,QAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,QAAA,KAAa,aAAA,EAAe;AAE5C,MACD,CAAC;AAAA;AACF,GACA,CAAA;AAED,EAAA,OAAO,iBAAiB,IAAI,CAAA;AAC7B;;;AChDO,SAAS,gBAAA,CAAiB,MAAA,GAA2B,EAAC,EAAoB;AAChF,EAAA,MAAM,OAAA,GAAU,MAAA,CAAO,OAAA,IAAW,OAAA,CAAQ,IAAI,aAAA,IAAiB,uBAAA;AAC/D,EAAA,MAAM,MAAA,GAAS,MAAA,CAAO,MAAA,IAAU,OAAA,CAAQ,GAAA,CAAI,aAAA;AAC5C,EAAA,MAAM,WAAA,GAAc,MAAA,CAAO,WAAA,IAAe,OAAA,CAAQ,GAAA,CAAI,kBAAA;AAMtD,EAAA,OAAO,iBAAA,CAAkB;AAAA,IACxB,OAAA;AAAA,IACA,MAAA;AAAA,IACA;AAAA,GACA,CAAA;AACF","file":"node.js","sourcesContent":["import { createORPCClient, onError } from \"@orpc/client\";\nimport { RPCLink } from \"@orpc/client/fetch\";\nimport type { ApiRouterClient } from \"./types\";\n\n/**\n * Configuration for creating a Vreko API client\n *\n * Better Auth supports three authentication methods:\n * 1. API Key (X-API-Key header) - for CLI/scripts\n * 2. Bearer Token (Authorization header) - for VS Code extension\n * 3. Session Cookies (automatic) - for web/browser\n */\nexport interface ClientConfig {\n\t/** Base URL of the API server */\n\tbaseUrl: string;\n\n\t/** Optional API key for authentication (sets X-API-Key header) */\n\tapiKey?: string;\n\n\t/** Optional access token for Bearer auth (sets Authorization header) */\n\taccessToken?: string;\n\n\t/** Custom headers to include with every request */\n\theaders?: Record<string, string>;\n\n\t/** Custom fetch implementation (for testing or special environments) */\n\tfetch?: typeof fetch;\n\n\t/** Error handler callback */\n\tonError?: (error: Error) => void;\n}\n\n/**\n * Create a Vreko API client with Better Auth integration.\n *\n * All requests flow through Better Auth middleware which validates:\n * - X-API-Key headers (for CLI/Node)\n * - Authorization Bearer tokens (for VS Code)\n * - Session cookies (for browser)\n *\n * @param config - Client configuration\n * @returns Fully typed API client\n *\n * @example\n * ```typescript\n * const client = createVrekoClient({\n * baseUrl: 'https://api.vreko.dev',\n * apiKey: 'sk_...'\n * });\n *\n * const metrics = await client.dashboard.getMetrics();\n * ```\n */\nexport function createVrekoClient(config: ClientConfig): ApiRouterClient {\n\tconst link = new RPCLink({\n\t\turl: `${config.baseUrl}/api/rpc`,\n\t\tfetch: config.fetch,\n\t\theaders: async () => {\n\t\t\tconst headers: Record<string, string> = {\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...config.headers,\n\t\t\t};\n\n\t\t\t// Better Auth Authentication Priority:\n\t\t\t// 1. API Key (for CLI/scripts) - most explicit\n\t\t\tif (config.apiKey) {\n\t\t\t\theaders[\"X-API-Key\"] = config.apiKey;\n\t\t\t}\n\t\t\t// 2. Bearer Token (for VS Code extension)\n\t\t\telse if (config.accessToken) {\n\t\t\t\theaders.Authorization = `Bearer ${config.accessToken}`;\n\t\t\t}\n\t\t\t// 3. Session cookies handled automatically by browser\n\n\t\t\treturn headers;\n\t\t},\n\t\tinterceptors: [\n\t\t\tonError((error) => {\n\t\t\t\t// Skip abort errors (user cancelled)\n\t\t\t\tif (error instanceof Error && error.name === \"AbortError\") {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Call custom error handler if provided\n\t\t\t\tconfig.onError?.(error instanceof Error ? error : new Error(String(error)));\n\n\t\t\t\t// Log to console in development\n\t\t\t\tif (process.env.NODE_ENV === \"development\") {\n\t\t\t\t\t// intentionally empty\n\t\t\t\t}\n\t\t\t}),\n\t\t],\n\t});\n\n\treturn createORPCClient(link) as ApiRouterClient;\n}\n","/**\n * Node.js/CLI adapter for Vreko API client.\n *\n * Better Auth Integration:\n * - Uses X-API-Key header for authentication\n * - Fallback to Bearer token if access token provided\n * - Environment variable support (VREKO_API_KEY)\n */\n\nimport { createVrekoClient } from \"../client\";\nimport type { ApiRouterClient } from \"../types\";\n\nexport interface NodeClientConfig {\n\t/** Base URL of the API server */\n\tbaseUrl?: string;\n\n\t/** API key for authentication (sent as X-API-Key header) */\n\tapiKey?: string;\n\n\t/** Access token (alternative to API key, sent as Bearer token) */\n\taccessToken?: string;\n}\n\n/**\n * Create a Node.js-optimized API client.\n *\n * Automatically handles:\n * - API key authentication via X-API-Key header (Better Auth validates)\n * - Bearer token authentication (fallback)\n * - Environment variable fallbacks (VREKO_API_KEY, VREKO_API_URL)\n *\n * @example\n * ```typescript\n * import { createNodeClient } from '@vreko/api-client/node';\n *\n * // Using environment variables\n * const client = createNodeClient();\n *\n * // Or explicit configuration\n * const client = createNodeClient({\n * baseUrl: 'https://api.vreko.dev',\n * apiKey: 'sk_...'\n * });\n *\n * const result = await client.signals.comprehensive({ files: [...] });\n * ```\n */\nexport function createNodeClient(config: NodeClientConfig = {}): ApiRouterClient {\n\tconst baseUrl = config.baseUrl || process.env.VREKO_API_URL || \"https://api.vreko.dev\";\n\tconst apiKey = config.apiKey || process.env.VREKO_API_KEY;\n\tconst accessToken = config.accessToken || process.env.VREKO_ACCESS_TOKEN;\n\n\tif (!apiKey && !accessToken) {\n\t\t// intentionally empty\n\t}\n\n\treturn createVrekoClient({\n\t\tbaseUrl,\n\t\tapiKey,\n\t\taccessToken,\n\t});\n}\n"]}
@@ -0,0 +1,59 @@
1
+ import { A as ApiRouterClient } from '../types-DX_FMVpM.js';
2
+ import '@orpc/server';
3
+ import '@vreko/api/orpc/router';
4
+
5
+ /**
6
+ * VS Code Extension adapter for Vreko API client.
7
+ *
8
+ * Better Auth Integration:
9
+ * - Uses Bearer token from VS Code SecretStorage
10
+ * - Automatic token refresh on expiration
11
+ * - Secure credential management
12
+ */
13
+
14
+ interface VSCodeClientConfig {
15
+ /** VS Code extension context */
16
+ context: {
17
+ secrets: {
18
+ get(key: string): PromiseLike<string | undefined>;
19
+ onDidChange(listener: (e: {
20
+ key: string;
21
+ }) => void): {
22
+ dispose(): void;
23
+ };
24
+ };
25
+ };
26
+ /** Key in SecretStorage for access token (default: 'vreko.apiKey') */
27
+ secretsKey?: string;
28
+ /** Base URL override */
29
+ baseUrl?: string;
30
+ }
31
+ /**
32
+ * Create a VS Code extension-optimized API client.
33
+ *
34
+ * Features:
35
+ * - Retrieves credentials from VS Code SecretStorage
36
+ * - Caches client instance for performance
37
+ * - Automatically refreshes on credential change
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * import { createVSCodeClient } from '@vreko/api-client/vscode';
42
+ *
43
+ * // In your extension's activate function
44
+ * export function activate(context: vscode.ExtensionContext) {
45
+ * const client = await createVSCodeClient({ context });
46
+ *
47
+ * // Use the client
48
+ * const metrics = await client.dashboard.getMetrics();
49
+ * }
50
+ * ```
51
+ */
52
+ declare function createVSCodeClient(config: VSCodeClientConfig): Promise<ApiRouterClient>;
53
+ /**
54
+ * Clear the cached client instance.
55
+ * Call this when the user logs out.
56
+ */
57
+ declare function clearVSCodeClient(): void;
58
+
59
+ export { ApiRouterClient, type VSCodeClientConfig, clearVSCodeClient, createVSCodeClient };
@@ -0,0 +1,79 @@
1
+ import { onError, createORPCClient } from '@orpc/client';
2
+ import { RPCLink } from '@orpc/client/fetch';
3
+
4
+ // src/client.ts
5
+ function createVrekoClient(config) {
6
+ const link = new RPCLink({
7
+ url: `${config.baseUrl}/api/rpc`,
8
+ fetch: config.fetch,
9
+ headers: async () => {
10
+ const headers = {
11
+ "Content-Type": "application/json",
12
+ ...config.headers
13
+ };
14
+ if (config.apiKey) {
15
+ headers["X-API-Key"] = config.apiKey;
16
+ } else if (config.accessToken) {
17
+ headers.Authorization = `Bearer ${config.accessToken}`;
18
+ }
19
+ return headers;
20
+ },
21
+ interceptors: [
22
+ onError((error) => {
23
+ if (error instanceof Error && error.name === "AbortError") {
24
+ return;
25
+ }
26
+ config.onError?.(error instanceof Error ? error : new Error(String(error)));
27
+ if (process.env.NODE_ENV === "development") ;
28
+ })
29
+ ]
30
+ });
31
+ return createORPCClient(link);
32
+ }
33
+
34
+ // src/adapters/vscode.ts
35
+ var clientInstance = null;
36
+ var currentToken = null;
37
+ async function createVSCodeClient(config) {
38
+ const secretsKey = config.secretsKey || "vreko.apiKey";
39
+ const baseUrl = config.baseUrl || "https://api.vreko.dev";
40
+ const token = await config.context.secrets.get(secretsKey);
41
+ if (clientInstance && token === currentToken) {
42
+ return clientInstance;
43
+ }
44
+ currentToken = token || null;
45
+ clientInstance = createVrekoClient({
46
+ baseUrl,
47
+ accessToken: token,
48
+ onError: async (error) => {
49
+ if (error.message.includes("401") || error.message.includes("403")) {
50
+ try {
51
+ const vscode = await import('vscode');
52
+ const selection = await vscode.window.showWarningMessage(
53
+ "Vreko session expired. Please reconnect your account.",
54
+ "Reconnect"
55
+ );
56
+ if (selection === "Reconnect") {
57
+ await vscode.commands.executeCommand("vreko.login");
58
+ }
59
+ } catch {
60
+ }
61
+ }
62
+ }
63
+ });
64
+ config.context.secrets.onDidChange((e) => {
65
+ if (e.key === secretsKey) {
66
+ clientInstance = null;
67
+ currentToken = null;
68
+ }
69
+ });
70
+ return clientInstance;
71
+ }
72
+ function clearVSCodeClient() {
73
+ clientInstance = null;
74
+ currentToken = null;
75
+ }
76
+
77
+ export { clearVSCodeClient, createVSCodeClient };
78
+ //# sourceMappingURL=vscode.js.map
79
+ //# sourceMappingURL=vscode.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/client.ts","../../src/adapters/vscode.ts"],"names":[],"mappings":";;;;AAqDO,SAAS,kBAAkB,MAAA,EAAuC;AACxE,EAAA,MAAM,IAAA,GAAO,IAAI,OAAA,CAAQ;AAAA,IACxB,GAAA,EAAK,CAAA,EAAG,MAAA,CAAO,OAAO,CAAA,QAAA,CAAA;AAAA,IACtB,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,SAAS,YAAY;AACpB,MAAA,MAAM,OAAA,GAAkC;AAAA,QACvC,cAAA,EAAgB,kBAAA;AAAA,QAChB,GAAG,MAAA,CAAO;AAAA,OACX;AAIA,MAAA,IAAI,OAAO,MAAA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AAA,EAAS,OAAO,KAAA,KAAU;AAEzB,MAAA,IAAI,KAAA,CAAM,QAAQ,QAAA,CAAS,KAAK,KAAK,KAAA,CAAM,OAAA,CAAQ,QAAA,CAAS,KAAK,CAAA,EAAG;AAEnE,QAAA,IAAI;AACH,UAAA,MAAM,MAAA,GAAS,MAAM,OAAO,QAAQ,CAAA;AACpC,UAAA,MAAM,SAAA,GAAY,MAAM,MAAA,CAAO,MAAA,CAAO,kBAAA;AAAA,YACrC,uDAAA;AAAA,YACA;AAAA,WACD;AACA,UAAA,IAAI,cAAc,WAAA,EAAa;AAC9B,YAAA,MAAM,MAAA,CAAO,QAAA,CAAS,cAAA,CAAe,aAAa,CAAA;AAAA,UACnD;AAAA,QACD,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACD;AAAA,IACD;AAAA,GACA,CAAA;AAGD,EAAA,MAAA,CAAO,OAAA,CAAQ,OAAA,CAAQ,WAAA,CAAY,CAAC,CAAA,KAAM;AACzC,IAAA,IAAI,CAAA,CAAE,QAAQ,UAAA,EAAY;AACzB,MAAA,cAAA,GAAiB,IAAA;AACjB,MAAA,YAAA,GAAe,IAAA;AAAA,IAChB;AAAA,EACD,CAAC,CAAA;AAED,EAAA,OAAO,cAAA;AACR;AAMO,SAAS,iBAAA,GAA0B;AACzC,EAAA,cAAA,GAAiB,IAAA;AACjB,EAAA,YAAA,GAAe,IAAA;AAChB","file":"vscode.js","sourcesContent":["import { createORPCClient, onError } from \"@orpc/client\";\nimport { RPCLink } from \"@orpc/client/fetch\";\nimport type { ApiRouterClient } from \"./types\";\n\n/**\n * Configuration for creating a Vreko API client\n *\n * Better Auth supports three authentication methods:\n * 1. API Key (X-API-Key header) - for CLI/scripts\n * 2. Bearer Token (Authorization header) - for VS Code extension\n * 3. Session Cookies (automatic) - for web/browser\n */\nexport interface ClientConfig {\n\t/** Base URL of the API server */\n\tbaseUrl: string;\n\n\t/** Optional API key for authentication (sets X-API-Key header) */\n\tapiKey?: string;\n\n\t/** Optional access token for Bearer auth (sets Authorization header) */\n\taccessToken?: string;\n\n\t/** Custom headers to include with every request */\n\theaders?: Record<string, string>;\n\n\t/** Custom fetch implementation (for testing or special environments) */\n\tfetch?: typeof fetch;\n\n\t/** Error handler callback */\n\tonError?: (error: Error) => void;\n}\n\n/**\n * Create a Vreko API client with Better Auth integration.\n *\n * All requests flow through Better Auth middleware which validates:\n * - X-API-Key headers (for CLI/Node)\n * - Authorization Bearer tokens (for VS Code)\n * - Session cookies (for browser)\n *\n * @param config - Client configuration\n * @returns Fully typed API client\n *\n * @example\n * ```typescript\n * const client = createVrekoClient({\n * baseUrl: 'https://api.vreko.dev',\n * apiKey: 'sk_...'\n * });\n *\n * const metrics = await client.dashboard.getMetrics();\n * ```\n */\nexport function createVrekoClient(config: ClientConfig): ApiRouterClient {\n\tconst link = new RPCLink({\n\t\turl: `${config.baseUrl}/api/rpc`,\n\t\tfetch: config.fetch,\n\t\theaders: async () => {\n\t\t\tconst headers: Record<string, string> = {\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...config.headers,\n\t\t\t};\n\n\t\t\t// Better Auth Authentication Priority:\n\t\t\t// 1. API Key (for CLI/scripts) - most explicit\n\t\t\tif (config.apiKey) {\n\t\t\t\theaders[\"X-API-Key\"] = config.apiKey;\n\t\t\t}\n\t\t\t// 2. Bearer Token (for VS Code extension)\n\t\t\telse if (config.accessToken) {\n\t\t\t\theaders.Authorization = `Bearer ${config.accessToken}`;\n\t\t\t}\n\t\t\t// 3. Session cookies handled automatically by browser\n\n\t\t\treturn headers;\n\t\t},\n\t\tinterceptors: [\n\t\t\tonError((error) => {\n\t\t\t\t// Skip abort errors (user cancelled)\n\t\t\t\tif (error instanceof Error && error.name === \"AbortError\") {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Call custom error handler if provided\n\t\t\t\tconfig.onError?.(error instanceof Error ? error : new Error(String(error)));\n\n\t\t\t\t// Log to console in development\n\t\t\t\tif (process.env.NODE_ENV === \"development\") {\n\t\t\t\t\t// intentionally empty\n\t\t\t\t}\n\t\t\t}),\n\t\t],\n\t});\n\n\treturn createORPCClient(link) as ApiRouterClient;\n}\n","/**\n * VS Code Extension adapter for Vreko API client.\n *\n * Better Auth Integration:\n * - Uses Bearer token from VS Code SecretStorage\n * - Automatic token refresh on expiration\n * - Secure credential management\n */\n\nimport { createVrekoClient } from \"../client\";\nimport type { ApiRouterClient } from \"../types\";\n\n// Re-export types for consumers importing from @vreko/api-client/vscode\nexport type { ApiRouterClient } from \"../types\";\n\nexport interface VSCodeClientConfig {\n\t/** VS Code extension context */\n\tcontext: {\n\t\tsecrets: {\n\t\t\tget(key: string): PromiseLike<string | undefined>;\n\t\t\tonDidChange(listener: (e: { key: string }) => void): { dispose(): void };\n\t\t};\n\t};\n\n\t/** Key in SecretStorage for access token (default: 'vreko.apiKey') */\n\tsecretsKey?: string;\n\n\t/** Base URL override */\n\tbaseUrl?: string;\n}\n\n// Singleton instance per workspace\nlet clientInstance: ApiRouterClient | null = null;\nlet currentToken: string | null = null;\n\n/**\n * Create a VS Code extension-optimized API client.\n *\n * Features:\n * - Retrieves credentials from VS Code SecretStorage\n * - Caches client instance for performance\n * - Automatically refreshes on credential change\n *\n * @example\n * ```typescript\n * import { createVSCodeClient } from '@vreko/api-client/vscode';\n *\n * // In your extension's activate function\n * export function activate(context: vscode.ExtensionContext) {\n * const client = await createVSCodeClient({ context });\n *\n * // Use the client\n * const metrics = await client.dashboard.getMetrics();\n * }\n * ```\n */\nexport async function createVSCodeClient(config: VSCodeClientConfig): Promise<ApiRouterClient> {\n\tconst secretsKey = config.secretsKey || \"vreko.apiKey\";\n\n\t// Use workspace configuration for base URL if available\n\tconst baseUrl = config.baseUrl || \"https://api.vreko.dev\";\n\n\t// Get token from SecretStorage\n\tconst token = await config.context.secrets.get(secretsKey);\n\n\t// Return cached instance if token hasn't changed\n\tif (clientInstance && token === currentToken) {\n\t\treturn clientInstance;\n\t}\n\n\t// Create new client\n\tcurrentToken = token || null;\n\tclientInstance = createVrekoClient({\n\t\tbaseUrl,\n\t\taccessToken: token,\n\t\tonError: async (error) => {\n\t\t\t// Handle session expiration\n\t\t\tif (error.message.includes(\"401\") || error.message.includes(\"403\")) {\n\t\t\t\t// Dynamic import to avoid bundling vscode in published package\n\t\t\t\ttry {\n\t\t\t\t\tconst vscode = await import(\"vscode\");\n\t\t\t\t\tconst selection = await vscode.window.showWarningMessage(\n\t\t\t\t\t\t\"Vreko session expired. Please reconnect your account.\",\n\t\t\t\t\t\t\"Reconnect\",\n\t\t\t\t\t);\n\t\t\t\t\tif (selection === \"Reconnect\") {\n\t\t\t\t\t\tawait vscode.commands.executeCommand(\"vreko.login\");\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t/* intentionally empty */\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t});\n\n\t// Listen for credential changes\n\tconfig.context.secrets.onDidChange((e) => {\n\t\tif (e.key === secretsKey) {\n\t\t\tclientInstance = null; // Force recreation on next call\n\t\t\tcurrentToken = null;\n\t\t}\n\t});\n\n\treturn clientInstance;\n}\n\n/**\n * Clear the cached client instance.\n * Call this when the user logs out.\n */\nexport function clearVSCodeClient(): void {\n\tclientInstance = null;\n\tcurrentToken = null;\n}\n"]}
@@ -0,0 +1,53 @@
1
+ export { BrowserClientConfig, createBrowserClient } from './adapters/browser.js';
2
+ export { NodeClientConfig, createNodeClient } from './adapters/node.js';
3
+ export { VSCodeClientConfig, clearVSCodeClient, createVSCodeClient } from './adapters/vscode.js';
4
+ import { A as ApiRouterClient } from './types-DX_FMVpM.js';
5
+ import '@orpc/server';
6
+ import '@vreko/api/orpc/router';
7
+
8
+ /**
9
+ * Configuration for creating a Vreko API client
10
+ *
11
+ * Better Auth supports three authentication methods:
12
+ * 1. API Key (X-API-Key header) - for CLI/scripts
13
+ * 2. Bearer Token (Authorization header) - for VS Code extension
14
+ * 3. Session Cookies (automatic) - for web/browser
15
+ */
16
+ interface ClientConfig {
17
+ /** Base URL of the API server */
18
+ baseUrl: string;
19
+ /** Optional API key for authentication (sets X-API-Key header) */
20
+ apiKey?: string;
21
+ /** Optional access token for Bearer auth (sets Authorization header) */
22
+ accessToken?: string;
23
+ /** Custom headers to include with every request */
24
+ headers?: Record<string, string>;
25
+ /** Custom fetch implementation (for testing or special environments) */
26
+ fetch?: typeof fetch;
27
+ /** Error handler callback */
28
+ onError?: (error: Error) => void;
29
+ }
30
+ /**
31
+ * Create a Vreko API client with Better Auth integration.
32
+ *
33
+ * All requests flow through Better Auth middleware which validates:
34
+ * - X-API-Key headers (for CLI/Node)
35
+ * - Authorization Bearer tokens (for VS Code)
36
+ * - Session cookies (for browser)
37
+ *
38
+ * @param config - Client configuration
39
+ * @returns Fully typed API client
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * const client = createVrekoClient({
44
+ * baseUrl: 'https://api.vreko.dev',
45
+ * apiKey: 'sk_...'
46
+ * });
47
+ *
48
+ * const metrics = await client.dashboard.getMetrics();
49
+ * ```
50
+ */
51
+ declare function createVrekoClient(config: ClientConfig): ApiRouterClient;
52
+
53
+ export { ApiRouterClient, type ClientConfig, createVrekoClient };
package/dist/index.js ADDED
@@ -0,0 +1,121 @@
1
+ import { onError, createORPCClient } from '@orpc/client';
2
+ import { RPCLink } from '@orpc/client/fetch';
3
+
4
+ // src/client.ts
5
+ function createVrekoClient(config) {
6
+ const link = new RPCLink({
7
+ url: `${config.baseUrl}/api/rpc`,
8
+ fetch: config.fetch,
9
+ headers: async () => {
10
+ const headers = {
11
+ "Content-Type": "application/json",
12
+ ...config.headers
13
+ };
14
+ if (config.apiKey) {
15
+ headers["X-API-Key"] = config.apiKey;
16
+ } else if (config.accessToken) {
17
+ headers.Authorization = `Bearer ${config.accessToken}`;
18
+ }
19
+ return headers;
20
+ },
21
+ interceptors: [
22
+ onError((error) => {
23
+ if (error instanceof Error && error.name === "AbortError") {
24
+ return;
25
+ }
26
+ config.onError?.(error instanceof Error ? error : new Error(String(error)));
27
+ if (process.env.NODE_ENV === "development") ;
28
+ })
29
+ ]
30
+ });
31
+ return createORPCClient(link);
32
+ }
33
+
34
+ // src/adapters/browser.ts
35
+ function createBrowserClient(config = {}) {
36
+ const baseUrl = config.baseUrl || getDefaultBaseUrl();
37
+ const fetchWithCredentials = (input, init) => {
38
+ return fetch(input, {
39
+ ...init,
40
+ credentials: "include"
41
+ // Critical for Better Auth session cookies
42
+ });
43
+ };
44
+ return createVrekoClient({
45
+ baseUrl,
46
+ headers: config.headers,
47
+ fetch: fetchWithCredentials
48
+ // No apiKey or accessToken - browser uses cookies
49
+ });
50
+ }
51
+ function getDefaultBaseUrl() {
52
+ if (typeof window === "undefined") {
53
+ return process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
54
+ }
55
+ if (process.env.NEXT_PUBLIC_API_URL) {
56
+ return process.env.NEXT_PUBLIC_API_URL;
57
+ }
58
+ if (process.env.NODE_ENV === "development") {
59
+ return "http://localhost:3001";
60
+ }
61
+ return window.location.origin;
62
+ }
63
+
64
+ // src/adapters/node.ts
65
+ function createNodeClient(config = {}) {
66
+ const baseUrl = config.baseUrl || process.env.VREKO_API_URL || "https://api.vreko.dev";
67
+ const apiKey = config.apiKey || process.env.VREKO_API_KEY;
68
+ const accessToken = config.accessToken || process.env.VREKO_ACCESS_TOKEN;
69
+ return createVrekoClient({
70
+ baseUrl,
71
+ apiKey,
72
+ accessToken
73
+ });
74
+ }
75
+
76
+ // src/adapters/vscode.ts
77
+ var clientInstance = null;
78
+ var currentToken = null;
79
+ async function createVSCodeClient(config) {
80
+ const secretsKey = config.secretsKey || "vreko.apiKey";
81
+ const baseUrl = config.baseUrl || "https://api.vreko.dev";
82
+ const token = await config.context.secrets.get(secretsKey);
83
+ if (clientInstance && token === currentToken) {
84
+ return clientInstance;
85
+ }
86
+ currentToken = token || null;
87
+ clientInstance = createVrekoClient({
88
+ baseUrl,
89
+ accessToken: token,
90
+ onError: async (error) => {
91
+ if (error.message.includes("401") || error.message.includes("403")) {
92
+ try {
93
+ const vscode = await import('vscode');
94
+ const selection = await vscode.window.showWarningMessage(
95
+ "Vreko session expired. Please reconnect your account.",
96
+ "Reconnect"
97
+ );
98
+ if (selection === "Reconnect") {
99
+ await vscode.commands.executeCommand("vreko.login");
100
+ }
101
+ } catch {
102
+ }
103
+ }
104
+ }
105
+ });
106
+ config.context.secrets.onDidChange((e) => {
107
+ if (e.key === secretsKey) {
108
+ clientInstance = null;
109
+ currentToken = null;
110
+ }
111
+ });
112
+ return clientInstance;
113
+ }
114
+ function clearVSCodeClient() {
115
+ clientInstance = null;
116
+ currentToken = null;
117
+ }
118
+
119
+ export { clearVSCodeClient, createBrowserClient, createNodeClient, createVSCodeClient, createVrekoClient };
120
+ //# sourceMappingURL=index.js.map
121
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts","../src/adapters/browser.ts","../src/adapters/node.ts","../src/adapters/vscode.ts"],"names":[],"mappings":";;;;AAqDO,SAAS,kBAAkB,MAAA,EAAuC;AACxE,EAAA,MAAM,IAAA,GAAO,IAAI,OAAA,CAAQ;AAAA,IACxB,GAAA,EAAK,CAAA,EAAG,MAAA,CAAO,OAAO,CAAA,QAAA,CAAA;AAAA,IACtB,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,SAAS,YAAY;AACpB,MAAA,MAAM,OAAA,GAAkC;AAAA,QACvC,cAAA,EAAgB,kBAAA;AAAA,QAChB,GAAG,MAAA,CAAO;AAAA,OACX;AAIA,MAAA,IAAI,OAAO,MAAA,EAAQ;AAClB,QAAA,OAAA,CAAQ,WAAW,IAAI,MAAA,CAAO,MAAA;AAAA,MAC/B,CAAA,MAAA,IAES,OAAO,WAAA,EAAa;AAC5B,QAAA,OAAA,CAAQ,aAAA,GAAgB,CAAA,OAAA,EAAU,MAAA,CAAO,WAAW,CAAA,CAAA;AAAA,MACrD;AAGA,MAAA,OAAO,OAAA;AAAA,IACR,CAAA;AAAA,IACA,YAAA,EAAc;AAA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,MAAM,SAAA,GAAY,MAAM,MAAA,CAAO,MAAA,CAAO,kBAAA;AAAA,YACrC,uDAAA;AAAA,YACA;AAAA,WACD;AACA,UAAA,IAAI,cAAc,WAAA,EAAa;AAC9B,YAAA,MAAM,MAAA,CAAO,QAAA,CAAS,cAAA,CAAe,aAAa,CAAA;AAAA,UACnD;AAAA,QACD,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACD;AAAA,IACD;AAAA,GACA,CAAA;AAGD,EAAA,MAAA,CAAO,OAAA,CAAQ,OAAA,CAAQ,WAAA,CAAY,CAAC,CAAA,KAAM;AACzC,IAAA,IAAI,CAAA,CAAE,QAAQ,UAAA,EAAY;AACzB,MAAA,cAAA,GAAiB,IAAA;AACjB,MAAA,YAAA,GAAe,IAAA;AAAA,IAChB;AAAA,EACD,CAAC,CAAA;AAED,EAAA,OAAO,cAAA;AACR;AAMO,SAAS,iBAAA,GAA0B;AACzC,EAAA,cAAA,GAAiB,IAAA;AACjB,EAAA,YAAA,GAAe,IAAA;AAChB","file":"index.js","sourcesContent":["import { createORPCClient, onError } from \"@orpc/client\";\nimport { RPCLink } from \"@orpc/client/fetch\";\nimport type { ApiRouterClient } from \"./types\";\n\n/**\n * Configuration for creating a Vreko API client\n *\n * Better Auth supports three authentication methods:\n * 1. API Key (X-API-Key header) - for CLI/scripts\n * 2. Bearer Token (Authorization header) - for VS Code extension\n * 3. Session Cookies (automatic) - for web/browser\n */\nexport interface ClientConfig {\n\t/** Base URL of the API server */\n\tbaseUrl: string;\n\n\t/** Optional API key for authentication (sets X-API-Key header) */\n\tapiKey?: string;\n\n\t/** Optional access token for Bearer auth (sets Authorization header) */\n\taccessToken?: string;\n\n\t/** Custom headers to include with every request */\n\theaders?: Record<string, string>;\n\n\t/** Custom fetch implementation (for testing or special environments) */\n\tfetch?: typeof fetch;\n\n\t/** Error handler callback */\n\tonError?: (error: Error) => void;\n}\n\n/**\n * Create a Vreko API client with Better Auth integration.\n *\n * All requests flow through Better Auth middleware which validates:\n * - X-API-Key headers (for CLI/Node)\n * - Authorization Bearer tokens (for VS Code)\n * - Session cookies (for browser)\n *\n * @param config - Client configuration\n * @returns Fully typed API client\n *\n * @example\n * ```typescript\n * const client = createVrekoClient({\n * baseUrl: 'https://api.vreko.dev',\n * apiKey: 'sk_...'\n * });\n *\n * const metrics = await client.dashboard.getMetrics();\n * ```\n */\nexport function createVrekoClient(config: ClientConfig): ApiRouterClient {\n\tconst link = new RPCLink({\n\t\turl: `${config.baseUrl}/api/rpc`,\n\t\tfetch: config.fetch,\n\t\theaders: async () => {\n\t\t\tconst headers: Record<string, string> = {\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...config.headers,\n\t\t\t};\n\n\t\t\t// Better Auth Authentication Priority:\n\t\t\t// 1. API Key (for CLI/scripts) - most explicit\n\t\t\tif (config.apiKey) {\n\t\t\t\theaders[\"X-API-Key\"] = config.apiKey;\n\t\t\t}\n\t\t\t// 2. Bearer Token (for VS Code extension)\n\t\t\telse if (config.accessToken) {\n\t\t\t\theaders.Authorization = `Bearer ${config.accessToken}`;\n\t\t\t}\n\t\t\t// 3. Session cookies handled automatically by browser\n\n\t\t\treturn headers;\n\t\t},\n\t\tinterceptors: [\n\t\t\tonError((error) => {\n\t\t\t\t// Skip abort errors (user cancelled)\n\t\t\t\tif (error instanceof Error && error.name === \"AbortError\") {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Call custom error handler if provided\n\t\t\t\tconfig.onError?.(error instanceof Error ? error : new Error(String(error)));\n\n\t\t\t\t// Log to console in development\n\t\t\t\tif (process.env.NODE_ENV === \"development\") {\n\t\t\t\t\t// intentionally empty\n\t\t\t\t}\n\t\t\t}),\n\t\t],\n\t});\n\n\treturn createORPCClient(link) as ApiRouterClient;\n}\n","/**\n * Browser/Web adapter for Vreko API client.\n *\n * Better Auth Integration:\n * - Uses session cookies (automatic via credentials: 'include')\n * - No explicit token needed - Better Auth validates cookies\n * - CORS credentials enabled for cross-subdomain requests\n */\n\nimport { createVrekoClient } from \"../client\";\nimport type { ApiRouterClient } from \"../types\";\n\nexport interface BrowserClientConfig {\n\t/** Base URL (defaults to NEXT_PUBLIC_API_URL or window.location.origin) */\n\tbaseUrl?: string;\n\n\t/** Custom headers */\n\theaders?: Record<string, string>;\n}\n\n/**\n * Create a browser-optimized API client.\n *\n * Automatically handles:\n * - Cookie-based authentication via Better Auth session cookies\n * - CORS credentials for cross-subdomain requests\n * - Environment detection for base URL\n *\n * @example\n * ```typescript\n * import { createBrowserClient } from '@vreko/api-client/browser';\n *\n * const client = createBrowserClient();\n * const metrics = await client.dashboard.getMetrics();\n * ```\n */\nexport function createBrowserClient(config: BrowserClientConfig = {}): ApiRouterClient {\n\tconst baseUrl = config.baseUrl || getDefaultBaseUrl();\n\n\t// Custom fetch that includes credentials for Better Auth cookies\n\tconst fetchWithCredentials: typeof fetch = (input, init) => {\n\t\treturn fetch(input, {\n\t\t\t...init,\n\t\t\tcredentials: \"include\", // Critical for Better Auth session cookies\n\t\t});\n\t};\n\n\treturn createVrekoClient({\n\t\tbaseUrl,\n\t\theaders: config.headers,\n\t\tfetch: fetchWithCredentials,\n\t\t// No apiKey or accessToken - browser uses cookies\n\t});\n}\n\nfunction getDefaultBaseUrl(): string {\n\t// Server-side (Next.js)\n\tif (typeof window === \"undefined\") {\n\t\treturn process.env.NEXT_PUBLIC_API_URL || \"http://localhost:3001\";\n\t}\n\n\t// Client-side\n\tif (process.env.NEXT_PUBLIC_API_URL) {\n\t\treturn process.env.NEXT_PUBLIC_API_URL;\n\t}\n\n\t// Development fallback\n\tif (process.env.NODE_ENV === \"development\") {\n\t\treturn \"http://localhost:3001\";\n\t}\n\n\t// Production - use same origin\n\treturn window.location.origin;\n}\n","/**\n * Node.js/CLI adapter for Vreko API client.\n *\n * Better Auth Integration:\n * - Uses X-API-Key header for authentication\n * - Fallback to Bearer token if access token provided\n * - Environment variable support (VREKO_API_KEY)\n */\n\nimport { createVrekoClient } from \"../client\";\nimport type { ApiRouterClient } from \"../types\";\n\nexport interface NodeClientConfig {\n\t/** Base URL of the API server */\n\tbaseUrl?: string;\n\n\t/** API key for authentication (sent as X-API-Key header) */\n\tapiKey?: string;\n\n\t/** Access token (alternative to API key, sent as Bearer token) */\n\taccessToken?: string;\n}\n\n/**\n * Create a Node.js-optimized API client.\n *\n * Automatically handles:\n * - API key authentication via X-API-Key header (Better Auth validates)\n * - Bearer token authentication (fallback)\n * - Environment variable fallbacks (VREKO_API_KEY, VREKO_API_URL)\n *\n * @example\n * ```typescript\n * import { createNodeClient } from '@vreko/api-client/node';\n *\n * // Using environment variables\n * const client = createNodeClient();\n *\n * // Or explicit configuration\n * const client = createNodeClient({\n * baseUrl: 'https://api.vreko.dev',\n * apiKey: 'sk_...'\n * });\n *\n * const result = await client.signals.comprehensive({ files: [...] });\n * ```\n */\nexport function createNodeClient(config: NodeClientConfig = {}): ApiRouterClient {\n\tconst baseUrl = config.baseUrl || process.env.VREKO_API_URL || \"https://api.vreko.dev\";\n\tconst apiKey = config.apiKey || process.env.VREKO_API_KEY;\n\tconst accessToken = config.accessToken || process.env.VREKO_ACCESS_TOKEN;\n\n\tif (!apiKey && !accessToken) {\n\t\t// intentionally empty\n\t}\n\n\treturn createVrekoClient({\n\t\tbaseUrl,\n\t\tapiKey,\n\t\taccessToken,\n\t});\n}\n","/**\n * VS Code Extension adapter for Vreko API client.\n *\n * Better Auth Integration:\n * - Uses Bearer token from VS Code SecretStorage\n * - Automatic token refresh on expiration\n * - Secure credential management\n */\n\nimport { createVrekoClient } from \"../client\";\nimport type { ApiRouterClient } from \"../types\";\n\n// Re-export types for consumers importing from @vreko/api-client/vscode\nexport type { ApiRouterClient } from \"../types\";\n\nexport interface VSCodeClientConfig {\n\t/** VS Code extension context */\n\tcontext: {\n\t\tsecrets: {\n\t\t\tget(key: string): PromiseLike<string | undefined>;\n\t\t\tonDidChange(listener: (e: { key: string }) => void): { dispose(): void };\n\t\t};\n\t};\n\n\t/** Key in SecretStorage for access token (default: 'vreko.apiKey') */\n\tsecretsKey?: string;\n\n\t/** Base URL override */\n\tbaseUrl?: string;\n}\n\n// Singleton instance per workspace\nlet clientInstance: ApiRouterClient | null = null;\nlet currentToken: string | null = null;\n\n/**\n * Create a VS Code extension-optimized API client.\n *\n * Features:\n * - Retrieves credentials from VS Code SecretStorage\n * - Caches client instance for performance\n * - Automatically refreshes on credential change\n *\n * @example\n * ```typescript\n * import { createVSCodeClient } from '@vreko/api-client/vscode';\n *\n * // In your extension's activate function\n * export function activate(context: vscode.ExtensionContext) {\n * const client = await createVSCodeClient({ context });\n *\n * // Use the client\n * const metrics = await client.dashboard.getMetrics();\n * }\n * ```\n */\nexport async function createVSCodeClient(config: VSCodeClientConfig): Promise<ApiRouterClient> {\n\tconst secretsKey = config.secretsKey || \"vreko.apiKey\";\n\n\t// Use workspace configuration for base URL if available\n\tconst baseUrl = config.baseUrl || \"https://api.vreko.dev\";\n\n\t// Get token from SecretStorage\n\tconst token = await config.context.secrets.get(secretsKey);\n\n\t// Return cached instance if token hasn't changed\n\tif (clientInstance && token === currentToken) {\n\t\treturn clientInstance;\n\t}\n\n\t// Create new client\n\tcurrentToken = token || null;\n\tclientInstance = createVrekoClient({\n\t\tbaseUrl,\n\t\taccessToken: token,\n\t\tonError: async (error) => {\n\t\t\t// Handle session expiration\n\t\t\tif (error.message.includes(\"401\") || error.message.includes(\"403\")) {\n\t\t\t\t// Dynamic import to avoid bundling vscode in published package\n\t\t\t\ttry {\n\t\t\t\t\tconst vscode = await import(\"vscode\");\n\t\t\t\t\tconst selection = await vscode.window.showWarningMessage(\n\t\t\t\t\t\t\"Vreko session expired. Please reconnect your account.\",\n\t\t\t\t\t\t\"Reconnect\",\n\t\t\t\t\t);\n\t\t\t\t\tif (selection === \"Reconnect\") {\n\t\t\t\t\t\tawait vscode.commands.executeCommand(\"vreko.login\");\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t/* intentionally empty */\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t});\n\n\t// Listen for credential changes\n\tconfig.context.secrets.onDidChange((e) => {\n\t\tif (e.key === secretsKey) {\n\t\t\tclientInstance = null; // Force recreation on next call\n\t\t\tcurrentToken = null;\n\t\t}\n\t});\n\n\treturn clientInstance;\n}\n\n/**\n * Clear the cached client instance.\n * Call this when the user logs out.\n */\nexport function clearVSCodeClient(): void {\n\tclientInstance = null;\n\tcurrentToken = null;\n}\n"]}
@@ -0,0 +1,26 @@
1
+ import { RouterClient } from '@orpc/server';
2
+ import { router } from '@vreko/api/orpc/router';
3
+
4
+ /**
5
+ * Type exports from the API package.
6
+ *
7
+ * These are re-exported to allow consumers to import types
8
+ * without depending directly on @vreko/api.
9
+ *
10
+ * Better Auth Integration:
11
+ * - All requests authenticated via Better Auth middleware
12
+ * - Supports: JWT (Bearer), API keys (X-API-Key), Session cookies
13
+ */
14
+
15
+ /**
16
+ * Fully typed API client interface.
17
+ * Provides autocomplete and type checking for all API endpoints.
18
+ *
19
+ * All endpoints protected by Better Auth's `protectedProcedure` which validates:
20
+ * - Authorization: Bearer <token> (VS Code, JWT)
21
+ * - X-API-Key: <key> (CLI, API keys)
22
+ * - Session cookies (Web, browser)
23
+ */
24
+ type ApiRouterClient = RouterClient<typeof router>;
25
+
26
+ export type { ApiRouterClient as A };
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@vreko/api-client",
3
+ "version": "1.0.0",
4
+ "description": "Unified type-safe API client for all Vreko applications with Better Auth integration",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "import": "./dist/index.js"
10
+ },
11
+ "./browser": {
12
+ "types": "./dist/adapters/browser.d.ts",
13
+ "import": "./dist/adapters/browser.js"
14
+ },
15
+ "./node": {
16
+ "types": "./dist/adapters/node.d.ts",
17
+ "import": "./dist/adapters/node.js"
18
+ },
19
+ "./vscode": {
20
+ "types": "./dist/adapters/vscode.d.ts",
21
+ "import": "./dist/adapters/vscode.js"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "dependencies": {
28
+ "@orpc/client": "1.13.14",
29
+ "@orpc/server": "1.13.14"
30
+ },
31
+ "peerDependencies": {
32
+ "typescript": "5.9.2"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "24.5.1",
36
+ "@types/vscode": "1.99.0",
37
+ "tsup": "8.5.0",
38
+ "typescript": "5.9.2",
39
+ "vitest": "3.2.6",
40
+ "@vreko/api": "3.0.0"
41
+ },
42
+ "keywords": [
43
+ "vreko",
44
+ "api-client",
45
+ "orpc",
46
+ "better-auth",
47
+ "type-safe"
48
+ ],
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "https://github.com/yourusername/vreko.git",
52
+ "directory": "packages/api-client"
53
+ },
54
+ "license": "MIT",
55
+ "scripts": {
56
+ "build": "tsup",
57
+ "build:docker": "tsup --no-dts",
58
+ "dev": "tsup --watch",
59
+ "test": "vitest",
60
+ "test:watch": "vitest --watch",
61
+ "type-check": "tsc --noEmit"
62
+ }
63
+ }