@oneclient/sdk 0.1.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/dist/index.js ADDED
@@ -0,0 +1,648 @@
1
+ import { aiRunRequestSchema, analyticsEventSchema, apiErrorSchema, createOrganizationRequestSchema, createPreviewEnvironmentRequestSchema, createPreviewEnvironmentResponseSchema, createDeploymentRequestSchema, createProjectRequestSchema, createProjectResponseSchema, dataQueryResponseSchema, deploymentSchema, domainSchema, emailSendRequestSchema, organizationSchema, projectSchema, queryAstSchema, walletSummarySchema, } from "@oneclient/contracts";
2
+ function idempotencyRequestOptions(options) {
3
+ return options?.idempotencyKey ? { headers: { "Idempotency-Key": options.idempotencyKey } } : {};
4
+ }
5
+ export class OneClientError extends Error {
6
+ code;
7
+ requestId;
8
+ status;
9
+ details;
10
+ constructor(code, message, requestId, status, details) {
11
+ super(message);
12
+ this.code = code;
13
+ this.requestId = requestId;
14
+ this.status = status;
15
+ this.details = details;
16
+ this.name = "OneClientError";
17
+ }
18
+ }
19
+ export class OneClient {
20
+ baseUrl;
21
+ fetcher;
22
+ baseHeaders;
23
+ organizationId;
24
+ auth = {
25
+ sendMagicLink: (input, options) => this.request("/v1/auth/sign-in/magic-link", {
26
+ method: "POST",
27
+ body: input,
28
+ idempotent: true,
29
+ ...idempotencyRequestOptions(options),
30
+ }),
31
+ sendOtp: (input, options) => this.request("/v1/auth/email-otp/send-verification-otp", {
32
+ method: "POST",
33
+ body: { type: "sign-in", ...input },
34
+ idempotent: true,
35
+ ...idempotencyRequestOptions(options),
36
+ }),
37
+ verifyOtp: (input, options) => this.request("/v1/auth/sign-in/email-otp", {
38
+ method: "POST",
39
+ body: input,
40
+ idempotent: true,
41
+ ...idempotencyRequestOptions(options),
42
+ }),
43
+ getSession: async () => {
44
+ const session = await this.request("/v1/auth/get-session");
45
+ if (!session?.needsRefresh)
46
+ return session;
47
+ return this.request("/v1/auth/get-session", {
48
+ method: "POST",
49
+ idempotent: true,
50
+ });
51
+ },
52
+ signOut: (options) => this.request("/v1/auth/sign-out", {
53
+ method: "POST",
54
+ idempotent: true,
55
+ ...idempotencyRequestOptions(options),
56
+ }),
57
+ };
58
+ account = {
59
+ me: () => this.request("/v1/me"),
60
+ };
61
+ organizations = {
62
+ list: async () => {
63
+ const response = await this.request("/v1/organizations");
64
+ return organizationSchema.array().parse(response.organizations);
65
+ },
66
+ create: async (input) => {
67
+ const response = await this.request("/v1/organizations", {
68
+ method: "POST",
69
+ body: createOrganizationRequestSchema.parse(input),
70
+ idempotent: true,
71
+ });
72
+ return organizationSchema.parse(response.organization);
73
+ },
74
+ update: (organizationId, input) => this.request(`/v1/organizations/${encodeURIComponent(organizationId)}`, { method: "PATCH", body: input, idempotent: true }),
75
+ members: (organizationId) => this.request(`/v1/organizations/${encodeURIComponent(organizationId)}/members`),
76
+ updateMember: (organizationId, memberId, role) => this.request(`/v1/organizations/${encodeURIComponent(organizationId)}/members/${encodeURIComponent(memberId)}`, { method: "PATCH", body: { role }, idempotent: true }),
77
+ removeMember: (organizationId, memberId) => this.request(`/v1/organizations/${encodeURIComponent(organizationId)}/members/${encodeURIComponent(memberId)}`, { method: "DELETE", idempotent: true }),
78
+ invitations: (organizationId) => this.request(`/v1/organizations/${encodeURIComponent(organizationId)}/invitations`),
79
+ invite: (organizationId, email, role) => this.request(`/v1/organizations/${encodeURIComponent(organizationId)}/invitations`, { method: "POST", body: { email, role }, idempotent: true }),
80
+ cancelInvitation: (organizationId, invitationId) => this.request(`/v1/organizations/${encodeURIComponent(organizationId)}/invitations/${encodeURIComponent(invitationId)}`, { method: "DELETE", idempotent: true }),
81
+ acceptInvitation: (invitationId) => this.request(`/v1/invitations/${encodeURIComponent(invitationId)}/accept`, { method: "POST" }),
82
+ };
83
+ projects = {
84
+ list: async () => {
85
+ const organizationId = this.requireOrganizationId();
86
+ const value = await this.request(`/v1/projects?organizationId=${encodeURIComponent(organizationId)}`);
87
+ return projectSchema.array().parse(value.projects);
88
+ },
89
+ create: async (input) => {
90
+ const body = createProjectRequestSchema.parse(input);
91
+ return createProjectResponseSchema.parse(await this.request("/v1/projects", { method: "POST", body, idempotent: true }));
92
+ },
93
+ get: async (projectId) => projectSchema.parse(await this.request(`/v1/projects/${encodeURIComponent(projectId)}`)),
94
+ createPreview: async (projectId, input) => {
95
+ const body = createPreviewEnvironmentRequestSchema.parse(input);
96
+ return createPreviewEnvironmentResponseSchema.parse(await this.request(`/v1/projects/${encodeURIComponent(projectId)}/preview-environments`, {
97
+ method: "POST",
98
+ body,
99
+ idempotent: true,
100
+ }));
101
+ },
102
+ deletePreview: (environmentId) => this.request(`/v1/environments/${encodeURIComponent(environmentId)}`, {
103
+ method: "DELETE",
104
+ idempotent: true,
105
+ }),
106
+ upgrade: (environmentId) => this.request(`/v1/environments/${encodeURIComponent(environmentId)}/upgrade`, { method: "POST", idempotent: true }),
107
+ retryProvisioning: (environmentId) => this.request(`/v1/environments/${encodeURIComponent(environmentId)}/retry-provisioning`, { method: "POST", idempotent: true }),
108
+ cleanupOrphans: (environmentId) => this.request(`/v1/environments/${encodeURIComponent(environmentId)}/cleanup-orphans`, { method: "POST", idempotent: true }),
109
+ };
110
+ authOrigins = {
111
+ list: (environmentId) => this.request(`/v1/environments/${encodeURIComponent(environmentId)}/auth/origins`),
112
+ create: (environmentId, origin) => this.request(`/v1/environments/${encodeURIComponent(environmentId)}/auth/origins`, { method: "POST", body: { origin } }),
113
+ delete: (environmentId, originId) => this.request(`/v1/environments/${encodeURIComponent(environmentId)}/auth/origins/${encodeURIComponent(originId)}`, { method: "DELETE" }),
114
+ };
115
+ data = {
116
+ publishPolicy: (table, policy) => this.request("/v1/data/policies", {
117
+ method: "POST",
118
+ body: { table, policy },
119
+ idempotent: true,
120
+ }),
121
+ };
122
+ sql = {
123
+ execute: (input) => this.request("/v1/sql", {
124
+ method: "POST",
125
+ body: input,
126
+ idempotent: true,
127
+ }),
128
+ };
129
+ credentials = {
130
+ list: (environmentId) => this.request(`/v1/environments/${encodeURIComponent(environmentId)}/keys`),
131
+ create: (environmentId, input) => this.request(`/v1/environments/${encodeURIComponent(environmentId)}/keys`, {
132
+ method: "POST",
133
+ body: input,
134
+ idempotent: true,
135
+ }),
136
+ revoke: (environmentId, keyId) => this.request(`/v1/environments/${encodeURIComponent(environmentId)}/keys/${encodeURIComponent(keyId)}`, { method: "DELETE" }),
137
+ };
138
+ secrets = {
139
+ list: (environmentId) => this.request(`/v1/environments/${encodeURIComponent(environmentId)}/secrets`),
140
+ put: (environmentId, name, value) => this.request(`/v1/environments/${encodeURIComponent(environmentId)}/secrets/${encodeURIComponent(name)}`, { method: "PUT", body: { value }, idempotent: true }),
141
+ delete: (environmentId, name) => this.request(`/v1/environments/${encodeURIComponent(environmentId)}/secrets/${encodeURIComponent(name)}`, { method: "DELETE" }),
142
+ };
143
+ integrations = {
144
+ github: {
145
+ setup: (organizationId) => this.request("/v1/integrations/github/setup", { method: "POST", body: { organizationId }, idempotent: true }),
146
+ installations: (organizationId) => this.request(`/v1/integrations/github/installations?organizationId=${encodeURIComponent(organizationId)}`),
147
+ repositories: (organizationId, installationId) => this.request(`/v1/integrations/github/repositories?organizationId=${encodeURIComponent(organizationId)}&installationId=${encodeURIComponent(installationId)}`),
148
+ links: (organizationId) => this.request(`/v1/integrations/github/links?organizationId=${encodeURIComponent(organizationId)}`),
149
+ link: (input) => this.request("/v1/integrations/github/links", { method: "POST", body: input, idempotent: true }),
150
+ unlink: (linkId) => this.request(`/v1/integrations/github/links/${encodeURIComponent(linkId)}`, { method: "DELETE", idempotent: true }),
151
+ },
152
+ };
153
+ deployments = {
154
+ list: async (environmentId) => {
155
+ const response = await this.request(`/v1/deployments?environmentId=${encodeURIComponent(environmentId)}`);
156
+ return deploymentSchema.array().parse(response.deployments);
157
+ },
158
+ get: async (deploymentId) => deploymentSchema.parse(await this.request(`/v1/deployments/${encodeURIComponent(deploymentId)}`)),
159
+ create: (input) => this.request("/v1/deployments", {
160
+ method: "POST",
161
+ body: createDeploymentRequestSchema.parse(input),
162
+ idempotent: true,
163
+ }),
164
+ upload: (deploymentId, archive, input) => this.request(`/v1/deployments/${encodeURIComponent(deploymentId)}/artifact`, {
165
+ method: "PUT",
166
+ rawBody: archive,
167
+ headers: {
168
+ "Content-Type": "application/x-tar",
169
+ "Content-Length": String(input.contentLength),
170
+ "X-Artifact-SHA256": input.artifactDigest,
171
+ },
172
+ idempotent: true,
173
+ }),
174
+ logs: async (deploymentId) => (await this.rawRequest(`/v1/deployments/${encodeURIComponent(deploymentId)}/logs`)).text(),
175
+ promote: (deploymentId) => this.request(`/v1/deployments/${encodeURIComponent(deploymentId)}/promote`, { method: "POST", idempotent: true }),
176
+ };
177
+ deployTokens = {
178
+ create: (input) => this.request("/v1/deploy-tokens", {
179
+ method: "POST",
180
+ body: input,
181
+ idempotent: true,
182
+ }),
183
+ };
184
+ retentionExports = {
185
+ create: (environmentId) => this.request(`/v1/environments/${encodeURIComponent(environmentId)}/retention-exports`, { method: "POST", idempotent: true }),
186
+ get: (sessionId) => this.request(`/v1/retention-exports/${encodeURIComponent(sessionId)}`),
187
+ prepareD1: (sessionId) => this.request(`/v1/retention-exports/${encodeURIComponent(sessionId)}/components/d1`, { method: "POST", idempotent: true }),
188
+ download: (sessionId, component) => this.rawRequest(`/v1/retention-exports/${encodeURIComponent(sessionId)}/components/${component}/download`, { method: "POST", idempotent: true }),
189
+ };
190
+ billing = {
191
+ subscriptionCheckout: () => {
192
+ const organizationId = this.requireOrganizationId();
193
+ return this.request("/v1/billing/subscription-checkout", {
194
+ method: "POST",
195
+ body: { organizationId },
196
+ idempotent: true,
197
+ });
198
+ },
199
+ topupCheckout: (amountMicros) => {
200
+ const organizationId = this.requireOrganizationId();
201
+ return this.request("/v1/billing/topup-checkout", {
202
+ method: "POST",
203
+ body: { organizationId, amountMicros },
204
+ idempotent: true,
205
+ });
206
+ },
207
+ portal: () => {
208
+ const organizationId = this.requireOrganizationId();
209
+ return this.request("/v1/billing/portal", {
210
+ method: "POST",
211
+ body: { organizationId },
212
+ idempotent: true,
213
+ });
214
+ },
215
+ };
216
+ registrar = {
217
+ quote: (domainName) => {
218
+ const organizationId = this.requireOrganizationId();
219
+ return this.request("/v1/registrar/quotes", {
220
+ method: "POST",
221
+ body: { organizationId, domainName },
222
+ idempotent: true,
223
+ });
224
+ },
225
+ checkout: (input) => {
226
+ const organizationId = this.requireOrganizationId();
227
+ return this.request("/v1/registrar/checkout", { method: "POST", body: { organizationId, ...input }, idempotent: true });
228
+ },
229
+ orders: () => {
230
+ const organizationId = this.requireOrganizationId();
231
+ return this.request(`/v1/registrar/orders?organizationId=${encodeURIComponent(organizationId)}`);
232
+ },
233
+ registration: (domainName) => {
234
+ const organizationId = this.requireOrganizationId();
235
+ return this.request(`/v1/registrar/registrations/${encodeURIComponent(domainName)}?organizationId=${encodeURIComponent(organizationId)}`);
236
+ },
237
+ };
238
+ storage = {
239
+ get: (bucket, key) => this.rawRequest(`/v1/storage/${encodeURIComponent(bucket)}/${encodePath(key)}`),
240
+ put: (bucket, key, body, contentType = "application/octet-stream") => this.rawRequest(`/v1/storage/${encodeURIComponent(bucket)}/${encodePath(key)}`, {
241
+ method: "PUT",
242
+ rawBody: body,
243
+ idempotent: true,
244
+ headers: { "Content-Type": contentType },
245
+ }),
246
+ delete: (bucket, key) => this.rawRequest(`/v1/storage/${encodeURIComponent(bucket)}/${encodePath(key)}`, {
247
+ method: "DELETE",
248
+ idempotent: true,
249
+ }),
250
+ signedUrl: (input) => this.request("/v1/storage/signed-url", {
251
+ method: "POST",
252
+ body: input,
253
+ idempotent: true,
254
+ }),
255
+ };
256
+ s3 = {
257
+ list: (bucket, options = {}) => {
258
+ const query = queryString({
259
+ prefix: options.prefix,
260
+ delimiter: options.delimiter,
261
+ "continuation-token": options.continuationToken,
262
+ "max-keys": options.maxKeys,
263
+ });
264
+ return this.request(`/v1/s3/${encodeURIComponent(bucket)}${query ? `?${query}` : ""}`, { idempotent: true, ...idempotencyRequestOptions(options) });
265
+ },
266
+ get: (bucket, key, options = {}) => this.rawRequest(`/v1/s3/${encodeURIComponent(bucket)}/${encodePath(key)}`, {
267
+ idempotent: true,
268
+ headers: {
269
+ ...(options.range ? { Range: options.range } : {}),
270
+ ...(options.idempotencyKey ? { "Idempotency-Key": options.idempotencyKey } : {}),
271
+ },
272
+ }),
273
+ head: async (bucket, key, options = {}) => {
274
+ const response = await this.rawRequest(`/v1/s3/${encodeURIComponent(bucket)}/${encodePath(key)}`, {
275
+ method: "HEAD",
276
+ idempotent: true,
277
+ ...idempotencyRequestOptions(options),
278
+ });
279
+ return {
280
+ etag: response.headers.get("ETag") ?? "",
281
+ contentLength: Number(response.headers.get("Content-Length") ?? "0"),
282
+ lastModified: response.headers.get("Last-Modified") ?? "",
283
+ storageClass: response.headers.get("X-OneClient-Storage-Class") ?? "",
284
+ contentType: response.headers.get("Content-Type"),
285
+ };
286
+ },
287
+ put: (bucket, key, body, options = {}) => this.request(`/v1/s3/${encodeURIComponent(bucket)}/${encodePath(key)}`, {
288
+ method: "PUT",
289
+ rawBody: body,
290
+ idempotent: true,
291
+ headers: {
292
+ "Content-Type": options.contentType ?? "application/octet-stream",
293
+ "Content-Length": String(resolveBodyLength(body, options.contentLength)),
294
+ ...(options.idempotencyKey ? { "Idempotency-Key": options.idempotencyKey } : {}),
295
+ },
296
+ }),
297
+ delete: (bucket, key, options = {}) => this.request(`/v1/s3/${encodeURIComponent(bucket)}/${encodePath(key)}`, {
298
+ method: "DELETE",
299
+ idempotent: true,
300
+ ...idempotencyRequestOptions(options),
301
+ }),
302
+ initiateMultipart: (bucket, key, options = {}) => this.request(`/v1/s3/${encodeURIComponent(bucket)}/${encodePath(key)}?uploads=`, {
303
+ method: "POST",
304
+ idempotent: true,
305
+ headers: {
306
+ ...(options.contentType ? { "Content-Type": options.contentType } : {}),
307
+ ...(options.idempotencyKey ? { "Idempotency-Key": options.idempotencyKey } : {}),
308
+ },
309
+ }),
310
+ uploadPart: (bucket, key, uploadId, partNumber, body, options = {}) => this.request(`/v1/s3/${encodeURIComponent(bucket)}/${encodePath(key)}?${queryString({ uploadId, partNumber })}`, {
311
+ method: "PUT",
312
+ rawBody: body,
313
+ idempotent: true,
314
+ headers: {
315
+ "Content-Type": options.contentType ?? "application/octet-stream",
316
+ "Content-Length": String(resolveBodyLength(body, options.contentLength)),
317
+ ...(options.idempotencyKey ? { "Idempotency-Key": options.idempotencyKey } : {}),
318
+ },
319
+ }),
320
+ completeMultipart: (bucket, key, uploadId, parts, options = {}) => this.request(`/v1/s3/${encodeURIComponent(bucket)}/${encodePath(key)}?${queryString({ uploadId })}`, {
321
+ method: "POST",
322
+ body: { parts: parts.map((part) => ({ ...part })) },
323
+ idempotent: true,
324
+ ...idempotencyRequestOptions(options),
325
+ }),
326
+ abortMultipart: (bucket, key, uploadId, options = {}) => this.request(`/v1/s3/${encodeURIComponent(bucket)}/${encodePath(key)}?${queryString({ uploadId })}`, {
327
+ method: "DELETE",
328
+ idempotent: true,
329
+ ...idempotencyRequestOptions(options),
330
+ }),
331
+ };
332
+ kv = {
333
+ get: (key) => this.request(`/v1/kv/${encodeURIComponent(key)}`),
334
+ put: (key, value, expirationTtl) => this.request(`/v1/kv/${encodeURIComponent(key)}`, {
335
+ method: "PUT",
336
+ body: { value, expirationTtl },
337
+ idempotent: true,
338
+ }),
339
+ delete: (key) => this.request(`/v1/kv/${encodeURIComponent(key)}`, {
340
+ method: "DELETE",
341
+ idempotent: true,
342
+ }),
343
+ };
344
+ jobs = {
345
+ enqueue: (queue, payload, delaySeconds = 0) => this.request(`/v1/jobs/${encodeURIComponent(queue)}`, {
346
+ method: "POST",
347
+ body: { payload, delaySeconds },
348
+ idempotent: true,
349
+ }),
350
+ list: () => this.request("/v1/jobs"),
351
+ deadLetter: () => this.request("/v1/jobs/dead-letter"),
352
+ retry: (jobId) => this.request(`/v1/jobs/${encodeURIComponent(jobId)}/retry`, { method: "POST", idempotent: true }),
353
+ schedules: () => this.request("/v1/jobs/schedules"),
354
+ schedule: (input) => this.request("/v1/jobs/schedules", {
355
+ method: "POST",
356
+ body: input,
357
+ idempotent: true,
358
+ }),
359
+ deleteSchedule: (scheduleId) => this.request(`/v1/jobs/schedules/${encodeURIComponent(scheduleId)}`, {
360
+ method: "DELETE",
361
+ idempotent: true,
362
+ }),
363
+ };
364
+ email = {
365
+ send: (input) => this.request("/v1/email/send", {
366
+ method: "POST",
367
+ body: emailSendRequestSchema.parse(input),
368
+ idempotent: true,
369
+ }),
370
+ developmentInbox: () => this.request("/v1/email/development-inbox"),
371
+ templates: () => this.request("/v1/email/templates"),
372
+ saveTemplate: (input) => this.request("/v1/email/templates", {
373
+ method: "POST",
374
+ body: input,
375
+ idempotent: true,
376
+ }),
377
+ deleteTemplate: (templateId) => this.request(`/v1/email/templates/${encodeURIComponent(templateId)}`, {
378
+ method: "DELETE",
379
+ idempotent: true,
380
+ }),
381
+ logs: () => this.request("/v1/email/logs"),
382
+ suppressions: () => this.request("/v1/email/suppressions"),
383
+ suppress: (email, reason) => this.request("/v1/email/suppressions", {
384
+ method: "POST",
385
+ body: { email, reason },
386
+ idempotent: true,
387
+ }),
388
+ unsuppress: (addressHash) => this.request(`/v1/email/suppressions/${encodeURIComponent(addressHash)}`, {
389
+ method: "DELETE",
390
+ idempotent: true,
391
+ }),
392
+ webhooks: () => this.request("/v1/email/webhooks"),
393
+ createWebhook: (url, events = ["email.*"]) => this.request("/v1/email/webhooks", {
394
+ method: "POST",
395
+ body: { url, events },
396
+ idempotent: true,
397
+ }),
398
+ deleteWebhook: (endpointId) => this.request(`/v1/email/webhooks/${encodeURIComponent(endpointId)}`, {
399
+ method: "DELETE",
400
+ idempotent: true,
401
+ }),
402
+ };
403
+ ai = {
404
+ models: () => this.request("/v1/ai/models"),
405
+ run: (input) => this.request("/v1/ai/run", {
406
+ method: "POST",
407
+ body: aiRunRequestSchema.parse(input),
408
+ idempotent: true,
409
+ }),
410
+ connections: () => this.request("/v1/ai/connections"),
411
+ connect: (input) => this.request("/v1/ai/connections", {
412
+ method: "POST",
413
+ body: input,
414
+ idempotent: true,
415
+ }),
416
+ disconnect: (connectionId) => this.request(`/v1/ai/connections/${encodeURIComponent(connectionId)}`, {
417
+ method: "DELETE",
418
+ idempotent: true,
419
+ }),
420
+ };
421
+ analytics = {
422
+ track: (events) => this.request("/v1/analytics/events", {
423
+ method: "POST",
424
+ body: { events: events.map((event) => analyticsEventSchema.parse(event)) },
425
+ idempotent: true,
426
+ }),
427
+ timeseries: (input = {}) => this.request(`/v1/analytics/timeseries?${queryString(input)}`),
428
+ users: (input = {}) => this.request(`/v1/analytics/users?${queryString(input)}`),
429
+ sessions: (input = {}) => this.request(`/v1/analytics/sessions?${queryString(input)}`),
430
+ export: (input) => this.request("/v1/analytics/exports", {
431
+ method: "POST",
432
+ body: input,
433
+ idempotent: true,
434
+ }),
435
+ downloadExport: (exportId) => this.rawRequest(`/v1/analytics/exports/${encodeURIComponent(exportId)}`),
436
+ funnel: (input) => this.request("/v1/analytics/funnels", { method: "POST", body: input }),
437
+ retention: (input) => this.request("/v1/analytics/retention", { method: "POST", body: input }),
438
+ };
439
+ domains = {
440
+ list: async () => {
441
+ const organizationId = this.requireOrganizationId();
442
+ const value = await this.request(`/v1/domains?organizationId=${encodeURIComponent(organizationId)}`);
443
+ return domainSchema.array().parse(value.domains);
444
+ },
445
+ add: async (input) => domainSchema.parse(await this.request("/v1/domains", {
446
+ method: "POST",
447
+ body: input,
448
+ idempotent: true,
449
+ })),
450
+ refresh: (domainId) => this.request(`/v1/domains/${encodeURIComponent(domainId)}/refresh`, {
451
+ method: "POST",
452
+ idempotent: true,
453
+ }),
454
+ remove: (domainId) => this.request(`/v1/domains/${encodeURIComponent(domainId)}`, {
455
+ method: "DELETE",
456
+ idempotent: true,
457
+ }),
458
+ };
459
+ usage = {
460
+ summary: async () => {
461
+ const organizationId = this.requireOrganizationId();
462
+ return walletSummarySchema.parse(await this.request(`/v1/usage?organizationId=${encodeURIComponent(organizationId)}`));
463
+ },
464
+ timeseries: (days = 14) => {
465
+ const organizationId = this.requireOrganizationId();
466
+ return this.request(`/v1/usage/timeseries?organizationId=${encodeURIComponent(organizationId)}&days=${encodeURIComponent(String(days))}`);
467
+ },
468
+ activity: (limit = 20) => {
469
+ const organizationId = this.requireOrganizationId();
470
+ return this.request(`/v1/activity?organizationId=${encodeURIComponent(organizationId)}&limit=${encodeURIComponent(String(limit))}`);
471
+ },
472
+ };
473
+ constructor(config) {
474
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
475
+ this.organizationId = config.organizationId;
476
+ this.fetcher = config.fetch ?? globalThis.fetch.bind(globalThis);
477
+ this.baseHeaders = { Accept: "application/json", ...config.headers };
478
+ if (config.publishableKey)
479
+ this.baseHeaders["X-OneClient-Key"] = config.publishableKey;
480
+ if (config.serverKey)
481
+ this.baseHeaders.Authorization = `Bearer ${config.serverKey}`;
482
+ if (config.deployToken)
483
+ this.baseHeaders.Authorization = `Bearer ${config.deployToken}`;
484
+ if (!config.publishableKey && !config.serverKey && !config.deployToken && !config.session) {
485
+ throw new TypeError("OneClient requires a publishableKey, serverKey, deployToken, or session mode");
486
+ }
487
+ }
488
+ from(table) {
489
+ return new DataQueryBuilder(this, table);
490
+ }
491
+ requireOrganizationId() {
492
+ if (!this.organizationId)
493
+ throw new TypeError("This operation requires organizationId in OneClientConfig");
494
+ return this.organizationId;
495
+ }
496
+ async executeQuery(query) {
497
+ return dataQueryResponseSchema.parse(await this.request("/v1/data/query", {
498
+ method: "POST",
499
+ body: { query: queryAstSchema.parse(query) },
500
+ }));
501
+ }
502
+ async request(path, options = {}) {
503
+ const response = await this.rawRequest(path, options);
504
+ if (response.status === 204)
505
+ return undefined;
506
+ return (await response.json());
507
+ }
508
+ async rawRequest(path, options = {}) {
509
+ const headers = new Headers({ ...this.baseHeaders, ...options.headers });
510
+ if (options.idempotent && !headers.has("Idempotency-Key")) {
511
+ headers.set("Idempotency-Key", `idem_${crypto.randomUUID()}`);
512
+ }
513
+ let body = options.rawBody;
514
+ if (options.body !== undefined) {
515
+ headers.set("Content-Type", "application/json");
516
+ body = JSON.stringify(options.body);
517
+ }
518
+ const response = await this.fetcher(`${this.baseUrl}${path}`, {
519
+ method: options.method ?? "GET",
520
+ headers,
521
+ ...(body === undefined ? {} : { body }),
522
+ credentials: "include",
523
+ });
524
+ if (!response.ok) {
525
+ let payload;
526
+ try {
527
+ payload = await response.json();
528
+ }
529
+ catch {
530
+ payload = undefined;
531
+ }
532
+ const parsed = apiErrorSchema.safeParse(payload);
533
+ if (parsed.success) {
534
+ throw new OneClientError(parsed.data.error.code, parsed.data.error.message, parsed.data.error.requestId, response.status, parsed.data.error.details);
535
+ }
536
+ throw new OneClientError("INTERNAL_ERROR", `OneClient request failed with status ${response.status}`, response.headers.get("X-Request-Id") ?? "unknown", response.status);
537
+ }
538
+ return response;
539
+ }
540
+ }
541
+ function queryString(input) {
542
+ const search = new URLSearchParams();
543
+ for (const [key, value] of Object.entries(input))
544
+ if (value !== undefined)
545
+ search.set(key, String(value));
546
+ return search.toString();
547
+ }
548
+ function resolveBodyLength(body, supplied) {
549
+ if (supplied !== undefined) {
550
+ if (!Number.isSafeInteger(supplied) || supplied < 0)
551
+ throw new TypeError("contentLength must be a non-negative safe integer");
552
+ return supplied;
553
+ }
554
+ if (typeof body === "string")
555
+ return new TextEncoder().encode(body).byteLength;
556
+ if (body instanceof ArrayBuffer)
557
+ return body.byteLength;
558
+ if (ArrayBuffer.isView(body))
559
+ return body.byteLength;
560
+ if (typeof Blob !== "undefined" && body instanceof Blob)
561
+ return body.size;
562
+ if (typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams)
563
+ return new TextEncoder().encode(body.toString()).byteLength;
564
+ throw new TypeError("contentLength is required for streamed S3 request bodies");
565
+ }
566
+ export class DataQueryBuilder {
567
+ client;
568
+ query;
569
+ constructor(client, table, query) {
570
+ this.client = client;
571
+ this.query = query ?? {
572
+ table,
573
+ select: ["id"],
574
+ filters: [],
575
+ orderBy: [],
576
+ limit: 100,
577
+ offset: 0,
578
+ };
579
+ }
580
+ select(...fields) {
581
+ return this.with({ select: fields });
582
+ }
583
+ eq(field, value) {
584
+ return this.filter(field, "eq", value);
585
+ }
586
+ in(field, values) {
587
+ return this.filter(field, "in", values);
588
+ }
589
+ filter(field, op, value) {
590
+ return this.with({
591
+ filters: [...this.query.filters, value === undefined ? { field, op } : { field, op, value }],
592
+ });
593
+ }
594
+ order(field, direction = "asc") {
595
+ return this.with({ orderBy: [...this.query.orderBy, { field, direction }] });
596
+ }
597
+ limit(limit) {
598
+ return this.with({ limit });
599
+ }
600
+ range(offset, limit) {
601
+ return this.with({ offset, limit });
602
+ }
603
+ execute() {
604
+ return this.client.executeQuery(this.query);
605
+ }
606
+ insert(record, maxStorageDeltaBytes) {
607
+ return this.client.request("/v1/data/insert", {
608
+ method: "POST",
609
+ body: { table: this.query.table, record, maxStorageDeltaBytes },
610
+ idempotent: true,
611
+ });
612
+ }
613
+ update(values, options) {
614
+ return this.client.request("/v1/data/update", {
615
+ method: "PATCH",
616
+ body: { table: this.query.table, values, filters: this.query.filters, ...options },
617
+ idempotent: true,
618
+ });
619
+ }
620
+ delete(maxRows) {
621
+ return this.client.request("/v1/data/delete", {
622
+ method: "DELETE",
623
+ body: { table: this.query.table, filters: this.query.filters, maxRows },
624
+ idempotent: true,
625
+ });
626
+ }
627
+ toJSON() {
628
+ return structuredClone(this.query);
629
+ }
630
+ with(patch) {
631
+ return new DataQueryBuilder(this.client, this.query.table, { ...this.query, ...patch });
632
+ }
633
+ }
634
+ function encodePath(value) {
635
+ return value.split("/").map(encodeURIComponent).join("/");
636
+ }
637
+ export function createClient(config) {
638
+ return new OneClient(config);
639
+ }
640
+ export function createServerClient(env, config = {}) {
641
+ if (!env.ONECLIENT_API_URL || !env.ONECLIENT_SERVER_KEY)
642
+ throw new TypeError("Managed OneClient runtime bindings are unavailable");
643
+ return new OneClient({
644
+ ...config,
645
+ baseUrl: env.ONECLIENT_API_URL,
646
+ serverKey: env.ONECLIENT_SERVER_KEY,
647
+ });
648
+ }