@buildspacestudio/sdk 0.2.2 → 0.4.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.
Files changed (106) hide show
  1. package/README.md +126 -0
  2. package/dist/auth/index.cjs +259 -0
  3. package/dist/auth/index.cjs.map +1 -0
  4. package/dist/auth/index.d.cts +3 -0
  5. package/dist/auth/index.d.ts +3 -5
  6. package/dist/auth/index.js +255 -2
  7. package/dist/auth/index.js.map +1 -1
  8. package/dist/billing/index.cjs +226 -0
  9. package/dist/billing/index.cjs.map +1 -0
  10. package/dist/billing/index.d.cts +60 -0
  11. package/dist/billing/index.d.ts +60 -0
  12. package/dist/billing/index.js +222 -0
  13. package/dist/billing/index.js.map +1 -0
  14. package/dist/client/index.cjs +558 -0
  15. package/dist/client/index.cjs.map +1 -0
  16. package/dist/client/index.d.cts +89 -0
  17. package/dist/client/index.d.ts +12 -7
  18. package/dist/client/index.js +546 -105
  19. package/dist/client/index.js.map +1 -1
  20. package/dist/client-BYUWUiGZ.d.cts +143 -0
  21. package/dist/{auth/client.d.ts → client-ByNR5EZz.d.ts} +7 -5
  22. package/dist/client-D0vypxWb.d.cts +58 -0
  23. package/dist/{auth/client.js → client-D7bqvGJv.d.cts} +27 -30
  24. package/dist/{events/client.d.ts → client-DbGRRMt7.d.ts} +5 -3
  25. package/dist/client-d7kX5WfR.d.ts +143 -0
  26. package/dist/events/index.cjs +131 -0
  27. package/dist/events/index.cjs.map +1 -0
  28. package/dist/events/{server.d.ts → index.d.cts} +7 -4
  29. package/dist/events/index.d.ts +59 -4
  30. package/dist/events/index.js +127 -2
  31. package/dist/events/index.js.map +1 -1
  32. package/dist/http-D2gXpNpr.d.cts +100 -0
  33. package/dist/http-D2gXpNpr.d.ts +100 -0
  34. package/dist/index.cjs +1029 -0
  35. package/dist/index.cjs.map +1 -0
  36. package/dist/index.d.cts +92 -0
  37. package/dist/index.d.ts +21 -15
  38. package/dist/index.js +1010 -106
  39. package/dist/index.js.map +1 -1
  40. package/dist/next/index.cjs +183 -0
  41. package/dist/next/index.cjs.map +1 -0
  42. package/dist/next/index.d.cts +164 -0
  43. package/dist/next/index.d.ts +164 -0
  44. package/dist/next/index.js +172 -0
  45. package/dist/next/index.js.map +1 -0
  46. package/dist/notifications/index.cjs +56 -0
  47. package/dist/notifications/index.cjs.map +1 -0
  48. package/dist/notifications/{server.d.ts → index.d.cts} +8 -6
  49. package/dist/notifications/index.d.ts +79 -3
  50. package/dist/notifications/index.js +53 -1
  51. package/dist/notifications/index.js.map +1 -1
  52. package/dist/react/index.cjs +120 -0
  53. package/dist/react/index.cjs.map +1 -0
  54. package/dist/react/index.d.cts +567 -0
  55. package/dist/react/index.d.ts +567 -0
  56. package/dist/react/index.js +92 -0
  57. package/dist/react/index.js.map +1 -0
  58. package/dist/server-CoPDzSUP.d.cts +117 -0
  59. package/dist/{auth/server.d.ts → server-Suq3tZZC.d.ts} +8 -6
  60. package/dist/storage/index.cjs +213 -0
  61. package/dist/storage/index.cjs.map +1 -0
  62. package/dist/storage/index.d.cts +195 -0
  63. package/dist/storage/index.d.ts +195 -5
  64. package/dist/storage/index.js +209 -2
  65. package/dist/storage/index.js.map +1 -1
  66. package/package.json +124 -16
  67. package/dist/auth/client.d.ts.map +0 -1
  68. package/dist/auth/client.js.map +0 -1
  69. package/dist/auth/index.d.ts.map +0 -1
  70. package/dist/auth/server.d.ts.map +0 -1
  71. package/dist/auth/server.js +0 -148
  72. package/dist/auth/server.js.map +0 -1
  73. package/dist/client/index.d.ts.map +0 -1
  74. package/dist/config.d.ts +0 -40
  75. package/dist/config.d.ts.map +0 -1
  76. package/dist/config.js +0 -27
  77. package/dist/config.js.map +0 -1
  78. package/dist/errors.d.ts +0 -31
  79. package/dist/errors.d.ts.map +0 -1
  80. package/dist/errors.js +0 -30
  81. package/dist/errors.js.map +0 -1
  82. package/dist/events/client.d.ts.map +0 -1
  83. package/dist/events/client.js +0 -97
  84. package/dist/events/client.js.map +0 -1
  85. package/dist/events/index.d.ts.map +0 -1
  86. package/dist/events/server.d.ts.map +0 -1
  87. package/dist/events/server.js +0 -65
  88. package/dist/events/server.js.map +0 -1
  89. package/dist/http.d.ts +0 -39
  90. package/dist/http.d.ts.map +0 -1
  91. package/dist/http.js +0 -74
  92. package/dist/http.js.map +0 -1
  93. package/dist/index.d.ts.map +0 -1
  94. package/dist/notifications/index.d.ts.map +0 -1
  95. package/dist/notifications/server.d.ts.map +0 -1
  96. package/dist/notifications/server.js +0 -73
  97. package/dist/notifications/server.js.map +0 -1
  98. package/dist/storage/client.d.ts +0 -91
  99. package/dist/storage/client.d.ts.map +0 -1
  100. package/dist/storage/client.js +0 -117
  101. package/dist/storage/client.js.map +0 -1
  102. package/dist/storage/index.d.ts.map +0 -1
  103. package/dist/storage/server.d.ts +0 -104
  104. package/dist/storage/server.d.ts.map +0 -1
  105. package/dist/storage/server.js +0 -104
  106. package/dist/storage/server.js.map +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1,1029 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ // src/auth/client.ts
6
+ var AuthClientNamespace = class {
7
+ transport;
8
+ constructor(transport) {
9
+ this.transport = transport;
10
+ }
11
+ /**
12
+ * Build a URL that redirects the user to the Buildspace sign-in page.
13
+ *
14
+ * After the user authenticates, they are redirected back to `redirectUri`
15
+ * with a `?code=` parameter that can be exchanged for tokens via
16
+ * `buildspace.auth.handleCallback()` on the server.
17
+ *
18
+ * @param opts - Sign-in URL options.
19
+ * @returns The full sign-in URL as a string.
20
+ */
21
+ getSignInUrl(opts) {
22
+ const url = new URL("/sign-in", this.transport.loginUrl);
23
+ if (opts.appSlug) {
24
+ url.searchParams.set("app", opts.appSlug);
25
+ }
26
+ url.searchParams.set("redirect_uri", opts.redirectUri);
27
+ url.searchParams.set("client_id", this.transport.key);
28
+ if (opts.env) {
29
+ url.searchParams.set("env", opts.env);
30
+ }
31
+ return url.toString();
32
+ }
33
+ /**
34
+ * Build a URL that redirects the user to the Buildspace sign-up page.
35
+ *
36
+ * Works identically to {@link getSignInUrl} but directs the user to the
37
+ * registration flow instead.
38
+ *
39
+ * @param opts - Sign-up URL options.
40
+ * @returns The full sign-up URL as a string.
41
+ */
42
+ getSignUpUrl(opts) {
43
+ const url = new URL("/sign-up", this.transport.loginUrl);
44
+ if (opts.appSlug) {
45
+ url.searchParams.set("app", opts.appSlug);
46
+ }
47
+ url.searchParams.set("redirect_uri", opts.redirectUri);
48
+ url.searchParams.set("client_id", this.transport.key);
49
+ if (opts.env) {
50
+ url.searchParams.set("env", opts.env);
51
+ }
52
+ return url.toString();
53
+ }
54
+ };
55
+
56
+ // src/errors.ts
57
+ var BuildspaceError = class extends Error {
58
+ /** Machine-readable error code, e.g. `"auth/invalid-token"`. */
59
+ code;
60
+ /** Which service produced the error. */
61
+ service;
62
+ /** HTTP status code from the API. */
63
+ status;
64
+ constructor({
65
+ code,
66
+ message,
67
+ service,
68
+ status
69
+ }) {
70
+ super(message);
71
+ this.name = "BuildspaceError";
72
+ this.code = code;
73
+ this.service = service;
74
+ this.status = status;
75
+ }
76
+ };
77
+
78
+ // src/auth/server.ts
79
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1", "0.0.0.0"]);
80
+ var FORWARDED_HOST_RE = /host="?([^;"]+)"?/i;
81
+ var FORWARDED_PROTO_RE = /proto="?([^;"]+)"?/i;
82
+ function getFirstForwardedValue(value) {
83
+ if (!value) {
84
+ return null;
85
+ }
86
+ return value.split(",").map((part) => part.trim()).find(Boolean) ?? null;
87
+ }
88
+ function stripPort(host) {
89
+ if (host.startsWith("[") && host.includes("]")) {
90
+ return host.slice(1, host.indexOf("]"));
91
+ }
92
+ const colonIndex = host.indexOf(":");
93
+ return colonIndex >= 0 ? host.slice(0, colonIndex) : host;
94
+ }
95
+ function isPrivateIpv4(hostname) {
96
+ const parts = hostname.split(".").map((part) => Number(part));
97
+ if (parts.length !== 4 || parts.some((part) => Number.isNaN(part) || part < 0 || part > 255)) {
98
+ return false;
99
+ }
100
+ return parts[0] === 10 || parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31 || parts[0] === 192 && parts[1] === 168;
101
+ }
102
+ function isInternalHostname(hostname) {
103
+ const normalized = hostname.toLowerCase();
104
+ return LOOPBACK_HOSTS.has(normalized) || normalized.endsWith(".local") || normalized.endsWith(".internal") || isPrivateIpv4(normalized);
105
+ }
106
+ function getForwardedOrigin(request) {
107
+ const forwarded = getFirstForwardedValue(request.headers.get("forwarded"));
108
+ if (forwarded) {
109
+ const forwardedHost2 = forwarded.match(FORWARDED_HOST_RE)?.[1]?.trim();
110
+ const forwardedProto2 = forwarded.match(FORWARDED_PROTO_RE)?.[1]?.trim();
111
+ if (forwardedHost2 && forwardedProto2) {
112
+ return `${forwardedProto2}://${forwardedHost2}`;
113
+ }
114
+ }
115
+ const forwardedHost = getFirstForwardedValue(request.headers.get("x-forwarded-host"));
116
+ const forwardedProto = getFirstForwardedValue(request.headers.get("x-forwarded-proto"));
117
+ if (forwardedHost && forwardedProto) {
118
+ return `${forwardedProto}://${forwardedHost}`;
119
+ }
120
+ return null;
121
+ }
122
+ function resolveDefaultRedirectUri(request, url) {
123
+ if (!(request instanceof Request)) {
124
+ return `${url.origin}${url.pathname}`;
125
+ }
126
+ const forwardedOrigin = getForwardedOrigin(request);
127
+ if (forwardedOrigin) {
128
+ return `${forwardedOrigin}${url.pathname}`;
129
+ }
130
+ const hostHeader = request.headers.get("host")?.trim();
131
+ if (hostHeader && !isInternalHostname(stripPort(hostHeader))) {
132
+ return `${url.protocol}//${hostHeader}${url.pathname}`;
133
+ }
134
+ if (!isInternalHostname(url.hostname)) {
135
+ return `${url.origin}${url.pathname}`;
136
+ }
137
+ return `${url.origin}${url.pathname}`;
138
+ }
139
+ var AuthServerNamespace = class {
140
+ transport;
141
+ constructor(transport) {
142
+ this.transport = transport;
143
+ }
144
+ /**
145
+ * Retrieve the session associated with a token.
146
+ *
147
+ * Returns the {@link AuthSession} if valid, or `null` if the token is
148
+ * expired, revoked, or invalid (401/404).
149
+ *
150
+ * @throws {BuildspaceError} On unexpected server errors (5xx, network issues).
151
+ */
152
+ async getSession(sessionToken) {
153
+ try {
154
+ return await this.transport.request({
155
+ service: "auth",
156
+ path: "/v1/auth/session",
157
+ headers: { "X-Session-Token": sessionToken }
158
+ });
159
+ } catch (error) {
160
+ if (error instanceof BuildspaceError && (error.status === 401 || error.status === 404)) {
161
+ return null;
162
+ }
163
+ throw error;
164
+ }
165
+ }
166
+ /**
167
+ * Exchange an OAuth authorization code for tokens.
168
+ *
169
+ * Extracts the `code` query parameter from the callback URL and exchanges
170
+ * it with the Buildspace API for an access token and user info.
171
+ *
172
+ * @param request - The incoming callback request. Accepts a `Request` object,
173
+ * a `URL`, or a raw URL string containing the `?code=` parameter.
174
+ * @param opts - Optional settings.
175
+ * @param opts.redirectUri - Override the redirect URI sent to the token endpoint.
176
+ * Defaults to the origin + pathname of the callback URL.
177
+ * @returns The token response containing `access_token`, `expires_in`, and `user`.
178
+ *
179
+ * @throws {BuildspaceError} If the code exchange fails (invalid code, expired, etc.).
180
+ *
181
+ * @example
182
+ * ```ts
183
+ * // Next.js Route Handler
184
+ * export async function GET(request: Request) {
185
+ * const { access_token, user } = await buildspace.auth.handleCallback(request);
186
+ * // Store access_token as a session cookie
187
+ * }
188
+ * ```
189
+ */
190
+ handleCallback(request, opts) {
191
+ let url;
192
+ if (typeof request === "string") {
193
+ url = new URL(request);
194
+ } else if (request instanceof URL) {
195
+ url = request;
196
+ } else {
197
+ url = new URL(request.url);
198
+ }
199
+ const code = url.searchParams.get("code");
200
+ if (!code) {
201
+ throw new BuildspaceError({
202
+ service: "auth",
203
+ status: 400,
204
+ code: "auth/missing-code",
205
+ message: "No auth code found in callback URL. Expected ?code= parameter."
206
+ });
207
+ }
208
+ const redirectUri = opts?.redirectUri ?? resolveDefaultRedirectUri(request, url);
209
+ return this.transport.request({
210
+ service: "auth",
211
+ path: "/v1/auth/token",
212
+ method: "POST",
213
+ body: {
214
+ code,
215
+ redirect_uri: redirectUri
216
+ }
217
+ });
218
+ }
219
+ /**
220
+ * Revoke a specific session token.
221
+ *
222
+ * @param sessionToken - The token to revoke.
223
+ * @throws {BuildspaceError} If the revocation fails.
224
+ */
225
+ async revokeSession(sessionToken) {
226
+ await this.transport.request({
227
+ service: "auth",
228
+ path: "/v1/auth/session",
229
+ method: "DELETE",
230
+ headers: { "X-Session-Token": sessionToken }
231
+ });
232
+ }
233
+ /**
234
+ * Sign the user out by revoking the session and clearing the SDK's stored token.
235
+ *
236
+ * If the session is already expired or not found, the error is silently
237
+ * ignored and the local session is still cleared.
238
+ *
239
+ * @param sessionToken - Token to revoke. If omitted, uses the token
240
+ * previously set via `buildspace.setSession()`.
241
+ */
242
+ async signOut(sessionToken) {
243
+ const token = sessionToken ?? this.transport.getSessionToken();
244
+ try {
245
+ if (token) {
246
+ await this.revokeSession(token);
247
+ }
248
+ } catch (error) {
249
+ if (!(error instanceof BuildspaceError && error.service === "auth" && (error.status === 401 || error.status === 404))) {
250
+ throw error;
251
+ }
252
+ } finally {
253
+ this.transport.clearSession();
254
+ }
255
+ }
256
+ };
257
+
258
+ // src/billing/shared.ts
259
+ function shouldShowTestBanner(status) {
260
+ return status.testMode;
261
+ }
262
+ function billingIdentityQuery(opts) {
263
+ return { app_user_id: opts?.appUserId, user_id: opts?.userId };
264
+ }
265
+ function checkoutRequestBody(opts) {
266
+ return {
267
+ app_user_id: "appUserId" in opts ? opts.appUserId : void 0,
268
+ cancel_url: opts.cancelUrl,
269
+ checkout_request_id: opts.checkoutRequestId,
270
+ lookup_key: opts.lookupKey,
271
+ metadata: opts.metadata,
272
+ price_id: opts.priceId,
273
+ quantity: opts.quantity,
274
+ success_url: opts.successUrl,
275
+ user_id: "userId" in opts ? opts.userId : void 0
276
+ };
277
+ }
278
+ function portalRequestBody(opts) {
279
+ return {
280
+ app_user_id: "appUserId" in opts ? opts.appUserId : void 0,
281
+ return_url: opts.returnUrl,
282
+ user_id: "userId" in opts ? opts.userId : void 0
283
+ };
284
+ }
285
+
286
+ // src/billing/client.ts
287
+ function redirectTo(url) {
288
+ const browser = globalThis;
289
+ if (!browser.window?.location) {
290
+ throw new Error("redirectToCheckout can only be used in a browser environment");
291
+ }
292
+ browser.window.location.href = url;
293
+ }
294
+ var BillingClientNamespace = class {
295
+ transport;
296
+ constructor(transport) {
297
+ this.transport = transport;
298
+ }
299
+ /**
300
+ * Read whether billing is enabled for the app environment tied to this
301
+ * publishable key, and whether the connected Stripe account is in test or
302
+ * live mode.
303
+ *
304
+ * Render a "Test mode" banner in your app whenever `testMode` is true.
305
+ */
306
+ getStatus() {
307
+ return this.transport.request({
308
+ service: "billing",
309
+ path: "/v1/billing/status"
310
+ });
311
+ }
312
+ /**
313
+ * List the active billing products for the app environment tied to this
314
+ * publishable key.
315
+ */
316
+ listProducts() {
317
+ return this.transport.request({
318
+ service: "billing",
319
+ path: "/v1/billing/products"
320
+ });
321
+ }
322
+ /**
323
+ * List the active billing prices for the app environment tied to this
324
+ * publishable key.
325
+ */
326
+ listPrices() {
327
+ return this.transport.request({
328
+ service: "billing",
329
+ path: "/v1/billing/prices"
330
+ });
331
+ }
332
+ /**
333
+ * Create a Checkout Session for the signed-in browser user and redirect to
334
+ * the Stripe-hosted Checkout page.
335
+ *
336
+ * This method depends on a Buildspace session being available through
337
+ * `setSession()` or your app's authenticated request context.
338
+ */
339
+ async redirectToCheckout(opts) {
340
+ const checkout = await this.transport.request({
341
+ service: "billing",
342
+ path: "/v1/billing/checkout",
343
+ method: "POST",
344
+ body: checkoutRequestBody(opts)
345
+ });
346
+ redirectTo(checkout.url);
347
+ }
348
+ /**
349
+ * Open the Stripe-hosted customer portal for the signed-in browser user.
350
+ */
351
+ async redirectToPortal(opts) {
352
+ const portal = await this.transport.request({
353
+ service: "billing",
354
+ path: "/v1/billing/portal",
355
+ method: "POST",
356
+ body: portalRequestBody(opts)
357
+ });
358
+ redirectTo(portal.url);
359
+ }
360
+ /**
361
+ * Discoverable alias for redirectToPortal — opens the Stripe-hosted customer
362
+ * portal so the signed-in user can manage their subscription, payment method,
363
+ * and invoices.
364
+ */
365
+ manageSubscription(opts) {
366
+ return this.redirectToPortal(opts);
367
+ }
368
+ /**
369
+ * Read the current subscription state for the signed-in browser user.
370
+ */
371
+ getSubscription() {
372
+ return this.transport.request({
373
+ service: "billing",
374
+ path: "/v1/billing/subscription"
375
+ });
376
+ }
377
+ /**
378
+ * Read the current paid entitlement state for the signed-in browser user.
379
+ */
380
+ getEntitlements() {
381
+ return this.transport.request({
382
+ service: "billing",
383
+ path: "/v1/billing/entitlements"
384
+ });
385
+ }
386
+ };
387
+
388
+ // src/billing/server.ts
389
+ var BillingServerNamespace = class {
390
+ transport;
391
+ constructor(transport) {
392
+ this.transport = transport;
393
+ }
394
+ /**
395
+ * Read whether billing is enabled for the app environment tied to this API
396
+ * key, and whether the connected Stripe account is in test or live mode.
397
+ *
398
+ * Render a "Test mode" banner in your app whenever `testMode` is true.
399
+ */
400
+ getStatus() {
401
+ return this.transport.request({
402
+ service: "billing",
403
+ path: "/v1/billing/status"
404
+ });
405
+ }
406
+ /**
407
+ * List the active billing products configured for the app environment tied to
408
+ * this API key.
409
+ */
410
+ listProducts() {
411
+ return this.transport.request({
412
+ service: "billing",
413
+ path: "/v1/billing/products"
414
+ });
415
+ }
416
+ /**
417
+ * List the active billing prices configured for the app environment tied to
418
+ * this API key.
419
+ */
420
+ listPrices() {
421
+ return this.transport.request({
422
+ service: "billing",
423
+ path: "/v1/billing/prices"
424
+ });
425
+ }
426
+ /**
427
+ * Create a Stripe Checkout Session on the creator's connected Stripe account.
428
+ *
429
+ * Use `userId` for Buildspace-authenticated users, or `appUserId` when your
430
+ * app uses its own auth system and you want Buildspace to track billing state
431
+ * against an app-defined user id.
432
+ */
433
+ createCheckout(opts) {
434
+ return this.transport.request({
435
+ service: "billing",
436
+ path: "/v1/billing/checkout",
437
+ method: "POST",
438
+ body: checkoutRequestBody(opts)
439
+ });
440
+ }
441
+ /**
442
+ * Create a Stripe-hosted customer portal session for the specified billing
443
+ * identity.
444
+ */
445
+ createPortalSession(opts) {
446
+ return this.transport.request({
447
+ service: "billing",
448
+ path: "/v1/billing/portal",
449
+ method: "POST",
450
+ body: portalRequestBody(opts)
451
+ });
452
+ }
453
+ /**
454
+ * Read the current subscription state for a Buildspace user or app-defined
455
+ * billing identity.
456
+ */
457
+ getSubscription(opts) {
458
+ return this.transport.request({
459
+ service: "billing",
460
+ path: "/v1/billing/subscription",
461
+ query: billingIdentityQuery(opts)
462
+ });
463
+ }
464
+ /**
465
+ * Read the current paid entitlement state for a Buildspace user or app-defined
466
+ * billing identity.
467
+ */
468
+ getEntitlements(opts) {
469
+ return this.transport.request({
470
+ service: "billing",
471
+ path: "/v1/billing/entitlements",
472
+ query: billingIdentityQuery(opts)
473
+ });
474
+ }
475
+ };
476
+
477
+ // src/config.ts
478
+ var DEFAULT_BASE_URL = "https://api.buildspace.studio";
479
+ var DEFAULT_LOGIN_URL = "https://login.buildspace.studio";
480
+ var DEFAULT_API_VERSION = "2025-06-01";
481
+ function resolveConfig(mode, config = {}) {
482
+ return {
483
+ mode,
484
+ baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,
485
+ loginUrl: config.loginUrl ?? DEFAULT_LOGIN_URL,
486
+ version: config.version ?? DEFAULT_API_VERSION,
487
+ fetch: config.fetch ?? fetch
488
+ };
489
+ }
490
+ function formatMode(mode) {
491
+ return mode === "server" ? "server SDK" : "client SDK";
492
+ }
493
+ function validateApiKey({ mode, key }) {
494
+ if (!key) {
495
+ throw new Error(`Missing API key. The ${formatMode(mode)} requires a valid Buildspace key.`);
496
+ }
497
+ if (mode === "server" && !key.startsWith("bs_sec_")) {
498
+ throw new Error(
499
+ "The server SDK requires a secret key (bs_sec_*). Use createClient() from '@buildspacestudio/sdk/client' for browser usage with publishable keys."
500
+ );
501
+ }
502
+ if (mode === "client" && !key.startsWith("bs_pub_")) {
503
+ throw new Error(
504
+ "The client SDK requires a publishable key (bs_pub_*). Use new Buildspace() from '@buildspacestudio/sdk' for server usage with secret keys."
505
+ );
506
+ }
507
+ }
508
+
509
+ // src/events/client.ts
510
+ var EventsClientNamespace = class {
511
+ queue = [];
512
+ transport;
513
+ timer = null;
514
+ constructor(transport, config = {}) {
515
+ this.transport = transport;
516
+ const flushInterval = config.flushInterval ?? 5e3;
517
+ this.maxBatchSize = config.maxBatchSize ?? 20;
518
+ this.timer = setInterval(() => {
519
+ this.flush().catch(() => {
520
+ });
521
+ }, flushInterval);
522
+ }
523
+ maxBatchSize;
524
+ /**
525
+ * Queue an event for batched delivery.
526
+ *
527
+ * This method is synchronous and returns immediately. Events are
528
+ * automatically flushed when the batch size is reached or on the
529
+ * configured interval.
530
+ *
531
+ * @param event - Event name, e.g. `"button.clicked"`.
532
+ * @param properties - Arbitrary key-value data to attach.
533
+ * @param actorId - Identifier of the user or entity that triggered the event.
534
+ */
535
+ track(event, properties, actorId) {
536
+ this.queue.push({
537
+ event,
538
+ properties,
539
+ actor_id: actorId,
540
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
541
+ });
542
+ if (this.queue.length >= this.maxBatchSize) {
543
+ this.flush().catch(() => {
544
+ });
545
+ }
546
+ }
547
+ /**
548
+ * Send all queued events to the API immediately.
549
+ *
550
+ * If the flush fails, events are re-queued for the next attempt.
551
+ */
552
+ async flush() {
553
+ if (this.queue.length === 0) {
554
+ return;
555
+ }
556
+ const batch = this.queue.splice(0, this.queue.length);
557
+ try {
558
+ await this.transport.request({
559
+ service: "events",
560
+ path: "/v1/events/batch",
561
+ method: "POST",
562
+ keepalive: true,
563
+ body: { events: batch }
564
+ });
565
+ } catch {
566
+ this.queue.unshift(...batch);
567
+ throw new Error("Failed to flush events batch.");
568
+ }
569
+ }
570
+ /**
571
+ * Stop the automatic flush timer and send any remaining events.
572
+ *
573
+ * Call this during app shutdown or cleanup to ensure no events are lost.
574
+ */
575
+ async shutdown() {
576
+ if (this.timer) {
577
+ clearInterval(this.timer);
578
+ this.timer = null;
579
+ }
580
+ await this.flush();
581
+ }
582
+ };
583
+
584
+ // src/events/server.ts
585
+ var EventsServerNamespace = class {
586
+ transport;
587
+ constructor(transport) {
588
+ this.transport = transport;
589
+ }
590
+ /**
591
+ * Track a single event.
592
+ *
593
+ * @param event - Event name, e.g. `"user.signed_up"`.
594
+ * @param properties - Arbitrary key-value data to attach to the event.
595
+ * @param actorId - Identifier of the user or entity that triggered the event.
596
+ * @returns The ID of the created event.
597
+ */
598
+ track(event, properties, actorId) {
599
+ return this.transport.request({
600
+ service: "events",
601
+ path: "/v1/events",
602
+ method: "POST",
603
+ body: {
604
+ event,
605
+ properties,
606
+ actor_id: actorId,
607
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
608
+ }
609
+ });
610
+ }
611
+ /**
612
+ * Track multiple events in a single request.
613
+ *
614
+ * Events without a `timestamp` are automatically timestamped.
615
+ *
616
+ * @param events - Array of events to track.
617
+ * @returns The count and IDs of created events.
618
+ */
619
+ batchTrack(events) {
620
+ return this.transport.request({
621
+ service: "events",
622
+ path: "/v1/events/batch",
623
+ method: "POST",
624
+ body: {
625
+ events: events.map((event) => ({
626
+ ...event,
627
+ timestamp: event.timestamp ?? (/* @__PURE__ */ new Date()).toISOString()
628
+ }))
629
+ }
630
+ });
631
+ }
632
+ };
633
+
634
+ // src/http.ts
635
+ var HttpTransport = class {
636
+ baseUrl;
637
+ fetcher;
638
+ key;
639
+ loginUrl;
640
+ mode;
641
+ version;
642
+ sessionToken = null;
643
+ constructor({ key, resolvedConfig }) {
644
+ validateApiKey({ mode: resolvedConfig.mode, key });
645
+ this.key = key;
646
+ this.mode = resolvedConfig.mode;
647
+ this.baseUrl = resolvedConfig.baseUrl;
648
+ this.loginUrl = resolvedConfig.loginUrl;
649
+ this.version = resolvedConfig.version;
650
+ this.fetcher = resolvedConfig.fetch;
651
+ }
652
+ /** Remove the stored session token. */
653
+ clearSession() {
654
+ this.sessionToken = null;
655
+ }
656
+ /** Return the current session token, or `null` if none is set. */
657
+ getSessionToken() {
658
+ return this.sessionToken;
659
+ }
660
+ /** Store a session token that will be sent as `X-Session-Token` on subsequent requests. */
661
+ setSession(sessionToken) {
662
+ this.sessionToken = sessionToken;
663
+ }
664
+ async request({
665
+ service,
666
+ path,
667
+ method = "GET",
668
+ query,
669
+ body,
670
+ headers,
671
+ keepalive
672
+ }) {
673
+ const url = new URL(path, this.baseUrl);
674
+ if (query) {
675
+ for (const [key, value] of Object.entries(query)) {
676
+ if (value !== void 0) {
677
+ url.searchParams.set(key, String(value));
678
+ }
679
+ }
680
+ }
681
+ const response = await this.fetcher(url.toString(), {
682
+ method,
683
+ keepalive,
684
+ headers: {
685
+ Authorization: `Bearer ${this.key}`,
686
+ "Content-Type": "application/json",
687
+ "X-Buildspace-Version": this.version,
688
+ ...this.sessionToken ? { "X-Session-Token": this.sessionToken } : {},
689
+ ...headers
690
+ },
691
+ body: body === void 0 ? void 0 : JSON.stringify(body)
692
+ });
693
+ if (!response.ok) {
694
+ const payload = await response.json().catch(() => null);
695
+ throw new BuildspaceError({
696
+ service,
697
+ status: response.status,
698
+ code: payload?.code ?? `${service}/http-${response.status}`,
699
+ message: payload?.error ?? payload?.message ?? response.statusText
700
+ });
701
+ }
702
+ if (response.status === 204) {
703
+ return void 0;
704
+ }
705
+ return response.json();
706
+ }
707
+ };
708
+
709
+ // src/notifications/server.ts
710
+ var NotificationsServerNamespace = class {
711
+ transport;
712
+ constructor(transport) {
713
+ this.transport = transport;
714
+ }
715
+ /**
716
+ * Send a custom email with inline HTML content.
717
+ *
718
+ * @param opts - Email content and recipient options.
719
+ * @returns The notification ID and optional provider message ID.
720
+ */
721
+ send(opts) {
722
+ return this.transport.request({
723
+ service: "notifications",
724
+ path: "/v1/notifications/send",
725
+ method: "POST",
726
+ body: {
727
+ to: opts.to,
728
+ subject: opts.subject,
729
+ html: opts.html,
730
+ text: opts.text,
731
+ reply_to: opts.replyTo,
732
+ metadata: opts.metadata
733
+ }
734
+ });
735
+ }
736
+ /**
737
+ * Send an email using a pre-configured template.
738
+ *
739
+ * Templates are created in the Buildspace Creator Studio.
740
+ *
741
+ * @param templateSlug - The slug of the template to use, e.g. `"welcome-email"`.
742
+ * @param opts - Recipient and template variable options.
743
+ * @returns The notification ID and optional provider message ID.
744
+ */
745
+ sendTemplate(templateSlug, opts) {
746
+ return this.transport.request({
747
+ service: "notifications",
748
+ path: "/v1/notifications/send-template",
749
+ method: "POST",
750
+ body: {
751
+ template: templateSlug,
752
+ to: opts.to,
753
+ variables: opts.variables,
754
+ metadata: opts.metadata
755
+ }
756
+ });
757
+ }
758
+ };
759
+
760
+ // src/storage/client.ts
761
+ var StorageClientNamespace = class {
762
+ transport;
763
+ constructor(transport) {
764
+ this.transport = transport;
765
+ }
766
+ /**
767
+ * Upload a `File` or `Blob` to Buildspace storage.
768
+ *
769
+ * This method handles the full upload flow:
770
+ * 1. Requests a pre-signed upload URL from the API
771
+ * 2. Uploads the file directly to the storage provider
772
+ * 3. Returns a signed download URL for the uploaded file
773
+ *
774
+ * @param file - The file or blob to upload.
775
+ * @param opts - Upload options including the storage path.
776
+ * @returns The storage key, file size, and a signed download URL.
777
+ *
778
+ * @throws {BuildspaceError} If the upload URL request or the direct upload fails.
779
+ */
780
+ async upload(file, opts) {
781
+ const contentType = opts.contentType ?? (file instanceof File ? file.type : "application/octet-stream");
782
+ const signed = await this.transport.request({
783
+ service: "storage",
784
+ path: "/v1/storage/upload",
785
+ method: "POST",
786
+ body: {
787
+ path: opts.path,
788
+ content_type: contentType,
789
+ size: file.size
790
+ }
791
+ });
792
+ const response = await this.transport.fetcher(signed.upload_url, {
793
+ method: "PUT",
794
+ headers: { "Content-Type": contentType },
795
+ body: file
796
+ });
797
+ if (!response.ok) {
798
+ throw new BuildspaceError({
799
+ service: "storage",
800
+ status: response.status,
801
+ code: "storage/upload-failed",
802
+ message: `Direct upload failed: ${response.statusText}`
803
+ });
804
+ }
805
+ const { url } = await this.getUrl(signed.key);
806
+ return {
807
+ key: signed.key,
808
+ size: file.size,
809
+ url
810
+ };
811
+ }
812
+ /**
813
+ * Get a time-limited signed URL for downloading a stored file.
814
+ *
815
+ * @param key - The storage key of the object.
816
+ * @param opts - Optional settings.
817
+ * @param opts.expiresIn - URL lifetime in seconds.
818
+ */
819
+ getUrl(key, opts) {
820
+ return this.transport.request({
821
+ service: "storage",
822
+ path: "/v1/storage/url",
823
+ query: {
824
+ key,
825
+ expires_in: opts?.expiresIn
826
+ }
827
+ });
828
+ }
829
+ /**
830
+ * List stored objects, optionally filtered by key prefix.
831
+ *
832
+ * @param prefix - Only return objects whose key starts with this prefix.
833
+ * @param opts - Pagination options.
834
+ */
835
+ list(prefix, opts) {
836
+ return this.transport.request({
837
+ service: "storage",
838
+ path: "/v1/storage/objects",
839
+ query: {
840
+ prefix,
841
+ limit: opts?.limit,
842
+ offset: opts?.offset
843
+ }
844
+ });
845
+ }
846
+ /**
847
+ * Delete a stored object by key.
848
+ *
849
+ * @param key - The storage key of the object to delete.
850
+ */
851
+ async delete(key) {
852
+ await this.transport.request({
853
+ service: "storage",
854
+ path: "/v1/storage/object",
855
+ method: "DELETE",
856
+ body: { key }
857
+ });
858
+ }
859
+ };
860
+
861
+ // src/storage/server.ts
862
+ var StorageServerNamespace = class {
863
+ transport;
864
+ constructor(transport) {
865
+ this.transport = transport;
866
+ }
867
+ /**
868
+ * Request a pre-signed URL for direct file upload.
869
+ *
870
+ * @param opts - Upload options including the storage key, content type, and file size.
871
+ * @returns The signed upload URL, the resolved key, and expiry time in seconds.
872
+ */
873
+ getUploadUrl(opts) {
874
+ return this.transport.request({
875
+ service: "storage",
876
+ path: "/v1/storage/upload",
877
+ method: "POST",
878
+ body: {
879
+ path: opts.key,
880
+ content_type: opts.contentType,
881
+ size: opts.size
882
+ }
883
+ });
884
+ }
885
+ /**
886
+ * Get a time-limited signed URL for downloading a stored file.
887
+ *
888
+ * @param key - The storage key of the object.
889
+ * @param opts - Optional settings.
890
+ * @param opts.expiresIn - URL lifetime in seconds. Uses server default if omitted.
891
+ */
892
+ getSignedUrl(key, opts) {
893
+ return this.transport.request({
894
+ service: "storage",
895
+ path: "/v1/storage/url",
896
+ query: {
897
+ key,
898
+ expires_in: opts?.expiresIn
899
+ }
900
+ });
901
+ }
902
+ /**
903
+ * List stored objects, optionally filtered by key prefix.
904
+ *
905
+ * @param prefix - Only return objects whose key starts with this prefix, e.g. `"avatars/"`.
906
+ * @param opts - Pagination options.
907
+ */
908
+ list(prefix, opts) {
909
+ return this.transport.request({
910
+ service: "storage",
911
+ path: "/v1/storage/objects",
912
+ query: {
913
+ prefix,
914
+ limit: opts?.limit,
915
+ offset: opts?.offset
916
+ }
917
+ });
918
+ }
919
+ /**
920
+ * Delete a stored object by key.
921
+ *
922
+ * @param key - The storage key of the object to delete.
923
+ */
924
+ async delete(key) {
925
+ await this.transport.request({
926
+ service: "storage",
927
+ path: "/v1/storage/object",
928
+ method: "DELETE",
929
+ body: { key }
930
+ });
931
+ }
932
+ /**
933
+ * Get current storage usage statistics for the app.
934
+ *
935
+ * @returns Byte counts and object count.
936
+ */
937
+ getUsage() {
938
+ return this.transport.request({
939
+ service: "storage",
940
+ path: "/v1/storage/usage"
941
+ });
942
+ }
943
+ };
944
+
945
+ // src/index.ts
946
+ var Buildspace = class {
947
+ transport;
948
+ _auth = null;
949
+ _billing = null;
950
+ _events = null;
951
+ _notifications = null;
952
+ _publicAuth = null;
953
+ _storage = null;
954
+ /**
955
+ * Create a new server SDK instance.
956
+ *
957
+ * @param secretKey - Your Buildspace secret key (starts with `bs_sec_`).
958
+ * @param config - Optional configuration overrides.
959
+ */
960
+ constructor(secretKey, config = {}) {
961
+ this.transport = new HttpTransport({
962
+ key: secretKey,
963
+ resolvedConfig: resolveConfig("server", config)
964
+ });
965
+ }
966
+ /** Server-side auth: session verification, OAuth callback handling, sign-out. */
967
+ get auth() {
968
+ this._auth ??= new AuthServerNamespace(this.transport);
969
+ return this._auth;
970
+ }
971
+ /**
972
+ * Client-style auth helpers available on the server (e.g. generating sign-in URLs
973
+ * in server-rendered pages). For full server auth, use {@link auth}.
974
+ */
975
+ get authClient() {
976
+ this._publicAuth ??= new AuthClientNamespace(this.transport);
977
+ return this._publicAuth;
978
+ }
979
+ /** Server-side event tracking. */
980
+ get events() {
981
+ this._events ??= new EventsServerNamespace(this.transport);
982
+ return this._events;
983
+ }
984
+ /** Server-side billing: Checkout, Portal, subscriptions, and entitlements. */
985
+ get billing() {
986
+ this._billing ??= new BillingServerNamespace(this.transport);
987
+ return this._billing;
988
+ }
989
+ /** Server-side file storage: upload URLs, signed downloads, listing, deletion. */
990
+ get storage() {
991
+ this._storage ??= new StorageServerNamespace(this.transport);
992
+ return this._storage;
993
+ }
994
+ /** Server-side transactional email notifications. */
995
+ get notifications() {
996
+ this._notifications ??= new NotificationsServerNamespace(this.transport);
997
+ return this._notifications;
998
+ }
999
+ /** Clear the stored session token. */
1000
+ clearSession() {
1001
+ this.transport.clearSession();
1002
+ }
1003
+ /**
1004
+ * Set a session token that will be sent as `X-Session-Token` on all
1005
+ * subsequent API requests.
1006
+ *
1007
+ * @param sessionToken - The session token to attach to requests.
1008
+ */
1009
+ setSession(sessionToken) {
1010
+ this.transport.setSession(sessionToken);
1011
+ }
1012
+ };
1013
+ var src_default = Buildspace;
1014
+
1015
+ exports.AuthClientNamespace = AuthClientNamespace;
1016
+ exports.AuthServerNamespace = AuthServerNamespace;
1017
+ exports.BillingClientNamespace = BillingClientNamespace;
1018
+ exports.BillingServerNamespace = BillingServerNamespace;
1019
+ exports.Buildspace = Buildspace;
1020
+ exports.BuildspaceError = BuildspaceError;
1021
+ exports.EventsClientNamespace = EventsClientNamespace;
1022
+ exports.EventsServerNamespace = EventsServerNamespace;
1023
+ exports.NotificationsServerNamespace = NotificationsServerNamespace;
1024
+ exports.StorageClientNamespace = StorageClientNamespace;
1025
+ exports.StorageServerNamespace = StorageServerNamespace;
1026
+ exports.default = src_default;
1027
+ exports.shouldShowTestBanner = shouldShowTestBanner;
1028
+ //# sourceMappingURL=index.cjs.map
1029
+ //# sourceMappingURL=index.cjs.map