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