@n-dream/builders-sdk 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,46 @@
1
- # Temporary Holding Version
1
+ # @n-dream/builders-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Platform helpers for apps on the Builders platform (builders.n-dream.com):
4
+ the signed-in user, a database, AI, file storage and notifications.
5
+
6
+ This package is for apps that the platform made. It does not work on other
7
+ hosting. The platform sets the environment variables that it needs.
8
+
9
+ ## Install
10
+
11
+ Apps import the package as `@builders/sdk`. Use an npm alias in
12
+ `package.json`:
13
+
14
+ ```json
15
+ "dependencies": {
16
+ "@builders/sdk": "npm:@n-dream/builders-sdk@^0.1.0"
17
+ }
18
+ ```
19
+
20
+ Node.js 22 or later is necessary. `@builders/sdk/next` needs Next.js 15 or
21
+ later.
22
+
23
+ ## Use
24
+
25
+ ```ts
26
+ import { currentUser } from "@builders/sdk/next"; // server code only
27
+ import { db, ai, storage, notify } from "@builders/sdk";
28
+
29
+ const user = await currentUser(); // { email, name }
30
+ const notes = db.collection<{ text: string; author: string }>("notes");
31
+ await notes.add({ text: "Hello", author: user.email });
32
+ await notes.where("author", "==", user.email).limit(20).list();
33
+
34
+ await ai.ask("Summarise: ...", { model: "fast" }); // AI add-on
35
+ await storage.upload("files/a.pdf", bytes); // storage add-on
36
+ await notify.slack("Done"); // notify add-on
37
+ ```
38
+
39
+ - `db` uses Firestore on the platform. In `next dev` and in tests, it uses
40
+ a temporary database in memory.
41
+ - `ai`, `storage` and `notify` are add-ons. If an add-on is off, the call
42
+ throws `AddOnNotEnabledError`.
43
+
44
+ ## License
45
+
46
+ UNLICENSED. Only for apps on the Builders platform.
@@ -0,0 +1,132 @@
1
+ // ../core/src/identity-token.ts
2
+ var IDENTITY_HEADER = "x-builders-identity";
3
+ var IDENTITY_ALG = "ES256";
4
+ var IDENTITY_TOKEN_TTL_S = 60;
5
+ var IDENTITY_CLOCK_TOLERANCE_S = 30;
6
+ var IDENTITY_ENV = {
7
+ audience: "BUILDERS_IDENTITY_AUDIENCE",
8
+ issuer: "BUILDERS_IDENTITY_ISSUER",
9
+ jwksUrl: "BUILDERS_IDENTITY_JWKS_URL",
10
+ // Inline JWKS (JSON), for tests and BYOC setups without the bucket.
11
+ jwks: "BUILDERS_IDENTITY_JWKS"
12
+ };
13
+
14
+ // src/errors.ts
15
+ var BuildersError = class extends Error {
16
+ constructor(message, status = 500) {
17
+ super(message);
18
+ this.status = status;
19
+ this.name = "BuildersError";
20
+ }
21
+ status;
22
+ };
23
+ var NotSignedInError = class extends BuildersError {
24
+ constructor(message) {
25
+ super(message, 401);
26
+ this.name = "NotSignedInError";
27
+ }
28
+ };
29
+ var NotFoundError = class extends BuildersError {
30
+ constructor(message) {
31
+ super(message, 404);
32
+ this.name = "NotFoundError";
33
+ }
34
+ };
35
+ var ADDON_LABELS = {
36
+ ai: "AI",
37
+ storage: "file storage",
38
+ cron: "scheduled jobs",
39
+ notify: "notifications",
40
+ internet: "internet access"
41
+ };
42
+ var AddOnNotEnabledError = class extends BuildersError {
43
+ constructor(addOn) {
44
+ super(
45
+ `This add-on (${ADDON_LABELS[addOn]}) is not switched on for your app. Ask for it in the Builders portal.`,
46
+ 503
47
+ );
48
+ this.addOn = addOn;
49
+ this.name = "AddOnNotEnabledError";
50
+ }
51
+ addOn;
52
+ };
53
+
54
+ // src/user.ts
55
+ import { createLocalJWKSet, createRemoteJWKSet, jwtVerify } from "jose";
56
+ var remoteKeys = /* @__PURE__ */ new Map();
57
+ function keysFrom(env) {
58
+ const inline = env[IDENTITY_ENV.jwks];
59
+ if (inline) return createLocalJWKSet(JSON.parse(inline));
60
+ const url = env[IDENTITY_ENV.jwksUrl];
61
+ if (!url) throw new BuildersError(`${IDENTITY_ENV.jwksUrl} is not set, so the signed-in user cannot be checked. The platform sets it on deploy.`);
62
+ let k = remoteKeys.get(url);
63
+ if (!k) {
64
+ k = createRemoteJWKSet(new URL(url), { cooldownDuration: 3e4, cacheMaxAge: 10 * 6e4 });
65
+ remoteKeys.set(url, k);
66
+ }
67
+ return k;
68
+ }
69
+ async function getUser(headers, opts = {}) {
70
+ const env = opts.env ?? process.env;
71
+ const token = readHeader(headers, IDENTITY_HEADER);
72
+ if (token) {
73
+ const audience = opts.audience ?? env[IDENTITY_ENV.audience];
74
+ const issuer = opts.issuer ?? env[IDENTITY_ENV.issuer];
75
+ if (!audience || !issuer) {
76
+ throw new BuildersError(
77
+ `${IDENTITY_ENV.audience} and ${IDENTITY_ENV.issuer} must be set, so the signed-in user can be checked. The platform sets them on deploy.`
78
+ );
79
+ }
80
+ let payload;
81
+ try {
82
+ ({ payload } = await jwtVerify(token, opts.keys ?? keysFrom(env), {
83
+ issuer,
84
+ audience,
85
+ algorithms: [IDENTITY_ALG],
86
+ requiredClaims: ["exp", "iat", "email"],
87
+ maxTokenAge: IDENTITY_TOKEN_TTL_S + IDENTITY_CLOCK_TOLERANCE_S,
88
+ clockTolerance: IDENTITY_CLOCK_TOLERANCE_S
89
+ }));
90
+ } catch (e) {
91
+ if (e instanceof BuildersError) throw e;
92
+ throw new NotSignedInError(`The sign-in token is not valid: ${e.message}`);
93
+ }
94
+ if (typeof payload.email !== "string" || !payload.email || payload.email_verified !== true) {
95
+ throw new NotSignedInError("The sign-in token has no verified email address.");
96
+ }
97
+ const email = payload.email.toLowerCase();
98
+ return { email, name: typeof payload.name === "string" && payload.name ? payload.name : nameFromEmail(email) };
99
+ }
100
+ const devUser = env.BUILDERS_DEV_USER;
101
+ if (env.NODE_ENV !== "production" && devUser) {
102
+ return { email: devUser.toLowerCase(), name: nameFromEmail(devUser) };
103
+ }
104
+ throw new NotSignedInError(
105
+ env.NODE_ENV === "production" ? "No signed-in user. Open the app through its Builders link, which signs you in." : "No signed-in user. For local development set BUILDERS_DEV_USER (the dev script does this)."
106
+ );
107
+ }
108
+ function nameFromEmail(email) {
109
+ const local = email.split("@")[0] ?? "";
110
+ const parts = local.split(/[._-]+/).filter((p) => /^[a-z]+$/i.test(p));
111
+ if (parts.length === 0) return void 0;
112
+ return parts.map((p) => p[0].toUpperCase() + p.slice(1).toLowerCase()).join(" ");
113
+ }
114
+ function readHeader(headers, name) {
115
+ if (typeof headers.get === "function") {
116
+ return headers.get(name) ?? void 0;
117
+ }
118
+ const rec = headers;
119
+ const key = Object.keys(rec).find((k) => k.toLowerCase() === name);
120
+ const v = key === void 0 ? void 0 : rec[key];
121
+ return (Array.isArray(v) ? v[0] : v) || void 0;
122
+ }
123
+
124
+ export {
125
+ IDENTITY_HEADER,
126
+ BuildersError,
127
+ NotSignedInError,
128
+ NotFoundError,
129
+ AddOnNotEnabledError,
130
+ getUser,
131
+ nameFromEmail
132
+ };
@@ -0,0 +1,20 @@
1
+ import { JWTVerifyGetKey } from 'jose';
2
+
3
+ interface User {
4
+ email: string;
5
+ name?: string;
6
+ }
7
+ type HeaderSource = {
8
+ get(name: string): string | null;
9
+ } | Record<string, string | string[] | undefined>;
10
+ interface GetUserOptions {
11
+ audience?: string;
12
+ issuer?: string;
13
+ keys?: JWTVerifyGetKey;
14
+ env?: Record<string, string | undefined>;
15
+ }
16
+ declare function getUser(headers: HeaderSource, opts?: GetUserOptions): Promise<User>;
17
+ declare function nameFromEmail(email: string): string | undefined;
18
+
19
+ export { getUser as g, nameFromEmail as n };
20
+ export type { GetUserOptions as G, HeaderSource as H, User as U };
@@ -0,0 +1,106 @@
1
+ export { G as GetUserOptions, H as HeaderSource, U as User, g as getUser, n as nameFromEmail } from './chunks/user-Dr8gM34m.js';
2
+ import 'jose';
3
+
4
+ declare const ADDONS: readonly ["ai", "storage", "cron", "notify", "internet"];
5
+ type AddOn = (typeof ADDONS)[number];
6
+
7
+ declare const IDENTITY_HEADER = "x-builders-identity";
8
+
9
+ declare const CLAUDE_MODELS: {
10
+ readonly fast: "claude-haiku-5-5";
11
+ readonly balanced: "claude-sonnet-5-5";
12
+ readonly best: "claude-opus-5-5";
13
+ };
14
+ type AiModelChoice = keyof typeof CLAUDE_MODELS;
15
+
16
+ declare function resetMemoryDb(): void;
17
+
18
+ declare const MAX_QUERY_LIMIT = 500;
19
+
20
+ type WhereOp = "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "not-in" | "array-contains" | "array-contains-any";
21
+ type Doc<T> = T & {
22
+ id: string;
23
+ };
24
+ interface Query<T extends object> {
25
+ where(field: keyof T & string, op: WhereOp, value: unknown): Query<T>;
26
+ orderBy(field: keyof T & string, direction?: "asc" | "desc"): Query<T>;
27
+ limit(n: number): Query<T>;
28
+ list(): Promise<Doc<T>[]>;
29
+ }
30
+ interface Collection<T extends object> extends Query<T> {
31
+ get(id: string): Promise<Doc<T> | null>;
32
+ add(data: T): Promise<Doc<T>>;
33
+ set(id: string, data: T): Promise<void>;
34
+ update(id: string, patch: Partial<T>): Promise<void>;
35
+ delete(id: string): Promise<void>;
36
+ }
37
+ type DbMode = "firestore" | "memory";
38
+ declare function dbMode(env?: Record<string, string | undefined>): DbMode;
39
+ declare const db: {
40
+ collection<T extends object>(name: string): Collection<T>;
41
+ reset: typeof resetMemoryDb;
42
+ };
43
+
44
+ type AiModel = AiModelChoice;
45
+ interface AskOptions {
46
+ system?: string;
47
+ model?: AiModel;
48
+ maxTokens?: number;
49
+ signal?: AbortSignal;
50
+ }
51
+ interface AskRequest {
52
+ prompt: string;
53
+ system?: string;
54
+ model: AiModel;
55
+ maxTokens: number;
56
+ }
57
+ interface AskResponse {
58
+ text: string;
59
+ model: string;
60
+ usage: {
61
+ inputTokens: number;
62
+ outputTokens: number;
63
+ };
64
+ }
65
+ declare const ai: {
66
+ ask(prompt: string, opts?: AskOptions): Promise<string>;
67
+ };
68
+
69
+ declare const storage: {
70
+ upload(path: string, data: string | Uint8Array, opts?: {
71
+ contentType?: string;
72
+ }): Promise<{
73
+ path: string;
74
+ }>;
75
+ download(path: string): Promise<Buffer>;
76
+ signedUrl(path: string, opts?: {
77
+ action?: "read" | "write";
78
+ expiresInMinutes?: number;
79
+ contentType?: string;
80
+ }): Promise<string>;
81
+ list(prefix?: string): Promise<string[]>;
82
+ delete(path: string): Promise<void>;
83
+ };
84
+
85
+ declare const notify: {
86
+ email(to: string | string[], subject: string, text: string): Promise<void>;
87
+ slack(text: string): Promise<void>;
88
+ };
89
+
90
+ declare class BuildersError extends Error {
91
+ readonly status: number;
92
+ constructor(message: string, status?: number);
93
+ }
94
+ declare class NotSignedInError extends BuildersError {
95
+ constructor(message: string);
96
+ }
97
+ declare class NotFoundError extends BuildersError {
98
+ constructor(message: string);
99
+ }
100
+ declare class AddOnNotEnabledError extends BuildersError {
101
+ readonly addOn: AddOn;
102
+ constructor(addOn: AddOn);
103
+ }
104
+
105
+ export { AddOnNotEnabledError, BuildersError, IDENTITY_HEADER, MAX_QUERY_LIMIT, NotFoundError, NotSignedInError, ai, db, dbMode, notify, storage };
106
+ export type { AiModel, AskOptions, AskRequest, AskResponse, Collection, DbMode, Doc, Query, WhereOp };
package/dist/index.js ADDED
@@ -0,0 +1,537 @@
1
+ import {
2
+ AddOnNotEnabledError,
3
+ BuildersError,
4
+ IDENTITY_HEADER,
5
+ NotFoundError,
6
+ NotSignedInError,
7
+ getUser,
8
+ nameFromEmail
9
+ } from "./chunks/chunk-AXQENVKW.js";
10
+
11
+ // ../core/src/firestore-indexes.ts
12
+ import { z } from "zod";
13
+ var INDEXES_FILE = "firestore.indexes.json";
14
+ var MAX_INDEXES_FILE_BYTES = 64 * 1024;
15
+ var MAX_INDEXES = 100;
16
+ var FIELD_PATH = /^[A-Za-z_][A-Za-z0-9_]{0,99}(\.[A-Za-z_][A-Za-z0-9_]{0,99}){0,4}$/;
17
+ var COLLECTION = /^[A-Za-z0-9_-]{1,100}$/;
18
+ var IndexFieldSchema = z.union([
19
+ z.object({ fieldPath: z.string().regex(FIELD_PATH), order: z.enum(["ASCENDING", "DESCENDING"]) }).strict(),
20
+ z.object({ fieldPath: z.string().regex(FIELD_PATH), arrayConfig: z.literal("CONTAINS") }).strict()
21
+ ]);
22
+ var FirestoreIndexSchema = z.object({
23
+ collectionGroup: z.string().regex(COLLECTION),
24
+ // The SDK has no collection group queries.
25
+ queryScope: z.literal("COLLECTION").default("COLLECTION"),
26
+ fields: z.array(IndexFieldSchema).min(2).max(10)
27
+ }).strict().superRefine((ix, ctx) => {
28
+ const paths = ix.fields.map((f) => f.fieldPath);
29
+ if (new Set(paths).size !== paths.length) ctx.addIssue({ code: "custom", message: "a field is listed twice" });
30
+ if (ix.fields.filter((f) => "arrayConfig" in f).length > 1) {
31
+ ctx.addIssue({ code: "custom", message: "an index can have at most one array field" });
32
+ }
33
+ });
34
+ var IndexesFileSchema = z.object({
35
+ indexes: z.array(FirestoreIndexSchema).max(MAX_INDEXES),
36
+ // Written by the Firebase CLI. The platform does not apply overrides.
37
+ fieldOverrides: z.array(z.unknown()).max(0, "fieldOverrides are not supported; leave the list empty").optional()
38
+ }).strict();
39
+ var IndexesFileError = class extends Error {
40
+ constructor(message) {
41
+ super(message);
42
+ this.name = "IndexesFileError";
43
+ }
44
+ };
45
+ function parseIndexesFile(text) {
46
+ if (new TextEncoder().encode(text).length > MAX_INDEXES_FILE_BYTES) {
47
+ throw new IndexesFileError(`${INDEXES_FILE} is larger than ${MAX_INDEXES_FILE_BYTES / 1024} KB.`);
48
+ }
49
+ let json;
50
+ try {
51
+ json = JSON.parse(text);
52
+ } catch (e) {
53
+ throw new IndexesFileError(`${INDEXES_FILE} is not valid JSON: ${e.message}`);
54
+ }
55
+ const parsed = IndexesFileSchema.safeParse(json);
56
+ if (!parsed.success) {
57
+ const issues = parsed.error.issues.slice(0, 5).map((i) => `${i.path.join(".") || "(file)"}: ${i.message}`);
58
+ throw new IndexesFileError(`${INDEXES_FILE} is not valid: ${issues.join("; ")}`);
59
+ }
60
+ const seen = /* @__PURE__ */ new Set();
61
+ return parsed.data.indexes.filter((ix) => {
62
+ const k = indexKey(ix);
63
+ if (seen.has(k)) return false;
64
+ seen.add(k);
65
+ return true;
66
+ });
67
+ }
68
+ var EQUALITY = ["==", "in"];
69
+ var ARRAY = ["array-contains", "array-contains-any"];
70
+ var order = (d) => d === "desc" ? "DESCENDING" : "ASCENDING";
71
+ function requiredIndex(collection, q) {
72
+ const equality = [...new Set(q.where.filter((w) => EQUALITY.includes(w.op)).map((w) => w.field))];
73
+ const arrays = [...new Set(q.where.filter((w) => ARRAY.includes(w.op)).map((w) => w.field))];
74
+ const inequality = [
75
+ ...new Set(q.where.filter((w) => !EQUALITY.includes(w.op) && !ARRAY.includes(w.op)).map((w) => w.field))
76
+ ];
77
+ const sort = [];
78
+ for (const o of q.orderBy) {
79
+ if (equality.includes(o.field) && !inequality.includes(o.field)) continue;
80
+ if (sort.some((s) => s.fieldPath === o.field)) continue;
81
+ sort.push({ fieldPath: o.field, order: order(o.direction) });
82
+ }
83
+ const lastOrder = sort.at(-1)?.order ?? "ASCENDING";
84
+ for (const f of [...inequality].sort()) {
85
+ if (!sort.some((s) => s.fieldPath === f)) sort.push({ fieldPath: f, order: lastOrder });
86
+ }
87
+ const array = arrays[0];
88
+ const eq = equality.filter((f) => f !== array && !sort.some((s) => s.fieldPath === f));
89
+ const fieldCount = eq.length + (array ? 1 : 0) + sort.length;
90
+ if (fieldCount <= 1) return null;
91
+ if (sort.length === 0 && !array) return null;
92
+ return {
93
+ collectionGroup: collection,
94
+ equality: eq,
95
+ ...array ? { array } : {},
96
+ sort,
97
+ ...inequality.length ? { inequality: true } : {}
98
+ };
99
+ }
100
+ function plainFields(ix) {
101
+ const f = ix.fields;
102
+ return f.length > 0 && f.at(-1).fieldPath === "__name__" ? f.slice(0, -1) : f;
103
+ }
104
+ function serves(ix, need, equality) {
105
+ if (ix.collectionGroup !== need.collectionGroup || ix.queryScope !== "COLLECTION") return false;
106
+ const fields = plainFields(ix);
107
+ const head = fields.slice(0, fields.length - need.sort.length);
108
+ const tail = fields.slice(fields.length - need.sort.length);
109
+ if (tail.length !== need.sort.length) return false;
110
+ if (!tail.every((f, i) => "order" in f && f.fieldPath === need.sort[i].fieldPath && f.order === need.sort[i].order)) return false;
111
+ const arrays = head.filter((f) => "arrayConfig" in f).map((f) => f.fieldPath);
112
+ if (arrays.length !== (need.array ? 1 : 0) || need.array && arrays[0] !== need.array) return false;
113
+ const eq = head.filter((f) => "order" in f).map((f) => f.fieldPath);
114
+ return eq.length === equality.length && eq.every((f) => equality.includes(f));
115
+ }
116
+ function indexesServe(declared, need) {
117
+ if (declared.some((ix) => serves(ix, need, need.equality))) return true;
118
+ if (need.array || need.inequality || need.equality.length < 2) return false;
119
+ const covered = /* @__PURE__ */ new Set();
120
+ for (const ix of declared) {
121
+ const fields = plainFields(ix);
122
+ const eq = fields.slice(0, fields.length - need.sort.length).map((f) => f.fieldPath);
123
+ if (eq.length > 0 && eq.every((f) => need.equality.includes(f)) && serves(ix, need, eq)) {
124
+ for (const f of eq) covered.add(f);
125
+ }
126
+ }
127
+ return need.equality.every((f) => covered.has(f));
128
+ }
129
+ function indexFor(need) {
130
+ return {
131
+ collectionGroup: need.collectionGroup,
132
+ queryScope: "COLLECTION",
133
+ fields: [
134
+ ...need.equality.map((fieldPath) => ({ fieldPath, order: "ASCENDING" })),
135
+ ...need.array ? [{ fieldPath: need.array, arrayConfig: "CONTAINS" }] : [],
136
+ ...need.sort
137
+ ]
138
+ };
139
+ }
140
+ function missingIndexMessage(need) {
141
+ return `This query on "${need.collectionGroup}" needs a database index. Add this entry to the "indexes" list in ${INDEXES_FILE} (in the app's root folder), then run the query again:
142
+ ` + JSON.stringify(indexFor(need), null, 2);
143
+ }
144
+ function indexKey(ix) {
145
+ const fields = plainFields(ix).map((f) => "order" in f ? `${f.fieldPath}:${f.order}` : `${f.fieldPath}:CONTAINS`);
146
+ return `${ix.collectionGroup}|${ix.queryScope}|${fields.join(",")}`;
147
+ }
148
+
149
+ // src/db-limit.ts
150
+ var MAX_QUERY_LIMIT = 500;
151
+ function checkLimit(n) {
152
+ if (!Number.isInteger(n) || n < 1 || n > MAX_QUERY_LIMIT) {
153
+ throw new BuildersError(`limit() must be a whole number from 1 to ${MAX_QUERY_LIMIT}, not ${n}.`);
154
+ }
155
+ return n;
156
+ }
157
+ var queryLimit = (spec) => spec.limit ?? MAX_QUERY_LIMIT;
158
+
159
+ // src/db-indexes.ts
160
+ import { readFileSync, statSync } from "node:fs";
161
+ import { join } from "node:path";
162
+ var cache = null;
163
+ function indexesFilePath(env = process.env) {
164
+ return env.BUILDERS_INDEXES_FILE || join(process.cwd(), INDEXES_FILE);
165
+ }
166
+ function declaredIndexes(path = indexesFilePath()) {
167
+ let st;
168
+ try {
169
+ st = statSync(path);
170
+ } catch {
171
+ return [];
172
+ }
173
+ if (cache && cache.path === path && cache.mtimeMs === st.mtimeMs && cache.size === st.size) return cache.indexes;
174
+ try {
175
+ const indexes = parseIndexesFile(readFileSync(path, "utf8"));
176
+ cache = { path, mtimeMs: st.mtimeMs, size: st.size, indexes };
177
+ return indexes;
178
+ } catch (e) {
179
+ if (e instanceof IndexesFileError) throw new BuildersError(e.message);
180
+ throw e;
181
+ }
182
+ }
183
+ function checkIndex(collection, spec) {
184
+ const declared = declaredIndexes();
185
+ const need = requiredIndex(collection, spec);
186
+ if (need && !indexesServe(declared, need)) throw new BuildersError(missingIndexMessage(need));
187
+ }
188
+ function missingIndexError(collection, spec, e) {
189
+ const err = e;
190
+ if (err?.code !== 9 || !/index/i.test(err.message ?? "")) return null;
191
+ const need = requiredIndex(collection, spec);
192
+ return need ? new BuildersError(`${missingIndexMessage(need)}
193
+ Then push a new version: the platform creates the index before the preview.`) : null;
194
+ }
195
+
196
+ // src/db-firestore.ts
197
+ var client;
198
+ function firestore() {
199
+ return client ??= import("@google-cloud/firestore").then((m) => {
200
+ const env = process.env;
201
+ const fs = new m.Firestore({
202
+ ignoreUndefinedProperties: true,
203
+ projectId: env.GOOGLE_CLOUD_PROJECT ?? (env.FIRESTORE_EMULATOR_HOST ? "demo-builders" : void 0),
204
+ databaseId: env.FIRESTORE_DATABASE || void 0
205
+ });
206
+ return { fs, Timestamp: m.Timestamp };
207
+ });
208
+ }
209
+ function firestoreCollection(name) {
210
+ const ref = async () => (await firestore()).fs.collection(name);
211
+ const query = (spec) => ({
212
+ where: (field, op, value) => query({ ...spec, where: [...spec.where, { field, op, value }] }),
213
+ orderBy: (field, direction = "asc") => query({ ...spec, orderBy: [...spec.orderBy, { field, direction }] }),
214
+ limit: (n) => query({ ...spec, limit: checkLimit(n) }),
215
+ async list() {
216
+ const { Timestamp } = await firestore();
217
+ let q = await ref();
218
+ for (const w of spec.where) q = q.where(w.field, w.op, w.value);
219
+ for (const o of spec.orderBy) q = q.orderBy(o.field, o.direction);
220
+ q = q.limit(queryLimit(spec));
221
+ let snap;
222
+ try {
223
+ snap = await q.get();
224
+ } catch (e) {
225
+ throw missingIndexError(name, spec, e) ?? e;
226
+ }
227
+ return snap.docs.map((d) => ({ ...toPlain(d.data(), Timestamp), id: d.id }));
228
+ },
229
+ async get(id) {
230
+ const { Timestamp } = await firestore();
231
+ const d = await (await ref()).doc(id).get();
232
+ return d.exists ? { ...toPlain(d.data(), Timestamp), id: d.id } : null;
233
+ },
234
+ async add(data) {
235
+ const body = withoutId(data);
236
+ const r = await (await ref()).add(body);
237
+ return { ...body, id: r.id };
238
+ },
239
+ async set(id, data) {
240
+ await (await ref()).doc(id).set(withoutId(data));
241
+ },
242
+ async update(id, patch) {
243
+ try {
244
+ await (await ref()).doc(id).update(withoutId(patch));
245
+ } catch (e) {
246
+ if (e.code === 5) throw new NotFoundError(`No document "${id}" in "${name}".`);
247
+ throw e;
248
+ }
249
+ },
250
+ async delete(id) {
251
+ await (await ref()).doc(id).delete();
252
+ }
253
+ });
254
+ return query({ where: [], orderBy: [] });
255
+ }
256
+ function withoutId(data) {
257
+ const { id: _id, ...rest } = data;
258
+ return rest;
259
+ }
260
+ function toPlain(v, Timestamp) {
261
+ if (v instanceof Timestamp) return v.toDate();
262
+ if (Array.isArray(v)) return v.map((x) => toPlain(x, Timestamp));
263
+ if (v && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype) {
264
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, toPlain(x, Timestamp)]));
265
+ }
266
+ return v;
267
+ }
268
+
269
+ // src/db-memory.ts
270
+ import { randomBytes } from "node:crypto";
271
+ var warnedCap = /* @__PURE__ */ new Set();
272
+ var g = globalThis;
273
+ var store = () => g.__buildersMemoryDb ??= /* @__PURE__ */ new Map();
274
+ function resetMemoryDb() {
275
+ store().clear();
276
+ }
277
+ function memoryCollection(name) {
278
+ const docs = () => {
279
+ let m = store().get(name);
280
+ if (!m) store().set(name, m = /* @__PURE__ */ new Map());
281
+ return m;
282
+ };
283
+ const out = (id, data) => ({ ...structuredClone(data), id });
284
+ const clean = (data) => {
285
+ const copy = structuredClone(data);
286
+ delete copy.id;
287
+ for (const k of Object.keys(copy)) if (copy[k] === void 0) delete copy[k];
288
+ return copy;
289
+ };
290
+ const query = (spec) => ({
291
+ where: (field, op, value) => query({ ...spec, where: [...spec.where, { field, op, value }] }),
292
+ orderBy: (field, direction = "asc") => query({ ...spec, orderBy: [...spec.orderBy, { field, direction }] }),
293
+ limit: (n) => query({ ...spec, limit: checkLimit(n) }),
294
+ async list() {
295
+ checkIndex(name, spec);
296
+ let rows = [...docs()].filter(([, d]) => spec.where.every((w) => matches(d[w.field], w.op, w.value)));
297
+ rows = rows.filter(([, d]) => spec.orderBy.every((o) => d[o.field] !== void 0));
298
+ rows.sort(([, a], [, b]) => {
299
+ for (const o of spec.orderBy) {
300
+ const c = compare(a[o.field], b[o.field]);
301
+ if (c !== 0) return o.direction === "desc" ? -c : c;
302
+ }
303
+ return 0;
304
+ });
305
+ if (spec.limit === void 0 && rows.length > MAX_QUERY_LIMIT && !warnedCap.has(name)) {
306
+ warnedCap.add(name);
307
+ console.warn(`[builders] A query on "${name}" matched more than ${MAX_QUERY_LIMIT} documents; list() returns only the first ${MAX_QUERY_LIMIT}.`);
308
+ }
309
+ rows = rows.slice(0, queryLimit(spec));
310
+ return rows.map(([id, d]) => out(id, d));
311
+ },
312
+ async get(id) {
313
+ const d = docs().get(id);
314
+ return d ? out(id, d) : null;
315
+ },
316
+ async add(data) {
317
+ const id = autoId();
318
+ docs().set(id, clean(data));
319
+ return out(id, docs().get(id));
320
+ },
321
+ async set(id, data) {
322
+ docs().set(id, clean(data));
323
+ },
324
+ async update(id, patch) {
325
+ const d = docs().get(id);
326
+ if (!d) throw new NotFoundError(`No document "${id}" in "${name}".`);
327
+ docs().set(id, { ...d, ...clean(patch) });
328
+ },
329
+ async delete(id) {
330
+ docs().delete(id);
331
+ }
332
+ });
333
+ return query({ where: [], orderBy: [] });
334
+ }
335
+ function autoId() {
336
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
337
+ return [...randomBytes(20)].map((b) => chars[b % chars.length]).join("");
338
+ }
339
+ function key(v) {
340
+ return v instanceof Date ? v.getTime() : v;
341
+ }
342
+ function compare(a, b) {
343
+ const x = key(a);
344
+ const y = key(b);
345
+ return x < y ? -1 : x > y ? 1 : 0;
346
+ }
347
+ function equal(a, b) {
348
+ return key(a) === key(b);
349
+ }
350
+ function matches(v, op, target) {
351
+ if (v === void 0) return false;
352
+ const list = Array.isArray(target) ? target : [];
353
+ switch (op) {
354
+ case "==":
355
+ return equal(v, target);
356
+ case "!=":
357
+ return !equal(v, target);
358
+ case "<":
359
+ return compare(v, target) < 0;
360
+ case "<=":
361
+ return compare(v, target) <= 0;
362
+ case ">":
363
+ return compare(v, target) > 0;
364
+ case ">=":
365
+ return compare(v, target) >= 0;
366
+ case "in":
367
+ return list.some((t) => equal(v, t));
368
+ case "not-in":
369
+ return !list.some((t) => equal(v, t));
370
+ case "array-contains":
371
+ return Array.isArray(v) && v.some((x) => equal(x, target));
372
+ case "array-contains-any":
373
+ return Array.isArray(v) && v.some((x) => list.some((t) => equal(x, t)));
374
+ }
375
+ }
376
+
377
+ // src/db.ts
378
+ function dbMode(env = process.env) {
379
+ if (env.BUILDERS_DB === "memory" || env.BUILDERS_DB === "firestore") return env.BUILDERS_DB;
380
+ if (env.FIRESTORE_EMULATOR_HOST || env.GOOGLE_APPLICATION_CREDENTIALS) return "firestore";
381
+ if (env.NODE_ENV === "production" || env.K_SERVICE) return "firestore";
382
+ return "memory";
383
+ }
384
+ var warned = false;
385
+ var db = {
386
+ collection(name) {
387
+ if (!/^[A-Za-z0-9_-]{1,100}$/.test(name)) {
388
+ throw new BuildersError(`"${name}" is not a valid collection name. Use letters, digits, "-" or "_".`);
389
+ }
390
+ if (dbMode() === "firestore") return firestoreCollection(name);
391
+ if (!warned && process.env.NODE_ENV !== "test") {
392
+ warned = true;
393
+ console.info("[builders] Using a temporary in-memory database. Data is lost when the dev server stops.");
394
+ }
395
+ return memoryCollection(name);
396
+ },
397
+ // Empties the in-memory database. For tests.
398
+ reset: resetMemoryDb
399
+ };
400
+
401
+ // src/http.ts
402
+ function requireEnv(addOn, ...names) {
403
+ const values = names.map((n) => process.env[n]);
404
+ if (values.some((v) => !v)) throw new AddOnNotEnabledError(addOn);
405
+ return values;
406
+ }
407
+ async function postJson(label, url, body, opts = {}) {
408
+ let res;
409
+ try {
410
+ res = await fetch(url, {
411
+ method: "POST",
412
+ headers: {
413
+ "content-type": "application/json",
414
+ ...opts.key ? { authorization: `Bearer ${opts.key}` } : {}
415
+ },
416
+ body: JSON.stringify(body),
417
+ signal: opts.signal ?? AbortSignal.timeout(opts.timeoutMs ?? 3e4)
418
+ });
419
+ } catch (e) {
420
+ throw new BuildersError(`Could not reach the ${label}: ${e.message}`, 502);
421
+ }
422
+ const text = await res.text();
423
+ let json = void 0;
424
+ try {
425
+ json = text ? JSON.parse(text) : void 0;
426
+ } catch {
427
+ }
428
+ if (!res.ok) {
429
+ const err = json?.error;
430
+ if (err?.code === "budget_exceeded") {
431
+ throw new BuildersError(`The ${label} budget for this month is used up. The app owner can ask for more in the Builders portal.`, 402);
432
+ }
433
+ throw new BuildersError(`The ${label} answered ${res.status}: ${err?.message ?? (text.slice(0, 200) || res.statusText)}`, 502);
434
+ }
435
+ return json;
436
+ }
437
+
438
+ // src/ai.ts
439
+ var MODELS = { fast: true, balanced: true, best: true };
440
+ var ai = {
441
+ async ask(prompt, opts = {}) {
442
+ const [url, key2] = requireEnv("ai", "AI_GATEWAY_URL", "AI_GATEWAY_KEY");
443
+ const model = opts.model ?? "balanced";
444
+ if (!Object.hasOwn(MODELS, model)) {
445
+ throw new BuildersError(`Unknown AI model "${model}". Use "fast", "balanced" or "best".`, 400);
446
+ }
447
+ const body = {
448
+ prompt,
449
+ system: opts.system,
450
+ model,
451
+ maxTokens: opts.maxTokens ?? 1024
452
+ };
453
+ const res = await postJson("AI service", `${url.replace(/\/+$/, "")}/v1/ask`, body, {
454
+ key: key2,
455
+ timeoutMs: 12e4,
456
+ signal: opts.signal
457
+ });
458
+ return res.text;
459
+ }
460
+ };
461
+
462
+ // src/storage.ts
463
+ var cached;
464
+ async function bucket() {
465
+ const [name] = requireEnv("storage", "STORAGE_BUCKET");
466
+ if (cached?.name !== name) {
467
+ cached = { name, bucket: import("@google-cloud/storage").then((m) => new m.Storage().bucket(name)) };
468
+ }
469
+ return cached.bucket;
470
+ }
471
+ function checkPath(path) {
472
+ if (!path || path.startsWith("/") || path.split("/").some((p) => p === ".." || p === "")) {
473
+ throw new BuildersError(`"${path}" is not a valid file path. Use something like "photos/cat.jpg".`, 400);
474
+ }
475
+ return path;
476
+ }
477
+ var storage = {
478
+ async upload(path, data, opts = {}) {
479
+ await (await bucket()).file(checkPath(path)).save(typeof data === "string" ? data : Buffer.from(data), {
480
+ contentType: opts.contentType,
481
+ resumable: false
482
+ });
483
+ return { path };
484
+ },
485
+ async download(path) {
486
+ const [buf] = await (await bucket()).file(checkPath(path)).download();
487
+ return buf;
488
+ },
489
+ async signedUrl(path, opts = {}) {
490
+ const minutes = Math.min(opts.expiresInMinutes ?? 15, 7 * 24 * 60);
491
+ const [url] = await (await bucket()).file(checkPath(path)).getSignedUrl({
492
+ version: "v4",
493
+ action: opts.action ?? "read",
494
+ expires: Date.now() + minutes * 6e4,
495
+ contentType: opts.contentType
496
+ });
497
+ return url;
498
+ },
499
+ async list(prefix = "") {
500
+ const [files] = await (await bucket()).getFiles({ prefix });
501
+ return files.map((f) => f.name);
502
+ },
503
+ async delete(path) {
504
+ await (await bucket()).file(checkPath(path)).delete({ ignoreNotFound: true });
505
+ }
506
+ };
507
+
508
+ // src/notify.ts
509
+ var notify = {
510
+ async email(to, subject, text) {
511
+ const [url] = requireEnv("notify", "NOTIFY_URL");
512
+ await postJson("notification service", `${url.replace(/\/+$/, "")}/v1/email`, {
513
+ to: Array.isArray(to) ? to : [to],
514
+ subject,
515
+ text
516
+ }, { key: process.env.NOTIFY_KEY });
517
+ },
518
+ async slack(text) {
519
+ const [url] = requireEnv("notify", "NOTIFY_URL");
520
+ await postJson("notification service", `${url.replace(/\/+$/, "")}/v1/slack`, { text }, { key: process.env.NOTIFY_KEY });
521
+ }
522
+ };
523
+ export {
524
+ AddOnNotEnabledError,
525
+ BuildersError,
526
+ IDENTITY_HEADER,
527
+ MAX_QUERY_LIMIT,
528
+ NotFoundError,
529
+ NotSignedInError,
530
+ ai,
531
+ db,
532
+ dbMode,
533
+ getUser,
534
+ nameFromEmail,
535
+ notify,
536
+ storage
537
+ };
package/dist/next.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { User } from './index.js';
2
+ import 'jose';
3
+
4
+ declare function currentUser(): Promise<User>;
5
+
6
+ export { currentUser };
package/dist/next.js ADDED
@@ -0,0 +1,12 @@
1
+ import {
2
+ getUser
3
+ } from "./chunks/chunk-AXQENVKW.js";
4
+
5
+ // src/next.ts
6
+ import { headers } from "next/headers.js";
7
+ async function currentUser() {
8
+ return getUser(await headers());
9
+ }
10
+ export {
11
+ currentUser
12
+ };
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@n-dream/builders-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Builders platform helpers for app code: signed-in user, database, AI, file storage, notifications.",
5
+ "license": "UNLICENSED",
6
+ "homepage": "https://builders.n-dream.com",
7
+ "keywords": [
8
+ "builders",
9
+ "nextjs"
10
+ ],
11
+ "type": "module",
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "./next": {
20
+ "types": "./dist/next.d.ts",
21
+ "default": "./dist/next.js"
22
+ },
23
+ "./package.json": "./package.json"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md"
28
+ ],
29
+ "engines": {
30
+ "node": ">=22"
31
+ },
32
+ "dependencies": {
33
+ "@google-cloud/firestore": "^9.4.0",
34
+ "@google-cloud/storage": "^8.4.0",
35
+ "jose": "^6.0.0",
36
+ "zod": "^4.6.7"
37
+ },
38
+ "peerDependencies": {
39
+ "next": ">=15"
40
+ },
41
+ "peerDependenciesMeta": {
42
+ "next": {
43
+ "optional": true
44
+ }
45
+ },
46
+ "publishConfig": {
47
+ "access": "public"
48
+ }
49
+ }