@buildspacestudio/sdk 0.3.0 → 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 (54) hide show
  1. package/README.md +126 -0
  2. package/dist/auth/index.cjs.map +1 -1
  3. package/dist/auth/index.d.cts +3 -118
  4. package/dist/auth/index.d.ts +3 -118
  5. package/dist/auth/index.js.map +1 -1
  6. package/dist/billing/index.cjs +226 -0
  7. package/dist/billing/index.cjs.map +1 -0
  8. package/dist/billing/index.d.cts +60 -0
  9. package/dist/billing/index.d.ts +60 -0
  10. package/dist/billing/index.js +222 -0
  11. package/dist/billing/index.js.map +1 -0
  12. package/dist/client/index.cjs +130 -0
  13. package/dist/client/index.cjs.map +1 -1
  14. package/dist/client/index.d.cts +7 -3
  15. package/dist/client/index.d.ts +7 -3
  16. package/dist/client/index.js +130 -0
  17. package/dist/client/index.js.map +1 -1
  18. package/dist/client-BYUWUiGZ.d.cts +143 -0
  19. package/dist/{client-BH7LbrKM.d.ts → client-ByNR5EZz.d.ts} +1 -1
  20. package/dist/{client-C67hy1kt.d.cts → client-D0vypxWb.d.cts} +1 -1
  21. package/dist/{client-DqWXAwCr.d.cts → client-D7bqvGJv.d.cts} +1 -1
  22. package/dist/{client-Dlif1JBf.d.ts → client-DbGRRMt7.d.ts} +1 -1
  23. package/dist/client-d7kX5WfR.d.ts +143 -0
  24. package/dist/events/index.d.cts +2 -2
  25. package/dist/events/index.d.ts +2 -2
  26. package/dist/{http-U-zzKmFF.d.cts → http-D2gXpNpr.d.cts} +2 -2
  27. package/dist/{http-U-zzKmFF.d.ts → http-D2gXpNpr.d.ts} +2 -2
  28. package/dist/index.cjs +228 -0
  29. package/dist/index.cjs.map +1 -1
  30. package/dist/index.d.cts +13 -8
  31. package/dist/index.d.ts +13 -8
  32. package/dist/index.js +226 -1
  33. package/dist/index.js.map +1 -1
  34. package/dist/next/index.cjs +183 -0
  35. package/dist/next/index.cjs.map +1 -0
  36. package/dist/next/index.d.cts +164 -0
  37. package/dist/next/index.d.ts +164 -0
  38. package/dist/next/index.js +172 -0
  39. package/dist/next/index.js.map +1 -0
  40. package/dist/notifications/index.d.cts +1 -1
  41. package/dist/notifications/index.d.ts +1 -1
  42. package/dist/react/index.cjs +120 -0
  43. package/dist/react/index.cjs.map +1 -0
  44. package/dist/react/index.d.cts +567 -0
  45. package/dist/react/index.d.ts +567 -0
  46. package/dist/react/index.js +92 -0
  47. package/dist/react/index.js.map +1 -0
  48. package/dist/server-CoPDzSUP.d.cts +117 -0
  49. package/dist/server-Suq3tZZC.d.ts +117 -0
  50. package/dist/storage/index.cjs.map +1 -1
  51. package/dist/storage/index.d.cts +1 -1
  52. package/dist/storage/index.d.ts +1 -1
  53. package/dist/storage/index.js.map +1 -1
  54. package/package.json +51 -2
@@ -0,0 +1,172 @@
1
+ // src/errors.ts
2
+ var BuildspaceError = class extends Error {
3
+ /** Machine-readable error code, e.g. `"auth/invalid-token"`. */
4
+ code;
5
+ /** Which service produced the error. */
6
+ service;
7
+ /** HTTP status code from the API. */
8
+ status;
9
+ constructor({
10
+ code,
11
+ message,
12
+ service,
13
+ status
14
+ }) {
15
+ super(message);
16
+ this.name = "BuildspaceError";
17
+ this.code = code;
18
+ this.service = service;
19
+ this.status = status;
20
+ }
21
+ };
22
+
23
+ // src/next/index.ts
24
+ var SESSION_COOKIE_NAME = "bs_session";
25
+ function isSecureDefault() {
26
+ return globalThis.process?.env?.NODE_ENV !== "development";
27
+ }
28
+ function serializeSessionCookie(value, maxAge, opts) {
29
+ const parts = [
30
+ `${SESSION_COOKIE_NAME}=${value}`,
31
+ `Path=${opts?.path ?? "/"}`,
32
+ "HttpOnly",
33
+ `SameSite=${opts?.sameSite === "strict" ? "Strict" : opts?.sameSite === "none" ? "None" : "Lax"}`
34
+ ];
35
+ if (maxAge !== null) {
36
+ parts.push(`Max-Age=${Math.max(0, Math.floor(maxAge))}`);
37
+ }
38
+ if (opts?.secure ?? isSecureDefault()) {
39
+ parts.push("Secure");
40
+ }
41
+ if (opts?.domain) {
42
+ parts.push(`Domain=${opts.domain}`);
43
+ }
44
+ return parts.join("; ");
45
+ }
46
+ function buildSessionCookie(token, maxAgeSeconds, opts) {
47
+ return serializeSessionCookie(token, maxAgeSeconds, opts);
48
+ }
49
+ function buildClearSessionCookie(opts) {
50
+ return serializeSessionCookie("", 0, opts);
51
+ }
52
+ function parseCookieHeader(header, name) {
53
+ for (const part of header.split(";")) {
54
+ const eq = part.indexOf("=");
55
+ if (eq === -1) {
56
+ continue;
57
+ }
58
+ if (part.slice(0, eq).trim() === name) {
59
+ return part.slice(eq + 1).trim();
60
+ }
61
+ }
62
+ return null;
63
+ }
64
+ function getSessionToken(source) {
65
+ if (source instanceof Request) {
66
+ const header = source.headers.get("cookie");
67
+ return header ? parseCookieHeader(header, SESSION_COOKIE_NAME) : null;
68
+ }
69
+ const cookie = source.get(SESSION_COOKIE_NAME);
70
+ if (!cookie) {
71
+ return null;
72
+ }
73
+ const value = typeof cookie === "string" ? cookie : cookie.value;
74
+ return value || null;
75
+ }
76
+ async function getSession(client, source) {
77
+ const token = getSessionToken(source);
78
+ if (!token) {
79
+ return null;
80
+ }
81
+ try {
82
+ const session = await client.auth.getSession(token);
83
+ return session ? { ...session, token } : null;
84
+ } catch {
85
+ return null;
86
+ }
87
+ }
88
+ async function requireSession(client, source) {
89
+ const session = await getSession(client, source);
90
+ if (!session) {
91
+ throw new BuildspaceError({
92
+ service: "auth",
93
+ status: 401,
94
+ code: "auth/session-required",
95
+ message: "No valid session. The bs_session cookie is missing, expired, or revoked."
96
+ });
97
+ }
98
+ return session;
99
+ }
100
+ function createAuthCallback(client, options) {
101
+ return async (request) => {
102
+ let tokens;
103
+ try {
104
+ tokens = await client.auth.handleCallback(request);
105
+ } catch (error) {
106
+ if (options?.onError) {
107
+ return await options.onError(error, request);
108
+ }
109
+ throw error;
110
+ }
111
+ if (options?.onSignIn) {
112
+ try {
113
+ await options.onSignIn({
114
+ accessToken: tokens.access_token,
115
+ request,
116
+ user: tokens.user
117
+ });
118
+ } catch (error) {
119
+ console.error("[buildspace] onSignIn hook failed", error);
120
+ }
121
+ }
122
+ return new Response(null, {
123
+ status: 303,
124
+ headers: {
125
+ Location: options?.redirectTo ?? "/",
126
+ "Set-Cookie": buildSessionCookie(tokens.access_token, tokens.expires_in, options?.cookie)
127
+ }
128
+ });
129
+ };
130
+ }
131
+ function createLogoutRoute(client, options) {
132
+ return async (request) => {
133
+ const token = getSessionToken(request);
134
+ if (token) {
135
+ try {
136
+ await client.auth.signOut(token);
137
+ } catch (error) {
138
+ console.error("[buildspace] session revoke failed during logout", error);
139
+ }
140
+ }
141
+ return new Response(JSON.stringify({ ok: true }), {
142
+ status: 200,
143
+ headers: {
144
+ "Content-Type": "application/json",
145
+ "Set-Cookie": buildClearSessionCookie(options?.cookie)
146
+ }
147
+ });
148
+ };
149
+ }
150
+ function createSessionRoute(client) {
151
+ return async (request) => {
152
+ const session = await getSession(client, request);
153
+ const publicSession = session ? { appId: session.appId, user: session.user } : null;
154
+ return new Response(JSON.stringify({ session: publicSession }), {
155
+ status: 200,
156
+ headers: { "Content-Type": "application/json" }
157
+ });
158
+ };
159
+ }
160
+ function createSessionCookieGuard(options) {
161
+ return (request) => {
162
+ if (getSessionToken(request)) {
163
+ return;
164
+ }
165
+ const target = new URL(options?.redirectTo ?? "/", new URL(request.url).origin);
166
+ return Response.redirect(target.toString(), 307);
167
+ };
168
+ }
169
+
170
+ export { SESSION_COOKIE_NAME, buildClearSessionCookie, buildSessionCookie, createAuthCallback, createLogoutRoute, createSessionCookieGuard, createSessionRoute, getSession, getSessionToken, requireSession };
171
+ //# sourceMappingURL=index.js.map
172
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/errors.ts","../../src/next/index.ts"],"names":[],"mappings":";AAiBO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA;AAAA,EAEhC,IAAA;AAAA;AAAA,EAEA,O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,MAAM;AAAA;AACvD,KACD,CAAA;AAAA,EACH,CAAA;AACF;AAQO,SAAS,mBACd,MAAA,EACyC;AACzC,EAAA,OAAO,OAAO,OAAA,KAAwC;AACpD,IAAA,MAAM,OAAA,GAAU,MAAM,UAAA,CAAW,MAAA,EAAQ,OAAO,CAAA;AAChD,IAAA,MAAM,aAAA,GAAgB,UAAU,EAAE,KAAA,EAAO,QAAQ,KAAA,EAAO,IAAA,EAAM,OAAA,CAAQ,IAAA,EAAK,GAAI,IAAA;AAE/E,IAAA,OAAO,IAAI,SAAS,IAAA,CAAK,SAAA,CAAU,EAAE,OAAA,EAAS,aAAA,EAAe,CAAA,EAAG;AAAA,MAC9D,MAAA,EAAQ,GAAA;AAAA,MACR,OAAA,EAAS,EAAE,cAAA,EAAgB,kBAAA;AAAmB,KAC/C,CAAA;AAAA,EACH,CAAA;AACF;AAkBO,SAAS,yBAAyB,OAAA,EAGM;AAC7C,EAAA,OAAO,CAAC,OAAA,KAA2C;AACjD,IAAA,IAAI,eAAA,CAAgB,OAAO,CAAA,EAAG;AAC5B,MAAA;AAAA,IACF;AAEA,IAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,OAAA,EAAS,UAAA,IAAc,GAAA,EAAK,IAAI,GAAA,CAAI,OAAA,CAAQ,GAAG,CAAA,CAAE,MAAM,CAAA;AAC9E,IAAA,OAAO,QAAA,CAAS,QAAA,CAAS,MAAA,CAAO,QAAA,IAAY,GAAG,CAAA;AAAA,EACjD,CAAA;AACF","file":"index.js","sourcesContent":["/** Services available in the Buildspace platform. */\nexport type BuildspaceService = \"auth\" | \"billing\" | \"events\" | \"notifications\" | \"storage\";\n\n/**\n * Error thrown by all Buildspace SDK methods on failure.\n *\n * @example\n * ```ts\n * try {\n * await buildspace.auth.getSession(token);\n * } catch (err) {\n * if (err instanceof BuildspaceError) {\n * console.error(err.service, err.code, err.status, err.message);\n * }\n * }\n * ```\n */\nexport class BuildspaceError extends Error {\n /** Machine-readable error code, e.g. `\"auth/invalid-token\"`. */\n readonly code: string;\n /** Which service produced the error. */\n readonly service: BuildspaceService;\n /** HTTP status code from the API. */\n readonly status: number;\n\n constructor({\n code,\n message,\n service,\n status,\n }: {\n code: string;\n message: string;\n service: BuildspaceService;\n status: number;\n }) {\n super(message);\n this.name = \"BuildspaceError\";\n this.code = code;\n this.service = service;\n this.status = status;\n }\n}\n","import type { AuthSession, AuthUser, TokenResponse } from \"../auth\";\nimport { BuildspaceError } from \"../errors\";\n\n/**\n * Framework adapter for Next.js (and any framework using web-standard\n * `Request`/`Response` route handlers).\n *\n * Replaces the auth glue every creator app used to hand-roll: the OAuth\n * callback route, logout + session routes, a cookie-aware `getSession()`,\n * and a middleware cookie guard — all standardized on the `bs_session`\n * cookie.\n *\n * @example\n * ```ts\n * // app/api/auth/callback/route.ts\n * import { createAuthCallback } from \"@buildspacestudio/sdk/next\";\n * import { getServerClient } from \"@/lib/buildspace\";\n *\n * export const GET = createAuthCallback(getServerClient(), { redirectTo: \"/dashboard\" });\n * ```\n */\n\n/** The session cookie name shared by every Buildspace app. */\nexport const SESSION_COOKIE_NAME = \"bs_session\";\n\n/** The minimal server-client surface the adapter needs (a `Buildspace` instance). */\nexport interface AuthServerClient {\n auth: {\n getSession(sessionToken: string): Promise<AuthSession | null>;\n handleCallback(\n request: Request | URL | string,\n opts?: { redirectUri?: string }\n ): Promise<TokenResponse>;\n signOut(sessionToken?: string): Promise<void>;\n };\n}\n\n/** Options controlling the `bs_session` cookie attributes. */\nexport interface SessionCookieOptions {\n /** Cookie domain. Omitted by default (host-only cookie). */\n domain?: string;\n /** Cookie path. Defaults to `/`. */\n path?: string;\n /** SameSite attribute. Defaults to `Lax`. */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n /** Set the `Secure` attribute. Defaults to `true` outside development. */\n secure?: boolean;\n}\n\nfunction isSecureDefault(): boolean {\n return (\n (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env\n ?.NODE_ENV !== \"development\"\n );\n}\n\nfunction serializeSessionCookie(\n value: string,\n maxAge: number | null,\n opts?: SessionCookieOptions\n): string {\n const parts = [\n `${SESSION_COOKIE_NAME}=${value}`,\n `Path=${opts?.path ?? \"/\"}`,\n \"HttpOnly\",\n `SameSite=${opts?.sameSite === \"strict\" ? \"Strict\" : opts?.sameSite === \"none\" ? \"None\" : \"Lax\"}`,\n ];\n\n if (maxAge !== null) {\n parts.push(`Max-Age=${Math.max(0, Math.floor(maxAge))}`);\n }\n\n if (opts?.secure ?? isSecureDefault()) {\n parts.push(\"Secure\");\n }\n\n if (opts?.domain) {\n parts.push(`Domain=${opts.domain}`);\n }\n\n return parts.join(\"; \");\n}\n\n/** Build a `Set-Cookie` header value that stores the session token. */\nexport function buildSessionCookie(\n token: string,\n maxAgeSeconds: number,\n opts?: SessionCookieOptions\n): string {\n return serializeSessionCookie(token, maxAgeSeconds, opts);\n}\n\n/** Build a `Set-Cookie` header value that clears the session cookie. */\nexport function buildClearSessionCookie(opts?: SessionCookieOptions): string {\n return serializeSessionCookie(\"\", 0, opts);\n}\n\n/**\n * Anything the adapter can read the session cookie from: a web `Request`,\n * or a cookie store with a `get(name)` method (e.g. the object returned by\n * Next.js `cookies()` in Server Components and Route Handlers).\n */\nexport type SessionCookieSource =\n | Request\n | {\n get(name: string): { value: string } | string | null | undefined;\n };\n\nfunction parseCookieHeader(header: string, name: string): string | null {\n for (const part of header.split(\";\")) {\n const eq = part.indexOf(\"=\");\n if (eq === -1) {\n continue;\n }\n\n if (part.slice(0, eq).trim() === name) {\n return part.slice(eq + 1).trim();\n }\n }\n\n return null;\n}\n\n/** Read the raw session token from a request or cookie store, or `null`. */\nexport function getSessionToken(source: SessionCookieSource): string | null {\n if (source instanceof Request) {\n const header = source.headers.get(\"cookie\");\n return header ? parseCookieHeader(header, SESSION_COOKIE_NAME) : null;\n }\n\n const cookie = source.get(SESSION_COOKIE_NAME);\n if (!cookie) {\n return null;\n }\n\n const value = typeof cookie === \"string\" ? cookie : cookie.value;\n return value || null;\n}\n\n/** An {@link AuthSession} plus the raw token it was resolved from. */\nexport type SessionWithToken = AuthSession & { token: string };\n\n/**\n * Cookie-aware session lookup.\n *\n * Reads the `bs_session` cookie from the given source and verifies it with\n * the Buildspace API. Returns `null` when there is no cookie or the token\n * is expired/revoked. Network/5xx errors also resolve to `null` so a blip\n * never crashes rendering — sign-in state degrades to \"signed out\".\n *\n * @example\n * ```ts\n * // Server Component\n * import { cookies } from \"next/headers\";\n * const session = await getSession(getServerClient(), await cookies());\n * ```\n */\nexport async function getSession(\n client: AuthServerClient,\n source: SessionCookieSource\n): Promise<SessionWithToken | null> {\n const token = getSessionToken(source);\n if (!token) {\n return null;\n }\n\n try {\n const session = await client.auth.getSession(token);\n return session ? { ...session, token } : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Like {@link getSession} but throws a `BuildspaceError` (401) when there is\n * no valid session. Use in route handlers and server actions that must only\n * run for signed-in users.\n */\nexport async function requireSession(\n client: AuthServerClient,\n source: SessionCookieSource\n): Promise<SessionWithToken> {\n const session = await getSession(client, source);\n if (!session) {\n throw new BuildspaceError({\n service: \"auth\",\n status: 401,\n code: \"auth/session-required\",\n message: \"No valid session. The bs_session cookie is missing, expired, or revoked.\",\n });\n }\n\n return session;\n}\n\n/** Options for {@link createAuthCallback}. */\nexport interface CreateAuthCallbackOptions {\n /** Cookie attribute overrides. */\n cookie?: SessionCookieOptions;\n /**\n * Called when the code exchange fails. Return a `Response` to control the\n * error page; by default the error is rethrown (surfacing your framework's\n * error handling).\n */\n onError?: (error: unknown, request: Request) => Response | Promise<Response>;\n /**\n * Signup/sign-in side effects (mirror the user into your DB, send a\n * welcome email, track an event). Failures are logged and never break\n * login.\n */\n onSignIn?: (ctx: {\n accessToken: string;\n request: Request;\n user: AuthUser;\n }) => void | Promise<void>;\n /** Where to send the user after login. Defaults to `/`. */\n redirectTo?: string;\n}\n\n/**\n * Create the OAuth callback route handler.\n *\n * Exchanges the `?code=` for tokens, runs your `onSignIn` hook, stores the\n * access token in the `bs_session` cookie (with `expires_in` as `Max-Age`),\n * and redirects to `redirectTo`.\n *\n * @example\n * ```ts\n * // app/api/auth/callback/route.ts\n * export const GET = createAuthCallback(getServerClient(), {\n * redirectTo: \"/dashboard\",\n * onSignIn: async ({ user }) => upsertUser(user),\n * });\n * ```\n */\nexport function createAuthCallback(\n client: AuthServerClient,\n options?: CreateAuthCallbackOptions\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n let tokens: TokenResponse;\n try {\n tokens = await client.auth.handleCallback(request);\n } catch (error) {\n if (options?.onError) {\n return await options.onError(error, request);\n }\n throw error;\n }\n\n if (options?.onSignIn) {\n try {\n await options.onSignIn({\n accessToken: tokens.access_token,\n request,\n user: tokens.user,\n });\n } catch (error) {\n console.error(\"[buildspace] onSignIn hook failed\", error);\n }\n }\n\n return new Response(null, {\n status: 303,\n headers: {\n Location: options?.redirectTo ?? \"/\",\n \"Set-Cookie\": buildSessionCookie(tokens.access_token, tokens.expires_in, options?.cookie),\n },\n });\n };\n}\n\n/**\n * Create the logout route handler (`POST /api/auth/logout`).\n *\n * Revokes the session with the Buildspace API (already-expired sessions are\n * ignored) and clears the `bs_session` cookie.\n */\nexport function createLogoutRoute(\n client: AuthServerClient,\n options?: { cookie?: SessionCookieOptions }\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const token = getSessionToken(request);\n\n if (token) {\n try {\n await client.auth.signOut(token);\n } catch (error) {\n console.error(\"[buildspace] session revoke failed during logout\", error);\n }\n }\n\n return new Response(JSON.stringify({ ok: true }), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Set-Cookie\": buildClearSessionCookie(options?.cookie),\n },\n });\n };\n}\n\n/**\n * Create the session route handler (`GET /api/auth/session`).\n *\n * Returns `{ session }` for the current cookie, with the raw token omitted —\n * this response is safe to expose to the browser.\n */\nexport function createSessionRoute(\n client: AuthServerClient\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const session = await getSession(client, request);\n const publicSession = session ? { appId: session.appId, user: session.user } : null;\n\n return new Response(JSON.stringify({ session: publicSession }), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n };\n}\n\n/**\n * Middleware helper: redirect requests that don't carry a session cookie.\n *\n * This is a fast presence check (no API call — middleware runs on every\n * matched request); route handlers and pages must still verify the session\n * with {@link getSession}.\n *\n * @example\n * ```ts\n * // middleware.ts / proxy.ts\n * import { createSessionCookieGuard } from \"@buildspacestudio/sdk/next\";\n *\n * export const proxy = createSessionCookieGuard({ redirectTo: \"/\" });\n * export const config = { matcher: [\"/dashboard/:path*\"] };\n * ```\n */\nexport function createSessionCookieGuard(options?: {\n /** Where to send signed-out users. Defaults to `/`. */\n redirectTo?: string;\n}): (request: Request) => Response | undefined {\n return (request: Request): Response | undefined => {\n if (getSessionToken(request)) {\n return;\n }\n\n const target = new URL(options?.redirectTo ?? \"/\", new URL(request.url).origin);\n return Response.redirect(target.toString(), 307);\n };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { H as HttpTransport } from '../http-U-zzKmFF.cjs';
1
+ import { H as HttpTransport } from '../http-D2gXpNpr.cjs';
2
2
 
3
3
  /** Options for sending a custom email. */
4
4
  interface SendOptions {
@@ -1,4 +1,4 @@
1
- import { H as HttpTransport } from '../http-U-zzKmFF.js';
1
+ import { H as HttpTransport } from '../http-D2gXpNpr.js';
2
2
 
3
3
  /** Options for sending a custom email. */
4
4
  interface SendOptions {
@@ -0,0 +1,120 @@
1
+ "use client";
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/react/index.ts
22
+ var react_exports = {};
23
+ __export(react_exports, {
24
+ BuildspaceProvider: () => BuildspaceProvider,
25
+ useAuth: () => useAuth,
26
+ useBuildspaceClient: () => useBuildspaceClient,
27
+ useSession: () => useSession,
28
+ useTrack: () => useTrack
29
+ });
30
+ module.exports = __toCommonJS(react_exports);
31
+ var import_react = require("react");
32
+ var BuildspaceContext = (0, import_react.createContext)({
33
+ client: null,
34
+ loading: false,
35
+ signIn: () => void 0,
36
+ signOut: () => Promise.resolve(),
37
+ signUp: () => void 0,
38
+ user: null
39
+ });
40
+ function browserLocation() {
41
+ const location = globalThis.location;
42
+ return location ?? null;
43
+ }
44
+ function BuildspaceProvider({
45
+ callbackPath = "/api/auth/callback",
46
+ children,
47
+ client,
48
+ initialUser = null,
49
+ logoutPath = "/api/auth/logout",
50
+ signedOutRedirect = "/"
51
+ }) {
52
+ const [user, setUser] = (0, import_react.useState)(initialUser);
53
+ const signIn = (0, import_react.useCallback)(() => {
54
+ const location = browserLocation();
55
+ if (!location) {
56
+ return;
57
+ }
58
+ location.href = client.auth.getSignInUrl({
59
+ redirectUri: `${location.origin}${callbackPath}`
60
+ });
61
+ }, [client, callbackPath]);
62
+ const signUp = (0, import_react.useCallback)(() => {
63
+ const location = browserLocation();
64
+ if (!location) {
65
+ return;
66
+ }
67
+ location.href = client.auth.getSignUpUrl({
68
+ redirectUri: `${location.origin}${callbackPath}`
69
+ });
70
+ }, [client, callbackPath]);
71
+ const signOut = (0, import_react.useCallback)(async () => {
72
+ await fetch(logoutPath, { method: "POST" });
73
+ setUser(null);
74
+ const location = browserLocation();
75
+ if (location) {
76
+ location.href = signedOutRedirect;
77
+ }
78
+ }, [logoutPath, signedOutRedirect]);
79
+ const value = (0, import_react.useMemo)(
80
+ () => ({ client, loading: false, signIn, signOut, signUp, user }),
81
+ [client, signIn, signOut, signUp, user]
82
+ );
83
+ return (0, import_react.createElement)(BuildspaceContext, { value }, children);
84
+ }
85
+ function useAuth() {
86
+ const { client: _client, ...auth } = (0, import_react.useContext)(BuildspaceContext);
87
+ return auth;
88
+ }
89
+ function useSession() {
90
+ const { loading, user } = (0, import_react.useContext)(BuildspaceContext);
91
+ return { loading, user };
92
+ }
93
+ function useBuildspaceClient() {
94
+ const { client } = (0, import_react.useContext)(BuildspaceContext);
95
+ if (!client) {
96
+ throw new Error("useBuildspaceClient must be used inside <BuildspaceProvider>.");
97
+ }
98
+ return client;
99
+ }
100
+ function useTrack() {
101
+ const { client, user } = (0, import_react.useContext)(BuildspaceContext);
102
+ return (0, import_react.useCallback)(
103
+ (event, properties) => {
104
+ try {
105
+ client?.events.track(event, properties, user?.id);
106
+ } catch {
107
+ }
108
+ },
109
+ [client, user?.id]
110
+ );
111
+ }
112
+ // Annotate the CommonJS export names for ESM import in node:
113
+ 0 && (module.exports = {
114
+ BuildspaceProvider,
115
+ useAuth,
116
+ useBuildspaceClient,
117
+ useSession,
118
+ useTrack
119
+ });
120
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/react/index.ts"],"sourcesContent":["import type { ReactNode } from \"react\";\nimport { createContext, createElement, useCallback, useContext, useMemo, useState } from \"react\";\nimport type { AuthUser } from \"../auth\";\nimport type { BuildspaceClient } from \"../client\";\n\n/**\n * React bindings for the Buildspace client SDK.\n *\n * Wrap your app in {@link BuildspaceProvider} (pass a client created with\n * `createClient()` from `@buildspacestudio/sdk/client` and, optionally, the\n * server-resolved user for a flash-free first paint), then read auth state\n * with {@link useAuth}/{@link useSession} and track events with\n * {@link useTrack}.\n *\n * @example\n * ```tsx\n * // app/layout.tsx (Server Component)\n * const session = await getSession(getServerClient(), await cookies());\n * <Providers initialUser={session?.user ?? null}>{children}</Providers>\n *\n * // components/providers.tsx (\"use client\")\n * <BuildspaceProvider client={getBrowserClient()} initialUser={initialUser}>\n * {children}\n * </BuildspaceProvider>\n * ```\n */\n\n/** Auth state and actions exposed by {@link useAuth}. */\nexport interface BuildspaceAuthState {\n /** True while the session is being resolved client-side. */\n loading: boolean;\n /** Redirect the browser to the Buildspace sign-in page. */\n signIn: () => void;\n /** Log out: POST the logout route, clear local state, and go home. */\n signOut: () => Promise<void>;\n /** Redirect the browser to the Buildspace sign-up page. */\n signUp: () => void;\n /** The signed-in user, or `null`. */\n user: AuthUser | null;\n}\n\ninterface BuildspaceContextValue extends BuildspaceAuthState {\n client: BuildspaceClient | null;\n}\n\nconst BuildspaceContext = createContext<BuildspaceContextValue>({\n client: null,\n loading: false,\n signIn: () => undefined,\n signOut: () => Promise.resolve(),\n signUp: () => undefined,\n user: null,\n});\n\nfunction browserLocation(): { href: string; origin: string } | null {\n const location = (globalThis as { location?: { href: string; origin: string } }).location;\n return location ?? null;\n}\n\n/** Options for {@link BuildspaceProvider}. */\nexport interface BuildspaceProviderProps {\n /** Path of your OAuth callback route. Defaults to `/api/auth/callback`. */\n callbackPath?: string;\n children: ReactNode;\n /** A client SDK instance (`createClient(\"bs_pub_...\")`). */\n client: BuildspaceClient;\n /**\n * The server-resolved user (from `getSession()` in a Server Component).\n * Pass it so the first client render already knows who is signed in.\n */\n initialUser?: AuthUser | null;\n /** Path of your logout route. Defaults to `/api/auth/logout`. */\n logoutPath?: string;\n /** Where to send the user after sign-out. Defaults to `/`. */\n signedOutRedirect?: string;\n}\n\n/**\n * Provides Buildspace auth state and the client SDK to the React tree.\n *\n * Must render inside a client boundary (`\"use client\"`).\n */\nexport function BuildspaceProvider({\n callbackPath = \"/api/auth/callback\",\n children,\n client,\n initialUser = null,\n logoutPath = \"/api/auth/logout\",\n signedOutRedirect = \"/\",\n}: BuildspaceProviderProps) {\n const [user, setUser] = useState<AuthUser | null>(initialUser);\n\n const signIn = useCallback(() => {\n const location = browserLocation();\n if (!location) {\n return;\n }\n\n location.href = client.auth.getSignInUrl({\n redirectUri: `${location.origin}${callbackPath}`,\n });\n }, [client, callbackPath]);\n\n const signUp = useCallback(() => {\n const location = browserLocation();\n if (!location) {\n return;\n }\n\n location.href = client.auth.getSignUpUrl({\n redirectUri: `${location.origin}${callbackPath}`,\n });\n }, [client, callbackPath]);\n\n const signOut = useCallback(async () => {\n await fetch(logoutPath, { method: \"POST\" });\n setUser(null);\n const location = browserLocation();\n if (location) {\n location.href = signedOutRedirect;\n }\n }, [logoutPath, signedOutRedirect]);\n\n const value = useMemo<BuildspaceContextValue>(\n () => ({ client, loading: false, signIn, signOut, signUp, user }),\n [client, signIn, signOut, signUp, user]\n );\n\n return createElement(BuildspaceContext, { value }, children);\n}\n\n/** Auth state and actions: `{ user, loading, signIn, signUp, signOut }`. */\nexport function useAuth(): BuildspaceAuthState {\n const { client: _client, ...auth } = useContext(BuildspaceContext);\n return auth;\n}\n\n/** The current session's user: `{ user, loading }`. */\nexport function useSession(): { loading: boolean; user: AuthUser | null } {\n const { loading, user } = useContext(BuildspaceContext);\n return { loading, user };\n}\n\n/** The client SDK instance passed to {@link BuildspaceProvider}. */\nexport function useBuildspaceClient(): BuildspaceClient {\n const { client } = useContext(BuildspaceContext);\n if (!client) {\n throw new Error(\"useBuildspaceClient must be used inside <BuildspaceProvider>.\");\n }\n\n return client;\n}\n\n/**\n * Fire-and-forget analytics tracking bound to the signed-in user.\n *\n * Wraps the batched client events namespace; analytics never throw and never\n * block the UI.\n *\n * @example\n * ```tsx\n * const track = useTrack();\n * <button onClick={() => track(\"upgrade.clicked\", { plan: \"pro\" })} />\n * ```\n */\nexport function useTrack(): (event: string, properties?: Record<string, unknown>) => void {\n const { client, user } = useContext(BuildspaceContext);\n\n return useCallback(\n (event: string, properties?: Record<string, unknown>) => {\n try {\n client?.events.track(event, properties, user?.id);\n } catch {\n // Analytics must never break the app.\n }\n },\n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